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