BUG-2138: Create DistributedShardFrontend
[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 =
1396                 new ShardManagerSnapshot(Arrays.asList("shard1", "shard2", "astronauts"), Collections.emptyMap());
1397         DatastoreSnapshot restoreFromSnapshot = new DatastoreSnapshot(shardMrgIDSuffix, snapshot,
1398                 Collections.<ShardSnapshot>emptyList());
1399         TestActorRef<TestShardManager> shardManager = actorFactory.createTestActor(newTestShardMgrBuilder(mockConfig)
1400                 .restoreFromSnapshot(restoreFromSnapshot).props().withDispatcher(Dispatchers.DefaultDispatcherId()));
1401
1402         shardManager.underlyingActor().waitForRecoveryComplete();
1403
1404         shardManager.tell(new UpdateSchemaContext(TestModel.createTestContext()), ActorRef.noSender());
1405
1406         waitForShardInitialized(shardManager, "shard1", kit);
1407         waitForShardInitialized(shardManager, "shard2", kit);
1408         waitForShardInitialized(shardManager, "astronauts", kit);
1409
1410         shardManager.tell(GetSnapshot.INSTANCE, kit.getRef());
1411
1412         DatastoreSnapshot datastoreSnapshot = expectMsgClassOrFailure(DatastoreSnapshot.class, kit, "GetSnapshot");
1413
1414         assertEquals("getType", shardMrgIDSuffix, datastoreSnapshot.getType());
1415
1416         assertNotNull("Expected ShardManagerSnapshot", datastoreSnapshot.getShardManagerSnapshot());
1417         assertEquals("Shard names", Sets.newHashSet("shard1", "shard2", "astronauts"),
1418                 Sets.newHashSet(datastoreSnapshot.getShardManagerSnapshot().getShardList()));
1419
1420         LOG.info("testRestoreFromSnapshot ending");
1421     }
1422
1423     @Test
1424     public void testAddShardReplicaForNonExistentShardConfig() throws Exception {
1425         new JavaTestKit(getSystem()) {
1426             {
1427                 ActorRef shardManager = actorFactory
1428                         .createActor(newShardMgrProps(new ConfigurationImpl(new EmptyModuleShardConfigProvider())));
1429
1430                 shardManager.tell(new AddShardReplica("model-inventory"), getRef());
1431                 Status.Failure resp = expectMsgClass(duration("2 seconds"), Status.Failure.class);
1432
1433                 assertEquals("Failure obtained", true, resp.cause() instanceof IllegalArgumentException);
1434             }
1435         };
1436     }
1437
1438     @Test
1439     public void testAddShardReplica() throws Exception {
1440         LOG.info("testAddShardReplica starting");
1441         MockConfiguration mockConfig = new MockConfiguration(
1442                 ImmutableMap.<String, List<String>>builder().put("default", Arrays.asList("member-1", "member-2"))
1443                         .put("astronauts", Arrays.asList("member-2")).build());
1444
1445         final String shardManagerID = ShardManagerIdentifier.builder().type(shardMrgIDSuffix).build().toString();
1446         datastoreContextBuilder.shardManagerPersistenceId(shardManagerID);
1447
1448         // Create an ActorSystem ShardManager actor for member-1.
1449         final ActorSystem system1 = newActorSystem("Member1");
1450         Cluster.get(system1).join(AddressFromURIString.parse("akka://cluster-test@127.0.0.1:2558"));
1451         ActorRef mockDefaultShardActor = newMockShardActor(system1, Shard.DEFAULT_NAME, "member-1");
1452         final TestActorRef<TestShardManager> newReplicaShardManager = TestActorRef.create(system1,
1453                 newTestShardMgrBuilder(mockConfig).shardActor(mockDefaultShardActor)
1454                         .cluster(new ClusterWrapperImpl(system1)).props()
1455                         .withDispatcher(Dispatchers.DefaultDispatcherId()),
1456                 shardManagerID);
1457
1458         // Create an ActorSystem ShardManager actor for member-2.
1459         final ActorSystem system2 = newActorSystem("Member2");
1460         Cluster.get(system2).join(AddressFromURIString.parse("akka://cluster-test@127.0.0.1:2558"));
1461
1462         String memberId2 = "member-2-shard-astronauts-" + shardMrgIDSuffix;
1463         String name = ShardIdentifier.create("astronauts", MEMBER_2, "config").toString();
1464         final TestActorRef<MockRespondActor> mockShardLeaderActor = TestActorRef.create(system2,
1465                 Props.create(MockRespondActor.class, AddServer.class,
1466                         new AddServerReply(ServerChangeStatus.OK, memberId2))
1467                         .withDispatcher(Dispatchers.DefaultDispatcherId()),
1468                 name);
1469         final TestActorRef<TestShardManager> leaderShardManager = TestActorRef.create(system2,
1470                 newTestShardMgrBuilder(mockConfig).shardActor(mockShardLeaderActor)
1471                         .cluster(new ClusterWrapperImpl(system2)).props()
1472                         .withDispatcher(Dispatchers.DefaultDispatcherId()),
1473                 shardManagerID);
1474
1475         new JavaTestKit(system1) {
1476             {
1477                 newReplicaShardManager.tell(new UpdateSchemaContext(TestModel.createTestContext()), getRef());
1478                 leaderShardManager.tell(new UpdateSchemaContext(TestModel.createTestContext()), getRef());
1479
1480                 leaderShardManager.tell(new ActorInitialized(), mockShardLeaderActor);
1481
1482                 short leaderVersion = DataStoreVersions.CURRENT_VERSION - 1;
1483                 leaderShardManager.tell(
1484                         new ShardLeaderStateChanged(memberId2, memberId2, mock(DataTree.class), leaderVersion),
1485                         mockShardLeaderActor);
1486                 leaderShardManager.tell(
1487                         new RoleChangeNotification(memberId2, RaftState.Candidate.name(), RaftState.Leader.name()),
1488                         mockShardLeaderActor);
1489
1490                 newReplicaShardManager.underlyingActor().waitForMemberUp();
1491                 leaderShardManager.underlyingActor().waitForMemberUp();
1492
1493                 // Have a dummy snapshot to be overwritten by the new data
1494                 // persisted.
1495                 String[] restoredShards = { "default", "people" };
1496                 ShardManagerSnapshot snapshot =
1497                         new ShardManagerSnapshot(Arrays.asList(restoredShards), Collections.emptyMap());
1498                 InMemorySnapshotStore.addSnapshot(shardManagerID, snapshot);
1499                 Uninterruptibles.sleepUninterruptibly(2, TimeUnit.MILLISECONDS);
1500
1501                 InMemorySnapshotStore.addSnapshotSavedLatch(shardManagerID);
1502                 InMemorySnapshotStore.addSnapshotDeletedLatch(shardManagerID);
1503
1504                 // construct a mock response message
1505                 newReplicaShardManager.tell(new AddShardReplica("astronauts"), getRef());
1506                 AddServer addServerMsg = MessageCollectorActor.expectFirstMatching(mockShardLeaderActor,
1507                         AddServer.class);
1508                 String addServerId = "member-1-shard-astronauts-" + shardMrgIDSuffix;
1509                 assertEquals("AddServer serverId", addServerId, addServerMsg.getNewServerId());
1510                 expectMsgClass(duration("5 seconds"), Status.Success.class);
1511
1512                 InMemorySnapshotStore.waitForSavedSnapshot(shardManagerID, ShardManagerSnapshot.class);
1513                 InMemorySnapshotStore.waitForDeletedSnapshot(shardManagerID);
1514                 List<ShardManagerSnapshot> persistedSnapshots = InMemorySnapshotStore.getSnapshots(shardManagerID,
1515                         ShardManagerSnapshot.class);
1516                 assertEquals("Number of snapshots persisted", 1, persistedSnapshots.size());
1517                 ShardManagerSnapshot shardManagerSnapshot = persistedSnapshots.get(0);
1518                 assertEquals("Persisted local shards", Sets.newHashSet("default", "astronauts"),
1519                         Sets.newHashSet(shardManagerSnapshot.getShardList()));
1520             }
1521         };
1522         LOG.info("testAddShardReplica ending");
1523     }
1524
1525     @Test
1526     public void testAddShardReplicaWithPreExistingReplicaInRemoteShardLeader() throws Exception {
1527         LOG.info("testAddShardReplicaWithPreExistingReplicaInRemoteShardLeader starting");
1528         new JavaTestKit(getSystem()) {
1529             {
1530                 TestActorRef<TestShardManager> shardManager = actorFactory
1531                         .createTestActor(newPropsShardMgrWithMockShardActor(), shardMgrID);
1532
1533                 shardManager.tell(new UpdateSchemaContext(TestModel.createTestContext()), getRef());
1534                 shardManager.tell(new ActorInitialized(), mockShardActor);
1535
1536                 String leaderId = "leader-member-shard-default-" + shardMrgIDSuffix;
1537                 AddServerReply addServerReply = new AddServerReply(ServerChangeStatus.ALREADY_EXISTS, null);
1538                 ActorRef leaderShardActor = shardManager.underlyingActor().getContext()
1539                         .actorOf(Props.create(MockRespondActor.class, AddServer.class, addServerReply), leaderId);
1540
1541                 MockClusterWrapper.sendMemberUp(shardManager, "leader-member", leaderShardActor.path().toString());
1542
1543                 String newReplicaId = "member-1-shard-default-" + shardMrgIDSuffix;
1544                 shardManager.tell(
1545                         new RoleChangeNotification(newReplicaId, RaftState.Candidate.name(), RaftState.Follower.name()),
1546                         mockShardActor);
1547                 shardManager.tell(
1548                         new ShardLeaderStateChanged(newReplicaId, leaderId, DataStoreVersions.CURRENT_VERSION),
1549                         mockShardActor);
1550
1551                 shardManager.tell(new AddShardReplica(Shard.DEFAULT_NAME), getRef());
1552
1553                 MessageCollectorActor.expectFirstMatching(leaderShardActor, AddServer.class);
1554
1555                 Failure resp = expectMsgClass(duration("5 seconds"), Failure.class);
1556                 assertEquals("Failure cause", AlreadyExistsException.class, resp.cause().getClass());
1557
1558                 shardManager.tell(new FindLocalShard(Shard.DEFAULT_NAME, false), getRef());
1559                 expectMsgClass(duration("5 seconds"), LocalShardFound.class);
1560
1561                 // Send message again to verify previous in progress state is
1562                 // cleared
1563
1564                 shardManager.tell(new AddShardReplica(Shard.DEFAULT_NAME), getRef());
1565                 resp = expectMsgClass(duration("5 seconds"), Failure.class);
1566                 assertEquals("Failure cause", AlreadyExistsException.class, resp.cause().getClass());
1567
1568                 // Send message again with an AddServer timeout to verify the
1569                 // pre-existing shard actor isn't terminated.
1570
1571                 shardManager.tell(
1572                         newDatastoreContextFactory(
1573                                 datastoreContextBuilder.shardLeaderElectionTimeout(100, TimeUnit.MILLISECONDS).build()),
1574                         getRef());
1575                 leaderShardActor.tell(MockRespondActor.CLEAR_RESPONSE, ActorRef.noSender());
1576                 shardManager.tell(new AddShardReplica(Shard.DEFAULT_NAME), getRef());
1577                 expectMsgClass(duration("5 seconds"), Failure.class);
1578
1579                 shardManager.tell(new FindLocalShard(Shard.DEFAULT_NAME, false), getRef());
1580                 expectMsgClass(duration("5 seconds"), LocalShardFound.class);
1581             }
1582         };
1583
1584         LOG.info("testAddShardReplicaWithPreExistingReplicaInRemoteShardLeader ending");
1585     }
1586
1587     @Test
1588     public void testAddShardReplicaWithPreExistingLocalReplicaLeader() throws Exception {
1589         LOG.info("testAddShardReplicaWithPreExistingLocalReplicaLeader starting");
1590         new JavaTestKit(getSystem()) {
1591             {
1592                 String memberId = "member-1-shard-default-" + shardMrgIDSuffix;
1593                 ActorRef shardManager = actorFactory.createActor(newPropsShardMgrWithMockShardActor());
1594
1595                 shardManager.tell(new UpdateSchemaContext(TestModel.createTestContext()), getRef());
1596                 shardManager.tell(new ActorInitialized(), mockShardActor);
1597                 shardManager.tell(new ShardLeaderStateChanged(memberId, memberId, mock(DataTree.class),
1598                         DataStoreVersions.CURRENT_VERSION), getRef());
1599                 shardManager.tell(
1600                         new RoleChangeNotification(memberId, RaftState.Candidate.name(), RaftState.Leader.name()),
1601                         mockShardActor);
1602
1603                 shardManager.tell(new AddShardReplica(Shard.DEFAULT_NAME), getRef());
1604                 Failure resp = expectMsgClass(duration("5 seconds"), Failure.class);
1605                 assertEquals("Failure cause", AlreadyExistsException.class, resp.cause().getClass());
1606
1607                 shardManager.tell(new FindLocalShard(Shard.DEFAULT_NAME, false), getRef());
1608                 expectMsgClass(duration("5 seconds"), LocalShardFound.class);
1609             }
1610         };
1611
1612         LOG.info("testAddShardReplicaWithPreExistingLocalReplicaLeader ending");
1613     }
1614
1615     @Test
1616     public void testAddShardReplicaWithAddServerReplyFailure() throws Exception {
1617         LOG.info("testAddShardReplicaWithAddServerReplyFailure starting");
1618         new JavaTestKit(getSystem()) {
1619             {
1620                 JavaTestKit mockShardLeaderKit = new JavaTestKit(getSystem());
1621
1622                 MockConfiguration mockConfig = new MockConfiguration(ImmutableMap.<String, List<String>>builder()
1623                         .put("astronauts", Arrays.asList("member-2")).build());
1624
1625                 ActorRef mockNewReplicaShardActor = newMockShardActor(getSystem(), "astronauts", "member-1");
1626                 final TestActorRef<TestShardManager> shardManager = actorFactory.createTestActor(
1627                         newTestShardMgrBuilder(mockConfig).shardActor(mockNewReplicaShardActor).props(), shardMgrID);
1628                 shardManager.underlyingActor()
1629                         .setMessageInterceptor(newFindPrimaryInterceptor(mockShardLeaderKit.getRef()));
1630
1631                 shardManager.tell(new UpdateSchemaContext(TestModel.createTestContext()), getRef());
1632
1633                 JavaTestKit terminateWatcher = new JavaTestKit(getSystem());
1634                 terminateWatcher.watch(mockNewReplicaShardActor);
1635
1636                 shardManager.tell(new AddShardReplica("astronauts"), getRef());
1637
1638                 AddServer addServerMsg = mockShardLeaderKit.expectMsgClass(AddServer.class);
1639                 assertEquals("AddServer serverId", "member-1-shard-astronauts-" + shardMrgIDSuffix,
1640                         addServerMsg.getNewServerId());
1641                 mockShardLeaderKit.reply(new AddServerReply(ServerChangeStatus.TIMEOUT, null));
1642
1643                 Failure failure = expectMsgClass(duration("5 seconds"), Failure.class);
1644                 assertEquals("Failure cause", TimeoutException.class, failure.cause().getClass());
1645
1646                 shardManager.tell(new FindLocalShard("astronauts", false), getRef());
1647                 expectMsgClass(duration("5 seconds"), LocalShardNotFound.class);
1648
1649                 terminateWatcher.expectTerminated(mockNewReplicaShardActor);
1650
1651                 shardManager.tell(new AddShardReplica("astronauts"), getRef());
1652                 mockShardLeaderKit.expectMsgClass(AddServer.class);
1653                 mockShardLeaderKit.reply(new AddServerReply(ServerChangeStatus.NO_LEADER, null));
1654                 failure = expectMsgClass(duration("5 seconds"), Failure.class);
1655                 assertEquals("Failure cause", NoShardLeaderException.class, failure.cause().getClass());
1656             }
1657         };
1658
1659         LOG.info("testAddShardReplicaWithAddServerReplyFailure ending");
1660     }
1661
1662     @Test
1663     public void testAddShardReplicaWithAlreadyInProgress() throws Exception {
1664         testServerChangeWhenAlreadyInProgress("astronauts", new AddShardReplica("astronauts"),
1665                 AddServer.class, new AddShardReplica("astronauts"));
1666     }
1667
1668     @Test
1669     public void testAddShardReplicaWithFindPrimaryTimeout() throws Exception {
1670         LOG.info("testAddShardReplicaWithFindPrimaryTimeout starting");
1671         datastoreContextBuilder.shardInitializationTimeout(100, TimeUnit.MILLISECONDS);
1672         new JavaTestKit(getSystem()) {
1673             {
1674                 MockConfiguration mockConfig = new MockConfiguration(ImmutableMap.<String, List<String>>builder()
1675                         .put("astronauts", Arrays.asList("member-2")).build());
1676
1677                 final ActorRef newReplicaShardManager = actorFactory
1678                         .createActor(newTestShardMgrBuilder(mockConfig).shardActor(mockShardActor).props(), shardMgrID);
1679
1680                 newReplicaShardManager.tell(new UpdateSchemaContext(TestModel.createTestContext()), getRef());
1681                 MockClusterWrapper.sendMemberUp(newReplicaShardManager, "member-2",
1682                         AddressFromURIString.parse("akka://non-existent@127.0.0.1:5").toString());
1683
1684                 newReplicaShardManager.tell(new AddShardReplica("astronauts"), getRef());
1685                 Status.Failure resp = expectMsgClass(duration("5 seconds"), Status.Failure.class);
1686                 assertEquals("Failure obtained", true, resp.cause() instanceof RuntimeException);
1687             }
1688         };
1689
1690         LOG.info("testAddShardReplicaWithFindPrimaryTimeout ending");
1691     }
1692
1693     @Test
1694     public void testRemoveShardReplicaForNonExistentShard() throws Exception {
1695         new JavaTestKit(getSystem()) {
1696             {
1697                 ActorRef shardManager = actorFactory
1698                         .createActor(newShardMgrProps(new ConfigurationImpl(new EmptyModuleShardConfigProvider())));
1699
1700                 shardManager.tell(new RemoveShardReplica("model-inventory", MEMBER_1), getRef());
1701                 Status.Failure resp = expectMsgClass(duration("10 seconds"), Status.Failure.class);
1702                 assertEquals("Failure obtained", true, resp.cause() instanceof PrimaryNotFoundException);
1703             }
1704         };
1705     }
1706
1707     @Test
1708     /**
1709      * Primary is Local
1710      */
1711     public void testRemoveShardReplicaLocal() throws Exception {
1712         new JavaTestKit(getSystem()) {
1713             {
1714                 String memberId = "member-1-shard-default-" + shardMrgIDSuffix;
1715
1716                 final TestActorRef<MockRespondActor> respondActor = actorFactory
1717                         .createTestActor(Props.create(MockRespondActor.class, RemoveServer.class,
1718                                 new RemoveServerReply(ServerChangeStatus.OK, null)), memberId);
1719
1720                 ActorRef shardManager = getSystem().actorOf(newPropsShardMgrWithMockShardActor(respondActor));
1721
1722                 shardManager.tell(new UpdateSchemaContext(TestModel.createTestContext()), getRef());
1723                 shardManager.tell(new ActorInitialized(), respondActor);
1724                 shardManager.tell(new ShardLeaderStateChanged(memberId, memberId, mock(DataTree.class),
1725                         DataStoreVersions.CURRENT_VERSION), getRef());
1726                 shardManager.tell(
1727                         new RoleChangeNotification(memberId, RaftState.Candidate.name(), RaftState.Leader.name()),
1728                         respondActor);
1729
1730                 shardManager.tell(new RemoveShardReplica(Shard.DEFAULT_NAME, MEMBER_1), getRef());
1731                 final RemoveServer removeServer = MessageCollectorActor.expectFirstMatching(respondActor,
1732                         RemoveServer.class);
1733                 assertEquals(ShardIdentifier.create("default", MEMBER_1, shardMrgIDSuffix).toString(),
1734                         removeServer.getServerId());
1735                 expectMsgClass(duration("5 seconds"), Success.class);
1736             }
1737         };
1738     }
1739
1740     @Test
1741     public void testRemoveShardReplicaRemote() throws Exception {
1742         MockConfiguration mockConfig = new MockConfiguration(
1743                 ImmutableMap.<String, List<String>>builder().put("default", Arrays.asList("member-1", "member-2"))
1744                         .put("astronauts", Arrays.asList("member-1")).build());
1745
1746         String shardManagerID = ShardManagerIdentifier.builder().type(shardMrgIDSuffix).build().toString();
1747
1748         // Create an ActorSystem ShardManager actor for member-1.
1749         final ActorSystem system1 = newActorSystem("Member1");
1750         Cluster.get(system1).join(AddressFromURIString.parse("akka://cluster-test@127.0.0.1:2558"));
1751         ActorRef mockDefaultShardActor = newMockShardActor(system1, Shard.DEFAULT_NAME, "member-1");
1752
1753         final TestActorRef<TestShardManager> newReplicaShardManager = TestActorRef.create(system1,
1754                 newTestShardMgrBuilder().configuration(mockConfig).shardActor(mockDefaultShardActor).cluster(
1755                         new ClusterWrapperImpl(system1)).props().withDispatcher(Dispatchers.DefaultDispatcherId()),
1756                 shardManagerID);
1757
1758         // Create an ActorSystem ShardManager actor for member-2.
1759         final ActorSystem system2 = newActorSystem("Member2");
1760         Cluster.get(system2).join(AddressFromURIString.parse("akka://cluster-test@127.0.0.1:2558"));
1761
1762         String name = ShardIdentifier.create("default", MEMBER_2, shardMrgIDSuffix).toString();
1763         String memberId2 = "member-2-shard-default-" + shardMrgIDSuffix;
1764         final TestActorRef<MockRespondActor> mockShardLeaderActor =
1765                 TestActorRef.create(system2, Props.create(MockRespondActor.class, RemoveServer.class,
1766                         new RemoveServerReply(ServerChangeStatus.OK, memberId2)), name);
1767
1768         LOG.error("Mock Shard Leader Actor : {}", mockShardLeaderActor);
1769
1770         final TestActorRef<TestShardManager> leaderShardManager = TestActorRef.create(system2,
1771                 newTestShardMgrBuilder().configuration(mockConfig).shardActor(mockShardLeaderActor).cluster(
1772                         new ClusterWrapperImpl(system2)).props().withDispatcher(Dispatchers.DefaultDispatcherId()),
1773                 shardManagerID);
1774
1775         // Because mockShardLeaderActor is created at the top level of the actor system it has an address like so,
1776         //    akka://cluster-test@127.0.0.1:2559/user/member-2-shard-default-config1
1777         // However when a shard manager has a local shard which is a follower and a leader that is remote it will
1778         // try to compute an address for the remote shard leader using the ShardPeerAddressResolver. This address will
1779         // look like so,
1780         //    akka://cluster-test@127.0.0.1:2559/user/shardmanager-config1/member-2-shard-default-config1
1781         // In this specific case if we did a FindPrimary for shard default from member-1 we would come up
1782         // with the address of an actor which does not exist, therefore any message sent to that actor would go to
1783         // dead letters.
1784         // To work around this problem we create a ForwardingActor with the right address and pass to it the
1785         // mockShardLeaderActor. The ForwardingActor simply forwards all messages to the mockShardLeaderActor and every
1786         // thing works as expected
1787         final ActorRef actorRef = leaderShardManager.underlyingActor().context()
1788                 .actorOf(Props.create(ForwardingActor.class, mockShardLeaderActor),
1789                         "member-2-shard-default-" + shardMrgIDSuffix);
1790
1791         LOG.error("Forwarding actor : {}", actorRef);
1792
1793         new JavaTestKit(system1) {
1794             {
1795                 newReplicaShardManager.tell(new UpdateSchemaContext(TestModel.createTestContext()), getRef());
1796                 leaderShardManager.tell(new UpdateSchemaContext(TestModel.createTestContext()), getRef());
1797
1798                 leaderShardManager.tell(new ActorInitialized(), mockShardLeaderActor);
1799                 newReplicaShardManager.tell(new ActorInitialized(), mockShardLeaderActor);
1800
1801                 short leaderVersion = DataStoreVersions.CURRENT_VERSION - 1;
1802                 leaderShardManager.tell(
1803                         new ShardLeaderStateChanged(memberId2, memberId2, mock(DataTree.class), leaderVersion),
1804                         mockShardLeaderActor);
1805                 leaderShardManager.tell(
1806                         new RoleChangeNotification(memberId2, RaftState.Candidate.name(), RaftState.Leader.name()),
1807                         mockShardLeaderActor);
1808
1809                 String memberId1 = "member-1-shard-default-" + shardMrgIDSuffix;
1810                 newReplicaShardManager.tell(
1811                         new ShardLeaderStateChanged(memberId1, memberId2, mock(DataTree.class), leaderVersion),
1812                         mockShardActor);
1813                 newReplicaShardManager.tell(
1814                         new RoleChangeNotification(memberId1, RaftState.Candidate.name(), RaftState.Follower.name()),
1815                         mockShardActor);
1816
1817                 newReplicaShardManager.underlyingActor().waitForMemberUp();
1818                 leaderShardManager.underlyingActor().waitForMemberUp();
1819
1820                 // construct a mock response message
1821                 newReplicaShardManager.tell(new RemoveShardReplica("default", MEMBER_1), getRef());
1822                 RemoveServer removeServer = MessageCollectorActor.expectFirstMatching(mockShardLeaderActor,
1823                         RemoveServer.class);
1824                 String removeServerId = ShardIdentifier.create("default", MEMBER_1, shardMrgIDSuffix).toString();
1825                 assertEquals("RemoveServer serverId", removeServerId, removeServer.getServerId());
1826                 expectMsgClass(duration("5 seconds"), Status.Success.class);
1827             }
1828         };
1829     }
1830
1831     @Test
1832     public void testRemoveShardReplicaWhenAnotherRemoveShardReplicaAlreadyInProgress() throws Exception {
1833         testServerChangeWhenAlreadyInProgress("astronauts", new RemoveShardReplica("astronauts", MEMBER_2),
1834                 RemoveServer.class, new RemoveShardReplica("astronauts", MEMBER_3));
1835     }
1836
1837     @Test
1838     public void testRemoveShardReplicaWhenAddShardReplicaAlreadyInProgress() throws Exception {
1839         testServerChangeWhenAlreadyInProgress("astronauts", new AddShardReplica("astronauts"),
1840                 AddServer.class, new RemoveShardReplica("astronauts", MEMBER_2));
1841     }
1842
1843
1844     public void testServerChangeWhenAlreadyInProgress(final String shardName, final Object firstServerChange,
1845                                                       final Class<?> firstForwardedServerChangeClass,
1846                                                       final Object secondServerChange) throws Exception {
1847         new JavaTestKit(getSystem()) {
1848             {
1849                 JavaTestKit mockShardLeaderKit = new JavaTestKit(getSystem());
1850                 final JavaTestKit secondRequestKit = new JavaTestKit(getSystem());
1851
1852                 MockConfiguration mockConfig = new MockConfiguration(ImmutableMap.<String, List<String>>builder()
1853                         .put(shardName, Arrays.asList("member-2")).build());
1854
1855                 final TestActorRef<TestShardManager> shardManager = TestActorRef.create(getSystem(),
1856                         newTestShardMgrBuilder().configuration(mockConfig).shardActor(mockShardActor)
1857                                 .cluster(new MockClusterWrapper()).props()
1858                                 .withDispatcher(Dispatchers.DefaultDispatcherId()),
1859                         shardMgrID);
1860
1861                 shardManager.underlyingActor()
1862                         .setMessageInterceptor(newFindPrimaryInterceptor(mockShardLeaderKit.getRef()));
1863
1864                 shardManager.tell(new UpdateSchemaContext(TestModel.createTestContext()), getRef());
1865
1866                 shardManager.tell(firstServerChange, getRef());
1867
1868                 mockShardLeaderKit.expectMsgClass(firstForwardedServerChangeClass);
1869
1870                 shardManager.tell(secondServerChange, secondRequestKit.getRef());
1871
1872                 secondRequestKit.expectMsgClass(duration("5 seconds"), Failure.class);
1873             }
1874         };
1875     }
1876
1877     @Test
1878     public void testServerRemovedShardActorNotRunning() throws Exception {
1879         LOG.info("testServerRemovedShardActorNotRunning starting");
1880         new JavaTestKit(getSystem()) {
1881             {
1882                 MockConfiguration mockConfig = new MockConfiguration(ImmutableMap.<String, List<String>>builder()
1883                         .put("default", Arrays.asList("member-1", "member-2"))
1884                         .put("astronauts", Arrays.asList("member-2"))
1885                         .put("people", Arrays.asList("member-1", "member-2")).build());
1886
1887                 TestActorRef<TestShardManager> shardManager = actorFactory
1888                         .createTestActor(newShardMgrProps(mockConfig));
1889
1890                 shardManager.underlyingActor().waitForRecoveryComplete();
1891                 shardManager.tell(new FindLocalShard("people", false), getRef());
1892                 expectMsgClass(duration("5 seconds"), NotInitializedException.class);
1893
1894                 shardManager.tell(new FindLocalShard("default", false), getRef());
1895                 expectMsgClass(duration("5 seconds"), NotInitializedException.class);
1896
1897                 // Removed the default shard replica from member-1
1898                 ShardIdentifier.Builder builder = new ShardIdentifier.Builder();
1899                 ShardIdentifier shardId = builder.shardName("default").memberName(MEMBER_1).type(shardMrgIDSuffix)
1900                         .build();
1901                 shardManager.tell(new ServerRemoved(shardId.toString()), getRef());
1902
1903                 shardManager.underlyingActor().verifySnapshotPersisted(Sets.newHashSet("people"));
1904             }
1905         };
1906
1907         LOG.info("testServerRemovedShardActorNotRunning ending");
1908     }
1909
1910     @Test
1911     public void testServerRemovedShardActorRunning() throws Exception {
1912         LOG.info("testServerRemovedShardActorRunning starting");
1913         new JavaTestKit(getSystem()) {
1914             {
1915                 MockConfiguration mockConfig = new MockConfiguration(ImmutableMap.<String, List<String>>builder()
1916                         .put("default", Arrays.asList("member-1", "member-2"))
1917                         .put("astronauts", Arrays.asList("member-2"))
1918                         .put("people", Arrays.asList("member-1", "member-2")).build());
1919
1920                 String shardId = ShardIdentifier.create("default", MEMBER_1, shardMrgIDSuffix).toString();
1921                 TestActorRef<MessageCollectorActor> shard = actorFactory.createTestActor(MessageCollectorActor.props(),
1922                         shardId);
1923
1924                 TestActorRef<TestShardManager> shardManager = actorFactory
1925                         .createTestActor(newTestShardMgrBuilder(mockConfig).addShardActor("default", shard).props());
1926
1927                 shardManager.underlyingActor().waitForRecoveryComplete();
1928
1929                 shardManager.tell(new UpdateSchemaContext(TestModel.createTestContext()), getRef());
1930                 shardManager.tell(new ActorInitialized(), shard);
1931
1932                 waitForShardInitialized(shardManager, "people", this);
1933                 waitForShardInitialized(shardManager, "default", this);
1934
1935                 // Removed the default shard replica from member-1
1936                 shardManager.tell(new ServerRemoved(shardId), getRef());
1937
1938                 shardManager.underlyingActor().verifySnapshotPersisted(Sets.newHashSet("people"));
1939
1940                 MessageCollectorActor.expectFirstMatching(shard, Shutdown.class);
1941             }
1942         };
1943
1944         LOG.info("testServerRemovedShardActorRunning ending");
1945     }
1946
1947     @Test
1948     public void testShardPersistenceWithRestoredData() throws Exception {
1949         LOG.info("testShardPersistenceWithRestoredData starting");
1950         new JavaTestKit(getSystem()) {
1951             {
1952                 MockConfiguration mockConfig =
1953                     new MockConfiguration(ImmutableMap.<String, List<String>>builder()
1954                             .put("default", Arrays.asList("member-1", "member-2"))
1955                             .put("astronauts", Arrays.asList("member-2"))
1956                             .put("people", Arrays.asList("member-1", "member-2")).build());
1957                 String[] restoredShards = {"default", "astronauts"};
1958                 ShardManagerSnapshot snapshot =
1959                         new ShardManagerSnapshot(Arrays.asList(restoredShards), Collections.emptyMap());
1960                 InMemorySnapshotStore.addSnapshot("shard-manager-" + shardMrgIDSuffix, snapshot);
1961
1962                 // create shardManager to come up with restored data
1963                 TestActorRef<TestShardManager> newRestoredShardManager = actorFactory
1964                         .createTestActor(newShardMgrProps(mockConfig));
1965
1966                 newRestoredShardManager.underlyingActor().waitForRecoveryComplete();
1967
1968                 newRestoredShardManager.tell(new FindLocalShard("people", false), getRef());
1969                 LocalShardNotFound notFound = expectMsgClass(duration("5 seconds"), LocalShardNotFound.class);
1970                 assertEquals("for uninitialized shard", "people", notFound.getShardName());
1971
1972                 // Verify a local shard is created for the restored shards,
1973                 // although we expect a NotInitializedException for the shards
1974                 // as the actor initialization
1975                 // message is not sent for them
1976                 newRestoredShardManager.tell(new FindLocalShard("default", false), getRef());
1977                 expectMsgClass(duration("5 seconds"), NotInitializedException.class);
1978
1979                 newRestoredShardManager.tell(new FindLocalShard("astronauts", false), getRef());
1980                 expectMsgClass(duration("5 seconds"), NotInitializedException.class);
1981             }
1982         };
1983
1984         LOG.info("testShardPersistenceWithRestoredData ending");
1985     }
1986
1987     @Test
1988     public void testShutDown() throws Exception {
1989         LOG.info("testShutDown starting");
1990         new JavaTestKit(getSystem()) {
1991             {
1992                 MockConfiguration mockConfig = new MockConfiguration(ImmutableMap.<String, List<String>>builder()
1993                         .put("shard1", Arrays.asList("member-1")).put("shard2", Arrays.asList("member-1")).build());
1994
1995                 String shardId1 = ShardIdentifier.create("shard1", MEMBER_1, shardMrgIDSuffix).toString();
1996                 TestActorRef<MessageCollectorActor> shard1 = actorFactory.createTestActor(
1997                         MessageCollectorActor.props().withDispatcher(Dispatchers.DefaultDispatcherId()), shardId1);
1998
1999                 String shardId2 = ShardIdentifier.create("shard2", MEMBER_1, shardMrgIDSuffix).toString();
2000                 TestActorRef<MessageCollectorActor> shard2 = actorFactory.createTestActor(
2001                         MessageCollectorActor.props().withDispatcher(Dispatchers.DefaultDispatcherId()), shardId2);
2002
2003                 TestActorRef<TestShardManager> shardManager = actorFactory
2004                         .createTestActor(newTestShardMgrBuilder(mockConfig).addShardActor("shard1", shard1)
2005                                 .addShardActor("shard2", shard2).props()
2006                                 .withDispatcher(Dispatchers.DefaultDispatcherId()));
2007
2008                 shardManager.tell(new UpdateSchemaContext(TestModel.createTestContext()), getRef());
2009                 shardManager.tell(new ActorInitialized(), shard1);
2010                 shardManager.tell(new ActorInitialized(), shard2);
2011
2012                 FiniteDuration duration = FiniteDuration.create(5, TimeUnit.SECONDS);
2013                 Future<Boolean> stopFuture = Patterns.gracefulStop(shardManager, duration, Shutdown.INSTANCE);
2014
2015                 MessageCollectorActor.expectFirstMatching(shard1, Shutdown.class);
2016                 MessageCollectorActor.expectFirstMatching(shard2, Shutdown.class);
2017
2018                 try {
2019                     Await.ready(stopFuture, FiniteDuration.create(500, TimeUnit.MILLISECONDS));
2020                     fail("ShardManager actor stopped without waiting for the Shards to be stopped");
2021                 } catch (TimeoutException e) {
2022                     // expected
2023                 }
2024
2025                 actorFactory.killActor(shard1, this);
2026                 actorFactory.killActor(shard2, this);
2027
2028                 Boolean stopped = Await.result(stopFuture, duration);
2029                 assertEquals("Stopped", Boolean.TRUE, stopped);
2030             }
2031         };
2032
2033         LOG.info("testShutDown ending");
2034     }
2035
2036     @Test
2037     public void testChangeServersVotingStatus() throws Exception {
2038         new JavaTestKit(getSystem()) {
2039             {
2040                 String memberId = "member-1-shard-default-" + shardMrgIDSuffix;
2041
2042                 TestActorRef<MockRespondActor> respondActor = actorFactory
2043                         .createTestActor(Props.create(MockRespondActor.class, ChangeServersVotingStatus.class,
2044                                 new ServerChangeReply(ServerChangeStatus.OK, null)), memberId);
2045
2046                 ActorRef shardManager = getSystem().actorOf(newPropsShardMgrWithMockShardActor(respondActor));
2047
2048                 shardManager.tell(new UpdateSchemaContext(TestModel.createTestContext()), getRef());
2049                 shardManager.tell(new ActorInitialized(), respondActor);
2050                 shardManager.tell(new ShardLeaderStateChanged(memberId, memberId, mock(DataTree.class),
2051                         DataStoreVersions.CURRENT_VERSION), getRef());
2052                 shardManager.tell(
2053                         new RoleChangeNotification(memberId, RaftState.Candidate.name(), RaftState.Leader.name()),
2054                         respondActor);
2055
2056                 shardManager.tell(
2057                         new ChangeShardMembersVotingStatus("default", ImmutableMap.of("member-2", Boolean.TRUE)),
2058                         getRef());
2059
2060                 ChangeServersVotingStatus actualChangeStatusMsg = MessageCollectorActor
2061                         .expectFirstMatching(respondActor, ChangeServersVotingStatus.class);
2062                 assertEquals("ChangeServersVotingStatus map", actualChangeStatusMsg.getServerVotingStatusMap(),
2063                         ImmutableMap.of(ShardIdentifier
2064                                 .create("default", MemberName.forName("member-2"), shardMrgIDSuffix).toString(),
2065                                 Boolean.TRUE));
2066
2067                 expectMsgClass(duration("5 seconds"), Success.class);
2068             }
2069         };
2070     }
2071
2072     @Test
2073     public void testChangeServersVotingStatusWithNoLeader() throws Exception {
2074         new JavaTestKit(getSystem()) {
2075             {
2076                 String memberId = "member-1-shard-default-" + shardMrgIDSuffix;
2077
2078                 TestActorRef<MockRespondActor> respondActor = actorFactory
2079                         .createTestActor(Props.create(MockRespondActor.class, ChangeServersVotingStatus.class,
2080                                 new ServerChangeReply(ServerChangeStatus.NO_LEADER, null)), memberId);
2081
2082                 ActorRef shardManager = getSystem().actorOf(newPropsShardMgrWithMockShardActor(respondActor));
2083
2084                 shardManager.tell(new UpdateSchemaContext(TestModel.createTestContext()), getRef());
2085                 shardManager.tell(new ActorInitialized(), respondActor);
2086                 shardManager.tell(new RoleChangeNotification(memberId, null, RaftState.Follower.name()), respondActor);
2087
2088                 shardManager.tell(
2089                         new ChangeShardMembersVotingStatus("default", ImmutableMap.of("member-2", Boolean.TRUE)),
2090                         getRef());
2091
2092                 MessageCollectorActor.expectFirstMatching(respondActor, ChangeServersVotingStatus.class);
2093
2094                 Status.Failure resp = expectMsgClass(duration("5 seconds"), Status.Failure.class);
2095                 assertEquals("Failure resposnse", true, resp.cause() instanceof NoShardLeaderException);
2096             }
2097         };
2098     }
2099
2100     public static class TestShardManager extends ShardManager {
2101         private final CountDownLatch recoveryComplete = new CountDownLatch(1);
2102         private final CountDownLatch snapshotPersist = new CountDownLatch(1);
2103         private ShardManagerSnapshot snapshot;
2104         private final Map<String, ActorRef> shardActors;
2105         private final ActorRef shardActor;
2106         private CountDownLatch findPrimaryMessageReceived = new CountDownLatch(1);
2107         private CountDownLatch memberUpReceived = new CountDownLatch(1);
2108         private CountDownLatch memberRemovedReceived = new CountDownLatch(1);
2109         private CountDownLatch memberUnreachableReceived = new CountDownLatch(1);
2110         private CountDownLatch memberReachableReceived = new CountDownLatch(1);
2111         private volatile MessageInterceptor messageInterceptor;
2112
2113         private TestShardManager(Builder builder) {
2114             super(builder);
2115             shardActor = builder.shardActor;
2116             shardActors = builder.shardActors;
2117         }
2118
2119         @Override
2120         protected void handleRecover(Object message) throws Exception {
2121             try {
2122                 super.handleRecover(message);
2123             } finally {
2124                 if (message instanceof RecoveryCompleted) {
2125                     recoveryComplete.countDown();
2126                 }
2127             }
2128         }
2129
2130         private void countDownIfOther(final Member member, CountDownLatch latch) {
2131             if (!getCluster().getCurrentMemberName().equals(memberToName(member))) {
2132                 latch.countDown();
2133             }
2134         }
2135
2136         @Override
2137         public void handleCommand(Object message) throws Exception {
2138             try {
2139                 if (messageInterceptor != null && messageInterceptor.canIntercept(message)) {
2140                     getSender().tell(messageInterceptor.apply(message), getSelf());
2141                 } else {
2142                     super.handleCommand(message);
2143                 }
2144             } finally {
2145                 if (message instanceof FindPrimary) {
2146                     findPrimaryMessageReceived.countDown();
2147                 } else if (message instanceof ClusterEvent.MemberUp) {
2148                     countDownIfOther(((ClusterEvent.MemberUp) message).member(), memberUpReceived);
2149                 } else if (message instanceof ClusterEvent.MemberRemoved) {
2150                     countDownIfOther(((ClusterEvent.MemberRemoved) message).member(), memberRemovedReceived);
2151                 } else if (message instanceof ClusterEvent.UnreachableMember) {
2152                     countDownIfOther(((ClusterEvent.UnreachableMember) message).member(), memberUnreachableReceived);
2153                 } else if (message instanceof ClusterEvent.ReachableMember) {
2154                     countDownIfOther(((ClusterEvent.ReachableMember) message).member(), memberReachableReceived);
2155                 }
2156             }
2157         }
2158
2159         void setMessageInterceptor(MessageInterceptor messageInterceptor) {
2160             this.messageInterceptor = messageInterceptor;
2161         }
2162
2163         void waitForRecoveryComplete() {
2164             assertEquals("Recovery complete", true,
2165                     Uninterruptibles.awaitUninterruptibly(recoveryComplete, 5, TimeUnit.SECONDS));
2166         }
2167
2168         public void waitForMemberUp() {
2169             assertEquals("MemberUp received", true,
2170                     Uninterruptibles.awaitUninterruptibly(memberUpReceived, 5, TimeUnit.SECONDS));
2171             memberUpReceived = new CountDownLatch(1);
2172         }
2173
2174         void waitForMemberRemoved() {
2175             assertEquals("MemberRemoved received", true,
2176                     Uninterruptibles.awaitUninterruptibly(memberRemovedReceived, 5, TimeUnit.SECONDS));
2177             memberRemovedReceived = new CountDownLatch(1);
2178         }
2179
2180         void waitForUnreachableMember() {
2181             assertEquals("UnreachableMember received", true,
2182                 Uninterruptibles.awaitUninterruptibly(memberUnreachableReceived, 5, TimeUnit.SECONDS
2183                 ));
2184             memberUnreachableReceived = new CountDownLatch(1);
2185         }
2186
2187         void waitForReachableMember() {
2188             assertEquals("ReachableMember received", true,
2189                 Uninterruptibles.awaitUninterruptibly(memberReachableReceived, 5, TimeUnit.SECONDS));
2190             memberReachableReceived = new CountDownLatch(1);
2191         }
2192
2193         void verifyFindPrimary() {
2194             assertEquals("FindPrimary received", true,
2195                     Uninterruptibles.awaitUninterruptibly(findPrimaryMessageReceived, 5, TimeUnit.SECONDS));
2196             findPrimaryMessageReceived = new CountDownLatch(1);
2197         }
2198
2199         public static Builder builder(DatastoreContext.Builder datastoreContextBuilder) {
2200             return new Builder(datastoreContextBuilder);
2201         }
2202
2203         public static class Builder extends AbstractGenericCreator<Builder, TestShardManager> {
2204             private ActorRef shardActor;
2205             private final Map<String, ActorRef> shardActors = new HashMap<>();
2206
2207             Builder(DatastoreContext.Builder datastoreContextBuilder) {
2208                 super(TestShardManager.class);
2209                 datastoreContextFactory(newDatastoreContextFactory(datastoreContextBuilder.build()));
2210             }
2211
2212             Builder shardActor(ActorRef newShardActor) {
2213                 this.shardActor = newShardActor;
2214                 return this;
2215             }
2216
2217             Builder addShardActor(String shardName, ActorRef actorRef) {
2218                 shardActors.put(shardName, actorRef);
2219                 return this;
2220             }
2221         }
2222
2223         @Override
2224         public void saveSnapshot(Object obj) {
2225             snapshot = (ShardManagerSnapshot) obj;
2226             snapshotPersist.countDown();
2227             super.saveSnapshot(obj);
2228         }
2229
2230         void verifySnapshotPersisted(Set<String> shardList) {
2231             assertEquals("saveSnapshot invoked", true,
2232                     Uninterruptibles.awaitUninterruptibly(snapshotPersist, 5, TimeUnit.SECONDS));
2233             assertEquals("Shard Persisted", shardList, Sets.newHashSet(snapshot.getShardList()));
2234         }
2235
2236         @Override
2237         protected ActorRef newShardActor(SchemaContext schemaContext, ShardInformation info) {
2238             if (shardActors.get(info.getShardName()) != null) {
2239                 return shardActors.get(info.getShardName());
2240             }
2241
2242             if (shardActor != null) {
2243                 return shardActor;
2244             }
2245
2246             return super.newShardActor(schemaContext, info);
2247         }
2248     }
2249
2250     private abstract static class AbstractGenericCreator<T extends AbstractGenericCreator<T, ?>, C extends ShardManager>
2251                                                      extends AbstractShardManagerCreator<T> {
2252         private final Class<C> shardManagerClass;
2253
2254         AbstractGenericCreator(Class<C> shardManagerClass) {
2255             this.shardManagerClass = shardManagerClass;
2256             cluster(new MockClusterWrapper()).configuration(new MockConfiguration()).waitTillReadyCountDownLatch(ready)
2257                     .primaryShardInfoCache(new PrimaryShardInfoFutureCache());
2258         }
2259
2260         @Override
2261         public Props props() {
2262             verify();
2263             return Props.create(shardManagerClass, this);
2264         }
2265     }
2266
2267     private static class GenericCreator<C extends ShardManager> extends AbstractGenericCreator<GenericCreator<C>, C> {
2268         GenericCreator(Class<C> shardManagerClass) {
2269             super(shardManagerClass);
2270         }
2271     }
2272
2273     private static class DelegatingShardManagerCreator implements Creator<ShardManager> {
2274         private static final long serialVersionUID = 1L;
2275         private final Creator<ShardManager> delegate;
2276
2277         DelegatingShardManagerCreator(Creator<ShardManager> delegate) {
2278             this.delegate = delegate;
2279         }
2280
2281         @Override
2282         public ShardManager create() throws Exception {
2283             return delegate.create();
2284         }
2285     }
2286
2287     interface MessageInterceptor extends Function<Object, Object> {
2288         boolean canIntercept(Object message);
2289     }
2290
2291     private static MessageInterceptor newFindPrimaryInterceptor(final ActorRef primaryActor) {
2292         return new MessageInterceptor() {
2293             @Override
2294             public Object apply(Object message) {
2295                 return new RemotePrimaryShardFound(Serialization.serializedActorPath(primaryActor), (short) 1);
2296             }
2297
2298             @Override
2299             public boolean canIntercept(Object message) {
2300                 return message instanceof FindPrimary;
2301             }
2302         };
2303     }
2304
2305     private static class MockRespondActor extends MessageCollectorActor {
2306         static final String CLEAR_RESPONSE = "clear-response";
2307
2308         private Object responseMsg;
2309         private final