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