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.japi.Creator;
16 import akka.persistence.RecoveryFailure;
17 import akka.serialization.Serialization;
18 import com.google.common.annotations.VisibleForTesting;
19 import com.google.common.base.Optional;
20 import com.google.common.base.Preconditions;
21 import java.io.IOException;
22 import java.util.HashMap;
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.MeteringBehavior;
28 import org.opendaylight.controller.cluster.datastore.ShardCommitCoordinator.CohortEntry;
29 import org.opendaylight.controller.cluster.datastore.exceptions.NoShardLeaderException;
30 import org.opendaylight.controller.cluster.datastore.identifiers.ShardIdentifier;
31 import org.opendaylight.controller.cluster.datastore.identifiers.ShardTransactionIdentifier;
32 import org.opendaylight.controller.cluster.datastore.jmx.mbeans.shard.ShardMBeanFactory;
33 import org.opendaylight.controller.cluster.datastore.jmx.mbeans.shard.ShardStats;
34 import org.opendaylight.controller.cluster.datastore.messages.AbortTransaction;
35 import org.opendaylight.controller.cluster.datastore.messages.ActorInitialized;
36 import org.opendaylight.controller.cluster.datastore.messages.BatchedModifications;
37 import org.opendaylight.controller.cluster.datastore.messages.CanCommitTransaction;
38 import org.opendaylight.controller.cluster.datastore.messages.CloseTransactionChain;
39 import org.opendaylight.controller.cluster.datastore.messages.CommitTransaction;
40 import org.opendaylight.controller.cluster.datastore.messages.CommitTransactionReply;
41 import org.opendaylight.controller.cluster.datastore.messages.CreateTransaction;
42 import org.opendaylight.controller.cluster.datastore.messages.CreateTransactionReply;
43 import org.opendaylight.controller.cluster.datastore.messages.ForwardedReadyTransaction;
44 import org.opendaylight.controller.cluster.datastore.messages.GetShardDataTree;
45 import org.opendaylight.controller.cluster.datastore.messages.PeerAddressResolved;
46 import org.opendaylight.controller.cluster.datastore.messages.ReadyLocalTransaction;
47 import org.opendaylight.controller.cluster.datastore.messages.RegisterChangeListener;
48 import org.opendaylight.controller.cluster.datastore.messages.RegisterDataTreeChangeListener;
49 import org.opendaylight.controller.cluster.datastore.messages.ShardLeaderStateChanged;
50 import org.opendaylight.controller.cluster.datastore.messages.UpdateSchemaContext;
51 import org.opendaylight.controller.cluster.datastore.modification.Modification;
52 import org.opendaylight.controller.cluster.datastore.modification.ModificationPayload;
53 import org.opendaylight.controller.cluster.datastore.modification.MutableCompositeModification;
54 import org.opendaylight.controller.cluster.datastore.utils.Dispatchers;
55 import org.opendaylight.controller.cluster.datastore.utils.MessageTracker;
56 import org.opendaylight.controller.cluster.notifications.LeaderStateChanged;
57 import org.opendaylight.controller.cluster.notifications.RegisterRoleChangeListener;
58 import org.opendaylight.controller.cluster.notifications.RoleChangeNotifier;
59 import org.opendaylight.controller.cluster.raft.RaftActor;
60 import org.opendaylight.controller.cluster.raft.RaftActorRecoveryCohort;
61 import org.opendaylight.controller.cluster.raft.RaftActorSnapshotCohort;
62 import org.opendaylight.controller.cluster.raft.RaftState;
63 import org.opendaylight.controller.cluster.raft.base.messages.FollowerInitialSyncUpStatus;
64 import org.opendaylight.controller.cluster.raft.messages.AppendEntriesReply;
65 import org.opendaylight.controller.cluster.raft.protobuff.client.messages.CompositeModificationByteStringPayload;
66 import org.opendaylight.controller.cluster.raft.protobuff.client.messages.CompositeModificationPayload;
67 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTree;
68 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidate;
69 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataValidationFailedException;
70 import org.opendaylight.yangtools.yang.data.api.schema.tree.ModificationType;
71 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
72 import scala.concurrent.duration.Duration;
73 import scala.concurrent.duration.FiniteDuration;
76 * A Shard represents a portion of the logical data tree <br/>
78 * Our Shard uses InMemoryDataTree as it's internal representation and delegates all requests it
81 public class Shard extends RaftActor {
83 protected static final Object TX_COMMIT_TIMEOUT_CHECK_MESSAGE = "txCommitTimeoutCheck";
86 static final Object GET_SHARD_MBEAN_MESSAGE = "getShardMBeanMessage";
89 static final String DEFAULT_NAME = "default";
91 // The state of this Shard
92 private final ShardDataTree store;
94 /// The name of this shard
95 private final String name;
97 private final ShardStats shardMBean;
99 private DatastoreContext datastoreContext;
101 private final ShardCommitCoordinator commitCoordinator;
103 private long transactionCommitTimeout;
105 private Cancellable txCommitTimeoutCheckSchedule;
107 private final Optional<ActorRef> roleChangeNotifier;
109 private final MessageTracker appendEntriesReplyTracker;
111 private final ShardTransactionActorFactory transactionActorFactory;
113 private final ShardSnapshotCohort snapshotCohort;
115 private final DataTreeChangeListenerSupport treeChangeSupport = new DataTreeChangeListenerSupport(this);
116 private final DataChangeListenerSupport changeSupport = new DataChangeListenerSupport(this);
118 protected Shard(final ShardIdentifier name, final Map<String, String> peerAddresses,
119 final DatastoreContext datastoreContext, final SchemaContext schemaContext) {
120 super(name.toString(), new HashMap<>(peerAddresses), Optional.of(datastoreContext.getShardRaftConfig()),
121 DataStoreVersions.CURRENT_VERSION);
123 this.name = name.toString();
124 this.datastoreContext = datastoreContext;
126 setPersistence(datastoreContext.isPersistent());
128 LOG.info("Shard created : {}, persistent : {}", name, datastoreContext.isPersistent());
130 store = new ShardDataTree(schemaContext);
132 shardMBean = ShardMBeanFactory.getShardStatsMBean(name.toString(),
133 datastoreContext.getDataStoreMXBeanType());
134 shardMBean.setShard(this);
136 if (isMetricsCaptureEnabled()) {
137 getContext().become(new MeteringBehavior(this));
140 commitCoordinator = new ShardCommitCoordinator(store,
141 datastoreContext.getShardCommitQueueExpiryTimeoutInMillis(),
142 datastoreContext.getShardTransactionCommitQueueCapacity(), self(), LOG, this.name);
144 setTransactionCommitTimeout();
146 // create a notifier actor for each cluster member
147 roleChangeNotifier = createRoleChangeNotifier(name.toString());
149 appendEntriesReplyTracker = new MessageTracker(AppendEntriesReply.class,
150 getRaftActorContext().getConfigParams().getIsolatedCheckIntervalInMillis());
152 transactionActorFactory = new ShardTransactionActorFactory(store, datastoreContext,
153 new Dispatchers(context().system().dispatchers()).getDispatcherPath(
154 Dispatchers.DispatcherType.Transaction), self(), getContext(), shardMBean);
156 snapshotCohort = new ShardSnapshotCohort(transactionActorFactory, store, LOG, this.name);
161 private void setTransactionCommitTimeout() {
162 transactionCommitTimeout = TimeUnit.MILLISECONDS.convert(
163 datastoreContext.getShardTransactionCommitTimeoutInSeconds(), TimeUnit.SECONDS) / 2;
166 public static Props props(final ShardIdentifier name, final Map<String, String> peerAddresses,
167 final DatastoreContext datastoreContext, final SchemaContext schemaContext) {
168 return Props.create(new ShardCreator(name, peerAddresses, datastoreContext, schemaContext));
171 private Optional<ActorRef> createRoleChangeNotifier(String shardId) {
172 ActorRef shardRoleChangeNotifier = this.getContext().actorOf(
173 RoleChangeNotifier.getProps(shardId), shardId + "-notifier");
174 return Optional.of(shardRoleChangeNotifier);
178 public void postStop() {
179 LOG.info("Stopping Shard {}", persistenceId());
183 if(txCommitTimeoutCheckSchedule != null) {
184 txCommitTimeoutCheckSchedule.cancel();
187 shardMBean.unregisterMBean();
191 public void onReceiveRecover(final Object message) throws Exception {
192 if(LOG.isDebugEnabled()) {
193 LOG.debug("{}: onReceiveRecover: Received message {} from {}", persistenceId(),
194 message.getClass().toString(), getSender());
197 if (message instanceof RecoveryFailure){
198 LOG.error("{}: Recovery failed because of this cause",
199 persistenceId(), ((RecoveryFailure) message).cause());
201 // Even though recovery failed, we still need to finish our recovery, eg send the
202 // ActorInitialized message and start the txCommitTimeoutCheckSchedule.
203 onRecoveryComplete();
205 super.onReceiveRecover(message);
206 if(LOG.isTraceEnabled()) {
207 appendEntriesReplyTracker.begin();
213 public void onReceiveCommand(final Object message) throws Exception {
215 MessageTracker.Context context = appendEntriesReplyTracker.received(message);
217 if(context.error().isPresent()){
218 LOG.trace("{} : AppendEntriesReply failed to arrive at the expected interval {}", persistenceId(),
223 if (CreateTransaction.SERIALIZABLE_CLASS.isInstance(message)) {
224 handleCreateTransaction(message);
225 } else if (BatchedModifications.class.isInstance(message)) {
226 handleBatchedModifications((BatchedModifications)message);
227 } else if (message instanceof ForwardedReadyTransaction) {
228 commitCoordinator.handleForwardedReadyTransaction((ForwardedReadyTransaction) message,
230 } else if (message instanceof ReadyLocalTransaction) {
231 handleReadyLocalTransaction((ReadyLocalTransaction)message);
232 } else if (CanCommitTransaction.SERIALIZABLE_CLASS.isInstance(message)) {
233 handleCanCommitTransaction(CanCommitTransaction.fromSerializable(message));
234 } else if (CommitTransaction.SERIALIZABLE_CLASS.isInstance(message)) {
235 handleCommitTransaction(CommitTransaction.fromSerializable(message));
236 } else if (AbortTransaction.SERIALIZABLE_CLASS.isInstance(message)) {
237 handleAbortTransaction(AbortTransaction.fromSerializable(message));
238 } else if (CloseTransactionChain.SERIALIZABLE_CLASS.isInstance(message)) {
239 closeTransactionChain(CloseTransactionChain.fromSerializable(message));
240 } else if (message instanceof RegisterChangeListener) {
241 changeSupport.onMessage((RegisterChangeListener) message, isLeader(), hasLeader());
242 } else if (message instanceof RegisterDataTreeChangeListener) {
243 treeChangeSupport.onMessage((RegisterDataTreeChangeListener) message, isLeader(), hasLeader());
244 } else if (message instanceof UpdateSchemaContext) {
245 updateSchemaContext((UpdateSchemaContext) message);
246 } else if (message instanceof PeerAddressResolved) {
247 PeerAddressResolved resolved = (PeerAddressResolved) message;
248 setPeerAddress(resolved.getPeerId().toString(),
249 resolved.getPeerAddress());
250 } else if (message.equals(TX_COMMIT_TIMEOUT_CHECK_MESSAGE)) {
251 handleTransactionCommitTimeoutCheck();
252 } else if(message instanceof DatastoreContext) {
253 onDatastoreContext((DatastoreContext)message);
254 } else if(message instanceof RegisterRoleChangeListener){
255 roleChangeNotifier.get().forward(message, context());
256 } else if (message instanceof FollowerInitialSyncUpStatus) {
257 shardMBean.setFollowerInitialSyncStatus(((FollowerInitialSyncUpStatus) message).isInitialSyncDone());
258 context().parent().tell(message, self());
259 } else if(GET_SHARD_MBEAN_MESSAGE.equals(message)){
260 sender().tell(getShardMBean(), self());
261 } else if(message instanceof GetShardDataTree){
262 sender().tell(store.getDataTree(), self());
264 super.onReceiveCommand(message);
271 private boolean hasLeader() {
272 return getLeaderId() != null;
275 public int getPendingTxCommitQueueSize() {
276 return commitCoordinator.getQueueSize();
280 protected Optional<ActorRef> getRoleChangeNotifier() {
281 return roleChangeNotifier;
285 protected LeaderStateChanged newLeaderStateChanged(String memberId, String leaderId, short leaderPayloadVersion) {
286 return new ShardLeaderStateChanged(memberId, leaderId,
287 isLeader() ? Optional.<DataTree>of(store.getDataTree()) : Optional.<DataTree>absent(),
288 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 void handleTransactionCommitTimeoutCheck() {
308 CohortEntry cohortEntry = commitCoordinator.getCurrentCohortEntry();
309 if(cohortEntry != null) {
310 if(cohortEntry.isExpired(transactionCommitTimeout)) {
311 LOG.warn("{}: Current transaction {} has timed out after {} ms - aborting",
312 persistenceId(), cohortEntry.getTransactionID(), transactionCommitTimeout);
314 doAbortTransaction(cohortEntry.getTransactionID(), null);
318 commitCoordinator.cleanupExpiredCohortEntries();
321 private static boolean isEmptyCommit(final DataTreeCandidate candidate) {
322 return ModificationType.UNMODIFIED.equals(candidate.getRootNode().getModificationType());
325 void continueCommit(final CohortEntry cohortEntry) {
326 final DataTreeCandidate candidate = cohortEntry.getCandidate();
328 // If we do not have any followers and we are not using persistence
329 // or if cohortEntry has no modifications
330 // we can apply modification to the state immediately
331 if ((!hasFollowers() && !persistence().isRecoveryApplicable()) || isEmptyCommit(candidate)) {
332 applyModificationToState(cohortEntry.getReplySender(), cohortEntry.getTransactionID(), candidate);
334 Shard.this.persistData(cohortEntry.getReplySender(), cohortEntry.getTransactionID(),
335 DataTreeCandidatePayload.create(candidate));
339 private void handleCommitTransaction(final CommitTransaction commit) {
340 if(!commitCoordinator.handleCommit(commit.getTransactionID(), getSender(), this)) {
341 shardMBean.incrementFailedTransactionsCount();
345 private void finishCommit(@Nonnull final ActorRef sender, @Nonnull final String transactionID, @Nonnull final CohortEntry cohortEntry) {
346 LOG.debug("{}: Finishing commit for transaction {}", persistenceId(), cohortEntry.getTransactionID());
349 cohortEntry.commit();
351 sender.tell(CommitTransactionReply.INSTANCE.toSerializable(), getSelf());
353 shardMBean.incrementCommittedTransactionCount();
354 shardMBean.setLastCommittedTransactionTime(System.currentTimeMillis());
356 } catch (Exception e) {
357 sender.tell(new akka.actor.Status.Failure(e), getSelf());
359 LOG.error("{}, An exception occurred while committing transaction {}", persistenceId(),
361 shardMBean.incrementFailedTransactionsCount();
363 commitCoordinator.currentTransactionComplete(transactionID, true);
367 private void finishCommit(@Nonnull final ActorRef sender, final @Nonnull String transactionID) {
368 // With persistence enabled, this method is called via applyState by the leader strategy
369 // after the commit has been replicated to a majority of the followers.
371 CohortEntry cohortEntry = commitCoordinator.getCohortEntryIfCurrent(transactionID);
372 if (cohortEntry == null) {
373 // The transaction is no longer the current commit. This can happen if the transaction
374 // was aborted prior, most likely due to timeout in the front-end. We need to finish
375 // committing the transaction though since it was successfully persisted and replicated
376 // however we can't use the original cohort b/c it was already preCommitted and may
377 // conflict with the current commit or may have been aborted so we commit with a new
379 cohortEntry = commitCoordinator.getAndRemoveCohortEntry(transactionID);
380 if(cohortEntry != null) {
382 store.applyForeignCandidate(transactionID, cohortEntry.getCandidate());
383 } catch (DataValidationFailedException e) {
384 shardMBean.incrementFailedTransactionsCount();
385 LOG.error("{}: Failed to re-apply transaction {}", persistenceId(), transactionID, e);
388 sender.tell(CommitTransactionReply.INSTANCE.toSerializable(), getSelf());
390 // This really shouldn't happen - it likely means that persistence or replication
391 // took so long to complete such that the cohort entry was expired from the cache.
392 IllegalStateException ex = new IllegalStateException(
393 String.format("%s: Could not finish committing transaction %s - no CohortEntry found",
394 persistenceId(), transactionID));
395 LOG.error(ex.getMessage());
396 sender.tell(new akka.actor.Status.Failure(ex), getSelf());
399 finishCommit(sender, transactionID, cohortEntry);
403 private void handleCanCommitTransaction(final CanCommitTransaction canCommit) {
404 LOG.debug("{}: Can committing transaction {}", persistenceId(), canCommit.getTransactionID());
405 commitCoordinator.handleCanCommit(canCommit.getTransactionID(), getSender(), this);
408 private void noLeaderError(String errMessage, Object message) {
409 // TODO: rather than throwing an immediate exception, we could schedule a timer to try again to make
410 // it more resilient in case we're in the process of electing a new leader.
411 getSender().tell(new akka.actor.Status.Failure(new NoShardLeaderException(errMessage, persistenceId())), getSelf());
414 protected void handleBatchedModificationsLocal(BatchedModifications batched, ActorRef sender) {
416 commitCoordinator.handleBatchedModifications(batched, sender, this);
417 } catch (Exception e) {
418 LOG.error("{}: Error handling BatchedModifications for Tx {}", persistenceId(),
419 batched.getTransactionID(), e);
420 sender.tell(new akka.actor.Status.Failure(e), getSelf());
424 private void handleBatchedModifications(BatchedModifications batched) {
425 // This message is sent to prepare the modifications transaction directly on the Shard as an
426 // optimization to avoid the extra overhead of a separate ShardTransaction actor. On the last
427 // BatchedModifications message, the caller sets the ready flag in the message indicating
428 // modifications are complete. The reply contains the cohort actor path (this actor) for the caller
429 // to initiate the 3-phase commit. This also avoids the overhead of sending an additional
430 // ReadyTransaction message.
432 // If we're not the leader then forward to the leader. This is a safety measure - we shouldn't
433 // normally get here if we're not the leader as the front-end (TransactionProxy) should determine
434 // the primary/leader shard. However with timing and caching on the front-end, there's a small
435 // window where it could have a stale leader during leadership transitions.
438 failIfIsolatedLeader(getSender());
440 handleBatchedModificationsLocal(batched, getSender());
442 ActorSelection leader = getLeader();
444 // TODO: what if this is not the first batch and leadership changed in between batched messages?
445 // We could check if the commitCoordinator already has a cached entry and forward all the previous
446 // batched modifications.
447 LOG.debug("{}: Forwarding BatchedModifications to leader {}", persistenceId(), leader);
448 leader.forward(batched, getContext());
450 noLeaderError("Could not commit transaction " + batched.getTransactionID(), batched);
455 private boolean failIfIsolatedLeader(ActorRef sender) {
456 if(isIsolatedLeader()) {
457 sender.tell(new akka.actor.Status.Failure(new NoShardLeaderException(String.format(
458 "Shard %s was the leader but has lost contact with all of its followers. Either all" +
459 " other follower nodes are down or this node is isolated by a network partition.",
460 persistenceId()))), getSelf());
467 protected boolean isIsolatedLeader() {
468 return getRaftState() == RaftState.IsolatedLeader;
471 private void handleReadyLocalTransaction(final ReadyLocalTransaction message) {
473 failIfIsolatedLeader(getSender());
476 commitCoordinator.handleReadyLocalTransaction(message, getSender(), this);
477 } catch (Exception e) {
478 LOG.error("{}: Error handling ReadyLocalTransaction for Tx {}", persistenceId(),
479 message.getTransactionID(), e);
480 getSender().tell(new akka.actor.Status.Failure(e), getSelf());
483 ActorSelection leader = getLeader();
484 if (leader != null) {
485 LOG.debug("{}: Forwarding ReadyLocalTransaction to leader {}", persistenceId(), leader);
486 message.setRemoteVersion(getCurrentBehavior().getLeaderPayloadVersion());
487 leader.forward(message, getContext());
489 noLeaderError("Could not commit transaction " + message.getTransactionID(), message);
494 private void handleAbortTransaction(final AbortTransaction abort) {
495 doAbortTransaction(abort.getTransactionID(), getSender());
498 void doAbortTransaction(final String transactionID, final ActorRef sender) {
499 commitCoordinator.handleAbort(transactionID, sender, this);
502 private void handleCreateTransaction(final Object message) {
504 createTransaction(CreateTransaction.fromSerializable(message));
505 } else if (getLeader() != null) {
506 getLeader().forward(message, getContext());
508 getSender().tell(new akka.actor.Status.Failure(new NoShardLeaderException(
509 "Could not create a shard transaction", persistenceId())), getSelf());
513 private void closeTransactionChain(final CloseTransactionChain closeTransactionChain) {
514 store.closeTransactionChain(closeTransactionChain.getTransactionChainId());
517 private ActorRef createTypedTransactionActor(int transactionType,
518 ShardTransactionIdentifier transactionId, String transactionChainId,
519 short clientVersion ) {
521 return transactionActorFactory.newShardTransaction(TransactionType.fromInt(transactionType),
522 transactionId, transactionChainId, clientVersion);
525 private void createTransaction(CreateTransaction createTransaction) {
527 if(TransactionType.fromInt(createTransaction.getTransactionType()) != TransactionType.READ_ONLY &&
528 failIfIsolatedLeader(getSender())) {
532 ActorRef transactionActor = createTransaction(createTransaction.getTransactionType(),
533 createTransaction.getTransactionId(), createTransaction.getTransactionChainId(),
534 createTransaction.getVersion());
536 getSender().tell(new CreateTransactionReply(Serialization.serializedActorPath(transactionActor),
537 createTransaction.getTransactionId()).toSerializable(), getSelf());
538 } catch (Exception e) {
539 getSender().tell(new akka.actor.Status.Failure(e), getSelf());
543 private ActorRef createTransaction(int transactionType, String remoteTransactionId,
544 String transactionChainId, short clientVersion) {
547 ShardTransactionIdentifier transactionId = new ShardTransactionIdentifier(remoteTransactionId);
549 if(LOG.isDebugEnabled()) {
550 LOG.debug("{}: Creating transaction : {} ", persistenceId(), transactionId);
553 ActorRef transactionActor = createTypedTransactionActor(transactionType, transactionId,
554 transactionChainId, clientVersion);
556 return transactionActor;
559 private void commitWithNewTransaction(final Modification modification) {
560 ReadWriteShardDataTreeTransaction tx = store.newReadWriteTransaction(modification.toString(), null);
561 modification.apply(tx.getSnapshot());
563 snapshotCohort.syncCommitTransaction(tx);
564 shardMBean.incrementCommittedTransactionCount();
565 shardMBean.setLastCommittedTransactionTime(System.currentTimeMillis());
566 } catch (Exception e) {
567 shardMBean.incrementFailedTransactionsCount();
568 LOG.error("{}: Failed to commit", persistenceId(), e);
572 private void updateSchemaContext(final UpdateSchemaContext message) {
573 updateSchemaContext(message.getSchemaContext());
577 void updateSchemaContext(final SchemaContext schemaContext) {
578 store.updateSchemaContext(schemaContext);
581 private boolean isMetricsCaptureEnabled() {
582 CommonConfig config = new CommonConfig(getContext().system().settings().config());
583 return config.isMetricCaptureEnabled();
588 public RaftActorSnapshotCohort getRaftActorSnapshotCohort() {
589 return snapshotCohort;
594 protected RaftActorRecoveryCohort getRaftActorRecoveryCohort() {
595 return new ShardRecoveryCoordinator(store, store.getSchemaContext(), persistenceId(), LOG);
599 protected void onRecoveryComplete() {
600 //notify shard manager
601 getContext().parent().tell(new ActorInitialized(), getSelf());
603 // Being paranoid here - this method should only be called once but just in case...
604 if(txCommitTimeoutCheckSchedule == null) {
605 // Schedule a message to be periodically sent to check if the current in-progress
606 // transaction should be expired and aborted.
607 FiniteDuration period = Duration.create(transactionCommitTimeout / 3, TimeUnit.MILLISECONDS);
608 txCommitTimeoutCheckSchedule = getContext().system().scheduler().schedule(
609 period, period, getSelf(),
610 TX_COMMIT_TIMEOUT_CHECK_MESSAGE, getContext().dispatcher(), ActorRef.noSender());
615 protected void applyState(final ActorRef clientActor, final String identifier, final Object data) {
616 if (data instanceof DataTreeCandidatePayload) {
617 if (clientActor == null) {
618 // No clientActor indicates a replica coming from the leader
620 store.applyForeignCandidate(identifier, ((DataTreeCandidatePayload)data).getCandidate());
621 } catch (DataValidationFailedException | IOException e) {
622 LOG.error("{}: Error applying replica {}", persistenceId(), identifier, e);
625 // Replication consensus reached, proceed to commit
626 finishCommit(clientActor, identifier);
628 } else if (data instanceof ModificationPayload) {
630 applyModificationToState(clientActor, identifier, ((ModificationPayload) data).getModification());
631 } catch (ClassNotFoundException | IOException e) {
632 LOG.error("{}: Error extracting ModificationPayload", persistenceId(), e);
634 } else if (data instanceof CompositeModificationPayload) {
635 Object modification = ((CompositeModificationPayload) data).getModification();
637 applyModificationToState(clientActor, identifier, modification);
638 } else if(data instanceof CompositeModificationByteStringPayload ){
639 Object modification = ((CompositeModificationByteStringPayload) data).getModification();
641 applyModificationToState(clientActor, identifier, modification);
643 LOG.error("{}: Unknown state received {} Class loader = {} CompositeNodeMod.ClassLoader = {}",
644 persistenceId(), data, data.getClass().getClassLoader(),
645 CompositeModificationPayload.class.getClassLoader());
649 private void applyModificationToState(ActorRef clientActor, String identifier, Object modification) {
650 if(modification == null) {
652 "{}: modification is null - this is very unexpected, clientActor = {}, identifier = {}",
653 persistenceId(), identifier, clientActor != null ? clientActor.path().toString() : null);
654 } else if(clientActor == null) {
655 // There's no clientActor to which to send a commit reply so we must be applying
656 // replicated state from the leader.
657 commitWithNewTransaction(MutableCompositeModification.fromSerializable(modification));
659 // This must be the OK to commit after replication consensus.
660 finishCommit(clientActor, identifier);
665 protected void onStateChanged() {
666 boolean isLeader = isLeader();
667 boolean hasLeader = hasLeader();
668 changeSupport.onLeadershipChange(isLeader, hasLeader);
669 treeChangeSupport.onLeadershipChange(isLeader, hasLeader);
671 // If this actor is no longer the leader close all the transaction chains
673 if(LOG.isDebugEnabled()) {
675 "{}: onStateChanged: Closing all transaction chains because shard {} is no longer the leader",
676 persistenceId(), getId());
679 store.closeAllTransactionChains();
684 protected void onLeaderChanged(String oldLeader, String newLeader) {
685 shardMBean.incrementLeadershipChangeCount();
689 public String persistenceId() {
694 ShardCommitCoordinator getCommitCoordinator() {
695 return commitCoordinator;
698 public DatastoreContext getDatastoreContext() {
699 return datastoreContext;
702 protected abstract static class AbstractShardCreator implements Creator<Shard> {
703 private static final long serialVersionUID = 1L;
705 protected final ShardIdentifier name;
706 protected final Map<String, String> peerAddresses;
707 protected final DatastoreContext datastoreContext;
708 protected final SchemaContext schemaContext;
710 protected AbstractShardCreator(final ShardIdentifier name, final Map<String, String> peerAddresses,
711 final DatastoreContext datastoreContext, final SchemaContext schemaContext) {
712 this.name = Preconditions.checkNotNull(name, "name should not be null");
713 this.peerAddresses = Preconditions.checkNotNull(peerAddresses, "peerAddresses should not be null");
714 this.datastoreContext = Preconditions.checkNotNull(datastoreContext, "dataStoreContext should not be null");
715 this.schemaContext = Preconditions.checkNotNull(schemaContext, "schemaContext should not be null");
719 private static class ShardCreator extends AbstractShardCreator {
720 private static final long serialVersionUID = 1L;
722 ShardCreator(final ShardIdentifier name, final Map<String, String> peerAddresses,
723 final DatastoreContext datastoreContext, final SchemaContext schemaContext) {
724 super(name, peerAddresses, datastoreContext, schemaContext);
728 public Shard create() throws Exception {
729 return new Shard(name, peerAddresses, datastoreContext, schemaContext);
734 public ShardDataTree getDataStore() {
739 ShardStats getShardMBean() {