ef4bab44f8ebb51c65312d60822dd36fdc6d9c49
[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     public int getCohortCacheSize() {
288         return commitCoordinator.getCohortCacheSize();
289     }
290
291     @Override
292     protected Optional<ActorRef> getRoleChangeNotifier() {
293         return roleChangeNotifier;
294     }
295
296     @Override
297     protected LeaderStateChanged newLeaderStateChanged(String memberId, String leaderId, short leaderPayloadVersion) {
298         return new ShardLeaderStateChanged(memberId, leaderId,
299                 isLeader() ? Optional.<DataTree>of(store.getDataTree()) : Optional.<DataTree>absent(),
300                 leaderPayloadVersion);
301     }
302
303     protected void onDatastoreContext(DatastoreContext context) {
304         datastoreContext = context;
305
306         commitCoordinator.setQueueCapacity(datastoreContext.getShardTransactionCommitQueueCapacity());
307
308         setTransactionCommitTimeout();
309
310         if(datastoreContext.isPersistent() && !persistence().isRecoveryApplicable()) {
311             setPersistence(true);
312         } else if(!datastoreContext.isPersistent() && persistence().isRecoveryApplicable()) {
313             setPersistence(false);
314         }
315
316         updateConfigParams(datastoreContext.getShardRaftConfig());
317     }
318
319     private void handleTransactionCommitTimeoutCheck() {
320         CohortEntry cohortEntry = commitCoordinator.getCurrentCohortEntry();
321         if(cohortEntry != null) {
322             if(cohortEntry.isExpired(transactionCommitTimeout)) {
323                 LOG.warn("{}: Current transaction {} has timed out after {} ms - aborting",
324                         persistenceId(), cohortEntry.getTransactionID(), transactionCommitTimeout);
325
326                 doAbortTransaction(cohortEntry.getTransactionID(), null);
327             }
328         }
329
330         commitCoordinator.cleanupExpiredCohortEntries();
331     }
332
333     private static boolean isEmptyCommit(final DataTreeCandidate candidate) {
334         return ModificationType.UNMODIFIED.equals(candidate.getRootNode().getModificationType());
335     }
336
337     void continueCommit(final CohortEntry cohortEntry) {
338         final DataTreeCandidate candidate = cohortEntry.getCandidate();
339
340         // If we do not have any followers and we are not using persistence
341         // or if cohortEntry has no modifications
342         // we can apply modification to the state immediately
343         if ((!hasFollowers() && !persistence().isRecoveryApplicable()) || isEmptyCommit(candidate)) {
344             applyModificationToState(cohortEntry.getReplySender(), cohortEntry.getTransactionID(), candidate);
345         } else {
346             Shard.this.persistData(cohortEntry.getReplySender(), cohortEntry.getTransactionID(),
347                     DataTreeCandidatePayload.create(candidate));
348         }
349     }
350
351     private void handleCommitTransaction(final CommitTransaction commit) {
352         if(!commitCoordinator.handleCommit(commit.getTransactionID(), getSender(), this)) {
353             shardMBean.incrementFailedTransactionsCount();
354         }
355     }
356
357     private void finishCommit(@Nonnull final ActorRef sender, @Nonnull final String transactionID, @Nonnull final CohortEntry cohortEntry) {
358         LOG.debug("{}: Finishing commit for transaction {}", persistenceId(), cohortEntry.getTransactionID());
359
360         try {
361             cohortEntry.commit();
362
363             sender.tell(CommitTransactionReply.INSTANCE.toSerializable(), getSelf());
364
365             shardMBean.incrementCommittedTransactionCount();
366             shardMBean.setLastCommittedTransactionTime(System.currentTimeMillis());
367
368         } catch (Exception e) {
369             sender.tell(new akka.actor.Status.Failure(e), getSelf());
370
371             LOG.error("{}, An exception occurred while committing transaction {}", persistenceId(),
372                     transactionID, e);
373             shardMBean.incrementFailedTransactionsCount();
374         } finally {
375             commitCoordinator.currentTransactionComplete(transactionID, true);
376         }
377     }
378
379     private void finishCommit(@Nonnull final ActorRef sender, final @Nonnull String transactionID) {
380         // With persistence enabled, this method is called via applyState by the leader strategy
381         // after the commit has been replicated to a majority of the followers.
382
383         CohortEntry cohortEntry = commitCoordinator.getCohortEntryIfCurrent(transactionID);
384         if (cohortEntry == null) {
385             // The transaction is no longer the current commit. This can happen if the transaction
386             // was aborted prior, most likely due to timeout in the front-end. We need to finish
387             // committing the transaction though since it was successfully persisted and replicated
388             // however we can't use the original cohort b/c it was already preCommitted and may
389             // conflict with the current commit or may have been aborted so we commit with a new
390             // transaction.
391             cohortEntry = commitCoordinator.getAndRemoveCohortEntry(transactionID);
392             if(cohortEntry != null) {
393                 try {
394                     store.applyForeignCandidate(transactionID, cohortEntry.getCandidate());
395                 } catch (DataValidationFailedException e) {
396                     shardMBean.incrementFailedTransactionsCount();
397                     LOG.error("{}: Failed to re-apply transaction {}", persistenceId(), transactionID, e);
398                 }
399
400                 sender.tell(CommitTransactionReply.INSTANCE.toSerializable(), getSelf());
401             } else {
402                 // This really shouldn't happen - it likely means that persistence or replication
403                 // took so long to complete such that the cohort entry was expired from the cache.
404                 IllegalStateException ex = new IllegalStateException(
405                         String.format("%s: Could not finish committing transaction %s - no CohortEntry found",
406                                 persistenceId(), transactionID));
407                 LOG.error(ex.getMessage());
408                 sender.tell(new akka.actor.Status.Failure(ex), getSelf());
409             }
410         } else {
411             finishCommit(sender, transactionID, cohortEntry);
412         }
413     }
414
415     private void handleCanCommitTransaction(final CanCommitTransaction canCommit) {
416         LOG.debug("{}: Can committing transaction {}", persistenceId(), canCommit.getTransactionID());
417         commitCoordinator.handleCanCommit(canCommit.getTransactionID(), getSender(), this);
418     }
419
420     protected void handleBatchedModificationsLocal(BatchedModifications batched, ActorRef sender) {
421         try {
422             commitCoordinator.handleBatchedModifications(batched, sender, this);
423         } catch (Exception e) {
424             LOG.error("{}: Error handling BatchedModifications for Tx {}", persistenceId(),
425                     batched.getTransactionID(), e);
426             sender.tell(new akka.actor.Status.Failure(e), getSelf());
427         }
428     }
429
430     private void handleBatchedModifications(BatchedModifications batched) {
431         // This message is sent to prepare the modifications transaction directly on the Shard as an
432         // optimization to avoid the extra overhead of a separate ShardTransaction actor. On the last
433         // BatchedModifications message, the caller sets the ready flag in the message indicating
434         // modifications are complete. The reply contains the cohort actor path (this actor) for the caller
435         // to initiate the 3-phase commit. This also avoids the overhead of sending an additional
436         // ReadyTransaction message.
437
438         // If we're not the leader then forward to the leader. This is a safety measure - we shouldn't
439         // normally get here if we're not the leader as the front-end (TransactionProxy) should determine
440         // the primary/leader shard. However with timing and caching on the front-end, there's a small
441         // window where it could have a stale leader during leadership transitions.
442         //
443         boolean isLeaderActive = isLeaderActive();
444         if (isLeader() && isLeaderActive) {
445             handleBatchedModificationsLocal(batched, getSender());
446         } else {
447             ActorSelection leader = getLeader();
448             if (!isLeaderActive || leader == null) {
449                 messageRetrySupport.addMessageToRetry(batched, getSender(),
450                         "Could not commit transaction " + batched.getTransactionID());
451             } else {
452                 // TODO: what if this is not the first batch and leadership changed in between batched messages?
453                 // We could check if the commitCoordinator already has a cached entry and forward all the previous
454                 // batched modifications.
455                 LOG.debug("{}: Forwarding BatchedModifications to leader {}", persistenceId(), leader);
456                 leader.forward(batched, getContext());
457             }
458         }
459     }
460
461     private boolean failIfIsolatedLeader(ActorRef sender) {
462         if(isIsolatedLeader()) {
463             sender.tell(new akka.actor.Status.Failure(new NoShardLeaderException(String.format(
464                     "Shard %s was the leader but has lost contact with all of its followers. Either all" +
465                     " other follower nodes are down or this node is isolated by a network partition.",
466                     persistenceId()))), getSelf());
467             return true;
468         }
469
470         return false;
471     }
472
473     protected boolean isIsolatedLeader() {
474         return getRaftState() == RaftState.IsolatedLeader;
475     }
476
477     private void handleReadyLocalTransaction(final ReadyLocalTransaction message) {
478         LOG.debug("{}: handleReadyLocalTransaction for {}", persistenceId(), message.getTransactionID());
479
480         boolean isLeaderActive = isLeaderActive();
481         if (isLeader() && isLeaderActive) {
482             try {
483                 commitCoordinator.handleReadyLocalTransaction(message, getSender(), this);
484             } catch (Exception e) {
485                 LOG.error("{}: Error handling ReadyLocalTransaction for Tx {}", persistenceId(),
486                         message.getTransactionID(), e);
487                 getSender().tell(new akka.actor.Status.Failure(e), getSelf());
488             }
489         } else {
490             ActorSelection leader = getLeader();
491             if (!isLeaderActive || leader == null) {
492                 messageRetrySupport.addMessageToRetry(message, getSender(),
493                         "Could not commit transaction " + message.getTransactionID());
494             } else {
495                 LOG.debug("{}: Forwarding ReadyLocalTransaction to leader {}", persistenceId(), leader);
496                 message.setRemoteVersion(getCurrentBehavior().getLeaderPayloadVersion());
497                 leader.forward(message, getContext());
498             }
499         }
500     }
501
502     private void handleForwardedReadyTransaction(ForwardedReadyTransaction forwardedReady) {
503         LOG.debug("{}: handleForwardedReadyTransaction for {}", persistenceId(), forwardedReady.getTransactionID());
504
505         boolean isLeaderActive = isLeaderActive();
506         if (isLeader() && isLeaderActive) {
507             commitCoordinator.handleForwardedReadyTransaction(forwardedReady, getSender(), this);
508         } else {
509             ActorSelection leader = getLeader();
510             if (!isLeaderActive || leader == null) {
511                 messageRetrySupport.addMessageToRetry(forwardedReady, getSender(),
512                         "Could not commit transaction " + forwardedReady.getTransactionID());
513             } else {
514                 LOG.debug("{}: Forwarding ForwardedReadyTransaction to leader {}", persistenceId(), leader);
515
516                 ReadyLocalTransaction readyLocal = new ReadyLocalTransaction(forwardedReady.getTransactionID(),
517                         forwardedReady.getTransaction().getSnapshot(), forwardedReady.isDoImmediateCommit());
518                 readyLocal.setRemoteVersion(getCurrentBehavior().getLeaderPayloadVersion());
519                 leader.forward(readyLocal, getContext());
520             }
521         }
522     }
523
524     private void handleAbortTransaction(final AbortTransaction abort) {
525         doAbortTransaction(abort.getTransactionID(), getSender());
526     }
527
528     void doAbortTransaction(final String transactionID, final ActorRef sender) {
529         commitCoordinator.handleAbort(transactionID, sender, this);
530     }
531
532     private void handleCreateTransaction(final Object message) {
533         if (isLeader()) {
534             createTransaction(CreateTransaction.fromSerializable(message));
535         } else if (getLeader() != null) {
536             getLeader().forward(message, getContext());
537         } else {
538             getSender().tell(new akka.actor.Status.Failure(new NoShardLeaderException(
539                     "Could not create a shard transaction", persistenceId())), getSelf());
540         }
541     }
542
543     private void closeTransactionChain(final CloseTransactionChain closeTransactionChain) {
544         store.closeTransactionChain(closeTransactionChain.getTransactionChainId());
545     }
546
547     private ActorRef createTypedTransactionActor(int transactionType,
548             ShardTransactionIdentifier transactionId, String transactionChainId,
549             short clientVersion ) {
550
551         return transactionActorFactory.newShardTransaction(TransactionType.fromInt(transactionType),
552                 transactionId, transactionChainId, clientVersion);
553     }
554
555     private void createTransaction(CreateTransaction createTransaction) {
556         try {
557             if(TransactionType.fromInt(createTransaction.getTransactionType()) != TransactionType.READ_ONLY &&
558                     failIfIsolatedLeader(getSender())) {
559                 return;
560             }
561
562             ActorRef transactionActor = createTransaction(createTransaction.getTransactionType(),
563                 createTransaction.getTransactionId(), createTransaction.getTransactionChainId(),
564                 createTransaction.getVersion());
565
566             getSender().tell(new CreateTransactionReply(Serialization.serializedActorPath(transactionActor),
567                     createTransaction.getTransactionId()).toSerializable(), getSelf());
568         } catch (Exception e) {
569             getSender().tell(new akka.actor.Status.Failure(e), getSelf());
570         }
571     }
572
573     private ActorRef createTransaction(int transactionType, String remoteTransactionId,
574             String transactionChainId, short clientVersion) {
575
576
577         ShardTransactionIdentifier transactionId = new ShardTransactionIdentifier(remoteTransactionId);
578
579         if(LOG.isDebugEnabled()) {
580             LOG.debug("{}: Creating transaction : {} ", persistenceId(), transactionId);
581         }
582
583         ActorRef transactionActor = createTypedTransactionActor(transactionType, transactionId,
584                 transactionChainId, clientVersion);
585
586         return transactionActor;
587     }
588
589     private void commitWithNewTransaction(final Modification modification) {
590         ReadWriteShardDataTreeTransaction tx = store.newReadWriteTransaction(modification.toString(), null);
591         modification.apply(tx.getSnapshot());
592         try {
593             snapshotCohort.syncCommitTransaction(tx);
594             shardMBean.incrementCommittedTransactionCount();
595             shardMBean.setLastCommittedTransactionTime(System.currentTimeMillis());
596         } catch (Exception e) {
597             shardMBean.incrementFailedTransactionsCount();
598             LOG.error("{}: Failed to commit", persistenceId(), e);
599         }
600     }
601
602     private void updateSchemaContext(final UpdateSchemaContext message) {
603         updateSchemaContext(message.getSchemaContext());
604     }
605
606     @VisibleForTesting
607     void updateSchemaContext(final SchemaContext schemaContext) {
608         store.updateSchemaContext(schemaContext);
609     }
610
611     private boolean isMetricsCaptureEnabled() {
612         CommonConfig config = new CommonConfig(getContext().system().settings().config());
613         return config.isMetricCaptureEnabled();
614     }
615
616     @Override
617     @VisibleForTesting
618     public RaftActorSnapshotCohort getRaftActorSnapshotCohort() {
619         return snapshotCohort;
620     }
621
622     @Override
623     @Nonnull
624     protected RaftActorRecoveryCohort getRaftActorRecoveryCohort() {
625         return new ShardRecoveryCoordinator(store, store.getSchemaContext(),
626                 restoreFromSnapshot != null ? restoreFromSnapshot.getSnapshot() : null, persistenceId(), LOG);
627     }
628
629     @Override
630     protected void onRecoveryComplete() {
631         restoreFromSnapshot = null;
632
633         //notify shard manager
634         getContext().parent().tell(new ActorInitialized(), getSelf());
635
636         // Being paranoid here - this method should only be called once but just in case...
637         if(txCommitTimeoutCheckSchedule == null) {
638             // Schedule a message to be periodically sent to check if the current in-progress
639             // transaction should be expired and aborted.
640             FiniteDuration period = Duration.create(transactionCommitTimeout / 3, TimeUnit.MILLISECONDS);
641             txCommitTimeoutCheckSchedule = getContext().system().scheduler().schedule(
642                     period, period, getSelf(),
643                     TX_COMMIT_TIMEOUT_CHECK_MESSAGE, getContext().dispatcher(), ActorRef.noSender());
644         }
645     }
646
647     @Override
648     protected void applyState(final ActorRef clientActor, final String identifier, final Object data) {
649         if (data instanceof DataTreeCandidatePayload) {
650             if (clientActor == null) {
651                 // No clientActor indicates a replica coming from the leader
652                 try {
653                     store.applyForeignCandidate(identifier, ((DataTreeCandidatePayload)data).getCandidate());
654                 } catch (DataValidationFailedException | IOException e) {
655                     LOG.error("{}: Error applying replica {}", persistenceId(), identifier, e);
656                 }
657             } else {
658                 // Replication consensus reached, proceed to commit
659                 finishCommit(clientActor, identifier);
660             }
661         } else if (data instanceof ModificationPayload) {
662             try {
663                 applyModificationToState(clientActor, identifier, ((ModificationPayload) data).getModification());
664             } catch (ClassNotFoundException | IOException e) {
665                 LOG.error("{}: Error extracting ModificationPayload", persistenceId(), e);
666             }
667         } else if (data instanceof CompositeModificationPayload) {
668             Object modification = ((CompositeModificationPayload) data).getModification();
669
670             applyModificationToState(clientActor, identifier, modification);
671         } else if(data instanceof CompositeModificationByteStringPayload ){
672             Object modification = ((CompositeModificationByteStringPayload) data).getModification();
673
674             applyModificationToState(clientActor, identifier, modification);
675         } else {
676             LOG.error("{}: Unknown state received {} Class loader = {} CompositeNodeMod.ClassLoader = {}",
677                     persistenceId(), data, data.getClass().getClassLoader(),
678                     CompositeModificationPayload.class.getClassLoader());
679         }
680     }
681
682     private void applyModificationToState(ActorRef clientActor, String identifier, Object modification) {
683         if(modification == null) {
684             LOG.error(
685                     "{}: modification is null - this is very unexpected, clientActor = {}, identifier = {}",
686                     persistenceId(), identifier, clientActor != null ? clientActor.path().toString() : null);
687         } else if(clientActor == null) {
688             // There's no clientActor to which to send a commit reply so we must be applying
689             // replicated state from the leader.
690             commitWithNewTransaction(MutableCompositeModification.fromSerializable(modification));
691         } else {
692             // This must be the OK to commit after replication consensus.
693             finishCommit(clientActor, identifier);
694         }
695     }
696
697     @Override
698     protected void onStateChanged() {
699         boolean isLeader = isLeader();
700         boolean hasLeader = hasLeader();
701         changeSupport.onLeadershipChange(isLeader, hasLeader);
702         treeChangeSupport.onLeadershipChange(isLeader, hasLeader);
703
704         // If this actor is no longer the leader close all the transaction chains
705         if (!isLeader) {
706             if(LOG.isDebugEnabled()) {
707                 LOG.debug(
708                     "{}: onStateChanged: Closing all transaction chains because shard {} is no longer the leader",
709                     persistenceId(), getId());
710             }
711
712             store.closeAllTransactionChains();
713         }
714
715         if(hasLeader && !isIsolatedLeader()) {
716             messageRetrySupport.retryMessages();
717         }
718     }
719
720     @Override
721     protected void onLeaderChanged(String oldLeader, String newLeader) {
722         shardMBean.incrementLeadershipChangeCount();
723
724         if(hasLeader() && !isIsolatedLeader()) {
725             messageRetrySupport.retryMessages();
726         }
727     }
728
729     @Override
730     protected void pauseLeader(Runnable operation) {
731         LOG.debug("{}: In pauseLeader, operation: {}", persistenceId(), operation);
732         commitCoordinator.setRunOnPendingTransactionsComplete(operation);
733     }
734
735     @Override
736     public String persistenceId() {
737         return this.name;
738     }
739
740     @VisibleForTesting
741     ShardCommitCoordinator getCommitCoordinator() {
742         return commitCoordinator;
743     }
744
745     public DatastoreContext getDatastoreContext() {
746         return datastoreContext;
747     }
748
749     @VisibleForTesting
750     public ShardDataTree getDataStore() {
751         return store;
752     }
753
754     @VisibleForTesting
755     ShardStats getShardMBean() {
756         return shardMBean;
757     }
758
759     public static Builder builder() {
760         return new Builder();
761     }
762
763     public static abstract class AbstractBuilder<T extends AbstractBuilder<T, S>, S extends Shard> {
764         private final Class<S> shardClass;
765         private ShardIdentifier id;
766         private Map<String, String> peerAddresses = Collections.emptyMap();
767         private DatastoreContext datastoreContext;
768         private SchemaContext schemaContext;
769         private DatastoreSnapshot.ShardSnapshot restoreFromSnapshot;
770         private volatile boolean sealed;
771
772         protected AbstractBuilder(Class<S> shardClass) {
773             this.shardClass = shardClass;
774         }
775
776         protected void checkSealed() {
777             Preconditions.checkState(!sealed, "Builder isalready sealed - further modifications are not allowed");
778         }
779
780         @SuppressWarnings("unchecked")
781         private T self() {
782             return (T) this;
783         }
784
785         public T id(ShardIdentifier id) {
786             checkSealed();
787             this.id = id;
788             return self();
789         }
790
791         public T peerAddresses(Map<String, String> peerAddresses) {
792             checkSealed();
793             this.peerAddresses = peerAddresses;
794             return self();
795         }
796
797         public T datastoreContext(DatastoreContext datastoreContext) {
798             checkSealed();
799             this.datastoreContext = datastoreContext;
800             return self();
801         }
802
803         public T schemaContext(SchemaContext schemaContext) {
804             checkSealed();
805             this.schemaContext = schemaContext;
806             return self();
807         }
808
809         public T restoreFromSnapshot(DatastoreSnapshot.ShardSnapshot restoreFromSnapshot) {
810             checkSealed();
811             this.restoreFromSnapshot = restoreFromSnapshot;
812             return self();
813         }
814
815         public ShardIdentifier getId() {
816             return id;
817         }
818
819         public Map<String, String> getPeerAddresses() {
820             return peerAddresses;
821         }
822
823         public DatastoreContext getDatastoreContext() {
824             return datastoreContext;
825         }
826
827         public SchemaContext getSchemaContext() {
828             return schemaContext;
829         }
830
831         public DatastoreSnapshot.ShardSnapshot getRestoreFromSnapshot() {
832             return restoreFromSnapshot;
833         }
834
835         public TreeType getTreeType() {
836             switch (datastoreContext.getLogicalStoreType()) {
837             case CONFIGURATION:
838                 return TreeType.CONFIGURATION;
839             case OPERATIONAL:
840                 return TreeType.OPERATIONAL;
841             }
842
843             throw new IllegalStateException("Unhandled logical store type " + datastoreContext.getLogicalStoreType());
844         }
845
846         protected void verify() {
847             Preconditions.checkNotNull(id, "id should not be null");
848             Preconditions.checkNotNull(peerAddresses, "peerAddresses should not be null");
849             Preconditions.checkNotNull(datastoreContext, "dataStoreContext should not be null");
850             Preconditions.checkNotNull(schemaContext, "schemaContext should not be null");
851         }
852
853         public Props props() {
854             sealed = true;
855             verify();
856             return Props.create(shardClass, this);
857         }
858     }
859
860     public static class Builder extends AbstractBuilder<Builder, Shard> {
861         private Builder() {
862             super(Shard.class);
863         }
864     }
865 }