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.util.concurrent.FluentFuture;
32 import com.google.common.util.concurrent.Futures;
33 import com.google.common.util.concurrent.ListenableFuture;
34 import com.google.common.util.concurrent.MoreExecutors;
35 import com.google.common.util.concurrent.SettableFuture;
36 import com.typesafe.config.ConfigFactory;
37 import io.netty.util.concurrent.EventExecutor;
38 import io.netty.util.concurrent.GlobalEventExecutor;
40 import java.util.Iterator;
41 import java.util.List;
43 import java.util.Map.Entry;
44 import java.util.Optional;
46 import java.util.concurrent.ExecutionException;
47 import java.util.concurrent.TimeUnit;
48 import java.util.concurrent.TimeoutException;
49 import org.apache.commons.io.FileUtils;
50 import org.eclipse.jdt.annotation.NonNull;
51 import org.junit.After;
52 import org.junit.Before;
53 import org.junit.Test;
54 import org.junit.runner.RunWith;
55 import org.mockito.Mock;
56 import org.mockito.junit.MockitoJUnitRunner;
57 import org.opendaylight.aaa.encrypt.AAAEncryptionService;
58 import org.opendaylight.controller.cluster.ActorSystemProvider;
59 import org.opendaylight.controller.config.threadpool.ScheduledThreadPool;
60 import org.opendaylight.controller.config.threadpool.ThreadPool;
61 import org.opendaylight.mdsal.binding.api.DataBroker;
62 import org.opendaylight.mdsal.binding.api.DataObjectModification;
63 import org.opendaylight.mdsal.binding.api.DataTreeIdentifier;
64 import org.opendaylight.mdsal.binding.api.DataTreeModification;
65 import org.opendaylight.mdsal.binding.api.ReadTransaction;
66 import org.opendaylight.mdsal.binding.api.RpcProviderService;
67 import org.opendaylight.mdsal.binding.api.Transaction;
68 import org.opendaylight.mdsal.binding.api.TransactionChain;
69 import org.opendaylight.mdsal.binding.api.TransactionChainListener;
70 import org.opendaylight.mdsal.binding.api.WriteTransaction;
71 import org.opendaylight.mdsal.binding.dom.adapter.test.AbstractConcurrentDataBrokerTest;
72 import org.opendaylight.mdsal.binding.dom.codec.api.BindingNormalizedNodeSerializer;
73 import org.opendaylight.mdsal.binding.runtime.spi.BindingRuntimeHelpers;
74 import org.opendaylight.mdsal.binding.spec.reflect.BindingReflections;
75 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
76 import org.opendaylight.mdsal.dom.api.DOMActionProviderService;
77 import org.opendaylight.mdsal.dom.api.DOMActionService;
78 import org.opendaylight.mdsal.dom.api.DOMDataBroker;
79 import org.opendaylight.mdsal.dom.api.DOMDataTreeReadOperations;
80 import org.opendaylight.mdsal.dom.api.DOMDataTreeReadWriteTransaction;
81 import org.opendaylight.mdsal.dom.api.DOMDataTreeWriteTransaction;
82 import org.opendaylight.mdsal.dom.api.DOMMountPoint;
83 import org.opendaylight.mdsal.dom.api.DOMMountPointListener;
84 import org.opendaylight.mdsal.dom.api.DOMMountPointService;
85 import org.opendaylight.mdsal.dom.api.DOMRpcIdentifier;
86 import org.opendaylight.mdsal.dom.api.DOMRpcImplementation;
87 import org.opendaylight.mdsal.dom.api.DOMRpcProviderService;
88 import org.opendaylight.mdsal.dom.api.DOMRpcResult;
89 import org.opendaylight.mdsal.dom.api.DOMRpcService;
90 import org.opendaylight.mdsal.dom.api.DOMService;
91 import org.opendaylight.mdsal.dom.broker.DOMMountPointServiceImpl;
92 import org.opendaylight.mdsal.dom.broker.DOMRpcRouter;
93 import org.opendaylight.mdsal.dom.spi.DefaultDOMRpcResult;
94 import org.opendaylight.mdsal.singleton.common.api.ClusterSingletonServiceProvider;
95 import org.opendaylight.mdsal.singleton.common.api.ClusterSingletonServiceRegistration;
96 import org.opendaylight.mdsal.singleton.common.api.ServiceGroupIdentifier;
97 import org.opendaylight.mdsal.singleton.dom.impl.DOMClusterSingletonServiceProviderImpl;
98 import org.opendaylight.netconf.client.NetconfClientDispatcher;
99 import org.opendaylight.netconf.nettyutil.ReconnectFuture;
100 import org.opendaylight.netconf.sal.connect.api.DeviceActionFactory;
101 import org.opendaylight.netconf.sal.connect.api.SchemaResourceManager;
102 import org.opendaylight.netconf.sal.connect.impl.DefaultSchemaResourceManager;
103 import org.opendaylight.netconf.sal.connect.netconf.listener.NetconfSessionPreferences;
104 import org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil;
105 import org.opendaylight.netconf.topology.singleton.impl.utils.ClusteringRpcException;
106 import org.opendaylight.netconf.topology.singleton.impl.utils.NetconfTopologySetup;
107 import org.opendaylight.netconf.topology.singleton.impl.utils.NetconfTopologyUtils;
108 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Host;
109 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpAddress;
110 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Ipv4Address;
111 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.PortNumber;
112 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.keystore.rev171017.Keystore;
113 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.NetconfNode;
114 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.NetconfNodeBuilder;
115 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.NetconfNodeConnectionStatus;
116 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.credentials.credentials.LoginPwUnencryptedBuilder;
117 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.credentials.credentials.login.pw.unencrypted.LoginPasswordUnencryptedBuilder;
118 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.network.topology.topology.topology.types.TopologyNetconf;
119 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.topology.singleton.config.rev170419.Config;
120 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.topology.singleton.config.rev170419.ConfigBuilder;
121 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.list.rev140701.GetTopInput;
122 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.list.rev140701.GetTopOutputBuilder;
123 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.list.rev140701.PutTopInputBuilder;
124 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.list.rev140701.Top;
125 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.list.rev140701.two.level.list.TopLevelList;
126 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.list.rev140701.two.level.list.TopLevelListBuilder;
127 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.list.rev140701.two.level.list.TopLevelListKey;
128 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NetworkTopology;
129 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NodeId;
130 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.TopologyBuilder;
131 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node;
132 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.NodeBuilder;
133 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.NodeKey;
134 import org.opendaylight.yangtools.rfc8528.data.util.EmptyMountPointContext;
135 import org.opendaylight.yangtools.util.concurrent.FluentFutures;
136 import org.opendaylight.yangtools.yang.binding.DataObject;
137 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
138 import org.opendaylight.yangtools.yang.binding.KeyedInstanceIdentifier;
139 import org.opendaylight.yangtools.yang.binding.YangModuleInfo;
140 import org.opendaylight.yangtools.yang.common.ErrorTag;
141 import org.opendaylight.yangtools.yang.common.ErrorType;
142 import org.opendaylight.yangtools.yang.common.QName;
143 import org.opendaylight.yangtools.yang.common.Revision;
144 import org.opendaylight.yangtools.yang.common.RpcError;
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.SourceIdentifier;
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 @NonNull 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 final var 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 var resources = resourceManager.getSchemaResources(TEST_DEFAULT_SUBDIR, "test");
284 resources.getSchemaRegistry().registerSchemaSource(
285 id -> Futures.immediateFuture(YangTextSchemaSource.delegateForByteSource(id,
286 topModuleInfo.getYangTextByteSource())),
287 PotentialSchemaSource.create(new SourceIdentifier(TOP_MODULE_NAME,
288 topModuleInfo.getName().getRevision().map(Revision::toString).orElse(null)),
289 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 final var context = super.newNetconfTopologyContext(setup, serviceGroupIdent, actorResponseWaitTime,
303 final var spiedContext = spy(context);
304 doAnswer(invocation -> {
305 final var 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 Exception {
379 LOG.info("****** Testing master");
381 writeNetconfNode(TEST_DEFAULT_SUBDIR, masterDataBroker);
383 final var masterSalFacade = masterSalFacadeFuture.get(5, TimeUnit.SECONDS);
384 masterSalFacade.onDeviceConnected(new EmptyMountPointContext(deviceSchemaContext),
385 NetconfSessionPreferences.fromStrings(
386 List.of(NetconfMessageTransformUtil.NETCONF_CANDIDATE_URI.toString())),
387 deviceRpcService.getRpcService());
389 final var masterMountPoint = awaitMountPoint(masterMountPointService);
391 LOG.info("****** Testing master DOMDataBroker operations");
393 testDOMDataBrokerOperations(getDOMDataBroker(masterMountPoint));
395 LOG.info("****** Testing master DOMRpcService");
397 testDOMRpcService(getDOMRpcService(masterMountPoint));
398 return masterSalFacade;
401 private void testSlave() throws Exception {
402 LOG.info("****** Testing slave");
404 writeNetconfNode("slave", slaveDataBroker);
406 verify(mockSlaveClusterSingletonServiceProvider, timeout(5000)).registerClusterSingletonService(any());
408 // Since the master and slave use separate DataBrokers we need to copy the master's oper node to the slave.
409 // This is essentially what happens in a clustered environment but we'll use a DTCL here.
411 masterDataBroker.registerDataTreeChangeListener(
412 DataTreeIdentifier.create(LogicalDatastoreType.OPERATIONAL, NODE_INSTANCE_ID), changes -> {
413 final WriteTransaction slaveTx = slaveTxChain.newWriteOnlyTransaction();
414 for (DataTreeModification<Node> dataTreeModification : changes) {
415 DataObjectModification<Node> rootNode = dataTreeModification.getRootNode();
416 InstanceIdentifier<Node> path = dataTreeModification.getRootPath().getRootIdentifier();
417 switch (rootNode.getModificationType()) {
419 case SUBTREE_MODIFIED:
420 slaveTx.merge(LogicalDatastoreType.OPERATIONAL, path, rootNode.getDataAfter());
423 slaveTx.delete(LogicalDatastoreType.OPERATIONAL, path);
433 DOMMountPoint slaveMountPoint = awaitMountPoint(slaveMountPointService);
435 final NetconfTopologyContext slaveNetconfTopologyContext =
436 slaveNetconfTopologyContextFuture.get(5, TimeUnit.SECONDS);
437 verify(slaveNetconfTopologyContext, never()).newMasterSalFacade();
439 LOG.info("****** Testing slave DOMDataBroker operations");
441 testDOMDataBrokerOperations(getDOMDataBroker(slaveMountPoint));
443 LOG.info("****** Testing slave DOMRpcService");
445 testDOMRpcService(getDOMRpcService(slaveMountPoint));
448 private MasterSalFacade testMasterNodeUpdated() throws Exception {
449 LOG.info("****** Testing update master node");
451 masterMountPointService.registerProvisionListener(masterMountPointListener);
452 slaveMountPointService.registerProvisionListener(slaveMountPointListener);
454 masterSalFacadeFuture = SettableFuture.create();
455 writeNetconfNode(TEST_DEFAULT_SUBDIR, masterDataBroker);
457 verify(masterMountPointListener, timeout(5000)).onMountPointRemoved(yangNodeInstanceId);
459 final var masterSalFacade = masterSalFacadeFuture.get(5, TimeUnit.SECONDS);
460 masterSalFacade.onDeviceConnected(new EmptyMountPointContext(deviceSchemaContext),
461 NetconfSessionPreferences.fromStrings(List.of(
462 NetconfMessageTransformUtil.NETCONF_CANDIDATE_URI.toString())),
463 deviceRpcService.getRpcService());
465 verify(masterMountPointListener, timeout(5000)).onMountPointCreated(yangNodeInstanceId);
467 verify(slaveMountPointListener, timeout(5000)).onMountPointRemoved(yangNodeInstanceId);
468 verify(slaveMountPointListener, timeout(5000)).onMountPointCreated(yangNodeInstanceId);
470 return masterSalFacade;
473 private void testMasterDisconnected(final MasterSalFacade masterSalFacade) throws Exception {
474 LOG.info("****** Testing master disconnected");
476 masterSalFacade.onDeviceDisconnected();
478 awaitMountPointNotPresent(masterMountPointService);
480 await().atMost(5, TimeUnit.SECONDS).until(() -> {
481 try (ReadTransaction readTx = masterDataBroker.newReadOnlyTransaction()) {
482 Optional<Node> node = readTx.read(LogicalDatastoreType.OPERATIONAL,
483 NODE_INSTANCE_ID).get(5, TimeUnit.SECONDS);
484 assertTrue(node.isPresent());
485 final NetconfNode netconfNode = node.get().augmentation(NetconfNode.class);
486 return netconfNode.getConnectionStatus() != NetconfNodeConnectionStatus.ConnectionStatus.Connected;
490 awaitMountPointNotPresent(slaveMountPointService);
493 private void testCleanup() throws Exception {
494 LOG.info("****** Testing cleanup");
496 slaveNetconfTopologyManager.close();
497 verify(mockSlaveClusterSingletonServiceReg).close();
500 private void testDOMRpcService(final DOMRpcService domRpcService)
501 throws InterruptedException, ExecutionException, TimeoutException {
502 testPutTopRpc(domRpcService, new DefaultDOMRpcResult((NormalizedNode)null));
503 testPutTopRpc(domRpcService, null);
504 testPutTopRpc(domRpcService, new DefaultDOMRpcResult(ImmutableList.of(
505 RpcResultBuilder.newError(ErrorType.APPLICATION, new ErrorTag("tag1"), "error1"),
506 RpcResultBuilder.newError(ErrorType.APPLICATION, new ErrorTag("tag2"), "error2"))));
508 testGetTopRpc(domRpcService, new DefaultDOMRpcResult(bindingToNormalized.toNormalizedNodeRpcData(
509 new GetTopOutputBuilder().setTopLevelList(oneTopLevelList()).build())));
511 testFailedRpc(domRpcService, getTopRpcSchemaPath, getTopInput);
514 private void testPutTopRpc(final DOMRpcService domRpcService, final DOMRpcResult result)
515 throws InterruptedException, ExecutionException, TimeoutException {
516 ContainerNode putTopInput = bindingToNormalized.toNormalizedNodeRpcData(
517 new PutTopInputBuilder().setTopLevelList(oneTopLevelList()).build());
518 testRpc(domRpcService, putTopRpcSchemaPath, putTopInput, result);
521 private static Map<TopLevelListKey, TopLevelList> oneTopLevelList() {
522 final TopLevelListKey key = new TopLevelListKey("one");
523 return ImmutableMap.of(key, new TopLevelListBuilder().withKey(key).build());
526 private void testGetTopRpc(final DOMRpcService domRpcService, final DOMRpcResult result)
527 throws InterruptedException, ExecutionException, TimeoutException {
528 testRpc(domRpcService, getTopRpcSchemaPath, getTopInput, result);
531 private void testRpc(final DOMRpcService domRpcService, final QName qname, final NormalizedNode input,
532 final DOMRpcResult result) throws InterruptedException, ExecutionException, TimeoutException {
533 final FluentFuture<DOMRpcResult> future = result == null ? FluentFutures.immediateNullFluentFuture()
534 : FluentFutures.immediateFluentFuture(result);
535 final DOMRpcResult actual = invokeRpc(domRpcService, qname, input, future);
536 if (result == null) {
541 assertNotNull(actual);
542 assertEquals(result.getResult(), actual.getResult());
544 assertEquals(result.getErrors().size(), actual.getErrors().size());
545 Iterator<? extends RpcError> iter1 = result.getErrors().iterator();
546 Iterator<? extends RpcError> iter2 = actual.getErrors().iterator();
547 while (iter1.hasNext() && iter2.hasNext()) {
548 RpcError err1 = iter1.next();
549 RpcError err2 = iter2.next();
550 assertEquals(err1.getErrorType(), err2.getErrorType());
551 assertEquals(err1.getTag(), err2.getTag());
552 assertEquals(err1.getMessage(), err2.getMessage());
553 assertEquals(err1.getSeverity(), err2.getSeverity());
554 assertEquals(err1.getApplicationTag(), err2.getApplicationTag());
555 assertEquals(err1.getInfo(), err2.getInfo());
559 private void testFailedRpc(final DOMRpcService domRpcService, final QName qname, final NormalizedNode input)
560 throws InterruptedException, TimeoutException {
562 invokeRpc(domRpcService, qname, input, FluentFutures.immediateFailedFluentFuture(
563 new ClusteringRpcException("mock")));
564 fail("Expected exception");
565 } catch (ExecutionException e) {
566 assertTrue(e.getCause() instanceof ClusteringRpcException);
567 assertEquals("mock", e.getCause().getMessage());
571 private DOMRpcResult invokeRpc(final DOMRpcService domRpcService, final QName qname, final NormalizedNode input,
572 final FluentFuture<DOMRpcResult> returnFuture)
573 throws InterruptedException, ExecutionException, TimeoutException {
574 topRpcImplementation.init(returnFuture);
575 final ListenableFuture<? extends DOMRpcResult> resultFuture = domRpcService.invokeRpc(qname, input);
577 topRpcImplementation.verify(DOMRpcIdentifier.create(qname), input);
579 return resultFuture.get(5, TimeUnit.SECONDS);
582 private static void testDOMDataBrokerOperations(final DOMDataBroker dataBroker)
583 throws InterruptedException, ExecutionException, TimeoutException {
585 DOMDataTreeWriteTransaction writeTx = dataBroker.newWriteOnlyTransaction();
587 final ContainerNode topNode = Builders.containerBuilder()
588 .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(Top.QNAME)).build();
589 final YangInstanceIdentifier topPath = YangInstanceIdentifier.of(Top.QNAME);
590 writeTx.put(LogicalDatastoreType.CONFIGURATION, topPath, topNode);
592 final QName name = QName.create(TopLevelList.QNAME, "name");
593 final YangInstanceIdentifier listPath = YangInstanceIdentifier.builder(topPath)
594 .node(TopLevelList.QNAME).build();
595 final MapEntryNode listEntryNode = ImmutableNodes.mapEntry(TopLevelList.QNAME, name, "one");
596 final MapNode listNode = ImmutableNodes.mapNodeBuilder(TopLevelList.QNAME).addChild(listEntryNode).build();
597 writeTx.merge(LogicalDatastoreType.CONFIGURATION, listPath, listNode);
598 writeTx.commit().get(5, TimeUnit.SECONDS);
600 verifyDataInStore(dataBroker.newReadWriteTransaction(), YangInstanceIdentifier.builder(listPath)
601 .nodeWithKey(TopLevelList.QNAME, name, "one").build(), listEntryNode);
603 writeTx = dataBroker.newWriteOnlyTransaction();
604 writeTx.delete(LogicalDatastoreType.CONFIGURATION, topPath);
605 writeTx.commit().get(5, TimeUnit.SECONDS);
607 DOMDataTreeReadWriteTransaction readTx = dataBroker.newReadWriteTransaction();
608 assertFalse(readTx.exists(LogicalDatastoreType.CONFIGURATION, topPath).get(5, TimeUnit.SECONDS));
609 assertTrue(readTx.cancel());
612 private static void writeNetconfNode(final String cacheDir, final DataBroker dataBroker) throws Exception {
613 putData(dataBroker, NODE_INSTANCE_ID, new NodeBuilder()
614 .withKey(NODE_INSTANCE_ID.getKey())
615 .addAugmentation(new NetconfNodeBuilder()
616 .setHost(new Host(new IpAddress(new Ipv4Address("127.0.0.1"))))
617 .setPort(new PortNumber(Uint16.valueOf(1234)))
618 .setActorResponseWaitTime(Uint16.valueOf(10))
619 .setTcpOnly(Boolean.TRUE)
620 .setSchemaless(Boolean.FALSE)
621 .setKeepaliveDelay(Uint32.ZERO)
622 .setConnectionTimeoutMillis(Uint32.valueOf(5000))
623 .setDefaultRequestTimeoutMillis(Uint32.valueOf(5000))
624 .setMaxConnectionAttempts(Uint32.ONE)
625 .setCredentials(new LoginPwUnencryptedBuilder()
626 .setLoginPasswordUnencrypted(new LoginPasswordUnencryptedBuilder()
631 .setSchemaCacheDirectory(cacheDir)
636 private static <T extends DataObject> void putData(final DataBroker databroker, final InstanceIdentifier<T> path,
637 final T data) throws Exception {
638 final var writeTx = databroker.newWriteOnlyTransaction();
639 writeTx.put(LogicalDatastoreType.CONFIGURATION, path, data);
640 writeTx.commit().get(5, TimeUnit.SECONDS);
643 private static void verifyDataInStore(final DOMDataTreeReadOperations readTx, final YangInstanceIdentifier path,
644 final NormalizedNode expNode) throws InterruptedException, ExecutionException, TimeoutException {
645 final Optional<NormalizedNode> read = readTx.read(LogicalDatastoreType.CONFIGURATION, path)
646 .get(5, TimeUnit.SECONDS);
647 assertTrue(read.isPresent());
648 assertEquals(expNode, read.get());
650 final Boolean exists = readTx.exists(LogicalDatastoreType.CONFIGURATION, path).get(5, TimeUnit.SECONDS);
654 private static void verifyTopologyNodesCreated(final DataBroker dataBroker) {
655 await().atMost(5, TimeUnit.SECONDS).until(() -> {
656 try (ReadTransaction readTx = dataBroker.newReadOnlyTransaction()) {
657 return readTx.exists(LogicalDatastoreType.OPERATIONAL,
658 NetconfTopologyUtils.createTopologyListPath(TOPOLOGY_ID)).get(3, TimeUnit.SECONDS);
663 private AbstractConcurrentDataBrokerTest newDataBrokerTest() throws Exception {
664 final var dataBrokerTest = new AbstractConcurrentDataBrokerTest(true) {
666 protected Set<YangModuleInfo> getModuleInfos() {
667 return Set.of(BindingReflections.getModuleInfo(NetconfNode.class),
668 BindingReflections.getModuleInfo(NetworkTopology.class),
669 BindingReflections.getModuleInfo(Keystore.class),
674 dataBrokerTest.setup();
676 final var path = NetconfTopologyUtils.createTopologyListPath(TOPOLOGY_ID);
677 putData(dataBrokerTest.getDataBroker(), path, new TopologyBuilder().withKey(path.getKey()).build());
678 return dataBrokerTest;
681 private void awaitMountPointNotPresent(final DOMMountPointService mountPointService) {
682 await().atMost(5, TimeUnit.SECONDS).until(
683 () -> mountPointService.getMountPoint(yangNodeInstanceId).isEmpty());
686 private static DOMDataBroker getDOMDataBroker(final DOMMountPoint mountPoint) {
687 return getMountPointService(mountPoint, DOMDataBroker.class);
690 private static DOMRpcService getDOMRpcService(final DOMMountPoint mountPoint) {
691 return getMountPointService(mountPoint, DOMRpcService.class);
694 private static DOMActionService getDomActionService(final DOMMountPoint mountPoint) {
695 return getMountPointService(mountPoint, DOMActionService.class);
698 private static <T extends DOMService> T getMountPointService(final DOMMountPoint mountPoint,
699 final Class<T> serviceClass) {
700 return mountPoint.getService(serviceClass).orElseThrow();
703 private DOMMountPoint awaitMountPoint(final DOMMountPointService mountPointService) {
704 await().atMost(5, TimeUnit.SECONDS).until(() ->
705 mountPointService.getMountPoint(yangNodeInstanceId).isPresent());
707 return mountPointService.getMountPoint(yangNodeInstanceId).orElseThrow();
710 private RpcDefinition findRpcDefinition(final String rpc) {
711 Module topModule = deviceSchemaContext.findModule(TOP_MODULE_NAME, topModuleInfo.getName().getRevision()).get();
712 RpcDefinition rpcDefinition = null;
713 for (RpcDefinition def: topModule.getRpcs()) {
714 if (def.getQName().getLocalName().equals(rpc)) {
720 assertNotNull(rpc + " rpc not found in " + topModule.getRpcs(), rpcDefinition);
721 return rpcDefinition;
724 private static class TopDOMRpcImplementation implements DOMRpcImplementation {
725 private volatile SettableFuture<Entry<DOMRpcIdentifier, NormalizedNode>> rpcInvokedFuture;
726 private volatile FluentFuture<DOMRpcResult> returnFuture;
729 public FluentFuture<DOMRpcResult> invokeRpc(final DOMRpcIdentifier rpc, final NormalizedNode input) {
730 rpcInvokedFuture.set(Map.entry(rpc, input));
734 void init(final FluentFuture<DOMRpcResult> retFuture) {
735 returnFuture = retFuture;
736 rpcInvokedFuture = SettableFuture.create();
739 void verify(final DOMRpcIdentifier expRpc, final NormalizedNode expInput)
740 throws InterruptedException, ExecutionException, TimeoutException {
741 final Entry<DOMRpcIdentifier, NormalizedNode> actual = rpcInvokedFuture.get(5, TimeUnit.SECONDS);
742 assertEquals(expRpc, actual.getKey());
743 assertEquals(expInput, actual.getValue());