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