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.DOMRpcAvailabilityListener;
86 import org.opendaylight.mdsal.dom.api.DOMRpcIdentifier;
87 import org.opendaylight.mdsal.dom.api.DOMRpcImplementation;
88 import org.opendaylight.mdsal.dom.api.DOMRpcProviderService;
89 import org.opendaylight.mdsal.dom.api.DOMRpcResult;
90 import org.opendaylight.mdsal.dom.api.DOMRpcService;
91 import org.opendaylight.mdsal.dom.api.DOMService;
92 import org.opendaylight.mdsal.dom.broker.DOMMountPointServiceImpl;
93 import org.opendaylight.mdsal.dom.broker.DOMRpcRouter;
94 import org.opendaylight.mdsal.dom.spi.DefaultDOMRpcResult;
95 import org.opendaylight.mdsal.dom.spi.FixedDOMSchemaService;
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.api.xml.XmlNetconfConstants;
101 import org.opendaylight.netconf.client.NetconfClientDispatcher;
102 import org.opendaylight.netconf.client.mdsal.NetconfDeviceSchema;
103 import org.opendaylight.netconf.client.mdsal.api.CredentialProvider;
104 import org.opendaylight.netconf.client.mdsal.api.DeviceActionFactory;
105 import org.opendaylight.netconf.client.mdsal.api.KeyStoreProvider;
106 import org.opendaylight.netconf.client.mdsal.api.RemoteDeviceServices;
107 import org.opendaylight.netconf.client.mdsal.api.RemoteDeviceServices.Rpcs;
108 import org.opendaylight.netconf.client.mdsal.api.SchemaResourceManager;
109 import org.opendaylight.netconf.client.mdsal.impl.DefaultSchemaResourceManager;
110 import org.opendaylight.netconf.nettyutil.ReconnectFuture;
111 import org.opendaylight.netconf.sal.connect.netconf.listener.NetconfDeviceCapabilities;
112 import org.opendaylight.netconf.sal.connect.netconf.listener.NetconfSessionPreferences;
113 import org.opendaylight.netconf.topology.singleton.impl.utils.ClusteringRpcException;
114 import org.opendaylight.netconf.topology.singleton.impl.utils.NetconfTopologySetup;
115 import org.opendaylight.netconf.topology.singleton.impl.utils.NetconfTopologyUtils;
116 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Host;
117 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpAddress;
118 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Ipv4Address;
119 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.PortNumber;
120 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.device.rev230430.ConnectionOper.ConnectionStatus;
121 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.device.rev230430.credentials.credentials.LoginPwUnencryptedBuilder;
122 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.device.rev230430.credentials.credentials.login.pw.unencrypted.LoginPasswordUnencryptedBuilder;
123 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.keystore.rev171017.Keystore;
124 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev221225.NetconfNode;
125 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev221225.NetconfNodeBuilder;
126 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev221225.network.topology.topology.topology.types.TopologyNetconf;
127 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.topology.singleton.config.rev170419.Config;
128 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.topology.singleton.config.rev170419.ConfigBuilder;
129 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.list.rev140701.GetTopInput;
130 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.list.rev140701.GetTopOutputBuilder;
131 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.list.rev140701.PutTopInputBuilder;
132 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.list.rev140701.Top;
133 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.list.rev140701.two.level.list.TopLevelList;
134 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.list.rev140701.two.level.list.TopLevelListBuilder;
135 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.list.rev140701.two.level.list.TopLevelListKey;
136 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NetworkTopology;
137 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NodeId;
138 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.TopologyBuilder;
139 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node;
140 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.NodeBuilder;
141 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.NodeKey;
142 import org.opendaylight.yangtools.concepts.ListenerRegistration;
143 import org.opendaylight.yangtools.rfc8528.data.api.MountPointContext;
144 import org.opendaylight.yangtools.rfc8528.data.util.EmptyMountPointContext;
145 import org.opendaylight.yangtools.util.concurrent.FluentFutures;
146 import org.opendaylight.yangtools.yang.binding.DataObject;
147 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
148 import org.opendaylight.yangtools.yang.binding.KeyedInstanceIdentifier;
149 import org.opendaylight.yangtools.yang.binding.YangModuleInfo;
150 import org.opendaylight.yangtools.yang.common.ErrorTag;
151 import org.opendaylight.yangtools.yang.common.ErrorType;
152 import org.opendaylight.yangtools.yang.common.QName;
153 import org.opendaylight.yangtools.yang.common.Revision;
154 import org.opendaylight.yangtools.yang.common.RpcError;
155 import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
156 import org.opendaylight.yangtools.yang.common.Uint16;
157 import org.opendaylight.yangtools.yang.common.Uint32;
158 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
159 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
160 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
161 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
162 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
163 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
164 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
165 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
166 import org.opendaylight.yangtools.yang.model.api.Module;
167 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
168 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
169 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
170 import org.opendaylight.yangtools.yang.model.repo.spi.PotentialSchemaSource;
171 import org.opendaylight.yangtools.yang.parser.impl.DefaultYangParserFactory;
172 import org.slf4j.Logger;
173 import org.slf4j.LoggerFactory;
176 * Tests netconf mount points end-to-end.
178 * @author Thomas Pantelis
180 @RunWith(MockitoJUnitRunner.StrictStubs.class)
181 public class MountPointEndToEndTest extends AbstractBaseSchemasTest {
182 private static final Logger LOG = LoggerFactory.getLogger(MountPointEndToEndTest.class);
184 private static final String TOP_MODULE_NAME = "opendaylight-mdsal-list-test";
185 private static final String ACTOR_SYSTEM_NAME = "test";
186 private static final String TOPOLOGY_ID = TopologyNetconf.QNAME.getLocalName();
187 private static final @NonNull KeyedInstanceIdentifier<Node, NodeKey> NODE_INSTANCE_ID =
188 NetconfTopologyUtils.createTopologyNodeListPath(new NodeKey(new NodeId("node-id")), TOPOLOGY_ID);
190 private static final String TEST_ROOT_DIRECTORY = "test-cache-root";
191 private static final String TEST_DEFAULT_SUBDIR = "test-schema";
193 @Mock private DOMRpcProviderService mockRpcProviderRegistry;
194 @Mock private RpcProviderService mockRpcProviderService;
195 @Mock private DOMActionProviderService mockActionProviderRegistry;
196 @Mock private NetconfClientDispatcher mockClientDispatcher;
197 @Mock private AAAEncryptionService mockEncryptionService;
198 @Mock private ThreadPool mockThreadPool;
199 @Mock private ScheduledThreadPool mockKeepaliveExecutor;
200 @Mock private DeviceActionFactory deviceActionFactory;
201 @Mock private CredentialProvider credentialProvider;
202 @Mock private KeyStoreProvider keyStoreProvider;
204 @Mock private ActorSystemProvider mockMasterActorSystemProvider;
205 @Mock private DOMMountPointListener masterMountPointListener;
206 private final DOMMountPointService masterMountPointService = new DOMMountPointServiceImpl();
207 private Rpcs.Normalized deviceRpcService;
209 private DOMClusterSingletonServiceProviderImpl masterClusterSingletonServiceProvider;
210 private DataBroker masterDataBroker;
211 private DOMDataBroker deviceDOMDataBroker;
212 private ActorSystem masterSystem;
213 private NetconfTopologyManager masterNetconfTopologyManager;
215 private volatile SettableFuture<MasterSalFacade> masterSalFacadeFuture = SettableFuture.create();
217 @Mock private ActorSystemProvider mockSlaveActorSystemProvider;
218 @Mock private ClusterSingletonServiceProvider mockSlaveClusterSingletonServiceProvider;
219 @Mock private ClusterSingletonServiceRegistration mockSlaveClusterSingletonServiceReg;
220 @Mock private DOMMountPointListener slaveMountPointListener;
221 private final DOMMountPointService slaveMountPointService = new DOMMountPointServiceImpl();
222 private DataBroker slaveDataBroker;
223 private ActorSystem slaveSystem;
224 private NetconfTopologyManager slaveNetconfTopologyManager;
225 private final SettableFuture<NetconfTopologyContext> slaveNetconfTopologyContextFuture = SettableFuture.create();
226 private TransactionChain slaveTxChain;
228 private final EventExecutor eventExecutor = GlobalEventExecutor.INSTANCE;
229 private final Config config = new ConfigBuilder().setWriteTransactionIdleTimeout(Uint16.ZERO).build();
230 private EffectiveModelContext deviceSchemaContext;
231 private YangModuleInfo topModuleInfo;
232 private QName putTopRpcSchemaPath;
233 private QName getTopRpcSchemaPath;
234 private BindingNormalizedNodeSerializer bindingToNormalized;
235 private YangInstanceIdentifier yangNodeInstanceId;
236 private final TopDOMRpcImplementation topRpcImplementation = new TopDOMRpcImplementation();
237 private final ContainerNode getTopInput = ImmutableNodes.containerNode(GetTopInput.QNAME);
239 private SchemaResourceManager resourceManager;
242 public void setUp() throws Exception {
245 resourceManager = new DefaultSchemaResourceManager(new DefaultYangParserFactory(), TEST_ROOT_DIRECTORY,
246 TEST_DEFAULT_SUBDIR);
248 topModuleInfo = BindingReflections.getModuleInfo(Top.class);
250 deviceSchemaContext = BindingRuntimeHelpers.createEffectiveModel(Top.class);
252 final var router = new DOMRpcRouter(FixedDOMSchemaService.of(deviceSchemaContext));
254 putTopRpcSchemaPath = findRpcDefinition("put-top").getQName();
255 getTopRpcSchemaPath = findRpcDefinition("get-top").getQName();
257 router.getRpcProviderService().registerRpcImplementation(topRpcImplementation,
258 DOMRpcIdentifier.create(putTopRpcSchemaPath), DOMRpcIdentifier.create(getTopRpcSchemaPath));
260 final var rpcService = router.getRpcService();
261 deviceRpcService = new Rpcs.Normalized() {
263 public ListenableFuture<? extends DOMRpcResult> invokeRpc(final QName type, final ContainerNode input) {
264 return rpcService.invokeRpc(type, input);
268 public <T extends DOMRpcAvailabilityListener> ListenerRegistration<T> registerRpcListener(
270 return rpcService.registerRpcListener(listener);
278 yangNodeInstanceId = bindingToNormalized.toYangInstanceIdentifier(NODE_INSTANCE_ID);
280 doReturn(mock(ReconnectFuture.class)).when(mockClientDispatcher).createReconnectingClient(any());
282 LOG.info("****** Setup complete");
285 private static void deleteCacheDir() {
286 FileUtils.deleteQuietly(new File(TEST_ROOT_DIRECTORY));
290 public void tearDown() throws Exception {
292 TestKit.shutdownActorSystem(slaveSystem, true);
293 TestKit.shutdownActorSystem(masterSystem, true);
296 private void setupMaster() throws Exception {
297 final var dataBrokerTest = newDataBrokerTest();
298 masterDataBroker = dataBrokerTest.getDataBroker();
299 deviceDOMDataBroker = dataBrokerTest.getDomBroker();
300 bindingToNormalized = dataBrokerTest.getDataBrokerTestCustomizer().getAdapterContext().currentSerializer();
302 masterSystem = ActorSystem.create(ACTOR_SYSTEM_NAME, ConfigFactory.load().getConfig("Master"));
304 masterClusterSingletonServiceProvider = new DOMClusterSingletonServiceProviderImpl();
305 masterClusterSingletonServiceProvider.initializeProvider();
307 doReturn(masterSystem).when(mockMasterActorSystemProvider).getActorSystem();
309 doReturn(MoreExecutors.newDirectExecutorService()).when(mockThreadPool).getExecutor();
311 final var resources = resourceManager.getSchemaResources(TEST_DEFAULT_SUBDIR, "test");
312 resources.getSchemaRegistry().registerSchemaSource(
313 id -> Futures.immediateFuture(YangTextSchemaSource.delegateForByteSource(id,
314 topModuleInfo.getYangTextByteSource())),
315 PotentialSchemaSource.create(new SourceIdentifier(TOP_MODULE_NAME,
316 topModuleInfo.getName().getRevision().map(Revision::toString).orElse(null)),
317 YangTextSchemaSource.class, 1));
319 masterNetconfTopologyManager = new NetconfTopologyManager(BASE_SCHEMAS, masterDataBroker,
320 mockRpcProviderRegistry, mockActionProviderRegistry, masterClusterSingletonServiceProvider,
321 mockKeepaliveExecutor, mockThreadPool, mockMasterActorSystemProvider, eventExecutor,
322 mockClientDispatcher, TOPOLOGY_ID, config, masterMountPointService, mockEncryptionService,
323 mockRpcProviderService, deviceActionFactory, resourceManager, credentialProvider, keyStoreProvider) {
325 protected NetconfTopologyContext newNetconfTopologyContext(final NetconfTopologySetup setup,
326 final ServiceGroupIdentifier serviceGroupIdent, final Timeout actorResponseWaitTime,
327 final DeviceActionFactory deviceActionFact) {
328 final var context = super.newNetconfTopologyContext(setup, serviceGroupIdent, actorResponseWaitTime,
331 final var spiedContext = spy(context);
332 doAnswer(invocation -> {
333 final var spiedFacade = (MasterSalFacade) spy(invocation.callRealMethod());
334 doReturn(deviceDOMDataBroker).when(spiedFacade)
335 .newDeviceDataBroker(any(MountPointContext.class), any(NetconfSessionPreferences.class));
336 masterSalFacadeFuture.set(spiedFacade);
338 }).when(spiedContext).newMasterSalFacade();
344 masterNetconfTopologyManager.init();
346 verifyTopologyNodesCreated(masterDataBroker);
349 private void setupSlave() throws Exception {
350 AbstractConcurrentDataBrokerTest dataBrokerTest = newDataBrokerTest();
351 slaveDataBroker = dataBrokerTest.getDataBroker();
353 slaveSystem = ActorSystem.create(ACTOR_SYSTEM_NAME, ConfigFactory.load().getConfig("Slave"));
355 doReturn(slaveSystem).when(mockSlaveActorSystemProvider).getActorSystem();
357 doReturn(mockSlaveClusterSingletonServiceReg).when(mockSlaveClusterSingletonServiceProvider)
358 .registerClusterSingletonService(any());
360 slaveNetconfTopologyManager = new NetconfTopologyManager(BASE_SCHEMAS, slaveDataBroker, mockRpcProviderRegistry,
361 mockActionProviderRegistry, mockSlaveClusterSingletonServiceProvider, mockKeepaliveExecutor, mockThreadPool,
362 mockSlaveActorSystemProvider, eventExecutor, mockClientDispatcher, TOPOLOGY_ID, config,
363 slaveMountPointService, mockEncryptionService, mockRpcProviderService, deviceActionFactory,
364 resourceManager, credentialProvider, keyStoreProvider) {
366 protected NetconfTopologyContext newNetconfTopologyContext(final NetconfTopologySetup setup,
367 final ServiceGroupIdentifier serviceGroupIdent, final Timeout actorResponseWaitTime,
368 final DeviceActionFactory actionFactory) {
369 NetconfTopologyContext spiedContext = spy(super.newNetconfTopologyContext(setup, serviceGroupIdent,
370 actorResponseWaitTime, actionFactory));
372 slaveNetconfTopologyContextFuture.set(spiedContext);
377 slaveNetconfTopologyManager.init();
379 verifyTopologyNodesCreated(slaveDataBroker);
381 slaveTxChain = slaveDataBroker.createTransactionChain(new TransactionChainListener() {
383 public void onTransactionChainSuccessful(final TransactionChain chain) {
387 public void onTransactionChainFailed(final TransactionChain chain, final Transaction transaction,
388 final Throwable cause) {
389 LOG.error("Slave transaction chain failed", cause);
395 public void test() throws Exception {
400 final MasterSalFacade masterSalFacade = testMasterNodeUpdated();
402 testMasterDisconnected(masterSalFacade);
407 private MasterSalFacade testMaster() throws Exception {
408 LOG.info("****** Testing master");
410 writeNetconfNode(TEST_DEFAULT_SUBDIR, masterDataBroker);
412 final var masterSalFacade = masterSalFacadeFuture.get(5, TimeUnit.SECONDS);
413 masterSalFacade.onDeviceConnected(new NetconfDeviceSchema(NetconfDeviceCapabilities.empty(),
414 new EmptyMountPointContext(deviceSchemaContext)),
415 NetconfSessionPreferences.fromStrings(
416 List.of(XmlNetconfConstants.URN_IETF_PARAMS_NETCONF_CAPABILITY_CANDIDATE_1_0)),
417 new RemoteDeviceServices(deviceRpcService, null));
419 final var masterMountPoint = awaitMountPoint(masterMountPointService);
421 LOG.info("****** Testing master DOMDataBroker operations");
423 testDOMDataBrokerOperations(getDOMDataBroker(masterMountPoint));
425 LOG.info("****** Testing master DOMRpcService");
427 testDOMRpcService(getDOMRpcService(masterMountPoint));
428 return masterSalFacade;
431 private void testSlave() throws Exception {
432 LOG.info("****** Testing slave");
434 writeNetconfNode("slave", slaveDataBroker);
436 verify(mockSlaveClusterSingletonServiceProvider, timeout(5000)).registerClusterSingletonService(any());
438 // Since the master and slave use separate DataBrokers we need to copy the master's oper node to the slave.
439 // This is essentially what happens in a clustered environment but we'll use a DTCL here.
441 masterDataBroker.registerDataTreeChangeListener(
442 DataTreeIdentifier.create(LogicalDatastoreType.OPERATIONAL, NODE_INSTANCE_ID), changes -> {
443 final WriteTransaction slaveTx = slaveTxChain.newWriteOnlyTransaction();
444 for (DataTreeModification<Node> dataTreeModification : changes) {
445 DataObjectModification<Node> rootNode = dataTreeModification.getRootNode();
446 InstanceIdentifier<Node> path = dataTreeModification.getRootPath().getRootIdentifier();
447 switch (rootNode.getModificationType()) {
449 case SUBTREE_MODIFIED:
450 slaveTx.merge(LogicalDatastoreType.OPERATIONAL, path, rootNode.getDataAfter());
453 slaveTx.delete(LogicalDatastoreType.OPERATIONAL, path);
463 DOMMountPoint slaveMountPoint = awaitMountPoint(slaveMountPointService);
465 final NetconfTopologyContext slaveNetconfTopologyContext =
466 slaveNetconfTopologyContextFuture.get(5, TimeUnit.SECONDS);
467 verify(slaveNetconfTopologyContext, never()).newMasterSalFacade();
469 LOG.info("****** Testing slave DOMDataBroker operations");
471 testDOMDataBrokerOperations(getDOMDataBroker(slaveMountPoint));
473 LOG.info("****** Testing slave DOMRpcService");
475 testDOMRpcService(getDOMRpcService(slaveMountPoint));
478 private MasterSalFacade testMasterNodeUpdated() throws Exception {
479 LOG.info("****** Testing update master node");
481 masterMountPointService.registerProvisionListener(masterMountPointListener);
482 slaveMountPointService.registerProvisionListener(slaveMountPointListener);
484 masterSalFacadeFuture = SettableFuture.create();
485 writeNetconfNode(TEST_DEFAULT_SUBDIR, masterDataBroker);
487 verify(masterMountPointListener, timeout(5000)).onMountPointRemoved(yangNodeInstanceId);
489 final var masterSalFacade = masterSalFacadeFuture.get(5, TimeUnit.SECONDS);
490 masterSalFacade.onDeviceConnected(
491 new NetconfDeviceSchema(NetconfDeviceCapabilities.empty(), new EmptyMountPointContext(deviceSchemaContext)),
492 NetconfSessionPreferences.fromStrings(List.of(
493 XmlNetconfConstants.URN_IETF_PARAMS_NETCONF_CAPABILITY_CANDIDATE_1_0)),
494 new RemoteDeviceServices(deviceRpcService, null));
496 verify(masterMountPointListener, timeout(5000)).onMountPointCreated(yangNodeInstanceId);
498 verify(slaveMountPointListener, timeout(5000)).onMountPointRemoved(yangNodeInstanceId);
499 verify(slaveMountPointListener, timeout(5000)).onMountPointCreated(yangNodeInstanceId);
501 return masterSalFacade;
504 private void testMasterDisconnected(final MasterSalFacade masterSalFacade) throws Exception {
505 LOG.info("****** Testing master disconnected");
507 masterSalFacade.onDeviceDisconnected();
509 awaitMountPointNotPresent(masterMountPointService);
511 await().atMost(5, TimeUnit.SECONDS).until(() -> {
512 try (ReadTransaction readTx = masterDataBroker.newReadOnlyTransaction()) {
513 Optional<Node> node = readTx.read(LogicalDatastoreType.OPERATIONAL,
514 NODE_INSTANCE_ID).get(5, TimeUnit.SECONDS);
515 assertTrue(node.isPresent());
516 final NetconfNode netconfNode = node.orElseThrow().augmentation(NetconfNode.class);
517 return netconfNode.getConnectionStatus() != ConnectionStatus.Connected;
521 awaitMountPointNotPresent(slaveMountPointService);
524 private void testCleanup() throws Exception {
525 LOG.info("****** Testing cleanup");
527 slaveNetconfTopologyManager.close();
528 verify(mockSlaveClusterSingletonServiceReg).close();
531 private void testDOMRpcService(final DOMRpcService domRpcService)
532 throws InterruptedException, ExecutionException, TimeoutException {
533 testPutTopRpc(domRpcService, new DefaultDOMRpcResult((ContainerNode)null));
534 testPutTopRpc(domRpcService, null);
535 testPutTopRpc(domRpcService, new DefaultDOMRpcResult(ImmutableList.of(
536 RpcResultBuilder.newError(ErrorType.APPLICATION, new ErrorTag("tag1"), "error1"),
537 RpcResultBuilder.newError(ErrorType.APPLICATION, new ErrorTag("tag2"), "error2"))));
539 testGetTopRpc(domRpcService, new DefaultDOMRpcResult(bindingToNormalized.toNormalizedNodeRpcData(
540 new GetTopOutputBuilder().setTopLevelList(oneTopLevelList()).build())));
542 testFailedRpc(domRpcService, getTopRpcSchemaPath, getTopInput);
545 private void testPutTopRpc(final DOMRpcService domRpcService, final DOMRpcResult result)
546 throws InterruptedException, ExecutionException, TimeoutException {
547 ContainerNode putTopInput = bindingToNormalized.toNormalizedNodeRpcData(
548 new PutTopInputBuilder().setTopLevelList(oneTopLevelList()).build());
549 testRpc(domRpcService, putTopRpcSchemaPath, putTopInput, result);
552 private static Map<TopLevelListKey, TopLevelList> oneTopLevelList() {
553 final TopLevelListKey key = new TopLevelListKey("one");
554 return ImmutableMap.of(key, new TopLevelListBuilder().withKey(key).build());
557 private void testGetTopRpc(final DOMRpcService domRpcService, final DOMRpcResult result)
558 throws InterruptedException, ExecutionException, TimeoutException {
559 testRpc(domRpcService, getTopRpcSchemaPath, getTopInput, result);
562 private void testRpc(final DOMRpcService domRpcService, final QName qname, final ContainerNode input,
563 final DOMRpcResult result) throws InterruptedException, ExecutionException, TimeoutException {
564 final FluentFuture<DOMRpcResult> future = result == null ? FluentFutures.immediateNullFluentFuture()
565 : FluentFutures.immediateFluentFuture(result);
566 final DOMRpcResult actual = invokeRpc(domRpcService, qname, input, future);
567 if (result == null) {
572 assertNotNull(actual);
573 assertEquals(result.value(), actual.value());
575 assertEquals(result.errors().size(), actual.errors().size());
576 Iterator<? extends RpcError> iter1 = result.errors().iterator();
577 Iterator<? extends RpcError> iter2 = actual.errors().iterator();
578 while (iter1.hasNext() && iter2.hasNext()) {
579 RpcError err1 = iter1.next();
580 RpcError err2 = iter2.next();
581 assertEquals(err1.getErrorType(), err2.getErrorType());
582 assertEquals(err1.getTag(), err2.getTag());
583 assertEquals(err1.getMessage(), err2.getMessage());
584 assertEquals(err1.getSeverity(), err2.getSeverity());
585 assertEquals(err1.getApplicationTag(), err2.getApplicationTag());
586 assertEquals(err1.getInfo(), err2.getInfo());
590 private void testFailedRpc(final DOMRpcService domRpcService, final QName qname, final ContainerNode input)
591 throws InterruptedException, TimeoutException {
593 invokeRpc(domRpcService, qname, input, Futures.immediateFailedFuture(new ClusteringRpcException("mock")));
594 fail("Expected exception");
595 } catch (ExecutionException e) {
596 assertTrue(e.getCause() instanceof ClusteringRpcException);
597 assertEquals("mock", e.getCause().getMessage());
601 private DOMRpcResult invokeRpc(final DOMRpcService domRpcService, final QName qname, final ContainerNode input,
602 final ListenableFuture<DOMRpcResult> returnFuture)
603 throws InterruptedException, ExecutionException, TimeoutException {
604 topRpcImplementation.init(returnFuture);
605 final ListenableFuture<? extends DOMRpcResult> resultFuture = domRpcService.invokeRpc(qname, input);
607 topRpcImplementation.verify(DOMRpcIdentifier.create(qname), input);
609 return resultFuture.get(5, TimeUnit.SECONDS);
612 private static void testDOMDataBrokerOperations(final DOMDataBroker dataBroker)
613 throws InterruptedException, ExecutionException, TimeoutException {
615 DOMDataTreeWriteTransaction writeTx = dataBroker.newWriteOnlyTransaction();
617 final ContainerNode topNode = Builders.containerBuilder()
618 .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(Top.QNAME)).build();
619 final YangInstanceIdentifier topPath = YangInstanceIdentifier.of(Top.QNAME);
620 writeTx.put(LogicalDatastoreType.CONFIGURATION, topPath, topNode);
622 final QName name = QName.create(TopLevelList.QNAME, "name");
623 final YangInstanceIdentifier listPath = YangInstanceIdentifier.builder(topPath)
624 .node(TopLevelList.QNAME).build();
625 final MapEntryNode listEntryNode = ImmutableNodes.mapEntry(TopLevelList.QNAME, name, "one");
626 final MapNode listNode = ImmutableNodes.mapNodeBuilder(TopLevelList.QNAME).addChild(listEntryNode).build();
627 writeTx.merge(LogicalDatastoreType.CONFIGURATION, listPath, listNode);
628 writeTx.commit().get(5, TimeUnit.SECONDS);
630 verifyDataInStore(dataBroker.newReadWriteTransaction(), YangInstanceIdentifier.builder(listPath)
631 .nodeWithKey(TopLevelList.QNAME, name, "one").build(), listEntryNode);
633 writeTx = dataBroker.newWriteOnlyTransaction();
634 writeTx.delete(LogicalDatastoreType.CONFIGURATION, topPath);
635 writeTx.commit().get(5, TimeUnit.SECONDS);
637 DOMDataTreeReadWriteTransaction readTx = dataBroker.newReadWriteTransaction();
638 assertFalse(readTx.exists(LogicalDatastoreType.CONFIGURATION, topPath).get(5, TimeUnit.SECONDS));
639 assertTrue(readTx.cancel());
642 private static void writeNetconfNode(final String cacheDir, final DataBroker dataBroker) throws Exception {
643 putData(dataBroker, NODE_INSTANCE_ID, new NodeBuilder()
644 .withKey(NODE_INSTANCE_ID.getKey())
645 .addAugmentation(new NetconfNodeBuilder()
646 .setHost(new Host(new IpAddress(new Ipv4Address("127.0.0.1"))))
647 .setPort(new PortNumber(Uint16.valueOf(1234)))
648 .setActorResponseWaitTime(Uint16.valueOf(10))
649 .setTcpOnly(Boolean.TRUE)
650 .setSchemaless(Boolean.FALSE)
651 .setKeepaliveDelay(Uint32.ZERO)
652 .setConnectionTimeoutMillis(Uint32.valueOf(5000))
653 .setDefaultRequestTimeoutMillis(Uint32.valueOf(5000))
654 .setMaxConnectionAttempts(Uint32.ONE)
655 .setCredentials(new LoginPwUnencryptedBuilder()
656 .setLoginPasswordUnencrypted(new LoginPasswordUnencryptedBuilder()
661 .setSchemaCacheDirectory(cacheDir)
666 private static <T extends DataObject> void putData(final DataBroker databroker, final InstanceIdentifier<T> path,
667 final T data) throws Exception {
668 final var writeTx = databroker.newWriteOnlyTransaction();
669 writeTx.put(LogicalDatastoreType.CONFIGURATION, path, data);
670 writeTx.commit().get(5, TimeUnit.SECONDS);
673 private static void verifyDataInStore(final DOMDataTreeReadOperations readTx, final YangInstanceIdentifier path,
674 final NormalizedNode expNode) throws InterruptedException, ExecutionException, TimeoutException {
675 assertEquals(Optional.of(expNode), readTx.read(LogicalDatastoreType.CONFIGURATION, path)
676 .get(5, TimeUnit.SECONDS));
677 assertTrue(readTx.exists(LogicalDatastoreType.CONFIGURATION, path).get(5, TimeUnit.SECONDS));
680 private static void verifyTopologyNodesCreated(final DataBroker dataBroker) {
681 await().atMost(5, TimeUnit.SECONDS).until(() -> {
682 try (ReadTransaction readTx = dataBroker.newReadOnlyTransaction()) {
683 return readTx.exists(LogicalDatastoreType.OPERATIONAL,
684 NetconfTopologyUtils.createTopologyListPath(TOPOLOGY_ID)).get(3, TimeUnit.SECONDS);
689 private AbstractConcurrentDataBrokerTest newDataBrokerTest() throws Exception {
690 final var dataBrokerTest = new AbstractConcurrentDataBrokerTest(true) {
692 protected Set<YangModuleInfo> getModuleInfos() {
693 return Set.of(BindingReflections.getModuleInfo(NetconfNode.class),
694 BindingReflections.getModuleInfo(NetworkTopology.class),
695 BindingReflections.getModuleInfo(Keystore.class),
700 dataBrokerTest.setup();
702 final var path = NetconfTopologyUtils.createTopologyListPath(TOPOLOGY_ID);
703 putData(dataBrokerTest.getDataBroker(), path, new TopologyBuilder().withKey(path.getKey()).build());
704 return dataBrokerTest;
707 private void awaitMountPointNotPresent(final DOMMountPointService mountPointService) {
708 await().atMost(5, TimeUnit.SECONDS).until(
709 () -> mountPointService.getMountPoint(yangNodeInstanceId).isEmpty());
712 private static DOMDataBroker getDOMDataBroker(final DOMMountPoint mountPoint) {
713 return getMountPointService(mountPoint, DOMDataBroker.class);
716 private static DOMRpcService getDOMRpcService(final DOMMountPoint mountPoint) {
717 return getMountPointService(mountPoint, DOMRpcService.class);
720 private static DOMActionService getDomActionService(final DOMMountPoint mountPoint) {
721 return getMountPointService(mountPoint, DOMActionService.class);
724 private static <T extends DOMService> T getMountPointService(final DOMMountPoint mountPoint,
725 final Class<T> serviceClass) {
726 return mountPoint.getService(serviceClass).orElseThrow();
729 private DOMMountPoint awaitMountPoint(final DOMMountPointService mountPointService) {
730 await().atMost(5, TimeUnit.SECONDS).until(() ->
731 mountPointService.getMountPoint(yangNodeInstanceId).isPresent());
733 return mountPointService.getMountPoint(yangNodeInstanceId).orElseThrow();
736 private RpcDefinition findRpcDefinition(final String rpc) {
737 Module topModule = deviceSchemaContext.findModule(TOP_MODULE_NAME, topModuleInfo.getName().getRevision())
739 RpcDefinition rpcDefinition = null;
740 for (RpcDefinition def: topModule.getRpcs()) {
741 if (def.getQName().getLocalName().equals(rpc)) {
747 assertNotNull(rpc + " rpc not found in " + topModule.getRpcs(), rpcDefinition);
748 return rpcDefinition;
751 private static class TopDOMRpcImplementation implements DOMRpcImplementation {
752 private volatile SettableFuture<Entry<DOMRpcIdentifier, NormalizedNode>> rpcInvokedFuture;
753 private volatile ListenableFuture<DOMRpcResult> returnFuture;
756 public ListenableFuture<DOMRpcResult> invokeRpc(final DOMRpcIdentifier rpc, final ContainerNode input) {
757 rpcInvokedFuture.set(Map.entry(rpc, input));
761 void init(final ListenableFuture<DOMRpcResult> retFuture) {
762 returnFuture = retFuture;
763 rpcInvokedFuture = SettableFuture.create();
766 void verify(final DOMRpcIdentifier expRpc, final NormalizedNode expInput)
767 throws InterruptedException, ExecutionException, TimeoutException {
768 final Entry<DOMRpcIdentifier, NormalizedNode> actual = rpcInvokedFuture.get(5, TimeUnit.SECONDS);
769 assertEquals(expRpc, actual.getKey());
770 assertEquals(expInput, actual.getValue());