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);
282 NetconfTopologyContext spiedContext = spy(context);
283 doAnswer(invocation -> {
284 final MasterSalFacade spiedFacade = (MasterSalFacade) spy(invocation.callRealMethod());
285 doReturn(deviceDOMDataBroker).when(spiedFacade).newDeviceDataBroker();
286 masterSalFacadeFuture.set(spiedFacade);
288 }).when(spiedContext).newMasterSalFacade();
294 masterNetconfTopologyManager.init();
296 verifyTopologyNodesCreated(masterDataBroker);
299 private void setupSlave() throws Exception {
300 AbstractConcurrentDataBrokerTest dataBrokerTest = newDataBrokerTest();
301 slaveDataBroker = dataBrokerTest.getDataBroker();
303 slaveSystem = ActorSystem.create(ACTOR_SYSTEM_NAME, ConfigFactory.load().getConfig("Slave"));
305 doReturn(slaveSystem).when(mockSlaveActorSystemProvider).getActorSystem();
307 doReturn(mockSlaveClusterSingletonServiceReg).when(mockSlaveClusterSingletonServiceProvider)
308 .registerClusterSingletonService(any());
310 slaveNetconfTopologyManager = new NetconfTopologyManager(slaveDataBroker, mockRpcProviderRegistry,
311 mockActionProviderRegistry, mockSlaveClusterSingletonServiceProvider, mockKeepaliveExecutor,
312 mockThreadPool, mockSlaveActorSystemProvider, eventExecutor, mockClientDispatcher, TOPOLOGY_ID, config,
313 slaveMountPointService, mockEncryptionService, deviceActionFactory) {
315 protected NetconfTopologyContext newNetconfTopologyContext(final NetconfTopologySetup setup,
316 final ServiceGroupIdentifier serviceGroupIdent, final Timeout actorResponseWaitTime,
317 final DeviceActionFactory deviceActionFact) {
318 NetconfTopologyContext spiedContext = spy(super.newNetconfTopologyContext(setup, serviceGroupIdent,
319 actorResponseWaitTime, deviceActionFact));
320 slaveNetconfTopologyContextFuture.set(spiedContext);
325 slaveNetconfTopologyManager.init();
327 verifyTopologyNodesCreated(slaveDataBroker);
329 slaveTxChain = slaveDataBroker.createTransactionChain(new TransactionChainListener() {
331 public void onTransactionChainSuccessful(final TransactionChain chain) {
335 public void onTransactionChainFailed(final TransactionChain chain, final Transaction transaction,
336 final Throwable cause) {
337 LOG.error("Slave transaction chain failed", cause);
343 public void test() throws Exception {
348 final MasterSalFacade masterSalFacade = testMasterNodeUpdated();
350 testMasterDisconnected(masterSalFacade);
355 private MasterSalFacade testMaster() throws InterruptedException, ExecutionException, TimeoutException {
356 LOG.info("****** Testing master");
358 writeNetconfNode(NetconfTopologyUtils.DEFAULT_CACHE_DIRECTORY, masterDataBroker);
360 final MasterSalFacade masterSalFacade = masterSalFacadeFuture.get(5, TimeUnit.SECONDS);
362 masterSalFacade.onDeviceConnected(deviceSchemaContext,
363 NetconfSessionPreferences.fromStrings(Collections.emptyList()), deviceRpcService.getRpcService());
365 DOMMountPoint masterMountPoint = awaitMountPoint(masterMountPointService);
367 LOG.info("****** Testing master DOMDataBroker operations");
369 testDOMDataBrokerOperations(getDOMDataBroker(masterMountPoint));
371 LOG.info("****** Testing master DOMRpcService");
373 testDOMRpcService(getDOMRpcService(masterMountPoint));
374 return masterSalFacade;
377 private void testSlave() throws InterruptedException, ExecutionException, TimeoutException {
378 LOG.info("****** Testing slave");
380 writeNetconfNode("slave", slaveDataBroker);
382 verify(mockSlaveClusterSingletonServiceProvider, timeout(5000)).registerClusterSingletonService(any());
384 // Since the master and slave use separate DataBrokers we need to copy the master's oper node to the slave.
385 // This is essentially what happens in a clustered environment but we'll use a DTCL here.
387 masterDataBroker.registerDataTreeChangeListener(
388 DataTreeIdentifier.create(LogicalDatastoreType.OPERATIONAL, NODE_INSTANCE_ID), changes -> {
389 final WriteTransaction slaveTx = slaveTxChain.newWriteOnlyTransaction();
390 for (DataTreeModification<Node> dataTreeModification : changes) {
391 DataObjectModification<Node> rootNode = dataTreeModification.getRootNode();
392 InstanceIdentifier<Node> path = dataTreeModification.getRootPath().getRootIdentifier();
393 switch (rootNode.getModificationType()) {
395 case SUBTREE_MODIFIED:
396 slaveTx.merge(LogicalDatastoreType.OPERATIONAL, path, rootNode.getDataAfter());
399 slaveTx.delete(LogicalDatastoreType.OPERATIONAL, path);
409 DOMMountPoint slaveMountPoint = awaitMountPoint(slaveMountPointService);
411 final NetconfTopologyContext slaveNetconfTopologyContext =
412 slaveNetconfTopologyContextFuture.get(5, TimeUnit.SECONDS);
413 verify(slaveNetconfTopologyContext, never()).newMasterSalFacade();
415 LOG.info("****** Testing slave DOMDataBroker operations");
417 testDOMDataBrokerOperations(getDOMDataBroker(slaveMountPoint));
419 LOG.info("****** Testing slave DOMRpcService");
421 testDOMRpcService(getDOMRpcService(slaveMountPoint));
424 private MasterSalFacade testMasterNodeUpdated() throws InterruptedException, ExecutionException, TimeoutException {
425 LOG.info("****** Testing update master node");
427 masterMountPointService.registerProvisionListener(masterMountPointListener);
428 slaveMountPointService.registerProvisionListener(slaveMountPointListener);
430 masterSalFacadeFuture = SettableFuture.create();
431 writeNetconfNode(NetconfTopologyUtils.DEFAULT_CACHE_DIRECTORY, masterDataBroker);
433 verify(masterMountPointListener, timeout(5000)).onMountPointRemoved(yangNodeInstanceId);
435 MasterSalFacade masterSalFacade = masterSalFacadeFuture.get(5, TimeUnit.SECONDS);
437 masterSalFacade.onDeviceConnected(deviceSchemaContext,
438 NetconfSessionPreferences.fromStrings(Collections.emptyList()), deviceRpcService.getRpcService());
440 verify(masterMountPointListener, timeout(5000)).onMountPointCreated(yangNodeInstanceId);
442 verify(slaveMountPointListener, timeout(5000)).onMountPointRemoved(yangNodeInstanceId);
443 verify(slaveMountPointListener, timeout(5000)).onMountPointCreated(yangNodeInstanceId);
445 return masterSalFacade;
448 private void testMasterDisconnected(final MasterSalFacade masterSalFacade)
449 throws InterruptedException, ExecutionException, TimeoutException {
450 LOG.info("****** Testing master disconnected");
452 masterSalFacade.onDeviceDisconnected();
454 awaitMountPointNotPresent(masterMountPointService);
456 await().atMost(5, TimeUnit.SECONDS).until(() -> {
457 try (ReadTransaction readTx = masterDataBroker.newReadOnlyTransaction()) {
458 Optional<Node> node = readTx.read(LogicalDatastoreType.OPERATIONAL,
459 NODE_INSTANCE_ID).get(5, TimeUnit.SECONDS);
460 assertTrue(node.isPresent());
461 final NetconfNode netconfNode = node.get().augmentation(NetconfNode.class);
462 return netconfNode.getConnectionStatus() != NetconfNodeConnectionStatus.ConnectionStatus.Connected;
466 awaitMountPointNotPresent(slaveMountPointService);
469 private void testCleanup() throws Exception {
470 LOG.info("****** Testing cleanup");
472 slaveNetconfTopologyManager.close();
473 verify(mockSlaveClusterSingletonServiceReg).close();
476 private void testDOMRpcService(final DOMRpcService domRpcService)
477 throws InterruptedException, ExecutionException, TimeoutException {
478 testPutTopRpc(domRpcService, new DefaultDOMRpcResult((NormalizedNode<?, ?>)null));
479 testPutTopRpc(domRpcService, null);
480 testPutTopRpc(domRpcService, new DefaultDOMRpcResult(ImmutableList.of(
481 RpcResultBuilder.newError(ErrorType.APPLICATION, "tag1", "error1"),
482 RpcResultBuilder.newError(ErrorType.APPLICATION, "tag2", "error2"))));
484 testGetTopRpc(domRpcService, new DefaultDOMRpcResult(bindingToNormalized.toNormalizedNodeRpcData(
485 new GetTopOutputBuilder().setTopLevelList(Arrays.asList(new TopLevelListBuilder().setName("one")
486 .build())).build())));
488 testFailedRpc(domRpcService, getTopRpcSchemaPath, null);
491 private void testPutTopRpc(final DOMRpcService domRpcService, final DOMRpcResult result)
492 throws InterruptedException, ExecutionException, TimeoutException {
493 ContainerNode putTopInput = bindingToNormalized.toNormalizedNodeRpcData(
494 new PutTopInputBuilder().setTopLevelList(Arrays.asList(new TopLevelListBuilder().setName("one")
496 testRpc(domRpcService, putTopRpcSchemaPath, putTopInput, result);
499 private void testGetTopRpc(final DOMRpcService domRpcService, final DOMRpcResult result)
500 throws InterruptedException, ExecutionException, TimeoutException {
501 testRpc(domRpcService, getTopRpcSchemaPath, null, result);
504 private void testRpc(final DOMRpcService domRpcService, final SchemaPath schemaPath,
505 final NormalizedNode<?, ?> input, final DOMRpcResult result) throws InterruptedException,
506 ExecutionException, TimeoutException {
507 final FluentFuture<DOMRpcResult> future = result == null ? FluentFutures.immediateNullFluentFuture()
508 : FluentFutures.immediateFluentFuture(result);
509 final DOMRpcResult actual = invokeRpc(domRpcService, schemaPath, input, future);
510 if (result == null) {
515 assertNotNull(actual);
516 assertEquals(result.getResult(), actual.getResult());
518 assertEquals(result.getErrors().size(), actual.getErrors().size());
519 Iterator<? extends RpcError> iter1 = result.getErrors().iterator();
520 Iterator<? extends RpcError> iter2 = actual.getErrors().iterator();
521 while (iter1.hasNext() && iter2.hasNext()) {
522 RpcError err1 = iter1.next();
523 RpcError err2 = iter2.next();
524 assertEquals(err1.getErrorType(), err2.getErrorType());
525 assertEquals(err1.getTag(), err2.getTag());
526 assertEquals(err1.getMessage(), err2.getMessage());
527 assertEquals(err1.getSeverity(), err2.getSeverity());
528 assertEquals(err1.getApplicationTag(), err2.getApplicationTag());
529 assertEquals(err1.getInfo(), err2.getInfo());
533 private void testFailedRpc(final DOMRpcService domRpcService, final SchemaPath schemaPath,
534 final NormalizedNode<?, ?> input) throws InterruptedException, TimeoutException {
536 invokeRpc(domRpcService, schemaPath, input, FluentFutures.immediateFailedFluentFuture(
537 new ClusteringRpcException("mock")));
538 fail("Expected exception");
539 } catch (ExecutionException e) {
540 assertTrue(e.getCause() instanceof ClusteringRpcException);
541 assertEquals("mock", e.getCause().getMessage());
545 private DOMRpcResult invokeRpc(final DOMRpcService domRpcService, final SchemaPath schemaPath,
546 final NormalizedNode<?, ?> input, final FluentFuture<DOMRpcResult> returnFuture)
547 throws InterruptedException, ExecutionException, TimeoutException {
548 topRpcImplementation.init(returnFuture);
549 final ListenableFuture<DOMRpcResult> resultFuture = domRpcService.invokeRpc(schemaPath, input);
551 topRpcImplementation.verify(DOMRpcIdentifier.create(schemaPath), input);
553 return resultFuture.get(5, TimeUnit.SECONDS);
556 private static void testDOMDataBrokerOperations(final DOMDataBroker dataBroker)
557 throws InterruptedException, ExecutionException, TimeoutException {
559 DOMDataTreeWriteTransaction writeTx = dataBroker.newWriteOnlyTransaction();
561 final ContainerNode topNode = Builders.containerBuilder()
562 .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(Top.QNAME)).build();
563 final YangInstanceIdentifier topPath = YangInstanceIdentifier.of(Top.QNAME);
564 writeTx.put(LogicalDatastoreType.CONFIGURATION, topPath, topNode);
566 final QName name = QName.create(TopLevelList.QNAME, "name");
567 final YangInstanceIdentifier listPath = YangInstanceIdentifier.builder(topPath)
568 .node(TopLevelList.QNAME).build();
569 final MapEntryNode listEntryNode = ImmutableNodes.mapEntry(TopLevelList.QNAME, name, "one");
570 final MapNode listNode = ImmutableNodes.mapNodeBuilder(TopLevelList.QNAME).addChild(listEntryNode).build();
571 writeTx.merge(LogicalDatastoreType.CONFIGURATION, listPath, listNode);
572 writeTx.commit().get(5, TimeUnit.SECONDS);
574 verifyDataInStore(dataBroker.newReadWriteTransaction(), YangInstanceIdentifier.builder(listPath)
575 .nodeWithKey(TopLevelList.QNAME, name, "one").build(), listEntryNode);
577 writeTx = dataBroker.newWriteOnlyTransaction();
578 writeTx.delete(LogicalDatastoreType.CONFIGURATION, topPath);
579 writeTx.commit().get(5, TimeUnit.SECONDS);
581 DOMDataTreeReadWriteTransaction readTx = dataBroker.newReadWriteTransaction();
582 assertFalse(readTx.exists(LogicalDatastoreType.CONFIGURATION, topPath).get(5, TimeUnit.SECONDS));
583 assertTrue(readTx.cancel());
586 private static void writeNetconfNode(final String cacheDir, final DataBroker databroker)
587 throws InterruptedException, ExecutionException, TimeoutException {
588 final NetconfNode netconfNode = new NetconfNodeBuilder()
589 .setHost(new Host(new IpAddress(new Ipv4Address("127.0.0.1"))))
590 .setPort(new PortNumber(1234))
591 .setActorResponseWaitTime(10)
592 .setTcpOnly(Boolean.TRUE)
593 .setSchemaless(Boolean.FALSE)
594 .setKeepaliveDelay(0L)
595 .setConnectionTimeoutMillis(5000L)
596 .setDefaultRequestTimeoutMillis(5000L)
597 .setMaxConnectionAttempts(1L)
598 .setCredentials(new LoginPwUnencryptedBuilder().setLoginPasswordUnencrypted(
599 new LoginPasswordUnencryptedBuilder().setUsername("user").setPassword("pass").build()).build())
600 .setSchemaCacheDirectory(cacheDir)
602 final Node node = new NodeBuilder().setNodeId(NODE_ID).addAugmentation(NetconfNode.class, netconfNode).build();
604 final WriteTransaction writeTx = databroker.newWriteOnlyTransaction();
605 writeTx.put(LogicalDatastoreType.CONFIGURATION, NODE_INSTANCE_ID, node);
606 writeTx.commit().get(5, TimeUnit.SECONDS);
609 private static void verifyDataInStore(final DOMDataTreeReadOperations readTx, final YangInstanceIdentifier path,
610 final NormalizedNode<?, ?> expNode) throws InterruptedException, ExecutionException, TimeoutException {
611 final Optional<NormalizedNode<?, ?>> read = readTx.read(LogicalDatastoreType.CONFIGURATION, path)
612 .get(5, TimeUnit.SECONDS);
613 assertTrue(read.isPresent());
614 assertEquals(expNode, read.get());
616 final Boolean exists = readTx.exists(LogicalDatastoreType.CONFIGURATION, path).get(5, TimeUnit.SECONDS);
620 private static void verifyTopologyNodesCreated(final DataBroker dataBroker) {
621 await().atMost(5, TimeUnit.SECONDS).until(() -> {
622 try (ReadTransaction readTx = dataBroker.newReadOnlyTransaction()) {
623 Optional<Topology> configTopology = readTx.read(LogicalDatastoreType.CONFIGURATION,
624 NetconfTopologyUtils.createTopologyListPath(TOPOLOGY_ID)).get(3, TimeUnit.SECONDS);
625 Optional<Topology> operTopology = readTx.read(LogicalDatastoreType.OPERATIONAL,
626 NetconfTopologyUtils.createTopologyListPath(TOPOLOGY_ID)).get(3, TimeUnit.SECONDS);
627 return configTopology.isPresent() && operTopology.isPresent();
632 private AbstractConcurrentDataBrokerTest newDataBrokerTest() throws Exception {
633 AbstractConcurrentDataBrokerTest dataBrokerTest = new AbstractConcurrentDataBrokerTest(true) {
635 protected Set<YangModuleInfo> getModuleInfos() throws Exception {
636 return ImmutableSet.of(BindingReflections.getModuleInfo(NetconfNode.class),
637 BindingReflections.getModuleInfo(NetworkTopology.class),
638 BindingReflections.getModuleInfo(Topology.class),
639 BindingReflections.getModuleInfo(Keystore.class),
644 dataBrokerTest.setup();
645 return dataBrokerTest;
648 private void awaitMountPointNotPresent(final DOMMountPointService mountPointService) {
649 await().atMost(5, TimeUnit.SECONDS).until(
650 () -> !mountPointService.getMountPoint(yangNodeInstanceId).isPresent());
653 private static DOMDataBroker getDOMDataBroker(final DOMMountPoint mountPoint) {
654 return getMountPointService(mountPoint, DOMDataBroker.class);
657 private static DOMRpcService getDOMRpcService(final DOMMountPoint mountPoint) {
658 return getMountPointService(mountPoint, DOMRpcService.class);
661 private static DOMActionService getDomActionService(final DOMMountPoint mountPoint) {
662 return getMountPointService(mountPoint, DOMActionService.class);
665 private static <T extends DOMService> T getMountPointService(final DOMMountPoint mountPoint,
666 final Class<T> serviceClass) {
667 final Optional<T> maybeService = mountPoint.getService(serviceClass);
668 assertTrue(maybeService.isPresent());
669 return maybeService.get();
672 private DOMMountPoint awaitMountPoint(final DOMMountPointService mountPointService) {
673 await().atMost(5, TimeUnit.SECONDS).until(() ->
674 mountPointService.getMountPoint(yangNodeInstanceId).isPresent());
676 return mountPointService.getMountPoint(yangNodeInstanceId).get();
679 private RpcDefinition findRpcDefinition(final String rpc) {
680 Module topModule = deviceSchemaContext.findModule(TOP_MODULE_NAME, topModuleInfo.getName().getRevision()).get();
681 RpcDefinition rpcDefinition = null;
682 for (RpcDefinition def: topModule.getRpcs()) {
683 if (def.getQName().getLocalName().equals(rpc)) {
689 assertNotNull(rpc + " rpc not found in " + topModule.getRpcs(), rpcDefinition);
690 return rpcDefinition;
693 private static class TopDOMRpcImplementation implements DOMRpcImplementation {
694 private volatile SettableFuture<Entry<DOMRpcIdentifier, NormalizedNode<?, ?>>> rpcInvokedFuture;
695 private volatile FluentFuture<DOMRpcResult> returnFuture;
698 public FluentFuture<DOMRpcResult> invokeRpc(final DOMRpcIdentifier rpc,
699 final NormalizedNode<?, ?> input) {
700 rpcInvokedFuture.set(new SimpleEntry<>(rpc, input));
704 void init(final FluentFuture<DOMRpcResult> retFuture) {
705 this.returnFuture = retFuture;
706 rpcInvokedFuture = SettableFuture.create();
709 void verify(final DOMRpcIdentifier expRpc, final NormalizedNode<?, ?> expInput)
710 throws InterruptedException, ExecutionException, TimeoutException {
711 final Entry<DOMRpcIdentifier, NormalizedNode<?, ?>> actual = rpcInvokedFuture.get(5, TimeUnit.SECONDS);
712 assertEquals(expRpc, actual.getKey());
713 assertEquals(expInput, actual.getValue());