2 * Copyright (c) 2018 Inocybe Technologies and others. All rights reserved.
4 * This program and the accompanying materials are made available under the
5 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6 * and is available at http://www.eclipse.org/legal/epl-v10.html
8 package org.opendaylight.netconf.topology.singleton.impl;
10 import static org.awaitility.Awaitility.await;
11 import static org.junit.Assert.assertEquals;
12 import static org.junit.Assert.assertFalse;
13 import static org.junit.Assert.assertNotNull;
14 import static org.junit.Assert.assertNull;
15 import static org.junit.Assert.assertTrue;
16 import static org.junit.Assert.fail;
17 import static org.mockito.ArgumentMatchers.any;
18 import static org.mockito.Mockito.doAnswer;
19 import static org.mockito.Mockito.doReturn;
20 import static org.mockito.Mockito.never;
21 import static org.mockito.Mockito.spy;
22 import static org.mockito.Mockito.timeout;
23 import static org.mockito.Mockito.verify;
24 import static org.mockito.MockitoAnnotations.initMocks;
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.ImmutableSet;
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 io.netty.util.concurrent.SucceededFuture;
41 import java.util.AbstractMap.SimpleEntry;
42 import java.util.Arrays;
43 import java.util.Collections;
44 import java.util.Iterator;
45 import java.util.Map.Entry;
46 import java.util.Optional;
48 import java.util.concurrent.ExecutionException;
49 import java.util.concurrent.TimeUnit;
50 import java.util.concurrent.TimeoutException;
51 import org.apache.commons.io.FileUtils;
52 import org.junit.After;
53 import org.junit.Before;
54 import org.junit.Test;
55 import org.mockito.Mock;
56 import org.opendaylight.aaa.encrypt.AAAEncryptionService;
57 import org.opendaylight.controller.cluster.ActorSystemProvider;
58 import org.opendaylight.controller.config.threadpool.ScheduledThreadPool;
59 import org.opendaylight.controller.config.threadpool.ThreadPool;
60 import org.opendaylight.mdsal.binding.api.DataBroker;
61 import org.opendaylight.mdsal.binding.api.DataObjectModification;
62 import org.opendaylight.mdsal.binding.api.DataTreeIdentifier;
63 import org.opendaylight.mdsal.binding.api.DataTreeModification;
64 import org.opendaylight.mdsal.binding.api.ReadTransaction;
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.generator.impl.ModuleInfoBackedContext;
72 import org.opendaylight.mdsal.binding.spec.reflect.BindingReflections;
73 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
74 import org.opendaylight.mdsal.dom.api.DOMActionProviderService;
75 import org.opendaylight.mdsal.dom.api.DOMActionService;
76 import org.opendaylight.mdsal.dom.api.DOMDataBroker;
77 import org.opendaylight.mdsal.dom.api.DOMDataTreeReadOperations;
78 import org.opendaylight.mdsal.dom.api.DOMDataTreeReadWriteTransaction;
79 import org.opendaylight.mdsal.dom.api.DOMDataTreeWriteTransaction;
80 import org.opendaylight.mdsal.dom.api.DOMMountPoint;
81 import org.opendaylight.mdsal.dom.api.DOMMountPointListener;
82 import org.opendaylight.mdsal.dom.api.DOMMountPointService;
83 import org.opendaylight.mdsal.dom.api.DOMRpcIdentifier;
84 import org.opendaylight.mdsal.dom.api.DOMRpcImplementation;
85 import org.opendaylight.mdsal.dom.api.DOMRpcProviderService;
86 import org.opendaylight.mdsal.dom.api.DOMRpcResult;
87 import org.opendaylight.mdsal.dom.api.DOMRpcService;
88 import org.opendaylight.mdsal.dom.api.DOMService;
89 import org.opendaylight.mdsal.dom.broker.DOMMountPointServiceImpl;
90 import org.opendaylight.mdsal.dom.broker.DOMRpcRouter;
91 import org.opendaylight.mdsal.dom.spi.DefaultDOMRpcResult;
92 import org.opendaylight.mdsal.eos.dom.simple.SimpleDOMEntityOwnershipService;
93 import org.opendaylight.mdsal.singleton.common.api.ClusterSingletonServiceProvider;
94 import org.opendaylight.mdsal.singleton.common.api.ClusterSingletonServiceRegistration;
95 import org.opendaylight.mdsal.singleton.common.api.ServiceGroupIdentifier;
96 import org.opendaylight.mdsal.singleton.dom.impl.DOMClusterSingletonServiceProviderImpl;
97 import org.opendaylight.netconf.client.NetconfClientDispatcher;
98 import org.opendaylight.netconf.sal.connect.api.DeviceActionFactory;
99 import org.opendaylight.netconf.sal.connect.netconf.listener.NetconfSessionPreferences;
100 import org.opendaylight.netconf.topology.singleton.impl.utils.ClusteringRpcException;
101 import org.opendaylight.netconf.topology.singleton.impl.utils.NetconfTopologySetup;
102 import org.opendaylight.netconf.topology.singleton.impl.utils.NetconfTopologyUtils;
103 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Host;
104 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpAddress;
105 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Ipv4Address;
106 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.PortNumber;
107 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.keystore.rev171017.Keystore;
108 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.NetconfNode;
109 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.NetconfNodeBuilder;
110 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.NetconfNodeConnectionStatus;
111 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.credentials.credentials.LoginPwUnencryptedBuilder;
112 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.credentials.credentials.login.pw.unencrypted.LoginPasswordUnencryptedBuilder;
113 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.network.topology.topology.topology.types.TopologyNetconf;
114 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.topology.singleton.config.rev170419.Config;
115 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.topology.singleton.config.rev170419.ConfigBuilder;
116 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.list.rev140701.GetTopOutputBuilder;
117 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.list.rev140701.PutTopInputBuilder;
118 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.list.rev140701.Top;
119 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.list.rev140701.two.level.list.TopLevelList;
120 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.list.rev140701.two.level.list.TopLevelListBuilder;
121 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NetworkTopology;
122 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NodeId;
123 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.Topology;
124 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node;
125 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.NodeBuilder;
126 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.NodeKey;
127 import org.opendaylight.yangtools.util.concurrent.FluentFutures;
128 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
129 import org.opendaylight.yangtools.yang.binding.YangModuleInfo;
130 import org.opendaylight.yangtools.yang.common.QName;
131 import org.opendaylight.yangtools.yang.common.RpcError;
132 import org.opendaylight.yangtools.yang.common.RpcError.ErrorType;
133 import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
134 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
135 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
136 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
137 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
138 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
139 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
140 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
141 import org.opendaylight.yangtools.yang.model.api.Module;
142 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
143 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
144 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
145 import org.opendaylight.yangtools.yang.model.repo.api.RevisionSourceIdentifier;
146 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
147 import org.opendaylight.yangtools.yang.model.repo.spi.PotentialSchemaSource;
148 import org.slf4j.Logger;
149 import org.slf4j.LoggerFactory;
152 * Tests netconf mount points end-to-end.
154 * @author Thomas Pantelis
156 public class MountPointEndToEndTest {
157 private static final Logger LOG = LoggerFactory.getLogger(MountPointEndToEndTest.class);
159 private static final String TOP_MODULE_NAME = "opendaylight-mdsal-list-test";
160 private static final String ACTOR_SYSTEM_NAME = "test";
161 private static final String TOPOLOGY_ID = TopologyNetconf.QNAME.getLocalName();
162 private static final NodeId NODE_ID = new NodeId("node-id");
163 private static final InstanceIdentifier<Node> NODE_INSTANCE_ID = NetconfTopologyUtils.createTopologyNodeListPath(
164 new NodeKey(NODE_ID), TOPOLOGY_ID);
166 @Mock private DOMRpcProviderService mockRpcProviderRegistry;
167 @Mock private DOMActionProviderService mockActionProviderRegistry;
168 @Mock private NetconfClientDispatcher mockClientDispatcher;
169 @Mock private AAAEncryptionService mockEncryptionService;
170 @Mock private ThreadPool mockThreadPool;
171 @Mock private ScheduledThreadPool mockKeepaliveExecutor;
172 @Mock private DeviceActionFactory deviceActionFactory;
174 @Mock private ActorSystemProvider mockMasterActorSystemProvider;
175 @Mock private DOMMountPointListener masterMountPointListener;
176 private final DOMMountPointService masterMountPointService = new DOMMountPointServiceImpl();
177 private final DOMRpcRouter deviceRpcService = new DOMRpcRouter();
178 private DOMClusterSingletonServiceProviderImpl masterClusterSingletonServiceProvider;
179 private DataBroker masterDataBroker;
180 private DOMDataBroker deviceDOMDataBroker;
181 private ActorSystem masterSystem;
182 private NetconfTopologyManager masterNetconfTopologyManager;
183 private volatile SettableFuture<MasterSalFacade> masterSalFacadeFuture = SettableFuture.create();
185 @Mock private ActorSystemProvider mockSlaveActorSystemProvider;
186 @Mock private ClusterSingletonServiceProvider mockSlaveClusterSingletonServiceProvider;
187 @Mock private ClusterSingletonServiceRegistration mockSlaveClusterSingletonServiceReg;
188 @Mock private DOMMountPointListener slaveMountPointListener;
189 private final DOMMountPointService slaveMountPointService = new DOMMountPointServiceImpl();
190 private DataBroker slaveDataBroker;
191 private ActorSystem slaveSystem;
192 private NetconfTopologyManager slaveNetconfTopologyManager;
193 private final SettableFuture<NetconfTopologyContext> slaveNetconfTopologyContextFuture = SettableFuture.create();
194 private TransactionChain slaveTxChain;
196 private final EventExecutor eventExecutor = GlobalEventExecutor.INSTANCE;
197 private final Config config = new ConfigBuilder().setWriteTransactionIdleTimeout(0).build();
198 private SchemaContext deviceSchemaContext;
199 private YangModuleInfo topModuleInfo;
200 private SchemaPath putTopRpcSchemaPath;
201 private SchemaPath getTopRpcSchemaPath;
202 private BindingNormalizedNodeSerializer bindingToNormalized;
203 private YangInstanceIdentifier yangNodeInstanceId;
204 private final TopDOMRpcImplementation topRpcImplementation = new TopDOMRpcImplementation();
206 @SuppressWarnings({ "unchecked", "rawtypes" })
208 public void setUp() throws Exception {
213 topModuleInfo = BindingReflections.getModuleInfo(Top.class);
215 final ModuleInfoBackedContext moduleContext = ModuleInfoBackedContext.create();
216 moduleContext.addModuleInfos(Arrays.asList(topModuleInfo));
217 deviceSchemaContext = moduleContext.tryToCreateSchemaContext().get();
219 deviceRpcService.onGlobalContextUpdated(deviceSchemaContext);
221 putTopRpcSchemaPath = findRpcDefinition("put-top").getPath();
222 getTopRpcSchemaPath = findRpcDefinition("get-top").getPath();
224 deviceRpcService.getRpcProviderService().registerRpcImplementation(topRpcImplementation,
225 DOMRpcIdentifier.create(putTopRpcSchemaPath), DOMRpcIdentifier.create(getTopRpcSchemaPath));
231 yangNodeInstanceId = bindingToNormalized.toYangInstanceIdentifier(NODE_INSTANCE_ID);
233 doReturn(new SucceededFuture(GlobalEventExecutor.INSTANCE, null)).when(mockClientDispatcher)
234 .createReconnectingClient(any());
236 LOG.info("****** Setup complete");
239 private static void deleteCacheDir() {
240 FileUtils.deleteQuietly(new File(NetconfTopologyUtils.CACHE_DIRECTORY));
244 public void tearDown() throws Exception {
246 TestKit.shutdownActorSystem(slaveSystem, true);
247 TestKit.shutdownActorSystem(masterSystem, true);
250 private void setupMaster() throws Exception {
251 AbstractConcurrentDataBrokerTest dataBrokerTest = newDataBrokerTest();
252 masterDataBroker = dataBrokerTest.getDataBroker();
253 deviceDOMDataBroker = dataBrokerTest.getDomBroker();
254 bindingToNormalized = dataBrokerTest.getDataBrokerTestCustomizer().getBindingToNormalized();
256 masterSystem = ActorSystem.create(ACTOR_SYSTEM_NAME, ConfigFactory.load().getConfig("Master"));
258 masterClusterSingletonServiceProvider = new DOMClusterSingletonServiceProviderImpl(
259 new SimpleDOMEntityOwnershipService());
260 masterClusterSingletonServiceProvider.initializeProvider();
262 doReturn(masterSystem).when(mockMasterActorSystemProvider).getActorSystem();
264 doReturn(MoreExecutors.newDirectExecutorService()).when(mockThreadPool).getExecutor();
266 NetconfTopologyUtils.DEFAULT_SCHEMA_REPOSITORY.registerSchemaSource(
267 id -> Futures.immediateFuture(YangTextSchemaSource.delegateForByteSource(id,
268 topModuleInfo.getYangTextByteSource())),
269 PotentialSchemaSource.create(RevisionSourceIdentifier.create(TOP_MODULE_NAME,
270 topModuleInfo.getName().getRevision()), YangTextSchemaSource.class, 1));
272 masterNetconfTopologyManager = new NetconfTopologyManager(masterDataBroker, mockRpcProviderRegistry,
273 mockActionProviderRegistry, masterClusterSingletonServiceProvider, mockKeepaliveExecutor, mockThreadPool,
274 mockMasterActorSystemProvider, eventExecutor, mockClientDispatcher, TOPOLOGY_ID, config,
275 masterMountPointService, mockEncryptionService, deviceActionFactory) {
277 protected NetconfTopologyContext newNetconfTopologyContext(final NetconfTopologySetup setup,
278 final ServiceGroupIdentifier serviceGroupIdent, final Timeout actorResponseWaitTime,
279 final DeviceActionFactory deviceActionFact) {
280 NetconfTopologyContext context =
281 super.newNetconfTopologyContext(setup, serviceGroupIdent, actorResponseWaitTime, deviceActionFact);
283 NetconfTopologyContext spiedContext = spy(context);
284 doAnswer(invocation -> {
285 final MasterSalFacade spiedFacade = (MasterSalFacade) spy(invocation.callRealMethod());
286 doReturn(deviceDOMDataBroker).when(spiedFacade).newDeviceDataBroker();
287 masterSalFacadeFuture.set(spiedFacade);
289 }).when(spiedContext).newMasterSalFacade();
295 masterNetconfTopologyManager.init();
297 verifyTopologyNodesCreated(masterDataBroker);
300 private void setupSlave() throws Exception {
301 AbstractConcurrentDataBrokerTest dataBrokerTest = newDataBrokerTest();
302 slaveDataBroker = dataBrokerTest.getDataBroker();
304 slaveSystem = ActorSystem.create(ACTOR_SYSTEM_NAME, ConfigFactory.load().getConfig("Slave"));
306 doReturn(slaveSystem).when(mockSlaveActorSystemProvider).getActorSystem();
308 doReturn(mockSlaveClusterSingletonServiceReg).when(mockSlaveClusterSingletonServiceProvider)
309 .registerClusterSingletonService(any());
311 slaveNetconfTopologyManager = new NetconfTopologyManager(slaveDataBroker, mockRpcProviderRegistry,
312 mockActionProviderRegistry, mockSlaveClusterSingletonServiceProvider, mockKeepaliveExecutor, mockThreadPool,
313 mockSlaveActorSystemProvider, eventExecutor, mockClientDispatcher, TOPOLOGY_ID, config,
314 slaveMountPointService, mockEncryptionService, deviceActionFactory) {
316 protected NetconfTopologyContext newNetconfTopologyContext(final NetconfTopologySetup setup,
317 final ServiceGroupIdentifier serviceGroupIdent, final Timeout actorResponseWaitTime,
318 final DeviceActionFactory actionFactory) {
319 NetconfTopologyContext spiedContext = spy(super.newNetconfTopologyContext(setup, serviceGroupIdent,
320 actorResponseWaitTime, actionFactory));
322 slaveNetconfTopologyContextFuture.set(spiedContext);
327 slaveNetconfTopologyManager.init();
329 verifyTopologyNodesCreated(slaveDataBroker);
331 slaveTxChain = slaveDataBroker.createTransactionChain(new TransactionChainListener() {
333 public void onTransactionChainSuccessful(final TransactionChain chain) {
337 public void onTransactionChainFailed(final TransactionChain chain, final Transaction transaction,
338 final Throwable cause) {
339 LOG.error("Slave transaction chain failed", cause);
345 public void test() throws Exception {
350 final MasterSalFacade masterSalFacade = testMasterNodeUpdated();
352 testMasterDisconnected(masterSalFacade);
357 private MasterSalFacade testMaster() throws InterruptedException, ExecutionException, TimeoutException {
358 LOG.info("****** Testing master");
360 writeNetconfNode(NetconfTopologyUtils.DEFAULT_CACHE_DIRECTORY, masterDataBroker);
362 final MasterSalFacade masterSalFacade = masterSalFacadeFuture.get(5, TimeUnit.SECONDS);
364 masterSalFacade.onDeviceConnected(deviceSchemaContext,
365 NetconfSessionPreferences.fromStrings(Collections.emptyList()), deviceRpcService.getRpcService());
367 DOMMountPoint masterMountPoint = awaitMountPoint(masterMountPointService);
369 LOG.info("****** Testing master DOMDataBroker operations");
371 testDOMDataBrokerOperations(getDOMDataBroker(masterMountPoint));
373 LOG.info("****** Testing master DOMRpcService");
375 testDOMRpcService(getDOMRpcService(masterMountPoint));
376 return masterSalFacade;
379 private void testSlave() throws InterruptedException, ExecutionException, TimeoutException {
380 LOG.info("****** Testing slave");
382 writeNetconfNode("slave", slaveDataBroker);
384 verify(mockSlaveClusterSingletonServiceProvider, timeout(5000)).registerClusterSingletonService(any());
386 // Since the master and slave use separate DataBrokers we need to copy the master's oper node to the slave.
387 // This is essentially what happens in a clustered environment but we'll use a DTCL here.
389 masterDataBroker.registerDataTreeChangeListener(
390 DataTreeIdentifier.create(LogicalDatastoreType.OPERATIONAL, NODE_INSTANCE_ID), changes -> {
391 final WriteTransaction slaveTx = slaveTxChain.newWriteOnlyTransaction();
392 for (DataTreeModification<Node> dataTreeModification : changes) {
393 DataObjectModification<Node> rootNode = dataTreeModification.getRootNode();
394 InstanceIdentifier<Node> path = dataTreeModification.getRootPath().getRootIdentifier();
395 switch (rootNode.getModificationType()) {
397 case SUBTREE_MODIFIED:
398 slaveTx.merge(LogicalDatastoreType.OPERATIONAL, path, rootNode.getDataAfter());
401 slaveTx.delete(LogicalDatastoreType.OPERATIONAL, path);
411 DOMMountPoint slaveMountPoint = awaitMountPoint(slaveMountPointService);
413 final NetconfTopologyContext slaveNetconfTopologyContext =
414 slaveNetconfTopologyContextFuture.get(5, TimeUnit.SECONDS);
415 verify(slaveNetconfTopologyContext, never()).newMasterSalFacade();
417 LOG.info("****** Testing slave DOMDataBroker operations");
419 testDOMDataBrokerOperations(getDOMDataBroker(slaveMountPoint));
421 LOG.info("****** Testing slave DOMRpcService");
423 testDOMRpcService(getDOMRpcService(slaveMountPoint));
426 private MasterSalFacade testMasterNodeUpdated() throws InterruptedException, ExecutionException, TimeoutException {
427 LOG.info("****** Testing update master node");
429 masterMountPointService.registerProvisionListener(masterMountPointListener);
430 slaveMountPointService.registerProvisionListener(slaveMountPointListener);
432 masterSalFacadeFuture = SettableFuture.create();
433 writeNetconfNode(NetconfTopologyUtils.DEFAULT_CACHE_DIRECTORY, masterDataBroker);
435 verify(masterMountPointListener, timeout(5000)).onMountPointRemoved(yangNodeInstanceId);
437 MasterSalFacade masterSalFacade = masterSalFacadeFuture.get(5, TimeUnit.SECONDS);
439 masterSalFacade.onDeviceConnected(deviceSchemaContext,
440 NetconfSessionPreferences.fromStrings(Collections.emptyList()), deviceRpcService.getRpcService());
442 verify(masterMountPointListener, timeout(5000)).onMountPointCreated(yangNodeInstanceId);
444 verify(slaveMountPointListener, timeout(5000)).onMountPointRemoved(yangNodeInstanceId);
445 verify(slaveMountPointListener, timeout(5000)).onMountPointCreated(yangNodeInstanceId);
447 return masterSalFacade;
450 private void testMasterDisconnected(final MasterSalFacade masterSalFacade)
451 throws InterruptedException, ExecutionException, TimeoutException {
452 LOG.info("****** Testing master disconnected");
454 masterSalFacade.onDeviceDisconnected();
456 awaitMountPointNotPresent(masterMountPointService);
458 await().atMost(5, TimeUnit.SECONDS).until(() -> {
459 try (ReadTransaction readTx = masterDataBroker.newReadOnlyTransaction()) {
460 Optional<Node> node = readTx.read(LogicalDatastoreType.OPERATIONAL,
461 NODE_INSTANCE_ID).get(5, TimeUnit.SECONDS);
462 assertTrue(node.isPresent());
463 final NetconfNode netconfNode = node.get().augmentation(NetconfNode.class);
464 return netconfNode.getConnectionStatus() != NetconfNodeConnectionStatus.ConnectionStatus.Connected;
468 awaitMountPointNotPresent(slaveMountPointService);
471 private void testCleanup() throws Exception {
472 LOG.info("****** Testing cleanup");
474 slaveNetconfTopologyManager.close();
475 verify(mockSlaveClusterSingletonServiceReg).close();
478 private void testDOMRpcService(final DOMRpcService domRpcService)
479 throws InterruptedException, ExecutionException, TimeoutException {
480 testPutTopRpc(domRpcService, new DefaultDOMRpcResult((NormalizedNode<?, ?>)null));
481 testPutTopRpc(domRpcService, null);
482 testPutTopRpc(domRpcService, new DefaultDOMRpcResult(ImmutableList.of(
483 RpcResultBuilder.newError(ErrorType.APPLICATION, "tag1", "error1"),
484 RpcResultBuilder.newError(ErrorType.APPLICATION, "tag2", "error2"))));
486 testGetTopRpc(domRpcService, new DefaultDOMRpcResult(bindingToNormalized.toNormalizedNodeRpcData(
487 new GetTopOutputBuilder().setTopLevelList(Arrays.asList(new TopLevelListBuilder().setName("one")
488 .build())).build())));
490 testFailedRpc(domRpcService, getTopRpcSchemaPath, null);
493 private void testPutTopRpc(final DOMRpcService domRpcService, final DOMRpcResult result)
494 throws InterruptedException, ExecutionException, TimeoutException {
495 ContainerNode putTopInput = bindingToNormalized.toNormalizedNodeRpcData(
496 new PutTopInputBuilder().setTopLevelList(Arrays.asList(new TopLevelListBuilder().setName("one")
498 testRpc(domRpcService, putTopRpcSchemaPath, putTopInput, result);
501 private void testGetTopRpc(final DOMRpcService domRpcService, final DOMRpcResult result)
502 throws InterruptedException, ExecutionException, TimeoutException {
503 testRpc(domRpcService, getTopRpcSchemaPath, null, result);
506 private void testRpc(final DOMRpcService domRpcService, final SchemaPath schemaPath,
507 final NormalizedNode<?, ?> input, final DOMRpcResult result) throws InterruptedException,
508 ExecutionException, TimeoutException {
509 final FluentFuture<DOMRpcResult> future = result == null ? FluentFutures.immediateNullFluentFuture()
510 : FluentFutures.immediateFluentFuture(result);
511 final DOMRpcResult actual = invokeRpc(domRpcService, schemaPath, input, future);
512 if (result == null) {
517 assertNotNull(actual);
518 assertEquals(result.getResult(), actual.getResult());
520 assertEquals(result.getErrors().size(), actual.getErrors().size());
521 Iterator<? extends RpcError> iter1 = result.getErrors().iterator();
522 Iterator<? extends RpcError> iter2 = actual.getErrors().iterator();
523 while (iter1.hasNext() && iter2.hasNext()) {
524 RpcError err1 = iter1.next();
525 RpcError err2 = iter2.next();
526 assertEquals(err1.getErrorType(), err2.getErrorType());
527 assertEquals(err1.getTag(), err2.getTag());
528 assertEquals(err1.getMessage(), err2.getMessage());
529 assertEquals(err1.getSeverity(), err2.getSeverity());
530 assertEquals(err1.getApplicationTag(), err2.getApplicationTag());
531 assertEquals(err1.getInfo(), err2.getInfo());
535 private void testFailedRpc(final DOMRpcService domRpcService, final SchemaPath schemaPath,
536 final NormalizedNode<?, ?> input) throws InterruptedException, TimeoutException {
538 invokeRpc(domRpcService, schemaPath, input, FluentFutures.immediateFailedFluentFuture(
539 new ClusteringRpcException("mock")));
540 fail("Expected exception");
541 } catch (ExecutionException e) {
542 assertTrue(e.getCause() instanceof ClusteringRpcException);
543 assertEquals("mock", e.getCause().getMessage());
547 private DOMRpcResult invokeRpc(final DOMRpcService domRpcService, final SchemaPath schemaPath,
548 final NormalizedNode<?, ?> input, final FluentFuture<DOMRpcResult> returnFuture)
549 throws InterruptedException, ExecutionException, TimeoutException {
550 topRpcImplementation.init(returnFuture);
551 final ListenableFuture<DOMRpcResult> resultFuture = domRpcService.invokeRpc(schemaPath, input);
553 topRpcImplementation.verify(DOMRpcIdentifier.create(schemaPath), input);
555 return resultFuture.get(5, TimeUnit.SECONDS);
558 private static void testDOMDataBrokerOperations(final DOMDataBroker dataBroker)
559 throws InterruptedException, ExecutionException, TimeoutException {
561 DOMDataTreeWriteTransaction writeTx = dataBroker.newWriteOnlyTransaction();
563 final ContainerNode topNode = Builders.containerBuilder()
564 .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(Top.QNAME)).build();
565 final YangInstanceIdentifier topPath = YangInstanceIdentifier.of(Top.QNAME);
566 writeTx.put(LogicalDatastoreType.CONFIGURATION, topPath, topNode);
568 final QName name = QName.create(TopLevelList.QNAME, "name");
569 final YangInstanceIdentifier listPath = YangInstanceIdentifier.builder(topPath)
570 .node(TopLevelList.QNAME).build();
571 final MapEntryNode listEntryNode = ImmutableNodes.mapEntry(TopLevelList.QNAME, name, "one");
572 final MapNode listNode = ImmutableNodes.mapNodeBuilder(TopLevelList.QNAME).addChild(listEntryNode).build();
573 writeTx.merge(LogicalDatastoreType.CONFIGURATION, listPath, listNode);
574 writeTx.commit().get(5, TimeUnit.SECONDS);
576 verifyDataInStore(dataBroker.newReadWriteTransaction(), YangInstanceIdentifier.builder(listPath)
577 .nodeWithKey(TopLevelList.QNAME, name, "one").build(), listEntryNode);
579 writeTx = dataBroker.newWriteOnlyTransaction();
580 writeTx.delete(LogicalDatastoreType.CONFIGURATION, topPath);
581 writeTx.commit().get(5, TimeUnit.SECONDS);
583 DOMDataTreeReadWriteTransaction readTx = dataBroker.newReadWriteTransaction();
584 assertFalse(readTx.exists(LogicalDatastoreType.CONFIGURATION, topPath).get(5, TimeUnit.SECONDS));
585 assertTrue(readTx.cancel());
588 private static void writeNetconfNode(final String cacheDir, final DataBroker databroker)
589 throws InterruptedException, ExecutionException, TimeoutException {
590 final NetconfNode netconfNode = new NetconfNodeBuilder()
591 .setHost(new Host(new IpAddress(new Ipv4Address("127.0.0.1"))))
592 .setPort(new PortNumber(1234))
593 .setActorResponseWaitTime(10)
594 .setTcpOnly(Boolean.TRUE)
595 .setSchemaless(Boolean.FALSE)
596 .setKeepaliveDelay(0L)
597 .setConnectionTimeoutMillis(5000L)
598 .setDefaultRequestTimeoutMillis(5000L)
599 .setMaxConnectionAttempts(1L)
600 .setCredentials(new LoginPwUnencryptedBuilder().setLoginPasswordUnencrypted(
601 new LoginPasswordUnencryptedBuilder().setUsername("user").setPassword("pass").build()).build())
602 .setSchemaCacheDirectory(cacheDir)
604 final Node node = new NodeBuilder().setNodeId(NODE_ID).addAugmentation(NetconfNode.class, netconfNode).build();
606 final WriteTransaction writeTx = databroker.newWriteOnlyTransaction();
607 writeTx.put(LogicalDatastoreType.CONFIGURATION, NODE_INSTANCE_ID, node);
608 writeTx.commit().get(5, TimeUnit.SECONDS);
611 private static void verifyDataInStore(final DOMDataTreeReadOperations readTx, final YangInstanceIdentifier path,
612 final NormalizedNode<?, ?> expNode) throws InterruptedException, ExecutionException, TimeoutException {
613 final Optional<NormalizedNode<?, ?>> read = readTx.read(LogicalDatastoreType.CONFIGURATION, path)
614 .get(5, TimeUnit.SECONDS);
615 assertTrue(read.isPresent());
616 assertEquals(expNode, read.get());
618 final Boolean exists = readTx.exists(LogicalDatastoreType.CONFIGURATION, path).get(5, TimeUnit.SECONDS);
622 private static void verifyTopologyNodesCreated(final DataBroker dataBroker) {
623 await().atMost(5, TimeUnit.SECONDS).until(() -> {
624 try (ReadTransaction readTx = dataBroker.newReadOnlyTransaction()) {
625 Optional<Topology> configTopology = readTx.read(LogicalDatastoreType.CONFIGURATION,
626 NetconfTopologyUtils.createTopologyListPath(TOPOLOGY_ID)).get(3, TimeUnit.SECONDS);
627 Optional<Topology> operTopology = readTx.read(LogicalDatastoreType.OPERATIONAL,
628 NetconfTopologyUtils.createTopologyListPath(TOPOLOGY_ID)).get(3, TimeUnit.SECONDS);
629 return configTopology.isPresent() && operTopology.isPresent();
634 private AbstractConcurrentDataBrokerTest newDataBrokerTest() throws Exception {
635 AbstractConcurrentDataBrokerTest dataBrokerTest = new AbstractConcurrentDataBrokerTest(true) {
637 protected Set<YangModuleInfo> getModuleInfos() throws Exception {
638 return ImmutableSet.of(BindingReflections.getModuleInfo(NetconfNode.class),
639 BindingReflections.getModuleInfo(NetworkTopology.class),
640 BindingReflections.getModuleInfo(Topology.class),
641 BindingReflections.getModuleInfo(Keystore.class),
646 dataBrokerTest.setup();
647 return dataBrokerTest;
650 private void awaitMountPointNotPresent(final DOMMountPointService mountPointService) {
651 await().atMost(5, TimeUnit.SECONDS).until(
652 () -> !mountPointService.getMountPoint(yangNodeInstanceId).isPresent());
655 private static DOMDataBroker getDOMDataBroker(final DOMMountPoint mountPoint) {
656 return getMountPointService(mountPoint, DOMDataBroker.class);
659 private static DOMRpcService getDOMRpcService(final DOMMountPoint mountPoint) {
660 return getMountPointService(mountPoint, DOMRpcService.class);
663 private static DOMActionService getDomActionService(final DOMMountPoint mountPoint) {
664 return getMountPointService(mountPoint, DOMActionService.class);
667 private static <T extends DOMService> T getMountPointService(final DOMMountPoint mountPoint,
668 final Class<T> serviceClass) {
669 final Optional<T> maybeService = mountPoint.getService(serviceClass);
670 assertTrue(maybeService.isPresent());
671 return maybeService.get();
674 private DOMMountPoint awaitMountPoint(final DOMMountPointService mountPointService) {
675 await().atMost(5, TimeUnit.SECONDS).until(() ->
676 mountPointService.getMountPoint(yangNodeInstanceId).isPresent());
678 return mountPointService.getMountPoint(yangNodeInstanceId).get();
681 private RpcDefinition findRpcDefinition(final String rpc) {
682 Module topModule = deviceSchemaContext.findModule(TOP_MODULE_NAME, topModuleInfo.getName().getRevision()).get();
683 RpcDefinition rpcDefinition = null;
684 for (RpcDefinition def: topModule.getRpcs()) {
685 if (def.getQName().getLocalName().equals(rpc)) {
691 assertNotNull(rpc + " rpc not found in " + topModule.getRpcs(), rpcDefinition);
692 return rpcDefinition;
695 private static class TopDOMRpcImplementation implements DOMRpcImplementation {
696 private volatile SettableFuture<Entry<DOMRpcIdentifier, NormalizedNode<?, ?>>> rpcInvokedFuture;
697 private volatile FluentFuture<DOMRpcResult> returnFuture;
700 public FluentFuture<DOMRpcResult> invokeRpc(final DOMRpcIdentifier rpc,
701 final NormalizedNode<?, ?> input) {
702 rpcInvokedFuture.set(new SimpleEntry<>(rpc, input));
706 void init(final FluentFuture<DOMRpcResult> retFuture) {
707 this.returnFuture = retFuture;
708 rpcInvokedFuture = SettableFuture.create();
711 void verify(final DOMRpcIdentifier expRpc, final NormalizedNode<?, ?> expInput)
712 throws InterruptedException, ExecutionException, TimeoutException {
713 final Entry<DOMRpcIdentifier, NormalizedNode<?, ?>> actual = rpcInvokedFuture.get(5, TimeUnit.SECONDS);
714 assertEquals(expRpc, actual.getKey());
715 assertEquals(expInput, actual.getValue());