Bump MRI projects
[netconf.git] / netconf / netconf-topology-singleton / src / test / java / org / opendaylight / netconf / topology / singleton / impl / NetconfNodeManagerTest.java
1 /*
2  * Copyright (c) 2018 Inocybe Technologies and others.  All rights reserved.
3  *
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
7  */
8 package org.opendaylight.netconf.topology.singleton.impl;
9
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;
25
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;
41 import java.util.Map;
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;
96
97 /**
98  * Unit tests for NetconfNodeManager.
99  *
100  * @author Thomas Pantelis
101  */
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"));
107
108     @Mock
109     private DOMMountPointService mockMountPointService;
110
111     @Mock
112     private DOMMountPointService.DOMMountPointBuilder mockMountPointBuilder;
113
114     @Mock
115     private ObjectRegistration<DOMMountPoint> mockMountPointReg;
116
117     @Mock
118     private DataBroker mockDataBroker;
119
120     @Mock
121     private NetconfDataTreeService netconfService;
122
123     @Mock
124     private DOMDataBroker mockDeviceDataBroker;
125
126     @Mock
127     private DOMRpcService mockRpcService;
128
129     @Mock
130     private DOMActionService mockActionService;
131
132     @Mock
133     private NetconfDeviceSchemasResolver mockSchemasResolver;
134
135     @Mock
136     private EffectiveModelContextFactory mockSchemaContextFactory;
137
138     private ActorSystem slaveSystem;
139     private ActorSystem masterSystem;
140     private TestActorRef<TestMasterActor> testMasterActorRef;
141     private NetconfNodeManager netconfNodeManager;
142     private String masterAddress;
143
144     @Before
145     public void setup() {
146         initMocks(this);
147
148         final Timeout responseTimeout = Timeout.apply(1, TimeUnit.SECONDS);
149
150         slaveSystem = ActorSystem.create(ACTOR_SYSTEM_NAME, ConfigFactory.load().getConfig("Slave"));
151         masterSystem = ActorSystem.create(ACTOR_SYSTEM_NAME, ConfigFactory.load().getConfig("Master"));
152
153         masterAddress = Cluster.get(masterSystem).selfAddress().toString();
154
155         SharedSchemaRepository masterSchemaRepository = new SharedSchemaRepository("master");
156         masterSchemaRepository.registerSchemaSourceListener(
157                 TextToIRTransformer.create(masterSchemaRepository, masterSchemaRepository));
158
159         String yangTemplate =
160                   "module ID {"
161                 + "  namespace \"ID\";"
162                 + "  prefix ID;"
163                 + "}";
164
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());
171
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();
176
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));
180
181         SharedSchemaRepository slaveSchemaRepository = new SharedSchemaRepository("slave");
182         slaveSchemaRepository.registerSchemaSourceListener(
183                 TextToIRTransformer.create(slaveSchemaRepository, slaveSchemaRepository));
184
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();
189
190         netconfNodeManager = new NetconfNodeManager(slaveSetup, DEVICE_ID, responseTimeout,
191                 mockMountPointService);
192
193         setupMountPointMocks();
194     }
195
196     @After
197     public void teardown() {
198         TestKit.shutdownActorSystem(slaveSystem, true);
199         TestKit.shutdownActorSystem(masterSystem, true);
200     }
201
202     @SuppressWarnings("unchecked")
203     @Test
204     public void testSlaveMountPointRegistration() throws InterruptedException, ExecutionException, TimeoutException {
205         initializeMaster();
206
207         ListenerRegistration<?> mockListenerReg = mock(ListenerRegistration.class);
208         doReturn(mockListenerReg).when(mockDataBroker).registerDataTreeChangeListener(any(), any());
209
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);
215
216         netconfNodeManager.registerDataTreeChangeListener(topologyId, nodeKey);
217         verify(mockDataBroker).registerDataTreeChangeListener(any(), eq(netconfNodeManager));
218
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.
221
222         final NetconfNode netconfNode = newNetconfNode();
223         final Node node = new NodeBuilder().setNodeId(nodeId).addAugmentation(netconfNode).build();
224
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();
229
230         netconfNodeManager.onDataTreeChanged(Collections.singletonList(
231                 new NetconfTopologyManagerTest.CustomTreeModification(DataTreeIdentifier.create(
232                         LogicalDatastoreType.OPERATIONAL, nodeListPath), mockDataObjModification)));
233
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());
239
240         // Notify that the NetconfNode operational state was deleted. Expect the slave mount point closed.
241
242         doReturn(DELETE).when(mockDataObjModification).getModificationType();
243         doReturn(node).when(mockDataObjModification).getDataBefore();
244         doReturn(null).when(mockDataObjModification).getDataAfter();
245
246         netconfNodeManager.onDataTreeChanged(Collections.singletonList(
247                 new NetconfTopologyManagerTest.CustomTreeModification(DataTreeIdentifier.create(
248                         LogicalDatastoreType.OPERATIONAL, nodeListPath), mockDataObjModification)));
249
250         verify(mockMountPointReg, timeout(5000)).close();
251
252         // Notify with a NetconfNode operational state WRITE. Expect the slave mount point re-created.
253
254         setupMountPointMocks();
255
256         doReturn(WRITE).when(mockDataObjModification).getModificationType();
257         doReturn(null).when(mockDataObjModification).getDataBefore();
258         doReturn(node).when(mockDataObjModification).getDataAfter();
259
260         netconfNodeManager.onDataTreeChanged(Collections.singletonList(
261                 new NetconfTopologyManagerTest.CustomTreeModification(DataTreeIdentifier.create(
262                         LogicalDatastoreType.OPERATIONAL, nodeListPath), mockDataObjModification)));
263
264         verify(mockMountPointBuilder, timeout(5000)).register();
265
266         // Notify again with a NetconfNode operational state WRITE. Expect the prior slave mount point closed and
267         // and a new one registered.
268
269         setupMountPointMocks();
270
271         doReturn(node).when(mockDataObjModification).getDataBefore();
272
273         netconfNodeManager.onDataTreeChanged(Collections.singletonList(
274                 new NetconfTopologyManagerTest.CustomTreeModification(DataTreeIdentifier.create(
275                         LogicalDatastoreType.OPERATIONAL, nodeListPath), mockDataObjModification)));
276
277         verify(mockMountPointReg, timeout(5000)).close();
278         verify(mockMountPointBuilder, timeout(5000)).register();
279
280         // Notify that the NetconfNode operational state was changed to UnableToConnect. Expect the slave mount point
281         // closed.
282
283         setupMountPointMocks();
284
285         final Node updatedNode = new NodeBuilder().setNodeId(nodeId)
286                 .addAugmentation(new NetconfNodeBuilder(netconfNode)
287                     .setConnectionStatus(NetconfNodeConnectionStatus.ConnectionStatus.UnableToConnect)
288                     .build())
289                 .build();
290
291         doReturn(SUBTREE_MODIFIED).when(mockDataObjModification).getModificationType();
292         doReturn(node).when(mockDataObjModification).getDataBefore();
293         doReturn(updatedNode).when(mockDataObjModification).getDataAfter();
294
295         netconfNodeManager.onDataTreeChanged(Collections.singletonList(
296                 new NetconfTopologyManagerTest.CustomTreeModification(DataTreeIdentifier.create(
297                         LogicalDatastoreType.OPERATIONAL, nodeListPath), mockDataObjModification)));
298
299         verify(mockMountPointReg, timeout(5000)).close();
300
301         netconfNodeManager.close();
302         verifyNoMoreInteractions(mockMountPointReg);
303     }
304
305     @SuppressWarnings("unchecked")
306     @Test
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);
314
315         final NetconfNode netconfNode = newNetconfNode();
316         final Node node = new NodeBuilder().setNodeId(nodeId).addAugmentation(netconfNode).build();
317
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();
322
323         // First try the registration where the perceived master hasn't been initialized as the master.
324
325         netconfNodeManager.onDataTreeChanged(Collections.singletonList(
326                 new NetconfTopologyManagerTest.CustomTreeModification(DataTreeIdentifier.create(
327                         LogicalDatastoreType.OPERATIONAL, nodeListPath), mockDataObjModification)));
328
329         verify(mockMountPointBuilder, after(1000).never()).register();
330
331         // Initialize the master but drop the initial YangTextSchemaSourceRequest message sent to the master so
332         // it retries.
333
334         initializeMaster();
335
336         CompletableFuture<AskForMasterMountPoint> yangTextSchemaSourceRequestFuture = new CompletableFuture<>();
337         testMasterActorRef.underlyingActor().messagesToDrop.put(YangTextSchemaSourceRequest.class,
338                 yangTextSchemaSourceRequestFuture);
339
340         netconfNodeManager.onDataTreeChanged(Collections.singletonList(
341                 new NetconfTopologyManagerTest.CustomTreeModification(DataTreeIdentifier.create(
342                         LogicalDatastoreType.OPERATIONAL, nodeListPath), mockDataObjModification)));
343
344         yangTextSchemaSourceRequestFuture.get(5, TimeUnit.SECONDS);
345         verify(mockMountPointBuilder, timeout(5000)).register();
346
347         // Initiate another registration but drop the initial AskForMasterMountPoint message sent to the master so
348         // it retries.
349
350         setupMountPointMocks();
351
352         CompletableFuture<AskForMasterMountPoint> askForMasterMountPointFuture = new CompletableFuture<>();
353         testMasterActorRef.underlyingActor().messagesToDrop.put(AskForMasterMountPoint.class,
354                 askForMasterMountPointFuture);
355
356         netconfNodeManager.onDataTreeChanged(Collections.singletonList(
357                 new NetconfTopologyManagerTest.CustomTreeModification(DataTreeIdentifier.create(
358                         LogicalDatastoreType.OPERATIONAL, nodeListPath), mockDataObjModification)));
359
360         askForMasterMountPointFuture.get(5, TimeUnit.SECONDS);
361         verify(mockMountPointReg, timeout(5000)).close();
362         verify(mockMountPointBuilder, timeout(5000)).register();
363
364         setupMountPointMocks();
365         netconfNodeManager.close();
366         verify(mockMountPointReg, timeout(5000)).close();
367     }
368
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())
376                 .build();
377     }
378
379     private void setupMountPointMocks() {
380         reset(mockMountPointService, mockMountPointBuilder, mockMountPointReg);
381
382         doNothing().when(mockMountPointReg).close();
383
384         doReturn(mockMountPointBuilder).when(mockMountPointBuilder).addInitialSchemaContext(any());
385         doReturn(mockMountPointBuilder).when(mockMountPointBuilder).addService(any(), any());
386         doReturn(mockMountPointReg).when(mockMountPointBuilder).register();
387
388         doReturn(mockMountPointBuilder).when(mockMountPointService).createMountPoint(any());
389     }
390
391     private void initializeMaster() {
392         TestKit kit = new TestKit(masterSystem);
393         testMasterActorRef.tell(new CreateInitialMasterActorData(mockDeviceDataBroker, netconfService,
394             SOURCE_IDENTIFIERS,
395                 mockRpcService, mockActionService), kit.getRef());
396
397         kit.expectMsgClass(MasterActorDataInitialized.class);
398     }
399
400     private static class TestMasterActor extends NetconfNodeActor {
401         final Map<Class<?>, CompletableFuture<? extends Object>> messagesToDrop = new ConcurrentHashMap<>();
402
403         TestMasterActor(final NetconfTopologySetup setup, final RemoteDeviceId deviceId,
404                 final Timeout actorResponseWaitTime, final DOMMountPointService mountPointService) {
405             super(setup, deviceId, actorResponseWaitTime, mountPointService);
406         }
407
408         @SuppressWarnings({ "rawtypes", "unchecked" })
409         @Override
410         public void handleReceive(final Object message) {
411             CompletableFuture dropFuture = messagesToDrop.remove(message.getClass());
412             if (dropFuture != null) {
413                 dropFuture.complete(message);
414             } else {
415                 super.handleReceive(message);
416             }
417         }
418     }
419 }