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.DataTreeCandidate;
71 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataValidationFailedException;
72 import org.opendaylight.yangtools.yang.data.api.schema.tree.ModificationType;
73 import org.opendaylight.yangtools.yang.data.api.schema.tree.TreeType;
74 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
75 import scala.concurrent.duration.Duration;
76 import scala.concurrent.duration.FiniteDuration;
79 * A Shard represents a portion of the logical data tree <br/>
81 * Our Shard uses InMemoryDataTree as it's internal representation and delegates all requests it
84 public class Shard extends RaftActor {
86 static final Object TX_COMMIT_TIMEOUT_CHECK_MESSAGE = new Object() {
88 public String toString() {
89 return "txCommitTimeoutCheck";
94 static final Object GET_SHARD_MBEAN_MESSAGE = new Object() {
96 public String toString() {
97 return "getShardMBeanMessage";
101 // FIXME: shard names should be encapsulated in their own class and this should be exposed as a constant.
102 public static final String DEFAULT_NAME = "default";
104 // The state of this Shard
105 private final ShardDataTree store;
107 /// The name of this shard
108 private final String name;
110 private final ShardStats shardMBean;
112 private DatastoreContext datastoreContext;
114 private final ShardCommitCoordinator commitCoordinator;
116 private long transactionCommitTimeout;
118 private Cancellable txCommitTimeoutCheckSchedule;
120 private final Optional<ActorRef> roleChangeNotifier;
122 private final MessageTracker appendEntriesReplyTracker;
124 private final ShardTransactionActorFactory transactionActorFactory;
126 private final ShardSnapshotCohort snapshotCohort;
128 private final DataTreeChangeListenerSupport treeChangeSupport = new DataTreeChangeListenerSupport(this);
129 private final DataChangeListenerSupport changeSupport = new DataChangeListenerSupport(this);
132 private ShardSnapshot restoreFromSnapshot;
134 private final ShardTransactionMessageRetrySupport messageRetrySupport;
136 protected Shard(AbstractBuilder<?, ?> builder) {
137 super(builder.getId().toString(), builder.getPeerAddresses(),
138 Optional.of(builder.getDatastoreContext().getShardRaftConfig()), DataStoreVersions.CURRENT_VERSION);
140 this.name = builder.getId().toString();
141 this.datastoreContext = builder.getDatastoreContext();
142 this.restoreFromSnapshot = builder.getRestoreFromSnapshot();
144 setPersistence(datastoreContext.isPersistent());
146 LOG.info("Shard created : {}, persistent : {}", name, datastoreContext.isPersistent());
148 store = new ShardDataTree(builder.getSchemaContext(), builder.getTreeType(),
149 new ShardDataTreeChangeListenerPublisherActorProxy(getContext(), name + "-DTCL-publisher"),
150 new ShardDataChangeListenerPublisherActorProxy(getContext(), name + "-DCL-publisher"), name);
152 shardMBean = ShardMBeanFactory.getShardStatsMBean(name.toString(),
153 datastoreContext.getDataStoreMXBeanType());
154 shardMBean.setShard(this);
156 if (isMetricsCaptureEnabled()) {
157 getContext().become(new MeteringBehavior(this));
160 commitCoordinator = new ShardCommitCoordinator(store,
161 datastoreContext.getShardCommitQueueExpiryTimeoutInMillis(),
162 datastoreContext.getShardTransactionCommitQueueCapacity(), LOG, this.name);
164 setTransactionCommitTimeout();
166 // create a notifier actor for each cluster member
167 roleChangeNotifier = createRoleChangeNotifier(name.toString());
169 appendEntriesReplyTracker = new MessageTracker(AppendEntriesReply.class,
170 getRaftActorContext().getConfigParams().getIsolatedCheckIntervalInMillis());
172 transactionActorFactory = new ShardTransactionActorFactory(store, datastoreContext,
173 new Dispatchers(context().system().dispatchers()).getDispatcherPath(
174 Dispatchers.DispatcherType.Transaction), self(), getContext(), shardMBean);
176 snapshotCohort = new ShardSnapshotCohort(transactionActorFactory, store, LOG, this.name);
178 messageRetrySupport = new ShardTransactionMessageRetrySupport(this);
181 private void setTransactionCommitTimeout() {
182 transactionCommitTimeout = TimeUnit.MILLISECONDS.convert(
183 datastoreContext.getShardTransactionCommitTimeoutInSeconds(), TimeUnit.SECONDS) / 2;
186 private Optional<ActorRef> createRoleChangeNotifier(String shardId) {
187 ActorRef shardRoleChangeNotifier = this.getContext().actorOf(
188 RoleChangeNotifier.getProps(shardId), shardId + "-notifier");
189 return Optional.of(shardRoleChangeNotifier);
193 public void postStop() {
194 LOG.info("Stopping Shard {}", persistenceId());
198 messageRetrySupport.close();
200 if(txCommitTimeoutCheckSchedule != null) {
201 txCommitTimeoutCheckSchedule.cancel();
204 commitCoordinator.abortPendingTransactions("Transaction aborted due to shutdown.", this);
206 shardMBean.unregisterMBean();
210 protected void handleRecover(final Object message) {
211 LOG.debug("{}: onReceiveRecover: Received message {} from {}", persistenceId(), message.getClass(),
214 super.handleRecover(message);
215 if (LOG.isTraceEnabled()) {
216 appendEntriesReplyTracker.begin();
221 protected void handleCommand(final Object message) {
222 try (final MessageTracker.Context context = appendEntriesReplyTracker.received(message)) {
223 final Optional<Error> maybeError = context.error();
224 if (maybeError.isPresent()) {
225 LOG.trace("{} : AppendEntriesReply failed to arrive at the expected interval {}", persistenceId(),
229 if (CreateTransaction.isSerializedType(message)) {
230 handleCreateTransaction(message);
231 } else if (message instanceof BatchedModifications) {
232 handleBatchedModifications((BatchedModifications)message);
233 } else if (message instanceof ForwardedReadyTransaction) {
234 handleForwardedReadyTransaction((ForwardedReadyTransaction) message);
235 } else if (message instanceof ReadyLocalTransaction) {
236 handleReadyLocalTransaction((ReadyLocalTransaction)message);
237 } else if (CanCommitTransaction.isSerializedType(message)) {
238 handleCanCommitTransaction(CanCommitTransaction.fromSerializable(message));
239 } else if (CommitTransaction.isSerializedType(message)) {
240 handleCommitTransaction(CommitTransaction.fromSerializable(message));
241 } else if (AbortTransaction.isSerializedType(message)) {
242 handleAbortTransaction(AbortTransaction.fromSerializable(message));
243 } else if (CloseTransactionChain.isSerializedType(message)) {
244 closeTransactionChain(CloseTransactionChain.fromSerializable(message));
245 } else if (message instanceof RegisterChangeListener) {
246 changeSupport.onMessage((RegisterChangeListener) message, isLeader(), hasLeader());
247 } else if (message instanceof RegisterDataTreeChangeListener) {
248 treeChangeSupport.onMessage((RegisterDataTreeChangeListener) message, isLeader(), hasLeader());
249 } else if (message instanceof UpdateSchemaContext) {
250 updateSchemaContext((UpdateSchemaContext) message);
251 } else if (message instanceof PeerAddressResolved) {
252 PeerAddressResolved resolved = (PeerAddressResolved) message;
253 setPeerAddress(resolved.getPeerId().toString(),
254 resolved.getPeerAddress());
255 } else if (TX_COMMIT_TIMEOUT_CHECK_MESSAGE.equals(message)) {
256 commitCoordinator.checkForExpiredTransactions(transactionCommitTimeout, this);
257 } else if(message instanceof DatastoreContext) {
258 onDatastoreContext((DatastoreContext)message);
259 } else if(message instanceof RegisterRoleChangeListener){
260 roleChangeNotifier.get().forward(message, context());
261 } else if (message instanceof FollowerInitialSyncUpStatus) {
262 shardMBean.setFollowerInitialSyncStatus(((FollowerInitialSyncUpStatus) message).isInitialSyncDone());
263 context().parent().tell(message, self());
264 } else if(GET_SHARD_MBEAN_MESSAGE.equals(message)){
265 sender().tell(getShardMBean(), self());
266 } else if(message instanceof GetShardDataTree) {
267 sender().tell(store.getDataTree(), self());
268 } else if(message instanceof ServerRemoved){
269 context().parent().forward(message, context());
270 } else if(ShardTransactionMessageRetrySupport.TIMER_MESSAGE_CLASS.isInstance(message)) {
271 messageRetrySupport.onTimerMessage(message);
273 super.handleCommand(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 Shard.this.persistData(cohortEntry.getReplySender(), cohortEntry.getTransactionID(),
331 DataTreeCandidatePayload.create(candidate));
335 private void handleCommitTransaction(final CommitTransaction commit) {
337 if(!commitCoordinator.handleCommit(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 String transactionID, @Nonnull final CohortEntry cohortEntry) {
353 LOG.debug("{}: Finishing commit for transaction {}", persistenceId(), cohortEntry.getTransactionID());
357 cohortEntry.commit();
358 } catch(ExecutionException e) {
359 // We may get a "store tree and candidate base differ" IllegalStateException from commit under
360 // certain edge case scenarios so we'll try to re-apply the candidate from scratch as a last
361 // resort. Eg, we're a follower and a tx payload is replicated but the leader goes down before
362 // applying it to the state. We then become the leader and a second tx is pre-committed and
363 // replicated. When consensus occurs, this will cause the first tx to be applied as a foreign
364 // candidate via applyState prior to the second tx. Since the second tx has already been
365 // pre-committed, when it gets here to commit it will get an IllegalStateException.
367 // FIXME - this is not an ideal way to handle this scenario. This is temporary - a cleaner
368 // solution will be forthcoming.
369 if(e.getCause() instanceof IllegalStateException) {
370 LOG.debug("{}: commit failed for transaction {} - retrying as foreign candidate", persistenceId(),
372 store.applyForeignCandidate(transactionID, cohortEntry.getCandidate());
378 sender.tell(CommitTransactionReply.instance(cohortEntry.getClientVersion()).toSerializable(), getSelf());
380 shardMBean.incrementCommittedTransactionCount();
381 shardMBean.setLastCommittedTransactionTime(System.currentTimeMillis());
383 } catch (Exception e) {
384 sender.tell(new akka.actor.Status.Failure(e), getSelf());
386 LOG.error("{}, An exception occurred while committing transaction {}", persistenceId(),
388 shardMBean.incrementFailedTransactionsCount();
390 commitCoordinator.currentTransactionComplete(transactionID, true);
394 private void finishCommit(@Nonnull final ActorRef sender, final @Nonnull String transactionID) {
395 // With persistence enabled, this method is called via applyState by the leader strategy
396 // after the commit has been replicated to a majority of the followers.
398 CohortEntry cohortEntry = commitCoordinator.getCohortEntryIfCurrent(transactionID);
399 if (cohortEntry == null) {
400 // The transaction is no longer the current commit. This can happen if the transaction
401 // was aborted prior, most likely due to timeout in the front-end. We need to finish
402 // committing the transaction though since it was successfully persisted and replicated
403 // however we can't use the original cohort b/c it was already preCommitted and may
404 // conflict with the current commit or may have been aborted so we commit with a new
406 cohortEntry = commitCoordinator.getAndRemoveCohortEntry(transactionID);
407 if(cohortEntry != null) {
409 store.applyForeignCandidate(transactionID, cohortEntry.getCandidate());
410 } catch (DataValidationFailedException e) {
411 shardMBean.incrementFailedTransactionsCount();
412 LOG.error("{}: Failed to re-apply transaction {}", persistenceId(), transactionID, e);
415 sender.tell(CommitTransactionReply.instance(cohortEntry.getClientVersion()).toSerializable(),
418 // This really shouldn't happen - it likely means that persistence or replication
419 // took so long to complete such that the cohort entry was expired from the cache.
420 IllegalStateException ex = new IllegalStateException(
421 String.format("%s: Could not finish committing transaction %s - no CohortEntry found",
422 persistenceId(), transactionID));
423 LOG.error(ex.getMessage());
424 sender.tell(new akka.actor.Status.Failure(ex), getSelf());
427 finishCommit(sender, transactionID, cohortEntry);
431 private void handleCanCommitTransaction(final CanCommitTransaction canCommit) {
432 LOG.debug("{}: Can committing transaction {}", persistenceId(), canCommit.getTransactionID());
435 commitCoordinator.handleCanCommit(canCommit.getTransactionID(), getSender(), this);
437 ActorSelection leader = getLeader();
438 if (leader == null) {
439 messageRetrySupport.addMessageToRetry(canCommit, getSender(),
440 "Could not canCommit transaction " + canCommit.getTransactionID());
442 LOG.debug("{}: Forwarding CanCommitTransaction to leader {}", persistenceId(), leader);
443 leader.forward(canCommit, getContext());
448 protected void handleBatchedModificationsLocal(BatchedModifications batched, ActorRef sender) {
450 commitCoordinator.handleBatchedModifications(batched, sender, this);
451 } catch (Exception e) {
452 LOG.error("{}: Error handling BatchedModifications for Tx {}", persistenceId(),
453 batched.getTransactionID(), e);
454 sender.tell(new akka.actor.Status.Failure(e), getSelf());
458 private void handleBatchedModifications(BatchedModifications batched) {
459 // This message is sent to prepare the modifications transaction directly on the Shard as an
460 // optimization to avoid the extra overhead of a separate ShardTransaction actor. On the last
461 // BatchedModifications message, the caller sets the ready flag in the message indicating
462 // modifications are complete. The reply contains the cohort actor path (this actor) for the caller
463 // to initiate the 3-phase commit. This also avoids the overhead of sending an additional
464 // ReadyTransaction message.
466 // If we're not the leader then forward to the leader. This is a safety measure - we shouldn't
467 // normally get here if we're not the leader as the front-end (TransactionProxy) should determine
468 // the primary/leader shard. However with timing and caching on the front-end, there's a small
469 // window where it could have a stale leader during leadership transitions.
471 boolean isLeaderActive = isLeaderActive();
472 if (isLeader() && isLeaderActive) {
473 handleBatchedModificationsLocal(batched, getSender());
475 ActorSelection leader = getLeader();
476 if (!isLeaderActive || leader == null) {
477 messageRetrySupport.addMessageToRetry(batched, getSender(),
478 "Could not commit transaction " + batched.getTransactionID());
480 // If this is not the first batch and leadership changed in between batched messages,
481 // we need to reconstruct previous BatchedModifications from the transaction
482 // DataTreeModification, honoring the max batched modification count, and forward all the
483 // previous BatchedModifications to the new leader.
484 Collection<BatchedModifications> newModifications = commitCoordinator.createForwardedBatchedModifications(
485 batched, datastoreContext.getShardBatchedModificationCount());
487 LOG.debug("{}: Forwarding {} BatchedModifications to leader {}", persistenceId(),
488 newModifications.size(), leader);
490 for(BatchedModifications bm: newModifications) {
491 leader.forward(bm, getContext());
497 private boolean failIfIsolatedLeader(ActorRef sender) {
498 if(isIsolatedLeader()) {
499 sender.tell(new akka.actor.Status.Failure(new NoShardLeaderException(String.format(
500 "Shard %s was the leader but has lost contact with all of its followers. Either all" +
501 " other follower nodes are down or this node is isolated by a network partition.",
502 persistenceId()))), getSelf());
509 protected boolean isIsolatedLeader() {
510 return getRaftState() == RaftState.IsolatedLeader;
513 private void handleReadyLocalTransaction(final ReadyLocalTransaction message) {
514 LOG.debug("{}: handleReadyLocalTransaction for {}", persistenceId(), message.getTransactionID());
516 boolean isLeaderActive = isLeaderActive();
517 if (isLeader() && isLeaderActive) {
519 commitCoordinator.handleReadyLocalTransaction(message, getSender(), this);
520 } catch (Exception e) {
521 LOG.error("{}: Error handling ReadyLocalTransaction for Tx {}", persistenceId(),
522 message.getTransactionID(), e);
523 getSender().tell(new akka.actor.Status.Failure(e), getSelf());
526 ActorSelection leader = getLeader();
527 if (!isLeaderActive || leader == null) {
528 messageRetrySupport.addMessageToRetry(message, getSender(),
529 "Could not commit transaction " + message.getTransactionID());
531 LOG.debug("{}: Forwarding ReadyLocalTransaction to leader {}", persistenceId(), leader);
532 message.setRemoteVersion(getCurrentBehavior().getLeaderPayloadVersion());
533 leader.forward(message, getContext());
538 private void handleForwardedReadyTransaction(ForwardedReadyTransaction forwardedReady) {
539 LOG.debug("{}: handleForwardedReadyTransaction for {}", persistenceId(), forwardedReady.getTransactionID());
541 boolean isLeaderActive = isLeaderActive();
542 if (isLeader() && isLeaderActive) {
543 commitCoordinator.handleForwardedReadyTransaction(forwardedReady, getSender(), this);
545 ActorSelection leader = getLeader();
546 if (!isLeaderActive || leader == null) {
547 messageRetrySupport.addMessageToRetry(forwardedReady, getSender(),
548 "Could not commit transaction " + forwardedReady.getTransactionID());
550 LOG.debug("{}: Forwarding ForwardedReadyTransaction to leader {}", persistenceId(), leader);
552 ReadyLocalTransaction readyLocal = new ReadyLocalTransaction(forwardedReady.getTransactionID(),
553 forwardedReady.getTransaction().getSnapshot(), forwardedReady.isDoImmediateCommit());
554 readyLocal.setRemoteVersion(getCurrentBehavior().getLeaderPayloadVersion());
555 leader.forward(readyLocal, getContext());
560 private void handleAbortTransaction(final AbortTransaction abort) {
561 doAbortTransaction(abort.getTransactionID(), getSender());
564 void doAbortTransaction(final String transactionID, final ActorRef sender) {
565 commitCoordinator.handleAbort(transactionID, sender, this);
568 private void handleCreateTransaction(final Object message) {
570 createTransaction(CreateTransaction.fromSerializable(message));
571 } else if (getLeader() != null) {
572 getLeader().forward(message, getContext());
574 getSender().tell(new akka.actor.Status.Failure(new NoShardLeaderException(
575 "Could not create a shard transaction", persistenceId())), getSelf());
579 private void closeTransactionChain(final CloseTransactionChain closeTransactionChain) {
580 store.closeTransactionChain(closeTransactionChain.getTransactionChainId());
583 private ActorRef createTypedTransactionActor(int transactionType,
584 ShardTransactionIdentifier transactionId, String transactionChainId) {
586 return transactionActorFactory.newShardTransaction(TransactionType.fromInt(transactionType),
587 transactionId, transactionChainId);
590 private void createTransaction(CreateTransaction createTransaction) {
592 if(TransactionType.fromInt(createTransaction.getTransactionType()) != TransactionType.READ_ONLY &&
593 failIfIsolatedLeader(getSender())) {
597 ActorRef transactionActor = createTransaction(createTransaction.getTransactionType(),
598 createTransaction.getTransactionId(), createTransaction.getTransactionChainId());
600 getSender().tell(new CreateTransactionReply(Serialization.serializedActorPath(transactionActor),
601 createTransaction.getTransactionId(), createTransaction.getVersion()).toSerializable(), getSelf());
602 } catch (Exception e) {
603 getSender().tell(new akka.actor.Status.Failure(e), getSelf());
607 private ActorRef createTransaction(int transactionType, String remoteTransactionId,
608 String transactionChainId) {
611 ShardTransactionIdentifier transactionId = new ShardTransactionIdentifier(remoteTransactionId);
613 if(LOG.isDebugEnabled()) {
614 LOG.debug("{}: Creating transaction : {} ", persistenceId(), transactionId);
617 ActorRef transactionActor = createTypedTransactionActor(transactionType, transactionId,
620 return transactionActor;
623 private void commitWithNewTransaction(final Modification modification) {
624 ReadWriteShardDataTreeTransaction tx = store.newReadWriteTransaction(modification.toString(), null);
625 modification.apply(tx.getSnapshot());
627 snapshotCohort.syncCommitTransaction(tx);
628 shardMBean.incrementCommittedTransactionCount();
629 shardMBean.setLastCommittedTransactionTime(System.currentTimeMillis());
630 } catch (Exception e) {
631 shardMBean.incrementFailedTransactionsCount();
632 LOG.error("{}: Failed to commit", persistenceId(), e);
636 private void updateSchemaContext(final UpdateSchemaContext message) {
637 updateSchemaContext(message.getSchemaContext());
641 void updateSchemaContext(final SchemaContext schemaContext) {
642 store.updateSchemaContext(schemaContext);
645 private boolean isMetricsCaptureEnabled() {
646 CommonConfig config = new CommonConfig(getContext().system().settings().config());
647 return config.isMetricCaptureEnabled();
652 public RaftActorSnapshotCohort getRaftActorSnapshotCohort() {
653 return snapshotCohort;
658 protected RaftActorRecoveryCohort getRaftActorRecoveryCohort() {
659 return new ShardRecoveryCoordinator(store, store.getSchemaContext(),
660 restoreFromSnapshot != null ? restoreFromSnapshot.getSnapshot() : null, persistenceId(), LOG);
664 protected void onRecoveryComplete() {
665 restoreFromSnapshot = null;
667 //notify shard manager
668 getContext().parent().tell(new ActorInitialized(), getSelf());
670 // Being paranoid here - this method should only be called once but just in case...
671 if(txCommitTimeoutCheckSchedule == null) {
672 // Schedule a message to be periodically sent to check if the current in-progress
673 // transaction should be expired and aborted.
674 FiniteDuration period = Duration.create(transactionCommitTimeout / 3, TimeUnit.MILLISECONDS);
675 txCommitTimeoutCheckSchedule = getContext().system().scheduler().schedule(
676 period, period, getSelf(),
677 TX_COMMIT_TIMEOUT_CHECK_MESSAGE, getContext().dispatcher(), ActorRef.noSender());
682 protected void applyState(final ActorRef clientActor, final String identifier, final Object data) {
683 if (data instanceof DataTreeCandidatePayload) {
684 if (clientActor == null) {
685 // No clientActor indicates a replica coming from the leader
687 store.applyForeignCandidate(identifier, ((DataTreeCandidatePayload)data).getCandidate());
688 } catch (DataValidationFailedException | IOException e) {
689 LOG.error("{}: Error applying replica {}", persistenceId(), identifier, e);
692 // Replication consensus reached, proceed to commit
693 finishCommit(clientActor, identifier);
695 } else if (data instanceof CompositeModificationPayload) {
696 Object modification = ((CompositeModificationPayload) data).getModification();
698 applyModificationToState(clientActor, identifier, modification);
699 } else if(data instanceof CompositeModificationByteStringPayload ){
700 Object modification = ((CompositeModificationByteStringPayload) data).getModification();
702 applyModificationToState(clientActor, identifier, modification);
704 LOG.error("{}: Unknown state received {} Class loader = {} CompositeNodeMod.ClassLoader = {}",
705 persistenceId(), data, data.getClass().getClassLoader(),
706 CompositeModificationPayload.class.getClassLoader());
710 private void applyModificationToState(ActorRef clientActor, String identifier, Object modification) {
711 if(modification == null) {
713 "{}: modification is null - this is very unexpected, clientActor = {}, identifier = {}",
714 persistenceId(), identifier, clientActor != null ? clientActor.path().toString() : null);
715 } else if(clientActor == null) {
716 // There's no clientActor to which to send a commit reply so we must be applying
717 // replicated state from the leader.
718 commitWithNewTransaction(MutableCompositeModification.fromSerializable(modification));
720 // This must be the OK to commit after replication consensus.
721 finishCommit(clientActor, identifier);
726 protected void onStateChanged() {
727 boolean isLeader = isLeader();
728 boolean hasLeader = hasLeader();
729 changeSupport.onLeadershipChange(isLeader, hasLeader);
730 treeChangeSupport.onLeadershipChange(isLeader, hasLeader);
732 // If this actor is no longer the leader close all the transaction chains
734 if(LOG.isDebugEnabled()) {
736 "{}: onStateChanged: Closing all transaction chains because shard {} is no longer the leader",
737 persistenceId(), getId());
740 store.closeAllTransactionChains();
743 if(hasLeader && !isIsolatedLeader()) {
744 messageRetrySupport.retryMessages();
749 protected void onLeaderChanged(String oldLeader, String newLeader) {
750 shardMBean.incrementLeadershipChangeCount();
752 boolean hasLeader = hasLeader();
753 if(hasLeader && !isLeader()) {
754 // Another leader was elected. If we were the previous leader and had pending transactions, convert
755 // them to transaction messages and send to the new leader.
756 ActorSelection leader = getLeader();
758 Collection<Object> messagesToForward = commitCoordinator.convertPendingTransactionsToMessages(
759 datastoreContext.getShardBatchedModificationCount());
761 if(!messagesToForward.isEmpty()) {
762 LOG.debug("{}: Forwarding {} pending transaction messages to leader {}", persistenceId(),
763 messagesToForward.size(), leader);
765 for(Object message: messagesToForward) {
766 leader.tell(message, self());
770 commitCoordinator.abortPendingTransactions(
771 "The transacton was aborted due to inflight leadership change and the leader address isn't available.",
776 if(hasLeader && !isIsolatedLeader()) {
777 messageRetrySupport.retryMessages();
782 protected void pauseLeader(Runnable operation) {
783 LOG.debug("{}: In pauseLeader, operation: {}", persistenceId(), operation);
784 commitCoordinator.setRunOnPendingTransactionsComplete(operation);
788 public String persistenceId() {
793 ShardCommitCoordinator getCommitCoordinator() {
794 return commitCoordinator;
797 public DatastoreContext getDatastoreContext() {
798 return datastoreContext;
802 public ShardDataTree getDataStore() {
807 ShardStats getShardMBean() {
811 public static Builder builder() {
812 return new Builder();
815 public static abstract class AbstractBuilder<T extends AbstractBuilder<T, S>, S extends Shard> {
816 private final Class<S> shardClass;
817 private ShardIdentifier id;
818 private Map<String, String> peerAddresses = Collections.emptyMap();
819 private DatastoreContext datastoreContext;
820 private SchemaContext schemaContext;
821 private DatastoreSnapshot.ShardSnapshot restoreFromSnapshot;
822 private volatile boolean sealed;
824 protected AbstractBuilder(Class<S> shardClass) {
825 this.shardClass = shardClass;
828 protected void checkSealed() {
829 Preconditions.checkState(!sealed, "Builder isalready sealed - further modifications are not allowed");
832 @SuppressWarnings("unchecked")
837 public T id(ShardIdentifier id) {
843 public T peerAddresses(Map<String, String> peerAddresses) {
845 this.peerAddresses = peerAddresses;
849 public T datastoreContext(DatastoreContext datastoreContext) {
851 this.datastoreContext = datastoreContext;
855 public T schemaContext(SchemaContext schemaContext) {
857 this.schemaContext = schemaContext;
861 public T restoreFromSnapshot(DatastoreSnapshot.ShardSnapshot restoreFromSnapshot) {
863 this.restoreFromSnapshot = restoreFromSnapshot;
867 public ShardIdentifier getId() {
871 public Map<String, String> getPeerAddresses() {
872 return peerAddresses;
875 public DatastoreContext getDatastoreContext() {
876 return datastoreContext;
879 public SchemaContext getSchemaContext() {
880 return schemaContext;
883 public DatastoreSnapshot.ShardSnapshot getRestoreFromSnapshot() {
884 return restoreFromSnapshot;
887 public TreeType getTreeType() {
888 switch (datastoreContext.getLogicalStoreType()) {
890 return TreeType.CONFIGURATION;
892 return TreeType.OPERATIONAL;
895 throw new IllegalStateException("Unhandled logical store type " + datastoreContext.getLogicalStoreType());
898 protected void verify() {
899 Preconditions.checkNotNull(id, "id should not be null");
900 Preconditions.checkNotNull(peerAddresses, "peerAddresses should not be null");
901 Preconditions.checkNotNull(datastoreContext, "dataStoreContext should not be null");
902 Preconditions.checkNotNull(schemaContext, "schemaContext should not be null");
905 public Props props() {
908 return Props.create(shardClass, this);
912 public static class Builder extends AbstractBuilder<Builder, Shard> {