c6b995d59d615fb9cc87526464aec3660d669188
[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.collect.Lists;
48 import com.google.common.io.ByteSource;
49 import com.google.common.net.InetAddresses;
50 import com.google.common.util.concurrent.FluentFuture;
51 import com.google.common.util.concurrent.Futures;
52 import com.google.common.util.concurrent.ListenableFuture;
53 import com.google.common.util.concurrent.SettableFuture;
54 import java.io.InputStream;
55 import java.net.InetSocketAddress;
56 import java.time.Duration;
57 import java.util.ArrayList;
58 import java.util.List;
59 import java.util.Optional;
60 import java.util.Scanner;
61 import java.util.concurrent.ExecutionException;
62 import java.util.concurrent.TimeUnit;
63 import org.junit.After;
64 import org.junit.Before;
65 import org.junit.Test;
66 import org.junit.runner.RunWith;
67 import org.mockito.ArgumentCaptor;
68 import org.mockito.Mock;
69 import org.mockito.junit.MockitoJUnitRunner;
70 import org.opendaylight.controller.cluster.schema.provider.impl.YangTextSchemaSourceSerializationProxy;
71 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
72 import org.opendaylight.mdsal.dom.api.DOMActionException;
73 import org.opendaylight.mdsal.dom.api.DOMActionResult;
74 import org.opendaylight.mdsal.dom.api.DOMActionService;
75 import org.opendaylight.mdsal.dom.api.DOMDataBroker;
76 import org.opendaylight.mdsal.dom.api.DOMDataTreeIdentifier;
77 import org.opendaylight.mdsal.dom.api.DOMDataTreeReadTransaction;
78 import org.opendaylight.mdsal.dom.api.DOMDataTreeReadWriteTransaction;
79 import org.opendaylight.mdsal.dom.api.DOMDataTreeWriteTransaction;
80 import org.opendaylight.mdsal.dom.api.DOMMountPoint;
81 import org.opendaylight.mdsal.dom.api.DOMMountPointService;
82 import org.opendaylight.mdsal.dom.api.DOMNotificationService;
83 import org.opendaylight.mdsal.dom.api.DOMRpcException;
84 import org.opendaylight.mdsal.dom.api.DOMRpcResult;
85 import org.opendaylight.mdsal.dom.api.DOMRpcService;
86 import org.opendaylight.mdsal.dom.api.DOMSchemaService;
87 import org.opendaylight.mdsal.dom.spi.DefaultDOMRpcResult;
88 import org.opendaylight.mdsal.dom.spi.SimpleDOMActionResult;
89 import org.opendaylight.netconf.dom.api.NetconfDataTreeService;
90 import org.opendaylight.netconf.sal.connect.netconf.NetconfDevice.SchemaResourcesDTO;
91 import org.opendaylight.netconf.sal.connect.util.RemoteDeviceId;
92 import org.opendaylight.netconf.topology.singleton.impl.actors.NetconfNodeActor;
93 import org.opendaylight.netconf.topology.singleton.impl.utils.ClusteringActionException;
94 import org.opendaylight.netconf.topology.singleton.impl.utils.ClusteringRpcException;
95 import org.opendaylight.netconf.topology.singleton.impl.utils.NetconfTopologySetup;
96 import org.opendaylight.netconf.topology.singleton.impl.utils.NetconfTopologySetup.NetconfTopologySetupBuilder;
97 import org.opendaylight.netconf.topology.singleton.messages.AskForMasterMountPoint;
98 import org.opendaylight.netconf.topology.singleton.messages.CreateInitialMasterActorData;
99 import org.opendaylight.netconf.topology.singleton.messages.MasterActorDataInitialized;
100 import org.opendaylight.netconf.topology.singleton.messages.NotMasterException;
101 import org.opendaylight.netconf.topology.singleton.messages.RefreshSetupMasterActorData;
102 import org.opendaylight.netconf.topology.singleton.messages.RegisterMountPoint;
103 import org.opendaylight.netconf.topology.singleton.messages.UnregisterSlaveMountPoint;
104 import org.opendaylight.yangtools.concepts.ObjectRegistration;
105 import org.opendaylight.yangtools.util.concurrent.FluentFutures;
106 import org.opendaylight.yangtools.yang.common.ErrorType;
107 import org.opendaylight.yangtools.yang.common.QName;
108 import org.opendaylight.yangtools.yang.common.RpcError;
109 import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
110 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
111 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
112 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
113 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
114 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
115 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableContainerNodeBuilder;
116 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
117 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
118 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier.Absolute;
119 import org.opendaylight.yangtools.yang.model.repo.api.EffectiveModelContextFactory;
120 import org.opendaylight.yangtools.yang.model.repo.api.MissingSchemaSourceException;
121 import org.opendaylight.yangtools.yang.model.repo.api.RevisionSourceIdentifier;
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 RevisionSourceIdentifier SOURCE_IDENTIFIER1 = RevisionSourceIdentifier.create("yang1");
139     private static final RevisionSourceIdentifier SOURCE_IDENTIFIER2 = RevisionSourceIdentifier.create("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 DOMRpcService mockDOMRpcService;
150
151     @Mock
152     private DOMActionService 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 = Lists.newArrayList(RevisionSourceIdentifier.create("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 = RevisionSourceIdentifier.create("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 = RevisionSourceIdentifier.create("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         final List<SourceIdentifier> sourceIdentifiers =
485                 Lists.newArrayList(RevisionSourceIdentifier.create("testID"));
486
487         initializeMaster(sourceIdentifiers);
488         registerSlaveMountPoint();
489
490         ArgumentCaptor<DOMRpcService> domRPCServiceCaptor = ArgumentCaptor.forClass(DOMRpcService.class);
491         verify(mockMountPointBuilder).addService(eq(DOMRpcService.class), domRPCServiceCaptor.capture());
492
493         final DOMRpcService slaveDomRPCService = domRPCServiceCaptor.getValue();
494         assertTrue(slaveDomRPCService instanceof ProxyDOMRpcService);
495
496         final QName testQName = QName.create("", "TestQname");
497         final NormalizedNode outputNode = ImmutableContainerNodeBuilder.create()
498                 .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(testQName))
499                 .withChild(ImmutableNodes.leafNode(testQName, "foo")).build();
500         final RpcError rpcError = RpcResultBuilder.newError(ErrorType.RPC, null, "Rpc invocation failed.");
501
502         // RPC with no response output.
503
504         doReturn(FluentFutures.immediateNullFluentFuture()).when(mockDOMRpcService).invokeRpc(any(), any());
505
506         DOMRpcResult result = slaveDomRPCService.invokeRpc(testQName, outputNode).get(2, TimeUnit.SECONDS);
507
508         assertEquals(null, result);
509
510         // RPC with response output.
511
512         doReturn(FluentFutures.immediateFluentFuture(new DefaultDOMRpcResult(outputNode)))
513                 .when(mockDOMRpcService).invokeRpc(any(), any());
514
515         result = slaveDomRPCService.invokeRpc(testQName, outputNode).get(2, TimeUnit.SECONDS);
516
517         assertEquals(outputNode, result.getResult());
518         assertTrue(result.getErrors().isEmpty());
519
520         // RPC with response error.
521
522         doReturn(FluentFutures.immediateFluentFuture(new DefaultDOMRpcResult(rpcError)))
523                 .when(mockDOMRpcService).invokeRpc(any(), any());
524
525         result = slaveDomRPCService.invokeRpc(testQName, outputNode).get(2, TimeUnit.SECONDS);
526
527         assertNull(result.getResult());
528         assertEquals(rpcError, result.getErrors().iterator().next());
529
530         // RPC with response output and error.
531
532         doReturn(FluentFutures.immediateFluentFuture(new DefaultDOMRpcResult(outputNode, rpcError)))
533                 .when(mockDOMRpcService).invokeRpc(any(), any());
534
535         final DOMRpcResult resultOutputError =
536                 slaveDomRPCService.invokeRpc(testQName, outputNode).get(2, TimeUnit.SECONDS);
537
538         assertEquals(outputNode, resultOutputError.getResult());
539         assertEquals(rpcError, resultOutputError.getErrors().iterator().next());
540
541         // RPC failure.
542         doReturn(FluentFutures.immediateFailedFluentFuture(new ClusteringRpcException("mock")))
543             .when(mockDOMRpcService).invokeRpc(any(), any());
544         final ListenableFuture<? extends DOMRpcResult> future = slaveDomRPCService.invokeRpc(testQName, outputNode);
545
546         final ExecutionException e = assertThrows(ExecutionException.class, () -> future.get(2, TimeUnit.SECONDS));
547         final Throwable cause = e.getCause();
548         assertThat(cause, instanceOf(DOMRpcException.class));
549         assertEquals("mock", cause.getMessage());
550     }
551
552     @Test
553     public void testSlaveInvokeAction() throws Exception {
554         final List<SourceIdentifier> sourceIdentifiers = Lists
555             .newArrayList(RevisionSourceIdentifier.create("testActionID"));
556         initializeMaster(sourceIdentifiers);
557         registerSlaveMountPoint();
558
559         ArgumentCaptor<DOMActionService> domActionServiceCaptor = ArgumentCaptor.forClass(DOMActionService.class);
560         verify(mockMountPointBuilder).addService(eq(DOMActionService.class), domActionServiceCaptor.capture());
561
562         final DOMActionService slaveDomActionService = domActionServiceCaptor.getValue();
563         assertTrue(slaveDomActionService instanceof ProxyDOMActionService);
564
565         final QName testQName = QName.create("test", "2019-08-16", "TestActionQname");
566         final Absolute schemaPath = Absolute.of(testQName);
567
568         final YangInstanceIdentifier yangIIdPath = YangInstanceIdentifier
569             .create(new YangInstanceIdentifier.NodeIdentifier(testQName));
570
571         final DOMDataTreeIdentifier domDataTreeIdentifier = new DOMDataTreeIdentifier(LogicalDatastoreType.OPERATIONAL,
572             yangIIdPath);
573
574         final ContainerNode outputNode = ImmutableContainerNodeBuilder.create()
575             .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(testQName))
576             .withChild(ImmutableNodes.leafNode(testQName, "foo")).build();
577
578         // Action with no response output.
579         doReturn(FluentFutures.immediateNullFluentFuture()).when(mockDOMActionService)
580             .invokeAction(any(), any(), any());
581         DOMActionResult result = slaveDomActionService.invokeAction(schemaPath, domDataTreeIdentifier, outputNode)
582             .get(2, TimeUnit.SECONDS);
583         assertEquals(null, result);
584
585         // Action with response output.
586         doReturn(FluentFutures.immediateFluentFuture(new SimpleDOMActionResult(outputNode))).when(mockDOMActionService)
587             .invokeAction(any(), any(), any());
588         result = slaveDomActionService.invokeAction(schemaPath, domDataTreeIdentifier, outputNode)
589             .get(2, TimeUnit.SECONDS);
590
591         assertEquals(outputNode, result.getOutput().get());
592         assertTrue(result.getErrors().isEmpty());
593
594         // Action failure.
595         doReturn(FluentFutures.immediateFailedFluentFuture(new ClusteringActionException("mock")))
596             .when(mockDOMActionService).invokeAction(any(), any(), any());
597         final ListenableFuture<? extends DOMActionResult> future = slaveDomActionService.invokeAction(schemaPath,
598             domDataTreeIdentifier, outputNode);
599
600         final ExecutionException e = assertThrows(ExecutionException.class, () -> future.get(2, TimeUnit.SECONDS));
601         final Throwable cause = e.getCause();
602         assertThat(cause, instanceOf(DOMActionException.class));
603         assertEquals("mock", cause.getMessage());
604     }
605
606     @Test
607     public void testSlaveNewTransactionRequests() {
608         doReturn(mock(DOMDataTreeReadTransaction.class)).when(mockDOMDataBroker).newReadOnlyTransaction();
609         doReturn(mock(DOMDataTreeReadWriteTransaction.class)).when(mockDOMDataBroker).newReadWriteTransaction();
610         doReturn(mock(DOMDataTreeWriteTransaction.class)).when(mockDOMDataBroker).newWriteOnlyTransaction();
611
612         initializeMaster(List.of());
613         registerSlaveMountPoint();
614
615         ArgumentCaptor<DOMDataBroker> domDataBrokerCaptor = ArgumentCaptor.forClass(DOMDataBroker.class);
616         verify(mockMountPointBuilder).addService(eq(DOMDataBroker.class), domDataBrokerCaptor.capture());
617
618         final DOMDataBroker slaveDOMDataBroker = domDataBrokerCaptor.getValue();
619         assertTrue(slaveDOMDataBroker instanceof ProxyDOMDataBroker);
620
621         slaveDOMDataBroker.newReadOnlyTransaction();
622         verify(mockDOMDataBroker).newReadOnlyTransaction();
623
624         slaveDOMDataBroker.newReadWriteTransaction();
625         verify(mockDOMDataBroker).newReadWriteTransaction();
626
627         slaveDOMDataBroker.newWriteOnlyTransaction();
628         verify(mockDOMDataBroker).newWriteOnlyTransaction();
629     }
630
631     @Test
632     public void testSlaveNewNetconfDataTreeServiceRequest() {
633         initializeMaster(List.of());
634         registerSlaveMountPoint();
635
636         ArgumentCaptor<NetconfDataTreeService> netconfCaptor = ArgumentCaptor.forClass(NetconfDataTreeService.class);
637         verify(mockMountPointBuilder).addService(eq(NetconfDataTreeService.class), netconfCaptor.capture());
638
639         final NetconfDataTreeService slaveNetconfService = netconfCaptor.getValue();
640         assertTrue(slaveNetconfService instanceof ProxyNetconfDataTreeService);
641
642         final YangInstanceIdentifier PATH = YangInstanceIdentifier.empty();
643         final LogicalDatastoreType STORE = LogicalDatastoreType.CONFIGURATION;
644         final ContainerNode NODE = Builders.containerBuilder()
645             .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(QName.create("", "cont")))
646             .build();
647
648         final FluentFuture<Optional<Object>> result = immediateFluentFuture(Optional.of(NODE));
649         doReturn(result).when(netconfService).get(PATH);
650         doReturn(result).when(netconfService).getConfig(PATH);
651         doReturn(emptyFluentFuture()).when(netconfService).commit();
652
653         slaveNetconfService.get(PATH);
654         slaveNetconfService.getConfig(PATH);
655         slaveNetconfService.lock();
656         slaveNetconfService.merge(STORE, PATH, NODE, Optional.empty());
657         slaveNetconfService.replace(STORE, PATH, NODE, Optional.empty());
658         slaveNetconfService.create(STORE, PATH, NODE, Optional.empty());
659         slaveNetconfService.delete(STORE, PATH);
660         slaveNetconfService.remove(STORE, PATH);
661         slaveNetconfService.discardChanges();
662         slaveNetconfService.commit();
663
664         verify(netconfService, timeout(1000)).get(PATH);
665         verify(netconfService, timeout(1000)).getConfig(PATH);
666         verify(netconfService, timeout(1000)).lock();
667         verify(netconfService, timeout(1000)).merge(STORE, PATH, NODE, Optional.empty());
668         verify(netconfService, timeout(1000)).replace(STORE, PATH, NODE, Optional.empty());
669         verify(netconfService, timeout(1000)).create(STORE, PATH, NODE, Optional.empty());
670         verify(netconfService, timeout(1000)).delete(STORE, PATH);
671         verify(netconfService, timeout(1000)).remove(STORE, PATH);
672         verify(netconfService, timeout(1000)).discardChanges();
673         verify(netconfService, timeout(1000)).commit();
674     }
675
676     private ActorRef registerSlaveMountPoint() {
677         SchemaResourcesDTO schemaResourceDTO2 = mock(SchemaResourcesDTO.class);
678         doReturn(mockRegistry).when(schemaResourceDTO2).getSchemaRegistry();
679         doReturn(mockSchemaRepository).when(schemaResourceDTO2).getSchemaRepository();
680         final ActorRef slaveRef = system.actorOf(NetconfNodeActor.props(
681                 NetconfTopologySetupBuilder.create().setSchemaResourceDTO(schemaResourceDTO2).setActorSystem(system)
682                 .setBaseSchemas(BASE_SCHEMAS).build(), remoteDeviceId, TIMEOUT, mockMountPointService));
683
684         doReturn(Futures.immediateFuture(mockSchemaContext))
685                 .when(mockSchemaContextFactory).createEffectiveModelContext(anyCollection());
686
687         slaveRef.tell(new RegisterMountPoint(ImmutableList.of(SOURCE_IDENTIFIER1, SOURCE_IDENTIFIER2),
688                 masterRef), testKit.getRef());
689
690         verify(mockMountPointBuilder, timeout(5000)).register();
691         verify(mockMountPointBuilder).addService(eq(DOMSchemaService.class), any());
692         verify(mockMountPointBuilder).addService(eq(DOMDataBroker.class), any());
693         verify(mockMountPointBuilder).addService(eq(NetconfDataTreeService.class), any());
694         verify(mockMountPointBuilder).addService(eq(DOMRpcService.class), any());
695         verify(mockMountPointBuilder).addService(eq(DOMNotificationService.class), any());
696
697         testKit.expectMsgClass(Success.class);
698         return slaveRef;
699     }
700
701     private void initializeMaster(final List<SourceIdentifier> sourceIdentifiers) {
702         masterRef.tell(new CreateInitialMasterActorData(mockDOMDataBroker, netconfService, sourceIdentifiers,
703                 mockDOMRpcService, mockDOMActionService), testKit.getRef());
704         testKit.expectMsgClass(MasterActorDataInitialized.class);
705     }
706
707     private void resetMountPointMocks() {
708         reset(mockMountPointReg, mockMountPointBuilder);
709
710         doNothing().when(mockMountPointReg).close();
711
712         doReturn(mockMountPointBuilder).when(mockMountPointBuilder).addService(any(), any());
713         doReturn(mockMountPointReg).when(mockMountPointBuilder).register();
714     }
715
716     private static PotentialSchemaSource<?> withSourceId(final SourceIdentifier identifier) {
717         return argThat(argument -> identifier.equals(argument.getSourceIdentifier()));
718     }
719
720     private static String convertStreamToString(final InputStream is) {
721         try (Scanner scanner = new Scanner(is)) {
722             return scanner.useDelimiter("\\A").hasNext() ? scanner.next() : "";
723         }
724     }
725 }