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