CDS: Retry remote front-end transactions on AskTimeoutException
[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.japi.Creator;
16 import akka.persistence.RecoveryFailure;
17 import akka.serialization.Serialization;
18 import com.google.common.annotations.VisibleForTesting;
19 import com.google.common.base.Optional;
20 import com.google.common.base.Preconditions;
21 import com.google.common.util.concurrent.FutureCallback;
22 import com.google.common.util.concurrent.Futures;
23 import com.google.common.util.concurrent.ListenableFuture;
24 import java.io.IOException;
25 import java.util.HashMap;
26 import java.util.Map;
27 import java.util.concurrent.TimeUnit;
28 import javax.annotation.Nonnull;
29 import org.opendaylight.controller.cluster.common.actor.CommonConfig;
30 import org.opendaylight.controller.cluster.common.actor.MeteringBehavior;
31 import org.opendaylight.controller.cluster.datastore.ShardCommitCoordinator.CohortEntry;
32 import org.opendaylight.controller.cluster.datastore.exceptions.NoShardLeaderException;
33 import org.opendaylight.controller.cluster.datastore.identifiers.ShardIdentifier;
34 import org.opendaylight.controller.cluster.datastore.identifiers.ShardTransactionIdentifier;
35 import org.opendaylight.controller.cluster.datastore.jmx.mbeans.shard.ShardMBeanFactory;
36 import org.opendaylight.controller.cluster.datastore.jmx.mbeans.shard.ShardStats;
37 import org.opendaylight.controller.cluster.datastore.messages.AbortTransaction;
38 import org.opendaylight.controller.cluster.datastore.messages.AbortTransactionReply;
39 import org.opendaylight.controller.cluster.datastore.messages.ActorInitialized;
40 import org.opendaylight.controller.cluster.datastore.messages.BatchedModifications;
41 import org.opendaylight.controller.cluster.datastore.messages.CanCommitTransaction;
42 import org.opendaylight.controller.cluster.datastore.messages.CloseTransactionChain;
43 import org.opendaylight.controller.cluster.datastore.messages.CommitTransaction;
44 import org.opendaylight.controller.cluster.datastore.messages.CommitTransactionReply;
45 import org.opendaylight.controller.cluster.datastore.messages.CreateTransaction;
46 import org.opendaylight.controller.cluster.datastore.messages.CreateTransactionReply;
47 import org.opendaylight.controller.cluster.datastore.messages.ForwardedReadyTransaction;
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.modification.Modification;
55 import org.opendaylight.controller.cluster.datastore.modification.ModificationPayload;
56 import org.opendaylight.controller.cluster.datastore.modification.MutableCompositeModification;
57 import org.opendaylight.controller.cluster.datastore.utils.Dispatchers;
58 import org.opendaylight.controller.cluster.datastore.utils.MessageTracker;
59 import org.opendaylight.controller.cluster.notifications.LeaderStateChanged;
60 import org.opendaylight.controller.cluster.notifications.RegisterRoleChangeListener;
61 import org.opendaylight.controller.cluster.notifications.RoleChangeNotifier;
62 import org.opendaylight.controller.cluster.raft.RaftActor;
63 import org.opendaylight.controller.cluster.raft.RaftActorRecoveryCohort;
64 import org.opendaylight.controller.cluster.raft.RaftActorSnapshotCohort;
65 import org.opendaylight.controller.cluster.raft.RaftState;
66 import org.opendaylight.controller.cluster.raft.base.messages.FollowerInitialSyncUpStatus;
67 import org.opendaylight.controller.cluster.raft.messages.AppendEntriesReply;
68 import org.opendaylight.controller.cluster.raft.protobuff.client.messages.CompositeModificationByteStringPayload;
69 import org.opendaylight.controller.cluster.raft.protobuff.client.messages.CompositeModificationPayload;
70 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTree;
71 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidate;
72 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataValidationFailedException;
73 import org.opendaylight.yangtools.yang.data.api.schema.tree.ModificationType;
74 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
75 import scala.concurrent.duration.Duration;
76 import scala.concurrent.duration.FiniteDuration;
77
78 /**
79  * A Shard represents a portion of the logical data tree <br/>
80  * <p>
81  * Our Shard uses InMemoryDataTree as it's internal representation and delegates all requests it
82  * </p>
83  */
84 public class Shard extends RaftActor {
85
86     private static final Object TX_COMMIT_TIMEOUT_CHECK_MESSAGE = "txCommitTimeoutCheck";
87
88     @VisibleForTesting
89     static final Object GET_SHARD_MBEAN_MESSAGE = "getShardMBeanMessage";
90
91     @VisibleForTesting
92     static final String DEFAULT_NAME = "default";
93
94     // The state of this Shard
95     private final ShardDataTree store;
96
97     /// The name of this shard
98     private final String name;
99
100     private final ShardStats shardMBean;
101
102     private DatastoreContext datastoreContext;
103
104     private final ShardCommitCoordinator commitCoordinator;
105
106     private long transactionCommitTimeout;
107
108     private Cancellable txCommitTimeoutCheckSchedule;
109
110     private final Optional<ActorRef> roleChangeNotifier;
111
112     private final MessageTracker appendEntriesReplyTracker;
113
114     private final ShardTransactionActorFactory transactionActorFactory;
115
116     private final ShardSnapshotCohort snapshotCohort;
117
118     private final DataTreeChangeListenerSupport treeChangeSupport = new DataTreeChangeListenerSupport(this);
119     private final DataChangeListenerSupport changeSupport = new DataChangeListenerSupport(this);
120
121     protected Shard(final ShardIdentifier name, final Map<String, String> peerAddresses,
122             final DatastoreContext datastoreContext, final SchemaContext schemaContext) {
123         super(name.toString(), new HashMap<>(peerAddresses), Optional.of(datastoreContext.getShardRaftConfig()),
124                 DataStoreVersions.CURRENT_VERSION);
125
126         this.name = name.toString();
127         this.datastoreContext = datastoreContext;
128
129         setPersistence(datastoreContext.isPersistent());
130
131         LOG.info("Shard created : {}, persistent : {}", name, datastoreContext.isPersistent());
132
133         store = new ShardDataTree(schemaContext);
134
135         shardMBean = ShardMBeanFactory.getShardStatsMBean(name.toString(),
136                 datastoreContext.getDataStoreMXBeanType());
137         shardMBean.setShard(this);
138
139         if (isMetricsCaptureEnabled()) {
140             getContext().become(new MeteringBehavior(this));
141         }
142
143         commitCoordinator = new ShardCommitCoordinator(store,
144                 datastoreContext.getShardCommitQueueExpiryTimeoutInMillis(),
145                 datastoreContext.getShardTransactionCommitQueueCapacity(), self(), LOG, this.name);
146
147         setTransactionCommitTimeout();
148
149         // create a notifier actor for each cluster member
150         roleChangeNotifier = createRoleChangeNotifier(name.toString());
151
152         appendEntriesReplyTracker = new MessageTracker(AppendEntriesReply.class,
153                 getRaftActorContext().getConfigParams().getIsolatedCheckIntervalInMillis());
154
155         transactionActorFactory = new ShardTransactionActorFactory(store, datastoreContext,
156                 new Dispatchers(context().system().dispatchers()).getDispatcherPath(
157                         Dispatchers.DispatcherType.Transaction), self(), getContext(), shardMBean);
158
159         snapshotCohort = new ShardSnapshotCohort(transactionActorFactory, store, LOG, this.name);
160
161
162     }
163
164     private void setTransactionCommitTimeout() {
165         transactionCommitTimeout = TimeUnit.MILLISECONDS.convert(
166                 datastoreContext.getShardTransactionCommitTimeoutInSeconds(), TimeUnit.SECONDS) / 2;
167     }
168
169     public static Props props(final ShardIdentifier name,
170         final Map<String, String> peerAddresses,
171         final DatastoreContext datastoreContext, final SchemaContext schemaContext) {
172         Preconditions.checkNotNull(name, "name should not be null");
173         Preconditions.checkNotNull(peerAddresses, "peerAddresses should not be null");
174         Preconditions.checkNotNull(datastoreContext, "dataStoreContext should not be null");
175         Preconditions.checkNotNull(schemaContext, "schemaContext should not be null");
176
177         return Props.create(new ShardCreator(name, peerAddresses, datastoreContext, schemaContext));
178     }
179
180     private Optional<ActorRef> createRoleChangeNotifier(String shardId) {
181         ActorRef shardRoleChangeNotifier = this.getContext().actorOf(
182             RoleChangeNotifier.getProps(shardId), shardId + "-notifier");
183         return Optional.of(shardRoleChangeNotifier);
184     }
185
186     @Override
187     public void postStop() {
188         LOG.info("Stopping Shard {}", persistenceId());
189
190         super.postStop();
191
192         if(txCommitTimeoutCheckSchedule != null) {
193             txCommitTimeoutCheckSchedule.cancel();
194         }
195
196         shardMBean.unregisterMBean();
197     }
198
199     @Override
200     public void onReceiveRecover(final Object message) throws Exception {
201         if(LOG.isDebugEnabled()) {
202             LOG.debug("{}: onReceiveRecover: Received message {} from {}", persistenceId(),
203                 message.getClass().toString(), getSender());
204         }
205
206         if (message instanceof RecoveryFailure){
207             LOG.error("{}: Recovery failed because of this cause",
208                     persistenceId(), ((RecoveryFailure) message).cause());
209
210             // Even though recovery failed, we still need to finish our recovery, eg send the
211             // ActorInitialized message and start the txCommitTimeoutCheckSchedule.
212             onRecoveryComplete();
213         } else {
214             super.onReceiveRecover(message);
215             if(LOG.isTraceEnabled()) {
216                 appendEntriesReplyTracker.begin();
217             }
218         }
219     }
220
221     @Override
222     public void onReceiveCommand(final Object message) throws Exception {
223
224         MessageTracker.Context context = appendEntriesReplyTracker.received(message);
225
226         if(context.error().isPresent()){
227             LOG.trace("{} : AppendEntriesReply failed to arrive at the expected interval {}", persistenceId(),
228                     context.error());
229         }
230
231         try {
232             if (CreateTransaction.SERIALIZABLE_CLASS.isInstance(message)) {
233                 handleCreateTransaction(message);
234             } else if (BatchedModifications.class.isInstance(message)) {
235                 handleBatchedModifications((BatchedModifications)message);
236             } else if (message instanceof ForwardedReadyTransaction) {
237                 commitCoordinator.handleForwardedReadyTransaction((ForwardedReadyTransaction) message,
238                         getSender(), this);
239             } else if (message instanceof ReadyLocalTransaction) {
240                 handleReadyLocalTransaction((ReadyLocalTransaction)message);
241             } else if (CanCommitTransaction.SERIALIZABLE_CLASS.isInstance(message)) {
242                 handleCanCommitTransaction(CanCommitTransaction.fromSerializable(message));
243             } else if (CommitTransaction.SERIALIZABLE_CLASS.isInstance(message)) {
244                 handleCommitTransaction(CommitTransaction.fromSerializable(message));
245             } else if (AbortTransaction.SERIALIZABLE_CLASS.isInstance(message)) {
246                 handleAbortTransaction(AbortTransaction.fromSerializable(message));
247             } else if (CloseTransactionChain.SERIALIZABLE_CLASS.isInstance(message)) {
248                 closeTransactionChain(CloseTransactionChain.fromSerializable(message));
249             } else if (message instanceof RegisterChangeListener) {
250                 changeSupport.onMessage((RegisterChangeListener) message, isLeader());
251             } else if (message instanceof RegisterDataTreeChangeListener) {
252                 treeChangeSupport.onMessage((RegisterDataTreeChangeListener) message, isLeader());
253             } else if (message instanceof UpdateSchemaContext) {
254                 updateSchemaContext((UpdateSchemaContext) message);
255             } else if (message instanceof PeerAddressResolved) {
256                 PeerAddressResolved resolved = (PeerAddressResolved) message;
257                 setPeerAddress(resolved.getPeerId().toString(),
258                         resolved.getPeerAddress());
259             } else if (message.equals(TX_COMMIT_TIMEOUT_CHECK_MESSAGE)) {
260                 handleTransactionCommitTimeoutCheck();
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 {
271                 super.onReceiveCommand(message);
272             }
273         } finally {
274             context.done();
275         }
276     }
277
278     public int getPendingTxCommitQueueSize() {
279         return commitCoordinator.getQueueSize();
280     }
281
282     @Override
283     protected Optional<ActorRef> getRoleChangeNotifier() {
284         return roleChangeNotifier;
285     }
286
287     @Override
288     protected LeaderStateChanged newLeaderStateChanged(String memberId, String leaderId, short leaderPayloadVersion) {
289         return new ShardLeaderStateChanged(memberId, leaderId,
290                 isLeader() ? Optional.<DataTree>of(store.getDataTree()) : Optional.<DataTree>absent(),
291                 leaderPayloadVersion);
292     }
293
294     private void onDatastoreContext(DatastoreContext context) {
295         datastoreContext = context;
296
297         commitCoordinator.setQueueCapacity(datastoreContext.getShardTransactionCommitQueueCapacity());
298
299         setTransactionCommitTimeout();
300
301         if(datastoreContext.isPersistent() && !persistence().isRecoveryApplicable()) {
302             setPersistence(true);
303         } else if(!datastoreContext.isPersistent() && persistence().isRecoveryApplicable()) {
304             setPersistence(false);
305         }
306
307         updateConfigParams(datastoreContext.getShardRaftConfig());
308     }
309
310     private void handleTransactionCommitTimeoutCheck() {
311         CohortEntry cohortEntry = commitCoordinator.getCurrentCohortEntry();
312         if(cohortEntry != null) {
313             if(cohortEntry.isExpired(transactionCommitTimeout)) {
314                 LOG.warn("{}: Current transaction {} has timed out after {} ms - aborting",
315                         persistenceId(), cohortEntry.getTransactionID(), transactionCommitTimeout);
316
317                 doAbortTransaction(cohortEntry.getTransactionID(), null);
318             }
319         }
320
321         commitCoordinator.cleanupExpiredCohortEntries();
322     }
323
324     private static boolean isEmptyCommit(final DataTreeCandidate candidate) {
325         return ModificationType.UNMODIFIED.equals(candidate.getRootNode().getModificationType());
326     }
327
328     void continueCommit(final CohortEntry cohortEntry) throws Exception {
329         final DataTreeCandidate candidate = cohortEntry.getCohort().getCandidate();
330
331         // If we do not have any followers and we are not using persistence
332         // or if cohortEntry has no modifications
333         // we can apply modification to the state immediately
334         if ((!hasFollowers() && !persistence().isRecoveryApplicable()) || isEmptyCommit(candidate)) {
335             applyModificationToState(cohortEntry.getReplySender(), cohortEntry.getTransactionID(), candidate);
336         } else {
337             Shard.this.persistData(cohortEntry.getReplySender(), cohortEntry.getTransactionID(),
338                 DataTreeCandidatePayload.create(candidate));
339         }
340     }
341
342     private void handleCommitTransaction(final CommitTransaction commit) {
343         if(!commitCoordinator.handleCommit(commit.getTransactionID(), getSender(), this)) {
344             shardMBean.incrementFailedTransactionsCount();
345         }
346     }
347
348     private void finishCommit(@Nonnull final ActorRef sender, @Nonnull final String transactionID, @Nonnull final CohortEntry cohortEntry) {
349         LOG.debug("{}: Finishing commit for transaction {}", persistenceId(), cohortEntry.getTransactionID());
350
351         try {
352             // We block on the future here so we don't have to worry about possibly accessing our
353             // state on a different thread outside of our dispatcher. Also, the data store
354             // currently uses a same thread executor anyway.
355             cohortEntry.getCohort().commit().get();
356
357             sender.tell(CommitTransactionReply.INSTANCE.toSerializable(), getSelf());
358
359             shardMBean.incrementCommittedTransactionCount();
360             shardMBean.setLastCommittedTransactionTime(System.currentTimeMillis());
361
362         } catch (Exception e) {
363             sender.tell(new akka.actor.Status.Failure(e), getSelf());
364
365             LOG.error("{}, An exception occurred while committing transaction {}", persistenceId(),
366                     transactionID, e);
367             shardMBean.incrementFailedTransactionsCount();
368         } finally {
369             commitCoordinator.currentTransactionComplete(transactionID, true);
370         }
371     }
372
373     private void finishCommit(@Nonnull final ActorRef sender, final @Nonnull String transactionID) {
374         // With persistence enabled, this method is called via applyState by the leader strategy
375         // after the commit has been replicated to a majority of the followers.
376
377         CohortEntry cohortEntry = commitCoordinator.getCohortEntryIfCurrent(transactionID);
378         if (cohortEntry == null) {
379             // The transaction is no longer the current commit. This can happen if the transaction
380             // was aborted prior, most likely due to timeout in the front-end. We need to finish
381             // committing the transaction though since it was successfully persisted and replicated
382             // however we can't use the original cohort b/c it was already preCommitted and may
383             // conflict with the current commit or may have been aborted so we commit with a new
384             // transaction.
385             cohortEntry = commitCoordinator.getAndRemoveCohortEntry(transactionID);
386             if(cohortEntry != null) {
387                 try {
388                     store.applyForeignCandidate(transactionID, cohortEntry.getCohort().getCandidate());
389                 } catch (DataValidationFailedException e) {
390                     shardMBean.incrementFailedTransactionsCount();
391                     LOG.error("{}: Failed to re-apply transaction {}", persistenceId(), transactionID, e);
392                 }
393
394                 sender.tell(CommitTransactionReply.INSTANCE.toSerializable(), getSelf());
395             } else {
396                 // This really shouldn't happen - it likely means that persistence or replication
397                 // took so long to complete such that the cohort entry was expired from the cache.
398                 IllegalStateException ex = new IllegalStateException(
399                         String.format("%s: Could not finish committing transaction %s - no CohortEntry found",
400                                 persistenceId(), transactionID));
401                 LOG.error(ex.getMessage());
402                 sender.tell(new akka.actor.Status.Failure(ex), getSelf());
403             }
404         } else {
405             finishCommit(sender, transactionID, cohortEntry);
406         }
407     }
408
409     private void handleCanCommitTransaction(final CanCommitTransaction canCommit) {
410         LOG.debug("{}: Can committing transaction {}", persistenceId(), canCommit.getTransactionID());
411         commitCoordinator.handleCanCommit(canCommit.getTransactionID(), getSender(), this);
412     }
413
414     private void noLeaderError(String errMessage, Object message) {
415         // TODO: rather than throwing an immediate exception, we could schedule a timer to try again to make
416         // it more resilient in case we're in the process of electing a new leader.
417         getSender().tell(new akka.actor.Status.Failure(new NoShardLeaderException(errMessage, persistenceId())), getSelf());
418     }
419
420     private void handleBatchedModifications(BatchedModifications batched) {
421         // This message is sent to prepare the modifications transaction directly on the Shard as an
422         // optimization to avoid the extra overhead of a separate ShardTransaction actor. On the last
423         // BatchedModifications message, the caller sets the ready flag in the message indicating
424         // modifications are complete. The reply contains the cohort actor path (this actor) for the caller
425         // to initiate the 3-phase commit. This also avoids the overhead of sending an additional
426         // ReadyTransaction message.
427
428         // If we're not the leader then forward to the leader. This is a safety measure - we shouldn't
429         // normally get here if we're not the leader as the front-end (TransactionProxy) should determine
430         // the primary/leader shard. However with timing and caching on the front-end, there's a small
431         // window where it could have a stale leader during leadership transitions.
432         //
433         if(isLeader()) {
434             failIfIsolatedLeader(getSender());
435
436             try {
437                 commitCoordinator.handleBatchedModifications(batched, getSender(), this);
438             } catch (Exception e) {
439                 LOG.error("{}: Error handling BatchedModifications for Tx {}", persistenceId(),
440                         batched.getTransactionID(), e);
441                 getSender().tell(new akka.actor.Status.Failure(e), getSelf());
442             }
443         } else {
444             ActorSelection leader = getLeader();
445             if(leader != null) {
446                 // TODO: what if this is not the first batch and leadership changed in between batched messages?
447                 // We could check if the commitCoordinator already has a cached entry and forward all the previous
448                 // batched modifications.
449                 LOG.debug("{}: Forwarding BatchedModifications to leader {}", persistenceId(), leader);
450                 leader.forward(batched, getContext());
451             } else {
452                 noLeaderError("Could not commit transaction " + batched.getTransactionID(), batched);
453             }
454         }
455     }
456
457     private boolean failIfIsolatedLeader(ActorRef sender) {
458         if(getRaftState() == RaftState.IsolatedLeader) {
459             sender.tell(new akka.actor.Status.Failure(new NoShardLeaderException(String.format(
460                     "Shard %s was the leader but has lost contact with all of its followers. Either all" +
461                     " other follower nodes are down or this node is isolated by a network partition.",
462                     persistenceId()))), getSelf());
463             return true;
464         }
465
466         return false;
467     }
468
469     private void handleReadyLocalTransaction(final ReadyLocalTransaction message) {
470         if (isLeader()) {
471             failIfIsolatedLeader(getSender());
472
473             try {
474                 commitCoordinator.handleReadyLocalTransaction(message, getSender(), this);
475             } catch (Exception e) {
476                 LOG.error("{}: Error handling ReadyLocalTransaction for Tx {}", persistenceId(),
477                         message.getTransactionID(), e);
478                 getSender().tell(new akka.actor.Status.Failure(e), getSelf());
479             }
480         } else {
481             ActorSelection leader = getLeader();
482             if (leader != null) {
483                 LOG.debug("{}: Forwarding ReadyLocalTransaction to leader {}", persistenceId(), leader);
484                 message.setRemoteVersion(getCurrentBehavior().getLeaderPayloadVersion());
485                 leader.forward(message, getContext());
486             } else {
487                 noLeaderError("Could not commit transaction " + message.getTransactionID(), message);
488             }
489         }
490     }
491
492     private void handleAbortTransaction(final AbortTransaction abort) {
493         doAbortTransaction(abort.getTransactionID(), getSender());
494     }
495
496     void doAbortTransaction(final String transactionID, final ActorRef sender) {
497         final CohortEntry cohortEntry = commitCoordinator.getCohortEntryIfCurrent(transactionID);
498         if(cohortEntry != null) {
499             LOG.debug("{}: Aborting transaction {}", persistenceId(), transactionID);
500
501             // We don't remove the cached cohort entry here (ie pass false) in case the Tx was
502             // aborted during replication in which case we may still commit locally if replication
503             // succeeds.
504             commitCoordinator.currentTransactionComplete(transactionID, false);
505
506             final ListenableFuture<Void> future = cohortEntry.getCohort().abort();
507             final ActorRef self = getSelf();
508
509             Futures.addCallback(future, new FutureCallback<Void>() {
510                 @Override
511                 public void onSuccess(final Void v) {
512                     shardMBean.incrementAbortTransactionsCount();
513
514                     if(sender != null) {
515                         sender.tell(AbortTransactionReply.INSTANCE.toSerializable(), self);
516                     }
517                 }
518
519                 @Override
520                 public void onFailure(final Throwable t) {
521                     LOG.error("{}: An exception happened during abort", persistenceId(), t);
522
523                     if(sender != null) {
524                         sender.tell(new akka.actor.Status.Failure(t), self);
525                     }
526                 }
527             });
528         }
529     }
530
531     private void handleCreateTransaction(final Object message) {
532         if (isLeader()) {
533             createTransaction(CreateTransaction.fromSerializable(message));
534         } else if (getLeader() != null) {
535             getLeader().forward(message, getContext());
536         } else {
537             getSender().tell(new akka.actor.Status.Failure(new NoShardLeaderException(
538                     "Could not create a shard transaction", persistenceId())), getSelf());
539         }
540     }
541
542     private void closeTransactionChain(final CloseTransactionChain closeTransactionChain) {
543         store.closeTransactionChain(closeTransactionChain.getTransactionChainId());
544     }
545
546     private ActorRef createTypedTransactionActor(int transactionType,
547             ShardTransactionIdentifier transactionId, String transactionChainId,
548             short clientVersion ) {
549
550         return transactionActorFactory.newShardTransaction(TransactionType.fromInt(transactionType),
551                 transactionId, transactionChainId, clientVersion);
552     }
553
554     private void createTransaction(CreateTransaction createTransaction) {
555         try {
556             if(TransactionType.fromInt(createTransaction.getTransactionType()) != TransactionType.READ_ONLY &&
557                     failIfIsolatedLeader(getSender())) {
558                 return;
559             }
560
561             ActorRef transactionActor = createTransaction(createTransaction.getTransactionType(),
562                 createTransaction.getTransactionId(), createTransaction.getTransactionChainId(),
563                 createTransaction.getVersion());
564
565             getSender().tell(new CreateTransactionReply(Serialization.serializedActorPath(transactionActor),
566                     createTransaction.getTransactionId()).toSerializable(), getSelf());
567         } catch (Exception e) {
568             getSender().tell(new akka.actor.Status.Failure(e), getSelf());
569         }
570     }
571
572     private ActorRef createTransaction(int transactionType, String remoteTransactionId,
573             String transactionChainId, short clientVersion) {
574
575
576         ShardTransactionIdentifier transactionId = new ShardTransactionIdentifier(remoteTransactionId);
577
578         if(LOG.isDebugEnabled()) {
579             LOG.debug("{}: Creating transaction : {} ", persistenceId(), transactionId);
580         }
581
582         ActorRef transactionActor = createTypedTransactionActor(transactionType, transactionId,
583                 transactionChainId, clientVersion);
584
585         return transactionActor;
586     }
587
588     private void commitWithNewTransaction(final Modification modification) {
589         ReadWriteShardDataTreeTransaction tx = store.newReadWriteTransaction(modification.toString(), null);
590         modification.apply(tx.getSnapshot());
591         try {
592             snapshotCohort.syncCommitTransaction(tx);
593             shardMBean.incrementCommittedTransactionCount();
594             shardMBean.setLastCommittedTransactionTime(System.currentTimeMillis());
595         } catch (Exception e) {
596             shardMBean.incrementFailedTransactionsCount();
597             LOG.error("{}: Failed to commit", persistenceId(), e);
598         }
599     }
600
601     private void updateSchemaContext(final UpdateSchemaContext message) {
602         updateSchemaContext(message.getSchemaContext());
603     }
604
605     @VisibleForTesting
606     void updateSchemaContext(final SchemaContext schemaContext) {
607         store.updateSchemaContext(schemaContext);
608     }
609
610     private boolean isMetricsCaptureEnabled() {
611         CommonConfig config = new CommonConfig(getContext().system().settings().config());
612         return config.isMetricCaptureEnabled();
613     }
614
615     @Override
616     @VisibleForTesting
617     public RaftActorSnapshotCohort getRaftActorSnapshotCohort() {
618         return snapshotCohort;
619     }
620
621     @Override
622     @Nonnull
623     protected RaftActorRecoveryCohort getRaftActorRecoveryCohort() {
624         return new ShardRecoveryCoordinator(store, store.getSchemaContext(), persistenceId(), LOG);
625     }
626
627     @Override
628     protected void onRecoveryComplete() {
629         //notify shard manager
630         getContext().parent().tell(new ActorInitialized(), getSelf());
631
632         // Being paranoid here - this method should only be called once but just in case...
633         if(txCommitTimeoutCheckSchedule == null) {
634             // Schedule a message to be periodically sent to check if the current in-progress
635             // transaction should be expired and aborted.
636             FiniteDuration period = Duration.create(transactionCommitTimeout / 3, TimeUnit.MILLISECONDS);
637             txCommitTimeoutCheckSchedule = getContext().system().scheduler().schedule(
638                     period, period, getSelf(),
639                     TX_COMMIT_TIMEOUT_CHECK_MESSAGE, getContext().dispatcher(), ActorRef.noSender());
640         }
641     }
642
643     @Override
644     protected void applyState(final ActorRef clientActor, final String identifier, final Object data) {
645         if (data instanceof DataTreeCandidatePayload) {
646             if (clientActor == null) {
647                 // No clientActor indicates a replica coming from the leader
648                 try {
649                     store.applyForeignCandidate(identifier, ((DataTreeCandidatePayload)data).getCandidate());
650                 } catch (DataValidationFailedException | IOException e) {
651                     LOG.error("{}: Error applying replica {}", persistenceId(), identifier, e);
652                 }
653             } else {
654                 // Replication consensus reached, proceed to commit
655                 finishCommit(clientActor, identifier);
656             }
657         } else if (data instanceof ModificationPayload) {
658             try {
659                 applyModificationToState(clientActor, identifier, ((ModificationPayload) data).getModification());
660             } catch (ClassNotFoundException | IOException e) {
661                 LOG.error("{}: Error extracting ModificationPayload", persistenceId(), e);
662             }
663         } else if (data instanceof CompositeModificationPayload) {
664             Object modification = ((CompositeModificationPayload) data).getModification();
665
666             applyModificationToState(clientActor, identifier, modification);
667         } else if(data instanceof CompositeModificationByteStringPayload ){
668             Object modification = ((CompositeModificationByteStringPayload) data).getModification();
669
670             applyModificationToState(clientActor, identifier, modification);
671         } else {
672             LOG.error("{}: Unknown state received {} Class loader = {} CompositeNodeMod.ClassLoader = {}",
673                     persistenceId(), data, data.getClass().getClassLoader(),
674                     CompositeModificationPayload.class.getClassLoader());
675         }
676     }
677
678     private void applyModificationToState(ActorRef clientActor, String identifier, Object modification) {
679         if(modification == null) {
680             LOG.error(
681                     "{}: modification is null - this is very unexpected, clientActor = {}, identifier = {}",
682                     persistenceId(), identifier, clientActor != null ? clientActor.path().toString() : null);
683         } else if(clientActor == null) {
684             // There's no clientActor to which to send a commit reply so we must be applying
685             // replicated state from the leader.
686             commitWithNewTransaction(MutableCompositeModification.fromSerializable(modification));
687         } else {
688             // This must be the OK to commit after replication consensus.
689             finishCommit(clientActor, identifier);
690         }
691     }
692
693     @Override
694     protected void onStateChanged() {
695         boolean isLeader = isLeader();
696         changeSupport.onLeadershipChange(isLeader);
697         treeChangeSupport.onLeadershipChange(isLeader);
698
699         // If this actor is no longer the leader close all the transaction chains
700         if (!isLeader) {
701             if(LOG.isDebugEnabled()) {
702                 LOG.debug(
703                     "{}: onStateChanged: Closing all transaction chains because shard {} is no longer the leader",
704                     persistenceId(), getId());
705             }
706
707             store.closeAllTransactionChains();
708         }
709     }
710
711     @Override
712     protected void onLeaderChanged(String oldLeader, String newLeader) {
713         shardMBean.incrementLeadershipChangeCount();
714     }
715
716     @Override
717     public String persistenceId() {
718         return this.name;
719     }
720
721     @VisibleForTesting
722     ShardCommitCoordinator getCommitCoordinator() {
723         return commitCoordinator;
724     }
725
726
727     private static class ShardCreator implements Creator<Shard> {
728
729         private static final long serialVersionUID = 1L;
730
731         final ShardIdentifier name;
732         final Map<String, String> peerAddresses;
733         final DatastoreContext datastoreContext;
734         final SchemaContext schemaContext;
735
736         ShardCreator(final ShardIdentifier name, final Map<String, String> peerAddresses,
737                 final DatastoreContext datastoreContext, final SchemaContext schemaContext) {
738             this.name = name;
739             this.peerAddresses = peerAddresses;
740             this.datastoreContext = datastoreContext;
741             this.schemaContext = schemaContext;
742         }
743
744         @Override
745         public Shard create() throws Exception {
746             return new Shard(name, peerAddresses, datastoreContext, schemaContext);
747         }
748     }
749
750     @VisibleForTesting
751     public ShardDataTree getDataStore() {
752         return store;
753     }
754
755     @VisibleForTesting
756     ShardStats getShardMBean() {
757         return shardMBean;
758     }
759 }