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.rcf8528.data.util.EmptyMountPointContext;
128 import org.opendaylight.yangtools.util.concurrent.FluentFutures;
129 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
130 import org.opendaylight.yangtools.yang.binding.YangModuleInfo;
131 import org.opendaylight.yangtools.yang.common.QName;
132 import org.opendaylight.yangtools.yang.common.RpcError;
133 import org.opendaylight.yangtools.yang.common.RpcError.ErrorType;
134 import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
135 import org.opendaylight.yangtools.yang.common.Uint16;
136 import org.opendaylight.yangtools.yang.common.Uint32;
137 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
138 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
139 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
140 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
141 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
142 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
143 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
144 import org.opendaylight.yangtools.yang.model.api.Module;
145 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
146 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
147 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
148 import org.opendaylight.yangtools.yang.model.repo.api.RevisionSourceIdentifier;
149 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
150 import org.opendaylight.yangtools.yang.model.repo.spi.PotentialSchemaSource;
151 import org.slf4j.Logger;
152 import org.slf4j.LoggerFactory;
155 * Tests netconf mount points end-to-end.
157 * @author Thomas Pantelis
159 public class MountPointEndToEndTest {
160 private static final Logger LOG = LoggerFactory.getLogger(MountPointEndToEndTest.class);
162 private static final String TOP_MODULE_NAME = "opendaylight-mdsal-list-test";
163 private static final String ACTOR_SYSTEM_NAME = "test";
164 private static final String TOPOLOGY_ID = TopologyNetconf.QNAME.getLocalName();
165 private static final NodeId NODE_ID = new NodeId("node-id");
166 private static final InstanceIdentifier<Node> NODE_INSTANCE_ID = NetconfTopologyUtils.createTopologyNodeListPath(
167 new NodeKey(NODE_ID), TOPOLOGY_ID);
169 @Mock private DOMRpcProviderService mockRpcProviderRegistry;
170 @Mock private DOMActionProviderService mockActionProviderRegistry;
171 @Mock private NetconfClientDispatcher mockClientDispatcher;
172 @Mock private AAAEncryptionService mockEncryptionService;
173 @Mock private ThreadPool mockThreadPool;
174 @Mock private ScheduledThreadPool mockKeepaliveExecutor;
175 @Mock private DeviceActionFactory deviceActionFactory;
177 @Mock private ActorSystemProvider mockMasterActorSystemProvider;
178 @Mock private DOMMountPointListener masterMountPointListener;
179 private final DOMMountPointService masterMountPointService = new DOMMountPointServiceImpl();
180 private final DOMRpcRouter deviceRpcService = new DOMRpcRouter();
181 private DOMClusterSingletonServiceProviderImpl masterClusterSingletonServiceProvider;
182 private DataBroker masterDataBroker;
183 private DOMDataBroker deviceDOMDataBroker;
184 private ActorSystem masterSystem;
185 private NetconfTopologyManager masterNetconfTopologyManager;
186 private volatile SettableFuture<MasterSalFacade> masterSalFacadeFuture = SettableFuture.create();
188 @Mock private ActorSystemProvider mockSlaveActorSystemProvider;
189 @Mock private ClusterSingletonServiceProvider mockSlaveClusterSingletonServiceProvider;
190 @Mock private ClusterSingletonServiceRegistration mockSlaveClusterSingletonServiceReg;
191 @Mock private DOMMountPointListener slaveMountPointListener;
192 private final DOMMountPointService slaveMountPointService = new DOMMountPointServiceImpl();
193 private DataBroker slaveDataBroker;
194 private ActorSystem slaveSystem;
195 private NetconfTopologyManager slaveNetconfTopologyManager;
196 private final SettableFuture<NetconfTopologyContext> slaveNetconfTopologyContextFuture = SettableFuture.create();
197 private TransactionChain slaveTxChain;
199 private final EventExecutor eventExecutor = GlobalEventExecutor.INSTANCE;
200 private final Config config = new ConfigBuilder().setWriteTransactionIdleTimeout(Uint16.ZERO).build();
201 private SchemaContext deviceSchemaContext;
202 private YangModuleInfo topModuleInfo;
203 private SchemaPath putTopRpcSchemaPath;
204 private SchemaPath getTopRpcSchemaPath;
205 private BindingNormalizedNodeSerializer bindingToNormalized;
206 private YangInstanceIdentifier yangNodeInstanceId;
207 private final TopDOMRpcImplementation topRpcImplementation = new TopDOMRpcImplementation();
209 @SuppressWarnings({ "unchecked", "rawtypes" })
211 public void setUp() throws Exception {
216 topModuleInfo = BindingReflections.getModuleInfo(Top.class);
218 final ModuleInfoBackedContext moduleContext = ModuleInfoBackedContext.create();
219 moduleContext.addModuleInfos(Arrays.asList(topModuleInfo));
220 deviceSchemaContext = moduleContext.tryToCreateSchemaContext().get();
222 deviceRpcService.onGlobalContextUpdated(deviceSchemaContext);
224 putTopRpcSchemaPath = findRpcDefinition("put-top").getPath();
225 getTopRpcSchemaPath = findRpcDefinition("get-top").getPath();
227 deviceRpcService.getRpcProviderService().registerRpcImplementation(topRpcImplementation,
228 DOMRpcIdentifier.create(putTopRpcSchemaPath), DOMRpcIdentifier.create(getTopRpcSchemaPath));
234 yangNodeInstanceId = bindingToNormalized.toYangInstanceIdentifier(NODE_INSTANCE_ID);
236 doReturn(new SucceededFuture(GlobalEventExecutor.INSTANCE, null)).when(mockClientDispatcher)
237 .createReconnectingClient(any());
239 LOG.info("****** Setup complete");
242 private static void deleteCacheDir() {
243 FileUtils.deleteQuietly(new File(NetconfTopologyUtils.CACHE_DIRECTORY));
247 public void tearDown() throws Exception {
249 TestKit.shutdownActorSystem(slaveSystem, true);
250 TestKit.shutdownActorSystem(masterSystem, true);
253 private void setupMaster() throws Exception {
254 AbstractConcurrentDataBrokerTest dataBrokerTest = newDataBrokerTest();
255 masterDataBroker = dataBrokerTest.getDataBroker();
256 deviceDOMDataBroker = dataBrokerTest.getDomBroker();
257 bindingToNormalized = dataBrokerTest.getDataBrokerTestCustomizer().getBindingToNormalized();
259 masterSystem = ActorSystem.create(ACTOR_SYSTEM_NAME, ConfigFactory.load().getConfig("Master"));
261 masterClusterSingletonServiceProvider = new DOMClusterSingletonServiceProviderImpl(
262 new SimpleDOMEntityOwnershipService());
263 masterClusterSingletonServiceProvider.initializeProvider();
265 doReturn(masterSystem).when(mockMasterActorSystemProvider).getActorSystem();
267 doReturn(MoreExecutors.newDirectExecutorService()).when(mockThreadPool).getExecutor();
269 NetconfTopologyUtils.DEFAULT_SCHEMA_REPOSITORY.registerSchemaSource(
270 id -> Futures.immediateFuture(YangTextSchemaSource.delegateForByteSource(id,
271 topModuleInfo.getYangTextByteSource())),
272 PotentialSchemaSource.create(RevisionSourceIdentifier.create(TOP_MODULE_NAME,
273 topModuleInfo.getName().getRevision()), YangTextSchemaSource.class, 1));
275 masterNetconfTopologyManager = new NetconfTopologyManager(masterDataBroker, mockRpcProviderRegistry,
276 mockActionProviderRegistry, masterClusterSingletonServiceProvider, mockKeepaliveExecutor, mockThreadPool,
277 mockMasterActorSystemProvider, eventExecutor, mockClientDispatcher, TOPOLOGY_ID, config,
278 masterMountPointService, mockEncryptionService, deviceActionFactory) {
280 protected NetconfTopologyContext newNetconfTopologyContext(final NetconfTopologySetup setup,
281 final ServiceGroupIdentifier serviceGroupIdent, final Timeout actorResponseWaitTime,
282 final DeviceActionFactory deviceActionFact) {
283 NetconfTopologyContext context =
284 super.newNetconfTopologyContext(setup, serviceGroupIdent, actorResponseWaitTime, deviceActionFact);
286 NetconfTopologyContext spiedContext = spy(context);
287 doAnswer(invocation -> {
288 final MasterSalFacade spiedFacade = (MasterSalFacade) spy(invocation.callRealMethod());
289 doReturn(deviceDOMDataBroker).when(spiedFacade).newDeviceDataBroker();
290 masterSalFacadeFuture.set(spiedFacade);
292 }).when(spiedContext).newMasterSalFacade();
298 masterNetconfTopologyManager.init();
300 verifyTopologyNodesCreated(masterDataBroker);
303 private void setupSlave() throws Exception {
304 AbstractConcurrentDataBrokerTest dataBrokerTest = newDataBrokerTest();
305 slaveDataBroker = dataBrokerTest.getDataBroker();
307 slaveSystem = ActorSystem.create(ACTOR_SYSTEM_NAME, ConfigFactory.load().getConfig("Slave"));
309 doReturn(slaveSystem).when(mockSlaveActorSystemProvider).getActorSystem();
311 doReturn(mockSlaveClusterSingletonServiceReg).when(mockSlaveClusterSingletonServiceProvider)
312 .registerClusterSingletonService(any());
314 slaveNetconfTopologyManager = new NetconfTopologyManager(slaveDataBroker, mockRpcProviderRegistry,
315 mockActionProviderRegistry, mockSlaveClusterSingletonServiceProvider, mockKeepaliveExecutor, mockThreadPool,
316 mockSlaveActorSystemProvider, eventExecutor, mockClientDispatcher, TOPOLOGY_ID, config,
317 slaveMountPointService, mockEncryptionService, deviceActionFactory) {
319 protected NetconfTopologyContext newNetconfTopologyContext(final NetconfTopologySetup setup,
320 final ServiceGroupIdentifier serviceGroupIdent, final Timeout actorResponseWaitTime,
321 final DeviceActionFactory actionFactory) {
322 NetconfTopologyContext spiedContext = spy(super.newNetconfTopologyContext(setup, serviceGroupIdent,
323 actorResponseWaitTime, actionFactory));
325 slaveNetconfTopologyContextFuture.set(spiedContext);
330 slaveNetconfTopologyManager.init();
332 verifyTopologyNodesCreated(slaveDataBroker);
334 slaveTxChain = slaveDataBroker.createTransactionChain(new TransactionChainListener() {
336 public void onTransactionChainSuccessful(final TransactionChain chain) {
340 public void onTransactionChainFailed(final TransactionChain chain, final Transaction transaction,
341 final Throwable cause) {
342 LOG.error("Slave transaction chain failed", cause);
348 public void test() throws Exception {
353 final MasterSalFacade masterSalFacade = testMasterNodeUpdated();
355 testMasterDisconnected(masterSalFacade);
360 private MasterSalFacade testMaster() throws InterruptedException, ExecutionException, TimeoutException {
361 LOG.info("****** Testing master");
363 writeNetconfNode(NetconfTopologyUtils.DEFAULT_CACHE_DIRECTORY, masterDataBroker);
365 final MasterSalFacade masterSalFacade = masterSalFacadeFuture.get(5, TimeUnit.SECONDS);
367 masterSalFacade.onDeviceConnected(new EmptyMountPointContext(deviceSchemaContext),
368 NetconfSessionPreferences.fromStrings(Collections.emptyList()), deviceRpcService.getRpcService());
370 DOMMountPoint masterMountPoint = awaitMountPoint(masterMountPointService);
372 LOG.info("****** Testing master DOMDataBroker operations");
374 testDOMDataBrokerOperations(getDOMDataBroker(masterMountPoint));
376 LOG.info("****** Testing master DOMRpcService");
378 testDOMRpcService(getDOMRpcService(masterMountPoint));
379 return masterSalFacade;
382 private void testSlave() throws InterruptedException, ExecutionException, TimeoutException {
383 LOG.info("****** Testing slave");
385 writeNetconfNode("slave", slaveDataBroker);
387 verify(mockSlaveClusterSingletonServiceProvider, timeout(5000)).registerClusterSingletonService(any());
389 // Since the master and slave use separate DataBrokers we need to copy the master's oper node to the slave.
390 // This is essentially what happens in a clustered environment but we'll use a DTCL here.
392 masterDataBroker.registerDataTreeChangeListener(
393 DataTreeIdentifier.create(LogicalDatastoreType.OPERATIONAL, NODE_INSTANCE_ID), changes -> {
394 final WriteTransaction slaveTx = slaveTxChain.newWriteOnlyTransaction();
395 for (DataTreeModification<Node> dataTreeModification : changes) {
396 DataObjectModification<Node> rootNode = dataTreeModification.getRootNode();
397 InstanceIdentifier<Node> path = dataTreeModification.getRootPath().getRootIdentifier();
398 switch (rootNode.getModificationType()) {
400 case SUBTREE_MODIFIED:
401 slaveTx.merge(LogicalDatastoreType.OPERATIONAL, path, rootNode.getDataAfter());
404 slaveTx.delete(LogicalDatastoreType.OPERATIONAL, path);
414 DOMMountPoint slaveMountPoint = awaitMountPoint(slaveMountPointService);
416 final NetconfTopologyContext slaveNetconfTopologyContext =
417 slaveNetconfTopologyContextFuture.get(5, TimeUnit.SECONDS);
418 verify(slaveNetconfTopologyContext, never()).newMasterSalFacade();
420 LOG.info("****** Testing slave DOMDataBroker operations");
422 testDOMDataBrokerOperations(getDOMDataBroker(slaveMountPoint));
424 LOG.info("****** Testing slave DOMRpcService");
426 testDOMRpcService(getDOMRpcService(slaveMountPoint));
429 private MasterSalFacade testMasterNodeUpdated() throws InterruptedException, ExecutionException, TimeoutException {
430 LOG.info("****** Testing update master node");
432 masterMountPointService.registerProvisionListener(masterMountPointListener);
433 slaveMountPointService.registerProvisionListener(slaveMountPointListener);
435 masterSalFacadeFuture = SettableFuture.create();
436 writeNetconfNode(NetconfTopologyUtils.DEFAULT_CACHE_DIRECTORY, masterDataBroker);
438 verify(masterMountPointListener, timeout(5000)).onMountPointRemoved(yangNodeInstanceId);
440 MasterSalFacade masterSalFacade = masterSalFacadeFuture.get(5, TimeUnit.SECONDS);
442 masterSalFacade.onDeviceConnected(new EmptyMountPointContext(deviceSchemaContext),
443 NetconfSessionPreferences.fromStrings(Collections.emptyList()), deviceRpcService.getRpcService());
445 verify(masterMountPointListener, timeout(5000)).onMountPointCreated(yangNodeInstanceId);
447 verify(slaveMountPointListener, timeout(5000)).onMountPointRemoved(yangNodeInstanceId);
448 verify(slaveMountPointListener, timeout(5000)).onMountPointCreated(yangNodeInstanceId);
450 return masterSalFacade;
453 private void testMasterDisconnected(final MasterSalFacade masterSalFacade)
454 throws InterruptedException, ExecutionException, TimeoutException {
455 LOG.info("****** Testing master disconnected");
457 masterSalFacade.onDeviceDisconnected();
459 awaitMountPointNotPresent(masterMountPointService);
461 await().atMost(5, TimeUnit.SECONDS).until(() -> {
462 try (ReadTransaction readTx = masterDataBroker.newReadOnlyTransaction()) {
463 Optional<Node> node = readTx.read(LogicalDatastoreType.OPERATIONAL,
464 NODE_INSTANCE_ID).get(5, TimeUnit.SECONDS);
465 assertTrue(node.isPresent());
466 final NetconfNode netconfNode = node.get().augmentation(NetconfNode.class);
467 return netconfNode.getConnectionStatus() != NetconfNodeConnectionStatus.ConnectionStatus.Connected;
471 awaitMountPointNotPresent(slaveMountPointService);
474 private void testCleanup() throws Exception {
475 LOG.info("****** Testing cleanup");
477 slaveNetconfTopologyManager.close();
478 verify(mockSlaveClusterSingletonServiceReg).close();
481 private void testDOMRpcService(final DOMRpcService domRpcService)
482 throws InterruptedException, ExecutionException, TimeoutException {
483 testPutTopRpc(domRpcService, new DefaultDOMRpcResult((NormalizedNode<?, ?>)null));
484 testPutTopRpc(domRpcService, null);
485 testPutTopRpc(domRpcService, new DefaultDOMRpcResult(ImmutableList.of(
486 RpcResultBuilder.newError(ErrorType.APPLICATION, "tag1", "error1"),
487 RpcResultBuilder.newError(ErrorType.APPLICATION, "tag2", "error2"))));
489 testGetTopRpc(domRpcService, new DefaultDOMRpcResult(bindingToNormalized.toNormalizedNodeRpcData(
490 new GetTopOutputBuilder().setTopLevelList(Arrays.asList(new TopLevelListBuilder().setName("one")
491 .build())).build())));
493 testFailedRpc(domRpcService, getTopRpcSchemaPath, null);
496 private void testPutTopRpc(final DOMRpcService domRpcService, final DOMRpcResult result)
497 throws InterruptedException, ExecutionException, TimeoutException {
498 ContainerNode putTopInput = bindingToNormalized.toNormalizedNodeRpcData(
499 new PutTopInputBuilder().setTopLevelList(Arrays.asList(new TopLevelListBuilder().setName("one")
501 testRpc(domRpcService, putTopRpcSchemaPath, putTopInput, result);
504 private void testGetTopRpc(final DOMRpcService domRpcService, final DOMRpcResult result)
505 throws InterruptedException, ExecutionException, TimeoutException {
506 testRpc(domRpcService, getTopRpcSchemaPath, null, result);
509 private void testRpc(final DOMRpcService domRpcService, final SchemaPath schemaPath,
510 final NormalizedNode<?, ?> input, final DOMRpcResult result) throws InterruptedException,
511 ExecutionException, TimeoutException {
512 final FluentFuture<DOMRpcResult> future = result == null ? FluentFutures.immediateNullFluentFuture()
513 : FluentFutures.immediateFluentFuture(result);
514 final DOMRpcResult actual = invokeRpc(domRpcService, schemaPath, input, future);
515 if (result == null) {
520 assertNotNull(actual);
521 assertEquals(result.getResult(), actual.getResult());
523 assertEquals(result.getErrors().size(), actual.getErrors().size());
524 Iterator<? extends RpcError> iter1 = result.getErrors().iterator();
525 Iterator<? extends RpcError> iter2 = actual.getErrors().iterator();
526 while (iter1.hasNext() && iter2.hasNext()) {
527 RpcError err1 = iter1.next();
528 RpcError err2 = iter2.next();
529 assertEquals(err1.getErrorType(), err2.getErrorType());
530 assertEquals(err1.getTag(), err2.getTag());
531 assertEquals(err1.getMessage(), err2.getMessage());
532 assertEquals(err1.getSeverity(), err2.getSeverity());
533 assertEquals(err1.getApplicationTag(), err2.getApplicationTag());
534 assertEquals(err1.getInfo(), err2.getInfo());
538 private void testFailedRpc(final DOMRpcService domRpcService, final SchemaPath schemaPath,
539 final NormalizedNode<?, ?> input) throws InterruptedException, TimeoutException {
541 invokeRpc(domRpcService, schemaPath, input, FluentFutures.immediateFailedFluentFuture(
542 new ClusteringRpcException("mock")));
543 fail("Expected exception");
544 } catch (ExecutionException e) {
545 assertTrue(e.getCause() instanceof ClusteringRpcException);
546 assertEquals("mock", e.getCause().getMessage());
550 private DOMRpcResult invokeRpc(final DOMRpcService domRpcService, final SchemaPath schemaPath,
551 final NormalizedNode<?, ?> input, final FluentFuture<DOMRpcResult> returnFuture)
552 throws InterruptedException, ExecutionException, TimeoutException {
553 topRpcImplementation.init(returnFuture);
554 final ListenableFuture<DOMRpcResult> resultFuture = domRpcService.invokeRpc(schemaPath, input);
556 topRpcImplementation.verify(DOMRpcIdentifier.create(schemaPath), input);
558 return resultFuture.get(5, TimeUnit.SECONDS);
561 private static void testDOMDataBrokerOperations(final DOMDataBroker dataBroker)
562 throws InterruptedException, ExecutionException, TimeoutException {
564 DOMDataTreeWriteTransaction writeTx = dataBroker.newWriteOnlyTransaction();
566 final ContainerNode topNode = Builders.containerBuilder()
567 .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(Top.QNAME)).build();
568 final YangInstanceIdentifier topPath = YangInstanceIdentifier.of(Top.QNAME);
569 writeTx.put(LogicalDatastoreType.CONFIGURATION, topPath, topNode);
571 final QName name = QName.create(TopLevelList.QNAME, "name");
572 final YangInstanceIdentifier listPath = YangInstanceIdentifier.builder(topPath)
573 .node(TopLevelList.QNAME).build();
574 final MapEntryNode listEntryNode = ImmutableNodes.mapEntry(TopLevelList.QNAME, name, "one");
575 final MapNode listNode = ImmutableNodes.mapNodeBuilder(TopLevelList.QNAME).addChild(listEntryNode).build();
576 writeTx.merge(LogicalDatastoreType.CONFIGURATION, listPath, listNode);
577 writeTx.commit().get(5, TimeUnit.SECONDS);
579 verifyDataInStore(dataBroker.newReadWriteTransaction(), YangInstanceIdentifier.builder(listPath)
580 .nodeWithKey(TopLevelList.QNAME, name, "one").build(), listEntryNode);
582 writeTx = dataBroker.newWriteOnlyTransaction();
583 writeTx.delete(LogicalDatastoreType.CONFIGURATION, topPath);
584 writeTx.commit().get(5, TimeUnit.SECONDS);
586 DOMDataTreeReadWriteTransaction readTx = dataBroker.newReadWriteTransaction();
587 assertFalse(readTx.exists(LogicalDatastoreType.CONFIGURATION, topPath).get(5, TimeUnit.SECONDS));
588 assertTrue(readTx.cancel());
591 private static void writeNetconfNode(final String cacheDir, final DataBroker databroker)
592 throws InterruptedException, ExecutionException, TimeoutException {
593 final NetconfNode netconfNode = new NetconfNodeBuilder()
594 .setHost(new Host(new IpAddress(new Ipv4Address("127.0.0.1"))))
595 .setPort(new PortNumber(Uint16.valueOf(1234)))
596 .setActorResponseWaitTime(Uint16.valueOf(10))
597 .setTcpOnly(Boolean.TRUE)
598 .setSchemaless(Boolean.FALSE)
599 .setKeepaliveDelay(Uint32.ZERO)
600 .setConnectionTimeoutMillis(Uint32.valueOf(5000))
601 .setDefaultRequestTimeoutMillis(Uint32.valueOf(5000))
602 .setMaxConnectionAttempts(Uint32.ONE)
603 .setCredentials(new LoginPwUnencryptedBuilder().setLoginPasswordUnencrypted(
604 new LoginPasswordUnencryptedBuilder().setUsername("user").setPassword("pass").build()).build())
605 .setSchemaCacheDirectory(cacheDir)
607 final Node node = new NodeBuilder().setNodeId(NODE_ID).addAugmentation(NetconfNode.class, netconfNode).build();
609 final WriteTransaction writeTx = databroker.newWriteOnlyTransaction();
610 writeTx.put(LogicalDatastoreType.CONFIGURATION, NODE_INSTANCE_ID, node);
611 writeTx.commit().get(5, TimeUnit.SECONDS);
614 private static void verifyDataInStore(final DOMDataTreeReadOperations readTx, final YangInstanceIdentifier path,
615 final NormalizedNode<?, ?> expNode) throws InterruptedException, ExecutionException, TimeoutException {
616 final Optional<NormalizedNode<?, ?>> read = readTx.read(LogicalDatastoreType.CONFIGURATION, path)
617 .get(5, TimeUnit.SECONDS);
618 assertTrue(read.isPresent());
619 assertEquals(expNode, read.get());
621 final Boolean exists = readTx.exists(LogicalDatastoreType.CONFIGURATION, path).get(5, TimeUnit.SECONDS);
625 private static void verifyTopologyNodesCreated(final DataBroker dataBroker) {
626 await().atMost(5, TimeUnit.SECONDS).until(() -> {
627 try (ReadTransaction readTx = dataBroker.newReadOnlyTransaction()) {
628 Optional<Topology> configTopology = readTx.read(LogicalDatastoreType.CONFIGURATION,
629 NetconfTopologyUtils.createTopologyListPath(TOPOLOGY_ID)).get(3, TimeUnit.SECONDS);
630 Optional<Topology> operTopology = readTx.read(LogicalDatastoreType.OPERATIONAL,
631 NetconfTopologyUtils.createTopologyListPath(TOPOLOGY_ID)).get(3, TimeUnit.SECONDS);
632 return configTopology.isPresent() && operTopology.isPresent();
637 private AbstractConcurrentDataBrokerTest newDataBrokerTest() throws Exception {
638 AbstractConcurrentDataBrokerTest dataBrokerTest = new AbstractConcurrentDataBrokerTest(true) {
640 protected Set<YangModuleInfo> getModuleInfos() throws Exception {
641 return ImmutableSet.of(BindingReflections.getModuleInfo(NetconfNode.class),
642 BindingReflections.getModuleInfo(NetworkTopology.class),
643 BindingReflections.getModuleInfo(Topology.class),
644 BindingReflections.getModuleInfo(Keystore.class),
649 dataBrokerTest.setup();
650 return dataBrokerTest;
653 private void awaitMountPointNotPresent(final DOMMountPointService mountPointService) {
654 await().atMost(5, TimeUnit.SECONDS).until(
655 () -> !mountPointService.getMountPoint(yangNodeInstanceId).isPresent());
658 private static DOMDataBroker getDOMDataBroker(final DOMMountPoint mountPoint) {
659 return getMountPointService(mountPoint, DOMDataBroker.class);
662 private static DOMRpcService getDOMRpcService(final DOMMountPoint mountPoint) {
663 return getMountPointService(mountPoint, DOMRpcService.class);
666 private static DOMActionService getDomActionService(final DOMMountPoint mountPoint) {
667 return getMountPointService(mountPoint, DOMActionService.class);
670 private static <T extends DOMService> T getMountPointService(final DOMMountPoint mountPoint,
671 final Class<T> serviceClass) {
672 final Optional<T> maybeService = mountPoint.getService(serviceClass);
673 assertTrue(maybeService.isPresent());
674 return maybeService.get();
677 private DOMMountPoint awaitMountPoint(final DOMMountPointService mountPointService) {
678 await().atMost(5, TimeUnit.SECONDS).until(() ->
679 mountPointService.getMountPoint(yangNodeInstanceId).isPresent());
681 return mountPointService.getMountPoint(yangNodeInstanceId).get();
684 private RpcDefinition findRpcDefinition(final String rpc) {
685 Module topModule = deviceSchemaContext.findModule(TOP_MODULE_NAME, topModuleInfo.getName().getRevision()).get();
686 RpcDefinition rpcDefinition = null;
687 for (RpcDefinition def: topModule.getRpcs()) {
688 if (def.getQName().getLocalName().equals(rpc)) {
694 assertNotNull(rpc + " rpc not found in " + topModule.getRpcs(), rpcDefinition);
695 return rpcDefinition;
698 private static class TopDOMRpcImplementation implements DOMRpcImplementation {
699 private volatile SettableFuture<Entry<DOMRpcIdentifier, NormalizedNode<?, ?>>> rpcInvokedFuture;
700 private volatile FluentFuture<DOMRpcResult> returnFuture;
703 public FluentFuture<DOMRpcResult> invokeRpc(final DOMRpcIdentifier rpc,
704 final NormalizedNode<?, ?> input) {
705 rpcInvokedFuture.set(new SimpleEntry<>(rpc, input));
709 void init(final FluentFuture<DOMRpcResult> retFuture) {
710 this.returnFuture = retFuture;
711 rpcInvokedFuture = SettableFuture.create();
714 void verify(final DOMRpcIdentifier expRpc, final NormalizedNode<?, ?> expInput)
715 throws InterruptedException, ExecutionException, TimeoutException {
716 final Entry<DOMRpcIdentifier, NormalizedNode<?, ?>> actual = rpcInvokedFuture.get(5, TimeUnit.SECONDS);
717 assertEquals(expRpc, actual.getKey());
718 assertEquals(expInput, actual.getValue());