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