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.access.concepts.TransactionIdentifier;
27 import org.opendaylight.controller.cluster.common.actor.CommonConfig;
28 import org.opendaylight.controller.cluster.common.actor.MessageTracker;
29 import org.opendaylight.controller.cluster.common.actor.MessageTracker.Error;
30 import org.opendaylight.controller.cluster.common.actor.MeteringBehavior;
31 import org.opendaylight.controller.cluster.datastore.exceptions.NoShardLeaderException;
32 import org.opendaylight.controller.cluster.datastore.identifiers.ShardIdentifier;
33 import org.opendaylight.controller.cluster.datastore.jmx.mbeans.shard.ShardMBeanFactory;
34 import org.opendaylight.controller.cluster.datastore.jmx.mbeans.shard.ShardStats;
35 import org.opendaylight.controller.cluster.datastore.messages.AbortTransaction;
36 import org.opendaylight.controller.cluster.datastore.messages.ActorInitialized;
37 import org.opendaylight.controller.cluster.datastore.messages.BatchedModifications;
38 import org.opendaylight.controller.cluster.datastore.messages.CanCommitTransaction;
39 import org.opendaylight.controller.cluster.datastore.messages.CloseTransactionChain;
40 import org.opendaylight.controller.cluster.datastore.messages.CommitTransaction;
41 import org.opendaylight.controller.cluster.datastore.messages.CommitTransactionReply;
42 import org.opendaylight.controller.cluster.datastore.messages.CreateTransaction;
43 import org.opendaylight.controller.cluster.datastore.messages.CreateTransactionReply;
44 import org.opendaylight.controller.cluster.datastore.messages.DatastoreSnapshot;
45 import org.opendaylight.controller.cluster.datastore.messages.DatastoreSnapshot.ShardSnapshot;
46 import org.opendaylight.controller.cluster.datastore.messages.ForwardedReadyTransaction;
47 import org.opendaylight.controller.cluster.datastore.messages.GetShardDataTree;
48 import org.opendaylight.controller.cluster.datastore.messages.PeerAddressResolved;
49 import org.opendaylight.controller.cluster.datastore.messages.ReadyLocalTransaction;
50 import org.opendaylight.controller.cluster.datastore.messages.RegisterChangeListener;
51 import org.opendaylight.controller.cluster.datastore.messages.RegisterDataTreeChangeListener;
52 import org.opendaylight.controller.cluster.datastore.messages.ShardLeaderStateChanged;
53 import org.opendaylight.controller.cluster.datastore.messages.UpdateSchemaContext;
54 import org.opendaylight.controller.cluster.datastore.utils.Dispatchers;
55 import org.opendaylight.controller.cluster.notifications.LeaderStateChanged;
56 import org.opendaylight.controller.cluster.notifications.RegisterRoleChangeListener;
57 import org.opendaylight.controller.cluster.notifications.RoleChangeNotifier;
58 import org.opendaylight.controller.cluster.raft.RaftActor;
59 import org.opendaylight.controller.cluster.raft.RaftActorRecoveryCohort;
60 import org.opendaylight.controller.cluster.raft.RaftActorSnapshotCohort;
61 import org.opendaylight.controller.cluster.raft.RaftState;
62 import org.opendaylight.controller.cluster.raft.base.messages.FollowerInitialSyncUpStatus;
63 import org.opendaylight.controller.cluster.raft.messages.AppendEntriesReply;
64 import org.opendaylight.controller.cluster.raft.messages.ServerRemoved;
65 import org.opendaylight.yangtools.concepts.Identifier;
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(builder.getId().getMemberName(), transactionActorFactory, store,
176 messageRetrySupport = new ShardTransactionMessageRetrySupport(this);
179 private void setTransactionCommitTimeout() {
180 transactionCommitTimeout = TimeUnit.MILLISECONDS.convert(
181 datastoreContext.getShardTransactionCommitTimeoutInSeconds(), TimeUnit.SECONDS) / 2;
184 private Optional<ActorRef> createRoleChangeNotifier(String shardId) {
185 ActorRef shardRoleChangeNotifier = this.getContext().actorOf(
186 RoleChangeNotifier.getProps(shardId), shardId + "-notifier");
187 return Optional.of(shardRoleChangeNotifier);
191 public void postStop() {
192 LOG.info("Stopping Shard {}", persistenceId());
196 messageRetrySupport.close();
198 if(txCommitTimeoutCheckSchedule != null) {
199 txCommitTimeoutCheckSchedule.cancel();
202 commitCoordinator.abortPendingTransactions("Transaction aborted due to shutdown.", this);
204 shardMBean.unregisterMBean();
208 protected void handleRecover(final Object message) {
209 LOG.debug("{}: onReceiveRecover: Received message {} from {}", persistenceId(), message.getClass(),
212 super.handleRecover(message);
213 if (LOG.isTraceEnabled()) {
214 appendEntriesReplyTracker.begin();
219 protected void handleNonRaftCommand(final Object message) {
220 try (final MessageTracker.Context context = appendEntriesReplyTracker.received(message)) {
221 final Optional<Error> maybeError = context.error();
222 if (maybeError.isPresent()) {
223 LOG.trace("{} : AppendEntriesReply failed to arrive at the expected interval {}", persistenceId(),
227 if (CreateTransaction.isSerializedType(message)) {
228 handleCreateTransaction(message);
229 } else if (message instanceof BatchedModifications) {
230 handleBatchedModifications((BatchedModifications)message);
231 } else if (message instanceof ForwardedReadyTransaction) {
232 handleForwardedReadyTransaction((ForwardedReadyTransaction) message);
233 } else if (message instanceof ReadyLocalTransaction) {
234 handleReadyLocalTransaction((ReadyLocalTransaction)message);
235 } else if (CanCommitTransaction.isSerializedType(message)) {
236 handleCanCommitTransaction(CanCommitTransaction.fromSerializable(message));
237 } else if (CommitTransaction.isSerializedType(message)) {
238 handleCommitTransaction(CommitTransaction.fromSerializable(message));
239 } else if (AbortTransaction.isSerializedType(message)) {
240 handleAbortTransaction(AbortTransaction.fromSerializable(message));
241 } else if (CloseTransactionChain.isSerializedType(message)) {
242 closeTransactionChain(CloseTransactionChain.fromSerializable(message));
243 } else if (message instanceof RegisterChangeListener) {
244 changeSupport.onMessage((RegisterChangeListener) message, isLeader(), hasLeader());
245 } else if (message instanceof RegisterDataTreeChangeListener) {
246 treeChangeSupport.onMessage((RegisterDataTreeChangeListener) message, isLeader(), hasLeader());
247 } else if (message instanceof UpdateSchemaContext) {
248 updateSchemaContext((UpdateSchemaContext) message);
249 } else if (message instanceof PeerAddressResolved) {
250 PeerAddressResolved resolved = (PeerAddressResolved) message;
251 setPeerAddress(resolved.getPeerId().toString(),
252 resolved.getPeerAddress());
253 } else if (TX_COMMIT_TIMEOUT_CHECK_MESSAGE.equals(message)) {
254 commitCoordinator.checkForExpiredTransactions(transactionCommitTimeout, this);
255 } else if(message instanceof DatastoreContext) {
256 onDatastoreContext((DatastoreContext)message);
257 } else if(message instanceof RegisterRoleChangeListener){
258 roleChangeNotifier.get().forward(message, context());
259 } else if (message instanceof FollowerInitialSyncUpStatus) {
260 shardMBean.setFollowerInitialSyncStatus(((FollowerInitialSyncUpStatus) message).isInitialSyncDone());
261 context().parent().tell(message, self());
262 } else if(GET_SHARD_MBEAN_MESSAGE.equals(message)){
263 sender().tell(getShardMBean(), self());
264 } else if(message instanceof GetShardDataTree) {
265 sender().tell(store.getDataTree(), self());
266 } else if(message instanceof ServerRemoved){
267 context().parent().forward(message, context());
268 } else if(ShardTransactionMessageRetrySupport.TIMER_MESSAGE_CLASS.isInstance(message)) {
269 messageRetrySupport.onTimerMessage(message);
270 } else if (message instanceof DataTreeCohortActorRegistry.CohortRegistryCommand) {
271 commitCoordinator.processCohortRegistryCommand(getSender(),
272 (DataTreeCohortActorRegistry.CohortRegistryCommand) message);
274 super.handleNonRaftCommand(message);
279 private boolean hasLeader() {
280 return getLeaderId() != null;
283 public int getPendingTxCommitQueueSize() {
284 return commitCoordinator.getQueueSize();
287 public int getCohortCacheSize() {
288 return commitCoordinator.getCohortCacheSize();
292 protected Optional<ActorRef> getRoleChangeNotifier() {
293 return roleChangeNotifier;
297 protected LeaderStateChanged newLeaderStateChanged(String memberId, String leaderId, short leaderPayloadVersion) {
298 return isLeader() ? new ShardLeaderStateChanged(memberId, leaderId, store.getDataTree(), leaderPayloadVersion)
299 : new ShardLeaderStateChanged(memberId, leaderId, leaderPayloadVersion);
302 protected void onDatastoreContext(DatastoreContext context) {
303 datastoreContext = context;
305 commitCoordinator.setQueueCapacity(datastoreContext.getShardTransactionCommitQueueCapacity());
307 setTransactionCommitTimeout();
309 if(datastoreContext.isPersistent() && !persistence().isRecoveryApplicable()) {
310 setPersistence(true);
311 } else if(!datastoreContext.isPersistent() && persistence().isRecoveryApplicable()) {
312 setPersistence(false);
315 updateConfigParams(datastoreContext.getShardRaftConfig());
318 private static boolean isEmptyCommit(final DataTreeCandidate candidate) {
319 return ModificationType.UNMODIFIED.equals(candidate.getRootNode().getModificationType());
322 void continueCommit(final CohortEntry cohortEntry) {
323 final DataTreeCandidate candidate = cohortEntry.getCandidate();
325 // If we do not have any followers and we are not using persistence
326 // or if cohortEntry has no modifications
327 // we can apply modification to the state immediately
328 if ((!hasFollowers() && !persistence().isRecoveryApplicable()) || isEmptyCommit(candidate)) {
329 applyModificationToState(cohortEntry.getReplySender(), cohortEntry.getTransactionID(), candidate);
331 persistData(cohortEntry.getReplySender(), cohortEntry.getTransactionID(),
332 DataTreeCandidatePayload.create(candidate));
336 private void handleCommitTransaction(final CommitTransaction commit) {
338 if(!commitCoordinator.handleCommit(commit.getTransactionID(), getSender(), this)) {
339 shardMBean.incrementFailedTransactionsCount();
342 ActorSelection leader = getLeader();
343 if (leader == null) {
344 messageRetrySupport.addMessageToRetry(commit, getSender(),
345 "Could not commit transaction " + commit.getTransactionID());
347 LOG.debug("{}: Forwarding CommitTransaction to leader {}", persistenceId(), leader);
348 leader.forward(commit, getContext());
353 private void finishCommit(@Nonnull final ActorRef sender, @Nonnull final Identifier transactionID,
354 @Nonnull final CohortEntry cohortEntry) {
355 LOG.debug("{}: Finishing commit for transaction {}", persistenceId(), cohortEntry.getTransactionID());
359 cohortEntry.commit();
360 } catch(ExecutionException e) {
361 // We may get a "store tree and candidate base differ" IllegalStateException from commit under
362 // certain edge case scenarios so we'll try to re-apply the candidate from scratch as a last
363 // resort. Eg, we're a follower and a tx payload is replicated but the leader goes down before
364 // applying it to the state. We then become the leader and a second tx is pre-committed and
365 // replicated. When consensus occurs, this will cause the first tx to be applied as a foreign
366 // candidate via applyState prior to the second tx. Since the second tx has already been
367 // pre-committed, when it gets here to commit it will get an IllegalStateException.
369 // FIXME - this is not an ideal way to handle this scenario. This is temporary - a cleaner
370 // solution will be forthcoming.
371 if(e.getCause() instanceof IllegalStateException) {
372 LOG.debug("{}: commit failed for transaction {} - retrying as foreign candidate", persistenceId(),
374 store.applyForeignCandidate(transactionID, cohortEntry.getCandidate());
380 sender.tell(CommitTransactionReply.instance(cohortEntry.getClientVersion()).toSerializable(), getSelf());
382 shardMBean.incrementCommittedTransactionCount();
383 shardMBean.setLastCommittedTransactionTime(System.currentTimeMillis());
385 } catch (Exception e) {
386 sender.tell(new akka.actor.Status.Failure(e), getSelf());
388 LOG.error("{}, An exception occurred while committing transaction {}", persistenceId(),
390 shardMBean.incrementFailedTransactionsCount();
392 commitCoordinator.currentTransactionComplete(transactionID, true);
396 private void finishCommit(@Nonnull final ActorRef sender, final @Nonnull Identifier transactionID) {
397 // With persistence enabled, this method is called via applyState by the leader strategy
398 // after the commit has been replicated to a majority of the followers.
400 CohortEntry cohortEntry = commitCoordinator.getCohortEntryIfCurrent(transactionID);
401 if (cohortEntry == null) {
402 // The transaction is no longer the current commit. This can happen if the transaction
403 // was aborted prior, most likely due to timeout in the front-end. We need to finish
404 // committing the transaction though since it was successfully persisted and replicated
405 // however we can't use the original cohort b/c it was already preCommitted and may
406 // conflict with the current commit or may have been aborted so we commit with a new
408 cohortEntry = commitCoordinator.getAndRemoveCohortEntry(transactionID);
409 if(cohortEntry != null) {
411 store.applyForeignCandidate(transactionID, cohortEntry.getCandidate());
412 } catch (DataValidationFailedException e) {
413 shardMBean.incrementFailedTransactionsCount();
414 LOG.error("{}: Failed to re-apply transaction {}", persistenceId(), transactionID, e);
417 sender.tell(CommitTransactionReply.instance(cohortEntry.getClientVersion()).toSerializable(),
420 // This really shouldn't happen - it likely means that persistence or replication
421 // took so long to complete such that the cohort entry was expired from the cache.
422 IllegalStateException ex = new IllegalStateException(
423 String.format("%s: Could not finish committing transaction %s - no CohortEntry found",
424 persistenceId(), transactionID));
425 LOG.error(ex.getMessage());
426 sender.tell(new akka.actor.Status.Failure(ex), getSelf());
429 finishCommit(sender, transactionID, cohortEntry);
433 private void handleCanCommitTransaction(final CanCommitTransaction canCommit) {
434 LOG.debug("{}: Can committing transaction {}", persistenceId(), canCommit.getTransactionID());
437 commitCoordinator.handleCanCommit(canCommit.getTransactionID(), getSender(), this);
439 ActorSelection leader = getLeader();
440 if (leader == null) {
441 messageRetrySupport.addMessageToRetry(canCommit, getSender(),
442 "Could not canCommit transaction " + canCommit.getTransactionID());
444 LOG.debug("{}: Forwarding CanCommitTransaction to leader {}", persistenceId(), leader);
445 leader.forward(canCommit, getContext());
450 protected void handleBatchedModificationsLocal(BatchedModifications batched, ActorRef sender) {
452 commitCoordinator.handleBatchedModifications(batched, sender, this, store.getSchemaContext());
453 } catch (Exception e) {
454 LOG.error("{}: Error handling BatchedModifications for Tx {}", persistenceId(),
455 batched.getTransactionID(), e);
456 sender.tell(new akka.actor.Status.Failure(e), getSelf());
460 private void handleBatchedModifications(BatchedModifications batched) {
461 // This message is sent to prepare the modifications transaction directly on the Shard as an
462 // optimization to avoid the extra overhead of a separate ShardTransaction actor. On the last
463 // BatchedModifications message, the caller sets the ready flag in the message indicating
464 // modifications are complete. The reply contains the cohort actor path (this actor) for the caller
465 // to initiate the 3-phase commit. This also avoids the overhead of sending an additional
466 // ReadyTransaction message.
468 // If we're not the leader then forward to the leader. This is a safety measure - we shouldn't
469 // normally get here if we're not the leader as the front-end (TransactionProxy) should determine
470 // the primary/leader shard. However with timing and caching on the front-end, there's a small
471 // window where it could have a stale leader during leadership transitions.
473 boolean isLeaderActive = isLeaderActive();
474 if (isLeader() && isLeaderActive) {
475 handleBatchedModificationsLocal(batched, getSender());
477 ActorSelection leader = getLeader();
478 if (!isLeaderActive || leader == null) {
479 messageRetrySupport.addMessageToRetry(batched, getSender(),
480 "Could not commit transaction " + batched.getTransactionID());
482 // If this is not the first batch and leadership changed in between batched messages,
483 // we need to reconstruct previous BatchedModifications from the transaction
484 // DataTreeModification, honoring the max batched modification count, and forward all the
485 // previous BatchedModifications to the new leader.
486 Collection<BatchedModifications> newModifications = commitCoordinator.createForwardedBatchedModifications(
487 batched, datastoreContext.getShardBatchedModificationCount());
489 LOG.debug("{}: Forwarding {} BatchedModifications to leader {}", persistenceId(),
490 newModifications.size(), leader);
492 for(BatchedModifications bm: newModifications) {
493 leader.forward(bm, getContext());
499 private boolean failIfIsolatedLeader(ActorRef sender) {
500 if(isIsolatedLeader()) {
501 sender.tell(new akka.actor.Status.Failure(new NoShardLeaderException(String.format(
502 "Shard %s was the leader but has lost contact with all of its followers. Either all" +
503 " other follower nodes are down or this node is isolated by a network partition.",
504 persistenceId()))), getSelf());
511 protected boolean isIsolatedLeader() {
512 return getRaftState() == RaftState.IsolatedLeader;
515 private void handleReadyLocalTransaction(final ReadyLocalTransaction message) {
516 LOG.debug("{}: handleReadyLocalTransaction for {}", persistenceId(), message.getTransactionID());
518 boolean isLeaderActive = isLeaderActive();
519 if (isLeader() && isLeaderActive) {
521 commitCoordinator.handleReadyLocalTransaction(message, getSender(), this, store.getSchemaContext());
522 } catch (Exception e) {
523 LOG.error("{}: Error handling ReadyLocalTransaction for Tx {}", persistenceId(),
524 message.getTransactionID(), e);
525 getSender().tell(new akka.actor.Status.Failure(e), getSelf());
528 ActorSelection leader = getLeader();
529 if (!isLeaderActive || leader == null) {
530 messageRetrySupport.addMessageToRetry(message, getSender(),
531 "Could not commit transaction " + message.getTransactionID());
533 LOG.debug("{}: Forwarding ReadyLocalTransaction to leader {}", persistenceId(), leader);
534 message.setRemoteVersion(getCurrentBehavior().getLeaderPayloadVersion());
535 leader.forward(message, getContext());
540 private void handleForwardedReadyTransaction(ForwardedReadyTransaction forwardedReady) {
541 LOG.debug("{}: handleForwardedReadyTransaction for {}", persistenceId(), forwardedReady.getTransactionID());
543 boolean isLeaderActive = isLeaderActive();
544 if (isLeader() && isLeaderActive) {
545 commitCoordinator.handleForwardedReadyTransaction(forwardedReady, getSender(), this,
546 store.getSchemaContext());
548 ActorSelection leader = getLeader();
549 if (!isLeaderActive || leader == null) {
550 messageRetrySupport.addMessageToRetry(forwardedReady, getSender(),
551 "Could not commit transaction " + forwardedReady.getTransactionID());
553 LOG.debug("{}: Forwarding ForwardedReadyTransaction to leader {}", persistenceId(), leader);
555 ReadyLocalTransaction readyLocal = new ReadyLocalTransaction(forwardedReady.getTransactionID(),
556 forwardedReady.getTransaction().getSnapshot(), forwardedReady.isDoImmediateCommit());
557 readyLocal.setRemoteVersion(getCurrentBehavior().getLeaderPayloadVersion());
558 leader.forward(readyLocal, getContext());
563 private void handleAbortTransaction(final AbortTransaction abort) {
564 doAbortTransaction(abort.getTransactionID(), getSender());
567 void doAbortTransaction(final TransactionIdentifier transactionID, final ActorRef sender) {
568 commitCoordinator.handleAbort(transactionID, sender, this);
571 private void handleCreateTransaction(final Object message) {
573 createTransaction(CreateTransaction.fromSerializable(message));
574 } else if (getLeader() != null) {
575 getLeader().forward(message, getContext());
577 getSender().tell(new akka.actor.Status.Failure(new NoShardLeaderException(
578 "Could not create a shard transaction", persistenceId())), getSelf());
582 private void closeTransactionChain(final CloseTransactionChain closeTransactionChain) {
583 store.closeTransactionChain(closeTransactionChain.getTransactionChainId());
586 private void createTransaction(CreateTransaction createTransaction) {
588 if(TransactionType.fromInt(createTransaction.getTransactionType()) != TransactionType.READ_ONLY &&
589 failIfIsolatedLeader(getSender())) {
593 ActorRef transactionActor = createTransaction(createTransaction.getTransactionType(),
594 createTransaction.getTransactionId());
596 getSender().tell(new CreateTransactionReply(Serialization.serializedActorPath(transactionActor),
597 createTransaction.getTransactionId(), createTransaction.getVersion()).toSerializable(), getSelf());
598 } catch (Exception e) {
599 getSender().tell(new akka.actor.Status.Failure(e), getSelf());
603 private ActorRef createTransaction(int transactionType, TransactionIdentifier transactionId) {
604 LOG.debug("{}: Creating transaction : {} ", persistenceId(), transactionId);
605 return transactionActorFactory.newShardTransaction(TransactionType.fromInt(transactionType),
609 private void commitWithNewTransaction(final BatchedModifications modification) {
610 ReadWriteShardDataTreeTransaction tx = store.newReadWriteTransaction(modification.getTransactionID());
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> {