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