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.DOMDataBroker;
75 import org.opendaylight.mdsal.dom.api.DOMDataTreeReadTransaction;
76 import org.opendaylight.mdsal.dom.api.DOMDataTreeReadWriteTransaction;
77 import org.opendaylight.mdsal.dom.api.DOMDataTreeWriteTransaction;
78 import org.opendaylight.mdsal.dom.api.DOMMountPoint;
79 import org.opendaylight.mdsal.dom.api.DOMMountPointListener;
80 import org.opendaylight.mdsal.dom.api.DOMMountPointService;
81 import org.opendaylight.mdsal.dom.api.DOMRpcIdentifier;
82 import org.opendaylight.mdsal.dom.api.DOMRpcImplementation;
83 import org.opendaylight.mdsal.dom.api.DOMRpcProviderService;
84 import org.opendaylight.mdsal.dom.api.DOMRpcResult;
85 import org.opendaylight.mdsal.dom.api.DOMRpcService;
86 import org.opendaylight.mdsal.dom.api.DOMService;
87 import org.opendaylight.mdsal.dom.broker.DOMMountPointServiceImpl;
88 import org.opendaylight.mdsal.dom.broker.DOMRpcRouter;
89 import org.opendaylight.mdsal.dom.spi.DefaultDOMRpcResult;
90 import org.opendaylight.mdsal.eos.dom.simple.SimpleDOMEntityOwnershipService;
91 import org.opendaylight.mdsal.singleton.common.api.ClusterSingletonServiceProvider;
92 import org.opendaylight.mdsal.singleton.common.api.ClusterSingletonServiceRegistration;
93 import org.opendaylight.mdsal.singleton.common.api.ServiceGroupIdentifier;
94 import org.opendaylight.mdsal.singleton.dom.impl.DOMClusterSingletonServiceProviderImpl;
95 import org.opendaylight.netconf.client.NetconfClientDispatcher;
96 import org.opendaylight.netconf.sal.connect.netconf.listener.NetconfSessionPreferences;
97 import org.opendaylight.netconf.topology.singleton.impl.utils.ClusteringRpcException;
98 import org.opendaylight.netconf.topology.singleton.impl.utils.NetconfTopologySetup;
99 import org.opendaylight.netconf.topology.singleton.impl.utils.NetconfTopologyUtils;
100 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Host;
101 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpAddress;
102 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Ipv4Address;
103 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.PortNumber;
104 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.keystore.rev171017.Keystore;
105 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.NetconfNode;
106 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.NetconfNodeBuilder;
107 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.NetconfNodeConnectionStatus;
108 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.credentials.credentials.LoginPwUnencryptedBuilder;
109 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.credentials.credentials.login.pw.unencrypted.LoginPasswordUnencryptedBuilder;
110 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.network.topology.topology.topology.types.TopologyNetconf;
111 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.topology.singleton.config.rev170419.Config;
112 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.topology.singleton.config.rev170419.ConfigBuilder;
113 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.list.rev140701.GetTopOutputBuilder;
114 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.list.rev140701.PutTopInputBuilder;
115 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.list.rev140701.Top;
116 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.list.rev140701.two.level.list.TopLevelList;
117 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.list.rev140701.two.level.list.TopLevelListBuilder;
118 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NetworkTopology;
119 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NodeId;
120 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.Topology;
121 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node;
122 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.NodeBuilder;
123 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.NodeKey;
124 import org.opendaylight.yangtools.util.concurrent.FluentFutures;
125 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
126 import org.opendaylight.yangtools.yang.binding.YangModuleInfo;
127 import org.opendaylight.yangtools.yang.common.QName;
128 import org.opendaylight.yangtools.yang.common.RpcError;
129 import org.opendaylight.yangtools.yang.common.RpcError.ErrorType;
130 import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
131 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
132 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
133 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
134 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
135 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
136 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
137 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
138 import org.opendaylight.yangtools.yang.model.api.Module;
139 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
140 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
141 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
142 import org.opendaylight.yangtools.yang.model.repo.api.RevisionSourceIdentifier;
143 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
144 import org.opendaylight.yangtools.yang.model.repo.spi.PotentialSchemaSource;
145 import org.slf4j.Logger;
146 import org.slf4j.LoggerFactory;
149 * Tests netconf mount points end-to-end.
151 * @author Thomas Pantelis
153 public class MountPointEndToEndTest {
154 private static final Logger LOG = LoggerFactory.getLogger(MountPointEndToEndTest.class);
156 private static final String TOP_MODULE_NAME = "opendaylight-mdsal-list-test";
157 private static final String ACTOR_SYSTEM_NAME = "test";
158 private static final String TOPOLOGY_ID = TopologyNetconf.QNAME.getLocalName();
159 private static final NodeId NODE_ID = new NodeId("node-id");
160 private static final InstanceIdentifier<Node> NODE_INSTANCE_ID = NetconfTopologyUtils.createTopologyNodeListPath(
161 new NodeKey(NODE_ID), TOPOLOGY_ID);
163 @Mock private DOMRpcProviderService mockRpcProviderRegistry;
164 @Mock private NetconfClientDispatcher mockClientDispatcher;
165 @Mock private AAAEncryptionService mockEncryptionService;
166 @Mock private ThreadPool mockThreadPool;
167 @Mock private ScheduledThreadPool mockKeepaliveExecutor;
169 @Mock private ActorSystemProvider mockMasterActorSystemProvider;
170 @Mock private DOMMountPointListener masterMountPointListener;
171 private final DOMMountPointService masterMountPointService = new DOMMountPointServiceImpl();
172 private final DOMRpcRouter deviceRpcService = new DOMRpcRouter();
173 private DOMClusterSingletonServiceProviderImpl masterClusterSingletonServiceProvider;
174 private DataBroker masterDataBroker;
175 private DOMDataBroker deviceDOMDataBroker;
176 private ActorSystem masterSystem;
177 private NetconfTopologyManager masterNetconfTopologyManager;
178 private volatile SettableFuture<MasterSalFacade> masterSalFacadeFuture = SettableFuture.create();
180 @Mock private ActorSystemProvider mockSlaveActorSystemProvider;
181 @Mock private ClusterSingletonServiceProvider mockSlaveClusterSingletonServiceProvider;
182 @Mock private ClusterSingletonServiceRegistration mockSlaveClusterSingletonServiceReg;
183 @Mock private DOMMountPointListener slaveMountPointListener;
184 private final DOMMountPointService slaveMountPointService = new DOMMountPointServiceImpl();
185 private DataBroker slaveDataBroker;
186 private ActorSystem slaveSystem;
187 private NetconfTopologyManager slaveNetconfTopologyManager;
188 private final SettableFuture<NetconfTopologyContext> slaveNetconfTopologyContextFuture = SettableFuture.create();
189 private TransactionChain slaveTxChain;
191 private final EventExecutor eventExecutor = GlobalEventExecutor.INSTANCE;
192 private final Config config = new ConfigBuilder().setWriteTransactionIdleTimeout(0).build();
193 private SchemaContext deviceSchemaContext;
194 private YangModuleInfo topModuleInfo;
195 private SchemaPath putTopRpcSchemaPath;
196 private SchemaPath getTopRpcSchemaPath;
197 private BindingNormalizedNodeSerializer bindingToNormalized;
198 private YangInstanceIdentifier yangNodeInstanceId;
199 private final TopDOMRpcImplementation topRpcImplementation = new TopDOMRpcImplementation();
201 @SuppressWarnings({ "unchecked", "rawtypes" })
203 public void setUp() throws Exception {
208 topModuleInfo = BindingReflections.getModuleInfo(Top.class);
210 final ModuleInfoBackedContext moduleContext = ModuleInfoBackedContext.create();
211 moduleContext.addModuleInfos(Arrays.asList(topModuleInfo));
212 deviceSchemaContext = moduleContext.tryToCreateSchemaContext().get();
214 deviceRpcService.onGlobalContextUpdated(deviceSchemaContext);
216 putTopRpcSchemaPath = findRpcDefinition("put-top").getPath();
217 getTopRpcSchemaPath = findRpcDefinition("get-top").getPath();
219 deviceRpcService.getRpcProviderService().registerRpcImplementation(topRpcImplementation,
220 DOMRpcIdentifier.create(putTopRpcSchemaPath), DOMRpcIdentifier.create(getTopRpcSchemaPath));
226 yangNodeInstanceId = bindingToNormalized.toYangInstanceIdentifier(NODE_INSTANCE_ID);
228 doReturn(new SucceededFuture(GlobalEventExecutor.INSTANCE, null)).when(mockClientDispatcher)
229 .createReconnectingClient(any());
231 LOG.info("****** Setup complete");
234 private static void deleteCacheDir() {
235 FileUtils.deleteQuietly(new File(NetconfTopologyUtils.CACHE_DIRECTORY));
239 public void tearDown() throws Exception {
241 TestKit.shutdownActorSystem(slaveSystem, true);
242 TestKit.shutdownActorSystem(masterSystem, true);
245 private void setupMaster() throws Exception {
246 AbstractConcurrentDataBrokerTest dataBrokerTest = newDataBrokerTest();
247 masterDataBroker = dataBrokerTest.getDataBroker();
248 deviceDOMDataBroker = dataBrokerTest.getDomBroker();
249 bindingToNormalized = dataBrokerTest.getDataBrokerTestCustomizer().getBindingToNormalized();
251 masterSystem = ActorSystem.create(ACTOR_SYSTEM_NAME, ConfigFactory.load().getConfig("Master"));
253 masterClusterSingletonServiceProvider = new DOMClusterSingletonServiceProviderImpl(
254 new SimpleDOMEntityOwnershipService());
255 masterClusterSingletonServiceProvider.initializeProvider();
257 doReturn(masterSystem).when(mockMasterActorSystemProvider).getActorSystem();
259 doReturn(MoreExecutors.newDirectExecutorService()).when(mockThreadPool).getExecutor();
261 NetconfTopologyUtils.DEFAULT_SCHEMA_REPOSITORY.registerSchemaSource(
262 id -> Futures.immediateFuture(YangTextSchemaSource.delegateForByteSource(id,
263 topModuleInfo.getYangTextByteSource())),
264 PotentialSchemaSource.create(RevisionSourceIdentifier.create(TOP_MODULE_NAME,
265 topModuleInfo.getName().getRevision()), YangTextSchemaSource.class, 1));
267 masterNetconfTopologyManager = new NetconfTopologyManager(masterDataBroker, mockRpcProviderRegistry,
268 masterClusterSingletonServiceProvider, mockKeepaliveExecutor, mockThreadPool,
269 mockMasterActorSystemProvider, eventExecutor, mockClientDispatcher, TOPOLOGY_ID, config,
270 masterMountPointService, mockEncryptionService) {
272 protected NetconfTopologyContext newNetconfTopologyContext(final NetconfTopologySetup setup,
273 final ServiceGroupIdentifier serviceGroupIdent, final Timeout actorResponseWaitTime) {
274 NetconfTopologyContext context =
275 super.newNetconfTopologyContext(setup, serviceGroupIdent, actorResponseWaitTime);
276 NetconfTopologyContext spiedContext = spy(context);
277 doAnswer(invocation -> {
278 final MasterSalFacade spiedFacade = (MasterSalFacade) spy(invocation.callRealMethod());
279 doReturn(deviceDOMDataBroker).when(spiedFacade).newDeviceDataBroker();
280 masterSalFacadeFuture.set(spiedFacade);
282 }).when(spiedContext).newMasterSalFacade();
288 masterNetconfTopologyManager.init();
290 verifyTopologyNodesCreated(masterDataBroker);
293 private void setupSlave() throws Exception {
294 AbstractConcurrentDataBrokerTest dataBrokerTest = newDataBrokerTest();
295 slaveDataBroker = dataBrokerTest.getDataBroker();
297 slaveSystem = ActorSystem.create(ACTOR_SYSTEM_NAME, ConfigFactory.load().getConfig("Slave"));
299 doReturn(slaveSystem).when(mockSlaveActorSystemProvider).getActorSystem();
301 doReturn(mockSlaveClusterSingletonServiceReg).when(mockSlaveClusterSingletonServiceProvider)
302 .registerClusterSingletonService(any());
304 slaveNetconfTopologyManager = new NetconfTopologyManager(slaveDataBroker, mockRpcProviderRegistry,
305 mockSlaveClusterSingletonServiceProvider, mockKeepaliveExecutor, mockThreadPool,
306 mockSlaveActorSystemProvider, eventExecutor, mockClientDispatcher, TOPOLOGY_ID, config,
307 slaveMountPointService, mockEncryptionService) {
309 protected NetconfTopologyContext newNetconfTopologyContext(final NetconfTopologySetup setup,
310 final ServiceGroupIdentifier serviceGroupIdent, final Timeout actorResponseWaitTime) {
311 NetconfTopologyContext spiedContext =
312 spy(super.newNetconfTopologyContext(setup, serviceGroupIdent, actorResponseWaitTime));
313 slaveNetconfTopologyContextFuture.set(spiedContext);
318 slaveNetconfTopologyManager.init();
320 verifyTopologyNodesCreated(slaveDataBroker);
322 slaveTxChain = slaveDataBroker.createTransactionChain(new TransactionChainListener() {
324 public void onTransactionChainSuccessful(final TransactionChain chain) {
328 public void onTransactionChainFailed(final TransactionChain chain, final Transaction transaction,
329 final Throwable cause) {
330 LOG.error("Slave transaction chain failed", cause);
336 public void test() throws Exception {
341 final MasterSalFacade masterSalFacade = testMasterNodeUpdated();
343 testMasterDisconnected(masterSalFacade);
348 private MasterSalFacade testMaster() throws InterruptedException, ExecutionException, TimeoutException {
349 LOG.info("****** Testing master");
351 writeNetconfNode(NetconfTopologyUtils.DEFAULT_CACHE_DIRECTORY, masterDataBroker);
353 final MasterSalFacade masterSalFacade = masterSalFacadeFuture.get(5, TimeUnit.SECONDS);
355 masterSalFacade.onDeviceConnected(deviceSchemaContext,
356 NetconfSessionPreferences.fromStrings(Collections.emptyList()), deviceRpcService.getRpcService());
358 DOMMountPoint masterMountPoint = awaitMountPoint(masterMountPointService);
360 LOG.info("****** Testing master DOMDataBroker operations");
362 testDOMDataBrokerOperations(getDOMDataBroker(masterMountPoint));
364 LOG.info("****** Testing master DOMRpcService");
366 testDOMRpcService(getDOMRpcService(masterMountPoint));
367 return masterSalFacade;
370 private void testSlave() throws InterruptedException, ExecutionException, TimeoutException {
371 LOG.info("****** Testing slave");
373 writeNetconfNode("slave", slaveDataBroker);
375 verify(mockSlaveClusterSingletonServiceProvider, timeout(5000)).registerClusterSingletonService(any());
377 // Since the master and slave use separate DataBrokers we need to copy the master's oper node to the slave.
378 // This is essentially what happens in a clustered environment but we'll use a DTCL here.
380 masterDataBroker.registerDataTreeChangeListener(
381 DataTreeIdentifier.create(LogicalDatastoreType.OPERATIONAL, NODE_INSTANCE_ID), changes -> {
382 final WriteTransaction slaveTx = slaveTxChain.newWriteOnlyTransaction();
383 for (DataTreeModification<Node> dataTreeModification : changes) {
384 DataObjectModification<Node> rootNode = dataTreeModification.getRootNode();
385 InstanceIdentifier<Node> path = dataTreeModification.getRootPath().getRootIdentifier();
386 switch (rootNode.getModificationType()) {
388 case SUBTREE_MODIFIED:
389 slaveTx.merge(LogicalDatastoreType.OPERATIONAL, path, rootNode.getDataAfter());
392 slaveTx.delete(LogicalDatastoreType.OPERATIONAL, path);
402 DOMMountPoint slaveMountPoint = awaitMountPoint(slaveMountPointService);
404 final NetconfTopologyContext slaveNetconfTopologyContext =
405 slaveNetconfTopologyContextFuture.get(5, TimeUnit.SECONDS);
406 verify(slaveNetconfTopologyContext, never()).newMasterSalFacade();
408 LOG.info("****** Testing slave DOMDataBroker operations");
410 testDOMDataBrokerOperations(getDOMDataBroker(slaveMountPoint));
412 LOG.info("****** Testing slave DOMRpcService");
414 testDOMRpcService(getDOMRpcService(slaveMountPoint));
417 private MasterSalFacade testMasterNodeUpdated() throws InterruptedException, ExecutionException, TimeoutException {
418 LOG.info("****** Testing update master node");
420 masterMountPointService.registerProvisionListener(masterMountPointListener);
421 slaveMountPointService.registerProvisionListener(slaveMountPointListener);
423 masterSalFacadeFuture = SettableFuture.create();
424 writeNetconfNode(NetconfTopologyUtils.DEFAULT_CACHE_DIRECTORY, masterDataBroker);
426 verify(masterMountPointListener, timeout(5000)).onMountPointRemoved(yangNodeInstanceId);
428 MasterSalFacade masterSalFacade = masterSalFacadeFuture.get(5, TimeUnit.SECONDS);
430 masterSalFacade.onDeviceConnected(deviceSchemaContext,
431 NetconfSessionPreferences.fromStrings(Collections.emptyList()), deviceRpcService.getRpcService());
433 verify(masterMountPointListener, timeout(5000)).onMountPointCreated(yangNodeInstanceId);
435 verify(slaveMountPointListener, timeout(5000)).onMountPointRemoved(yangNodeInstanceId);
436 verify(slaveMountPointListener, timeout(5000)).onMountPointCreated(yangNodeInstanceId);
438 return masterSalFacade;
441 private void testMasterDisconnected(final MasterSalFacade masterSalFacade)
442 throws InterruptedException, ExecutionException, TimeoutException {
443 LOG.info("****** Testing master disconnected");
445 masterSalFacade.onDeviceDisconnected();
447 awaitMountPointNotPresent(masterMountPointService);
449 await().atMost(5, TimeUnit.SECONDS).until(() -> {
450 try (ReadTransaction readTx = masterDataBroker.newReadOnlyTransaction()) {
451 Optional<Node> node = readTx.read(LogicalDatastoreType.OPERATIONAL,
452 NODE_INSTANCE_ID).get(5, TimeUnit.SECONDS);
453 assertTrue(node.isPresent());
454 final NetconfNode netconfNode = node.get().augmentation(NetconfNode.class);
455 return netconfNode.getConnectionStatus() != NetconfNodeConnectionStatus.ConnectionStatus.Connected;
459 awaitMountPointNotPresent(slaveMountPointService);
462 private void testCleanup() throws Exception {
463 LOG.info("****** Testing cleanup");
465 slaveNetconfTopologyManager.close();
466 verify(mockSlaveClusterSingletonServiceReg).close();
469 private void testDOMRpcService(final DOMRpcService domRpcService)
470 throws InterruptedException, ExecutionException, TimeoutException {
471 testPutTopRpc(domRpcService, new DefaultDOMRpcResult((NormalizedNode<?, ?>)null));
472 testPutTopRpc(domRpcService, null);
473 testPutTopRpc(domRpcService, new DefaultDOMRpcResult(ImmutableList.of(
474 RpcResultBuilder.newError(ErrorType.APPLICATION, "tag1", "error1"),
475 RpcResultBuilder.newError(ErrorType.APPLICATION, "tag2", "error2"))));
477 testGetTopRpc(domRpcService, new DefaultDOMRpcResult(bindingToNormalized.toNormalizedNodeRpcData(
478 new GetTopOutputBuilder().setTopLevelList(Arrays.asList(new TopLevelListBuilder().setName("one")
479 .build())).build())));
481 testFailedRpc(domRpcService, getTopRpcSchemaPath, null);
484 private void testPutTopRpc(final DOMRpcService domRpcService, final DOMRpcResult result)
485 throws InterruptedException, ExecutionException, TimeoutException {
486 ContainerNode putTopInput = bindingToNormalized.toNormalizedNodeRpcData(
487 new PutTopInputBuilder().setTopLevelList(Arrays.asList(new TopLevelListBuilder().setName("one")
489 testRpc(domRpcService, putTopRpcSchemaPath, putTopInput, result);
492 private void testGetTopRpc(final DOMRpcService domRpcService, final DOMRpcResult result)
493 throws InterruptedException, ExecutionException, TimeoutException {
494 testRpc(domRpcService, getTopRpcSchemaPath, null, result);
497 private void testRpc(final DOMRpcService domRpcService, final SchemaPath schemaPath,
498 final NormalizedNode<?, ?> input, final DOMRpcResult result) throws InterruptedException,
499 ExecutionException, TimeoutException {
500 final FluentFuture<DOMRpcResult> future = result == null ? FluentFutures.immediateNullFluentFuture()
501 : FluentFutures.immediateFluentFuture(result);
502 final DOMRpcResult actual = invokeRpc(domRpcService, schemaPath, input, future);
503 if (result == null) {
508 assertNotNull(actual);
509 assertEquals(result.getResult(), actual.getResult());
511 assertEquals(result.getErrors().size(), actual.getErrors().size());
512 Iterator<? extends RpcError> iter1 = result.getErrors().iterator();
513 Iterator<? extends RpcError> iter2 = actual.getErrors().iterator();
514 while (iter1.hasNext() && iter2.hasNext()) {
515 RpcError err1 = iter1.next();
516 RpcError err2 = iter2.next();
517 assertEquals(err1.getErrorType(), err2.getErrorType());
518 assertEquals(err1.getTag(), err2.getTag());
519 assertEquals(err1.getMessage(), err2.getMessage());
520 assertEquals(err1.getSeverity(), err2.getSeverity());
521 assertEquals(err1.getApplicationTag(), err2.getApplicationTag());
522 assertEquals(err1.getInfo(), err2.getInfo());
526 private void testFailedRpc(final DOMRpcService domRpcService, final SchemaPath schemaPath,
527 final NormalizedNode<?, ?> input) throws InterruptedException, TimeoutException {
529 invokeRpc(domRpcService, schemaPath, input, FluentFutures.immediateFailedFluentFuture(
530 new ClusteringRpcException("mock")));
531 fail("Expected exception");
532 } catch (ExecutionException e) {
533 assertTrue(e.getCause() instanceof ClusteringRpcException);
534 assertEquals("mock", e.getCause().getMessage());
538 private DOMRpcResult invokeRpc(final DOMRpcService domRpcService, final SchemaPath schemaPath,
539 final NormalizedNode<?, ?> input, final FluentFuture<DOMRpcResult> returnFuture)
540 throws InterruptedException, ExecutionException, TimeoutException {
541 topRpcImplementation.init(returnFuture);
542 final ListenableFuture<DOMRpcResult> resultFuture = domRpcService.invokeRpc(schemaPath, input);
544 topRpcImplementation.verify(DOMRpcIdentifier.create(schemaPath), input);
546 return resultFuture.get(5, TimeUnit.SECONDS);
549 private static void testDOMDataBrokerOperations(final DOMDataBroker dataBroker)
550 throws InterruptedException, ExecutionException, TimeoutException {
552 DOMDataTreeWriteTransaction writeTx = dataBroker.newWriteOnlyTransaction();
554 final ContainerNode topNode = Builders.containerBuilder()
555 .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(Top.QNAME)).build();
556 final YangInstanceIdentifier topPath = YangInstanceIdentifier.of(Top.QNAME);
557 writeTx.put(LogicalDatastoreType.CONFIGURATION, topPath, topNode);
559 final QName name = QName.create(TopLevelList.QNAME, "name");
560 final YangInstanceIdentifier listPath = YangInstanceIdentifier.builder(topPath)
561 .node(TopLevelList.QNAME).build();
562 final MapEntryNode listEntryNode = ImmutableNodes.mapEntry(TopLevelList.QNAME, name, "one");
563 final MapNode listNode = ImmutableNodes.mapNodeBuilder(TopLevelList.QNAME).addChild(listEntryNode).build();
564 writeTx.merge(LogicalDatastoreType.CONFIGURATION, listPath, listNode);
565 writeTx.commit().get(5, TimeUnit.SECONDS);
567 verifyDataInStore(dataBroker.newReadWriteTransaction(), YangInstanceIdentifier.builder(listPath)
568 .nodeWithKey(TopLevelList.QNAME, name, "one").build(), listEntryNode);
570 writeTx = dataBroker.newWriteOnlyTransaction();
571 writeTx.delete(LogicalDatastoreType.CONFIGURATION, topPath);
572 writeTx.commit().get(5, TimeUnit.SECONDS);
574 DOMDataTreeReadWriteTransaction readTx = dataBroker.newReadWriteTransaction();
575 assertFalse(readTx.exists(LogicalDatastoreType.CONFIGURATION, topPath).get(5, TimeUnit.SECONDS));
576 assertTrue(readTx.cancel());
579 private static void writeNetconfNode(final String cacheDir, final DataBroker databroker)
580 throws InterruptedException, ExecutionException, TimeoutException {
581 final NetconfNode netconfNode = new NetconfNodeBuilder()
582 .setHost(new Host(new IpAddress(new Ipv4Address("127.0.0.1"))))
583 .setPort(new PortNumber(1234))
584 .setActorResponseWaitTime(10)
585 .setTcpOnly(Boolean.TRUE)
586 .setSchemaless(Boolean.FALSE)
587 .setKeepaliveDelay(0L)
588 .setConnectionTimeoutMillis(5000L)
589 .setDefaultRequestTimeoutMillis(5000L)
590 .setMaxConnectionAttempts(1L)
591 .setCredentials(new LoginPwUnencryptedBuilder().setLoginPasswordUnencrypted(
592 new LoginPasswordUnencryptedBuilder().setUsername("user").setPassword("pass").build()).build())
593 .setSchemaCacheDirectory(cacheDir)
595 final Node node = new NodeBuilder().setNodeId(NODE_ID).addAugmentation(NetconfNode.class, netconfNode).build();
597 final WriteTransaction writeTx = databroker.newWriteOnlyTransaction();
598 writeTx.put(LogicalDatastoreType.CONFIGURATION, NODE_INSTANCE_ID, node);
599 writeTx.commit().get(5, TimeUnit.SECONDS);
602 private static void verifyDataInStore(final DOMDataTreeReadTransaction readTx, final YangInstanceIdentifier path,
603 final NormalizedNode<?, ?> expNode) throws InterruptedException, ExecutionException, TimeoutException {
604 final Optional<NormalizedNode<?, ?>> read = readTx.read(LogicalDatastoreType.CONFIGURATION, path)
605 .get(5, TimeUnit.SECONDS);
606 assertTrue(read.isPresent());
607 assertEquals(expNode, read.get());
609 final Boolean exists = readTx.exists(LogicalDatastoreType.CONFIGURATION, path).get(5, TimeUnit.SECONDS);
613 private static void verifyTopologyNodesCreated(final DataBroker dataBroker) {
614 await().atMost(5, TimeUnit.SECONDS).until(() -> {
615 try (ReadTransaction readTx = dataBroker.newReadOnlyTransaction()) {
616 Optional<Topology> configTopology = readTx.read(LogicalDatastoreType.CONFIGURATION,
617 NetconfTopologyUtils.createTopologyListPath(TOPOLOGY_ID)).get(3, TimeUnit.SECONDS);
618 Optional<Topology> operTopology = readTx.read(LogicalDatastoreType.OPERATIONAL,
619 NetconfTopologyUtils.createTopologyListPath(TOPOLOGY_ID)).get(3, TimeUnit.SECONDS);
620 return configTopology.isPresent() && operTopology.isPresent();
625 private AbstractConcurrentDataBrokerTest newDataBrokerTest() throws Exception {
626 AbstractConcurrentDataBrokerTest dataBrokerTest = new AbstractConcurrentDataBrokerTest(true) {
628 protected Set<YangModuleInfo> getModuleInfos() throws Exception {
629 return ImmutableSet.of(BindingReflections.getModuleInfo(NetconfNode.class),
630 BindingReflections.getModuleInfo(NetworkTopology.class),
631 BindingReflections.getModuleInfo(Topology.class),
632 BindingReflections.getModuleInfo(Keystore.class),
637 dataBrokerTest.setup();
638 return dataBrokerTest;
641 private void awaitMountPointNotPresent(final DOMMountPointService mountPointService) {
642 await().atMost(5, TimeUnit.SECONDS).until(
643 () -> !mountPointService.getMountPoint(yangNodeInstanceId).isPresent());
646 private static DOMDataBroker getDOMDataBroker(final DOMMountPoint mountPoint) {
647 return getMountPointService(mountPoint, DOMDataBroker.class);
650 private static DOMRpcService getDOMRpcService(final DOMMountPoint mountPoint) {
651 return getMountPointService(mountPoint, DOMRpcService.class);
654 private static <T extends DOMService> T getMountPointService(final DOMMountPoint mountPoint,
655 final Class<T> serviceClass) {
656 final Optional<T> maybeService = mountPoint.getService(serviceClass);
657 assertTrue(maybeService.isPresent());
658 return maybeService.get();
661 private DOMMountPoint awaitMountPoint(final DOMMountPointService mountPointService) {
662 await().atMost(5, TimeUnit.SECONDS).until(() -> {
663 return mountPointService.getMountPoint(yangNodeInstanceId).isPresent();
666 return mountPointService.getMountPoint(yangNodeInstanceId).get();
669 private RpcDefinition findRpcDefinition(final String rpc) {
670 Module topModule = deviceSchemaContext.findModule(TOP_MODULE_NAME, topModuleInfo.getName().getRevision()).get();
671 RpcDefinition rpcDefinition = null;
672 for (RpcDefinition def: topModule.getRpcs()) {
673 if (def.getQName().getLocalName().equals(rpc)) {
679 assertNotNull(rpc + " rpc not found in " + topModule.getRpcs(), rpcDefinition);
680 return rpcDefinition;
683 private static class TopDOMRpcImplementation implements DOMRpcImplementation {
684 private volatile SettableFuture<Entry<DOMRpcIdentifier, NormalizedNode<?, ?>>> rpcInvokedFuture;
685 private volatile FluentFuture<DOMRpcResult> returnFuture;
688 public FluentFuture<DOMRpcResult> invokeRpc(final DOMRpcIdentifier rpc,
689 final NormalizedNode<?, ?> input) {
690 rpcInvokedFuture.set(new SimpleEntry<>(rpc, input));
694 void init(final FluentFuture<DOMRpcResult> retFuture) {
695 this.returnFuture = retFuture;
696 rpcInvokedFuture = SettableFuture.create();
699 void verify(final DOMRpcIdentifier expRpc, final NormalizedNode<?, ?> expInput)
700 throws InterruptedException, ExecutionException, TimeoutException {
701 final Entry<DOMRpcIdentifier, NormalizedNode<?, ?>> actual = rpcInvokedFuture.get(5, TimeUnit.SECONDS);
702 assertEquals(expRpc, actual.getKey());
703 assertEquals(expInput, actual.getValue());