Remove obsoleted way of configuring password
[netconf.git] / apps / netconf-topology-singleton / src / test / java / org / opendaylight / netconf / topology / singleton / impl / MountPointEndToEndTest.java
1 /*
2  * Copyright (c) 2018 Inocybe Technologies and others.  All rights reserved.
3  *
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
7  */
8 package org.opendaylight.netconf.topology.singleton.impl;
9
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;
24
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.concurrent.EventExecutor;
37 import io.netty.util.concurrent.Future;
38 import io.netty.util.concurrent.GlobalEventExecutor;
39 import java.io.File;
40 import java.util.Iterator;
41 import java.util.List;
42 import java.util.Map;
43 import java.util.Map.Entry;
44 import java.util.Optional;
45 import java.util.Set;
46 import java.util.concurrent.ExecutionException;
47 import java.util.concurrent.ScheduledExecutorService;
48 import java.util.concurrent.TimeUnit;
49 import java.util.concurrent.TimeoutException;
50 import org.apache.commons.io.FileUtils;
51 import org.eclipse.jdt.annotation.NonNull;
52 import org.junit.After;
53 import org.junit.Before;
54 import org.junit.Test;
55 import org.junit.runner.RunWith;
56 import org.mockito.Mock;
57 import org.mockito.junit.MockitoJUnitRunner;
58 import org.opendaylight.aaa.encrypt.AAAEncryptionService;
59 import org.opendaylight.mdsal.binding.api.DataBroker;
60 import org.opendaylight.mdsal.binding.api.DataObjectModification;
61 import org.opendaylight.mdsal.binding.api.DataTreeIdentifier;
62 import org.opendaylight.mdsal.binding.api.DataTreeModification;
63 import org.opendaylight.mdsal.binding.api.ReadTransaction;
64 import org.opendaylight.mdsal.binding.api.RpcProviderService;
65 import org.opendaylight.mdsal.binding.api.Transaction;
66 import org.opendaylight.mdsal.binding.api.TransactionChain;
67 import org.opendaylight.mdsal.binding.api.TransactionChainListener;
68 import org.opendaylight.mdsal.binding.api.WriteTransaction;
69 import org.opendaylight.mdsal.binding.dom.adapter.test.AbstractConcurrentDataBrokerTest;
70 import org.opendaylight.mdsal.binding.dom.codec.api.BindingNormalizedNodeSerializer;
71 import org.opendaylight.mdsal.binding.runtime.spi.BindingRuntimeHelpers;
72 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
73 import org.opendaylight.mdsal.dom.api.DOMActionService;
74 import org.opendaylight.mdsal.dom.api.DOMDataBroker;
75 import org.opendaylight.mdsal.dom.api.DOMDataTreeReadOperations;
76 import org.opendaylight.mdsal.dom.api.DOMDataTreeReadWriteTransaction;
77 import org.opendaylight.mdsal.dom.api.DOMDataTreeWriteTransaction;
78 import org.opendaylight.mdsal.dom.api.DOMMountPoint;
79 import org.opendaylight.mdsal.dom.api.DOMMountPointListener;
80 import org.opendaylight.mdsal.dom.api.DOMMountPointService;
81 import org.opendaylight.mdsal.dom.api.DOMRpcAvailabilityListener;
82 import org.opendaylight.mdsal.dom.api.DOMRpcIdentifier;
83 import org.opendaylight.mdsal.dom.api.DOMRpcImplementation;
84 import org.opendaylight.mdsal.dom.api.DOMRpcResult;
85 import org.opendaylight.mdsal.dom.api.DOMRpcService;
86 import org.opendaylight.mdsal.dom.api.DOMService;
87 import org.opendaylight.mdsal.dom.broker.DOMMountPointServiceImpl;
88 import org.opendaylight.mdsal.dom.broker.DOMRpcRouter;
89 import org.opendaylight.mdsal.dom.spi.DefaultDOMRpcResult;
90 import org.opendaylight.mdsal.dom.spi.FixedDOMSchemaService;
91 import org.opendaylight.mdsal.singleton.common.api.ClusterSingletonServiceProvider;
92 import org.opendaylight.mdsal.singleton.common.api.ClusterSingletonServiceRegistration;
93 import org.opendaylight.mdsal.singleton.common.api.ServiceGroupIdentifier;
94 import org.opendaylight.mdsal.singleton.dom.impl.DOMClusterSingletonServiceProviderImpl;
95 import org.opendaylight.netconf.api.CapabilityURN;
96 import org.opendaylight.netconf.client.NetconfClientDispatcher;
97 import org.opendaylight.netconf.client.mdsal.NetconfDeviceCapabilities;
98 import org.opendaylight.netconf.client.mdsal.NetconfDeviceSchema;
99 import org.opendaylight.netconf.client.mdsal.api.CredentialProvider;
100 import org.opendaylight.netconf.client.mdsal.api.DeviceActionFactory;
101 import org.opendaylight.netconf.client.mdsal.api.NetconfSessionPreferences;
102 import org.opendaylight.netconf.client.mdsal.api.RemoteDeviceServices;
103 import org.opendaylight.netconf.client.mdsal.api.RemoteDeviceServices.Rpcs;
104 import org.opendaylight.netconf.client.mdsal.api.SchemaResourceManager;
105 import org.opendaylight.netconf.client.mdsal.api.SslHandlerFactoryProvider;
106 import org.opendaylight.netconf.client.mdsal.impl.DefaultSchemaResourceManager;
107 import org.opendaylight.netconf.topology.singleton.impl.utils.ClusteringRpcException;
108 import org.opendaylight.netconf.topology.singleton.impl.utils.NetconfTopologySetup;
109 import org.opendaylight.netconf.topology.singleton.impl.utils.NetconfTopologyUtils;
110 import org.opendaylight.netconf.topology.spi.DefaultNetconfClientConfigurationBuilderFactory;
111 import org.opendaylight.netconf.topology.spi.NetconfClientConfigurationBuilderFactory;
112 import org.opendaylight.netconf.topology.spi.NetconfNodeUtils;
113 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Host;
114 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpAddress;
115 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Ipv4Address;
116 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.PortNumber;
117 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.device.rev231025.ConnectionOper.ConnectionStatus;
118 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.device.rev231025.credentials.credentials.LoginPwUnencryptedBuilder;
119 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.device.rev231025.credentials.credentials.login.pw.unencrypted.LoginPasswordUnencryptedBuilder;
120 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.keystore.rev171017.Keystore;
121 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev221225.NetconfNode;
122 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev221225.NetconfNodeBuilder;
123 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.list.rev140701.GetTopInput;
124 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.list.rev140701.GetTopOutputBuilder;
125 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.list.rev140701.PutTopInputBuilder;
126 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.list.rev140701.Top;
127 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.list.rev140701.two.level.list.TopLevelList;
128 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.list.rev140701.two.level.list.TopLevelListBuilder;
129 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.list.rev140701.two.level.list.TopLevelListKey;
130 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NetworkTopology;
131 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NodeId;
132 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.TopologyBuilder;
133 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node;
134 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.NodeBuilder;
135 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.NodeKey;
136 import org.opendaylight.yangtools.concepts.ListenerRegistration;
137 import org.opendaylight.yangtools.concepts.Registration;
138 import org.opendaylight.yangtools.util.concurrent.FluentFutures;
139 import org.opendaylight.yangtools.yang.binding.DataObject;
140 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
141 import org.opendaylight.yangtools.yang.binding.KeyedInstanceIdentifier;
142 import org.opendaylight.yangtools.yang.binding.YangModuleInfo;
143 import org.opendaylight.yangtools.yang.common.ErrorTag;
144 import org.opendaylight.yangtools.yang.common.ErrorType;
145 import org.opendaylight.yangtools.yang.common.QName;
146 import org.opendaylight.yangtools.yang.common.Revision;
147 import org.opendaylight.yangtools.yang.common.RpcError;
148 import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
149 import org.opendaylight.yangtools.yang.common.Uint16;
150 import org.opendaylight.yangtools.yang.common.Uint32;
151 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
152 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
153 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
154 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
155 import org.opendaylight.yangtools.yang.data.api.schema.MountPointContext;
156 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
157 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
158 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
159 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
160 import org.opendaylight.yangtools.yang.model.api.Module;
161 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
162 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
163 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
164 import org.opendaylight.yangtools.yang.model.repo.spi.PotentialSchemaSource;
165 import org.opendaylight.yangtools.yang.parser.impl.DefaultYangParserFactory;
166 import org.slf4j.Logger;
167 import org.slf4j.LoggerFactory;
168
169 /**
170  * Tests netconf mount points end-to-end.
171  *
172  * @author Thomas Pantelis
173  */
174 @RunWith(MockitoJUnitRunner.StrictStubs.class)
175 public class MountPointEndToEndTest extends AbstractBaseSchemasTest {
176     private static final Logger LOG = LoggerFactory.getLogger(MountPointEndToEndTest.class);
177
178     private static final String TOP_MODULE_NAME = "opendaylight-mdsal-list-test";
179     private static final String ACTOR_SYSTEM_NAME = "test";
180     private static final String TOPOLOGY_ID = NetconfNodeUtils.DEFAULT_TOPOLOGY_NAME;
181     private static final @NonNull KeyedInstanceIdentifier<Node, NodeKey> NODE_INSTANCE_ID =
182         NetconfTopologyUtils.createTopologyNodeListPath(new NodeKey(new NodeId("node-id")), TOPOLOGY_ID);
183
184     private static final String TEST_ROOT_DIRECTORY = "test-cache-root";
185     private static final String TEST_DEFAULT_SUBDIR = "test-schema";
186
187     @Mock private RpcProviderService mockRpcProviderService;
188     @Mock private Registration mockRpcReg;
189     @Mock private NetconfClientDispatcher mockClientDispatcher;
190     @Mock private AAAEncryptionService mockEncryptionService;
191     @Mock private ScheduledExecutorService mockKeepaliveExecutor;
192     @Mock private DeviceActionFactory deviceActionFactory;
193     @Mock private CredentialProvider credentialProvider;
194     @Mock private SslHandlerFactoryProvider sslHandlerFactoryProvider;
195
196     @Mock private DOMMountPointListener masterMountPointListener;
197     private final DOMMountPointService masterMountPointService = new DOMMountPointServiceImpl();
198     private Rpcs.Normalized deviceRpcService;
199
200     private DOMClusterSingletonServiceProviderImpl masterClusterSingletonServiceProvider;
201     private DataBroker masterDataBroker;
202     private DOMDataBroker deviceDOMDataBroker;
203     private ActorSystem masterSystem;
204     private NetconfTopologyManager masterNetconfTopologyManager;
205
206     private volatile SettableFuture<MasterSalFacade> masterSalFacadeFuture = SettableFuture.create();
207
208     @Mock private ClusterSingletonServiceProvider mockSlaveClusterSingletonServiceProvider;
209     @Mock private ClusterSingletonServiceRegistration mockSlaveClusterSingletonServiceReg;
210     @Mock private DOMMountPointListener slaveMountPointListener;
211     private final DOMMountPointService slaveMountPointService = new DOMMountPointServiceImpl();
212     private DataBroker slaveDataBroker;
213     private ActorSystem slaveSystem;
214     private NetconfTopologyManager slaveNetconfTopologyManager;
215     private final SettableFuture<NetconfTopologyContext> slaveNetconfTopologyContextFuture = SettableFuture.create();
216     private TransactionChain slaveTxChain;
217
218     private NetconfClientConfigurationBuilderFactory builderFactory;
219     private final EventExecutor eventExecutor = GlobalEventExecutor.INSTANCE;
220     private EffectiveModelContext deviceSchemaContext;
221     private YangModuleInfo topModuleInfo;
222     private QName putTopRpcSchemaPath;
223     private QName getTopRpcSchemaPath;
224     private BindingNormalizedNodeSerializer bindingToNormalized;
225     private YangInstanceIdentifier yangNodeInstanceId;
226     private final TopDOMRpcImplementation topRpcImplementation = new TopDOMRpcImplementation();
227     private final ContainerNode getTopInput = ImmutableNodes.containerNode(GetTopInput.QNAME);
228
229     private SchemaResourceManager resourceManager;
230
231     @Before
232     public void setUp() throws Exception {
233         deleteCacheDir();
234
235         resourceManager = new DefaultSchemaResourceManager(new DefaultYangParserFactory(), TEST_ROOT_DIRECTORY,
236             TEST_DEFAULT_SUBDIR);
237
238         topModuleInfo = BindingRuntimeHelpers.getYangModuleInfo(Top.class);
239
240         deviceSchemaContext = BindingRuntimeHelpers.createEffectiveModel(Top.class);
241
242         final var router = new DOMRpcRouter(FixedDOMSchemaService.of(deviceSchemaContext));
243
244         putTopRpcSchemaPath = findRpcDefinition("put-top").getQName();
245         getTopRpcSchemaPath = findRpcDefinition("get-top").getQName();
246
247         router.getRpcProviderService().registerRpcImplementation(topRpcImplementation,
248                 DOMRpcIdentifier.create(putTopRpcSchemaPath), DOMRpcIdentifier.create(getTopRpcSchemaPath));
249
250         final var rpcService = router.getRpcService();
251         deviceRpcService = new Rpcs.Normalized() {
252             @Override
253             public ListenableFuture<? extends DOMRpcResult> invokeRpc(final QName type, final ContainerNode input) {
254                 return rpcService.invokeRpc(type, input);
255             }
256
257             @Override
258             public <T extends DOMRpcAvailabilityListener> ListenerRegistration<T> registerRpcListener(
259                     final T listener) {
260                 return rpcService.registerRpcListener(listener);
261             }
262         };
263
264         builderFactory = new DefaultNetconfClientConfigurationBuilderFactory(mockEncryptionService, credentialProvider,
265             sslHandlerFactoryProvider);
266
267         doReturn(mockRpcReg).when(mockRpcProviderService).registerRpcImplementations(any());
268
269         setupMaster();
270
271         setupSlave();
272
273         yangNodeInstanceId = bindingToNormalized.toYangInstanceIdentifier(NODE_INSTANCE_ID);
274         doReturn(mock(Future.class)).when(mockClientDispatcher).createClient(any());
275
276         LOG.info("****** Setup complete");
277     }
278
279     private static void deleteCacheDir() {
280         FileUtils.deleteQuietly(new File(TEST_ROOT_DIRECTORY));
281     }
282
283     @After
284     public void tearDown() throws Exception {
285         deleteCacheDir();
286         TestKit.shutdownActorSystem(slaveSystem, true);
287         TestKit.shutdownActorSystem(masterSystem, true);
288     }
289
290     private void setupMaster() throws Exception {
291         final var dataBrokerTest = newDataBrokerTest();
292         masterDataBroker = dataBrokerTest.getDataBroker();
293         deviceDOMDataBroker = dataBrokerTest.getDomBroker();
294         bindingToNormalized = dataBrokerTest.getDataBrokerTestCustomizer().getAdapterContext().currentSerializer();
295
296         masterSystem = ActorSystem.create(ACTOR_SYSTEM_NAME, ConfigFactory.load().getConfig("Master"));
297
298         masterClusterSingletonServiceProvider = new DOMClusterSingletonServiceProviderImpl();
299         masterClusterSingletonServiceProvider.initializeProvider();
300
301         final var resources =  resourceManager.getSchemaResources(TEST_DEFAULT_SUBDIR, "test");
302         resources.getSchemaRegistry().registerSchemaSource(
303             id -> Futures.immediateFuture(YangTextSchemaSource.delegateForCharSource(id,
304                     topModuleInfo.getYangTextCharSource())),
305             PotentialSchemaSource.create(new SourceIdentifier(TOP_MODULE_NAME,
306                     topModuleInfo.getName().getRevision().map(Revision::toString).orElse(null)),
307                 YangTextSchemaSource.class, 1));
308
309         masterNetconfTopologyManager = new NetconfTopologyManager(BASE_SCHEMAS, masterDataBroker,
310                 masterClusterSingletonServiceProvider, mockKeepaliveExecutor, MoreExecutors.directExecutor(),
311                 masterSystem, eventExecutor, mockClientDispatcher, masterMountPointService,
312                 mockEncryptionService, mockRpcProviderService, deviceActionFactory, resourceManager, builderFactory,
313                 TOPOLOGY_ID, Uint16.ZERO) {
314             @Override
315             protected NetconfTopologyContext newNetconfTopologyContext(final NetconfTopologySetup setup,
316                     final ServiceGroupIdentifier serviceGroupIdent, final Timeout actorResponseWaitTime,
317                     final DeviceActionFactory deviceActionFact) {
318                 final var context = super.newNetconfTopologyContext(setup, serviceGroupIdent, actorResponseWaitTime,
319                     deviceActionFact);
320                 final var spiedContext = spy(context);
321                 final var spiedSingleton = spy(context.getTopologySingleton());
322                 doAnswer(invocation -> {
323                     final var spiedFacade = (MasterSalFacade) spy(invocation.callRealMethod());
324                     doReturn(deviceDOMDataBroker).when(spiedFacade)
325                         .newDeviceDataBroker(any(MountPointContext.class), any(NetconfSessionPreferences.class));
326                     masterSalFacadeFuture.set(spiedFacade);
327                     return spiedFacade;
328                 }).when(spiedSingleton).createSalFacade(any(boolean.class));
329                 doReturn(spiedSingleton).when(spiedContext).getTopologySingleton();
330                 return spiedContext;
331             }
332         };
333
334         verifyTopologyNodesCreated(masterDataBroker);
335     }
336
337     private void setupSlave() throws Exception {
338         AbstractConcurrentDataBrokerTest dataBrokerTest = newDataBrokerTest();
339         slaveDataBroker = dataBrokerTest.getDataBroker();
340
341         slaveSystem = ActorSystem.create(ACTOR_SYSTEM_NAME, ConfigFactory.load().getConfig("Slave"));
342
343         doReturn(mockSlaveClusterSingletonServiceReg).when(mockSlaveClusterSingletonServiceProvider)
344                 .registerClusterSingletonService(any());
345
346         slaveNetconfTopologyManager = new NetconfTopologyManager(BASE_SCHEMAS, slaveDataBroker,
347                 mockSlaveClusterSingletonServiceProvider, mockKeepaliveExecutor, MoreExecutors.directExecutor(),
348                 slaveSystem, eventExecutor, mockClientDispatcher, slaveMountPointService,
349                 mockEncryptionService, mockRpcProviderService, deviceActionFactory, resourceManager, builderFactory,
350                 TOPOLOGY_ID, Uint16.ZERO) {
351             @Override
352             protected NetconfTopologyContext newNetconfTopologyContext(final NetconfTopologySetup setup,
353                 final ServiceGroupIdentifier serviceGroupIdent, final Timeout actorResponseWaitTime,
354                 final DeviceActionFactory actionFactory) {
355                 NetconfTopologyContext spiedContext = spy(super.newNetconfTopologyContext(setup, serviceGroupIdent,
356                     actorResponseWaitTime, actionFactory));
357
358                 slaveNetconfTopologyContextFuture.set(spiedContext);
359                 return spiedContext;
360             }
361         };
362
363         verifyTopologyNodesCreated(slaveDataBroker);
364
365         slaveTxChain = slaveDataBroker.createTransactionChain(new TransactionChainListener() {
366             @Override
367             public void onTransactionChainSuccessful(final TransactionChain chain) {
368             }
369
370             @Override
371             public void onTransactionChainFailed(final TransactionChain chain, final Transaction transaction,
372                     final Throwable cause) {
373                 LOG.error("Slave transaction chain failed", cause);
374             }
375         });
376     }
377
378     @Test
379     public void test() throws Exception {
380         testMaster();
381
382         testSlave();
383
384         final MasterSalFacade masterSalFacade = testMasterNodeUpdated();
385
386         testMasterDisconnected(masterSalFacade);
387
388         testCleanup();
389     }
390
391     private MasterSalFacade testMaster() throws Exception {
392         LOG.info("****** Testing master");
393
394         writeNetconfNode(TEST_DEFAULT_SUBDIR, masterDataBroker);
395
396         final var masterSalFacade = masterSalFacadeFuture.get(5, TimeUnit.SECONDS);
397         masterSalFacade.onDeviceConnected(new NetconfDeviceSchema(NetconfDeviceCapabilities.empty(),
398             MountPointContext.of(deviceSchemaContext)),
399             NetconfSessionPreferences.fromStrings(List.of(CapabilityURN.CANDIDATE)),
400             new RemoteDeviceServices(deviceRpcService, null));
401
402         final var masterMountPoint = awaitMountPoint(masterMountPointService);
403
404         LOG.info("****** Testing master DOMDataBroker operations");
405
406         testDOMDataBrokerOperations(getDOMDataBroker(masterMountPoint));
407
408         LOG.info("****** Testing master DOMRpcService");
409
410         testDOMRpcService(getDOMRpcService(masterMountPoint));
411         return masterSalFacade;
412     }
413
414     private void testSlave() throws Exception {
415         LOG.info("****** Testing slave");
416
417         writeNetconfNode("slave", slaveDataBroker);
418
419         verify(mockSlaveClusterSingletonServiceProvider, timeout(5000)).registerClusterSingletonService(any());
420
421         // Since the master and slave use separate DataBrokers we need to copy the master's oper node to the slave.
422         // This is essentially what happens in a clustered environment but we'll use a DTCL here.
423
424         masterDataBroker.registerDataTreeChangeListener(
425             DataTreeIdentifier.create(LogicalDatastoreType.OPERATIONAL, NODE_INSTANCE_ID), changes -> {
426                 final WriteTransaction slaveTx = slaveTxChain.newWriteOnlyTransaction();
427                 for (DataTreeModification<Node> dataTreeModification : changes) {
428                     DataObjectModification<Node> rootNode = dataTreeModification.getRootNode();
429                     InstanceIdentifier<Node> path = dataTreeModification.getRootPath().getRootIdentifier();
430                     switch (rootNode.getModificationType()) {
431                         case WRITE:
432                         case SUBTREE_MODIFIED:
433                             slaveTx.merge(LogicalDatastoreType.OPERATIONAL, path, rootNode.getDataAfter());
434                             break;
435                         case DELETE:
436                             slaveTx.delete(LogicalDatastoreType.OPERATIONAL, path);
437                             break;
438                         default:
439                             break;
440                     }
441                 }
442
443                 slaveTx.commit();
444             });
445
446         DOMMountPoint slaveMountPoint = awaitMountPoint(slaveMountPointService);
447
448         LOG.info("****** Testing slave DOMDataBroker operations");
449
450         testDOMDataBrokerOperations(getDOMDataBroker(slaveMountPoint));
451
452         LOG.info("****** Testing slave DOMRpcService");
453
454         testDOMRpcService(getDOMRpcService(slaveMountPoint));
455     }
456
457     private MasterSalFacade testMasterNodeUpdated() throws Exception {
458         LOG.info("****** Testing update master node");
459
460         masterMountPointService.registerProvisionListener(masterMountPointListener);
461         slaveMountPointService.registerProvisionListener(slaveMountPointListener);
462
463         masterSalFacadeFuture = SettableFuture.create();
464         writeNetconfNode(TEST_DEFAULT_SUBDIR, masterDataBroker);
465
466         verify(masterMountPointListener, timeout(5000)).onMountPointRemoved(yangNodeInstanceId);
467
468         final var masterSalFacade = masterSalFacadeFuture.get(5, TimeUnit.SECONDS);
469         masterSalFacade.onDeviceConnected(
470             new NetconfDeviceSchema(NetconfDeviceCapabilities.empty(), MountPointContext.of(deviceSchemaContext)),
471             NetconfSessionPreferences.fromStrings(List.of(CapabilityURN.CANDIDATE)),
472             new RemoteDeviceServices(deviceRpcService, null));
473
474         verify(masterMountPointListener, timeout(5000)).onMountPointCreated(yangNodeInstanceId);
475
476         verify(slaveMountPointListener, timeout(5000)).onMountPointRemoved(yangNodeInstanceId);
477         verify(slaveMountPointListener, timeout(5000)).onMountPointCreated(yangNodeInstanceId);
478
479         return masterSalFacade;
480     }
481
482     private void testMasterDisconnected(final MasterSalFacade masterSalFacade) throws Exception {
483         LOG.info("****** Testing master disconnected");
484
485         masterSalFacade.onDeviceDisconnected();
486
487         awaitMountPointNotPresent(masterMountPointService);
488
489         await().atMost(5, TimeUnit.SECONDS).until(() -> {
490             try (ReadTransaction readTx = masterDataBroker.newReadOnlyTransaction()) {
491                 Optional<Node> node = readTx.read(LogicalDatastoreType.OPERATIONAL,
492                         NODE_INSTANCE_ID).get(5, TimeUnit.SECONDS);
493                 assertTrue(node.isPresent());
494                 final NetconfNode netconfNode = node.orElseThrow().augmentation(NetconfNode.class);
495                 return netconfNode.getConnectionStatus() != ConnectionStatus.Connected;
496             }
497         });
498
499         awaitMountPointNotPresent(slaveMountPointService);
500     }
501
502     private void testCleanup() throws Exception {
503         LOG.info("****** Testing cleanup");
504
505         slaveNetconfTopologyManager.close();
506         verify(mockSlaveClusterSingletonServiceReg).close();
507     }
508
509     private void testDOMRpcService(final DOMRpcService domRpcService)
510             throws InterruptedException, ExecutionException, TimeoutException {
511         testPutTopRpc(domRpcService, new DefaultDOMRpcResult((ContainerNode)null));
512         testPutTopRpc(domRpcService, null);
513         testPutTopRpc(domRpcService, new DefaultDOMRpcResult(ImmutableList.of(
514                 RpcResultBuilder.newError(ErrorType.APPLICATION, new ErrorTag("tag1"), "error1"),
515                 RpcResultBuilder.newError(ErrorType.APPLICATION, new ErrorTag("tag2"), "error2"))));
516
517         testGetTopRpc(domRpcService, new DefaultDOMRpcResult(bindingToNormalized.toNormalizedNodeRpcData(
518                 new GetTopOutputBuilder().setTopLevelList(oneTopLevelList()).build())));
519
520         testFailedRpc(domRpcService, getTopRpcSchemaPath, getTopInput);
521     }
522
523     private void testPutTopRpc(final DOMRpcService domRpcService, final DOMRpcResult result)
524             throws InterruptedException, ExecutionException, TimeoutException {
525         ContainerNode putTopInput = bindingToNormalized.toNormalizedNodeRpcData(
526                 new PutTopInputBuilder().setTopLevelList(oneTopLevelList()).build());
527         testRpc(domRpcService, putTopRpcSchemaPath, putTopInput, result);
528     }
529
530     private static Map<TopLevelListKey, TopLevelList> oneTopLevelList() {
531         final TopLevelListKey key = new TopLevelListKey("one");
532         return ImmutableMap.of(key, new TopLevelListBuilder().withKey(key).build());
533     }
534
535     private void testGetTopRpc(final DOMRpcService domRpcService, final DOMRpcResult result)
536             throws InterruptedException, ExecutionException, TimeoutException {
537         testRpc(domRpcService, getTopRpcSchemaPath, getTopInput, result);
538     }
539
540     private void testRpc(final DOMRpcService domRpcService, final QName qname, final ContainerNode input,
541             final DOMRpcResult result) throws InterruptedException, ExecutionException, TimeoutException {
542         final FluentFuture<DOMRpcResult> future = result == null ? FluentFutures.immediateNullFluentFuture()
543                 : FluentFutures.immediateFluentFuture(result);
544         final DOMRpcResult actual = invokeRpc(domRpcService, qname, input, future);
545         if (result == null) {
546             assertNull(actual);
547             return;
548         }
549
550         assertNotNull(actual);
551         assertEquals(result.value(), actual.value());
552
553         assertEquals(result.errors().size(), actual.errors().size());
554         Iterator<? extends RpcError> iter1 = result.errors().iterator();
555         Iterator<? extends RpcError> iter2 = actual.errors().iterator();
556         while (iter1.hasNext() && iter2.hasNext()) {
557             RpcError err1 = iter1.next();
558             RpcError err2 = iter2.next();
559             assertEquals(err1.getErrorType(), err2.getErrorType());
560             assertEquals(err1.getTag(), err2.getTag());
561             assertEquals(err1.getMessage(), err2.getMessage());
562             assertEquals(err1.getSeverity(), err2.getSeverity());
563             assertEquals(err1.getApplicationTag(), err2.getApplicationTag());
564             assertEquals(err1.getInfo(), err2.getInfo());
565         }
566     }
567
568     private void testFailedRpc(final DOMRpcService domRpcService, final QName qname, final ContainerNode input)
569             throws InterruptedException, TimeoutException {
570         try {
571             invokeRpc(domRpcService, qname, input, Futures.immediateFailedFuture(new ClusteringRpcException("mock")));
572             fail("Expected exception");
573         } catch (ExecutionException e) {
574             assertTrue(e.getCause() instanceof ClusteringRpcException);
575             assertEquals("mock", e.getCause().getMessage());
576         }
577     }
578
579     private DOMRpcResult invokeRpc(final DOMRpcService domRpcService, final QName qname, final ContainerNode input,
580             final ListenableFuture<DOMRpcResult> returnFuture)
581                 throws InterruptedException, ExecutionException, TimeoutException {
582         topRpcImplementation.init(returnFuture);
583         final ListenableFuture<? extends DOMRpcResult> resultFuture = domRpcService.invokeRpc(qname, input);
584
585         topRpcImplementation.verify(DOMRpcIdentifier.create(qname), input);
586
587         return resultFuture.get(5, TimeUnit.SECONDS);
588     }
589
590     private static void testDOMDataBrokerOperations(final DOMDataBroker dataBroker)
591             throws InterruptedException, ExecutionException, TimeoutException {
592
593         DOMDataTreeWriteTransaction writeTx = dataBroker.newWriteOnlyTransaction();
594
595         final ContainerNode topNode = Builders.containerBuilder()
596                 .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(Top.QNAME)).build();
597         final YangInstanceIdentifier topPath = YangInstanceIdentifier.of(Top.QNAME);
598         writeTx.put(LogicalDatastoreType.CONFIGURATION, topPath, topNode);
599
600         final QName name = QName.create(TopLevelList.QNAME, "name");
601         final YangInstanceIdentifier listPath = YangInstanceIdentifier.builder(topPath)
602                 .node(TopLevelList.QNAME).build();
603         final MapEntryNode listEntryNode = ImmutableNodes.mapEntry(TopLevelList.QNAME, name, "one");
604         final MapNode listNode = ImmutableNodes.mapNodeBuilder(TopLevelList.QNAME).addChild(listEntryNode).build();
605         writeTx.merge(LogicalDatastoreType.CONFIGURATION, listPath, listNode);
606         writeTx.commit().get(5, TimeUnit.SECONDS);
607
608         verifyDataInStore(dataBroker.newReadWriteTransaction(), YangInstanceIdentifier.builder(listPath)
609                 .nodeWithKey(TopLevelList.QNAME, name, "one").build(), listEntryNode);
610
611         writeTx = dataBroker.newWriteOnlyTransaction();
612         writeTx.delete(LogicalDatastoreType.CONFIGURATION, topPath);
613         writeTx.commit().get(5, TimeUnit.SECONDS);
614
615         DOMDataTreeReadWriteTransaction readTx = dataBroker.newReadWriteTransaction();
616         assertFalse(readTx.exists(LogicalDatastoreType.CONFIGURATION, topPath).get(5, TimeUnit.SECONDS));
617         assertTrue(readTx.cancel());
618     }
619
620     private static void writeNetconfNode(final String cacheDir, final DataBroker dataBroker) throws Exception {
621         putData(dataBroker, NODE_INSTANCE_ID, new NodeBuilder()
622             .withKey(NODE_INSTANCE_ID.getKey())
623             .addAugmentation(new NetconfNodeBuilder()
624                 .setHost(new Host(new IpAddress(new Ipv4Address("127.0.0.1"))))
625                 .setPort(new PortNumber(Uint16.valueOf(1234)))
626                 .setActorResponseWaitTime(Uint16.valueOf(10))
627                 .setTcpOnly(Boolean.TRUE)
628                 .setSchemaless(Boolean.FALSE)
629                 .setKeepaliveDelay(Uint32.ZERO)
630                 .setConnectionTimeoutMillis(Uint32.valueOf(5000))
631                 .setDefaultRequestTimeoutMillis(Uint32.valueOf(5000))
632                 .setMaxConnectionAttempts(Uint32.ONE)
633                 .setCredentials(new LoginPwUnencryptedBuilder()
634                     .setLoginPasswordUnencrypted(new LoginPasswordUnencryptedBuilder()
635                         .setUsername("user")
636                         .setPassword("pass")
637                         .build())
638                     .build())
639                 .setSchemaCacheDirectory(cacheDir)
640                 .build())
641             .build());
642     }
643
644     private static <T extends DataObject> void putData(final DataBroker databroker, final InstanceIdentifier<T> path,
645             final T data) throws Exception {
646         final var writeTx = databroker.newWriteOnlyTransaction();
647         writeTx.put(LogicalDatastoreType.CONFIGURATION, path, data);
648         writeTx.commit().get(5, TimeUnit.SECONDS);
649     }
650
651     private static void verifyDataInStore(final DOMDataTreeReadOperations readTx, final YangInstanceIdentifier path,
652             final NormalizedNode expNode) throws InterruptedException, ExecutionException, TimeoutException {
653         assertEquals(Optional.of(expNode), readTx.read(LogicalDatastoreType.CONFIGURATION, path)
654             .get(5, TimeUnit.SECONDS));
655         assertTrue(readTx.exists(LogicalDatastoreType.CONFIGURATION, path).get(5, TimeUnit.SECONDS));
656     }
657
658     private static void verifyTopologyNodesCreated(final DataBroker dataBroker) {
659         await().atMost(5, TimeUnit.SECONDS).until(() -> {
660             try (ReadTransaction readTx = dataBroker.newReadOnlyTransaction()) {
661                 return readTx.exists(LogicalDatastoreType.OPERATIONAL,
662                     NetconfTopologyUtils.createTopologyListPath(TOPOLOGY_ID)).get(3, TimeUnit.SECONDS);
663             }
664         });
665     }
666
667     private AbstractConcurrentDataBrokerTest newDataBrokerTest() throws Exception {
668         final var dataBrokerTest = new AbstractConcurrentDataBrokerTest(true) {
669             @Override
670             protected Set<YangModuleInfo> getModuleInfos() {
671                 return Set.of(
672                     BindingRuntimeHelpers.getYangModuleInfo(NetconfNode.class),
673                     BindingRuntimeHelpers.getYangModuleInfo(NetworkTopology.class),
674                     BindingRuntimeHelpers.getYangModuleInfo(Keystore.class),
675                     topModuleInfo);
676             }
677         };
678
679         dataBrokerTest.setup();
680
681         final var path = NetconfTopologyUtils.createTopologyListPath(TOPOLOGY_ID);
682         putData(dataBrokerTest.getDataBroker(), path, new TopologyBuilder().withKey(path.getKey()).build());
683         return dataBrokerTest;
684     }
685
686     private void awaitMountPointNotPresent(final DOMMountPointService mountPointService) {
687         await().atMost(5, TimeUnit.SECONDS).until(
688             () -> mountPointService.getMountPoint(yangNodeInstanceId).isEmpty());
689     }
690
691     private static DOMDataBroker getDOMDataBroker(final DOMMountPoint mountPoint) {
692         return getMountPointService(mountPoint, DOMDataBroker.class);
693     }
694
695     private static DOMRpcService getDOMRpcService(final DOMMountPoint mountPoint) {
696         return getMountPointService(mountPoint, DOMRpcService.class);
697     }
698
699     private static DOMActionService getDomActionService(final DOMMountPoint mountPoint) {
700         return getMountPointService(mountPoint, DOMActionService.class);
701     }
702
703     private static <T extends DOMService> T getMountPointService(final DOMMountPoint mountPoint,
704             final Class<T> serviceClass) {
705         return mountPoint.getService(serviceClass).orElseThrow();
706     }
707
708     private DOMMountPoint awaitMountPoint(final DOMMountPointService mountPointService) {
709         await().atMost(5, TimeUnit.SECONDS).until(() ->
710                 mountPointService.getMountPoint(yangNodeInstanceId).isPresent());
711
712         return mountPointService.getMountPoint(yangNodeInstanceId).orElseThrow();
713     }
714
715     private RpcDefinition findRpcDefinition(final String rpc) {
716         Module topModule = deviceSchemaContext.findModule(TOP_MODULE_NAME, topModuleInfo.getName().getRevision())
717             .orElseThrow();
718         RpcDefinition rpcDefinition = null;
719         for (RpcDefinition def: topModule.getRpcs()) {
720             if (def.getQName().getLocalName().equals(rpc)) {
721                 rpcDefinition = def;
722                 break;
723             }
724         }
725
726         assertNotNull(rpc + " rpc not found in " + topModule.getRpcs(), rpcDefinition);
727         return rpcDefinition;
728     }
729
730     private static final class TopDOMRpcImplementation implements DOMRpcImplementation {
731         private volatile SettableFuture<Entry<DOMRpcIdentifier, NormalizedNode>> rpcInvokedFuture;
732         private volatile ListenableFuture<DOMRpcResult> returnFuture;
733
734         @Override
735         public ListenableFuture<DOMRpcResult> invokeRpc(final DOMRpcIdentifier rpc, final ContainerNode input) {
736             rpcInvokedFuture.set(Map.entry(rpc, input));
737             return returnFuture;
738         }
739
740         void init(final ListenableFuture<DOMRpcResult> retFuture) {
741             returnFuture = retFuture;
742             rpcInvokedFuture = SettableFuture.create();
743         }
744
745         void verify(final DOMRpcIdentifier expRpc, final NormalizedNode expInput)
746                 throws InterruptedException, ExecutionException, TimeoutException {
747             final Entry<DOMRpcIdentifier, NormalizedNode> actual = rpcInvokedFuture.get(5, TimeUnit.SECONDS);
748             assertEquals(expRpc, actual.getKey());
749             assertEquals(expInput, actual.getValue());
750         }
751     }
752 }