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