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.ImmutableMap;
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.Collections;
43 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.junit.runner.RunWith;
56 import org.mockito.Mock;
57 import org.mockito.junit.MockitoJUnitRunner;
58 import org.opendaylight.aaa.encrypt.AAAEncryptionService;
59 import org.opendaylight.binding.runtime.spi.BindingRuntimeHelpers;
60 import org.opendaylight.controller.cluster.ActorSystemProvider;
61 import org.opendaylight.controller.config.threadpool.ScheduledThreadPool;
62 import org.opendaylight.controller.config.threadpool.ThreadPool;
63 import org.opendaylight.mdsal.binding.api.DataBroker;
64 import org.opendaylight.mdsal.binding.api.DataObjectModification;
65 import org.opendaylight.mdsal.binding.api.DataTreeIdentifier;
66 import org.opendaylight.mdsal.binding.api.DataTreeModification;
67 import org.opendaylight.mdsal.binding.api.ReadTransaction;
68 import org.opendaylight.mdsal.binding.api.Transaction;
69 import org.opendaylight.mdsal.binding.api.TransactionChain;
70 import org.opendaylight.mdsal.binding.api.TransactionChainListener;
71 import org.opendaylight.mdsal.binding.api.WriteTransaction;
72 import org.opendaylight.mdsal.binding.dom.adapter.test.AbstractConcurrentDataBrokerTest;
73 import org.opendaylight.mdsal.binding.dom.codec.api.BindingNormalizedNodeSerializer;
74 import org.opendaylight.mdsal.binding.spec.reflect.BindingReflections;
75 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
76 import org.opendaylight.mdsal.dom.api.DOMActionProviderService;
77 import org.opendaylight.mdsal.dom.api.DOMActionService;
78 import org.opendaylight.mdsal.dom.api.DOMDataBroker;
79 import org.opendaylight.mdsal.dom.api.DOMDataTreeReadOperations;
80 import org.opendaylight.mdsal.dom.api.DOMDataTreeReadWriteTransaction;
81 import org.opendaylight.mdsal.dom.api.DOMDataTreeWriteTransaction;
82 import org.opendaylight.mdsal.dom.api.DOMMountPoint;
83 import org.opendaylight.mdsal.dom.api.DOMMountPointListener;
84 import org.opendaylight.mdsal.dom.api.DOMMountPointService;
85 import org.opendaylight.mdsal.dom.api.DOMRpcIdentifier;
86 import org.opendaylight.mdsal.dom.api.DOMRpcImplementation;
87 import org.opendaylight.mdsal.dom.api.DOMRpcProviderService;
88 import org.opendaylight.mdsal.dom.api.DOMRpcResult;
89 import org.opendaylight.mdsal.dom.api.DOMRpcService;
90 import org.opendaylight.mdsal.dom.api.DOMService;
91 import org.opendaylight.mdsal.dom.broker.DOMMountPointServiceImpl;
92 import org.opendaylight.mdsal.dom.broker.DOMRpcRouter;
93 import org.opendaylight.mdsal.dom.spi.DefaultDOMRpcResult;
94 import org.opendaylight.mdsal.eos.dom.simple.SimpleDOMEntityOwnershipService;
95 import org.opendaylight.mdsal.singleton.common.api.ClusterSingletonServiceProvider;
96 import org.opendaylight.mdsal.singleton.common.api.ClusterSingletonServiceRegistration;
97 import org.opendaylight.mdsal.singleton.common.api.ServiceGroupIdentifier;
98 import org.opendaylight.mdsal.singleton.dom.impl.DOMClusterSingletonServiceProviderImpl;
99 import org.opendaylight.netconf.client.NetconfClientDispatcher;
100 import org.opendaylight.netconf.sal.connect.api.DeviceActionFactory;
101 import org.opendaylight.netconf.sal.connect.api.SchemaResourceManager;
102 import org.opendaylight.netconf.sal.connect.impl.DefaultSchemaResourceManager;
103 import org.opendaylight.netconf.sal.connect.netconf.NetconfDevice.SchemaResourcesDTO;
104 import org.opendaylight.netconf.sal.connect.netconf.listener.NetconfSessionPreferences;
105 import org.opendaylight.netconf.topology.singleton.impl.utils.ClusteringRpcException;
106 import org.opendaylight.netconf.topology.singleton.impl.utils.NetconfTopologySetup;
107 import org.opendaylight.netconf.topology.singleton.impl.utils.NetconfTopologyUtils;
108 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Host;
109 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpAddress;
110 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Ipv4Address;
111 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.PortNumber;
112 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.keystore.rev171017.Keystore;
113 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.NetconfNode;
114 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.NetconfNodeBuilder;
115 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.NetconfNodeConnectionStatus;
116 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.credentials.credentials.LoginPwUnencryptedBuilder;
117 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.credentials.credentials.login.pw.unencrypted.LoginPasswordUnencryptedBuilder;
118 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.network.topology.topology.topology.types.TopologyNetconf;
119 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.topology.singleton.config.rev170419.Config;
120 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.topology.singleton.config.rev170419.ConfigBuilder;
121 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.list.rev140701.GetTopInput;
122 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.list.rev140701.GetTopOutputBuilder;
123 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.list.rev140701.PutTopInputBuilder;
124 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.list.rev140701.Top;
125 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.list.rev140701.two.level.list.TopLevelList;
126 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.list.rev140701.two.level.list.TopLevelListBuilder;
127 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.list.rev140701.two.level.list.TopLevelListKey;
128 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NetworkTopology;
129 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NodeId;
130 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.Topology;
131 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node;
132 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.NodeBuilder;
133 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.NodeKey;
134 import org.opendaylight.yangtools.rcf8528.data.util.EmptyMountPointContext;
135 import org.opendaylight.yangtools.util.concurrent.FluentFutures;
136 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
137 import org.opendaylight.yangtools.yang.binding.YangModuleInfo;
138 import org.opendaylight.yangtools.yang.common.QName;
139 import org.opendaylight.yangtools.yang.common.RpcError;
140 import org.opendaylight.yangtools.yang.common.RpcError.ErrorType;
141 import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
142 import org.opendaylight.yangtools.yang.common.Uint16;
143 import org.opendaylight.yangtools.yang.common.Uint32;
144 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
145 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
146 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
147 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
148 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
149 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
150 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
151 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
152 import org.opendaylight.yangtools.yang.model.api.Module;
153 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
154 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
155 import org.opendaylight.yangtools.yang.model.repo.api.RevisionSourceIdentifier;
156 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
157 import org.opendaylight.yangtools.yang.model.repo.spi.PotentialSchemaSource;
158 import org.opendaylight.yangtools.yang.parser.impl.YangParserFactoryImpl;
159 import org.slf4j.Logger;
160 import org.slf4j.LoggerFactory;
163 * Tests netconf mount points end-to-end.
165 * @author Thomas Pantelis
167 @RunWith(MockitoJUnitRunner.class)
168 public class MountPointEndToEndTest extends AbstractBaseSchemasTest {
169 private static final Logger LOG = LoggerFactory.getLogger(MountPointEndToEndTest.class);
171 private static final String TOP_MODULE_NAME = "opendaylight-mdsal-list-test";
172 private static final String ACTOR_SYSTEM_NAME = "test";
173 private static final String TOPOLOGY_ID = TopologyNetconf.QNAME.getLocalName();
174 private static final NodeId NODE_ID = new NodeId("node-id");
175 private static final InstanceIdentifier<Node> NODE_INSTANCE_ID = NetconfTopologyUtils.createTopologyNodeListPath(
176 new NodeKey(NODE_ID), TOPOLOGY_ID);
178 private static final String TEST_ROOT_DIRECTORY = "test-cache-root";
179 private static final String TEST_DEFAULT_SUBDIR = "test-schema";
181 @Mock private DOMRpcProviderService mockRpcProviderRegistry;
182 @Mock private DOMActionProviderService mockActionProviderRegistry;
183 @Mock private NetconfClientDispatcher mockClientDispatcher;
184 @Mock private AAAEncryptionService mockEncryptionService;
185 @Mock private ThreadPool mockThreadPool;
186 @Mock private ScheduledThreadPool mockKeepaliveExecutor;
187 @Mock private DeviceActionFactory deviceActionFactory;
189 @Mock private ActorSystemProvider mockMasterActorSystemProvider;
190 @Mock private DOMMountPointListener masterMountPointListener;
191 private final DOMMountPointService masterMountPointService = new DOMMountPointServiceImpl();
192 private final DOMRpcRouter deviceRpcService = new DOMRpcRouter();
193 private DOMClusterSingletonServiceProviderImpl masterClusterSingletonServiceProvider;
194 private DataBroker masterDataBroker;
195 private DOMDataBroker deviceDOMDataBroker;
196 private ActorSystem masterSystem;
197 private NetconfTopologyManager masterNetconfTopologyManager;
198 private volatile SettableFuture<MasterSalFacade> masterSalFacadeFuture = SettableFuture.create();
200 @Mock private ActorSystemProvider mockSlaveActorSystemProvider;
201 @Mock private ClusterSingletonServiceProvider mockSlaveClusterSingletonServiceProvider;
202 @Mock private ClusterSingletonServiceRegistration mockSlaveClusterSingletonServiceReg;
203 @Mock private DOMMountPointListener slaveMountPointListener;
204 private final DOMMountPointService slaveMountPointService = new DOMMountPointServiceImpl();
205 private DataBroker slaveDataBroker;
206 private ActorSystem slaveSystem;
207 private NetconfTopologyManager slaveNetconfTopologyManager;
208 private final SettableFuture<NetconfTopologyContext> slaveNetconfTopologyContextFuture = SettableFuture.create();
209 private TransactionChain slaveTxChain;
211 private final EventExecutor eventExecutor = GlobalEventExecutor.INSTANCE;
212 private final Config config = new ConfigBuilder().setWriteTransactionIdleTimeout(Uint16.ZERO).build();
213 private EffectiveModelContext deviceSchemaContext;
214 private YangModuleInfo topModuleInfo;
215 private SchemaPath putTopRpcSchemaPath;
216 private SchemaPath getTopRpcSchemaPath;
217 private BindingNormalizedNodeSerializer bindingToNormalized;
218 private YangInstanceIdentifier yangNodeInstanceId;
219 private final TopDOMRpcImplementation topRpcImplementation = new TopDOMRpcImplementation();
220 private final ContainerNode getTopInput = ImmutableNodes.containerNode(GetTopInput.QNAME);
222 private SchemaResourceManager resourceManager;
224 @SuppressWarnings({ "unchecked", "rawtypes" })
226 public void setUp() throws Exception {
229 resourceManager = new DefaultSchemaResourceManager(new YangParserFactoryImpl(), TEST_ROOT_DIRECTORY,
230 TEST_DEFAULT_SUBDIR);
232 topModuleInfo = BindingReflections.getModuleInfo(Top.class);
234 deviceSchemaContext = BindingRuntimeHelpers.createEffectiveModel(Top.class);
236 deviceRpcService.onModelContextUpdated(deviceSchemaContext);
238 putTopRpcSchemaPath = findRpcDefinition("put-top").getPath();
239 getTopRpcSchemaPath = findRpcDefinition("get-top").getPath();
241 deviceRpcService.getRpcProviderService().registerRpcImplementation(topRpcImplementation,
242 DOMRpcIdentifier.create(putTopRpcSchemaPath), DOMRpcIdentifier.create(getTopRpcSchemaPath));
248 yangNodeInstanceId = bindingToNormalized.toYangInstanceIdentifier(NODE_INSTANCE_ID);
250 doReturn(new SucceededFuture(GlobalEventExecutor.INSTANCE, null)).when(mockClientDispatcher)
251 .createReconnectingClient(any());
253 LOG.info("****** Setup complete");
256 private static void deleteCacheDir() {
257 FileUtils.deleteQuietly(new File(TEST_ROOT_DIRECTORY));
261 public void tearDown() throws Exception {
263 TestKit.shutdownActorSystem(slaveSystem, true);
264 TestKit.shutdownActorSystem(masterSystem, true);
267 private void setupMaster() throws Exception {
268 AbstractConcurrentDataBrokerTest dataBrokerTest = newDataBrokerTest();
269 masterDataBroker = dataBrokerTest.getDataBroker();
270 deviceDOMDataBroker = dataBrokerTest.getDomBroker();
271 bindingToNormalized = dataBrokerTest.getDataBrokerTestCustomizer().getAdapterContext().currentSerializer();
273 masterSystem = ActorSystem.create(ACTOR_SYSTEM_NAME, ConfigFactory.load().getConfig("Master"));
275 masterClusterSingletonServiceProvider = new DOMClusterSingletonServiceProviderImpl(
276 new SimpleDOMEntityOwnershipService());
277 masterClusterSingletonServiceProvider.initializeProvider();
279 doReturn(masterSystem).when(mockMasterActorSystemProvider).getActorSystem();
281 doReturn(MoreExecutors.newDirectExecutorService()).when(mockThreadPool).getExecutor();
283 final SchemaResourcesDTO resources = resourceManager.getSchemaResources(
284 new NetconfNodeBuilder().setSchemaCacheDirectory(TEST_DEFAULT_SUBDIR).build(), "test");
285 resources.getSchemaRegistry().registerSchemaSource(
286 id -> Futures.immediateFuture(YangTextSchemaSource.delegateForByteSource(id,
287 topModuleInfo.getYangTextByteSource())),
288 PotentialSchemaSource.create(RevisionSourceIdentifier.create(TOP_MODULE_NAME,
289 topModuleInfo.getName().getRevision()), YangTextSchemaSource.class, 1));
291 masterNetconfTopologyManager = new NetconfTopologyManager(BASE_SCHEMAS, masterDataBroker,
292 mockRpcProviderRegistry, mockActionProviderRegistry, masterClusterSingletonServiceProvider,
293 mockKeepaliveExecutor, mockThreadPool, mockMasterActorSystemProvider, eventExecutor,
294 mockClientDispatcher, TOPOLOGY_ID, config, masterMountPointService, mockEncryptionService,
295 deviceActionFactory, resourceManager) {
297 protected NetconfTopologyContext newNetconfTopologyContext(final NetconfTopologySetup setup,
298 final ServiceGroupIdentifier serviceGroupIdent, final Timeout actorResponseWaitTime,
299 final DeviceActionFactory deviceActionFact) {
300 NetconfTopologyContext context =
301 super.newNetconfTopologyContext(setup, serviceGroupIdent, actorResponseWaitTime, deviceActionFact);
303 NetconfTopologyContext spiedContext = spy(context);
304 doAnswer(invocation -> {
305 final MasterSalFacade spiedFacade = (MasterSalFacade) spy(invocation.callRealMethod());
306 doReturn(deviceDOMDataBroker).when(spiedFacade).newDeviceDataBroker();
307 masterSalFacadeFuture.set(spiedFacade);
309 }).when(spiedContext).newMasterSalFacade();
315 masterNetconfTopologyManager.init();
317 verifyTopologyNodesCreated(masterDataBroker);
320 private void setupSlave() throws Exception {
321 AbstractConcurrentDataBrokerTest dataBrokerTest = newDataBrokerTest();
322 slaveDataBroker = dataBrokerTest.getDataBroker();
324 slaveSystem = ActorSystem.create(ACTOR_SYSTEM_NAME, ConfigFactory.load().getConfig("Slave"));
326 doReturn(slaveSystem).when(mockSlaveActorSystemProvider).getActorSystem();
328 doReturn(mockSlaveClusterSingletonServiceReg).when(mockSlaveClusterSingletonServiceProvider)
329 .registerClusterSingletonService(any());
331 slaveNetconfTopologyManager = new NetconfTopologyManager(BASE_SCHEMAS, slaveDataBroker, mockRpcProviderRegistry,
332 mockActionProviderRegistry, mockSlaveClusterSingletonServiceProvider, mockKeepaliveExecutor, mockThreadPool,
333 mockSlaveActorSystemProvider, eventExecutor, mockClientDispatcher, TOPOLOGY_ID, config,
334 slaveMountPointService, mockEncryptionService, deviceActionFactory, resourceManager) {
336 protected NetconfTopologyContext newNetconfTopologyContext(final NetconfTopologySetup setup,
337 final ServiceGroupIdentifier serviceGroupIdent, final Timeout actorResponseWaitTime,
338 final DeviceActionFactory actionFactory) {
339 NetconfTopologyContext spiedContext = spy(super.newNetconfTopologyContext(setup, serviceGroupIdent,
340 actorResponseWaitTime, actionFactory));
342 slaveNetconfTopologyContextFuture.set(spiedContext);
347 slaveNetconfTopologyManager.init();
349 verifyTopologyNodesCreated(slaveDataBroker);
351 slaveTxChain = slaveDataBroker.createTransactionChain(new TransactionChainListener() {
353 public void onTransactionChainSuccessful(final TransactionChain chain) {
357 public void onTransactionChainFailed(final TransactionChain chain, final Transaction transaction,
358 final Throwable cause) {
359 LOG.error("Slave transaction chain failed", cause);
365 public void test() throws Exception {
370 final MasterSalFacade masterSalFacade = testMasterNodeUpdated();
372 testMasterDisconnected(masterSalFacade);
377 private MasterSalFacade testMaster() throws InterruptedException, ExecutionException, TimeoutException {
378 LOG.info("****** Testing master");
380 writeNetconfNode(TEST_DEFAULT_SUBDIR, masterDataBroker);
382 final MasterSalFacade masterSalFacade = masterSalFacadeFuture.get(5, TimeUnit.SECONDS);
384 masterSalFacade.onDeviceConnected(new EmptyMountPointContext(deviceSchemaContext),
385 NetconfSessionPreferences.fromStrings(Collections.emptyList()), deviceRpcService.getRpcService());
387 DOMMountPoint masterMountPoint = awaitMountPoint(masterMountPointService);
389 LOG.info("****** Testing master DOMDataBroker operations");
391 testDOMDataBrokerOperations(getDOMDataBroker(masterMountPoint));
393 LOG.info("****** Testing master DOMRpcService");
395 testDOMRpcService(getDOMRpcService(masterMountPoint));
396 return masterSalFacade;
399 private void testSlave() throws InterruptedException, ExecutionException, TimeoutException {
400 LOG.info("****** Testing slave");
402 writeNetconfNode("slave", slaveDataBroker);
404 verify(mockSlaveClusterSingletonServiceProvider, timeout(5000)).registerClusterSingletonService(any());
406 // Since the master and slave use separate DataBrokers we need to copy the master's oper node to the slave.
407 // This is essentially what happens in a clustered environment but we'll use a DTCL here.
409 masterDataBroker.registerDataTreeChangeListener(
410 DataTreeIdentifier.create(LogicalDatastoreType.OPERATIONAL, NODE_INSTANCE_ID), changes -> {
411 final WriteTransaction slaveTx = slaveTxChain.newWriteOnlyTransaction();
412 for (DataTreeModification<Node> dataTreeModification : changes) {
413 DataObjectModification<Node> rootNode = dataTreeModification.getRootNode();
414 InstanceIdentifier<Node> path = dataTreeModification.getRootPath().getRootIdentifier();
415 switch (rootNode.getModificationType()) {
417 case SUBTREE_MODIFIED:
418 slaveTx.merge(LogicalDatastoreType.OPERATIONAL, path, rootNode.getDataAfter());
421 slaveTx.delete(LogicalDatastoreType.OPERATIONAL, path);
431 DOMMountPoint slaveMountPoint = awaitMountPoint(slaveMountPointService);
433 final NetconfTopologyContext slaveNetconfTopologyContext =
434 slaveNetconfTopologyContextFuture.get(5, TimeUnit.SECONDS);
435 verify(slaveNetconfTopologyContext, never()).newMasterSalFacade();
437 LOG.info("****** Testing slave DOMDataBroker operations");
439 testDOMDataBrokerOperations(getDOMDataBroker(slaveMountPoint));
441 LOG.info("****** Testing slave DOMRpcService");
443 testDOMRpcService(getDOMRpcService(slaveMountPoint));
446 private MasterSalFacade testMasterNodeUpdated() throws InterruptedException, ExecutionException, TimeoutException {
447 LOG.info("****** Testing update master node");
449 masterMountPointService.registerProvisionListener(masterMountPointListener);
450 slaveMountPointService.registerProvisionListener(slaveMountPointListener);
452 masterSalFacadeFuture = SettableFuture.create();
453 writeNetconfNode(TEST_DEFAULT_SUBDIR, masterDataBroker);
455 verify(masterMountPointListener, timeout(5000)).onMountPointRemoved(yangNodeInstanceId);
457 MasterSalFacade masterSalFacade = masterSalFacadeFuture.get(5, TimeUnit.SECONDS);
459 masterSalFacade.onDeviceConnected(new EmptyMountPointContext(deviceSchemaContext),
460 NetconfSessionPreferences.fromStrings(Collections.emptyList()), deviceRpcService.getRpcService());
462 verify(masterMountPointListener, timeout(5000)).onMountPointCreated(yangNodeInstanceId);
464 verify(slaveMountPointListener, timeout(5000)).onMountPointRemoved(yangNodeInstanceId);
465 verify(slaveMountPointListener, timeout(5000)).onMountPointCreated(yangNodeInstanceId);
467 return masterSalFacade;
470 private void testMasterDisconnected(final MasterSalFacade masterSalFacade)
471 throws InterruptedException, ExecutionException, TimeoutException {
472 LOG.info("****** Testing master disconnected");
474 masterSalFacade.onDeviceDisconnected();
476 awaitMountPointNotPresent(masterMountPointService);
478 await().atMost(5, TimeUnit.SECONDS).until(() -> {
479 try (ReadTransaction readTx = masterDataBroker.newReadOnlyTransaction()) {
480 Optional<Node> node = readTx.read(LogicalDatastoreType.OPERATIONAL,
481 NODE_INSTANCE_ID).get(5, TimeUnit.SECONDS);
482 assertTrue(node.isPresent());
483 final NetconfNode netconfNode = node.get().augmentation(NetconfNode.class);
484 return netconfNode.getConnectionStatus() != NetconfNodeConnectionStatus.ConnectionStatus.Connected;
488 awaitMountPointNotPresent(slaveMountPointService);
491 private void testCleanup() throws Exception {
492 LOG.info("****** Testing cleanup");
494 slaveNetconfTopologyManager.close();
495 verify(mockSlaveClusterSingletonServiceReg).close();
498 private void testDOMRpcService(final DOMRpcService domRpcService)
499 throws InterruptedException, ExecutionException, TimeoutException {
500 testPutTopRpc(domRpcService, new DefaultDOMRpcResult((NormalizedNode<?, ?>)null));
501 testPutTopRpc(domRpcService, null);
502 testPutTopRpc(domRpcService, new DefaultDOMRpcResult(ImmutableList.of(
503 RpcResultBuilder.newError(ErrorType.APPLICATION, "tag1", "error1"),
504 RpcResultBuilder.newError(ErrorType.APPLICATION, "tag2", "error2"))));
506 testGetTopRpc(domRpcService, new DefaultDOMRpcResult(bindingToNormalized.toNormalizedNodeRpcData(
507 new GetTopOutputBuilder().setTopLevelList(oneTopLevelList()).build())));
509 testFailedRpc(domRpcService, getTopRpcSchemaPath, getTopInput);
512 private void testPutTopRpc(final DOMRpcService domRpcService, final DOMRpcResult result)
513 throws InterruptedException, ExecutionException, TimeoutException {
514 ContainerNode putTopInput = bindingToNormalized.toNormalizedNodeRpcData(
515 new PutTopInputBuilder().setTopLevelList(oneTopLevelList()).build());
516 testRpc(domRpcService, putTopRpcSchemaPath, putTopInput, result);
519 private static Map<TopLevelListKey, TopLevelList> oneTopLevelList() {
520 final TopLevelListKey key = new TopLevelListKey("one");
521 return ImmutableMap.of(key, new TopLevelListBuilder().withKey(key).build());
524 private void testGetTopRpc(final DOMRpcService domRpcService, final DOMRpcResult result)
525 throws InterruptedException, ExecutionException, TimeoutException {
526 testRpc(domRpcService, getTopRpcSchemaPath, getTopInput, result);
529 private void testRpc(final DOMRpcService domRpcService, final SchemaPath schemaPath,
530 final NormalizedNode<?, ?> input, final DOMRpcResult result) throws InterruptedException,
531 ExecutionException, TimeoutException {
532 final FluentFuture<DOMRpcResult> future = result == null ? FluentFutures.immediateNullFluentFuture()
533 : FluentFutures.immediateFluentFuture(result);
534 final DOMRpcResult actual = invokeRpc(domRpcService, schemaPath, input, future);
535 if (result == null) {
540 assertNotNull(actual);
541 assertEquals(result.getResult(), actual.getResult());
543 assertEquals(result.getErrors().size(), actual.getErrors().size());
544 Iterator<? extends RpcError> iter1 = result.getErrors().iterator();
545 Iterator<? extends RpcError> iter2 = actual.getErrors().iterator();
546 while (iter1.hasNext() && iter2.hasNext()) {
547 RpcError err1 = iter1.next();
548 RpcError err2 = iter2.next();
549 assertEquals(err1.getErrorType(), err2.getErrorType());
550 assertEquals(err1.getTag(), err2.getTag());
551 assertEquals(err1.getMessage(), err2.getMessage());
552 assertEquals(err1.getSeverity(), err2.getSeverity());
553 assertEquals(err1.getApplicationTag(), err2.getApplicationTag());
554 assertEquals(err1.getInfo(), err2.getInfo());
558 private void testFailedRpc(final DOMRpcService domRpcService, final SchemaPath schemaPath,
559 final NormalizedNode<?, ?> input) throws InterruptedException, TimeoutException {
561 invokeRpc(domRpcService, schemaPath, input, FluentFutures.immediateFailedFluentFuture(
562 new ClusteringRpcException("mock")));
563 fail("Expected exception");
564 } catch (ExecutionException e) {
565 assertTrue(e.getCause() instanceof ClusteringRpcException);
566 assertEquals("mock", e.getCause().getMessage());
570 private DOMRpcResult invokeRpc(final DOMRpcService domRpcService, final SchemaPath schemaPath,
571 final NormalizedNode<?, ?> input, final FluentFuture<DOMRpcResult> returnFuture)
572 throws InterruptedException, ExecutionException, TimeoutException {
573 topRpcImplementation.init(returnFuture);
574 final ListenableFuture<? extends DOMRpcResult> resultFuture = domRpcService.invokeRpc(schemaPath, input);
576 topRpcImplementation.verify(DOMRpcIdentifier.create(schemaPath), input);
578 return resultFuture.get(5, TimeUnit.SECONDS);
581 private static void testDOMDataBrokerOperations(final DOMDataBroker dataBroker)
582 throws InterruptedException, ExecutionException, TimeoutException {
584 DOMDataTreeWriteTransaction writeTx = dataBroker.newWriteOnlyTransaction();
586 final ContainerNode topNode = Builders.containerBuilder()
587 .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(Top.QNAME)).build();
588 final YangInstanceIdentifier topPath = YangInstanceIdentifier.of(Top.QNAME);
589 writeTx.put(LogicalDatastoreType.CONFIGURATION, topPath, topNode);
591 final QName name = QName.create(TopLevelList.QNAME, "name");
592 final YangInstanceIdentifier listPath = YangInstanceIdentifier.builder(topPath)
593 .node(TopLevelList.QNAME).build();
594 final MapEntryNode listEntryNode = ImmutableNodes.mapEntry(TopLevelList.QNAME, name, "one");
595 final MapNode listNode = ImmutableNodes.mapNodeBuilder(TopLevelList.QNAME).addChild(listEntryNode).build();
596 writeTx.merge(LogicalDatastoreType.CONFIGURATION, listPath, listNode);
597 writeTx.commit().get(5, TimeUnit.SECONDS);
599 verifyDataInStore(dataBroker.newReadWriteTransaction(), YangInstanceIdentifier.builder(listPath)
600 .nodeWithKey(TopLevelList.QNAME, name, "one").build(), listEntryNode);
602 writeTx = dataBroker.newWriteOnlyTransaction();
603 writeTx.delete(LogicalDatastoreType.CONFIGURATION, topPath);
604 writeTx.commit().get(5, TimeUnit.SECONDS);
606 DOMDataTreeReadWriteTransaction readTx = dataBroker.newReadWriteTransaction();
607 assertFalse(readTx.exists(LogicalDatastoreType.CONFIGURATION, topPath).get(5, TimeUnit.SECONDS));
608 assertTrue(readTx.cancel());
611 private static void writeNetconfNode(final String cacheDir, final DataBroker databroker)
612 throws InterruptedException, ExecutionException, TimeoutException {
613 final Node node = new NodeBuilder()
615 .addAugmentation(new NetconfNodeBuilder()
616 .setHost(new Host(new IpAddress(new Ipv4Address("127.0.0.1"))))
617 .setPort(new PortNumber(Uint16.valueOf(1234)))
618 .setActorResponseWaitTime(Uint16.valueOf(10))
619 .setTcpOnly(Boolean.TRUE)
620 .setSchemaless(Boolean.FALSE)
621 .setKeepaliveDelay(Uint32.ZERO)
622 .setConnectionTimeoutMillis(Uint32.valueOf(5000))
623 .setDefaultRequestTimeoutMillis(Uint32.valueOf(5000))
624 .setMaxConnectionAttempts(Uint32.ONE)
625 .setCredentials(new LoginPwUnencryptedBuilder()
626 .setLoginPasswordUnencrypted(new LoginPasswordUnencryptedBuilder()
631 .setSchemaCacheDirectory(cacheDir)
635 final WriteTransaction writeTx = databroker.newWriteOnlyTransaction();
636 writeTx.put(LogicalDatastoreType.CONFIGURATION, NODE_INSTANCE_ID, node);
637 writeTx.commit().get(5, TimeUnit.SECONDS);
640 private static void verifyDataInStore(final DOMDataTreeReadOperations readTx, final YangInstanceIdentifier path,
641 final NormalizedNode<?, ?> expNode) throws InterruptedException, ExecutionException, TimeoutException {
642 final Optional<NormalizedNode<?, ?>> read = readTx.read(LogicalDatastoreType.CONFIGURATION, path)
643 .get(5, TimeUnit.SECONDS);
644 assertTrue(read.isPresent());
645 assertEquals(expNode, read.get());
647 final Boolean exists = readTx.exists(LogicalDatastoreType.CONFIGURATION, path).get(5, TimeUnit.SECONDS);
651 private static void verifyTopologyNodesCreated(final DataBroker dataBroker) {
652 await().atMost(5, TimeUnit.SECONDS).until(() -> {
653 try (ReadTransaction readTx = dataBroker.newReadOnlyTransaction()) {
654 Optional<Topology> configTopology = readTx.read(LogicalDatastoreType.CONFIGURATION,
655 NetconfTopologyUtils.createTopologyListPath(TOPOLOGY_ID)).get(3, TimeUnit.SECONDS);
656 Optional<Topology> operTopology = readTx.read(LogicalDatastoreType.OPERATIONAL,
657 NetconfTopologyUtils.createTopologyListPath(TOPOLOGY_ID)).get(3, TimeUnit.SECONDS);
658 return configTopology.isPresent() && operTopology.isPresent();
663 private AbstractConcurrentDataBrokerTest newDataBrokerTest() throws Exception {
664 AbstractConcurrentDataBrokerTest dataBrokerTest = new AbstractConcurrentDataBrokerTest(true) {
666 protected Set<YangModuleInfo> getModuleInfos() throws Exception {
667 return ImmutableSet.of(BindingReflections.getModuleInfo(NetconfNode.class),
668 BindingReflections.getModuleInfo(NetworkTopology.class),
669 BindingReflections.getModuleInfo(Topology.class),
670 BindingReflections.getModuleInfo(Keystore.class),
675 dataBrokerTest.setup();
676 return dataBrokerTest;
679 private void awaitMountPointNotPresent(final DOMMountPointService mountPointService) {
680 await().atMost(5, TimeUnit.SECONDS).until(
681 () -> !mountPointService.getMountPoint(yangNodeInstanceId).isPresent());
684 private static DOMDataBroker getDOMDataBroker(final DOMMountPoint mountPoint) {
685 return getMountPointService(mountPoint, DOMDataBroker.class);
688 private static DOMRpcService getDOMRpcService(final DOMMountPoint mountPoint) {
689 return getMountPointService(mountPoint, DOMRpcService.class);
692 private static DOMActionService getDomActionService(final DOMMountPoint mountPoint) {
693 return getMountPointService(mountPoint, DOMActionService.class);
696 private static <T extends DOMService> T getMountPointService(final DOMMountPoint mountPoint,
697 final Class<T> serviceClass) {
698 final Optional<T> maybeService = mountPoint.getService(serviceClass);
699 assertTrue(maybeService.isPresent());
700 return maybeService.get();
703 private DOMMountPoint awaitMountPoint(final DOMMountPointService mountPointService) {
704 await().atMost(5, TimeUnit.SECONDS).until(() ->
705 mountPointService.getMountPoint(yangNodeInstanceId).isPresent());
707 return mountPointService.getMountPoint(yangNodeInstanceId).get();
710 private RpcDefinition findRpcDefinition(final String rpc) {
711 Module topModule = deviceSchemaContext.findModule(TOP_MODULE_NAME, topModuleInfo.getName().getRevision()).get();
712 RpcDefinition rpcDefinition = null;
713 for (RpcDefinition def: topModule.getRpcs()) {
714 if (def.getQName().getLocalName().equals(rpc)) {
720 assertNotNull(rpc + " rpc not found in " + topModule.getRpcs(), rpcDefinition);
721 return rpcDefinition;
724 private static class TopDOMRpcImplementation implements DOMRpcImplementation {
725 private volatile SettableFuture<Entry<DOMRpcIdentifier, NormalizedNode<?, ?>>> rpcInvokedFuture;
726 private volatile FluentFuture<DOMRpcResult> returnFuture;
729 public FluentFuture<DOMRpcResult> invokeRpc(final DOMRpcIdentifier rpc,
730 final NormalizedNode<?, ?> input) {
731 rpcInvokedFuture.set(new SimpleEntry<>(rpc, input));
735 void init(final FluentFuture<DOMRpcResult> retFuture) {
736 this.returnFuture = retFuture;
737 rpcInvokedFuture = SettableFuture.create();
740 void verify(final DOMRpcIdentifier expRpc, final NormalizedNode<?, ?> expInput)
741 throws InterruptedException, ExecutionException, TimeoutException {
742 final Entry<DOMRpcIdentifier, NormalizedNode<?, ?>> actual = rpcInvokedFuture.get(5, TimeUnit.SECONDS);
743 assertEquals(expRpc, actual.getKey());
744 assertEquals(expInput, actual.getValue());