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.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;
75 * A Shard represents a portion of the logical data tree <br/>
77 * Our Shard uses InMemoryDataTree as it's internal representation and delegates all requests it
80 public class Shard extends RaftActor {
83 static final Object TX_COMMIT_TIMEOUT_CHECK_MESSAGE = new Object() {
85 public String toString() {
86 return "txCommitTimeoutCheck";
91 static final Object GET_SHARD_MBEAN_MESSAGE = new Object() {
93 public String toString() {
94 return "getShardMBeanMessage";
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";
101 // The state of this Shard
102 private final ShardDataTree store;
104 /// The name of this shard
105 private final String name;
107 private final ShardStats shardMBean;
109 private DatastoreContext datastoreContext;
111 private final ShardCommitCoordinator commitCoordinator;
113 private long transactionCommitTimeout;
115 private Cancellable txCommitTimeoutCheckSchedule;
117 private final Optional<ActorRef> roleChangeNotifier;
119 private final MessageTracker appendEntriesReplyTracker;
121 private final ShardTransactionActorFactory transactionActorFactory;
123 private final ShardSnapshotCohort snapshotCohort;
125 private final DataTreeChangeListenerSupport treeChangeSupport = new DataTreeChangeListenerSupport(this);
126 private final DataChangeListenerSupport changeSupport = new DataChangeListenerSupport(this);
129 private ShardSnapshot restoreFromSnapshot;
131 private final ShardTransactionMessageRetrySupport messageRetrySupport;
133 protected Shard(AbstractBuilder<?, ?> builder) {
134 super(builder.getId().toString(), builder.getPeerAddresses(),
135 Optional.of(builder.getDatastoreContext().getShardRaftConfig()), DataStoreVersions.CURRENT_VERSION);
137 this.name = builder.getId().toString();
138 this.datastoreContext = builder.getDatastoreContext();
139 this.restoreFromSnapshot = builder.getRestoreFromSnapshot();
141 setPersistence(datastoreContext.isPersistent());
143 LOG.info("Shard created : {}, persistent : {}", name, datastoreContext.isPersistent());
145 store = new ShardDataTree(builder.getSchemaContext(), builder.getTreeType(),
146 new ShardDataTreeChangeListenerPublisherActorProxy(getContext(), name + "-DTCL-publisher"),
147 new ShardDataChangeListenerPublisherActorProxy(getContext(), name + "-DCL-publisher"), name);
149 shardMBean = ShardMBeanFactory.getShardStatsMBean(name.toString(),
150 datastoreContext.getDataStoreMXBeanType());
151 shardMBean.setShard(this);
153 if (isMetricsCaptureEnabled()) {
154 getContext().become(new MeteringBehavior(this));
157 commitCoordinator = new ShardCommitCoordinator(store,
158 datastoreContext.getShardCommitQueueExpiryTimeoutInMillis(),
159 datastoreContext.getShardTransactionCommitQueueCapacity(), LOG, this.name);
161 setTransactionCommitTimeout();
163 // create a notifier actor for each cluster member
164 roleChangeNotifier = createRoleChangeNotifier(name.toString());
166 appendEntriesReplyTracker = new MessageTracker(AppendEntriesReply.class,
167 getRaftActorContext().getConfigParams().getIsolatedCheckIntervalInMillis());
169 transactionActorFactory = new ShardTransactionActorFactory(store, datastoreContext,
170 new Dispatchers(context().system().dispatchers()).getDispatcherPath(
171 Dispatchers.DispatcherType.Transaction), self(), getContext(), shardMBean);
173 snapshotCohort = new ShardSnapshotCohort(transactionActorFactory, store, LOG, this.name);
175 messageRetrySupport = new ShardTransactionMessageRetrySupport(this);
178 private void setTransactionCommitTimeout() {
179 transactionCommitTimeout = TimeUnit.MILLISECONDS.convert(
180 datastoreContext.getShardTransactionCommitTimeoutInSeconds(), TimeUnit.SECONDS) / 2;
183 private Optional<ActorRef> createRoleChangeNotifier(String shardId) {
184 ActorRef shardRoleChangeNotifier = this.getContext().actorOf(
185 RoleChangeNotifier.getProps(shardId), shardId + "-notifier");
186 return Optional.of(shardRoleChangeNotifier);
190 public void postStop() {
191 LOG.info("Stopping Shard {}", persistenceId());
195 messageRetrySupport.close();
197 if(txCommitTimeoutCheckSchedule != null) {
198 txCommitTimeoutCheckSchedule.cancel();
201 commitCoordinator.abortPendingTransactions("Transaction aborted due to shutdown.", this);
203 shardMBean.unregisterMBean();
207 protected void handleRecover(final Object message) {
208 LOG.debug("{}: onReceiveRecover: Received message {} from {}", persistenceId(), message.getClass(),
211 super.handleRecover(message);
212 if (LOG.isTraceEnabled()) {
213 appendEntriesReplyTracker.begin();
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(),
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);
273 super.handleNonRaftCommand(message);
278 private boolean hasLeader() {
279 return getLeaderId() != null;
282 public int getPendingTxCommitQueueSize() {
283 return commitCoordinator.getQueueSize();
286 public int getCohortCacheSize() {
287 return commitCoordinator.getCohortCacheSize();
291 protected Optional<ActorRef> getRoleChangeNotifier() {
292 return roleChangeNotifier;
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);
301 protected void onDatastoreContext(DatastoreContext context) {
302 datastoreContext = context;
304 commitCoordinator.setQueueCapacity(datastoreContext.getShardTransactionCommitQueueCapacity());
306 setTransactionCommitTimeout();
308 if(datastoreContext.isPersistent() && !persistence().isRecoveryApplicable()) {
309 setPersistence(true);
310 } else if(!datastoreContext.isPersistent() && persistence().isRecoveryApplicable()) {
311 setPersistence(false);
314 updateConfigParams(datastoreContext.getShardRaftConfig());
317 private static boolean isEmptyCommit(final DataTreeCandidate candidate) {
318 return ModificationType.UNMODIFIED.equals(candidate.getRootNode().getModificationType());
321 void continueCommit(final CohortEntry cohortEntry) {
322 final DataTreeCandidate candidate = cohortEntry.getCandidate();
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);
330 persistData(cohortEntry.getReplySender(), cohortEntry.getTransactionID(),
331 DataTreeCandidatePayload.create(candidate));
335 private void handleCommitTransaction(final CommitTransaction commit) {
337 if(!commitCoordinator.handleCommit(new StringIdentifier(commit.getTransactionID()), getSender(), this)) {
338 shardMBean.incrementFailedTransactionsCount();
341 ActorSelection leader = getLeader();
342 if (leader == null) {
343 messageRetrySupport.addMessageToRetry(commit, getSender(),
344 "Could not commit transaction " + commit.getTransactionID());
346 LOG.debug("{}: Forwarding CommitTransaction to leader {}", persistenceId(), leader);
347 leader.forward(commit, getContext());
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());
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.
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(),
373 store.applyForeignCandidate(transactionID, cohortEntry.getCandidate());
379 sender.tell(CommitTransactionReply.instance(cohortEntry.getClientVersion()).toSerializable(), getSelf());
381 shardMBean.incrementCommittedTransactionCount();
382 shardMBean.setLastCommittedTransactionTime(System.currentTimeMillis());
384 } catch (Exception e) {
385 sender.tell(new akka.actor.Status.Failure(e), getSelf());
387 LOG.error("{}, An exception occurred while committing transaction {}", persistenceId(),
389 shardMBean.incrementFailedTransactionsCount();
391 commitCoordinator.currentTransactionComplete(transactionID, true);
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.
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
407 cohortEntry = commitCoordinator.getAndRemoveCohortEntry(transactionID);
408 if(cohortEntry != null) {
410 store.applyForeignCandidate(transactionID, cohortEntry.getCandidate());
411 } catch (DataValidationFailedException e) {
412 shardMBean.incrementFailedTransactionsCount();
413 LOG.error("{}: Failed to re-apply transaction {}", persistenceId(), transactionID, e);
416 sender.tell(CommitTransactionReply.instance(cohortEntry.getClientVersion()).toSerializable(),
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());
428 finishCommit(sender, transactionID, cohortEntry);
432 private void handleCanCommitTransaction(final CanCommitTransaction canCommit) {
433 LOG.debug("{}: Can committing transaction {}", persistenceId(), canCommit.getTransactionID());
436 commitCoordinator.handleCanCommit(new StringIdentifier(canCommit.getTransactionID()), getSender(), this);
438 ActorSelection leader = getLeader();
439 if (leader == null) {
440 messageRetrySupport.addMessageToRetry(canCommit, getSender(),
441 "Could not canCommit transaction " + canCommit.getTransactionID());
443 LOG.debug("{}: Forwarding CanCommitTransaction to leader {}", persistenceId(), leader);
444 leader.forward(canCommit, getContext());
449 protected void handleBatchedModificationsLocal(BatchedModifications batched, ActorRef sender) {
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());
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.
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.
472 boolean isLeaderActive = isLeaderActive();
473 if (isLeader() && isLeaderActive) {
474 handleBatchedModificationsLocal(batched, getSender());
476 ActorSelection leader = getLeader();
477 if (!isLeaderActive || leader == null) {
478 messageRetrySupport.addMessageToRetry(batched, getSender(),
479 "Could not commit transaction " + batched.getTransactionID());
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());
488 LOG.debug("{}: Forwarding {} BatchedModifications to leader {}", persistenceId(),
489 newModifications.size(), leader);
491 for(BatchedModifications bm: newModifications) {
492 leader.forward(bm, getContext());
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());
510 protected boolean isIsolatedLeader() {
511 return getRaftState() == RaftState.IsolatedLeader;
514 private void handleReadyLocalTransaction(final ReadyLocalTransaction message) {
515 LOG.debug("{}: handleReadyLocalTransaction for {}", persistenceId(), message.getTransactionID());
517 boolean isLeaderActive = isLeaderActive();
518 if (isLeader() && isLeaderActive) {
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());
527 ActorSelection leader = getLeader();
528 if (!isLeaderActive || leader == null) {
529 messageRetrySupport.addMessageToRetry(message, getSender(),
530 "Could not commit transaction " + message.getTransactionID());
532 LOG.debug("{}: Forwarding ReadyLocalTransaction to leader {}", persistenceId(), leader);
533 message.setRemoteVersion(getCurrentBehavior().getLeaderPayloadVersion());
534 leader.forward(message, getContext());
539 private void handleForwardedReadyTransaction(ForwardedReadyTransaction forwardedReady) {
540 LOG.debug("{}: handleForwardedReadyTransaction for {}", persistenceId(), forwardedReady.getTransactionID());
542 boolean isLeaderActive = isLeaderActive();
543 if (isLeader() && isLeaderActive) {
544 commitCoordinator.handleForwardedReadyTransaction(forwardedReady, getSender(), this,
545 store.getSchemaContext());
547 ActorSelection leader = getLeader();
548 if (!isLeaderActive || leader == null) {
549 messageRetrySupport.addMessageToRetry(forwardedReady, getSender(),
550 "Could not commit transaction " + forwardedReady.getTransactionID());
552 LOG.debug("{}: Forwarding ForwardedReadyTransaction to leader {}", persistenceId(), leader);
554 ReadyLocalTransaction readyLocal = new ReadyLocalTransaction(forwardedReady.getTransactionID(),
555 forwardedReady.getTransaction().getSnapshot(), forwardedReady.isDoImmediateCommit());
556 readyLocal.setRemoteVersion(getCurrentBehavior().getLeaderPayloadVersion());
557 leader.forward(readyLocal, getContext());
562 private void handleAbortTransaction(final AbortTransaction abort) {
563 doAbortTransaction(abort.getTransactionID(), getSender());
566 void doAbortTransaction(final String transactionID, final ActorRef sender) {
567 commitCoordinator.handleAbort(new StringIdentifier(transactionID), sender, this);
570 private void handleCreateTransaction(final Object message) {
572 createTransaction(CreateTransaction.fromSerializable(message));
573 } else if (getLeader() != null) {
574 getLeader().forward(message, getContext());
576 getSender().tell(new akka.actor.Status.Failure(new NoShardLeaderException(
577 "Could not create a shard transaction", persistenceId())), getSelf());
581 private void closeTransactionChain(final CloseTransactionChain closeTransactionChain) {
582 store.closeTransactionChain(closeTransactionChain.getTransactionChainId());
585 private void createTransaction(CreateTransaction createTransaction) {
587 if(TransactionType.fromInt(createTransaction.getTransactionType()) != TransactionType.READ_ONLY &&
588 failIfIsolatedLeader(getSender())) {
592 ActorRef transactionActor = createTransaction(createTransaction.getTransactionType(),
593 createTransaction.getTransactionId(), createTransaction.getTransactionChainId());
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());
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);
608 private void commitWithNewTransaction(final BatchedModifications modification) {
609 ReadWriteShardDataTreeTransaction tx = store.newReadWriteTransaction(modification.getTransactionID(),
610 modification.getTransactionChainID());
611 modification.apply(tx.getSnapshot());
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);
622 private void updateSchemaContext(final UpdateSchemaContext message) {
623 updateSchemaContext(message.getSchemaContext());
627 void updateSchemaContext(final SchemaContext schemaContext) {
628 store.updateSchemaContext(schemaContext);
631 private boolean isMetricsCaptureEnabled() {
632 CommonConfig config = new CommonConfig(getContext().system().settings().config());
633 return config.isMetricCaptureEnabled();
638 public RaftActorSnapshotCohort getRaftActorSnapshotCohort() {
639 return snapshotCohort;
644 protected RaftActorRecoveryCohort getRaftActorRecoveryCohort() {
645 return new ShardRecoveryCoordinator(store, store.getSchemaContext(),
646 restoreFromSnapshot != null ? restoreFromSnapshot.getSnapshot() : null, persistenceId(), LOG);
650 protected void onRecoveryComplete() {
651 restoreFromSnapshot = null;
653 //notify shard manager
654 getContext().parent().tell(new ActorInitialized(), getSelf());
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());
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
673 store.applyForeignCandidate(identifier, ((DataTreeCandidatePayload)data).getCandidate());
674 } catch (DataValidationFailedException | IOException e) {
675 LOG.error("{}: Error applying replica {}", persistenceId(), identifier, e);
678 // Replication consensus reached, proceed to commit
679 finishCommit(clientActor, identifier);
682 LOG.error("{}: Unknown state received {} ClassLoader {}", persistenceId(), data,
683 data.getClass().getClassLoader());
687 private void applyModificationToState(ActorRef clientActor, Identifier identifier, Object modification) {
688 if(modification == null) {
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.
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);
701 // This must be the OK to commit after replication consensus.
702 finishCommit(clientActor, identifier);
707 protected void onStateChanged() {
708 boolean isLeader = isLeader();
709 boolean hasLeader = hasLeader();
710 changeSupport.onLeadershipChange(isLeader, hasLeader);
711 treeChangeSupport.onLeadershipChange(isLeader, hasLeader);
713 // If this actor is no longer the leader close all the transaction chains
715 if(LOG.isDebugEnabled()) {
717 "{}: onStateChanged: Closing all transaction chains because shard {} is no longer the leader",
718 persistenceId(), getId());
721 store.closeAllTransactionChains();
724 if(hasLeader && !isIsolatedLeader()) {
725 messageRetrySupport.retryMessages();
730 protected void onLeaderChanged(String oldLeader, String newLeader) {
731 shardMBean.incrementLeadershipChangeCount();
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();
739 Collection<Object> messagesToForward = commitCoordinator.convertPendingTransactionsToMessages(
740 datastoreContext.getShardBatchedModificationCount());
742 if(!messagesToForward.isEmpty()) {
743 LOG.debug("{}: Forwarding {} pending transaction messages to leader {}", persistenceId(),
744 messagesToForward.size(), leader);
746 for(Object message: messagesToForward) {
747 leader.tell(message, self());
751 commitCoordinator.abortPendingTransactions(
752 "The transacton was aborted due to inflight leadership change and the leader address isn't available.",
757 if(hasLeader && !isIsolatedLeader()) {
758 messageRetrySupport.retryMessages();
763 protected void pauseLeader(Runnable operation) {
764 LOG.debug("{}: In pauseLeader, operation: {}", persistenceId(), operation);
765 commitCoordinator.setRunOnPendingTransactionsComplete(operation);
769 public String persistenceId() {
774 ShardCommitCoordinator getCommitCoordinator() {
775 return commitCoordinator;
778 public DatastoreContext getDatastoreContext() {
779 return datastoreContext;
783 public ShardDataTree getDataStore() {
788 ShardStats getShardMBean() {
792 public static Builder builder() {
793 return new Builder();
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;
805 protected AbstractBuilder(Class<S> shardClass) {
806 this.shardClass = shardClass;
809 protected void checkSealed() {
810 Preconditions.checkState(!sealed, "Builder isalready sealed - further modifications are not allowed");
813 @SuppressWarnings("unchecked")
818 public T id(ShardIdentifier id) {
824 public T peerAddresses(Map<String, String> peerAddresses) {
826 this.peerAddresses = peerAddresses;
830 public T datastoreContext(DatastoreContext datastoreContext) {
832 this.datastoreContext = datastoreContext;
836 public T schemaContext(SchemaContext schemaContext) {
838 this.schemaContext = schemaContext;
842 public T restoreFromSnapshot(DatastoreSnapshot.ShardSnapshot restoreFromSnapshot) {
844 this.restoreFromSnapshot = restoreFromSnapshot;
848 public ShardIdentifier getId() {
852 public Map<String, String> getPeerAddresses() {
853 return peerAddresses;
856 public DatastoreContext getDatastoreContext() {
857 return datastoreContext;
860 public SchemaContext getSchemaContext() {
861 return schemaContext;
864 public DatastoreSnapshot.ShardSnapshot getRestoreFromSnapshot() {
865 return restoreFromSnapshot;
868 public TreeType getTreeType() {
869 switch (datastoreContext.getLogicalStoreType()) {
871 return TreeType.CONFIGURATION;
873 return TreeType.OPERATIONAL;
876 throw new IllegalStateException("Unhandled logical store type " + datastoreContext.getLogicalStoreType());
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");
886 public Props props() {
889 return Props.create(shardClass, this);
893 public static class Builder extends AbstractBuilder<Builder, Shard> {