2 * Copyright (c) 2018 Inocybe Technologies and others. All rights reserved.
4 * This program and the accompanying materials are made available under the
5 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6 * and is available at http://www.eclipse.org/legal/epl-v10.html
8 package org.opendaylight.netconf.topology.singleton.impl;
10 import static org.awaitility.Awaitility.await;
11 import static org.junit.Assert.assertEquals;
12 import static org.junit.Assert.assertFalse;
13 import static org.junit.Assert.assertNotNull;
14 import static org.junit.Assert.assertNull;
15 import static org.junit.Assert.assertTrue;
16 import static org.junit.Assert.fail;
17 import static org.mockito.ArgumentMatchers.any;
18 import static org.mockito.Mockito.doAnswer;
19 import static org.mockito.Mockito.doReturn;
20 import static org.mockito.Mockito.mock;
21 import static org.mockito.Mockito.spy;
22 import static org.mockito.Mockito.timeout;
23 import static org.mockito.Mockito.verify;
25 import akka.actor.ActorSystem;
26 import akka.testkit.javadsl.TestKit;
27 import akka.util.Timeout;
28 import com.google.common.collect.ImmutableList;
29 import com.google.common.collect.ImmutableMap;
30 import com.google.common.util.concurrent.FluentFuture;
31 import com.google.common.util.concurrent.Futures;
32 import com.google.common.util.concurrent.ListenableFuture;
33 import com.google.common.util.concurrent.MoreExecutors;
34 import com.google.common.util.concurrent.SettableFuture;
35 import com.typesafe.config.ConfigFactory;
36 import io.netty.util.Timer;
38 import java.util.Iterator;
39 import java.util.List;
41 import java.util.Map.Entry;
42 import java.util.Optional;
44 import java.util.concurrent.ExecutionException;
45 import java.util.concurrent.TimeUnit;
46 import java.util.concurrent.TimeoutException;
47 import org.apache.commons.io.FileUtils;
48 import org.eclipse.jdt.annotation.NonNull;
49 import org.junit.After;
50 import org.junit.Before;
51 import org.junit.Test;
52 import org.junit.runner.RunWith;
53 import org.mockito.Mock;
54 import org.mockito.junit.MockitoJUnitRunner;
55 import org.opendaylight.aaa.encrypt.AAAEncryptionService;
56 import org.opendaylight.mdsal.binding.api.DataBroker;
57 import org.opendaylight.mdsal.binding.api.DataObjectModification;
58 import org.opendaylight.mdsal.binding.api.DataTreeIdentifier;
59 import org.opendaylight.mdsal.binding.api.DataTreeModification;
60 import org.opendaylight.mdsal.binding.api.ReadTransaction;
61 import org.opendaylight.mdsal.binding.api.RpcProviderService;
62 import org.opendaylight.mdsal.binding.api.Transaction;
63 import org.opendaylight.mdsal.binding.api.TransactionChain;
64 import org.opendaylight.mdsal.binding.api.TransactionChainListener;
65 import org.opendaylight.mdsal.binding.api.WriteTransaction;
66 import org.opendaylight.mdsal.binding.dom.adapter.test.AbstractConcurrentDataBrokerTest;
67 import org.opendaylight.mdsal.binding.dom.codec.api.BindingNormalizedNodeSerializer;
68 import org.opendaylight.mdsal.binding.runtime.spi.BindingRuntimeHelpers;
69 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
70 import org.opendaylight.mdsal.dom.api.DOMActionService;
71 import org.opendaylight.mdsal.dom.api.DOMDataBroker;
72 import org.opendaylight.mdsal.dom.api.DOMDataTreeReadOperations;
73 import org.opendaylight.mdsal.dom.api.DOMDataTreeReadWriteTransaction;
74 import org.opendaylight.mdsal.dom.api.DOMDataTreeWriteTransaction;
75 import org.opendaylight.mdsal.dom.api.DOMMountPoint;
76 import org.opendaylight.mdsal.dom.api.DOMMountPointListener;
77 import org.opendaylight.mdsal.dom.api.DOMMountPointService;
78 import org.opendaylight.mdsal.dom.api.DOMRpcAvailabilityListener;
79 import org.opendaylight.mdsal.dom.api.DOMRpcIdentifier;
80 import org.opendaylight.mdsal.dom.api.DOMRpcImplementation;
81 import org.opendaylight.mdsal.dom.api.DOMRpcResult;
82 import org.opendaylight.mdsal.dom.api.DOMRpcService;
83 import org.opendaylight.mdsal.dom.api.DOMService;
84 import org.opendaylight.mdsal.dom.broker.DOMMountPointServiceImpl;
85 import org.opendaylight.mdsal.dom.broker.DOMRpcRouter;
86 import org.opendaylight.mdsal.dom.spi.DefaultDOMRpcResult;
87 import org.opendaylight.mdsal.dom.spi.FixedDOMSchemaService;
88 import org.opendaylight.mdsal.singleton.common.api.ClusterSingletonServiceProvider;
89 import org.opendaylight.mdsal.singleton.common.api.ClusterSingletonServiceRegistration;
90 import org.opendaylight.mdsal.singleton.common.api.ServiceGroupIdentifier;
91 import org.opendaylight.mdsal.singleton.dom.impl.DOMClusterSingletonServiceProviderImpl;
92 import org.opendaylight.netconf.api.CapabilityURN;
93 import org.opendaylight.netconf.client.NetconfClientFactory;
94 import org.opendaylight.netconf.client.mdsal.NetconfDeviceCapabilities;
95 import org.opendaylight.netconf.client.mdsal.NetconfDeviceSchema;
96 import org.opendaylight.netconf.client.mdsal.api.CredentialProvider;
97 import org.opendaylight.netconf.client.mdsal.api.DeviceActionFactory;
98 import org.opendaylight.netconf.client.mdsal.api.NetconfSessionPreferences;
99 import org.opendaylight.netconf.client.mdsal.api.RemoteDeviceServices;
100 import org.opendaylight.netconf.client.mdsal.api.RemoteDeviceServices.Rpcs;
101 import org.opendaylight.netconf.client.mdsal.api.SchemaResourceManager;
102 import org.opendaylight.netconf.client.mdsal.api.SslHandlerFactoryProvider;
103 import org.opendaylight.netconf.client.mdsal.impl.DefaultSchemaResourceManager;
104 import org.opendaylight.netconf.topology.singleton.impl.utils.ClusteringRpcException;
105 import org.opendaylight.netconf.topology.singleton.impl.utils.NetconfTopologySetup;
106 import org.opendaylight.netconf.topology.singleton.impl.utils.NetconfTopologyUtils;
107 import org.opendaylight.netconf.topology.spi.NetconfClientConfigurationBuilderFactory;
108 import org.opendaylight.netconf.topology.spi.NetconfClientConfigurationBuilderFactoryImpl;
109 import org.opendaylight.netconf.topology.spi.NetconfNodeUtils;
110 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Host;
111 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpAddress;
112 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Ipv4Address;
113 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.PortNumber;
114 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.device.rev231025.ConnectionOper.ConnectionStatus;
115 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.device.rev231025.credentials.credentials.LoginPwUnencryptedBuilder;
116 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.device.rev231025.credentials.credentials.login.pw.unencrypted.LoginPasswordUnencryptedBuilder;
117 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.keystore.rev171017.Keystore;
118 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev221225.NetconfNode;
119 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev221225.NetconfNodeBuilder;
120 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.list.rev140701.GetTopInput;
121 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.list.rev140701.GetTopOutputBuilder;
122 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.list.rev140701.PutTopInputBuilder;
123 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.list.rev140701.Top;
124 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.list.rev140701.two.level.list.TopLevelList;
125 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.list.rev140701.two.level.list.TopLevelListBuilder;
126 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.list.rev140701.two.level.list.TopLevelListKey;
127 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NetworkTopology;
128 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NodeId;
129 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.TopologyBuilder;
130 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node;
131 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.NodeBuilder;
132 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.NodeKey;
133 import org.opendaylight.yangtools.concepts.ListenerRegistration;
134 import org.opendaylight.yangtools.concepts.Registration;
135 import org.opendaylight.yangtools.util.concurrent.FluentFutures;
136 import org.opendaylight.yangtools.yang.binding.DataObject;
137 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
138 import org.opendaylight.yangtools.yang.binding.KeyedInstanceIdentifier;
139 import org.opendaylight.yangtools.yang.binding.YangModuleInfo;
140 import org.opendaylight.yangtools.yang.common.ErrorTag;
141 import org.opendaylight.yangtools.yang.common.ErrorType;
142 import org.opendaylight.yangtools.yang.common.QName;
143 import org.opendaylight.yangtools.yang.common.Revision;
144 import org.opendaylight.yangtools.yang.common.RpcError;
145 import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
146 import org.opendaylight.yangtools.yang.common.Uint16;
147 import org.opendaylight.yangtools.yang.common.Uint32;
148 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
149 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
150 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
151 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
152 import org.opendaylight.yangtools.yang.data.api.schema.MountPointContext;
153 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
154 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
155 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
156 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
157 import org.opendaylight.yangtools.yang.model.api.Module;
158 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
159 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
160 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
161 import org.opendaylight.yangtools.yang.model.repo.spi.PotentialSchemaSource;
162 import org.opendaylight.yangtools.yang.parser.impl.DefaultYangParserFactory;
163 import org.slf4j.Logger;
164 import org.slf4j.LoggerFactory;
167 * Tests netconf mount points end-to-end.
169 * @author Thomas Pantelis
171 @RunWith(MockitoJUnitRunner.StrictStubs.class)
172 public class MountPointEndToEndTest extends AbstractBaseSchemasTest {
173 private static final Logger LOG = LoggerFactory.getLogger(MountPointEndToEndTest.class);
175 private static final String TOP_MODULE_NAME = "opendaylight-mdsal-list-test";
176 private static final String ACTOR_SYSTEM_NAME = "test";
177 private static final String TOPOLOGY_ID = NetconfNodeUtils.DEFAULT_TOPOLOGY_NAME;
178 private static final @NonNull KeyedInstanceIdentifier<Node, NodeKey> NODE_INSTANCE_ID =
179 NetconfTopologyUtils.createTopologyNodeListPath(new NodeKey(new NodeId("node-id")), TOPOLOGY_ID);
181 private static final String TEST_ROOT_DIRECTORY = "test-cache-root";
182 private static final String TEST_DEFAULT_SUBDIR = "test-schema";
185 private RpcProviderService mockRpcProviderService;
187 private Registration mockRpcReg;
189 private NetconfClientFactory mockClientFactory;
191 private AAAEncryptionService mockEncryptionService;
193 private Timer mockTimer;
195 private DeviceActionFactory deviceActionFactory;
197 private CredentialProvider credentialProvider;
199 private SslHandlerFactoryProvider sslHandlerFactoryProvider;
201 private DOMMountPointListener masterMountPointListener;
202 private final DOMMountPointService masterMountPointService = new DOMMountPointServiceImpl();
203 private Rpcs.Normalized deviceRpcService;
205 private DOMClusterSingletonServiceProviderImpl masterClusterSingletonServiceProvider;
206 private DataBroker masterDataBroker;
207 private DOMDataBroker deviceDOMDataBroker;
208 private ActorSystem masterSystem;
209 private NetconfTopologyManager masterNetconfTopologyManager;
211 private volatile SettableFuture<MasterSalFacade> masterSalFacadeFuture = SettableFuture.create();
214 private ClusterSingletonServiceProvider mockSlaveClusterSingletonServiceProvider;
216 private ClusterSingletonServiceRegistration mockSlaveClusterSingletonServiceReg;
218 private DOMMountPointListener slaveMountPointListener;
219 private final DOMMountPointService slaveMountPointService = new DOMMountPointServiceImpl();
220 private DataBroker slaveDataBroker;
221 private ActorSystem slaveSystem;
222 private NetconfTopologyManager slaveNetconfTopologyManager;
223 private final SettableFuture<NetconfTopologyContext> slaveNetconfTopologyContextFuture = SettableFuture.create();
224 private TransactionChain slaveTxChain;
226 private NetconfClientConfigurationBuilderFactory builderFactory;
227 private EffectiveModelContext deviceSchemaContext;
228 private YangModuleInfo topModuleInfo;
229 private QName putTopRpcSchemaPath;
230 private QName getTopRpcSchemaPath;
231 private BindingNormalizedNodeSerializer bindingToNormalized;
232 private YangInstanceIdentifier yangNodeInstanceId;
233 private final TopDOMRpcImplementation topRpcImplementation = new TopDOMRpcImplementation();
234 private final ContainerNode getTopInput = ImmutableNodes.containerNode(GetTopInput.QNAME);
236 private SchemaResourceManager resourceManager;
239 public void setUp() throws Exception {
242 resourceManager = new DefaultSchemaResourceManager(new DefaultYangParserFactory(), TEST_ROOT_DIRECTORY,
243 TEST_DEFAULT_SUBDIR);
245 topModuleInfo = BindingRuntimeHelpers.getYangModuleInfo(Top.class);
247 deviceSchemaContext = BindingRuntimeHelpers.createEffectiveModel(Top.class);
249 final var router = new DOMRpcRouter(FixedDOMSchemaService.of(deviceSchemaContext));
251 putTopRpcSchemaPath = findRpcDefinition("put-top").getQName();
252 getTopRpcSchemaPath = findRpcDefinition("get-top").getQName();
254 router.getRpcProviderService().registerRpcImplementation(topRpcImplementation,
255 DOMRpcIdentifier.create(putTopRpcSchemaPath), DOMRpcIdentifier.create(getTopRpcSchemaPath));
257 final var rpcService = router.getRpcService();
258 deviceRpcService = new Rpcs.Normalized() {
260 public ListenableFuture<? extends DOMRpcResult> invokeRpc(final QName type, final ContainerNode input) {
261 return rpcService.invokeRpc(type, input);
265 public <T extends DOMRpcAvailabilityListener> ListenerRegistration<T> registerRpcListener(
267 return rpcService.registerRpcListener(listener);
271 builderFactory = new NetconfClientConfigurationBuilderFactoryImpl(mockEncryptionService, credentialProvider,
272 sslHandlerFactoryProvider);
274 doReturn(mockRpcReg).when(mockRpcProviderService).registerRpcImplementations(any());
280 yangNodeInstanceId = bindingToNormalized.toYangInstanceIdentifier(NODE_INSTANCE_ID);
281 doReturn(mock(ListenableFuture.class)).when(mockClientFactory).createClient(any());
283 LOG.info("****** Setup complete");
286 private static void deleteCacheDir() {
287 FileUtils.deleteQuietly(new File(TEST_ROOT_DIRECTORY));
291 public void tearDown() throws Exception {
293 TestKit.shutdownActorSystem(slaveSystem, true);
294 TestKit.shutdownActorSystem(masterSystem, true);
297 private void setupMaster() throws Exception {
298 final var dataBrokerTest = newDataBrokerTest();
299 masterDataBroker = dataBrokerTest.getDataBroker();
300 deviceDOMDataBroker = dataBrokerTest.getDomBroker();
301 bindingToNormalized = dataBrokerTest.getDataBrokerTestCustomizer().getAdapterContext().currentSerializer();
303 masterSystem = ActorSystem.create(ACTOR_SYSTEM_NAME, ConfigFactory.load().getConfig("Master"));
305 masterClusterSingletonServiceProvider = new DOMClusterSingletonServiceProviderImpl();
306 masterClusterSingletonServiceProvider.initializeProvider();
308 final var resources = resourceManager.getSchemaResources(TEST_DEFAULT_SUBDIR, "test");
309 resources.getSchemaRegistry().registerSchemaSource(
310 id -> Futures.immediateFuture(YangTextSchemaSource.delegateForCharSource(id,
311 topModuleInfo.getYangTextCharSource())),
312 PotentialSchemaSource.create(new SourceIdentifier(TOP_MODULE_NAME,
313 topModuleInfo.getName().getRevision().map(Revision::toString).orElse(null)),
314 YangTextSchemaSource.class, 1));
316 masterNetconfTopologyManager = new NetconfTopologyManager(BASE_SCHEMAS, masterDataBroker,
317 masterClusterSingletonServiceProvider, mockTimer, MoreExecutors.directExecutor(), masterSystem,
318 mockClientFactory, masterMountPointService, mockEncryptionService, mockRpcProviderService,
319 deviceActionFactory, resourceManager, builderFactory, TOPOLOGY_ID, Uint16.ZERO) {
321 protected NetconfTopologyContext newNetconfTopologyContext(final NetconfTopologySetup setup,
322 final ServiceGroupIdentifier serviceGroupIdent, final Timeout actorResponseWaitTime,
323 final DeviceActionFactory deviceActionFact) {
324 final var context = super.newNetconfTopologyContext(setup, serviceGroupIdent, actorResponseWaitTime,
326 final var spiedContext = spy(context);
327 final var spiedSingleton = spy(context.getTopologySingleton());
328 doAnswer(invocation -> {
329 final var spiedFacade = (MasterSalFacade) spy(invocation.callRealMethod());
330 doReturn(deviceDOMDataBroker).when(spiedFacade)
331 .newDeviceDataBroker(any(MountPointContext.class), any(NetconfSessionPreferences.class));
332 masterSalFacadeFuture.set(spiedFacade);
334 }).when(spiedSingleton).createSalFacade(any(boolean.class));
335 doReturn(spiedSingleton).when(spiedContext).getTopologySingleton();
340 verifyTopologyNodesCreated(masterDataBroker);
343 private void setupSlave() throws Exception {
344 AbstractConcurrentDataBrokerTest dataBrokerTest = newDataBrokerTest();
345 slaveDataBroker = dataBrokerTest.getDataBroker();
347 slaveSystem = ActorSystem.create(ACTOR_SYSTEM_NAME, ConfigFactory.load().getConfig("Slave"));
349 doReturn(mockSlaveClusterSingletonServiceReg).when(mockSlaveClusterSingletonServiceProvider)
350 .registerClusterSingletonService(any());
352 slaveNetconfTopologyManager = new NetconfTopologyManager(BASE_SCHEMAS, slaveDataBroker,
353 mockSlaveClusterSingletonServiceProvider, mockTimer, MoreExecutors.directExecutor(), slaveSystem,
354 mockClientFactory, slaveMountPointService, mockEncryptionService, mockRpcProviderService,
355 deviceActionFactory, resourceManager, builderFactory, TOPOLOGY_ID, Uint16.ZERO) {
357 protected NetconfTopologyContext newNetconfTopologyContext(final NetconfTopologySetup setup,
358 final ServiceGroupIdentifier serviceGroupIdent, final Timeout actorResponseWaitTime,
359 final DeviceActionFactory actionFactory) {
360 NetconfTopologyContext spiedContext = spy(super.newNetconfTopologyContext(setup, serviceGroupIdent,
361 actorResponseWaitTime, actionFactory));
363 slaveNetconfTopologyContextFuture.set(spiedContext);
368 verifyTopologyNodesCreated(slaveDataBroker);
370 slaveTxChain = slaveDataBroker.createTransactionChain(new TransactionChainListener() {
372 public void onTransactionChainSuccessful(final TransactionChain chain) {
377 public void onTransactionChainFailed(final TransactionChain chain, final Transaction transaction,
378 final Throwable cause) {
379 LOG.error("Slave transaction chain failed", cause);
385 public void test() throws Exception {
390 final MasterSalFacade masterSalFacade = testMasterNodeUpdated();
392 testMasterDisconnected(masterSalFacade);
397 private MasterSalFacade testMaster() throws Exception {
398 LOG.info("****** Testing master");
400 writeNetconfNode(TEST_DEFAULT_SUBDIR, masterDataBroker);
402 final var masterSalFacade = masterSalFacadeFuture.get(5, TimeUnit.SECONDS);
403 masterSalFacade.onDeviceConnected(new NetconfDeviceSchema(NetconfDeviceCapabilities.empty(),
404 MountPointContext.of(deviceSchemaContext)),
405 NetconfSessionPreferences.fromStrings(List.of(CapabilityURN.CANDIDATE)),
406 new RemoteDeviceServices(deviceRpcService, null));
408 final var masterMountPoint = awaitMountPoint(masterMountPointService);
410 LOG.info("****** Testing master DOMDataBroker operations");
412 testDOMDataBrokerOperations(getDOMDataBroker(masterMountPoint));
414 LOG.info("****** Testing master DOMRpcService");
416 testDOMRpcService(getDOMRpcService(masterMountPoint));
417 return masterSalFacade;
420 private void testSlave() throws Exception {
421 LOG.info("****** Testing slave");
423 writeNetconfNode("slave", slaveDataBroker);
425 verify(mockSlaveClusterSingletonServiceProvider, timeout(5000)).registerClusterSingletonService(any());
427 // Since the master and slave use separate DataBrokers we need to copy the master's oper node to the slave.
428 // This is essentially what happens in a clustered environment but we'll use a DTCL here.
430 masterDataBroker.registerDataTreeChangeListener(
431 DataTreeIdentifier.create(LogicalDatastoreType.OPERATIONAL, NODE_INSTANCE_ID), changes -> {
432 final WriteTransaction slaveTx = slaveTxChain.newWriteOnlyTransaction();
433 for (DataTreeModification<Node> dataTreeModification : changes) {
434 DataObjectModification<Node> rootNode = dataTreeModification.getRootNode();
435 InstanceIdentifier<Node> path = dataTreeModification.getRootPath().getRootIdentifier();
436 switch (rootNode.getModificationType()) {
438 case SUBTREE_MODIFIED:
439 slaveTx.merge(LogicalDatastoreType.OPERATIONAL, path, rootNode.getDataAfter());
442 slaveTx.delete(LogicalDatastoreType.OPERATIONAL, path);
452 DOMMountPoint slaveMountPoint = awaitMountPoint(slaveMountPointService);
454 LOG.info("****** Testing slave DOMDataBroker operations");
456 testDOMDataBrokerOperations(getDOMDataBroker(slaveMountPoint));
458 LOG.info("****** Testing slave DOMRpcService");
460 testDOMRpcService(getDOMRpcService(slaveMountPoint));
463 private MasterSalFacade testMasterNodeUpdated() throws Exception {
464 LOG.info("****** Testing update master node");
466 masterMountPointService.registerProvisionListener(masterMountPointListener);
467 slaveMountPointService.registerProvisionListener(slaveMountPointListener);
469 masterSalFacadeFuture = SettableFuture.create();
470 writeNetconfNode(TEST_DEFAULT_SUBDIR, masterDataBroker);
472 verify(masterMountPointListener, timeout(5000)).onMountPointRemoved(yangNodeInstanceId);
474 final var masterSalFacade = masterSalFacadeFuture.get(5, TimeUnit.SECONDS);
475 masterSalFacade.onDeviceConnected(
476 new NetconfDeviceSchema(NetconfDeviceCapabilities.empty(), MountPointContext.of(deviceSchemaContext)),
477 NetconfSessionPreferences.fromStrings(List.of(CapabilityURN.CANDIDATE)),
478 new RemoteDeviceServices(deviceRpcService, null));
480 verify(masterMountPointListener, timeout(5000)).onMountPointCreated(yangNodeInstanceId);
482 verify(slaveMountPointListener, timeout(5000)).onMountPointRemoved(yangNodeInstanceId);
483 verify(slaveMountPointListener, timeout(5000)).onMountPointCreated(yangNodeInstanceId);
485 return masterSalFacade;
488 private void testMasterDisconnected(final MasterSalFacade masterSalFacade) throws Exception {
489 LOG.info("****** Testing master disconnected");
491 masterSalFacade.onDeviceDisconnected();
493 awaitMountPointNotPresent(masterMountPointService);
495 await().atMost(5, TimeUnit.SECONDS).until(() -> {
496 try (ReadTransaction readTx = masterDataBroker.newReadOnlyTransaction()) {
497 Optional<Node> node = readTx.read(LogicalDatastoreType.OPERATIONAL,
498 NODE_INSTANCE_ID).get(5, TimeUnit.SECONDS);
499 assertTrue(node.isPresent());
500 final NetconfNode netconfNode = node.orElseThrow().augmentation(NetconfNode.class);
501 return netconfNode.getConnectionStatus() != ConnectionStatus.Connected;
505 awaitMountPointNotPresent(slaveMountPointService);
508 private void testCleanup() throws Exception {
509 LOG.info("****** Testing cleanup");
511 slaveNetconfTopologyManager.close();
512 verify(mockSlaveClusterSingletonServiceReg).close();
515 private void testDOMRpcService(final DOMRpcService domRpcService)
516 throws InterruptedException, ExecutionException, TimeoutException {
517 testPutTopRpc(domRpcService, new DefaultDOMRpcResult((ContainerNode)null));
518 testPutTopRpc(domRpcService, null);
519 testPutTopRpc(domRpcService, new DefaultDOMRpcResult(ImmutableList.of(
520 RpcResultBuilder.newError(ErrorType.APPLICATION, new ErrorTag("tag1"), "error1"),
521 RpcResultBuilder.newError(ErrorType.APPLICATION, new ErrorTag("tag2"), "error2"))));
523 testGetTopRpc(domRpcService, new DefaultDOMRpcResult(bindingToNormalized.toNormalizedNodeRpcData(
524 new GetTopOutputBuilder().setTopLevelList(oneTopLevelList()).build())));
526 testFailedRpc(domRpcService, getTopRpcSchemaPath, getTopInput);
529 private void testPutTopRpc(final DOMRpcService domRpcService, final DOMRpcResult result)
530 throws InterruptedException, ExecutionException, TimeoutException {
531 ContainerNode putTopInput = bindingToNormalized.toNormalizedNodeRpcData(
532 new PutTopInputBuilder().setTopLevelList(oneTopLevelList()).build());
533 testRpc(domRpcService, putTopRpcSchemaPath, putTopInput, result);
536 private static Map<TopLevelListKey, TopLevelList> oneTopLevelList() {
537 final TopLevelListKey key = new TopLevelListKey("one");
538 return ImmutableMap.of(key, new TopLevelListBuilder().withKey(key).build());
541 private void testGetTopRpc(final DOMRpcService domRpcService, final DOMRpcResult result)
542 throws InterruptedException, ExecutionException, TimeoutException {
543 testRpc(domRpcService, getTopRpcSchemaPath, getTopInput, result);
546 private void testRpc(final DOMRpcService domRpcService, final QName qname, final ContainerNode input,
547 final DOMRpcResult result) throws InterruptedException, ExecutionException, TimeoutException {
548 final FluentFuture<DOMRpcResult> future = result == null ? FluentFutures.immediateNullFluentFuture()
549 : FluentFutures.immediateFluentFuture(result);
550 final DOMRpcResult actual = invokeRpc(domRpcService, qname, input, future);
551 if (result == null) {
556 assertNotNull(actual);
557 assertEquals(result.value(), actual.value());
559 assertEquals(result.errors().size(), actual.errors().size());
560 Iterator<? extends RpcError> iter1 = result.errors().iterator();
561 Iterator<? extends RpcError> iter2 = actual.errors().iterator();
562 while (iter1.hasNext() && iter2.hasNext()) {
563 RpcError err1 = iter1.next();
564 RpcError err2 = iter2.next();
565 assertEquals(err1.getErrorType(), err2.getErrorType());
566 assertEquals(err1.getTag(), err2.getTag());
567 assertEquals(err1.getMessage(), err2.getMessage());
568 assertEquals(err1.getSeverity(), err2.getSeverity());
569 assertEquals(err1.getApplicationTag(), err2.getApplicationTag());
570 assertEquals(err1.getInfo(), err2.getInfo());
574 private void testFailedRpc(final DOMRpcService domRpcService, final QName qname, final ContainerNode input)
575 throws InterruptedException, TimeoutException {
577 invokeRpc(domRpcService, qname, input, Futures.immediateFailedFuture(new ClusteringRpcException("mock")));
578 fail("Expected exception");
579 } catch (ExecutionException e) {
580 assertTrue(e.getCause() instanceof ClusteringRpcException);
581 assertEquals("mock", e.getCause().getMessage());
585 private DOMRpcResult invokeRpc(final DOMRpcService domRpcService, final QName qname, final ContainerNode input,
586 final ListenableFuture<DOMRpcResult> returnFuture)
587 throws InterruptedException, ExecutionException, TimeoutException {
588 topRpcImplementation.init(returnFuture);
589 final ListenableFuture<? extends DOMRpcResult> resultFuture = domRpcService.invokeRpc(qname, input);
591 topRpcImplementation.verify(DOMRpcIdentifier.create(qname), input);
593 return resultFuture.get(5, TimeUnit.SECONDS);
596 private static void testDOMDataBrokerOperations(final DOMDataBroker dataBroker)
597 throws InterruptedException, ExecutionException, TimeoutException {
599 DOMDataTreeWriteTransaction writeTx = dataBroker.newWriteOnlyTransaction();
601 final ContainerNode topNode = Builders.containerBuilder()
602 .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(Top.QNAME)).build();
603 final YangInstanceIdentifier topPath = YangInstanceIdentifier.of(Top.QNAME);
604 writeTx.put(LogicalDatastoreType.CONFIGURATION, topPath, topNode);
606 final QName name = QName.create(TopLevelList.QNAME, "name");
607 final YangInstanceIdentifier listPath = YangInstanceIdentifier.builder(topPath)
608 .node(TopLevelList.QNAME).build();
609 final MapEntryNode listEntryNode = ImmutableNodes.mapEntry(TopLevelList.QNAME, name, "one");
610 final MapNode listNode = ImmutableNodes.mapNodeBuilder(TopLevelList.QNAME).addChild(listEntryNode).build();
611 writeTx.merge(LogicalDatastoreType.CONFIGURATION, listPath, listNode);
612 writeTx.commit().get(5, TimeUnit.SECONDS);
614 verifyDataInStore(dataBroker.newReadWriteTransaction(), YangInstanceIdentifier.builder(listPath)
615 .nodeWithKey(TopLevelList.QNAME, name, "one").build(), listEntryNode);
617 writeTx = dataBroker.newWriteOnlyTransaction();
618 writeTx.delete(LogicalDatastoreType.CONFIGURATION, topPath);
619 writeTx.commit().get(5, TimeUnit.SECONDS);
621 DOMDataTreeReadWriteTransaction readTx = dataBroker.newReadWriteTransaction();
622 assertFalse(readTx.exists(LogicalDatastoreType.CONFIGURATION, topPath).get(5, TimeUnit.SECONDS));
623 assertTrue(readTx.cancel());
626 private static void writeNetconfNode(final String cacheDir, final DataBroker dataBroker) throws Exception {
627 putData(dataBroker, NODE_INSTANCE_ID, new NodeBuilder()
628 .withKey(NODE_INSTANCE_ID.getKey())
629 .addAugmentation(new NetconfNodeBuilder()
630 .setHost(new Host(new IpAddress(new Ipv4Address("127.0.0.1"))))
631 .setPort(new PortNumber(Uint16.valueOf(1234)))
632 .setActorResponseWaitTime(Uint16.valueOf(10))
633 .setTcpOnly(Boolean.TRUE)
634 .setSchemaless(Boolean.FALSE)
635 .setKeepaliveDelay(Uint32.ZERO)
636 .setConnectionTimeoutMillis(Uint32.valueOf(5000))
637 .setDefaultRequestTimeoutMillis(Uint32.valueOf(5000))
638 .setMaxConnectionAttempts(Uint32.ONE)
639 .setCredentials(new LoginPwUnencryptedBuilder()
640 .setLoginPasswordUnencrypted(new LoginPasswordUnencryptedBuilder()
645 .setSchemaCacheDirectory(cacheDir)
650 private static <T extends DataObject> void putData(final DataBroker databroker, final InstanceIdentifier<T> path,
651 final T data) throws Exception {
652 final var writeTx = databroker.newWriteOnlyTransaction();
653 writeTx.put(LogicalDatastoreType.CONFIGURATION, path, data);
654 writeTx.commit().get(5, TimeUnit.SECONDS);
657 private static void verifyDataInStore(final DOMDataTreeReadOperations readTx, final YangInstanceIdentifier path,
658 final NormalizedNode expNode) throws InterruptedException, ExecutionException, TimeoutException {
659 assertEquals(Optional.of(expNode), readTx.read(LogicalDatastoreType.CONFIGURATION, path)
660 .get(5, TimeUnit.SECONDS));
661 assertTrue(readTx.exists(LogicalDatastoreType.CONFIGURATION, path).get(5, TimeUnit.SECONDS));
664 private static void verifyTopologyNodesCreated(final DataBroker dataBroker) {
665 await().atMost(5, TimeUnit.SECONDS).until(() -> {
666 try (ReadTransaction readTx = dataBroker.newReadOnlyTransaction()) {
667 return readTx.exists(LogicalDatastoreType.OPERATIONAL,
668 NetconfTopologyUtils.createTopologyListPath(TOPOLOGY_ID)).get(3, TimeUnit.SECONDS);
673 private AbstractConcurrentDataBrokerTest newDataBrokerTest() throws Exception {
674 final var dataBrokerTest = new AbstractConcurrentDataBrokerTest(true) {
676 protected Set<YangModuleInfo> getModuleInfos() {
678 BindingRuntimeHelpers.getYangModuleInfo(NetconfNode.class),
679 BindingRuntimeHelpers.getYangModuleInfo(NetworkTopology.class),
680 BindingRuntimeHelpers.getYangModuleInfo(Keystore.class),
685 dataBrokerTest.setup();
687 final var path = NetconfTopologyUtils.createTopologyListPath(TOPOLOGY_ID);
688 putData(dataBrokerTest.getDataBroker(), path, new TopologyBuilder().withKey(path.getKey()).build());
689 return dataBrokerTest;
692 private void awaitMountPointNotPresent(final DOMMountPointService mountPointService) {
693 await().atMost(5, TimeUnit.SECONDS).until(
694 () -> mountPointService.getMountPoint(yangNodeInstanceId).isEmpty());
697 private static DOMDataBroker getDOMDataBroker(final DOMMountPoint mountPoint) {
698 return getMountPointService(mountPoint, DOMDataBroker.class);
701 private static DOMRpcService getDOMRpcService(final DOMMountPoint mountPoint) {
702 return getMountPointService(mountPoint, DOMRpcService.class);
705 private static DOMActionService getDomActionService(final DOMMountPoint mountPoint) {
706 return getMountPointService(mountPoint, DOMActionService.class);
709 private static <T extends DOMService> T getMountPointService(final DOMMountPoint mountPoint,
710 final Class<T> serviceClass) {
711 return mountPoint.getService(serviceClass).orElseThrow();
714 private DOMMountPoint awaitMountPoint(final DOMMountPointService mountPointService) {
715 await().atMost(5, TimeUnit.SECONDS).until(() ->
716 mountPointService.getMountPoint(yangNodeInstanceId).isPresent());
718 return mountPointService.getMountPoint(yangNodeInstanceId).orElseThrow();
721 private RpcDefinition findRpcDefinition(final String rpc) {
722 Module topModule = deviceSchemaContext.findModule(TOP_MODULE_NAME, topModuleInfo.getName().getRevision())
724 RpcDefinition rpcDefinition = null;
725 for (RpcDefinition def: topModule.getRpcs()) {
726 if (def.getQName().getLocalName().equals(rpc)) {
732 assertNotNull(rpc + " rpc not found in " + topModule.getRpcs(), rpcDefinition);
733 return rpcDefinition;
736 private static final class TopDOMRpcImplementation implements DOMRpcImplementation {
737 private volatile SettableFuture<Entry<DOMRpcIdentifier, NormalizedNode>> rpcInvokedFuture;
738 private volatile ListenableFuture<DOMRpcResult> returnFuture;
741 public ListenableFuture<DOMRpcResult> invokeRpc(final DOMRpcIdentifier rpc, final ContainerNode input) {
742 rpcInvokedFuture.set(Map.entry(rpc, input));
746 void init(final ListenableFuture<DOMRpcResult> retFuture) {
747 returnFuture = retFuture;
748 rpcInvokedFuture = SettableFuture.create();
751 void verify(final DOMRpcIdentifier expRpc, final NormalizedNode expInput)
752 throws InterruptedException, ExecutionException, TimeoutException {
753 final Entry<DOMRpcIdentifier, NormalizedNode> actual = rpcInvokedFuture.get(5, TimeUnit.SECONDS);
754 assertEquals(expRpc, actual.getKey());
755 assertEquals(expInput, actual.getValue());