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) {
212 try (final MessageTracker.Context context = appendEntriesReplyTracker.received(message)) {
213 final Optional<Error> maybeError = context.error();
214 if (maybeError.isPresent()) {
215 LOG.trace("{} : AppendEntriesReply failed to arrive at the expected interval {}", persistenceId(),
219 if (CreateTransaction.isSerializedType(message)) {
220 handleCreateTransaction(message);
221 } else if (message instanceof BatchedModifications) {
222 handleBatchedModifications((BatchedModifications)message);
223 } else if (message instanceof ForwardedReadyTransaction) {
224 handleForwardedReadyTransaction((ForwardedReadyTransaction) message);
225 } else if (message instanceof ReadyLocalTransaction) {
226 handleReadyLocalTransaction((ReadyLocalTransaction)message);
227 } else if (CanCommitTransaction.isSerializedType(message)) {
228 handleCanCommitTransaction(CanCommitTransaction.fromSerializable(message));
229 } else if (CommitTransaction.isSerializedType(message)) {
230 handleCommitTransaction(CommitTransaction.fromSerializable(message));
231 } else if (AbortTransaction.isSerializedType(message)) {
232 handleAbortTransaction(AbortTransaction.fromSerializable(message));
233 } else if (CloseTransactionChain.isSerializedType(message)) {
234 closeTransactionChain(CloseTransactionChain.fromSerializable(message));
235 } else if (message instanceof RegisterChangeListener) {
236 changeSupport.onMessage((RegisterChangeListener) message, isLeader(), hasLeader());
237 } else if (message instanceof RegisterDataTreeChangeListener) {
238 treeChangeSupport.onMessage((RegisterDataTreeChangeListener) message, isLeader(), hasLeader());
239 } else if (message instanceof UpdateSchemaContext) {
240 updateSchemaContext((UpdateSchemaContext) message);
241 } else if (message instanceof PeerAddressResolved) {
242 PeerAddressResolved resolved = (PeerAddressResolved) message;
243 setPeerAddress(resolved.getPeerId().toString(),
244 resolved.getPeerAddress());
245 } else if (TX_COMMIT_TIMEOUT_CHECK_MESSAGE.equals(message)) {
246 commitCoordinator.checkForExpiredTransactions(transactionCommitTimeout, this);
247 } else if(message instanceof DatastoreContext) {
248 onDatastoreContext((DatastoreContext)message);
249 } else if(message instanceof RegisterRoleChangeListener){
250 roleChangeNotifier.get().forward(message, context());
251 } else if (message instanceof FollowerInitialSyncUpStatus) {
252 shardMBean.setFollowerInitialSyncStatus(((FollowerInitialSyncUpStatus) message).isInitialSyncDone());
253 context().parent().tell(message, self());
254 } else if(GET_SHARD_MBEAN_MESSAGE.equals(message)){
255 sender().tell(getShardMBean(), self());
256 } else if(message instanceof GetShardDataTree) {
257 sender().tell(store.getDataTree(), self());
258 } else if(message instanceof ServerRemoved){
259 context().parent().forward(message, context());
260 } else if(ShardTransactionMessageRetrySupport.TIMER_MESSAGE_CLASS.isInstance(message)) {
261 messageRetrySupport.onTimerMessage(message);
263 super.handleCommand(message);
268 private boolean hasLeader() {
269 return getLeaderId() != null;
272 public int getPendingTxCommitQueueSize() {
273 return commitCoordinator.getQueueSize();
276 public int getCohortCacheSize() {
277 return commitCoordinator.getCohortCacheSize();
281 protected Optional<ActorRef> getRoleChangeNotifier() {
282 return roleChangeNotifier;
286 protected LeaderStateChanged newLeaderStateChanged(String memberId, String leaderId, short leaderPayloadVersion) {
287 return isLeader() ? new ShardLeaderStateChanged(memberId, leaderId, store.getDataTree(), leaderPayloadVersion)
288 : new ShardLeaderStateChanged(memberId, leaderId, leaderPayloadVersion);
291 protected void onDatastoreContext(DatastoreContext context) {
292 datastoreContext = context;
294 commitCoordinator.setQueueCapacity(datastoreContext.getShardTransactionCommitQueueCapacity());
296 setTransactionCommitTimeout();
298 if(datastoreContext.isPersistent() && !persistence().isRecoveryApplicable()) {
299 setPersistence(true);
300 } else if(!datastoreContext.isPersistent() && persistence().isRecoveryApplicable()) {
301 setPersistence(false);
304 updateConfigParams(datastoreContext.getShardRaftConfig());
307 private static boolean isEmptyCommit(final DataTreeCandidate candidate) {
308 return ModificationType.UNMODIFIED.equals(candidate.getRootNode().getModificationType());
311 void continueCommit(final CohortEntry cohortEntry) {
312 final DataTreeCandidate candidate = cohortEntry.getCandidate();
314 // If we do not have any followers and we are not using persistence
315 // or if cohortEntry has no modifications
316 // we can apply modification to the state immediately
317 if ((!hasFollowers() && !persistence().isRecoveryApplicable()) || isEmptyCommit(candidate)) {
318 applyModificationToState(cohortEntry.getReplySender(), cohortEntry.getTransactionID(), candidate);
320 Shard.this.persistData(cohortEntry.getReplySender(), cohortEntry.getTransactionID(),
321 DataTreeCandidatePayload.create(candidate));
325 private void handleCommitTransaction(final CommitTransaction commit) {
327 if(!commitCoordinator.handleCommit(commit.getTransactionID(), getSender(), this)) {
328 shardMBean.incrementFailedTransactionsCount();
331 ActorSelection leader = getLeader();
332 if (leader == null) {
333 messageRetrySupport.addMessageToRetry(commit, getSender(),
334 "Could not commit transaction " + commit.getTransactionID());
336 LOG.debug("{}: Forwarding CommitTransaction to leader {}", persistenceId(), leader);
337 leader.forward(commit, getContext());
342 private void finishCommit(@Nonnull final ActorRef sender, @Nonnull final String transactionID, @Nonnull final CohortEntry cohortEntry) {
343 LOG.debug("{}: Finishing commit for transaction {}", persistenceId(), cohortEntry.getTransactionID());
347 cohortEntry.commit();
348 } catch(ExecutionException e) {
349 // We may get a "store tree and candidate base differ" IllegalStateException from commit under
350 // certain edge case scenarios so we'll try to re-apply the candidate from scratch as a last
351 // resort. Eg, we're a follower and a tx payload is replicated but the leader goes down before
352 // applying it to the state. We then become the leader and a second tx is pre-committed and
353 // replicated. When consensus occurs, this will cause the first tx to be applied as a foreign
354 // candidate via applyState prior to the second tx. Since the second tx has already been
355 // pre-committed, when it gets here to commit it will get an IllegalStateException.
357 // FIXME - this is not an ideal way to handle this scenario. This is temporary - a cleaner
358 // solution will be forthcoming.
359 if(e.getCause() instanceof IllegalStateException) {
360 LOG.debug("{}: commit failed for transaction {} - retrying as foreign candidate", persistenceId(),
362 store.applyForeignCandidate(transactionID, cohortEntry.getCandidate());
368 sender.tell(CommitTransactionReply.instance(cohortEntry.getClientVersion()).toSerializable(), getSelf());
370 shardMBean.incrementCommittedTransactionCount();
371 shardMBean.setLastCommittedTransactionTime(System.currentTimeMillis());
373 } catch (Exception e) {
374 sender.tell(new akka.actor.Status.Failure(e), getSelf());
376 LOG.error("{}, An exception occurred while committing transaction {}", persistenceId(),
378 shardMBean.incrementFailedTransactionsCount();
380 commitCoordinator.currentTransactionComplete(transactionID, true);
384 private void finishCommit(@Nonnull final ActorRef sender, final @Nonnull String transactionID) {
385 // With persistence enabled, this method is called via applyState by the leader strategy
386 // after the commit has been replicated to a majority of the followers.
388 CohortEntry cohortEntry = commitCoordinator.getCohortEntryIfCurrent(transactionID);
389 if (cohortEntry == null) {
390 // The transaction is no longer the current commit. This can happen if the transaction
391 // was aborted prior, most likely due to timeout in the front-end. We need to finish
392 // committing the transaction though since it was successfully persisted and replicated
393 // however we can't use the original cohort b/c it was already preCommitted and may
394 // conflict with the current commit or may have been aborted so we commit with a new
396 cohortEntry = commitCoordinator.getAndRemoveCohortEntry(transactionID);
397 if(cohortEntry != null) {
399 store.applyForeignCandidate(transactionID, cohortEntry.getCandidate());
400 } catch (DataValidationFailedException e) {
401 shardMBean.incrementFailedTransactionsCount();
402 LOG.error("{}: Failed to re-apply transaction {}", persistenceId(), transactionID, e);
405 sender.tell(CommitTransactionReply.instance(cohortEntry.getClientVersion()).toSerializable(),
408 // This really shouldn't happen - it likely means that persistence or replication
409 // took so long to complete such that the cohort entry was expired from the cache.
410 IllegalStateException ex = new IllegalStateException(
411 String.format("%s: Could not finish committing transaction %s - no CohortEntry found",
412 persistenceId(), transactionID));
413 LOG.error(ex.getMessage());
414 sender.tell(new akka.actor.Status.Failure(ex), getSelf());
417 finishCommit(sender, transactionID, cohortEntry);
421 private void handleCanCommitTransaction(final CanCommitTransaction canCommit) {
422 LOG.debug("{}: Can committing transaction {}", persistenceId(), canCommit.getTransactionID());
425 commitCoordinator.handleCanCommit(canCommit.getTransactionID(), getSender(), this);
427 ActorSelection leader = getLeader();
428 if (leader == null) {
429 messageRetrySupport.addMessageToRetry(canCommit, getSender(),
430 "Could not canCommit transaction " + canCommit.getTransactionID());
432 LOG.debug("{}: Forwarding CanCommitTransaction to leader {}", persistenceId(), leader);
433 leader.forward(canCommit, getContext());
438 protected void handleBatchedModificationsLocal(BatchedModifications batched, ActorRef sender) {
440 commitCoordinator.handleBatchedModifications(batched, sender, this);
441 } catch (Exception e) {
442 LOG.error("{}: Error handling BatchedModifications for Tx {}", persistenceId(),
443 batched.getTransactionID(), e);
444 sender.tell(new akka.actor.Status.Failure(e), getSelf());
448 private void handleBatchedModifications(BatchedModifications batched) {
449 // This message is sent to prepare the modifications transaction directly on the Shard as an
450 // optimization to avoid the extra overhead of a separate ShardTransaction actor. On the last
451 // BatchedModifications message, the caller sets the ready flag in the message indicating
452 // modifications are complete. The reply contains the cohort actor path (this actor) for the caller
453 // to initiate the 3-phase commit. This also avoids the overhead of sending an additional
454 // ReadyTransaction message.
456 // If we're not the leader then forward to the leader. This is a safety measure - we shouldn't
457 // normally get here if we're not the leader as the front-end (TransactionProxy) should determine
458 // the primary/leader shard. However with timing and caching on the front-end, there's a small
459 // window where it could have a stale leader during leadership transitions.
461 boolean isLeaderActive = isLeaderActive();
462 if (isLeader() && isLeaderActive) {
463 handleBatchedModificationsLocal(batched, getSender());
465 ActorSelection leader = getLeader();
466 if (!isLeaderActive || leader == null) {
467 messageRetrySupport.addMessageToRetry(batched, getSender(),
468 "Could not commit transaction " + batched.getTransactionID());
470 // If this is not the first batch and leadership changed in between batched messages,
471 // we need to reconstruct previous BatchedModifications from the transaction
472 // DataTreeModification, honoring the max batched modification count, and forward all the
473 // previous BatchedModifications to the new leader.
474 Collection<BatchedModifications> newModifications = commitCoordinator.createForwardedBatchedModifications(
475 batched, datastoreContext.getShardBatchedModificationCount());
477 LOG.debug("{}: Forwarding {} BatchedModifications to leader {}", persistenceId(),
478 newModifications.size(), leader);
480 for(BatchedModifications bm: newModifications) {
481 leader.forward(bm, getContext());
487 private boolean failIfIsolatedLeader(ActorRef sender) {
488 if(isIsolatedLeader()) {
489 sender.tell(new akka.actor.Status.Failure(new NoShardLeaderException(String.format(
490 "Shard %s was the leader but has lost contact with all of its followers. Either all" +
491 " other follower nodes are down or this node is isolated by a network partition.",
492 persistenceId()))), getSelf());
499 protected boolean isIsolatedLeader() {
500 return getRaftState() == RaftState.IsolatedLeader;
503 private void handleReadyLocalTransaction(final ReadyLocalTransaction message) {
504 LOG.debug("{}: handleReadyLocalTransaction for {}", persistenceId(), message.getTransactionID());
506 boolean isLeaderActive = isLeaderActive();
507 if (isLeader() && isLeaderActive) {
509 commitCoordinator.handleReadyLocalTransaction(message, getSender(), this);
510 } catch (Exception e) {
511 LOG.error("{}: Error handling ReadyLocalTransaction for Tx {}", persistenceId(),
512 message.getTransactionID(), e);
513 getSender().tell(new akka.actor.Status.Failure(e), getSelf());
516 ActorSelection leader = getLeader();
517 if (!isLeaderActive || leader == null) {
518 messageRetrySupport.addMessageToRetry(message, getSender(),
519 "Could not commit transaction " + message.getTransactionID());
521 LOG.debug("{}: Forwarding ReadyLocalTransaction to leader {}", persistenceId(), leader);
522 message.setRemoteVersion(getCurrentBehavior().getLeaderPayloadVersion());
523 leader.forward(message, getContext());
528 private void handleForwardedReadyTransaction(ForwardedReadyTransaction forwardedReady) {
529 LOG.debug("{}: handleForwardedReadyTransaction for {}", persistenceId(), forwardedReady.getTransactionID());
531 boolean isLeaderActive = isLeaderActive();
532 if (isLeader() && isLeaderActive) {
533 commitCoordinator.handleForwardedReadyTransaction(forwardedReady, getSender(), this);
535 ActorSelection leader = getLeader();
536 if (!isLeaderActive || leader == null) {
537 messageRetrySupport.addMessageToRetry(forwardedReady, getSender(),
538 "Could not commit transaction " + forwardedReady.getTransactionID());
540 LOG.debug("{}: Forwarding ForwardedReadyTransaction to leader {}", persistenceId(), leader);
542 ReadyLocalTransaction readyLocal = new ReadyLocalTransaction(forwardedReady.getTransactionID(),
543 forwardedReady.getTransaction().getSnapshot(), forwardedReady.isDoImmediateCommit());
544 readyLocal.setRemoteVersion(getCurrentBehavior().getLeaderPayloadVersion());
545 leader.forward(readyLocal, getContext());
550 private void handleAbortTransaction(final AbortTransaction abort) {
551 doAbortTransaction(abort.getTransactionID(), getSender());
554 void doAbortTransaction(final String transactionID, final ActorRef sender) {
555 commitCoordinator.handleAbort(transactionID, sender, this);
558 private void handleCreateTransaction(final Object message) {
560 createTransaction(CreateTransaction.fromSerializable(message));
561 } else if (getLeader() != null) {
562 getLeader().forward(message, getContext());
564 getSender().tell(new akka.actor.Status.Failure(new NoShardLeaderException(
565 "Could not create a shard transaction", persistenceId())), getSelf());
569 private void closeTransactionChain(final CloseTransactionChain closeTransactionChain) {
570 store.closeTransactionChain(closeTransactionChain.getTransactionChainId());
573 private ActorRef createTypedTransactionActor(int transactionType,
574 ShardTransactionIdentifier transactionId, String transactionChainId) {
576 return transactionActorFactory.newShardTransaction(TransactionType.fromInt(transactionType),
577 transactionId, transactionChainId);
580 private void createTransaction(CreateTransaction createTransaction) {
582 if(TransactionType.fromInt(createTransaction.getTransactionType()) != TransactionType.READ_ONLY &&
583 failIfIsolatedLeader(getSender())) {
587 ActorRef transactionActor = createTransaction(createTransaction.getTransactionType(),
588 createTransaction.getTransactionId(), createTransaction.getTransactionChainId());
590 getSender().tell(new CreateTransactionReply(Serialization.serializedActorPath(transactionActor),
591 createTransaction.getTransactionId(), createTransaction.getVersion()).toSerializable(), getSelf());
592 } catch (Exception e) {
593 getSender().tell(new akka.actor.Status.Failure(e), getSelf());
597 private ActorRef createTransaction(int transactionType, String remoteTransactionId,
598 String transactionChainId) {
601 ShardTransactionIdentifier transactionId = new ShardTransactionIdentifier(remoteTransactionId);
603 if(LOG.isDebugEnabled()) {
604 LOG.debug("{}: Creating transaction : {} ", persistenceId(), transactionId);
607 ActorRef transactionActor = createTypedTransactionActor(transactionType, transactionId,
610 return transactionActor;
613 private void commitWithNewTransaction(final Modification modification) {
614 ReadWriteShardDataTreeTransaction tx = store.newReadWriteTransaction(modification.toString(), null);
615 modification.apply(tx.getSnapshot());
617 snapshotCohort.syncCommitTransaction(tx);
618 shardMBean.incrementCommittedTransactionCount();
619 shardMBean.setLastCommittedTransactionTime(System.currentTimeMillis());
620 } catch (Exception e) {
621 shardMBean.incrementFailedTransactionsCount();
622 LOG.error("{}: Failed to commit", persistenceId(), e);
626 private void updateSchemaContext(final UpdateSchemaContext message) {
627 updateSchemaContext(message.getSchemaContext());
631 void updateSchemaContext(final SchemaContext schemaContext) {
632 store.updateSchemaContext(schemaContext);
635 private boolean isMetricsCaptureEnabled() {
636 CommonConfig config = new CommonConfig(getContext().system().settings().config());
637 return config.isMetricCaptureEnabled();
642 public RaftActorSnapshotCohort getRaftActorSnapshotCohort() {
643 return snapshotCohort;
648 protected RaftActorRecoveryCohort getRaftActorRecoveryCohort() {
649 return new ShardRecoveryCoordinator(store, store.getSchemaContext(),
650 restoreFromSnapshot != null ? restoreFromSnapshot.getSnapshot() : null, persistenceId(), LOG);
654 protected void onRecoveryComplete() {
655 restoreFromSnapshot = null;
657 //notify shard manager
658 getContext().parent().tell(new ActorInitialized(), getSelf());
660 // Being paranoid here - this method should only be called once but just in case...
661 if(txCommitTimeoutCheckSchedule == null) {
662 // Schedule a message to be periodically sent to check if the current in-progress
663 // transaction should be expired and aborted.
664 FiniteDuration period = Duration.create(transactionCommitTimeout / 3, TimeUnit.MILLISECONDS);
665 txCommitTimeoutCheckSchedule = getContext().system().scheduler().schedule(
666 period, period, getSelf(),
667 TX_COMMIT_TIMEOUT_CHECK_MESSAGE, getContext().dispatcher(), ActorRef.noSender());
672 protected void applyState(final ActorRef clientActor, final String identifier, final Object data) {
673 if (data instanceof DataTreeCandidatePayload) {
674 if (clientActor == null) {
675 // No clientActor indicates a replica coming from the leader
677 store.applyForeignCandidate(identifier, ((DataTreeCandidatePayload)data).getCandidate());
678 } catch (DataValidationFailedException | IOException e) {
679 LOG.error("{}: Error applying replica {}", persistenceId(), identifier, e);
682 // Replication consensus reached, proceed to commit
683 finishCommit(clientActor, identifier);
685 } else if (data instanceof CompositeModificationPayload) {
686 Object modification = ((CompositeModificationPayload) data).getModification();
688 applyModificationToState(clientActor, identifier, modification);
689 } else if(data instanceof CompositeModificationByteStringPayload ){
690 Object modification = ((CompositeModificationByteStringPayload) data).getModification();
692 applyModificationToState(clientActor, identifier, modification);
694 LOG.error("{}: Unknown state received {} Class loader = {} CompositeNodeMod.ClassLoader = {}",
695 persistenceId(), data, data.getClass().getClassLoader(),
696 CompositeModificationPayload.class.getClassLoader());
700 private void applyModificationToState(ActorRef clientActor, String identifier, Object modification) {
701 if(modification == null) {
703 "{}: modification is null - this is very unexpected, clientActor = {}, identifier = {}",
704 persistenceId(), identifier, clientActor != null ? clientActor.path().toString() : null);
705 } else if(clientActor == null) {
706 // There's no clientActor to which to send a commit reply so we must be applying
707 // replicated state from the leader.
708 commitWithNewTransaction(MutableCompositeModification.fromSerializable(modification));
710 // This must be the OK to commit after replication consensus.
711 finishCommit(clientActor, identifier);
716 protected void onStateChanged() {
717 boolean isLeader = isLeader();
718 boolean hasLeader = hasLeader();
719 changeSupport.onLeadershipChange(isLeader, hasLeader);
720 treeChangeSupport.onLeadershipChange(isLeader, hasLeader);
722 // If this actor is no longer the leader close all the transaction chains
724 if(LOG.isDebugEnabled()) {
726 "{}: onStateChanged: Closing all transaction chains because shard {} is no longer the leader",
727 persistenceId(), getId());
730 store.closeAllTransactionChains();
733 if(hasLeader && !isIsolatedLeader()) {
734 messageRetrySupport.retryMessages();
739 protected void onLeaderChanged(String oldLeader, String newLeader) {
740 shardMBean.incrementLeadershipChangeCount();
742 boolean hasLeader = hasLeader();
743 if(hasLeader && !isLeader()) {
744 // Another leader was elected. If we were the previous leader and had pending transactions, convert
745 // them to transaction messages and send to the new leader.
746 ActorSelection leader = getLeader();
748 Collection<Object> messagesToForward = commitCoordinator.convertPendingTransactionsToMessages(
749 datastoreContext.getShardBatchedModificationCount());
751 if(!messagesToForward.isEmpty()) {
752 LOG.debug("{}: Forwarding {} pending transaction messages to leader {}", persistenceId(),
753 messagesToForward.size(), leader);
755 for(Object message: messagesToForward) {
756 leader.tell(message, self());
760 commitCoordinator.abortPendingTransactions(
761 "The transacton was aborted due to inflight leadership change and the leader address isn't available.",
766 if(hasLeader && !isIsolatedLeader()) {
767 messageRetrySupport.retryMessages();
772 protected void pauseLeader(Runnable operation) {
773 LOG.debug("{}: In pauseLeader, operation: {}", persistenceId(), operation);
774 commitCoordinator.setRunOnPendingTransactionsComplete(operation);
778 public String persistenceId() {
783 ShardCommitCoordinator getCommitCoordinator() {
784 return commitCoordinator;
787 public DatastoreContext getDatastoreContext() {
788 return datastoreContext;
792 public ShardDataTree getDataStore() {
797 ShardStats getShardMBean() {
801 public static Builder builder() {
802 return new Builder();
805 public static abstract class AbstractBuilder<T extends AbstractBuilder<T, S>, S extends Shard> {
806 private final Class<S> shardClass;
807 private ShardIdentifier id;
808 private Map<String, String> peerAddresses = Collections.emptyMap();
809 private DatastoreContext datastoreContext;
810 private SchemaContext schemaContext;
811 private DatastoreSnapshot.ShardSnapshot restoreFromSnapshot;
812 private volatile boolean sealed;
814 protected AbstractBuilder(Class<S> shardClass) {
815 this.shardClass = shardClass;
818 protected void checkSealed() {
819 Preconditions.checkState(!sealed, "Builder isalready sealed - further modifications are not allowed");
822 @SuppressWarnings("unchecked")
827 public T id(ShardIdentifier id) {
833 public T peerAddresses(Map<String, String> peerAddresses) {
835 this.peerAddresses = peerAddresses;
839 public T datastoreContext(DatastoreContext datastoreContext) {
841 this.datastoreContext = datastoreContext;
845 public T schemaContext(SchemaContext schemaContext) {
847 this.schemaContext = schemaContext;
851 public T restoreFromSnapshot(DatastoreSnapshot.ShardSnapshot restoreFromSnapshot) {
853 this.restoreFromSnapshot = restoreFromSnapshot;
857 public ShardIdentifier getId() {
861 public Map<String, String> getPeerAddresses() {
862 return peerAddresses;
865 public DatastoreContext getDatastoreContext() {
866 return datastoreContext;
869 public SchemaContext getSchemaContext() {
870 return schemaContext;
873 public DatastoreSnapshot.ShardSnapshot getRestoreFromSnapshot() {
874 return restoreFromSnapshot;
877 public TreeType getTreeType() {
878 switch (datastoreContext.getLogicalStoreType()) {
880 return TreeType.CONFIGURATION;
882 return TreeType.OPERATIONAL;
885 throw new IllegalStateException("Unhandled logical store type " + datastoreContext.getLogicalStoreType());
888 protected void verify() {
889 Preconditions.checkNotNull(id, "id should not be null");
890 Preconditions.checkNotNull(peerAddresses, "peerAddresses should not be null");
891 Preconditions.checkNotNull(datastoreContext, "dataStoreContext should not be null");
892 Preconditions.checkNotNull(schemaContext, "schemaContext should not be null");
895 public Props props() {
898 return Props.create(shardClass, this);
902 public static class Builder extends AbstractBuilder<Builder, Shard> {