4aed6e3209a703842bc4727e3607fc51500e8d60
[controller.git] / opendaylight / md-sal / sal-distributed-datastore / src / main / java / org / opendaylight / controller / cluster / datastore / Shard.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.ActorRef;
12 import akka.actor.ActorSelection;
13 import akka.actor.Cancellable;
14 import akka.actor.Props;
15 import akka.serialization.Serialization;
16 import com.google.common.annotations.VisibleForTesting;
17 import com.google.common.base.Optional;
18 import com.google.common.base.Preconditions;
19 import com.google.common.base.Ticker;
20 import java.io.IOException;
21 import java.util.Collection;
22 import java.util.Collections;
23 import java.util.Map;
24 import java.util.concurrent.TimeUnit;
25 import javax.annotation.Nonnull;
26 import org.opendaylight.controller.cluster.access.concepts.TransactionIdentifier;
27 import org.opendaylight.controller.cluster.common.actor.CommonConfig;
28 import org.opendaylight.controller.cluster.common.actor.MessageTracker;
29 import org.opendaylight.controller.cluster.common.actor.MessageTracker.Error;
30 import org.opendaylight.controller.cluster.common.actor.MeteringBehavior;
31 import org.opendaylight.controller.cluster.datastore.exceptions.NoShardLeaderException;
32 import org.opendaylight.controller.cluster.datastore.identifiers.ShardIdentifier;
33 import org.opendaylight.controller.cluster.datastore.jmx.mbeans.shard.ShardMBeanFactory;
34 import org.opendaylight.controller.cluster.datastore.jmx.mbeans.shard.ShardStats;
35 import org.opendaylight.controller.cluster.datastore.messages.AbortTransaction;
36 import org.opendaylight.controller.cluster.datastore.messages.ActorInitialized;
37 import org.opendaylight.controller.cluster.datastore.messages.BatchedModifications;
38 import org.opendaylight.controller.cluster.datastore.messages.CanCommitTransaction;
39 import org.opendaylight.controller.cluster.datastore.messages.CloseTransactionChain;
40 import org.opendaylight.controller.cluster.datastore.messages.CommitTransaction;
41 import org.opendaylight.controller.cluster.datastore.messages.CreateTransaction;
42 import org.opendaylight.controller.cluster.datastore.messages.CreateTransactionReply;
43 import org.opendaylight.controller.cluster.datastore.messages.DatastoreSnapshot;
44 import org.opendaylight.controller.cluster.datastore.messages.DatastoreSnapshot.ShardSnapshot;
45 import org.opendaylight.controller.cluster.datastore.messages.ForwardedReadyTransaction;
46 import org.opendaylight.controller.cluster.datastore.messages.GetShardDataTree;
47 import org.opendaylight.controller.cluster.datastore.messages.PeerAddressResolved;
48 import org.opendaylight.controller.cluster.datastore.messages.ReadyLocalTransaction;
49 import org.opendaylight.controller.cluster.datastore.messages.RegisterChangeListener;
50 import org.opendaylight.controller.cluster.datastore.messages.RegisterDataTreeChangeListener;
51 import org.opendaylight.controller.cluster.datastore.messages.ShardLeaderStateChanged;
52 import org.opendaylight.controller.cluster.datastore.messages.UpdateSchemaContext;
53 import org.opendaylight.controller.cluster.datastore.utils.Dispatchers;
54 import org.opendaylight.controller.cluster.notifications.LeaderStateChanged;
55 import org.opendaylight.controller.cluster.notifications.RegisterRoleChangeListener;
56 import org.opendaylight.controller.cluster.notifications.RoleChangeNotifier;
57 import org.opendaylight.controller.cluster.raft.RaftActor;
58 import org.opendaylight.controller.cluster.raft.RaftActorRecoveryCohort;
59 import org.opendaylight.controller.cluster.raft.RaftActorSnapshotCohort;
60 import org.opendaylight.controller.cluster.raft.RaftState;
61 import org.opendaylight.controller.cluster.raft.base.messages.FollowerInitialSyncUpStatus;
62 import org.opendaylight.controller.cluster.raft.messages.AppendEntriesReply;
63 import org.opendaylight.controller.cluster.raft.messages.ServerRemoved;
64 import org.opendaylight.controller.cluster.raft.protobuff.client.messages.Payload;
65 import org.opendaylight.yangtools.concepts.Identifier;
66 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataValidationFailedException;
67 import org.opendaylight.yangtools.yang.data.api.schema.tree.TipProducingDataTree;
68 import org.opendaylight.yangtools.yang.data.api.schema.tree.TreeType;
69 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
70 import scala.concurrent.duration.Duration;
71 import scala.concurrent.duration.FiniteDuration;
72
73 /**
74  * A Shard represents a portion of the logical data tree <br/>
75  * <p>
76  * Our Shard uses InMemoryDataTree as it's internal representation and delegates all requests it
77  * </p>
78  */
79 public class Shard extends RaftActor {
80
81     @VisibleForTesting
82     static final Object TX_COMMIT_TIMEOUT_CHECK_MESSAGE = new Object() {
83         @Override
84         public String toString() {
85             return "txCommitTimeoutCheck";
86         }
87     };
88
89     @VisibleForTesting
90     static final Object GET_SHARD_MBEAN_MESSAGE = new Object() {
91         @Override
92         public String toString() {
93             return "getShardMBeanMessage";
94         }
95     };
96
97     // FIXME: shard names should be encapsulated in their own class and this should be exposed as a constant.
98     public static final String DEFAULT_NAME = "default";
99
100     // The state of this Shard
101     private final ShardDataTree store;
102
103     /// The name of this shard
104     private final String name;
105
106     private final ShardStats shardMBean;
107
108     private DatastoreContext datastoreContext;
109
110     private final ShardCommitCoordinator commitCoordinator;
111
112     private long transactionCommitTimeout;
113
114     private Cancellable txCommitTimeoutCheckSchedule;
115
116     private final Optional<ActorRef> roleChangeNotifier;
117
118     private final MessageTracker appendEntriesReplyTracker;
119
120     private final ShardTransactionActorFactory transactionActorFactory;
121
122     private final ShardSnapshotCohort snapshotCohort;
123
124     private final DataTreeChangeListenerSupport treeChangeSupport = new DataTreeChangeListenerSupport(this);
125     private final DataChangeListenerSupport changeSupport = new DataChangeListenerSupport(this);
126
127
128     private ShardSnapshot restoreFromSnapshot;
129
130     private final ShardTransactionMessageRetrySupport messageRetrySupport;
131
132     protected Shard(final AbstractBuilder<?, ?> builder) {
133         super(builder.getId().toString(), builder.getPeerAddresses(),
134                 Optional.of(builder.getDatastoreContext().getShardRaftConfig()), DataStoreVersions.CURRENT_VERSION);
135
136         this.name = builder.getId().toString();
137         this.datastoreContext = builder.getDatastoreContext();
138         this.restoreFromSnapshot = builder.getRestoreFromSnapshot();
139
140         setPersistence(datastoreContext.isPersistent());
141
142         LOG.info("Shard created : {}, persistent : {}", name, datastoreContext.isPersistent());
143
144         ShardDataTreeChangeListenerPublisherActorProxy treeChangeListenerPublisher =
145                 new ShardDataTreeChangeListenerPublisherActorProxy(getContext(), name + "-DTCL-publisher");
146         ShardDataChangeListenerPublisherActorProxy dataChangeListenerPublisher =
147                 new ShardDataChangeListenerPublisherActorProxy(getContext(), name + "-DCL-publisher");
148         if(builder.getDataTree() != null) {
149             store = new ShardDataTree(this, builder.getSchemaContext(), builder.getDataTree(),
150                     treeChangeListenerPublisher, dataChangeListenerPublisher, name);
151         } else {
152             store = new ShardDataTree(this, builder.getSchemaContext(), builder.getTreeType(),
153                     treeChangeListenerPublisher, dataChangeListenerPublisher, name);
154         }
155
156         shardMBean = ShardMBeanFactory.getShardStatsMBean(name.toString(),
157                 datastoreContext.getDataStoreMXBeanType());
158         shardMBean.setShard(this);
159
160         if (isMetricsCaptureEnabled()) {
161             getContext().become(new MeteringBehavior(this));
162         }
163
164         commitCoordinator = new ShardCommitCoordinator(store, LOG, this.name);
165
166         setTransactionCommitTimeout();
167
168         // create a notifier actor for each cluster member
169         roleChangeNotifier = createRoleChangeNotifier(name.toString());
170
171         appendEntriesReplyTracker = new MessageTracker(AppendEntriesReply.class,
172                 getRaftActorContext().getConfigParams().getIsolatedCheckIntervalInMillis());
173
174         transactionActorFactory = new ShardTransactionActorFactory(store, datastoreContext,
175                 new Dispatchers(context().system().dispatchers()).getDispatcherPath(
176                         Dispatchers.DispatcherType.Transaction), self(), getContext(), shardMBean);
177
178         snapshotCohort = ShardSnapshotCohort.create(getContext(), builder.getId().getMemberName(), store, LOG,
179             this.name);
180
181         messageRetrySupport = new ShardTransactionMessageRetrySupport(this);
182     }
183
184     private void setTransactionCommitTimeout() {
185         transactionCommitTimeout = TimeUnit.MILLISECONDS.convert(
186                 datastoreContext.getShardTransactionCommitTimeoutInSeconds(), TimeUnit.SECONDS) / 2;
187     }
188
189     private Optional<ActorRef> createRoleChangeNotifier(final String shardId) {
190         ActorRef shardRoleChangeNotifier = this.getContext().actorOf(
191             RoleChangeNotifier.getProps(shardId), shardId + "-notifier");
192         return Optional.of(shardRoleChangeNotifier);
193     }
194
195     @Override
196     public void postStop() {
197         LOG.info("Stopping Shard {}", persistenceId());
198
199         super.postStop();
200
201         messageRetrySupport.close();
202
203         if (txCommitTimeoutCheckSchedule != null) {
204             txCommitTimeoutCheckSchedule.cancel();
205         }
206
207         commitCoordinator.abortPendingTransactions("Transaction aborted due to shutdown.", this);
208
209         shardMBean.unregisterMBean();
210     }
211
212     @Override
213     protected void handleRecover(final Object message) {
214         LOG.debug("{}: onReceiveRecover: Received message {} from {}", persistenceId(), message.getClass(),
215             getSender());
216
217         super.handleRecover(message);
218         if (LOG.isTraceEnabled()) {
219             appendEntriesReplyTracker.begin();
220         }
221     }
222
223     @Override
224     protected void handleNonRaftCommand(final Object message) {
225         try (final MessageTracker.Context context = appendEntriesReplyTracker.received(message)) {
226             final Optional<Error> maybeError = context.error();
227             if (maybeError.isPresent()) {
228                 LOG.trace("{} : AppendEntriesReply failed to arrive at the expected interval {}", persistenceId(),
229                     maybeError.get());
230             }
231
232             if (CreateTransaction.isSerializedType(message)) {
233                 handleCreateTransaction(message);
234             } else if (message instanceof BatchedModifications) {
235                 handleBatchedModifications((BatchedModifications)message);
236             } else if (message instanceof ForwardedReadyTransaction) {
237                 handleForwardedReadyTransaction((ForwardedReadyTransaction) message);
238             } else if (message instanceof ReadyLocalTransaction) {
239                 handleReadyLocalTransaction((ReadyLocalTransaction)message);
240             } else if (CanCommitTransaction.isSerializedType(message)) {
241                 handleCanCommitTransaction(CanCommitTransaction.fromSerializable(message));
242             } else if (CommitTransaction.isSerializedType(message)) {
243                 handleCommitTransaction(CommitTransaction.fromSerializable(message));
244             } else if (AbortTransaction.isSerializedType(message)) {
245                 handleAbortTransaction(AbortTransaction.fromSerializable(message));
246             } else if (CloseTransactionChain.isSerializedType(message)) {
247                 closeTransactionChain(CloseTransactionChain.fromSerializable(message));
248             } else if (message instanceof RegisterChangeListener) {
249                 changeSupport.onMessage((RegisterChangeListener) message, isLeader(), hasLeader());
250             } else if (message instanceof RegisterDataTreeChangeListener) {
251                 treeChangeSupport.onMessage((RegisterDataTreeChangeListener) message, isLeader(), hasLeader());
252             } else if (message instanceof UpdateSchemaContext) {
253                 updateSchemaContext((UpdateSchemaContext) message);
254             } else if (message instanceof PeerAddressResolved) {
255                 PeerAddressResolved resolved = (PeerAddressResolved) message;
256                 setPeerAddress(resolved.getPeerId().toString(),
257                         resolved.getPeerAddress());
258             } else if (TX_COMMIT_TIMEOUT_CHECK_MESSAGE.equals(message)) {
259                 store.checkForExpiredTransactions(transactionCommitTimeout);
260                 commitCoordinator.checkForExpiredTransactions(transactionCommitTimeout, this);
261             } else if (message instanceof DatastoreContext) {
262                 onDatastoreContext((DatastoreContext)message);
263             } else if (message instanceof RegisterRoleChangeListener){
264                 roleChangeNotifier.get().forward(message, context());
265             } else if (message instanceof FollowerInitialSyncUpStatus) {
266                 shardMBean.setFollowerInitialSyncStatus(((FollowerInitialSyncUpStatus) message).isInitialSyncDone());
267                 context().parent().tell(message, self());
268             } else if (GET_SHARD_MBEAN_MESSAGE.equals(message)){
269                 sender().tell(getShardMBean(), self());
270             } else if (message instanceof GetShardDataTree) {
271                 sender().tell(store.getDataTree(), self());
272             } else if (message instanceof ServerRemoved){
273                 context().parent().forward(message, context());
274             } else if (ShardTransactionMessageRetrySupport.TIMER_MESSAGE_CLASS.isInstance(message)) {
275                 messageRetrySupport.onTimerMessage(message);
276             } else if (message instanceof DataTreeCohortActorRegistry.CohortRegistryCommand) {
277                 store.processCohortRegistryCommand(getSender(),
278                         (DataTreeCohortActorRegistry.CohortRegistryCommand) message);
279             } else {
280                 super.handleNonRaftCommand(message);
281             }
282         }
283     }
284
285     private boolean hasLeader() {
286         return getLeaderId() != null;
287     }
288
289     public int getPendingTxCommitQueueSize() {
290         return store.getQueueSize();
291     }
292
293     public int getCohortCacheSize() {
294         return commitCoordinator.getCohortCacheSize();
295     }
296
297     @Override
298     protected Optional<ActorRef> getRoleChangeNotifier() {
299         return roleChangeNotifier;
300     }
301
302     @Override
303     protected LeaderStateChanged newLeaderStateChanged(final String memberId, final String leaderId, final short leaderPayloadVersion) {
304         return isLeader() ? new ShardLeaderStateChanged(memberId, leaderId, store.getDataTree(), leaderPayloadVersion)
305                 : new ShardLeaderStateChanged(memberId, leaderId, leaderPayloadVersion);
306     }
307
308     protected void onDatastoreContext(final DatastoreContext context) {
309         datastoreContext = context;
310
311         setTransactionCommitTimeout();
312
313         setPersistence(datastoreContext.isPersistent());
314
315         updateConfigParams(datastoreContext.getShardRaftConfig());
316     }
317
318     boolean canSkipPayload() {
319         // If we do not have any followers and we are not using persistence we can apply modification to the state
320         // immediately
321         return !hasFollowers() && !persistence().isRecoveryApplicable();
322     }
323
324     // applyState() will be invoked once consensus is reached on the payload
325     void persistPayload(final TransactionIdentifier transactionId, final Payload payload) {
326         // We are faking the sender
327         persistData(self(), transactionId, payload);
328     }
329
330     private void handleCommitTransaction(final CommitTransaction commit) {
331         if (isLeader()) {
332             commitCoordinator.handleCommit(commit.getTransactionID(), getSender(), this);
333         } else {
334             ActorSelection leader = getLeader();
335             if (leader == null) {
336                 messageRetrySupport.addMessageToRetry(commit, getSender(),
337                         "Could not commit transaction " + commit.getTransactionID());
338             } else {
339                 LOG.debug("{}: Forwarding CommitTransaction to leader {}", persistenceId(), leader);
340                 leader.forward(commit, getContext());
341             }
342         }
343     }
344
345     private void handleCanCommitTransaction(final CanCommitTransaction canCommit) {
346         LOG.debug("{}: Can committing transaction {}", persistenceId(), canCommit.getTransactionID());
347
348         if (isLeader()) {
349         commitCoordinator.handleCanCommit(canCommit.getTransactionID(), getSender(), this);
350         } else {
351             ActorSelection leader = getLeader();
352             if (leader == null) {
353                 messageRetrySupport.addMessageToRetry(canCommit, getSender(),
354                         "Could not canCommit transaction " + canCommit.getTransactionID());
355             } else {
356                 LOG.debug("{}: Forwarding CanCommitTransaction to leader {}", persistenceId(), leader);
357                 leader.forward(canCommit, getContext());
358             }
359         }
360     }
361
362     protected void handleBatchedModificationsLocal(final BatchedModifications batched, final ActorRef sender) {
363         try {
364             commitCoordinator.handleBatchedModifications(batched, sender, this);
365         } catch (Exception e) {
366             LOG.error("{}: Error handling BatchedModifications for Tx {}", persistenceId(),
367                     batched.getTransactionID(), e);
368             sender.tell(new akka.actor.Status.Failure(e), getSelf());
369         }
370     }
371
372     private void handleBatchedModifications(final BatchedModifications batched) {
373         // This message is sent to prepare the modifications transaction directly on the Shard as an
374         // optimization to avoid the extra overhead of a separate ShardTransaction actor. On the last
375         // BatchedModifications message, the caller sets the ready flag in the message indicating
376         // modifications are complete. The reply contains the cohort actor path (this actor) for the caller
377         // to initiate the 3-phase commit. This also avoids the overhead of sending an additional
378         // ReadyTransaction message.
379
380         // If we're not the leader then forward to the leader. This is a safety measure - we shouldn't
381         // normally get here if we're not the leader as the front-end (TransactionProxy) should determine
382         // the primary/leader shard. However with timing and caching on the front-end, there's a small
383         // window where it could have a stale leader during leadership transitions.
384         //
385         boolean isLeaderActive = isLeaderActive();
386         if (isLeader() && isLeaderActive) {
387             handleBatchedModificationsLocal(batched, getSender());
388         } else {
389             ActorSelection leader = getLeader();
390             if (!isLeaderActive || leader == null) {
391                 messageRetrySupport.addMessageToRetry(batched, getSender(),
392                         "Could not commit transaction " + batched.getTransactionID());
393             } else {
394                 // If this is not the first batch and leadership changed in between batched messages,
395                 // we need to reconstruct previous BatchedModifications from the transaction
396                 // DataTreeModification, honoring the max batched modification count, and forward all the
397                 // previous BatchedModifications to the new leader.
398                 Collection<BatchedModifications> newModifications = commitCoordinator.createForwardedBatchedModifications(
399                         batched, datastoreContext.getShardBatchedModificationCount());
400
401                 LOG.debug("{}: Forwarding {} BatchedModifications to leader {}", persistenceId(),
402                         newModifications.size(), leader);
403
404                 for (BatchedModifications bm : newModifications) {
405                     leader.forward(bm, getContext());
406                 }
407             }
408         }
409     }
410
411     private boolean failIfIsolatedLeader(final ActorRef sender) {
412         if (isIsolatedLeader()) {
413             sender.tell(new akka.actor.Status.Failure(new NoShardLeaderException(String.format(
414                     "Shard %s was the leader but has lost contact with all of its followers. Either all" +
415                     " other follower nodes are down or this node is isolated by a network partition.",
416                     persistenceId()))), getSelf());
417             return true;
418         }
419
420         return false;
421     }
422
423     protected boolean isIsolatedLeader() {
424         return getRaftState() == RaftState.IsolatedLeader;
425     }
426
427     private void handleReadyLocalTransaction(final ReadyLocalTransaction message) {
428         LOG.debug("{}: handleReadyLocalTransaction for {}", persistenceId(), message.getTransactionID());
429
430         boolean isLeaderActive = isLeaderActive();
431         if (isLeader() && isLeaderActive) {
432             try {
433                 commitCoordinator.handleReadyLocalTransaction(message, getSender(), this);
434             } catch (Exception e) {
435                 LOG.error("{}: Error handling ReadyLocalTransaction for Tx {}", persistenceId(),
436                         message.getTransactionID(), e);
437                 getSender().tell(new akka.actor.Status.Failure(e), getSelf());
438             }
439         } else {
440             ActorSelection leader = getLeader();
441             if (!isLeaderActive || leader == null) {
442                 messageRetrySupport.addMessageToRetry(message, getSender(),
443                         "Could not commit transaction " + message.getTransactionID());
444             } else {
445                 LOG.debug("{}: Forwarding ReadyLocalTransaction to leader {}", persistenceId(), leader);
446                 message.setRemoteVersion(getCurrentBehavior().getLeaderPayloadVersion());
447                 leader.forward(message, getContext());
448             }
449         }
450     }
451
452     private void handleForwardedReadyTransaction(final ForwardedReadyTransaction forwardedReady) {
453         LOG.debug("{}: handleForwardedReadyTransaction for {}", persistenceId(), forwardedReady.getTransactionID());
454
455         boolean isLeaderActive = isLeaderActive();
456         if (isLeader() && isLeaderActive) {
457             commitCoordinator.handleForwardedReadyTransaction(forwardedReady, getSender(), this);
458         } else {
459             ActorSelection leader = getLeader();
460             if (!isLeaderActive || leader == null) {
461                 messageRetrySupport.addMessageToRetry(forwardedReady, getSender(),
462                         "Could not commit transaction " + forwardedReady.getTransactionID());
463             } else {
464                 LOG.debug("{}: Forwarding ForwardedReadyTransaction to leader {}", persistenceId(), leader);
465
466                 ReadyLocalTransaction readyLocal = new ReadyLocalTransaction(forwardedReady.getTransactionID(),
467                         forwardedReady.getTransaction().getSnapshot(), forwardedReady.isDoImmediateCommit());
468                 readyLocal.setRemoteVersion(getCurrentBehavior().getLeaderPayloadVersion());
469                 leader.forward(readyLocal, getContext());
470             }
471         }
472     }
473
474     private void handleAbortTransaction(final AbortTransaction abort) {
475         doAbortTransaction(abort.getTransactionID(), getSender());
476     }
477
478     void doAbortTransaction(final TransactionIdentifier transactionID, final ActorRef sender) {
479         commitCoordinator.handleAbort(transactionID, sender, this);
480     }
481
482     private void handleCreateTransaction(final Object message) {
483         if (isLeader()) {
484             createTransaction(CreateTransaction.fromSerializable(message));
485         } else if (getLeader() != null) {
486             getLeader().forward(message, getContext());
487         } else {
488             getSender().tell(new akka.actor.Status.Failure(new NoShardLeaderException(
489                     "Could not create a shard transaction", persistenceId())), getSelf());
490         }
491     }
492
493     private void closeTransactionChain(final CloseTransactionChain closeTransactionChain) {
494         store.closeTransactionChain(closeTransactionChain.getIdentifier());
495     }
496
497     private void createTransaction(final CreateTransaction createTransaction) {
498         try {
499             if (TransactionType.fromInt(createTransaction.getTransactionType()) != TransactionType.READ_ONLY &&
500                     failIfIsolatedLeader(getSender())) {
501                 return;
502             }
503
504             ActorRef transactionActor = createTransaction(createTransaction.getTransactionType(),
505                 createTransaction.getTransactionId());
506
507             getSender().tell(new CreateTransactionReply(Serialization.serializedActorPath(transactionActor),
508                     createTransaction.getTransactionId(), createTransaction.getVersion()).toSerializable(), getSelf());
509         } catch (Exception e) {
510             getSender().tell(new akka.actor.Status.Failure(e), getSelf());
511         }
512     }
513
514     private ActorRef createTransaction(final int transactionType, final TransactionIdentifier transactionId) {
515         LOG.debug("{}: Creating transaction : {} ", persistenceId(), transactionId);
516         return transactionActorFactory.newShardTransaction(TransactionType.fromInt(transactionType),
517             transactionId);
518     }
519
520     private void updateSchemaContext(final UpdateSchemaContext message) {
521         updateSchemaContext(message.getSchemaContext());
522     }
523
524     @VisibleForTesting
525     void updateSchemaContext(final SchemaContext schemaContext) {
526         store.updateSchemaContext(schemaContext);
527     }
528
529     private boolean isMetricsCaptureEnabled() {
530         CommonConfig config = new CommonConfig(getContext().system().settings().config());
531         return config.isMetricCaptureEnabled();
532     }
533
534     @Override
535     @VisibleForTesting
536     public RaftActorSnapshotCohort getRaftActorSnapshotCohort() {
537         return snapshotCohort;
538     }
539
540     @Override
541     @Nonnull
542     protected RaftActorRecoveryCohort getRaftActorRecoveryCohort() {
543         return new ShardRecoveryCoordinator(store,
544             restoreFromSnapshot != null ? restoreFromSnapshot.getSnapshot() : null, persistenceId(), LOG);
545     }
546
547     @Override
548     protected void onRecoveryComplete() {
549         restoreFromSnapshot = null;
550
551         //notify shard manager
552         getContext().parent().tell(new ActorInitialized(), getSelf());
553
554         // Being paranoid here - this method should only be called once but just in case...
555         if (txCommitTimeoutCheckSchedule == null) {
556             // Schedule a message to be periodically sent to check if the current in-progress
557             // transaction should be expired and aborted.
558             FiniteDuration period = Duration.create(transactionCommitTimeout / 3, TimeUnit.MILLISECONDS);
559             txCommitTimeoutCheckSchedule = getContext().system().scheduler().schedule(
560                     period, period, getSelf(),
561                     TX_COMMIT_TIMEOUT_CHECK_MESSAGE, getContext().dispatcher(), ActorRef.noSender());
562         }
563     }
564
565     @Override
566     protected void applyState(final ActorRef clientActor, final Identifier identifier, final Object data) {
567         if (data instanceof Payload) {
568             try {
569                 store.applyReplicatedPayload(identifier, (Payload)data);
570             } catch (DataValidationFailedException | IOException e) {
571                 LOG.error("{}: Error applying replica {}", persistenceId(), identifier, e);
572             }
573         } else {
574             LOG.error("{}: Unknown state for {} received {}", persistenceId(), identifier, data);
575         }
576     }
577
578     @Override
579     protected void onStateChanged() {
580         boolean isLeader = isLeader();
581         boolean hasLeader = hasLeader();
582         changeSupport.onLeadershipChange(isLeader, hasLeader);
583         treeChangeSupport.onLeadershipChange(isLeader, hasLeader);
584
585         // If this actor is no longer the leader close all the transaction chains
586         if (!isLeader) {
587             if (LOG.isDebugEnabled()) {
588                 LOG.debug(
589                     "{}: onStateChanged: Closing all transaction chains because shard {} is no longer the leader",
590                     persistenceId(), getId());
591             }
592
593             store.closeAllTransactionChains();
594         }
595
596         if (hasLeader && !isIsolatedLeader()) {
597             messageRetrySupport.retryMessages();
598         }
599     }
600
601     @Override
602     protected void onLeaderChanged(final String oldLeader, final String newLeader) {
603         shardMBean.incrementLeadershipChangeCount();
604
605         boolean hasLeader = hasLeader();
606         if (hasLeader && !isLeader()) {
607             // Another leader was elected. If we were the previous leader and had pending transactions, convert
608             // them to transaction messages and send to the new leader.
609             ActorSelection leader = getLeader();
610             if (leader != null) {
611                 Collection<?> messagesToForward = convertPendingTransactionsToMessages();
612
613                 if (!messagesToForward.isEmpty()) {
614                     LOG.debug("{}: Forwarding {} pending transaction messages to leader {}", persistenceId(),
615                             messagesToForward.size(), leader);
616
617                     for (Object message : messagesToForward) {
618                         leader.tell(message, self());
619                     }
620                 }
621             } else {
622                 commitCoordinator.abortPendingTransactions(
623                         "The transacton was aborted due to inflight leadership change and the leader address isn't available.",
624                         this);
625             }
626         }
627
628         if (hasLeader && !isIsolatedLeader()) {
629             messageRetrySupport.retryMessages();
630         }
631     }
632
633     /**
634      * Clears all pending transactions and converts them to messages to be forwarded to a new leader.
635      *
636      * @return the converted messages
637      */
638     public Collection<?> convertPendingTransactionsToMessages() {
639         return commitCoordinator.convertPendingTransactionsToMessages(datastoreContext.getShardBatchedModificationCount());
640     }
641
642     @Override
643     protected void pauseLeader(final Runnable operation) {
644         LOG.debug("{}: In pauseLeader, operation: {}", persistenceId(), operation);
645         store.setRunOnPendingTransactionsComplete(operation);
646     }
647
648     @Override
649     public String persistenceId() {
650         return this.name;
651     }
652
653     @VisibleForTesting
654     ShardCommitCoordinator getCommitCoordinator() {
655         return commitCoordinator;
656     }
657
658     public DatastoreContext getDatastoreContext() {
659         return datastoreContext;
660     }
661
662     @VisibleForTesting
663     public ShardDataTree getDataStore() {
664         return store;
665     }
666
667     @VisibleForTesting
668     ShardStats getShardMBean() {
669         return shardMBean;
670     }
671
672     public static Builder builder() {
673         return new Builder();
674     }
675
676     public static abstract class AbstractBuilder<T extends AbstractBuilder<T, S>, S extends Shard> {
677         private final Class<S> shardClass;
678         private ShardIdentifier id;
679         private Map<String, String> peerAddresses = Collections.emptyMap();
680         private DatastoreContext datastoreContext;
681         private SchemaContext schemaContext;
682         private DatastoreSnapshot.ShardSnapshot restoreFromSnapshot;
683         private TipProducingDataTree dataTree;
684         private volatile boolean sealed;
685
686         protected AbstractBuilder(final Class<S> shardClass) {
687             this.shardClass = shardClass;
688         }
689
690         protected void checkSealed() {
691             Preconditions.checkState(!sealed, "Builder isalready sealed - further modifications are not allowed");
692         }
693
694         @SuppressWarnings("unchecked")
695         private T self() {
696             return (T) this;
697         }
698
699         public T id(final ShardIdentifier id) {
700             checkSealed();
701             this.id = id;
702             return self();
703         }
704
705         public T peerAddresses(final Map<String, String> peerAddresses) {
706             checkSealed();
707             this.peerAddresses = peerAddresses;
708             return self();
709         }
710
711         public T datastoreContext(final DatastoreContext datastoreContext) {
712             checkSealed();
713             this.datastoreContext = datastoreContext;
714             return self();
715         }
716
717         public T schemaContext(final SchemaContext schemaContext) {
718             checkSealed();
719             this.schemaContext = schemaContext;
720             return self();
721         }
722
723         public T restoreFromSnapshot(final DatastoreSnapshot.ShardSnapshot restoreFromSnapshot) {
724             checkSealed();
725             this.restoreFromSnapshot = restoreFromSnapshot;
726             return self();
727         }
728
729         public T dataTree(final TipProducingDataTree dataTree) {
730             checkSealed();
731             this.dataTree = dataTree;
732             return self();
733         }
734
735         public ShardIdentifier getId() {
736             return id;
737         }
738
739         public Map<String, String> getPeerAddresses() {
740             return peerAddresses;
741         }
742
743         public DatastoreContext getDatastoreContext() {
744             return datastoreContext;
745         }
746
747         public SchemaContext getSchemaContext() {
748             return schemaContext;
749         }
750
751         public DatastoreSnapshot.ShardSnapshot getRestoreFromSnapshot() {
752             return restoreFromSnapshot;
753         }
754
755         public TipProducingDataTree getDataTree() {
756             return dataTree;
757         }
758
759         public TreeType getTreeType() {
760             switch (datastoreContext.getLogicalStoreType()) {
761             case CONFIGURATION:
762                 return TreeType.CONFIGURATION;
763             case OPERATIONAL:
764                 return TreeType.OPERATIONAL;
765             }
766
767             throw new IllegalStateException("Unhandled logical store type " + datastoreContext.getLogicalStoreType());
768         }
769
770         protected void verify() {
771             Preconditions.checkNotNull(id, "id should not be null");
772             Preconditions.checkNotNull(peerAddresses, "peerAddresses should not be null");
773             Preconditions.checkNotNull(datastoreContext, "dataStoreContext should not be null");
774             Preconditions.checkNotNull(schemaContext, "schemaContext should not be null");
775         }
776
777         public Props props() {
778             sealed = true;
779             verify();
780             return Props.create(shardClass, this);
781         }
782     }
783
784     public static class Builder extends AbstractBuilder<Builder, Shard> {
785         private Builder() {
786             super(Shard.class);
787         }
788     }
789
790     Ticker ticker() {
791         return Ticker.systemTicker();
792     }
793 }