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