Merge "Export BindingNormalizedNodeSerializer via Config Subsystem."
[controller.git] / opendaylight / md-sal / sal-distributed-datastore / src / main / java / org / opendaylight / controller / cluster / datastore / ShardManager.java
1 /*
2  * Copyright (c) 2014 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;
10
11 import akka.actor.ActorPath;
12 import akka.actor.ActorRef;
13 import akka.actor.Address;
14 import akka.actor.Cancellable;
15 import akka.actor.OneForOneStrategy;
16 import akka.actor.Props;
17 import akka.actor.SupervisorStrategy;
18 import akka.cluster.ClusterEvent;
19 import akka.japi.Creator;
20 import akka.japi.Function;
21 import akka.japi.Procedure;
22 import akka.persistence.RecoveryCompleted;
23 import akka.persistence.RecoveryFailure;
24 import akka.serialization.Serialization;
25 import com.google.common.annotations.VisibleForTesting;
26 import com.google.common.base.Objects;
27 import com.google.common.base.Preconditions;
28 import com.google.common.base.Strings;
29 import com.google.common.base.Supplier;
30 import com.google.common.collect.ImmutableSet;
31 import com.google.common.collect.Sets;
32 import java.io.Serializable;
33 import java.util.ArrayList;
34 import java.util.Collection;
35 import java.util.Collections;
36 import java.util.HashMap;
37 import java.util.HashSet;
38 import java.util.Iterator;
39 import java.util.List;
40 import java.util.Map;
41 import java.util.Set;
42 import java.util.concurrent.CountDownLatch;
43 import org.opendaylight.controller.cluster.DataPersistenceProvider;
44 import org.opendaylight.controller.cluster.NonPersistentDataProvider;
45 import org.opendaylight.controller.cluster.PersistentDataProvider;
46 import org.opendaylight.controller.cluster.common.actor.AbstractUntypedPersistentActorWithMetering;
47 import org.opendaylight.controller.cluster.datastore.exceptions.NoShardLeaderException;
48 import org.opendaylight.controller.cluster.datastore.exceptions.NotInitializedException;
49 import org.opendaylight.controller.cluster.datastore.exceptions.PrimaryNotFoundException;
50 import org.opendaylight.controller.cluster.datastore.identifiers.ShardIdentifier;
51 import org.opendaylight.controller.cluster.datastore.identifiers.ShardManagerIdentifier;
52 import org.opendaylight.controller.cluster.datastore.jmx.mbeans.shardmanager.ShardManagerInfo;
53 import org.opendaylight.controller.cluster.datastore.jmx.mbeans.shardmanager.ShardManagerInfoMBean;
54 import org.opendaylight.controller.cluster.datastore.messages.ActorInitialized;
55 import org.opendaylight.controller.cluster.datastore.messages.FindLocalShard;
56 import org.opendaylight.controller.cluster.datastore.messages.FindPrimary;
57 import org.opendaylight.controller.cluster.datastore.messages.LocalShardFound;
58 import org.opendaylight.controller.cluster.datastore.messages.LocalShardNotFound;
59 import org.opendaylight.controller.cluster.datastore.messages.PeerAddressResolved;
60 import org.opendaylight.controller.cluster.datastore.messages.PrimaryFound;
61 import org.opendaylight.controller.cluster.datastore.messages.UpdateSchemaContext;
62 import org.opendaylight.controller.cluster.datastore.utils.Dispatchers;
63 import org.opendaylight.controller.cluster.notifications.LeaderStateChanged;
64 import org.opendaylight.controller.cluster.notifications.RegisterRoleChangeListener;
65 import org.opendaylight.controller.cluster.notifications.RoleChangeNotification;
66 import org.opendaylight.controller.cluster.raft.RaftState;
67 import org.opendaylight.controller.cluster.raft.base.messages.FollowerInitialSyncUpStatus;
68 import org.opendaylight.yangtools.yang.model.api.ModuleIdentifier;
69 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
70 import org.slf4j.Logger;
71 import org.slf4j.LoggerFactory;
72 import scala.concurrent.duration.Duration;
73
74 /**
75  * The ShardManager has the following jobs,
76  * <ul>
77  * <li> Create all the local shard replicas that belong on this cluster member
78  * <li> Find the address of the local shard
79  * <li> Find the primary replica for any given shard
80  * <li> Monitor the cluster members and store their addresses
81  * <ul>
82  */
83 public class ShardManager extends AbstractUntypedPersistentActorWithMetering {
84
85     private static final Logger LOG = LoggerFactory.getLogger(ShardManager.class);
86
87     // Stores a mapping between a member name and the address of the member
88     // Member names look like "member-1", "member-2" etc and are as specified
89     // in configuration
90     private final Map<String, Address> memberNameToAddress = new HashMap<>();
91
92     // Stores a mapping between a shard name and it's corresponding information
93     // Shard names look like inventory, topology etc and are as specified in
94     // configuration
95     private final Map<String, ShardInformation> localShards = new HashMap<>();
96
97     // The type of a ShardManager reflects the type of the datastore itself
98     // A data store could be of type config/operational
99     private final String type;
100
101     private final String shardManagerIdentifierString;
102
103     private final ClusterWrapper cluster;
104
105     private final Configuration configuration;
106
107     private final String shardDispatcherPath;
108
109     private ShardManagerInfo mBean;
110
111     private DatastoreContext datastoreContext;
112
113     private Collection<String> knownModules = Collections.emptySet();
114
115     private final DataPersistenceProvider dataPersistenceProvider;
116
117     private final CountDownLatch waitTillReadyCountdownLatch;
118
119     /**
120      */
121     protected ShardManager(ClusterWrapper cluster, Configuration configuration,
122             DatastoreContext datastoreContext, CountDownLatch waitTillReadyCountdownLatch) {
123
124         this.cluster = Preconditions.checkNotNull(cluster, "cluster should not be null");
125         this.configuration = Preconditions.checkNotNull(configuration, "configuration should not be null");
126         this.datastoreContext = datastoreContext;
127         this.dataPersistenceProvider = createDataPersistenceProvider(datastoreContext.isPersistent());
128         this.type = datastoreContext.getDataStoreType();
129         this.shardManagerIdentifierString = ShardManagerIdentifier.builder().type(type).build().toString();
130         this.shardDispatcherPath =
131                 new Dispatchers(context().system().dispatchers()).getDispatcherPath(Dispatchers.DispatcherType.Shard);
132         this.waitTillReadyCountdownLatch = waitTillReadyCountdownLatch;
133
134         // Subscribe this actor to cluster member events
135         cluster.subscribeToMemberEvents(getSelf());
136
137         createLocalShards();
138     }
139
140     protected DataPersistenceProvider createDataPersistenceProvider(boolean persistent) {
141         return (persistent) ? new PersistentDataProvider(this) : new NonPersistentDataProvider();
142     }
143
144     public static Props props(
145         final ClusterWrapper cluster,
146         final Configuration configuration,
147         final DatastoreContext datastoreContext,
148         final CountDownLatch waitTillReadyCountdownLatch) {
149
150         Preconditions.checkNotNull(cluster, "cluster should not be null");
151         Preconditions.checkNotNull(configuration, "configuration should not be null");
152         Preconditions.checkNotNull(waitTillReadyCountdownLatch, "waitTillReadyCountdownLatch should not be null");
153
154         return Props.create(new ShardManagerCreator(cluster, configuration, datastoreContext, waitTillReadyCountdownLatch));
155     }
156
157     @Override
158     public void postStop() {
159         LOG.info("Stopping ShardManager");
160
161         mBean.unregisterMBean();
162     }
163
164     @Override
165     public void handleCommand(Object message) throws Exception {
166         if (message  instanceof FindPrimary) {
167             findPrimary((FindPrimary)message);
168         } else if(message instanceof FindLocalShard){
169             findLocalShard((FindLocalShard) message);
170         } else if (message instanceof UpdateSchemaContext) {
171             updateSchemaContext(message);
172         } else if(message instanceof ActorInitialized) {
173             onActorInitialized(message);
174         } else if (message instanceof ClusterEvent.MemberUp){
175             memberUp((ClusterEvent.MemberUp) message);
176         } else if(message instanceof ClusterEvent.MemberRemoved) {
177             memberRemoved((ClusterEvent.MemberRemoved) message);
178         } else if(message instanceof ClusterEvent.UnreachableMember) {
179             ignoreMessage(message);
180         } else if(message instanceof DatastoreContext) {
181             onDatastoreContext((DatastoreContext)message);
182         } else if(message instanceof RoleChangeNotification) {
183             onRoleChangeNotification((RoleChangeNotification) message);
184         } else if(message instanceof FollowerInitialSyncUpStatus){
185             onFollowerInitialSyncStatus((FollowerInitialSyncUpStatus) message);
186         } else if(message instanceof ShardNotInitializedTimeout) {
187             onShardNotInitializedTimeout((ShardNotInitializedTimeout)message);
188         } else if(message instanceof LeaderStateChanged) {
189             onLeaderStateChanged((LeaderStateChanged)message);
190         } else {
191             unknownMessage(message);
192         }
193
194     }
195
196     private void onLeaderStateChanged(LeaderStateChanged leaderStateChanged) {
197         LOG.info("{}: Received LeaderStateChanged message: {}", persistenceId(), leaderStateChanged);
198
199         ShardInformation shardInformation = findShardInformation(leaderStateChanged.getMemberId());
200         if(shardInformation != null) {
201             shardInformation.setLeaderId(leaderStateChanged.getLeaderId());
202             if (isReadyWithLeaderId()) {
203                 LOG.info("{}: All Shards are ready - data store {} is ready, available count is {}",
204                         persistenceId(), type, waitTillReadyCountdownLatch.getCount());
205
206                 waitTillReadyCountdownLatch.countDown();
207             }
208
209         } else {
210             LOG.debug("No shard found with member Id {}", leaderStateChanged.getMemberId());
211         }
212     }
213
214     private void onShardNotInitializedTimeout(ShardNotInitializedTimeout message) {
215         ShardInformation shardInfo = message.getShardInfo();
216
217         LOG.debug("{}: Received ShardNotInitializedTimeout message for shard {}", persistenceId(),
218                 shardInfo.getShardName());
219
220         shardInfo.removeOnShardInitialized(message.getOnShardInitialized());
221
222         if(!shardInfo.isShardInitialized()) {
223             LOG.debug("{}: Returning NotInitializedException for shard {}", persistenceId(), shardInfo.getShardName());
224             message.getSender().tell(createNotInitializedException(shardInfo.shardId), getSelf());
225         } else {
226             LOG.debug("{}: Returning NoShardLeaderException for shard {}", persistenceId(), shardInfo.getShardName());
227             message.getSender().tell(createNoShardLeaderException(shardInfo.shardId), getSelf());
228         }
229     }
230
231     private void onFollowerInitialSyncStatus(FollowerInitialSyncUpStatus status) {
232         LOG.info("{} Received follower initial sync status for {} status sync done {}", persistenceId(),
233                 status.getName(), status.isInitialSyncDone());
234
235         ShardInformation shardInformation = findShardInformation(status.getName());
236
237         if(shardInformation != null) {
238             shardInformation.setFollowerSyncStatus(status.isInitialSyncDone());
239
240             mBean.setSyncStatus(isInSync());
241         }
242
243     }
244
245     private void onRoleChangeNotification(RoleChangeNotification roleChanged) {
246         LOG.info("{}: Received role changed for {} from {} to {}", persistenceId(), roleChanged.getMemberId(),
247                 roleChanged.getOldRole(), roleChanged.getNewRole());
248
249         ShardInformation shardInformation = findShardInformation(roleChanged.getMemberId());
250         if(shardInformation != null) {
251             shardInformation.setRole(roleChanged.getNewRole());
252
253             if (isReadyWithLeaderId()) {
254                 LOG.info("{}: All Shards are ready - data store {} is ready, available count is {}",
255                         persistenceId(), type, waitTillReadyCountdownLatch.getCount());
256
257                 waitTillReadyCountdownLatch.countDown();
258             }
259
260             mBean.setSyncStatus(isInSync());
261         }
262     }
263
264
265     private ShardInformation findShardInformation(String memberId) {
266         for(ShardInformation info : localShards.values()){
267             if(info.getShardId().toString().equals(memberId)){
268                 return info;
269             }
270         }
271
272         return null;
273     }
274
275     private boolean isReadyWithLeaderId() {
276         boolean isReady = true;
277         for (ShardInformation info : localShards.values()) {
278             if(!info.isShardReadyWithLeaderId()){
279                 isReady = false;
280                 break;
281             }
282         }
283         return isReady;
284     }
285
286     private boolean isInSync(){
287         for (ShardInformation info : localShards.values()) {
288             if(!info.isInSync()){
289                 return false;
290             }
291         }
292         return true;
293     }
294
295     private void onActorInitialized(Object message) {
296         final ActorRef sender = getSender();
297
298         if (sender == null) {
299             return; //why is a non-actor sending this message? Just ignore.
300         }
301
302         String actorName = sender.path().name();
303         //find shard name from actor name; actor name is stringified shardId
304         ShardIdentifier shardId = ShardIdentifier.builder().fromShardIdString(actorName).build();
305
306         if (shardId.getShardName() == null) {
307             return;
308         }
309
310         markShardAsInitialized(shardId.getShardName());
311     }
312
313     private void markShardAsInitialized(String shardName) {
314         LOG.debug("{}: Initializing shard [{}]", persistenceId(), shardName);
315
316         ShardInformation shardInformation = localShards.get(shardName);
317         if (shardInformation != null) {
318             shardInformation.setActorInitialized();
319
320             shardInformation.getActor().tell(new RegisterRoleChangeListener(), self());
321         }
322     }
323
324     @Override
325     protected void handleRecover(Object message) throws Exception {
326         if(dataPersistenceProvider.isRecoveryApplicable()) {
327             if (message instanceof SchemaContextModules) {
328                 SchemaContextModules msg = (SchemaContextModules) message;
329                 knownModules = ImmutableSet.copyOf(msg.getModules());
330             } else if (message instanceof RecoveryFailure) {
331                 RecoveryFailure failure = (RecoveryFailure) message;
332                 LOG.error("Recovery failed", failure.cause());
333             } else if (message instanceof RecoveryCompleted) {
334                 LOG.info("Recovery complete : {}", persistenceId());
335
336                 // Delete all the messages from the akka journal except the last one
337                 deleteMessages(lastSequenceNr() - 1);
338             }
339         } else {
340             if (message instanceof RecoveryCompleted) {
341                 LOG.info("Recovery complete : {}", persistenceId());
342
343                 // Delete all the messages from the akka journal
344                 deleteMessages(lastSequenceNr());
345             }
346         }
347     }
348
349     private void findLocalShard(FindLocalShard message) {
350         final ShardInformation shardInformation = localShards.get(message.getShardName());
351
352         if(shardInformation == null){
353             getSender().tell(new LocalShardNotFound(message.getShardName()), getSelf());
354             return;
355         }
356
357         sendResponse(shardInformation, message.isWaitUntilInitialized(), false, new Supplier<Object>() {
358             @Override
359             public Object get() {
360                 return new LocalShardFound(shardInformation.getActor());
361             }
362         });
363     }
364
365     private void sendResponse(ShardInformation shardInformation, boolean doWait,
366             boolean wantShardReady, final Supplier<Object> messageSupplier) {
367         if (!shardInformation.isShardInitialized() || (wantShardReady && !shardInformation.isShardReadyWithLeaderId())) {
368             if(doWait) {
369                 final ActorRef sender = getSender();
370                 final ActorRef self = self();
371
372                 Runnable replyRunnable = new Runnable() {
373                     @Override
374                     public void run() {
375                         sender.tell(messageSupplier.get(), self);
376                     }
377                 };
378
379                 OnShardInitialized onShardInitialized = wantShardReady ? new OnShardReady(replyRunnable) :
380                     new OnShardInitialized(replyRunnable);
381
382                 shardInformation.addOnShardInitialized(onShardInitialized);
383
384                 LOG.debug("{}: Scheduling timer to wait for shard {}", persistenceId(), shardInformation.getShardName());
385
386                 Cancellable timeoutSchedule = getContext().system().scheduler().scheduleOnce(
387                         datastoreContext.getShardInitializationTimeout().duration(), getSelf(),
388                         new ShardNotInitializedTimeout(shardInformation, onShardInitialized, sender),
389                         getContext().dispatcher(), getSelf());
390
391                 onShardInitialized.setTimeoutSchedule(timeoutSchedule);
392
393             } else if (!shardInformation.isShardInitialized()) {
394                 LOG.debug("{}: Returning NotInitializedException for shard {}", persistenceId(),
395                         shardInformation.getShardName());
396                 getSender().tell(createNotInitializedException(shardInformation.shardId), getSelf());
397             } else {
398                 LOG.debug("{}: Returning NoShardLeaderException for shard {}", persistenceId(),
399                         shardInformation.getShardName());
400                 getSender().tell(createNoShardLeaderException(shardInformation.shardId), getSelf());
401             }
402
403             return;
404         }
405
406         getSender().tell(messageSupplier.get(), getSelf());
407     }
408
409     private NoShardLeaderException createNoShardLeaderException(ShardIdentifier shardId) {
410         return new NoShardLeaderException(String.format(
411                 "Could not find a leader for shard %s. This typically happens when the system is coming up or " +
412                 "recovering and a leader is being elected. Try again later.", shardId));
413     }
414
415     private NotInitializedException createNotInitializedException(ShardIdentifier shardId) {
416         return new NotInitializedException(String.format(
417                 "Found primary shard %s but it's not initialized yet. Please try again later", shardId));
418     }
419
420     private void memberRemoved(ClusterEvent.MemberRemoved message) {
421         String memberName = message.member().roles().head();
422
423         LOG.debug("{}: Received MemberRemoved: memberName: {}, address: {}", persistenceId(), memberName,
424                 message.member().address());
425
426         memberNameToAddress.remove(message.member().roles().head());
427     }
428
429     private void memberUp(ClusterEvent.MemberUp message) {
430         String memberName = message.member().roles().head();
431
432         LOG.debug("{}: Received MemberUp: memberName: {}, address: {}", persistenceId(), memberName,
433                 message.member().address());
434
435         memberNameToAddress.put(memberName, message.member().address());
436
437         for(ShardInformation info : localShards.values()){
438             String shardName = info.getShardName();
439             info.updatePeerAddress(getShardIdentifier(memberName, shardName).toString(),
440                 getShardActorPath(shardName, memberName), getSelf());
441         }
442     }
443
444     private void onDatastoreContext(DatastoreContext context) {
445         datastoreContext = context;
446         for (ShardInformation info : localShards.values()) {
447             if (info.getActor() != null) {
448                 info.getActor().tell(datastoreContext, getSelf());
449             }
450         }
451     }
452
453     /**
454      * Notifies all the local shards of a change in the schema context
455      *
456      * @param message
457      */
458     private void updateSchemaContext(final Object message) {
459         final SchemaContext schemaContext = ((UpdateSchemaContext) message).getSchemaContext();
460
461         Set<ModuleIdentifier> allModuleIdentifiers = schemaContext.getAllModuleIdentifiers();
462         Set<String> newModules = new HashSet<>(128);
463
464         for(ModuleIdentifier moduleIdentifier : allModuleIdentifiers){
465             String s = moduleIdentifier.getNamespace().toString();
466             newModules.add(s);
467         }
468
469         if(newModules.containsAll(knownModules)) {
470
471             LOG.debug("New SchemaContext has a super set of current knownModules - persisting info");
472
473             knownModules = ImmutableSet.copyOf(newModules);
474
475             dataPersistenceProvider.persist(new SchemaContextModules(newModules), new Procedure<SchemaContextModules>() {
476
477                 @Override
478                 public void apply(SchemaContextModules param) throws Exception {
479                     LOG.debug("Sending new SchemaContext to Shards");
480                     for (ShardInformation info : localShards.values()) {
481                         if (info.getActor() == null) {
482                             info.setActor(newShardActor(schemaContext, info));
483                         } else {
484                             info.getActor().tell(message, getSelf());
485                         }
486                     }
487                 }
488
489             });
490         } else {
491             LOG.debug("Rejecting schema context update - not a super set of previously known modules:\nUPDATE: {}\nKNOWN: {}",
492                     newModules, knownModules);
493         }
494
495     }
496
497     @VisibleForTesting
498     protected ClusterWrapper getCluster() {
499         return cluster;
500     }
501
502     @VisibleForTesting
503     protected ActorRef newShardActor(final SchemaContext schemaContext, ShardInformation info) {
504         return getContext().actorOf(Shard.props(info.getShardId(),
505                 info.getPeerAddresses(), datastoreContext, schemaContext)
506                         .withDispatcher(shardDispatcherPath), info.getShardId().toString());
507     }
508
509     private void findPrimary(FindPrimary message) {
510         LOG.debug("{}: In findPrimary: {}", persistenceId(), message);
511
512         final String shardName = message.getShardName();
513
514         // First see if the there is a local replica for the shard
515         final ShardInformation info = localShards.get(shardName);
516         if (info != null) {
517             sendResponse(info, message.isWaitUntilReady(), true, new Supplier<Object>() {
518                 @Override
519                 public Object get() {
520                     Object found = new PrimaryFound(info.getSerializedLeaderActor());
521
522                     if(LOG.isDebugEnabled()) {
523                         LOG.debug("{}: Found primary for {}: {}", persistenceId(), shardName, found);
524                     }
525
526                     return found;
527                 }
528             });
529
530             return;
531         }
532
533         for(Map.Entry<String, Address> entry: memberNameToAddress.entrySet()) {
534             if(!cluster.getCurrentMemberName().equals(entry.getKey())) {
535                 String path = getShardManagerActorPathBuilder(entry.getValue()).toString();
536
537                 LOG.debug("{}: findPrimary for {} forwarding to remote ShardManager {}", persistenceId(),
538                         shardName, path);
539
540                 getContext().actorSelection(path).forward(message, getContext());
541                 return;
542             }
543         }
544
545         LOG.debug("{}: No shard found for {}", persistenceId(), shardName);
546
547         getSender().tell(new PrimaryNotFoundException(
548                 String.format("No primary shard found for %s.", shardName)), getSelf());
549     }
550
551     private StringBuilder getShardManagerActorPathBuilder(Address address) {
552         StringBuilder builder = new StringBuilder();
553         builder.append(address.toString()).append("/user/").append(shardManagerIdentifierString);
554         return builder;
555     }
556
557     private String getShardActorPath(String shardName, String memberName) {
558         Address address = memberNameToAddress.get(memberName);
559         if(address != null) {
560             StringBuilder builder = getShardManagerActorPathBuilder(address);
561             builder.append("/")
562                 .append(getShardIdentifier(memberName, shardName));
563             return builder.toString();
564         }
565         return null;
566     }
567
568     /**
569      * Construct the name of the shard actor given the name of the member on
570      * which the shard resides and the name of the shard
571      *
572      * @param memberName
573      * @param shardName
574      * @return
575      */
576     private ShardIdentifier getShardIdentifier(String memberName, String shardName){
577         return ShardIdentifier.builder().memberName(memberName).shardName(shardName).type(type).build();
578     }
579
580     /**
581      * Create shards that are local to the member on which the ShardManager
582      * runs
583      *
584      */
585     private void createLocalShards() {
586         String memberName = this.cluster.getCurrentMemberName();
587         List<String> memberShardNames =
588             this.configuration.getMemberShardNames(memberName);
589
590         List<String> localShardActorNames = new ArrayList<>();
591         for(String shardName : memberShardNames){
592             ShardIdentifier shardId = getShardIdentifier(memberName, shardName);
593             Map<String, String> peerAddresses = getPeerAddresses(shardName);
594             localShardActorNames.add(shardId.toString());
595             localShards.put(shardName, new ShardInformation(shardName, shardId, peerAddresses));
596         }
597
598         mBean = ShardManagerInfo.createShardManagerMBean("shard-manager-" + this.type,
599                     datastoreContext.getDataStoreMXBeanType(), localShardActorNames);
600     }
601
602     /**
603      * Given the name of the shard find the addresses of all it's peers
604      *
605      * @param shardName
606      * @return
607      */
608     private Map<String, String> getPeerAddresses(String shardName){
609
610         Map<String, String> peerAddresses = new HashMap<>();
611
612         List<String> members = this.configuration.getMembersFromShardName(shardName);
613
614         String currentMemberName = this.cluster.getCurrentMemberName();
615
616         for(String memberName : members){
617             if(!currentMemberName.equals(memberName)){
618                 ShardIdentifier shardId = getShardIdentifier(memberName, shardName);
619                 String path = getShardActorPath(shardName, currentMemberName);
620                 peerAddresses.put(shardId.toString(), path);
621             }
622         }
623         return peerAddresses;
624     }
625
626     @Override
627     public SupervisorStrategy supervisorStrategy() {
628
629         return new OneForOneStrategy(10, Duration.create("1 minute"),
630             new Function<Throwable, SupervisorStrategy.Directive>() {
631                 @Override
632                 public SupervisorStrategy.Directive apply(Throwable t) {
633                     LOG.warn("Supervisor Strategy caught unexpected exception - resuming", t);
634                     return SupervisorStrategy.resume();
635                 }
636             }
637         );
638
639     }
640
641     @Override
642     public String persistenceId() {
643         return "shard-manager-" + type;
644     }
645
646     @VisibleForTesting
647     Collection<String> getKnownModules() {
648         return knownModules;
649     }
650
651     @VisibleForTesting
652     DataPersistenceProvider getDataPersistenceProvider() {
653         return dataPersistenceProvider;
654     }
655
656     @VisibleForTesting
657     ShardManagerInfoMBean getMBean(){
658         return mBean;
659     }
660
661     @VisibleForTesting
662     protected static class ShardInformation {
663         private final ShardIdentifier shardId;
664         private final String shardName;
665         private ActorRef actor;
666         private ActorPath actorPath;
667         private final Map<String, String> peerAddresses;
668
669         // flag that determines if the actor is ready for business
670         private boolean actorInitialized = false;
671
672         private boolean followerSyncStatus = false;
673
674         private final Set<OnShardInitialized> onShardInitializedSet = Sets.newHashSet();
675         private String role ;
676         private String leaderId;
677
678         private ShardInformation(String shardName, ShardIdentifier shardId,
679                 Map<String, String> peerAddresses) {
680             this.shardName = shardName;
681             this.shardId = shardId;
682             this.peerAddresses = peerAddresses;
683         }
684
685         String getShardName() {
686             return shardName;
687         }
688
689         ActorRef getActor(){
690             return actor;
691         }
692
693         ActorPath getActorPath() {
694             return actorPath;
695         }
696
697         void setActor(ActorRef actor) {
698             this.actor = actor;
699             this.actorPath = actor.path();
700         }
701
702         ShardIdentifier getShardId() {
703             return shardId;
704         }
705
706         Map<String, String> getPeerAddresses() {
707             return peerAddresses;
708         }
709
710         void updatePeerAddress(String peerId, String peerAddress, ActorRef sender){
711             LOG.info("updatePeerAddress for peer {} with address {}", peerId,
712                 peerAddress);
713             if(peerAddresses.containsKey(peerId)){
714                 peerAddresses.put(peerId, peerAddress);
715
716                 if(actor != null) {
717                     if(LOG.isDebugEnabled()) {
718                         LOG.debug("Sending PeerAddressResolved for peer {} with address {} to {}",
719                                 peerId, peerAddress, actor.path());
720                     }
721
722                     actor.tell(new PeerAddressResolved(peerId.toString(), peerAddress), sender);
723                 }
724
725                 notifyOnShardInitializedCallbacks();
726             }
727         }
728
729         boolean isShardReady() {
730             return !RaftState.Candidate.name().equals(role) && !Strings.isNullOrEmpty(role);
731         }
732
733         boolean isShardReadyWithLeaderId() {
734             return isShardReady() && (isLeader() || peerAddresses.containsKey(leaderId));
735         }
736
737         boolean isShardInitialized() {
738             return getActor() != null && actorInitialized;
739         }
740
741         boolean isLeader() {
742             return Objects.equal(leaderId, shardId.toString());
743         }
744
745         String getSerializedLeaderActor() {
746             if(isLeader()) {
747                 return Serialization.serializedActorPath(getActor());
748             } else {
749                 return peerAddresses.get(leaderId);
750             }
751         }
752
753         void setActorInitialized() {
754             LOG.debug("Shard {} is initialized", shardId);
755
756             this.actorInitialized = true;
757
758             notifyOnShardInitializedCallbacks();
759         }
760
761         private void notifyOnShardInitializedCallbacks() {
762             if(onShardInitializedSet.isEmpty()) {
763                 return;
764             }
765
766             boolean ready = isShardReadyWithLeaderId();
767
768             if(LOG.isDebugEnabled()) {
769                 LOG.debug("Shard {} is {} - notifying {} OnShardInitialized callbacks", shardId,
770                         ready ? "ready" : "initialized", onShardInitializedSet.size());
771             }
772
773             Iterator<OnShardInitialized> iter = onShardInitializedSet.iterator();
774             while(iter.hasNext()) {
775                 OnShardInitialized onShardInitialized = iter.next();
776                 if(!(onShardInitialized instanceof OnShardReady) || ready) {
777                     iter.remove();
778                     onShardInitialized.getTimeoutSchedule().cancel();
779                     onShardInitialized.getReplyRunnable().run();
780                 }
781             }
782         }
783
784         void addOnShardInitialized(OnShardInitialized onShardInitialized) {
785             onShardInitializedSet.add(onShardInitialized);
786         }
787
788         void removeOnShardInitialized(OnShardInitialized onShardInitialized) {
789             onShardInitializedSet.remove(onShardInitialized);
790         }
791
792         void setRole(String newRole) {
793             this.role = newRole;
794
795             notifyOnShardInitializedCallbacks();
796         }
797
798         void setFollowerSyncStatus(boolean syncStatus){
799             this.followerSyncStatus = syncStatus;
800         }
801
802         boolean isInSync(){
803             if(RaftState.Follower.name().equals(this.role)){
804                 return followerSyncStatus;
805             } else if(RaftState.Leader.name().equals(this.role)){
806                 return true;
807             }
808
809             return false;
810         }
811
812         void setLeaderId(String leaderId) {
813             this.leaderId = leaderId;
814
815             notifyOnShardInitializedCallbacks();
816         }
817     }
818
819     private static class ShardManagerCreator implements Creator<ShardManager> {
820         private static final long serialVersionUID = 1L;
821
822         final ClusterWrapper cluster;
823         final Configuration configuration;
824         final DatastoreContext datastoreContext;
825         private final CountDownLatch waitTillReadyCountdownLatch;
826
827         ShardManagerCreator(ClusterWrapper cluster,
828                             Configuration configuration, DatastoreContext datastoreContext, CountDownLatch waitTillReadyCountdownLatch) {
829             this.cluster = cluster;
830             this.configuration = configuration;
831             this.datastoreContext = datastoreContext;
832             this.waitTillReadyCountdownLatch = waitTillReadyCountdownLatch;
833         }
834
835         @Override
836         public ShardManager create() throws Exception {
837             return new ShardManager(cluster, configuration, datastoreContext, waitTillReadyCountdownLatch);
838         }
839     }
840
841     private static class OnShardInitialized {
842         private final Runnable replyRunnable;
843         private Cancellable timeoutSchedule;
844
845         OnShardInitialized(Runnable replyRunnable) {
846             this.replyRunnable = replyRunnable;
847         }
848
849         Runnable getReplyRunnable() {
850             return replyRunnable;
851         }
852
853         Cancellable getTimeoutSchedule() {
854             return timeoutSchedule;
855         }
856
857         void setTimeoutSchedule(Cancellable timeoutSchedule) {
858             this.timeoutSchedule = timeoutSchedule;
859         }
860     }
861
862     private static class OnShardReady extends OnShardInitialized {
863         OnShardReady(Runnable replyRunnable) {
864             super(replyRunnable);
865         }
866     }
867
868     private static class ShardNotInitializedTimeout {
869         private final ActorRef sender;
870         private final ShardInformation shardInfo;
871         private final OnShardInitialized onShardInitialized;
872
873         ShardNotInitializedTimeout(ShardInformation shardInfo, OnShardInitialized onShardInitialized, ActorRef sender) {
874             this.sender = sender;
875             this.shardInfo = shardInfo;
876             this.onShardInitialized = onShardInitialized;
877         }
878
879         ActorRef getSender() {
880             return sender;
881         }
882
883         ShardInformation getShardInfo() {
884             return shardInfo;
885         }
886
887         OnShardInitialized getOnShardInitialized() {
888             return onShardInitialized;
889         }
890     }
891
892     static class SchemaContextModules implements Serializable {
893         private static final long serialVersionUID = -8884620101025936590L;
894
895         private final Set<String> modules;
896
897         SchemaContextModules(Set<String> modules){
898             this.modules = modules;
899         }
900
901         public Set<String> getModules() {
902             return modules;
903         }
904     }
905 }
906
907
908