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() {
115 remoteDeviceId = new RemoteDeviceId("netconf-topology",
116 new InetSocketAddress(InetAddresses.forString("127.0.0.1"), 9999));
117 final NetconfTopologySetup setup = mock(NetconfTopologySetup.class);
119 final Props props = NetconfNodeActor.props(setup, remoteDeviceId, DEFAULT_SCHEMA_REPOSITORY,
120 DEFAULT_SCHEMA_REPOSITORY, TIMEOUT, mountPointService);
122 system = ActorSystem.create();
124 masterRef = TestActorRef.create(system, props, "master_messages");
128 public void teardown() {
129 JavaTestKit.shutdownActorSystem(system);
134 public void testInitDataMessages() throws Exception {
136 final DOMDataBroker domDataBroker = mock(DOMDataBroker.class);
137 final List<SourceIdentifier> sourceIdentifiers = Lists.newArrayList();
139 /* Test init master data */
141 final Future<Object> initialDataToActor =
142 Patterns.ask(masterRef, new CreateInitialMasterActorData(domDataBroker, sourceIdentifiers,
143 domRpcService), TIMEOUT);
145 final Object success = Await.result(initialDataToActor, TIMEOUT.duration());
146 assertTrue(success instanceof MasterActorDataInitialized);
149 /* Test refresh master data */
151 final RemoteDeviceId remoteDeviceId2 = new RemoteDeviceId("netconf-topology2",
152 new InetSocketAddress(InetAddresses.forString("127.0.0.2"), 9999));
154 final NetconfTopologySetup setup2 = mock(NetconfTopologySetup.class);
156 final Future<Object> refreshDataToActor =
157 Patterns.ask(masterRef, new RefreshSetupMasterActorData(setup2, remoteDeviceId2),
160 final Object success2 = Await.result(refreshDataToActor, TIMEOUT.duration());
161 assertTrue(success2 instanceof MasterActorDataInitialized);
166 public void testRegisterMountPointMessage() throws Exception {
168 final DOMDataBroker domDataBroker = mock(DOMDataBroker.class);
169 final List<SourceIdentifier> sourceIdentifiers =
170 Lists.newArrayList(RevisionSourceIdentifier.create("testID", Optional.absent()));
174 final Future<Object> initialDataToActor =
175 Patterns.ask(masterRef, new CreateInitialMasterActorData(domDataBroker, sourceIdentifiers,
176 domRpcService), TIMEOUT);
178 final Object successInit = Await.result(initialDataToActor, TIMEOUT.duration());
180 assertTrue(successInit instanceof MasterActorDataInitialized);
182 // test if slave get right identifiers from master
184 final Future<Object> registerMountPointFuture =
185 Patterns.ask(masterRef, new AskForMasterMountPoint(),
188 final RegisterMountPoint success =
189 (RegisterMountPoint) Await.result(registerMountPointFuture, TIMEOUT.duration());
191 assertEquals(sourceIdentifiers, success.getSourceIndentifiers());
196 public void testReceiveRegisterMountpoint() throws Exception {
197 final NetconfTopologySetup setup = mock(NetconfTopologySetup.class);
198 final RevisionSourceIdentifier yang1 = RevisionSourceIdentifier.create("yang1");
199 final RevisionSourceIdentifier yang2 = RevisionSourceIdentifier.create("yang2");
200 final SchemaSourceRegistry registry = mock(SchemaSourceRegistry.class);
201 final SchemaRepository schemaRepository = mock(SchemaRepository.class);
202 final SchemaSourceRegistration regYang1 = mock(SchemaSourceRegistration.class);
203 final SchemaSourceRegistration regYang2 = mock(SchemaSourceRegistration.class);
204 doReturn(regYang1).when(registry).registerSchemaSource(any(), withSourceId(yang1));
205 doReturn(regYang2).when(registry).registerSchemaSource(any(), withSourceId(yang2));
206 final SchemaContextFactory schemaContextFactory = mock(SchemaContextFactory.class);
207 doReturn(schemaContextFactory).when(schemaRepository).createSchemaContextFactory(any());
208 final SettableFuture<SchemaContext> schemaContextFuture = SettableFuture.create();
209 final CheckedFuture<SchemaContext, SchemaResolutionException> checkedFuture =
210 Futures.makeChecked(schemaContextFuture, e -> new SchemaResolutionException("fail", e));
211 doReturn(checkedFuture).when(schemaContextFactory).createSchemaContext(any());
212 final ActorRef slaveRef =
213 system.actorOf(NetconfNodeActor.props(setup, remoteDeviceId, registry, schemaRepository, TIMEOUT,
215 final List<SourceIdentifier> sources = ImmutableList.of(yang1, yang2);
216 slaveRef.tell(new RegisterMountPoint(sources), masterRef);
218 verify(registry, timeout(1000)).registerSchemaSource(any(), withSourceId(yang1));
219 verify(registry, timeout(1000)).registerSchemaSource(any(), withSourceId(yang2));
221 final Future<Boolean> stopFuture = Patterns.gracefulStop(slaveRef, TIMEOUT.duration());
222 Await.result(stopFuture, TIMEOUT.duration());
223 //provider should be deregistered
224 verify(regYang1).close();
225 verify(regYang2).close();
229 public void testYangTextSchemaSourceRequestMessage() throws Exception {
230 final SchemaRepository schemaRepository = mock(SchemaRepository.class);
231 final SourceIdentifier sourceIdentifier = RevisionSourceIdentifier.create("testID", Optional.absent());
232 final Props props = NetconfNodeActor.props(mock(NetconfTopologySetup.class), remoteDeviceId,
233 DEFAULT_SCHEMA_REPOSITORY, schemaRepository, TIMEOUT, mountPointService);
235 final ActorRef actorRefSchemaRepo = TestActorRef.create(system, props, "master_mocked_schema_repository");
236 final ActorContext actorContext = mock(ActorContext.class);
237 doReturn(system.dispatcher()).when(actorContext).dispatcher();
239 final ProxyYangTextSourceProvider proxyYang =
240 new ProxyYangTextSourceProvider(actorRefSchemaRepo, actorContext, TIMEOUT);
241 // test if asking for source is resolved and sended back
243 final YangTextSchemaSource yangTextSchemaSource = new YangTextSchemaSource(sourceIdentifier) {
245 protected MoreObjects.ToStringHelper addToStringAttributes(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 = new ProxyDOMRpcService(system, masterRef, remoteDeviceId, TIMEOUT);
309 final SchemaPath schemaPath = SchemaPath.create(true, QName.create("TestQname"));
310 final NormalizedNode<?, ?> outputNode = ImmutableContainerNodeBuilder.create()
311 .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(QName.create("TestQname")))
312 .withChild(ImmutableNodes.leafNode(QName.create("NodeQname"), "foo")).build();
313 final RpcError rpcError = RpcResultBuilder.newError(RpcError.ErrorType.RPC, null, "Rpc invocation failed.");
314 // EmptyResultResponse message
316 doReturn(Futures.immediateCheckedFuture(null)).when(domRpcService).invokeRpc(any(), any());
318 final CheckedFuture<DOMRpcResult, DOMRpcException> resultFutureEmpty =
319 slaveDomRPCService.invokeRpc(schemaPath, outputNode);
321 final Object resultNull = resultFutureEmpty.checkedGet(2, TimeUnit.SECONDS);
323 assertEquals(null, resultNull);
325 // InvokeRpcMessageReply message
327 doReturn(Futures.immediateCheckedFuture(new DefaultDOMRpcResult(outputNode))).
328 when(domRpcService).invokeRpc(any(), any());
330 final CheckedFuture<DOMRpcResult, DOMRpcException> resultFutureNn =
331 slaveDomRPCService.invokeRpc(schemaPath, outputNode);
333 final DOMRpcResult resultNn = resultFutureNn.checkedGet(2, TimeUnit.SECONDS);
335 assertEquals(outputNode, resultNn.getResult());
336 assertTrue(resultNn.getErrors().isEmpty());
338 // InvokeRpcMessageReply message only error
340 doReturn(Futures.immediateCheckedFuture(new DefaultDOMRpcResult(rpcError)))
341 .when(domRpcService).invokeRpc(any(), any());
343 final CheckedFuture<DOMRpcResult, DOMRpcException> resultFutureError =
344 slaveDomRPCService.invokeRpc(schemaPath, outputNode);
346 final DOMRpcResult resultError = resultFutureError.checkedGet(2, TimeUnit.SECONDS);
348 assertNull(resultError.getResult());
349 assertEquals(rpcError, resultError.getErrors().iterator().next());
351 // InvokeRpcMessageReply message error + result
353 doReturn(Futures.immediateCheckedFuture(new DefaultDOMRpcResult(outputNode, rpcError)))
354 .when(domRpcService).invokeRpc(any(), any());
356 final CheckedFuture<DOMRpcResult, DOMRpcException> resultFutureOutputError =
357 slaveDomRPCService.invokeRpc(schemaPath, outputNode);
359 final DOMRpcResult resultOutputError = resultFutureOutputError.checkedGet(2, TimeUnit.SECONDS);
361 assertEquals(outputNode, resultOutputError.getResult());
362 assertEquals(rpcError, resultOutputError.getErrors().iterator().next());
366 exception.expect(DOMRpcException.class);
368 doReturn(Futures.immediateFailedCheckedFuture(new ClusteringRpcException("")))
369 .when(domRpcService).invokeRpc(any(), any());
371 final CheckedFuture<DOMRpcResult, DOMRpcException> resultFutureThrowable =
372 slaveDomRPCService.invokeRpc(schemaPath, outputNode);
374 resultFutureThrowable.checkedGet(2, TimeUnit.SECONDS);
378 private PotentialSchemaSource<?> withSourceId(final SourceIdentifier identifier) {
379 return argThat(new ArgumentMatcher<PotentialSchemaSource>() {
381 public boolean matches(final Object argument) {
382 final PotentialSchemaSource potentialSchemaSource = (PotentialSchemaSource) argument;
383 return identifier.equals(potentialSchemaSource.getSourceIdentifier());
388 private String convertStreamToString(final java.io.InputStream is) {
389 final java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");
390 return s.hasNext() ? s.next() : "";