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.data.api.YangInstanceIdentifier;
137 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
138 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
139 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
140 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
141 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
142 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
143 import org.opendaylight.yangtools.yang.model.api.Module;
144 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
145 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
146 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
147 import org.opendaylight.yangtools.yang.model.repo.api.RevisionSourceIdentifier;
148 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
149 import org.opendaylight.yangtools.yang.model.repo.spi.PotentialSchemaSource;
150 import org.slf4j.Logger;
151 import org.slf4j.LoggerFactory;
154 * Tests netconf mount points end-to-end.
156 * @author Thomas Pantelis
158 public class MountPointEndToEndTest {
159 private static final Logger LOG = LoggerFactory.getLogger(MountPointEndToEndTest.class);
161 private static final String TOP_MODULE_NAME = "opendaylight-mdsal-list-test";
162 private static final String ACTOR_SYSTEM_NAME = "test";
163 private static final String TOPOLOGY_ID = TopologyNetconf.QNAME.getLocalName();
164 private static final NodeId NODE_ID = new NodeId("node-id");
165 private static final InstanceIdentifier<Node> NODE_INSTANCE_ID = NetconfTopologyUtils.createTopologyNodeListPath(
166 new NodeKey(NODE_ID), TOPOLOGY_ID);
168 @Mock private DOMRpcProviderService mockRpcProviderRegistry;
169 @Mock private DOMActionProviderService mockActionProviderRegistry;
170 @Mock private NetconfClientDispatcher mockClientDispatcher;
171 @Mock private AAAEncryptionService mockEncryptionService;
172 @Mock private ThreadPool mockThreadPool;
173 @Mock private ScheduledThreadPool mockKeepaliveExecutor;
174 @Mock private DeviceActionFactory deviceActionFactory;
176 @Mock private ActorSystemProvider mockMasterActorSystemProvider;
177 @Mock private DOMMountPointListener masterMountPointListener;
178 private final DOMMountPointService masterMountPointService = new DOMMountPointServiceImpl();
179 private final DOMRpcRouter deviceRpcService = new DOMRpcRouter();
180 private DOMClusterSingletonServiceProviderImpl masterClusterSingletonServiceProvider;
181 private DataBroker masterDataBroker;
182 private DOMDataBroker deviceDOMDataBroker;
183 private ActorSystem masterSystem;
184 private NetconfTopologyManager masterNetconfTopologyManager;
185 private volatile SettableFuture<MasterSalFacade> masterSalFacadeFuture = SettableFuture.create();
187 @Mock private ActorSystemProvider mockSlaveActorSystemProvider;
188 @Mock private ClusterSingletonServiceProvider mockSlaveClusterSingletonServiceProvider;
189 @Mock private ClusterSingletonServiceRegistration mockSlaveClusterSingletonServiceReg;
190 @Mock private DOMMountPointListener slaveMountPointListener;
191 private final DOMMountPointService slaveMountPointService = new DOMMountPointServiceImpl();
192 private DataBroker slaveDataBroker;
193 private ActorSystem slaveSystem;
194 private NetconfTopologyManager slaveNetconfTopologyManager;
195 private final SettableFuture<NetconfTopologyContext> slaveNetconfTopologyContextFuture = SettableFuture.create();
196 private TransactionChain slaveTxChain;
198 private final EventExecutor eventExecutor = GlobalEventExecutor.INSTANCE;
199 private final Config config = new ConfigBuilder().setWriteTransactionIdleTimeout(0).build();
200 private SchemaContext deviceSchemaContext;
201 private YangModuleInfo topModuleInfo;
202 private SchemaPath putTopRpcSchemaPath;
203 private SchemaPath getTopRpcSchemaPath;
204 private BindingNormalizedNodeSerializer bindingToNormalized;
205 private YangInstanceIdentifier yangNodeInstanceId;
206 private final TopDOMRpcImplementation topRpcImplementation = new TopDOMRpcImplementation();
208 @SuppressWarnings({ "unchecked", "rawtypes" })
210 public void setUp() throws Exception {
215 topModuleInfo = BindingReflections.getModuleInfo(Top.class);
217 final ModuleInfoBackedContext moduleContext = ModuleInfoBackedContext.create();
218 moduleContext.addModuleInfos(Arrays.asList(topModuleInfo));
219 deviceSchemaContext = moduleContext.tryToCreateSchemaContext().get();
221 deviceRpcService.onGlobalContextUpdated(deviceSchemaContext);
223 putTopRpcSchemaPath = findRpcDefinition("put-top").getPath();
224 getTopRpcSchemaPath = findRpcDefinition("get-top").getPath();
226 deviceRpcService.getRpcProviderService().registerRpcImplementation(topRpcImplementation,
227 DOMRpcIdentifier.create(putTopRpcSchemaPath), DOMRpcIdentifier.create(getTopRpcSchemaPath));
233 yangNodeInstanceId = bindingToNormalized.toYangInstanceIdentifier(NODE_INSTANCE_ID);
235 doReturn(new SucceededFuture(GlobalEventExecutor.INSTANCE, null)).when(mockClientDispatcher)
236 .createReconnectingClient(any());
238 LOG.info("****** Setup complete");
241 private static void deleteCacheDir() {
242 FileUtils.deleteQuietly(new File(NetconfTopologyUtils.CACHE_DIRECTORY));
246 public void tearDown() throws Exception {
248 TestKit.shutdownActorSystem(slaveSystem, true);
249 TestKit.shutdownActorSystem(masterSystem, true);
252 private void setupMaster() throws Exception {
253 AbstractConcurrentDataBrokerTest dataBrokerTest = newDataBrokerTest();
254 masterDataBroker = dataBrokerTest.getDataBroker();
255 deviceDOMDataBroker = dataBrokerTest.getDomBroker();
256 bindingToNormalized = dataBrokerTest.getDataBrokerTestCustomizer().getBindingToNormalized();
258 masterSystem = ActorSystem.create(ACTOR_SYSTEM_NAME, ConfigFactory.load().getConfig("Master"));
260 masterClusterSingletonServiceProvider = new DOMClusterSingletonServiceProviderImpl(
261 new SimpleDOMEntityOwnershipService());
262 masterClusterSingletonServiceProvider.initializeProvider();
264 doReturn(masterSystem).when(mockMasterActorSystemProvider).getActorSystem();
266 doReturn(MoreExecutors.newDirectExecutorService()).when(mockThreadPool).getExecutor();
268 NetconfTopologyUtils.DEFAULT_SCHEMA_REPOSITORY.registerSchemaSource(
269 id -> Futures.immediateFuture(YangTextSchemaSource.delegateForByteSource(id,
270 topModuleInfo.getYangTextByteSource())),
271 PotentialSchemaSource.create(RevisionSourceIdentifier.create(TOP_MODULE_NAME,
272 topModuleInfo.getName().getRevision()), YangTextSchemaSource.class, 1));
274 masterNetconfTopologyManager = new NetconfTopologyManager(masterDataBroker, mockRpcProviderRegistry,
275 mockActionProviderRegistry, masterClusterSingletonServiceProvider, mockKeepaliveExecutor, mockThreadPool,
276 mockMasterActorSystemProvider, eventExecutor, mockClientDispatcher, TOPOLOGY_ID, config,
277 masterMountPointService, mockEncryptionService, deviceActionFactory) {
279 protected NetconfTopologyContext newNetconfTopologyContext(final NetconfTopologySetup setup,
280 final ServiceGroupIdentifier serviceGroupIdent, final Timeout actorResponseWaitTime,
281 final DeviceActionFactory deviceActionFact) {
282 NetconfTopologyContext context =
283 super.newNetconfTopologyContext(setup, serviceGroupIdent, actorResponseWaitTime, deviceActionFact);
285 NetconfTopologyContext spiedContext = spy(context);
286 doAnswer(invocation -> {
287 final MasterSalFacade spiedFacade = (MasterSalFacade) spy(invocation.callRealMethod());
288 doReturn(deviceDOMDataBroker).when(spiedFacade).newDeviceDataBroker();
289 masterSalFacadeFuture.set(spiedFacade);
291 }).when(spiedContext).newMasterSalFacade();
297 masterNetconfTopologyManager.init();
299 verifyTopologyNodesCreated(masterDataBroker);
302 private void setupSlave() throws Exception {
303 AbstractConcurrentDataBrokerTest dataBrokerTest = newDataBrokerTest();
304 slaveDataBroker = dataBrokerTest.getDataBroker();
306 slaveSystem = ActorSystem.create(ACTOR_SYSTEM_NAME, ConfigFactory.load().getConfig("Slave"));
308 doReturn(slaveSystem).when(mockSlaveActorSystemProvider).getActorSystem();
310 doReturn(mockSlaveClusterSingletonServiceReg).when(mockSlaveClusterSingletonServiceProvider)
311 .registerClusterSingletonService(any());
313 slaveNetconfTopologyManager = new NetconfTopologyManager(slaveDataBroker, mockRpcProviderRegistry,
314 mockActionProviderRegistry, mockSlaveClusterSingletonServiceProvider, mockKeepaliveExecutor, mockThreadPool,
315 mockSlaveActorSystemProvider, eventExecutor, mockClientDispatcher, TOPOLOGY_ID, config,
316 slaveMountPointService, mockEncryptionService, deviceActionFactory) {
318 protected NetconfTopologyContext newNetconfTopologyContext(final NetconfTopologySetup setup,
319 final ServiceGroupIdentifier serviceGroupIdent, final Timeout actorResponseWaitTime,
320 final DeviceActionFactory actionFactory) {
321 NetconfTopologyContext spiedContext = spy(super.newNetconfTopologyContext(setup, serviceGroupIdent,
322 actorResponseWaitTime, actionFactory));
324 slaveNetconfTopologyContextFuture.set(spiedContext);
329 slaveNetconfTopologyManager.init();
331 verifyTopologyNodesCreated(slaveDataBroker);
333 slaveTxChain = slaveDataBroker.createTransactionChain(new TransactionChainListener() {
335 public void onTransactionChainSuccessful(final TransactionChain chain) {
339 public void onTransactionChainFailed(final TransactionChain chain, final Transaction transaction,
340 final Throwable cause) {
341 LOG.error("Slave transaction chain failed", cause);
347 public void test() throws Exception {
352 final MasterSalFacade masterSalFacade = testMasterNodeUpdated();
354 testMasterDisconnected(masterSalFacade);
359 private MasterSalFacade testMaster() throws InterruptedException, ExecutionException, TimeoutException {
360 LOG.info("****** Testing master");
362 writeNetconfNode(NetconfTopologyUtils.DEFAULT_CACHE_DIRECTORY, masterDataBroker);
364 final MasterSalFacade masterSalFacade = masterSalFacadeFuture.get(5, TimeUnit.SECONDS);
366 masterSalFacade.onDeviceConnected(new EmptyMountPointContext(deviceSchemaContext),
367 NetconfSessionPreferences.fromStrings(Collections.emptyList()), deviceRpcService.getRpcService());
369 DOMMountPoint masterMountPoint = awaitMountPoint(masterMountPointService);
371 LOG.info("****** Testing master DOMDataBroker operations");
373 testDOMDataBrokerOperations(getDOMDataBroker(masterMountPoint));
375 LOG.info("****** Testing master DOMRpcService");
377 testDOMRpcService(getDOMRpcService(masterMountPoint));
378 return masterSalFacade;
381 private void testSlave() throws InterruptedException, ExecutionException, TimeoutException {
382 LOG.info("****** Testing slave");
384 writeNetconfNode("slave", slaveDataBroker);
386 verify(mockSlaveClusterSingletonServiceProvider, timeout(5000)).registerClusterSingletonService(any());
388 // Since the master and slave use separate DataBrokers we need to copy the master's oper node to the slave.
389 // This is essentially what happens in a clustered environment but we'll use a DTCL here.
391 masterDataBroker.registerDataTreeChangeListener(
392 DataTreeIdentifier.create(LogicalDatastoreType.OPERATIONAL, NODE_INSTANCE_ID), changes -> {
393 final WriteTransaction slaveTx = slaveTxChain.newWriteOnlyTransaction();
394 for (DataTreeModification<Node> dataTreeModification : changes) {
395 DataObjectModification<Node> rootNode = dataTreeModification.getRootNode();
396 InstanceIdentifier<Node> path = dataTreeModification.getRootPath().getRootIdentifier();
397 switch (rootNode.getModificationType()) {
399 case SUBTREE_MODIFIED:
400 slaveTx.merge(LogicalDatastoreType.OPERATIONAL, path, rootNode.getDataAfter());
403 slaveTx.delete(LogicalDatastoreType.OPERATIONAL, path);
413 DOMMountPoint slaveMountPoint = awaitMountPoint(slaveMountPointService);
415 final NetconfTopologyContext slaveNetconfTopologyContext =
416 slaveNetconfTopologyContextFuture.get(5, TimeUnit.SECONDS);
417 verify(slaveNetconfTopologyContext, never()).newMasterSalFacade();
419 LOG.info("****** Testing slave DOMDataBroker operations");
421 testDOMDataBrokerOperations(getDOMDataBroker(slaveMountPoint));
423 LOG.info("****** Testing slave DOMRpcService");
425 testDOMRpcService(getDOMRpcService(slaveMountPoint));
428 private MasterSalFacade testMasterNodeUpdated() throws InterruptedException, ExecutionException, TimeoutException {
429 LOG.info("****** Testing update master node");
431 masterMountPointService.registerProvisionListener(masterMountPointListener);
432 slaveMountPointService.registerProvisionListener(slaveMountPointListener);
434 masterSalFacadeFuture = SettableFuture.create();
435 writeNetconfNode(NetconfTopologyUtils.DEFAULT_CACHE_DIRECTORY, masterDataBroker);
437 verify(masterMountPointListener, timeout(5000)).onMountPointRemoved(yangNodeInstanceId);
439 MasterSalFacade masterSalFacade = masterSalFacadeFuture.get(5, TimeUnit.SECONDS);
441 masterSalFacade.onDeviceConnected(new EmptyMountPointContext(deviceSchemaContext),
442 NetconfSessionPreferences.fromStrings(Collections.emptyList()), deviceRpcService.getRpcService());
444 verify(masterMountPointListener, timeout(5000)).onMountPointCreated(yangNodeInstanceId);
446 verify(slaveMountPointListener, timeout(5000)).onMountPointRemoved(yangNodeInstanceId);
447 verify(slaveMountPointListener, timeout(5000)).onMountPointCreated(yangNodeInstanceId);
449 return masterSalFacade;
452 private void testMasterDisconnected(final MasterSalFacade masterSalFacade)
453 throws InterruptedException, ExecutionException, TimeoutException {
454 LOG.info("****** Testing master disconnected");
456 masterSalFacade.onDeviceDisconnected();
458 awaitMountPointNotPresent(masterMountPointService);
460 await().atMost(5, TimeUnit.SECONDS).until(() -> {
461 try (ReadTransaction readTx = masterDataBroker.newReadOnlyTransaction()) {
462 Optional<Node> node = readTx.read(LogicalDatastoreType.OPERATIONAL,
463 NODE_INSTANCE_ID).get(5, TimeUnit.SECONDS);
464 assertTrue(node.isPresent());
465 final NetconfNode netconfNode = node.get().augmentation(NetconfNode.class);
466 return netconfNode.getConnectionStatus() != NetconfNodeConnectionStatus.ConnectionStatus.Connected;
470 awaitMountPointNotPresent(slaveMountPointService);
473 private void testCleanup() throws Exception {
474 LOG.info("****** Testing cleanup");
476 slaveNetconfTopologyManager.close();
477 verify(mockSlaveClusterSingletonServiceReg).close();
480 private void testDOMRpcService(final DOMRpcService domRpcService)
481 throws InterruptedException, ExecutionException, TimeoutException {
482 testPutTopRpc(domRpcService, new DefaultDOMRpcResult((NormalizedNode<?, ?>)null));
483 testPutTopRpc(domRpcService, null);
484 testPutTopRpc(domRpcService, new DefaultDOMRpcResult(ImmutableList.of(
485 RpcResultBuilder.newError(ErrorType.APPLICATION, "tag1", "error1"),
486 RpcResultBuilder.newError(ErrorType.APPLICATION, "tag2", "error2"))));
488 testGetTopRpc(domRpcService, new DefaultDOMRpcResult(bindingToNormalized.toNormalizedNodeRpcData(
489 new GetTopOutputBuilder().setTopLevelList(Arrays.asList(new TopLevelListBuilder().setName("one")
490 .build())).build())));
492 testFailedRpc(domRpcService, getTopRpcSchemaPath, null);
495 private void testPutTopRpc(final DOMRpcService domRpcService, final DOMRpcResult result)
496 throws InterruptedException, ExecutionException, TimeoutException {
497 ContainerNode putTopInput = bindingToNormalized.toNormalizedNodeRpcData(
498 new PutTopInputBuilder().setTopLevelList(Arrays.asList(new TopLevelListBuilder().setName("one")
500 testRpc(domRpcService, putTopRpcSchemaPath, putTopInput, result);
503 private void testGetTopRpc(final DOMRpcService domRpcService, final DOMRpcResult result)
504 throws InterruptedException, ExecutionException, TimeoutException {
505 testRpc(domRpcService, getTopRpcSchemaPath, null, result);
508 private void testRpc(final DOMRpcService domRpcService, final SchemaPath schemaPath,
509 final NormalizedNode<?, ?> input, final DOMRpcResult result) throws InterruptedException,
510 ExecutionException, TimeoutException {
511 final FluentFuture<DOMRpcResult> future = result == null ? FluentFutures.immediateNullFluentFuture()
512 : FluentFutures.immediateFluentFuture(result);
513 final DOMRpcResult actual = invokeRpc(domRpcService, schemaPath, input, future);
514 if (result == null) {
519 assertNotNull(actual);
520 assertEquals(result.getResult(), actual.getResult());
522 assertEquals(result.getErrors().size(), actual.getErrors().size());
523 Iterator<? extends RpcError> iter1 = result.getErrors().iterator();
524 Iterator<? extends RpcError> iter2 = actual.getErrors().iterator();
525 while (iter1.hasNext() && iter2.hasNext()) {
526 RpcError err1 = iter1.next();
527 RpcError err2 = iter2.next();
528 assertEquals(err1.getErrorType(), err2.getErrorType());
529 assertEquals(err1.getTag(), err2.getTag());
530 assertEquals(err1.getMessage(), err2.getMessage());
531 assertEquals(err1.getSeverity(), err2.getSeverity());
532 assertEquals(err1.getApplicationTag(), err2.getApplicationTag());
533 assertEquals(err1.getInfo(), err2.getInfo());
537 private void testFailedRpc(final DOMRpcService domRpcService, final SchemaPath schemaPath,
538 final NormalizedNode<?, ?> input) throws InterruptedException, TimeoutException {
540 invokeRpc(domRpcService, schemaPath, input, FluentFutures.immediateFailedFluentFuture(
541 new ClusteringRpcException("mock")));
542 fail("Expected exception");
543 } catch (ExecutionException e) {
544 assertTrue(e.getCause() instanceof ClusteringRpcException);
545 assertEquals("mock", e.getCause().getMessage());
549 private DOMRpcResult invokeRpc(final DOMRpcService domRpcService, final SchemaPath schemaPath,
550 final NormalizedNode<?, ?> input, final FluentFuture<DOMRpcResult> returnFuture)
551 throws InterruptedException, ExecutionException, TimeoutException {
552 topRpcImplementation.init(returnFuture);
553 final ListenableFuture<DOMRpcResult> resultFuture = domRpcService.invokeRpc(schemaPath, input);
555 topRpcImplementation.verify(DOMRpcIdentifier.create(schemaPath), input);
557 return resultFuture.get(5, TimeUnit.SECONDS);
560 private static void testDOMDataBrokerOperations(final DOMDataBroker dataBroker)
561 throws InterruptedException, ExecutionException, TimeoutException {
563 DOMDataTreeWriteTransaction writeTx = dataBroker.newWriteOnlyTransaction();
565 final ContainerNode topNode = Builders.containerBuilder()
566 .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(Top.QNAME)).build();
567 final YangInstanceIdentifier topPath = YangInstanceIdentifier.of(Top.QNAME);
568 writeTx.put(LogicalDatastoreType.CONFIGURATION, topPath, topNode);
570 final QName name = QName.create(TopLevelList.QNAME, "name");
571 final YangInstanceIdentifier listPath = YangInstanceIdentifier.builder(topPath)
572 .node(TopLevelList.QNAME).build();
573 final MapEntryNode listEntryNode = ImmutableNodes.mapEntry(TopLevelList.QNAME, name, "one");
574 final MapNode listNode = ImmutableNodes.mapNodeBuilder(TopLevelList.QNAME).addChild(listEntryNode).build();
575 writeTx.merge(LogicalDatastoreType.CONFIGURATION, listPath, listNode);
576 writeTx.commit().get(5, TimeUnit.SECONDS);
578 verifyDataInStore(dataBroker.newReadWriteTransaction(), YangInstanceIdentifier.builder(listPath)
579 .nodeWithKey(TopLevelList.QNAME, name, "one").build(), listEntryNode);
581 writeTx = dataBroker.newWriteOnlyTransaction();
582 writeTx.delete(LogicalDatastoreType.CONFIGURATION, topPath);
583 writeTx.commit().get(5, TimeUnit.SECONDS);
585 DOMDataTreeReadWriteTransaction readTx = dataBroker.newReadWriteTransaction();
586 assertFalse(readTx.exists(LogicalDatastoreType.CONFIGURATION, topPath).get(5, TimeUnit.SECONDS));
587 assertTrue(readTx.cancel());
590 private static void writeNetconfNode(final String cacheDir, final DataBroker databroker)
591 throws InterruptedException, ExecutionException, TimeoutException {
592 final NetconfNode netconfNode = new NetconfNodeBuilder()
593 .setHost(new Host(new IpAddress(new Ipv4Address("127.0.0.1"))))
594 .setPort(new PortNumber(Uint16.valueOf(1234)))
595 .setActorResponseWaitTime(10)
596 .setTcpOnly(Boolean.TRUE)
597 .setSchemaless(Boolean.FALSE)
598 .setKeepaliveDelay(0L)
599 .setConnectionTimeoutMillis(5000L)
600 .setDefaultRequestTimeoutMillis(5000L)
601 .setMaxConnectionAttempts(1L)
602 .setCredentials(new LoginPwUnencryptedBuilder().setLoginPasswordUnencrypted(
603 new LoginPasswordUnencryptedBuilder().setUsername("user").setPassword("pass").build()).build())
604 .setSchemaCacheDirectory(cacheDir)
606 final Node node = new NodeBuilder().setNodeId(NODE_ID).addAugmentation(NetconfNode.class, netconfNode).build();
608 final WriteTransaction writeTx = databroker.newWriteOnlyTransaction();
609 writeTx.put(LogicalDatastoreType.CONFIGURATION, NODE_INSTANCE_ID, node);
610 writeTx.commit().get(5, TimeUnit.SECONDS);
613 private static void verifyDataInStore(final DOMDataTreeReadOperations readTx, final YangInstanceIdentifier path,
614 final NormalizedNode<?, ?> expNode) throws InterruptedException, ExecutionException, TimeoutException {
615 final Optional<NormalizedNode<?, ?>> read = readTx.read(LogicalDatastoreType.CONFIGURATION, path)
616 .get(5, TimeUnit.SECONDS);
617 assertTrue(read.isPresent());
618 assertEquals(expNode, read.get());
620 final Boolean exists = readTx.exists(LogicalDatastoreType.CONFIGURATION, path).get(5, TimeUnit.SECONDS);
624 private static void verifyTopologyNodesCreated(final DataBroker dataBroker) {
625 await().atMost(5, TimeUnit.SECONDS).until(() -> {
626 try (ReadTransaction readTx = dataBroker.newReadOnlyTransaction()) {
627 Optional<Topology> configTopology = readTx.read(LogicalDatastoreType.CONFIGURATION,
628 NetconfTopologyUtils.createTopologyListPath(TOPOLOGY_ID)).get(3, TimeUnit.SECONDS);
629 Optional<Topology> operTopology = readTx.read(LogicalDatastoreType.OPERATIONAL,
630 NetconfTopologyUtils.createTopologyListPath(TOPOLOGY_ID)).get(3, TimeUnit.SECONDS);
631 return configTopology.isPresent() && operTopology.isPresent();
636 private AbstractConcurrentDataBrokerTest newDataBrokerTest() throws Exception {
637 AbstractConcurrentDataBrokerTest dataBrokerTest = new AbstractConcurrentDataBrokerTest(true) {
639 protected Set<YangModuleInfo> getModuleInfos() throws Exception {
640 return ImmutableSet.of(BindingReflections.getModuleInfo(NetconfNode.class),
641 BindingReflections.getModuleInfo(NetworkTopology.class),
642 BindingReflections.getModuleInfo(Topology.class),
643 BindingReflections.getModuleInfo(Keystore.class),
648 dataBrokerTest.setup();
649 return dataBrokerTest;
652 private void awaitMountPointNotPresent(final DOMMountPointService mountPointService) {
653 await().atMost(5, TimeUnit.SECONDS).until(
654 () -> !mountPointService.getMountPoint(yangNodeInstanceId).isPresent());
657 private static DOMDataBroker getDOMDataBroker(final DOMMountPoint mountPoint) {
658 return getMountPointService(mountPoint, DOMDataBroker.class);
661 private static DOMRpcService getDOMRpcService(final DOMMountPoint mountPoint) {
662 return getMountPointService(mountPoint, DOMRpcService.class);
665 private static DOMActionService getDomActionService(final DOMMountPoint mountPoint) {
666 return getMountPointService(mountPoint, DOMActionService.class);
669 private static <T extends DOMService> T getMountPointService(final DOMMountPoint mountPoint,
670 final Class<T> serviceClass) {
671 final Optional<T> maybeService = mountPoint.getService(serviceClass);
672 assertTrue(maybeService.isPresent());
673 return maybeService.get();
676 private DOMMountPoint awaitMountPoint(final DOMMountPointService mountPointService) {
677 await().atMost(5, TimeUnit.SECONDS).until(() ->
678 mountPointService.getMountPoint(yangNodeInstanceId).isPresent());
680 return mountPointService.getMountPoint(yangNodeInstanceId).get();
683 private RpcDefinition findRpcDefinition(final String rpc) {
684 Module topModule = deviceSchemaContext.findModule(TOP_MODULE_NAME, topModuleInfo.getName().getRevision()).get();
685 RpcDefinition rpcDefinition = null;
686 for (RpcDefinition def: topModule.getRpcs()) {
687 if (def.getQName().getLocalName().equals(rpc)) {
693 assertNotNull(rpc + " rpc not found in " + topModule.getRpcs(), rpcDefinition);
694 return rpcDefinition;
697 private static class TopDOMRpcImplementation implements DOMRpcImplementation {
698 private volatile SettableFuture<Entry<DOMRpcIdentifier, NormalizedNode<?, ?>>> rpcInvokedFuture;
699 private volatile FluentFuture<DOMRpcResult> returnFuture;
702 public FluentFuture<DOMRpcResult> invokeRpc(final DOMRpcIdentifier rpc,
703 final NormalizedNode<?, ?> input) {
704 rpcInvokedFuture.set(new SimpleEntry<>(rpc, input));
708 void init(final FluentFuture<DOMRpcResult> retFuture) {
709 this.returnFuture = retFuture;
710 rpcInvokedFuture = SettableFuture.create();
713 void verify(final DOMRpcIdentifier expRpc, final NormalizedNode<?, ?> expInput)
714 throws InterruptedException, ExecutionException, TimeoutException {
715 final Entry<DOMRpcIdentifier, NormalizedNode<?, ?>> actual = rpcInvokedFuture.get(5, TimeUnit.SECONDS);
716 assertEquals(expRpc, actual.getKey());
717 assertEquals(expInput, actual.getValue());