2 * Copyright (c) 2014, 2015 Cisco Systems, Inc. and others. All rights reserved.
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
9 package org.opendaylight.controller.cluster.datastore.utils;
11 import static org.junit.Assert.assertEquals;
12 import static org.junit.Assert.assertFalse;
13 import static org.junit.Assert.assertNotEquals;
14 import static org.junit.Assert.assertNotNull;
15 import static org.junit.Assert.assertNull;
16 import static org.junit.Assert.assertSame;
17 import static org.junit.Assert.assertTrue;
18 import static org.junit.Assert.fail;
19 import static org.mockito.Mockito.doReturn;
20 import static org.mockito.Mockito.mock;
22 import akka.actor.ActorRef;
23 import akka.actor.ActorSelection;
24 import akka.actor.ActorSystem;
25 import akka.actor.Address;
26 import akka.actor.Props;
27 import akka.actor.UntypedAbstractActor;
28 import akka.dispatch.Futures;
29 import akka.japi.Creator;
30 import akka.testkit.TestActorRef;
31 import akka.testkit.javadsl.TestKit;
32 import akka.util.Timeout;
33 import com.google.common.base.Optional;
34 import com.google.common.collect.Maps;
35 import com.google.common.collect.Sets;
36 import com.typesafe.config.ConfigFactory;
37 import java.time.Duration;
38 import java.util.Arrays;
40 import java.util.concurrent.TimeUnit;
41 import org.junit.Assert;
42 import org.junit.Test;
43 import org.mockito.Mockito;
44 import org.opendaylight.controller.cluster.datastore.AbstractActorTest;
45 import org.opendaylight.controller.cluster.datastore.ClusterWrapper;
46 import org.opendaylight.controller.cluster.datastore.DataStoreVersions;
47 import org.opendaylight.controller.cluster.datastore.DatastoreContext;
48 import org.opendaylight.controller.cluster.datastore.DatastoreContextFactory;
49 import org.opendaylight.controller.cluster.datastore.config.Configuration;
50 import org.opendaylight.controller.cluster.datastore.exceptions.NoShardLeaderException;
51 import org.opendaylight.controller.cluster.datastore.exceptions.NotInitializedException;
52 import org.opendaylight.controller.cluster.datastore.exceptions.PrimaryNotFoundException;
53 import org.opendaylight.controller.cluster.datastore.messages.FindLocalShard;
54 import org.opendaylight.controller.cluster.datastore.messages.FindPrimary;
55 import org.opendaylight.controller.cluster.datastore.messages.LocalPrimaryShardFound;
56 import org.opendaylight.controller.cluster.datastore.messages.LocalShardFound;
57 import org.opendaylight.controller.cluster.datastore.messages.LocalShardNotFound;
58 import org.opendaylight.controller.cluster.datastore.messages.PrimaryShardInfo;
59 import org.opendaylight.controller.cluster.datastore.messages.RemotePrimaryShardFound;
60 import org.opendaylight.controller.cluster.raft.utils.EchoActor;
61 import org.opendaylight.controller.cluster.raft.utils.MessageCollectorActor;
62 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
63 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTree;
64 import org.slf4j.Logger;
65 import org.slf4j.LoggerFactory;
66 import scala.concurrent.Await;
67 import scala.concurrent.Future;
68 import scala.concurrent.duration.FiniteDuration;
70 public class ActorUtilsTest extends AbstractActorTest {
72 static final Logger LOG = LoggerFactory.getLogger(ActorUtilsTest.class);
74 private static class TestMessage {
77 private static final class MockShardManager extends UntypedAbstractActor {
79 private final boolean found;
80 private final ActorRef actorRef;
81 private final Map<String,Object> findPrimaryResponses = Maps.newHashMap();
83 private MockShardManager(final boolean found, final ActorRef actorRef) {
86 this.actorRef = actorRef;
89 @Override public void onReceive(final Object message) {
90 if (message instanceof FindPrimary) {
91 FindPrimary fp = (FindPrimary)message;
92 Object resp = findPrimaryResponses.get(fp.getShardName());
94 LOG.error("No expected FindPrimary response found for shard name {}", fp.getShardName());
96 getSender().tell(resp, getSelf());
103 getSender().tell(new LocalShardFound(actorRef), getSelf());
105 getSender().tell(new LocalShardNotFound(((FindLocalShard) message).getShardName()), getSelf());
109 void addFindPrimaryResp(final String shardName, final Object resp) {
110 findPrimaryResponses.put(shardName, resp);
113 private static Props props(final boolean found, final ActorRef actorRef) {
114 return Props.create(new MockShardManagerCreator(found, actorRef));
117 private static Props props() {
118 return Props.create(new MockShardManagerCreator());
121 @SuppressWarnings("serial")
122 private static class MockShardManagerCreator implements Creator<MockShardManager> {
124 final ActorRef actorRef;
126 MockShardManagerCreator() {
128 this.actorRef = null;
131 MockShardManagerCreator(final boolean found, final ActorRef actorRef) {
133 this.actorRef = actorRef;
137 public MockShardManager create() {
138 return new MockShardManager(found, actorRef);
144 public void testFindLocalShardWithShardFound() {
145 final TestKit testKit = new TestKit(getSystem());
146 testKit.within(Duration.ofSeconds(1), () -> {
147 ActorRef shardActorRef = getSystem().actorOf(Props.create(EchoActor.class));
149 ActorRef shardManagerActorRef = getSystem().actorOf(MockShardManager.props(true, shardActorRef));
151 ActorUtils actorUtils = new ActorUtils(getSystem(), shardManagerActorRef,
152 mock(ClusterWrapper.class), mock(Configuration.class));
154 Optional<ActorRef> out = actorUtils.findLocalShard("default");
156 assertEquals(shardActorRef, out.get());
158 testKit.expectNoMessage();
164 public void testFindLocalShardWithShardNotFound() {
165 ActorRef shardManagerActorRef = getSystem().actorOf(MockShardManager.props(false, null));
167 ActorUtils actorUtils = new ActorUtils(getSystem(), shardManagerActorRef, mock(ClusterWrapper.class),
168 mock(Configuration.class));
170 Optional<ActorRef> out = actorUtils.findLocalShard("default");
171 assertFalse(out.isPresent());
175 public void testExecuteRemoteOperation() {
176 ActorRef shardActorRef = getSystem().actorOf(Props.create(EchoActor.class));
178 ActorRef shardManagerActorRef = getSystem().actorOf(MockShardManager.props(true, shardActorRef));
180 ActorUtils actorUtils = new ActorUtils(getSystem(), shardManagerActorRef,
181 mock(ClusterWrapper.class), mock(Configuration.class));
183 ActorSelection actor = actorUtils.actorSelection(shardActorRef.path());
185 Object out = actorUtils.executeOperation(actor, "hello");
187 assertEquals("hello", out);
191 public void testExecuteRemoteOperationAsync() throws Exception {
192 ActorRef shardActorRef = getSystem().actorOf(Props.create(EchoActor.class));
194 ActorRef shardManagerActorRef = getSystem().actorOf(MockShardManager.props(true, shardActorRef));
196 ActorUtils actorUtils = new ActorUtils(getSystem(), shardManagerActorRef,
197 mock(ClusterWrapper.class), mock(Configuration.class));
199 ActorSelection actor = actorUtils.actorSelection(shardActorRef.path());
201 Future<Object> future = actorUtils.executeOperationAsync(actor, "hello");
203 Object result = Await.result(future, FiniteDuration.create(3, TimeUnit.SECONDS));
204 assertEquals("Result", "hello", result);
208 public void testIsPathLocal() {
209 MockClusterWrapper clusterWrapper = new MockClusterWrapper();
210 ActorUtils actorUtils = null;
212 actorUtils = new ActorUtils(getSystem(), null, clusterWrapper, mock(Configuration.class));
213 assertFalse(actorUtils.isPathLocal(null));
214 assertFalse(actorUtils.isPathLocal(""));
216 clusterWrapper.setSelfAddress(null);
217 actorUtils = new ActorUtils(getSystem(), null, clusterWrapper, mock(Configuration.class));
218 assertFalse(actorUtils.isPathLocal(""));
220 // even if the path is in local format, match the primary path (first 3 elements) and return true
221 clusterWrapper.setSelfAddress(new Address("akka", "test"));
222 actorUtils = new ActorUtils(getSystem(), null, clusterWrapper, mock(Configuration.class));
223 assertTrue(actorUtils.isPathLocal("akka://test/user/$a"));
225 clusterWrapper.setSelfAddress(new Address("akka", "test"));
226 actorUtils = new ActorUtils(getSystem(), null, clusterWrapper, mock(Configuration.class));
227 assertTrue(actorUtils.isPathLocal("akka://test/user/$a"));
229 clusterWrapper.setSelfAddress(new Address("akka", "test"));
230 actorUtils = new ActorUtils(getSystem(), null, clusterWrapper, mock(Configuration.class));
231 assertTrue(actorUtils.isPathLocal("akka://test/user/token2/token3/$a"));
233 // self address of remote format,but Tx path local format.
234 clusterWrapper.setSelfAddress(new Address("akka", "system", "127.0.0.1", 2550));
235 actorUtils = new ActorUtils(getSystem(), null, clusterWrapper, mock(Configuration.class));
236 assertTrue(actorUtils.isPathLocal("akka://system/user/shardmanager/shard/transaction"));
238 // self address of local format,but Tx path remote format.
239 clusterWrapper.setSelfAddress(new Address("akka", "system"));
240 actorUtils = new ActorUtils(getSystem(), null, clusterWrapper, mock(Configuration.class));
241 assertFalse(actorUtils.isPathLocal("akka://system@127.0.0.1:2550/user/shardmanager/shard/transaction"));
243 //local path but not same
244 clusterWrapper.setSelfAddress(new Address("akka", "test"));
245 actorUtils = new ActorUtils(getSystem(), null, clusterWrapper, mock(Configuration.class));
246 assertTrue(actorUtils.isPathLocal("akka://test1/user/$a"));
249 clusterWrapper.setSelfAddress(new Address("akka", "system", "127.0.0.1", 2550));
250 actorUtils = new ActorUtils(getSystem(), null, clusterWrapper, mock(Configuration.class));
251 assertTrue(actorUtils.isPathLocal("akka://system@127.0.0.1:2550/"));
253 // forward-slash missing in address
254 clusterWrapper.setSelfAddress(new Address("akka", "system", "127.0.0.1", 2550));
255 actorUtils = new ActorUtils(getSystem(), null, clusterWrapper, mock(Configuration.class));
256 assertFalse(actorUtils.isPathLocal("akka://system@127.0.0.1:2550"));
259 clusterWrapper.setSelfAddress(new Address("akka", "system", "127.0.0.1", 2550));
260 actorUtils = new ActorUtils(getSystem(), null, clusterWrapper, mock(Configuration.class));
261 assertFalse(actorUtils.isPathLocal("akka://system@127.1.0.1:2550/"));
264 clusterWrapper.setSelfAddress(new Address("akka", "system", "127.0.0.1", 2550));
265 actorUtils = new ActorUtils(getSystem(), null, clusterWrapper, mock(Configuration.class));
266 assertFalse(actorUtils.isPathLocal("akka://system@127.0.0.1:2551/"));
270 public void testClientDispatcherIsGlobalDispatcher() {
271 ActorUtils actorUtils = new ActorUtils(getSystem(), mock(ActorRef.class), mock(ClusterWrapper.class),
272 mock(Configuration.class), DatastoreContext.newBuilder().build(), new PrimaryShardInfoFutureCache());
274 assertEquals(getSystem().dispatchers().defaultGlobalDispatcher(), actorUtils.getClientDispatcher());
278 public void testClientDispatcherIsNotGlobalDispatcher() {
279 ActorSystem actorSystem = ActorSystem.create("with-custom-dispatchers",
280 ConfigFactory.load("application-with-custom-dispatchers.conf"));
282 ActorUtils actorUtils = new ActorUtils(actorSystem, mock(ActorRef.class), mock(ClusterWrapper.class),
283 mock(Configuration.class), DatastoreContext.newBuilder().build(), new PrimaryShardInfoFutureCache());
285 assertNotEquals(actorSystem.dispatchers().defaultGlobalDispatcher(), actorUtils.getClientDispatcher());
287 actorSystem.terminate();
291 public void testSetDatastoreContext() {
292 final TestKit testKit = new TestKit(getSystem());
293 ActorUtils actorUtils = new ActorUtils(getSystem(), testKit.getRef(),
294 mock(ClusterWrapper.class), mock(Configuration.class), DatastoreContext.newBuilder()
295 .operationTimeoutInSeconds(5).shardTransactionCommitTimeoutInSeconds(7).build(),
296 new PrimaryShardInfoFutureCache());
298 assertEquals("getOperationDuration", 5, actorUtils.getOperationDuration().toSeconds());
299 assertEquals("getTransactionCommitOperationTimeout", 7,
300 actorUtils.getTransactionCommitOperationTimeout().duration().toSeconds());
302 DatastoreContext newContext = DatastoreContext.newBuilder().operationTimeoutInSeconds(6)
303 .shardTransactionCommitTimeoutInSeconds(8).build();
305 DatastoreContextFactory mockContextFactory = mock(DatastoreContextFactory.class);
306 Mockito.doReturn(newContext).when(mockContextFactory).getBaseDatastoreContext();
308 actorUtils.setDatastoreContext(mockContextFactory);
310 testKit.expectMsgClass(Duration.ofSeconds(5), DatastoreContextFactory.class);
312 Assert.assertSame("getDatastoreContext", newContext, actorUtils.getDatastoreContext());
314 assertEquals("getOperationDuration", 6, actorUtils.getOperationDuration().toSeconds());
315 assertEquals("getTransactionCommitOperationTimeout", 8,
316 actorUtils.getTransactionCommitOperationTimeout().duration().toSeconds());
320 public void testFindPrimaryShardAsyncRemotePrimaryFound() throws Exception {
322 ActorRef shardManager = getSystem().actorOf(MessageCollectorActor.props());
324 DatastoreContext dataStoreContext = DatastoreContext.newBuilder()
325 .logicalStoreType(LogicalDatastoreType.CONFIGURATION)
326 .shardLeaderElectionTimeout(100, TimeUnit.MILLISECONDS).build();
328 final String expPrimaryPath = "akka://test-system/find-primary-shard";
329 final short expPrimaryVersion = DataStoreVersions.CURRENT_VERSION;
330 ActorUtils actorUtils = new ActorUtils(getSystem(), shardManager, mock(ClusterWrapper.class),
331 mock(Configuration.class), dataStoreContext, new PrimaryShardInfoFutureCache()) {
333 protected Future<Object> doAsk(final ActorRef actorRef, final Object message, final Timeout timeout) {
334 return Futures.successful((Object) new RemotePrimaryShardFound(expPrimaryPath, expPrimaryVersion));
338 Future<PrimaryShardInfo> foobar = actorUtils.findPrimaryShardAsync("foobar");
339 PrimaryShardInfo actual = Await.result(foobar, FiniteDuration.apply(5000, TimeUnit.MILLISECONDS));
341 assertNotNull(actual);
342 assertFalse("LocalShardDataTree present", actual.getLocalShardDataTree().isPresent());
343 assertTrue("Unexpected PrimaryShardActor path " + actual.getPrimaryShardActor().path(),
344 expPrimaryPath.endsWith(actual.getPrimaryShardActor().pathString()));
345 assertEquals("getPrimaryShardVersion", expPrimaryVersion, actual.getPrimaryShardVersion());
347 Future<PrimaryShardInfo> cached = actorUtils.getPrimaryShardInfoCache().getIfPresent("foobar");
349 PrimaryShardInfo cachedInfo = Await.result(cached, FiniteDuration.apply(1, TimeUnit.MILLISECONDS));
351 assertEquals(cachedInfo, actual);
353 actorUtils.getPrimaryShardInfoCache().remove("foobar");
355 cached = actorUtils.getPrimaryShardInfoCache().getIfPresent("foobar");
361 public void testFindPrimaryShardAsyncLocalPrimaryFound() throws Exception {
363 ActorRef shardManager = getSystem().actorOf(MessageCollectorActor.props());
365 DatastoreContext dataStoreContext = DatastoreContext.newBuilder()
366 .logicalStoreType(LogicalDatastoreType.CONFIGURATION)
367 .shardLeaderElectionTimeout(100, TimeUnit.MILLISECONDS).build();
369 final DataTree mockDataTree = Mockito.mock(DataTree.class);
370 final String expPrimaryPath = "akka://test-system/find-primary-shard";
371 ActorUtils actorUtils = new ActorUtils(getSystem(), shardManager, mock(ClusterWrapper.class),
372 mock(Configuration.class), dataStoreContext, new PrimaryShardInfoFutureCache()) {
374 protected Future<Object> doAsk(final ActorRef actorRef, final Object message, final Timeout timeout) {
375 return Futures.successful((Object) new LocalPrimaryShardFound(expPrimaryPath, mockDataTree));
379 Future<PrimaryShardInfo> foobar = actorUtils.findPrimaryShardAsync("foobar");
380 PrimaryShardInfo actual = Await.result(foobar, FiniteDuration.apply(5000, TimeUnit.MILLISECONDS));
382 assertNotNull(actual);
383 assertTrue("LocalShardDataTree present", actual.getLocalShardDataTree().isPresent());
384 assertSame("LocalShardDataTree", mockDataTree, actual.getLocalShardDataTree().get());
385 assertTrue("Unexpected PrimaryShardActor path " + actual.getPrimaryShardActor().path(),
386 expPrimaryPath.endsWith(actual.getPrimaryShardActor().pathString()));
387 assertEquals("getPrimaryShardVersion", DataStoreVersions.CURRENT_VERSION, actual.getPrimaryShardVersion());
389 Future<PrimaryShardInfo> cached = actorUtils.getPrimaryShardInfoCache().getIfPresent("foobar");
391 PrimaryShardInfo cachedInfo = Await.result(cached, FiniteDuration.apply(1, TimeUnit.MILLISECONDS));
393 assertEquals(cachedInfo, actual);
395 actorUtils.getPrimaryShardInfoCache().remove("foobar");
397 cached = actorUtils.getPrimaryShardInfoCache().getIfPresent("foobar");
403 public void testFindPrimaryShardAsyncPrimaryNotFound() {
404 testFindPrimaryExceptions(new PrimaryNotFoundException("not found"));
408 public void testFindPrimaryShardAsyncActorNotInitialized() {
409 testFindPrimaryExceptions(new NotInitializedException("not initialized"));
412 @SuppressWarnings("checkstyle:IllegalCatch")
413 private static void testFindPrimaryExceptions(final Object expectedException) {
414 ActorRef shardManager = getSystem().actorOf(MessageCollectorActor.props());
416 DatastoreContext dataStoreContext = DatastoreContext.newBuilder()
417 .logicalStoreType(LogicalDatastoreType.CONFIGURATION)
418 .shardLeaderElectionTimeout(100, TimeUnit.MILLISECONDS).build();
420 ActorUtils actorUtils = new ActorUtils(getSystem(), shardManager, mock(ClusterWrapper.class),
421 mock(Configuration.class), dataStoreContext, new PrimaryShardInfoFutureCache()) {
423 protected Future<Object> doAsk(final ActorRef actorRef, final Object message, final Timeout timeout) {
424 return Futures.successful(expectedException);
428 Future<PrimaryShardInfo> foobar = actorUtils.findPrimaryShardAsync("foobar");
431 Await.result(foobar, FiniteDuration.apply(100, TimeUnit.MILLISECONDS));
432 fail("Expected" + expectedException.getClass().toString());
433 } catch (Exception e) {
434 if (!expectedException.getClass().isInstance(e)) {
435 fail("Expected Exception of type " + expectedException.getClass().toString());
439 Future<PrimaryShardInfo> cached = actorUtils.getPrimaryShardInfoCache().getIfPresent("foobar");
445 public void testBroadcast() {
446 ActorRef shardActorRef1 = getSystem().actorOf(MessageCollectorActor.props());
447 ActorRef shardActorRef2 = getSystem().actorOf(MessageCollectorActor.props());
449 TestActorRef<MockShardManager> shardManagerActorRef = TestActorRef.create(getSystem(),
450 MockShardManager.props());
451 MockShardManager shardManagerActor = shardManagerActorRef.underlyingActor();
452 shardManagerActor.addFindPrimaryResp("shard1", new RemotePrimaryShardFound(
453 shardActorRef1.path().toString(), DataStoreVersions.CURRENT_VERSION));
454 shardManagerActor.addFindPrimaryResp("shard2", new RemotePrimaryShardFound(
455 shardActorRef2.path().toString(), DataStoreVersions.CURRENT_VERSION));
456 shardManagerActor.addFindPrimaryResp("shard3", new NoShardLeaderException("not found"));
458 Configuration mockConfig = mock(Configuration.class);
459 doReturn(Sets.newLinkedHashSet(Arrays.asList("shard1", "shard2", "shard3"))).when(mockConfig)
462 ActorUtils actorUtils = new ActorUtils(getSystem(), shardManagerActorRef,
463 mock(ClusterWrapper.class), mockConfig,
464 DatastoreContext.newBuilder().shardInitializationTimeout(200, TimeUnit.MILLISECONDS).build(),
465 new PrimaryShardInfoFutureCache());
467 actorUtils.broadcast(v -> new TestMessage(), TestMessage.class);
469 MessageCollectorActor.expectFirstMatching(shardActorRef1, TestMessage.class);
470 MessageCollectorActor.expectFirstMatching(shardActorRef2, TestMessage.class);