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 java.nio.charset.StandardCharsets.UTF_8;
11 import static org.mockito.ArgumentMatchers.any;
12 import static org.mockito.ArgumentMatchers.eq;
13 import static org.mockito.Mockito.after;
14 import static org.mockito.Mockito.doNothing;
15 import static org.mockito.Mockito.doReturn;
16 import static org.mockito.Mockito.mock;
17 import static org.mockito.Mockito.reset;
18 import static org.mockito.Mockito.timeout;
19 import static org.mockito.Mockito.verify;
20 import static org.mockito.Mockito.verifyNoMoreInteractions;
21 import static org.mockito.MockitoAnnotations.initMocks;
22 import static org.opendaylight.mdsal.binding.api.DataObjectModification.ModificationType.DELETE;
23 import static org.opendaylight.mdsal.binding.api.DataObjectModification.ModificationType.SUBTREE_MODIFIED;
24 import static org.opendaylight.mdsal.binding.api.DataObjectModification.ModificationType.WRITE;
26 import akka.actor.ActorSystem;
27 import akka.actor.Props;
28 import akka.cluster.Cluster;
29 import akka.dispatch.Dispatchers;
30 import akka.testkit.TestActorRef;
31 import akka.testkit.javadsl.TestKit;
32 import akka.util.Timeout;
33 import com.google.common.collect.ImmutableList;
34 import com.google.common.collect.Iterables;
35 import com.google.common.io.ByteSource;
36 import com.google.common.util.concurrent.Futures;
37 import com.typesafe.config.ConfigFactory;
38 import java.net.InetSocketAddress;
39 import java.util.Collections;
40 import java.util.List;
42 import java.util.concurrent.CompletableFuture;
43 import java.util.concurrent.ConcurrentHashMap;
44 import java.util.concurrent.ExecutionException;
45 import java.util.concurrent.TimeUnit;
46 import java.util.concurrent.TimeoutException;
47 import java.util.stream.Collectors;
48 import org.junit.After;
49 import org.junit.Before;
50 import org.junit.Test;
51 import org.mockito.Mock;
52 import org.opendaylight.mdsal.binding.api.DataBroker;
53 import org.opendaylight.mdsal.binding.api.DataObjectModification;
54 import org.opendaylight.mdsal.binding.api.DataTreeIdentifier;
55 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
56 import org.opendaylight.mdsal.dom.api.DOMActionService;
57 import org.opendaylight.mdsal.dom.api.DOMDataBroker;
58 import org.opendaylight.mdsal.dom.api.DOMMountPoint;
59 import org.opendaylight.mdsal.dom.api.DOMMountPointService;
60 import org.opendaylight.mdsal.dom.api.DOMNotificationService;
61 import org.opendaylight.mdsal.dom.api.DOMRpcService;
62 import org.opendaylight.netconf.dom.api.NetconfDataTreeService;
63 import org.opendaylight.netconf.sal.connect.api.NetconfDeviceSchemasResolver;
64 import org.opendaylight.netconf.sal.connect.netconf.NetconfDevice;
65 import org.opendaylight.netconf.sal.connect.util.RemoteDeviceId;
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.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Host;
74 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpAddress;
75 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Ipv4Address;
76 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.PortNumber;
77 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.NetconfNode;
78 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.NetconfNodeBuilder;
79 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.NetconfNodeConnectionStatus;
80 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.connection.status.ClusteredConnectionStatusBuilder;
81 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NodeId;
82 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node;
83 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.NodeBuilder;
84 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.NodeKey;
85 import org.opendaylight.yangtools.concepts.ListenerRegistration;
86 import org.opendaylight.yangtools.concepts.ObjectRegistration;
87 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
88 import org.opendaylight.yangtools.yang.common.Uint16;
89 import org.opendaylight.yangtools.yang.model.repo.api.EffectiveModelContextFactory;
90 import org.opendaylight.yangtools.yang.model.repo.api.RevisionSourceIdentifier;
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 public class NetconfNodeManagerTest extends AbstractBaseSchemasTest {
103 private static final String ACTOR_SYSTEM_NAME = "test";
104 private static final RemoteDeviceId DEVICE_ID = new RemoteDeviceId("device", new InetSocketAddress(65535));
105 private static final List<SourceIdentifier> SOURCE_IDENTIFIERS =
106 ImmutableList.of(RevisionSourceIdentifier.create("testID"));
109 private DOMMountPointService mockMountPointService;
112 private DOMMountPointService.DOMMountPointBuilder mockMountPointBuilder;
115 private ObjectRegistration<DOMMountPoint> mockMountPointReg;
118 private DataBroker mockDataBroker;
121 private NetconfDataTreeService netconfService;
124 private DOMDataBroker mockDeviceDataBroker;
127 private DOMRpcService mockRpcService;
130 private DOMActionService mockActionService;
133 private NetconfDeviceSchemasResolver mockSchemasResolver;
136 private EffectiveModelContextFactory mockSchemaContextFactory;
138 private ActorSystem slaveSystem;
139 private ActorSystem masterSystem;
140 private TestActorRef<TestMasterActor> testMasterActorRef;
141 private NetconfNodeManager netconfNodeManager;
142 private String masterAddress;
145 public void setup() {
148 final Timeout responseTimeout = Timeout.apply(1, TimeUnit.SECONDS);
150 slaveSystem = ActorSystem.create(ACTOR_SYSTEM_NAME, ConfigFactory.load().getConfig("Slave"));
151 masterSystem = ActorSystem.create(ACTOR_SYSTEM_NAME, ConfigFactory.load().getConfig("Master"));
153 masterAddress = Cluster.get(masterSystem).selfAddress().toString();
155 SharedSchemaRepository masterSchemaRepository = new SharedSchemaRepository("master");
156 masterSchemaRepository.registerSchemaSourceListener(
157 TextToIRTransformer.create(masterSchemaRepository, masterSchemaRepository));
159 String yangTemplate =
161 + " namespace \"ID\";"
165 SOURCE_IDENTIFIERS.stream().map(
166 sourceId -> masterSchemaRepository.registerSchemaSource(
167 id -> Futures.immediateFuture(YangTextSchemaSource.delegateForByteSource(id,
168 ByteSource.wrap(yangTemplate.replaceAll("ID", id.getName()).getBytes(UTF_8)))),
169 PotentialSchemaSource.create(sourceId, YangTextSchemaSource.class, 1)))
170 .collect(Collectors.toList());
172 NetconfTopologySetup masterSetup = new NetconfTopologySetup.NetconfTopologySetupBuilder()
173 .setActorSystem(masterSystem).setDataBroker(mockDataBroker).setSchemaResourceDTO(
174 new NetconfDevice.SchemaResourcesDTO(masterSchemaRepository, masterSchemaRepository,
175 mockSchemaContextFactory, mockSchemasResolver)).setBaseSchemas(BASE_SCHEMAS).build();
177 testMasterActorRef = TestActorRef.create(masterSystem, Props.create(TestMasterActor.class, masterSetup,
178 DEVICE_ID, responseTimeout, mockMountPointService).withDispatcher(Dispatchers.DefaultDispatcherId()),
179 NetconfTopologyUtils.createMasterActorName(DEVICE_ID.getName(), masterAddress));
181 SharedSchemaRepository slaveSchemaRepository = new SharedSchemaRepository("slave");
182 slaveSchemaRepository.registerSchemaSourceListener(
183 TextToIRTransformer.create(slaveSchemaRepository, slaveSchemaRepository));
185 NetconfTopologySetup slaveSetup = new NetconfTopologySetup.NetconfTopologySetupBuilder()
186 .setActorSystem(slaveSystem).setDataBroker(mockDataBroker).setSchemaResourceDTO(
187 new NetconfDevice.SchemaResourcesDTO(slaveSchemaRepository, slaveSchemaRepository,
188 mockSchemaContextFactory, mockSchemasResolver)).setBaseSchemas(BASE_SCHEMAS).build();
190 netconfNodeManager = new NetconfNodeManager(slaveSetup, DEVICE_ID, responseTimeout,
191 mockMountPointService);
193 setupMountPointMocks();
197 public void teardown() {
198 TestKit.shutdownActorSystem(slaveSystem, true);
199 TestKit.shutdownActorSystem(masterSystem, true);
202 @SuppressWarnings("unchecked")
204 public void testSlaveMountPointRegistration() throws InterruptedException, ExecutionException, TimeoutException {
207 ListenerRegistration<?> mockListenerReg = mock(ListenerRegistration.class);
208 doReturn(mockListenerReg).when(mockDataBroker).registerDataTreeChangeListener(any(), any());
210 final NodeId nodeId = new NodeId("device");
211 final NodeKey nodeKey = new NodeKey(nodeId);
212 final String topologyId = "topology-netconf";
213 final InstanceIdentifier<Node> nodeListPath = NetconfTopologyUtils.createTopologyNodeListPath(
214 nodeKey, topologyId);
216 netconfNodeManager.registerDataTreeChangeListener(topologyId, nodeKey);
217 verify(mockDataBroker).registerDataTreeChangeListener(any(), eq(netconfNodeManager));
219 // Invoke onDataTreeChanged with a NetconfNode WRITE to simulate the master writing the operational state to
220 // Connected. Expect the slave mount point created and registered.
222 final NetconfNode netconfNode = newNetconfNode();
223 final Node node = new NodeBuilder().setNodeId(nodeId).addAugmentation(netconfNode).build();
225 DataObjectModification<Node> mockDataObjModification = mock(DataObjectModification.class);
226 doReturn(Iterables.getLast(nodeListPath.getPathArguments())).when(mockDataObjModification).getIdentifier();
227 doReturn(WRITE).when(mockDataObjModification).getModificationType();
228 doReturn(node).when(mockDataObjModification).getDataAfter();
230 netconfNodeManager.onDataTreeChanged(Collections.singletonList(
231 new NetconfTopologyManagerTest.CustomTreeModification(DataTreeIdentifier.create(
232 LogicalDatastoreType.OPERATIONAL, nodeListPath), mockDataObjModification)));
234 verify(mockMountPointBuilder, timeout(5000)).register();
235 verify(mockMountPointBuilder).addService(eq(DOMDataBroker.class), any());
236 verify(mockMountPointBuilder).addService(eq(DOMRpcService.class), any());
237 verify(mockMountPointBuilder).addService(eq(DOMNotificationService.class), any());
238 verify(mockMountPointService).createMountPoint(DEVICE_ID.getTopologyPath());
240 // Notify that the NetconfNode operational state was deleted. Expect the slave mount point closed.
242 doReturn(DELETE).when(mockDataObjModification).getModificationType();
243 doReturn(node).when(mockDataObjModification).getDataBefore();
244 doReturn(null).when(mockDataObjModification).getDataAfter();
246 netconfNodeManager.onDataTreeChanged(Collections.singletonList(
247 new NetconfTopologyManagerTest.CustomTreeModification(DataTreeIdentifier.create(
248 LogicalDatastoreType.OPERATIONAL, nodeListPath), mockDataObjModification)));
250 verify(mockMountPointReg, timeout(5000)).close();
252 // Notify with a NetconfNode operational state WRITE. Expect the slave mount point re-created.
254 setupMountPointMocks();
256 doReturn(WRITE).when(mockDataObjModification).getModificationType();
257 doReturn(null).when(mockDataObjModification).getDataBefore();
258 doReturn(node).when(mockDataObjModification).getDataAfter();
260 netconfNodeManager.onDataTreeChanged(Collections.singletonList(
261 new NetconfTopologyManagerTest.CustomTreeModification(DataTreeIdentifier.create(
262 LogicalDatastoreType.OPERATIONAL, nodeListPath), mockDataObjModification)));
264 verify(mockMountPointBuilder, timeout(5000)).register();
266 // Notify again with a NetconfNode operational state WRITE. Expect the prior slave mount point closed and
267 // and a new one registered.
269 setupMountPointMocks();
271 doReturn(node).when(mockDataObjModification).getDataBefore();
273 netconfNodeManager.onDataTreeChanged(Collections.singletonList(
274 new NetconfTopologyManagerTest.CustomTreeModification(DataTreeIdentifier.create(
275 LogicalDatastoreType.OPERATIONAL, nodeListPath), mockDataObjModification)));
277 verify(mockMountPointReg, timeout(5000)).close();
278 verify(mockMountPointBuilder, timeout(5000)).register();
280 // Notify that the NetconfNode operational state was changed to UnableToConnect. Expect the slave mount point
283 setupMountPointMocks();
285 final Node updatedNode = new NodeBuilder().setNodeId(nodeId)
286 .addAugmentation(new NetconfNodeBuilder(netconfNode)
287 .setConnectionStatus(NetconfNodeConnectionStatus.ConnectionStatus.UnableToConnect)
291 doReturn(SUBTREE_MODIFIED).when(mockDataObjModification).getModificationType();
292 doReturn(node).when(mockDataObjModification).getDataBefore();
293 doReturn(updatedNode).when(mockDataObjModification).getDataAfter();
295 netconfNodeManager.onDataTreeChanged(Collections.singletonList(
296 new NetconfTopologyManagerTest.CustomTreeModification(DataTreeIdentifier.create(
297 LogicalDatastoreType.OPERATIONAL, nodeListPath), mockDataObjModification)));
299 verify(mockMountPointReg, timeout(5000)).close();
301 netconfNodeManager.close();
302 verifyNoMoreInteractions(mockMountPointReg);
305 @SuppressWarnings("unchecked")
307 public void testSlaveMountPointRegistrationFailuresAndRetries()
308 throws InterruptedException, ExecutionException, TimeoutException {
309 final NodeId nodeId = new NodeId("device");
310 final NodeKey nodeKey = new NodeKey(nodeId);
311 final String topologyId = "topology-netconf";
312 final InstanceIdentifier<Node> nodeListPath = NetconfTopologyUtils.createTopologyNodeListPath(
313 nodeKey, topologyId);
315 final NetconfNode netconfNode = newNetconfNode();
316 final Node node = new NodeBuilder().setNodeId(nodeId).addAugmentation(netconfNode).build();
318 DataObjectModification<Node> mockDataObjModification = mock(DataObjectModification.class);
319 doReturn(Iterables.getLast(nodeListPath.getPathArguments())).when(mockDataObjModification).getIdentifier();
320 doReturn(WRITE).when(mockDataObjModification).getModificationType();
321 doReturn(node).when(mockDataObjModification).getDataAfter();
323 // First try the registration where the perceived master hasn't been initialized as the master.
325 netconfNodeManager.onDataTreeChanged(Collections.singletonList(
326 new NetconfTopologyManagerTest.CustomTreeModification(DataTreeIdentifier.create(
327 LogicalDatastoreType.OPERATIONAL, nodeListPath), mockDataObjModification)));
329 verify(mockMountPointBuilder, after(1000).never()).register();
331 // Initialize the master but drop the initial YangTextSchemaSourceRequest message sent to the master so
336 CompletableFuture<AskForMasterMountPoint> yangTextSchemaSourceRequestFuture = new CompletableFuture<>();
337 testMasterActorRef.underlyingActor().messagesToDrop.put(YangTextSchemaSourceRequest.class,
338 yangTextSchemaSourceRequestFuture);
340 netconfNodeManager.onDataTreeChanged(Collections.singletonList(
341 new NetconfTopologyManagerTest.CustomTreeModification(DataTreeIdentifier.create(
342 LogicalDatastoreType.OPERATIONAL, nodeListPath), mockDataObjModification)));
344 yangTextSchemaSourceRequestFuture.get(5, TimeUnit.SECONDS);
345 verify(mockMountPointBuilder, timeout(5000)).register();
347 // Initiate another registration but drop the initial AskForMasterMountPoint message sent to the master so
350 setupMountPointMocks();
352 CompletableFuture<AskForMasterMountPoint> askForMasterMountPointFuture = new CompletableFuture<>();
353 testMasterActorRef.underlyingActor().messagesToDrop.put(AskForMasterMountPoint.class,
354 askForMasterMountPointFuture);
356 netconfNodeManager.onDataTreeChanged(Collections.singletonList(
357 new NetconfTopologyManagerTest.CustomTreeModification(DataTreeIdentifier.create(
358 LogicalDatastoreType.OPERATIONAL, nodeListPath), mockDataObjModification)));
360 askForMasterMountPointFuture.get(5, TimeUnit.SECONDS);
361 verify(mockMountPointReg, timeout(5000)).close();
362 verify(mockMountPointBuilder, timeout(5000)).register();
364 setupMountPointMocks();
365 netconfNodeManager.close();
366 verify(mockMountPointReg, timeout(5000)).close();
369 private NetconfNode newNetconfNode() {
370 return new NetconfNodeBuilder()
371 .setHost(new Host(new IpAddress(new Ipv4Address("127.0.0.1"))))
372 .setPort(new PortNumber(Uint16.valueOf(9999)))
373 .setConnectionStatus(NetconfNodeConnectionStatus.ConnectionStatus.Connected)
374 .setClusteredConnectionStatus(new ClusteredConnectionStatusBuilder()
375 .setNetconfMasterNode(masterAddress).build())
379 private void setupMountPointMocks() {
380 reset(mockMountPointService, mockMountPointBuilder, mockMountPointReg);
382 doNothing().when(mockMountPointReg).close();
384 doReturn(mockMountPointBuilder).when(mockMountPointBuilder).addInitialSchemaContext(any());
385 doReturn(mockMountPointBuilder).when(mockMountPointBuilder).addService(any(), any());
386 doReturn(mockMountPointReg).when(mockMountPointBuilder).register();
388 doReturn(mockMountPointBuilder).when(mockMountPointService).createMountPoint(any());
391 private void initializeMaster() {
392 TestKit kit = new TestKit(masterSystem);
393 testMasterActorRef.tell(new CreateInitialMasterActorData(mockDeviceDataBroker, netconfService,
395 mockRpcService, mockActionService), kit.getRef());
397 kit.expectMsgClass(MasterActorDataInitialized.class);
400 private static class TestMasterActor extends NetconfNodeActor {
401 final Map<Class<?>, CompletableFuture<? extends Object>> messagesToDrop = new ConcurrentHashMap<>();
403 TestMasterActor(final NetconfTopologySetup setup, final RemoteDeviceId deviceId,
404 final Timeout actorResponseWaitTime, final DOMMountPointService mountPointService) {
405 super(setup, deviceId, actorResponseWaitTime, mountPointService);
408 @SuppressWarnings({ "rawtypes", "unchecked" })
410 public void handleReceive(final Object message) {
411 CompletableFuture dropFuture = messagesToDrop.remove(message.getClass());
412 if (dropFuture != null) {
413 dropFuture.complete(message);
415 super.handleReceive(message);