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.QName;
143 import org.opendaylight.yangtools.yang.common.RpcError;
144 import org.opendaylight.yangtools.yang.common.RpcError.ErrorType;
145 import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
146 import org.opendaylight.yangtools.yang.common.Uint16;
147 import org.opendaylight.yangtools.yang.common.Uint32;
148 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
149 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
150 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
151 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
152 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
153 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
154 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
155 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
156 import org.opendaylight.yangtools.yang.model.api.Module;
157 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
158 import org.opendaylight.yangtools.yang.model.repo.api.RevisionSourceIdentifier;
159 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
160 import org.opendaylight.yangtools.yang.model.repo.spi.PotentialSchemaSource;
161 import org.opendaylight.yangtools.yang.parser.impl.DefaultYangParserFactory;
162 import org.slf4j.Logger;
163 import org.slf4j.LoggerFactory;
166 * Tests netconf mount points end-to-end.
168 * @author Thomas Pantelis
170 @RunWith(MockitoJUnitRunner.StrictStubs.class)
171 public class MountPointEndToEndTest extends AbstractBaseSchemasTest {
172 private static final Logger LOG = LoggerFactory.getLogger(MountPointEndToEndTest.class);
174 private static final String TOP_MODULE_NAME = "opendaylight-mdsal-list-test";
175 private static final String ACTOR_SYSTEM_NAME = "test";
176 private static final String TOPOLOGY_ID = TopologyNetconf.QNAME.getLocalName();
177 private static final KeyedInstanceIdentifier<Node, NodeKey> NODE_INSTANCE_ID =
178 NetconfTopologyUtils.createTopologyNodeListPath(new NodeKey(new NodeId("node-id")), TOPOLOGY_ID);
180 private static final String TEST_ROOT_DIRECTORY = "test-cache-root";
181 private static final String TEST_DEFAULT_SUBDIR = "test-schema";
183 @Mock private DOMRpcProviderService mockRpcProviderRegistry;
184 @Mock private RpcProviderService mockRpcProviderService;
185 @Mock private DOMActionProviderService mockActionProviderRegistry;
186 @Mock private NetconfClientDispatcher mockClientDispatcher;
187 @Mock private AAAEncryptionService mockEncryptionService;
188 @Mock private ThreadPool mockThreadPool;
189 @Mock private ScheduledThreadPool mockKeepaliveExecutor;
190 @Mock private DeviceActionFactory deviceActionFactory;
192 @Mock private ActorSystemProvider mockMasterActorSystemProvider;
193 @Mock private DOMMountPointListener masterMountPointListener;
194 private final DOMMountPointService masterMountPointService = new DOMMountPointServiceImpl();
195 private final DOMRpcRouter deviceRpcService = new DOMRpcRouter();
196 private DOMClusterSingletonServiceProviderImpl masterClusterSingletonServiceProvider;
197 private DataBroker masterDataBroker;
198 private DOMDataBroker deviceDOMDataBroker;
199 private ActorSystem masterSystem;
200 private NetconfTopologyManager masterNetconfTopologyManager;
201 private volatile SettableFuture<MasterSalFacade> masterSalFacadeFuture = SettableFuture.create();
203 @Mock private ActorSystemProvider mockSlaveActorSystemProvider;
204 @Mock private ClusterSingletonServiceProvider mockSlaveClusterSingletonServiceProvider;
205 @Mock private ClusterSingletonServiceRegistration mockSlaveClusterSingletonServiceReg;
206 @Mock private DOMMountPointListener slaveMountPointListener;
207 private final DOMMountPointService slaveMountPointService = new DOMMountPointServiceImpl();
208 private DataBroker slaveDataBroker;
209 private ActorSystem slaveSystem;
210 private NetconfTopologyManager slaveNetconfTopologyManager;
211 private final SettableFuture<NetconfTopologyContext> slaveNetconfTopologyContextFuture = SettableFuture.create();
212 private TransactionChain slaveTxChain;
214 private final EventExecutor eventExecutor = GlobalEventExecutor.INSTANCE;
215 private final Config config = new ConfigBuilder().setWriteTransactionIdleTimeout(Uint16.ZERO).build();
216 private EffectiveModelContext deviceSchemaContext;
217 private YangModuleInfo topModuleInfo;
218 private QName putTopRpcSchemaPath;
219 private QName getTopRpcSchemaPath;
220 private BindingNormalizedNodeSerializer bindingToNormalized;
221 private YangInstanceIdentifier yangNodeInstanceId;
222 private final TopDOMRpcImplementation topRpcImplementation = new TopDOMRpcImplementation();
223 private final ContainerNode getTopInput = ImmutableNodes.containerNode(GetTopInput.QNAME);
225 private SchemaResourceManager resourceManager;
228 public void setUp() throws Exception {
231 resourceManager = new DefaultSchemaResourceManager(new DefaultYangParserFactory(), TEST_ROOT_DIRECTORY,
232 TEST_DEFAULT_SUBDIR);
234 topModuleInfo = BindingReflections.getModuleInfo(Top.class);
236 deviceSchemaContext = BindingRuntimeHelpers.createEffectiveModel(Top.class);
238 deviceRpcService.onModelContextUpdated(deviceSchemaContext);
240 putTopRpcSchemaPath = findRpcDefinition("put-top").getQName();
241 getTopRpcSchemaPath = findRpcDefinition("get-top").getQName();
243 deviceRpcService.getRpcProviderService().registerRpcImplementation(topRpcImplementation,
244 DOMRpcIdentifier.create(putTopRpcSchemaPath), DOMRpcIdentifier.create(getTopRpcSchemaPath));
250 yangNodeInstanceId = bindingToNormalized.toYangInstanceIdentifier(NODE_INSTANCE_ID);
252 doReturn(mock(ReconnectFuture.class)).when(mockClientDispatcher).createReconnectingClient(any());
254 LOG.info("****** Setup complete");
257 private static void deleteCacheDir() {
258 FileUtils.deleteQuietly(new File(TEST_ROOT_DIRECTORY));
262 public void tearDown() throws Exception {
264 TestKit.shutdownActorSystem(slaveSystem, true);
265 TestKit.shutdownActorSystem(masterSystem, true);
268 private void setupMaster() throws Exception {
269 AbstractConcurrentDataBrokerTest dataBrokerTest = newDataBrokerTest();
270 masterDataBroker = dataBrokerTest.getDataBroker();
271 deviceDOMDataBroker = dataBrokerTest.getDomBroker();
272 bindingToNormalized = dataBrokerTest.getDataBrokerTestCustomizer().getAdapterContext().currentSerializer();
274 masterSystem = ActorSystem.create(ACTOR_SYSTEM_NAME, ConfigFactory.load().getConfig("Master"));
276 masterClusterSingletonServiceProvider = new DOMClusterSingletonServiceProviderImpl();
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 mockRpcProviderService, 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, mockRpcProviderService, deviceActionFactory,
337 protected NetconfTopologyContext newNetconfTopologyContext(final NetconfTopologySetup setup,
338 final ServiceGroupIdentifier serviceGroupIdent, final Timeout actorResponseWaitTime,
339 final DeviceActionFactory actionFactory) {
340 NetconfTopologyContext spiedContext = spy(super.newNetconfTopologyContext(setup, serviceGroupIdent,
341 actorResponseWaitTime, actionFactory));
343 slaveNetconfTopologyContextFuture.set(spiedContext);
348 slaveNetconfTopologyManager.init();
350 verifyTopologyNodesCreated(slaveDataBroker);
352 slaveTxChain = slaveDataBroker.createTransactionChain(new TransactionChainListener() {
354 public void onTransactionChainSuccessful(final TransactionChain chain) {
358 public void onTransactionChainFailed(final TransactionChain chain, final Transaction transaction,
359 final Throwable cause) {
360 LOG.error("Slave transaction chain failed", cause);
366 public void test() throws Exception {
371 final MasterSalFacade masterSalFacade = testMasterNodeUpdated();
373 testMasterDisconnected(masterSalFacade);
378 private MasterSalFacade testMaster() throws InterruptedException, ExecutionException, TimeoutException {
379 LOG.info("****** Testing master");
381 writeNetconfNode(TEST_DEFAULT_SUBDIR, masterDataBroker);
383 final MasterSalFacade masterSalFacade = masterSalFacadeFuture.get(5, TimeUnit.SECONDS);
384 final ArrayList<String> capabilities = Lists.newArrayList(
385 NetconfMessageTransformUtil.NETCONF_CANDIDATE_URI.toString());
387 masterSalFacade.onDeviceConnected(new EmptyMountPointContext(deviceSchemaContext),
388 NetconfSessionPreferences.fromStrings(capabilities), deviceRpcService.getRpcService());
390 DOMMountPoint masterMountPoint = awaitMountPoint(masterMountPointService);
392 LOG.info("****** Testing master DOMDataBroker operations");
394 testDOMDataBrokerOperations(getDOMDataBroker(masterMountPoint));
396 LOG.info("****** Testing master DOMRpcService");
398 testDOMRpcService(getDOMRpcService(masterMountPoint));
399 return masterSalFacade;
402 private void testSlave() throws InterruptedException, ExecutionException, TimeoutException {
403 LOG.info("****** Testing slave");
405 writeNetconfNode("slave", slaveDataBroker);
407 verify(mockSlaveClusterSingletonServiceProvider, timeout(5000)).registerClusterSingletonService(any());
409 // Since the master and slave use separate DataBrokers we need to copy the master's oper node to the slave.
410 // This is essentially what happens in a clustered environment but we'll use a DTCL here.
412 masterDataBroker.registerDataTreeChangeListener(
413 DataTreeIdentifier.create(LogicalDatastoreType.OPERATIONAL, NODE_INSTANCE_ID), changes -> {
414 final WriteTransaction slaveTx = slaveTxChain.newWriteOnlyTransaction();
415 for (DataTreeModification<Node> dataTreeModification : changes) {
416 DataObjectModification<Node> rootNode = dataTreeModification.getRootNode();
417 InstanceIdentifier<Node> path = dataTreeModification.getRootPath().getRootIdentifier();
418 switch (rootNode.getModificationType()) {
420 case SUBTREE_MODIFIED:
421 slaveTx.merge(LogicalDatastoreType.OPERATIONAL, path, rootNode.getDataAfter());
424 slaveTx.delete(LogicalDatastoreType.OPERATIONAL, path);
434 DOMMountPoint slaveMountPoint = awaitMountPoint(slaveMountPointService);
436 final NetconfTopologyContext slaveNetconfTopologyContext =
437 slaveNetconfTopologyContextFuture.get(5, TimeUnit.SECONDS);
438 verify(slaveNetconfTopologyContext, never()).newMasterSalFacade();
440 LOG.info("****** Testing slave DOMDataBroker operations");
442 testDOMDataBrokerOperations(getDOMDataBroker(slaveMountPoint));
444 LOG.info("****** Testing slave DOMRpcService");
446 testDOMRpcService(getDOMRpcService(slaveMountPoint));
449 private MasterSalFacade testMasterNodeUpdated() throws InterruptedException, ExecutionException, TimeoutException {
450 LOG.info("****** Testing update master node");
452 masterMountPointService.registerProvisionListener(masterMountPointListener);
453 slaveMountPointService.registerProvisionListener(slaveMountPointListener);
455 masterSalFacadeFuture = SettableFuture.create();
456 writeNetconfNode(TEST_DEFAULT_SUBDIR, masterDataBroker);
458 verify(masterMountPointListener, timeout(5000)).onMountPointRemoved(yangNodeInstanceId);
460 MasterSalFacade masterSalFacade = masterSalFacadeFuture.get(5, TimeUnit.SECONDS);
461 final ArrayList<String> capabilities = Lists.newArrayList(
462 NetconfMessageTransformUtil.NETCONF_CANDIDATE_URI.toString());
464 masterSalFacade.onDeviceConnected(new EmptyMountPointContext(deviceSchemaContext),
465 NetconfSessionPreferences.fromStrings(capabilities), deviceRpcService.getRpcService());
467 verify(masterMountPointListener, timeout(5000)).onMountPointCreated(yangNodeInstanceId);
469 verify(slaveMountPointListener, timeout(5000)).onMountPointRemoved(yangNodeInstanceId);
470 verify(slaveMountPointListener, timeout(5000)).onMountPointCreated(yangNodeInstanceId);
472 return masterSalFacade;
475 private void testMasterDisconnected(final MasterSalFacade masterSalFacade)
476 throws InterruptedException, ExecutionException, TimeoutException {
477 LOG.info("****** Testing master disconnected");
479 masterSalFacade.onDeviceDisconnected();
481 awaitMountPointNotPresent(masterMountPointService);
483 await().atMost(5, TimeUnit.SECONDS).until(() -> {
484 try (ReadTransaction readTx = masterDataBroker.newReadOnlyTransaction()) {
485 Optional<Node> node = readTx.read(LogicalDatastoreType.OPERATIONAL,
486 NODE_INSTANCE_ID).get(5, TimeUnit.SECONDS);
487 assertTrue(node.isPresent());
488 final NetconfNode netconfNode = node.get().augmentation(NetconfNode.class);
489 return netconfNode.getConnectionStatus() != NetconfNodeConnectionStatus.ConnectionStatus.Connected;
493 awaitMountPointNotPresent(slaveMountPointService);
496 private void testCleanup() throws Exception {
497 LOG.info("****** Testing cleanup");
499 slaveNetconfTopologyManager.close();
500 verify(mockSlaveClusterSingletonServiceReg).close();
503 private void testDOMRpcService(final DOMRpcService domRpcService)
504 throws InterruptedException, ExecutionException, TimeoutException {
505 testPutTopRpc(domRpcService, new DefaultDOMRpcResult((NormalizedNode)null));
506 testPutTopRpc(domRpcService, null);
507 testPutTopRpc(domRpcService, new DefaultDOMRpcResult(ImmutableList.of(
508 RpcResultBuilder.newError(ErrorType.APPLICATION, "tag1", "error1"),
509 RpcResultBuilder.newError(ErrorType.APPLICATION, "tag2", "error2"))));
511 testGetTopRpc(domRpcService, new DefaultDOMRpcResult(bindingToNormalized.toNormalizedNodeRpcData(
512 new GetTopOutputBuilder().setTopLevelList(oneTopLevelList()).build())));
514 testFailedRpc(domRpcService, getTopRpcSchemaPath, getTopInput);
517 private void testPutTopRpc(final DOMRpcService domRpcService, final DOMRpcResult result)
518 throws InterruptedException, ExecutionException, TimeoutException {
519 ContainerNode putTopInput = bindingToNormalized.toNormalizedNodeRpcData(
520 new PutTopInputBuilder().setTopLevelList(oneTopLevelList()).build());
521 testRpc(domRpcService, putTopRpcSchemaPath, putTopInput, result);
524 private static Map<TopLevelListKey, TopLevelList> oneTopLevelList() {
525 final TopLevelListKey key = new TopLevelListKey("one");
526 return ImmutableMap.of(key, new TopLevelListBuilder().withKey(key).build());
529 private void testGetTopRpc(final DOMRpcService domRpcService, final DOMRpcResult result)
530 throws InterruptedException, ExecutionException, TimeoutException {
531 testRpc(domRpcService, getTopRpcSchemaPath, getTopInput, result);
534 private void testRpc(final DOMRpcService domRpcService, final QName qname, final NormalizedNode input,
535 final DOMRpcResult result) throws InterruptedException, ExecutionException, TimeoutException {
536 final FluentFuture<DOMRpcResult> future = result == null ? FluentFutures.immediateNullFluentFuture()
537 : FluentFutures.immediateFluentFuture(result);
538 final DOMRpcResult actual = invokeRpc(domRpcService, qname, input, future);
539 if (result == null) {
544 assertNotNull(actual);
545 assertEquals(result.getResult(), actual.getResult());
547 assertEquals(result.getErrors().size(), actual.getErrors().size());
548 Iterator<? extends RpcError> iter1 = result.getErrors().iterator();
549 Iterator<? extends RpcError> iter2 = actual.getErrors().iterator();
550 while (iter1.hasNext() && iter2.hasNext()) {
551 RpcError err1 = iter1.next();
552 RpcError err2 = iter2.next();
553 assertEquals(err1.getErrorType(), err2.getErrorType());
554 assertEquals(err1.getTag(), err2.getTag());
555 assertEquals(err1.getMessage(), err2.getMessage());
556 assertEquals(err1.getSeverity(), err2.getSeverity());
557 assertEquals(err1.getApplicationTag(), err2.getApplicationTag());
558 assertEquals(err1.getInfo(), err2.getInfo());
562 private void testFailedRpc(final DOMRpcService domRpcService, final QName qname, final NormalizedNode input)
563 throws InterruptedException, TimeoutException {
565 invokeRpc(domRpcService, qname, input, FluentFutures.immediateFailedFluentFuture(
566 new ClusteringRpcException("mock")));
567 fail("Expected exception");
568 } catch (ExecutionException e) {
569 assertTrue(e.getCause() instanceof ClusteringRpcException);
570 assertEquals("mock", e.getCause().getMessage());
574 private DOMRpcResult invokeRpc(final DOMRpcService domRpcService, final QName qname, final NormalizedNode input,
575 final FluentFuture<DOMRpcResult> returnFuture)
576 throws InterruptedException, ExecutionException, TimeoutException {
577 topRpcImplementation.init(returnFuture);
578 final ListenableFuture<? extends DOMRpcResult> resultFuture = domRpcService.invokeRpc(qname, input);
580 topRpcImplementation.verify(DOMRpcIdentifier.create(qname), input);
582 return resultFuture.get(5, TimeUnit.SECONDS);
585 private static void testDOMDataBrokerOperations(final DOMDataBroker dataBroker)
586 throws InterruptedException, ExecutionException, TimeoutException {
588 DOMDataTreeWriteTransaction writeTx = dataBroker.newWriteOnlyTransaction();
590 final ContainerNode topNode = Builders.containerBuilder()
591 .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(Top.QNAME)).build();
592 final YangInstanceIdentifier topPath = YangInstanceIdentifier.of(Top.QNAME);
593 writeTx.put(LogicalDatastoreType.CONFIGURATION, topPath, topNode);
595 final QName name = QName.create(TopLevelList.QNAME, "name");
596 final YangInstanceIdentifier listPath = YangInstanceIdentifier.builder(topPath)
597 .node(TopLevelList.QNAME).build();
598 final MapEntryNode listEntryNode = ImmutableNodes.mapEntry(TopLevelList.QNAME, name, "one");
599 final MapNode listNode = ImmutableNodes.mapNodeBuilder(TopLevelList.QNAME).addChild(listEntryNode).build();
600 writeTx.merge(LogicalDatastoreType.CONFIGURATION, listPath, listNode);
601 writeTx.commit().get(5, TimeUnit.SECONDS);
603 verifyDataInStore(dataBroker.newReadWriteTransaction(), YangInstanceIdentifier.builder(listPath)
604 .nodeWithKey(TopLevelList.QNAME, name, "one").build(), listEntryNode);
606 writeTx = dataBroker.newWriteOnlyTransaction();
607 writeTx.delete(LogicalDatastoreType.CONFIGURATION, topPath);
608 writeTx.commit().get(5, TimeUnit.SECONDS);
610 DOMDataTreeReadWriteTransaction readTx = dataBroker.newReadWriteTransaction();
611 assertFalse(readTx.exists(LogicalDatastoreType.CONFIGURATION, topPath).get(5, TimeUnit.SECONDS));
612 assertTrue(readTx.cancel());
615 private static void writeNetconfNode(final String cacheDir, final DataBroker databroker)
616 throws InterruptedException, ExecutionException, TimeoutException {
617 final Node node = new NodeBuilder()
618 .withKey(NODE_INSTANCE_ID.getKey())
619 .addAugmentation(new NetconfNodeBuilder()
620 .setHost(new Host(new IpAddress(new Ipv4Address("127.0.0.1"))))
621 .setPort(new PortNumber(Uint16.valueOf(1234)))
622 .setActorResponseWaitTime(Uint16.valueOf(10))
623 .setTcpOnly(Boolean.TRUE)
624 .setSchemaless(Boolean.FALSE)
625 .setKeepaliveDelay(Uint32.ZERO)
626 .setConnectionTimeoutMillis(Uint32.valueOf(5000))
627 .setDefaultRequestTimeoutMillis(Uint32.valueOf(5000))
628 .setMaxConnectionAttempts(Uint32.ONE)
629 .setCredentials(new LoginPwUnencryptedBuilder()
630 .setLoginPasswordUnencrypted(new LoginPasswordUnencryptedBuilder()
635 .setSchemaCacheDirectory(cacheDir)
639 final WriteTransaction writeTx = databroker.newWriteOnlyTransaction();
640 writeTx.put(LogicalDatastoreType.CONFIGURATION, NODE_INSTANCE_ID, node);
641 writeTx.commit().get(5, TimeUnit.SECONDS);
644 private static void verifyDataInStore(final DOMDataTreeReadOperations readTx, final YangInstanceIdentifier path,
645 final NormalizedNode expNode) throws InterruptedException, ExecutionException, TimeoutException {
646 final Optional<NormalizedNode> read = readTx.read(LogicalDatastoreType.CONFIGURATION, path)
647 .get(5, TimeUnit.SECONDS);
648 assertTrue(read.isPresent());
649 assertEquals(expNode, read.get());
651 final Boolean exists = readTx.exists(LogicalDatastoreType.CONFIGURATION, path).get(5, TimeUnit.SECONDS);
655 private static void verifyTopologyNodesCreated(final DataBroker dataBroker) {
656 await().atMost(5, TimeUnit.SECONDS).until(() -> {
657 try (ReadTransaction readTx = dataBroker.newReadOnlyTransaction()) {
658 Optional<Topology> configTopology = readTx.read(LogicalDatastoreType.CONFIGURATION,
659 NetconfTopologyUtils.createTopologyListPath(TOPOLOGY_ID)).get(3, TimeUnit.SECONDS);
660 Optional<Topology> operTopology = readTx.read(LogicalDatastoreType.OPERATIONAL,
661 NetconfTopologyUtils.createTopologyListPath(TOPOLOGY_ID)).get(3, TimeUnit.SECONDS);
662 return configTopology.isPresent() && operTopology.isPresent();
667 private AbstractConcurrentDataBrokerTest newDataBrokerTest() throws Exception {
668 AbstractConcurrentDataBrokerTest dataBrokerTest = new AbstractConcurrentDataBrokerTest(true) {
670 protected Set<YangModuleInfo> getModuleInfos() throws Exception {
671 return ImmutableSet.of(BindingReflections.getModuleInfo(NetconfNode.class),
672 BindingReflections.getModuleInfo(NetworkTopology.class),
673 BindingReflections.getModuleInfo(Topology.class),
674 BindingReflections.getModuleInfo(Keystore.class),
679 dataBrokerTest.setup();
680 return dataBrokerTest;
683 private void awaitMountPointNotPresent(final DOMMountPointService mountPointService) {
684 await().atMost(5, TimeUnit.SECONDS).until(
685 () -> mountPointService.getMountPoint(yangNodeInstanceId).isEmpty());
688 private static DOMDataBroker getDOMDataBroker(final DOMMountPoint mountPoint) {
689 return getMountPointService(mountPoint, DOMDataBroker.class);
692 private static DOMRpcService getDOMRpcService(final DOMMountPoint mountPoint) {
693 return getMountPointService(mountPoint, DOMRpcService.class);
696 private static DOMActionService getDomActionService(final DOMMountPoint mountPoint) {
697 return getMountPointService(mountPoint, DOMActionService.class);
700 private static <T extends DOMService> T getMountPointService(final DOMMountPoint mountPoint,
701 final Class<T> serviceClass) {
702 final Optional<T> maybeService = mountPoint.getService(serviceClass);
703 assertTrue(maybeService.isPresent());
704 return maybeService.get();
707 private DOMMountPoint awaitMountPoint(final DOMMountPointService mountPointService) {
708 await().atMost(5, TimeUnit.SECONDS).until(() ->
709 mountPointService.getMountPoint(yangNodeInstanceId).isPresent());
711 return mountPointService.getMountPoint(yangNodeInstanceId).get();
714 private RpcDefinition findRpcDefinition(final String rpc) {
715 Module topModule = deviceSchemaContext.findModule(TOP_MODULE_NAME, topModuleInfo.getName().getRevision()).get();
716 RpcDefinition rpcDefinition = null;
717 for (RpcDefinition def: topModule.getRpcs()) {
718 if (def.getQName().getLocalName().equals(rpc)) {
724 assertNotNull(rpc + " rpc not found in " + topModule.getRpcs(), rpcDefinition);
725 return rpcDefinition;
728 private static class TopDOMRpcImplementation implements DOMRpcImplementation {
729 private volatile SettableFuture<Entry<DOMRpcIdentifier, NormalizedNode>> rpcInvokedFuture;
730 private volatile FluentFuture<DOMRpcResult> returnFuture;
733 public FluentFuture<DOMRpcResult> invokeRpc(final DOMRpcIdentifier rpc, final NormalizedNode input) {
734 rpcInvokedFuture.set(new SimpleEntry<>(rpc, input));
738 void init(final FluentFuture<DOMRpcResult> retFuture) {
739 this.returnFuture = retFuture;
740 rpcInvokedFuture = SettableFuture.create();
743 void verify(final DOMRpcIdentifier expRpc, final NormalizedNode expInput)
744 throws InterruptedException, ExecutionException, TimeoutException {
745 final Entry<DOMRpcIdentifier, NormalizedNode> actual = rpcInvokedFuture.get(5, TimeUnit.SECONDS);
746 assertEquals(expRpc, actual.getKey());
747 assertEquals(expInput, actual.getValue());