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.NetconfDeviceSchema;
104 import org.opendaylight.netconf.sal.connect.netconf.listener.NetconfDeviceCapabilities;
105 import org.opendaylight.netconf.sal.connect.netconf.listener.NetconfSessionPreferences;
106 import org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil;
107 import org.opendaylight.netconf.topology.singleton.impl.utils.ClusteringRpcException;
108 import org.opendaylight.netconf.topology.singleton.impl.utils.NetconfTopologySetup;
109 import org.opendaylight.netconf.topology.singleton.impl.utils.NetconfTopologyUtils;
110 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Host;
111 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpAddress;
112 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Ipv4Address;
113 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.PortNumber;
114 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.keystore.rev171017.Keystore;
115 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.NetconfNode;
116 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.NetconfNodeBuilder;
117 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.NetconfNodeConnectionStatus;
118 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.credentials.credentials.LoginPwUnencryptedBuilder;
119 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.credentials.credentials.login.pw.unencrypted.LoginPasswordUnencryptedBuilder;
120 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.network.topology.topology.topology.types.TopologyNetconf;
121 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.topology.singleton.config.rev170419.Config;
122 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.topology.singleton.config.rev170419.ConfigBuilder;
123 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.list.rev140701.GetTopInput;
124 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.list.rev140701.GetTopOutputBuilder;
125 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.list.rev140701.PutTopInputBuilder;
126 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.list.rev140701.Top;
127 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.list.rev140701.two.level.list.TopLevelList;
128 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.list.rev140701.two.level.list.TopLevelListBuilder;
129 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.list.rev140701.two.level.list.TopLevelListKey;
130 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NetworkTopology;
131 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NodeId;
132 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.TopologyBuilder;
133 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node;
134 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.NodeBuilder;
135 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.NodeKey;
136 import org.opendaylight.yangtools.rfc8528.data.api.MountPointContext;
137 import org.opendaylight.yangtools.rfc8528.data.util.EmptyMountPointContext;
138 import org.opendaylight.yangtools.util.concurrent.FluentFutures;
139 import org.opendaylight.yangtools.yang.binding.DataObject;
140 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
141 import org.opendaylight.yangtools.yang.binding.KeyedInstanceIdentifier;
142 import org.opendaylight.yangtools.yang.binding.YangModuleInfo;
143 import org.opendaylight.yangtools.yang.common.ErrorTag;
144 import org.opendaylight.yangtools.yang.common.ErrorType;
145 import org.opendaylight.yangtools.yang.common.QName;
146 import org.opendaylight.yangtools.yang.common.Revision;
147 import org.opendaylight.yangtools.yang.common.RpcError;
148 import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
149 import org.opendaylight.yangtools.yang.common.Uint16;
150 import org.opendaylight.yangtools.yang.common.Uint32;
151 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
152 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
153 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
154 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
155 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
156 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
157 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
158 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
159 import org.opendaylight.yangtools.yang.model.api.Module;
160 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
161 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
162 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
163 import org.opendaylight.yangtools.yang.model.repo.spi.PotentialSchemaSource;
164 import org.opendaylight.yangtools.yang.parser.impl.DefaultYangParserFactory;
165 import org.slf4j.Logger;
166 import org.slf4j.LoggerFactory;
169 * Tests netconf mount points end-to-end.
171 * @author Thomas Pantelis
173 @RunWith(MockitoJUnitRunner.StrictStubs.class)
174 public class MountPointEndToEndTest extends AbstractBaseSchemasTest {
175 private static final Logger LOG = LoggerFactory.getLogger(MountPointEndToEndTest.class);
177 private static final String TOP_MODULE_NAME = "opendaylight-mdsal-list-test";
178 private static final String ACTOR_SYSTEM_NAME = "test";
179 private static final String TOPOLOGY_ID = TopologyNetconf.QNAME.getLocalName();
180 private static final @NonNull KeyedInstanceIdentifier<Node, NodeKey> NODE_INSTANCE_ID =
181 NetconfTopologyUtils.createTopologyNodeListPath(new NodeKey(new NodeId("node-id")), TOPOLOGY_ID);
183 private static final String TEST_ROOT_DIRECTORY = "test-cache-root";
184 private static final String TEST_DEFAULT_SUBDIR = "test-schema";
186 @Mock private DOMRpcProviderService mockRpcProviderRegistry;
187 @Mock private RpcProviderService mockRpcProviderService;
188 @Mock private DOMActionProviderService mockActionProviderRegistry;
189 @Mock private NetconfClientDispatcher mockClientDispatcher;
190 @Mock private AAAEncryptionService mockEncryptionService;
191 @Mock private ThreadPool mockThreadPool;
192 @Mock private ScheduledThreadPool mockKeepaliveExecutor;
193 @Mock private DeviceActionFactory deviceActionFactory;
195 @Mock private ActorSystemProvider mockMasterActorSystemProvider;
196 @Mock private DOMMountPointListener masterMountPointListener;
197 private final DOMMountPointService masterMountPointService = new DOMMountPointServiceImpl();
198 private final DOMRpcRouter deviceRpcService = new DOMRpcRouter();
199 private DOMClusterSingletonServiceProviderImpl masterClusterSingletonServiceProvider;
200 private DataBroker masterDataBroker;
201 private DOMDataBroker deviceDOMDataBroker;
202 private ActorSystem masterSystem;
203 private NetconfTopologyManager masterNetconfTopologyManager;
204 private volatile SettableFuture<MasterSalFacade> masterSalFacadeFuture = SettableFuture.create();
206 @Mock private ActorSystemProvider mockSlaveActorSystemProvider;
207 @Mock private ClusterSingletonServiceProvider mockSlaveClusterSingletonServiceProvider;
208 @Mock private ClusterSingletonServiceRegistration mockSlaveClusterSingletonServiceReg;
209 @Mock private DOMMountPointListener slaveMountPointListener;
210 private final DOMMountPointService slaveMountPointService = new DOMMountPointServiceImpl();
211 private DataBroker slaveDataBroker;
212 private ActorSystem slaveSystem;
213 private NetconfTopologyManager slaveNetconfTopologyManager;
214 private final SettableFuture<NetconfTopologyContext> slaveNetconfTopologyContextFuture = SettableFuture.create();
215 private TransactionChain slaveTxChain;
217 private final EventExecutor eventExecutor = GlobalEventExecutor.INSTANCE;
218 private final Config config = new ConfigBuilder().setWriteTransactionIdleTimeout(Uint16.ZERO).build();
219 private EffectiveModelContext deviceSchemaContext;
220 private YangModuleInfo topModuleInfo;
221 private QName putTopRpcSchemaPath;
222 private QName getTopRpcSchemaPath;
223 private BindingNormalizedNodeSerializer bindingToNormalized;
224 private YangInstanceIdentifier yangNodeInstanceId;
225 private final TopDOMRpcImplementation topRpcImplementation = new TopDOMRpcImplementation();
226 private final ContainerNode getTopInput = ImmutableNodes.containerNode(GetTopInput.QNAME);
228 private SchemaResourceManager resourceManager;
231 public void setUp() throws Exception {
234 resourceManager = new DefaultSchemaResourceManager(new DefaultYangParserFactory(), TEST_ROOT_DIRECTORY,
235 TEST_DEFAULT_SUBDIR);
237 topModuleInfo = BindingReflections.getModuleInfo(Top.class);
239 deviceSchemaContext = BindingRuntimeHelpers.createEffectiveModel(Top.class);
241 deviceRpcService.onModelContextUpdated(deviceSchemaContext);
243 putTopRpcSchemaPath = findRpcDefinition("put-top").getQName();
244 getTopRpcSchemaPath = findRpcDefinition("get-top").getQName();
246 deviceRpcService.getRpcProviderService().registerRpcImplementation(topRpcImplementation,
247 DOMRpcIdentifier.create(putTopRpcSchemaPath), DOMRpcIdentifier.create(getTopRpcSchemaPath));
253 yangNodeInstanceId = bindingToNormalized.toYangInstanceIdentifier(NODE_INSTANCE_ID);
255 doReturn(mock(ReconnectFuture.class)).when(mockClientDispatcher).createReconnectingClient(any());
257 LOG.info("****** Setup complete");
260 private static void deleteCacheDir() {
261 FileUtils.deleteQuietly(new File(TEST_ROOT_DIRECTORY));
265 public void tearDown() throws Exception {
267 TestKit.shutdownActorSystem(slaveSystem, true);
268 TestKit.shutdownActorSystem(masterSystem, true);
271 private void setupMaster() throws Exception {
272 final var dataBrokerTest = newDataBrokerTest();
273 masterDataBroker = dataBrokerTest.getDataBroker();
274 deviceDOMDataBroker = dataBrokerTest.getDomBroker();
275 bindingToNormalized = dataBrokerTest.getDataBrokerTestCustomizer().getAdapterContext().currentSerializer();
277 masterSystem = ActorSystem.create(ACTOR_SYSTEM_NAME, ConfigFactory.load().getConfig("Master"));
279 masterClusterSingletonServiceProvider = new DOMClusterSingletonServiceProviderImpl();
280 masterClusterSingletonServiceProvider.initializeProvider();
282 doReturn(masterSystem).when(mockMasterActorSystemProvider).getActorSystem();
284 doReturn(MoreExecutors.newDirectExecutorService()).when(mockThreadPool).getExecutor();
286 final var resources = resourceManager.getSchemaResources(TEST_DEFAULT_SUBDIR, "test");
287 resources.getSchemaRegistry().registerSchemaSource(
288 id -> Futures.immediateFuture(YangTextSchemaSource.delegateForByteSource(id,
289 topModuleInfo.getYangTextByteSource())),
290 PotentialSchemaSource.create(new SourceIdentifier(TOP_MODULE_NAME,
291 topModuleInfo.getName().getRevision().map(Revision::toString).orElse(null)),
292 YangTextSchemaSource.class, 1));
294 masterNetconfTopologyManager = new NetconfTopologyManager(BASE_SCHEMAS, masterDataBroker,
295 mockRpcProviderRegistry, mockActionProviderRegistry, masterClusterSingletonServiceProvider,
296 mockKeepaliveExecutor, mockThreadPool, mockMasterActorSystemProvider, eventExecutor,
297 mockClientDispatcher, TOPOLOGY_ID, config, masterMountPointService, mockEncryptionService,
298 mockRpcProviderService, deviceActionFactory, resourceManager) {
300 protected NetconfTopologyContext newNetconfTopologyContext(final NetconfTopologySetup setup,
301 final ServiceGroupIdentifier serviceGroupIdent, final Timeout actorResponseWaitTime,
302 final DeviceActionFactory deviceActionFact) {
303 final var context = super.newNetconfTopologyContext(setup, serviceGroupIdent, actorResponseWaitTime,
306 final var spiedContext = spy(context);
307 doAnswer(invocation -> {
308 final var spiedFacade = (MasterSalFacade) spy(invocation.callRealMethod());
309 doReturn(deviceDOMDataBroker).when(spiedFacade)
310 .newDeviceDataBroker(any(MountPointContext.class), any(NetconfSessionPreferences.class));
311 masterSalFacadeFuture.set(spiedFacade);
313 }).when(spiedContext).newMasterSalFacade();
319 masterNetconfTopologyManager.init();
321 verifyTopologyNodesCreated(masterDataBroker);
324 private void setupSlave() throws Exception {
325 AbstractConcurrentDataBrokerTest dataBrokerTest = newDataBrokerTest();
326 slaveDataBroker = dataBrokerTest.getDataBroker();
328 slaveSystem = ActorSystem.create(ACTOR_SYSTEM_NAME, ConfigFactory.load().getConfig("Slave"));
330 doReturn(slaveSystem).when(mockSlaveActorSystemProvider).getActorSystem();
332 doReturn(mockSlaveClusterSingletonServiceReg).when(mockSlaveClusterSingletonServiceProvider)
333 .registerClusterSingletonService(any());
335 slaveNetconfTopologyManager = new NetconfTopologyManager(BASE_SCHEMAS, slaveDataBroker, mockRpcProviderRegistry,
336 mockActionProviderRegistry, mockSlaveClusterSingletonServiceProvider, mockKeepaliveExecutor, mockThreadPool,
337 mockSlaveActorSystemProvider, eventExecutor, mockClientDispatcher, TOPOLOGY_ID, config,
338 slaveMountPointService, mockEncryptionService, mockRpcProviderService, deviceActionFactory,
341 protected NetconfTopologyContext newNetconfTopologyContext(final NetconfTopologySetup setup,
342 final ServiceGroupIdentifier serviceGroupIdent, final Timeout actorResponseWaitTime,
343 final DeviceActionFactory actionFactory) {
344 NetconfTopologyContext spiedContext = spy(super.newNetconfTopologyContext(setup, serviceGroupIdent,
345 actorResponseWaitTime, actionFactory));
347 slaveNetconfTopologyContextFuture.set(spiedContext);
352 slaveNetconfTopologyManager.init();
354 verifyTopologyNodesCreated(slaveDataBroker);
356 slaveTxChain = slaveDataBroker.createTransactionChain(new TransactionChainListener() {
358 public void onTransactionChainSuccessful(final TransactionChain chain) {
362 public void onTransactionChainFailed(final TransactionChain chain, final Transaction transaction,
363 final Throwable cause) {
364 LOG.error("Slave transaction chain failed", cause);
370 public void test() throws Exception {
375 final MasterSalFacade masterSalFacade = testMasterNodeUpdated();
377 testMasterDisconnected(masterSalFacade);
382 private MasterSalFacade testMaster() throws Exception {
383 LOG.info("****** Testing master");
385 writeNetconfNode(TEST_DEFAULT_SUBDIR, masterDataBroker);
387 final var masterSalFacade = masterSalFacadeFuture.get(5, TimeUnit.SECONDS);
388 masterSalFacade.onDeviceConnected(new NetconfDeviceSchema(NetconfDeviceCapabilities.empty(),
389 new EmptyMountPointContext(deviceSchemaContext)),
390 NetconfSessionPreferences.fromStrings(
391 List.of(NetconfMessageTransformUtil.NETCONF_CANDIDATE_URI.toString())),
392 deviceRpcService.getRpcService());
394 final var masterMountPoint = awaitMountPoint(masterMountPointService);
396 LOG.info("****** Testing master DOMDataBroker operations");
398 testDOMDataBrokerOperations(getDOMDataBroker(masterMountPoint));
400 LOG.info("****** Testing master DOMRpcService");
402 testDOMRpcService(getDOMRpcService(masterMountPoint));
403 return masterSalFacade;
406 private void testSlave() throws Exception {
407 LOG.info("****** Testing slave");
409 writeNetconfNode("slave", slaveDataBroker);
411 verify(mockSlaveClusterSingletonServiceProvider, timeout(5000)).registerClusterSingletonService(any());
413 // Since the master and slave use separate DataBrokers we need to copy the master's oper node to the slave.
414 // This is essentially what happens in a clustered environment but we'll use a DTCL here.
416 masterDataBroker.registerDataTreeChangeListener(
417 DataTreeIdentifier.create(LogicalDatastoreType.OPERATIONAL, NODE_INSTANCE_ID), changes -> {
418 final WriteTransaction slaveTx = slaveTxChain.newWriteOnlyTransaction();
419 for (DataTreeModification<Node> dataTreeModification : changes) {
420 DataObjectModification<Node> rootNode = dataTreeModification.getRootNode();
421 InstanceIdentifier<Node> path = dataTreeModification.getRootPath().getRootIdentifier();
422 switch (rootNode.getModificationType()) {
424 case SUBTREE_MODIFIED:
425 slaveTx.merge(LogicalDatastoreType.OPERATIONAL, path, rootNode.getDataAfter());
428 slaveTx.delete(LogicalDatastoreType.OPERATIONAL, path);
438 DOMMountPoint slaveMountPoint = awaitMountPoint(slaveMountPointService);
440 final NetconfTopologyContext slaveNetconfTopologyContext =
441 slaveNetconfTopologyContextFuture.get(5, TimeUnit.SECONDS);
442 verify(slaveNetconfTopologyContext, never()).newMasterSalFacade();
444 LOG.info("****** Testing slave DOMDataBroker operations");
446 testDOMDataBrokerOperations(getDOMDataBroker(slaveMountPoint));
448 LOG.info("****** Testing slave DOMRpcService");
450 testDOMRpcService(getDOMRpcService(slaveMountPoint));
453 private MasterSalFacade testMasterNodeUpdated() throws Exception {
454 LOG.info("****** Testing update master node");
456 masterMountPointService.registerProvisionListener(masterMountPointListener);
457 slaveMountPointService.registerProvisionListener(slaveMountPointListener);
459 masterSalFacadeFuture = SettableFuture.create();
460 writeNetconfNode(TEST_DEFAULT_SUBDIR, masterDataBroker);
462 verify(masterMountPointListener, timeout(5000)).onMountPointRemoved(yangNodeInstanceId);
464 final var masterSalFacade = masterSalFacadeFuture.get(5, TimeUnit.SECONDS);
465 masterSalFacade.onDeviceConnected(new NetconfDeviceSchema(NetconfDeviceCapabilities.empty(),
466 new EmptyMountPointContext(deviceSchemaContext)), NetconfSessionPreferences.fromStrings(List.of(
467 NetconfMessageTransformUtil.NETCONF_CANDIDATE_URI.toString())),
468 deviceRpcService.getRpcService());
470 verify(masterMountPointListener, timeout(5000)).onMountPointCreated(yangNodeInstanceId);
472 verify(slaveMountPointListener, timeout(5000)).onMountPointRemoved(yangNodeInstanceId);
473 verify(slaveMountPointListener, timeout(5000)).onMountPointCreated(yangNodeInstanceId);
475 return masterSalFacade;
478 private void testMasterDisconnected(final MasterSalFacade masterSalFacade) throws Exception {
479 LOG.info("****** Testing master disconnected");
481 masterSalFacade.onDeviceDisconnected();
483 awaitMountPointNotPresent(masterMountPointService);
485 await().atMost(5, TimeUnit.SECONDS).until(() -> {
486 try (ReadTransaction readTx = masterDataBroker.newReadOnlyTransaction()) {
487 Optional<Node> node = readTx.read(LogicalDatastoreType.OPERATIONAL,
488 NODE_INSTANCE_ID).get(5, TimeUnit.SECONDS);
489 assertTrue(node.isPresent());
490 final NetconfNode netconfNode = node.get().augmentation(NetconfNode.class);
491 return netconfNode.getConnectionStatus() != NetconfNodeConnectionStatus.ConnectionStatus.Connected;
495 awaitMountPointNotPresent(slaveMountPointService);
498 private void testCleanup() throws Exception {
499 LOG.info("****** Testing cleanup");
501 slaveNetconfTopologyManager.close();
502 verify(mockSlaveClusterSingletonServiceReg).close();
505 private void testDOMRpcService(final DOMRpcService domRpcService)
506 throws InterruptedException, ExecutionException, TimeoutException {
507 testPutTopRpc(domRpcService, new DefaultDOMRpcResult((NormalizedNode)null));
508 testPutTopRpc(domRpcService, null);
509 testPutTopRpc(domRpcService, new DefaultDOMRpcResult(ImmutableList.of(
510 RpcResultBuilder.newError(ErrorType.APPLICATION, new ErrorTag("tag1"), "error1"),
511 RpcResultBuilder.newError(ErrorType.APPLICATION, new ErrorTag("tag2"), "error2"))));
513 testGetTopRpc(domRpcService, new DefaultDOMRpcResult(bindingToNormalized.toNormalizedNodeRpcData(
514 new GetTopOutputBuilder().setTopLevelList(oneTopLevelList()).build())));
516 testFailedRpc(domRpcService, getTopRpcSchemaPath, getTopInput);
519 private void testPutTopRpc(final DOMRpcService domRpcService, final DOMRpcResult result)
520 throws InterruptedException, ExecutionException, TimeoutException {
521 ContainerNode putTopInput = bindingToNormalized.toNormalizedNodeRpcData(
522 new PutTopInputBuilder().setTopLevelList(oneTopLevelList()).build());
523 testRpc(domRpcService, putTopRpcSchemaPath, putTopInput, result);
526 private static Map<TopLevelListKey, TopLevelList> oneTopLevelList() {
527 final TopLevelListKey key = new TopLevelListKey("one");
528 return ImmutableMap.of(key, new TopLevelListBuilder().withKey(key).build());
531 private void testGetTopRpc(final DOMRpcService domRpcService, final DOMRpcResult result)
532 throws InterruptedException, ExecutionException, TimeoutException {
533 testRpc(domRpcService, getTopRpcSchemaPath, getTopInput, result);
536 private void testRpc(final DOMRpcService domRpcService, final QName qname, final NormalizedNode input,
537 final DOMRpcResult result) throws InterruptedException, ExecutionException, TimeoutException {
538 final FluentFuture<DOMRpcResult> future = result == null ? FluentFutures.immediateNullFluentFuture()
539 : FluentFutures.immediateFluentFuture(result);
540 final DOMRpcResult actual = invokeRpc(domRpcService, qname, input, future);
541 if (result == null) {
546 assertNotNull(actual);
547 assertEquals(result.getResult(), actual.getResult());
549 assertEquals(result.getErrors().size(), actual.getErrors().size());
550 Iterator<? extends RpcError> iter1 = result.getErrors().iterator();
551 Iterator<? extends RpcError> iter2 = actual.getErrors().iterator();
552 while (iter1.hasNext() && iter2.hasNext()) {
553 RpcError err1 = iter1.next();
554 RpcError err2 = iter2.next();
555 assertEquals(err1.getErrorType(), err2.getErrorType());
556 assertEquals(err1.getTag(), err2.getTag());
557 assertEquals(err1.getMessage(), err2.getMessage());
558 assertEquals(err1.getSeverity(), err2.getSeverity());
559 assertEquals(err1.getApplicationTag(), err2.getApplicationTag());
560 assertEquals(err1.getInfo(), err2.getInfo());
564 private void testFailedRpc(final DOMRpcService domRpcService, final QName qname, final NormalizedNode input)
565 throws InterruptedException, TimeoutException {
567 invokeRpc(domRpcService, qname, input, FluentFutures.immediateFailedFluentFuture(
568 new ClusteringRpcException("mock")));
569 fail("Expected exception");
570 } catch (ExecutionException e) {
571 assertTrue(e.getCause() instanceof ClusteringRpcException);
572 assertEquals("mock", e.getCause().getMessage());
576 private DOMRpcResult invokeRpc(final DOMRpcService domRpcService, final QName qname, final NormalizedNode input,
577 final FluentFuture<DOMRpcResult> returnFuture)
578 throws InterruptedException, ExecutionException, TimeoutException {
579 topRpcImplementation.init(returnFuture);
580 final ListenableFuture<? extends DOMRpcResult> resultFuture = domRpcService.invokeRpc(qname, input);
582 topRpcImplementation.verify(DOMRpcIdentifier.create(qname), input);
584 return resultFuture.get(5, TimeUnit.SECONDS);
587 private static void testDOMDataBrokerOperations(final DOMDataBroker dataBroker)
588 throws InterruptedException, ExecutionException, TimeoutException {
590 DOMDataTreeWriteTransaction writeTx = dataBroker.newWriteOnlyTransaction();
592 final ContainerNode topNode = Builders.containerBuilder()
593 .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(Top.QNAME)).build();
594 final YangInstanceIdentifier topPath = YangInstanceIdentifier.of(Top.QNAME);
595 writeTx.put(LogicalDatastoreType.CONFIGURATION, topPath, topNode);
597 final QName name = QName.create(TopLevelList.QNAME, "name");
598 final YangInstanceIdentifier listPath = YangInstanceIdentifier.builder(topPath)
599 .node(TopLevelList.QNAME).build();
600 final MapEntryNode listEntryNode = ImmutableNodes.mapEntry(TopLevelList.QNAME, name, "one");
601 final MapNode listNode = ImmutableNodes.mapNodeBuilder(TopLevelList.QNAME).addChild(listEntryNode).build();
602 writeTx.merge(LogicalDatastoreType.CONFIGURATION, listPath, listNode);
603 writeTx.commit().get(5, TimeUnit.SECONDS);
605 verifyDataInStore(dataBroker.newReadWriteTransaction(), YangInstanceIdentifier.builder(listPath)
606 .nodeWithKey(TopLevelList.QNAME, name, "one").build(), listEntryNode);
608 writeTx = dataBroker.newWriteOnlyTransaction();
609 writeTx.delete(LogicalDatastoreType.CONFIGURATION, topPath);
610 writeTx.commit().get(5, TimeUnit.SECONDS);
612 DOMDataTreeReadWriteTransaction readTx = dataBroker.newReadWriteTransaction();
613 assertFalse(readTx.exists(LogicalDatastoreType.CONFIGURATION, topPath).get(5, TimeUnit.SECONDS));
614 assertTrue(readTx.cancel());
617 private static void writeNetconfNode(final String cacheDir, final DataBroker dataBroker) throws Exception {
618 putData(dataBroker, NODE_INSTANCE_ID, 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)
641 private static <T extends DataObject> void putData(final DataBroker databroker, final InstanceIdentifier<T> path,
642 final T data) throws Exception {
643 final var writeTx = databroker.newWriteOnlyTransaction();
644 writeTx.put(LogicalDatastoreType.CONFIGURATION, path, data);
645 writeTx.commit().get(5, TimeUnit.SECONDS);
648 private static void verifyDataInStore(final DOMDataTreeReadOperations readTx, final YangInstanceIdentifier path,
649 final NormalizedNode expNode) throws InterruptedException, ExecutionException, TimeoutException {
650 final Optional<NormalizedNode> read = readTx.read(LogicalDatastoreType.CONFIGURATION, path)
651 .get(5, TimeUnit.SECONDS);
652 assertTrue(read.isPresent());
653 assertEquals(expNode, read.get());
655 final Boolean exists = readTx.exists(LogicalDatastoreType.CONFIGURATION, path).get(5, TimeUnit.SECONDS);
659 private static void verifyTopologyNodesCreated(final DataBroker dataBroker) {
660 await().atMost(5, TimeUnit.SECONDS).until(() -> {
661 try (ReadTransaction readTx = dataBroker.newReadOnlyTransaction()) {
662 return readTx.exists(LogicalDatastoreType.OPERATIONAL,
663 NetconfTopologyUtils.createTopologyListPath(TOPOLOGY_ID)).get(3, TimeUnit.SECONDS);
668 private AbstractConcurrentDataBrokerTest newDataBrokerTest() throws Exception {
669 final var dataBrokerTest = new AbstractConcurrentDataBrokerTest(true) {
671 protected Set<YangModuleInfo> getModuleInfos() {
672 return Set.of(BindingReflections.getModuleInfo(NetconfNode.class),
673 BindingReflections.getModuleInfo(NetworkTopology.class),
674 BindingReflections.getModuleInfo(Keystore.class),
679 dataBrokerTest.setup();
681 final var path = NetconfTopologyUtils.createTopologyListPath(TOPOLOGY_ID);
682 putData(dataBrokerTest.getDataBroker(), path, new TopologyBuilder().withKey(path.getKey()).build());
683 return dataBrokerTest;
686 private void awaitMountPointNotPresent(final DOMMountPointService mountPointService) {
687 await().atMost(5, TimeUnit.SECONDS).until(
688 () -> mountPointService.getMountPoint(yangNodeInstanceId).isEmpty());
691 private static DOMDataBroker getDOMDataBroker(final DOMMountPoint mountPoint) {
692 return getMountPointService(mountPoint, DOMDataBroker.class);
695 private static DOMRpcService getDOMRpcService(final DOMMountPoint mountPoint) {
696 return getMountPointService(mountPoint, DOMRpcService.class);
699 private static DOMActionService getDomActionService(final DOMMountPoint mountPoint) {
700 return getMountPointService(mountPoint, DOMActionService.class);
703 private static <T extends DOMService> T getMountPointService(final DOMMountPoint mountPoint,
704 final Class<T> serviceClass) {
705 return mountPoint.getService(serviceClass).orElseThrow();
708 private DOMMountPoint awaitMountPoint(final DOMMountPointService mountPointService) {
709 await().atMost(5, TimeUnit.SECONDS).until(() ->
710 mountPointService.getMountPoint(yangNodeInstanceId).isPresent());
712 return mountPointService.getMountPoint(yangNodeInstanceId).orElseThrow();
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(Map.entry(rpc, input));
739 void init(final FluentFuture<DOMRpcResult> retFuture) {
740 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());