Bug 4105: Pass ModuleShardConfiguration with CreateShard
[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.persistence.RecoveryCompleted;
22 import akka.serialization.Serialization;
23 import com.google.common.annotations.VisibleForTesting;
24 import com.google.common.base.Objects;
25 import com.google.common.base.Optional;
26 import com.google.common.base.Preconditions;
27 import com.google.common.base.Strings;
28 import com.google.common.base.Supplier;
29 import com.google.common.collect.Sets;
30 import java.io.Serializable;
31 import java.util.ArrayList;
32 import java.util.Collection;
33 import java.util.HashMap;
34 import java.util.Iterator;
35 import java.util.List;
36 import java.util.Map;
37 import java.util.Set;
38 import java.util.concurrent.CountDownLatch;
39 import java.util.concurrent.TimeUnit;
40 import org.opendaylight.controller.cluster.common.actor.AbstractUntypedPersistentActorWithMetering;
41 import org.opendaylight.controller.cluster.datastore.config.Configuration;
42 import org.opendaylight.controller.cluster.datastore.config.ModuleShardConfiguration;
43 import org.opendaylight.controller.cluster.datastore.exceptions.NoShardLeaderException;
44 import org.opendaylight.controller.cluster.datastore.exceptions.NotInitializedException;
45 import org.opendaylight.controller.cluster.datastore.exceptions.PrimaryNotFoundException;
46 import org.opendaylight.controller.cluster.datastore.identifiers.ShardIdentifier;
47 import org.opendaylight.controller.cluster.datastore.identifiers.ShardManagerIdentifier;
48 import org.opendaylight.controller.cluster.datastore.jmx.mbeans.shardmanager.ShardManagerInfo;
49 import org.opendaylight.controller.cluster.datastore.jmx.mbeans.shardmanager.ShardManagerInfoMBean;
50 import org.opendaylight.controller.cluster.datastore.messages.ActorInitialized;
51 import org.opendaylight.controller.cluster.datastore.messages.CreateShard;
52 import org.opendaylight.controller.cluster.datastore.messages.CreateShardReply;
53 import org.opendaylight.controller.cluster.datastore.messages.FindLocalShard;
54 import org.opendaylight.controller.cluster.datastore.messages.FindPrimary;
55 import org.opendaylight.controller.cluster.datastore.messages.LocalPrimaryShardFound;
56 import org.opendaylight.controller.cluster.datastore.messages.LocalShardFound;
57 import org.opendaylight.controller.cluster.datastore.messages.LocalShardNotFound;
58 import org.opendaylight.controller.cluster.datastore.messages.PeerAddressResolved;
59 import org.opendaylight.controller.cluster.datastore.messages.PeerDown;
60 import org.opendaylight.controller.cluster.datastore.messages.PeerUp;
61 import org.opendaylight.controller.cluster.datastore.messages.RemoteFindPrimary;
62 import org.opendaylight.controller.cluster.datastore.messages.RemotePrimaryShardFound;
63 import org.opendaylight.controller.cluster.datastore.messages.ShardLeaderStateChanged;
64 import org.opendaylight.controller.cluster.datastore.messages.SwitchShardBehavior;
65 import org.opendaylight.controller.cluster.datastore.messages.UpdateSchemaContext;
66 import org.opendaylight.controller.cluster.datastore.utils.Dispatchers;
67 import org.opendaylight.controller.cluster.datastore.utils.PrimaryShardInfoFutureCache;
68 import org.opendaylight.controller.cluster.notifications.RegisterRoleChangeListener;
69 import org.opendaylight.controller.cluster.notifications.RoleChangeNotification;
70 import org.opendaylight.controller.cluster.raft.RaftState;
71 import org.opendaylight.controller.cluster.raft.base.messages.FollowerInitialSyncUpStatus;
72 import org.opendaylight.controller.cluster.raft.base.messages.SwitchBehavior;
73 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTree;
74 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
75 import org.slf4j.Logger;
76 import org.slf4j.LoggerFactory;
77 import scala.concurrent.duration.Duration;
78 import scala.concurrent.duration.FiniteDuration;
79
80 /**
81  * The ShardManager has the following jobs,
82  * <ul>
83  * <li> Create all the local shard replicas that belong on this cluster member
84  * <li> Find the address of the local shard
85  * <li> Find the primary replica for any given shard
86  * <li> Monitor the cluster members and store their addresses
87  * <ul>
88  */
89 public class ShardManager extends AbstractUntypedPersistentActorWithMetering {
90
91     private static final Logger LOG = LoggerFactory.getLogger(ShardManager.class);
92
93     // Stores a mapping between a member name and the address of the member
94     // Member names look like "member-1", "member-2" etc and are as specified
95     // in configuration
96     private final Map<String, Address> memberNameToAddress = new HashMap<>();
97
98     // Stores a mapping between a shard name and it's corresponding information
99     // Shard names look like inventory, topology etc and are as specified in
100     // configuration
101     private final Map<String, ShardInformation> localShards = new HashMap<>();
102
103     // The type of a ShardManager reflects the type of the datastore itself
104     // A data store could be of type config/operational
105     private final String type;
106
107     private final String shardManagerIdentifierString;
108
109     private final ClusterWrapper cluster;
110
111     private final Configuration configuration;
112
113     private final String shardDispatcherPath;
114
115     private ShardManagerInfo mBean;
116
117     private DatastoreContext datastoreContext;
118
119     private final CountDownLatch waitTillReadyCountdownLatch;
120
121     private final PrimaryShardInfoFutureCache primaryShardInfoCache;
122
123     private SchemaContext schemaContext;
124
125     /**
126      */
127     protected ShardManager(ClusterWrapper cluster, Configuration configuration,
128             DatastoreContext datastoreContext, CountDownLatch waitTillReadyCountdownLatch,
129             PrimaryShardInfoFutureCache primaryShardInfoCache) {
130
131         this.cluster = Preconditions.checkNotNull(cluster, "cluster should not be null");
132         this.configuration = Preconditions.checkNotNull(configuration, "configuration should not be null");
133         this.datastoreContext = datastoreContext;
134         this.type = datastoreContext.getDataStoreType();
135         this.shardManagerIdentifierString = ShardManagerIdentifier.builder().type(type).build().toString();
136         this.shardDispatcherPath =
137                 new Dispatchers(context().system().dispatchers()).getDispatcherPath(Dispatchers.DispatcherType.Shard);
138         this.waitTillReadyCountdownLatch = waitTillReadyCountdownLatch;
139         this.primaryShardInfoCache = primaryShardInfoCache;
140
141         // Subscribe this actor to cluster member events
142         cluster.subscribeToMemberEvents(getSelf());
143
144         createLocalShards();
145     }
146
147     public static Props props(
148         final ClusterWrapper cluster,
149         final Configuration configuration,
150         final DatastoreContext datastoreContext,
151         final CountDownLatch waitTillReadyCountdownLatch,
152         final PrimaryShardInfoFutureCache primaryShardInfoCache) {
153
154         Preconditions.checkNotNull(cluster, "cluster should not be null");
155         Preconditions.checkNotNull(configuration, "configuration should not be null");
156         Preconditions.checkNotNull(waitTillReadyCountdownLatch, "waitTillReadyCountdownLatch should not be null");
157         Preconditions.checkNotNull(primaryShardInfoCache, "primaryShardInfoCache should not be null");
158
159         return Props.create(new ShardManagerCreator(cluster, configuration, datastoreContext,
160                 waitTillReadyCountdownLatch, primaryShardInfoCache));
161     }
162
163     @Override
164     public void postStop() {
165         LOG.info("Stopping ShardManager");
166
167         mBean.unregisterMBean();
168     }
169
170     @Override
171     public void handleCommand(Object message) throws Exception {
172         if (message  instanceof FindPrimary) {
173             findPrimary((FindPrimary)message);
174         } else if(message instanceof FindLocalShard){
175             findLocalShard((FindLocalShard) message);
176         } else if (message instanceof UpdateSchemaContext) {
177             updateSchemaContext(message);
178         } else if(message instanceof ActorInitialized) {
179             onActorInitialized(message);
180         } else if (message instanceof ClusterEvent.MemberUp){
181             memberUp((ClusterEvent.MemberUp) message);
182         } else if (message instanceof ClusterEvent.MemberExited){
183             memberExited((ClusterEvent.MemberExited) message);
184         } else if(message instanceof ClusterEvent.MemberRemoved) {
185             memberRemoved((ClusterEvent.MemberRemoved) message);
186         } else if(message instanceof ClusterEvent.UnreachableMember) {
187             memberUnreachable((ClusterEvent.UnreachableMember)message);
188         } else if(message instanceof ClusterEvent.ReachableMember) {
189             memberReachable((ClusterEvent.ReachableMember) message);
190         } else if(message instanceof DatastoreContext) {
191             onDatastoreContext((DatastoreContext)message);
192         } else if(message instanceof RoleChangeNotification) {
193             onRoleChangeNotification((RoleChangeNotification) message);
194         } else if(message instanceof FollowerInitialSyncUpStatus){
195             onFollowerInitialSyncStatus((FollowerInitialSyncUpStatus) message);
196         } else if(message instanceof ShardNotInitializedTimeout) {
197             onShardNotInitializedTimeout((ShardNotInitializedTimeout)message);
198         } else if(message instanceof ShardLeaderStateChanged) {
199             onLeaderStateChanged((ShardLeaderStateChanged) message);
200         } else if(message instanceof SwitchShardBehavior){
201             onSwitchShardBehavior((SwitchShardBehavior) message);
202         } else if(message instanceof CreateShard) {
203             onCreateShard((CreateShard)message);
204         } else {
205             unknownMessage(message);
206         }
207
208     }
209
210     private void onCreateShard(CreateShard createShard) {
211         Object reply;
212         try {
213             ModuleShardConfiguration moduleShardConfig = createShard.getModuleShardConfig();
214             if(localShards.containsKey(moduleShardConfig.getShardName())) {
215                 throw new IllegalStateException(String.format("Shard with name %s already exists",
216                         moduleShardConfig.getShardName()));
217             }
218
219             configuration.addModuleShardConfiguration(moduleShardConfig);
220
221             ShardIdentifier shardId = getShardIdentifier(cluster.getCurrentMemberName(), moduleShardConfig.getShardName());
222             Map<String, String> peerAddresses = getPeerAddresses(moduleShardConfig.getShardName()/*,
223                     moduleShardConfig.getShardMemberNames()*/);
224
225             LOG.debug("onCreateShard: shardId: {}, memberNames: {}. peerAddresses: {}", shardId,
226                     moduleShardConfig.getShardMemberNames(), peerAddresses);
227
228             DatastoreContext shardDatastoreContext = createShard.getDatastoreContext();
229             if(shardDatastoreContext == null) {
230                 shardDatastoreContext = datastoreContext;
231             }
232
233             ShardInformation info = new ShardInformation(moduleShardConfig.getShardName(), shardId, peerAddresses,
234                     shardDatastoreContext, createShard.getShardPropsCreator());
235             localShards.put(info.getShardName(), info);
236
237             mBean.addLocalShard(shardId.toString());
238
239             if(schemaContext != null) {
240                 info.setActor(newShardActor(schemaContext, info));
241             }
242
243             reply = new CreateShardReply();
244         } catch (Exception e) {
245             LOG.error("onCreateShard failed", e);
246             reply = new akka.actor.Status.Failure(e);
247         }
248
249         if(getSender() != null && !getContext().system().deadLetters().equals(getSender())) {
250             getSender().tell(reply, getSelf());
251         }
252     }
253
254     private void checkReady(){
255         if (isReadyWithLeaderId()) {
256             LOG.info("{}: All Shards are ready - data store {} is ready, available count is {}",
257                     persistenceId(), type, waitTillReadyCountdownLatch.getCount());
258
259             waitTillReadyCountdownLatch.countDown();
260         }
261     }
262
263     private void onLeaderStateChanged(ShardLeaderStateChanged leaderStateChanged) {
264         LOG.info("{}: Received LeaderStateChanged message: {}", persistenceId(), leaderStateChanged);
265
266         ShardInformation shardInformation = findShardInformation(leaderStateChanged.getMemberId());
267         if(shardInformation != null) {
268             shardInformation.setLocalDataTree(leaderStateChanged.getLocalShardDataTree());
269             shardInformation.setLeaderVersion(leaderStateChanged.getLeaderPayloadVersion());
270             if(shardInformation.setLeaderId(leaderStateChanged.getLeaderId())) {
271                 primaryShardInfoCache.remove(shardInformation.getShardName());
272             }
273
274             checkReady();
275         } else {
276             LOG.debug("No shard found with member Id {}", leaderStateChanged.getMemberId());
277         }
278     }
279
280     private void onShardNotInitializedTimeout(ShardNotInitializedTimeout message) {
281         ShardInformation shardInfo = message.getShardInfo();
282
283         LOG.debug("{}: Received ShardNotInitializedTimeout message for shard {}", persistenceId(),
284                 shardInfo.getShardName());
285
286         shardInfo.removeOnShardInitialized(message.getOnShardInitialized());
287
288         if(!shardInfo.isShardInitialized()) {
289             LOG.debug("{}: Returning NotInitializedException for shard {}", persistenceId(), shardInfo.getShardName());
290             message.getSender().tell(createNotInitializedException(shardInfo.shardId), getSelf());
291         } else {
292             LOG.debug("{}: Returning NoShardLeaderException for shard {}", persistenceId(), shardInfo.getShardName());
293             message.getSender().tell(createNoShardLeaderException(shardInfo.shardId), getSelf());
294         }
295     }
296
297     private void onFollowerInitialSyncStatus(FollowerInitialSyncUpStatus status) {
298         LOG.info("{} Received follower initial sync status for {} status sync done {}", persistenceId(),
299                 status.getName(), status.isInitialSyncDone());
300
301         ShardInformation shardInformation = findShardInformation(status.getName());
302
303         if(shardInformation != null) {
304             shardInformation.setFollowerSyncStatus(status.isInitialSyncDone());
305
306             mBean.setSyncStatus(isInSync());
307         }
308
309     }
310
311     private void onRoleChangeNotification(RoleChangeNotification roleChanged) {
312         LOG.info("{}: Received role changed for {} from {} to {}", persistenceId(), roleChanged.getMemberId(),
313                 roleChanged.getOldRole(), roleChanged.getNewRole());
314
315         ShardInformation shardInformation = findShardInformation(roleChanged.getMemberId());
316         if(shardInformation != null) {
317             shardInformation.setRole(roleChanged.getNewRole());
318             checkReady();
319             mBean.setSyncStatus(isInSync());
320         }
321     }
322
323
324     private ShardInformation findShardInformation(String memberId) {
325         for(ShardInformation info : localShards.values()){
326             if(info.getShardId().toString().equals(memberId)){
327                 return info;
328             }
329         }
330
331         return null;
332     }
333
334     private boolean isReadyWithLeaderId() {
335         boolean isReady = true;
336         for (ShardInformation info : localShards.values()) {
337             if(!info.isShardReadyWithLeaderId()){
338                 isReady = false;
339                 break;
340             }
341         }
342         return isReady;
343     }
344
345     private boolean isInSync(){
346         for (ShardInformation info : localShards.values()) {
347             if(!info.isInSync()){
348                 return false;
349             }
350         }
351         return true;
352     }
353
354     private void onActorInitialized(Object message) {
355         final ActorRef sender = getSender();
356
357         if (sender == null) {
358             return; //why is a non-actor sending this message? Just ignore.
359         }
360
361         String actorName = sender.path().name();
362         //find shard name from actor name; actor name is stringified shardId
363         ShardIdentifier shardId = ShardIdentifier.builder().fromShardIdString(actorName).build();
364
365         if (shardId.getShardName() == null) {
366             return;
367         }
368
369         markShardAsInitialized(shardId.getShardName());
370     }
371
372     private void markShardAsInitialized(String shardName) {
373         LOG.debug("{}: Initializing shard [{}]", persistenceId(), shardName);
374
375         ShardInformation shardInformation = localShards.get(shardName);
376         if (shardInformation != null) {
377             shardInformation.setActorInitialized();
378
379             shardInformation.getActor().tell(new RegisterRoleChangeListener(), self());
380         }
381     }
382
383     @Override
384     protected void handleRecover(Object message) throws Exception {
385         if (message instanceof RecoveryCompleted) {
386             LOG.info("Recovery complete : {}", persistenceId());
387
388             // We no longer persist SchemaContext modules so delete all the prior messages from the akka
389             // journal on upgrade from Helium.
390             deleteMessages(lastSequenceNr());
391         }
392     }
393
394     private void findLocalShard(FindLocalShard message) {
395         final ShardInformation shardInformation = localShards.get(message.getShardName());
396
397         if(shardInformation == null){
398             getSender().tell(new LocalShardNotFound(message.getShardName()), getSelf());
399             return;
400         }
401
402         sendResponse(shardInformation, message.isWaitUntilInitialized(), false, new Supplier<Object>() {
403             @Override
404             public Object get() {
405                 return new LocalShardFound(shardInformation.getActor());
406             }
407         });
408     }
409
410     private void sendResponse(ShardInformation shardInformation, boolean doWait,
411             boolean wantShardReady, final Supplier<Object> messageSupplier) {
412         if (!shardInformation.isShardInitialized() || (wantShardReady && !shardInformation.isShardReadyWithLeaderId())) {
413             if(doWait) {
414                 final ActorRef sender = getSender();
415                 final ActorRef self = self();
416
417                 Runnable replyRunnable = new Runnable() {
418                     @Override
419                     public void run() {
420                         sender.tell(messageSupplier.get(), self);
421                     }
422                 };
423
424                 OnShardInitialized onShardInitialized = wantShardReady ? new OnShardReady(replyRunnable) :
425                     new OnShardInitialized(replyRunnable);
426
427                 shardInformation.addOnShardInitialized(onShardInitialized);
428
429                 LOG.debug("{}: Scheduling timer to wait for shard {}", persistenceId(), shardInformation.getShardName());
430
431                 FiniteDuration timeout = datastoreContext.getShardInitializationTimeout().duration();
432                 if(shardInformation.isShardInitialized()) {
433                     // If the shard is already initialized then we'll wait enough time for the shard to
434                     // elect a leader, ie 2 times the election timeout.
435                     timeout = FiniteDuration.create(datastoreContext.getShardRaftConfig()
436                             .getElectionTimeOutInterval().toMillis() * 2, TimeUnit.MILLISECONDS);
437                 }
438
439                 Cancellable timeoutSchedule = getContext().system().scheduler().scheduleOnce(
440                         timeout, getSelf(),
441                         new ShardNotInitializedTimeout(shardInformation, onShardInitialized, sender),
442                         getContext().dispatcher(), getSelf());
443
444                 onShardInitialized.setTimeoutSchedule(timeoutSchedule);
445
446             } else if (!shardInformation.isShardInitialized()) {
447                 LOG.debug("{}: Returning NotInitializedException for shard {}", persistenceId(),
448                         shardInformation.getShardName());
449                 getSender().tell(createNotInitializedException(shardInformation.shardId), getSelf());
450             } else {
451                 LOG.debug("{}: Returning NoShardLeaderException for shard {}", persistenceId(),
452                         shardInformation.getShardName());
453                 getSender().tell(createNoShardLeaderException(shardInformation.shardId), getSelf());
454             }
455
456             return;
457         }
458
459         getSender().tell(messageSupplier.get(), getSelf());
460     }
461
462     private NoShardLeaderException createNoShardLeaderException(ShardIdentifier shardId) {
463         return new NoShardLeaderException(null, shardId.toString());
464     }
465
466     private NotInitializedException createNotInitializedException(ShardIdentifier shardId) {
467         return new NotInitializedException(String.format(
468                 "Found primary shard %s but it's not initialized yet. Please try again later", shardId));
469     }
470
471     private void memberRemoved(ClusterEvent.MemberRemoved message) {
472         String memberName = message.member().roles().head();
473
474         LOG.debug("{}: Received MemberRemoved: memberName: {}, address: {}", persistenceId(), memberName,
475                 message.member().address());
476
477         memberNameToAddress.remove(memberName);
478
479         for(ShardInformation info : localShards.values()){
480             info.peerDown(memberName, getShardIdentifier(memberName, info.getShardName()).toString(), getSelf());
481         }
482     }
483
484     private void memberExited(ClusterEvent.MemberExited message) {
485         String memberName = message.member().roles().head();
486
487         LOG.debug("{}: Received MemberExited: memberName: {}, address: {}", persistenceId(), memberName,
488                 message.member().address());
489
490         memberNameToAddress.remove(memberName);
491
492         for(ShardInformation info : localShards.values()){
493             info.peerDown(memberName, getShardIdentifier(memberName, info.getShardName()).toString(), getSelf());
494         }
495     }
496
497     private void memberUp(ClusterEvent.MemberUp message) {
498         String memberName = message.member().roles().head();
499
500         LOG.debug("{}: Received MemberUp: memberName: {}, address: {}", persistenceId(), memberName,
501                 message.member().address());
502
503         memberNameToAddress.put(memberName, message.member().address());
504
505         for(ShardInformation info : localShards.values()){
506             String shardName = info.getShardName();
507             String peerId = getShardIdentifier(memberName, shardName).toString();
508             info.updatePeerAddress(peerId, getShardActorPath(shardName, memberName), getSelf());
509
510             info.peerUp(memberName, peerId, getSelf());
511         }
512
513         checkReady();
514     }
515
516     private void memberReachable(ClusterEvent.ReachableMember message) {
517         String memberName = message.member().roles().head();
518         LOG.debug("Received ReachableMember: memberName {}, address: {}", memberName, message.member().address());
519
520         markMemberAvailable(memberName);
521     }
522
523     private void memberUnreachable(ClusterEvent.UnreachableMember message) {
524         String memberName = message.member().roles().head();
525         LOG.debug("Received UnreachableMember: memberName {}, address: {}", memberName, message.member().address());
526
527         markMemberUnavailable(memberName);
528     }
529
530     private void markMemberUnavailable(final String memberName) {
531         for(ShardInformation info : localShards.values()){
532             String leaderId = info.getLeaderId();
533             if(leaderId != null && leaderId.contains(memberName)) {
534                 LOG.debug("Marking Leader {} as unavailable.", leaderId);
535                 info.setLeaderAvailable(false);
536
537                 primaryShardInfoCache.remove(info.getShardName());
538             }
539
540             info.peerDown(memberName, getShardIdentifier(memberName, info.getShardName()).toString(), getSelf());
541         }
542     }
543
544     private void markMemberAvailable(final String memberName) {
545         for(ShardInformation info : localShards.values()){
546             String leaderId = info.getLeaderId();
547             if(leaderId != null && leaderId.contains(memberName)) {
548                 LOG.debug("Marking Leader {} as available.", leaderId);
549                 info.setLeaderAvailable(true);
550             }
551
552             info.peerUp(memberName, getShardIdentifier(memberName, info.getShardName()).toString(), getSelf());
553         }
554     }
555
556     private void onDatastoreContext(DatastoreContext context) {
557         datastoreContext = context;
558         for (ShardInformation info : localShards.values()) {
559             if (info.getActor() != null) {
560                 info.getActor().tell(datastoreContext, getSelf());
561             }
562         }
563     }
564
565     private void onSwitchShardBehavior(SwitchShardBehavior message) {
566         ShardIdentifier identifier = ShardIdentifier.builder().fromShardIdString(message.getShardName()).build();
567
568         ShardInformation shardInformation = localShards.get(identifier.getShardName());
569
570         if(shardInformation != null && shardInformation.getActor() != null) {
571             shardInformation.getActor().tell(
572                     new SwitchBehavior(RaftState.valueOf(message.getNewState()), message.getTerm()), getSelf());
573         } else {
574             LOG.warn("Could not switch the behavior of shard {} to {} - shard is not yet available",
575                     message.getShardName(), message.getNewState());
576         }
577     }
578
579     /**
580      * Notifies all the local shards of a change in the schema context
581      *
582      * @param message
583      */
584     private void updateSchemaContext(final Object message) {
585         schemaContext = ((UpdateSchemaContext) message).getSchemaContext();
586
587         LOG.debug("Got updated SchemaContext: # of modules {}", schemaContext.getAllModuleIdentifiers().size());
588
589         for (ShardInformation info : localShards.values()) {
590             if (info.getActor() == null) {
591                 LOG.debug("Creating Shard {}", info.getShardId());
592                 info.setActor(newShardActor(schemaContext, info));
593             } else {
594                 info.getActor().tell(message, getSelf());
595             }
596         }
597     }
598
599     @VisibleForTesting
600     protected ClusterWrapper getCluster() {
601         return cluster;
602     }
603
604     @VisibleForTesting
605     protected ActorRef newShardActor(final SchemaContext schemaContext, ShardInformation info) {
606         return getContext().actorOf(info.newProps(schemaContext)
607                         .withDispatcher(shardDispatcherPath), info.getShardId().toString());
608     }
609
610     private void findPrimary(FindPrimary message) {
611         LOG.debug("{}: In findPrimary: {}", persistenceId(), message);
612
613         final String shardName = message.getShardName();
614         final boolean canReturnLocalShardState = !(message instanceof RemoteFindPrimary);
615
616         // First see if the there is a local replica for the shard
617         final ShardInformation info = localShards.get(shardName);
618         if (info != null) {
619             sendResponse(info, message.isWaitUntilReady(), true, new Supplier<Object>() {
620                 @Override
621                 public Object get() {
622                     String primaryPath = info.getSerializedLeaderActor();
623                     Object found = canReturnLocalShardState && info.isLeader() ?
624                             new LocalPrimaryShardFound(primaryPath, info.getLocalShardDataTree().get()) :
625                                 new RemotePrimaryShardFound(primaryPath, info.getLeaderVersion());
626
627                     if(LOG.isDebugEnabled()) {
628                         LOG.debug("{}: Found primary for {}: {}", persistenceId(), shardName, found);
629                     }
630
631                     return found;
632                 }
633             });
634
635             return;
636         }
637
638         for(Map.Entry<String, Address> entry: memberNameToAddress.entrySet()) {
639             if(!cluster.getCurrentMemberName().equals(entry.getKey())) {
640                 String path = getShardManagerActorPathBuilder(entry.getValue()).toString();
641
642                 LOG.debug("{}: findPrimary for {} forwarding to remote ShardManager {}", persistenceId(),
643                         shardName, path);
644
645                 getContext().actorSelection(path).forward(new RemoteFindPrimary(shardName,
646                         message.isWaitUntilReady()), getContext());
647                 return;
648             }
649         }
650
651         LOG.debug("{}: No shard found for {}", persistenceId(), shardName);
652
653         getSender().tell(new PrimaryNotFoundException(
654                 String.format("No primary shard found for %s.", shardName)), getSelf());
655     }
656
657     private StringBuilder getShardManagerActorPathBuilder(Address address) {
658         StringBuilder builder = new StringBuilder();
659         builder.append(address.toString()).append("/user/").append(shardManagerIdentifierString);
660         return builder;
661     }
662
663     private String getShardActorPath(String shardName, String memberName) {
664         Address address = memberNameToAddress.get(memberName);
665         if(address != null) {
666             StringBuilder builder = getShardManagerActorPathBuilder(address);
667             builder.append("/")
668                 .append(getShardIdentifier(memberName, shardName));
669             return builder.toString();
670         }
671         return null;
672     }
673
674     /**
675      * Construct the name of the shard actor given the name of the member on
676      * which the shard resides and the name of the shard
677      *
678      * @param memberName
679      * @param shardName
680      * @return
681      */
682     private ShardIdentifier getShardIdentifier(String memberName, String shardName){
683         return ShardIdentifier.builder().memberName(memberName).shardName(shardName).type(type).build();
684     }
685
686     /**
687      * Create shards that are local to the member on which the ShardManager
688      * runs
689      *
690      */
691     private void createLocalShards() {
692         String memberName = this.cluster.getCurrentMemberName();
693         Collection<String> memberShardNames = this.configuration.getMemberShardNames(memberName);
694
695         ShardPropsCreator shardPropsCreator = new DefaultShardPropsCreator();
696         List<String> localShardActorNames = new ArrayList<>();
697         for(String shardName : memberShardNames){
698             ShardIdentifier shardId = getShardIdentifier(memberName, shardName);
699             Map<String, String> peerAddresses = getPeerAddresses(shardName);
700             localShardActorNames.add(shardId.toString());
701             localShards.put(shardName, new ShardInformation(shardName, shardId, peerAddresses, datastoreContext,
702                     shardPropsCreator));
703         }
704
705         mBean = ShardManagerInfo.createShardManagerMBean(memberName, "shard-manager-" + this.type,
706                     datastoreContext.getDataStoreMXBeanType(), localShardActorNames);
707
708         mBean.setShardManager(this);
709     }
710
711     /**
712      * Given the name of the shard find the addresses of all it's peers
713      *
714      * @param shardName
715      */
716     private Map<String, String> getPeerAddresses(String shardName) {
717         Collection<String> members = configuration.getMembersFromShardName(shardName);
718         Map<String, String> peerAddresses = new HashMap<>();
719
720         String currentMemberName = this.cluster.getCurrentMemberName();
721
722         for(String memberName : members) {
723             if(!currentMemberName.equals(memberName)) {
724                 ShardIdentifier shardId = getShardIdentifier(memberName, shardName);
725                 String path = getShardActorPath(shardName, memberName);
726                 peerAddresses.put(shardId.toString(), path);
727             }
728         }
729         return peerAddresses;
730     }
731
732     @Override
733     public SupervisorStrategy supervisorStrategy() {
734
735         return new OneForOneStrategy(10, Duration.create("1 minute"),
736             new Function<Throwable, SupervisorStrategy.Directive>() {
737                 @Override
738                 public SupervisorStrategy.Directive apply(Throwable t) {
739                     LOG.warn("Supervisor Strategy caught unexpected exception - resuming", t);
740                     return SupervisorStrategy.resume();
741                 }
742             }
743         );
744
745     }
746
747     @Override
748     public String persistenceId() {
749         return "shard-manager-" + type;
750     }
751
752     @VisibleForTesting
753     ShardManagerInfoMBean getMBean(){
754         return mBean;
755     }
756
757     @VisibleForTesting
758     protected static class ShardInformation {
759         private final ShardIdentifier shardId;
760         private final String shardName;
761         private ActorRef actor;
762         private ActorPath actorPath;
763         private final Map<String, String> peerAddresses;
764         private Optional<DataTree> localShardDataTree;
765         private boolean leaderAvailable = false;
766
767         // flag that determines if the actor is ready for business
768         private boolean actorInitialized = false;
769
770         private boolean followerSyncStatus = false;
771
772         private final Set<OnShardInitialized> onShardInitializedSet = Sets.newHashSet();
773         private String role ;
774         private String leaderId;
775         private short leaderVersion;
776
777         private final DatastoreContext datastoreContext;
778         private final ShardPropsCreator shardPropsCreator;
779
780         private ShardInformation(String shardName, ShardIdentifier shardId,
781                 Map<String, String> peerAddresses, DatastoreContext datastoreContext,
782                 ShardPropsCreator shardPropsCreator) {
783             this.shardName = shardName;
784             this.shardId = shardId;
785             this.peerAddresses = peerAddresses;
786             this.datastoreContext = datastoreContext;
787             this.shardPropsCreator = shardPropsCreator;
788         }
789
790         Props newProps(SchemaContext schemaContext) {
791             return shardPropsCreator.newProps(shardId, peerAddresses, datastoreContext, schemaContext);
792         }
793
794         String getShardName() {
795             return shardName;
796         }
797
798         ActorRef getActor(){
799             return actor;
800         }
801
802         ActorPath getActorPath() {
803             return actorPath;
804         }
805
806         void setActor(ActorRef actor) {
807             this.actor = actor;
808             this.actorPath = actor.path();
809         }
810
811         ShardIdentifier getShardId() {
812             return shardId;
813         }
814
815         void setLocalDataTree(Optional<DataTree> localShardDataTree) {
816             this.localShardDataTree = localShardDataTree;
817         }
818
819         Optional<DataTree> getLocalShardDataTree() {
820             return localShardDataTree;
821         }
822
823         Map<String, String> getPeerAddresses() {
824             return peerAddresses;
825         }
826
827         void updatePeerAddress(String peerId, String peerAddress, ActorRef sender){
828             LOG.info("updatePeerAddress for peer {} with address {}", peerId,
829                 peerAddress);
830             if(peerAddresses.containsKey(peerId)){
831                 peerAddresses.put(peerId, peerAddress);
832
833                 if(actor != null) {
834                     if(LOG.isDebugEnabled()) {
835                         LOG.debug("Sending PeerAddressResolved for peer {} with address {} to {}",
836                                 peerId, peerAddress, actor.path());
837                     }
838
839                     actor.tell(new PeerAddressResolved(peerId, peerAddress), sender);
840                 }
841
842                 notifyOnShardInitializedCallbacks();
843             }
844         }
845
846         void peerDown(String memberName, String peerId, ActorRef sender) {
847             if(peerAddresses.containsKey(peerId) && actor != null) {
848                 actor.tell(new PeerDown(memberName, peerId), sender);
849             }
850         }
851
852         void peerUp(String memberName, String peerId, ActorRef sender) {
853             if(peerAddresses.containsKey(peerId) && actor != null) {
854                 actor.tell(new PeerUp(memberName, peerId), sender);
855             }
856         }
857
858         boolean isShardReady() {
859             return !RaftState.Candidate.name().equals(role) && !Strings.isNullOrEmpty(role);
860         }
861
862         boolean isShardReadyWithLeaderId() {
863             return leaderAvailable && isShardReady() && !RaftState.IsolatedLeader.name().equals(role) &&
864                     (isLeader() || peerAddresses.get(leaderId) != null);
865         }
866
867         boolean isShardInitialized() {
868             return getActor() != null && actorInitialized;
869         }
870
871         boolean isLeader() {
872             return Objects.equal(leaderId, shardId.toString());
873         }
874
875         String getSerializedLeaderActor() {
876             if(isLeader()) {
877                 return Serialization.serializedActorPath(getActor());
878             } else {
879                 return peerAddresses.get(leaderId);
880             }
881         }
882
883         void setActorInitialized() {
884             LOG.debug("Shard {} is initialized", shardId);
885
886             this.actorInitialized = true;
887
888             notifyOnShardInitializedCallbacks();
889         }
890
891         private void notifyOnShardInitializedCallbacks() {
892             if(onShardInitializedSet.isEmpty()) {
893                 return;
894             }
895
896             boolean ready = isShardReadyWithLeaderId();
897
898             if(LOG.isDebugEnabled()) {
899                 LOG.debug("Shard {} is {} - notifying {} OnShardInitialized callbacks", shardId,
900                         ready ? "ready" : "initialized", onShardInitializedSet.size());
901             }
902
903             Iterator<OnShardInitialized> iter = onShardInitializedSet.iterator();
904             while(iter.hasNext()) {
905                 OnShardInitialized onShardInitialized = iter.next();
906                 if(!(onShardInitialized instanceof OnShardReady) || ready) {
907                     iter.remove();
908                     onShardInitialized.getTimeoutSchedule().cancel();
909                     onShardInitialized.getReplyRunnable().run();
910                 }
911             }
912         }
913
914         void addOnShardInitialized(OnShardInitialized onShardInitialized) {
915             onShardInitializedSet.add(onShardInitialized);
916         }
917
918         void removeOnShardInitialized(OnShardInitialized onShardInitialized) {
919             onShardInitializedSet.remove(onShardInitialized);
920         }
921
922         void setRole(String newRole) {
923             this.role = newRole;
924
925             notifyOnShardInitializedCallbacks();
926         }
927
928         void setFollowerSyncStatus(boolean syncStatus){
929             this.followerSyncStatus = syncStatus;
930         }
931
932         boolean isInSync(){
933             if(RaftState.Follower.name().equals(this.role)){
934                 return followerSyncStatus;
935             } else if(RaftState.Leader.name().equals(this.role)){
936                 return true;
937             }
938
939             return false;
940         }
941
942         boolean setLeaderId(String leaderId) {
943             boolean changed = !Objects.equal(this.leaderId, leaderId);
944             this.leaderId = leaderId;
945             if(leaderId != null) {
946                 this.leaderAvailable = true;
947             }
948             notifyOnShardInitializedCallbacks();
949
950             return changed;
951         }
952
953         String getLeaderId() {
954             return leaderId;
955         }
956
957         void setLeaderAvailable(boolean leaderAvailable) {
958             this.leaderAvailable = leaderAvailable;
959         }
960
961         short getLeaderVersion() {
962             return leaderVersion;
963         }
964
965         void setLeaderVersion(short leaderVersion) {
966             this.leaderVersion = leaderVersion;
967         }
968     }
969
970     private static class ShardManagerCreator implements Creator<ShardManager> {
971         private static final long serialVersionUID = 1L;
972
973         final ClusterWrapper cluster;
974         final Configuration configuration;
975         final DatastoreContext datastoreContext;
976         private final CountDownLatch waitTillReadyCountdownLatch;
977         private final PrimaryShardInfoFutureCache primaryShardInfoCache;
978
979         ShardManagerCreator(ClusterWrapper cluster, Configuration configuration, DatastoreContext datastoreContext,
980                 CountDownLatch waitTillReadyCountdownLatch, PrimaryShardInfoFutureCache primaryShardInfoCache) {
981             this.cluster = cluster;
982             this.configuration = configuration;
983             this.datastoreContext = datastoreContext;
984             this.waitTillReadyCountdownLatch = waitTillReadyCountdownLatch;
985             this.primaryShardInfoCache = primaryShardInfoCache;
986         }
987
988         @Override
989         public ShardManager create() throws Exception {
990             return new ShardManager(cluster, configuration, datastoreContext, waitTillReadyCountdownLatch,
991                     primaryShardInfoCache);
992         }
993     }
994
995     private static class OnShardInitialized {
996         private final Runnable replyRunnable;
997         private Cancellable timeoutSchedule;
998
999         OnShardInitialized(Runnable replyRunnable) {
1000             this.replyRunnable = replyRunnable;
1001         }
1002
1003         Runnable getReplyRunnable() {
1004             return replyRunnable;
1005         }
1006
1007         Cancellable getTimeoutSchedule() {
1008             return timeoutSchedule;
1009         }
1010
1011         void setTimeoutSchedule(Cancellable timeoutSchedule) {
1012             this.timeoutSchedule = timeoutSchedule;
1013         }
1014     }
1015
1016     private static class OnShardReady extends OnShardInitialized {
1017         OnShardReady(Runnable replyRunnable) {
1018             super(replyRunnable);
1019         }
1020     }
1021
1022     private static class ShardNotInitializedTimeout {
1023         private final ActorRef sender;
1024         private final ShardInformation shardInfo;
1025         private final OnShardInitialized onShardInitialized;
1026
1027         ShardNotInitializedTimeout(ShardInformation shardInfo, OnShardInitialized onShardInitialized, ActorRef sender) {
1028             this.sender = sender;
1029             this.shardInfo = shardInfo;
1030             this.onShardInitialized = onShardInitialized;
1031         }
1032
1033         ActorRef getSender() {
1034             return sender;
1035         }
1036
1037         ShardInformation getShardInfo() {
1038             return shardInfo;
1039         }
1040
1041         OnShardInitialized getOnShardInitialized() {
1042             return onShardInitialized;
1043         }
1044     }
1045
1046     /**
1047      * We no longer persist SchemaContextModules but keep this class around for now for backwards
1048      * compatibility so we don't get de-serialization failures on upgrade from Helium.
1049      */
1050     @Deprecated
1051     static class SchemaContextModules implements Serializable {
1052         private static final long serialVersionUID = -8884620101025936590L;
1053
1054         private final Set<String> modules;
1055
1056         SchemaContextModules(Set<String> modules){
1057             this.modules = modules;
1058         }
1059
1060         public Set<String> getModules() {
1061             return modules;
1062         }
1063     }
1064 }
1065
1066
1067