Use base64 encoding for netconf device passwords
[netconf.git] / apps / 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 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;
23
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;
37 import java.util.Map;
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.rev231121.ConnectionOper.ConnectionStatus;
79 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.device.rev231121.connection.oper.ClusteredConnectionStatusBuilder;
80 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev231121.NetconfNode;
81 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev231121.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;
96
97 /**
98  * Unit tests for NetconfNodeManager.
99  *
100  * @author Thomas Pantelis
101  */
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"));
107
108     @Mock
109     private DOMMountPointService mockMountPointService;
110     @Mock
111     private DOMMountPointService.DOMMountPointBuilder mockMountPointBuilder;
112     @Mock
113     private ObjectRegistration<DOMMountPoint> mockMountPointReg;
114     @Mock
115     private DataBroker mockDataBroker;
116     @Mock
117     private NetconfDataTreeService netconfService;
118     @Mock
119     private DOMDataBroker mockDeviceDataBroker;
120     @Mock
121     private Rpcs.Normalized mockRpcService;
122     @Mock
123     private Actions.Normalized mockActionService;
124     @Mock
125     private NetconfDeviceSchemasResolver mockSchemasResolver;
126     @Mock
127     private EffectiveModelContextFactory mockSchemaContextFactory;
128
129     private ActorSystem slaveSystem;
130     private ActorSystem masterSystem;
131     private TestActorRef<TestMasterActor> testMasterActorRef;
132     private NetconfNodeManager netconfNodeManager;
133     private String masterAddress;
134
135     @Before
136     public void setup() {
137         final Timeout responseTimeout = Timeout.apply(1, TimeUnit.SECONDS);
138
139         slaveSystem = ActorSystem.create(ACTOR_SYSTEM_NAME, ConfigFactory.load().getConfig("Slave"));
140         masterSystem = ActorSystem.create(ACTOR_SYSTEM_NAME, ConfigFactory.load().getConfig("Master"));
141
142         masterAddress = Cluster.get(masterSystem).selfAddress().toString();
143
144         SharedSchemaRepository masterSchemaRepository = new SharedSchemaRepository("master");
145         masterSchemaRepository.registerSchemaSourceListener(
146                 TextToIRTransformer.create(masterSchemaRepository, masterSchemaRepository));
147
148         final String yangTemplate = """
149             module ID {\
150               namespace "ID";\
151               prefix ID;\
152             }""";
153
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());
160
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)
167                 .build();
168
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));
172
173         SharedSchemaRepository slaveSchemaRepository = new SharedSchemaRepository("slave");
174         slaveSchemaRepository.registerSchemaSourceListener(
175                 TextToIRTransformer.create(slaveSchemaRepository, slaveSchemaRepository));
176
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)
183                 .build();
184
185         netconfNodeManager = new NetconfNodeManager(slaveSetup, DEVICE_ID, responseTimeout,
186                 mockMountPointService);
187
188         setupMountPointMocks();
189     }
190
191     @After
192     public void teardown() {
193         TestKit.shutdownActorSystem(slaveSystem, true);
194         TestKit.shutdownActorSystem(masterSystem, true);
195     }
196
197     @SuppressWarnings("unchecked")
198     @Test
199     public void testSlaveMountPointRegistration() throws InterruptedException, ExecutionException, TimeoutException {
200         initializeMaster();
201
202         ListenerRegistration<?> mockListenerReg = mock(ListenerRegistration.class);
203         doReturn(mockListenerReg).when(mockDataBroker).registerDataTreeChangeListener(any(), any());
204
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);
210
211         netconfNodeManager.registerDataTreeChangeListener(topologyId, nodeKey);
212         verify(mockDataBroker).registerDataTreeChangeListener(any(), eq(netconfNodeManager));
213
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.
216
217         final NetconfNode netconfNode = newNetconfNode();
218         final Node node = new NodeBuilder().setNodeId(nodeId).addAugmentation(netconfNode).build();
219
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();
224
225         netconfNodeManager.onDataTreeChanged(List.of(
226                 new NetconfTopologyManagerTest.CustomTreeModification(DataTreeIdentifier.create(
227                         LogicalDatastoreType.OPERATIONAL, nodeListPath), mockDataObjModification)));
228
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));
234
235         // Notify that the NetconfNode operational state was deleted. Expect the slave mount point closed.
236
237         doReturn(DELETE).when(mockDataObjModification).getModificationType();
238
239         netconfNodeManager.onDataTreeChanged(List.of(
240                 new NetconfTopologyManagerTest.CustomTreeModification(DataTreeIdentifier.create(
241                         LogicalDatastoreType.OPERATIONAL, nodeListPath), mockDataObjModification)));
242
243         verify(mockMountPointReg, timeout(5000)).close();
244
245         // Notify with a NetconfNode operational state WRITE. Expect the slave mount point re-created.
246
247         setupMountPointMocks();
248
249         doReturn(WRITE).when(mockDataObjModification).getModificationType();
250         doReturn(null).when(mockDataObjModification).getDataBefore();
251         doReturn(node).when(mockDataObjModification).getDataAfter();
252
253         netconfNodeManager.onDataTreeChanged(List.of(
254                 new NetconfTopologyManagerTest.CustomTreeModification(DataTreeIdentifier.create(
255                         LogicalDatastoreType.OPERATIONAL, nodeListPath), mockDataObjModification)));
256
257         verify(mockMountPointBuilder, timeout(5000)).register();
258
259         // Notify again with a NetconfNode operational state WRITE. Expect the prior slave mount point closed and
260         // and a new one registered.
261
262         setupMountPointMocks();
263
264         doReturn(node).when(mockDataObjModification).getDataBefore();
265
266         netconfNodeManager.onDataTreeChanged(List.of(
267                 new NetconfTopologyManagerTest.CustomTreeModification(DataTreeIdentifier.create(
268                         LogicalDatastoreType.OPERATIONAL, nodeListPath), mockDataObjModification)));
269
270         verify(mockMountPointReg, timeout(5000)).close();
271         verify(mockMountPointBuilder, timeout(5000)).register();
272
273         // Notify that the NetconfNode operational state was changed to UnableToConnect. Expect the slave mount point
274         // closed.
275
276         reset(mockMountPointService, mockMountPointBuilder, mockMountPointReg);
277         doNothing().when(mockMountPointReg).close();
278
279         final Node updatedNode = new NodeBuilder().setNodeId(nodeId)
280                 .addAugmentation(new NetconfNodeBuilder(netconfNode)
281                     .setConnectionStatus(ConnectionStatus.UnableToConnect)
282                     .build())
283                 .build();
284
285         doReturn(SUBTREE_MODIFIED).when(mockDataObjModification).getModificationType();
286         doReturn(node).when(mockDataObjModification).getDataBefore();
287         doReturn(updatedNode).when(mockDataObjModification).getDataAfter();
288
289         netconfNodeManager.onDataTreeChanged(List.of(
290                 new NetconfTopologyManagerTest.CustomTreeModification(DataTreeIdentifier.create(
291                         LogicalDatastoreType.OPERATIONAL, nodeListPath), mockDataObjModification)));
292
293         verify(mockMountPointReg, timeout(5000)).close();
294
295         netconfNodeManager.close();
296         verifyNoMoreInteractions(mockMountPointReg);
297     }
298
299     @SuppressWarnings("unchecked")
300     @Test
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);
308
309         final NetconfNode netconfNode = newNetconfNode();
310         final Node node = new NodeBuilder().setNodeId(nodeId).addAugmentation(netconfNode).build();
311
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();
316
317         // First try the registration where the perceived master hasn't been initialized as the master.
318
319         netconfNodeManager.onDataTreeChanged(List.of(
320                 new NetconfTopologyManagerTest.CustomTreeModification(DataTreeIdentifier.create(
321                         LogicalDatastoreType.OPERATIONAL, nodeListPath), mockDataObjModification)));
322
323         verify(mockMountPointBuilder, after(1000).never()).register();
324
325         // Initialize the master but drop the initial YangTextSchemaSourceRequest message sent to the master so
326         // it retries.
327
328         initializeMaster();
329
330         CompletableFuture<AskForMasterMountPoint> yangTextSchemaSourceRequestFuture = new CompletableFuture<>();
331         testMasterActorRef.underlyingActor().messagesToDrop.put(YangTextSchemaSourceRequest.class,
332                 yangTextSchemaSourceRequestFuture);
333
334         netconfNodeManager.onDataTreeChanged(List.of(
335                 new NetconfTopologyManagerTest.CustomTreeModification(DataTreeIdentifier.create(
336                         LogicalDatastoreType.OPERATIONAL, nodeListPath), mockDataObjModification)));
337
338         yangTextSchemaSourceRequestFuture.get(5, TimeUnit.SECONDS);
339         verify(mockMountPointBuilder, timeout(5000)).register();
340
341         // Initiate another registration but drop the initial AskForMasterMountPoint message sent to the master so
342         // it retries.
343
344         setupMountPointMocks();
345
346         CompletableFuture<AskForMasterMountPoint> askForMasterMountPointFuture = new CompletableFuture<>();
347         testMasterActorRef.underlyingActor().messagesToDrop.put(AskForMasterMountPoint.class,
348                 askForMasterMountPointFuture);
349
350         netconfNodeManager.onDataTreeChanged(List.of(
351                 new NetconfTopologyManagerTest.CustomTreeModification(DataTreeIdentifier.create(
352                         LogicalDatastoreType.OPERATIONAL, nodeListPath), mockDataObjModification)));
353
354         askForMasterMountPointFuture.get(5, TimeUnit.SECONDS);
355         verify(mockMountPointReg, timeout(5000)).close();
356         verify(mockMountPointBuilder, timeout(5000)).register();
357
358         reset(mockMountPointService, mockMountPointBuilder, mockMountPointReg);
359         doNothing().when(mockMountPointReg).close();
360         netconfNodeManager.close();
361         verify(mockMountPointReg, timeout(5000)).close();
362     }
363
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())
371                 .build();
372     }
373
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());
379     }
380
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());
385
386         kit.expectMsgClass(MasterActorDataInitialized.class);
387     }
388
389     private static class TestMasterActor extends NetconfNodeActor {
390         final Map<Class<?>, CompletableFuture<? extends Object>> messagesToDrop = new ConcurrentHashMap<>();
391
392         TestMasterActor(final NetconfTopologySetup setup, final RemoteDeviceId deviceId,
393                 final Timeout actorResponseWaitTime, final DOMMountPointService mountPointService) {
394             super(setup, deviceId, actorResponseWaitTime, mountPointService);
395         }
396
397         @SuppressWarnings({ "rawtypes", "unchecked" })
398         @Override
399         public void handleReceive(final Object message) {
400             CompletableFuture dropFuture = messagesToDrop.remove(message.getClass());
401             if (dropFuture != null) {
402                 dropFuture.complete(message);
403             } else {
404                 super.handleReceive(message);
405             }
406         }
407     }
408 }