1 package org.opendaylight.controller.cluster.datastore.utils;
3 import static org.junit.Assert.assertEquals;
4 import static org.junit.Assert.assertNotEquals;
5 import static org.junit.Assert.assertNotNull;
6 import static org.junit.Assert.assertNull;
7 import static org.junit.Assert.assertSame;
8 import static org.junit.Assert.assertTrue;
9 import static org.junit.Assert.fail;
10 import static org.mockito.Mockito.doReturn;
11 import static org.mockito.Mockito.mock;
12 import akka.actor.ActorRef;
13 import akka.actor.ActorSelection;
14 import akka.actor.ActorSystem;
15 import akka.actor.Address;
16 import akka.actor.Props;
17 import akka.actor.UntypedActor;
18 import akka.dispatch.Futures;
19 import akka.japi.Creator;
20 import akka.testkit.JavaTestKit;
21 import akka.testkit.TestActorRef;
22 import akka.util.Timeout;
23 import com.google.common.base.Optional;
24 import com.google.common.collect.Maps;
25 import com.google.common.collect.Sets;
26 import com.google.common.util.concurrent.Uninterruptibles;
27 import com.typesafe.config.ConfigFactory;
28 import java.util.Arrays;
30 import java.util.concurrent.TimeUnit;
31 import org.junit.Assert;
32 import org.junit.Test;
33 import org.mockito.Mockito;
34 import org.opendaylight.controller.cluster.datastore.AbstractActorTest;
35 import org.opendaylight.controller.cluster.datastore.ClusterWrapper;
36 import org.opendaylight.controller.cluster.datastore.Configuration;
37 import org.opendaylight.controller.cluster.datastore.DataStoreVersions;
38 import org.opendaylight.controller.cluster.datastore.DatastoreContext;
39 import org.opendaylight.controller.cluster.datastore.exceptions.NoShardLeaderException;
40 import org.opendaylight.controller.cluster.datastore.exceptions.NotInitializedException;
41 import org.opendaylight.controller.cluster.datastore.exceptions.PrimaryNotFoundException;
42 import org.opendaylight.controller.cluster.datastore.messages.FindLocalShard;
43 import org.opendaylight.controller.cluster.datastore.messages.FindPrimary;
44 import org.opendaylight.controller.cluster.datastore.messages.LocalPrimaryShardFound;
45 import org.opendaylight.controller.cluster.datastore.messages.LocalShardFound;
46 import org.opendaylight.controller.cluster.datastore.messages.LocalShardNotFound;
47 import org.opendaylight.controller.cluster.datastore.messages.PrimaryShardInfo;
48 import org.opendaylight.controller.cluster.datastore.messages.RemotePrimaryShardFound;
49 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTree;
50 import org.slf4j.Logger;
51 import org.slf4j.LoggerFactory;
52 import scala.concurrent.Await;
53 import scala.concurrent.Future;
54 import scala.concurrent.duration.Duration;
55 import scala.concurrent.duration.FiniteDuration;
57 public class ActorContextTest extends AbstractActorTest{
59 static final Logger log = LoggerFactory.getLogger(ActorContextTest.class);
61 private static class TestMessage {
64 private static class MockShardManager extends UntypedActor {
66 private final boolean found;
67 private final ActorRef actorRef;
68 private final Map<String,Object> findPrimaryResponses = Maps.newHashMap();
70 private MockShardManager(boolean found, ActorRef actorRef){
73 this.actorRef = actorRef;
76 @Override public void onReceive(Object message) throws Exception {
77 if(message instanceof FindPrimary) {
78 FindPrimary fp = (FindPrimary)message;
79 Object resp = findPrimaryResponses.get(fp.getShardName());
81 log.error("No expected FindPrimary response found for shard name {}", fp.getShardName());
83 getSender().tell(resp, getSelf());
90 getSender().tell(new LocalShardFound(actorRef), getSelf());
92 getSender().tell(new LocalShardNotFound(((FindLocalShard) message).getShardName()), getSelf());
96 void addFindPrimaryResp(String shardName, Object resp) {
97 findPrimaryResponses.put(shardName, resp);
100 private static Props props(final boolean found, final ActorRef actorRef){
101 return Props.create(new MockShardManagerCreator(found, actorRef) );
104 private static Props props(){
105 return Props.create(new MockShardManagerCreator() );
108 @SuppressWarnings("serial")
109 private static class MockShardManagerCreator implements Creator<MockShardManager> {
111 final ActorRef actorRef;
113 MockShardManagerCreator() {
115 this.actorRef = null;
118 MockShardManagerCreator(boolean found, ActorRef actorRef) {
120 this.actorRef = actorRef;
124 public MockShardManager create() throws Exception {
125 return new MockShardManager(found, actorRef);
131 public void testFindLocalShardWithShardFound(){
132 new JavaTestKit(getSystem()) {{
134 new Within(duration("1 seconds")) {
136 protected void run() {
138 ActorRef shardActorRef = getSystem().actorOf(Props.create(EchoActor.class));
140 ActorRef shardManagerActorRef = getSystem()
141 .actorOf(MockShardManager.props(true, shardActorRef));
143 ActorContext actorContext =
144 new ActorContext(getSystem(), shardManagerActorRef , mock(ClusterWrapper.class),
145 mock(Configuration.class));
147 Optional<ActorRef> out = actorContext.findLocalShard("default");
149 assertEquals(shardActorRef, out.get());
160 public void testFindLocalShardWithShardNotFound(){
161 new JavaTestKit(getSystem()) {{
162 ActorRef shardManagerActorRef = getSystem()
163 .actorOf(MockShardManager.props(false, null));
165 ActorContext actorContext =
166 new ActorContext(getSystem(), shardManagerActorRef , mock(ClusterWrapper.class),
167 mock(Configuration.class));
169 Optional<ActorRef> out = actorContext.findLocalShard("default");
170 assertTrue(!out.isPresent());
176 public void testExecuteRemoteOperation() {
177 new JavaTestKit(getSystem()) {{
178 ActorRef shardActorRef = getSystem().actorOf(Props.create(EchoActor.class));
180 ActorRef shardManagerActorRef = getSystem()
181 .actorOf(MockShardManager.props(true, shardActorRef));
183 ActorContext actorContext =
184 new ActorContext(getSystem(), shardManagerActorRef , mock(ClusterWrapper.class),
185 mock(Configuration.class));
187 ActorSelection actor = actorContext.actorSelection(shardActorRef.path());
189 Object out = actorContext.executeOperation(actor, "hello");
191 assertEquals("hello", out);
196 public void testExecuteRemoteOperationAsync() {
197 new JavaTestKit(getSystem()) {{
198 ActorRef shardActorRef = getSystem().actorOf(Props.create(EchoActor.class));
200 ActorRef shardManagerActorRef = getSystem()
201 .actorOf(MockShardManager.props(true, shardActorRef));
203 ActorContext actorContext =
204 new ActorContext(getSystem(), shardManagerActorRef , mock(ClusterWrapper.class),
205 mock(Configuration.class));
207 ActorSelection actor = actorContext.actorSelection(shardActorRef.path());
209 Future<Object> future = actorContext.executeOperationAsync(actor, "hello");
212 Object result = Await.result(future, Duration.create(3, TimeUnit.SECONDS));
213 assertEquals("Result", "hello", result);
214 } catch(Exception e) {
215 throw new AssertionError(e);
221 public void testIsPathLocal() {
222 MockClusterWrapper clusterWrapper = new MockClusterWrapper();
223 ActorContext actorContext = null;
225 actorContext = new ActorContext(getSystem(), null, clusterWrapper, mock(Configuration.class));
226 assertEquals(false, actorContext.isPathLocal(null));
227 assertEquals(false, actorContext.isPathLocal(""));
229 clusterWrapper.setSelfAddress(null);
230 actorContext = new ActorContext(getSystem(), null, clusterWrapper, mock(Configuration.class));
231 assertEquals(false, actorContext.isPathLocal(""));
233 // even if the path is in local format, match the primary path (first 3 elements) and return true
234 clusterWrapper.setSelfAddress(new Address("akka", "test"));
235 actorContext = new ActorContext(getSystem(), null, clusterWrapper, mock(Configuration.class));
236 assertEquals(true, actorContext.isPathLocal("akka://test/user/$a"));
238 clusterWrapper.setSelfAddress(new Address("akka", "test"));
239 actorContext = new ActorContext(getSystem(), null, clusterWrapper, mock(Configuration.class));
240 assertEquals(true, actorContext.isPathLocal("akka://test/user/$a"));
242 clusterWrapper.setSelfAddress(new Address("akka", "test"));
243 actorContext = new ActorContext(getSystem(), null, clusterWrapper, mock(Configuration.class));
244 assertEquals(true, actorContext.isPathLocal("akka://test/user/token2/token3/$a"));
246 // self address of remote format,but Tx path local format.
247 clusterWrapper.setSelfAddress(new Address("akka.tcp", "system", "127.0.0.1", 2550));
248 actorContext = new ActorContext(getSystem(), null, clusterWrapper, mock(Configuration.class));
249 assertEquals(true, actorContext.isPathLocal(
250 "akka://system/user/shardmanager/shard/transaction"));
252 // self address of local format,but Tx path remote format.
253 clusterWrapper.setSelfAddress(new Address("akka.tcp", "system"));
254 actorContext = new ActorContext(getSystem(), null, clusterWrapper, mock(Configuration.class));
255 assertEquals(false, actorContext.isPathLocal(
258 //local path but not same
259 clusterWrapper.setSelfAddress(new Address("akka", "test"));
260 actorContext = new ActorContext(getSystem(), null, clusterWrapper, mock(Configuration.class));
261 assertEquals(true, actorContext.isPathLocal("akka://test1/user/$a"));
264 clusterWrapper.setSelfAddress(new Address("akka.tcp", "system", "127.0.0.1", 2550));
265 actorContext = new ActorContext(getSystem(), null, clusterWrapper, mock(Configuration.class));
268 // forward-slash missing in address
269 clusterWrapper.setSelfAddress(new Address("akka.tcp", "system", "127.0.0.1", 2550));
270 actorContext = new ActorContext(getSystem(), null, clusterWrapper, mock(Configuration.class));
274 clusterWrapper.setSelfAddress(new Address("akka.tcp", "system", "127.0.0.1", 2550));
275 actorContext = new ActorContext(getSystem(), null, clusterWrapper, mock(Configuration.class));
279 clusterWrapper.setSelfAddress(new Address("akka.tcp", "system", "127.0.0.1", 2550));
280 actorContext = new ActorContext(getSystem(), null, clusterWrapper, mock(Configuration.class));
285 public void testResolvePathForRemoteActor() {
286 ActorContext actorContext =
287 new ActorContext(getSystem(), mock(ActorRef.class), mock(
288 ClusterWrapper.class),
289 mock(Configuration.class));
291 String actual = actorContext.resolvePath(
293 "akka://system/user/shardmanager/shard/transaction");
297 assertEquals(expected, actual);
301 public void testResolvePathForLocalActor() {
302 ActorContext actorContext =
303 new ActorContext(getSystem(), mock(ActorRef.class), mock(ClusterWrapper.class),
304 mock(Configuration.class));
306 String actual = actorContext.resolvePath(
307 "akka://system/user/shardmanager/shard",
308 "akka://system/user/shardmanager/shard/transaction");
310 String expected = "akka://system/user/shardmanager/shard/transaction";
312 assertEquals(expected, actual);
316 public void testResolvePathForRemoteActorWithProperRemoteAddress() {
317 ActorContext actorContext =
318 new ActorContext(getSystem(), mock(ActorRef.class), mock(ClusterWrapper.class),
319 mock(Configuration.class));
321 String actual = actorContext.resolvePath(
327 assertEquals(expected, actual);
332 public void testClientDispatcherIsGlobalDispatcher(){
333 ActorContext actorContext =
334 new ActorContext(getSystem(), mock(ActorRef.class), mock(ClusterWrapper.class),
335 mock(Configuration.class), DatastoreContext.newBuilder().build(), new PrimaryShardInfoFutureCache());
337 assertEquals(getSystem().dispatchers().defaultGlobalDispatcher(), actorContext.getClientDispatcher());
342 public void testClientDispatcherIsNotGlobalDispatcher(){
343 ActorSystem actorSystem = ActorSystem.create("with-custom-dispatchers", ConfigFactory.load("application-with-custom-dispatchers.conf"));
345 ActorContext actorContext =
346 new ActorContext(actorSystem, mock(ActorRef.class), mock(ClusterWrapper.class),
347 mock(Configuration.class), DatastoreContext.newBuilder().build(), new PrimaryShardInfoFutureCache());
349 assertNotEquals(actorSystem.dispatchers().defaultGlobalDispatcher(), actorContext.getClientDispatcher());
351 actorSystem.shutdown();
356 public void testSetDatastoreContext() {
357 new JavaTestKit(getSystem()) {{
358 ActorContext actorContext = new ActorContext(getSystem(), getRef(), mock(ClusterWrapper.class),
359 mock(Configuration.class), DatastoreContext.newBuilder().
360 operationTimeoutInSeconds(5).shardTransactionCommitTimeoutInSeconds(7).build(), new PrimaryShardInfoFutureCache());
362 assertEquals("getOperationDuration", 5, actorContext.getOperationDuration().toSeconds());
363 assertEquals("getTransactionCommitOperationTimeout", 7,
364 actorContext.getTransactionCommitOperationTimeout().duration().toSeconds());
366 DatastoreContext newContext = DatastoreContext.newBuilder().operationTimeoutInSeconds(6).
367 shardTransactionCommitTimeoutInSeconds(8).build();
369 actorContext.setDatastoreContext(newContext);
371 expectMsgClass(duration("5 seconds"), DatastoreContext.class);
373 Assert.assertSame("getDatastoreContext", newContext, actorContext.getDatastoreContext());
375 assertEquals("getOperationDuration", 6, actorContext.getOperationDuration().toSeconds());
376 assertEquals("getTransactionCommitOperationTimeout", 8,
377 actorContext.getTransactionCommitOperationTimeout().duration().toSeconds());
382 public void testFindPrimaryShardAsyncRemotePrimaryFound() throws Exception {
384 TestActorRef<MessageCollectorActor> shardManager =
385 TestActorRef.create(getSystem(), Props.create(MessageCollectorActor.class));
387 DatastoreContext dataStoreContext = DatastoreContext.newBuilder().dataStoreType("config").
388 shardLeaderElectionTimeout(100, TimeUnit.MILLISECONDS).build();
390 final String expPrimaryPath = "akka://test-system/find-primary-shard";
391 final short expPrimaryVersion = DataStoreVersions.CURRENT_VERSION;
392 ActorContext actorContext =
393 new ActorContext(getSystem(), shardManager, mock(ClusterWrapper.class),
394 mock(Configuration.class), dataStoreContext, new PrimaryShardInfoFutureCache()) {
396 protected Future<Object> doAsk(ActorRef actorRef, Object message, Timeout timeout) {
397 return Futures.successful((Object) new RemotePrimaryShardFound(expPrimaryPath, expPrimaryVersion));
401 Future<PrimaryShardInfo> foobar = actorContext.findPrimaryShardAsync("foobar");
402 PrimaryShardInfo actual = Await.result(foobar, Duration.apply(5000, TimeUnit.MILLISECONDS));
404 assertNotNull(actual);
405 assertEquals("LocalShardDataTree present", false, actual.getLocalShardDataTree().isPresent());
406 assertTrue("Unexpected PrimaryShardActor path " + actual.getPrimaryShardActor().path(),
407 expPrimaryPath.endsWith(actual.getPrimaryShardActor().pathString()));
408 assertEquals("getPrimaryShardVersion", expPrimaryVersion, actual.getPrimaryShardVersion());
410 Future<PrimaryShardInfo> cached = actorContext.getPrimaryShardInfoCache().getIfPresent("foobar");
412 PrimaryShardInfo cachedInfo = Await.result(cached, FiniteDuration.apply(1, TimeUnit.MILLISECONDS));
414 assertEquals(cachedInfo, actual);
416 actorContext.getPrimaryShardInfoCache().remove("foobar");
418 cached = actorContext.getPrimaryShardInfoCache().getIfPresent("foobar");
424 public void testFindPrimaryShardAsyncLocalPrimaryFound() throws Exception {
426 TestActorRef<MessageCollectorActor> shardManager =
427 TestActorRef.create(getSystem(), Props.create(MessageCollectorActor.class));
429 DatastoreContext dataStoreContext = DatastoreContext.newBuilder().dataStoreType("config").
430 shardLeaderElectionTimeout(100, TimeUnit.MILLISECONDS).build();
432 final DataTree mockDataTree = Mockito.mock(DataTree.class);
433 final String expPrimaryPath = "akka://test-system/find-primary-shard";
434 ActorContext actorContext =
435 new ActorContext(getSystem(), shardManager, mock(ClusterWrapper.class),
436 mock(Configuration.class), dataStoreContext, new PrimaryShardInfoFutureCache()) {
438 protected Future<Object> doAsk(ActorRef actorRef, Object message, Timeout timeout) {
439 return Futures.successful((Object) new LocalPrimaryShardFound(expPrimaryPath, mockDataTree));
443 Future<PrimaryShardInfo> foobar = actorContext.findPrimaryShardAsync("foobar");
444 PrimaryShardInfo actual = Await.result(foobar, Duration.apply(5000, TimeUnit.MILLISECONDS));
446 assertNotNull(actual);
447 assertEquals("LocalShardDataTree present", true, actual.getLocalShardDataTree().isPresent());
448 assertSame("LocalShardDataTree", mockDataTree, actual.getLocalShardDataTree().get());
449 assertTrue("Unexpected PrimaryShardActor path " + actual.getPrimaryShardActor().path(),
450 expPrimaryPath.endsWith(actual.getPrimaryShardActor().pathString()));
451 assertEquals("getPrimaryShardVersion", DataStoreVersions.CURRENT_VERSION, actual.getPrimaryShardVersion());
453 Future<PrimaryShardInfo> cached = actorContext.getPrimaryShardInfoCache().getIfPresent("foobar");
455 PrimaryShardInfo cachedInfo = Await.result(cached, FiniteDuration.apply(1, TimeUnit.MILLISECONDS));
457 assertEquals(cachedInfo, actual);
459 actorContext.getPrimaryShardInfoCache().remove("foobar");
461 cached = actorContext.getPrimaryShardInfoCache().getIfPresent("foobar");
467 public void testFindPrimaryShardAsyncPrimaryNotFound() throws Exception {
468 testFindPrimaryExceptions(new PrimaryNotFoundException("not found"));
472 public void testFindPrimaryShardAsyncActorNotInitialized() throws Exception {
473 testFindPrimaryExceptions(new NotInitializedException("not initialized"));
476 private void testFindPrimaryExceptions(final Object expectedException) throws Exception {
477 TestActorRef<MessageCollectorActor> shardManager =
478 TestActorRef.create(getSystem(), Props.create(MessageCollectorActor.class));
480 DatastoreContext dataStoreContext = DatastoreContext.newBuilder().dataStoreType("config").
481 shardLeaderElectionTimeout(100, TimeUnit.MILLISECONDS).build();
483 ActorContext actorContext =
484 new ActorContext(getSystem(), shardManager, mock(ClusterWrapper.class),
485 mock(Configuration.class), dataStoreContext, new PrimaryShardInfoFutureCache()) {
487 protected Future<Object> doAsk(ActorRef actorRef, Object message, Timeout timeout) {
488 return Futures.successful(expectedException);
492 Future<PrimaryShardInfo> foobar = actorContext.findPrimaryShardAsync("foobar");
495 Await.result(foobar, Duration.apply(100, TimeUnit.MILLISECONDS));
496 fail("Expected" + expectedException.getClass().toString());
497 } catch(Exception e){
498 if(!expectedException.getClass().isInstance(e)) {
499 fail("Expected Exception of type " + expectedException.getClass().toString());
503 Future<PrimaryShardInfo> cached = actorContext.getPrimaryShardInfoCache().getIfPresent("foobar");
509 public void testBroadcast() {
510 new JavaTestKit(getSystem()) {{
511 ActorRef shardActorRef1 = getSystem().actorOf(Props.create(MessageCollectorActor.class));
512 ActorRef shardActorRef2 = getSystem().actorOf(Props.create(MessageCollectorActor.class));
514 TestActorRef<MockShardManager> shardManagerActorRef = TestActorRef.create(getSystem(), MockShardManager.props());
515 MockShardManager shardManagerActor = shardManagerActorRef.underlyingActor();
516 shardManagerActor.addFindPrimaryResp("shard1", new RemotePrimaryShardFound(shardActorRef1.path().toString(),
517 DataStoreVersions.CURRENT_VERSION));
518 shardManagerActor.addFindPrimaryResp("shard2", new RemotePrimaryShardFound(shardActorRef2.path().toString(),
519 DataStoreVersions.CURRENT_VERSION));
520 shardManagerActor.addFindPrimaryResp("shard3", new NoShardLeaderException("not found"));
522 Configuration mockConfig = mock(Configuration.class);
523 doReturn(Sets.newLinkedHashSet(Arrays.asList("shard1", "shard2", "shard3"))).
524 when(mockConfig).getAllShardNames();
526 ActorContext actorContext = new ActorContext(getSystem(), shardManagerActorRef,
527 mock(ClusterWrapper.class), mockConfig,
528 DatastoreContext.newBuilder().shardInitializationTimeout(200, TimeUnit.MILLISECONDS).build(), new PrimaryShardInfoFutureCache());
530 actorContext.broadcast(new TestMessage());
532 expectFirstMatching(shardActorRef1, TestMessage.class);
533 expectFirstMatching(shardActorRef2, TestMessage.class);
537 private <T> T expectFirstMatching(ActorRef actor, Class<T> clazz) {
538 int count = 5000 / 50;
539 for(int i = 0; i < count; i++) {
541 T message = (T) MessageCollectorActor.getFirstMatching(actor, clazz);
542 if(message != null) {
545 } catch (Exception e) {}
547 Uninterruptibles.sleepUninterruptibly(50, TimeUnit.MILLISECONDS);
550 Assert.fail("Did not receive message of type " + clazz);