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.RpcError;
146 import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
147 import org.opendaylight.yangtools.yang.common.Uint16;
148 import org.opendaylight.yangtools.yang.common.Uint32;
149 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
150 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
151 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
152 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
153 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
154 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
155 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
156 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
157 import org.opendaylight.yangtools.yang.model.api.Module;
158 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
159 import org.opendaylight.yangtools.yang.model.repo.api.RevisionSourceIdentifier;
160 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
161 import org.opendaylight.yangtools.yang.model.repo.spi.PotentialSchemaSource;
162 import org.opendaylight.yangtools.yang.parser.impl.DefaultYangParserFactory;
163 import org.slf4j.Logger;
164 import org.slf4j.LoggerFactory;
167 * Tests netconf mount points end-to-end.
169 * @author Thomas Pantelis
171 @RunWith(MockitoJUnitRunner.StrictStubs.class)
172 public class MountPointEndToEndTest extends AbstractBaseSchemasTest {
173 private static final Logger LOG = LoggerFactory.getLogger(MountPointEndToEndTest.class);
175 private static final String TOP_MODULE_NAME = "opendaylight-mdsal-list-test";
176 private static final String ACTOR_SYSTEM_NAME = "test";
177 private static final String TOPOLOGY_ID = TopologyNetconf.QNAME.getLocalName();
178 private static final KeyedInstanceIdentifier<Node, NodeKey> NODE_INSTANCE_ID =
179 NetconfTopologyUtils.createTopologyNodeListPath(new NodeKey(new NodeId("node-id")), TOPOLOGY_ID);
181 private static final String TEST_ROOT_DIRECTORY = "test-cache-root";
182 private static final String TEST_DEFAULT_SUBDIR = "test-schema";
184 @Mock private DOMRpcProviderService mockRpcProviderRegistry;
185 @Mock private RpcProviderService mockRpcProviderService;
186 @Mock private DOMActionProviderService mockActionProviderRegistry;
187 @Mock private NetconfClientDispatcher mockClientDispatcher;
188 @Mock private AAAEncryptionService mockEncryptionService;
189 @Mock private ThreadPool mockThreadPool;
190 @Mock private ScheduledThreadPool mockKeepaliveExecutor;
191 @Mock private DeviceActionFactory deviceActionFactory;
193 @Mock private ActorSystemProvider mockMasterActorSystemProvider;
194 @Mock private DOMMountPointListener masterMountPointListener;
195 private final DOMMountPointService masterMountPointService = new DOMMountPointServiceImpl();
196 private final DOMRpcRouter deviceRpcService = new DOMRpcRouter();
197 private DOMClusterSingletonServiceProviderImpl masterClusterSingletonServiceProvider;
198 private DataBroker masterDataBroker;
199 private DOMDataBroker deviceDOMDataBroker;
200 private ActorSystem masterSystem;
201 private NetconfTopologyManager masterNetconfTopologyManager;
202 private volatile SettableFuture<MasterSalFacade> masterSalFacadeFuture = SettableFuture.create();
204 @Mock private ActorSystemProvider mockSlaveActorSystemProvider;
205 @Mock private ClusterSingletonServiceProvider mockSlaveClusterSingletonServiceProvider;
206 @Mock private ClusterSingletonServiceRegistration mockSlaveClusterSingletonServiceReg;
207 @Mock private DOMMountPointListener slaveMountPointListener;
208 private final DOMMountPointService slaveMountPointService = new DOMMountPointServiceImpl();
209 private DataBroker slaveDataBroker;
210 private ActorSystem slaveSystem;
211 private NetconfTopologyManager slaveNetconfTopologyManager;
212 private final SettableFuture<NetconfTopologyContext> slaveNetconfTopologyContextFuture = SettableFuture.create();
213 private TransactionChain slaveTxChain;
215 private final EventExecutor eventExecutor = GlobalEventExecutor.INSTANCE;
216 private final Config config = new ConfigBuilder().setWriteTransactionIdleTimeout(Uint16.ZERO).build();
217 private EffectiveModelContext deviceSchemaContext;
218 private YangModuleInfo topModuleInfo;
219 private QName putTopRpcSchemaPath;
220 private QName getTopRpcSchemaPath;
221 private BindingNormalizedNodeSerializer bindingToNormalized;
222 private YangInstanceIdentifier yangNodeInstanceId;
223 private final TopDOMRpcImplementation topRpcImplementation = new TopDOMRpcImplementation();
224 private final ContainerNode getTopInput = ImmutableNodes.containerNode(GetTopInput.QNAME);
226 private SchemaResourceManager resourceManager;
229 public void setUp() throws Exception {
232 resourceManager = new DefaultSchemaResourceManager(new DefaultYangParserFactory(), TEST_ROOT_DIRECTORY,
233 TEST_DEFAULT_SUBDIR);
235 topModuleInfo = BindingReflections.getModuleInfo(Top.class);
237 deviceSchemaContext = BindingRuntimeHelpers.createEffectiveModel(Top.class);
239 deviceRpcService.onModelContextUpdated(deviceSchemaContext);
241 putTopRpcSchemaPath = findRpcDefinition("put-top").getQName();
242 getTopRpcSchemaPath = findRpcDefinition("get-top").getQName();
244 deviceRpcService.getRpcProviderService().registerRpcImplementation(topRpcImplementation,
245 DOMRpcIdentifier.create(putTopRpcSchemaPath), DOMRpcIdentifier.create(getTopRpcSchemaPath));
251 yangNodeInstanceId = bindingToNormalized.toYangInstanceIdentifier(NODE_INSTANCE_ID);
253 doReturn(mock(ReconnectFuture.class)).when(mockClientDispatcher).createReconnectingClient(any());
255 LOG.info("****** Setup complete");
258 private static void deleteCacheDir() {
259 FileUtils.deleteQuietly(new File(TEST_ROOT_DIRECTORY));
263 public void tearDown() throws Exception {
265 TestKit.shutdownActorSystem(slaveSystem, true);
266 TestKit.shutdownActorSystem(masterSystem, true);
269 private void setupMaster() throws Exception {
270 AbstractConcurrentDataBrokerTest dataBrokerTest = newDataBrokerTest();
271 masterDataBroker = dataBrokerTest.getDataBroker();
272 deviceDOMDataBroker = dataBrokerTest.getDomBroker();
273 bindingToNormalized = dataBrokerTest.getDataBrokerTestCustomizer().getAdapterContext().currentSerializer();
275 masterSystem = ActorSystem.create(ACTOR_SYSTEM_NAME, ConfigFactory.load().getConfig("Master"));
277 masterClusterSingletonServiceProvider = new DOMClusterSingletonServiceProviderImpl();
278 masterClusterSingletonServiceProvider.initializeProvider();
280 doReturn(masterSystem).when(mockMasterActorSystemProvider).getActorSystem();
282 doReturn(MoreExecutors.newDirectExecutorService()).when(mockThreadPool).getExecutor();
284 final SchemaResourcesDTO resources = resourceManager.getSchemaResources(
285 new NetconfNodeBuilder().setSchemaCacheDirectory(TEST_DEFAULT_SUBDIR).build(), "test");
286 resources.getSchemaRegistry().registerSchemaSource(
287 id -> Futures.immediateFuture(YangTextSchemaSource.delegateForByteSource(id,
288 topModuleInfo.getYangTextByteSource())),
289 PotentialSchemaSource.create(RevisionSourceIdentifier.create(TOP_MODULE_NAME,
290 topModuleInfo.getName().getRevision()), YangTextSchemaSource.class, 1));
292 masterNetconfTopologyManager = new NetconfTopologyManager(BASE_SCHEMAS, masterDataBroker,
293 mockRpcProviderRegistry, mockActionProviderRegistry, masterClusterSingletonServiceProvider,
294 mockKeepaliveExecutor, mockThreadPool, mockMasterActorSystemProvider, eventExecutor,
295 mockClientDispatcher, TOPOLOGY_ID, config, masterMountPointService, mockEncryptionService,
296 mockRpcProviderService, deviceActionFactory, resourceManager) {
298 protected NetconfTopologyContext newNetconfTopologyContext(final NetconfTopologySetup setup,
299 final ServiceGroupIdentifier serviceGroupIdent, final Timeout actorResponseWaitTime,
300 final DeviceActionFactory deviceActionFact) {
301 NetconfTopologyContext context =
302 super.newNetconfTopologyContext(setup, serviceGroupIdent, actorResponseWaitTime, deviceActionFact);
304 NetconfTopologyContext spiedContext = spy(context);
305 doAnswer(invocation -> {
306 final MasterSalFacade spiedFacade = (MasterSalFacade) spy(invocation.callRealMethod());
307 doReturn(deviceDOMDataBroker).when(spiedFacade).newDeviceDataBroker();
308 masterSalFacadeFuture.set(spiedFacade);
310 }).when(spiedContext).newMasterSalFacade();
316 masterNetconfTopologyManager.init();
318 verifyTopologyNodesCreated(masterDataBroker);
321 private void setupSlave() throws Exception {
322 AbstractConcurrentDataBrokerTest dataBrokerTest = newDataBrokerTest();
323 slaveDataBroker = dataBrokerTest.getDataBroker();
325 slaveSystem = ActorSystem.create(ACTOR_SYSTEM_NAME, ConfigFactory.load().getConfig("Slave"));
327 doReturn(slaveSystem).when(mockSlaveActorSystemProvider).getActorSystem();
329 doReturn(mockSlaveClusterSingletonServiceReg).when(mockSlaveClusterSingletonServiceProvider)
330 .registerClusterSingletonService(any());
332 slaveNetconfTopologyManager = new NetconfTopologyManager(BASE_SCHEMAS, slaveDataBroker, mockRpcProviderRegistry,
333 mockActionProviderRegistry, mockSlaveClusterSingletonServiceProvider, mockKeepaliveExecutor, mockThreadPool,
334 mockSlaveActorSystemProvider, eventExecutor, mockClientDispatcher, TOPOLOGY_ID, config,
335 slaveMountPointService, mockEncryptionService, mockRpcProviderService, deviceActionFactory,
338 protected NetconfTopologyContext newNetconfTopologyContext(final NetconfTopologySetup setup,
339 final ServiceGroupIdentifier serviceGroupIdent, final Timeout actorResponseWaitTime,
340 final DeviceActionFactory actionFactory) {
341 NetconfTopologyContext spiedContext = spy(super.newNetconfTopologyContext(setup, serviceGroupIdent,
342 actorResponseWaitTime, actionFactory));
344 slaveNetconfTopologyContextFuture.set(spiedContext);
349 slaveNetconfTopologyManager.init();
351 verifyTopologyNodesCreated(slaveDataBroker);
353 slaveTxChain = slaveDataBroker.createTransactionChain(new TransactionChainListener() {
355 public void onTransactionChainSuccessful(final TransactionChain chain) {
359 public void onTransactionChainFailed(final TransactionChain chain, final Transaction transaction,
360 final Throwable cause) {
361 LOG.error("Slave transaction chain failed", cause);
367 public void test() throws Exception {
372 final MasterSalFacade masterSalFacade = testMasterNodeUpdated();
374 testMasterDisconnected(masterSalFacade);
379 private MasterSalFacade testMaster() throws InterruptedException, ExecutionException, TimeoutException {
380 LOG.info("****** Testing master");
382 writeNetconfNode(TEST_DEFAULT_SUBDIR, masterDataBroker);
384 final MasterSalFacade masterSalFacade = masterSalFacadeFuture.get(5, TimeUnit.SECONDS);
385 final ArrayList<String> capabilities = Lists.newArrayList(
386 NetconfMessageTransformUtil.NETCONF_CANDIDATE_URI.toString());
388 masterSalFacade.onDeviceConnected(new EmptyMountPointContext(deviceSchemaContext),
389 NetconfSessionPreferences.fromStrings(capabilities), deviceRpcService.getRpcService());
391 DOMMountPoint masterMountPoint = awaitMountPoint(masterMountPointService);
393 LOG.info("****** Testing master DOMDataBroker operations");
395 testDOMDataBrokerOperations(getDOMDataBroker(masterMountPoint));
397 LOG.info("****** Testing master DOMRpcService");
399 testDOMRpcService(getDOMRpcService(masterMountPoint));
400 return masterSalFacade;
403 private void testSlave() throws InterruptedException, ExecutionException, TimeoutException {
404 LOG.info("****** Testing slave");
406 writeNetconfNode("slave", slaveDataBroker);
408 verify(mockSlaveClusterSingletonServiceProvider, timeout(5000)).registerClusterSingletonService(any());
410 // Since the master and slave use separate DataBrokers we need to copy the master's oper node to the slave.
411 // This is essentially what happens in a clustered environment but we'll use a DTCL here.
413 masterDataBroker.registerDataTreeChangeListener(
414 DataTreeIdentifier.create(LogicalDatastoreType.OPERATIONAL, NODE_INSTANCE_ID), changes -> {
415 final WriteTransaction slaveTx = slaveTxChain.newWriteOnlyTransaction();
416 for (DataTreeModification<Node> dataTreeModification : changes) {
417 DataObjectModification<Node> rootNode = dataTreeModification.getRootNode();
418 InstanceIdentifier<Node> path = dataTreeModification.getRootPath().getRootIdentifier();
419 switch (rootNode.getModificationType()) {
421 case SUBTREE_MODIFIED:
422 slaveTx.merge(LogicalDatastoreType.OPERATIONAL, path, rootNode.getDataAfter());
425 slaveTx.delete(LogicalDatastoreType.OPERATIONAL, path);
435 DOMMountPoint slaveMountPoint = awaitMountPoint(slaveMountPointService);
437 final NetconfTopologyContext slaveNetconfTopologyContext =
438 slaveNetconfTopologyContextFuture.get(5, TimeUnit.SECONDS);
439 verify(slaveNetconfTopologyContext, never()).newMasterSalFacade();
441 LOG.info("****** Testing slave DOMDataBroker operations");
443 testDOMDataBrokerOperations(getDOMDataBroker(slaveMountPoint));
445 LOG.info("****** Testing slave DOMRpcService");
447 testDOMRpcService(getDOMRpcService(slaveMountPoint));
450 private MasterSalFacade testMasterNodeUpdated() throws InterruptedException, ExecutionException, TimeoutException {
451 LOG.info("****** Testing update master node");
453 masterMountPointService.registerProvisionListener(masterMountPointListener);
454 slaveMountPointService.registerProvisionListener(slaveMountPointListener);
456 masterSalFacadeFuture = SettableFuture.create();
457 writeNetconfNode(TEST_DEFAULT_SUBDIR, masterDataBroker);
459 verify(masterMountPointListener, timeout(5000)).onMountPointRemoved(yangNodeInstanceId);
461 MasterSalFacade masterSalFacade = masterSalFacadeFuture.get(5, TimeUnit.SECONDS);
462 final ArrayList<String> capabilities = Lists.newArrayList(
463 NetconfMessageTransformUtil.NETCONF_CANDIDATE_URI.toString());
465 masterSalFacade.onDeviceConnected(new EmptyMountPointContext(deviceSchemaContext),
466 NetconfSessionPreferences.fromStrings(capabilities), deviceRpcService.getRpcService());
468 verify(masterMountPointListener, timeout(5000)).onMountPointCreated(yangNodeInstanceId);
470 verify(slaveMountPointListener, timeout(5000)).onMountPointRemoved(yangNodeInstanceId);
471 verify(slaveMountPointListener, timeout(5000)).onMountPointCreated(yangNodeInstanceId);
473 return masterSalFacade;
476 private void testMasterDisconnected(final MasterSalFacade masterSalFacade)
477 throws InterruptedException, ExecutionException, TimeoutException {
478 LOG.info("****** Testing master disconnected");
480 masterSalFacade.onDeviceDisconnected();
482 awaitMountPointNotPresent(masterMountPointService);
484 await().atMost(5, TimeUnit.SECONDS).until(() -> {
485 try (ReadTransaction readTx = masterDataBroker.newReadOnlyTransaction()) {
486 Optional<Node> node = readTx.read(LogicalDatastoreType.OPERATIONAL,
487 NODE_INSTANCE_ID).get(5, TimeUnit.SECONDS);
488 assertTrue(node.isPresent());
489 final NetconfNode netconfNode = node.get().augmentation(NetconfNode.class);
490 return netconfNode.getConnectionStatus() != NetconfNodeConnectionStatus.ConnectionStatus.Connected;
494 awaitMountPointNotPresent(slaveMountPointService);
497 private void testCleanup() throws Exception {
498 LOG.info("****** Testing cleanup");
500 slaveNetconfTopologyManager.close();
501 verify(mockSlaveClusterSingletonServiceReg).close();
504 private void testDOMRpcService(final DOMRpcService domRpcService)
505 throws InterruptedException, ExecutionException, TimeoutException {
506 testPutTopRpc(domRpcService, new DefaultDOMRpcResult((NormalizedNode)null));
507 testPutTopRpc(domRpcService, null);
508 testPutTopRpc(domRpcService, new DefaultDOMRpcResult(ImmutableList.of(
509 RpcResultBuilder.newError(ErrorType.APPLICATION, new ErrorTag("tag1"), "error1"),
510 RpcResultBuilder.newError(ErrorType.APPLICATION, new ErrorTag("tag2"), "error2"))));
512 testGetTopRpc(domRpcService, new DefaultDOMRpcResult(bindingToNormalized.toNormalizedNodeRpcData(
513 new GetTopOutputBuilder().setTopLevelList(oneTopLevelList()).build())));
515 testFailedRpc(domRpcService, getTopRpcSchemaPath, getTopInput);
518 private void testPutTopRpc(final DOMRpcService domRpcService, final DOMRpcResult result)
519 throws InterruptedException, ExecutionException, TimeoutException {
520 ContainerNode putTopInput = bindingToNormalized.toNormalizedNodeRpcData(
521 new PutTopInputBuilder().setTopLevelList(oneTopLevelList()).build());
522 testRpc(domRpcService, putTopRpcSchemaPath, putTopInput, result);
525 private static Map<TopLevelListKey, TopLevelList> oneTopLevelList() {
526 final TopLevelListKey key = new TopLevelListKey("one");
527 return ImmutableMap.of(key, new TopLevelListBuilder().withKey(key).build());
530 private void testGetTopRpc(final DOMRpcService domRpcService, final DOMRpcResult result)
531 throws InterruptedException, ExecutionException, TimeoutException {
532 testRpc(domRpcService, getTopRpcSchemaPath, getTopInput, result);
535 private void testRpc(final DOMRpcService domRpcService, final QName qname, final NormalizedNode input,
536 final DOMRpcResult result) throws InterruptedException, ExecutionException, TimeoutException {
537 final FluentFuture<DOMRpcResult> future = result == null ? FluentFutures.immediateNullFluentFuture()
538 : FluentFutures.immediateFluentFuture(result);
539 final DOMRpcResult actual = invokeRpc(domRpcService, qname, input, future);
540 if (result == null) {
545 assertNotNull(actual);
546 assertEquals(result.getResult(), actual.getResult());
548 assertEquals(result.getErrors().size(), actual.getErrors().size());
549 Iterator<? extends RpcError> iter1 = result.getErrors().iterator();
550 Iterator<? extends RpcError> iter2 = actual.getErrors().iterator();
551 while (iter1.hasNext() && iter2.hasNext()) {
552 RpcError err1 = iter1.next();
553 RpcError err2 = iter2.next();
554 assertEquals(err1.getErrorType(), err2.getErrorType());
555 assertEquals(err1.getTag(), err2.getTag());
556 assertEquals(err1.getMessage(), err2.getMessage());
557 assertEquals(err1.getSeverity(), err2.getSeverity());
558 assertEquals(err1.getApplicationTag(), err2.getApplicationTag());
559 assertEquals(err1.getInfo(), err2.getInfo());
563 private void testFailedRpc(final DOMRpcService domRpcService, final QName qname, final NormalizedNode input)
564 throws InterruptedException, TimeoutException {
566 invokeRpc(domRpcService, qname, input, FluentFutures.immediateFailedFluentFuture(
567 new ClusteringRpcException("mock")));
568 fail("Expected exception");
569 } catch (ExecutionException e) {
570 assertTrue(e.getCause() instanceof ClusteringRpcException);
571 assertEquals("mock", e.getCause().getMessage());
575 private DOMRpcResult invokeRpc(final DOMRpcService domRpcService, final QName qname, final NormalizedNode input,
576 final FluentFuture<DOMRpcResult> returnFuture)
577 throws InterruptedException, ExecutionException, TimeoutException {
578 topRpcImplementation.init(returnFuture);
579 final ListenableFuture<? extends DOMRpcResult> resultFuture = domRpcService.invokeRpc(qname, input);
581 topRpcImplementation.verify(DOMRpcIdentifier.create(qname), input);
583 return resultFuture.get(5, TimeUnit.SECONDS);
586 private static void testDOMDataBrokerOperations(final DOMDataBroker dataBroker)
587 throws InterruptedException, ExecutionException, TimeoutException {
589 DOMDataTreeWriteTransaction writeTx = dataBroker.newWriteOnlyTransaction();
591 final ContainerNode topNode = Builders.containerBuilder()
592 .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(Top.QNAME)).build();
593 final YangInstanceIdentifier topPath = YangInstanceIdentifier.of(Top.QNAME);
594 writeTx.put(LogicalDatastoreType.CONFIGURATION, topPath, topNode);
596 final QName name = QName.create(TopLevelList.QNAME, "name");
597 final YangInstanceIdentifier listPath = YangInstanceIdentifier.builder(topPath)
598 .node(TopLevelList.QNAME).build();
599 final MapEntryNode listEntryNode = ImmutableNodes.mapEntry(TopLevelList.QNAME, name, "one");
600 final MapNode listNode = ImmutableNodes.mapNodeBuilder(TopLevelList.QNAME).addChild(listEntryNode).build();
601 writeTx.merge(LogicalDatastoreType.CONFIGURATION, listPath, listNode);
602 writeTx.commit().get(5, TimeUnit.SECONDS);
604 verifyDataInStore(dataBroker.newReadWriteTransaction(), YangInstanceIdentifier.builder(listPath)
605 .nodeWithKey(TopLevelList.QNAME, name, "one").build(), listEntryNode);
607 writeTx = dataBroker.newWriteOnlyTransaction();
608 writeTx.delete(LogicalDatastoreType.CONFIGURATION, topPath);
609 writeTx.commit().get(5, TimeUnit.SECONDS);
611 DOMDataTreeReadWriteTransaction readTx = dataBroker.newReadWriteTransaction();
612 assertFalse(readTx.exists(LogicalDatastoreType.CONFIGURATION, topPath).get(5, TimeUnit.SECONDS));
613 assertTrue(readTx.cancel());
616 private static void writeNetconfNode(final String cacheDir, final DataBroker databroker)
617 throws InterruptedException, ExecutionException, TimeoutException {
618 final Node node = new NodeBuilder()
619 .withKey(NODE_INSTANCE_ID.getKey())
620 .addAugmentation(new NetconfNodeBuilder()
621 .setHost(new Host(new IpAddress(new Ipv4Address("127.0.0.1"))))
622 .setPort(new PortNumber(Uint16.valueOf(1234)))
623 .setActorResponseWaitTime(Uint16.valueOf(10))
624 .setTcpOnly(Boolean.TRUE)
625 .setSchemaless(Boolean.FALSE)
626 .setKeepaliveDelay(Uint32.ZERO)
627 .setConnectionTimeoutMillis(Uint32.valueOf(5000))
628 .setDefaultRequestTimeoutMillis(Uint32.valueOf(5000))
629 .setMaxConnectionAttempts(Uint32.ONE)
630 .setCredentials(new LoginPwUnencryptedBuilder()
631 .setLoginPasswordUnencrypted(new LoginPasswordUnencryptedBuilder()
636 .setSchemaCacheDirectory(cacheDir)
640 final WriteTransaction writeTx = databroker.newWriteOnlyTransaction();
641 writeTx.put(LogicalDatastoreType.CONFIGURATION, NODE_INSTANCE_ID, node);
642 writeTx.commit().get(5, TimeUnit.SECONDS);
645 private static void verifyDataInStore(final DOMDataTreeReadOperations readTx, final YangInstanceIdentifier path,
646 final NormalizedNode expNode) throws InterruptedException, ExecutionException, TimeoutException {
647 final Optional<NormalizedNode> read = readTx.read(LogicalDatastoreType.CONFIGURATION, path)
648 .get(5, TimeUnit.SECONDS);
649 assertTrue(read.isPresent());
650 assertEquals(expNode, read.get());
652 final Boolean exists = readTx.exists(LogicalDatastoreType.CONFIGURATION, path).get(5, TimeUnit.SECONDS);
656 private static void verifyTopologyNodesCreated(final DataBroker dataBroker) {
657 await().atMost(5, TimeUnit.SECONDS).until(() -> {
658 try (ReadTransaction readTx = dataBroker.newReadOnlyTransaction()) {
659 Optional<Topology> configTopology = readTx.read(LogicalDatastoreType.CONFIGURATION,
660 NetconfTopologyUtils.createTopologyListPath(TOPOLOGY_ID)).get(3, TimeUnit.SECONDS);
661 Optional<Topology> operTopology = readTx.read(LogicalDatastoreType.OPERATIONAL,
662 NetconfTopologyUtils.createTopologyListPath(TOPOLOGY_ID)).get(3, TimeUnit.SECONDS);
663 return configTopology.isPresent() && operTopology.isPresent();
668 private AbstractConcurrentDataBrokerTest newDataBrokerTest() throws Exception {
669 AbstractConcurrentDataBrokerTest dataBrokerTest = new AbstractConcurrentDataBrokerTest(true) {
671 protected Set<YangModuleInfo> getModuleInfos() throws Exception {
672 return ImmutableSet.of(BindingReflections.getModuleInfo(NetconfNode.class),
673 BindingReflections.getModuleInfo(NetworkTopology.class),
674 BindingReflections.getModuleInfo(Topology.class),
675 BindingReflections.getModuleInfo(Keystore.class),
680 dataBrokerTest.setup();
681 return dataBrokerTest;
684 private void awaitMountPointNotPresent(final DOMMountPointService mountPointService) {
685 await().atMost(5, TimeUnit.SECONDS).until(
686 () -> mountPointService.getMountPoint(yangNodeInstanceId).isEmpty());
689 private static DOMDataBroker getDOMDataBroker(final DOMMountPoint mountPoint) {
690 return getMountPointService(mountPoint, DOMDataBroker.class);
693 private static DOMRpcService getDOMRpcService(final DOMMountPoint mountPoint) {
694 return getMountPointService(mountPoint, DOMRpcService.class);
697 private static DOMActionService getDomActionService(final DOMMountPoint mountPoint) {
698 return getMountPointService(mountPoint, DOMActionService.class);
701 private static <T extends DOMService> T getMountPointService(final DOMMountPoint mountPoint,
702 final Class<T> serviceClass) {
703 final Optional<T> maybeService = mountPoint.getService(serviceClass);
704 assertTrue(maybeService.isPresent());
705 return maybeService.get();
708 private DOMMountPoint awaitMountPoint(final DOMMountPointService mountPointService) {
709 await().atMost(5, TimeUnit.SECONDS).until(() ->
710 mountPointService.getMountPoint(yangNodeInstanceId).isPresent());
712 return mountPointService.getMountPoint(yangNodeInstanceId).get();
715 private RpcDefinition findRpcDefinition(final String rpc) {
716 Module topModule = deviceSchemaContext.findModule(TOP_MODULE_NAME, topModuleInfo.getName().getRevision()).get();
717 RpcDefinition rpcDefinition = null;
718 for (RpcDefinition def: topModule.getRpcs()) {
719 if (def.getQName().getLocalName().equals(rpc)) {
725 assertNotNull(rpc + " rpc not found in " + topModule.getRpcs(), rpcDefinition);
726 return rpcDefinition;
729 private static class TopDOMRpcImplementation implements DOMRpcImplementation {
730 private volatile SettableFuture<Entry<DOMRpcIdentifier, NormalizedNode>> rpcInvokedFuture;
731 private volatile FluentFuture<DOMRpcResult> returnFuture;
734 public FluentFuture<DOMRpcResult> invokeRpc(final DOMRpcIdentifier rpc, final NormalizedNode input) {
735 rpcInvokedFuture.set(new SimpleEntry<>(rpc, input));
739 void init(final FluentFuture<DOMRpcResult> retFuture) {
740 this.returnFuture = retFuture;
741 rpcInvokedFuture = SettableFuture.create();
744 void verify(final DOMRpcIdentifier expRpc, final NormalizedNode expInput)
745 throws InterruptedException, ExecutionException, TimeoutException {
746 final Entry<DOMRpcIdentifier, NormalizedNode> actual = rpcInvokedFuture.get(5, TimeUnit.SECONDS);
747 assertEquals(expRpc, actual.getKey());
748 assertEquals(expInput, actual.getValue());