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