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 protected static final Object TX_COMMIT_TIMEOUT_CHECK_MESSAGE = "txCommitTimeoutCheck";
89 static final Object GET_SHARD_MBEAN_MESSAGE = "getShardMBeanMessage";
91 // FIXME: shard names should be encapsulated in their own class and this should be exposed as a constant.
92 public static final String DEFAULT_NAME = "default";
94 // The state of this Shard
95 private final ShardDataTree store;
97 /// The name of this shard
98 private final String name;
100 private final ShardStats shardMBean;
102 private DatastoreContext datastoreContext;
104 private final ShardCommitCoordinator commitCoordinator;
106 private long transactionCommitTimeout;
108 private Cancellable txCommitTimeoutCheckSchedule;
110 private final Optional<ActorRef> roleChangeNotifier;
112 private final MessageTracker appendEntriesReplyTracker;
114 private final ShardTransactionActorFactory transactionActorFactory;
116 private final ShardSnapshotCohort snapshotCohort;
118 private final DataTreeChangeListenerSupport treeChangeSupport = new DataTreeChangeListenerSupport(this);
119 private final DataChangeListenerSupport changeSupport = new DataChangeListenerSupport(this);
122 private ShardSnapshot restoreFromSnapshot;
124 private final ShardTransactionMessageRetrySupport messageRetrySupport;
126 protected Shard(AbstractBuilder<?, ?> builder) {
127 super(builder.getId().toString(), builder.getPeerAddresses(),
128 Optional.of(builder.getDatastoreContext().getShardRaftConfig()), DataStoreVersions.CURRENT_VERSION);
130 this.name = builder.getId().toString();
131 this.datastoreContext = builder.getDatastoreContext();
132 this.restoreFromSnapshot = builder.getRestoreFromSnapshot();
134 setPersistence(datastoreContext.isPersistent());
136 LOG.info("Shard created : {}, persistent : {}", name, datastoreContext.isPersistent());
138 store = new ShardDataTree(builder.getSchemaContext(), builder.getTreeType(),
139 new ShardDataTreeChangeListenerPublisherActorProxy(getContext(), name + "-DTCL-publisher"),
140 new ShardDataChangeListenerPublisherActorProxy(getContext(), name + "-DCL-publisher"), name);
142 shardMBean = ShardMBeanFactory.getShardStatsMBean(name.toString(),
143 datastoreContext.getDataStoreMXBeanType());
144 shardMBean.setShard(this);
146 if (isMetricsCaptureEnabled()) {
147 getContext().become(new MeteringBehavior(this));
150 commitCoordinator = new ShardCommitCoordinator(store,
151 datastoreContext.getShardCommitQueueExpiryTimeoutInMillis(),
152 datastoreContext.getShardTransactionCommitQueueCapacity(), LOG, this.name);
154 setTransactionCommitTimeout();
156 // create a notifier actor for each cluster member
157 roleChangeNotifier = createRoleChangeNotifier(name.toString());
159 appendEntriesReplyTracker = new MessageTracker(AppendEntriesReply.class,
160 getRaftActorContext().getConfigParams().getIsolatedCheckIntervalInMillis());
162 transactionActorFactory = new ShardTransactionActorFactory(store, datastoreContext,
163 new Dispatchers(context().system().dispatchers()).getDispatcherPath(
164 Dispatchers.DispatcherType.Transaction), self(), getContext(), shardMBean);
166 snapshotCohort = new ShardSnapshotCohort(transactionActorFactory, store, LOG, this.name);
168 messageRetrySupport = new ShardTransactionMessageRetrySupport(this);
171 private void setTransactionCommitTimeout() {
172 transactionCommitTimeout = TimeUnit.MILLISECONDS.convert(
173 datastoreContext.getShardTransactionCommitTimeoutInSeconds(), TimeUnit.SECONDS) / 2;
176 private Optional<ActorRef> createRoleChangeNotifier(String shardId) {
177 ActorRef shardRoleChangeNotifier = this.getContext().actorOf(
178 RoleChangeNotifier.getProps(shardId), shardId + "-notifier");
179 return Optional.of(shardRoleChangeNotifier);
183 public void postStop() {
184 LOG.info("Stopping Shard {}", persistenceId());
188 messageRetrySupport.close();
190 if(txCommitTimeoutCheckSchedule != null) {
191 txCommitTimeoutCheckSchedule.cancel();
194 commitCoordinator.abortPendingTransactions("Transaction aborted due to shutdown.", this);
196 shardMBean.unregisterMBean();
200 protected void handleRecover(final Object message) {
201 LOG.debug("{}: onReceiveRecover: Received message {} from {}", persistenceId(), message.getClass(),
204 super.handleRecover(message);
205 if (LOG.isTraceEnabled()) {
206 appendEntriesReplyTracker.begin();
211 protected void handleCommand(final Object message) {
213 final MessageTracker.Context context = appendEntriesReplyTracker.received(message);
214 final Optional<Error> maybeError = context.error();
215 if (maybeError.isPresent()) {
216 LOG.trace("{} : AppendEntriesReply failed to arrive at the expected interval {}", persistenceId(),
221 if (CreateTransaction.isSerializedType(message)) {
222 handleCreateTransaction(message);
223 } else if (message instanceof BatchedModifications) {
224 handleBatchedModifications((BatchedModifications)message);
225 } else if (message instanceof ForwardedReadyTransaction) {
226 handleForwardedReadyTransaction((ForwardedReadyTransaction) message);
227 } else if (message instanceof ReadyLocalTransaction) {
228 handleReadyLocalTransaction((ReadyLocalTransaction)message);
229 } else if (CanCommitTransaction.isSerializedType(message)) {
230 handleCanCommitTransaction(CanCommitTransaction.fromSerializable(message));
231 } else if (CommitTransaction.isSerializedType(message)) {
232 handleCommitTransaction(CommitTransaction.fromSerializable(message));
233 } else if (AbortTransaction.isSerializedType(message)) {
234 handleAbortTransaction(AbortTransaction.fromSerializable(message));
235 } else if (CloseTransactionChain.isSerializedType(message)) {
236 closeTransactionChain(CloseTransactionChain.fromSerializable(message));
237 } else if (message instanceof RegisterChangeListener) {
238 changeSupport.onMessage((RegisterChangeListener) message, isLeader(), hasLeader());
239 } else if (message instanceof RegisterDataTreeChangeListener) {
240 treeChangeSupport.onMessage((RegisterDataTreeChangeListener) message, isLeader(), hasLeader());
241 } else if (message instanceof UpdateSchemaContext) {
242 updateSchemaContext((UpdateSchemaContext) message);
243 } else if (message instanceof PeerAddressResolved) {
244 PeerAddressResolved resolved = (PeerAddressResolved) message;
245 setPeerAddress(resolved.getPeerId().toString(),
246 resolved.getPeerAddress());
247 } else if (TX_COMMIT_TIMEOUT_CHECK_MESSAGE.equals(message)) {
248 commitCoordinator.checkForExpiredTransactions(transactionCommitTimeout, this);
249 } else if(message instanceof DatastoreContext) {
250 onDatastoreContext((DatastoreContext)message);
251 } else if(message instanceof RegisterRoleChangeListener){
252 roleChangeNotifier.get().forward(message, context());
253 } else if (message instanceof FollowerInitialSyncUpStatus) {
254 shardMBean.setFollowerInitialSyncStatus(((FollowerInitialSyncUpStatus) message).isInitialSyncDone());
255 context().parent().tell(message, self());
256 } else if(GET_SHARD_MBEAN_MESSAGE.equals(message)){
257 sender().tell(getShardMBean(), self());
258 } else if(message instanceof GetShardDataTree) {
259 sender().tell(store.getDataTree(), self());
260 } else if(message instanceof ServerRemoved){
261 context().parent().forward(message, context());
262 } else if(ShardTransactionMessageRetrySupport.TIMER_MESSAGE_CLASS.isInstance(message)) {
263 messageRetrySupport.onTimerMessage(message);
265 super.handleCommand(message);
272 private boolean hasLeader() {
273 return getLeaderId() != null;
276 public int getPendingTxCommitQueueSize() {
277 return commitCoordinator.getQueueSize();
280 public int getCohortCacheSize() {
281 return commitCoordinator.getCohortCacheSize();
285 protected Optional<ActorRef> getRoleChangeNotifier() {
286 return roleChangeNotifier;
290 protected LeaderStateChanged newLeaderStateChanged(String memberId, String leaderId, short leaderPayloadVersion) {
291 return isLeader() ? new ShardLeaderStateChanged(memberId, leaderId, store.getDataTree(), leaderPayloadVersion)
292 : new ShardLeaderStateChanged(memberId, leaderId, leaderPayloadVersion);
295 protected void onDatastoreContext(DatastoreContext context) {
296 datastoreContext = context;
298 commitCoordinator.setQueueCapacity(datastoreContext.getShardTransactionCommitQueueCapacity());
300 setTransactionCommitTimeout();
302 if(datastoreContext.isPersistent() && !persistence().isRecoveryApplicable()) {
303 setPersistence(true);
304 } else if(!datastoreContext.isPersistent() && persistence().isRecoveryApplicable()) {
305 setPersistence(false);
308 updateConfigParams(datastoreContext.getShardRaftConfig());
311 private static boolean isEmptyCommit(final DataTreeCandidate candidate) {
312 return ModificationType.UNMODIFIED.equals(candidate.getRootNode().getModificationType());
315 void continueCommit(final CohortEntry cohortEntry) {
316 final DataTreeCandidate candidate = cohortEntry.getCandidate();
318 // If we do not have any followers and we are not using persistence
319 // or if cohortEntry has no modifications
320 // we can apply modification to the state immediately
321 if ((!hasFollowers() && !persistence().isRecoveryApplicable()) || isEmptyCommit(candidate)) {
322 applyModificationToState(cohortEntry.getReplySender(), cohortEntry.getTransactionID(), candidate);
324 Shard.this.persistData(cohortEntry.getReplySender(), cohortEntry.getTransactionID(),
325 DataTreeCandidatePayload.create(candidate));
329 private void handleCommitTransaction(final CommitTransaction commit) {
331 if(!commitCoordinator.handleCommit(commit.getTransactionID(), getSender(), this)) {
332 shardMBean.incrementFailedTransactionsCount();
335 ActorSelection leader = getLeader();
336 if (leader == null) {
337 messageRetrySupport.addMessageToRetry(commit, getSender(),
338 "Could not commit transaction " + commit.getTransactionID());
340 LOG.debug("{}: Forwarding CommitTransaction to leader {}", persistenceId(), leader);
341 leader.forward(commit, getContext());
346 private void finishCommit(@Nonnull final ActorRef sender, @Nonnull final String transactionID, @Nonnull final CohortEntry cohortEntry) {
347 LOG.debug("{}: Finishing commit for transaction {}", persistenceId(), cohortEntry.getTransactionID());
351 cohortEntry.commit();
352 } catch(ExecutionException e) {
353 // We may get a "store tree and candidate base differ" IllegalStateException from commit under
354 // certain edge case scenarios so we'll try to re-apply the candidate from scratch as a last
355 // resort. Eg, we're a follower and a tx payload is replicated but the leader goes down before
356 // applying it to the state. We then become the leader and a second tx is pre-committed and
357 // replicated. When consensus occurs, this will cause the first tx to be applied as a foreign
358 // candidate via applyState prior to the second tx. Since the second tx has already been
359 // pre-committed, when it gets here to commit it will get an IllegalStateException.
361 // FIXME - this is not an ideal way to handle this scenario. This is temporary - a cleaner
362 // solution will be forthcoming.
363 if(e.getCause() instanceof IllegalStateException) {
364 LOG.debug("{}: commit failed for transaction {} - retrying as foreign candidate", persistenceId(),
366 store.applyForeignCandidate(transactionID, cohortEntry.getCandidate());
372 sender.tell(CommitTransactionReply.instance(cohortEntry.getClientVersion()).toSerializable(), getSelf());
374 shardMBean.incrementCommittedTransactionCount();
375 shardMBean.setLastCommittedTransactionTime(System.currentTimeMillis());
377 } catch (Exception e) {
378 sender.tell(new akka.actor.Status.Failure(e), getSelf());
380 LOG.error("{}, An exception occurred while committing transaction {}", persistenceId(),
382 shardMBean.incrementFailedTransactionsCount();
384 commitCoordinator.currentTransactionComplete(transactionID, true);
388 private void finishCommit(@Nonnull final ActorRef sender, final @Nonnull String transactionID) {
389 // With persistence enabled, this method is called via applyState by the leader strategy
390 // after the commit has been replicated to a majority of the followers.
392 CohortEntry cohortEntry = commitCoordinator.getCohortEntryIfCurrent(transactionID);
393 if (cohortEntry == null) {
394 // The transaction is no longer the current commit. This can happen if the transaction
395 // was aborted prior, most likely due to timeout in the front-end. We need to finish
396 // committing the transaction though since it was successfully persisted and replicated
397 // however we can't use the original cohort b/c it was already preCommitted and may
398 // conflict with the current commit or may have been aborted so we commit with a new
400 cohortEntry = commitCoordinator.getAndRemoveCohortEntry(transactionID);
401 if(cohortEntry != null) {
403 store.applyForeignCandidate(transactionID, cohortEntry.getCandidate());
404 } catch (DataValidationFailedException e) {
405 shardMBean.incrementFailedTransactionsCount();
406 LOG.error("{}: Failed to re-apply transaction {}", persistenceId(), transactionID, e);
409 sender.tell(CommitTransactionReply.instance(cohortEntry.getClientVersion()).toSerializable(),
412 // This really shouldn't happen - it likely means that persistence or replication
413 // took so long to complete such that the cohort entry was expired from the cache.
414 IllegalStateException ex = new IllegalStateException(
415 String.format("%s: Could not finish committing transaction %s - no CohortEntry found",
416 persistenceId(), transactionID));
417 LOG.error(ex.getMessage());
418 sender.tell(new akka.actor.Status.Failure(ex), getSelf());
421 finishCommit(sender, transactionID, cohortEntry);
425 private void handleCanCommitTransaction(final CanCommitTransaction canCommit) {
426 LOG.debug("{}: Can committing transaction {}", persistenceId(), canCommit.getTransactionID());
429 commitCoordinator.handleCanCommit(canCommit.getTransactionID(), getSender(), this);
431 ActorSelection leader = getLeader();
432 if (leader == null) {
433 messageRetrySupport.addMessageToRetry(canCommit, getSender(),
434 "Could not canCommit transaction " + canCommit.getTransactionID());
436 LOG.debug("{}: Forwarding CanCommitTransaction to leader {}", persistenceId(), leader);
437 leader.forward(canCommit, getContext());
442 protected void handleBatchedModificationsLocal(BatchedModifications batched, ActorRef sender) {
444 commitCoordinator.handleBatchedModifications(batched, sender, this);
445 } catch (Exception e) {
446 LOG.error("{}: Error handling BatchedModifications for Tx {}", persistenceId(),
447 batched.getTransactionID(), e);
448 sender.tell(new akka.actor.Status.Failure(e), getSelf());
452 private void handleBatchedModifications(BatchedModifications batched) {
453 // This message is sent to prepare the modifications transaction directly on the Shard as an
454 // optimization to avoid the extra overhead of a separate ShardTransaction actor. On the last
455 // BatchedModifications message, the caller sets the ready flag in the message indicating
456 // modifications are complete. The reply contains the cohort actor path (this actor) for the caller
457 // to initiate the 3-phase commit. This also avoids the overhead of sending an additional
458 // ReadyTransaction message.
460 // If we're not the leader then forward to the leader. This is a safety measure - we shouldn't
461 // normally get here if we're not the leader as the front-end (TransactionProxy) should determine
462 // the primary/leader shard. However with timing and caching on the front-end, there's a small
463 // window where it could have a stale leader during leadership transitions.
465 boolean isLeaderActive = isLeaderActive();
466 if (isLeader() && isLeaderActive) {
467 handleBatchedModificationsLocal(batched, getSender());
469 ActorSelection leader = getLeader();
470 if (!isLeaderActive || leader == null) {
471 messageRetrySupport.addMessageToRetry(batched, getSender(),
472 "Could not commit transaction " + batched.getTransactionID());
474 // If this is not the first batch and leadership changed in between batched messages,
475 // we need to reconstruct previous BatchedModifications from the transaction
476 // DataTreeModification, honoring the max batched modification count, and forward all the
477 // previous BatchedModifications to the new leader.
478 Collection<BatchedModifications> newModifications = commitCoordinator.createForwardedBatchedModifications(
479 batched, datastoreContext.getShardBatchedModificationCount());
481 LOG.debug("{}: Forwarding {} BatchedModifications to leader {}", persistenceId(),
482 newModifications.size(), leader);
484 for(BatchedModifications bm: newModifications) {
485 leader.forward(bm, getContext());
491 private boolean failIfIsolatedLeader(ActorRef sender) {
492 if(isIsolatedLeader()) {
493 sender.tell(new akka.actor.Status.Failure(new NoShardLeaderException(String.format(
494 "Shard %s was the leader but has lost contact with all of its followers. Either all" +
495 " other follower nodes are down or this node is isolated by a network partition.",
496 persistenceId()))), getSelf());
503 protected boolean isIsolatedLeader() {
504 return getRaftState() == RaftState.IsolatedLeader;
507 private void handleReadyLocalTransaction(final ReadyLocalTransaction message) {
508 LOG.debug("{}: handleReadyLocalTransaction for {}", persistenceId(), message.getTransactionID());
510 boolean isLeaderActive = isLeaderActive();
511 if (isLeader() && isLeaderActive) {
513 commitCoordinator.handleReadyLocalTransaction(message, getSender(), this);
514 } catch (Exception e) {
515 LOG.error("{}: Error handling ReadyLocalTransaction for Tx {}", persistenceId(),
516 message.getTransactionID(), e);
517 getSender().tell(new akka.actor.Status.Failure(e), getSelf());
520 ActorSelection leader = getLeader();
521 if (!isLeaderActive || leader == null) {
522 messageRetrySupport.addMessageToRetry(message, getSender(),
523 "Could not commit transaction " + message.getTransactionID());
525 LOG.debug("{}: Forwarding ReadyLocalTransaction to leader {}", persistenceId(), leader);
526 message.setRemoteVersion(getCurrentBehavior().getLeaderPayloadVersion());
527 leader.forward(message, getContext());
532 private void handleForwardedReadyTransaction(ForwardedReadyTransaction forwardedReady) {
533 LOG.debug("{}: handleForwardedReadyTransaction for {}", persistenceId(), forwardedReady.getTransactionID());
535 boolean isLeaderActive = isLeaderActive();
536 if (isLeader() && isLeaderActive) {
537 commitCoordinator.handleForwardedReadyTransaction(forwardedReady, getSender(), this);
539 ActorSelection leader = getLeader();
540 if (!isLeaderActive || leader == null) {
541 messageRetrySupport.addMessageToRetry(forwardedReady, getSender(),
542 "Could not commit transaction " + forwardedReady.getTransactionID());
544 LOG.debug("{}: Forwarding ForwardedReadyTransaction to leader {}", persistenceId(), leader);
546 ReadyLocalTransaction readyLocal = new ReadyLocalTransaction(forwardedReady.getTransactionID(),
547 forwardedReady.getTransaction().getSnapshot(), forwardedReady.isDoImmediateCommit());
548 readyLocal.setRemoteVersion(getCurrentBehavior().getLeaderPayloadVersion());
549 leader.forward(readyLocal, getContext());
554 private void handleAbortTransaction(final AbortTransaction abort) {
555 doAbortTransaction(abort.getTransactionID(), getSender());
558 void doAbortTransaction(final String transactionID, final ActorRef sender) {
559 commitCoordinator.handleAbort(transactionID, sender, this);
562 private void handleCreateTransaction(final Object message) {
564 createTransaction(CreateTransaction.fromSerializable(message));
565 } else if (getLeader() != null) {
566 getLeader().forward(message, getContext());
568 getSender().tell(new akka.actor.Status.Failure(new NoShardLeaderException(
569 "Could not create a shard transaction", persistenceId())), getSelf());
573 private void closeTransactionChain(final CloseTransactionChain closeTransactionChain) {
574 store.closeTransactionChain(closeTransactionChain.getTransactionChainId());
577 private ActorRef createTypedTransactionActor(int transactionType,
578 ShardTransactionIdentifier transactionId, String transactionChainId) {
580 return transactionActorFactory.newShardTransaction(TransactionType.fromInt(transactionType),
581 transactionId, transactionChainId);
584 private void createTransaction(CreateTransaction createTransaction) {
586 if(TransactionType.fromInt(createTransaction.getTransactionType()) != TransactionType.READ_ONLY &&
587 failIfIsolatedLeader(getSender())) {
591 ActorRef transactionActor = createTransaction(createTransaction.getTransactionType(),
592 createTransaction.getTransactionId(), createTransaction.getTransactionChainId());
594 getSender().tell(new CreateTransactionReply(Serialization.serializedActorPath(transactionActor),
595 createTransaction.getTransactionId(), createTransaction.getVersion()).toSerializable(), getSelf());
596 } catch (Exception e) {
597 getSender().tell(new akka.actor.Status.Failure(e), getSelf());
601 private ActorRef createTransaction(int transactionType, String remoteTransactionId,
602 String transactionChainId) {
605 ShardTransactionIdentifier transactionId = new ShardTransactionIdentifier(remoteTransactionId);
607 if(LOG.isDebugEnabled()) {
608 LOG.debug("{}: Creating transaction : {} ", persistenceId(), transactionId);
611 ActorRef transactionActor = createTypedTransactionActor(transactionType, transactionId,
614 return transactionActor;
617 private void commitWithNewTransaction(final Modification modification) {
618 ReadWriteShardDataTreeTransaction tx = store.newReadWriteTransaction(modification.toString(), null);
619 modification.apply(tx.getSnapshot());
621 snapshotCohort.syncCommitTransaction(tx);
622 shardMBean.incrementCommittedTransactionCount();
623 shardMBean.setLastCommittedTransactionTime(System.currentTimeMillis());
624 } catch (Exception e) {
625 shardMBean.incrementFailedTransactionsCount();
626 LOG.error("{}: Failed to commit", persistenceId(), e);
630 private void updateSchemaContext(final UpdateSchemaContext message) {
631 updateSchemaContext(message.getSchemaContext());
635 void updateSchemaContext(final SchemaContext schemaContext) {
636 store.updateSchemaContext(schemaContext);
639 private boolean isMetricsCaptureEnabled() {
640 CommonConfig config = new CommonConfig(getContext().system().settings().config());
641 return config.isMetricCaptureEnabled();
646 public RaftActorSnapshotCohort getRaftActorSnapshotCohort() {
647 return snapshotCohort;
652 protected RaftActorRecoveryCohort getRaftActorRecoveryCohort() {
653 return new ShardRecoveryCoordinator(store, store.getSchemaContext(),
654 restoreFromSnapshot != null ? restoreFromSnapshot.getSnapshot() : null, persistenceId(), LOG);
658 protected void onRecoveryComplete() {
659 restoreFromSnapshot = null;
661 //notify shard manager
662 getContext().parent().tell(new ActorInitialized(), getSelf());
664 // Being paranoid here - this method should only be called once but just in case...
665 if(txCommitTimeoutCheckSchedule == null) {
666 // Schedule a message to be periodically sent to check if the current in-progress
667 // transaction should be expired and aborted.
668 FiniteDuration period = Duration.create(transactionCommitTimeout / 3, TimeUnit.MILLISECONDS);
669 txCommitTimeoutCheckSchedule = getContext().system().scheduler().schedule(
670 period, period, getSelf(),
671 TX_COMMIT_TIMEOUT_CHECK_MESSAGE, getContext().dispatcher(), ActorRef.noSender());
676 protected void applyState(final ActorRef clientActor, final String identifier, final Object data) {
677 if (data instanceof DataTreeCandidatePayload) {
678 if (clientActor == null) {
679 // No clientActor indicates a replica coming from the leader
681 store.applyForeignCandidate(identifier, ((DataTreeCandidatePayload)data).getCandidate());
682 } catch (DataValidationFailedException | IOException e) {
683 LOG.error("{}: Error applying replica {}", persistenceId(), identifier, e);
686 // Replication consensus reached, proceed to commit
687 finishCommit(clientActor, identifier);
689 } else if (data instanceof CompositeModificationPayload) {
690 Object modification = ((CompositeModificationPayload) data).getModification();
692 applyModificationToState(clientActor, identifier, modification);
693 } else if(data instanceof CompositeModificationByteStringPayload ){
694 Object modification = ((CompositeModificationByteStringPayload) data).getModification();
696 applyModificationToState(clientActor, identifier, modification);
698 LOG.error("{}: Unknown state received {} Class loader = {} CompositeNodeMod.ClassLoader = {}",
699 persistenceId(), data, data.getClass().getClassLoader(),
700 CompositeModificationPayload.class.getClassLoader());
704 private void applyModificationToState(ActorRef clientActor, String identifier, Object modification) {
705 if(modification == null) {
707 "{}: modification is null - this is very unexpected, clientActor = {}, identifier = {}",
708 persistenceId(), identifier, clientActor != null ? clientActor.path().toString() : null);
709 } else if(clientActor == null) {
710 // There's no clientActor to which to send a commit reply so we must be applying
711 // replicated state from the leader.
712 commitWithNewTransaction(MutableCompositeModification.fromSerializable(modification));
714 // This must be the OK to commit after replication consensus.
715 finishCommit(clientActor, identifier);
720 protected void onStateChanged() {
721 boolean isLeader = isLeader();
722 boolean hasLeader = hasLeader();
723 changeSupport.onLeadershipChange(isLeader, hasLeader);
724 treeChangeSupport.onLeadershipChange(isLeader, hasLeader);
726 // If this actor is no longer the leader close all the transaction chains
728 if(LOG.isDebugEnabled()) {
730 "{}: onStateChanged: Closing all transaction chains because shard {} is no longer the leader",
731 persistenceId(), getId());
734 store.closeAllTransactionChains();
737 if(hasLeader && !isIsolatedLeader()) {
738 messageRetrySupport.retryMessages();
743 protected void onLeaderChanged(String oldLeader, String newLeader) {
744 shardMBean.incrementLeadershipChangeCount();
746 boolean hasLeader = hasLeader();
747 if(hasLeader && !isLeader()) {
748 // Another leader was elected. If we were the previous leader and had pending transactions, convert
749 // them to transaction messages and send to the new leader.
750 ActorSelection leader = getLeader();
752 Collection<Object> messagesToForward = commitCoordinator.convertPendingTransactionsToMessages(
753 datastoreContext.getShardBatchedModificationCount());
755 if(!messagesToForward.isEmpty()) {
756 LOG.debug("{}: Forwarding {} pending transaction messages to leader {}", persistenceId(),
757 messagesToForward.size(), leader);
759 for(Object message: messagesToForward) {
760 leader.tell(message, self());
764 commitCoordinator.abortPendingTransactions(
765 "The transacton was aborted due to inflight leadership change and the leader address isn't available.",
770 if(hasLeader && !isIsolatedLeader()) {
771 messageRetrySupport.retryMessages();
776 protected void pauseLeader(Runnable operation) {
777 LOG.debug("{}: In pauseLeader, operation: {}", persistenceId(), operation);
778 commitCoordinator.setRunOnPendingTransactionsComplete(operation);
782 public String persistenceId() {
787 ShardCommitCoordinator getCommitCoordinator() {
788 return commitCoordinator;
791 public DatastoreContext getDatastoreContext() {
792 return datastoreContext;
796 public ShardDataTree getDataStore() {
801 ShardStats getShardMBean() {
805 public static Builder builder() {
806 return new Builder();
809 public static abstract class AbstractBuilder<T extends AbstractBuilder<T, S>, S extends Shard> {
810 private final Class<S> shardClass;
811 private ShardIdentifier id;
812 private Map<String, String> peerAddresses = Collections.emptyMap();
813 private DatastoreContext datastoreContext;
814 private SchemaContext schemaContext;
815 private DatastoreSnapshot.ShardSnapshot restoreFromSnapshot;
816 private volatile boolean sealed;
818 protected AbstractBuilder(Class<S> shardClass) {
819 this.shardClass = shardClass;
822 protected void checkSealed() {
823 Preconditions.checkState(!sealed, "Builder isalready sealed - further modifications are not allowed");
826 @SuppressWarnings("unchecked")
831 public T id(ShardIdentifier id) {
837 public T peerAddresses(Map<String, String> peerAddresses) {
839 this.peerAddresses = peerAddresses;
843 public T datastoreContext(DatastoreContext datastoreContext) {
845 this.datastoreContext = datastoreContext;
849 public T schemaContext(SchemaContext schemaContext) {
851 this.schemaContext = schemaContext;
855 public T restoreFromSnapshot(DatastoreSnapshot.ShardSnapshot restoreFromSnapshot) {
857 this.restoreFromSnapshot = restoreFromSnapshot;
861 public ShardIdentifier getId() {
865 public Map<String, String> getPeerAddresses() {
866 return peerAddresses;
869 public DatastoreContext getDatastoreContext() {
870 return datastoreContext;
873 public SchemaContext getSchemaContext() {
874 return schemaContext;
877 public DatastoreSnapshot.ShardSnapshot getRestoreFromSnapshot() {
878 return restoreFromSnapshot;
881 public TreeType getTreeType() {
882 switch (datastoreContext.getLogicalStoreType()) {
884 return TreeType.CONFIGURATION;
886 return TreeType.OPERATIONAL;
889 throw new IllegalStateException("Unhandled logical store type " + datastoreContext.getLogicalStoreType());
892 protected void verify() {
893 Preconditions.checkNotNull(id, "id should not be null");
894 Preconditions.checkNotNull(peerAddresses, "peerAddresses should not be null");
895 Preconditions.checkNotNull(datastoreContext, "dataStoreContext should not be null");
896 Preconditions.checkNotNull(schemaContext, "schemaContext should not be null");
899 public Props props() {
902 return Props.create(shardClass, this);
906 public static class Builder extends AbstractBuilder<Builder, Shard> {