b29a4ce9b60cc95553d1fa351bc74c21faed41a2
[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 package org.opendaylight.netconf.topology.singleton.impl;
9
10 import static java.nio.charset.StandardCharsets.UTF_8;
11 import static org.hamcrest.CoreMatchers.containsString;
12 import static org.hamcrest.CoreMatchers.instanceOf;
13 import static org.hamcrest.CoreMatchers.startsWith;
14 import static org.hamcrest.MatcherAssert.assertThat;
15 import static org.junit.Assert.assertEquals;
16 import static org.junit.Assert.assertNull;
17 import static org.junit.Assert.assertThrows;
18 import static org.junit.Assert.assertTrue;
19 import static org.mockito.ArgumentMatchers.any;
20 import static org.mockito.ArgumentMatchers.anyCollection;
21 import static org.mockito.ArgumentMatchers.argThat;
22 import static org.mockito.ArgumentMatchers.eq;
23 import static org.mockito.Mockito.after;
24 import static org.mockito.Mockito.doAnswer;
25 import static org.mockito.Mockito.doNothing;
26 import static org.mockito.Mockito.doReturn;
27 import static org.mockito.Mockito.mock;
28 import static org.mockito.Mockito.reset;
29 import static org.mockito.Mockito.timeout;
30 import static org.mockito.Mockito.times;
31 import static org.mockito.Mockito.verify;
32 import static org.mockito.Mockito.verifyNoMoreInteractions;
33 import static org.opendaylight.mdsal.common.api.CommitInfo.emptyFluentFuture;
34 import static org.opendaylight.yangtools.util.concurrent.FluentFutures.immediateFluentFuture;
35
36 import akka.actor.ActorRef;
37 import akka.actor.ActorSystem;
38 import akka.actor.Props;
39 import akka.actor.Status.Failure;
40 import akka.actor.Status.Success;
41 import akka.pattern.AskTimeoutException;
42 import akka.pattern.Patterns;
43 import akka.testkit.TestActorRef;
44 import akka.testkit.javadsl.TestKit;
45 import akka.util.Timeout;
46 import com.google.common.collect.ImmutableList;
47 import com.google.common.io.ByteSource;
48 import com.google.common.net.InetAddresses;
49 import com.google.common.util.concurrent.FluentFuture;
50 import com.google.common.util.concurrent.Futures;
51 import com.google.common.util.concurrent.ListenableFuture;
52 import com.google.common.util.concurrent.SettableFuture;
53 import java.io.InputStream;
54 import java.net.InetSocketAddress;
55 import java.time.Duration;
56 import java.util.ArrayList;
57 import java.util.List;
58 import java.util.Optional;
59 import java.util.Scanner;
60 import java.util.concurrent.ExecutionException;
61 import java.util.concurrent.TimeUnit;
62 import org.junit.After;
63 import org.junit.Before;
64 import org.junit.Test;
65 import org.junit.runner.RunWith;
66 import org.mockito.ArgumentCaptor;
67 import org.mockito.Mock;
68 import org.mockito.junit.MockitoJUnitRunner;
69 import org.opendaylight.controller.cluster.schema.provider.impl.YangTextSchemaSourceSerializationProxy;
70 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
71 import org.opendaylight.mdsal.dom.api.DOMActionException;
72 import org.opendaylight.mdsal.dom.api.DOMActionResult;
73 import org.opendaylight.mdsal.dom.api.DOMActionService;
74 import org.opendaylight.mdsal.dom.api.DOMDataBroker;
75 import org.opendaylight.mdsal.dom.api.DOMDataTreeIdentifier;
76 import org.opendaylight.mdsal.dom.api.DOMDataTreeReadTransaction;
77 import org.opendaylight.mdsal.dom.api.DOMDataTreeReadWriteTransaction;
78 import org.opendaylight.mdsal.dom.api.DOMDataTreeWriteTransaction;
79 import org.opendaylight.mdsal.dom.api.DOMMountPoint;
80 import org.opendaylight.mdsal.dom.api.DOMMountPointService;
81 import org.opendaylight.mdsal.dom.api.DOMNotificationService;
82 import org.opendaylight.mdsal.dom.api.DOMRpcException;
83 import org.opendaylight.mdsal.dom.api.DOMRpcResult;
84 import org.opendaylight.mdsal.dom.api.DOMRpcService;
85 import org.opendaylight.mdsal.dom.api.DOMSchemaService;
86 import org.opendaylight.mdsal.dom.spi.DefaultDOMRpcResult;
87 import org.opendaylight.mdsal.dom.spi.SimpleDOMActionResult;
88 import org.opendaylight.netconf.dom.api.NetconfDataTreeService;
89 import org.opendaylight.netconf.sal.connect.api.RemoteDeviceServices;
90 import org.opendaylight.netconf.sal.connect.api.RemoteDeviceServices.Actions;
91 import org.opendaylight.netconf.sal.connect.api.RemoteDeviceServices.Rpcs;
92 import org.opendaylight.netconf.sal.connect.netconf.NetconfDevice.SchemaResourcesDTO;
93 import org.opendaylight.netconf.sal.connect.util.RemoteDeviceId;
94 import org.opendaylight.netconf.topology.singleton.impl.actors.NetconfNodeActor;
95 import org.opendaylight.netconf.topology.singleton.impl.utils.ClusteringActionException;
96 import org.opendaylight.netconf.topology.singleton.impl.utils.ClusteringRpcException;
97 import org.opendaylight.netconf.topology.singleton.impl.utils.NetconfTopologySetup;
98 import org.opendaylight.netconf.topology.singleton.impl.utils.NetconfTopologySetup.NetconfTopologySetupBuilder;
99 import org.opendaylight.netconf.topology.singleton.messages.AskForMasterMountPoint;
100 import org.opendaylight.netconf.topology.singleton.messages.CreateInitialMasterActorData;
101 import org.opendaylight.netconf.topology.singleton.messages.MasterActorDataInitialized;
102 import org.opendaylight.netconf.topology.singleton.messages.NotMasterException;
103 import org.opendaylight.netconf.topology.singleton.messages.RefreshSetupMasterActorData;
104 import org.opendaylight.netconf.topology.singleton.messages.RegisterMountPoint;
105 import org.opendaylight.netconf.topology.singleton.messages.UnregisterSlaveMountPoint;
106 import org.opendaylight.yangtools.concepts.ObjectRegistration;
107 import org.opendaylight.yangtools.util.concurrent.FluentFutures;
108 import org.opendaylight.yangtools.yang.common.ErrorType;
109 import org.opendaylight.yangtools.yang.common.QName;
110 import org.opendaylight.yangtools.yang.common.RpcError;
111 import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
112 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
113 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
114 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
115 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
116 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
117 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
118 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
119 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier.Absolute;
120 import org.opendaylight.yangtools.yang.model.repo.api.EffectiveModelContextFactory;
121 import org.opendaylight.yangtools.yang.model.repo.api.MissingSchemaSourceException;
122 import org.opendaylight.yangtools.yang.model.repo.api.SchemaRepository;
123 import org.opendaylight.yangtools.yang.model.repo.api.SchemaResolutionException;
124 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
125 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
126 import org.opendaylight.yangtools.yang.model.repo.spi.PotentialSchemaSource;
127 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistration;
128 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistry;
129 import org.opendaylight.yangtools.yang.parser.repo.SharedSchemaRepository;
130 import org.opendaylight.yangtools.yang.parser.rfc7950.repo.TextToIRTransformer;
131 import scala.concurrent.Await;
132 import scala.concurrent.Future;
133
134 @RunWith(MockitoJUnitRunner.StrictStubs.class)
135 public class NetconfNodeActorTest extends AbstractBaseSchemasTest {
136
137     private static final Timeout TIMEOUT = Timeout.create(Duration.ofSeconds(5));
138     private static final SourceIdentifier SOURCE_IDENTIFIER1 = new SourceIdentifier("yang1");
139     private static final SourceIdentifier SOURCE_IDENTIFIER2 = new SourceIdentifier("yang2");
140
141     private ActorSystem system = ActorSystem.create();
142     private final TestKit testKit = new TestKit(system);
143
144     private ActorRef masterRef;
145     private RemoteDeviceId remoteDeviceId;
146     private final SharedSchemaRepository masterSchemaRepository = new SharedSchemaRepository("master");
147
148     @Mock
149     private Rpcs.Normalized mockDOMRpcService;
150
151     @Mock
152     private Actions.Normalized mockDOMActionService;
153
154     @Mock
155     private DOMMountPointService mockMountPointService;
156
157     @Mock
158     private DOMMountPointService.DOMMountPointBuilder mockMountPointBuilder;
159
160     @Mock
161     private ObjectRegistration<DOMMountPoint> mockMountPointReg;
162
163     @Mock
164     private DOMDataBroker mockDOMDataBroker;
165
166     @Mock
167     private NetconfDataTreeService netconfService;
168
169     @Mock
170     private SchemaSourceRegistration<?> mockSchemaSourceReg1;
171
172     @Mock
173     private SchemaSourceRegistration<?> mockSchemaSourceReg2;
174
175     @Mock
176     private SchemaSourceRegistry mockRegistry;
177
178     @Mock
179     private EffectiveModelContextFactory mockSchemaContextFactory;
180
181     @Mock
182     private SchemaRepository mockSchemaRepository;
183
184     @Mock
185     private EffectiveModelContext mockSchemaContext;
186
187     @Mock
188     private SchemaResourcesDTO schemaResourceDTO;
189
190     @Before
191     public void setup() {
192         remoteDeviceId = new RemoteDeviceId("netconf-topology",
193                 new InetSocketAddress(InetAddresses.forString("127.0.0.1"), 9999));
194
195         masterSchemaRepository.registerSchemaSourceListener(
196                 TextToIRTransformer.create(masterSchemaRepository, masterSchemaRepository));
197
198         doReturn(masterSchemaRepository).when(schemaResourceDTO).getSchemaRepository();
199         doReturn(mockRegistry).when(schemaResourceDTO).getSchemaRegistry();
200         final NetconfTopologySetup setup = NetconfTopologySetupBuilder.create().setActorSystem(system)
201                 .setIdleTimeout(Duration.ofSeconds(1)).setSchemaResourceDTO(schemaResourceDTO)
202                 .setBaseSchemas(BASE_SCHEMAS).build();
203
204         final Props props = NetconfNodeActor.props(setup, remoteDeviceId, TIMEOUT, mockMountPointService);
205
206         masterRef = TestActorRef.create(system, props, "master_messages");
207
208         resetMountPointMocks();
209
210         doReturn(mockMountPointBuilder).when(mockMountPointService).createMountPoint(any());
211
212         doReturn(mockSchemaSourceReg1).when(mockRegistry).registerSchemaSource(any(), withSourceId(SOURCE_IDENTIFIER1));
213         doReturn(mockSchemaSourceReg2).when(mockRegistry).registerSchemaSource(any(), withSourceId(SOURCE_IDENTIFIER2));
214
215         doReturn(mockSchemaContextFactory).when(mockSchemaRepository)
216                 .createEffectiveModelContextFactory();
217     }
218
219     @After
220     public void teardown() {
221         TestKit.shutdownActorSystem(system, true);
222         system = null;
223     }
224
225     @Test
226     public void testInitializeAndRefreshMasterData() {
227
228         // Test CreateInitialMasterActorData.
229
230         initializeMaster(new ArrayList<>());
231
232         // Test RefreshSetupMasterActorData.
233
234         final RemoteDeviceId newRemoteDeviceId = new RemoteDeviceId("netconf-topology2",
235                 new InetSocketAddress(InetAddresses.forString("127.0.0.2"), 9999));
236
237         final NetconfTopologySetup newSetup = NetconfTopologySetupBuilder.create().setBaseSchemas(BASE_SCHEMAS)
238                 .setSchemaResourceDTO(schemaResourceDTO).setActorSystem(system).build();
239
240         masterRef.tell(new RefreshSetupMasterActorData(newSetup, newRemoteDeviceId), testKit.getRef());
241
242         testKit.expectMsgClass(MasterActorDataInitialized.class);
243     }
244
245     @Test
246     public void testAskForMasterMountPoint() {
247
248         // Test with master not setup yet.
249
250         final TestKit kit = new TestKit(system);
251
252         masterRef.tell(new AskForMasterMountPoint(kit.getRef()), kit.getRef());
253
254         final Failure failure = kit.expectMsgClass(Failure.class);
255         assertTrue(failure.cause() instanceof NotMasterException);
256
257         // Now initialize - master should send the RegisterMountPoint message.
258
259         List<SourceIdentifier> sourceIdentifiers = List.of(new SourceIdentifier("testID"));
260         initializeMaster(sourceIdentifiers);
261
262         masterRef.tell(new AskForMasterMountPoint(kit.getRef()), kit.getRef());
263
264         final RegisterMountPoint registerMountPoint = kit.expectMsgClass(RegisterMountPoint.class);
265
266         assertEquals(sourceIdentifiers, registerMountPoint.getSourceIndentifiers());
267     }
268
269     @Test
270     public void testRegisterAndUnregisterMountPoint() throws Exception {
271
272         ActorRef slaveRef = registerSlaveMountPoint();
273
274         // Unregister
275
276         slaveRef.tell(new UnregisterSlaveMountPoint(), testKit.getRef());
277
278         verify(mockMountPointReg, timeout(5000)).close();
279         verify(mockSchemaSourceReg1, timeout(1000)).close();
280         verify(mockSchemaSourceReg2, timeout(1000)).close();
281
282         // Test registration with another interleaved registration that completes while the first registration
283         // is resolving the schema context.
284
285         reset(mockSchemaSourceReg1, mockRegistry, mockSchemaRepository);
286         resetMountPointMocks();
287
288         doReturn(mockSchemaSourceReg1).when(mockRegistry).registerSchemaSource(any(), withSourceId(SOURCE_IDENTIFIER1));
289
290         final SchemaSourceRegistration<?> newMockSchemaSourceReg = mock(SchemaSourceRegistration.class);
291
292         final EffectiveModelContextFactory newMockSchemaContextFactory = mock(EffectiveModelContextFactory.class);
293         doReturn(Futures.immediateFuture(mockSchemaContext))
294                 .when(newMockSchemaContextFactory).createEffectiveModelContext(anyCollection());
295
296         doAnswer(unused -> {
297             SettableFuture<SchemaContext> future = SettableFuture.create();
298             new Thread(() -> {
299                 doReturn(newMockSchemaSourceReg).when(mockRegistry).registerSchemaSource(any(),
300                         withSourceId(SOURCE_IDENTIFIER1));
301
302                 doReturn(newMockSchemaContextFactory).when(mockSchemaRepository)
303                         .createEffectiveModelContextFactory();
304
305                 slaveRef.tell(new RegisterMountPoint(ImmutableList.of(SOURCE_IDENTIFIER1), masterRef),
306                         testKit.getRef());
307
308                 future.set(mockSchemaContext);
309             }).start();
310             return future;
311         }).when(mockSchemaContextFactory).createEffectiveModelContext(anyCollection());
312
313         doReturn(mockSchemaContextFactory).when(mockSchemaRepository)
314                 .createEffectiveModelContextFactory();
315
316         slaveRef.tell(new RegisterMountPoint(ImmutableList.of(SOURCE_IDENTIFIER1), masterRef), testKit.getRef());
317
318         verify(mockMountPointBuilder, timeout(5000)).register();
319         verify(mockMountPointBuilder, after(500)).addService(eq(DOMDataBroker.class), any());
320         verify(mockMountPointBuilder).addService(eq(DOMRpcService.class), any());
321         verify(mockMountPointBuilder).addService(eq(DOMActionService.class), any());
322         verify(mockMountPointBuilder).addService(eq(DOMNotificationService.class), any());
323         verify(mockMountPointBuilder).addService(eq(DOMSchemaService.class), any());
324         verify(mockSchemaSourceReg1).close();
325         verify(mockRegistry, times(2)).registerSchemaSource(any(), withSourceId(SOURCE_IDENTIFIER1));
326         verify(mockSchemaRepository, times(2)).createEffectiveModelContextFactory();
327         verifyNoMoreInteractions(mockMountPointBuilder, newMockSchemaSourceReg);
328
329         // Stop the slave actor and verify schema source registrations are closed.
330
331         final Future<Boolean> stopFuture = Patterns.gracefulStop(slaveRef, TIMEOUT.duration());
332         Await.result(stopFuture, TIMEOUT.duration());
333
334         verify(mockMountPointReg).close();
335         verify(newMockSchemaSourceReg).close();
336     }
337
338     @SuppressWarnings("unchecked")
339     @Test
340     public void testRegisterMountPointWithSchemaFailures() throws Exception {
341         SchemaResourcesDTO schemaResourceDTO2 = mock(SchemaResourcesDTO.class);
342         doReturn(mockRegistry).when(schemaResourceDTO2).getSchemaRegistry();
343         doReturn(mockSchemaRepository).when(schemaResourceDTO2).getSchemaRepository();
344         final NetconfTopologySetup setup = NetconfTopologySetupBuilder.create()
345                 .setSchemaResourceDTO(schemaResourceDTO2)
346                 .setBaseSchemas(BASE_SCHEMAS)
347                 .setActorSystem(system)
348                 .build();
349
350         final ActorRef slaveRef = system.actorOf(NetconfNodeActor.props(setup, remoteDeviceId, TIMEOUT,
351                 mockMountPointService));
352
353         // Test unrecoverable failure.
354
355         doReturn(Futures.immediateFailedFuture(new SchemaResolutionException("mock")))
356                 .when(mockSchemaContextFactory).createEffectiveModelContext(anyCollection());
357
358         slaveRef.tell(new RegisterMountPoint(ImmutableList.of(SOURCE_IDENTIFIER1, SOURCE_IDENTIFIER2),
359                 masterRef), testKit.getRef());
360
361         testKit.expectMsgClass(Success.class);
362
363         verify(mockRegistry, timeout(5000)).registerSchemaSource(any(), withSourceId(SOURCE_IDENTIFIER1));
364         verify(mockRegistry, timeout(5000)).registerSchemaSource(any(), withSourceId(SOURCE_IDENTIFIER2));
365
366         verify(mockMountPointBuilder, after(1000).never()).register();
367         verify(mockSchemaSourceReg1, timeout(1000)).close();
368         verify(mockSchemaSourceReg2, timeout(1000)).close();
369
370         // Test recoverable AskTimeoutException - schema context resolution should be retried.
371
372         reset(mockSchemaSourceReg1, mockSchemaSourceReg2);
373
374         doReturn(Futures.immediateFailedFuture(new SchemaResolutionException("mock",
375                 new AskTimeoutException("timeout"))))
376             .doReturn(Futures.immediateFuture(mockSchemaContext))
377             .when(mockSchemaContextFactory).createEffectiveModelContext(anyCollection());
378
379         slaveRef.tell(new RegisterMountPoint(ImmutableList.of(SOURCE_IDENTIFIER1, SOURCE_IDENTIFIER2),
380                 masterRef), testKit.getRef());
381
382         testKit.expectMsgClass(Success.class);
383
384         verify(mockMountPointBuilder, timeout(5000)).register();
385         verifyNoMoreInteractions(mockSchemaSourceReg1, mockSchemaSourceReg2);
386
387         // Test AskTimeoutException with an interleaved successful registration. The first schema context resolution
388         // attempt should not be retried.
389
390         reset(mockSchemaSourceReg1, mockSchemaSourceReg2, mockSchemaRepository, mockSchemaContextFactory);
391         resetMountPointMocks();
392
393         final EffectiveModelContextFactory mockSchemaContextFactorySuccess = mock(EffectiveModelContextFactory.class);
394         doReturn(Futures.immediateFuture(mockSchemaContext))
395                 .when(mockSchemaContextFactorySuccess).createEffectiveModelContext(anyCollection());
396
397         doAnswer(unused -> {
398             SettableFuture<SchemaContext> future = SettableFuture.create();
399             new Thread(() -> {
400                 doReturn(mockSchemaContextFactorySuccess).when(mockSchemaRepository)
401                     .createEffectiveModelContextFactory();
402
403                 slaveRef.tell(new RegisterMountPoint(ImmutableList.of(SOURCE_IDENTIFIER1, SOURCE_IDENTIFIER2),
404                         masterRef), testKit.getRef());
405
406                 future.setException(new SchemaResolutionException("mock", new AskTimeoutException("timeout")));
407             }).start();
408             return future;
409         }).when(mockSchemaContextFactory).createEffectiveModelContext(anyCollection());
410
411         doReturn(mockSchemaContextFactory).when(mockSchemaRepository).createEffectiveModelContextFactory();
412
413         slaveRef.tell(new RegisterMountPoint(ImmutableList.of(SOURCE_IDENTIFIER1, SOURCE_IDENTIFIER2),
414                 masterRef), testKit.getRef());
415
416         verify(mockMountPointBuilder, timeout(5000)).register();
417         verify(mockSchemaRepository, times(2)).createEffectiveModelContextFactory();
418     }
419
420     @Test(expected = MissingSchemaSourceException.class)
421     public void testMissingSchemaSourceOnMissingProvider() throws Exception {
422         final SharedSchemaRepository repository = new SharedSchemaRepository("test");
423
424         SchemaResourcesDTO schemaResourceDTO2 = mock(SchemaResourcesDTO.class);
425         doReturn(repository).when(schemaResourceDTO2).getSchemaRegistry();
426         doReturn(repository).when(schemaResourceDTO2).getSchemaRepository();
427         final NetconfTopologySetup setup = NetconfTopologySetupBuilder.create().setActorSystem(system)
428                 .setSchemaResourceDTO(schemaResourceDTO2).setIdleTimeout(Duration.ofSeconds(1))
429                 .setBaseSchemas(BASE_SCHEMAS).build();
430         final Props props = NetconfNodeActor.props(setup, remoteDeviceId, TIMEOUT, mockMountPointService);
431         ActorRef actor = TestActorRef.create(system, props, "master_messages_2");
432
433         final SourceIdentifier sourceIdentifier = new SourceIdentifier("testID");
434
435         final ProxyYangTextSourceProvider proxyYangProvider =
436                 new ProxyYangTextSourceProvider(actor, system.dispatcher(), TIMEOUT);
437
438         final Future<YangTextSchemaSourceSerializationProxy> resolvedSchemaFuture =
439                 proxyYangProvider.getYangTextSchemaSource(sourceIdentifier);
440         Await.result(resolvedSchemaFuture, TIMEOUT.duration());
441     }
442
443     @Test
444     public void testYangTextSchemaSourceRequest() throws Exception {
445         final SourceIdentifier sourceIdentifier = new SourceIdentifier("testID");
446
447         final ProxyYangTextSourceProvider proxyYangProvider =
448                 new ProxyYangTextSourceProvider(masterRef, system.dispatcher(), TIMEOUT);
449
450         final YangTextSchemaSource yangTextSchemaSource = YangTextSchemaSource.delegateForByteSource(sourceIdentifier,
451                 ByteSource.wrap("YANG".getBytes(UTF_8)));
452
453         // Test success.
454
455         final SchemaSourceRegistration<YangTextSchemaSource> schemaSourceReg = masterSchemaRepository
456                 .registerSchemaSource(id -> Futures.immediateFuture(yangTextSchemaSource),
457                      PotentialSchemaSource.create(sourceIdentifier, YangTextSchemaSource.class, 1));
458
459         final Future<YangTextSchemaSourceSerializationProxy> resolvedSchemaFuture =
460                 proxyYangProvider.getYangTextSchemaSource(sourceIdentifier);
461
462         final YangTextSchemaSourceSerializationProxy success = Await.result(resolvedSchemaFuture, TIMEOUT.duration());
463
464         assertEquals(sourceIdentifier, success.getRepresentation().getIdentifier());
465         assertEquals("YANG", convertStreamToString(success.getRepresentation().openStream()));
466
467         // Test missing source failure.
468
469         schemaSourceReg.close();
470
471         final MissingSchemaSourceException ex = assertThrows(MissingSchemaSourceException.class,
472             () -> {
473                 final Future<YangTextSchemaSourceSerializationProxy> failedSchemaFuture =
474                         proxyYangProvider.getYangTextSchemaSource(sourceIdentifier);
475                 Await.result(failedSchemaFuture, TIMEOUT.duration());
476             });
477         assertThat(ex.getMessage(), startsWith("No providers registered for source"));
478         assertThat(ex.getMessage(), containsString(sourceIdentifier.toString()));
479     }
480
481     @Test
482     public void testSlaveInvokeRpc() throws Exception {
483
484         initializeMaster(List.of(new SourceIdentifier("testID")));
485         registerSlaveMountPoint();
486
487         ArgumentCaptor<DOMRpcService> domRPCServiceCaptor = ArgumentCaptor.forClass(DOMRpcService.class);
488         verify(mockMountPointBuilder).addService(eq(DOMRpcService.class), domRPCServiceCaptor.capture());
489
490         final DOMRpcService slaveDomRPCService = domRPCServiceCaptor.getValue();
491         assertTrue(slaveDomRPCService instanceof ProxyDOMRpcService);
492
493         final QName testQName = QName.create("", "TestQname");
494         final ContainerNode outputNode = Builders.containerBuilder()
495                 .withNodeIdentifier(new NodeIdentifier(testQName))
496                 .withChild(ImmutableNodes.leafNode(testQName, "foo")).build();
497         final RpcError rpcError = RpcResultBuilder.newError(ErrorType.RPC, null, "Rpc invocation failed.");
498
499         // RPC with no response output.
500
501         doReturn(FluentFutures.immediateNullFluentFuture()).when(mockDOMRpcService).invokeRpc(any(), any());
502
503         DOMRpcResult result = slaveDomRPCService.invokeRpc(testQName, outputNode).get(2, TimeUnit.SECONDS);
504
505         assertEquals(null, result);
506
507         // RPC with response output.
508
509         doReturn(FluentFutures.immediateFluentFuture(new DefaultDOMRpcResult(outputNode)))
510                 .when(mockDOMRpcService).invokeRpc(any(), any());
511
512         result = slaveDomRPCService.invokeRpc(testQName, outputNode).get(2, TimeUnit.SECONDS);
513
514         assertEquals(outputNode, result.value());
515         assertTrue(result.errors().isEmpty());
516
517         // RPC with response error.
518
519         doReturn(FluentFutures.immediateFluentFuture(new DefaultDOMRpcResult(rpcError)))
520                 .when(mockDOMRpcService).invokeRpc(any(), any());
521
522         result = slaveDomRPCService.invokeRpc(testQName, outputNode).get(2, TimeUnit.SECONDS);
523
524         assertNull(result.value());
525         assertEquals(rpcError, result.errors().iterator().next());
526
527         // RPC with response output and error.
528
529         doReturn(FluentFutures.immediateFluentFuture(new DefaultDOMRpcResult(outputNode, rpcError)))
530                 .when(mockDOMRpcService).invokeRpc(any(), any());
531
532         final DOMRpcResult resultOutputError =
533                 slaveDomRPCService.invokeRpc(testQName, outputNode).get(2, TimeUnit.SECONDS);
534
535         assertEquals(outputNode, resultOutputError.value());
536         assertEquals(rpcError, resultOutputError.errors().iterator().next());
537
538         // RPC failure.
539         doReturn(FluentFutures.immediateFailedFluentFuture(new ClusteringRpcException("mock")))
540             .when(mockDOMRpcService).invokeRpc(any(), any());
541         final ListenableFuture<? extends DOMRpcResult> future = slaveDomRPCService.invokeRpc(testQName, outputNode);
542
543         final ExecutionException e = assertThrows(ExecutionException.class, () -> future.get(2, TimeUnit.SECONDS));
544         final Throwable cause = e.getCause();
545         assertThat(cause, instanceOf(DOMRpcException.class));
546         assertEquals("mock", cause.getMessage());
547     }
548
549     @Test
550     public void testSlaveInvokeAction() throws Exception {
551         initializeMaster(List.of(new SourceIdentifier("testActionID")));
552         registerSlaveMountPoint();
553
554         ArgumentCaptor<DOMActionService> domActionServiceCaptor = ArgumentCaptor.forClass(DOMActionService.class);
555         verify(mockMountPointBuilder).addService(eq(DOMActionService.class), domActionServiceCaptor.capture());
556
557         final DOMActionService slaveDomActionService = domActionServiceCaptor.getValue();
558         assertTrue(slaveDomActionService instanceof ProxyDOMActionService);
559
560         final QName testQName = QName.create("test", "2019-08-16", "TestActionQname");
561         final Absolute schemaPath = Absolute.of(testQName);
562
563         final YangInstanceIdentifier yangIIdPath = YangInstanceIdentifier.create(new NodeIdentifier(testQName));
564
565         final DOMDataTreeIdentifier domDataTreeIdentifier = new DOMDataTreeIdentifier(LogicalDatastoreType.OPERATIONAL,
566             yangIIdPath);
567
568         final ContainerNode outputNode = Builders.containerBuilder()
569             .withNodeIdentifier(new NodeIdentifier(testQName))
570             .withChild(ImmutableNodes.leafNode(testQName, "foo")).build();
571
572         // Action with no response output.
573         doReturn(FluentFutures.immediateNullFluentFuture()).when(mockDOMActionService)
574             .invokeAction(any(), any(), any());
575         DOMActionResult result = slaveDomActionService.invokeAction(schemaPath, domDataTreeIdentifier, outputNode)
576             .get(2, TimeUnit.SECONDS);
577         assertEquals(null, result);
578
579         // Action with response output.
580         doReturn(FluentFutures.immediateFluentFuture(new SimpleDOMActionResult(outputNode))).when(mockDOMActionService)
581             .invokeAction(any(), any(), any());
582         result = slaveDomActionService.invokeAction(schemaPath, domDataTreeIdentifier, outputNode)
583             .get(2, TimeUnit.SECONDS);
584
585         assertEquals(outputNode, result.getOutput().get());
586         assertTrue(result.getErrors().isEmpty());
587
588         // Action failure.
589         doReturn(FluentFutures.immediateFailedFluentFuture(new ClusteringActionException("mock")))
590             .when(mockDOMActionService).invokeAction(any(), any(), any());
591         final ListenableFuture<? extends DOMActionResult> future = slaveDomActionService.invokeAction(schemaPath,
592             domDataTreeIdentifier, outputNode);
593
594         final ExecutionException e = assertThrows(ExecutionException.class, () -> future.get(2, TimeUnit.SECONDS));
595         final Throwable cause = e.getCause();
596         assertThat(cause, instanceOf(DOMActionException.class));
597         assertEquals("mock", cause.getMessage());
598     }
599
600     @Test
601     public void testSlaveNewTransactionRequests() {
602         doReturn(mock(DOMDataTreeReadTransaction.class)).when(mockDOMDataBroker).newReadOnlyTransaction();
603         doReturn(mock(DOMDataTreeReadWriteTransaction.class)).when(mockDOMDataBroker).newReadWriteTransaction();
604         doReturn(mock(DOMDataTreeWriteTransaction.class)).when(mockDOMDataBroker).newWriteOnlyTransaction();
605
606         initializeMaster(List.of());
607         registerSlaveMountPoint();
608
609         ArgumentCaptor<DOMDataBroker> domDataBrokerCaptor = ArgumentCaptor.forClass(DOMDataBroker.class);
610         verify(mockMountPointBuilder).addService(eq(DOMDataBroker.class), domDataBrokerCaptor.capture());
611
612         final DOMDataBroker slaveDOMDataBroker = domDataBrokerCaptor.getValue();
613         assertTrue(slaveDOMDataBroker instanceof ProxyDOMDataBroker);
614
615         slaveDOMDataBroker.newReadOnlyTransaction();
616         verify(mockDOMDataBroker).newReadOnlyTransaction();
617
618         slaveDOMDataBroker.newReadWriteTransaction();
619         verify(mockDOMDataBroker).newReadWriteTransaction();
620
621         slaveDOMDataBroker.newWriteOnlyTransaction();
622         verify(mockDOMDataBroker).newWriteOnlyTransaction();
623     }
624
625     @Test
626     public void testSlaveNewNetconfDataTreeServiceRequest() {
627         initializeMaster(List.of());
628         registerSlaveMountPoint();
629
630         ArgumentCaptor<NetconfDataTreeService> netconfCaptor = ArgumentCaptor.forClass(NetconfDataTreeService.class);
631         verify(mockMountPointBuilder).addService(eq(NetconfDataTreeService.class), netconfCaptor.capture());
632
633         final NetconfDataTreeService slaveNetconfService = netconfCaptor.getValue();
634         assertTrue(slaveNetconfService instanceof ProxyNetconfDataTreeService);
635
636         final YangInstanceIdentifier PATH = YangInstanceIdentifier.empty();
637         final LogicalDatastoreType STORE = LogicalDatastoreType.CONFIGURATION;
638         final ContainerNode NODE = Builders.containerBuilder()
639             .withNodeIdentifier(new NodeIdentifier(QName.create("", "cont")))
640             .build();
641
642         final FluentFuture<Optional<Object>> result = immediateFluentFuture(Optional.of(NODE));
643         doReturn(result).when(netconfService).get(PATH);
644         doReturn(result).when(netconfService).getConfig(PATH);
645         doReturn(emptyFluentFuture()).when(netconfService).commit();
646
647         slaveNetconfService.get(PATH);
648         slaveNetconfService.getConfig(PATH);
649         slaveNetconfService.lock();
650         slaveNetconfService.merge(STORE, PATH, NODE, Optional.empty());
651         slaveNetconfService.replace(STORE, PATH, NODE, Optional.empty());
652         slaveNetconfService.create(STORE, PATH, NODE, Optional.empty());
653         slaveNetconfService.delete(STORE, PATH);
654         slaveNetconfService.remove(STORE, PATH);
655         slaveNetconfService.discardChanges();
656         slaveNetconfService.commit();
657
658         verify(netconfService, timeout(1000)).get(PATH);
659         verify(netconfService, timeout(1000)).getConfig(PATH);
660         verify(netconfService, timeout(1000)).lock();
661         verify(netconfService, timeout(1000)).merge(STORE, PATH, NODE, Optional.empty());
662         verify(netconfService, timeout(1000)).replace(STORE, PATH, NODE, Optional.empty());
663         verify(netconfService, timeout(1000)).create(STORE, PATH, NODE, Optional.empty());
664         verify(netconfService, timeout(1000)).delete(STORE, PATH);
665         verify(netconfService, timeout(1000)).remove(STORE, PATH);
666         verify(netconfService, timeout(1000)).discardChanges();
667         verify(netconfService, timeout(1000)).commit();
668     }
669
670     private ActorRef registerSlaveMountPoint() {
671         SchemaResourcesDTO schemaResourceDTO2 = mock(SchemaResourcesDTO.class);
672         doReturn(mockRegistry).when(schemaResourceDTO2).getSchemaRegistry();
673         doReturn(mockSchemaRepository).when(schemaResourceDTO2).getSchemaRepository();
674         final ActorRef slaveRef = system.actorOf(NetconfNodeActor.props(
675                 NetconfTopologySetupBuilder.create().setSchemaResourceDTO(schemaResourceDTO2).setActorSystem(system)
676                 .setBaseSchemas(BASE_SCHEMAS).build(), remoteDeviceId, TIMEOUT, mockMountPointService));
677
678         doReturn(Futures.immediateFuture(mockSchemaContext))
679                 .when(mockSchemaContextFactory).createEffectiveModelContext(anyCollection());
680
681         slaveRef.tell(new RegisterMountPoint(ImmutableList.of(SOURCE_IDENTIFIER1, SOURCE_IDENTIFIER2),
682                 masterRef), testKit.getRef());
683
684         verify(mockMountPointBuilder, timeout(5000)).register();
685         verify(mockMountPointBuilder).addService(eq(DOMSchemaService.class), any());
686         verify(mockMountPointBuilder).addService(eq(DOMDataBroker.class), any());
687         verify(mockMountPointBuilder).addService(eq(NetconfDataTreeService.class), any());
688         verify(mockMountPointBuilder).addService(eq(DOMRpcService.class), any());
689         verify(mockMountPointBuilder).addService(eq(DOMNotificationService.class), any());
690
691         testKit.expectMsgClass(Success.class);
692         return slaveRef;
693     }
694
695     private void initializeMaster(final List<SourceIdentifier> sourceIdentifiers) {
696         masterRef.tell(new CreateInitialMasterActorData(mockDOMDataBroker, netconfService, sourceIdentifiers,
697                 new RemoteDeviceServices(mockDOMRpcService, mockDOMActionService)), testKit.getRef());
698         testKit.expectMsgClass(MasterActorDataInitialized.class);
699     }
700
701     private void resetMountPointMocks() {
702         reset(mockMountPointReg, mockMountPointBuilder);
703
704         doNothing().when(mockMountPointReg).close();
705
706         doReturn(mockMountPointBuilder).when(mockMountPointBuilder).addService(any(), any());
707         doReturn(mockMountPointReg).when(mockMountPointBuilder).register();
708     }
709
710     private static PotentialSchemaSource<?> withSourceId(final SourceIdentifier identifier) {
711         return argThat(argument -> identifier.equals(argument.getSourceIdentifier()));
712     }
713
714     private static String convertStreamToString(final InputStream is) {
715         try (Scanner scanner = new Scanner(is)) {
716             return scanner.useDelimiter("\\A").hasNext() ? scanner.next() : "";
717         }
718     }
719 }