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 com.google.common.util.concurrent.FutureCallback;
22 import com.google.common.util.concurrent.Futures;
23 import com.google.common.util.concurrent.ListenableFuture;
24 import java.io.IOException;
25 import java.util.HashMap;
27 import java.util.concurrent.TimeUnit;
28 import javax.annotation.Nonnull;
29 import org.opendaylight.controller.cluster.common.actor.CommonConfig;
30 import org.opendaylight.controller.cluster.common.actor.MeteringBehavior;
31 import org.opendaylight.controller.cluster.datastore.ShardCommitCoordinator.CohortEntry;
32 import org.opendaylight.controller.cluster.datastore.exceptions.NoShardLeaderException;
33 import org.opendaylight.controller.cluster.datastore.identifiers.ShardIdentifier;
34 import org.opendaylight.controller.cluster.datastore.identifiers.ShardTransactionIdentifier;
35 import org.opendaylight.controller.cluster.datastore.jmx.mbeans.shard.ShardMBeanFactory;
36 import org.opendaylight.controller.cluster.datastore.jmx.mbeans.shard.ShardStats;
37 import org.opendaylight.controller.cluster.datastore.messages.AbortTransaction;
38 import org.opendaylight.controller.cluster.datastore.messages.AbortTransactionReply;
39 import org.opendaylight.controller.cluster.datastore.messages.ActorInitialized;
40 import org.opendaylight.controller.cluster.datastore.messages.BatchedModifications;
41 import org.opendaylight.controller.cluster.datastore.messages.CanCommitTransaction;
42 import org.opendaylight.controller.cluster.datastore.messages.CloseTransactionChain;
43 import org.opendaylight.controller.cluster.datastore.messages.CommitTransaction;
44 import org.opendaylight.controller.cluster.datastore.messages.CommitTransactionReply;
45 import org.opendaylight.controller.cluster.datastore.messages.CreateTransaction;
46 import org.opendaylight.controller.cluster.datastore.messages.CreateTransactionReply;
47 import org.opendaylight.controller.cluster.datastore.messages.ForwardedReadyTransaction;
48 import org.opendaylight.controller.cluster.datastore.messages.PeerAddressResolved;
49 import org.opendaylight.controller.cluster.datastore.messages.ReadyLocalTransaction;
50 import org.opendaylight.controller.cluster.datastore.messages.RegisterChangeListener;
51 import org.opendaylight.controller.cluster.datastore.messages.RegisterDataTreeChangeListener;
52 import org.opendaylight.controller.cluster.datastore.messages.ShardLeaderStateChanged;
53 import org.opendaylight.controller.cluster.datastore.messages.UpdateSchemaContext;
54 import org.opendaylight.controller.cluster.datastore.modification.Modification;
55 import org.opendaylight.controller.cluster.datastore.modification.ModificationPayload;
56 import org.opendaylight.controller.cluster.datastore.modification.MutableCompositeModification;
57 import org.opendaylight.controller.cluster.datastore.utils.Dispatchers;
58 import org.opendaylight.controller.cluster.datastore.utils.MessageTracker;
59 import org.opendaylight.controller.cluster.notifications.LeaderStateChanged;
60 import org.opendaylight.controller.cluster.notifications.RegisterRoleChangeListener;
61 import org.opendaylight.controller.cluster.notifications.RoleChangeNotifier;
62 import org.opendaylight.controller.cluster.raft.RaftActor;
63 import org.opendaylight.controller.cluster.raft.RaftActorRecoveryCohort;
64 import org.opendaylight.controller.cluster.raft.RaftActorSnapshotCohort;
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.protobuff.client.messages.CompositeModificationByteStringPayload;
68 import org.opendaylight.controller.cluster.raft.protobuff.client.messages.CompositeModificationPayload;
69 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTree;
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.model.api.SchemaContext;
74 import scala.concurrent.duration.Duration;
75 import scala.concurrent.duration.FiniteDuration;
78 * A Shard represents a portion of the logical data tree <br/>
80 * Our Shard uses InMemoryDataTree as it's internal representation and delegates all requests it
83 public class Shard extends RaftActor {
85 private static final Object TX_COMMIT_TIMEOUT_CHECK_MESSAGE = "txCommitTimeoutCheck";
88 static final String DEFAULT_NAME = "default";
90 // The state of this Shard
91 private final ShardDataTree store;
93 /// The name of this shard
94 private final String name;
96 private final ShardStats shardMBean;
98 private DatastoreContext datastoreContext;
100 private final ShardCommitCoordinator commitCoordinator;
102 private long transactionCommitTimeout;
104 private Cancellable txCommitTimeoutCheckSchedule;
106 private final Optional<ActorRef> roleChangeNotifier;
108 private final MessageTracker appendEntriesReplyTracker;
110 private final ShardTransactionActorFactory transactionActorFactory;
112 private final ShardSnapshotCohort snapshotCohort;
114 private final DataTreeChangeListenerSupport treeChangeSupport = new DataTreeChangeListenerSupport(this);
115 private final DataChangeListenerSupport changeSupport = new DataChangeListenerSupport(this);
117 protected Shard(final ShardIdentifier name, final Map<String, String> peerAddresses,
118 final DatastoreContext datastoreContext, final SchemaContext schemaContext) {
119 super(name.toString(), new HashMap<>(peerAddresses), Optional.of(datastoreContext.getShardRaftConfig()));
121 this.name = name.toString();
122 this.datastoreContext = datastoreContext;
124 setPersistence(datastoreContext.isPersistent());
126 LOG.info("Shard created : {}, persistent : {}", name, datastoreContext.isPersistent());
128 store = new ShardDataTree(schemaContext);
130 shardMBean = ShardMBeanFactory.getShardStatsMBean(name.toString(),
131 datastoreContext.getDataStoreMXBeanType());
132 shardMBean.setShardActor(getSelf());
134 if (isMetricsCaptureEnabled()) {
135 getContext().become(new MeteringBehavior(this));
138 commitCoordinator = new ShardCommitCoordinator(store,
139 TimeUnit.SECONDS.convert(5, TimeUnit.MINUTES),
140 datastoreContext.getShardTransactionCommitQueueCapacity(), self(), LOG, this.name);
142 setTransactionCommitTimeout();
144 // create a notifier actor for each cluster member
145 roleChangeNotifier = createRoleChangeNotifier(name.toString());
147 appendEntriesReplyTracker = new MessageTracker(AppendEntriesReply.class,
148 getRaftActorContext().getConfigParams().getIsolatedCheckIntervalInMillis());
150 transactionActorFactory = new ShardTransactionActorFactory(store, datastoreContext,
151 new Dispatchers(context().system().dispatchers()).getDispatcherPath(
152 Dispatchers.DispatcherType.Transaction), self(), getContext(), shardMBean);
154 snapshotCohort = new ShardSnapshotCohort(transactionActorFactory, store, LOG, this.name);
157 private void setTransactionCommitTimeout() {
158 transactionCommitTimeout = TimeUnit.MILLISECONDS.convert(
159 datastoreContext.getShardTransactionCommitTimeoutInSeconds(), TimeUnit.SECONDS);
162 public static Props props(final ShardIdentifier name,
163 final Map<String, String> peerAddresses,
164 final DatastoreContext datastoreContext, final SchemaContext schemaContext) {
165 Preconditions.checkNotNull(name, "name should not be null");
166 Preconditions.checkNotNull(peerAddresses, "peerAddresses should not be null");
167 Preconditions.checkNotNull(datastoreContext, "dataStoreContext should not be null");
168 Preconditions.checkNotNull(schemaContext, "schemaContext should not be null");
170 return Props.create(new ShardCreator(name, peerAddresses, datastoreContext, schemaContext));
173 private Optional<ActorRef> createRoleChangeNotifier(String shardId) {
174 ActorRef shardRoleChangeNotifier = this.getContext().actorOf(
175 RoleChangeNotifier.getProps(shardId), shardId + "-notifier");
176 return Optional.of(shardRoleChangeNotifier);
180 public void postStop() {
181 LOG.info("Stopping Shard {}", persistenceId());
185 if(txCommitTimeoutCheckSchedule != null) {
186 txCommitTimeoutCheckSchedule.cancel();
189 shardMBean.unregisterMBean();
193 public void onReceiveRecover(final Object message) throws Exception {
194 if(LOG.isDebugEnabled()) {
195 LOG.debug("{}: onReceiveRecover: Received message {} from {}", persistenceId(),
196 message.getClass().toString(), getSender());
199 if (message instanceof RecoveryFailure){
200 LOG.error("{}: Recovery failed because of this cause",
201 persistenceId(), ((RecoveryFailure) message).cause());
203 // Even though recovery failed, we still need to finish our recovery, eg send the
204 // ActorInitialized message and start the txCommitTimeoutCheckSchedule.
205 onRecoveryComplete();
207 super.onReceiveRecover(message);
208 if(LOG.isTraceEnabled()) {
209 appendEntriesReplyTracker.begin();
215 public void onReceiveCommand(final Object message) throws Exception {
217 MessageTracker.Context context = appendEntriesReplyTracker.received(message);
219 if(context.error().isPresent()){
220 LOG.trace("{} : AppendEntriesReply failed to arrive at the expected interval {}", persistenceId(),
225 if (CreateTransaction.SERIALIZABLE_CLASS.isInstance(message)) {
226 handleCreateTransaction(message);
227 } else if (BatchedModifications.class.isInstance(message)) {
228 handleBatchedModifications((BatchedModifications)message);
229 } else if (message instanceof ForwardedReadyTransaction) {
230 commitCoordinator.handleForwardedReadyTransaction((ForwardedReadyTransaction) message,
232 } else if (message instanceof ReadyLocalTransaction) {
233 handleReadyLocalTransaction((ReadyLocalTransaction)message);
234 } else if (CanCommitTransaction.SERIALIZABLE_CLASS.isInstance(message)) {
235 handleCanCommitTransaction(CanCommitTransaction.fromSerializable(message));
236 } else if (CommitTransaction.SERIALIZABLE_CLASS.isInstance(message)) {
237 handleCommitTransaction(CommitTransaction.fromSerializable(message));
238 } else if (AbortTransaction.SERIALIZABLE_CLASS.isInstance(message)) {
239 handleAbortTransaction(AbortTransaction.fromSerializable(message));
240 } else if (CloseTransactionChain.SERIALIZABLE_CLASS.isInstance(message)) {
241 closeTransactionChain(CloseTransactionChain.fromSerializable(message));
242 } else if (message instanceof RegisterChangeListener) {
243 changeSupport.onMessage((RegisterChangeListener) message, isLeader());
244 } else if (message instanceof RegisterDataTreeChangeListener) {
245 treeChangeSupport.onMessage((RegisterDataTreeChangeListener) message, isLeader());
246 } else if (message instanceof UpdateSchemaContext) {
247 updateSchemaContext((UpdateSchemaContext) message);
248 } else if (message instanceof PeerAddressResolved) {
249 PeerAddressResolved resolved = (PeerAddressResolved) message;
250 setPeerAddress(resolved.getPeerId().toString(),
251 resolved.getPeerAddress());
252 } else if (message.equals(TX_COMMIT_TIMEOUT_CHECK_MESSAGE)) {
253 handleTransactionCommitTimeoutCheck();
254 } else if(message instanceof DatastoreContext) {
255 onDatastoreContext((DatastoreContext)message);
256 } else if(message instanceof RegisterRoleChangeListener){
257 roleChangeNotifier.get().forward(message, context());
258 } else if (message instanceof FollowerInitialSyncUpStatus){
259 shardMBean.setFollowerInitialSyncStatus(((FollowerInitialSyncUpStatus) message).isInitialSyncDone());
260 context().parent().tell(message, self());
262 super.onReceiveCommand(message);
270 protected Optional<ActorRef> getRoleChangeNotifier() {
271 return roleChangeNotifier;
275 protected LeaderStateChanged newLeaderStateChanged(String memberId, String leaderId) {
276 return new ShardLeaderStateChanged(memberId, leaderId,
277 isLeader() ? Optional.<DataTree>of(store.getDataTree()) : Optional.<DataTree>absent());
280 private void onDatastoreContext(DatastoreContext context) {
281 datastoreContext = context;
283 commitCoordinator.setQueueCapacity(datastoreContext.getShardTransactionCommitQueueCapacity());
285 setTransactionCommitTimeout();
287 if(datastoreContext.isPersistent() && !persistence().isRecoveryApplicable()) {
288 setPersistence(true);
289 } else if(!datastoreContext.isPersistent() && persistence().isRecoveryApplicable()) {
290 setPersistence(false);
293 updateConfigParams(datastoreContext.getShardRaftConfig());
296 private void handleTransactionCommitTimeoutCheck() {
297 CohortEntry cohortEntry = commitCoordinator.getCurrentCohortEntry();
298 if(cohortEntry != null) {
299 long elapsed = System.currentTimeMillis() - cohortEntry.getLastAccessTime();
300 if(elapsed > transactionCommitTimeout) {
301 LOG.warn("{}: Current transaction {} has timed out after {} ms - aborting",
302 persistenceId(), cohortEntry.getTransactionID(), transactionCommitTimeout);
304 doAbortTransaction(cohortEntry.getTransactionID(), null);
309 private static boolean isEmptyCommit(final DataTreeCandidate candidate) {
310 return ModificationType.UNMODIFIED.equals(candidate.getRootNode().getModificationType());
313 void continueCommit(final CohortEntry cohortEntry) throws Exception {
314 final DataTreeCandidate candidate = cohortEntry.getCohort().getCandidate();
316 // If we do not have any followers and we are not using persistence
317 // or if cohortEntry has no modifications
318 // we can apply modification to the state immediately
319 if ((!hasFollowers() && !persistence().isRecoveryApplicable()) || isEmptyCommit(candidate)) {
320 applyModificationToState(getSender(), cohortEntry.getTransactionID(), candidate);
322 Shard.this.persistData(getSender(), cohortEntry.getTransactionID(),
323 DataTreeCandidatePayload.create(candidate));
327 private void handleCommitTransaction(final CommitTransaction commit) {
328 if(!commitCoordinator.handleCommit(commit.getTransactionID(), getSender(), this)) {
329 shardMBean.incrementFailedTransactionsCount();
333 private void finishCommit(@Nonnull final ActorRef sender, @Nonnull final String transactionID, @Nonnull final CohortEntry cohortEntry) {
334 LOG.debug("{}: Finishing commit for transaction {}", persistenceId(), cohortEntry.getTransactionID());
337 // We block on the future here so we don't have to worry about possibly accessing our
338 // state on a different thread outside of our dispatcher. Also, the data store
339 // currently uses a same thread executor anyway.
340 cohortEntry.getCohort().commit().get();
342 sender.tell(CommitTransactionReply.INSTANCE.toSerializable(), getSelf());
344 shardMBean.incrementCommittedTransactionCount();
345 shardMBean.setLastCommittedTransactionTime(System.currentTimeMillis());
347 } catch (Exception e) {
348 sender.tell(new akka.actor.Status.Failure(e), getSelf());
350 LOG.error("{}, An exception occurred while committing transaction {}", persistenceId(),
352 shardMBean.incrementFailedTransactionsCount();
354 commitCoordinator.currentTransactionComplete(transactionID, true);
358 private void finishCommit(@Nonnull final ActorRef sender, final @Nonnull String transactionID) {
359 // With persistence enabled, this method is called via applyState by the leader strategy
360 // after the commit has been replicated to a majority of the followers.
362 CohortEntry cohortEntry = commitCoordinator.getCohortEntryIfCurrent(transactionID);
363 if (cohortEntry == null) {
364 // The transaction is no longer the current commit. This can happen if the transaction
365 // was aborted prior, most likely due to timeout in the front-end. We need to finish
366 // committing the transaction though since it was successfully persisted and replicated
367 // however we can't use the original cohort b/c it was already preCommitted and may
368 // conflict with the current commit or may have been aborted so we commit with a new
370 cohortEntry = commitCoordinator.getAndRemoveCohortEntry(transactionID);
371 if(cohortEntry != null) {
373 store.applyForeignCandidate(transactionID, cohortEntry.getCohort().getCandidate());
374 } catch (DataValidationFailedException e) {
375 shardMBean.incrementFailedTransactionsCount();
376 LOG.error("{}: Failed to re-apply transaction {}", persistenceId(), transactionID, e);
379 sender.tell(CommitTransactionReply.INSTANCE.toSerializable(), getSelf());
381 // This really shouldn't happen - it likely means that persistence or replication
382 // took so long to complete such that the cohort entry was expired from the cache.
383 IllegalStateException ex = new IllegalStateException(
384 String.format("%s: Could not finish committing transaction %s - no CohortEntry found",
385 persistenceId(), transactionID));
386 LOG.error(ex.getMessage());
387 sender.tell(new akka.actor.Status.Failure(ex), getSelf());
390 finishCommit(sender, transactionID, cohortEntry);
394 private void handleCanCommitTransaction(final CanCommitTransaction canCommit) {
395 LOG.debug("{}: Can committing transaction {}", persistenceId(), canCommit.getTransactionID());
396 commitCoordinator.handleCanCommit(canCommit.getTransactionID(), getSender(), this);
399 private void noLeaderError(Object message) {
400 // TODO: rather than throwing an immediate exception, we could schedule a timer to try again to make
401 // it more resilient in case we're in the process of electing a new leader.
402 getSender().tell(new akka.actor.Status.Failure(new NoShardLeaderException(String.format(
403 "Could not find the leader for shard %s. This typically happens" +
404 " when the system is coming up or recovering and a leader is being elected. Try again" +
405 " later.", persistenceId()))), getSelf());
408 private void handleBatchedModifications(BatchedModifications batched) {
409 // This message is sent to prepare the modificationsa transaction directly on the Shard as an
410 // optimization to avoid the extra overhead of a separate ShardTransaction actor. On the last
411 // BatchedModifications message, the caller sets the ready flag in the message indicating
412 // modifications are complete. The reply contains the cohort actor path (this actor) for the caller
413 // to initiate the 3-phase commit. This also avoids the overhead of sending an additional
414 // ReadyTransaction message.
416 // If we're not the leader then forward to the leader. This is a safety measure - we shouldn't
417 // normally get here if we're not the leader as the front-end (TransactionProxy) should determine
418 // the primary/leader shard. However with timing and caching on the front-end, there's a small
419 // window where it could have a stale leader during leadership transitions.
423 commitCoordinator.handleBatchedModifications(batched, getSender(), this);
424 } catch (Exception e) {
425 LOG.error("{}: Error handling BatchedModifications for Tx {}", persistenceId(),
426 batched.getTransactionID(), e);
427 getSender().tell(new akka.actor.Status.Failure(e), getSelf());
430 ActorSelection leader = getLeader();
432 // TODO: what if this is not the first batch and leadership changed in between batched messages?
433 // We could check if the commitCoordinator already has a cached entry and forward all the previous
434 // batched modifications.
435 LOG.debug("{}: Forwarding BatchedModifications to leader {}", persistenceId(), leader);
436 leader.forward(batched, getContext());
438 noLeaderError(batched);
443 private void handleReadyLocalTransaction(final ReadyLocalTransaction message) {
446 commitCoordinator.handleReadyLocalTransaction(message, getSender(), this);
447 } catch (Exception e) {
448 LOG.error("{}: Error handling LocalModifications for Tx {}", persistenceId(),
449 message.getTransactionID(), e);
450 getSender().tell(new akka.actor.Status.Failure(e), getSelf());
453 ActorSelection leader = getLeader();
454 if (leader != null) {
455 LOG.debug("{}: Forwarding LocalModifications to leader {}", persistenceId(), leader);
456 leader.forward(message, getContext());
458 noLeaderError(message);
463 private void handleAbortTransaction(final AbortTransaction abort) {
464 doAbortTransaction(abort.getTransactionID(), getSender());
467 void doAbortTransaction(final String transactionID, final ActorRef sender) {
468 final CohortEntry cohortEntry = commitCoordinator.getCohortEntryIfCurrent(transactionID);
469 if(cohortEntry != null) {
470 LOG.debug("{}: Aborting transaction {}", persistenceId(), transactionID);
472 // We don't remove the cached cohort entry here (ie pass false) in case the Tx was
473 // aborted during replication in which case we may still commit locally if replication
475 commitCoordinator.currentTransactionComplete(transactionID, false);
477 final ListenableFuture<Void> future = cohortEntry.getCohort().abort();
478 final ActorRef self = getSelf();
480 Futures.addCallback(future, new FutureCallback<Void>() {
482 public void onSuccess(final Void v) {
483 shardMBean.incrementAbortTransactionsCount();
486 sender.tell(AbortTransactionReply.INSTANCE.toSerializable(), self);
491 public void onFailure(final Throwable t) {
492 LOG.error("{}: An exception happened during abort", persistenceId(), t);
495 sender.tell(new akka.actor.Status.Failure(t), self);
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(String.format(
509 "Could not find leader for shard %s so transaction cannot be created. This typically happens" +
510 " when the system is coming up or recovering and a leader is being elected. Try again" +
511 " later.", persistenceId()))), getSelf());
515 private void closeTransactionChain(final CloseTransactionChain closeTransactionChain) {
516 store.closeTransactionChain(closeTransactionChain.getTransactionChainId());
519 private ActorRef createTypedTransactionActor(int transactionType,
520 ShardTransactionIdentifier transactionId, String transactionChainId,
521 short clientVersion ) {
523 return transactionActorFactory.newShardTransaction(TransactionType.fromInt(transactionType),
524 transactionId, transactionChainId, clientVersion);
527 private void createTransaction(CreateTransaction createTransaction) {
529 ActorRef transactionActor = createTransaction(createTransaction.getTransactionType(),
530 createTransaction.getTransactionId(), createTransaction.getTransactionChainId(),
531 createTransaction.getVersion());
533 getSender().tell(new CreateTransactionReply(Serialization.serializedActorPath(transactionActor),
534 createTransaction.getTransactionId()).toSerializable(), getSelf());
535 } catch (Exception e) {
536 getSender().tell(new akka.actor.Status.Failure(e), getSelf());
540 private ActorRef createTransaction(int transactionType, String remoteTransactionId,
541 String transactionChainId, short clientVersion) {
544 ShardTransactionIdentifier transactionId = new ShardTransactionIdentifier(remoteTransactionId);
546 if(LOG.isDebugEnabled()) {
547 LOG.debug("{}: Creating transaction : {} ", persistenceId(), transactionId);
550 ActorRef transactionActor = createTypedTransactionActor(transactionType, transactionId,
551 transactionChainId, clientVersion);
553 return transactionActor;
556 private void commitWithNewTransaction(final Modification modification) {
557 ReadWriteShardDataTreeTransaction tx = store.newReadWriteTransaction(modification.toString(), null);
558 modification.apply(tx.getSnapshot());
560 snapshotCohort.syncCommitTransaction(tx);
561 shardMBean.incrementCommittedTransactionCount();
562 shardMBean.setLastCommittedTransactionTime(System.currentTimeMillis());
563 } catch (Exception e) {
564 shardMBean.incrementFailedTransactionsCount();
565 LOG.error("{}: Failed to commit", persistenceId(), e);
569 private void updateSchemaContext(final UpdateSchemaContext message) {
570 updateSchemaContext(message.getSchemaContext());
574 void updateSchemaContext(final SchemaContext schemaContext) {
575 store.updateSchemaContext(schemaContext);
578 private boolean isMetricsCaptureEnabled() {
579 CommonConfig config = new CommonConfig(getContext().system().settings().config());
580 return config.isMetricCaptureEnabled();
584 protected RaftActorSnapshotCohort getRaftActorSnapshotCohort() {
585 return snapshotCohort;
590 protected RaftActorRecoveryCohort getRaftActorRecoveryCohort() {
591 return new ShardRecoveryCoordinator(store, persistenceId(), LOG);
595 protected void onRecoveryComplete() {
596 //notify shard manager
597 getContext().parent().tell(new ActorInitialized(), getSelf());
599 // Being paranoid here - this method should only be called once but just in case...
600 if(txCommitTimeoutCheckSchedule == null) {
601 // Schedule a message to be periodically sent to check if the current in-progress
602 // transaction should be expired and aborted.
603 FiniteDuration period = Duration.create(transactionCommitTimeout / 3, TimeUnit.MILLISECONDS);
604 txCommitTimeoutCheckSchedule = getContext().system().scheduler().schedule(
605 period, period, getSelf(),
606 TX_COMMIT_TIMEOUT_CHECK_MESSAGE, getContext().dispatcher(), ActorRef.noSender());
611 protected void applyState(final ActorRef clientActor, final String identifier, final Object data) {
612 if (data instanceof DataTreeCandidatePayload) {
613 if (clientActor == null) {
614 // No clientActor indicates a replica coming from the leader
616 store.applyForeignCandidate(identifier, ((DataTreeCandidatePayload)data).getCandidate());
617 } catch (DataValidationFailedException | IOException e) {
618 LOG.error("{}: Error applying replica {}", persistenceId(), identifier, e);
621 // Replication consensus reached, proceed to commit
622 finishCommit(clientActor, identifier);
624 } else if (data instanceof ModificationPayload) {
626 applyModificationToState(clientActor, identifier, ((ModificationPayload) data).getModification());
627 } catch (ClassNotFoundException | IOException e) {
628 LOG.error("{}: Error extracting ModificationPayload", persistenceId(), e);
630 } else if (data instanceof CompositeModificationPayload) {
631 Object modification = ((CompositeModificationPayload) data).getModification();
633 applyModificationToState(clientActor, identifier, modification);
634 } else if(data instanceof CompositeModificationByteStringPayload ){
635 Object modification = ((CompositeModificationByteStringPayload) data).getModification();
637 applyModificationToState(clientActor, identifier, modification);
639 LOG.error("{}: Unknown state received {} Class loader = {} CompositeNodeMod.ClassLoader = {}",
640 persistenceId(), data, data.getClass().getClassLoader(),
641 CompositeModificationPayload.class.getClassLoader());
645 private void applyModificationToState(ActorRef clientActor, String identifier, Object modification) {
646 if(modification == null) {
648 "{}: modification is null - this is very unexpected, clientActor = {}, identifier = {}",
649 persistenceId(), identifier, clientActor != null ? clientActor.path().toString() : null);
650 } else if(clientActor == null) {
651 // There's no clientActor to which to send a commit reply so we must be applying
652 // replicated state from the leader.
653 commitWithNewTransaction(MutableCompositeModification.fromSerializable(modification));
655 // This must be the OK to commit after replication consensus.
656 finishCommit(clientActor, identifier);
661 protected void onStateChanged() {
662 boolean isLeader = isLeader();
663 changeSupport.onLeadershipChange(isLeader);
664 treeChangeSupport.onLeadershipChange(isLeader);
666 // If this actor is no longer the leader close all the transaction chains
668 if(LOG.isDebugEnabled()) {
670 "{}: onStateChanged: Closing all transaction chains because shard {} is no longer the leader",
671 persistenceId(), getId());
674 store.closeAllTransactionChains();
679 protected void onLeaderChanged(String oldLeader, String newLeader) {
680 shardMBean.incrementLeadershipChangeCount();
684 public String persistenceId() {
689 ShardCommitCoordinator getCommitCoordinator() {
690 return commitCoordinator;
694 private static class ShardCreator implements Creator<Shard> {
696 private static final long serialVersionUID = 1L;
698 final ShardIdentifier name;
699 final Map<String, String> peerAddresses;
700 final DatastoreContext datastoreContext;
701 final SchemaContext schemaContext;
703 ShardCreator(final ShardIdentifier name, final Map<String, String> peerAddresses,
704 final DatastoreContext datastoreContext, final SchemaContext schemaContext) {
706 this.peerAddresses = peerAddresses;
707 this.datastoreContext = datastoreContext;
708 this.schemaContext = schemaContext;
712 public Shard create() throws Exception {
713 return new Shard(name, peerAddresses, datastoreContext, schemaContext);
718 public ShardDataTree getDataStore() {
723 ShardStats getShardMBean() {