Add RemoteDeviceServices
[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.RemoteDeviceServices;
102 import org.opendaylight.netconf.sal.connect.api.SchemaResourceManager;
103 import org.opendaylight.netconf.sal.connect.impl.DefaultSchemaResourceManager;
104 import org.opendaylight.netconf.sal.connect.netconf.NetconfDeviceSchema;
105 import org.opendaylight.netconf.sal.connect.netconf.listener.NetconfDeviceCapabilities;
106 import org.opendaylight.netconf.sal.connect.netconf.listener.NetconfSessionPreferences;
107 import org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil;
108 import org.opendaylight.netconf.topology.singleton.impl.utils.ClusteringRpcException;
109 import org.opendaylight.netconf.topology.singleton.impl.utils.NetconfTopologySetup;
110 import org.opendaylight.netconf.topology.singleton.impl.utils.NetconfTopologyUtils;
111 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Host;
112 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpAddress;
113 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Ipv4Address;
114 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.PortNumber;
115 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.keystore.rev171017.Keystore;
116 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.NetconfNode;
117 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.NetconfNodeBuilder;
118 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.NetconfNodeConnectionStatus;
119 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.credentials.credentials.LoginPwUnencryptedBuilder;
120 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.credentials.credentials.login.pw.unencrypted.LoginPasswordUnencryptedBuilder;
121 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.network.topology.topology.topology.types.TopologyNetconf;
122 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.topology.singleton.config.rev170419.Config;
123 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.topology.singleton.config.rev170419.ConfigBuilder;
124 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.list.rev140701.GetTopInput;
125 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.list.rev140701.GetTopOutputBuilder;
126 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.list.rev140701.PutTopInputBuilder;
127 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.list.rev140701.Top;
128 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.list.rev140701.two.level.list.TopLevelList;
129 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.list.rev140701.two.level.list.TopLevelListBuilder;
130 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.list.rev140701.two.level.list.TopLevelListKey;
131 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NetworkTopology;
132 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NodeId;
133 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.TopologyBuilder;
134 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node;
135 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.NodeBuilder;
136 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.NodeKey;
137 import org.opendaylight.yangtools.rfc8528.data.api.MountPointContext;
138 import org.opendaylight.yangtools.rfc8528.data.util.EmptyMountPointContext;
139 import org.opendaylight.yangtools.util.concurrent.FluentFutures;
140 import org.opendaylight.yangtools.yang.binding.DataObject;
141 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
142 import org.opendaylight.yangtools.yang.binding.KeyedInstanceIdentifier;
143 import org.opendaylight.yangtools.yang.binding.YangModuleInfo;
144 import org.opendaylight.yangtools.yang.common.ErrorTag;
145 import org.opendaylight.yangtools.yang.common.ErrorType;
146 import org.opendaylight.yangtools.yang.common.QName;
147 import org.opendaylight.yangtools.yang.common.Revision;
148 import org.opendaylight.yangtools.yang.common.RpcError;
149 import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
150 import org.opendaylight.yangtools.yang.common.Uint16;
151 import org.opendaylight.yangtools.yang.common.Uint32;
152 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
153 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
154 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
155 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
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 = TopologyNetconf.QNAME.getLocalName();
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 DOMRpcProviderService mockRpcProviderRegistry;
188     @Mock private RpcProviderService mockRpcProviderService;
189     @Mock private DOMActionProviderService mockActionProviderRegistry;
190     @Mock private NetconfClientDispatcher mockClientDispatcher;
191     @Mock private AAAEncryptionService mockEncryptionService;
192     @Mock private ThreadPool mockThreadPool;
193     @Mock private ScheduledThreadPool mockKeepaliveExecutor;
194     @Mock private DeviceActionFactory deviceActionFactory;
195
196     @Mock private ActorSystemProvider mockMasterActorSystemProvider;
197     @Mock private DOMMountPointListener masterMountPointListener;
198     private final DOMMountPointService masterMountPointService = new DOMMountPointServiceImpl();
199     private final DOMRpcRouter deviceRpcService = new DOMRpcRouter();
200     private DOMClusterSingletonServiceProviderImpl masterClusterSingletonServiceProvider;
201     private DataBroker masterDataBroker;
202     private DOMDataBroker deviceDOMDataBroker;
203     private ActorSystem masterSystem;
204     private NetconfTopologyManager masterNetconfTopologyManager;
205     private volatile SettableFuture<MasterSalFacade> masterSalFacadeFuture = SettableFuture.create();
206
207     @Mock private ActorSystemProvider mockSlaveActorSystemProvider;
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 final EventExecutor eventExecutor = GlobalEventExecutor.INSTANCE;
219     private final Config config = new ConfigBuilder().setWriteTransactionIdleTimeout(Uint16.ZERO).build();
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 = BindingReflections.getModuleInfo(Top.class);
239
240         deviceSchemaContext = BindingRuntimeHelpers.createEffectiveModel(Top.class);
241
242         deviceRpcService.onModelContextUpdated(deviceSchemaContext);
243
244         putTopRpcSchemaPath = findRpcDefinition("put-top").getQName();
245         getTopRpcSchemaPath = findRpcDefinition("get-top").getQName();
246
247         deviceRpcService.getRpcProviderService().registerRpcImplementation(topRpcImplementation,
248                 DOMRpcIdentifier.create(putTopRpcSchemaPath), DOMRpcIdentifier.create(getTopRpcSchemaPath));
249
250         setupMaster();
251
252         setupSlave();
253
254         yangNodeInstanceId = bindingToNormalized.toYangInstanceIdentifier(NODE_INSTANCE_ID);
255
256         doReturn(mock(ReconnectFuture.class)).when(mockClientDispatcher).createReconnectingClient(any());
257
258         LOG.info("****** Setup complete");
259     }
260
261     private static void deleteCacheDir() {
262         FileUtils.deleteQuietly(new File(TEST_ROOT_DIRECTORY));
263     }
264
265     @After
266     public void tearDown() throws Exception {
267         deleteCacheDir();
268         TestKit.shutdownActorSystem(slaveSystem, true);
269         TestKit.shutdownActorSystem(masterSystem, true);
270     }
271
272     private void setupMaster() throws Exception {
273         final var dataBrokerTest = newDataBrokerTest();
274         masterDataBroker = dataBrokerTest.getDataBroker();
275         deviceDOMDataBroker = dataBrokerTest.getDomBroker();
276         bindingToNormalized = dataBrokerTest.getDataBrokerTestCustomizer().getAdapterContext().currentSerializer();
277
278         masterSystem = ActorSystem.create(ACTOR_SYSTEM_NAME, ConfigFactory.load().getConfig("Master"));
279
280         masterClusterSingletonServiceProvider = new DOMClusterSingletonServiceProviderImpl();
281         masterClusterSingletonServiceProvider.initializeProvider();
282
283         doReturn(masterSystem).when(mockMasterActorSystemProvider).getActorSystem();
284
285         doReturn(MoreExecutors.newDirectExecutorService()).when(mockThreadPool).getExecutor();
286
287         final var resources =  resourceManager.getSchemaResources(TEST_DEFAULT_SUBDIR, "test");
288         resources.getSchemaRegistry().registerSchemaSource(
289             id -> Futures.immediateFuture(YangTextSchemaSource.delegateForByteSource(id,
290                     topModuleInfo.getYangTextByteSource())),
291             PotentialSchemaSource.create(new SourceIdentifier(TOP_MODULE_NAME,
292                     topModuleInfo.getName().getRevision().map(Revision::toString).orElse(null)),
293                 YangTextSchemaSource.class, 1));
294
295         masterNetconfTopologyManager = new NetconfTopologyManager(BASE_SCHEMAS, masterDataBroker,
296                 mockRpcProviderRegistry, mockActionProviderRegistry, masterClusterSingletonServiceProvider,
297                 mockKeepaliveExecutor, mockThreadPool, mockMasterActorSystemProvider, eventExecutor,
298                 mockClientDispatcher, TOPOLOGY_ID, config, masterMountPointService, mockEncryptionService,
299                 mockRpcProviderService, deviceActionFactory, resourceManager) {
300             @Override
301             protected NetconfTopologyContext newNetconfTopologyContext(final NetconfTopologySetup setup,
302                     final ServiceGroupIdentifier serviceGroupIdent, final Timeout actorResponseWaitTime,
303                     final DeviceActionFactory deviceActionFact) {
304                 final var context = super.newNetconfTopologyContext(setup, serviceGroupIdent, actorResponseWaitTime,
305                     deviceActionFact);
306
307                 final var spiedContext = spy(context);
308                 doAnswer(invocation -> {
309                     final var spiedFacade = (MasterSalFacade) spy(invocation.callRealMethod());
310                     doReturn(deviceDOMDataBroker).when(spiedFacade)
311                         .newDeviceDataBroker(any(MountPointContext.class), any(NetconfSessionPreferences.class));
312                     masterSalFacadeFuture.set(spiedFacade);
313                     return spiedFacade;
314                 }).when(spiedContext).newMasterSalFacade();
315
316                 return spiedContext;
317             }
318         };
319
320         masterNetconfTopologyManager.init();
321
322         verifyTopologyNodesCreated(masterDataBroker);
323     }
324
325     private void setupSlave() throws Exception {
326         AbstractConcurrentDataBrokerTest dataBrokerTest = newDataBrokerTest();
327         slaveDataBroker = dataBrokerTest.getDataBroker();
328
329         slaveSystem = ActorSystem.create(ACTOR_SYSTEM_NAME, ConfigFactory.load().getConfig("Slave"));
330
331         doReturn(slaveSystem).when(mockSlaveActorSystemProvider).getActorSystem();
332
333         doReturn(mockSlaveClusterSingletonServiceReg).when(mockSlaveClusterSingletonServiceProvider)
334                 .registerClusterSingletonService(any());
335
336         slaveNetconfTopologyManager = new NetconfTopologyManager(BASE_SCHEMAS, slaveDataBroker, mockRpcProviderRegistry,
337             mockActionProviderRegistry, mockSlaveClusterSingletonServiceProvider, mockKeepaliveExecutor, mockThreadPool,
338                 mockSlaveActorSystemProvider, eventExecutor, mockClientDispatcher, TOPOLOGY_ID, config,
339                 slaveMountPointService, mockEncryptionService, mockRpcProviderService, deviceActionFactory,
340                 resourceManager) {
341             @Override
342             protected NetconfTopologyContext newNetconfTopologyContext(final NetconfTopologySetup setup,
343                 final ServiceGroupIdentifier serviceGroupIdent, final Timeout actorResponseWaitTime,
344                 final DeviceActionFactory actionFactory) {
345                 NetconfTopologyContext spiedContext = spy(super.newNetconfTopologyContext(setup, serviceGroupIdent,
346                     actorResponseWaitTime, actionFactory));
347
348                 slaveNetconfTopologyContextFuture.set(spiedContext);
349                 return spiedContext;
350             }
351         };
352
353         slaveNetconfTopologyManager.init();
354
355         verifyTopologyNodesCreated(slaveDataBroker);
356
357         slaveTxChain = slaveDataBroker.createTransactionChain(new TransactionChainListener() {
358             @Override
359             public void onTransactionChainSuccessful(final TransactionChain chain) {
360             }
361
362             @Override
363             public void onTransactionChainFailed(final TransactionChain chain, final Transaction transaction,
364                     final Throwable cause) {
365                 LOG.error("Slave transaction chain failed", cause);
366             }
367         });
368     }
369
370     @Test
371     public void test() throws Exception {
372         testMaster();
373
374         testSlave();
375
376         final MasterSalFacade masterSalFacade = testMasterNodeUpdated();
377
378         testMasterDisconnected(masterSalFacade);
379
380         testCleanup();
381     }
382
383     private MasterSalFacade testMaster() throws Exception {
384         LOG.info("****** Testing master");
385
386         writeNetconfNode(TEST_DEFAULT_SUBDIR, masterDataBroker);
387
388         final var masterSalFacade = masterSalFacadeFuture.get(5, TimeUnit.SECONDS);
389         masterSalFacade.onDeviceConnected(new NetconfDeviceSchema(NetconfDeviceCapabilities.empty(),
390             new EmptyMountPointContext(deviceSchemaContext)),
391             NetconfSessionPreferences.fromStrings(
392                 List.of(NetconfMessageTransformUtil.NETCONF_CANDIDATE_URI.toString())),
393             new RemoteDeviceServices(deviceRpcService.getRpcService(), null));
394
395         final var masterMountPoint = awaitMountPoint(masterMountPointService);
396
397         LOG.info("****** Testing master DOMDataBroker operations");
398
399         testDOMDataBrokerOperations(getDOMDataBroker(masterMountPoint));
400
401         LOG.info("****** Testing master DOMRpcService");
402
403         testDOMRpcService(getDOMRpcService(masterMountPoint));
404         return masterSalFacade;
405     }
406
407     private void testSlave() throws Exception {
408         LOG.info("****** Testing slave");
409
410         writeNetconfNode("slave", slaveDataBroker);
411
412         verify(mockSlaveClusterSingletonServiceProvider, timeout(5000)).registerClusterSingletonService(any());
413
414         // Since the master and slave use separate DataBrokers we need to copy the master's oper node to the slave.
415         // This is essentially what happens in a clustered environment but we'll use a DTCL here.
416
417         masterDataBroker.registerDataTreeChangeListener(
418             DataTreeIdentifier.create(LogicalDatastoreType.OPERATIONAL, NODE_INSTANCE_ID), changes -> {
419                 final WriteTransaction slaveTx = slaveTxChain.newWriteOnlyTransaction();
420                 for (DataTreeModification<Node> dataTreeModification : changes) {
421                     DataObjectModification<Node> rootNode = dataTreeModification.getRootNode();
422                     InstanceIdentifier<Node> path = dataTreeModification.getRootPath().getRootIdentifier();
423                     switch (rootNode.getModificationType()) {
424                         case WRITE:
425                         case SUBTREE_MODIFIED:
426                             slaveTx.merge(LogicalDatastoreType.OPERATIONAL, path, rootNode.getDataAfter());
427                             break;
428                         case DELETE:
429                             slaveTx.delete(LogicalDatastoreType.OPERATIONAL, path);
430                             break;
431                         default:
432                             break;
433                     }
434                 }
435
436                 slaveTx.commit();
437             });
438
439         DOMMountPoint slaveMountPoint = awaitMountPoint(slaveMountPointService);
440
441         final NetconfTopologyContext slaveNetconfTopologyContext =
442                 slaveNetconfTopologyContextFuture.get(5, TimeUnit.SECONDS);
443         verify(slaveNetconfTopologyContext, never()).newMasterSalFacade();
444
445         LOG.info("****** Testing slave DOMDataBroker operations");
446
447         testDOMDataBrokerOperations(getDOMDataBroker(slaveMountPoint));
448
449         LOG.info("****** Testing slave DOMRpcService");
450
451         testDOMRpcService(getDOMRpcService(slaveMountPoint));
452     }
453
454     private MasterSalFacade testMasterNodeUpdated() throws Exception {
455         LOG.info("****** Testing update master node");
456
457         masterMountPointService.registerProvisionListener(masterMountPointListener);
458         slaveMountPointService.registerProvisionListener(slaveMountPointListener);
459
460         masterSalFacadeFuture = SettableFuture.create();
461         writeNetconfNode(TEST_DEFAULT_SUBDIR, masterDataBroker);
462
463         verify(masterMountPointListener, timeout(5000)).onMountPointRemoved(yangNodeInstanceId);
464
465         final var masterSalFacade = masterSalFacadeFuture.get(5, TimeUnit.SECONDS);
466         masterSalFacade.onDeviceConnected(new NetconfDeviceSchema(NetconfDeviceCapabilities.empty(),
467             new EmptyMountPointContext(deviceSchemaContext)), NetconfSessionPreferences.fromStrings(List.of(
468                     NetconfMessageTransformUtil.NETCONF_CANDIDATE_URI.toString())),
469                 new RemoteDeviceServices(deviceRpcService.getRpcService(), null));
470
471         verify(masterMountPointListener, timeout(5000)).onMountPointCreated(yangNodeInstanceId);
472
473         verify(slaveMountPointListener, timeout(5000)).onMountPointRemoved(yangNodeInstanceId);
474         verify(slaveMountPointListener, timeout(5000)).onMountPointCreated(yangNodeInstanceId);
475
476         return masterSalFacade;
477     }
478
479     private void testMasterDisconnected(final MasterSalFacade masterSalFacade) throws Exception {
480         LOG.info("****** Testing master disconnected");
481
482         masterSalFacade.onDeviceDisconnected();
483
484         awaitMountPointNotPresent(masterMountPointService);
485
486         await().atMost(5, TimeUnit.SECONDS).until(() -> {
487             try (ReadTransaction readTx = masterDataBroker.newReadOnlyTransaction()) {
488                 Optional<Node> node = readTx.read(LogicalDatastoreType.OPERATIONAL,
489                         NODE_INSTANCE_ID).get(5, TimeUnit.SECONDS);
490                 assertTrue(node.isPresent());
491                 final NetconfNode netconfNode = node.get().augmentation(NetconfNode.class);
492                 return netconfNode.getConnectionStatus() != NetconfNodeConnectionStatus.ConnectionStatus.Connected;
493             }
494         });
495
496         awaitMountPointNotPresent(slaveMountPointService);
497     }
498
499     private void testCleanup() throws Exception {
500         LOG.info("****** Testing cleanup");
501
502         slaveNetconfTopologyManager.close();
503         verify(mockSlaveClusterSingletonServiceReg).close();
504     }
505
506     private void testDOMRpcService(final DOMRpcService domRpcService)
507             throws InterruptedException, ExecutionException, TimeoutException {
508         testPutTopRpc(domRpcService, new DefaultDOMRpcResult((NormalizedNode)null));
509         testPutTopRpc(domRpcService, null);
510         testPutTopRpc(domRpcService, new DefaultDOMRpcResult(ImmutableList.of(
511                 RpcResultBuilder.newError(ErrorType.APPLICATION, new ErrorTag("tag1"), "error1"),
512                 RpcResultBuilder.newError(ErrorType.APPLICATION, new ErrorTag("tag2"), "error2"))));
513
514         testGetTopRpc(domRpcService, new DefaultDOMRpcResult(bindingToNormalized.toNormalizedNodeRpcData(
515                 new GetTopOutputBuilder().setTopLevelList(oneTopLevelList()).build())));
516
517         testFailedRpc(domRpcService, getTopRpcSchemaPath, getTopInput);
518     }
519
520     private void testPutTopRpc(final DOMRpcService domRpcService, final DOMRpcResult result)
521             throws InterruptedException, ExecutionException, TimeoutException {
522         ContainerNode putTopInput = bindingToNormalized.toNormalizedNodeRpcData(
523                 new PutTopInputBuilder().setTopLevelList(oneTopLevelList()).build());
524         testRpc(domRpcService, putTopRpcSchemaPath, putTopInput, result);
525     }
526
527     private static Map<TopLevelListKey, TopLevelList> oneTopLevelList() {
528         final TopLevelListKey key = new TopLevelListKey("one");
529         return ImmutableMap.of(key, new TopLevelListBuilder().withKey(key).build());
530     }
531
532     private void testGetTopRpc(final DOMRpcService domRpcService, final DOMRpcResult result)
533             throws InterruptedException, ExecutionException, TimeoutException {
534         testRpc(domRpcService, getTopRpcSchemaPath, getTopInput, result);
535     }
536
537     private void testRpc(final DOMRpcService domRpcService, final QName qname, final NormalizedNode input,
538             final DOMRpcResult result) throws InterruptedException, ExecutionException, TimeoutException {
539         final FluentFuture<DOMRpcResult> future = result == null ? FluentFutures.immediateNullFluentFuture()
540                 : FluentFutures.immediateFluentFuture(result);
541         final DOMRpcResult actual = invokeRpc(domRpcService, qname, input, future);
542         if (result == null) {
543             assertNull(actual);
544             return;
545         }
546
547         assertNotNull(actual);
548         assertEquals(result.getResult(), actual.getResult());
549
550         assertEquals(result.getErrors().size(), actual.getErrors().size());
551         Iterator<? extends RpcError> iter1 = result.getErrors().iterator();
552         Iterator<? extends RpcError> iter2 = actual.getErrors().iterator();
553         while (iter1.hasNext() && iter2.hasNext()) {
554             RpcError err1 = iter1.next();
555             RpcError err2 = iter2.next();
556             assertEquals(err1.getErrorType(), err2.getErrorType());
557             assertEquals(err1.getTag(), err2.getTag());
558             assertEquals(err1.getMessage(), err2.getMessage());
559             assertEquals(err1.getSeverity(), err2.getSeverity());
560             assertEquals(err1.getApplicationTag(), err2.getApplicationTag());
561             assertEquals(err1.getInfo(), err2.getInfo());
562         }
563     }
564
565     private void testFailedRpc(final DOMRpcService domRpcService, final QName qname, final NormalizedNode input)
566             throws InterruptedException, TimeoutException {
567         try {
568             invokeRpc(domRpcService, qname, input, FluentFutures.immediateFailedFluentFuture(
569                     new ClusteringRpcException("mock")));
570             fail("Expected exception");
571         } catch (ExecutionException e) {
572             assertTrue(e.getCause() instanceof ClusteringRpcException);
573             assertEquals("mock", e.getCause().getMessage());
574         }
575     }
576
577     private DOMRpcResult invokeRpc(final DOMRpcService domRpcService, final QName qname, final NormalizedNode input,
578             final FluentFuture<DOMRpcResult> returnFuture)
579                 throws InterruptedException, ExecutionException, TimeoutException {
580         topRpcImplementation.init(returnFuture);
581         final ListenableFuture<? extends DOMRpcResult> resultFuture = domRpcService.invokeRpc(qname, input);
582
583         topRpcImplementation.verify(DOMRpcIdentifier.create(qname), input);
584
585         return resultFuture.get(5, TimeUnit.SECONDS);
586     }
587
588     private static void testDOMDataBrokerOperations(final DOMDataBroker dataBroker)
589             throws InterruptedException, ExecutionException, TimeoutException {
590
591         DOMDataTreeWriteTransaction writeTx = dataBroker.newWriteOnlyTransaction();
592
593         final ContainerNode topNode = Builders.containerBuilder()
594                 .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(Top.QNAME)).build();
595         final YangInstanceIdentifier topPath = YangInstanceIdentifier.of(Top.QNAME);
596         writeTx.put(LogicalDatastoreType.CONFIGURATION, topPath, topNode);
597
598         final QName name = QName.create(TopLevelList.QNAME, "name");
599         final YangInstanceIdentifier listPath = YangInstanceIdentifier.builder(topPath)
600                 .node(TopLevelList.QNAME).build();
601         final MapEntryNode listEntryNode = ImmutableNodes.mapEntry(TopLevelList.QNAME, name, "one");
602         final MapNode listNode = ImmutableNodes.mapNodeBuilder(TopLevelList.QNAME).addChild(listEntryNode).build();
603         writeTx.merge(LogicalDatastoreType.CONFIGURATION, listPath, listNode);
604         writeTx.commit().get(5, TimeUnit.SECONDS);
605
606         verifyDataInStore(dataBroker.newReadWriteTransaction(), YangInstanceIdentifier.builder(listPath)
607                 .nodeWithKey(TopLevelList.QNAME, name, "one").build(), listEntryNode);
608
609         writeTx = dataBroker.newWriteOnlyTransaction();
610         writeTx.delete(LogicalDatastoreType.CONFIGURATION, topPath);
611         writeTx.commit().get(5, TimeUnit.SECONDS);
612
613         DOMDataTreeReadWriteTransaction readTx = dataBroker.newReadWriteTransaction();
614         assertFalse(readTx.exists(LogicalDatastoreType.CONFIGURATION, topPath).get(5, TimeUnit.SECONDS));
615         assertTrue(readTx.cancel());
616     }
617
618     private static void writeNetconfNode(final String cacheDir, final DataBroker dataBroker) throws Exception {
619         putData(dataBroker, NODE_INSTANCE_ID, new NodeBuilder()
620             .withKey(NODE_INSTANCE_ID.getKey())
621             .addAugmentation(new NetconfNodeBuilder()
622                 .setHost(new Host(new IpAddress(new Ipv4Address("127.0.0.1"))))
623                 .setPort(new PortNumber(Uint16.valueOf(1234)))
624                 .setActorResponseWaitTime(Uint16.valueOf(10))
625                 .setTcpOnly(Boolean.TRUE)
626                 .setSchemaless(Boolean.FALSE)
627                 .setKeepaliveDelay(Uint32.ZERO)
628                 .setConnectionTimeoutMillis(Uint32.valueOf(5000))
629                 .setDefaultRequestTimeoutMillis(Uint32.valueOf(5000))
630                 .setMaxConnectionAttempts(Uint32.ONE)
631                 .setCredentials(new LoginPwUnencryptedBuilder()
632                     .setLoginPasswordUnencrypted(new LoginPasswordUnencryptedBuilder()
633                         .setUsername("user")
634                         .setPassword("pass")
635                         .build())
636                     .build())
637                 .setSchemaCacheDirectory(cacheDir)
638                 .build())
639             .build());
640     }
641
642     private static <T extends DataObject> void putData(final DataBroker databroker, final InstanceIdentifier<T> path,
643             final T data) throws Exception {
644         final var writeTx = databroker.newWriteOnlyTransaction();
645         writeTx.put(LogicalDatastoreType.CONFIGURATION, path, data);
646         writeTx.commit().get(5, TimeUnit.SECONDS);
647     }
648
649     private static void verifyDataInStore(final DOMDataTreeReadOperations readTx, final YangInstanceIdentifier path,
650             final NormalizedNode expNode) throws InterruptedException, ExecutionException, TimeoutException {
651         final Optional<NormalizedNode> read = readTx.read(LogicalDatastoreType.CONFIGURATION, path)
652                 .get(5, TimeUnit.SECONDS);
653         assertTrue(read.isPresent());
654         assertEquals(expNode, read.get());
655
656         final Boolean exists = readTx.exists(LogicalDatastoreType.CONFIGURATION, path).get(5, TimeUnit.SECONDS);
657         assertTrue(exists);
658     }
659
660     private static void verifyTopologyNodesCreated(final DataBroker dataBroker) {
661         await().atMost(5, TimeUnit.SECONDS).until(() -> {
662             try (ReadTransaction readTx = dataBroker.newReadOnlyTransaction()) {
663                 return readTx.exists(LogicalDatastoreType.OPERATIONAL,
664                     NetconfTopologyUtils.createTopologyListPath(TOPOLOGY_ID)).get(3, TimeUnit.SECONDS);
665             }
666         });
667     }
668
669     private AbstractConcurrentDataBrokerTest newDataBrokerTest() throws Exception {
670         final var dataBrokerTest = new AbstractConcurrentDataBrokerTest(true) {
671             @Override
672             protected Set<YangModuleInfo> getModuleInfos() {
673                 return Set.of(BindingReflections.getModuleInfo(NetconfNode.class),
674                         BindingReflections.getModuleInfo(NetworkTopology.class),
675                         BindingReflections.getModuleInfo(Keystore.class),
676                         topModuleInfo);
677             }
678         };
679
680         dataBrokerTest.setup();
681
682         final var path = NetconfTopologyUtils.createTopologyListPath(TOPOLOGY_ID);
683         putData(dataBrokerTest.getDataBroker(), path, new TopologyBuilder().withKey(path.getKey()).build());
684         return dataBrokerTest;
685     }
686
687     private void awaitMountPointNotPresent(final DOMMountPointService mountPointService) {
688         await().atMost(5, TimeUnit.SECONDS).until(
689             () -> mountPointService.getMountPoint(yangNodeInstanceId).isEmpty());
690     }
691
692     private static DOMDataBroker getDOMDataBroker(final DOMMountPoint mountPoint) {
693         return getMountPointService(mountPoint, DOMDataBroker.class);
694     }
695
696     private static DOMRpcService getDOMRpcService(final DOMMountPoint mountPoint) {
697         return getMountPointService(mountPoint, DOMRpcService.class);
698     }
699
700     private static DOMActionService getDomActionService(final DOMMountPoint mountPoint) {
701         return getMountPointService(mountPoint, DOMActionService.class);
702     }
703
704     private static <T extends DOMService> T getMountPointService(final DOMMountPoint mountPoint,
705             final Class<T> serviceClass) {
706         return mountPoint.getService(serviceClass).orElseThrow();
707     }
708
709     private DOMMountPoint awaitMountPoint(final DOMMountPointService mountPointService) {
710         await().atMost(5, TimeUnit.SECONDS).until(() ->
711                 mountPointService.getMountPoint(yangNodeInstanceId).isPresent());
712
713         return mountPointService.getMountPoint(yangNodeInstanceId).orElseThrow();
714     }
715
716     private RpcDefinition findRpcDefinition(final String rpc) {
717         Module topModule = deviceSchemaContext.findModule(TOP_MODULE_NAME, topModuleInfo.getName().getRevision()).get();
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 class TopDOMRpcImplementation implements DOMRpcImplementation {
731         private volatile SettableFuture<Entry<DOMRpcIdentifier, NormalizedNode>> rpcInvokedFuture;
732         private volatile FluentFuture<DOMRpcResult> returnFuture;
733
734         @Override
735         public FluentFuture<DOMRpcResult> invokeRpc(final DOMRpcIdentifier rpc, final NormalizedNode input) {
736             rpcInvokedFuture.set(Map.entry(rpc, input));
737             return returnFuture;
738         }
739
740         void init(final FluentFuture<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 }