2 * Copyright (c) 2016 Cisco Systems, Inc. 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
9 package org.opendaylight.netconf.topology.singleton.impl;
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;
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;
93 public class NetconfNodeActorTest {
95 private static final Timeout TIMEOUT = new Timeout(Duration.create(5, "seconds"));
96 private static ActorSystem system;
99 public final ExpectedException exception = ExpectedException.none();
101 private ActorRef masterRef;
102 private RemoteDeviceId remoteDeviceId;
105 private DOMRpcService domRpcService;
107 private DOMMountPointService mountPointService;
109 private DataBroker dataBroker;
112 public void setup() {
114 remoteDeviceId = new RemoteDeviceId("netconf-topology",
115 new InetSocketAddress(InetAddresses.forString("127.0.0.1"), 9999));
116 final NetconfTopologySetup setup = mock(NetconfTopologySetup.class);
118 final Props props = NetconfNodeActor.props(setup, remoteDeviceId, DEFAULT_SCHEMA_REPOSITORY,
119 DEFAULT_SCHEMA_REPOSITORY, TIMEOUT, mountPointService);
121 system = ActorSystem.create();
123 masterRef = TestActorRef.create(system, props, "master_messages");
127 public void teardown() {
128 JavaTestKit.shutdownActorSystem(system);
133 public void testInitDataMessages() throws Exception {
135 final DOMDataBroker domDataBroker = mock(DOMDataBroker.class);
136 final List<SourceIdentifier> sourceIdentifiers = Lists.newArrayList();
138 /* Test init master data */
140 final Future<Object> initialDataToActor =
141 Patterns.ask(masterRef, new CreateInitialMasterActorData(domDataBroker, sourceIdentifiers,
142 domRpcService), TIMEOUT);
144 final Object success = Await.result(initialDataToActor, TIMEOUT.duration());
145 assertTrue(success instanceof MasterActorDataInitialized);
148 /* Test refresh master data */
150 final RemoteDeviceId remoteDeviceId2 = new RemoteDeviceId("netconf-topology2",
151 new InetSocketAddress(InetAddresses.forString("127.0.0.2"), 9999));
153 final NetconfTopologySetup setup2 = mock(NetconfTopologySetup.class);
155 final Future<Object> refreshDataToActor =
156 Patterns.ask(masterRef, new RefreshSetupMasterActorData(setup2, remoteDeviceId2),
159 final Object success2 = Await.result(refreshDataToActor, TIMEOUT.duration());
160 assertTrue(success2 instanceof MasterActorDataInitialized);
165 public void testRegisterMountPointMessage() throws Exception {
167 final DOMDataBroker domDataBroker = mock(DOMDataBroker.class);
168 final List<SourceIdentifier> sourceIdentifiers =
169 Lists.newArrayList(RevisionSourceIdentifier.create("testID", Optional.absent()));
173 final Future<Object> initialDataToActor =
174 Patterns.ask(masterRef, new CreateInitialMasterActorData(domDataBroker, sourceIdentifiers,
175 domRpcService), TIMEOUT);
177 final Object successInit = Await.result(initialDataToActor, TIMEOUT.duration());
179 assertTrue(successInit instanceof MasterActorDataInitialized);
181 // test if slave get right identifiers from master
183 final Future<Object> registerMountPointFuture =
184 Patterns.ask(masterRef, new AskForMasterMountPoint(),
187 final RegisterMountPoint success =
188 (RegisterMountPoint) Await.result(registerMountPointFuture, TIMEOUT.duration());
190 assertEquals(sourceIdentifiers, success.getSourceIndentifiers());
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,
214 final List<SourceIdentifier> sources = ImmutableList.of(yang1, yang2);
215 slaveRef.tell(new RegisterMountPoint(sources), masterRef);
217 verify(registry, timeout(1000)).registerSchemaSource(any(), withSourceId(yang1));
218 verify(registry, timeout(1000)).registerSchemaSource(any(), withSourceId(yang2));
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();
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);
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();
238 final ProxyYangTextSourceProvider proxyYang =
239 new ProxyYangTextSourceProvider(actorRefSchemaRepo, actorContext, TIMEOUT);
240 // test if asking for source is resolved and sended back
242 final YangTextSchemaSource yangTextSchemaSource = new YangTextSchemaSource(sourceIdentifier) {
244 protected MoreObjects.ToStringHelper addToStringAttributes(
245 final MoreObjects.ToStringHelper toStringHelper) {
250 public InputStream openStream() throws IOException {
251 return new ByteArrayInputStream("YANG".getBytes());
256 final CheckedFuture<YangTextSchemaSource, SchemaSourceException> result =
257 Futures.immediateCheckedFuture(yangTextSchemaSource);
259 doReturn(result).when(schemaRepository).getSchemaSource(sourceIdentifier, YangTextSchemaSource.class);
261 final Future<YangTextSchemaSourceSerializationProxy> resolvedSchema =
262 proxyYang.getYangTextSchemaSource(sourceIdentifier);
264 final YangTextSchemaSourceSerializationProxy success = Await.result(resolvedSchema, TIMEOUT.duration());
266 assertEquals(sourceIdentifier, success.getRepresentation().getIdentifier());
267 assertEquals("YANG", convertStreamToString(success.getRepresentation().openStream()));
270 // test if asking for source is missing
271 exception.expect(MissingSchemaSourceException.class);
273 final SchemaSourceException schemaSourceException =
274 new MissingSchemaSourceException("Fail", sourceIdentifier);
276 final CheckedFuture<YangTextSchemaSource, SchemaSourceException> resultFail =
277 Futures.immediateFailedCheckedFuture(schemaSourceException);
279 doReturn(resultFail).when(schemaRepository).getSchemaSource(sourceIdentifier, YangTextSchemaSource.class);
281 final Future<YangTextSchemaSourceSerializationProxy> failedSchema =
282 proxyYang.getYangTextSchemaSource(sourceIdentifier);
284 Await.result(failedSchema, TIMEOUT.duration());
289 public void testProxyDOMRpcService() throws Exception {
291 final DOMDataBroker domDataBroker = mock(DOMDataBroker.class);
292 final List<SourceIdentifier> sourceIdentifiers =
293 Lists.newArrayList(RevisionSourceIdentifier.create("testID", Optional.absent()));
297 final Future<Object> initialDataToActor =
298 Patterns.ask(masterRef, new CreateInitialMasterActorData(domDataBroker, sourceIdentifiers,
299 domRpcService), TIMEOUT);
301 final Object successInit = Await.result(initialDataToActor, TIMEOUT.duration());
303 assertTrue(successInit instanceof MasterActorDataInitialized);
305 // test if slave get right identifiers from master
307 final ProxyDOMRpcService slaveDomRPCService =
308 new ProxyDOMRpcService(system, masterRef, remoteDeviceId, TIMEOUT);
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
317 doReturn(Futures.immediateCheckedFuture(null)).when(domRpcService).invokeRpc(any(), any());
319 final CheckedFuture<DOMRpcResult, DOMRpcException> resultFutureEmpty =
320 slaveDomRPCService.invokeRpc(schemaPath, outputNode);
322 final Object resultNull = resultFutureEmpty.checkedGet(2, TimeUnit.SECONDS);
324 assertEquals(null, resultNull);
326 // InvokeRpcMessageReply message
328 doReturn(Futures.immediateCheckedFuture(new DefaultDOMRpcResult(outputNode)))
329 .when(domRpcService).invokeRpc(any(), any());
331 final CheckedFuture<DOMRpcResult, DOMRpcException> resultFutureNn =
332 slaveDomRPCService.invokeRpc(schemaPath, outputNode);
334 final DOMRpcResult resultNn = resultFutureNn.checkedGet(2, TimeUnit.SECONDS);
336 assertEquals(outputNode, resultNn.getResult());
337 assertTrue(resultNn.getErrors().isEmpty());
339 // InvokeRpcMessageReply message only error
341 doReturn(Futures.immediateCheckedFuture(new DefaultDOMRpcResult(rpcError)))
342 .when(domRpcService).invokeRpc(any(), any());
344 final CheckedFuture<DOMRpcResult, DOMRpcException> resultFutureError =
345 slaveDomRPCService.invokeRpc(schemaPath, outputNode);
347 final DOMRpcResult resultError = resultFutureError.checkedGet(2, TimeUnit.SECONDS);
349 assertNull(resultError.getResult());
350 assertEquals(rpcError, resultError.getErrors().iterator().next());
352 // InvokeRpcMessageReply message error + result
354 doReturn(Futures.immediateCheckedFuture(new DefaultDOMRpcResult(outputNode, rpcError)))
355 .when(domRpcService).invokeRpc(any(), any());
357 final CheckedFuture<DOMRpcResult, DOMRpcException> resultFutureOutputError =
358 slaveDomRPCService.invokeRpc(schemaPath, outputNode);
360 final DOMRpcResult resultOutputError = resultFutureOutputError.checkedGet(2, TimeUnit.SECONDS);
362 assertEquals(outputNode, resultOutputError.getResult());
363 assertEquals(rpcError, resultOutputError.getErrors().iterator().next());
367 exception.expect(DOMRpcException.class);
369 doReturn(Futures.immediateFailedCheckedFuture(new ClusteringRpcException("")))
370 .when(domRpcService).invokeRpc(any(), any());
372 final CheckedFuture<DOMRpcResult, DOMRpcException> resultFutureThrowable =
373 slaveDomRPCService.invokeRpc(schemaPath, outputNode);
375 resultFutureThrowable.checkedGet(2, TimeUnit.SECONDS);
379 private PotentialSchemaSource<?> withSourceId(final SourceIdentifier identifier) {
380 return argThat(new ArgumentMatcher<PotentialSchemaSource>() {
382 public boolean matches(final Object argument) {
383 final PotentialSchemaSource potentialSchemaSource = (PotentialSchemaSource) argument;
384 return identifier.equals(potentialSchemaSource.getSourceIdentifier());
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() : "";