e5e5bf16486db9960223ccac0a87a3f8d8420999
[controller.git] / opendaylight / md-sal / sal-distributed-datastore / src / test / java / org / opendaylight / controller / cluster / datastore / shardmanager / ShardManagerTest.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.shardmanager;
10
11 import static org.junit.Assert.assertEquals;
12 import static org.junit.Assert.assertNotNull;
13 import static org.junit.Assert.assertNull;
14 import static org.junit.Assert.assertSame;
15 import static org.junit.Assert.assertTrue;
16 import static org.junit.Assert.fail;
17 import static org.mockito.Mockito.mock;
18 import static org.mockito.Mockito.never;
19 import static org.mockito.Mockito.times;
20 import static org.mockito.Mockito.verify;
21 import akka.actor.ActorRef;
22 import akka.actor.ActorSystem;
23 import akka.actor.AddressFromURIString;
24 import akka.actor.Props;
25 import akka.actor.Status;
26 import akka.actor.Status.Failure;
27 import akka.actor.Status.Success;
28 import akka.cluster.Cluster;
29 import akka.cluster.ClusterEvent;
30 import akka.dispatch.Dispatchers;
31 import akka.japi.Creator;
32 import akka.pattern.Patterns;
33 import akka.persistence.RecoveryCompleted;
34 import akka.serialization.Serialization;
35 import akka.testkit.JavaTestKit;
36 import akka.testkit.TestActorRef;
37 import akka.util.Timeout;
38 import com.google.common.base.Function;
39 import com.google.common.base.Optional;
40 import com.google.common.base.Stopwatch;
41 import com.google.common.collect.ImmutableMap;
42 import com.google.common.collect.ImmutableSet;
43 import com.google.common.collect.Lists;
44 import com.google.common.collect.Sets;
45 import com.google.common.util.concurrent.Uninterruptibles;
46 import com.typesafe.config.ConfigFactory;
47 import java.net.URI;
48 import java.util.AbstractMap;
49 import java.util.ArrayList;
50 import java.util.Arrays;
51 import java.util.Collection;
52 import java.util.Collections;
53 import java.util.HashMap;
54 import java.util.List;
55 import java.util.Map;
56 import java.util.Map.Entry;
57 import java.util.Set;
58 import java.util.concurrent.CountDownLatch;
59 import java.util.concurrent.TimeUnit;
60 import java.util.concurrent.TimeoutException;
61 import org.apache.commons.lang3.SerializationUtils;
62 import org.junit.After;
63 import org.junit.Before;
64 import org.junit.Test;
65 import org.mockito.Mock;
66 import org.mockito.Mockito;
67 import org.mockito.MockitoAnnotations;
68 import org.opendaylight.controller.cluster.datastore.AbstractActorTest;
69 import org.opendaylight.controller.cluster.datastore.ClusterWrapperImpl;
70 import org.opendaylight.controller.cluster.datastore.DataStoreVersions;
71 import org.opendaylight.controller.cluster.datastore.DatastoreContext;
72 import org.opendaylight.controller.cluster.datastore.DatastoreContextFactory;
73 import org.opendaylight.controller.cluster.datastore.Shard;
74 import org.opendaylight.controller.cluster.datastore.ShardManager.SchemaContextModules;
75 import org.opendaylight.controller.cluster.datastore.ShardManagerSnapshot;
76 import org.opendaylight.controller.cluster.datastore.config.Configuration;
77 import org.opendaylight.controller.cluster.datastore.config.ConfigurationImpl;
78 import org.opendaylight.controller.cluster.datastore.config.EmptyModuleShardConfigProvider;
79 import org.opendaylight.controller.cluster.datastore.config.ModuleShardConfiguration;
80 import org.opendaylight.controller.cluster.datastore.exceptions.AlreadyExistsException;
81 import org.opendaylight.controller.cluster.datastore.exceptions.NoShardLeaderException;
82 import org.opendaylight.controller.cluster.datastore.exceptions.NotInitializedException;
83 import org.opendaylight.controller.cluster.datastore.exceptions.PrimaryNotFoundException;
84 import org.opendaylight.controller.cluster.datastore.identifiers.ShardIdentifier;
85 import org.opendaylight.controller.cluster.datastore.identifiers.ShardManagerIdentifier;
86 import org.opendaylight.controller.cluster.datastore.messages.ActorInitialized;
87 import org.opendaylight.controller.cluster.datastore.messages.AddShardReplica;
88 import org.opendaylight.controller.cluster.datastore.messages.CreateShard;
89 import org.opendaylight.controller.cluster.datastore.messages.DatastoreSnapshot;
90 import org.opendaylight.controller.cluster.datastore.messages.DatastoreSnapshot.ShardSnapshot;
91 import org.opendaylight.controller.cluster.datastore.messages.FindLocalShard;
92 import org.opendaylight.controller.cluster.datastore.messages.FindPrimary;
93 import org.opendaylight.controller.cluster.datastore.messages.LocalPrimaryShardFound;
94 import org.opendaylight.controller.cluster.datastore.messages.LocalShardFound;
95 import org.opendaylight.controller.cluster.datastore.messages.LocalShardNotFound;
96 import org.opendaylight.controller.cluster.datastore.messages.PeerDown;
97 import org.opendaylight.controller.cluster.datastore.messages.PeerUp;
98 import org.opendaylight.controller.cluster.datastore.messages.PrimaryShardInfo;
99 import org.opendaylight.controller.cluster.datastore.messages.RemotePrimaryShardFound;
100 import org.opendaylight.controller.cluster.datastore.messages.RemoveShardReplica;
101 import org.opendaylight.controller.cluster.datastore.messages.ShardLeaderStateChanged;
102 import org.opendaylight.controller.cluster.datastore.messages.SwitchShardBehavior;
103 import org.opendaylight.controller.cluster.datastore.messages.UpdateSchemaContext;
104 import org.opendaylight.controller.cluster.datastore.utils.ForwardingActor;
105 import org.opendaylight.controller.cluster.datastore.utils.MockClusterWrapper;
106 import org.opendaylight.controller.cluster.datastore.utils.MockConfiguration;
107 import org.opendaylight.controller.cluster.datastore.utils.PrimaryShardInfoFutureCache;
108 import org.opendaylight.controller.cluster.notifications.LeaderStateChanged;
109 import org.opendaylight.controller.cluster.notifications.RegisterRoleChangeListener;
110 import org.opendaylight.controller.cluster.notifications.RoleChangeNotification;
111 import org.opendaylight.controller.cluster.raft.RaftState;
112 import org.opendaylight.controller.cluster.raft.TestActorFactory;
113 import org.opendaylight.controller.cluster.raft.base.messages.FollowerInitialSyncUpStatus;
114 import org.opendaylight.controller.cluster.raft.base.messages.SwitchBehavior;
115 import org.opendaylight.controller.cluster.raft.client.messages.GetSnapshot;
116 import org.opendaylight.controller.cluster.raft.client.messages.Shutdown;
117 import org.opendaylight.controller.cluster.raft.messages.AddServer;
118 import org.opendaylight.controller.cluster.raft.messages.AddServerReply;
119 import org.opendaylight.controller.cluster.raft.messages.RemoveServer;
120 import org.opendaylight.controller.cluster.raft.messages.RemoveServerReply;
121 import org.opendaylight.controller.cluster.raft.messages.ServerChangeStatus;
122 import org.opendaylight.controller.cluster.raft.messages.ServerRemoved;
123 import org.opendaylight.controller.cluster.raft.policy.DisableElectionsRaftPolicy;
124 import org.opendaylight.controller.cluster.raft.utils.InMemoryJournal;
125 import org.opendaylight.controller.cluster.raft.utils.InMemorySnapshotStore;
126 import org.opendaylight.controller.cluster.raft.utils.MessageCollectorActor;
127 import org.opendaylight.controller.md.cluster.datastore.model.TestModel;
128 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTree;
129 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
130 import org.slf4j.Logger;
131 import org.slf4j.LoggerFactory;
132 import scala.concurrent.Await;
133 import scala.concurrent.Future;
134 import scala.concurrent.duration.FiniteDuration;
135
136 public class ShardManagerTest extends AbstractActorTest {
137     private static final Logger LOG = LoggerFactory.getLogger(ShardManagerTest.class);
138
139     private static int ID_COUNTER = 1;
140
141     private final String shardMrgIDSuffix = "config" + ID_COUNTER++;
142     private final String shardMgrID = ShardManagerIdentifier.builder().type(shardMrgIDSuffix).build().toString();
143
144     @Mock
145     private static CountDownLatch ready;
146
147     private static TestActorRef<MessageCollectorActor> mockShardActor;
148
149     private static String mockShardName;
150
151     private final DatastoreContext.Builder datastoreContextBuilder = DatastoreContext.newBuilder().
152             dataStoreName(shardMrgIDSuffix).shardInitializationTimeout(600, TimeUnit.MILLISECONDS)
153                    .shardHeartbeatIntervalInMillis(100).shardElectionTimeoutFactor(6);
154
155     private final Collection<ActorSystem> actorSystems = new ArrayList<>();
156
157     private final TestActorFactory actorFactory = new TestActorFactory(getSystem());
158
159     @Before
160     public void setUp() {
161         MockitoAnnotations.initMocks(this);
162
163         InMemoryJournal.clear();
164         InMemorySnapshotStore.clear();
165
166         if(mockShardActor == null) {
167             mockShardName = new ShardIdentifier(Shard.DEFAULT_NAME, "member-1", "config").toString();
168             mockShardActor = TestActorRef.create(getSystem(), Props.create(MessageCollectorActor.class), mockShardName);
169         }
170
171         mockShardActor.underlyingActor().clear();
172     }
173
174     @After
175     public void tearDown() {
176         InMemoryJournal.clear();
177         InMemorySnapshotStore.clear();
178
179         for(ActorSystem system: actorSystems) {
180             JavaTestKit.shutdownActorSystem(system, null, Boolean.TRUE);
181         }
182
183         actorFactory.close();
184     }
185
186     private ActorSystem newActorSystem(String config) {
187         ActorSystem system = ActorSystem.create("cluster-test", ConfigFactory.load().getConfig(config));
188         actorSystems.add(system);
189         return system;
190     }
191
192     private ActorRef newMockShardActor(ActorSystem system, String shardName, String memberName) {
193         String name = new ShardIdentifier(shardName, memberName,"config").toString();
194         if(system == getSystem()) {
195             return actorFactory.createTestActor(Props.create(MessageCollectorActor.class), name);
196         }
197
198         return TestActorRef.create(system, Props.create(MessageCollectorActor.class), name);
199     }
200
201     private Props newShardMgrProps() {
202         return newShardMgrProps(new MockConfiguration());
203     }
204
205     private static DatastoreContextFactory newDatastoreContextFactory(DatastoreContext datastoreContext) {
206         DatastoreContextFactory mockFactory = mock(DatastoreContextFactory.class);
207         Mockito.doReturn(datastoreContext).when(mockFactory).getBaseDatastoreContext();
208         Mockito.doReturn(datastoreContext).when(mockFactory).getShardDatastoreContext(Mockito.anyString());
209         return mockFactory;
210     }
211
212     private TestShardManager.Builder newTestShardMgrBuilder() {
213         return TestShardManager.builder(datastoreContextBuilder);
214     }
215
216     private TestShardManager.Builder newTestShardMgrBuilder(Configuration config) {
217         return TestShardManager.builder(datastoreContextBuilder).configuration(config);
218     }
219
220     private Props newShardMgrProps(Configuration config) {
221         return newTestShardMgrBuilder(config).props();
222     }
223
224     private TestShardManager.Builder newTestShardMgrBuilderWithMockShardActor() {
225         return newTestShardMgrBuilderWithMockShardActor(mockShardActor);
226     }
227
228     private TestShardManager.Builder newTestShardMgrBuilderWithMockShardActor(ActorRef shardActor) {
229         return TestShardManager.builder(datastoreContextBuilder).shardActor(shardActor);
230     }
231
232
233     private Props newPropsShardMgrWithMockShardActor() {
234         return newTestShardMgrBuilderWithMockShardActor().props();
235     }
236
237     private Props newPropsShardMgrWithMockShardActor(ActorRef shardActor) {
238         return newTestShardMgrBuilderWithMockShardActor(shardActor).props();
239     }
240
241
242     private TestShardManager newTestShardManager() {
243         return newTestShardManager(newShardMgrProps());
244     }
245
246     private TestShardManager newTestShardManager(Props props) {
247         TestActorRef<TestShardManager> shardManagerActor = actorFactory.createTestActor(props);
248         TestShardManager shardManager = shardManagerActor.underlyingActor();
249         shardManager.waitForRecoveryComplete();
250         return shardManager;
251     }
252
253     private static void waitForShardInitialized(ActorRef shardManager, String shardName, JavaTestKit kit) {
254         AssertionError last = null;
255         Stopwatch sw = Stopwatch.createStarted();
256         while(sw.elapsed(TimeUnit.SECONDS) <= 5) {
257             try {
258                 shardManager.tell(new FindLocalShard(shardName, true), kit.getRef());
259                 kit.expectMsgClass(LocalShardFound.class);
260                 return;
261             } catch(AssertionError e) {
262                 last = e;
263             }
264
265             Uninterruptibles.sleepUninterruptibly(50, TimeUnit.MILLISECONDS);
266         }
267
268         throw last;
269     }
270
271     private static <T> T expectMsgClassOrFailure(Class<T> msgClass, JavaTestKit kit, String msg) {
272         Object reply = kit.expectMsgAnyClassOf(JavaTestKit.duration("5 sec"), msgClass, Failure.class);
273         if(reply instanceof Failure) {
274             throw new AssertionError(msg + " failed", ((Failure)reply).cause());
275         }
276
277         return (T)reply;
278     }
279
280     @Test
281     public void testPerShardDatastoreContext() throws Exception {
282         LOG.info("testPerShardDatastoreContext starting");
283         final DatastoreContextFactory mockFactory = newDatastoreContextFactory(
284                 datastoreContextBuilder.shardElectionTimeoutFactor(5).build());
285
286         Mockito.doReturn(DatastoreContext.newBuilderFrom(datastoreContextBuilder.build()).
287                 shardElectionTimeoutFactor(6).build()).when(mockFactory).getShardDatastoreContext("default");
288
289         Mockito.doReturn(DatastoreContext.newBuilderFrom(datastoreContextBuilder.build()).
290                 shardElectionTimeoutFactor(7).build()).when(mockFactory).getShardDatastoreContext("topology");
291
292         final MockConfiguration mockConfig = new MockConfiguration() {
293             @Override
294             public Collection<String> getMemberShardNames(String memberName) {
295                 return Arrays.asList("default", "topology");
296             }
297
298             @Override
299             public Collection<String> getMembersFromShardName(String shardName) {
300                 return Arrays.asList("member-1");
301             }
302         };
303
304         final TestActorRef<MessageCollectorActor> defaultShardActor = actorFactory.createTestActor(
305                 Props.create(MessageCollectorActor.class), actorFactory.generateActorId("default"));
306         final TestActorRef<MessageCollectorActor> topologyShardActor = actorFactory.createTestActor(
307                 Props.create(MessageCollectorActor.class), actorFactory.generateActorId("topology"));
308
309         final Map<String, Entry<ActorRef, DatastoreContext>> shardInfoMap = Collections.synchronizedMap(
310                 new HashMap<String, Entry<ActorRef, DatastoreContext>>());
311         shardInfoMap.put("default", new AbstractMap.SimpleEntry<ActorRef, DatastoreContext>(defaultShardActor, null));
312         shardInfoMap.put("topology", new AbstractMap.SimpleEntry<ActorRef, DatastoreContext>(topologyShardActor, null));
313
314         final PrimaryShardInfoFutureCache primaryShardInfoCache = new PrimaryShardInfoFutureCache();
315         final CountDownLatch newShardActorLatch = new CountDownLatch(2);
316         class LocalShardManager extends ShardManager {
317             public LocalShardManager(AbstractBuilder<?> builder) {
318                 super(builder);
319             }
320
321             @Override
322             protected ActorRef newShardActor(SchemaContext schemaContext, ShardInformation info) {
323                 Entry<ActorRef, DatastoreContext> entry = shardInfoMap.get(info.getShardName());
324                 ActorRef ref = null;
325                 if(entry != null) {
326                     ref = entry.getKey();
327                     entry.setValue(info.getDatastoreContext());
328                 }
329
330                 newShardActorLatch.countDown();
331                 return ref;
332             }
333         }
334
335         final Creator<ShardManager> creator = new Creator<ShardManager>() {
336             private static final long serialVersionUID = 1L;
337             @Override
338             public ShardManager create() throws Exception {
339                 return new LocalShardManager(new GenericBuilder<LocalShardManager>(LocalShardManager.class).
340                         datastoreContextFactory(mockFactory).primaryShardInfoCache(primaryShardInfoCache).
341                         configuration(mockConfig));
342             }
343         };
344
345         JavaTestKit kit = new JavaTestKit(getSystem());
346
347         final ActorRef shardManager = actorFactory.createActor(Props.create(
348                 new DelegatingShardManagerCreator(creator)).withDispatcher(Dispatchers.DefaultDispatcherId()));
349
350         shardManager.tell(new UpdateSchemaContext(TestModel.createTestContext()), kit.getRef());
351
352         assertEquals("Shard actors created", true, newShardActorLatch.await(5, TimeUnit.SECONDS));
353         assertEquals("getShardElectionTimeoutFactor", 6, shardInfoMap.get("default").getValue().
354                 getShardElectionTimeoutFactor());
355         assertEquals("getShardElectionTimeoutFactor", 7, shardInfoMap.get("topology").getValue().
356                 getShardElectionTimeoutFactor());
357
358         DatastoreContextFactory newMockFactory = newDatastoreContextFactory(
359                 datastoreContextBuilder.shardElectionTimeoutFactor(5).build());
360         Mockito.doReturn(DatastoreContext.newBuilderFrom(datastoreContextBuilder.build()).
361                 shardElectionTimeoutFactor(66).build()).when(newMockFactory).getShardDatastoreContext("default");
362
363         Mockito.doReturn(DatastoreContext.newBuilderFrom(datastoreContextBuilder.build()).
364                 shardElectionTimeoutFactor(77).build()).when(newMockFactory).getShardDatastoreContext("topology");
365
366         shardManager.tell(newMockFactory, kit.getRef());
367
368         DatastoreContext newContext = MessageCollectorActor.expectFirstMatching(defaultShardActor, DatastoreContext.class);
369         assertEquals("getShardElectionTimeoutFactor", 66, newContext.getShardElectionTimeoutFactor());
370
371         newContext = MessageCollectorActor.expectFirstMatching(topologyShardActor, DatastoreContext.class);
372         assertEquals("getShardElectionTimeoutFactor", 77, newContext.getShardElectionTimeoutFactor());
373
374         LOG.info("testPerShardDatastoreContext ending");
375     }
376
377     @Test
378     public void testOnReceiveFindPrimaryForNonExistentShard() throws Exception {
379         new JavaTestKit(getSystem()) {{
380             final ActorRef shardManager = actorFactory.createActor(newPropsShardMgrWithMockShardActor());
381
382             shardManager.tell(new UpdateSchemaContext(TestModel.createTestContext()), getRef());
383
384             shardManager.tell(new FindPrimary("non-existent", false), getRef());
385
386             expectMsgClass(duration("5 seconds"), PrimaryNotFoundException.class);
387         }};
388     }
389
390     @Test
391     public void testOnReceiveFindPrimaryForLocalLeaderShard() throws Exception {
392         LOG.info("testOnReceiveFindPrimaryForLocalLeaderShard starting");
393         new JavaTestKit(getSystem()) {{
394             String memberId = "member-1-shard-default-" + shardMrgIDSuffix;
395
396             final ActorRef shardManager = actorFactory.createActor(newPropsShardMgrWithMockShardActor());
397
398             shardManager.tell(new UpdateSchemaContext(TestModel.createTestContext()), getRef());
399             shardManager.tell(new ActorInitialized(), mockShardActor);
400
401             DataTree mockDataTree = mock(DataTree.class);
402             shardManager.tell(new ShardLeaderStateChanged(memberId, memberId, Optional.of(mockDataTree),
403                     DataStoreVersions.CURRENT_VERSION), getRef());
404
405             MessageCollectorActor.expectFirstMatching(mockShardActor, RegisterRoleChangeListener.class);
406             shardManager.tell((new RoleChangeNotification(memberId, RaftState.Candidate.name(),
407                     RaftState.Leader.name())), mockShardActor);
408
409             shardManager.tell(new FindPrimary(Shard.DEFAULT_NAME, false), getRef());
410
411             LocalPrimaryShardFound primaryFound = expectMsgClass(duration("5 seconds"), LocalPrimaryShardFound.class);
412             assertTrue("Unexpected primary path " +  primaryFound.getPrimaryPath(),
413                     primaryFound.getPrimaryPath().contains("member-1-shard-default"));
414             assertSame("getLocalShardDataTree", mockDataTree, primaryFound.getLocalShardDataTree());
415         }};
416
417         LOG.info("testOnReceiveFindPrimaryForLocalLeaderShard ending");
418     }
419
420     @Test
421     public void testOnReceiveFindPrimaryForNonLocalLeaderShardBeforeMemberUp() throws Exception {
422         LOG.info("testOnReceiveFindPrimaryForNonLocalLeaderShardBeforeMemberUp starting");
423         new JavaTestKit(getSystem()) {{
424             final ActorRef shardManager = actorFactory.createActor(newPropsShardMgrWithMockShardActor());
425
426             shardManager.tell(new UpdateSchemaContext(TestModel.createTestContext()), getRef());
427             shardManager.tell(new ActorInitialized(), mockShardActor);
428
429             String memberId2 = "member-2-shard-default-" + shardMrgIDSuffix;
430             String memberId1 = "member-1-shard-default-" + shardMrgIDSuffix;
431             shardManager.tell(new RoleChangeNotification(memberId1,
432                     RaftState.Candidate.name(), RaftState.Follower.name()), mockShardActor);
433             shardManager.tell(new LeaderStateChanged(memberId1, memberId2, DataStoreVersions.CURRENT_VERSION), mockShardActor);
434
435             shardManager.tell(new FindPrimary(Shard.DEFAULT_NAME, false), getRef());
436
437             expectMsgClass(duration("5 seconds"), NoShardLeaderException.class);
438         }};
439
440         LOG.info("testOnReceiveFindPrimaryForNonLocalLeaderShardBeforeMemberUp ending");
441     }
442
443     @Test
444     public void testOnReceiveFindPrimaryForNonLocalLeaderShard() throws Exception {
445         LOG.info("testOnReceiveFindPrimaryForNonLocalLeaderShard starting");
446         new JavaTestKit(getSystem()) {{
447             final ActorRef shardManager = actorFactory.createActor(newPropsShardMgrWithMockShardActor());
448
449             shardManager.tell(new UpdateSchemaContext(TestModel.createTestContext()), getRef());
450             shardManager.tell(new ActorInitialized(), mockShardActor);
451
452             String memberId2 = "member-2-shard-default-" + shardMrgIDSuffix;
453             MockClusterWrapper.sendMemberUp(shardManager, "member-2", getRef().path().toString());
454
455             String memberId1 = "member-1-shard-default-" + shardMrgIDSuffix;
456             shardManager.tell(new RoleChangeNotification(memberId1,
457                     RaftState.Candidate.name(), RaftState.Follower.name()), mockShardActor);
458             short leaderVersion = DataStoreVersions.CURRENT_VERSION - 1;
459             shardManager.tell(new ShardLeaderStateChanged(memberId1, memberId2, Optional.<DataTree>absent(),
460                     leaderVersion), mockShardActor);
461
462             shardManager.tell(new FindPrimary(Shard.DEFAULT_NAME, false), getRef());
463
464             RemotePrimaryShardFound primaryFound = expectMsgClass(duration("5 seconds"), RemotePrimaryShardFound.class);
465             assertTrue("Unexpected primary path " +  primaryFound.getPrimaryPath(),
466                     primaryFound.getPrimaryPath().contains("member-2-shard-default"));
467             assertEquals("getPrimaryVersion", leaderVersion, primaryFound.getPrimaryVersion());
468         }};
469
470         LOG.info("testOnReceiveFindPrimaryForNonLocalLeaderShard ending");
471     }
472
473     @Test
474     public void testOnReceiveFindPrimaryForUninitializedShard() throws Exception {
475         new JavaTestKit(getSystem()) {{
476             final ActorRef shardManager = actorFactory.createActor(newPropsShardMgrWithMockShardActor());
477
478             shardManager.tell(new FindPrimary(Shard.DEFAULT_NAME, false), getRef());
479
480             expectMsgClass(duration("5 seconds"), NotInitializedException.class);
481         }};
482     }
483
484     @Test
485     public void testOnReceiveFindPrimaryForInitializedShardWithNoRole() throws Exception {
486         new JavaTestKit(getSystem()) {{
487             final ActorRef shardManager = actorFactory.createActor(newPropsShardMgrWithMockShardActor());
488
489             shardManager.tell(new UpdateSchemaContext(TestModel.createTestContext()), getRef());
490             shardManager.tell(new ActorInitialized(), mockShardActor);
491
492             shardManager.tell(new FindPrimary(Shard.DEFAULT_NAME, false), getRef());
493
494             expectMsgClass(duration("5 seconds"), NoShardLeaderException.class);
495         }};
496     }
497
498     @Test
499     public void testOnReceiveFindPrimaryForFollowerShardWithNoInitialLeaderId() throws Exception {
500         LOG.info("testOnReceiveFindPrimaryForFollowerShardWithNoInitialLeaderId starting");
501         new JavaTestKit(getSystem()) {{
502             final ActorRef shardManager = actorFactory.createActor(newPropsShardMgrWithMockShardActor());
503
504             shardManager.tell(new UpdateSchemaContext(TestModel.createTestContext()), getRef());
505             shardManager.tell(new ActorInitialized(), mockShardActor);
506
507             String memberId = "member-1-shard-default-" + shardMrgIDSuffix;
508             shardManager.tell(new RoleChangeNotification(memberId,
509                     RaftState.Candidate.name(), RaftState.Follower.name()), mockShardActor);
510
511             shardManager.tell(new FindPrimary(Shard.DEFAULT_NAME, false), getRef());
512
513             expectMsgClass(duration("5 seconds"), NoShardLeaderException.class);
514
515             DataTree mockDataTree = mock(DataTree.class);
516             shardManager.tell(new ShardLeaderStateChanged(memberId, memberId, Optional.of(mockDataTree),
517                     DataStoreVersions.CURRENT_VERSION), mockShardActor);
518
519             shardManager.tell(new FindPrimary(Shard.DEFAULT_NAME, false), getRef());
520
521             LocalPrimaryShardFound primaryFound = expectMsgClass(duration("5 seconds"), LocalPrimaryShardFound.class);
522             assertTrue("Unexpected primary path " +  primaryFound.getPrimaryPath(),
523                     primaryFound.getPrimaryPath().contains("member-1-shard-default"));
524             assertSame("getLocalShardDataTree", mockDataTree, primaryFound.getLocalShardDataTree());
525         }};
526
527         LOG.info("testOnReceiveFindPrimaryForFollowerShardWithNoInitialLeaderId starting");
528     }
529
530     @Test
531     public void testOnReceiveFindPrimaryWaitForShardLeader() throws Exception {
532         LOG.info("testOnReceiveFindPrimaryWaitForShardLeader starting");
533         datastoreContextBuilder.shardInitializationTimeout(10, TimeUnit.SECONDS);
534         new JavaTestKit(getSystem()) {{
535             final ActorRef shardManager = actorFactory.createActor(newPropsShardMgrWithMockShardActor());
536
537             shardManager.tell(new UpdateSchemaContext(TestModel.createTestContext()), getRef());
538
539             // We're passing waitUntilInitialized = true to FindPrimary so the response should be
540             // delayed until we send ActorInitialized and RoleChangeNotification.
541             shardManager.tell(new FindPrimary(Shard.DEFAULT_NAME, true), getRef());
542
543             expectNoMsg(FiniteDuration.create(150, TimeUnit.MILLISECONDS));
544
545             shardManager.tell(new ActorInitialized(), mockShardActor);
546
547             expectNoMsg(FiniteDuration.create(150, TimeUnit.MILLISECONDS));
548
549             String memberId = "member-1-shard-default-" + shardMrgIDSuffix;
550             shardManager.tell(new RoleChangeNotification(memberId,
551                     RaftState.Candidate.name(), RaftState.Leader.name()), mockShardActor);
552
553             expectNoMsg(FiniteDuration.create(150, TimeUnit.MILLISECONDS));
554
555             DataTree mockDataTree = mock(DataTree.class);
556             shardManager.tell(new ShardLeaderStateChanged(memberId, memberId, Optional.of(mockDataTree),
557                     DataStoreVersions.CURRENT_VERSION), mockShardActor);
558
559             LocalPrimaryShardFound primaryFound = expectMsgClass(duration("5 seconds"), LocalPrimaryShardFound.class);
560             assertTrue("Unexpected primary path " +  primaryFound.getPrimaryPath(),
561                     primaryFound.getPrimaryPath().contains("member-1-shard-default"));
562             assertSame("getLocalShardDataTree", mockDataTree, primaryFound.getLocalShardDataTree() );
563
564             expectNoMsg(FiniteDuration.create(200, TimeUnit.MILLISECONDS));
565         }};
566
567         LOG.info("testOnReceiveFindPrimaryWaitForShardLeader ending");
568     }
569
570     @Test
571     public void testOnReceiveFindPrimaryWaitForReadyWithUninitializedShard() throws Exception {
572         LOG.info("testOnReceiveFindPrimaryWaitForReadyWithUninitializedShard starting");
573         new JavaTestKit(getSystem()) {{
574             final ActorRef shardManager = actorFactory.createActor(newPropsShardMgrWithMockShardActor());
575
576             shardManager.tell(new UpdateSchemaContext(TestModel.createTestContext()), getRef());
577
578             shardManager.tell(new FindPrimary(Shard.DEFAULT_NAME, true), getRef());
579
580             expectMsgClass(duration("2 seconds"), NotInitializedException.class);
581
582             shardManager.tell(new ActorInitialized(), mockShardActor);
583
584             expectNoMsg(FiniteDuration.create(200, TimeUnit.MILLISECONDS));
585         }};
586
587         LOG.info("testOnReceiveFindPrimaryWaitForReadyWithUninitializedShard ending");
588     }
589
590     @Test
591     public void testOnReceiveFindPrimaryWaitForReadyWithCandidateShard() throws Exception {
592         LOG.info("testOnReceiveFindPrimaryWaitForReadyWithCandidateShard starting");
593         new JavaTestKit(getSystem()) {{
594             final ActorRef shardManager = actorFactory.createActor(newPropsShardMgrWithMockShardActor());
595
596             shardManager.tell(new UpdateSchemaContext(TestModel.createTestContext()), getRef());
597             shardManager.tell(new ActorInitialized(), mockShardActor);
598             shardManager.tell(new RoleChangeNotification("member-1-shard-default-" + shardMrgIDSuffix,
599                     null, RaftState.Candidate.name()), mockShardActor);
600
601             shardManager.tell(new FindPrimary(Shard.DEFAULT_NAME, true), getRef());
602
603             expectMsgClass(duration("2 seconds"), NoShardLeaderException.class);
604         }};
605
606         LOG.info("testOnReceiveFindPrimaryWaitForReadyWithCandidateShard ending");
607     }
608
609     @Test
610     public void testOnReceiveFindPrimaryWaitForReadyWithIsolatedLeaderShard() throws Exception {
611         LOG.info("testOnReceiveFindPrimaryWaitForReadyWithIsolatedLeaderShard starting");
612         new JavaTestKit(getSystem()) {{
613             final ActorRef shardManager = actorFactory.createActor(newPropsShardMgrWithMockShardActor());
614
615             shardManager.tell(new UpdateSchemaContext(TestModel.createTestContext()), getRef());
616             shardManager.tell(new ActorInitialized(), mockShardActor);
617             shardManager.tell(new RoleChangeNotification("member-1-shard-default-" + shardMrgIDSuffix,
618                     null, RaftState.IsolatedLeader.name()), mockShardActor);
619
620             shardManager.tell(new FindPrimary(Shard.DEFAULT_NAME, true), getRef());
621
622             expectMsgClass(duration("2 seconds"), NoShardLeaderException.class);
623         }};
624
625         LOG.info("testOnReceiveFindPrimaryWaitForReadyWithIsolatedLeaderShard ending");
626     }
627
628     @Test
629     public void testOnReceiveFindPrimaryWaitForReadyWithNoRoleShard() throws Exception {
630         LOG.info("testOnReceiveFindPrimaryWaitForReadyWithNoRoleShard starting");
631         new JavaTestKit(getSystem()) {{
632             final ActorRef shardManager = actorFactory.createActor(newPropsShardMgrWithMockShardActor());
633
634             shardManager.tell(new UpdateSchemaContext(TestModel.createTestContext()), getRef());
635             shardManager.tell(new ActorInitialized(), mockShardActor);
636
637             shardManager.tell(new FindPrimary(Shard.DEFAULT_NAME, true), getRef());
638
639             expectMsgClass(duration("2 seconds"), NoShardLeaderException.class);
640         }};
641
642         LOG.info("testOnReceiveFindPrimaryWaitForReadyWithNoRoleShard ending");
643     }
644
645     @Test
646     public void testOnReceiveFindPrimaryForRemoteShard() throws Exception {
647         LOG.info("testOnReceiveFindPrimaryForRemoteShard starting");
648         String shardManagerID = ShardManagerIdentifier.builder().type(shardMrgIDSuffix).build().toString();
649
650         // Create an ActorSystem ShardManager actor for member-1.
651
652         final ActorSystem system1 = newActorSystem("Member1");
653         Cluster.get(system1).join(AddressFromURIString.parse("akka.tcp://cluster-test@127.0.0.1:2558"));
654
655         final TestActorRef<TestShardManager> shardManager1 = TestActorRef.create(system1,
656                 newTestShardMgrBuilderWithMockShardActor().cluster(
657                         new ClusterWrapperImpl(system1)).props().withDispatcher(
658                                 Dispatchers.DefaultDispatcherId()), shardManagerID);
659
660         // Create an ActorSystem ShardManager actor for member-2.
661
662         final ActorSystem system2 = newActorSystem("Member2");
663
664         Cluster.get(system2).join(AddressFromURIString.parse("akka.tcp://cluster-test@127.0.0.1:2558"));
665
666         final ActorRef mockShardActor2 = newMockShardActor(system2, "astronauts", "member-2");
667
668         MockConfiguration mockConfig2 = new MockConfiguration(ImmutableMap.<String, List<String>>builder().
669                 put("default", Arrays.asList("member-1", "member-2")).
670                 put("astronauts", Arrays.asList("member-2")).build());
671
672         final TestActorRef<TestShardManager> shardManager2 = TestActorRef.create(system2,
673                 newTestShardMgrBuilder(mockConfig2).shardActor(mockShardActor2).cluster(
674                         new ClusterWrapperImpl(system2)).props().withDispatcher(
675                                 Dispatchers.DefaultDispatcherId()), shardManagerID);
676
677         new JavaTestKit(system1) {{
678
679             shardManager1.tell(new UpdateSchemaContext(TestModel.createTestContext()), getRef());
680             shardManager2.tell(new UpdateSchemaContext(TestModel.createTestContext()), getRef());
681
682             shardManager2.tell(new ActorInitialized(), mockShardActor2);
683
684             String memberId2 = "member-2-shard-astronauts-" + shardMrgIDSuffix;
685             short leaderVersion = DataStoreVersions.CURRENT_VERSION - 1;
686             shardManager2.tell(new ShardLeaderStateChanged(memberId2, memberId2,
687                     Optional.of(mock(DataTree.class)), leaderVersion), mockShardActor2);
688             shardManager2.tell(new RoleChangeNotification(memberId2,
689                     RaftState.Candidate.name(), RaftState.Leader.name()), mockShardActor2);
690
691             shardManager1.underlyingActor().waitForMemberUp();
692
693             shardManager1.tell(new FindPrimary("astronauts", false), getRef());
694
695             RemotePrimaryShardFound found = expectMsgClass(duration("5 seconds"), RemotePrimaryShardFound.class);
696             String path = found.getPrimaryPath();
697             assertTrue("Unexpected primary path " + path, path.contains("member-2-shard-astronauts-config"));
698             assertEquals("getPrimaryVersion", leaderVersion, found.getPrimaryVersion());
699
700             shardManager2.underlyingActor().verifyFindPrimary();
701
702             Cluster.get(system2).down(AddressFromURIString.parse("akka.tcp://cluster-test@127.0.0.1:2558"));
703
704             shardManager1.underlyingActor().waitForMemberRemoved();
705
706             shardManager1.tell(new FindPrimary("astronauts", false), getRef());
707
708             expectMsgClass(duration("5 seconds"), PrimaryNotFoundException.class);
709         }};
710
711         LOG.info("testOnReceiveFindPrimaryForRemoteShard ending");
712     }
713
714     @Test
715     public void testShardAvailabilityOnChangeOfMemberReachability() throws Exception {
716         LOG.info("testShardAvailabilityOnChangeOfMemberReachability starting");
717         String shardManagerID = ShardManagerIdentifier.builder().type(shardMrgIDSuffix).build().toString();
718
719         // Create an ActorSystem ShardManager actor for member-1.
720
721         final ActorSystem system1 = newActorSystem("Member1");
722         Cluster.get(system1).join(AddressFromURIString.parse("akka.tcp://cluster-test@127.0.0.1:2558"));
723
724         final ActorRef mockShardActor1 = newMockShardActor(system1, Shard.DEFAULT_NAME, "member-1");
725
726         final TestActorRef<TestShardManager> shardManager1 = TestActorRef.create(system1,
727                 newTestShardMgrBuilder().shardActor(mockShardActor1).cluster(
728                         new ClusterWrapperImpl(system1)).props().withDispatcher(
729                                 Dispatchers.DefaultDispatcherId()), shardManagerID);
730
731         // Create an ActorSystem ShardManager actor for member-2.
732
733         final ActorSystem system2 = newActorSystem("Member2");
734
735         Cluster.get(system2).join(AddressFromURIString.parse("akka.tcp://cluster-test@127.0.0.1:2558"));
736
737         final ActorRef mockShardActor2 = newMockShardActor(system2, Shard.DEFAULT_NAME, "member-2");
738
739         MockConfiguration mockConfig2 = new MockConfiguration(ImmutableMap.<String, List<String>>builder().
740             put("default", Arrays.asList("member-1", "member-2")).build());
741
742         final TestActorRef<TestShardManager> shardManager2 = TestActorRef.create(system2,
743                 newTestShardMgrBuilder(mockConfig2).shardActor(mockShardActor2).cluster(
744                         new ClusterWrapperImpl(system2)).props().withDispatcher(
745                                 Dispatchers.DefaultDispatcherId()), shardManagerID);
746
747         new JavaTestKit(system1) {{
748
749             shardManager1.tell(new UpdateSchemaContext(TestModel.createTestContext()), getRef());
750             shardManager2.tell(new UpdateSchemaContext(TestModel.createTestContext()), getRef());
751             shardManager1.tell(new ActorInitialized(), mockShardActor1);
752             shardManager2.tell(new ActorInitialized(), mockShardActor2);
753
754             String memberId2 = "member-2-shard-default-" + shardMrgIDSuffix;
755             String memberId1 = "member-1-shard-default-" + shardMrgIDSuffix;
756             shardManager1.tell(new ShardLeaderStateChanged(memberId1, memberId2,
757                 Optional.of(mock(DataTree.class)), DataStoreVersions.CURRENT_VERSION), mockShardActor1);
758             shardManager1.tell(new RoleChangeNotification(memberId1,
759                 RaftState.Candidate.name(), RaftState.Follower.name()), mockShardActor1);
760             shardManager2.tell(new ShardLeaderStateChanged(memberId2, memberId2, Optional.of(mock(DataTree.class)),
761                     DataStoreVersions.CURRENT_VERSION),
762                 mockShardActor2);
763             shardManager2.tell(new RoleChangeNotification(memberId2,
764                 RaftState.Candidate.name(), RaftState.Leader.name()), mockShardActor2);
765             shardManager1.underlyingActor().waitForMemberUp();
766
767             shardManager1.tell(new FindPrimary("default", true), getRef());
768
769             RemotePrimaryShardFound found = expectMsgClass(duration("5 seconds"), RemotePrimaryShardFound.class);
770             String path = found.getPrimaryPath();
771             assertTrue("Unexpected primary path " + path, path.contains("member-2-shard-default-config"));
772
773             shardManager1.tell(MockClusterWrapper.
774                 createUnreachableMember("member-2", "akka.tcp://cluster-test@127.0.0.1:2558"), getRef());
775
776             shardManager1.underlyingActor().waitForUnreachableMember();
777
778             PeerDown peerDown = MessageCollectorActor.expectFirstMatching(mockShardActor1, PeerDown.class);
779             assertEquals("getMemberName", "member-2", peerDown.getMemberName());
780             MessageCollectorActor.clearMessages(mockShardActor1);
781
782             shardManager1.tell(MockClusterWrapper.
783                     createMemberRemoved("member-2", "akka.tcp://cluster-test@127.0.0.1:2558"), getRef());
784
785             MessageCollectorActor.expectFirstMatching(mockShardActor1, PeerDown.class);
786
787             shardManager1.tell(new FindPrimary("default", true), getRef());
788
789             expectMsgClass(duration("5 seconds"), NoShardLeaderException.class);
790
791             shardManager1.tell(MockClusterWrapper.
792                 createReachableMember("member-2", "akka.tcp://cluster-test@127.0.0.1:2558"), getRef());
793
794             shardManager1.underlyingActor().waitForReachableMember();
795
796             PeerUp peerUp = MessageCollectorActor.expectFirstMatching(mockShardActor1, PeerUp.class);
797             assertEquals("getMemberName", "member-2", peerUp.getMemberName());
798             MessageCollectorActor.clearMessages(mockShardActor1);
799
800             shardManager1.tell(new FindPrimary("default", true), getRef());
801
802             RemotePrimaryShardFound found1 = expectMsgClass(duration("5 seconds"), RemotePrimaryShardFound.class);
803             String path1 = found1.getPrimaryPath();
804             assertTrue("Unexpected primary path " + path1, path1.contains("member-2-shard-default-config"));
805
806             shardManager1.tell(MockClusterWrapper.
807                     createMemberUp("member-2", "akka.tcp://cluster-test@127.0.0.1:2558"), getRef());
808
809             MessageCollectorActor.expectFirstMatching(mockShardActor1, PeerUp.class);
810
811             // Test FindPrimary wait succeeds after reachable member event.
812
813             shardManager1.tell(MockClusterWrapper.
814                     createUnreachableMember("member-2", "akka.tcp://cluster-test@127.0.0.1:2558"), getRef());
815             shardManager1.underlyingActor().waitForUnreachableMember();
816
817             shardManager1.tell(new FindPrimary("default", true), getRef());
818
819             shardManager1.tell(MockClusterWrapper.
820                     createReachableMember("member-2", "akka.tcp://cluster-test@127.0.0.1:2558"), getRef());
821
822             RemotePrimaryShardFound found2 = expectMsgClass(duration("5 seconds"), RemotePrimaryShardFound.class);
823             String path2 = found2.getPrimaryPath();
824             assertTrue("Unexpected primary path " + path2, path2.contains("member-2-shard-default-config"));
825         }};
826
827         LOG.info("testShardAvailabilityOnChangeOfMemberReachability ending");
828     }
829
830     @Test
831     public void testShardAvailabilityChangeOnMemberUnreachableAndLeadershipChange() throws Exception {
832         LOG.info("testShardAvailabilityChangeOnMemberUnreachableAndLeadershipChange starting");
833         String shardManagerID = ShardManagerIdentifier.builder().type(shardMrgIDSuffix).build().toString();
834
835         // Create an ActorSystem ShardManager actor for member-1.
836
837         final ActorSystem system1 = newActorSystem("Member1");
838         Cluster.get(system1).join(AddressFromURIString.parse("akka.tcp://cluster-test@127.0.0.1:2558"));
839
840         final ActorRef mockShardActor1 = newMockShardActor(system1, Shard.DEFAULT_NAME, "member-1");
841
842         final PrimaryShardInfoFutureCache primaryShardInfoCache = new PrimaryShardInfoFutureCache();
843         final TestActorRef<TestShardManager> shardManager1 = TestActorRef.create(system1,
844                 newTestShardMgrBuilder().shardActor(mockShardActor1).cluster(
845                         new ClusterWrapperImpl(system1)).primaryShardInfoCache(primaryShardInfoCache).props().
846                             withDispatcher(Dispatchers.DefaultDispatcherId()), shardManagerID);
847
848         // Create an ActorSystem ShardManager actor for member-2.
849
850         final ActorSystem system2 = newActorSystem("Member2");
851
852         Cluster.get(system2).join(AddressFromURIString.parse("akka.tcp://cluster-test@127.0.0.1:2558"));
853
854         final ActorRef mockShardActor2 = newMockShardActor(system2, Shard.DEFAULT_NAME, "member-2");
855
856         MockConfiguration mockConfig2 = new MockConfiguration(ImmutableMap.<String, List<String>>builder().
857             put("default", Arrays.asList("member-1", "member-2")).build());
858
859         final TestActorRef<TestShardManager> shardManager2 = TestActorRef.create(system2,
860                 newTestShardMgrBuilder(mockConfig2).shardActor(mockShardActor2).cluster(
861                         new ClusterWrapperImpl(system2)).props().withDispatcher(
862                                 Dispatchers.DefaultDispatcherId()), shardManagerID);
863
864         new JavaTestKit(system1) {{
865             shardManager1.tell(new UpdateSchemaContext(TestModel.createTestContext()), getRef());
866             shardManager2.tell(new UpdateSchemaContext(TestModel.createTestContext()), getRef());
867             shardManager1.tell(new ActorInitialized(), mockShardActor1);
868             shardManager2.tell(new ActorInitialized(), mockShardActor2);
869
870             String memberId2 = "member-2-shard-default-" + shardMrgIDSuffix;
871             String memberId1 = "member-1-shard-default-" + shardMrgIDSuffix;
872             shardManager1.tell(new ShardLeaderStateChanged(memberId1, memberId2,
873                 Optional.of(mock(DataTree.class)), DataStoreVersions.CURRENT_VERSION), mockShardActor1);
874             shardManager1.tell(new RoleChangeNotification(memberId1,
875                 RaftState.Candidate.name(), RaftState.Follower.name()), mockShardActor1);
876             shardManager2.tell(new ShardLeaderStateChanged(memberId2, memberId2, Optional.of(mock(DataTree.class)),
877                     DataStoreVersions.CURRENT_VERSION),
878                 mockShardActor2);
879             shardManager2.tell(new RoleChangeNotification(memberId2,
880                 RaftState.Candidate.name(), RaftState.Leader.name()), mockShardActor2);
881             shardManager1.underlyingActor().waitForMemberUp();
882
883             shardManager1.tell(new FindPrimary("default", true), getRef());
884
885             RemotePrimaryShardFound found = expectMsgClass(duration("5 seconds"), RemotePrimaryShardFound.class);
886             String path = found.getPrimaryPath();
887             assertTrue("Unexpected primary path " + path, path.contains("member-2-shard-default-config"));
888
889             primaryShardInfoCache.putSuccessful("default", new PrimaryShardInfo(system1.actorSelection(
890                     mockShardActor1.path()), DataStoreVersions.CURRENT_VERSION, Optional.<DataTree>absent()));
891
892             shardManager1.tell(MockClusterWrapper.
893                 createUnreachableMember("member-2", "akka.tcp://cluster-test@127.0.0.1:2558"), getRef());
894
895             shardManager1.underlyingActor().waitForUnreachableMember();
896
897             shardManager1.tell(new FindPrimary("default", true), getRef());
898
899             expectMsgClass(duration("5 seconds"), NoShardLeaderException.class);
900
901             assertNull("Expected primaryShardInfoCache entry removed", primaryShardInfoCache.getIfPresent("default"));
902
903             shardManager1.tell(new ShardLeaderStateChanged(memberId1, memberId1, Optional.of(mock(DataTree.class)),
904                     DataStoreVersions.CURRENT_VERSION), mockShardActor1);
905             shardManager1.tell(new RoleChangeNotification(memberId1,
906                 RaftState.Follower.name(), RaftState.Leader.name()), mockShardActor1);
907
908             shardManager1.tell(new FindPrimary("default", true), getRef());
909
910             LocalPrimaryShardFound found1 = expectMsgClass(duration("5 seconds"), LocalPrimaryShardFound.class);
911             String path1 = found1.getPrimaryPath();
912             assertTrue("Unexpected primary path " + path1, path1.contains("member-1-shard-default-config"));
913
914         }};
915
916         LOG.info("testShardAvailabilityChangeOnMemberUnreachableAndLeadershipChange ending");
917     }
918
919
920     @Test
921     public void testOnReceiveFindLocalShardForNonExistentShard() throws Exception {
922         new JavaTestKit(getSystem()) {{
923             final ActorRef shardManager = actorFactory.createActor(newPropsShardMgrWithMockShardActor());
924
925             shardManager.tell(new UpdateSchemaContext(TestModel.createTestContext()), getRef());
926
927             shardManager.tell(new FindLocalShard("non-existent", false), getRef());
928
929             LocalShardNotFound notFound = expectMsgClass(duration("5 seconds"), LocalShardNotFound.class);
930
931             assertEquals("getShardName", "non-existent", notFound.getShardName());
932         }};
933     }
934
935     @Test
936     public void testOnReceiveFindLocalShardForExistentShard() throws Exception {
937         new JavaTestKit(getSystem()) {{
938             final ActorRef shardManager = actorFactory.createActor(newPropsShardMgrWithMockShardActor());
939
940             shardManager.tell(new UpdateSchemaContext(TestModel.createTestContext()), getRef());
941             shardManager.tell(new ActorInitialized(), mockShardActor);
942
943             shardManager.tell(new FindLocalShard(Shard.DEFAULT_NAME, false), getRef());
944
945             LocalShardFound found = expectMsgClass(duration("5 seconds"), LocalShardFound.class);
946
947             assertTrue("Found path contains " + found.getPath().path().toString(),
948                     found.getPath().path().toString().contains("member-1-shard-default-config"));
949         }};
950     }
951
952     @Test
953     public void testOnReceiveFindLocalShardForNotInitializedShard() throws Exception {
954         new JavaTestKit(getSystem()) {{
955             final ActorRef shardManager = actorFactory.createActor(newPropsShardMgrWithMockShardActor());
956
957             shardManager.tell(new FindLocalShard(Shard.DEFAULT_NAME, false), getRef());
958
959             expectMsgClass(duration("5 seconds"), NotInitializedException.class);
960         }};
961     }
962
963     @Test
964     public void testOnReceiveFindLocalShardWaitForShardInitialized() throws Exception {
965         LOG.info("testOnReceiveFindLocalShardWaitForShardInitialized starting");
966         new JavaTestKit(getSystem()) {{
967             final ActorRef shardManager = actorFactory.createActor(newPropsShardMgrWithMockShardActor());
968
969             shardManager.tell(new UpdateSchemaContext(TestModel.createTestContext()), getRef());
970
971             // We're passing waitUntilInitialized = true to FindLocalShard so the response should be
972             // delayed until we send ActorInitialized.
973             Future<Object> future = Patterns.ask(shardManager, new FindLocalShard(Shard.DEFAULT_NAME, true),
974                     new Timeout(5, TimeUnit.SECONDS));
975
976             shardManager.tell(new ActorInitialized(), mockShardActor);
977
978             Object resp = Await.result(future, duration("5 seconds"));
979             assertTrue("Expected: LocalShardFound, Actual: " + resp, resp instanceof LocalShardFound);
980         }};
981
982         LOG.info("testOnReceiveFindLocalShardWaitForShardInitialized starting");
983     }
984
985     @Test
986     public void testOnRecoveryJournalIsCleaned() {
987         String persistenceID = "shard-manager-" + shardMrgIDSuffix;
988         InMemoryJournal.addEntry(persistenceID, 1L, new SchemaContextModules(ImmutableSet.of("foo")));
989         InMemoryJournal.addEntry(persistenceID, 2L, new SchemaContextModules(ImmutableSet.of("bar")));
990         InMemoryJournal.addDeleteMessagesCompleteLatch(persistenceID);
991
992         TestShardManager shardManager = newTestShardManager();
993
994         InMemoryJournal.waitForDeleteMessagesComplete(persistenceID);
995
996         // Journal entries up to the last one should've been deleted
997         Map<Long, Object> journal = InMemoryJournal.get(persistenceID);
998         synchronized (journal) {
999             assertEquals("Journal size", 0, journal.size());
1000         }
1001     }
1002
1003     @Test
1004     public void testRoleChangeNotificationAndShardLeaderStateChangedReleaseReady() throws Exception {
1005         TestShardManager shardManager = newTestShardManager();
1006
1007         String memberId = "member-1-shard-default-" + shardMrgIDSuffix;
1008         shardManager.onReceiveCommand(new RoleChangeNotification(
1009                 memberId, RaftState.Candidate.name(), RaftState.Leader.name()));
1010
1011         verify(ready, never()).countDown();
1012
1013         shardManager.onReceiveCommand(new ShardLeaderStateChanged(memberId, memberId,
1014                 Optional.of(mock(DataTree.class)), DataStoreVersions.CURRENT_VERSION));
1015
1016         verify(ready, times(1)).countDown();
1017     }
1018
1019     @Test
1020     public void testRoleChangeNotificationToFollowerWithShardLeaderStateChangedReleaseReady() throws Exception {
1021         new JavaTestKit(getSystem()) {{
1022             TestShardManager shardManager = newTestShardManager();
1023
1024             String memberId = "member-1-shard-default-" + shardMrgIDSuffix;
1025             shardManager.onReceiveCommand(new RoleChangeNotification(
1026                     memberId, null, RaftState.Follower.name()));
1027
1028             verify(ready, never()).countDown();
1029
1030             shardManager.onReceiveCommand(MockClusterWrapper.createMemberUp("member-2", getRef().path().toString()));
1031
1032             shardManager.onReceiveCommand(new ShardLeaderStateChanged(memberId,
1033                     "member-2-shard-default-" + shardMrgIDSuffix, Optional.of(mock(DataTree.class)),
1034                     DataStoreVersions.CURRENT_VERSION));
1035
1036             verify(ready, times(1)).countDown();
1037         }};
1038     }
1039
1040     @Test
1041     public void testReadyCountDownForMemberUpAfterLeaderStateChanged() throws Exception {
1042         new JavaTestKit(getSystem()) {{
1043             TestShardManager shardManager = newTestShardManager();
1044
1045             String memberId = "member-1-shard-default-" + shardMrgIDSuffix;
1046             shardManager.onReceiveCommand(new RoleChangeNotification(memberId, null, RaftState.Follower.name()));
1047
1048             verify(ready, never()).countDown();
1049
1050             shardManager.onReceiveCommand(new ShardLeaderStateChanged(memberId,
1051                     "member-2-shard-default-" + shardMrgIDSuffix, Optional.of(mock(DataTree.class)),
1052                     DataStoreVersions.CURRENT_VERSION));
1053
1054             shardManager.onReceiveCommand(MockClusterWrapper.createMemberUp("member-2", getRef().path().toString()));
1055
1056             verify(ready, times(1)).countDown();
1057         }};
1058     }
1059
1060     @Test
1061     public void testRoleChangeNotificationDoNothingForUnknownShard() throws Exception {
1062         TestShardManager shardManager = newTestShardManager();
1063
1064         shardManager.onReceiveCommand(new RoleChangeNotification(
1065                 "unknown", RaftState.Candidate.name(), RaftState.Leader.name()));
1066
1067         verify(ready, never()).countDown();
1068     }
1069
1070     @Test
1071     public void testByDefaultSyncStatusIsFalse() throws Exception{
1072         TestShardManager shardManager = newTestShardManager();
1073
1074         assertEquals(false, shardManager.getMBean().getSyncStatus());
1075     }
1076
1077     @Test
1078     public void testWhenShardIsLeaderSyncStatusIsTrue() throws Exception{
1079         TestShardManager shardManager = newTestShardManager();
1080
1081         shardManager.onReceiveCommand(new RoleChangeNotification("member-1-shard-default-" + shardMrgIDSuffix,
1082                 RaftState.Follower.name(), RaftState.Leader.name()));
1083
1084         assertEquals(true, shardManager.getMBean().getSyncStatus());
1085     }
1086
1087     @Test
1088     public void testWhenShardIsCandidateSyncStatusIsFalse() throws Exception{
1089         TestShardManager shardManager = newTestShardManager();
1090
1091         String shardId = "member-1-shard-default-" + shardMrgIDSuffix;
1092         shardManager.onReceiveCommand(new RoleChangeNotification(shardId,
1093                 RaftState.Follower.name(), RaftState.Candidate.name()));
1094
1095         assertEquals(false, shardManager.getMBean().getSyncStatus());
1096
1097         // Send a FollowerInitialSyncStatus with status = true for the replica whose current state is candidate
1098         shardManager.onReceiveCommand(new FollowerInitialSyncUpStatus(
1099                 true, shardId));
1100
1101         assertEquals(false, shardManager.getMBean().getSyncStatus());
1102     }
1103
1104     @Test
1105     public void testWhenShardIsFollowerSyncStatusDependsOnFollowerInitialSyncStatus() throws Exception{
1106         TestShardManager shardManager = newTestShardManager();
1107
1108         String shardId = "member-1-shard-default-" + shardMrgIDSuffix;
1109         shardManager.onReceiveCommand(new RoleChangeNotification(shardId,
1110                 RaftState.Candidate.name(), RaftState.Follower.name()));
1111
1112         // Initially will be false
1113         assertEquals(false, shardManager.getMBean().getSyncStatus());
1114
1115         // Send status true will make sync status true
1116         shardManager.onReceiveCommand(new FollowerInitialSyncUpStatus(true, shardId));
1117
1118         assertEquals(true, shardManager.getMBean().getSyncStatus());
1119
1120         // Send status false will make sync status false
1121         shardManager.onReceiveCommand(new FollowerInitialSyncUpStatus(false, shardId));
1122
1123         assertEquals(false, shardManager.getMBean().getSyncStatus());
1124
1125     }
1126
1127     @Test
1128     public void testWhenMultipleShardsPresentSyncStatusMustBeTrueForAllShards() throws Exception{
1129         LOG.info("testWhenMultipleShardsPresentSyncStatusMustBeTrueForAllShards starting");
1130         TestShardManager shardManager = newTestShardManager(newShardMgrProps(new MockConfiguration() {
1131             @Override
1132             public List<String> getMemberShardNames(String memberName) {
1133                 return Arrays.asList("default", "astronauts");
1134             }
1135         }));
1136
1137         // Initially will be false
1138         assertEquals(false, shardManager.getMBean().getSyncStatus());
1139
1140         // Make default shard leader
1141         String defaultShardId = "member-1-shard-default-" + shardMrgIDSuffix;
1142         shardManager.onReceiveCommand(new RoleChangeNotification(defaultShardId,
1143                 RaftState.Follower.name(), RaftState.Leader.name()));
1144
1145         // default = Leader, astronauts is unknown so sync status remains false
1146         assertEquals(false, shardManager.getMBean().getSyncStatus());
1147
1148         // Make astronauts shard leader as well
1149         String astronautsShardId = "member-1-shard-astronauts-" + shardMrgIDSuffix;
1150         shardManager.onReceiveCommand(new RoleChangeNotification(astronautsShardId,
1151                 RaftState.Follower.name(), RaftState.Leader.name()));
1152
1153         // Now sync status should be true
1154         assertEquals(true, shardManager.getMBean().getSyncStatus());
1155
1156         // Make astronauts a Follower
1157         shardManager.onReceiveCommand(new RoleChangeNotification(astronautsShardId,
1158                 RaftState.Leader.name(), RaftState.Follower.name()));
1159
1160         // Sync status is not true
1161         assertEquals(false, shardManager.getMBean().getSyncStatus());
1162
1163         // Make the astronauts follower sync status true
1164         shardManager.onReceiveCommand(new FollowerInitialSyncUpStatus(true, astronautsShardId));
1165
1166         // Sync status is now true
1167         assertEquals(true, shardManager.getMBean().getSyncStatus());
1168
1169         LOG.info("testWhenMultipleShardsPresentSyncStatusMustBeTrueForAllShards ending");
1170     }
1171
1172     @Test
1173     public void testOnReceiveSwitchShardBehavior() throws Exception {
1174         new JavaTestKit(getSystem()) {{
1175             final ActorRef shardManager = actorFactory.createActor(newPropsShardMgrWithMockShardActor());
1176
1177             shardManager.tell(new UpdateSchemaContext(TestModel.createTestContext()), getRef());
1178             shardManager.tell(new ActorInitialized(), mockShardActor);
1179
1180             shardManager.tell(new SwitchShardBehavior(mockShardName, RaftState.Leader, 1000), getRef());
1181
1182             SwitchBehavior switchBehavior = MessageCollectorActor.expectFirstMatching(mockShardActor, SwitchBehavior.class);
1183
1184             assertEquals(RaftState.Leader, switchBehavior.getNewState());
1185             assertEquals(1000, switchBehavior.getNewTerm());
1186         }};
1187     }
1188
1189     @Test
1190     public void testOnCreateShard() {
1191         LOG.info("testOnCreateShard starting");
1192         new JavaTestKit(getSystem()) {{
1193             datastoreContextBuilder.shardInitializationTimeout(1, TimeUnit.MINUTES).persistent(true);
1194
1195             ActorRef shardManager = actorFactory.createActor(newShardMgrProps(
1196                     new ConfigurationImpl(new EmptyModuleShardConfigProvider())));
1197
1198             SchemaContext schemaContext = TestModel.createTestContext();
1199             shardManager.tell(new UpdateSchemaContext(schemaContext), ActorRef.noSender());
1200
1201             DatastoreContext datastoreContext = DatastoreContext.newBuilder().shardElectionTimeoutFactor(100).
1202                     persistent(false).build();
1203             Shard.Builder shardBuilder = Shard.builder();
1204
1205             ModuleShardConfiguration config = new ModuleShardConfiguration(URI.create("foo-ns"), "foo-module",
1206                     "foo", null, Arrays.asList("member-1", "member-5", "member-6"));
1207             shardManager.tell(new CreateShard(config, shardBuilder, datastoreContext), getRef());
1208
1209             expectMsgClass(duration("5 seconds"), Success.class);
1210
1211             shardManager.tell(new FindLocalShard("foo", true), getRef());
1212
1213             expectMsgClass(duration("5 seconds"), LocalShardFound.class);
1214
1215             assertEquals("isRecoveryApplicable", false, shardBuilder.getDatastoreContext().isPersistent());
1216             assertTrue("Epxected ShardPeerAddressResolver", shardBuilder.getDatastoreContext().getShardRaftConfig().
1217                     getPeerAddressResolver() instanceof ShardPeerAddressResolver);
1218             assertEquals("peerMembers", Sets.newHashSet(new ShardIdentifier("foo", "member-5", shardMrgIDSuffix).toString(),
1219                     new ShardIdentifier("foo", "member-6", shardMrgIDSuffix).toString()),
1220                     shardBuilder.getPeerAddresses().keySet());
1221             assertEquals("ShardIdentifier", new ShardIdentifier("foo", "member-1", shardMrgIDSuffix),
1222                     shardBuilder.getId());
1223             assertSame("schemaContext", schemaContext, shardBuilder.getSchemaContext());
1224
1225             // Send CreateShard with same name - should return Success with a message.
1226
1227             shardManager.tell(new CreateShard(config, shardBuilder, null), getRef());
1228
1229             Success success = expectMsgClass(duration("5 seconds"), Success.class);
1230             assertNotNull("Success status is null", success.status());
1231         }};
1232
1233         LOG.info("testOnCreateShard ending");
1234     }
1235
1236     @Test
1237     public void testOnCreateShardWithLocalMemberNotInShardConfig() {
1238         LOG.info("testOnCreateShardWithLocalMemberNotInShardConfig starting");
1239         new JavaTestKit(getSystem()) {{
1240             datastoreContextBuilder.shardInitializationTimeout(1, TimeUnit.MINUTES).persistent(true);
1241
1242             ActorRef shardManager = actorFactory.createActor(newShardMgrProps(
1243                     new ConfigurationImpl(new EmptyModuleShardConfigProvider())));
1244
1245             shardManager.tell(new UpdateSchemaContext(TestModel.createTestContext()), ActorRef.noSender());
1246
1247             Shard.Builder shardBuilder = Shard.builder();
1248             ModuleShardConfiguration config = new ModuleShardConfiguration(URI.create("foo-ns"), "foo-module",
1249                     "foo", null, Arrays.asList("member-5", "member-6"));
1250
1251             shardManager.tell(new CreateShard(config, shardBuilder, null), getRef());
1252             expectMsgClass(duration("5 seconds"), Success.class);
1253
1254             shardManager.tell(new FindLocalShard("foo", true), getRef());
1255             expectMsgClass(duration("5 seconds"), LocalShardFound.class);
1256
1257             assertEquals("peerMembers size", 0, shardBuilder.getPeerAddresses().size());
1258             assertEquals("schemaContext", DisableElectionsRaftPolicy.class.getName(),
1259                     shardBuilder.getDatastoreContext().getShardRaftConfig().getCustomRaftPolicyImplementationClass());
1260         }};
1261
1262         LOG.info("testOnCreateShardWithLocalMemberNotInShardConfig ending");
1263     }
1264
1265     @Test
1266     public void testOnCreateShardWithNoInitialSchemaContext() {
1267         LOG.info("testOnCreateShardWithNoInitialSchemaContext starting");
1268         new JavaTestKit(getSystem()) {{
1269             ActorRef shardManager = actorFactory.createActor(newShardMgrProps(
1270                     new ConfigurationImpl(new EmptyModuleShardConfigProvider())));
1271
1272             Shard.Builder shardBuilder = Shard.builder();
1273
1274             ModuleShardConfiguration config = new ModuleShardConfiguration(URI.create("foo-ns"), "foo-module",
1275                     "foo", null, Arrays.asList("member-1"));
1276             shardManager.tell(new CreateShard(config, shardBuilder, null), getRef());
1277
1278             expectMsgClass(duration("5 seconds"), Success.class);
1279
1280             SchemaContext schemaContext = TestModel.createTestContext();
1281             shardManager.tell(new UpdateSchemaContext(schemaContext), ActorRef.noSender());
1282
1283             shardManager.tell(new FindLocalShard("foo", true), getRef());
1284
1285             expectMsgClass(duration("5 seconds"), LocalShardFound.class);
1286
1287             assertSame("schemaContext", schemaContext, shardBuilder.getSchemaContext());
1288             assertNotNull("schemaContext is null", shardBuilder.getDatastoreContext());
1289         }};
1290
1291         LOG.info("testOnCreateShardWithNoInitialSchemaContext ending");
1292     }
1293
1294     @Test
1295     public void testGetSnapshot() throws Throwable {
1296         LOG.info("testGetSnapshot starting");
1297         JavaTestKit kit = new JavaTestKit(getSystem());
1298
1299         MockConfiguration mockConfig = new MockConfiguration(ImmutableMap.<String, List<String>>builder().
1300                    put("shard1", Arrays.asList("member-1")).
1301                    put("shard2", Arrays.asList("member-1")).
1302                    put("astronauts", Collections.<String>emptyList()).build());
1303
1304         TestActorRef<TestShardManager> shardManager = actorFactory.createTestActor(newShardMgrProps(mockConfig).
1305                 withDispatcher(Dispatchers.DefaultDispatcherId()));
1306
1307         shardManager.tell(GetSnapshot.INSTANCE, kit.getRef());
1308         Failure failure = kit.expectMsgClass(Failure.class);
1309         assertEquals("Failure cause type", IllegalStateException.class, failure.cause().getClass());
1310
1311         shardManager.tell(new UpdateSchemaContext(TestModel.createTestContext()), ActorRef.noSender());
1312
1313         waitForShardInitialized(shardManager, "shard1", kit);
1314         waitForShardInitialized(shardManager, "shard2", kit);
1315
1316         shardManager.tell(GetSnapshot.INSTANCE, kit.getRef());
1317
1318         DatastoreSnapshot datastoreSnapshot = expectMsgClassOrFailure(DatastoreSnapshot.class, kit, "GetSnapshot");
1319
1320         assertEquals("getType", shardMrgIDSuffix, datastoreSnapshot.getType());
1321         assertNull("Expected null ShardManagerSnapshot", datastoreSnapshot.getShardManagerSnapshot());
1322
1323         Function<ShardSnapshot, String> shardNameTransformer = new Function<ShardSnapshot, String>() {
1324             @Override
1325             public String apply(ShardSnapshot s) {
1326                 return s.getName();
1327             }
1328         };
1329
1330         assertEquals("Shard names", Sets.newHashSet("shard1", "shard2"), Sets.newHashSet(
1331                 Lists.transform(datastoreSnapshot.getShardSnapshots(), shardNameTransformer)));
1332
1333         // Add a new replica
1334
1335         JavaTestKit mockShardLeaderKit = new JavaTestKit(getSystem());
1336
1337         TestShardManager shardManagerInstance = shardManager.underlyingActor();
1338         shardManagerInstance.setMessageInterceptor(newFindPrimaryInterceptor(mockShardLeaderKit.getRef()));
1339
1340         shardManager.tell(new AddShardReplica("astronauts"), kit.getRef());
1341         mockShardLeaderKit.expectMsgClass(AddServer.class);
1342         mockShardLeaderKit.reply(new AddServerReply(ServerChangeStatus.OK, ""));
1343         kit.expectMsgClass(Status.Success.class);
1344         waitForShardInitialized(shardManager, "astronauts", kit);
1345
1346         // Send another GetSnapshot and verify
1347
1348         shardManager.tell(GetSnapshot.INSTANCE, kit.getRef());
1349         datastoreSnapshot = expectMsgClassOrFailure(DatastoreSnapshot.class, kit, "GetSnapshot");
1350
1351         assertEquals("Shard names", Sets.newHashSet("shard1", "shard2", "astronauts"), Sets.newHashSet(
1352                 Lists.transform(datastoreSnapshot.getShardSnapshots(), shardNameTransformer)));
1353
1354         byte[] snapshotBytes = datastoreSnapshot.getShardManagerSnapshot();
1355         assertNotNull("Expected ShardManagerSnapshot", snapshotBytes);
1356         ShardManagerSnapshot snapshot = SerializationUtils.deserialize(snapshotBytes);
1357         assertEquals("Shard names", Sets.newHashSet("shard1", "shard2", "astronauts"),
1358                 Sets.newHashSet(snapshot.getShardList()));
1359
1360         LOG.info("testGetSnapshot ending");
1361     }
1362
1363     @Test
1364     public void testRestoreFromSnapshot() throws Throwable {
1365         LOG.info("testRestoreFromSnapshot starting");
1366
1367         datastoreContextBuilder.shardInitializationTimeout(3, TimeUnit.SECONDS);
1368
1369         JavaTestKit kit = new JavaTestKit(getSystem());
1370
1371         MockConfiguration mockConfig = new MockConfiguration(ImmutableMap.<String, List<String>>builder().
1372                    put("shard1", Collections.<String>emptyList()).
1373                    put("shard2", Collections.<String>emptyList()).
1374                    put("astronauts", Collections.<String>emptyList()).build());
1375
1376
1377         ShardManagerSnapshot snapshot = new ShardManagerSnapshot(Arrays.asList("shard1", "shard2", "astronauts"));
1378         DatastoreSnapshot restoreFromSnapshot = new DatastoreSnapshot(shardMrgIDSuffix,
1379                 SerializationUtils.serialize(snapshot), Collections.<ShardSnapshot>emptyList());
1380         TestActorRef<TestShardManager> shardManager = actorFactory.createTestActor(newTestShardMgrBuilder(mockConfig).
1381                 restoreFromSnapshot(restoreFromSnapshot).props().withDispatcher(Dispatchers.DefaultDispatcherId()));
1382
1383         shardManager.underlyingActor().waitForRecoveryComplete();
1384
1385         shardManager.tell(new UpdateSchemaContext(TestModel.createTestContext()), ActorRef.noSender());
1386
1387         waitForShardInitialized(shardManager, "shard1", kit);
1388         waitForShardInitialized(shardManager, "shard2", kit);
1389         waitForShardInitialized(shardManager, "astronauts", kit);
1390
1391         shardManager.tell(GetSnapshot.INSTANCE, kit.getRef());
1392
1393         DatastoreSnapshot datastoreSnapshot = expectMsgClassOrFailure(DatastoreSnapshot.class, kit, "GetSnapshot");
1394
1395         assertEquals("getType", shardMrgIDSuffix, datastoreSnapshot.getType());
1396
1397         byte[] snapshotBytes = datastoreSnapshot.getShardManagerSnapshot();
1398         assertNotNull("Expected ShardManagerSnapshot", snapshotBytes);
1399         snapshot = SerializationUtils.deserialize(snapshotBytes);
1400         assertEquals("Shard names", Sets.newHashSet("shard1", "shard2", "astronauts"),
1401                 Sets.newHashSet(snapshot.getShardList()));
1402
1403         LOG.info("testRestoreFromSnapshot ending");
1404     }
1405
1406     @Test
1407     public void testAddShardReplicaForNonExistentShardConfig() throws Exception {
1408         new JavaTestKit(getSystem()) {{
1409             ActorRef shardManager = actorFactory.createActor(newShardMgrProps(
1410                     new ConfigurationImpl(new EmptyModuleShardConfigProvider())));
1411
1412             shardManager.tell(new AddShardReplica("model-inventory"), getRef());
1413             Status.Failure resp = expectMsgClass(duration("2 seconds"), Status.Failure.class);
1414
1415             assertEquals("Failure obtained", true,
1416                           (resp.cause() instanceof IllegalArgumentException));
1417         }};
1418     }
1419
1420     @Test
1421     public void testAddShardReplica() throws Exception {
1422         LOG.info("testAddShardReplica starting");
1423         MockConfiguration mockConfig =
1424                 new MockConfiguration(ImmutableMap.<String, List<String>>builder().
1425                    put("default", Arrays.asList("member-1", "member-2")).
1426                    put("astronauts", Arrays.asList("member-2")).build());
1427
1428         final String shardManagerID = ShardManagerIdentifier.builder().type(shardMrgIDSuffix).build().toString();
1429         datastoreContextBuilder.shardManagerPersistenceId(shardManagerID);
1430
1431         // Create an ActorSystem ShardManager actor for member-1.
1432         final ActorSystem system1 = newActorSystem("Member1");
1433         Cluster.get(system1).join(AddressFromURIString.parse("akka.tcp://cluster-test@127.0.0.1:2558"));
1434         ActorRef mockDefaultShardActor = newMockShardActor(system1, Shard.DEFAULT_NAME, "member-1");
1435         final TestActorRef<TestShardManager> newReplicaShardManager = TestActorRef.create(system1,
1436                 newTestShardMgrBuilder(mockConfig).shardActor(mockDefaultShardActor).cluster(
1437                         new ClusterWrapperImpl(system1)).props().withDispatcher(Dispatchers.DefaultDispatcherId()), shardManagerID);
1438
1439         // Create an ActorSystem ShardManager actor for member-2.
1440         final ActorSystem system2 = newActorSystem("Member2");
1441         Cluster.get(system2).join(AddressFromURIString.parse("akka.tcp://cluster-test@127.0.0.1:2558"));
1442
1443         String name = new ShardIdentifier("astronauts", "member-2", "config").toString();
1444         final TestActorRef<MockRespondActor> mockShardLeaderActor =
1445                 TestActorRef.create(system2, Props.create(MockRespondActor.class).
1446                         withDispatcher(Dispatchers.DefaultDispatcherId()), name);
1447         final TestActorRef<TestShardManager> leaderShardManager = TestActorRef.create(system2,
1448                 newTestShardMgrBuilder(mockConfig).shardActor(mockShardLeaderActor).cluster(
1449                         new ClusterWrapperImpl(system2)).props().
1450                             withDispatcher(Dispatchers.DefaultDispatcherId()), shardManagerID);
1451
1452         new JavaTestKit(system1) {{
1453
1454             newReplicaShardManager.tell(new UpdateSchemaContext(TestModel.createTestContext()), getRef());
1455             leaderShardManager.tell(new UpdateSchemaContext(TestModel.createTestContext()), getRef());
1456
1457             leaderShardManager.tell(new ActorInitialized(), mockShardLeaderActor);
1458
1459             String memberId2 = "member-2-shard-astronauts-" + shardMrgIDSuffix;
1460             short leaderVersion = DataStoreVersions.CURRENT_VERSION - 1;
1461             leaderShardManager.tell(new ShardLeaderStateChanged(memberId2, memberId2,
1462                     Optional.of(mock(DataTree.class)), leaderVersion), mockShardLeaderActor);
1463             leaderShardManager.tell(new RoleChangeNotification(memberId2,
1464                     RaftState.Candidate.name(), RaftState.Leader.name()), mockShardLeaderActor);
1465
1466             newReplicaShardManager.underlyingActor().waitForMemberUp();
1467             leaderShardManager.underlyingActor().waitForMemberUp();
1468
1469             //Have a dummy snapshot to be overwritten by the new data persisted.
1470             String[] restoredShards = {"default", "people"};
1471             ShardManagerSnapshot snapshot = new ShardManagerSnapshot(Arrays.asList(restoredShards));
1472             InMemorySnapshotStore.addSnapshot(shardManagerID, snapshot);
1473             Uninterruptibles.sleepUninterruptibly(2, TimeUnit.MILLISECONDS);
1474
1475             InMemorySnapshotStore.addSnapshotSavedLatch(shardManagerID);
1476             InMemorySnapshotStore.addSnapshotDeletedLatch(shardManagerID);
1477
1478             //construct a mock response message
1479             AddServerReply response = new AddServerReply(ServerChangeStatus.OK, memberId2);
1480             mockShardLeaderActor.underlyingActor().updateResponse(response);
1481             newReplicaShardManager.tell(new AddShardReplica("astronauts"), getRef());
1482             AddServer addServerMsg = MessageCollectorActor.expectFirstMatching(mockShardLeaderActor,
1483                 AddServer.class);
1484             String addServerId = "member-1-shard-astronauts-" + shardMrgIDSuffix;
1485             assertEquals("AddServer serverId", addServerId, addServerMsg.getNewServerId());
1486             expectMsgClass(duration("5 seconds"), Status.Success.class);
1487
1488             InMemorySnapshotStore.waitForSavedSnapshot(shardManagerID, ShardManagerSnapshot.class);
1489             InMemorySnapshotStore.waitForDeletedSnapshot(shardManagerID);
1490             List<ShardManagerSnapshot> persistedSnapshots =
1491                 InMemorySnapshotStore.getSnapshots(shardManagerID, ShardManagerSnapshot.class);
1492             assertEquals("Number of snapshots persisted", 1, persistedSnapshots.size());
1493             ShardManagerSnapshot shardManagerSnapshot = persistedSnapshots.get(0);
1494             assertEquals("Persisted local shards", Sets.newHashSet("default", "astronauts"),
1495                     Sets.newHashSet(shardManagerSnapshot.getShardList()));
1496         }};
1497         LOG.info("testAddShardReplica ending");
1498     }
1499
1500     @Test
1501     public void testAddShardReplicaWithPreExistingReplicaInRemoteShardLeader() throws Exception {
1502         LOG.info("testAddShardReplicaWithPreExistingReplicaInRemoteShardLeader starting");
1503         new JavaTestKit(getSystem()) {{
1504             TestActorRef<TestShardManager> shardManager = actorFactory.createTestActor(
1505                     newPropsShardMgrWithMockShardActor(), shardMgrID);
1506
1507             shardManager.tell(new UpdateSchemaContext(TestModel.createTestContext()), getRef());
1508             shardManager.tell(new ActorInitialized(), mockShardActor);
1509
1510             String leaderId = "leader-member-shard-default-" + shardMrgIDSuffix;
1511             AddServerReply addServerReply = new AddServerReply(ServerChangeStatus.ALREADY_EXISTS, null);
1512             ActorRef leaderShardActor = shardManager.underlyingActor().getContext().actorOf(
1513                     Props.create(MockRespondActor.class, addServerReply), leaderId);
1514
1515             MockClusterWrapper.sendMemberUp(shardManager, "leader-member", leaderShardActor.path().toString());
1516
1517             String newReplicaId = "member-1-shard-default-" + shardMrgIDSuffix;
1518             shardManager.tell(new RoleChangeNotification(newReplicaId,
1519                     RaftState.Candidate.name(), RaftState.Follower.name()), mockShardActor);
1520             shardManager.tell(new ShardLeaderStateChanged(newReplicaId, leaderId, Optional.<DataTree>absent(),
1521                     DataStoreVersions.CURRENT_VERSION), mockShardActor);
1522
1523             shardManager.tell(new AddShardReplica(Shard.DEFAULT_NAME), getRef());
1524
1525             MessageCollectorActor.expectFirstMatching(leaderShardActor, AddServer.class);
1526
1527             Failure resp = expectMsgClass(duration("5 seconds"), Failure.class);
1528             assertEquals("Failure cause", AlreadyExistsException.class, resp.cause().getClass());
1529
1530             shardManager.tell(new FindLocalShard(Shard.DEFAULT_NAME, false), getRef());
1531             expectMsgClass(duration("5 seconds"), LocalShardFound.class);
1532
1533             // Send message again to verify previous in progress state is cleared
1534
1535             shardManager.tell(new AddShardReplica(Shard.DEFAULT_NAME), getRef());
1536             resp = expectMsgClass(duration("5 seconds"), Failure.class);
1537             assertEquals("Failure cause", AlreadyExistsException.class, resp.cause().getClass());
1538
1539             // Send message again with an AddServer timeout to verify the pre-existing shard actor isn't terminated.
1540
1541             shardManager.tell(newDatastoreContextFactory(datastoreContextBuilder.
1542                     shardLeaderElectionTimeout(100, TimeUnit.MILLISECONDS).build()), getRef());
1543             leaderShardActor.tell(MockRespondActor.CLEAR_RESPONSE, ActorRef.noSender());
1544             shardManager.tell(new AddShardReplica(Shard.DEFAULT_NAME), getRef());
1545             expectMsgClass(duration("5 seconds"), Failure.class);
1546
1547             shardManager.tell(new FindLocalShard(Shard.DEFAULT_NAME, false), getRef());
1548             expectMsgClass(duration("5 seconds"), LocalShardFound.class);
1549         }};
1550
1551         LOG.info("testAddShardReplicaWithPreExistingReplicaInRemoteShardLeader ending");
1552     }
1553
1554     @Test
1555     public void testAddShardReplicaWithPreExistingLocalReplicaLeader() throws Exception {
1556         LOG.info("testAddShardReplicaWithPreExistingLocalReplicaLeader starting");
1557         new JavaTestKit(getSystem()) {{
1558             String memberId = "member-1-shard-default-" + shardMrgIDSuffix;
1559             ActorRef shardManager = actorFactory.createActor(newPropsShardMgrWithMockShardActor());
1560
1561             shardManager.tell(new UpdateSchemaContext(TestModel.createTestContext()), getRef());
1562             shardManager.tell(new ActorInitialized(), mockShardActor);
1563             shardManager.tell(new ShardLeaderStateChanged(memberId, memberId, Optional.of(mock(DataTree.class)),
1564                     DataStoreVersions.CURRENT_VERSION), getRef());
1565             shardManager.tell((new RoleChangeNotification(memberId, RaftState.Candidate.name(),
1566                     RaftState.Leader.name())), mockShardActor);
1567
1568             shardManager.tell(new AddShardReplica(Shard.DEFAULT_NAME), getRef());
1569             Failure resp = expectMsgClass(duration("5 seconds"), Failure.class);
1570             assertEquals("Failure cause", AlreadyExistsException.class, resp.cause().getClass());
1571
1572             shardManager.tell(new FindLocalShard(Shard.DEFAULT_NAME, false), getRef());
1573             expectMsgClass(duration("5 seconds"), LocalShardFound.class);
1574         }};
1575
1576         LOG.info("testAddShardReplicaWithPreExistingLocalReplicaLeader ending");
1577     }
1578
1579     @Test
1580     public void testAddShardReplicaWithAddServerReplyFailure() throws Exception {
1581         LOG.info("testAddShardReplicaWithAddServerReplyFailure starting");
1582         new JavaTestKit(getSystem()) {{
1583             JavaTestKit mockShardLeaderKit = new JavaTestKit(getSystem());
1584
1585             MockConfiguration mockConfig =
1586                     new MockConfiguration(ImmutableMap.<String, List<String>>builder().
1587                        put("astronauts", Arrays.asList("member-2")).build());
1588
1589             ActorRef mockNewReplicaShardActor = newMockShardActor(getSystem(), "astronauts", "member-1");
1590             final TestActorRef<TestShardManager> shardManager = actorFactory.createTestActor(
1591                     newTestShardMgrBuilder(mockConfig).shardActor(mockNewReplicaShardActor).props(), shardMgrID);
1592             shardManager.underlyingActor().setMessageInterceptor(newFindPrimaryInterceptor(mockShardLeaderKit.getRef()));
1593
1594             shardManager.tell(new UpdateSchemaContext(TestModel.createTestContext()), getRef());
1595
1596             JavaTestKit terminateWatcher = new JavaTestKit(getSystem());
1597             terminateWatcher.watch(mockNewReplicaShardActor);
1598
1599             shardManager.tell(new AddShardReplica("astronauts"), getRef());
1600
1601             AddServer addServerMsg = mockShardLeaderKit.expectMsgClass(AddServer.class);
1602             assertEquals("AddServer serverId", "member-1-shard-astronauts-" + shardMrgIDSuffix,
1603                     addServerMsg.getNewServerId());
1604             mockShardLeaderKit.reply(new AddServerReply(ServerChangeStatus.TIMEOUT, null));
1605
1606             Failure failure = expectMsgClass(duration("5 seconds"), Failure.class);
1607             assertEquals("Failure cause", TimeoutException.class, failure.cause().getClass());
1608
1609             shardManager.tell(new FindLocalShard("astronauts", false), getRef());
1610             expectMsgClass(duration("5 seconds"), LocalShardNotFound.class);
1611
1612             terminateWatcher.expectTerminated(mockNewReplicaShardActor);
1613
1614             shardManager.tell(new AddShardReplica("astronauts"), getRef());
1615             mockShardLeaderKit.expectMsgClass(AddServer.class);
1616             mockShardLeaderKit.reply(new AddServerReply(ServerChangeStatus.NO_LEADER, null));
1617             failure = expectMsgClass(duration("5 seconds"), Failure.class);
1618             assertEquals("Failure cause", NoShardLeaderException.class, failure.cause().getClass());
1619         }};
1620
1621         LOG.info("testAddShardReplicaWithAddServerReplyFailure ending");
1622     }
1623
1624     @Test
1625     public void testAddShardReplicaWithAlreadyInProgress() throws Exception {
1626         testServerChangeWhenAlreadyInProgress("astronauts", new AddShardReplica("astronauts"),
1627                 AddServer.class, new AddShardReplica("astronauts"));
1628     }
1629
1630     @Test
1631     public void testAddShardReplicaWithFindPrimaryTimeout() throws Exception {
1632         LOG.info("testAddShardReplicaWithFindPrimaryTimeout starting");
1633         datastoreContextBuilder.shardInitializationTimeout(100, TimeUnit.MILLISECONDS);
1634         new JavaTestKit(getSystem()) {{
1635             MockConfiguration mockConfig = new MockConfiguration(ImmutableMap.<String, List<String>>builder().
1636                        put("astronauts", Arrays.asList("member-2")).build());
1637
1638             final ActorRef newReplicaShardManager = actorFactory.createActor(newTestShardMgrBuilder(mockConfig).
1639                     shardActor(mockShardActor).props(), shardMgrID);
1640
1641             newReplicaShardManager.tell(new UpdateSchemaContext(TestModel.createTestContext()), getRef());
1642             MockClusterWrapper.sendMemberUp(newReplicaShardManager, "member-2",
1643                     AddressFromURIString.parse("akka.tcp://non-existent@127.0.0.1:5").toString());
1644
1645             newReplicaShardManager.tell(new AddShardReplica("astronauts"), getRef());
1646             Status.Failure resp = expectMsgClass(duration("5 seconds"), Status.Failure.class);
1647             assertEquals("Failure obtained", true,
1648                           (resp.cause() instanceof RuntimeException));
1649         }};
1650
1651         LOG.info("testAddShardReplicaWithFindPrimaryTimeout ending");
1652     }
1653
1654     @Test
1655     public void testRemoveShardReplicaForNonExistentShard() throws Exception {
1656         new JavaTestKit(getSystem()) {{
1657             ActorRef shardManager = actorFactory.createActor(newShardMgrProps(
1658                     new ConfigurationImpl(new EmptyModuleShardConfigProvider())));
1659
1660             shardManager.tell(new RemoveShardReplica("model-inventory", "member-1"), getRef());
1661             Status.Failure resp = expectMsgClass(duration("10 seconds"), Status.Failure.class);
1662             assertEquals("Failure obtained", true,
1663                          (resp.cause() instanceof PrimaryNotFoundException));
1664         }};
1665     }
1666
1667     @Test
1668     /**
1669      * Primary is Local
1670      */
1671     public void testRemoveShardReplicaLocal() throws Exception {
1672         new JavaTestKit(getSystem()) {{
1673             String memberId = "member-1-shard-default-" + shardMrgIDSuffix;
1674
1675             final TestActorRef<MockRespondActor> respondActor =
1676                     TestActorRef.create(getSystem(), Props.create(MockRespondActor.class), memberId);
1677
1678             ActorRef shardManager = getSystem().actorOf(newPropsShardMgrWithMockShardActor(respondActor));
1679
1680             shardManager.tell(new UpdateSchemaContext(TestModel.createTestContext()), getRef());
1681             shardManager.tell(new ActorInitialized(), respondActor);
1682             shardManager.tell(new ShardLeaderStateChanged(memberId, memberId, Optional.of(mock(DataTree.class)),
1683                     DataStoreVersions.CURRENT_VERSION), getRef());
1684             shardManager.tell((new RoleChangeNotification(memberId, RaftState.Candidate.name(),
1685                     RaftState.Leader.name())), respondActor);
1686
1687             respondActor.underlyingActor().updateResponse(new RemoveServerReply(ServerChangeStatus.OK, null));
1688             shardManager.tell(new RemoveShardReplica(Shard.DEFAULT_NAME, "member-1"), getRef());
1689             final RemoveServer removeServer = MessageCollectorActor.expectFirstMatching(respondActor, RemoveServer.class);
1690             assertEquals(new ShardIdentifier("default", "member-1", shardMrgIDSuffix).toString(),
1691                     removeServer.getServerId());
1692             expectMsgClass(duration("5 seconds"), Success.class);
1693         }};
1694     }
1695
1696     @Test
1697     public void testRemoveShardReplicaRemote() throws Exception {
1698         MockConfiguration mockConfig =
1699                 new MockConfiguration(ImmutableMap.<String, List<String>>builder().
1700                         put("default", Arrays.asList("member-1", "member-2")).
1701                         put("astronauts", Arrays.asList("member-1")).build());
1702
1703         String shardManagerID = ShardManagerIdentifier.builder().type(shardMrgIDSuffix).build().toString();
1704
1705         // Create an ActorSystem ShardManager actor for member-1.
1706         final ActorSystem system1 = newActorSystem("Member1");
1707         Cluster.get(system1).join(AddressFromURIString.parse("akka.tcp://cluster-test@127.0.0.1:2558"));
1708         ActorRef mockDefaultShardActor = newMockShardActor(system1, Shard.DEFAULT_NAME, "member-1");
1709
1710         final TestActorRef<TestShardManager> newReplicaShardManager = TestActorRef.create(system1,
1711                 newTestShardMgrBuilder().configuration(mockConfig).shardActor(mockDefaultShardActor).cluster(
1712                         new ClusterWrapperImpl(system1)).props().withDispatcher(Dispatchers.DefaultDispatcherId()),
1713                 shardManagerID);
1714
1715         // Create an ActorSystem ShardManager actor for member-2.
1716         final ActorSystem system2 = newActorSystem("Member2");
1717         Cluster.get(system2).join(AddressFromURIString.parse("akka.tcp://cluster-test@127.0.0.1:2558"));
1718
1719         String name = new ShardIdentifier("default", "member-2", shardMrgIDSuffix).toString();
1720         final TestActorRef<MockRespondActor> mockShardLeaderActor =
1721                 TestActorRef.create(system2, Props.create(MockRespondActor.class), name);
1722
1723         LOG.error("Mock Shard Leader Actor : {}", mockShardLeaderActor);
1724
1725         final TestActorRef<TestShardManager> leaderShardManager = TestActorRef.create(system2,
1726                 newTestShardMgrBuilder().configuration(mockConfig).shardActor(mockShardLeaderActor).cluster(
1727                         new ClusterWrapperImpl(system2)).props().withDispatcher(Dispatchers.DefaultDispatcherId()),
1728                 shardManagerID);
1729
1730         // Because mockShardLeaderActor is created at the top level of the actor system it has an address like so,
1731         //    akka.tcp://cluster-test@127.0.0.1:2559/user/member-2-shard-default-config1
1732         // However when a shard manager has a local shard which is a follower and a leader that is remote it will
1733         // try to compute an address for the remote shard leader using the ShardPeerAddressResolver. This address will
1734         // look like so,
1735         //    akka.tcp://cluster-test@127.0.0.1:2559/user/shardmanager-config1/member-2-shard-default-config1
1736         // In this specific case if we did a FindPrimary for shard default from member-1 we would come up
1737         // with the address of an actor which does not exist, therefore any message sent to that actor would go to
1738         // dead letters.
1739         // To work around this problem we create a ForwardingActor with the right address and pass to it the
1740         // mockShardLeaderActor. The ForwardingActor simply forwards all messages to the mockShardLeaderActor and every
1741         // thing works as expected
1742         final ActorRef actorRef = leaderShardManager.underlyingActor().context()
1743                 .actorOf(Props.create(ForwardingActor.class, mockShardLeaderActor), "member-2-shard-default-" + shardMrgIDSuffix);
1744
1745         LOG.error("Forwarding actor : {}", actorRef);
1746
1747         new JavaTestKit(system1) {{
1748
1749             newReplicaShardManager.tell(new UpdateSchemaContext(TestModel.createTestContext()), getRef());
1750             leaderShardManager.tell(new UpdateSchemaContext(TestModel.createTestContext()), getRef());
1751
1752             leaderShardManager.tell(new ActorInitialized(), mockShardLeaderActor);
1753             newReplicaShardManager.tell(new ActorInitialized(), mockShardLeaderActor);
1754
1755             String memberId2 = "member-2-shard-default-" + shardMrgIDSuffix;
1756             short leaderVersion = DataStoreVersions.CURRENT_VERSION - 1;
1757             leaderShardManager.tell(new ShardLeaderStateChanged(memberId2, memberId2,
1758                     Optional.of(mock(DataTree.class)), leaderVersion), mockShardLeaderActor);
1759             leaderShardManager.tell(new RoleChangeNotification(memberId2,
1760                     RaftState.Candidate.name(), RaftState.Leader.name()), mockShardLeaderActor);
1761
1762             String memberId1 = "member-1-shard-default-" + shardMrgIDSuffix;
1763             newReplicaShardManager.tell(new ShardLeaderStateChanged(memberId1, memberId2,
1764                     Optional.of(mock(DataTree.class)), leaderVersion), mockShardActor);
1765             newReplicaShardManager.tell(new RoleChangeNotification(memberId1,
1766                     RaftState.Candidate.name(), RaftState.Follower.name()), mockShardActor);
1767
1768             newReplicaShardManager.underlyingActor().waitForMemberUp();
1769             leaderShardManager.underlyingActor().waitForMemberUp();
1770
1771             //construct a mock response message
1772             RemoveServerReply response = new RemoveServerReply(ServerChangeStatus.OK, memberId2);
1773             mockShardLeaderActor.underlyingActor().updateResponse(response);
1774             newReplicaShardManager.tell(new RemoveShardReplica("default", "member-1"), getRef());
1775             RemoveServer removeServer = MessageCollectorActor.expectFirstMatching(mockShardLeaderActor,
1776                     RemoveServer.class);
1777             String removeServerId = new ShardIdentifier("default", "member-1", shardMrgIDSuffix).toString();
1778             assertEquals("RemoveServer serverId", removeServerId, removeServer.getServerId());
1779             expectMsgClass(duration("5 seconds"), Status.Success.class);
1780         }};
1781
1782     }
1783
1784     @Test
1785     public void testRemoveShardReplicaWhenAnotherRemoveShardReplicaAlreadyInProgress() throws Exception {
1786         testServerChangeWhenAlreadyInProgress("astronauts", new RemoveShardReplica("astronauts", "member-2"),
1787                 RemoveServer.class, new RemoveShardReplica("astronauts", "member-3"));
1788     }
1789
1790     @Test
1791     public void testRemoveShardReplicaWhenAddShardReplicaAlreadyInProgress() throws Exception {
1792         testServerChangeWhenAlreadyInProgress("astronauts", new AddShardReplica("astronauts"),
1793                 AddServer.class, new RemoveShardReplica("astronauts", "member-2"));
1794     }
1795
1796
1797     public void testServerChangeWhenAlreadyInProgress(final String shardName, final Object firstServerChange,
1798                                                       final Class<?> firstForwardedServerChangeClass,
1799                                                       final Object secondServerChange) throws Exception {
1800         new JavaTestKit(getSystem()) {{
1801             JavaTestKit mockShardLeaderKit = new JavaTestKit(getSystem());
1802             JavaTestKit secondRequestKit = new JavaTestKit(getSystem());
1803
1804             MockConfiguration mockConfig =
1805                     new MockConfiguration(ImmutableMap.<String, List<String>>builder().
1806                             put(shardName, Arrays.asList("member-2")).build());
1807
1808             final TestActorRef<TestShardManager> shardManager = TestActorRef.create(getSystem(),
1809                     newTestShardMgrBuilder().configuration(mockConfig).shardActor(mockShardActor).cluster(
1810                             new MockClusterWrapper()).props().withDispatcher(Dispatchers.DefaultDispatcherId()),
1811                     shardMgrID);
1812
1813             shardManager.underlyingActor().setMessageInterceptor(newFindPrimaryInterceptor(mockShardLeaderKit.getRef()));
1814
1815             shardManager.tell(new UpdateSchemaContext(TestModel.createTestContext()), getRef());
1816
1817             shardManager.tell(firstServerChange, getRef());
1818
1819             mockShardLeaderKit.expectMsgClass(firstForwardedServerChangeClass);
1820
1821             shardManager.tell(secondServerChange, secondRequestKit.getRef());
1822
1823             secondRequestKit.expectMsgClass(duration("5 seconds"), Failure.class);
1824         }};
1825     }
1826
1827     @Test
1828     public void testServerRemovedShardActorNotRunning() throws Exception {
1829         LOG.info("testServerRemovedShardActorNotRunning starting");
1830         new JavaTestKit(getSystem()) {{
1831             MockConfiguration mockConfig =
1832                     new MockConfiguration(ImmutableMap.<String, List<String>>builder().
1833                             put("default", Arrays.asList("member-1", "member-2")).
1834                             put("astronauts", Arrays.asList("member-2")).
1835                             put("people", Arrays.asList("member-1", "member-2")).build());
1836
1837             TestActorRef<TestShardManager> shardManager = actorFactory.createTestActor(newShardMgrProps(mockConfig));
1838
1839             shardManager.underlyingActor().waitForRecoveryComplete();
1840             shardManager.tell(new FindLocalShard("people", false), getRef());
1841             expectMsgClass(duration("5 seconds"), NotInitializedException.class);
1842
1843             shardManager.tell(new FindLocalShard("default", false), getRef());
1844             expectMsgClass(duration("5 seconds"), NotInitializedException.class);
1845
1846             // Removed the default shard replica from member-1
1847             ShardIdentifier.Builder builder = new ShardIdentifier.Builder();
1848             ShardIdentifier shardId = builder.shardName("default").memberName("member-1").type(shardMrgIDSuffix).build();
1849             shardManager.tell(new ServerRemoved(shardId.toString()), getRef());
1850
1851             shardManager.underlyingActor().verifySnapshotPersisted(Sets.newHashSet("people"));
1852         }};
1853
1854         LOG.info("testServerRemovedShardActorNotRunning ending");
1855     }
1856
1857     @Test
1858     public void testServerRemovedShardActorRunning() throws Exception {
1859         LOG.info("testServerRemovedShardActorRunning starting");
1860         new JavaTestKit(getSystem()) {{
1861             MockConfiguration mockConfig =
1862                     new MockConfiguration(ImmutableMap.<String, List<String>>builder().
1863                             put("default", Arrays.asList("member-1", "member-2")).
1864                             put("astronauts", Arrays.asList("member-2")).
1865                             put("people", Arrays.asList("member-1", "member-2")).build());
1866
1867             String shardId = ShardIdentifier.builder().shardName("default").memberName("member-1").
1868                     type(shardMrgIDSuffix).build().toString();
1869             TestActorRef<MessageCollectorActor> shard = actorFactory.createTestActor(
1870                     MessageCollectorActor.props(), shardId);
1871
1872             TestActorRef<TestShardManager> shardManager = actorFactory.createTestActor(
1873                     newTestShardMgrBuilder(mockConfig).addShardActor("default", shard).props());
1874
1875             shardManager.underlyingActor().waitForRecoveryComplete();
1876
1877             shardManager.tell(new UpdateSchemaContext(TestModel.createTestContext()), getRef());
1878             shardManager.tell(new ActorInitialized(), shard);
1879
1880             waitForShardInitialized(shardManager, "people", this);
1881             waitForShardInitialized(shardManager, "default", this);
1882
1883             // Removed the default shard replica from member-1
1884             shardManager.tell(new ServerRemoved(shardId), getRef());
1885
1886             shardManager.underlyingActor().verifySnapshotPersisted(Sets.newHashSet("people"));
1887
1888             MessageCollectorActor.expectFirstMatching(shard, Shutdown.class);
1889         }};
1890
1891         LOG.info("testServerRemovedShardActorRunning ending");
1892     }
1893
1894
1895     @Test
1896     public void testShardPersistenceWithRestoredData() throws Exception {
1897         LOG.info("testShardPersistenceWithRestoredData starting");
1898         new JavaTestKit(getSystem()) {{
1899             MockConfiguration mockConfig =
1900                 new MockConfiguration(ImmutableMap.<String, List<String>>builder().
1901                    put("default", Arrays.asList("member-1", "member-2")).
1902                    put("astronauts", Arrays.asList("member-2")).
1903                    put("people", Arrays.asList("member-1", "member-2")).build());
1904             String[] restoredShards = {"default", "astronauts"};
1905             ShardManagerSnapshot snapshot = new ShardManagerSnapshot(Arrays.asList(restoredShards));
1906             InMemorySnapshotStore.addSnapshot("shard-manager-" + shardMrgIDSuffix, snapshot);
1907
1908             //create shardManager to come up with restored data
1909             TestActorRef<TestShardManager> newRestoredShardManager = actorFactory.createTestActor(
1910                     newShardMgrProps(mockConfig));
1911
1912             newRestoredShardManager.underlyingActor().waitForRecoveryComplete();
1913
1914             newRestoredShardManager.tell(new FindLocalShard("people", false), getRef());
1915             LocalShardNotFound notFound = expectMsgClass(duration("5 seconds"), LocalShardNotFound.class);
1916             assertEquals("for uninitialized shard", "people", notFound.getShardName());
1917
1918             //Verify a local shard is created for the restored shards,
1919             //although we expect a NotInitializedException for the shards as the actor initialization
1920             //message is not sent for them
1921             newRestoredShardManager.tell(new FindLocalShard("default", false), getRef());
1922             expectMsgClass(duration("5 seconds"), NotInitializedException.class);
1923
1924             newRestoredShardManager.tell(new FindLocalShard("astronauts", false), getRef());
1925             expectMsgClass(duration("5 seconds"), NotInitializedException.class);
1926         }};
1927
1928         LOG.info("testShardPersistenceWithRestoredData ending");
1929     }
1930
1931     @Test
1932     public void testShutDown() throws Exception {
1933         LOG.info("testShutDown starting");
1934         new JavaTestKit(getSystem()) {{
1935             MockConfiguration mockConfig =
1936                     new MockConfiguration(ImmutableMap.<String, List<String>>builder().
1937                             put("shard1", Arrays.asList("member-1")).
1938                             put("shard2", Arrays.asList("member-1")).build());
1939
1940             String shardId1 = ShardIdentifier.builder().shardName("shard1").memberName("member-1").
1941                     type(shardMrgIDSuffix).build().toString();
1942             TestActorRef<MessageCollectorActor> shard1 = actorFactory.createTestActor(
1943                     MessageCollectorActor.props().withDispatcher(Dispatchers.DefaultDispatcherId()), shardId1);
1944
1945             String shardId2 = ShardIdentifier.builder().shardName("shard2").memberName("member-1").
1946                     type(shardMrgIDSuffix).build().toString();
1947             TestActorRef<MessageCollectorActor> shard2 = actorFactory.createTestActor(
1948                     MessageCollectorActor.props().withDispatcher(Dispatchers.DefaultDispatcherId()), shardId2);
1949
1950             TestActorRef<TestShardManager> shardManager = actorFactory.createTestActor(newTestShardMgrBuilder(
1951                     mockConfig).addShardActor("shard1", shard1).addShardActor("shard2", shard2).props().
1952                         withDispatcher(Dispatchers.DefaultDispatcherId()));
1953
1954             shardManager.tell(new UpdateSchemaContext(TestModel.createTestContext()), getRef());
1955             shardManager.tell(new ActorInitialized(), shard1);
1956             shardManager.tell(new ActorInitialized(), shard2);
1957
1958             FiniteDuration duration = FiniteDuration.create(5, TimeUnit.SECONDS);
1959             Future<Boolean> stopFuture = Patterns.gracefulStop(shardManager, duration, Shutdown.INSTANCE);
1960
1961             MessageCollectorActor.expectFirstMatching(shard1, Shutdown.class);
1962             MessageCollectorActor.expectFirstMatching(shard2, Shutdown.class);
1963
1964             try {
1965                 Await.ready(stopFuture, FiniteDuration.create(500, TimeUnit.MILLISECONDS));
1966                 fail("ShardManager actor stopped without waiting for the Shards to be stopped");
1967             } catch(TimeoutException e) {
1968                 // expected
1969             }
1970
1971             actorFactory.killActor(shard1, this);
1972             actorFactory.killActor(shard2, this);
1973
1974             Boolean stopped = Await.result(stopFuture, duration);
1975             assertEquals("Stopped", Boolean.TRUE, stopped);
1976         }};
1977
1978         LOG.info("testShutDown ending");
1979     }
1980
1981     private static class TestShardManager extends ShardManager {
1982         private final CountDownLatch recoveryComplete = new CountDownLatch(1);
1983         private final CountDownLatch snapshotPersist = new CountDownLatch(1);
1984         private ShardManagerSnapshot snapshot;
1985         private final Map<String, ActorRef> shardActors;
1986         private final ActorRef shardActor;
1987         private CountDownLatch findPrimaryMessageReceived = new CountDownLatch(1);
1988         private CountDownLatch memberUpReceived = new CountDownLatch(1);
1989         private CountDownLatch memberRemovedReceived = new CountDownLatch(1);
1990         private CountDownLatch memberUnreachableReceived = new CountDownLatch(1);
1991         private CountDownLatch memberReachableReceived = new CountDownLatch(1);
1992         private volatile MessageInterceptor messageInterceptor;
1993
1994         private TestShardManager(Builder builder) {
1995             super(builder);
1996             shardActor = builder.shardActor;
1997             shardActors = builder.shardActors;
1998         }
1999
2000         @Override
2001         protected void handleRecover(Object message) throws Exception {
2002             try {
2003                 super.handleRecover(message);
2004             } finally {
2005                 if(message instanceof RecoveryCompleted) {
2006                     recoveryComplete.countDown();
2007                 }
2008             }
2009         }
2010
2011         @Override
2012         public void handleCommand(Object message) throws Exception {
2013             try{
2014                 if(messageInterceptor != null && messageInterceptor.canIntercept(message)) {
2015                     getSender().tell(messageInterceptor.apply(message), getSelf());
2016                 } else {
2017                     super.handleCommand(message);
2018                 }
2019             } finally {
2020                 if(message instanceof FindPrimary) {
2021                     findPrimaryMessageReceived.countDown();
2022                 } else if(message instanceof ClusterEvent.MemberUp) {
2023                     String role = ((ClusterEvent.MemberUp)message).member().roles().iterator().next();
2024                     if(!getCluster().getCurrentMemberName().equals(role)) {
2025                         memberUpReceived.countDown();
2026                     }
2027                 } else if(message instanceof ClusterEvent.MemberRemoved) {
2028                     String role = ((ClusterEvent.MemberRemoved)message).member().roles().iterator().next();
2029                     if(!getCluster().getCurrentMemberName().equals(role)) {
2030                         memberRemovedReceived.countDown();
2031                     }
2032                 } else if(message instanceof ClusterEvent.UnreachableMember) {
2033                     String role = ((ClusterEvent.UnreachableMember)message).member().roles().iterator().next();
2034                     if(!getCluster().getCurrentMemberName().equals(role)) {
2035                         memberUnreachableReceived.countDown();
2036                     }
2037                 } else if(message instanceof ClusterEvent.ReachableMember) {
2038                     String role = ((ClusterEvent.ReachableMember)message).member().roles().iterator().next();
2039                     if(!getCluster().getCurrentMemberName().equals(role)) {
2040                         memberReachableReceived.countDown();
2041                     }
2042                 }
2043             }
2044         }
2045
2046         void setMessageInterceptor(MessageInterceptor messageInterceptor) {
2047             this.messageInterceptor = messageInterceptor;
2048         }
2049
2050         void waitForRecoveryComplete() {
2051             assertEquals("Recovery complete", true,
2052                     Uninterruptibles.awaitUninterruptibly(recoveryComplete, 5, TimeUnit.SECONDS));
2053         }
2054
2055         void waitForMemberUp() {
2056             assertEquals("MemberUp received", true,
2057                     Uninterruptibles.awaitUninterruptibly(memberUpReceived, 5, TimeUnit.SECONDS));
2058             memberUpReceived = new CountDownLatch(1);
2059         }
2060
2061         void waitForMemberRemoved() {
2062             assertEquals("MemberRemoved received", true,
2063                     Uninterruptibles.awaitUninterruptibly(memberRemovedReceived, 5, TimeUnit.SECONDS));
2064             memberRemovedReceived = new CountDownLatch(1);
2065         }
2066
2067         void waitForUnreachableMember() {
2068             assertEquals("UnreachableMember received", true,
2069                 Uninterruptibles.awaitUninterruptibly(memberUnreachableReceived, 5, TimeUnit.SECONDS
2070                 ));
2071             memberUnreachableReceived = new CountDownLatch(1);
2072         }
2073
2074         void waitForReachableMember() {
2075             assertEquals("ReachableMember received", true,
2076                 Uninterruptibles.awaitUninterruptibly(memberReachableReceived, 5, TimeUnit.SECONDS));
2077             memberReachableReceived = new CountDownLatch(1);
2078         }
2079
2080         void verifyFindPrimary() {
2081             assertEquals("FindPrimary received", true,
2082                     Uninterruptibles.awaitUninterruptibly(findPrimaryMessageReceived, 5, TimeUnit.SECONDS));
2083             findPrimaryMessageReceived = new CountDownLatch(1);
2084         }
2085
2086         public static Builder builder(DatastoreContext.Builder datastoreContextBuilder) {
2087             return new Builder(datastoreContextBuilder);
2088         }
2089
2090         private static class Builder extends AbstractGenericBuilder<Builder, TestShardManager> {
2091             private ActorRef shardActor;
2092             private final Map<String, ActorRef> shardActors = new HashMap<>();
2093
2094             Builder(DatastoreContext.Builder datastoreContextBuilder) {
2095                 super(TestShardManager.class);
2096                 datastoreContextFactory(newDatastoreContextFactory(datastoreContextBuilder.build()));
2097             }
2098
2099             Builder shardActor(ActorRef shardActor) {
2100                 this.shardActor = shardActor;
2101                 return this;
2102             }
2103
2104             Builder addShardActor(String shardName, ActorRef actorRef){
2105                 shardActors.put(shardName, actorRef);
2106                 return this;
2107             }
2108         }
2109
2110         @Override
2111         public void saveSnapshot(Object obj) {
2112             snapshot = (ShardManagerSnapshot) obj;
2113             snapshotPersist.countDown();
2114             super.saveSnapshot(obj);
2115         }
2116
2117         void verifySnapshotPersisted(Set<String> shardList) {
2118             assertEquals("saveSnapshot invoked", true,
2119                     Uninterruptibles.awaitUninterruptibly(snapshotPersist, 5, TimeUnit.SECONDS));
2120             assertEquals("Shard Persisted", shardList, Sets.newHashSet(snapshot.getShardList()));
2121         }
2122
2123         @Override
2124         protected ActorRef newShardActor(SchemaContext schemaContext, ShardInformation info) {
2125             if(shardActors.get(info.getShardName()) != null){
2126                 return shardActors.get(info.getShardName());
2127             }
2128
2129             if(shardActor != null) {
2130                 return shardActor;
2131             }
2132
2133             return super.newShardActor(schemaContext, info);
2134         }
2135     }
2136
2137     private static abstract class AbstractGenericBuilder<T extends AbstractGenericBuilder<T, ?>, C extends ShardManager>
2138                                                      extends ShardManager.AbstractBuilder<T> {
2139         private final Class<C> shardManagerClass;
2140
2141         AbstractGenericBuilder(Class<C> shardManagerClass) {
2142             this.shardManagerClass = shardManagerClass;
2143             cluster(new MockClusterWrapper()).configuration(new MockConfiguration()).
2144                     waitTillReadyCountdownLatch(ready).primaryShardInfoCache(new PrimaryShardInfoFutureCache());
2145         }
2146
2147         @Override
2148         public Props props() {
2149             verify();
2150             return Props.create(shardManagerClass, this);
2151         }
2152     }
2153
2154     private static class GenericBuilder<C extends ShardManager> extends AbstractGenericBuilder<GenericBuilder<C>, C> {
2155         GenericBuilder(Class<C> shardManagerClass) {
2156             super(shardManagerClass);
2157         }
2158     }
2159
2160     private static class DelegatingShardManagerCreator implements Creator<ShardManager> {
2161         private static final long serialVersionUID = 1L;
2162         private final Creator<ShardManager> delegate;
2163
2164         public DelegatingShardManagerCreator(Creator<ShardManager> delegate) {
2165             this.delegate = delegate;
2166         }
2167
2168         @Override
2169         public ShardManager create() throws Exception {
2170             return delegate.create();
2171         }
2172     }
2173
2174     interface MessageInterceptor extends Function<Object, Object> {
2175         boolean canIntercept(Object message);
2176     }
2177
2178     private static MessageInterceptor newFindPrimaryInterceptor(final ActorRef primaryActor) {
2179         return new MessageInterceptor(){
2180             @Override
2181             public Object apply(Object message) {
2182                 return new RemotePrimaryShardFound(Serialization.serializedActorPath(primaryActor), (short) 1);
2183             }
2184
2185             @Override
2186             public boolean canIntercept(Object message) {
2187                 return message instanceof FindPrimary;
2188             }
2189         };
2190     }
2191
2192     private static class MockRespondActor extends MessageCollectorActor {
2193         static final String CLEAR_RESPONSE = "clear-response";
2194         static final org.slf4j.Logger LOG = LoggerFactory.getLogger(MockRespondActor.class);
2195
2196         private volatile Object responseMsg;
2197
2198         @SuppressWarnings("unused")
2199         public MockRespondActor() {
2200         }
2201
2202         @SuppressWarnings("unused")
2203         public MockRespondActor(Object responseMsg) {
2204             this.responseMsg = responseMsg;
2205         }
2206
2207         public void updateResponse(Object response) {
2208             responseMsg = response;
2209         }
2210
2211         @Override
2212         public void onReceive(Object message) throws Exception {
2213             if(!"get-all-messages".equals(message)) {
2214                 LOG.debug("Received message : {}", message);
2215             }
2216             super.onReceive(message);
2217             if (message instanceof AddServer && responseMsg != null) {
2218                 getSender().tell(responseMsg, getSelf());
2219             } else if(message instanceof RemoveServer && responseMsg != null){
2220                 getSender().tell(responseMsg, getSelf());
2221             } else if(message.equals(CLEAR_RESPONSE)) {
2222                 responseMsg = null;
2223             }
2224         }
2225     }
2226 }

©2013 OpenDaylight, A Linux Foundation Collaborative Project. All Rights Reserved.
OpenDaylight is a registered trademark of The OpenDaylight Project, Inc.
Linux Foundation and OpenDaylight are registered trademarks of the Linux Foundation.
Linux is a registered trademark of Linus Torvalds.