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.ShardCommitCoordinator.CohortEntry;
31 import org.opendaylight.controller.cluster.datastore.exceptions.NoShardLeaderException;
32 import org.opendaylight.controller.cluster.datastore.identifiers.ShardIdentifier;
33 import org.opendaylight.controller.cluster.datastore.identifiers.ShardTransactionIdentifier;
34 import org.opendaylight.controller.cluster.datastore.jmx.mbeans.shard.ShardMBeanFactory;
35 import org.opendaylight.controller.cluster.datastore.jmx.mbeans.shard.ShardStats;
36 import org.opendaylight.controller.cluster.datastore.messages.AbortTransaction;
37 import org.opendaylight.controller.cluster.datastore.messages.ActorInitialized;
38 import org.opendaylight.controller.cluster.datastore.messages.BatchedModifications;
39 import org.opendaylight.controller.cluster.datastore.messages.CanCommitTransaction;
40 import org.opendaylight.controller.cluster.datastore.messages.CloseTransactionChain;
41 import org.opendaylight.controller.cluster.datastore.messages.CommitTransaction;
42 import org.opendaylight.controller.cluster.datastore.messages.CommitTransactionReply;
43 import org.opendaylight.controller.cluster.datastore.messages.CreateTransaction;
44 import org.opendaylight.controller.cluster.datastore.messages.CreateTransactionReply;
45 import org.opendaylight.controller.cluster.datastore.messages.DatastoreSnapshot;
46 import org.opendaylight.controller.cluster.datastore.messages.DatastoreSnapshot.ShardSnapshot;
47 import org.opendaylight.controller.cluster.datastore.messages.ForwardedReadyTransaction;
48 import org.opendaylight.controller.cluster.datastore.messages.GetShardDataTree;
49 import org.opendaylight.controller.cluster.datastore.messages.PeerAddressResolved;
50 import org.opendaylight.controller.cluster.datastore.messages.ReadyLocalTransaction;
51 import org.opendaylight.controller.cluster.datastore.messages.RegisterChangeListener;
52 import org.opendaylight.controller.cluster.datastore.messages.RegisterDataTreeChangeListener;
53 import org.opendaylight.controller.cluster.datastore.messages.ShardLeaderStateChanged;
54 import org.opendaylight.controller.cluster.datastore.messages.UpdateSchemaContext;
55 import org.opendaylight.controller.cluster.datastore.modification.Modification;
56 import org.opendaylight.controller.cluster.datastore.modification.MutableCompositeModification;
57 import org.opendaylight.controller.cluster.datastore.utils.Dispatchers;
58 import org.opendaylight.controller.cluster.notifications.LeaderStateChanged;
59 import org.opendaylight.controller.cluster.notifications.RegisterRoleChangeListener;
60 import org.opendaylight.controller.cluster.notifications.RoleChangeNotifier;
61 import org.opendaylight.controller.cluster.raft.RaftActor;
62 import org.opendaylight.controller.cluster.raft.RaftActorRecoveryCohort;
63 import org.opendaylight.controller.cluster.raft.RaftActorSnapshotCohort;
64 import org.opendaylight.controller.cluster.raft.RaftState;
65 import org.opendaylight.controller.cluster.raft.base.messages.FollowerInitialSyncUpStatus;
66 import org.opendaylight.controller.cluster.raft.messages.AppendEntriesReply;
67 import org.opendaylight.controller.cluster.raft.messages.ServerRemoved;
68 import org.opendaylight.controller.cluster.raft.protobuff.client.messages.CompositeModificationByteStringPayload;
69 import org.opendaylight.controller.cluster.raft.protobuff.client.messages.CompositeModificationPayload;
70 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTree;
71 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidate;
72 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataValidationFailedException;
73 import org.opendaylight.yangtools.yang.data.api.schema.tree.ModificationType;
74 import org.opendaylight.yangtools.yang.data.api.schema.tree.TreeType;
75 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
76 import scala.concurrent.duration.Duration;
77 import scala.concurrent.duration.FiniteDuration;
80 * A Shard represents a portion of the logical data tree <br/>
82 * Our Shard uses InMemoryDataTree as it's internal representation and delegates all requests it
85 public class Shard extends RaftActor {
87 protected static final Object TX_COMMIT_TIMEOUT_CHECK_MESSAGE = "txCommitTimeoutCheck";
90 static final Object GET_SHARD_MBEAN_MESSAGE = "getShardMBeanMessage";
92 // FIXME: shard names should be encapsulated in their own class and this should be exposed as a constant.
93 public static final String DEFAULT_NAME = "default";
95 // The state of this Shard
96 private final ShardDataTree store;
98 /// The name of this shard
99 private final String name;
101 private final ShardStats shardMBean;
103 private DatastoreContext datastoreContext;
105 private final ShardCommitCoordinator commitCoordinator;
107 private long transactionCommitTimeout;
109 private Cancellable txCommitTimeoutCheckSchedule;
111 private final Optional<ActorRef> roleChangeNotifier;
113 private final MessageTracker appendEntriesReplyTracker;
115 private final ShardTransactionActorFactory transactionActorFactory;
117 private final ShardSnapshotCohort snapshotCohort;
119 private final DataTreeChangeListenerSupport treeChangeSupport = new DataTreeChangeListenerSupport(this);
120 private final DataChangeListenerSupport changeSupport = new DataChangeListenerSupport(this);
123 private ShardSnapshot restoreFromSnapshot;
125 private final ShardTransactionMessageRetrySupport messageRetrySupport;
127 protected Shard(AbstractBuilder<?, ?> builder) {
128 super(builder.getId().toString(), builder.getPeerAddresses(),
129 Optional.of(builder.getDatastoreContext().getShardRaftConfig()), DataStoreVersions.CURRENT_VERSION);
131 this.name = builder.getId().toString();
132 this.datastoreContext = builder.getDatastoreContext();
133 this.restoreFromSnapshot = builder.getRestoreFromSnapshot();
135 setPersistence(datastoreContext.isPersistent());
137 LOG.info("Shard created : {}, persistent : {}", name, datastoreContext.isPersistent());
139 store = new ShardDataTree(builder.getSchemaContext(), builder.getTreeType(),
140 new ShardDataTreeChangeListenerPublisherActorProxy(getContext(), name + "-DTCL-publisher"),
141 new ShardDataChangeListenerPublisherActorProxy(getContext(), name + "-DCL-publisher"), name);
143 shardMBean = ShardMBeanFactory.getShardStatsMBean(name.toString(),
144 datastoreContext.getDataStoreMXBeanType());
145 shardMBean.setShard(this);
147 if (isMetricsCaptureEnabled()) {
148 getContext().become(new MeteringBehavior(this));
151 commitCoordinator = new ShardCommitCoordinator(store,
152 datastoreContext.getShardCommitQueueExpiryTimeoutInMillis(),
153 datastoreContext.getShardTransactionCommitQueueCapacity(), LOG, this.name);
155 setTransactionCommitTimeout();
157 // create a notifier actor for each cluster member
158 roleChangeNotifier = createRoleChangeNotifier(name.toString());
160 appendEntriesReplyTracker = new MessageTracker(AppendEntriesReply.class,
161 getRaftActorContext().getConfigParams().getIsolatedCheckIntervalInMillis());
163 transactionActorFactory = new ShardTransactionActorFactory(store, datastoreContext,
164 new Dispatchers(context().system().dispatchers()).getDispatcherPath(
165 Dispatchers.DispatcherType.Transaction), self(), getContext(), shardMBean);
167 snapshotCohort = new ShardSnapshotCohort(transactionActorFactory, store, LOG, this.name);
169 messageRetrySupport = new ShardTransactionMessageRetrySupport(this);
172 private void setTransactionCommitTimeout() {
173 transactionCommitTimeout = TimeUnit.MILLISECONDS.convert(
174 datastoreContext.getShardTransactionCommitTimeoutInSeconds(), TimeUnit.SECONDS) / 2;
177 private Optional<ActorRef> createRoleChangeNotifier(String shardId) {
178 ActorRef shardRoleChangeNotifier = this.getContext().actorOf(
179 RoleChangeNotifier.getProps(shardId), shardId + "-notifier");
180 return Optional.of(shardRoleChangeNotifier);
184 public void postStop() {
185 LOG.info("Stopping Shard {}", persistenceId());
189 messageRetrySupport.close();
191 if(txCommitTimeoutCheckSchedule != null) {
192 txCommitTimeoutCheckSchedule.cancel();
195 commitCoordinator.abortPendingTransactions("Transaction aborted due to shutdown.", this);
197 shardMBean.unregisterMBean();
201 protected void handleRecover(final Object message) {
202 LOG.debug("{}: onReceiveRecover: Received message {} from {}", persistenceId(), message.getClass(),
205 super.handleRecover(message);
206 if (LOG.isTraceEnabled()) {
207 appendEntriesReplyTracker.begin();
212 protected void handleCommand(final Object message) {
214 final MessageTracker.Context context = appendEntriesReplyTracker.received(message);
215 final Optional<Error> maybeError = context.error();
216 if (maybeError.isPresent()) {
217 LOG.trace("{} : AppendEntriesReply failed to arrive at the expected interval {}", persistenceId(),
222 if (CreateTransaction.isSerializedType(message)) {
223 handleCreateTransaction(message);
224 } else if (message instanceof BatchedModifications) {
225 handleBatchedModifications((BatchedModifications)message);
226 } else if (message instanceof ForwardedReadyTransaction) {
227 handleForwardedReadyTransaction((ForwardedReadyTransaction) message);
228 } else if (message instanceof ReadyLocalTransaction) {
229 handleReadyLocalTransaction((ReadyLocalTransaction)message);
230 } else if (CanCommitTransaction.isSerializedType(message)) {
231 handleCanCommitTransaction(CanCommitTransaction.fromSerializable(message));
232 } else if (CommitTransaction.isSerializedType(message)) {
233 handleCommitTransaction(CommitTransaction.fromSerializable(message));
234 } else if (AbortTransaction.isSerializedType(message)) {
235 handleAbortTransaction(AbortTransaction.fromSerializable(message));
236 } else if (CloseTransactionChain.isSerializedType(message)) {
237 closeTransactionChain(CloseTransactionChain.fromSerializable(message));
238 } else if (message instanceof RegisterChangeListener) {
239 changeSupport.onMessage((RegisterChangeListener) message, isLeader(), hasLeader());
240 } else if (message instanceof RegisterDataTreeChangeListener) {
241 treeChangeSupport.onMessage((RegisterDataTreeChangeListener) message, isLeader(), hasLeader());
242 } else if (message instanceof UpdateSchemaContext) {
243 updateSchemaContext((UpdateSchemaContext) message);
244 } else if (message instanceof PeerAddressResolved) {
245 PeerAddressResolved resolved = (PeerAddressResolved) message;
246 setPeerAddress(resolved.getPeerId().toString(),
247 resolved.getPeerAddress());
248 } else if (message.equals(TX_COMMIT_TIMEOUT_CHECK_MESSAGE)) {
249 commitCoordinator.checkForExpiredTransactions(transactionCommitTimeout, this);
250 } else if(message instanceof DatastoreContext) {
251 onDatastoreContext((DatastoreContext)message);
252 } else if(message instanceof RegisterRoleChangeListener){
253 roleChangeNotifier.get().forward(message, context());
254 } else if (message instanceof FollowerInitialSyncUpStatus) {
255 shardMBean.setFollowerInitialSyncStatus(((FollowerInitialSyncUpStatus) message).isInitialSyncDone());
256 context().parent().tell(message, self());
257 } else if(GET_SHARD_MBEAN_MESSAGE.equals(message)){
258 sender().tell(getShardMBean(), self());
259 } else if(message instanceof GetShardDataTree) {
260 sender().tell(store.getDataTree(), self());
261 } else if(message instanceof ServerRemoved){
262 context().parent().forward(message, context());
263 } else if(ShardTransactionMessageRetrySupport.TIMER_MESSAGE_CLASS.isInstance(message)) {
264 messageRetrySupport.onTimerMessage(message);
266 super.handleCommand(message);
273 private boolean hasLeader() {
274 return getLeaderId() != null;
277 public int getPendingTxCommitQueueSize() {
278 return commitCoordinator.getQueueSize();
281 public int getCohortCacheSize() {
282 return commitCoordinator.getCohortCacheSize();
286 protected Optional<ActorRef> getRoleChangeNotifier() {
287 return roleChangeNotifier;
291 protected LeaderStateChanged newLeaderStateChanged(String memberId, String leaderId, short leaderPayloadVersion) {
292 return new ShardLeaderStateChanged(memberId, leaderId,
293 isLeader() ? Optional.<DataTree>of(store.getDataTree()) : Optional.<DataTree>absent(),
294 leaderPayloadVersion);
297 protected void onDatastoreContext(DatastoreContext context) {
298 datastoreContext = context;
300 commitCoordinator.setQueueCapacity(datastoreContext.getShardTransactionCommitQueueCapacity());
302 setTransactionCommitTimeout();
304 if(datastoreContext.isPersistent() && !persistence().isRecoveryApplicable()) {
305 setPersistence(true);
306 } else if(!datastoreContext.isPersistent() && persistence().isRecoveryApplicable()) {
307 setPersistence(false);
310 updateConfigParams(datastoreContext.getShardRaftConfig());
313 private static boolean isEmptyCommit(final DataTreeCandidate candidate) {
314 return ModificationType.UNMODIFIED.equals(candidate.getRootNode().getModificationType());
317 void continueCommit(final CohortEntry cohortEntry) {
318 final DataTreeCandidate candidate = cohortEntry.getCandidate();
320 // If we do not have any followers and we are not using persistence
321 // or if cohortEntry has no modifications
322 // we can apply modification to the state immediately
323 if ((!hasFollowers() && !persistence().isRecoveryApplicable()) || isEmptyCommit(candidate)) {
324 applyModificationToState(cohortEntry.getReplySender(), cohortEntry.getTransactionID(), candidate);
326 Shard.this.persistData(cohortEntry.getReplySender(), cohortEntry.getTransactionID(),
327 DataTreeCandidatePayload.create(candidate));
331 private void handleCommitTransaction(final CommitTransaction commit) {
333 if(!commitCoordinator.handleCommit(commit.getTransactionID(), getSender(), this)) {
334 shardMBean.incrementFailedTransactionsCount();
337 ActorSelection leader = getLeader();
338 if (leader == null) {
339 messageRetrySupport.addMessageToRetry(commit, getSender(),
340 "Could not commit transaction " + commit.getTransactionID());
342 LOG.debug("{}: Forwarding CommitTransaction to leader {}", persistenceId(), leader);
343 leader.forward(commit, getContext());
348 private void finishCommit(@Nonnull final ActorRef sender, @Nonnull final String transactionID, @Nonnull final CohortEntry cohortEntry) {
349 LOG.debug("{}: Finishing commit for transaction {}", persistenceId(), cohortEntry.getTransactionID());
353 cohortEntry.commit();
354 } catch(ExecutionException e) {
355 // We may get a "store tree and candidate base differ" IllegalStateException from commit under
356 // certain edge case scenarios so we'll try to re-apply the candidate from scratch as a last
357 // resort. Eg, we're a follower and a tx payload is replicated but the leader goes down before
358 // applying it to the state. We then become the leader and a second tx is pre-committed and
359 // replicated. When consensus occurs, this will cause the first tx to be applied as a foreign
360 // candidate via applyState prior to the second tx. Since the second tx has already been
361 // pre-committed, when it gets here to commit it will get an IllegalStateException.
363 // FIXME - this is not an ideal way to handle this scenario. This is temporary - a cleaner
364 // solution will be forthcoming.
365 if(e.getCause() instanceof IllegalStateException) {
366 LOG.debug("{}: commit failed for transaction {} - retrying as foreign candidate", persistenceId(),
368 store.applyForeignCandidate(transactionID, cohortEntry.getCandidate());
374 sender.tell(CommitTransactionReply.instance(cohortEntry.getClientVersion()).toSerializable(), getSelf());
376 shardMBean.incrementCommittedTransactionCount();
377 shardMBean.setLastCommittedTransactionTime(System.currentTimeMillis());
379 } catch (Exception e) {
380 sender.tell(new akka.actor.Status.Failure(e), getSelf());
382 LOG.error("{}, An exception occurred while committing transaction {}", persistenceId(),
384 shardMBean.incrementFailedTransactionsCount();
386 commitCoordinator.currentTransactionComplete(transactionID, true);
390 private void finishCommit(@Nonnull final ActorRef sender, final @Nonnull String transactionID) {
391 // With persistence enabled, this method is called via applyState by the leader strategy
392 // after the commit has been replicated to a majority of the followers.
394 CohortEntry cohortEntry = commitCoordinator.getCohortEntryIfCurrent(transactionID);
395 if (cohortEntry == null) {
396 // The transaction is no longer the current commit. This can happen if the transaction
397 // was aborted prior, most likely due to timeout in the front-end. We need to finish
398 // committing the transaction though since it was successfully persisted and replicated
399 // however we can't use the original cohort b/c it was already preCommitted and may
400 // conflict with the current commit or may have been aborted so we commit with a new
402 cohortEntry = commitCoordinator.getAndRemoveCohortEntry(transactionID);
403 if(cohortEntry != null) {
405 store.applyForeignCandidate(transactionID, cohortEntry.getCandidate());
406 } catch (DataValidationFailedException e) {
407 shardMBean.incrementFailedTransactionsCount();
408 LOG.error("{}: Failed to re-apply transaction {}", persistenceId(), transactionID, e);
411 sender.tell(CommitTransactionReply.instance(cohortEntry.getClientVersion()).toSerializable(),
414 // This really shouldn't happen - it likely means that persistence or replication
415 // took so long to complete such that the cohort entry was expired from the cache.
416 IllegalStateException ex = new IllegalStateException(
417 String.format("%s: Could not finish committing transaction %s - no CohortEntry found",
418 persistenceId(), transactionID));
419 LOG.error(ex.getMessage());
420 sender.tell(new akka.actor.Status.Failure(ex), getSelf());
423 finishCommit(sender, transactionID, cohortEntry);
427 private void handleCanCommitTransaction(final CanCommitTransaction canCommit) {
428 LOG.debug("{}: Can committing transaction {}", persistenceId(), canCommit.getTransactionID());
431 commitCoordinator.handleCanCommit(canCommit.getTransactionID(), getSender(), this);
433 ActorSelection leader = getLeader();
434 if (leader == null) {
435 messageRetrySupport.addMessageToRetry(canCommit, getSender(),
436 "Could not canCommit transaction " + canCommit.getTransactionID());
438 LOG.debug("{}: Forwarding CanCommitTransaction to leader {}", persistenceId(), leader);
439 leader.forward(canCommit, getContext());
444 protected void handleBatchedModificationsLocal(BatchedModifications batched, ActorRef sender) {
446 commitCoordinator.handleBatchedModifications(batched, sender, this);
447 } catch (Exception e) {
448 LOG.error("{}: Error handling BatchedModifications for Tx {}", persistenceId(),
449 batched.getTransactionID(), e);
450 sender.tell(new akka.actor.Status.Failure(e), getSelf());
454 private void handleBatchedModifications(BatchedModifications batched) {
455 // This message is sent to prepare the modifications transaction directly on the Shard as an
456 // optimization to avoid the extra overhead of a separate ShardTransaction actor. On the last
457 // BatchedModifications message, the caller sets the ready flag in the message indicating
458 // modifications are complete. The reply contains the cohort actor path (this actor) for the caller
459 // to initiate the 3-phase commit. This also avoids the overhead of sending an additional
460 // ReadyTransaction message.
462 // If we're not the leader then forward to the leader. This is a safety measure - we shouldn't
463 // normally get here if we're not the leader as the front-end (TransactionProxy) should determine
464 // the primary/leader shard. However with timing and caching on the front-end, there's a small
465 // window where it could have a stale leader during leadership transitions.
467 boolean isLeaderActive = isLeaderActive();
468 if (isLeader() && isLeaderActive) {
469 handleBatchedModificationsLocal(batched, getSender());
471 ActorSelection leader = getLeader();
472 if (!isLeaderActive || leader == null) {
473 messageRetrySupport.addMessageToRetry(batched, getSender(),
474 "Could not commit transaction " + batched.getTransactionID());
476 // If this is not the first batch and leadership changed in between batched messages,
477 // we need to reconstruct previous BatchedModifications from the transaction
478 // DataTreeModification, honoring the max batched modification count, and forward all the
479 // previous BatchedModifications to the new leader.
480 Collection<BatchedModifications> newModifications = commitCoordinator.createForwardedBatchedModifications(
481 batched, datastoreContext.getShardBatchedModificationCount());
483 LOG.debug("{}: Forwarding {} BatchedModifications to leader {}", persistenceId(),
484 newModifications.size(), leader);
486 for(BatchedModifications bm: newModifications) {
487 leader.forward(bm, getContext());
493 private boolean failIfIsolatedLeader(ActorRef sender) {
494 if(isIsolatedLeader()) {
495 sender.tell(new akka.actor.Status.Failure(new NoShardLeaderException(String.format(
496 "Shard %s was the leader but has lost contact with all of its followers. Either all" +
497 " other follower nodes are down or this node is isolated by a network partition.",
498 persistenceId()))), getSelf());
505 protected boolean isIsolatedLeader() {
506 return getRaftState() == RaftState.IsolatedLeader;
509 private void handleReadyLocalTransaction(final ReadyLocalTransaction message) {
510 LOG.debug("{}: handleReadyLocalTransaction for {}", persistenceId(), message.getTransactionID());
512 boolean isLeaderActive = isLeaderActive();
513 if (isLeader() && isLeaderActive) {
515 commitCoordinator.handleReadyLocalTransaction(message, getSender(), this);
516 } catch (Exception e) {
517 LOG.error("{}: Error handling ReadyLocalTransaction for Tx {}", persistenceId(),
518 message.getTransactionID(), e);
519 getSender().tell(new akka.actor.Status.Failure(e), getSelf());
522 ActorSelection leader = getLeader();
523 if (!isLeaderActive || leader == null) {
524 messageRetrySupport.addMessageToRetry(message, getSender(),
525 "Could not commit transaction " + message.getTransactionID());
527 LOG.debug("{}: Forwarding ReadyLocalTransaction to leader {}", persistenceId(), leader);
528 message.setRemoteVersion(getCurrentBehavior().getLeaderPayloadVersion());
529 leader.forward(message, getContext());
534 private void handleForwardedReadyTransaction(ForwardedReadyTransaction forwardedReady) {
535 LOG.debug("{}: handleForwardedReadyTransaction for {}", persistenceId(), forwardedReady.getTransactionID());
537 boolean isLeaderActive = isLeaderActive();
538 if (isLeader() && isLeaderActive) {
539 commitCoordinator.handleForwardedReadyTransaction(forwardedReady, getSender(), this);
541 ActorSelection leader = getLeader();
542 if (!isLeaderActive || leader == null) {
543 messageRetrySupport.addMessageToRetry(forwardedReady, getSender(),
544 "Could not commit transaction " + forwardedReady.getTransactionID());
546 LOG.debug("{}: Forwarding ForwardedReadyTransaction to leader {}", persistenceId(), leader);
548 ReadyLocalTransaction readyLocal = new ReadyLocalTransaction(forwardedReady.getTransactionID(),
549 forwardedReady.getTransaction().getSnapshot(), forwardedReady.isDoImmediateCommit());
550 readyLocal.setRemoteVersion(getCurrentBehavior().getLeaderPayloadVersion());
551 leader.forward(readyLocal, getContext());
556 private void handleAbortTransaction(final AbortTransaction abort) {
557 doAbortTransaction(abort.getTransactionID(), getSender());
560 void doAbortTransaction(final String transactionID, final ActorRef sender) {
561 commitCoordinator.handleAbort(transactionID, sender, this);
564 private void handleCreateTransaction(final Object message) {
566 createTransaction(CreateTransaction.fromSerializable(message));
567 } else if (getLeader() != null) {
568 getLeader().forward(message, getContext());
570 getSender().tell(new akka.actor.Status.Failure(new NoShardLeaderException(
571 "Could not create a shard transaction", persistenceId())), getSelf());
575 private void closeTransactionChain(final CloseTransactionChain closeTransactionChain) {
576 store.closeTransactionChain(closeTransactionChain.getTransactionChainId());
579 private ActorRef createTypedTransactionActor(int transactionType,
580 ShardTransactionIdentifier transactionId, String transactionChainId) {
582 return transactionActorFactory.newShardTransaction(TransactionType.fromInt(transactionType),
583 transactionId, transactionChainId);
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(), createTransaction.getTransactionChainId());
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, String remoteTransactionId,
604 String transactionChainId) {
607 ShardTransactionIdentifier transactionId = new ShardTransactionIdentifier(remoteTransactionId);
609 if(LOG.isDebugEnabled()) {
610 LOG.debug("{}: Creating transaction : {} ", persistenceId(), transactionId);
613 ActorRef transactionActor = createTypedTransactionActor(transactionType, transactionId,
616 return transactionActor;
619 private void commitWithNewTransaction(final Modification modification) {
620 ReadWriteShardDataTreeTransaction tx = store.newReadWriteTransaction(modification.toString(), null);
621 modification.apply(tx.getSnapshot());
623 snapshotCohort.syncCommitTransaction(tx);
624 shardMBean.incrementCommittedTransactionCount();
625 shardMBean.setLastCommittedTransactionTime(System.currentTimeMillis());
626 } catch (Exception e) {
627 shardMBean.incrementFailedTransactionsCount();
628 LOG.error("{}: Failed to commit", persistenceId(), e);
632 private void updateSchemaContext(final UpdateSchemaContext message) {
633 updateSchemaContext(message.getSchemaContext());
637 void updateSchemaContext(final SchemaContext schemaContext) {
638 store.updateSchemaContext(schemaContext);
641 private boolean isMetricsCaptureEnabled() {
642 CommonConfig config = new CommonConfig(getContext().system().settings().config());
643 return config.isMetricCaptureEnabled();
648 public RaftActorSnapshotCohort getRaftActorSnapshotCohort() {
649 return snapshotCohort;
654 protected RaftActorRecoveryCohort getRaftActorRecoveryCohort() {
655 return new ShardRecoveryCoordinator(store, store.getSchemaContext(),
656 restoreFromSnapshot != null ? restoreFromSnapshot.getSnapshot() : null, persistenceId(), LOG);
660 protected void onRecoveryComplete() {
661 restoreFromSnapshot = null;
663 //notify shard manager
664 getContext().parent().tell(new ActorInitialized(), getSelf());
666 // Being paranoid here - this method should only be called once but just in case...
667 if(txCommitTimeoutCheckSchedule == null) {
668 // Schedule a message to be periodically sent to check if the current in-progress
669 // transaction should be expired and aborted.
670 FiniteDuration period = Duration.create(transactionCommitTimeout / 3, TimeUnit.MILLISECONDS);
671 txCommitTimeoutCheckSchedule = getContext().system().scheduler().schedule(
672 period, period, getSelf(),
673 TX_COMMIT_TIMEOUT_CHECK_MESSAGE, getContext().dispatcher(), ActorRef.noSender());
678 protected void applyState(final ActorRef clientActor, final String identifier, final Object data) {
679 if (data instanceof DataTreeCandidatePayload) {
680 if (clientActor == null) {
681 // No clientActor indicates a replica coming from the leader
683 store.applyForeignCandidate(identifier, ((DataTreeCandidatePayload)data).getCandidate());
684 } catch (DataValidationFailedException | IOException e) {
685 LOG.error("{}: Error applying replica {}", persistenceId(), identifier, e);
688 // Replication consensus reached, proceed to commit
689 finishCommit(clientActor, identifier);
691 } else if (data instanceof CompositeModificationPayload) {
692 Object modification = ((CompositeModificationPayload) data).getModification();
694 applyModificationToState(clientActor, identifier, modification);
695 } else if(data instanceof CompositeModificationByteStringPayload ){
696 Object modification = ((CompositeModificationByteStringPayload) data).getModification();
698 applyModificationToState(clientActor, identifier, modification);
700 LOG.error("{}: Unknown state received {} Class loader = {} CompositeNodeMod.ClassLoader = {}",
701 persistenceId(), data, data.getClass().getClassLoader(),
702 CompositeModificationPayload.class.getClassLoader());
706 private void applyModificationToState(ActorRef clientActor, String identifier, Object modification) {
707 if(modification == null) {
709 "{}: modification is null - this is very unexpected, clientActor = {}, identifier = {}",
710 persistenceId(), identifier, clientActor != null ? clientActor.path().toString() : null);
711 } else if(clientActor == null) {
712 // There's no clientActor to which to send a commit reply so we must be applying
713 // replicated state from the leader.
714 commitWithNewTransaction(MutableCompositeModification.fromSerializable(modification));
716 // This must be the OK to commit after replication consensus.
717 finishCommit(clientActor, identifier);
722 protected void onStateChanged() {
723 boolean isLeader = isLeader();
724 boolean hasLeader = hasLeader();
725 changeSupport.onLeadershipChange(isLeader, hasLeader);
726 treeChangeSupport.onLeadershipChange(isLeader, hasLeader);
728 // If this actor is no longer the leader close all the transaction chains
730 if(LOG.isDebugEnabled()) {
732 "{}: onStateChanged: Closing all transaction chains because shard {} is no longer the leader",
733 persistenceId(), getId());
736 store.closeAllTransactionChains();
739 if(hasLeader && !isIsolatedLeader()) {
740 messageRetrySupport.retryMessages();
745 protected void onLeaderChanged(String oldLeader, String newLeader) {
746 shardMBean.incrementLeadershipChangeCount();
748 boolean hasLeader = hasLeader();
749 if(hasLeader && !isLeader()) {
750 // Another leader was elected. If we were the previous leader and had pending transactions, convert
751 // them to transaction messages and send to the new leader.
752 ActorSelection leader = getLeader();
754 Collection<Object> messagesToForward = commitCoordinator.convertPendingTransactionsToMessages(
755 datastoreContext.getShardBatchedModificationCount());
757 if(!messagesToForward.isEmpty()) {
758 LOG.debug("{}: Forwarding {} pending transaction messages to leader {}", persistenceId(),
759 messagesToForward.size(), leader);
761 for(Object message: messagesToForward) {
762 leader.tell(message, self());
766 commitCoordinator.abortPendingTransactions(
767 "The transacton was aborted due to inflight leadership change and the leader address isn't available.",
772 if(hasLeader && !isIsolatedLeader()) {
773 messageRetrySupport.retryMessages();
778 protected void pauseLeader(Runnable operation) {
779 LOG.debug("{}: In pauseLeader, operation: {}", persistenceId(), operation);
780 commitCoordinator.setRunOnPendingTransactionsComplete(operation);
784 public String persistenceId() {
789 ShardCommitCoordinator getCommitCoordinator() {
790 return commitCoordinator;
793 public DatastoreContext getDatastoreContext() {
794 return datastoreContext;
798 public ShardDataTree getDataStore() {
803 ShardStats getShardMBean() {
807 public static Builder builder() {
808 return new Builder();
811 public static abstract class AbstractBuilder<T extends AbstractBuilder<T, S>, S extends Shard> {
812 private final Class<S> shardClass;
813 private ShardIdentifier id;
814 private Map<String, String> peerAddresses = Collections.emptyMap();
815 private DatastoreContext datastoreContext;
816 private SchemaContext schemaContext;
817 private DatastoreSnapshot.ShardSnapshot restoreFromSnapshot;
818 private volatile boolean sealed;
820 protected AbstractBuilder(Class<S> shardClass) {
821 this.shardClass = shardClass;
824 protected void checkSealed() {
825 Preconditions.checkState(!sealed, "Builder isalready sealed - further modifications are not allowed");
828 @SuppressWarnings("unchecked")
833 public T id(ShardIdentifier id) {
839 public T peerAddresses(Map<String, String> peerAddresses) {
841 this.peerAddresses = peerAddresses;
845 public T datastoreContext(DatastoreContext datastoreContext) {
847 this.datastoreContext = datastoreContext;
851 public T schemaContext(SchemaContext schemaContext) {
853 this.schemaContext = schemaContext;
857 public T restoreFromSnapshot(DatastoreSnapshot.ShardSnapshot restoreFromSnapshot) {
859 this.restoreFromSnapshot = restoreFromSnapshot;
863 public ShardIdentifier getId() {
867 public Map<String, String> getPeerAddresses() {
868 return peerAddresses;
871 public DatastoreContext getDatastoreContext() {
872 return datastoreContext;
875 public SchemaContext getSchemaContext() {
876 return schemaContext;
879 public DatastoreSnapshot.ShardSnapshot getRestoreFromSnapshot() {
880 return restoreFromSnapshot;
883 public TreeType getTreeType() {
884 switch (datastoreContext.getLogicalStoreType()) {
886 return TreeType.CONFIGURATION;
888 return TreeType.OPERATIONAL;
891 throw new IllegalStateException("Unhandled logical store type " + datastoreContext.getLogicalStoreType());
894 protected void verify() {
895 Preconditions.checkNotNull(id, "id should not be null");
896 Preconditions.checkNotNull(peerAddresses, "peerAddresses should not be null");
897 Preconditions.checkNotNull(datastoreContext, "dataStoreContext should not be null");
898 Preconditions.checkNotNull(schemaContext, "schemaContext should not be null");
901 public Props props() {
904 return Props.create(shardClass, this);
908 public static class Builder extends AbstractBuilder<Builder, Shard> {