Merge "Bug 8361 - NetconfConnector cannot be created due to NullPointerException"
[netconf.git] / netconf / netconf-topology-singleton / src / test / java / org / opendaylight / netconf / topology / singleton / impl / NetconfNodeActorTest.java
1 /*
2  * Copyright (c) 2016 Cisco Systems, Inc. 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
9 package org.opendaylight.netconf.topology.singleton.impl;
10
11 import static org.junit.Assert.assertEquals;
12 import static org.junit.Assert.assertNull;
13 import static org.junit.Assert.assertTrue;
14 import static org.mockito.Matchers.any;
15 import static org.mockito.Matchers.argThat;
16 import static org.mockito.Mockito.doReturn;
17 import static org.mockito.Mockito.mock;
18 import static org.mockito.Mockito.timeout;
19 import static org.mockito.Mockito.verify;
20 import static org.mockito.MockitoAnnotations.initMocks;
21 import static org.opendaylight.netconf.topology.singleton.impl.utils.NetconfTopologyUtils.DEFAULT_SCHEMA_REPOSITORY;
22
23 import akka.actor.ActorContext;
24 import akka.actor.ActorRef;
25 import akka.actor.ActorSystem;
26 import akka.actor.Props;
27 import akka.pattern.Patterns;
28 import akka.testkit.JavaTestKit;
29 import akka.testkit.TestActorRef;
30 import akka.util.Timeout;
31 import com.google.common.base.MoreObjects;
32 import com.google.common.base.Optional;
33 import com.google.common.collect.ImmutableList;
34 import com.google.common.collect.Lists;
35 import com.google.common.net.InetAddresses;
36 import com.google.common.util.concurrent.CheckedFuture;
37 import com.google.common.util.concurrent.Futures;
38 import com.google.common.util.concurrent.SettableFuture;
39 import java.io.ByteArrayInputStream;
40 import java.io.IOException;
41 import java.io.InputStream;
42 import java.net.InetSocketAddress;
43 import java.util.List;
44 import java.util.concurrent.TimeUnit;
45 import org.junit.After;
46 import org.junit.Before;
47 import org.junit.Rule;
48 import org.junit.Test;
49 import org.junit.rules.ExpectedException;
50 import org.mockito.ArgumentMatcher;
51 import org.mockito.Mock;
52 import org.opendaylight.controller.cluster.schema.provider.impl.YangTextSchemaSourceSerializationProxy;
53 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
54 import org.opendaylight.controller.md.sal.dom.api.DOMDataBroker;
55 import org.opendaylight.controller.md.sal.dom.api.DOMMountPointService;
56 import org.opendaylight.controller.md.sal.dom.api.DOMRpcException;
57 import org.opendaylight.controller.md.sal.dom.api.DOMRpcResult;
58 import org.opendaylight.controller.md.sal.dom.api.DOMRpcService;
59 import org.opendaylight.controller.md.sal.dom.spi.DefaultDOMRpcResult;
60 import org.opendaylight.netconf.sal.connect.util.RemoteDeviceId;
61 import org.opendaylight.netconf.topology.singleton.impl.actors.NetconfNodeActor;
62 import org.opendaylight.netconf.topology.singleton.impl.utils.ClusteringRpcException;
63 import org.opendaylight.netconf.topology.singleton.impl.utils.NetconfTopologySetup;
64 import org.opendaylight.netconf.topology.singleton.messages.AskForMasterMountPoint;
65 import org.opendaylight.netconf.topology.singleton.messages.CreateInitialMasterActorData;
66 import org.opendaylight.netconf.topology.singleton.messages.MasterActorDataInitialized;
67 import org.opendaylight.netconf.topology.singleton.messages.RefreshSetupMasterActorData;
68 import org.opendaylight.netconf.topology.singleton.messages.RegisterMountPoint;
69 import org.opendaylight.yangtools.yang.common.QName;
70 import org.opendaylight.yangtools.yang.common.RpcError;
71 import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
72 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
73 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
74 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
75 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableContainerNodeBuilder;
76 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
77 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
78 import org.opendaylight.yangtools.yang.model.repo.api.MissingSchemaSourceException;
79 import org.opendaylight.yangtools.yang.model.repo.api.RevisionSourceIdentifier;
80 import org.opendaylight.yangtools.yang.model.repo.api.SchemaContextFactory;
81 import org.opendaylight.yangtools.yang.model.repo.api.SchemaRepository;
82 import org.opendaylight.yangtools.yang.model.repo.api.SchemaResolutionException;
83 import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceException;
84 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
85 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
86 import org.opendaylight.yangtools.yang.model.repo.spi.PotentialSchemaSource;
87 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistration;
88 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistry;
89 import scala.concurrent.Await;
90 import scala.concurrent.Future;
91 import scala.concurrent.duration.Duration;
92
93 public class NetconfNodeActorTest {
94
95     private static final Timeout TIMEOUT = new Timeout(Duration.create(5, "seconds"));
96     private static ActorSystem system;
97
98     @Rule
99     public final ExpectedException exception = ExpectedException.none();
100
101     private ActorRef masterRef;
102     private RemoteDeviceId remoteDeviceId;
103
104     @Mock
105     private DOMRpcService domRpcService;
106     @Mock
107     private DOMMountPointService mountPointService;
108     @Mock
109     private DataBroker dataBroker;
110
111     @Before
112     public void setup() {
113         initMocks(this);
114         remoteDeviceId = new RemoteDeviceId("netconf-topology",
115                 new InetSocketAddress(InetAddresses.forString("127.0.0.1"), 9999));
116         final NetconfTopologySetup setup = mock(NetconfTopologySetup.class);
117
118         final Props props = NetconfNodeActor.props(setup, remoteDeviceId, DEFAULT_SCHEMA_REPOSITORY,
119                 DEFAULT_SCHEMA_REPOSITORY, TIMEOUT, mountPointService);
120
121         system = ActorSystem.create();
122
123         masterRef = TestActorRef.create(system, props, "master_messages");
124     }
125
126     @After
127     public void teardown() {
128         JavaTestKit.shutdownActorSystem(system);
129         system = null;
130     }
131
132     @Test
133     public void testInitDataMessages() throws Exception {
134
135         final DOMDataBroker domDataBroker = mock(DOMDataBroker.class);
136         final List<SourceIdentifier> sourceIdentifiers = Lists.newArrayList();
137
138         /* Test init master data */
139
140         final Future<Object> initialDataToActor =
141                 Patterns.ask(masterRef, new CreateInitialMasterActorData(domDataBroker, sourceIdentifiers,
142                                 domRpcService), TIMEOUT);
143
144         final Object success = Await.result(initialDataToActor, TIMEOUT.duration());
145         assertTrue(success instanceof MasterActorDataInitialized);
146
147
148         /* Test refresh master data */
149
150         final RemoteDeviceId remoteDeviceId2 = new RemoteDeviceId("netconf-topology2",
151                 new InetSocketAddress(InetAddresses.forString("127.0.0.2"), 9999));
152
153         final NetconfTopologySetup setup2 = mock(NetconfTopologySetup.class);
154
155         final Future<Object> refreshDataToActor =
156                 Patterns.ask(masterRef, new RefreshSetupMasterActorData(setup2, remoteDeviceId2),
157                         TIMEOUT);
158
159         final Object success2 = Await.result(refreshDataToActor, TIMEOUT.duration());
160         assertTrue(success2 instanceof MasterActorDataInitialized);
161
162     }
163
164     @Test
165     public void testRegisterMountPointMessage() throws Exception {
166
167         final DOMDataBroker domDataBroker = mock(DOMDataBroker.class);
168         final List<SourceIdentifier> sourceIdentifiers =
169                 Lists.newArrayList(RevisionSourceIdentifier.create("testID", Optional.absent()));
170
171         // init master data
172
173         final Future<Object> initialDataToActor =
174                 Patterns.ask(masterRef, new CreateInitialMasterActorData(domDataBroker, sourceIdentifiers,
175                                 domRpcService), TIMEOUT);
176
177         final Object successInit = Await.result(initialDataToActor, TIMEOUT.duration());
178
179         assertTrue(successInit instanceof MasterActorDataInitialized);
180
181         // test if slave get right identifiers from master
182
183         final Future<Object> registerMountPointFuture =
184                 Patterns.ask(masterRef, new AskForMasterMountPoint(),
185                         TIMEOUT);
186
187         final RegisterMountPoint success =
188                 (RegisterMountPoint) Await.result(registerMountPointFuture, TIMEOUT.duration());
189
190         assertEquals(sourceIdentifiers, success.getSourceIndentifiers());
191
192     }
193
194     @Test
195     public void testReceiveRegisterMountpoint() throws Exception {
196         final NetconfTopologySetup setup = mock(NetconfTopologySetup.class);
197         final RevisionSourceIdentifier yang1 = RevisionSourceIdentifier.create("yang1");
198         final RevisionSourceIdentifier yang2 = RevisionSourceIdentifier.create("yang2");
199         final SchemaSourceRegistry registry = mock(SchemaSourceRegistry.class);
200         final SchemaRepository schemaRepository = mock(SchemaRepository.class);
201         final SchemaSourceRegistration regYang1 = mock(SchemaSourceRegistration.class);
202         final SchemaSourceRegistration regYang2 = mock(SchemaSourceRegistration.class);
203         doReturn(regYang1).when(registry).registerSchemaSource(any(), withSourceId(yang1));
204         doReturn(regYang2).when(registry).registerSchemaSource(any(), withSourceId(yang2));
205         final SchemaContextFactory schemaContextFactory = mock(SchemaContextFactory.class);
206         doReturn(schemaContextFactory).when(schemaRepository).createSchemaContextFactory(any());
207         final SettableFuture<SchemaContext> schemaContextFuture = SettableFuture.create();
208         final CheckedFuture<SchemaContext, SchemaResolutionException> checkedFuture =
209                 Futures.makeChecked(schemaContextFuture, e -> new SchemaResolutionException("fail", e));
210         doReturn(checkedFuture).when(schemaContextFactory).createSchemaContext(any());
211         final ActorRef slaveRef =
212                 system.actorOf(NetconfNodeActor.props(setup, remoteDeviceId, registry, schemaRepository, TIMEOUT,
213                         mountPointService));
214         final List<SourceIdentifier> sources = ImmutableList.of(yang1, yang2);
215         slaveRef.tell(new RegisterMountPoint(sources), masterRef);
216
217         verify(registry, timeout(1000)).registerSchemaSource(any(), withSourceId(yang1));
218         verify(registry, timeout(1000)).registerSchemaSource(any(), withSourceId(yang2));
219         //stop actor
220         final Future<Boolean> stopFuture = Patterns.gracefulStop(slaveRef, TIMEOUT.duration());
221         Await.result(stopFuture, TIMEOUT.duration());
222         //provider should be deregistered
223         verify(regYang1).close();
224         verify(regYang2).close();
225     }
226
227     @Test
228     public void testYangTextSchemaSourceRequestMessage() throws Exception {
229         final SchemaRepository schemaRepository = mock(SchemaRepository.class);
230         final SourceIdentifier sourceIdentifier = RevisionSourceIdentifier.create("testID", Optional.absent());
231         final Props props = NetconfNodeActor.props(mock(NetconfTopologySetup.class), remoteDeviceId,
232                 DEFAULT_SCHEMA_REPOSITORY, schemaRepository, TIMEOUT, mountPointService);
233
234         final ActorRef actorRefSchemaRepo = TestActorRef.create(system, props, "master_mocked_schema_repository");
235         final ActorContext actorContext = mock(ActorContext.class);
236         doReturn(system.dispatcher()).when(actorContext).dispatcher();
237
238         final ProxyYangTextSourceProvider proxyYang =
239                 new ProxyYangTextSourceProvider(actorRefSchemaRepo, actorContext, TIMEOUT);
240         // test if asking for source is resolved and sended back
241
242         final YangTextSchemaSource yangTextSchemaSource = new YangTextSchemaSource(sourceIdentifier) {
243             @Override
244             protected MoreObjects.ToStringHelper addToStringAttributes(
245                     final MoreObjects.ToStringHelper toStringHelper) {
246                 return null;
247             }
248
249             @Override
250             public InputStream openStream() throws IOException {
251                 return new ByteArrayInputStream("YANG".getBytes());
252             }
253         };
254
255
256         final CheckedFuture<YangTextSchemaSource, SchemaSourceException> result =
257                 Futures.immediateCheckedFuture(yangTextSchemaSource);
258
259         doReturn(result).when(schemaRepository).getSchemaSource(sourceIdentifier, YangTextSchemaSource.class);
260
261         final Future<YangTextSchemaSourceSerializationProxy> resolvedSchema =
262                 proxyYang.getYangTextSchemaSource(sourceIdentifier);
263
264         final YangTextSchemaSourceSerializationProxy success = Await.result(resolvedSchema, TIMEOUT.duration());
265
266         assertEquals(sourceIdentifier, success.getRepresentation().getIdentifier());
267         assertEquals("YANG", convertStreamToString(success.getRepresentation().openStream()));
268
269
270         // test if asking for source is missing
271         exception.expect(MissingSchemaSourceException.class);
272
273         final SchemaSourceException schemaSourceException =
274                 new MissingSchemaSourceException("Fail", sourceIdentifier);
275
276         final CheckedFuture<YangTextSchemaSource, SchemaSourceException> resultFail =
277                 Futures.immediateFailedCheckedFuture(schemaSourceException);
278
279         doReturn(resultFail).when(schemaRepository).getSchemaSource(sourceIdentifier, YangTextSchemaSource.class);
280
281         final Future<YangTextSchemaSourceSerializationProxy> failedSchema =
282                 proxyYang.getYangTextSchemaSource(sourceIdentifier);
283
284         Await.result(failedSchema, TIMEOUT.duration());
285
286     }
287
288     @Test
289     public void testProxyDOMRpcService() throws Exception {
290
291         final DOMDataBroker domDataBroker = mock(DOMDataBroker.class);
292         final List<SourceIdentifier> sourceIdentifiers =
293                 Lists.newArrayList(RevisionSourceIdentifier.create("testID", Optional.absent()));
294
295         // init master data
296
297         final Future<Object> initialDataToActor =
298                 Patterns.ask(masterRef, new CreateInitialMasterActorData(domDataBroker, sourceIdentifiers,
299                         domRpcService), TIMEOUT);
300
301         final Object successInit = Await.result(initialDataToActor, TIMEOUT.duration());
302
303         assertTrue(successInit instanceof MasterActorDataInitialized);
304
305         // test if slave get right identifiers from master
306
307         final ProxyDOMRpcService slaveDomRPCService =
308                 new ProxyDOMRpcService(system, masterRef, remoteDeviceId, TIMEOUT);
309
310         final SchemaPath schemaPath = SchemaPath.create(true, QName.create("TestQname"));
311         final NormalizedNode<?, ?> outputNode = ImmutableContainerNodeBuilder.create()
312                 .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(QName.create("TestQname")))
313                 .withChild(ImmutableNodes.leafNode(QName.create("NodeQname"), "foo")).build();
314         final RpcError rpcError = RpcResultBuilder.newError(RpcError.ErrorType.RPC, null, "Rpc invocation failed.");
315         // EmptyResultResponse message
316
317         doReturn(Futures.immediateCheckedFuture(null)).when(domRpcService).invokeRpc(any(), any());
318
319         final CheckedFuture<DOMRpcResult, DOMRpcException> resultFutureEmpty =
320                 slaveDomRPCService.invokeRpc(schemaPath, outputNode);
321
322         final Object resultNull = resultFutureEmpty.checkedGet(2, TimeUnit.SECONDS);
323
324         assertEquals(null, resultNull);
325
326         // InvokeRpcMessageReply message
327
328         doReturn(Futures.immediateCheckedFuture(new DefaultDOMRpcResult(outputNode)))
329                 .when(domRpcService).invokeRpc(any(), any());
330
331         final CheckedFuture<DOMRpcResult, DOMRpcException> resultFutureNn =
332                 slaveDomRPCService.invokeRpc(schemaPath, outputNode);
333
334         final DOMRpcResult resultNn = resultFutureNn.checkedGet(2, TimeUnit.SECONDS);
335
336         assertEquals(outputNode, resultNn.getResult());
337         assertTrue(resultNn.getErrors().isEmpty());
338
339         // InvokeRpcMessageReply message only error
340
341         doReturn(Futures.immediateCheckedFuture(new DefaultDOMRpcResult(rpcError)))
342                 .when(domRpcService).invokeRpc(any(), any());
343
344         final CheckedFuture<DOMRpcResult, DOMRpcException> resultFutureError =
345                 slaveDomRPCService.invokeRpc(schemaPath, outputNode);
346
347         final DOMRpcResult resultError = resultFutureError.checkedGet(2, TimeUnit.SECONDS);
348
349         assertNull(resultError.getResult());
350         assertEquals(rpcError, resultError.getErrors().iterator().next());
351
352         // InvokeRpcMessageReply message error + result
353
354         doReturn(Futures.immediateCheckedFuture(new DefaultDOMRpcResult(outputNode, rpcError)))
355                 .when(domRpcService).invokeRpc(any(), any());
356
357         final CheckedFuture<DOMRpcResult, DOMRpcException> resultFutureOutputError =
358                 slaveDomRPCService.invokeRpc(schemaPath, outputNode);
359
360         final DOMRpcResult resultOutputError = resultFutureOutputError.checkedGet(2, TimeUnit.SECONDS);
361
362         assertEquals(outputNode, resultOutputError.getResult());
363         assertEquals(rpcError, resultOutputError.getErrors().iterator().next());
364
365         // Throwable message
366
367         exception.expect(DOMRpcException.class);
368
369         doReturn(Futures.immediateFailedCheckedFuture(new ClusteringRpcException("")))
370                 .when(domRpcService).invokeRpc(any(), any());
371
372         final CheckedFuture<DOMRpcResult, DOMRpcException> resultFutureThrowable =
373                 slaveDomRPCService.invokeRpc(schemaPath, outputNode);
374
375         resultFutureThrowable.checkedGet(2, TimeUnit.SECONDS);
376
377     }
378
379     private PotentialSchemaSource<?> withSourceId(final SourceIdentifier identifier) {
380         return argThat(new ArgumentMatcher<PotentialSchemaSource>() {
381             @Override
382             public boolean matches(final Object argument) {
383                 final PotentialSchemaSource potentialSchemaSource = (PotentialSchemaSource) argument;
384                 return identifier.equals(potentialSchemaSource.getSourceIdentifier());
385             }
386         });
387     }
388
389     private String convertStreamToString(final java.io.InputStream is) {
390         final java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");
391         return s.hasNext() ? s.next() : "";
392     }
393
394 }