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