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