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

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