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