2 * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
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
9 package org.opendaylight.controller.cluster.datastore;
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;
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.modification.Modification;
54 import org.opendaylight.controller.cluster.datastore.modification.MutableCompositeModification;
55 import org.opendaylight.controller.cluster.datastore.utils.Dispatchers;
56 import org.opendaylight.controller.cluster.notifications.LeaderStateChanged;
57 import org.opendaylight.controller.cluster.notifications.RegisterRoleChangeListener;
58 import org.opendaylight.controller.cluster.notifications.RoleChangeNotifier;
59 import org.opendaylight.controller.cluster.raft.RaftActor;
60 import org.opendaylight.controller.cluster.raft.RaftActorRecoveryCohort;
61 import org.opendaylight.controller.cluster.raft.RaftActorSnapshotCohort;
62 import org.opendaylight.controller.cluster.raft.RaftState;
63 import org.opendaylight.controller.cluster.raft.base.messages.FollowerInitialSyncUpStatus;
64 import org.opendaylight.controller.cluster.raft.messages.AppendEntriesReply;
65 import org.opendaylight.controller.cluster.raft.messages.ServerRemoved;
66 import org.opendaylight.yangtools.concepts.Identifier;
67 import org.opendaylight.yangtools.util.StringIdentifier;
68 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidate;
69 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataValidationFailedException;
70 import org.opendaylight.yangtools.yang.data.api.schema.tree.ModificationType;
71 import org.opendaylight.yangtools.yang.data.api.schema.tree.TreeType;
72 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
73 import scala.concurrent.duration.Duration;
74 import scala.concurrent.duration.FiniteDuration;
77 * A Shard represents a portion of the logical data tree <br/>
79 * Our Shard uses InMemoryDataTree as it's internal representation and delegates all requests it
82 public class Shard extends RaftActor {
85 static final Object TX_COMMIT_TIMEOUT_CHECK_MESSAGE = new Object() {
87 public String toString() {
88 return "txCommitTimeoutCheck";
93 static final Object GET_SHARD_MBEAN_MESSAGE = new Object() {
95 public String toString() {
96 return "getShardMBeanMessage";
100 // FIXME: shard names should be encapsulated in their own class and this should be exposed as a constant.
101 public static final String DEFAULT_NAME = "default";
103 // The state of this Shard
104 private final ShardDataTree store;
106 /// The name of this shard
107 private final String name;
109 private final ShardStats shardMBean;
111 private DatastoreContext datastoreContext;
113 private final ShardCommitCoordinator commitCoordinator;
115 private long transactionCommitTimeout;
117 private Cancellable txCommitTimeoutCheckSchedule;
119 private final Optional<ActorRef> roleChangeNotifier;
121 private final MessageTracker appendEntriesReplyTracker;
123 private final ShardTransactionActorFactory transactionActorFactory;
125 private final ShardSnapshotCohort snapshotCohort;
127 private final DataTreeChangeListenerSupport treeChangeSupport = new DataTreeChangeListenerSupport(this);
128 private final DataChangeListenerSupport changeSupport = new DataChangeListenerSupport(this);
131 private ShardSnapshot restoreFromSnapshot;
133 private final ShardTransactionMessageRetrySupport messageRetrySupport;
135 protected Shard(AbstractBuilder<?, ?> builder) {
136 super(builder.getId().toString(), builder.getPeerAddresses(),
137 Optional.of(builder.getDatastoreContext().getShardRaftConfig()), DataStoreVersions.CURRENT_VERSION);
139 this.name = builder.getId().toString();
140 this.datastoreContext = builder.getDatastoreContext();
141 this.restoreFromSnapshot = builder.getRestoreFromSnapshot();
143 setPersistence(datastoreContext.isPersistent());
145 LOG.info("Shard created : {}, persistent : {}", name, datastoreContext.isPersistent());
147 store = new ShardDataTree(builder.getSchemaContext(), builder.getTreeType(),
148 new ShardDataTreeChangeListenerPublisherActorProxy(getContext(), name + "-DTCL-publisher"),
149 new ShardDataChangeListenerPublisherActorProxy(getContext(), name + "-DCL-publisher"), name);
151 shardMBean = ShardMBeanFactory.getShardStatsMBean(name.toString(),
152 datastoreContext.getDataStoreMXBeanType());
153 shardMBean.setShard(this);
155 if (isMetricsCaptureEnabled()) {
156 getContext().become(new MeteringBehavior(this));
159 commitCoordinator = new ShardCommitCoordinator(store,
160 datastoreContext.getShardCommitQueueExpiryTimeoutInMillis(),
161 datastoreContext.getShardTransactionCommitQueueCapacity(), LOG, this.name);
163 setTransactionCommitTimeout();
165 // create a notifier actor for each cluster member
166 roleChangeNotifier = createRoleChangeNotifier(name.toString());
168 appendEntriesReplyTracker = new MessageTracker(AppendEntriesReply.class,
169 getRaftActorContext().getConfigParams().getIsolatedCheckIntervalInMillis());
171 transactionActorFactory = new ShardTransactionActorFactory(store, datastoreContext,
172 new Dispatchers(context().system().dispatchers()).getDispatcherPath(
173 Dispatchers.DispatcherType.Transaction), self(), getContext(), shardMBean);
175 snapshotCohort = new ShardSnapshotCohort(transactionActorFactory, store, LOG, this.name);
177 messageRetrySupport = new ShardTransactionMessageRetrySupport(this);
180 private void setTransactionCommitTimeout() {
181 transactionCommitTimeout = TimeUnit.MILLISECONDS.convert(
182 datastoreContext.getShardTransactionCommitTimeoutInSeconds(), TimeUnit.SECONDS) / 2;
185 private Optional<ActorRef> createRoleChangeNotifier(String shardId) {
186 ActorRef shardRoleChangeNotifier = this.getContext().actorOf(
187 RoleChangeNotifier.getProps(shardId), shardId + "-notifier");
188 return Optional.of(shardRoleChangeNotifier);
192 public void postStop() {
193 LOG.info("Stopping Shard {}", persistenceId());
197 messageRetrySupport.close();
199 if(txCommitTimeoutCheckSchedule != null) {
200 txCommitTimeoutCheckSchedule.cancel();
203 commitCoordinator.abortPendingTransactions("Transaction aborted due to shutdown.", this);
205 shardMBean.unregisterMBean();
209 protected void handleRecover(final Object message) {
210 LOG.debug("{}: onReceiveRecover: Received message {} from {}", persistenceId(), message.getClass(),
213 super.handleRecover(message);
214 if (LOG.isTraceEnabled()) {
215 appendEntriesReplyTracker.begin();
220 protected void handleNonRaftCommand(final Object message) {
221 try (final MessageTracker.Context context = appendEntriesReplyTracker.received(message)) {
222 final Optional<Error> maybeError = context.error();
223 if (maybeError.isPresent()) {
224 LOG.trace("{} : AppendEntriesReply failed to arrive at the expected interval {}", persistenceId(),
228 if (CreateTransaction.isSerializedType(message)) {
229 handleCreateTransaction(message);
230 } else if (message instanceof BatchedModifications) {
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.isSerializedType(message)) {
237 handleCanCommitTransaction(CanCommitTransaction.fromSerializable(message));
238 } else if (CommitTransaction.isSerializedType(message)) {
239 handleCommitTransaction(CommitTransaction.fromSerializable(message));
240 } else if (AbortTransaction.isSerializedType(message)) {
241 handleAbortTransaction(AbortTransaction.fromSerializable(message));
242 } else if (CloseTransactionChain.isSerializedType(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 (TX_COMMIT_TIMEOUT_CHECK_MESSAGE.equals(message)) {
255 commitCoordinator.checkForExpiredTransactions(transactionCommitTimeout, this);
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 if (message instanceof DataTreeCohortActorRegistry.CohortRegistryCommand) {
272 commitCoordinator.processCohortRegistryCommand(getSender(),
273 (DataTreeCohortActorRegistry.CohortRegistryCommand) message);
275 super.handleNonRaftCommand(message);
280 private boolean hasLeader() {
281 return getLeaderId() != null;
284 public int getPendingTxCommitQueueSize() {
285 return commitCoordinator.getQueueSize();
288 public int getCohortCacheSize() {
289 return commitCoordinator.getCohortCacheSize();
293 protected Optional<ActorRef> getRoleChangeNotifier() {
294 return roleChangeNotifier;
298 protected LeaderStateChanged newLeaderStateChanged(String memberId, String leaderId, short leaderPayloadVersion) {
299 return isLeader() ? new ShardLeaderStateChanged(memberId, leaderId, store.getDataTree(), leaderPayloadVersion)
300 : new ShardLeaderStateChanged(memberId, leaderId, leaderPayloadVersion);
303 protected void onDatastoreContext(DatastoreContext context) {
304 datastoreContext = context;
306 commitCoordinator.setQueueCapacity(datastoreContext.getShardTransactionCommitQueueCapacity());
308 setTransactionCommitTimeout();
310 if(datastoreContext.isPersistent() && !persistence().isRecoveryApplicable()) {
311 setPersistence(true);
312 } else if(!datastoreContext.isPersistent() && persistence().isRecoveryApplicable()) {
313 setPersistence(false);
316 updateConfigParams(datastoreContext.getShardRaftConfig());
319 private static boolean isEmptyCommit(final DataTreeCandidate candidate) {
320 return ModificationType.UNMODIFIED.equals(candidate.getRootNode().getModificationType());
323 void continueCommit(final CohortEntry cohortEntry) {
324 final DataTreeCandidate candidate = cohortEntry.getCandidate();
326 // If we do not have any followers and we are not using persistence
327 // or if cohortEntry has no modifications
328 // we can apply modification to the state immediately
329 if ((!hasFollowers() && !persistence().isRecoveryApplicable()) || isEmptyCommit(candidate)) {
330 applyModificationToState(cohortEntry.getReplySender(), cohortEntry.getTransactionID(), candidate);
332 persistData(cohortEntry.getReplySender(), cohortEntry.getTransactionID(),
333 DataTreeCandidatePayload.create(candidate));
337 private void handleCommitTransaction(final CommitTransaction commit) {
339 if(!commitCoordinator.handleCommit(new StringIdentifier(commit.getTransactionID()), getSender(), this)) {
340 shardMBean.incrementFailedTransactionsCount();
343 ActorSelection leader = getLeader();
344 if (leader == null) {
345 messageRetrySupport.addMessageToRetry(commit, getSender(),
346 "Could not commit transaction " + commit.getTransactionID());
348 LOG.debug("{}: Forwarding CommitTransaction to leader {}", persistenceId(), leader);
349 leader.forward(commit, getContext());
354 private void finishCommit(@Nonnull final ActorRef sender, @Nonnull final Identifier transactionID,
355 @Nonnull final CohortEntry cohortEntry) {
356 LOG.debug("{}: Finishing commit for transaction {}", persistenceId(), cohortEntry.getTransactionID());
360 cohortEntry.commit();
361 } catch(ExecutionException e) {
362 // We may get a "store tree and candidate base differ" IllegalStateException from commit under
363 // certain edge case scenarios so we'll try to re-apply the candidate from scratch as a last
364 // resort. Eg, we're a follower and a tx payload is replicated but the leader goes down before
365 // applying it to the state. We then become the leader and a second tx is pre-committed and
366 // replicated. When consensus occurs, this will cause the first tx to be applied as a foreign
367 // candidate via applyState prior to the second tx. Since the second tx has already been
368 // pre-committed, when it gets here to commit it will get an IllegalStateException.
370 // FIXME - this is not an ideal way to handle this scenario. This is temporary - a cleaner
371 // solution will be forthcoming.
372 if(e.getCause() instanceof IllegalStateException) {
373 LOG.debug("{}: commit failed for transaction {} - retrying as foreign candidate", persistenceId(),
375 store.applyForeignCandidate(transactionID, cohortEntry.getCandidate());
381 sender.tell(CommitTransactionReply.instance(cohortEntry.getClientVersion()).toSerializable(), getSelf());
383 shardMBean.incrementCommittedTransactionCount();
384 shardMBean.setLastCommittedTransactionTime(System.currentTimeMillis());
386 } catch (Exception e) {
387 sender.tell(new akka.actor.Status.Failure(e), getSelf());
389 LOG.error("{}, An exception occurred while committing transaction {}", persistenceId(),
391 shardMBean.incrementFailedTransactionsCount();
393 commitCoordinator.currentTransactionComplete(transactionID, true);
397 private void finishCommit(@Nonnull final ActorRef sender, final @Nonnull Identifier transactionID) {
398 // With persistence enabled, this method is called via applyState by the leader strategy
399 // after the commit has been replicated to a majority of the followers.
401 CohortEntry cohortEntry = commitCoordinator.getCohortEntryIfCurrent(transactionID);
402 if (cohortEntry == null) {
403 // The transaction is no longer the current commit. This can happen if the transaction
404 // was aborted prior, most likely due to timeout in the front-end. We need to finish
405 // committing the transaction though since it was successfully persisted and replicated
406 // however we can't use the original cohort b/c it was already preCommitted and may
407 // conflict with the current commit or may have been aborted so we commit with a new
409 cohortEntry = commitCoordinator.getAndRemoveCohortEntry(transactionID);
410 if(cohortEntry != null) {
412 store.applyForeignCandidate(transactionID, cohortEntry.getCandidate());
413 } catch (DataValidationFailedException e) {
414 shardMBean.incrementFailedTransactionsCount();
415 LOG.error("{}: Failed to re-apply transaction {}", persistenceId(), transactionID, e);
418 sender.tell(CommitTransactionReply.instance(cohortEntry.getClientVersion()).toSerializable(),
421 // This really shouldn't happen - it likely means that persistence or replication
422 // took so long to complete such that the cohort entry was expired from the cache.
423 IllegalStateException ex = new IllegalStateException(
424 String.format("%s: Could not finish committing transaction %s - no CohortEntry found",
425 persistenceId(), transactionID));
426 LOG.error(ex.getMessage());
427 sender.tell(new akka.actor.Status.Failure(ex), getSelf());
430 finishCommit(sender, transactionID, cohortEntry);
434 private void handleCanCommitTransaction(final CanCommitTransaction canCommit) {
435 LOG.debug("{}: Can committing transaction {}", persistenceId(), canCommit.getTransactionID());
438 commitCoordinator.handleCanCommit(new StringIdentifier(canCommit.getTransactionID()), getSender(), this);
440 ActorSelection leader = getLeader();
441 if (leader == null) {
442 messageRetrySupport.addMessageToRetry(canCommit, getSender(),
443 "Could not canCommit transaction " + canCommit.getTransactionID());
445 LOG.debug("{}: Forwarding CanCommitTransaction to leader {}", persistenceId(), leader);
446 leader.forward(canCommit, getContext());
451 protected void handleBatchedModificationsLocal(BatchedModifications batched, ActorRef sender) {
453 commitCoordinator.handleBatchedModifications(batched, sender, this, store.getSchemaContext());
454 } catch (Exception e) {
455 LOG.error("{}: Error handling BatchedModifications for Tx {}", persistenceId(),
456 batched.getTransactionID(), e);
457 sender.tell(new akka.actor.Status.Failure(e), getSelf());
461 private void handleBatchedModifications(BatchedModifications batched) {
462 // This message is sent to prepare the modifications transaction directly on the Shard as an
463 // optimization to avoid the extra overhead of a separate ShardTransaction actor. On the last
464 // BatchedModifications message, the caller sets the ready flag in the message indicating
465 // modifications are complete. The reply contains the cohort actor path (this actor) for the caller
466 // to initiate the 3-phase commit. This also avoids the overhead of sending an additional
467 // ReadyTransaction message.
469 // If we're not the leader then forward to the leader. This is a safety measure - we shouldn't
470 // normally get here if we're not the leader as the front-end (TransactionProxy) should determine
471 // the primary/leader shard. However with timing and caching on the front-end, there's a small
472 // window where it could have a stale leader during leadership transitions.
474 boolean isLeaderActive = isLeaderActive();
475 if (isLeader() && isLeaderActive) {
476 handleBatchedModificationsLocal(batched, getSender());
478 ActorSelection leader = getLeader();
479 if (!isLeaderActive || leader == null) {
480 messageRetrySupport.addMessageToRetry(batched, getSender(),
481 "Could not commit transaction " + batched.getTransactionID());
483 // If this is not the first batch and leadership changed in between batched messages,
484 // we need to reconstruct previous BatchedModifications from the transaction
485 // DataTreeModification, honoring the max batched modification count, and forward all the
486 // previous BatchedModifications to the new leader.
487 Collection<BatchedModifications> newModifications = commitCoordinator.createForwardedBatchedModifications(
488 batched, datastoreContext.getShardBatchedModificationCount());
490 LOG.debug("{}: Forwarding {} BatchedModifications to leader {}", persistenceId(),
491 newModifications.size(), leader);
493 for(BatchedModifications bm: newModifications) {
494 leader.forward(bm, getContext());
500 private boolean failIfIsolatedLeader(ActorRef sender) {
501 if(isIsolatedLeader()) {
502 sender.tell(new akka.actor.Status.Failure(new NoShardLeaderException(String.format(
503 "Shard %s was the leader but has lost contact with all of its followers. Either all" +
504 " other follower nodes are down or this node is isolated by a network partition.",
505 persistenceId()))), getSelf());
512 protected boolean isIsolatedLeader() {
513 return getRaftState() == RaftState.IsolatedLeader;
516 private void handleReadyLocalTransaction(final ReadyLocalTransaction message) {
517 LOG.debug("{}: handleReadyLocalTransaction for {}", persistenceId(), message.getTransactionID());
519 boolean isLeaderActive = isLeaderActive();
520 if (isLeader() && isLeaderActive) {
522 commitCoordinator.handleReadyLocalTransaction(message, getSender(), this, store.getSchemaContext());
523 } catch (Exception e) {
524 LOG.error("{}: Error handling ReadyLocalTransaction for Tx {}", persistenceId(),
525 message.getTransactionID(), e);
526 getSender().tell(new akka.actor.Status.Failure(e), getSelf());
529 ActorSelection leader = getLeader();
530 if (!isLeaderActive || leader == null) {
531 messageRetrySupport.addMessageToRetry(message, getSender(),
532 "Could not commit transaction " + message.getTransactionID());
534 LOG.debug("{}: Forwarding ReadyLocalTransaction to leader {}", persistenceId(), leader);
535 message.setRemoteVersion(getCurrentBehavior().getLeaderPayloadVersion());
536 leader.forward(message, getContext());
541 private void handleForwardedReadyTransaction(ForwardedReadyTransaction forwardedReady) {
542 LOG.debug("{}: handleForwardedReadyTransaction for {}", persistenceId(), forwardedReady.getTransactionID());
544 boolean isLeaderActive = isLeaderActive();
545 if (isLeader() && isLeaderActive) {
546 commitCoordinator.handleForwardedReadyTransaction(forwardedReady, getSender(), this,
547 store.getSchemaContext());
549 ActorSelection leader = getLeader();
550 if (!isLeaderActive || leader == null) {
551 messageRetrySupport.addMessageToRetry(forwardedReady, getSender(),
552 "Could not commit transaction " + forwardedReady.getTransactionID());
554 LOG.debug("{}: Forwarding ForwardedReadyTransaction to leader {}", persistenceId(), leader);
556 ReadyLocalTransaction readyLocal = new ReadyLocalTransaction(forwardedReady.getTransactionID(),
557 forwardedReady.getTransaction().getSnapshot(), forwardedReady.isDoImmediateCommit());
558 readyLocal.setRemoteVersion(getCurrentBehavior().getLeaderPayloadVersion());
559 leader.forward(readyLocal, getContext());
564 private void handleAbortTransaction(final AbortTransaction abort) {
565 doAbortTransaction(abort.getTransactionID(), getSender());
568 void doAbortTransaction(final String transactionID, final ActorRef sender) {
569 commitCoordinator.handleAbort(new StringIdentifier(transactionID), sender, this);
572 private void handleCreateTransaction(final Object message) {
574 createTransaction(CreateTransaction.fromSerializable(message));
575 } else if (getLeader() != null) {
576 getLeader().forward(message, getContext());
578 getSender().tell(new akka.actor.Status.Failure(new NoShardLeaderException(
579 "Could not create a shard transaction", persistenceId())), getSelf());
583 private void closeTransactionChain(final CloseTransactionChain closeTransactionChain) {
584 store.closeTransactionChain(closeTransactionChain.getTransactionChainId());
587 private void createTransaction(CreateTransaction createTransaction) {
589 if(TransactionType.fromInt(createTransaction.getTransactionType()) != TransactionType.READ_ONLY &&
590 failIfIsolatedLeader(getSender())) {
594 ActorRef transactionActor = createTransaction(createTransaction.getTransactionType(),
595 createTransaction.getTransactionId(), createTransaction.getTransactionChainId());
597 getSender().tell(new CreateTransactionReply(Serialization.serializedActorPath(transactionActor),
598 createTransaction.getTransactionId(), createTransaction.getVersion()).toSerializable(), getSelf());
599 } catch (Exception e) {
600 getSender().tell(new akka.actor.Status.Failure(e), getSelf());
604 private ActorRef createTransaction(int transactionType, String transactionId, String transactionChainId) {
605 LOG.debug("{}: Creating transaction : {} ", persistenceId(), transactionId);
606 return transactionActorFactory.newShardTransaction(TransactionType.fromInt(transactionType),
607 transactionId, transactionChainId);
610 private void commitWithNewTransaction(final Modification modification) {
611 ReadWriteShardDataTreeTransaction tx = store.newReadWriteTransaction(modification.toString(), null);
612 modification.apply(tx.getSnapshot());
614 snapshotCohort.syncCommitTransaction(tx);
615 shardMBean.incrementCommittedTransactionCount();
616 shardMBean.setLastCommittedTransactionTime(System.currentTimeMillis());
617 } catch (Exception e) {
618 shardMBean.incrementFailedTransactionsCount();
619 LOG.error("{}: Failed to commit", persistenceId(), e);
623 private void updateSchemaContext(final UpdateSchemaContext message) {
624 updateSchemaContext(message.getSchemaContext());
628 void updateSchemaContext(final SchemaContext schemaContext) {
629 store.updateSchemaContext(schemaContext);
632 private boolean isMetricsCaptureEnabled() {
633 CommonConfig config = new CommonConfig(getContext().system().settings().config());
634 return config.isMetricCaptureEnabled();
639 public RaftActorSnapshotCohort getRaftActorSnapshotCohort() {
640 return snapshotCohort;
645 protected RaftActorRecoveryCohort getRaftActorRecoveryCohort() {
646 return new ShardRecoveryCoordinator(store, store.getSchemaContext(),
647 restoreFromSnapshot != null ? restoreFromSnapshot.getSnapshot() : null, persistenceId(), LOG);
651 protected void onRecoveryComplete() {
652 restoreFromSnapshot = null;
654 //notify shard manager
655 getContext().parent().tell(new ActorInitialized(), getSelf());
657 // Being paranoid here - this method should only be called once but just in case...
658 if(txCommitTimeoutCheckSchedule == null) {
659 // Schedule a message to be periodically sent to check if the current in-progress
660 // transaction should be expired and aborted.
661 FiniteDuration period = Duration.create(transactionCommitTimeout / 3, TimeUnit.MILLISECONDS);
662 txCommitTimeoutCheckSchedule = getContext().system().scheduler().schedule(
663 period, period, getSelf(),
664 TX_COMMIT_TIMEOUT_CHECK_MESSAGE, getContext().dispatcher(), ActorRef.noSender());
669 protected void applyState(final ActorRef clientActor, final Identifier identifier, final Object data) {
670 if (data instanceof DataTreeCandidatePayload) {
671 if (clientActor == null) {
672 // No clientActor indicates a replica coming from the leader
674 store.applyForeignCandidate(identifier, ((DataTreeCandidatePayload)data).getCandidate());
675 } catch (DataValidationFailedException | IOException e) {
676 LOG.error("{}: Error applying replica {}", persistenceId(), identifier, e);
679 // Replication consensus reached, proceed to commit
680 finishCommit(clientActor, identifier);
683 LOG.error("{}: Unknown state received {} ClassLoader {}", persistenceId(), data,
684 data.getClass().getClassLoader());
688 private void applyModificationToState(ActorRef clientActor, Identifier identifier, Object modification) {
689 if(modification == null) {
691 "{}: modification is null - this is very unexpected, clientActor = {}, identifier = {}",
692 persistenceId(), identifier, clientActor != null ? clientActor.path().toString() : null);
693 } else if(clientActor == null) {
694 // There's no clientActor to which to send a commit reply so we must be applying
695 // replicated state from the leader.
696 commitWithNewTransaction(MutableCompositeModification.fromSerializable(modification));
698 // This must be the OK to commit after replication consensus.
699 finishCommit(clientActor, identifier);
704 protected void onStateChanged() {
705 boolean isLeader = isLeader();
706 boolean hasLeader = hasLeader();
707 changeSupport.onLeadershipChange(isLeader, hasLeader);
708 treeChangeSupport.onLeadershipChange(isLeader, hasLeader);
710 // If this actor is no longer the leader close all the transaction chains
712 if(LOG.isDebugEnabled()) {
714 "{}: onStateChanged: Closing all transaction chains because shard {} is no longer the leader",
715 persistenceId(), getId());
718 store.closeAllTransactionChains();
721 if(hasLeader && !isIsolatedLeader()) {
722 messageRetrySupport.retryMessages();
727 protected void onLeaderChanged(String oldLeader, String newLeader) {
728 shardMBean.incrementLeadershipChangeCount();
730 boolean hasLeader = hasLeader();
731 if(hasLeader && !isLeader()) {
732 // Another leader was elected. If we were the previous leader and had pending transactions, convert
733 // them to transaction messages and send to the new leader.
734 ActorSelection leader = getLeader();
736 Collection<Object> messagesToForward = commitCoordinator.convertPendingTransactionsToMessages(
737 datastoreContext.getShardBatchedModificationCount());
739 if(!messagesToForward.isEmpty()) {
740 LOG.debug("{}: Forwarding {} pending transaction messages to leader {}", persistenceId(),
741 messagesToForward.size(), leader);
743 for(Object message: messagesToForward) {
744 leader.tell(message, self());
748 commitCoordinator.abortPendingTransactions(
749 "The transacton was aborted due to inflight leadership change and the leader address isn't available.",
754 if(hasLeader && !isIsolatedLeader()) {
755 messageRetrySupport.retryMessages();
760 protected void pauseLeader(Runnable operation) {
761 LOG.debug("{}: In pauseLeader, operation: {}", persistenceId(), operation);
762 commitCoordinator.setRunOnPendingTransactionsComplete(operation);
766 public String persistenceId() {
771 ShardCommitCoordinator getCommitCoordinator() {
772 return commitCoordinator;
775 public DatastoreContext getDatastoreContext() {
776 return datastoreContext;
780 public ShardDataTree getDataStore() {
785 ShardStats getShardMBean() {
789 public static Builder builder() {
790 return new Builder();
793 public static abstract class AbstractBuilder<T extends AbstractBuilder<T, S>, S extends Shard> {
794 private final Class<S> shardClass;
795 private ShardIdentifier id;
796 private Map<String, String> peerAddresses = Collections.emptyMap();
797 private DatastoreContext datastoreContext;
798 private SchemaContext schemaContext;
799 private DatastoreSnapshot.ShardSnapshot restoreFromSnapshot;
800 private volatile boolean sealed;
802 protected AbstractBuilder(Class<S> shardClass) {
803 this.shardClass = shardClass;
806 protected void checkSealed() {
807 Preconditions.checkState(!sealed, "Builder isalready sealed - further modifications are not allowed");
810 @SuppressWarnings("unchecked")
815 public T id(ShardIdentifier id) {
821 public T peerAddresses(Map<String, String> peerAddresses) {
823 this.peerAddresses = peerAddresses;
827 public T datastoreContext(DatastoreContext datastoreContext) {
829 this.datastoreContext = datastoreContext;
833 public T schemaContext(SchemaContext schemaContext) {
835 this.schemaContext = schemaContext;
839 public T restoreFromSnapshot(DatastoreSnapshot.ShardSnapshot restoreFromSnapshot) {
841 this.restoreFromSnapshot = restoreFromSnapshot;
845 public ShardIdentifier getId() {
849 public Map<String, String> getPeerAddresses() {
850 return peerAddresses;
853 public DatastoreContext getDatastoreContext() {
854 return datastoreContext;
857 public SchemaContext getSchemaContext() {
858 return schemaContext;
861 public DatastoreSnapshot.ShardSnapshot getRestoreFromSnapshot() {
862 return restoreFromSnapshot;
865 public TreeType getTreeType() {
866 switch (datastoreContext.getLogicalStoreType()) {
868 return TreeType.CONFIGURATION;
870 return TreeType.OPERATIONAL;
873 throw new IllegalStateException("Unhandled logical store type " + datastoreContext.getLogicalStoreType());
876 protected void verify() {
877 Preconditions.checkNotNull(id, "id should not be null");
878 Preconditions.checkNotNull(peerAddresses, "peerAddresses should not be null");
879 Preconditions.checkNotNull(datastoreContext, "dataStoreContext should not be null");
880 Preconditions.checkNotNull(schemaContext, "schemaContext should not be null");
883 public Props props() {
886 return Props.create(shardClass, this);
890 public static class Builder extends AbstractBuilder<Builder, Shard> {