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.spy;
22 import static org.mockito.Mockito.timeout;
23 import static org.mockito.Mockito.verify;
25 import akka.actor.ActorSystem;
26 import akka.testkit.javadsl.TestKit;
27 import akka.util.Timeout;
28 import com.google.common.collect.ImmutableList;
29 import com.google.common.collect.ImmutableMap;
30 import com.google.common.util.concurrent.FluentFuture;
31 import com.google.common.util.concurrent.Futures;
32 import com.google.common.util.concurrent.ListenableFuture;
33 import com.google.common.util.concurrent.SettableFuture;
34 import com.typesafe.config.ConfigFactory;
36 import java.util.Iterator;
37 import java.util.List;
39 import java.util.Map.Entry;
40 import java.util.Optional;
42 import java.util.concurrent.ExecutionException;
43 import java.util.concurrent.TimeUnit;
44 import java.util.concurrent.TimeoutException;
45 import org.apache.commons.io.FileUtils;
46 import org.eclipse.jdt.annotation.NonNull;
47 import org.junit.After;
48 import org.junit.Before;
49 import org.junit.Test;
50 import org.junit.runner.RunWith;
51 import org.mockito.Mock;
52 import org.mockito.junit.MockitoJUnitRunner;
53 import org.opendaylight.aaa.encrypt.AAAEncryptionService;
54 import org.opendaylight.mdsal.binding.api.DataBroker;
55 import org.opendaylight.mdsal.binding.api.DataObjectModification;
56 import org.opendaylight.mdsal.binding.api.DataTreeIdentifier;
57 import org.opendaylight.mdsal.binding.api.DataTreeModification;
58 import org.opendaylight.mdsal.binding.api.ReadTransaction;
59 import org.opendaylight.mdsal.binding.api.RpcProviderService;
60 import org.opendaylight.mdsal.binding.api.Transaction;
61 import org.opendaylight.mdsal.binding.api.TransactionChain;
62 import org.opendaylight.mdsal.binding.api.TransactionChainListener;
63 import org.opendaylight.mdsal.binding.api.WriteTransaction;
64 import org.opendaylight.mdsal.binding.dom.adapter.test.AbstractConcurrentDataBrokerTest;
65 import org.opendaylight.mdsal.binding.dom.codec.api.BindingNormalizedNodeSerializer;
66 import org.opendaylight.mdsal.binding.runtime.spi.BindingRuntimeHelpers;
67 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
68 import org.opendaylight.mdsal.dom.api.DOMActionService;
69 import org.opendaylight.mdsal.dom.api.DOMDataBroker;
70 import org.opendaylight.mdsal.dom.api.DOMDataTreeReadOperations;
71 import org.opendaylight.mdsal.dom.api.DOMDataTreeReadWriteTransaction;
72 import org.opendaylight.mdsal.dom.api.DOMDataTreeWriteTransaction;
73 import org.opendaylight.mdsal.dom.api.DOMMountPoint;
74 import org.opendaylight.mdsal.dom.api.DOMMountPointListener;
75 import org.opendaylight.mdsal.dom.api.DOMMountPointService;
76 import org.opendaylight.mdsal.dom.api.DOMRpcAvailabilityListener;
77 import org.opendaylight.mdsal.dom.api.DOMRpcIdentifier;
78 import org.opendaylight.mdsal.dom.api.DOMRpcImplementation;
79 import org.opendaylight.mdsal.dom.api.DOMRpcResult;
80 import org.opendaylight.mdsal.dom.api.DOMRpcService;
81 import org.opendaylight.mdsal.dom.api.DOMService;
82 import org.opendaylight.mdsal.dom.broker.DOMMountPointServiceImpl;
83 import org.opendaylight.mdsal.dom.broker.DOMRpcRouter;
84 import org.opendaylight.mdsal.dom.spi.DefaultDOMRpcResult;
85 import org.opendaylight.mdsal.dom.spi.FixedDOMSchemaService;
86 import org.opendaylight.mdsal.singleton.common.api.ClusterSingletonServiceProvider;
87 import org.opendaylight.mdsal.singleton.common.api.ClusterSingletonServiceRegistration;
88 import org.opendaylight.mdsal.singleton.common.api.ServiceGroupIdentifier;
89 import org.opendaylight.mdsal.singleton.dom.impl.DOMClusterSingletonServiceProviderImpl;
90 import org.opendaylight.netconf.api.CapabilityURN;
91 import org.opendaylight.netconf.client.NetconfClientFactory;
92 import org.opendaylight.netconf.client.mdsal.NetconfDeviceCapabilities;
93 import org.opendaylight.netconf.client.mdsal.NetconfDeviceSchema;
94 import org.opendaylight.netconf.client.mdsal.api.CredentialProvider;
95 import org.opendaylight.netconf.client.mdsal.api.DeviceActionFactory;
96 import org.opendaylight.netconf.client.mdsal.api.NetconfSessionPreferences;
97 import org.opendaylight.netconf.client.mdsal.api.RemoteDeviceServices;
98 import org.opendaylight.netconf.client.mdsal.api.RemoteDeviceServices.Rpcs;
99 import org.opendaylight.netconf.client.mdsal.api.SchemaResourceManager;
100 import org.opendaylight.netconf.client.mdsal.api.SslHandlerFactoryProvider;
101 import org.opendaylight.netconf.client.mdsal.impl.DefaultSchemaResourceManager;
102 import org.opendaylight.netconf.common.NetconfTimer;
103 import org.opendaylight.netconf.topology.singleton.impl.utils.ClusteringRpcException;
104 import org.opendaylight.netconf.topology.singleton.impl.utils.NetconfTopologySetup;
105 import org.opendaylight.netconf.topology.singleton.impl.utils.NetconfTopologyUtils;
106 import org.opendaylight.netconf.topology.spi.NetconfClientConfigurationBuilderFactory;
107 import org.opendaylight.netconf.topology.spi.NetconfClientConfigurationBuilderFactoryImpl;
108 import org.opendaylight.netconf.topology.spi.NetconfNodeUtils;
109 import org.opendaylight.netconf.topology.spi.NetconfTopologySchemaAssembler;
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.device.rev240120.ConnectionOper.ConnectionStatus;
115 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.device.rev240120.credentials.credentials.LoginPwUnencryptedBuilder;
116 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.device.rev240120.credentials.credentials.login.pw.unencrypted.LoginPasswordUnencryptedBuilder;
117 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.keystore.rev171017.Keystore;
118 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev231121.NetconfNode;
119 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev231121.NetconfNodeBuilder;
120 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.list.rev140701.GetTopInput;
121 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.list.rev140701.GetTopOutputBuilder;
122 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.list.rev140701.PutTopInputBuilder;
123 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.list.rev140701.Top;
124 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.list.rev140701.two.level.list.TopLevelList;
125 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.list.rev140701.two.level.list.TopLevelListBuilder;
126 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.list.rev140701.two.level.list.TopLevelListKey;
127 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NetworkTopology;
128 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NodeId;
129 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.TopologyBuilder;
130 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node;
131 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.NodeBuilder;
132 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.NodeKey;
133 import org.opendaylight.yangtools.concepts.ListenerRegistration;
134 import org.opendaylight.yangtools.concepts.Registration;
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.MountPointContext;
153 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
154 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
155 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
156 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
157 import org.opendaylight.yangtools.yang.model.api.Module;
158 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
159 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
160 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
161 import org.opendaylight.yangtools.yang.model.repo.spi.PotentialSchemaSource;
162 import org.opendaylight.yangtools.yang.parser.impl.DefaultYangParserFactory;
163 import org.slf4j.Logger;
164 import org.slf4j.LoggerFactory;
167 * Tests netconf mount points end-to-end.
169 * @author Thomas Pantelis
171 @RunWith(MockitoJUnitRunner.StrictStubs.class)
172 public class MountPointEndToEndTest extends AbstractBaseSchemasTest {
173 private static final Logger LOG = LoggerFactory.getLogger(MountPointEndToEndTest.class);
175 private static final String TOP_MODULE_NAME = "opendaylight-mdsal-list-test";
176 private static final String ACTOR_SYSTEM_NAME = "test";
177 private static final String TOPOLOGY_ID = NetconfNodeUtils.DEFAULT_TOPOLOGY_NAME;
178 private static final @NonNull KeyedInstanceIdentifier<Node, NodeKey> NODE_INSTANCE_ID =
179 NetconfTopologyUtils.createTopologyNodeListPath(new NodeKey(new NodeId("node-id")), TOPOLOGY_ID);
181 private static final String TEST_ROOT_DIRECTORY = "test-cache-root";
182 private static final String TEST_DEFAULT_SUBDIR = "test-schema";
185 private RpcProviderService mockRpcProviderService;
187 private Registration mockRpcReg;
189 private NetconfClientFactory mockClientFactory;
191 private AAAEncryptionService mockEncryptionService;
193 private NetconfTimer mockTimer;
195 private DeviceActionFactory deviceActionFactory;
197 private CredentialProvider credentialProvider;
199 private SslHandlerFactoryProvider sslHandlerFactoryProvider;
201 private DOMMountPointListener masterMountPointListener;
202 private final DOMMountPointService masterMountPointService = new DOMMountPointServiceImpl();
203 private Rpcs.Normalized deviceRpcService;
205 private DOMClusterSingletonServiceProviderImpl masterClusterSingletonServiceProvider;
206 private DataBroker masterDataBroker;
207 private DOMDataBroker deviceDOMDataBroker;
208 private ActorSystem masterSystem;
209 private NetconfTopologyManager masterNetconfTopologyManager;
211 private volatile SettableFuture<MasterSalFacade> masterSalFacadeFuture = SettableFuture.create();
214 private ClusterSingletonServiceProvider mockSlaveClusterSingletonServiceProvider;
216 private ClusterSingletonServiceRegistration mockSlaveClusterSingletonServiceReg;
218 private DOMMountPointListener slaveMountPointListener;
219 private final DOMMountPointService slaveMountPointService = new DOMMountPointServiceImpl();
220 private DataBroker slaveDataBroker;
221 private ActorSystem slaveSystem;
222 private NetconfTopologyManager slaveNetconfTopologyManager;
223 private final SettableFuture<NetconfTopologyContext> slaveNetconfTopologyContextFuture = SettableFuture.create();
224 private TransactionChain slaveTxChain;
226 private NetconfClientConfigurationBuilderFactory builderFactory;
227 private EffectiveModelContext deviceSchemaContext;
228 private YangModuleInfo topModuleInfo;
229 private QName putTopRpcSchemaPath;
230 private QName getTopRpcSchemaPath;
231 private BindingNormalizedNodeSerializer bindingToNormalized;
232 private YangInstanceIdentifier yangNodeInstanceId;
233 private final TopDOMRpcImplementation topRpcImplementation = new TopDOMRpcImplementation();
234 private final ContainerNode getTopInput = ImmutableNodes.containerNode(GetTopInput.QNAME);
236 private SchemaResourceManager resourceManager;
237 private NetconfTopologySchemaAssembler schemaAssembler;
240 public void setUp() throws Exception {
243 schemaAssembler = new NetconfTopologySchemaAssembler(1, 1, 0, TimeUnit.SECONDS);
245 resourceManager = new DefaultSchemaResourceManager(new DefaultYangParserFactory(), TEST_ROOT_DIRECTORY,
246 TEST_DEFAULT_SUBDIR);
248 topModuleInfo = BindingRuntimeHelpers.getYangModuleInfo(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);
274 builderFactory = new NetconfClientConfigurationBuilderFactoryImpl(mockEncryptionService, credentialProvider,
275 sslHandlerFactoryProvider);
277 doReturn(mockRpcReg).when(mockRpcProviderService).registerRpcImplementations(any());
283 yangNodeInstanceId = bindingToNormalized.toYangInstanceIdentifier(NODE_INSTANCE_ID);
284 doReturn(mock(ListenableFuture.class)).when(mockClientFactory).createClient(any());
286 LOG.info("****** Setup complete");
289 private static void deleteCacheDir() {
290 FileUtils.deleteQuietly(new File(TEST_ROOT_DIRECTORY));
294 public void tearDown() throws Exception {
296 TestKit.shutdownActorSystem(slaveSystem, true);
297 TestKit.shutdownActorSystem(masterSystem, true);
298 schemaAssembler.close();
301 private void setupMaster() throws Exception {
302 final var dataBrokerTest = newDataBrokerTest();
303 masterDataBroker = dataBrokerTest.getDataBroker();
304 deviceDOMDataBroker = dataBrokerTest.getDomBroker();
305 bindingToNormalized = dataBrokerTest.getDataBrokerTestCustomizer().getAdapterContext().currentSerializer();
307 masterSystem = ActorSystem.create(ACTOR_SYSTEM_NAME, ConfigFactory.load().getConfig("Master"));
309 masterClusterSingletonServiceProvider = new DOMClusterSingletonServiceProviderImpl();
310 masterClusterSingletonServiceProvider.initializeProvider();
312 final var resources = resourceManager.getSchemaResources(TEST_DEFAULT_SUBDIR, "test");
313 resources.getSchemaRegistry().registerSchemaSource(
314 id -> Futures.immediateFuture(YangTextSchemaSource.delegateForCharSource(id,
315 topModuleInfo.getYangTextCharSource())),
316 PotentialSchemaSource.create(new SourceIdentifier(TOP_MODULE_NAME,
317 topModuleInfo.getName().getRevision().map(Revision::toString).orElse(null)),
318 YangTextSchemaSource.class, 1));
320 masterNetconfTopologyManager = new NetconfTopologyManager(BASE_SCHEMAS, masterDataBroker,
321 masterClusterSingletonServiceProvider, mockTimer, schemaAssembler, masterSystem,
322 mockClientFactory, masterMountPointService, mockEncryptionService, mockRpcProviderService,
323 deviceActionFactory, resourceManager, builderFactory, TOPOLOGY_ID, Uint16.ZERO) {
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,
330 final var spiedContext = spy(context);
331 final var spiedSingleton = spy(context.getTopologySingleton());
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(spiedSingleton).createSalFacade(any(boolean.class));
339 doReturn(spiedSingleton).when(spiedContext).getTopologySingleton();
344 verifyTopologyNodesCreated(masterDataBroker);
347 private void setupSlave() throws Exception {
348 AbstractConcurrentDataBrokerTest dataBrokerTest = newDataBrokerTest();
349 slaveDataBroker = dataBrokerTest.getDataBroker();
351 slaveSystem = ActorSystem.create(ACTOR_SYSTEM_NAME, ConfigFactory.load().getConfig("Slave"));
353 doReturn(mockSlaveClusterSingletonServiceReg).when(mockSlaveClusterSingletonServiceProvider)
354 .registerClusterSingletonService(any());
356 slaveNetconfTopologyManager = new NetconfTopologyManager(BASE_SCHEMAS, slaveDataBroker,
357 mockSlaveClusterSingletonServiceProvider, mockTimer, schemaAssembler, slaveSystem,
358 mockClientFactory, slaveMountPointService, mockEncryptionService, mockRpcProviderService,
359 deviceActionFactory, resourceManager, builderFactory, TOPOLOGY_ID, Uint16.ZERO) {
361 protected NetconfTopologyContext newNetconfTopologyContext(final NetconfTopologySetup setup,
362 final ServiceGroupIdentifier serviceGroupIdent, final Timeout actorResponseWaitTime,
363 final DeviceActionFactory actionFactory) {
364 NetconfTopologyContext spiedContext = spy(super.newNetconfTopologyContext(setup, serviceGroupIdent,
365 actorResponseWaitTime, actionFactory));
367 slaveNetconfTopologyContextFuture.set(spiedContext);
372 verifyTopologyNodesCreated(slaveDataBroker);
374 slaveTxChain = slaveDataBroker.createTransactionChain(new TransactionChainListener() {
376 public void onTransactionChainSuccessful(final TransactionChain chain) {
381 public void onTransactionChainFailed(final TransactionChain chain, final Transaction transaction,
382 final Throwable cause) {
383 LOG.error("Slave transaction chain failed", cause);
389 public void test() throws Exception {
394 final MasterSalFacade masterSalFacade = testMasterNodeUpdated();
396 testMasterDisconnected(masterSalFacade);
401 private MasterSalFacade testMaster() throws Exception {
402 LOG.info("****** Testing master");
404 writeNetconfNode(TEST_DEFAULT_SUBDIR, masterDataBroker);
406 final var masterSalFacade = masterSalFacadeFuture.get(5, TimeUnit.SECONDS);
407 masterSalFacade.onDeviceConnected(new NetconfDeviceSchema(NetconfDeviceCapabilities.empty(),
408 MountPointContext.of(deviceSchemaContext)),
409 NetconfSessionPreferences.fromStrings(List.of(CapabilityURN.CANDIDATE)),
410 new RemoteDeviceServices(deviceRpcService, null));
412 final var masterMountPoint = awaitMountPoint(masterMountPointService);
414 LOG.info("****** Testing master DOMDataBroker operations");
416 testDOMDataBrokerOperations(getDOMDataBroker(masterMountPoint));
418 LOG.info("****** Testing master DOMRpcService");
420 testDOMRpcService(getDOMRpcService(masterMountPoint));
421 return masterSalFacade;
424 private void testSlave() throws Exception {
425 LOG.info("****** Testing slave");
427 writeNetconfNode("slave", slaveDataBroker);
429 verify(mockSlaveClusterSingletonServiceProvider, timeout(5000)).registerClusterSingletonService(any());
431 // Since the master and slave use separate DataBrokers we need to copy the master's oper node to the slave.
432 // This is essentially what happens in a clustered environment but we'll use a DTCL here.
434 masterDataBroker.registerDataTreeChangeListener(
435 DataTreeIdentifier.create(LogicalDatastoreType.OPERATIONAL, NODE_INSTANCE_ID), changes -> {
436 final WriteTransaction slaveTx = slaveTxChain.newWriteOnlyTransaction();
437 for (DataTreeModification<Node> dataTreeModification : changes) {
438 DataObjectModification<Node> rootNode = dataTreeModification.getRootNode();
439 InstanceIdentifier<Node> path = dataTreeModification.getRootPath().getRootIdentifier();
440 switch (rootNode.getModificationType()) {
442 case SUBTREE_MODIFIED:
443 slaveTx.merge(LogicalDatastoreType.OPERATIONAL, path, rootNode.getDataAfter());
446 slaveTx.delete(LogicalDatastoreType.OPERATIONAL, path);
456 DOMMountPoint slaveMountPoint = awaitMountPoint(slaveMountPointService);
458 LOG.info("****** Testing slave DOMDataBroker operations");
460 testDOMDataBrokerOperations(getDOMDataBroker(slaveMountPoint));
462 LOG.info("****** Testing slave DOMRpcService");
464 testDOMRpcService(getDOMRpcService(slaveMountPoint));
467 private MasterSalFacade testMasterNodeUpdated() throws Exception {
468 LOG.info("****** Testing update master node");
470 masterMountPointService.registerProvisionListener(masterMountPointListener);
471 slaveMountPointService.registerProvisionListener(slaveMountPointListener);
473 masterSalFacadeFuture = SettableFuture.create();
474 writeNetconfNode(TEST_DEFAULT_SUBDIR, masterDataBroker);
476 verify(masterMountPointListener, timeout(5000)).onMountPointRemoved(yangNodeInstanceId);
478 final var masterSalFacade = masterSalFacadeFuture.get(5, TimeUnit.SECONDS);
479 masterSalFacade.onDeviceConnected(
480 new NetconfDeviceSchema(NetconfDeviceCapabilities.empty(), MountPointContext.of(deviceSchemaContext)),
481 NetconfSessionPreferences.fromStrings(List.of(CapabilityURN.CANDIDATE)),
482 new RemoteDeviceServices(deviceRpcService, null));
484 verify(masterMountPointListener, timeout(5000)).onMountPointCreated(yangNodeInstanceId);
486 verify(slaveMountPointListener, timeout(5000)).onMountPointRemoved(yangNodeInstanceId);
487 verify(slaveMountPointListener, timeout(5000)).onMountPointCreated(yangNodeInstanceId);
489 return masterSalFacade;
492 private void testMasterDisconnected(final MasterSalFacade masterSalFacade) throws Exception {
493 LOG.info("****** Testing master disconnected");
495 masterSalFacade.onDeviceDisconnected();
497 awaitMountPointNotPresent(masterMountPointService);
499 await().atMost(5, TimeUnit.SECONDS).until(() -> {
500 try (ReadTransaction readTx = masterDataBroker.newReadOnlyTransaction()) {
501 Optional<Node> node = readTx.read(LogicalDatastoreType.OPERATIONAL,
502 NODE_INSTANCE_ID).get(5, TimeUnit.SECONDS);
503 assertTrue(node.isPresent());
504 final NetconfNode netconfNode = node.orElseThrow().augmentation(NetconfNode.class);
505 return netconfNode.getConnectionStatus() != ConnectionStatus.Connected;
509 awaitMountPointNotPresent(slaveMountPointService);
512 private void testCleanup() throws Exception {
513 LOG.info("****** Testing cleanup");
515 slaveNetconfTopologyManager.close();
516 verify(mockSlaveClusterSingletonServiceReg).close();
519 private void testDOMRpcService(final DOMRpcService domRpcService)
520 throws InterruptedException, ExecutionException, TimeoutException {
521 testPutTopRpc(domRpcService, new DefaultDOMRpcResult((ContainerNode)null));
522 testPutTopRpc(domRpcService, null);
523 testPutTopRpc(domRpcService, new DefaultDOMRpcResult(ImmutableList.of(
524 RpcResultBuilder.newError(ErrorType.APPLICATION, new ErrorTag("tag1"), "error1"),
525 RpcResultBuilder.newError(ErrorType.APPLICATION, new ErrorTag("tag2"), "error2"))));
527 testGetTopRpc(domRpcService, new DefaultDOMRpcResult(bindingToNormalized.toNormalizedNodeRpcData(
528 new GetTopOutputBuilder().setTopLevelList(oneTopLevelList()).build())));
530 testFailedRpc(domRpcService, getTopRpcSchemaPath, getTopInput);
533 private void testPutTopRpc(final DOMRpcService domRpcService, final DOMRpcResult result)
534 throws InterruptedException, ExecutionException, TimeoutException {
535 ContainerNode putTopInput = bindingToNormalized.toNormalizedNodeRpcData(
536 new PutTopInputBuilder().setTopLevelList(oneTopLevelList()).build());
537 testRpc(domRpcService, putTopRpcSchemaPath, putTopInput, result);
540 private static Map<TopLevelListKey, TopLevelList> oneTopLevelList() {
541 final TopLevelListKey key = new TopLevelListKey("one");
542 return ImmutableMap.of(key, new TopLevelListBuilder().withKey(key).build());
545 private void testGetTopRpc(final DOMRpcService domRpcService, final DOMRpcResult result)
546 throws InterruptedException, ExecutionException, TimeoutException {
547 testRpc(domRpcService, getTopRpcSchemaPath, getTopInput, result);
550 private void testRpc(final DOMRpcService domRpcService, final QName qname, final ContainerNode input,
551 final DOMRpcResult result) throws InterruptedException, ExecutionException, TimeoutException {
552 final FluentFuture<DOMRpcResult> future = result == null ? FluentFutures.immediateNullFluentFuture()
553 : FluentFutures.immediateFluentFuture(result);
554 final DOMRpcResult actual = invokeRpc(domRpcService, qname, input, future);
555 if (result == null) {
560 assertNotNull(actual);
561 assertEquals(result.value(), actual.value());
563 assertEquals(result.errors().size(), actual.errors().size());
564 Iterator<? extends RpcError> iter1 = result.errors().iterator();
565 Iterator<? extends RpcError> iter2 = actual.errors().iterator();
566 while (iter1.hasNext() && iter2.hasNext()) {
567 RpcError err1 = iter1.next();
568 RpcError err2 = iter2.next();
569 assertEquals(err1.getErrorType(), err2.getErrorType());
570 assertEquals(err1.getTag(), err2.getTag());
571 assertEquals(err1.getMessage(), err2.getMessage());
572 assertEquals(err1.getSeverity(), err2.getSeverity());
573 assertEquals(err1.getApplicationTag(), err2.getApplicationTag());
574 assertEquals(err1.getInfo(), err2.getInfo());
578 private void testFailedRpc(final DOMRpcService domRpcService, final QName qname, final ContainerNode input)
579 throws InterruptedException, TimeoutException {
581 invokeRpc(domRpcService, qname, input, Futures.immediateFailedFuture(new ClusteringRpcException("mock")));
582 fail("Expected exception");
583 } catch (ExecutionException e) {
584 assertTrue(e.getCause() instanceof ClusteringRpcException);
585 assertEquals("mock", e.getCause().getMessage());
589 private DOMRpcResult invokeRpc(final DOMRpcService domRpcService, final QName qname, final ContainerNode input,
590 final ListenableFuture<DOMRpcResult> returnFuture)
591 throws InterruptedException, ExecutionException, TimeoutException {
592 topRpcImplementation.init(returnFuture);
593 final ListenableFuture<? extends DOMRpcResult> resultFuture = domRpcService.invokeRpc(qname, input);
595 topRpcImplementation.verify(DOMRpcIdentifier.create(qname), input);
597 return resultFuture.get(5, TimeUnit.SECONDS);
600 private static void testDOMDataBrokerOperations(final DOMDataBroker dataBroker)
601 throws InterruptedException, ExecutionException, TimeoutException {
603 DOMDataTreeWriteTransaction writeTx = dataBroker.newWriteOnlyTransaction();
605 final ContainerNode topNode = Builders.containerBuilder()
606 .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(Top.QNAME)).build();
607 final YangInstanceIdentifier topPath = YangInstanceIdentifier.of(Top.QNAME);
608 writeTx.put(LogicalDatastoreType.CONFIGURATION, topPath, topNode);
610 final QName name = QName.create(TopLevelList.QNAME, "name");
611 final YangInstanceIdentifier listPath = YangInstanceIdentifier.builder(topPath)
612 .node(TopLevelList.QNAME).build();
613 final MapEntryNode listEntryNode = ImmutableNodes.mapEntry(TopLevelList.QNAME, name, "one");
614 final MapNode listNode = ImmutableNodes.mapNodeBuilder(TopLevelList.QNAME).addChild(listEntryNode).build();
615 writeTx.merge(LogicalDatastoreType.CONFIGURATION, listPath, listNode);
616 writeTx.commit().get(5, TimeUnit.SECONDS);
618 verifyDataInStore(dataBroker.newReadWriteTransaction(), YangInstanceIdentifier.builder(listPath)
619 .nodeWithKey(TopLevelList.QNAME, name, "one").build(), listEntryNode);
621 writeTx = dataBroker.newWriteOnlyTransaction();
622 writeTx.delete(LogicalDatastoreType.CONFIGURATION, topPath);
623 writeTx.commit().get(5, TimeUnit.SECONDS);
625 DOMDataTreeReadWriteTransaction readTx = dataBroker.newReadWriteTransaction();
626 assertFalse(readTx.exists(LogicalDatastoreType.CONFIGURATION, topPath).get(5, TimeUnit.SECONDS));
627 assertTrue(readTx.cancel());
630 private static void writeNetconfNode(final String cacheDir, final DataBroker dataBroker) throws Exception {
631 putData(dataBroker, NODE_INSTANCE_ID, new NodeBuilder()
632 .withKey(NODE_INSTANCE_ID.getKey())
633 .addAugmentation(new NetconfNodeBuilder()
634 .setHost(new Host(new IpAddress(new Ipv4Address("127.0.0.1"))))
635 .setPort(new PortNumber(Uint16.valueOf(1234)))
636 .setActorResponseWaitTime(Uint16.valueOf(10))
637 .setTcpOnly(Boolean.TRUE)
638 .setSchemaless(Boolean.FALSE)
639 .setKeepaliveDelay(Uint32.ZERO)
640 .setConnectionTimeoutMillis(Uint32.valueOf(5000))
641 .setDefaultRequestTimeoutMillis(Uint32.valueOf(5000))
642 .setMaxConnectionAttempts(Uint32.ONE)
643 .setCredentials(new LoginPwUnencryptedBuilder()
644 .setLoginPasswordUnencrypted(new LoginPasswordUnencryptedBuilder()
649 .setSchemaCacheDirectory(cacheDir)
654 private static <T extends DataObject> void putData(final DataBroker databroker, final InstanceIdentifier<T> path,
655 final T data) throws Exception {
656 final var writeTx = databroker.newWriteOnlyTransaction();
657 writeTx.put(LogicalDatastoreType.CONFIGURATION, path, data);
658 writeTx.commit().get(5, TimeUnit.SECONDS);
661 private static void verifyDataInStore(final DOMDataTreeReadOperations readTx, final YangInstanceIdentifier path,
662 final NormalizedNode expNode) throws InterruptedException, ExecutionException, TimeoutException {
663 assertEquals(Optional.of(expNode), readTx.read(LogicalDatastoreType.CONFIGURATION, path)
664 .get(5, TimeUnit.SECONDS));
665 assertTrue(readTx.exists(LogicalDatastoreType.CONFIGURATION, path).get(5, TimeUnit.SECONDS));
668 private static void verifyTopologyNodesCreated(final DataBroker dataBroker) {
669 await().atMost(5, TimeUnit.SECONDS).until(() -> {
670 try (ReadTransaction readTx = dataBroker.newReadOnlyTransaction()) {
671 return readTx.exists(LogicalDatastoreType.OPERATIONAL,
672 NetconfTopologyUtils.createTopologyListPath(TOPOLOGY_ID)).get(3, TimeUnit.SECONDS);
677 private AbstractConcurrentDataBrokerTest newDataBrokerTest() throws Exception {
678 final var dataBrokerTest = new AbstractConcurrentDataBrokerTest(true) {
680 protected Set<YangModuleInfo> getModuleInfos() {
682 BindingRuntimeHelpers.getYangModuleInfo(NetconfNode.class),
683 BindingRuntimeHelpers.getYangModuleInfo(NetworkTopology.class),
684 BindingRuntimeHelpers.getYangModuleInfo(Keystore.class),
689 dataBrokerTest.setup();
691 final var path = NetconfTopologyUtils.createTopologyListPath(TOPOLOGY_ID);
692 putData(dataBrokerTest.getDataBroker(), path, new TopologyBuilder().withKey(path.getKey()).build());
693 return dataBrokerTest;
696 private void awaitMountPointNotPresent(final DOMMountPointService mountPointService) {
697 await().atMost(5, TimeUnit.SECONDS).until(
698 () -> mountPointService.getMountPoint(yangNodeInstanceId).isEmpty());
701 private static DOMDataBroker getDOMDataBroker(final DOMMountPoint mountPoint) {
702 return getMountPointService(mountPoint, DOMDataBroker.class);
705 private static DOMRpcService getDOMRpcService(final DOMMountPoint mountPoint) {
706 return getMountPointService(mountPoint, DOMRpcService.class);
709 private static DOMActionService getDomActionService(final DOMMountPoint mountPoint) {
710 return getMountPointService(mountPoint, DOMActionService.class);
713 private static <T extends DOMService> T getMountPointService(final DOMMountPoint mountPoint,
714 final Class<T> serviceClass) {
715 return mountPoint.getService(serviceClass).orElseThrow();
718 private DOMMountPoint awaitMountPoint(final DOMMountPointService mountPointService) {
719 await().atMost(5, TimeUnit.SECONDS).until(() ->
720 mountPointService.getMountPoint(yangNodeInstanceId).isPresent());
722 return mountPointService.getMountPoint(yangNodeInstanceId).orElseThrow();
725 private RpcDefinition findRpcDefinition(final String rpc) {
726 Module topModule = deviceSchemaContext.findModule(TOP_MODULE_NAME, topModuleInfo.getName().getRevision())
728 RpcDefinition rpcDefinition = null;
729 for (RpcDefinition def: topModule.getRpcs()) {
730 if (def.getQName().getLocalName().equals(rpc)) {
736 assertNotNull(rpc + " rpc not found in " + topModule.getRpcs(), rpcDefinition);
737 return rpcDefinition;
740 private static final class TopDOMRpcImplementation implements DOMRpcImplementation {
741 private volatile SettableFuture<Entry<DOMRpcIdentifier, NormalizedNode>> rpcInvokedFuture;
742 private volatile ListenableFuture<DOMRpcResult> returnFuture;
745 public ListenableFuture<DOMRpcResult> invokeRpc(final DOMRpcIdentifier rpc, final ContainerNode input) {
746 rpcInvokedFuture.set(Map.entry(rpc, input));
750 void init(final ListenableFuture<DOMRpcResult> retFuture) {
751 returnFuture = retFuture;
752 rpcInvokedFuture = SettableFuture.create();
755 void verify(final DOMRpcIdentifier expRpc, final NormalizedNode expInput)
756 throws InterruptedException, ExecutionException, TimeoutException {
757 final Entry<DOMRpcIdentifier, NormalizedNode> actual = rpcInvokedFuture.get(5, TimeUnit.SECONDS);
758 assertEquals(expRpc, actual.getKey());
759 assertEquals(expInput, actual.getValue());