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.mockito.ArgumentMatchers.any;
11 import static org.mockito.ArgumentMatchers.eq;
12 import static org.mockito.Mockito.after;
13 import static org.mockito.Mockito.doNothing;
14 import static org.mockito.Mockito.doReturn;
15 import static org.mockito.Mockito.mock;
16 import static org.mockito.Mockito.reset;
17 import static org.mockito.Mockito.timeout;
18 import static org.mockito.Mockito.verify;
19 import static org.mockito.Mockito.verifyNoMoreInteractions;
20 import static org.opendaylight.mdsal.binding.api.DataObjectModification.ModificationType.DELETE;
21 import static org.opendaylight.mdsal.binding.api.DataObjectModification.ModificationType.SUBTREE_MODIFIED;
22 import static org.opendaylight.mdsal.binding.api.DataObjectModification.ModificationType.WRITE;
24 import akka.actor.ActorSystem;
25 import akka.actor.Props;
26 import akka.cluster.Cluster;
27 import akka.dispatch.Dispatchers;
28 import akka.testkit.TestActorRef;
29 import akka.testkit.javadsl.TestKit;
30 import akka.util.Timeout;
31 import com.google.common.collect.Iterables;
32 import com.google.common.io.CharSource;
33 import com.google.common.util.concurrent.Futures;
34 import com.typesafe.config.ConfigFactory;
35 import java.net.InetSocketAddress;
36 import java.util.List;
38 import java.util.concurrent.CompletableFuture;
39 import java.util.concurrent.ConcurrentHashMap;
40 import java.util.concurrent.ExecutionException;
41 import java.util.concurrent.TimeUnit;
42 import java.util.concurrent.TimeoutException;
43 import java.util.stream.Collectors;
44 import org.junit.After;
45 import org.junit.Before;
46 import org.junit.Test;
47 import org.junit.runner.RunWith;
48 import org.mockito.Mock;
49 import org.mockito.junit.MockitoJUnitRunner;
50 import org.opendaylight.mdsal.binding.api.DataBroker;
51 import org.opendaylight.mdsal.binding.api.DataObjectModification;
52 import org.opendaylight.mdsal.binding.api.DataTreeIdentifier;
53 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
54 import org.opendaylight.mdsal.dom.api.DOMDataBroker;
55 import org.opendaylight.mdsal.dom.api.DOMMountPoint;
56 import org.opendaylight.mdsal.dom.api.DOMMountPointService;
57 import org.opendaylight.mdsal.dom.api.DOMNotificationService;
58 import org.opendaylight.mdsal.dom.api.DOMRpcService;
59 import org.opendaylight.netconf.client.mdsal.NetconfDevice;
60 import org.opendaylight.netconf.client.mdsal.api.NetconfDeviceSchemasResolver;
61 import org.opendaylight.netconf.client.mdsal.api.RemoteDeviceId;
62 import org.opendaylight.netconf.client.mdsal.api.RemoteDeviceServices;
63 import org.opendaylight.netconf.client.mdsal.api.RemoteDeviceServices.Actions;
64 import org.opendaylight.netconf.client.mdsal.api.RemoteDeviceServices.Rpcs;
65 import org.opendaylight.netconf.dom.api.NetconfDataTreeService;
66 import org.opendaylight.netconf.topology.singleton.impl.actors.NetconfNodeActor;
67 import org.opendaylight.netconf.topology.singleton.impl.utils.NetconfTopologySetup;
68 import org.opendaylight.netconf.topology.singleton.impl.utils.NetconfTopologyUtils;
69 import org.opendaylight.netconf.topology.singleton.messages.AskForMasterMountPoint;
70 import org.opendaylight.netconf.topology.singleton.messages.CreateInitialMasterActorData;
71 import org.opendaylight.netconf.topology.singleton.messages.MasterActorDataInitialized;
72 import org.opendaylight.netconf.topology.singleton.messages.YangTextSchemaSourceRequest;
73 import org.opendaylight.netconf.topology.spi.NetconfNodeUtils;
74 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Host;
75 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpAddress;
76 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Ipv4Address;
77 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.PortNumber;
78 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.device.rev231025.ConnectionOper.ConnectionStatus;
79 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.device.rev231025.connection.oper.ClusteredConnectionStatusBuilder;
80 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev221225.NetconfNode;
81 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev221225.NetconfNodeBuilder;
82 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NodeId;
83 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node;
84 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.NodeBuilder;
85 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.NodeKey;
86 import org.opendaylight.yangtools.concepts.ListenerRegistration;
87 import org.opendaylight.yangtools.concepts.ObjectRegistration;
88 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
89 import org.opendaylight.yangtools.yang.common.Uint16;
90 import org.opendaylight.yangtools.yang.model.repo.api.EffectiveModelContextFactory;
91 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
92 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
93 import org.opendaylight.yangtools.yang.model.repo.spi.PotentialSchemaSource;
94 import org.opendaylight.yangtools.yang.parser.repo.SharedSchemaRepository;
95 import org.opendaylight.yangtools.yang.parser.rfc7950.repo.TextToIRTransformer;
98 * Unit tests for NetconfNodeManager.
100 * @author Thomas Pantelis
102 @RunWith(MockitoJUnitRunner.StrictStubs.class)
103 public class NetconfNodeManagerTest extends AbstractBaseSchemasTest {
104 private static final String ACTOR_SYSTEM_NAME = "test";
105 private static final RemoteDeviceId DEVICE_ID = new RemoteDeviceId("device", new InetSocketAddress(65535));
106 private static final List<SourceIdentifier> SOURCE_IDENTIFIERS = List.of(new SourceIdentifier("testID"));
109 private DOMMountPointService mockMountPointService;
111 private DOMMountPointService.DOMMountPointBuilder mockMountPointBuilder;
113 private ObjectRegistration<DOMMountPoint> mockMountPointReg;
115 private DataBroker mockDataBroker;
117 private NetconfDataTreeService netconfService;
119 private DOMDataBroker mockDeviceDataBroker;
121 private Rpcs.Normalized mockRpcService;
123 private Actions.Normalized mockActionService;
125 private NetconfDeviceSchemasResolver mockSchemasResolver;
127 private EffectiveModelContextFactory mockSchemaContextFactory;
129 private ActorSystem slaveSystem;
130 private ActorSystem masterSystem;
131 private TestActorRef<TestMasterActor> testMasterActorRef;
132 private NetconfNodeManager netconfNodeManager;
133 private String masterAddress;
136 public void setup() {
137 final Timeout responseTimeout = Timeout.apply(1, TimeUnit.SECONDS);
139 slaveSystem = ActorSystem.create(ACTOR_SYSTEM_NAME, ConfigFactory.load().getConfig("Slave"));
140 masterSystem = ActorSystem.create(ACTOR_SYSTEM_NAME, ConfigFactory.load().getConfig("Master"));
142 masterAddress = Cluster.get(masterSystem).selfAddress().toString();
144 SharedSchemaRepository masterSchemaRepository = new SharedSchemaRepository("master");
145 masterSchemaRepository.registerSchemaSourceListener(
146 TextToIRTransformer.create(masterSchemaRepository, masterSchemaRepository));
148 final String yangTemplate = """
154 SOURCE_IDENTIFIERS.stream().map(
155 sourceId -> masterSchemaRepository.registerSchemaSource(
156 id -> Futures.immediateFuture(YangTextSchemaSource.delegateForCharSource(id,
157 CharSource.wrap(yangTemplate.replaceAll("ID", id.name().getLocalName())))),
158 PotentialSchemaSource.create(sourceId, YangTextSchemaSource.class, 1)))
159 .collect(Collectors.toList());
161 NetconfTopologySetup masterSetup = NetconfTopologySetup.builder()
162 .setActorSystem(masterSystem)
163 .setDataBroker(mockDataBroker)
164 .setSchemaResourceDTO(new NetconfDevice.SchemaResourcesDTO(
165 masterSchemaRepository, masterSchemaRepository, mockSchemaContextFactory, mockSchemasResolver))
166 .setBaseSchemas(BASE_SCHEMAS)
169 testMasterActorRef = TestActorRef.create(masterSystem, Props.create(TestMasterActor.class, masterSetup,
170 DEVICE_ID, responseTimeout, mockMountPointService).withDispatcher(Dispatchers.DefaultDispatcherId()),
171 NetconfTopologyUtils.createMasterActorName(DEVICE_ID.name(), masterAddress));
173 SharedSchemaRepository slaveSchemaRepository = new SharedSchemaRepository("slave");
174 slaveSchemaRepository.registerSchemaSourceListener(
175 TextToIRTransformer.create(slaveSchemaRepository, slaveSchemaRepository));
177 NetconfTopologySetup slaveSetup = NetconfTopologySetup.builder()
178 .setActorSystem(slaveSystem)
179 .setDataBroker(mockDataBroker)
180 .setSchemaResourceDTO(new NetconfDevice.SchemaResourcesDTO(
181 slaveSchemaRepository, slaveSchemaRepository, mockSchemaContextFactory, mockSchemasResolver))
182 .setBaseSchemas(BASE_SCHEMAS)
185 netconfNodeManager = new NetconfNodeManager(slaveSetup, DEVICE_ID, responseTimeout,
186 mockMountPointService);
188 setupMountPointMocks();
192 public void teardown() {
193 TestKit.shutdownActorSystem(slaveSystem, true);
194 TestKit.shutdownActorSystem(masterSystem, true);
197 @SuppressWarnings("unchecked")
199 public void testSlaveMountPointRegistration() throws InterruptedException, ExecutionException, TimeoutException {
202 ListenerRegistration<?> mockListenerReg = mock(ListenerRegistration.class);
203 doReturn(mockListenerReg).when(mockDataBroker).registerDataTreeChangeListener(any(), any());
205 final NodeId nodeId = new NodeId("device");
206 final NodeKey nodeKey = new NodeKey(nodeId);
207 final String topologyId = "topology-netconf";
208 final InstanceIdentifier<Node> nodeListPath = NetconfTopologyUtils.createTopologyNodeListPath(
209 nodeKey, topologyId);
211 netconfNodeManager.registerDataTreeChangeListener(topologyId, nodeKey);
212 verify(mockDataBroker).registerDataTreeChangeListener(any(), eq(netconfNodeManager));
214 // Invoke onDataTreeChanged with a NetconfNode WRITE to simulate the master writing the operational state to
215 // Connected. Expect the slave mount point created and registered.
217 final NetconfNode netconfNode = newNetconfNode();
218 final Node node = new NodeBuilder().setNodeId(nodeId).addAugmentation(netconfNode).build();
220 DataObjectModification<Node> mockDataObjModification = mock(DataObjectModification.class);
221 doReturn(Iterables.getLast(nodeListPath.getPathArguments())).when(mockDataObjModification).getIdentifier();
222 doReturn(WRITE).when(mockDataObjModification).getModificationType();
223 doReturn(node).when(mockDataObjModification).getDataAfter();
225 netconfNodeManager.onDataTreeChanged(List.of(
226 new NetconfTopologyManagerTest.CustomTreeModification(DataTreeIdentifier.create(
227 LogicalDatastoreType.OPERATIONAL, nodeListPath), mockDataObjModification)));
229 verify(mockMountPointBuilder, timeout(5000)).register();
230 verify(mockMountPointBuilder).addService(eq(DOMDataBroker.class), any());
231 verify(mockMountPointBuilder).addService(eq(DOMRpcService.class), any());
232 verify(mockMountPointBuilder).addService(eq(DOMNotificationService.class), any());
233 verify(mockMountPointService).createMountPoint(NetconfNodeUtils.defaultTopologyMountPath(DEVICE_ID));
235 // Notify that the NetconfNode operational state was deleted. Expect the slave mount point closed.
237 doReturn(DELETE).when(mockDataObjModification).getModificationType();
239 netconfNodeManager.onDataTreeChanged(List.of(
240 new NetconfTopologyManagerTest.CustomTreeModification(DataTreeIdentifier.create(
241 LogicalDatastoreType.OPERATIONAL, nodeListPath), mockDataObjModification)));
243 verify(mockMountPointReg, timeout(5000)).close();
245 // Notify with a NetconfNode operational state WRITE. Expect the slave mount point re-created.
247 setupMountPointMocks();
249 doReturn(WRITE).when(mockDataObjModification).getModificationType();
250 doReturn(null).when(mockDataObjModification).getDataBefore();
251 doReturn(node).when(mockDataObjModification).getDataAfter();
253 netconfNodeManager.onDataTreeChanged(List.of(
254 new NetconfTopologyManagerTest.CustomTreeModification(DataTreeIdentifier.create(
255 LogicalDatastoreType.OPERATIONAL, nodeListPath), mockDataObjModification)));
257 verify(mockMountPointBuilder, timeout(5000)).register();
259 // Notify again with a NetconfNode operational state WRITE. Expect the prior slave mount point closed and
260 // and a new one registered.
262 setupMountPointMocks();
264 doReturn(node).when(mockDataObjModification).getDataBefore();
266 netconfNodeManager.onDataTreeChanged(List.of(
267 new NetconfTopologyManagerTest.CustomTreeModification(DataTreeIdentifier.create(
268 LogicalDatastoreType.OPERATIONAL, nodeListPath), mockDataObjModification)));
270 verify(mockMountPointReg, timeout(5000)).close();
271 verify(mockMountPointBuilder, timeout(5000)).register();
273 // Notify that the NetconfNode operational state was changed to UnableToConnect. Expect the slave mount point
276 reset(mockMountPointService, mockMountPointBuilder, mockMountPointReg);
277 doNothing().when(mockMountPointReg).close();
279 final Node updatedNode = new NodeBuilder().setNodeId(nodeId)
280 .addAugmentation(new NetconfNodeBuilder(netconfNode)
281 .setConnectionStatus(ConnectionStatus.UnableToConnect)
285 doReturn(SUBTREE_MODIFIED).when(mockDataObjModification).getModificationType();
286 doReturn(node).when(mockDataObjModification).getDataBefore();
287 doReturn(updatedNode).when(mockDataObjModification).getDataAfter();
289 netconfNodeManager.onDataTreeChanged(List.of(
290 new NetconfTopologyManagerTest.CustomTreeModification(DataTreeIdentifier.create(
291 LogicalDatastoreType.OPERATIONAL, nodeListPath), mockDataObjModification)));
293 verify(mockMountPointReg, timeout(5000)).close();
295 netconfNodeManager.close();
296 verifyNoMoreInteractions(mockMountPointReg);
299 @SuppressWarnings("unchecked")
301 public void testSlaveMountPointRegistrationFailuresAndRetries()
302 throws InterruptedException, ExecutionException, TimeoutException {
303 final NodeId nodeId = new NodeId("device");
304 final NodeKey nodeKey = new NodeKey(nodeId);
305 final String topologyId = "topology-netconf";
306 final InstanceIdentifier<Node> nodeListPath = NetconfTopologyUtils.createTopologyNodeListPath(
307 nodeKey, topologyId);
309 final NetconfNode netconfNode = newNetconfNode();
310 final Node node = new NodeBuilder().setNodeId(nodeId).addAugmentation(netconfNode).build();
312 DataObjectModification<Node> mockDataObjModification = mock(DataObjectModification.class);
313 doReturn(Iterables.getLast(nodeListPath.getPathArguments())).when(mockDataObjModification).getIdentifier();
314 doReturn(WRITE).when(mockDataObjModification).getModificationType();
315 doReturn(node).when(mockDataObjModification).getDataAfter();
317 // First try the registration where the perceived master hasn't been initialized as the master.
319 netconfNodeManager.onDataTreeChanged(List.of(
320 new NetconfTopologyManagerTest.CustomTreeModification(DataTreeIdentifier.create(
321 LogicalDatastoreType.OPERATIONAL, nodeListPath), mockDataObjModification)));
323 verify(mockMountPointBuilder, after(1000).never()).register();
325 // Initialize the master but drop the initial YangTextSchemaSourceRequest message sent to the master so
330 CompletableFuture<AskForMasterMountPoint> yangTextSchemaSourceRequestFuture = new CompletableFuture<>();
331 testMasterActorRef.underlyingActor().messagesToDrop.put(YangTextSchemaSourceRequest.class,
332 yangTextSchemaSourceRequestFuture);
334 netconfNodeManager.onDataTreeChanged(List.of(
335 new NetconfTopologyManagerTest.CustomTreeModification(DataTreeIdentifier.create(
336 LogicalDatastoreType.OPERATIONAL, nodeListPath), mockDataObjModification)));
338 yangTextSchemaSourceRequestFuture.get(5, TimeUnit.SECONDS);
339 verify(mockMountPointBuilder, timeout(5000)).register();
341 // Initiate another registration but drop the initial AskForMasterMountPoint message sent to the master so
344 setupMountPointMocks();
346 CompletableFuture<AskForMasterMountPoint> askForMasterMountPointFuture = new CompletableFuture<>();
347 testMasterActorRef.underlyingActor().messagesToDrop.put(AskForMasterMountPoint.class,
348 askForMasterMountPointFuture);
350 netconfNodeManager.onDataTreeChanged(List.of(
351 new NetconfTopologyManagerTest.CustomTreeModification(DataTreeIdentifier.create(
352 LogicalDatastoreType.OPERATIONAL, nodeListPath), mockDataObjModification)));
354 askForMasterMountPointFuture.get(5, TimeUnit.SECONDS);
355 verify(mockMountPointReg, timeout(5000)).close();
356 verify(mockMountPointBuilder, timeout(5000)).register();
358 reset(mockMountPointService, mockMountPointBuilder, mockMountPointReg);
359 doNothing().when(mockMountPointReg).close();
360 netconfNodeManager.close();
361 verify(mockMountPointReg, timeout(5000)).close();
364 private NetconfNode newNetconfNode() {
365 return new NetconfNodeBuilder()
366 .setHost(new Host(new IpAddress(new Ipv4Address("127.0.0.1"))))
367 .setPort(new PortNumber(Uint16.valueOf(9999)))
368 .setConnectionStatus(ConnectionStatus.Connected)
369 .setClusteredConnectionStatus(new ClusteredConnectionStatusBuilder()
370 .setNetconfMasterNode(masterAddress).build())
374 private void setupMountPointMocks() {
375 reset(mockMountPointService, mockMountPointBuilder, mockMountPointReg);
376 doNothing().when(mockMountPointReg).close();
377 doReturn(mockMountPointReg).when(mockMountPointBuilder).register();
378 doReturn(mockMountPointBuilder).when(mockMountPointService).createMountPoint(any());
381 private void initializeMaster() {
382 TestKit kit = new TestKit(masterSystem);
383 testMasterActorRef.tell(new CreateInitialMasterActorData(mockDeviceDataBroker, netconfService,
384 SOURCE_IDENTIFIERS, new RemoteDeviceServices(mockRpcService, mockActionService)), kit.getRef());
386 kit.expectMsgClass(MasterActorDataInitialized.class);
389 private static class TestMasterActor extends NetconfNodeActor {
390 final Map<Class<?>, CompletableFuture<? extends Object>> messagesToDrop = new ConcurrentHashMap<>();
392 TestMasterActor(final NetconfTopologySetup setup, final RemoteDeviceId deviceId,
393 final Timeout actorResponseWaitTime, final DOMMountPointService mountPointService) {
394 super(setup, deviceId, actorResponseWaitTime, mountPointService);
397 @SuppressWarnings({ "rawtypes", "unchecked" })
399 public void handleReceive(final Object message) {
400 CompletableFuture dropFuture = messagesToDrop.remove(message.getClass());
401 if (dropFuture != null) {
402 dropFuture.complete(message);
404 super.handleReceive(message);