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