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.RegisterChangeListener;
50 import org.opendaylight.controller.cluster.datastore.messages.RegisterDataTreeChangeListener;
51 import org.opendaylight.controller.cluster.datastore.messages.ShardLeaderStateChanged;
52 import org.opendaylight.controller.cluster.datastore.messages.UpdateSchemaContext;
53 import org.opendaylight.controller.cluster.datastore.modification.Modification;
54 import org.opendaylight.controller.cluster.datastore.modification.ModificationPayload;
55 import org.opendaylight.controller.cluster.datastore.modification.MutableCompositeModification;
56 import org.opendaylight.controller.cluster.datastore.utils.Dispatchers;
57 import org.opendaylight.controller.cluster.datastore.utils.MessageTracker;
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.base.messages.FollowerInitialSyncUpStatus;
65 import org.opendaylight.controller.cluster.raft.messages.AppendEntriesReply;
66 import org.opendaylight.controller.cluster.raft.protobuff.client.messages.CompositeModificationByteStringPayload;
67 import org.opendaylight.controller.cluster.raft.protobuff.client.messages.CompositeModificationPayload;
68 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTree;
69 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidate;
70 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataValidationFailedException;
71 import org.opendaylight.yangtools.yang.data.api.schema.tree.ModificationType;
72 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
73 import scala.concurrent.duration.Duration;
74 import scala.concurrent.duration.FiniteDuration;
77 * A Shard represents a portion of the logical data tree <br/>
79 * Our Shard uses InMemoryDataTree as it's internal representation and delegates all requests it
82 public class Shard extends RaftActor {
84 private static final Object TX_COMMIT_TIMEOUT_CHECK_MESSAGE = "txCommitTimeoutCheck";
87 static final String DEFAULT_NAME = "default";
89 // The state of this Shard
90 private final ShardDataTree store;
92 /// The name of this shard
93 private final String name;
95 private final ShardStats shardMBean;
97 private DatastoreContext datastoreContext;
99 private final ShardCommitCoordinator commitCoordinator;
101 private long transactionCommitTimeout;
103 private Cancellable txCommitTimeoutCheckSchedule;
105 private final Optional<ActorRef> roleChangeNotifier;
107 private final MessageTracker appendEntriesReplyTracker;
109 private final ShardTransactionActorFactory transactionActorFactory;
111 private final ShardSnapshotCohort snapshotCohort;
113 private final DataTreeChangeListenerSupport treeChangeSupport = new DataTreeChangeListenerSupport(this);
114 private final DataChangeListenerSupport changeSupport = new DataChangeListenerSupport(this);
116 protected Shard(final ShardIdentifier name, final Map<String, String> peerAddresses,
117 final DatastoreContext datastoreContext, final SchemaContext schemaContext) {
118 super(name.toString(), new HashMap<>(peerAddresses), Optional.of(datastoreContext.getShardRaftConfig()));
120 this.name = name.toString();
121 this.datastoreContext = datastoreContext;
123 setPersistence(datastoreContext.isPersistent());
125 LOG.info("Shard created : {}, persistent : {}", name, datastoreContext.isPersistent());
127 store = new ShardDataTree(schemaContext);
129 shardMBean = ShardMBeanFactory.getShardStatsMBean(name.toString(),
130 datastoreContext.getDataStoreMXBeanType());
131 shardMBean.setShardActor(getSelf());
133 if (isMetricsCaptureEnabled()) {
134 getContext().become(new MeteringBehavior(this));
137 commitCoordinator = new ShardCommitCoordinator(store,
138 TimeUnit.SECONDS.convert(5, TimeUnit.MINUTES),
139 datastoreContext.getShardTransactionCommitQueueCapacity(), self(), LOG, this.name);
141 setTransactionCommitTimeout();
143 // create a notifier actor for each cluster member
144 roleChangeNotifier = createRoleChangeNotifier(name.toString());
146 appendEntriesReplyTracker = new MessageTracker(AppendEntriesReply.class,
147 getRaftActorContext().getConfigParams().getIsolatedCheckIntervalInMillis());
149 transactionActorFactory = new ShardTransactionActorFactory(store, datastoreContext,
150 new Dispatchers(context().system().dispatchers()).getDispatcherPath(
151 Dispatchers.DispatcherType.Transaction), self(), getContext(), shardMBean);
153 snapshotCohort = new ShardSnapshotCohort(transactionActorFactory, store, LOG, this.name);
156 private void setTransactionCommitTimeout() {
157 transactionCommitTimeout = TimeUnit.MILLISECONDS.convert(
158 datastoreContext.getShardTransactionCommitTimeoutInSeconds(), TimeUnit.SECONDS);
161 public static Props props(final ShardIdentifier name,
162 final Map<String, String> peerAddresses,
163 final DatastoreContext datastoreContext, final SchemaContext schemaContext) {
164 Preconditions.checkNotNull(name, "name should not be null");
165 Preconditions.checkNotNull(peerAddresses, "peerAddresses should not be null");
166 Preconditions.checkNotNull(datastoreContext, "dataStoreContext should not be null");
167 Preconditions.checkNotNull(schemaContext, "schemaContext should not be null");
169 return Props.create(new ShardCreator(name, peerAddresses, datastoreContext, schemaContext));
172 private Optional<ActorRef> createRoleChangeNotifier(String shardId) {
173 ActorRef shardRoleChangeNotifier = this.getContext().actorOf(
174 RoleChangeNotifier.getProps(shardId), shardId + "-notifier");
175 return Optional.of(shardRoleChangeNotifier);
179 public void postStop() {
180 LOG.info("Stopping Shard {}", persistenceId());
184 if(txCommitTimeoutCheckSchedule != null) {
185 txCommitTimeoutCheckSchedule.cancel();
188 shardMBean.unregisterMBean();
192 public void onReceiveRecover(final Object message) throws Exception {
193 if(LOG.isDebugEnabled()) {
194 LOG.debug("{}: onReceiveRecover: Received message {} from {}", persistenceId(),
195 message.getClass().toString(), getSender());
198 if (message instanceof RecoveryFailure){
199 LOG.error("{}: Recovery failed because of this cause",
200 persistenceId(), ((RecoveryFailure) message).cause());
202 // Even though recovery failed, we still need to finish our recovery, eg send the
203 // ActorInitialized message and start the txCommitTimeoutCheckSchedule.
204 onRecoveryComplete();
206 super.onReceiveRecover(message);
207 if(LOG.isTraceEnabled()) {
208 appendEntriesReplyTracker.begin();
214 public void onReceiveCommand(final Object message) throws Exception {
216 MessageTracker.Context context = appendEntriesReplyTracker.received(message);
218 if(context.error().isPresent()){
219 LOG.trace("{} : AppendEntriesReply failed to arrive at the expected interval {}", persistenceId(),
224 if (CreateTransaction.SERIALIZABLE_CLASS.isInstance(message)) {
225 handleCreateTransaction(message);
226 } else if (BatchedModifications.class.isInstance(message)) {
227 handleBatchedModifications((BatchedModifications)message);
228 } else if (message instanceof ForwardedReadyTransaction) {
229 commitCoordinator.handleForwardedReadyTransaction((ForwardedReadyTransaction) message,
231 } else if (CanCommitTransaction.SERIALIZABLE_CLASS.isInstance(message)) {
232 handleCanCommitTransaction(CanCommitTransaction.fromSerializable(message));
233 } else if (CommitTransaction.SERIALIZABLE_CLASS.isInstance(message)) {
234 handleCommitTransaction(CommitTransaction.fromSerializable(message));
235 } else if (AbortTransaction.SERIALIZABLE_CLASS.isInstance(message)) {
236 handleAbortTransaction(AbortTransaction.fromSerializable(message));
237 } else if (CloseTransactionChain.SERIALIZABLE_CLASS.isInstance(message)) {
238 closeTransactionChain(CloseTransactionChain.fromSerializable(message));
239 } else if (message instanceof RegisterChangeListener) {
240 changeSupport.onMessage((RegisterChangeListener) message, isLeader());
241 } else if (message instanceof RegisterDataTreeChangeListener) {
242 treeChangeSupport.onMessage((RegisterDataTreeChangeListener) message, isLeader());
243 } else if (message instanceof UpdateSchemaContext) {
244 updateSchemaContext((UpdateSchemaContext) message);
245 } else if (message instanceof PeerAddressResolved) {
246 PeerAddressResolved resolved = (PeerAddressResolved) message;
247 setPeerAddress(resolved.getPeerId().toString(),
248 resolved.getPeerAddress());
249 } else if (message.equals(TX_COMMIT_TIMEOUT_CHECK_MESSAGE)) {
250 handleTransactionCommitTimeoutCheck();
251 } else if(message instanceof DatastoreContext) {
252 onDatastoreContext((DatastoreContext)message);
253 } else if(message instanceof RegisterRoleChangeListener){
254 roleChangeNotifier.get().forward(message, context());
255 } else if (message instanceof FollowerInitialSyncUpStatus){
256 shardMBean.setFollowerInitialSyncStatus(((FollowerInitialSyncUpStatus) message).isInitialSyncDone());
257 context().parent().tell(message, self());
259 super.onReceiveCommand(message);
267 protected Optional<ActorRef> getRoleChangeNotifier() {
268 return roleChangeNotifier;
272 protected LeaderStateChanged newLeaderStateChanged(String memberId, String leaderId) {
273 return new ShardLeaderStateChanged(memberId, leaderId,
274 isLeader() ? Optional.<DataTree>of(store.getDataTree()) : Optional.<DataTree>absent());
277 private void onDatastoreContext(DatastoreContext context) {
278 datastoreContext = context;
280 commitCoordinator.setQueueCapacity(datastoreContext.getShardTransactionCommitQueueCapacity());
282 setTransactionCommitTimeout();
284 if(datastoreContext.isPersistent() && !persistence().isRecoveryApplicable()) {
285 setPersistence(true);
286 } else if(!datastoreContext.isPersistent() && persistence().isRecoveryApplicable()) {
287 setPersistence(false);
290 updateConfigParams(datastoreContext.getShardRaftConfig());
293 private void handleTransactionCommitTimeoutCheck() {
294 CohortEntry cohortEntry = commitCoordinator.getCurrentCohortEntry();
295 if(cohortEntry != null) {
296 long elapsed = System.currentTimeMillis() - cohortEntry.getLastAccessTime();
297 if(elapsed > transactionCommitTimeout) {
298 LOG.warn("{}: Current transaction {} has timed out after {} ms - aborting",
299 persistenceId(), cohortEntry.getTransactionID(), transactionCommitTimeout);
301 doAbortTransaction(cohortEntry.getTransactionID(), null);
306 private static boolean isEmptyCommit(final DataTreeCandidate candidate) {
307 return ModificationType.UNMODIFIED.equals(candidate.getRootNode().getModificationType());
310 void continueCommit(final CohortEntry cohortEntry) throws Exception {
311 final DataTreeCandidate candidate = cohortEntry.getCohort().getCandidate();
313 // If we do not have any followers and we are not using persistence
314 // or if cohortEntry has no modifications
315 // we can apply modification to the state immediately
316 if ((!hasFollowers() && !persistence().isRecoveryApplicable()) || isEmptyCommit(candidate)) {
317 applyModificationToState(getSender(), cohortEntry.getTransactionID(), candidate);
319 Shard.this.persistData(getSender(), cohortEntry.getTransactionID(),
320 DataTreeCandidatePayload.create(candidate));
324 private void handleCommitTransaction(final CommitTransaction commit) {
325 if(!commitCoordinator.handleCommit(commit.getTransactionID(), getSender(), this)) {
326 shardMBean.incrementFailedTransactionsCount();
330 private void finishCommit(@Nonnull final ActorRef sender, @Nonnull final String transactionID, @Nonnull final CohortEntry cohortEntry) {
331 LOG.debug("{}: Finishing commit for transaction {}", persistenceId(), cohortEntry.getTransactionID());
334 // We block on the future here so we don't have to worry about possibly accessing our
335 // state on a different thread outside of our dispatcher. Also, the data store
336 // currently uses a same thread executor anyway.
337 cohortEntry.getCohort().commit().get();
339 sender.tell(CommitTransactionReply.INSTANCE.toSerializable(), getSelf());
341 shardMBean.incrementCommittedTransactionCount();
342 shardMBean.setLastCommittedTransactionTime(System.currentTimeMillis());
344 } catch (Exception e) {
345 sender.tell(new akka.actor.Status.Failure(e), getSelf());
347 LOG.error("{}, An exception occurred while committing transaction {}", persistenceId(),
349 shardMBean.incrementFailedTransactionsCount();
351 commitCoordinator.currentTransactionComplete(transactionID, true);
355 private void finishCommit(@Nonnull final ActorRef sender, final @Nonnull String transactionID) {
356 // With persistence enabled, this method is called via applyState by the leader strategy
357 // after the commit has been replicated to a majority of the followers.
359 CohortEntry cohortEntry = commitCoordinator.getCohortEntryIfCurrent(transactionID);
360 if (cohortEntry == null) {
361 // The transaction is no longer the current commit. This can happen if the transaction
362 // was aborted prior, most likely due to timeout in the front-end. We need to finish
363 // committing the transaction though since it was successfully persisted and replicated
364 // however we can't use the original cohort b/c it was already preCommitted and may
365 // conflict with the current commit or may have been aborted so we commit with a new
367 cohortEntry = commitCoordinator.getAndRemoveCohortEntry(transactionID);
368 if(cohortEntry != null) {
370 store.applyForeignCandidate(transactionID, cohortEntry.getCohort().getCandidate());
371 } catch (DataValidationFailedException e) {
372 shardMBean.incrementFailedTransactionsCount();
373 LOG.error("{}: Failed to re-apply transaction {}", persistenceId(), transactionID, e);
376 sender.tell(CommitTransactionReply.INSTANCE.toSerializable(), getSelf());
378 // This really shouldn't happen - it likely means that persistence or replication
379 // took so long to complete such that the cohort entry was expired from the cache.
380 IllegalStateException ex = new IllegalStateException(
381 String.format("%s: Could not finish committing transaction %s - no CohortEntry found",
382 persistenceId(), transactionID));
383 LOG.error(ex.getMessage());
384 sender.tell(new akka.actor.Status.Failure(ex), getSelf());
387 finishCommit(sender, transactionID, cohortEntry);
391 private void handleCanCommitTransaction(final CanCommitTransaction canCommit) {
392 LOG.debug("{}: Can committing transaction {}", persistenceId(), canCommit.getTransactionID());
393 commitCoordinator.handleCanCommit(canCommit.getTransactionID(), getSender(), this);
396 private void handleBatchedModifications(BatchedModifications batched) {
397 // This message is sent to prepare the modificationsa transaction directly on the Shard as an
398 // optimization to avoid the extra overhead of a separate ShardTransaction actor. On the last
399 // BatchedModifications message, the caller sets the ready flag in the message indicating
400 // modifications are complete. The reply contains the cohort actor path (this actor) for the caller
401 // to initiate the 3-phase commit. This also avoids the overhead of sending an additional
402 // ReadyTransaction message.
404 // If we're not the leader then forward to the leader. This is a safety measure - we shouldn't
405 // normally get here if we're not the leader as the front-end (TransactionProxy) should determine
406 // the primary/leader shard. However with timing and caching on the front-end, there's a small
407 // window where it could have a stale leader during leadership transitions.
411 commitCoordinator.handleBatchedModifications(batched, getSender(), this);
412 } catch (Exception e) {
413 LOG.error("{}: Error handling BatchedModifications for Tx {}", persistenceId(),
414 batched.getTransactionID(), e);
415 getSender().tell(new akka.actor.Status.Failure(e), getSelf());
418 ActorSelection leader = getLeader();
420 // TODO: what if this is not the first batch and leadership changed in between batched messages?
421 // We could check if the commitCoordinator already has a cached entry and forward all the previous
422 // batched modifications.
423 LOG.debug("{}: Forwarding BatchedModifications to leader {}", persistenceId(), leader);
424 leader.forward(batched, getContext());
426 // TODO: rather than throwing an immediate exception, we could schedule a timer to try again to make
427 // it more resilient in case we're in the process of electing a new leader.
428 getSender().tell(new akka.actor.Status.Failure(new NoShardLeaderException(String.format(
429 "Could not find the leader for shard %s. This typically happens" +
430 " when the system is coming up or recovering and a leader is being elected. Try again" +
431 " later.", persistenceId()))), getSelf());
436 private void handleAbortTransaction(final AbortTransaction abort) {
437 doAbortTransaction(abort.getTransactionID(), getSender());
440 void doAbortTransaction(final String transactionID, final ActorRef sender) {
441 final CohortEntry cohortEntry = commitCoordinator.getCohortEntryIfCurrent(transactionID);
442 if(cohortEntry != null) {
443 LOG.debug("{}: Aborting transaction {}", persistenceId(), transactionID);
445 // We don't remove the cached cohort entry here (ie pass false) in case the Tx was
446 // aborted during replication in which case we may still commit locally if replication
448 commitCoordinator.currentTransactionComplete(transactionID, false);
450 final ListenableFuture<Void> future = cohortEntry.getCohort().abort();
451 final ActorRef self = getSelf();
453 Futures.addCallback(future, new FutureCallback<Void>() {
455 public void onSuccess(final Void v) {
456 shardMBean.incrementAbortTransactionsCount();
459 sender.tell(AbortTransactionReply.INSTANCE.toSerializable(), self);
464 public void onFailure(final Throwable t) {
465 LOG.error("{}: An exception happened during abort", persistenceId(), t);
468 sender.tell(new akka.actor.Status.Failure(t), self);
475 private void handleCreateTransaction(final Object message) {
477 createTransaction(CreateTransaction.fromSerializable(message));
478 } else if (getLeader() != null) {
479 getLeader().forward(message, getContext());
481 getSender().tell(new akka.actor.Status.Failure(new NoShardLeaderException(String.format(
482 "Could not find leader for shard %s so transaction cannot be created. This typically happens" +
483 " when the system is coming up or recovering and a leader is being elected. Try again" +
484 " later.", persistenceId()))), getSelf());
488 private void closeTransactionChain(final CloseTransactionChain closeTransactionChain) {
489 store.closeTransactionChain(closeTransactionChain.getTransactionChainId());
492 private ActorRef createTypedTransactionActor(int transactionType,
493 ShardTransactionIdentifier transactionId, String transactionChainId,
494 short clientVersion ) {
496 return transactionActorFactory.newShardTransaction(TransactionProxy.TransactionType.fromInt(transactionType),
497 transactionId, transactionChainId, clientVersion);
500 private void createTransaction(CreateTransaction createTransaction) {
502 ActorRef transactionActor = createTransaction(createTransaction.getTransactionType(),
503 createTransaction.getTransactionId(), createTransaction.getTransactionChainId(),
504 createTransaction.getVersion());
506 getSender().tell(new CreateTransactionReply(Serialization.serializedActorPath(transactionActor),
507 createTransaction.getTransactionId()).toSerializable(), getSelf());
508 } catch (Exception e) {
509 getSender().tell(new akka.actor.Status.Failure(e), getSelf());
513 private ActorRef createTransaction(int transactionType, String remoteTransactionId,
514 String transactionChainId, short clientVersion) {
517 ShardTransactionIdentifier transactionId = new ShardTransactionIdentifier(remoteTransactionId);
519 if(LOG.isDebugEnabled()) {
520 LOG.debug("{}: Creating transaction : {} ", persistenceId(), transactionId);
523 ActorRef transactionActor = createTypedTransactionActor(transactionType, transactionId,
524 transactionChainId, clientVersion);
526 return transactionActor;
529 private void commitWithNewTransaction(final Modification modification) {
530 ReadWriteShardDataTreeTransaction tx = store.newReadWriteTransaction(modification.toString(), null);
531 modification.apply(tx.getSnapshot());
533 snapshotCohort.syncCommitTransaction(tx);
534 shardMBean.incrementCommittedTransactionCount();
535 shardMBean.setLastCommittedTransactionTime(System.currentTimeMillis());
536 } catch (Exception e) {
537 shardMBean.incrementFailedTransactionsCount();
538 LOG.error("{}: Failed to commit", persistenceId(), e);
542 private void updateSchemaContext(final UpdateSchemaContext message) {
543 updateSchemaContext(message.getSchemaContext());
547 void updateSchemaContext(final SchemaContext schemaContext) {
548 store.updateSchemaContext(schemaContext);
551 private boolean isMetricsCaptureEnabled() {
552 CommonConfig config = new CommonConfig(getContext().system().settings().config());
553 return config.isMetricCaptureEnabled();
557 protected RaftActorSnapshotCohort getRaftActorSnapshotCohort() {
558 return snapshotCohort;
563 protected RaftActorRecoveryCohort getRaftActorRecoveryCohort() {
564 return new ShardRecoveryCoordinator(store, persistenceId(), LOG);
568 protected void onRecoveryComplete() {
569 //notify shard manager
570 getContext().parent().tell(new ActorInitialized(), getSelf());
572 // Being paranoid here - this method should only be called once but just in case...
573 if(txCommitTimeoutCheckSchedule == null) {
574 // Schedule a message to be periodically sent to check if the current in-progress
575 // transaction should be expired and aborted.
576 FiniteDuration period = Duration.create(transactionCommitTimeout / 3, TimeUnit.MILLISECONDS);
577 txCommitTimeoutCheckSchedule = getContext().system().scheduler().schedule(
578 period, period, getSelf(),
579 TX_COMMIT_TIMEOUT_CHECK_MESSAGE, getContext().dispatcher(), ActorRef.noSender());
584 protected void applyState(final ActorRef clientActor, final String identifier, final Object data) {
585 if (data instanceof DataTreeCandidatePayload) {
586 if (clientActor == null) {
587 // No clientActor indicates a replica coming from the leader
589 store.applyForeignCandidate(identifier, ((DataTreeCandidatePayload)data).getCandidate());
590 } catch (DataValidationFailedException | IOException e) {
591 LOG.error("{}: Error applying replica {}", persistenceId(), identifier, e);
594 // Replication consensus reached, proceed to commit
595 finishCommit(clientActor, identifier);
597 } else if (data instanceof ModificationPayload) {
599 applyModificationToState(clientActor, identifier, ((ModificationPayload) data).getModification());
600 } catch (ClassNotFoundException | IOException e) {
601 LOG.error("{}: Error extracting ModificationPayload", persistenceId(), e);
603 } else if (data instanceof CompositeModificationPayload) {
604 Object modification = ((CompositeModificationPayload) data).getModification();
606 applyModificationToState(clientActor, identifier, modification);
607 } else if(data instanceof CompositeModificationByteStringPayload ){
608 Object modification = ((CompositeModificationByteStringPayload) data).getModification();
610 applyModificationToState(clientActor, identifier, modification);
612 LOG.error("{}: Unknown state received {} Class loader = {} CompositeNodeMod.ClassLoader = {}",
613 persistenceId(), data, data.getClass().getClassLoader(),
614 CompositeModificationPayload.class.getClassLoader());
618 private void applyModificationToState(ActorRef clientActor, String identifier, Object modification) {
619 if(modification == null) {
621 "{}: modification is null - this is very unexpected, clientActor = {}, identifier = {}",
622 persistenceId(), identifier, clientActor != null ? clientActor.path().toString() : null);
623 } else if(clientActor == null) {
624 // There's no clientActor to which to send a commit reply so we must be applying
625 // replicated state from the leader.
626 commitWithNewTransaction(MutableCompositeModification.fromSerializable(modification));
628 // This must be the OK to commit after replication consensus.
629 finishCommit(clientActor, identifier);
634 protected void onStateChanged() {
635 boolean isLeader = isLeader();
636 changeSupport.onLeadershipChange(isLeader);
637 treeChangeSupport.onLeadershipChange(isLeader);
639 // If this actor is no longer the leader close all the transaction chains
641 if(LOG.isDebugEnabled()) {
643 "{}: onStateChanged: Closing all transaction chains because shard {} is no longer the leader",
644 persistenceId(), getId());
647 store.closeAllTransactionChains();
652 protected void onLeaderChanged(String oldLeader, String newLeader) {
653 shardMBean.incrementLeadershipChangeCount();
657 public String persistenceId() {
662 ShardCommitCoordinator getCommitCoordinator() {
663 return commitCoordinator;
667 private static class ShardCreator implements Creator<Shard> {
669 private static final long serialVersionUID = 1L;
671 final ShardIdentifier name;
672 final Map<String, String> peerAddresses;
673 final DatastoreContext datastoreContext;
674 final SchemaContext schemaContext;
676 ShardCreator(final ShardIdentifier name, final Map<String, String> peerAddresses,
677 final DatastoreContext datastoreContext, final SchemaContext schemaContext) {
679 this.peerAddresses = peerAddresses;
680 this.datastoreContext = datastoreContext;
681 this.schemaContext = schemaContext;
685 public Shard create() throws Exception {
686 return new Shard(name, peerAddresses, datastoreContext, schemaContext);
691 public ShardDataTree getDataStore() {
696 ShardStats getShardMBean() {