Fix checkstyle reported by odlparent-3.0.0
[controller.git] / opendaylight / md-sal / sal-distributed-datastore / src / test / java / org / opendaylight / controller / cluster / datastore / utils / ActorContextTest.java
1 /*
2  * Copyright (c) 2014, 2015 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
9 package org.opendaylight.controller.cluster.datastore.utils;
10
11 import static org.junit.Assert.assertEquals;
12 import static org.junit.Assert.assertNotEquals;
13 import static org.junit.Assert.assertNotNull;
14 import static org.junit.Assert.assertNull;
15 import static org.junit.Assert.assertSame;
16 import static org.junit.Assert.assertTrue;
17 import static org.junit.Assert.fail;
18 import static org.mockito.Mockito.doReturn;
19 import static org.mockito.Mockito.mock;
20
21 import akka.actor.ActorRef;
22 import akka.actor.ActorSelection;
23 import akka.actor.ActorSystem;
24 import akka.actor.Address;
25 import akka.actor.Props;
26 import akka.actor.UntypedActor;
27 import akka.dispatch.Futures;
28 import akka.japi.Creator;
29 import akka.testkit.JavaTestKit;
30 import akka.testkit.TestActorRef;
31 import akka.util.Timeout;
32 import com.google.common.base.Optional;
33 import com.google.common.collect.Maps;
34 import com.google.common.collect.Sets;
35 import com.typesafe.config.ConfigFactory;
36 import java.util.Arrays;
37 import java.util.Map;
38 import java.util.concurrent.TimeUnit;
39 import org.junit.Assert;
40 import org.junit.Test;
41 import org.mockito.Mockito;
42 import org.opendaylight.controller.cluster.datastore.AbstractActorTest;
43 import org.opendaylight.controller.cluster.datastore.ClusterWrapper;
44 import org.opendaylight.controller.cluster.datastore.DataStoreVersions;
45 import org.opendaylight.controller.cluster.datastore.DatastoreContext;
46 import org.opendaylight.controller.cluster.datastore.DatastoreContextFactory;
47 import org.opendaylight.controller.cluster.datastore.config.Configuration;
48 import org.opendaylight.controller.cluster.datastore.exceptions.NoShardLeaderException;
49 import org.opendaylight.controller.cluster.datastore.exceptions.NotInitializedException;
50 import org.opendaylight.controller.cluster.datastore.exceptions.PrimaryNotFoundException;
51 import org.opendaylight.controller.cluster.datastore.messages.FindLocalShard;
52 import org.opendaylight.controller.cluster.datastore.messages.FindPrimary;
53 import org.opendaylight.controller.cluster.datastore.messages.LocalPrimaryShardFound;
54 import org.opendaylight.controller.cluster.datastore.messages.LocalShardFound;
55 import org.opendaylight.controller.cluster.datastore.messages.LocalShardNotFound;
56 import org.opendaylight.controller.cluster.datastore.messages.PrimaryShardInfo;
57 import org.opendaylight.controller.cluster.datastore.messages.RemotePrimaryShardFound;
58 import org.opendaylight.controller.cluster.raft.utils.EchoActor;
59 import org.opendaylight.controller.cluster.raft.utils.MessageCollectorActor;
60 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
61 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTree;
62 import org.slf4j.Logger;
63 import org.slf4j.LoggerFactory;
64 import scala.concurrent.Await;
65 import scala.concurrent.Future;
66 import scala.concurrent.duration.Duration;
67 import scala.concurrent.duration.FiniteDuration;
68
69 public class ActorContextTest extends AbstractActorTest {
70
71     static final Logger LOG = LoggerFactory.getLogger(ActorContextTest.class);
72
73     private static class TestMessage {
74     }
75
76     private static final class MockShardManager extends UntypedActor {
77
78         private final boolean found;
79         private final ActorRef actorRef;
80         private final Map<String,Object> findPrimaryResponses = Maps.newHashMap();
81
82         private MockShardManager(final boolean found, final ActorRef actorRef) {
83
84             this.found = found;
85             this.actorRef = actorRef;
86         }
87
88         @Override public void onReceive(final Object message) throws Exception {
89             if (message instanceof FindPrimary) {
90                 FindPrimary fp = (FindPrimary)message;
91                 Object resp = findPrimaryResponses.get(fp.getShardName());
92                 if (resp == null) {
93                     LOG.error("No expected FindPrimary response found for shard name {}", fp.getShardName());
94                 } else {
95                     getSender().tell(resp, getSelf());
96                 }
97
98                 return;
99             }
100
101             if (found) {
102                 getSender().tell(new LocalShardFound(actorRef), getSelf());
103             } else {
104                 getSender().tell(new LocalShardNotFound(((FindLocalShard) message).getShardName()), getSelf());
105             }
106         }
107
108         void addFindPrimaryResp(final String shardName, final Object resp) {
109             findPrimaryResponses.put(shardName, resp);
110         }
111
112         private static Props props(final boolean found, final ActorRef actorRef) {
113             return Props.create(new MockShardManagerCreator(found, actorRef));
114         }
115
116         private static Props props() {
117             return Props.create(new MockShardManagerCreator());
118         }
119
120         @SuppressWarnings("serial")
121         private static class MockShardManagerCreator implements Creator<MockShardManager> {
122             final boolean found;
123             final ActorRef actorRef;
124
125             MockShardManagerCreator() {
126                 this.found = false;
127                 this.actorRef = null;
128             }
129
130             MockShardManagerCreator(final boolean found, final ActorRef actorRef) {
131                 this.found = found;
132                 this.actorRef = actorRef;
133             }
134
135             @Override
136             public MockShardManager create() throws Exception {
137                 return new MockShardManager(found, actorRef);
138             }
139         }
140     }
141
142     @Test
143     public void testFindLocalShardWithShardFound() {
144         new JavaTestKit(getSystem()) {
145             {
146                 new Within(duration("1 seconds")) {
147                     @Override
148                     protected void run() {
149
150                         ActorRef shardActorRef = getSystem().actorOf(Props.create(EchoActor.class));
151
152                         ActorRef shardManagerActorRef = getSystem()
153                                 .actorOf(MockShardManager.props(true, shardActorRef));
154
155                         ActorContext actorContext = new ActorContext(getSystem(), shardManagerActorRef,
156                                 mock(ClusterWrapper.class), mock(Configuration.class));
157
158                         Optional<ActorRef> out = actorContext.findLocalShard("default");
159
160                         assertEquals(shardActorRef, out.get());
161
162                         expectNoMsg();
163                     }
164                 };
165             }
166         };
167
168     }
169
170     @Test
171     public void testFindLocalShardWithShardNotFound() {
172         new JavaTestKit(getSystem()) {
173             {
174                 ActorRef shardManagerActorRef = getSystem().actorOf(MockShardManager.props(false, null));
175
176                 ActorContext actorContext = new ActorContext(getSystem(), shardManagerActorRef,
177                         mock(ClusterWrapper.class), mock(Configuration.class));
178
179                 Optional<ActorRef> out = actorContext.findLocalShard("default");
180                 assertTrue(!out.isPresent());
181             }
182         };
183
184     }
185
186     @Test
187     public void testExecuteRemoteOperation() {
188         new JavaTestKit(getSystem()) {
189             {
190                 ActorRef shardActorRef = getSystem().actorOf(Props.create(EchoActor.class));
191
192                 ActorRef shardManagerActorRef = getSystem().actorOf(MockShardManager.props(true, shardActorRef));
193
194                 ActorContext actorContext = new ActorContext(getSystem(), shardManagerActorRef,
195                         mock(ClusterWrapper.class), mock(Configuration.class));
196
197                 ActorSelection actor = actorContext.actorSelection(shardActorRef.path());
198
199                 Object out = actorContext.executeOperation(actor, "hello");
200
201                 assertEquals("hello", out);
202             }
203         };
204     }
205
206     @Test
207     @SuppressWarnings("checkstyle:IllegalCatch")
208     public void testExecuteRemoteOperationAsync() {
209         new JavaTestKit(getSystem()) {
210             {
211                 ActorRef shardActorRef = getSystem().actorOf(Props.create(EchoActor.class));
212
213                 ActorRef shardManagerActorRef = getSystem().actorOf(MockShardManager.props(true, shardActorRef));
214
215                 ActorContext actorContext = new ActorContext(getSystem(), shardManagerActorRef,
216                         mock(ClusterWrapper.class), mock(Configuration.class));
217
218                 ActorSelection actor = actorContext.actorSelection(shardActorRef.path());
219
220                 Future<Object> future = actorContext.executeOperationAsync(actor, "hello");
221
222                 try {
223                     Object result = Await.result(future, Duration.create(3, TimeUnit.SECONDS));
224                     assertEquals("Result", "hello", result);
225                 } catch (Exception e) {
226                     throw new AssertionError(e);
227                 }
228             }
229         };
230     }
231
232     @Test
233     public void testIsPathLocal() {
234         MockClusterWrapper clusterWrapper = new MockClusterWrapper();
235         ActorContext actorContext = null;
236
237         actorContext = new ActorContext(getSystem(), null, clusterWrapper, mock(Configuration.class));
238         assertEquals(false, actorContext.isPathLocal(null));
239         assertEquals(false, actorContext.isPathLocal(""));
240
241         clusterWrapper.setSelfAddress(null);
242         actorContext = new ActorContext(getSystem(), null, clusterWrapper, mock(Configuration.class));
243         assertEquals(false, actorContext.isPathLocal(""));
244
245         // even if the path is in local format, match the primary path (first 3 elements) and return true
246         clusterWrapper.setSelfAddress(new Address("akka", "test"));
247         actorContext = new ActorContext(getSystem(), null, clusterWrapper, mock(Configuration.class));
248         assertEquals(true, actorContext.isPathLocal("akka://test/user/$a"));
249
250         clusterWrapper.setSelfAddress(new Address("akka", "test"));
251         actorContext = new ActorContext(getSystem(), null, clusterWrapper, mock(Configuration.class));
252         assertEquals(true, actorContext.isPathLocal("akka://test/user/$a"));
253
254         clusterWrapper.setSelfAddress(new Address("akka", "test"));
255         actorContext = new ActorContext(getSystem(), null, clusterWrapper, mock(Configuration.class));
256         assertEquals(true, actorContext.isPathLocal("akka://test/user/token2/token3/$a"));
257
258         // self address of remote format,but Tx path local format.
259         clusterWrapper.setSelfAddress(new Address("akka", "system", "127.0.0.1", 2550));
260         actorContext = new ActorContext(getSystem(), null, clusterWrapper, mock(Configuration.class));
261         assertEquals(true, actorContext.isPathLocal(
262             "akka://system/user/shardmanager/shard/transaction"));
263
264         // self address of local format,but Tx path remote format.
265         clusterWrapper.setSelfAddress(new Address("akka", "system"));
266         actorContext = new ActorContext(getSystem(), null, clusterWrapper, mock(Configuration.class));
267         assertEquals(false, actorContext.isPathLocal(
268             "akka://system@127.0.0.1:2550/user/shardmanager/shard/transaction"));
269
270         //local path but not same
271         clusterWrapper.setSelfAddress(new Address("akka", "test"));
272         actorContext = new ActorContext(getSystem(), null, clusterWrapper, mock(Configuration.class));
273         assertEquals(true, actorContext.isPathLocal("akka://test1/user/$a"));
274
275         //ip and port same
276         clusterWrapper.setSelfAddress(new Address("akka", "system", "127.0.0.1", 2550));
277         actorContext = new ActorContext(getSystem(), null, clusterWrapper, mock(Configuration.class));
278         assertEquals(true, actorContext.isPathLocal("akka://system@127.0.0.1:2550/"));
279
280         // forward-slash missing in address
281         clusterWrapper.setSelfAddress(new Address("akka", "system", "127.0.0.1", 2550));
282         actorContext = new ActorContext(getSystem(), null, clusterWrapper, mock(Configuration.class));
283         assertEquals(false, actorContext.isPathLocal("akka://system@127.0.0.1:2550"));
284
285         //ips differ
286         clusterWrapper.setSelfAddress(new Address("akka", "system", "127.0.0.1", 2550));
287         actorContext = new ActorContext(getSystem(), null, clusterWrapper, mock(Configuration.class));
288         assertEquals(false, actorContext.isPathLocal("akka://system@127.1.0.1:2550/"));
289
290         //ports differ
291         clusterWrapper.setSelfAddress(new Address("akka", "system", "127.0.0.1", 2550));
292         actorContext = new ActorContext(getSystem(), null, clusterWrapper, mock(Configuration.class));
293         assertEquals(false, actorContext.isPathLocal("akka://system@127.0.0.1:2551/"));
294     }
295
296     @Test
297     public void testClientDispatcherIsGlobalDispatcher() {
298         ActorContext actorContext = new ActorContext(getSystem(), mock(ActorRef.class), mock(ClusterWrapper.class),
299                 mock(Configuration.class), DatastoreContext.newBuilder().build(), new PrimaryShardInfoFutureCache());
300
301         assertEquals(getSystem().dispatchers().defaultGlobalDispatcher(), actorContext.getClientDispatcher());
302     }
303
304     @Test
305     public void testClientDispatcherIsNotGlobalDispatcher() {
306         ActorSystem actorSystem = ActorSystem.create("with-custom-dispatchers",
307                 ConfigFactory.load("application-with-custom-dispatchers.conf"));
308
309         ActorContext actorContext = new ActorContext(actorSystem, mock(ActorRef.class), mock(ClusterWrapper.class),
310                 mock(Configuration.class), DatastoreContext.newBuilder().build(), new PrimaryShardInfoFutureCache());
311
312         assertNotEquals(actorSystem.dispatchers().defaultGlobalDispatcher(), actorContext.getClientDispatcher());
313
314         actorSystem.terminate();
315     }
316
317     @Test
318     public void testSetDatastoreContext() {
319         new JavaTestKit(getSystem()) {
320             {
321                 ActorContext actorContext = new ActorContext(getSystem(), getRef(),
322                         mock(ClusterWrapper.class), mock(Configuration.class), DatastoreContext.newBuilder()
323                                 .operationTimeoutInSeconds(5).shardTransactionCommitTimeoutInSeconds(7).build(),
324                         new PrimaryShardInfoFutureCache());
325
326                 assertEquals("getOperationDuration", 5, actorContext.getOperationDuration().toSeconds());
327                 assertEquals("getTransactionCommitOperationTimeout", 7,
328                         actorContext.getTransactionCommitOperationTimeout().duration().toSeconds());
329
330                 DatastoreContext newContext = DatastoreContext.newBuilder().operationTimeoutInSeconds(6)
331                         .shardTransactionCommitTimeoutInSeconds(8).build();
332
333                 DatastoreContextFactory mockContextFactory = mock(DatastoreContextFactory.class);
334                 Mockito.doReturn(newContext).when(mockContextFactory).getBaseDatastoreContext();
335
336                 actorContext.setDatastoreContext(mockContextFactory);
337
338                 expectMsgClass(duration("5 seconds"), DatastoreContextFactory.class);
339
340                 Assert.assertSame("getDatastoreContext", newContext, actorContext.getDatastoreContext());
341
342                 assertEquals("getOperationDuration", 6, actorContext.getOperationDuration().toSeconds());
343                 assertEquals("getTransactionCommitOperationTimeout", 8,
344                         actorContext.getTransactionCommitOperationTimeout().duration().toSeconds());
345             }
346         };
347     }
348
349     @Test
350     public void testFindPrimaryShardAsyncRemotePrimaryFound() throws Exception {
351
352         ActorRef shardManager = getSystem().actorOf(MessageCollectorActor.props());
353
354         DatastoreContext dataStoreContext = DatastoreContext.newBuilder()
355                 .logicalStoreType(LogicalDatastoreType.CONFIGURATION)
356                 .shardLeaderElectionTimeout(100, TimeUnit.MILLISECONDS).build();
357
358         final String expPrimaryPath = "akka://test-system/find-primary-shard";
359         final short expPrimaryVersion = DataStoreVersions.CURRENT_VERSION;
360         ActorContext actorContext = new ActorContext(getSystem(), shardManager, mock(ClusterWrapper.class),
361                 mock(Configuration.class), dataStoreContext, new PrimaryShardInfoFutureCache()) {
362             @Override
363             protected Future<Object> doAsk(final ActorRef actorRef, final Object message, final Timeout timeout) {
364                 return Futures.successful((Object) new RemotePrimaryShardFound(expPrimaryPath, expPrimaryVersion));
365             }
366         };
367
368         Future<PrimaryShardInfo> foobar = actorContext.findPrimaryShardAsync("foobar");
369         PrimaryShardInfo actual = Await.result(foobar, Duration.apply(5000, TimeUnit.MILLISECONDS));
370
371         assertNotNull(actual);
372         assertEquals("LocalShardDataTree present", false, actual.getLocalShardDataTree().isPresent());
373         assertTrue("Unexpected PrimaryShardActor path " + actual.getPrimaryShardActor().path(),
374                 expPrimaryPath.endsWith(actual.getPrimaryShardActor().pathString()));
375         assertEquals("getPrimaryShardVersion", expPrimaryVersion, actual.getPrimaryShardVersion());
376
377         Future<PrimaryShardInfo> cached = actorContext.getPrimaryShardInfoCache().getIfPresent("foobar");
378
379         PrimaryShardInfo cachedInfo = Await.result(cached, FiniteDuration.apply(1, TimeUnit.MILLISECONDS));
380
381         assertEquals(cachedInfo, actual);
382
383         actorContext.getPrimaryShardInfoCache().remove("foobar");
384
385         cached = actorContext.getPrimaryShardInfoCache().getIfPresent("foobar");
386
387         assertNull(cached);
388     }
389
390     @Test
391     public void testFindPrimaryShardAsyncLocalPrimaryFound() throws Exception {
392
393         ActorRef shardManager = getSystem().actorOf(MessageCollectorActor.props());
394
395         DatastoreContext dataStoreContext = DatastoreContext.newBuilder()
396                 .logicalStoreType(LogicalDatastoreType.CONFIGURATION)
397                 .shardLeaderElectionTimeout(100, TimeUnit.MILLISECONDS).build();
398
399         final DataTree mockDataTree = Mockito.mock(DataTree.class);
400         final String expPrimaryPath = "akka://test-system/find-primary-shard";
401         ActorContext actorContext = new ActorContext(getSystem(), shardManager, mock(ClusterWrapper.class),
402                 mock(Configuration.class), dataStoreContext, new PrimaryShardInfoFutureCache()) {
403             @Override
404             protected Future<Object> doAsk(final ActorRef actorRef, final Object message, final Timeout timeout) {
405                 return Futures.successful((Object) new LocalPrimaryShardFound(expPrimaryPath, mockDataTree));
406             }
407         };
408
409         Future<PrimaryShardInfo> foobar = actorContext.findPrimaryShardAsync("foobar");
410         PrimaryShardInfo actual = Await.result(foobar, Duration.apply(5000, TimeUnit.MILLISECONDS));
411
412         assertNotNull(actual);
413         assertEquals("LocalShardDataTree present", true, actual.getLocalShardDataTree().isPresent());
414         assertSame("LocalShardDataTree", mockDataTree, actual.getLocalShardDataTree().get());
415         assertTrue("Unexpected PrimaryShardActor path " + actual.getPrimaryShardActor().path(),
416                 expPrimaryPath.endsWith(actual.getPrimaryShardActor().pathString()));
417         assertEquals("getPrimaryShardVersion", DataStoreVersions.CURRENT_VERSION, actual.getPrimaryShardVersion());
418
419         Future<PrimaryShardInfo> cached = actorContext.getPrimaryShardInfoCache().getIfPresent("foobar");
420
421         PrimaryShardInfo cachedInfo = Await.result(cached, FiniteDuration.apply(1, TimeUnit.MILLISECONDS));
422
423         assertEquals(cachedInfo, actual);
424
425         actorContext.getPrimaryShardInfoCache().remove("foobar");
426
427         cached = actorContext.getPrimaryShardInfoCache().getIfPresent("foobar");
428
429         assertNull(cached);
430     }
431
432     @Test
433     public void testFindPrimaryShardAsyncPrimaryNotFound() throws Exception {
434         testFindPrimaryExceptions(new PrimaryNotFoundException("not found"));
435     }
436
437     @Test
438     public void testFindPrimaryShardAsyncActorNotInitialized() throws Exception {
439         testFindPrimaryExceptions(new NotInitializedException("not initialized"));
440     }
441
442     @SuppressWarnings("checkstyle:IllegalCatch")
443     private static void testFindPrimaryExceptions(final Object expectedException) throws Exception {
444         ActorRef shardManager = getSystem().actorOf(MessageCollectorActor.props());
445
446         DatastoreContext dataStoreContext = DatastoreContext.newBuilder()
447                 .logicalStoreType(LogicalDatastoreType.CONFIGURATION)
448                 .shardLeaderElectionTimeout(100, TimeUnit.MILLISECONDS).build();
449
450         ActorContext actorContext =
451             new ActorContext(getSystem(), shardManager, mock(ClusterWrapper.class),
452                 mock(Configuration.class), dataStoreContext, new PrimaryShardInfoFutureCache()) {
453                 @Override
454                 protected Future<Object> doAsk(final ActorRef actorRef, final Object message, final Timeout timeout) {
455                     return Futures.successful(expectedException);
456                 }
457             };
458
459         Future<PrimaryShardInfo> foobar = actorContext.findPrimaryShardAsync("foobar");
460
461         try {
462             Await.result(foobar, Duration.apply(100, TimeUnit.MILLISECONDS));
463             fail("Expected" + expectedException.getClass().toString());
464         } catch (Exception e) {
465             if (!expectedException.getClass().isInstance(e)) {
466                 fail("Expected Exception of type " + expectedException.getClass().toString());
467             }
468         }
469
470         Future<PrimaryShardInfo> cached = actorContext.getPrimaryShardInfoCache().getIfPresent("foobar");
471
472         assertNull(cached);
473     }
474
475     @Test
476     public void testBroadcast() {
477         new JavaTestKit(getSystem()) {
478             {
479                 ActorRef shardActorRef1 = getSystem().actorOf(MessageCollectorActor.props());
480                 ActorRef shardActorRef2 = getSystem().actorOf(MessageCollectorActor.props());
481
482                 TestActorRef<MockShardManager> shardManagerActorRef = TestActorRef.create(getSystem(),
483                         MockShardManager.props());
484                 MockShardManager shardManagerActor = shardManagerActorRef.underlyingActor();
485                 shardManagerActor.addFindPrimaryResp("shard1", new RemotePrimaryShardFound(
486                         shardActorRef1.path().toString(), DataStoreVersions.CURRENT_VERSION));
487                 shardManagerActor.addFindPrimaryResp("shard2", new RemotePrimaryShardFound(
488                         shardActorRef2.path().toString(), DataStoreVersions.CURRENT_VERSION));
489                 shardManagerActor.addFindPrimaryResp("shard3", new NoShardLeaderException("not found"));
490
491                 Configuration mockConfig = mock(Configuration.class);
492                 doReturn(Sets.newLinkedHashSet(Arrays.asList("shard1", "shard2", "shard3"))).when(mockConfig)
493                         .getAllShardNames();
494
495                 ActorContext actorContext = new ActorContext(getSystem(), shardManagerActorRef,
496                         mock(ClusterWrapper.class), mockConfig,
497                         DatastoreContext.newBuilder().shardInitializationTimeout(200, TimeUnit.MILLISECONDS).build(),
498                         new PrimaryShardInfoFutureCache());
499
500                 actorContext.broadcast(v -> new TestMessage(), TestMessage.class);
501
502                 MessageCollectorActor.expectFirstMatching(shardActorRef1, TestMessage.class);
503                 MessageCollectorActor.expectFirstMatching(shardActorRef2, TestMessage.class);
504             }
505         };
506     }
507 }