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.mock;
21 import static org.mockito.Mockito.never;
22 import static org.mockito.Mockito.spy;
23 import static org.mockito.Mockito.timeout;
24 import static org.mockito.Mockito.verify;
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.ImmutableMap;
31 import com.google.common.collect.ImmutableSet;
32 import com.google.common.collect.Lists;
33 import com.google.common.util.concurrent.FluentFuture;
34 import com.google.common.util.concurrent.Futures;
35 import com.google.common.util.concurrent.ListenableFuture;
36 import com.google.common.util.concurrent.MoreExecutors;
37 import com.google.common.util.concurrent.SettableFuture;
38 import com.typesafe.config.ConfigFactory;
39 import io.netty.util.concurrent.EventExecutor;
40 import io.netty.util.concurrent.GlobalEventExecutor;
42 import java.util.AbstractMap.SimpleEntry;
43 import java.util.ArrayList;
44 import java.util.Iterator;
46 import java.util.Map.Entry;
47 import java.util.Optional;
49 import java.util.concurrent.ExecutionException;
50 import java.util.concurrent.TimeUnit;
51 import java.util.concurrent.TimeoutException;
52 import org.apache.commons.io.FileUtils;
53 import org.junit.After;
54 import org.junit.Before;
55 import org.junit.Test;
56 import org.junit.runner.RunWith;
57 import org.mockito.Mock;
58 import org.mockito.junit.MockitoJUnitRunner;
59 import org.opendaylight.aaa.encrypt.AAAEncryptionService;
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.RpcProviderService;
69 import org.opendaylight.mdsal.binding.api.Transaction;
70 import org.opendaylight.mdsal.binding.api.TransactionChain;
71 import org.opendaylight.mdsal.binding.api.TransactionChainListener;
72 import org.opendaylight.mdsal.binding.api.WriteTransaction;
73 import org.opendaylight.mdsal.binding.dom.adapter.test.AbstractConcurrentDataBrokerTest;
74 import org.opendaylight.mdsal.binding.dom.codec.api.BindingNormalizedNodeSerializer;
75 import org.opendaylight.mdsal.binding.runtime.spi.BindingRuntimeHelpers;
76 import org.opendaylight.mdsal.binding.spec.reflect.BindingReflections;
77 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
78 import org.opendaylight.mdsal.dom.api.DOMActionProviderService;
79 import org.opendaylight.mdsal.dom.api.DOMActionService;
80 import org.opendaylight.mdsal.dom.api.DOMDataBroker;
81 import org.opendaylight.mdsal.dom.api.DOMDataTreeReadOperations;
82 import org.opendaylight.mdsal.dom.api.DOMDataTreeReadWriteTransaction;
83 import org.opendaylight.mdsal.dom.api.DOMDataTreeWriteTransaction;
84 import org.opendaylight.mdsal.dom.api.DOMMountPoint;
85 import org.opendaylight.mdsal.dom.api.DOMMountPointListener;
86 import org.opendaylight.mdsal.dom.api.DOMMountPointService;
87 import org.opendaylight.mdsal.dom.api.DOMRpcIdentifier;
88 import org.opendaylight.mdsal.dom.api.DOMRpcImplementation;
89 import org.opendaylight.mdsal.dom.api.DOMRpcProviderService;
90 import org.opendaylight.mdsal.dom.api.DOMRpcResult;
91 import org.opendaylight.mdsal.dom.api.DOMRpcService;
92 import org.opendaylight.mdsal.dom.api.DOMService;
93 import org.opendaylight.mdsal.dom.broker.DOMMountPointServiceImpl;
94 import org.opendaylight.mdsal.dom.broker.DOMRpcRouter;
95 import org.opendaylight.mdsal.dom.spi.DefaultDOMRpcResult;
96 import org.opendaylight.mdsal.singleton.common.api.ClusterSingletonServiceProvider;
97 import org.opendaylight.mdsal.singleton.common.api.ClusterSingletonServiceRegistration;
98 import org.opendaylight.mdsal.singleton.common.api.ServiceGroupIdentifier;
99 import org.opendaylight.mdsal.singleton.dom.impl.DOMClusterSingletonServiceProviderImpl;
100 import org.opendaylight.netconf.client.NetconfClientDispatcher;
101 import org.opendaylight.netconf.nettyutil.ReconnectFuture;
102 import org.opendaylight.netconf.sal.connect.api.DeviceActionFactory;
103 import org.opendaylight.netconf.sal.connect.api.SchemaResourceManager;
104 import org.opendaylight.netconf.sal.connect.impl.DefaultSchemaResourceManager;
105 import org.opendaylight.netconf.sal.connect.netconf.NetconfDevice.SchemaResourcesDTO;
106 import org.opendaylight.netconf.sal.connect.netconf.listener.NetconfSessionPreferences;
107 import org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil;
108 import org.opendaylight.netconf.topology.singleton.impl.utils.ClusteringRpcException;
109 import org.opendaylight.netconf.topology.singleton.impl.utils.NetconfTopologySetup;
110 import org.opendaylight.netconf.topology.singleton.impl.utils.NetconfTopologyUtils;
111 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Host;
112 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpAddress;
113 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Ipv4Address;
114 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.PortNumber;
115 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.keystore.rev171017.Keystore;
116 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.NetconfNode;
117 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.NetconfNodeBuilder;
118 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.NetconfNodeConnectionStatus;
119 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.credentials.credentials.LoginPwUnencryptedBuilder;
120 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.credentials.credentials.login.pw.unencrypted.LoginPasswordUnencryptedBuilder;
121 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.network.topology.topology.topology.types.TopologyNetconf;
122 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.topology.singleton.config.rev170419.Config;
123 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.topology.singleton.config.rev170419.ConfigBuilder;
124 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.list.rev140701.GetTopInput;
125 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.list.rev140701.GetTopOutputBuilder;
126 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.list.rev140701.PutTopInputBuilder;
127 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.list.rev140701.Top;
128 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.list.rev140701.two.level.list.TopLevelList;
129 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.list.rev140701.two.level.list.TopLevelListBuilder;
130 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.list.rev140701.two.level.list.TopLevelListKey;
131 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NetworkTopology;
132 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NodeId;
133 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.Topology;
134 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node;
135 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.NodeBuilder;
136 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.NodeKey;
137 import org.opendaylight.yangtools.rfc8528.data.util.EmptyMountPointContext;
138 import org.opendaylight.yangtools.util.concurrent.FluentFutures;
139 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
140 import org.opendaylight.yangtools.yang.binding.KeyedInstanceIdentifier;
141 import org.opendaylight.yangtools.yang.binding.YangModuleInfo;
142 import org.opendaylight.yangtools.yang.common.ErrorTag;
143 import org.opendaylight.yangtools.yang.common.ErrorType;
144 import org.opendaylight.yangtools.yang.common.QName;
145 import org.opendaylight.yangtools.yang.common.Revision;
146 import org.opendaylight.yangtools.yang.common.RpcError;
147 import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
148 import org.opendaylight.yangtools.yang.common.Uint16;
149 import org.opendaylight.yangtools.yang.common.Uint32;
150 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
151 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
152 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
153 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
154 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
155 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
156 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
157 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
158 import org.opendaylight.yangtools.yang.model.api.Module;
159 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
160 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
161 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
162 import org.opendaylight.yangtools.yang.model.repo.spi.PotentialSchemaSource;
163 import org.opendaylight.yangtools.yang.parser.impl.DefaultYangParserFactory;
164 import org.slf4j.Logger;
165 import org.slf4j.LoggerFactory;
168 * Tests netconf mount points end-to-end.
170 * @author Thomas Pantelis
172 @RunWith(MockitoJUnitRunner.StrictStubs.class)
173 public class MountPointEndToEndTest extends AbstractBaseSchemasTest {
174 private static final Logger LOG = LoggerFactory.getLogger(MountPointEndToEndTest.class);
176 private static final String TOP_MODULE_NAME = "opendaylight-mdsal-list-test";
177 private static final String ACTOR_SYSTEM_NAME = "test";
178 private static final String TOPOLOGY_ID = TopologyNetconf.QNAME.getLocalName();
179 private static final KeyedInstanceIdentifier<Node, NodeKey> NODE_INSTANCE_ID =
180 NetconfTopologyUtils.createTopologyNodeListPath(new NodeKey(new NodeId("node-id")), TOPOLOGY_ID);
182 private static final String TEST_ROOT_DIRECTORY = "test-cache-root";
183 private static final String TEST_DEFAULT_SUBDIR = "test-schema";
185 @Mock private DOMRpcProviderService mockRpcProviderRegistry;
186 @Mock private RpcProviderService mockRpcProviderService;
187 @Mock private DOMActionProviderService mockActionProviderRegistry;
188 @Mock private NetconfClientDispatcher mockClientDispatcher;
189 @Mock private AAAEncryptionService mockEncryptionService;
190 @Mock private ThreadPool mockThreadPool;
191 @Mock private ScheduledThreadPool mockKeepaliveExecutor;
192 @Mock private DeviceActionFactory deviceActionFactory;
194 @Mock private ActorSystemProvider mockMasterActorSystemProvider;
195 @Mock private DOMMountPointListener masterMountPointListener;
196 private final DOMMountPointService masterMountPointService = new DOMMountPointServiceImpl();
197 private final DOMRpcRouter deviceRpcService = new DOMRpcRouter();
198 private DOMClusterSingletonServiceProviderImpl masterClusterSingletonServiceProvider;
199 private DataBroker masterDataBroker;
200 private DOMDataBroker deviceDOMDataBroker;
201 private ActorSystem masterSystem;
202 private NetconfTopologyManager masterNetconfTopologyManager;
203 private volatile SettableFuture<MasterSalFacade> masterSalFacadeFuture = SettableFuture.create();
205 @Mock private ActorSystemProvider mockSlaveActorSystemProvider;
206 @Mock private ClusterSingletonServiceProvider mockSlaveClusterSingletonServiceProvider;
207 @Mock private ClusterSingletonServiceRegistration mockSlaveClusterSingletonServiceReg;
208 @Mock private DOMMountPointListener slaveMountPointListener;
209 private final DOMMountPointService slaveMountPointService = new DOMMountPointServiceImpl();
210 private DataBroker slaveDataBroker;
211 private ActorSystem slaveSystem;
212 private NetconfTopologyManager slaveNetconfTopologyManager;
213 private final SettableFuture<NetconfTopologyContext> slaveNetconfTopologyContextFuture = SettableFuture.create();
214 private TransactionChain slaveTxChain;
216 private final EventExecutor eventExecutor = GlobalEventExecutor.INSTANCE;
217 private final Config config = new ConfigBuilder().setWriteTransactionIdleTimeout(Uint16.ZERO).build();
218 private EffectiveModelContext deviceSchemaContext;
219 private YangModuleInfo topModuleInfo;
220 private QName putTopRpcSchemaPath;
221 private QName getTopRpcSchemaPath;
222 private BindingNormalizedNodeSerializer bindingToNormalized;
223 private YangInstanceIdentifier yangNodeInstanceId;
224 private final TopDOMRpcImplementation topRpcImplementation = new TopDOMRpcImplementation();
225 private final ContainerNode getTopInput = ImmutableNodes.containerNode(GetTopInput.QNAME);
227 private SchemaResourceManager resourceManager;
230 public void setUp() throws Exception {
233 resourceManager = new DefaultSchemaResourceManager(new DefaultYangParserFactory(), TEST_ROOT_DIRECTORY,
234 TEST_DEFAULT_SUBDIR);
236 topModuleInfo = BindingReflections.getModuleInfo(Top.class);
238 deviceSchemaContext = BindingRuntimeHelpers.createEffectiveModel(Top.class);
240 deviceRpcService.onModelContextUpdated(deviceSchemaContext);
242 putTopRpcSchemaPath = findRpcDefinition("put-top").getQName();
243 getTopRpcSchemaPath = findRpcDefinition("get-top").getQName();
245 deviceRpcService.getRpcProviderService().registerRpcImplementation(topRpcImplementation,
246 DOMRpcIdentifier.create(putTopRpcSchemaPath), DOMRpcIdentifier.create(getTopRpcSchemaPath));
252 yangNodeInstanceId = bindingToNormalized.toYangInstanceIdentifier(NODE_INSTANCE_ID);
254 doReturn(mock(ReconnectFuture.class)).when(mockClientDispatcher).createReconnectingClient(any());
256 LOG.info("****** Setup complete");
259 private static void deleteCacheDir() {
260 FileUtils.deleteQuietly(new File(TEST_ROOT_DIRECTORY));
264 public void tearDown() throws Exception {
266 TestKit.shutdownActorSystem(slaveSystem, true);
267 TestKit.shutdownActorSystem(masterSystem, true);
270 private void setupMaster() throws Exception {
271 AbstractConcurrentDataBrokerTest dataBrokerTest = newDataBrokerTest();
272 masterDataBroker = dataBrokerTest.getDataBroker();
273 deviceDOMDataBroker = dataBrokerTest.getDomBroker();
274 bindingToNormalized = dataBrokerTest.getDataBrokerTestCustomizer().getAdapterContext().currentSerializer();
276 masterSystem = ActorSystem.create(ACTOR_SYSTEM_NAME, ConfigFactory.load().getConfig("Master"));
278 masterClusterSingletonServiceProvider = new DOMClusterSingletonServiceProviderImpl();
279 masterClusterSingletonServiceProvider.initializeProvider();
281 doReturn(masterSystem).when(mockMasterActorSystemProvider).getActorSystem();
283 doReturn(MoreExecutors.newDirectExecutorService()).when(mockThreadPool).getExecutor();
285 final SchemaResourcesDTO resources = resourceManager.getSchemaResources(
286 new NetconfNodeBuilder().setSchemaCacheDirectory(TEST_DEFAULT_SUBDIR).build(), "test");
287 resources.getSchemaRegistry().registerSchemaSource(
288 id -> Futures.immediateFuture(YangTextSchemaSource.delegateForByteSource(id,
289 topModuleInfo.getYangTextByteSource())),
290 PotentialSchemaSource.create(new SourceIdentifier(TOP_MODULE_NAME,
291 topModuleInfo.getName().getRevision().map(Revision::toString).orElse(null)),
292 YangTextSchemaSource.class, 1));
294 masterNetconfTopologyManager = new NetconfTopologyManager(BASE_SCHEMAS, masterDataBroker,
295 mockRpcProviderRegistry, mockActionProviderRegistry, masterClusterSingletonServiceProvider,
296 mockKeepaliveExecutor, mockThreadPool, mockMasterActorSystemProvider, eventExecutor,
297 mockClientDispatcher, TOPOLOGY_ID, config, masterMountPointService, mockEncryptionService,
298 mockRpcProviderService, deviceActionFactory, resourceManager) {
300 protected NetconfTopologyContext newNetconfTopologyContext(final NetconfTopologySetup setup,
301 final ServiceGroupIdentifier serviceGroupIdent, final Timeout actorResponseWaitTime,
302 final DeviceActionFactory deviceActionFact) {
303 NetconfTopologyContext context =
304 super.newNetconfTopologyContext(setup, serviceGroupIdent, actorResponseWaitTime, deviceActionFact);
306 NetconfTopologyContext spiedContext = spy(context);
307 doAnswer(invocation -> {
308 final MasterSalFacade spiedFacade = (MasterSalFacade) spy(invocation.callRealMethod());
309 doReturn(deviceDOMDataBroker).when(spiedFacade).newDeviceDataBroker();
310 masterSalFacadeFuture.set(spiedFacade);
312 }).when(spiedContext).newMasterSalFacade();
318 masterNetconfTopologyManager.init();
320 verifyTopologyNodesCreated(masterDataBroker);
323 private void setupSlave() throws Exception {
324 AbstractConcurrentDataBrokerTest dataBrokerTest = newDataBrokerTest();
325 slaveDataBroker = dataBrokerTest.getDataBroker();
327 slaveSystem = ActorSystem.create(ACTOR_SYSTEM_NAME, ConfigFactory.load().getConfig("Slave"));
329 doReturn(slaveSystem).when(mockSlaveActorSystemProvider).getActorSystem();
331 doReturn(mockSlaveClusterSingletonServiceReg).when(mockSlaveClusterSingletonServiceProvider)
332 .registerClusterSingletonService(any());
334 slaveNetconfTopologyManager = new NetconfTopologyManager(BASE_SCHEMAS, slaveDataBroker, mockRpcProviderRegistry,
335 mockActionProviderRegistry, mockSlaveClusterSingletonServiceProvider, mockKeepaliveExecutor, mockThreadPool,
336 mockSlaveActorSystemProvider, eventExecutor, mockClientDispatcher, TOPOLOGY_ID, config,
337 slaveMountPointService, mockEncryptionService, mockRpcProviderService, deviceActionFactory,
340 protected NetconfTopologyContext newNetconfTopologyContext(final NetconfTopologySetup setup,
341 final ServiceGroupIdentifier serviceGroupIdent, final Timeout actorResponseWaitTime,
342 final DeviceActionFactory actionFactory) {
343 NetconfTopologyContext spiedContext = spy(super.newNetconfTopologyContext(setup, serviceGroupIdent,
344 actorResponseWaitTime, actionFactory));
346 slaveNetconfTopologyContextFuture.set(spiedContext);
351 slaveNetconfTopologyManager.init();
353 verifyTopologyNodesCreated(slaveDataBroker);
355 slaveTxChain = slaveDataBroker.createTransactionChain(new TransactionChainListener() {
357 public void onTransactionChainSuccessful(final TransactionChain chain) {
361 public void onTransactionChainFailed(final TransactionChain chain, final Transaction transaction,
362 final Throwable cause) {
363 LOG.error("Slave transaction chain failed", cause);
369 public void test() throws Exception {
374 final MasterSalFacade masterSalFacade = testMasterNodeUpdated();
376 testMasterDisconnected(masterSalFacade);
381 private MasterSalFacade testMaster() throws InterruptedException, ExecutionException, TimeoutException {
382 LOG.info("****** Testing master");
384 writeNetconfNode(TEST_DEFAULT_SUBDIR, masterDataBroker);
386 final MasterSalFacade masterSalFacade = masterSalFacadeFuture.get(5, TimeUnit.SECONDS);
387 final ArrayList<String> capabilities = Lists.newArrayList(
388 NetconfMessageTransformUtil.NETCONF_CANDIDATE_URI.toString());
390 masterSalFacade.onDeviceConnected(new EmptyMountPointContext(deviceSchemaContext),
391 NetconfSessionPreferences.fromStrings(capabilities), deviceRpcService.getRpcService());
393 DOMMountPoint masterMountPoint = awaitMountPoint(masterMountPointService);
395 LOG.info("****** Testing master DOMDataBroker operations");
397 testDOMDataBrokerOperations(getDOMDataBroker(masterMountPoint));
399 LOG.info("****** Testing master DOMRpcService");
401 testDOMRpcService(getDOMRpcService(masterMountPoint));
402 return masterSalFacade;
405 private void testSlave() throws InterruptedException, ExecutionException, TimeoutException {
406 LOG.info("****** Testing slave");
408 writeNetconfNode("slave", slaveDataBroker);
410 verify(mockSlaveClusterSingletonServiceProvider, timeout(5000)).registerClusterSingletonService(any());
412 // Since the master and slave use separate DataBrokers we need to copy the master's oper node to the slave.
413 // This is essentially what happens in a clustered environment but we'll use a DTCL here.
415 masterDataBroker.registerDataTreeChangeListener(
416 DataTreeIdentifier.create(LogicalDatastoreType.OPERATIONAL, NODE_INSTANCE_ID), changes -> {
417 final WriteTransaction slaveTx = slaveTxChain.newWriteOnlyTransaction();
418 for (DataTreeModification<Node> dataTreeModification : changes) {
419 DataObjectModification<Node> rootNode = dataTreeModification.getRootNode();
420 InstanceIdentifier<Node> path = dataTreeModification.getRootPath().getRootIdentifier();
421 switch (rootNode.getModificationType()) {
423 case SUBTREE_MODIFIED:
424 slaveTx.merge(LogicalDatastoreType.OPERATIONAL, path, rootNode.getDataAfter());
427 slaveTx.delete(LogicalDatastoreType.OPERATIONAL, path);
437 DOMMountPoint slaveMountPoint = awaitMountPoint(slaveMountPointService);
439 final NetconfTopologyContext slaveNetconfTopologyContext =
440 slaveNetconfTopologyContextFuture.get(5, TimeUnit.SECONDS);
441 verify(slaveNetconfTopologyContext, never()).newMasterSalFacade();
443 LOG.info("****** Testing slave DOMDataBroker operations");
445 testDOMDataBrokerOperations(getDOMDataBroker(slaveMountPoint));
447 LOG.info("****** Testing slave DOMRpcService");
449 testDOMRpcService(getDOMRpcService(slaveMountPoint));
452 private MasterSalFacade testMasterNodeUpdated() throws InterruptedException, ExecutionException, TimeoutException {
453 LOG.info("****** Testing update master node");
455 masterMountPointService.registerProvisionListener(masterMountPointListener);
456 slaveMountPointService.registerProvisionListener(slaveMountPointListener);
458 masterSalFacadeFuture = SettableFuture.create();
459 writeNetconfNode(TEST_DEFAULT_SUBDIR, masterDataBroker);
461 verify(masterMountPointListener, timeout(5000)).onMountPointRemoved(yangNodeInstanceId);
463 MasterSalFacade masterSalFacade = masterSalFacadeFuture.get(5, TimeUnit.SECONDS);
464 final ArrayList<String> capabilities = Lists.newArrayList(
465 NetconfMessageTransformUtil.NETCONF_CANDIDATE_URI.toString());
467 masterSalFacade.onDeviceConnected(new EmptyMountPointContext(deviceSchemaContext),
468 NetconfSessionPreferences.fromStrings(capabilities), deviceRpcService.getRpcService());
470 verify(masterMountPointListener, timeout(5000)).onMountPointCreated(yangNodeInstanceId);
472 verify(slaveMountPointListener, timeout(5000)).onMountPointRemoved(yangNodeInstanceId);
473 verify(slaveMountPointListener, timeout(5000)).onMountPointCreated(yangNodeInstanceId);
475 return masterSalFacade;
478 private void testMasterDisconnected(final MasterSalFacade masterSalFacade)
479 throws InterruptedException, ExecutionException, TimeoutException {
480 LOG.info("****** Testing master disconnected");
482 masterSalFacade.onDeviceDisconnected();
484 awaitMountPointNotPresent(masterMountPointService);
486 await().atMost(5, TimeUnit.SECONDS).until(() -> {
487 try (ReadTransaction readTx = masterDataBroker.newReadOnlyTransaction()) {
488 Optional<Node> node = readTx.read(LogicalDatastoreType.OPERATIONAL,
489 NODE_INSTANCE_ID).get(5, TimeUnit.SECONDS);
490 assertTrue(node.isPresent());
491 final NetconfNode netconfNode = node.get().augmentation(NetconfNode.class);
492 return netconfNode.getConnectionStatus() != NetconfNodeConnectionStatus.ConnectionStatus.Connected;
496 awaitMountPointNotPresent(slaveMountPointService);
499 private void testCleanup() throws Exception {
500 LOG.info("****** Testing cleanup");
502 slaveNetconfTopologyManager.close();
503 verify(mockSlaveClusterSingletonServiceReg).close();
506 private void testDOMRpcService(final DOMRpcService domRpcService)
507 throws InterruptedException, ExecutionException, TimeoutException {
508 testPutTopRpc(domRpcService, new DefaultDOMRpcResult((NormalizedNode)null));
509 testPutTopRpc(domRpcService, null);
510 testPutTopRpc(domRpcService, new DefaultDOMRpcResult(ImmutableList.of(
511 RpcResultBuilder.newError(ErrorType.APPLICATION, new ErrorTag("tag1"), "error1"),
512 RpcResultBuilder.newError(ErrorType.APPLICATION, new ErrorTag("tag2"), "error2"))));
514 testGetTopRpc(domRpcService, new DefaultDOMRpcResult(bindingToNormalized.toNormalizedNodeRpcData(
515 new GetTopOutputBuilder().setTopLevelList(oneTopLevelList()).build())));
517 testFailedRpc(domRpcService, getTopRpcSchemaPath, getTopInput);
520 private void testPutTopRpc(final DOMRpcService domRpcService, final DOMRpcResult result)
521 throws InterruptedException, ExecutionException, TimeoutException {
522 ContainerNode putTopInput = bindingToNormalized.toNormalizedNodeRpcData(
523 new PutTopInputBuilder().setTopLevelList(oneTopLevelList()).build());
524 testRpc(domRpcService, putTopRpcSchemaPath, putTopInput, result);
527 private static Map<TopLevelListKey, TopLevelList> oneTopLevelList() {
528 final TopLevelListKey key = new TopLevelListKey("one");
529 return ImmutableMap.of(key, new TopLevelListBuilder().withKey(key).build());
532 private void testGetTopRpc(final DOMRpcService domRpcService, final DOMRpcResult result)
533 throws InterruptedException, ExecutionException, TimeoutException {
534 testRpc(domRpcService, getTopRpcSchemaPath, getTopInput, result);
537 private void testRpc(final DOMRpcService domRpcService, final QName qname, final NormalizedNode input,
538 final DOMRpcResult result) throws InterruptedException, ExecutionException, TimeoutException {
539 final FluentFuture<DOMRpcResult> future = result == null ? FluentFutures.immediateNullFluentFuture()
540 : FluentFutures.immediateFluentFuture(result);
541 final DOMRpcResult actual = invokeRpc(domRpcService, qname, input, future);
542 if (result == null) {
547 assertNotNull(actual);
548 assertEquals(result.getResult(), actual.getResult());
550 assertEquals(result.getErrors().size(), actual.getErrors().size());
551 Iterator<? extends RpcError> iter1 = result.getErrors().iterator();
552 Iterator<? extends RpcError> iter2 = actual.getErrors().iterator();
553 while (iter1.hasNext() && iter2.hasNext()) {
554 RpcError err1 = iter1.next();
555 RpcError err2 = iter2.next();
556 assertEquals(err1.getErrorType(), err2.getErrorType());
557 assertEquals(err1.getTag(), err2.getTag());
558 assertEquals(err1.getMessage(), err2.getMessage());
559 assertEquals(err1.getSeverity(), err2.getSeverity());
560 assertEquals(err1.getApplicationTag(), err2.getApplicationTag());
561 assertEquals(err1.getInfo(), err2.getInfo());
565 private void testFailedRpc(final DOMRpcService domRpcService, final QName qname, final NormalizedNode input)
566 throws InterruptedException, TimeoutException {
568 invokeRpc(domRpcService, qname, input, FluentFutures.immediateFailedFluentFuture(
569 new ClusteringRpcException("mock")));
570 fail("Expected exception");
571 } catch (ExecutionException e) {
572 assertTrue(e.getCause() instanceof ClusteringRpcException);
573 assertEquals("mock", e.getCause().getMessage());
577 private DOMRpcResult invokeRpc(final DOMRpcService domRpcService, final QName qname, final NormalizedNode input,
578 final FluentFuture<DOMRpcResult> returnFuture)
579 throws InterruptedException, ExecutionException, TimeoutException {
580 topRpcImplementation.init(returnFuture);
581 final ListenableFuture<? extends DOMRpcResult> resultFuture = domRpcService.invokeRpc(qname, input);
583 topRpcImplementation.verify(DOMRpcIdentifier.create(qname), input);
585 return resultFuture.get(5, TimeUnit.SECONDS);
588 private static void testDOMDataBrokerOperations(final DOMDataBroker dataBroker)
589 throws InterruptedException, ExecutionException, TimeoutException {
591 DOMDataTreeWriteTransaction writeTx = dataBroker.newWriteOnlyTransaction();
593 final ContainerNode topNode = Builders.containerBuilder()
594 .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(Top.QNAME)).build();
595 final YangInstanceIdentifier topPath = YangInstanceIdentifier.of(Top.QNAME);
596 writeTx.put(LogicalDatastoreType.CONFIGURATION, topPath, topNode);
598 final QName name = QName.create(TopLevelList.QNAME, "name");
599 final YangInstanceIdentifier listPath = YangInstanceIdentifier.builder(topPath)
600 .node(TopLevelList.QNAME).build();
601 final MapEntryNode listEntryNode = ImmutableNodes.mapEntry(TopLevelList.QNAME, name, "one");
602 final MapNode listNode = ImmutableNodes.mapNodeBuilder(TopLevelList.QNAME).addChild(listEntryNode).build();
603 writeTx.merge(LogicalDatastoreType.CONFIGURATION, listPath, listNode);
604 writeTx.commit().get(5, TimeUnit.SECONDS);
606 verifyDataInStore(dataBroker.newReadWriteTransaction(), YangInstanceIdentifier.builder(listPath)
607 .nodeWithKey(TopLevelList.QNAME, name, "one").build(), listEntryNode);
609 writeTx = dataBroker.newWriteOnlyTransaction();
610 writeTx.delete(LogicalDatastoreType.CONFIGURATION, topPath);
611 writeTx.commit().get(5, TimeUnit.SECONDS);
613 DOMDataTreeReadWriteTransaction readTx = dataBroker.newReadWriteTransaction();
614 assertFalse(readTx.exists(LogicalDatastoreType.CONFIGURATION, topPath).get(5, TimeUnit.SECONDS));
615 assertTrue(readTx.cancel());
618 private static void writeNetconfNode(final String cacheDir, final DataBroker databroker)
619 throws InterruptedException, ExecutionException, TimeoutException {
620 final Node node = new NodeBuilder()
621 .withKey(NODE_INSTANCE_ID.getKey())
622 .addAugmentation(new NetconfNodeBuilder()
623 .setHost(new Host(new IpAddress(new Ipv4Address("127.0.0.1"))))
624 .setPort(new PortNumber(Uint16.valueOf(1234)))
625 .setActorResponseWaitTime(Uint16.valueOf(10))
626 .setTcpOnly(Boolean.TRUE)
627 .setSchemaless(Boolean.FALSE)
628 .setKeepaliveDelay(Uint32.ZERO)
629 .setConnectionTimeoutMillis(Uint32.valueOf(5000))
630 .setDefaultRequestTimeoutMillis(Uint32.valueOf(5000))
631 .setMaxConnectionAttempts(Uint32.ONE)
632 .setCredentials(new LoginPwUnencryptedBuilder()
633 .setLoginPasswordUnencrypted(new LoginPasswordUnencryptedBuilder()
638 .setSchemaCacheDirectory(cacheDir)
642 final WriteTransaction writeTx = databroker.newWriteOnlyTransaction();
643 writeTx.put(LogicalDatastoreType.CONFIGURATION, NODE_INSTANCE_ID, node);
644 writeTx.commit().get(5, TimeUnit.SECONDS);
647 private static void verifyDataInStore(final DOMDataTreeReadOperations readTx, final YangInstanceIdentifier path,
648 final NormalizedNode expNode) throws InterruptedException, ExecutionException, TimeoutException {
649 final Optional<NormalizedNode> read = readTx.read(LogicalDatastoreType.CONFIGURATION, path)
650 .get(5, TimeUnit.SECONDS);
651 assertTrue(read.isPresent());
652 assertEquals(expNode, read.get());
654 final Boolean exists = readTx.exists(LogicalDatastoreType.CONFIGURATION, path).get(5, TimeUnit.SECONDS);
658 private static void verifyTopologyNodesCreated(final DataBroker dataBroker) {
659 await().atMost(5, TimeUnit.SECONDS).until(() -> {
660 try (ReadTransaction readTx = dataBroker.newReadOnlyTransaction()) {
661 Optional<Topology> configTopology = readTx.read(LogicalDatastoreType.CONFIGURATION,
662 NetconfTopologyUtils.createTopologyListPath(TOPOLOGY_ID)).get(3, TimeUnit.SECONDS);
663 Optional<Topology> operTopology = readTx.read(LogicalDatastoreType.OPERATIONAL,
664 NetconfTopologyUtils.createTopologyListPath(TOPOLOGY_ID)).get(3, TimeUnit.SECONDS);
665 return configTopology.isPresent() && operTopology.isPresent();
670 private AbstractConcurrentDataBrokerTest newDataBrokerTest() throws Exception {
671 AbstractConcurrentDataBrokerTest dataBrokerTest = new AbstractConcurrentDataBrokerTest(true) {
673 protected Set<YangModuleInfo> getModuleInfos() throws Exception {
674 return ImmutableSet.of(BindingReflections.getModuleInfo(NetconfNode.class),
675 BindingReflections.getModuleInfo(NetworkTopology.class),
676 BindingReflections.getModuleInfo(Topology.class),
677 BindingReflections.getModuleInfo(Keystore.class),
682 dataBrokerTest.setup();
683 return dataBrokerTest;
686 private void awaitMountPointNotPresent(final DOMMountPointService mountPointService) {
687 await().atMost(5, TimeUnit.SECONDS).until(
688 () -> mountPointService.getMountPoint(yangNodeInstanceId).isEmpty());
691 private static DOMDataBroker getDOMDataBroker(final DOMMountPoint mountPoint) {
692 return getMountPointService(mountPoint, DOMDataBroker.class);
695 private static DOMRpcService getDOMRpcService(final DOMMountPoint mountPoint) {
696 return getMountPointService(mountPoint, DOMRpcService.class);
699 private static DOMActionService getDomActionService(final DOMMountPoint mountPoint) {
700 return getMountPointService(mountPoint, DOMActionService.class);
703 private static <T extends DOMService> T getMountPointService(final DOMMountPoint mountPoint,
704 final Class<T> serviceClass) {
705 final Optional<T> maybeService = mountPoint.getService(serviceClass);
706 assertTrue(maybeService.isPresent());
707 return maybeService.get();
710 private DOMMountPoint awaitMountPoint(final DOMMountPointService mountPointService) {
711 await().atMost(5, TimeUnit.SECONDS).until(() ->
712 mountPointService.getMountPoint(yangNodeInstanceId).isPresent());
714 return mountPointService.getMountPoint(yangNodeInstanceId).get();
717 private RpcDefinition findRpcDefinition(final String rpc) {
718 Module topModule = deviceSchemaContext.findModule(TOP_MODULE_NAME, topModuleInfo.getName().getRevision()).get();
719 RpcDefinition rpcDefinition = null;
720 for (RpcDefinition def: topModule.getRpcs()) {
721 if (def.getQName().getLocalName().equals(rpc)) {
727 assertNotNull(rpc + " rpc not found in " + topModule.getRpcs(), rpcDefinition);
728 return rpcDefinition;
731 private static class TopDOMRpcImplementation implements DOMRpcImplementation {
732 private volatile SettableFuture<Entry<DOMRpcIdentifier, NormalizedNode>> rpcInvokedFuture;
733 private volatile FluentFuture<DOMRpcResult> returnFuture;
736 public FluentFuture<DOMRpcResult> invokeRpc(final DOMRpcIdentifier rpc, final NormalizedNode input) {
737 rpcInvokedFuture.set(new SimpleEntry<>(rpc, input));
741 void init(final FluentFuture<DOMRpcResult> retFuture) {
742 returnFuture = retFuture;
743 rpcInvokedFuture = SettableFuture.create();
746 void verify(final DOMRpcIdentifier expRpc, final NormalizedNode expInput)
747 throws InterruptedException, ExecutionException, TimeoutException {
748 final Entry<DOMRpcIdentifier, NormalizedNode> actual = rpcInvokedFuture.get(5, TimeUnit.SECONDS);
749 assertEquals(expRpc, actual.getKey());
750 assertEquals(expInput, actual.getValue());