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;
25 import akka.actor.ActorSystem;
26 import akka.testkit.javadsl.TestKit;
27 import akka.util.Timeout;
28 import com.google.common.collect.ImmutableList;
29 import com.google.common.collect.ImmutableSet;
30 import com.google.common.util.concurrent.FluentFuture;
31 import com.google.common.util.concurrent.Futures;
32 import com.google.common.util.concurrent.ListenableFuture;
33 import com.google.common.util.concurrent.MoreExecutors;
34 import com.google.common.util.concurrent.SettableFuture;
35 import com.typesafe.config.ConfigFactory;
36 import io.netty.util.concurrent.EventExecutor;
37 import io.netty.util.concurrent.GlobalEventExecutor;
38 import io.netty.util.concurrent.SucceededFuture;
40 import java.util.AbstractMap.SimpleEntry;
41 import java.util.Arrays;
42 import java.util.Collections;
43 import java.util.Iterator;
44 import java.util.Map.Entry;
45 import java.util.Optional;
47 import java.util.concurrent.ExecutionException;
48 import java.util.concurrent.TimeUnit;
49 import java.util.concurrent.TimeoutException;
50 import org.apache.commons.io.FileUtils;
51 import org.junit.After;
52 import org.junit.Before;
53 import org.junit.Test;
54 import org.junit.runner.RunWith;
55 import org.mockito.Mock;
56 import org.mockito.junit.MockitoJUnitRunner;
57 import org.opendaylight.aaa.encrypt.AAAEncryptionService;
58 import org.opendaylight.controller.cluster.ActorSystemProvider;
59 import org.opendaylight.controller.config.threadpool.ScheduledThreadPool;
60 import org.opendaylight.controller.config.threadpool.ThreadPool;
61 import org.opendaylight.mdsal.binding.api.DataBroker;
62 import org.opendaylight.mdsal.binding.api.DataObjectModification;
63 import org.opendaylight.mdsal.binding.api.DataTreeIdentifier;
64 import org.opendaylight.mdsal.binding.api.DataTreeModification;
65 import org.opendaylight.mdsal.binding.api.ReadTransaction;
66 import org.opendaylight.mdsal.binding.api.Transaction;
67 import org.opendaylight.mdsal.binding.api.TransactionChain;
68 import org.opendaylight.mdsal.binding.api.TransactionChainListener;
69 import org.opendaylight.mdsal.binding.api.WriteTransaction;
70 import org.opendaylight.mdsal.binding.dom.adapter.test.AbstractConcurrentDataBrokerTest;
71 import org.opendaylight.mdsal.binding.dom.codec.api.BindingNormalizedNodeSerializer;
72 import org.opendaylight.mdsal.binding.generator.impl.ModuleInfoBackedContext;
73 import org.opendaylight.mdsal.binding.spec.reflect.BindingReflections;
74 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
75 import org.opendaylight.mdsal.dom.api.DOMActionProviderService;
76 import org.opendaylight.mdsal.dom.api.DOMActionService;
77 import org.opendaylight.mdsal.dom.api.DOMDataBroker;
78 import org.opendaylight.mdsal.dom.api.DOMDataTreeReadOperations;
79 import org.opendaylight.mdsal.dom.api.DOMDataTreeReadWriteTransaction;
80 import org.opendaylight.mdsal.dom.api.DOMDataTreeWriteTransaction;
81 import org.opendaylight.mdsal.dom.api.DOMMountPoint;
82 import org.opendaylight.mdsal.dom.api.DOMMountPointListener;
83 import org.opendaylight.mdsal.dom.api.DOMMountPointService;
84 import org.opendaylight.mdsal.dom.api.DOMRpcIdentifier;
85 import org.opendaylight.mdsal.dom.api.DOMRpcImplementation;
86 import org.opendaylight.mdsal.dom.api.DOMRpcProviderService;
87 import org.opendaylight.mdsal.dom.api.DOMRpcResult;
88 import org.opendaylight.mdsal.dom.api.DOMRpcService;
89 import org.opendaylight.mdsal.dom.api.DOMService;
90 import org.opendaylight.mdsal.dom.broker.DOMMountPointServiceImpl;
91 import org.opendaylight.mdsal.dom.broker.DOMRpcRouter;
92 import org.opendaylight.mdsal.dom.spi.DefaultDOMRpcResult;
93 import org.opendaylight.mdsal.eos.dom.simple.SimpleDOMEntityOwnershipService;
94 import org.opendaylight.mdsal.singleton.common.api.ClusterSingletonServiceProvider;
95 import org.opendaylight.mdsal.singleton.common.api.ClusterSingletonServiceRegistration;
96 import org.opendaylight.mdsal.singleton.common.api.ServiceGroupIdentifier;
97 import org.opendaylight.mdsal.singleton.dom.impl.DOMClusterSingletonServiceProviderImpl;
98 import org.opendaylight.netconf.client.NetconfClientDispatcher;
99 import org.opendaylight.netconf.sal.connect.api.DeviceActionFactory;
100 import org.opendaylight.netconf.sal.connect.api.SchemaResourceManager;
101 import org.opendaylight.netconf.sal.connect.impl.DefaultSchemaResourceManager;
102 import org.opendaylight.netconf.sal.connect.netconf.NetconfDevice.SchemaResourcesDTO;
103 import org.opendaylight.netconf.sal.connect.netconf.listener.NetconfSessionPreferences;
104 import org.opendaylight.netconf.topology.singleton.impl.utils.ClusteringRpcException;
105 import org.opendaylight.netconf.topology.singleton.impl.utils.NetconfTopologySetup;
106 import org.opendaylight.netconf.topology.singleton.impl.utils.NetconfTopologyUtils;
107 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Host;
108 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpAddress;
109 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Ipv4Address;
110 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.PortNumber;
111 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.keystore.rev171017.Keystore;
112 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.NetconfNode;
113 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.NetconfNodeBuilder;
114 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.NetconfNodeConnectionStatus;
115 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.credentials.credentials.LoginPwUnencryptedBuilder;
116 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.credentials.credentials.login.pw.unencrypted.LoginPasswordUnencryptedBuilder;
117 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.network.topology.topology.topology.types.TopologyNetconf;
118 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.topology.singleton.config.rev170419.Config;
119 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.topology.singleton.config.rev170419.ConfigBuilder;
120 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.list.rev140701.GetTopOutputBuilder;
121 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.list.rev140701.PutTopInputBuilder;
122 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.list.rev140701.Top;
123 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.list.rev140701.two.level.list.TopLevelList;
124 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.list.rev140701.two.level.list.TopLevelListBuilder;
125 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NetworkTopology;
126 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NodeId;
127 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.Topology;
128 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node;
129 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.NodeBuilder;
130 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.NodeKey;
131 import org.opendaylight.yangtools.rcf8528.data.util.EmptyMountPointContext;
132 import org.opendaylight.yangtools.util.concurrent.FluentFutures;
133 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
134 import org.opendaylight.yangtools.yang.binding.YangModuleInfo;
135 import org.opendaylight.yangtools.yang.common.QName;
136 import org.opendaylight.yangtools.yang.common.RpcError;
137 import org.opendaylight.yangtools.yang.common.RpcError.ErrorType;
138 import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
139 import org.opendaylight.yangtools.yang.common.Uint16;
140 import org.opendaylight.yangtools.yang.common.Uint32;
141 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
142 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
143 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
144 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
145 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
146 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
147 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
148 import org.opendaylight.yangtools.yang.model.api.Module;
149 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
150 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
151 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
152 import org.opendaylight.yangtools.yang.model.repo.api.RevisionSourceIdentifier;
153 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
154 import org.opendaylight.yangtools.yang.model.repo.spi.PotentialSchemaSource;
155 import org.slf4j.Logger;
156 import org.slf4j.LoggerFactory;
159 * Tests netconf mount points end-to-end.
161 * @author Thomas Pantelis
163 @RunWith(MockitoJUnitRunner.class)
164 public class MountPointEndToEndTest {
165 private static final Logger LOG = LoggerFactory.getLogger(MountPointEndToEndTest.class);
167 private static final String TOP_MODULE_NAME = "opendaylight-mdsal-list-test";
168 private static final String ACTOR_SYSTEM_NAME = "test";
169 private static final String TOPOLOGY_ID = TopologyNetconf.QNAME.getLocalName();
170 private static final NodeId NODE_ID = new NodeId("node-id");
171 private static final InstanceIdentifier<Node> NODE_INSTANCE_ID = NetconfTopologyUtils.createTopologyNodeListPath(
172 new NodeKey(NODE_ID), TOPOLOGY_ID);
174 private static final String TEST_ROOT_DIRECTORY = "test-cache-root";
175 private static final String TEST_DEFAULT_SUBDIR = "test-schema";
177 @Mock private DOMRpcProviderService mockRpcProviderRegistry;
178 @Mock private DOMActionProviderService mockActionProviderRegistry;
179 @Mock private NetconfClientDispatcher mockClientDispatcher;
180 @Mock private AAAEncryptionService mockEncryptionService;
181 @Mock private ThreadPool mockThreadPool;
182 @Mock private ScheduledThreadPool mockKeepaliveExecutor;
183 @Mock private DeviceActionFactory deviceActionFactory;
185 @Mock private ActorSystemProvider mockMasterActorSystemProvider;
186 @Mock private DOMMountPointListener masterMountPointListener;
187 private final DOMMountPointService masterMountPointService = new DOMMountPointServiceImpl();
188 private final DOMRpcRouter deviceRpcService = new DOMRpcRouter();
189 private DOMClusterSingletonServiceProviderImpl masterClusterSingletonServiceProvider;
190 private DataBroker masterDataBroker;
191 private DOMDataBroker deviceDOMDataBroker;
192 private ActorSystem masterSystem;
193 private NetconfTopologyManager masterNetconfTopologyManager;
194 private volatile SettableFuture<MasterSalFacade> masterSalFacadeFuture = SettableFuture.create();
196 @Mock private ActorSystemProvider mockSlaveActorSystemProvider;
197 @Mock private ClusterSingletonServiceProvider mockSlaveClusterSingletonServiceProvider;
198 @Mock private ClusterSingletonServiceRegistration mockSlaveClusterSingletonServiceReg;
199 @Mock private DOMMountPointListener slaveMountPointListener;
200 private final DOMMountPointService slaveMountPointService = new DOMMountPointServiceImpl();
201 private DataBroker slaveDataBroker;
202 private ActorSystem slaveSystem;
203 private NetconfTopologyManager slaveNetconfTopologyManager;
204 private final SettableFuture<NetconfTopologyContext> slaveNetconfTopologyContextFuture = SettableFuture.create();
205 private TransactionChain slaveTxChain;
207 private final EventExecutor eventExecutor = GlobalEventExecutor.INSTANCE;
208 private final Config config = new ConfigBuilder().setWriteTransactionIdleTimeout(Uint16.ZERO).build();
209 private SchemaContext deviceSchemaContext;
210 private YangModuleInfo topModuleInfo;
211 private SchemaPath putTopRpcSchemaPath;
212 private SchemaPath getTopRpcSchemaPath;
213 private BindingNormalizedNodeSerializer bindingToNormalized;
214 private YangInstanceIdentifier yangNodeInstanceId;
215 private final TopDOMRpcImplementation topRpcImplementation = new TopDOMRpcImplementation();
217 private SchemaResourceManager resourceManager;
219 @SuppressWarnings({ "unchecked", "rawtypes" })
221 public void setUp() throws Exception {
224 resourceManager = new DefaultSchemaResourceManager(TEST_ROOT_DIRECTORY, TEST_DEFAULT_SUBDIR);
226 topModuleInfo = BindingReflections.getModuleInfo(Top.class);
228 final ModuleInfoBackedContext moduleContext = ModuleInfoBackedContext.create();
229 moduleContext.addModuleInfos(Arrays.asList(topModuleInfo));
230 deviceSchemaContext = moduleContext.tryToCreateSchemaContext().get();
232 deviceRpcService.onGlobalContextUpdated(deviceSchemaContext);
234 putTopRpcSchemaPath = findRpcDefinition("put-top").getPath();
235 getTopRpcSchemaPath = findRpcDefinition("get-top").getPath();
237 deviceRpcService.getRpcProviderService().registerRpcImplementation(topRpcImplementation,
238 DOMRpcIdentifier.create(putTopRpcSchemaPath), DOMRpcIdentifier.create(getTopRpcSchemaPath));
244 yangNodeInstanceId = bindingToNormalized.toYangInstanceIdentifier(NODE_INSTANCE_ID);
246 doReturn(new SucceededFuture(GlobalEventExecutor.INSTANCE, null)).when(mockClientDispatcher)
247 .createReconnectingClient(any());
249 LOG.info("****** Setup complete");
252 private static void deleteCacheDir() {
253 FileUtils.deleteQuietly(new File(TEST_ROOT_DIRECTORY));
257 public void tearDown() throws Exception {
259 TestKit.shutdownActorSystem(slaveSystem, true);
260 TestKit.shutdownActorSystem(masterSystem, true);
263 private void setupMaster() throws Exception {
264 AbstractConcurrentDataBrokerTest dataBrokerTest = newDataBrokerTest();
265 masterDataBroker = dataBrokerTest.getDataBroker();
266 deviceDOMDataBroker = dataBrokerTest.getDomBroker();
267 bindingToNormalized = dataBrokerTest.getDataBrokerTestCustomizer().getBindingToNormalized();
269 masterSystem = ActorSystem.create(ACTOR_SYSTEM_NAME, ConfigFactory.load().getConfig("Master"));
271 masterClusterSingletonServiceProvider = new DOMClusterSingletonServiceProviderImpl(
272 new SimpleDOMEntityOwnershipService());
273 masterClusterSingletonServiceProvider.initializeProvider();
275 doReturn(masterSystem).when(mockMasterActorSystemProvider).getActorSystem();
277 doReturn(MoreExecutors.newDirectExecutorService()).when(mockThreadPool).getExecutor();
279 final SchemaResourcesDTO resources = resourceManager.getSchemaResources(
280 new NetconfNodeBuilder().setSchemaCacheDirectory(TEST_DEFAULT_SUBDIR).build(), "test");
281 resources.getSchemaRegistry().registerSchemaSource(
282 id -> Futures.immediateFuture(YangTextSchemaSource.delegateForByteSource(id,
283 topModuleInfo.getYangTextByteSource())),
284 PotentialSchemaSource.create(RevisionSourceIdentifier.create(TOP_MODULE_NAME,
285 topModuleInfo.getName().getRevision()), YangTextSchemaSource.class, 1));
287 masterNetconfTopologyManager = new NetconfTopologyManager(masterDataBroker, mockRpcProviderRegistry,
288 mockActionProviderRegistry, masterClusterSingletonServiceProvider, mockKeepaliveExecutor, mockThreadPool,
289 mockMasterActorSystemProvider, eventExecutor, mockClientDispatcher, TOPOLOGY_ID, config,
290 masterMountPointService, mockEncryptionService, deviceActionFactory, resourceManager) {
292 protected NetconfTopologyContext newNetconfTopologyContext(final NetconfTopologySetup setup,
293 final ServiceGroupIdentifier serviceGroupIdent, final Timeout actorResponseWaitTime,
294 final DeviceActionFactory deviceActionFact) {
295 NetconfTopologyContext context =
296 super.newNetconfTopologyContext(setup, serviceGroupIdent, actorResponseWaitTime, deviceActionFact);
298 NetconfTopologyContext spiedContext = spy(context);
299 doAnswer(invocation -> {
300 final MasterSalFacade spiedFacade = (MasterSalFacade) spy(invocation.callRealMethod());
301 doReturn(deviceDOMDataBroker).when(spiedFacade).newDeviceDataBroker();
302 masterSalFacadeFuture.set(spiedFacade);
304 }).when(spiedContext).newMasterSalFacade();
310 masterNetconfTopologyManager.init();
312 verifyTopologyNodesCreated(masterDataBroker);
315 private void setupSlave() throws Exception {
316 AbstractConcurrentDataBrokerTest dataBrokerTest = newDataBrokerTest();
317 slaveDataBroker = dataBrokerTest.getDataBroker();
319 slaveSystem = ActorSystem.create(ACTOR_SYSTEM_NAME, ConfigFactory.load().getConfig("Slave"));
321 doReturn(slaveSystem).when(mockSlaveActorSystemProvider).getActorSystem();
323 doReturn(mockSlaveClusterSingletonServiceReg).when(mockSlaveClusterSingletonServiceProvider)
324 .registerClusterSingletonService(any());
326 slaveNetconfTopologyManager = new NetconfTopologyManager(slaveDataBroker, mockRpcProviderRegistry,
327 mockActionProviderRegistry, mockSlaveClusterSingletonServiceProvider, mockKeepaliveExecutor, mockThreadPool,
328 mockSlaveActorSystemProvider, eventExecutor, mockClientDispatcher, TOPOLOGY_ID, config,
329 slaveMountPointService, mockEncryptionService, deviceActionFactory, resourceManager) {
331 protected NetconfTopologyContext newNetconfTopologyContext(final NetconfTopologySetup setup,
332 final ServiceGroupIdentifier serviceGroupIdent, final Timeout actorResponseWaitTime,
333 final DeviceActionFactory actionFactory) {
334 NetconfTopologyContext spiedContext = spy(super.newNetconfTopologyContext(setup, serviceGroupIdent,
335 actorResponseWaitTime, actionFactory));
337 slaveNetconfTopologyContextFuture.set(spiedContext);
342 slaveNetconfTopologyManager.init();
344 verifyTopologyNodesCreated(slaveDataBroker);
346 slaveTxChain = slaveDataBroker.createTransactionChain(new TransactionChainListener() {
348 public void onTransactionChainSuccessful(final TransactionChain chain) {
352 public void onTransactionChainFailed(final TransactionChain chain, final Transaction transaction,
353 final Throwable cause) {
354 LOG.error("Slave transaction chain failed", cause);
360 public void test() throws Exception {
365 final MasterSalFacade masterSalFacade = testMasterNodeUpdated();
367 testMasterDisconnected(masterSalFacade);
372 private MasterSalFacade testMaster() throws InterruptedException, ExecutionException, TimeoutException {
373 LOG.info("****** Testing master");
375 writeNetconfNode(TEST_DEFAULT_SUBDIR, masterDataBroker);
377 final MasterSalFacade masterSalFacade = masterSalFacadeFuture.get(5, TimeUnit.SECONDS);
379 masterSalFacade.onDeviceConnected(new EmptyMountPointContext(deviceSchemaContext),
380 NetconfSessionPreferences.fromStrings(Collections.emptyList()), deviceRpcService.getRpcService());
382 DOMMountPoint masterMountPoint = awaitMountPoint(masterMountPointService);
384 LOG.info("****** Testing master DOMDataBroker operations");
386 testDOMDataBrokerOperations(getDOMDataBroker(masterMountPoint));
388 LOG.info("****** Testing master DOMRpcService");
390 testDOMRpcService(getDOMRpcService(masterMountPoint));
391 return masterSalFacade;
394 private void testSlave() throws InterruptedException, ExecutionException, TimeoutException {
395 LOG.info("****** Testing slave");
397 writeNetconfNode("slave", slaveDataBroker);
399 verify(mockSlaveClusterSingletonServiceProvider, timeout(5000)).registerClusterSingletonService(any());
401 // Since the master and slave use separate DataBrokers we need to copy the master's oper node to the slave.
402 // This is essentially what happens in a clustered environment but we'll use a DTCL here.
404 masterDataBroker.registerDataTreeChangeListener(
405 DataTreeIdentifier.create(LogicalDatastoreType.OPERATIONAL, NODE_INSTANCE_ID), changes -> {
406 final WriteTransaction slaveTx = slaveTxChain.newWriteOnlyTransaction();
407 for (DataTreeModification<Node> dataTreeModification : changes) {
408 DataObjectModification<Node> rootNode = dataTreeModification.getRootNode();
409 InstanceIdentifier<Node> path = dataTreeModification.getRootPath().getRootIdentifier();
410 switch (rootNode.getModificationType()) {
412 case SUBTREE_MODIFIED:
413 slaveTx.merge(LogicalDatastoreType.OPERATIONAL, path, rootNode.getDataAfter());
416 slaveTx.delete(LogicalDatastoreType.OPERATIONAL, path);
426 DOMMountPoint slaveMountPoint = awaitMountPoint(slaveMountPointService);
428 final NetconfTopologyContext slaveNetconfTopologyContext =
429 slaveNetconfTopologyContextFuture.get(5, TimeUnit.SECONDS);
430 verify(slaveNetconfTopologyContext, never()).newMasterSalFacade();
432 LOG.info("****** Testing slave DOMDataBroker operations");
434 testDOMDataBrokerOperations(getDOMDataBroker(slaveMountPoint));
436 LOG.info("****** Testing slave DOMRpcService");
438 testDOMRpcService(getDOMRpcService(slaveMountPoint));
441 private MasterSalFacade testMasterNodeUpdated() throws InterruptedException, ExecutionException, TimeoutException {
442 LOG.info("****** Testing update master node");
444 masterMountPointService.registerProvisionListener(masterMountPointListener);
445 slaveMountPointService.registerProvisionListener(slaveMountPointListener);
447 masterSalFacadeFuture = SettableFuture.create();
448 writeNetconfNode(TEST_DEFAULT_SUBDIR, masterDataBroker);
450 verify(masterMountPointListener, timeout(5000)).onMountPointRemoved(yangNodeInstanceId);
452 MasterSalFacade masterSalFacade = masterSalFacadeFuture.get(5, TimeUnit.SECONDS);
454 masterSalFacade.onDeviceConnected(new EmptyMountPointContext(deviceSchemaContext),
455 NetconfSessionPreferences.fromStrings(Collections.emptyList()), deviceRpcService.getRpcService());
457 verify(masterMountPointListener, timeout(5000)).onMountPointCreated(yangNodeInstanceId);
459 verify(slaveMountPointListener, timeout(5000)).onMountPointRemoved(yangNodeInstanceId);
460 verify(slaveMountPointListener, timeout(5000)).onMountPointCreated(yangNodeInstanceId);
462 return masterSalFacade;
465 private void testMasterDisconnected(final MasterSalFacade masterSalFacade)
466 throws InterruptedException, ExecutionException, TimeoutException {
467 LOG.info("****** Testing master disconnected");
469 masterSalFacade.onDeviceDisconnected();
471 awaitMountPointNotPresent(masterMountPointService);
473 await().atMost(5, TimeUnit.SECONDS).until(() -> {
474 try (ReadTransaction readTx = masterDataBroker.newReadOnlyTransaction()) {
475 Optional<Node> node = readTx.read(LogicalDatastoreType.OPERATIONAL,
476 NODE_INSTANCE_ID).get(5, TimeUnit.SECONDS);
477 assertTrue(node.isPresent());
478 final NetconfNode netconfNode = node.get().augmentation(NetconfNode.class);
479 return netconfNode.getConnectionStatus() != NetconfNodeConnectionStatus.ConnectionStatus.Connected;
483 awaitMountPointNotPresent(slaveMountPointService);
486 private void testCleanup() throws Exception {
487 LOG.info("****** Testing cleanup");
489 slaveNetconfTopologyManager.close();
490 verify(mockSlaveClusterSingletonServiceReg).close();
493 private void testDOMRpcService(final DOMRpcService domRpcService)
494 throws InterruptedException, ExecutionException, TimeoutException {
495 testPutTopRpc(domRpcService, new DefaultDOMRpcResult((NormalizedNode<?, ?>)null));
496 testPutTopRpc(domRpcService, null);
497 testPutTopRpc(domRpcService, new DefaultDOMRpcResult(ImmutableList.of(
498 RpcResultBuilder.newError(ErrorType.APPLICATION, "tag1", "error1"),
499 RpcResultBuilder.newError(ErrorType.APPLICATION, "tag2", "error2"))));
501 testGetTopRpc(domRpcService, new DefaultDOMRpcResult(bindingToNormalized.toNormalizedNodeRpcData(
502 new GetTopOutputBuilder().setTopLevelList(Arrays.asList(new TopLevelListBuilder().setName("one")
503 .build())).build())));
505 testFailedRpc(domRpcService, getTopRpcSchemaPath, null);
508 private void testPutTopRpc(final DOMRpcService domRpcService, final DOMRpcResult result)
509 throws InterruptedException, ExecutionException, TimeoutException {
510 ContainerNode putTopInput = bindingToNormalized.toNormalizedNodeRpcData(
511 new PutTopInputBuilder().setTopLevelList(Arrays.asList(new TopLevelListBuilder().setName("one")
513 testRpc(domRpcService, putTopRpcSchemaPath, putTopInput, result);
516 private void testGetTopRpc(final DOMRpcService domRpcService, final DOMRpcResult result)
517 throws InterruptedException, ExecutionException, TimeoutException {
518 testRpc(domRpcService, getTopRpcSchemaPath, null, result);
521 private void testRpc(final DOMRpcService domRpcService, final SchemaPath schemaPath,
522 final NormalizedNode<?, ?> input, final DOMRpcResult result) throws InterruptedException,
523 ExecutionException, TimeoutException {
524 final FluentFuture<DOMRpcResult> future = result == null ? FluentFutures.immediateNullFluentFuture()
525 : FluentFutures.immediateFluentFuture(result);
526 final DOMRpcResult actual = invokeRpc(domRpcService, schemaPath, input, future);
527 if (result == null) {
532 assertNotNull(actual);
533 assertEquals(result.getResult(), actual.getResult());
535 assertEquals(result.getErrors().size(), actual.getErrors().size());
536 Iterator<? extends RpcError> iter1 = result.getErrors().iterator();
537 Iterator<? extends RpcError> iter2 = actual.getErrors().iterator();
538 while (iter1.hasNext() && iter2.hasNext()) {
539 RpcError err1 = iter1.next();
540 RpcError err2 = iter2.next();
541 assertEquals(err1.getErrorType(), err2.getErrorType());
542 assertEquals(err1.getTag(), err2.getTag());
543 assertEquals(err1.getMessage(), err2.getMessage());
544 assertEquals(err1.getSeverity(), err2.getSeverity());
545 assertEquals(err1.getApplicationTag(), err2.getApplicationTag());
546 assertEquals(err1.getInfo(), err2.getInfo());
550 private void testFailedRpc(final DOMRpcService domRpcService, final SchemaPath schemaPath,
551 final NormalizedNode<?, ?> input) throws InterruptedException, TimeoutException {
553 invokeRpc(domRpcService, schemaPath, input, FluentFutures.immediateFailedFluentFuture(
554 new ClusteringRpcException("mock")));
555 fail("Expected exception");
556 } catch (ExecutionException e) {
557 assertTrue(e.getCause() instanceof ClusteringRpcException);
558 assertEquals("mock", e.getCause().getMessage());
562 private DOMRpcResult invokeRpc(final DOMRpcService domRpcService, final SchemaPath schemaPath,
563 final NormalizedNode<?, ?> input, final FluentFuture<DOMRpcResult> returnFuture)
564 throws InterruptedException, ExecutionException, TimeoutException {
565 topRpcImplementation.init(returnFuture);
566 final ListenableFuture<DOMRpcResult> resultFuture = domRpcService.invokeRpc(schemaPath, input);
568 topRpcImplementation.verify(DOMRpcIdentifier.create(schemaPath), input);
570 return resultFuture.get(5, TimeUnit.SECONDS);
573 private static void testDOMDataBrokerOperations(final DOMDataBroker dataBroker)
574 throws InterruptedException, ExecutionException, TimeoutException {
576 DOMDataTreeWriteTransaction writeTx = dataBroker.newWriteOnlyTransaction();
578 final ContainerNode topNode = Builders.containerBuilder()
579 .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(Top.QNAME)).build();
580 final YangInstanceIdentifier topPath = YangInstanceIdentifier.of(Top.QNAME);
581 writeTx.put(LogicalDatastoreType.CONFIGURATION, topPath, topNode);
583 final QName name = QName.create(TopLevelList.QNAME, "name");
584 final YangInstanceIdentifier listPath = YangInstanceIdentifier.builder(topPath)
585 .node(TopLevelList.QNAME).build();
586 final MapEntryNode listEntryNode = ImmutableNodes.mapEntry(TopLevelList.QNAME, name, "one");
587 final MapNode listNode = ImmutableNodes.mapNodeBuilder(TopLevelList.QNAME).addChild(listEntryNode).build();
588 writeTx.merge(LogicalDatastoreType.CONFIGURATION, listPath, listNode);
589 writeTx.commit().get(5, TimeUnit.SECONDS);
591 verifyDataInStore(dataBroker.newReadWriteTransaction(), YangInstanceIdentifier.builder(listPath)
592 .nodeWithKey(TopLevelList.QNAME, name, "one").build(), listEntryNode);
594 writeTx = dataBroker.newWriteOnlyTransaction();
595 writeTx.delete(LogicalDatastoreType.CONFIGURATION, topPath);
596 writeTx.commit().get(5, TimeUnit.SECONDS);
598 DOMDataTreeReadWriteTransaction readTx = dataBroker.newReadWriteTransaction();
599 assertFalse(readTx.exists(LogicalDatastoreType.CONFIGURATION, topPath).get(5, TimeUnit.SECONDS));
600 assertTrue(readTx.cancel());
603 private static void writeNetconfNode(final String cacheDir, final DataBroker databroker)
604 throws InterruptedException, ExecutionException, TimeoutException {
605 final NetconfNode netconfNode = new NetconfNodeBuilder()
606 .setHost(new Host(new IpAddress(new Ipv4Address("127.0.0.1"))))
607 .setPort(new PortNumber(Uint16.valueOf(1234)))
608 .setActorResponseWaitTime(Uint16.valueOf(10))
609 .setTcpOnly(Boolean.TRUE)
610 .setSchemaless(Boolean.FALSE)
611 .setKeepaliveDelay(Uint32.ZERO)
612 .setConnectionTimeoutMillis(Uint32.valueOf(5000))
613 .setDefaultRequestTimeoutMillis(Uint32.valueOf(5000))
614 .setMaxConnectionAttempts(Uint32.ONE)
615 .setCredentials(new LoginPwUnencryptedBuilder().setLoginPasswordUnencrypted(
616 new LoginPasswordUnencryptedBuilder().setUsername("user").setPassword("pass").build()).build())
617 .setSchemaCacheDirectory(cacheDir)
619 final Node node = new NodeBuilder().setNodeId(NODE_ID).addAugmentation(NetconfNode.class, netconfNode).build();
621 final WriteTransaction writeTx = databroker.newWriteOnlyTransaction();
622 writeTx.put(LogicalDatastoreType.CONFIGURATION, NODE_INSTANCE_ID, node);
623 writeTx.commit().get(5, TimeUnit.SECONDS);
626 private static void verifyDataInStore(final DOMDataTreeReadOperations readTx, final YangInstanceIdentifier path,
627 final NormalizedNode<?, ?> expNode) throws InterruptedException, ExecutionException, TimeoutException {
628 final Optional<NormalizedNode<?, ?>> read = readTx.read(LogicalDatastoreType.CONFIGURATION, path)
629 .get(5, TimeUnit.SECONDS);
630 assertTrue(read.isPresent());
631 assertEquals(expNode, read.get());
633 final Boolean exists = readTx.exists(LogicalDatastoreType.CONFIGURATION, path).get(5, TimeUnit.SECONDS);
637 private static void verifyTopologyNodesCreated(final DataBroker dataBroker) {
638 await().atMost(5, TimeUnit.SECONDS).until(() -> {
639 try (ReadTransaction readTx = dataBroker.newReadOnlyTransaction()) {
640 Optional<Topology> configTopology = readTx.read(LogicalDatastoreType.CONFIGURATION,
641 NetconfTopologyUtils.createTopologyListPath(TOPOLOGY_ID)).get(3, TimeUnit.SECONDS);
642 Optional<Topology> operTopology = readTx.read(LogicalDatastoreType.OPERATIONAL,
643 NetconfTopologyUtils.createTopologyListPath(TOPOLOGY_ID)).get(3, TimeUnit.SECONDS);
644 return configTopology.isPresent() && operTopology.isPresent();
649 private AbstractConcurrentDataBrokerTest newDataBrokerTest() throws Exception {
650 AbstractConcurrentDataBrokerTest dataBrokerTest = new AbstractConcurrentDataBrokerTest(true) {
652 protected Set<YangModuleInfo> getModuleInfos() throws Exception {
653 return ImmutableSet.of(BindingReflections.getModuleInfo(NetconfNode.class),
654 BindingReflections.getModuleInfo(NetworkTopology.class),
655 BindingReflections.getModuleInfo(Topology.class),
656 BindingReflections.getModuleInfo(Keystore.class),
661 dataBrokerTest.setup();
662 return dataBrokerTest;
665 private void awaitMountPointNotPresent(final DOMMountPointService mountPointService) {
666 await().atMost(5, TimeUnit.SECONDS).until(
667 () -> !mountPointService.getMountPoint(yangNodeInstanceId).isPresent());
670 private static DOMDataBroker getDOMDataBroker(final DOMMountPoint mountPoint) {
671 return getMountPointService(mountPoint, DOMDataBroker.class);
674 private static DOMRpcService getDOMRpcService(final DOMMountPoint mountPoint) {
675 return getMountPointService(mountPoint, DOMRpcService.class);
678 private static DOMActionService getDomActionService(final DOMMountPoint mountPoint) {
679 return getMountPointService(mountPoint, DOMActionService.class);
682 private static <T extends DOMService> T getMountPointService(final DOMMountPoint mountPoint,
683 final Class<T> serviceClass) {
684 final Optional<T> maybeService = mountPoint.getService(serviceClass);
685 assertTrue(maybeService.isPresent());
686 return maybeService.get();
689 private DOMMountPoint awaitMountPoint(final DOMMountPointService mountPointService) {
690 await().atMost(5, TimeUnit.SECONDS).until(() ->
691 mountPointService.getMountPoint(yangNodeInstanceId).isPresent());
693 return mountPointService.getMountPoint(yangNodeInstanceId).get();
696 private RpcDefinition findRpcDefinition(final String rpc) {
697 Module topModule = deviceSchemaContext.findModule(TOP_MODULE_NAME, topModuleInfo.getName().getRevision()).get();
698 RpcDefinition rpcDefinition = null;
699 for (RpcDefinition def: topModule.getRpcs()) {
700 if (def.getQName().getLocalName().equals(rpc)) {
706 assertNotNull(rpc + " rpc not found in " + topModule.getRpcs(), rpcDefinition);
707 return rpcDefinition;
710 private static class TopDOMRpcImplementation implements DOMRpcImplementation {
711 private volatile SettableFuture<Entry<DOMRpcIdentifier, NormalizedNode<?, ?>>> rpcInvokedFuture;
712 private volatile FluentFuture<DOMRpcResult> returnFuture;
715 public FluentFuture<DOMRpcResult> invokeRpc(final DOMRpcIdentifier rpc,
716 final NormalizedNode<?, ?> input) {
717 rpcInvokedFuture.set(new SimpleEntry<>(rpc, input));
721 void init(final FluentFuture<DOMRpcResult> retFuture) {
722 this.returnFuture = retFuture;
723 rpcInvokedFuture = SettableFuture.create();
726 void verify(final DOMRpcIdentifier expRpc, final NormalizedNode<?, ?> expInput)
727 throws InterruptedException, ExecutionException, TimeoutException {
728 final Entry<DOMRpcIdentifier, NormalizedNode<?, ?>> actual = rpcInvokedFuture.get(5, TimeUnit.SECONDS);
729 assertEquals(expRpc, actual.getKey());
730 assertEquals(expInput, actual.getValue());