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()),
120 DataStoreVersions.CURRENT_VERSION);
122 this.name = name.toString();
123 this.datastoreContext = datastoreContext;
125 setPersistence(datastoreContext.isPersistent());
127 LOG.info("Shard created : {}, persistent : {}", name, datastoreContext.isPersistent());
129 store = new ShardDataTree(schemaContext);
131 shardMBean = ShardMBeanFactory.getShardStatsMBean(name.toString(),
132 datastoreContext.getDataStoreMXBeanType());
133 shardMBean.setShardActor(getSelf());
135 if (isMetricsCaptureEnabled()) {
136 getContext().become(new MeteringBehavior(this));
139 commitCoordinator = new ShardCommitCoordinator(store,
140 TimeUnit.SECONDS.convert(5, TimeUnit.MINUTES),
141 datastoreContext.getShardTransactionCommitQueueCapacity(), self(), LOG, this.name);
143 setTransactionCommitTimeout();
145 // create a notifier actor for each cluster member
146 roleChangeNotifier = createRoleChangeNotifier(name.toString());
148 appendEntriesReplyTracker = new MessageTracker(AppendEntriesReply.class,
149 getRaftActorContext().getConfigParams().getIsolatedCheckIntervalInMillis());
151 transactionActorFactory = new ShardTransactionActorFactory(store, datastoreContext,
152 new Dispatchers(context().system().dispatchers()).getDispatcherPath(
153 Dispatchers.DispatcherType.Transaction), self(), getContext(), shardMBean);
155 snapshotCohort = new ShardSnapshotCohort(transactionActorFactory, store, LOG, this.name);
158 private void setTransactionCommitTimeout() {
159 transactionCommitTimeout = TimeUnit.MILLISECONDS.convert(
160 datastoreContext.getShardTransactionCommitTimeoutInSeconds(), TimeUnit.SECONDS);
163 public static Props props(final ShardIdentifier name,
164 final Map<String, String> peerAddresses,
165 final DatastoreContext datastoreContext, final SchemaContext schemaContext) {
166 Preconditions.checkNotNull(name, "name should not be null");
167 Preconditions.checkNotNull(peerAddresses, "peerAddresses should not be null");
168 Preconditions.checkNotNull(datastoreContext, "dataStoreContext should not be null");
169 Preconditions.checkNotNull(schemaContext, "schemaContext should not be null");
171 return Props.create(new ShardCreator(name, peerAddresses, datastoreContext, schemaContext));
174 private Optional<ActorRef> createRoleChangeNotifier(String shardId) {
175 ActorRef shardRoleChangeNotifier = this.getContext().actorOf(
176 RoleChangeNotifier.getProps(shardId), shardId + "-notifier");
177 return Optional.of(shardRoleChangeNotifier);
181 public void postStop() {
182 LOG.info("Stopping Shard {}", persistenceId());
186 if(txCommitTimeoutCheckSchedule != null) {
187 txCommitTimeoutCheckSchedule.cancel();
190 shardMBean.unregisterMBean();
194 public void onReceiveRecover(final Object message) throws Exception {
195 if(LOG.isDebugEnabled()) {
196 LOG.debug("{}: onReceiveRecover: Received message {} from {}", persistenceId(),
197 message.getClass().toString(), getSender());
200 if (message instanceof RecoveryFailure){
201 LOG.error("{}: Recovery failed because of this cause",
202 persistenceId(), ((RecoveryFailure) message).cause());
204 // Even though recovery failed, we still need to finish our recovery, eg send the
205 // ActorInitialized message and start the txCommitTimeoutCheckSchedule.
206 onRecoveryComplete();
208 super.onReceiveRecover(message);
209 if(LOG.isTraceEnabled()) {
210 appendEntriesReplyTracker.begin();
216 public void onReceiveCommand(final Object message) throws Exception {
218 MessageTracker.Context context = appendEntriesReplyTracker.received(message);
220 if(context.error().isPresent()){
221 LOG.trace("{} : AppendEntriesReply failed to arrive at the expected interval {}", persistenceId(),
226 if (CreateTransaction.SERIALIZABLE_CLASS.isInstance(message)) {
227 handleCreateTransaction(message);
228 } else if (BatchedModifications.class.isInstance(message)) {
229 handleBatchedModifications((BatchedModifications)message);
230 } else if (message instanceof ForwardedReadyTransaction) {
231 commitCoordinator.handleForwardedReadyTransaction((ForwardedReadyTransaction) message,
233 } else if (message instanceof ReadyLocalTransaction) {
234 handleReadyLocalTransaction((ReadyLocalTransaction)message);
235 } else if (CanCommitTransaction.SERIALIZABLE_CLASS.isInstance(message)) {
236 handleCanCommitTransaction(CanCommitTransaction.fromSerializable(message));
237 } else if (CommitTransaction.SERIALIZABLE_CLASS.isInstance(message)) {
238 handleCommitTransaction(CommitTransaction.fromSerializable(message));
239 } else if (AbortTransaction.SERIALIZABLE_CLASS.isInstance(message)) {
240 handleAbortTransaction(AbortTransaction.fromSerializable(message));
241 } else if (CloseTransactionChain.SERIALIZABLE_CLASS.isInstance(message)) {
242 closeTransactionChain(CloseTransactionChain.fromSerializable(message));
243 } else if (message instanceof RegisterChangeListener) {
244 changeSupport.onMessage((RegisterChangeListener) message, isLeader());
245 } else if (message instanceof RegisterDataTreeChangeListener) {
246 treeChangeSupport.onMessage((RegisterDataTreeChangeListener) message, isLeader());
247 } else if (message instanceof UpdateSchemaContext) {
248 updateSchemaContext((UpdateSchemaContext) message);
249 } else if (message instanceof PeerAddressResolved) {
250 PeerAddressResolved resolved = (PeerAddressResolved) message;
251 setPeerAddress(resolved.getPeerId().toString(),
252 resolved.getPeerAddress());
253 } else if (message.equals(TX_COMMIT_TIMEOUT_CHECK_MESSAGE)) {
254 handleTransactionCommitTimeoutCheck();
255 } else if(message instanceof DatastoreContext) {
256 onDatastoreContext((DatastoreContext)message);
257 } else if(message instanceof RegisterRoleChangeListener){
258 roleChangeNotifier.get().forward(message, context());
259 } else if (message instanceof FollowerInitialSyncUpStatus){
260 shardMBean.setFollowerInitialSyncStatus(((FollowerInitialSyncUpStatus) message).isInitialSyncDone());
261 context().parent().tell(message, self());
263 super.onReceiveCommand(message);
271 protected Optional<ActorRef> getRoleChangeNotifier() {
272 return roleChangeNotifier;
276 protected LeaderStateChanged newLeaderStateChanged(String memberId, String leaderId) {
277 return new ShardLeaderStateChanged(memberId, leaderId,
278 isLeader() ? Optional.<DataTree>of(store.getDataTree()) : Optional.<DataTree>absent());
281 private void onDatastoreContext(DatastoreContext context) {
282 datastoreContext = context;
284 commitCoordinator.setQueueCapacity(datastoreContext.getShardTransactionCommitQueueCapacity());
286 setTransactionCommitTimeout();
288 if(datastoreContext.isPersistent() && !persistence().isRecoveryApplicable()) {
289 setPersistence(true);
290 } else if(!datastoreContext.isPersistent() && persistence().isRecoveryApplicable()) {
291 setPersistence(false);
294 updateConfigParams(datastoreContext.getShardRaftConfig());
297 private void handleTransactionCommitTimeoutCheck() {
298 CohortEntry cohortEntry = commitCoordinator.getCurrentCohortEntry();
299 if(cohortEntry != null) {
300 long elapsed = System.currentTimeMillis() - cohortEntry.getLastAccessTime();
301 if(elapsed > transactionCommitTimeout) {
302 LOG.warn("{}: Current transaction {} has timed out after {} ms - aborting",
303 persistenceId(), cohortEntry.getTransactionID(), transactionCommitTimeout);
305 doAbortTransaction(cohortEntry.getTransactionID(), null);
310 private static boolean isEmptyCommit(final DataTreeCandidate candidate) {
311 return ModificationType.UNMODIFIED.equals(candidate.getRootNode().getModificationType());
314 void continueCommit(final CohortEntry cohortEntry) throws Exception {
315 final DataTreeCandidate candidate = cohortEntry.getCohort().getCandidate();
317 // If we do not have any followers and we are not using persistence
318 // or if cohortEntry has no modifications
319 // we can apply modification to the state immediately
320 if ((!hasFollowers() && !persistence().isRecoveryApplicable()) || isEmptyCommit(candidate)) {
321 applyModificationToState(getSender(), cohortEntry.getTransactionID(), candidate);
323 Shard.this.persistData(getSender(), cohortEntry.getTransactionID(),
324 DataTreeCandidatePayload.create(candidate));
328 private void handleCommitTransaction(final CommitTransaction commit) {
329 if(!commitCoordinator.handleCommit(commit.getTransactionID(), getSender(), this)) {
330 shardMBean.incrementFailedTransactionsCount();
334 private void finishCommit(@Nonnull final ActorRef sender, @Nonnull final String transactionID, @Nonnull final CohortEntry cohortEntry) {
335 LOG.debug("{}: Finishing commit for transaction {}", persistenceId(), cohortEntry.getTransactionID());
338 // We block on the future here so we don't have to worry about possibly accessing our
339 // state on a different thread outside of our dispatcher. Also, the data store
340 // currently uses a same thread executor anyway.
341 cohortEntry.getCohort().commit().get();
343 sender.tell(CommitTransactionReply.INSTANCE.toSerializable(), getSelf());
345 shardMBean.incrementCommittedTransactionCount();
346 shardMBean.setLastCommittedTransactionTime(System.currentTimeMillis());
348 } catch (Exception e) {
349 sender.tell(new akka.actor.Status.Failure(e), getSelf());
351 LOG.error("{}, An exception occurred while committing transaction {}", persistenceId(),
353 shardMBean.incrementFailedTransactionsCount();
355 commitCoordinator.currentTransactionComplete(transactionID, true);
359 private void finishCommit(@Nonnull final ActorRef sender, final @Nonnull String transactionID) {
360 // With persistence enabled, this method is called via applyState by the leader strategy
361 // after the commit has been replicated to a majority of the followers.
363 CohortEntry cohortEntry = commitCoordinator.getCohortEntryIfCurrent(transactionID);
364 if (cohortEntry == null) {
365 // The transaction is no longer the current commit. This can happen if the transaction
366 // was aborted prior, most likely due to timeout in the front-end. We need to finish
367 // committing the transaction though since it was successfully persisted and replicated
368 // however we can't use the original cohort b/c it was already preCommitted and may
369 // conflict with the current commit or may have been aborted so we commit with a new
371 cohortEntry = commitCoordinator.getAndRemoveCohortEntry(transactionID);
372 if(cohortEntry != null) {
374 store.applyForeignCandidate(transactionID, cohortEntry.getCohort().getCandidate());
375 } catch (DataValidationFailedException e) {
376 shardMBean.incrementFailedTransactionsCount();
377 LOG.error("{}: Failed to re-apply transaction {}", persistenceId(), transactionID, e);
380 sender.tell(CommitTransactionReply.INSTANCE.toSerializable(), getSelf());
382 // This really shouldn't happen - it likely means that persistence or replication
383 // took so long to complete such that the cohort entry was expired from the cache.
384 IllegalStateException ex = new IllegalStateException(
385 String.format("%s: Could not finish committing transaction %s - no CohortEntry found",
386 persistenceId(), transactionID));
387 LOG.error(ex.getMessage());
388 sender.tell(new akka.actor.Status.Failure(ex), getSelf());
391 finishCommit(sender, transactionID, cohortEntry);
395 private void handleCanCommitTransaction(final CanCommitTransaction canCommit) {
396 LOG.debug("{}: Can committing transaction {}", persistenceId(), canCommit.getTransactionID());
397 commitCoordinator.handleCanCommit(canCommit.getTransactionID(), getSender(), this);
400 private void noLeaderError(Object message) {
401 // TODO: rather than throwing an immediate exception, we could schedule a timer to try again to make
402 // it more resilient in case we're in the process of electing a new leader.
403 getSender().tell(new akka.actor.Status.Failure(new NoShardLeaderException(String.format(
404 "Could not find the leader for shard %s. This typically happens" +
405 " when the system is coming up or recovering and a leader is being elected. Try again" +
406 " later.", persistenceId()))), getSelf());
409 private void handleBatchedModifications(BatchedModifications batched) {
410 // This message is sent to prepare the modificationsa transaction directly on the Shard as an
411 // optimization to avoid the extra overhead of a separate ShardTransaction actor. On the last
412 // BatchedModifications message, the caller sets the ready flag in the message indicating
413 // modifications are complete. The reply contains the cohort actor path (this actor) for the caller
414 // to initiate the 3-phase commit. This also avoids the overhead of sending an additional
415 // ReadyTransaction message.
417 // If we're not the leader then forward to the leader. This is a safety measure - we shouldn't
418 // normally get here if we're not the leader as the front-end (TransactionProxy) should determine
419 // the primary/leader shard. However with timing and caching on the front-end, there's a small
420 // window where it could have a stale leader during leadership transitions.
424 commitCoordinator.handleBatchedModifications(batched, getSender(), this);
425 } catch (Exception e) {
426 LOG.error("{}: Error handling BatchedModifications for Tx {}", persistenceId(),
427 batched.getTransactionID(), e);
428 getSender().tell(new akka.actor.Status.Failure(e), getSelf());
431 ActorSelection leader = getLeader();
433 // TODO: what if this is not the first batch and leadership changed in between batched messages?
434 // We could check if the commitCoordinator already has a cached entry and forward all the previous
435 // batched modifications.
436 LOG.debug("{}: Forwarding BatchedModifications to leader {}", persistenceId(), leader);
437 leader.forward(batched, getContext());
439 noLeaderError(batched);
444 private void handleReadyLocalTransaction(final ReadyLocalTransaction message) {
447 commitCoordinator.handleReadyLocalTransaction(message, getSender(), this);
448 } catch (Exception e) {
449 LOG.error("{}: Error handling LocalModifications for Tx {}", persistenceId(),
450 message.getTransactionID(), e);
451 getSender().tell(new akka.actor.Status.Failure(e), getSelf());
454 ActorSelection leader = getLeader();
455 if (leader != null) {
456 LOG.debug("{}: Forwarding LocalModifications to leader {}", persistenceId(), leader);
457 leader.forward(message, getContext());
459 noLeaderError(message);
464 private void handleAbortTransaction(final AbortTransaction abort) {
465 doAbortTransaction(abort.getTransactionID(), getSender());
468 void doAbortTransaction(final String transactionID, final ActorRef sender) {
469 final CohortEntry cohortEntry = commitCoordinator.getCohortEntryIfCurrent(transactionID);
470 if(cohortEntry != null) {
471 LOG.debug("{}: Aborting transaction {}", persistenceId(), transactionID);
473 // We don't remove the cached cohort entry here (ie pass false) in case the Tx was
474 // aborted during replication in which case we may still commit locally if replication
476 commitCoordinator.currentTransactionComplete(transactionID, false);
478 final ListenableFuture<Void> future = cohortEntry.getCohort().abort();
479 final ActorRef self = getSelf();
481 Futures.addCallback(future, new FutureCallback<Void>() {
483 public void onSuccess(final Void v) {
484 shardMBean.incrementAbortTransactionsCount();
487 sender.tell(AbortTransactionReply.INSTANCE.toSerializable(), self);
492 public void onFailure(final Throwable t) {
493 LOG.error("{}: An exception happened during abort", persistenceId(), t);
496 sender.tell(new akka.actor.Status.Failure(t), self);
503 private void handleCreateTransaction(final Object message) {
505 createTransaction(CreateTransaction.fromSerializable(message));
506 } else if (getLeader() != null) {
507 getLeader().forward(message, getContext());
509 getSender().tell(new akka.actor.Status.Failure(new NoShardLeaderException(String.format(
510 "Could not find leader for shard %s so transaction cannot be created. This typically happens" +
511 " when the system is coming up or recovering and a leader is being elected. Try again" +
512 " later.", persistenceId()))), getSelf());
516 private void closeTransactionChain(final CloseTransactionChain closeTransactionChain) {
517 store.closeTransactionChain(closeTransactionChain.getTransactionChainId());
520 private ActorRef createTypedTransactionActor(int transactionType,
521 ShardTransactionIdentifier transactionId, String transactionChainId,
522 short clientVersion ) {
524 return transactionActorFactory.newShardTransaction(TransactionType.fromInt(transactionType),
525 transactionId, transactionChainId, clientVersion);
528 private void createTransaction(CreateTransaction createTransaction) {
530 ActorRef transactionActor = createTransaction(createTransaction.getTransactionType(),
531 createTransaction.getTransactionId(), createTransaction.getTransactionChainId(),
532 createTransaction.getVersion());
534 getSender().tell(new CreateTransactionReply(Serialization.serializedActorPath(transactionActor),
535 createTransaction.getTransactionId()).toSerializable(), getSelf());
536 } catch (Exception e) {
537 getSender().tell(new akka.actor.Status.Failure(e), getSelf());
541 private ActorRef createTransaction(int transactionType, String remoteTransactionId,
542 String transactionChainId, short clientVersion) {
545 ShardTransactionIdentifier transactionId = new ShardTransactionIdentifier(remoteTransactionId);
547 if(LOG.isDebugEnabled()) {
548 LOG.debug("{}: Creating transaction : {} ", persistenceId(), transactionId);
551 ActorRef transactionActor = createTypedTransactionActor(transactionType, transactionId,
552 transactionChainId, clientVersion);
554 return transactionActor;
557 private void commitWithNewTransaction(final Modification modification) {
558 ReadWriteShardDataTreeTransaction tx = store.newReadWriteTransaction(modification.toString(), null);
559 modification.apply(tx.getSnapshot());
561 snapshotCohort.syncCommitTransaction(tx);
562 shardMBean.incrementCommittedTransactionCount();
563 shardMBean.setLastCommittedTransactionTime(System.currentTimeMillis());
564 } catch (Exception e) {
565 shardMBean.incrementFailedTransactionsCount();
566 LOG.error("{}: Failed to commit", persistenceId(), e);
570 private void updateSchemaContext(final UpdateSchemaContext message) {
571 updateSchemaContext(message.getSchemaContext());
575 void updateSchemaContext(final SchemaContext schemaContext) {
576 store.updateSchemaContext(schemaContext);
579 private boolean isMetricsCaptureEnabled() {
580 CommonConfig config = new CommonConfig(getContext().system().settings().config());
581 return config.isMetricCaptureEnabled();
585 protected RaftActorSnapshotCohort getRaftActorSnapshotCohort() {
586 return snapshotCohort;
591 protected RaftActorRecoveryCohort getRaftActorRecoveryCohort() {
592 return new ShardRecoveryCoordinator(store, persistenceId(), LOG);
596 protected void onRecoveryComplete() {
597 //notify shard manager
598 getContext().parent().tell(new ActorInitialized(), getSelf());
600 // Being paranoid here - this method should only be called once but just in case...
601 if(txCommitTimeoutCheckSchedule == null) {
602 // Schedule a message to be periodically sent to check if the current in-progress
603 // transaction should be expired and aborted.
604 FiniteDuration period = Duration.create(transactionCommitTimeout / 3, TimeUnit.MILLISECONDS);
605 txCommitTimeoutCheckSchedule = getContext().system().scheduler().schedule(
606 period, period, getSelf(),
607 TX_COMMIT_TIMEOUT_CHECK_MESSAGE, getContext().dispatcher(), ActorRef.noSender());
612 protected void applyState(final ActorRef clientActor, final String identifier, final Object data) {
613 if (data instanceof DataTreeCandidatePayload) {
614 if (clientActor == null) {
615 // No clientActor indicates a replica coming from the leader
617 store.applyForeignCandidate(identifier, ((DataTreeCandidatePayload)data).getCandidate());
618 } catch (DataValidationFailedException | IOException e) {
619 LOG.error("{}: Error applying replica {}", persistenceId(), identifier, e);
622 // Replication consensus reached, proceed to commit
623 finishCommit(clientActor, identifier);
625 } else if (data instanceof ModificationPayload) {
627 applyModificationToState(clientActor, identifier, ((ModificationPayload) data).getModification());
628 } catch (ClassNotFoundException | IOException e) {
629 LOG.error("{}: Error extracting ModificationPayload", persistenceId(), e);
631 } else if (data instanceof CompositeModificationPayload) {
632 Object modification = ((CompositeModificationPayload) data).getModification();
634 applyModificationToState(clientActor, identifier, modification);
635 } else if(data instanceof CompositeModificationByteStringPayload ){
636 Object modification = ((CompositeModificationByteStringPayload) data).getModification();
638 applyModificationToState(clientActor, identifier, modification);
640 LOG.error("{}: Unknown state received {} Class loader = {} CompositeNodeMod.ClassLoader = {}",
641 persistenceId(), data, data.getClass().getClassLoader(),
642 CompositeModificationPayload.class.getClassLoader());
646 private void applyModificationToState(ActorRef clientActor, String identifier, Object modification) {
647 if(modification == null) {
649 "{}: modification is null - this is very unexpected, clientActor = {}, identifier = {}",
650 persistenceId(), identifier, clientActor != null ? clientActor.path().toString() : null);
651 } else if(clientActor == null) {
652 // There's no clientActor to which to send a commit reply so we must be applying
653 // replicated state from the leader.
654 commitWithNewTransaction(MutableCompositeModification.fromSerializable(modification));
656 // This must be the OK to commit after replication consensus.
657 finishCommit(clientActor, identifier);
662 protected void onStateChanged() {
663 boolean isLeader = isLeader();
664 changeSupport.onLeadershipChange(isLeader);
665 treeChangeSupport.onLeadershipChange(isLeader);
667 // If this actor is no longer the leader close all the transaction chains
669 if(LOG.isDebugEnabled()) {
671 "{}: onStateChanged: Closing all transaction chains because shard {} is no longer the leader",
672 persistenceId(), getId());
675 store.closeAllTransactionChains();
680 protected void onLeaderChanged(String oldLeader, String newLeader) {
681 shardMBean.incrementLeadershipChangeCount();
685 public String persistenceId() {
690 ShardCommitCoordinator getCommitCoordinator() {
691 return commitCoordinator;
695 private static class ShardCreator implements Creator<Shard> {
697 private static final long serialVersionUID = 1L;
699 final ShardIdentifier name;
700 final Map<String, String> peerAddresses;
701 final DatastoreContext datastoreContext;
702 final SchemaContext schemaContext;
704 ShardCreator(final ShardIdentifier name, final Map<String, String> peerAddresses,
705 final DatastoreContext datastoreContext, final SchemaContext schemaContext) {
707 this.peerAddresses = peerAddresses;
708 this.datastoreContext = datastoreContext;
709 this.schemaContext = schemaContext;
713 public Shard create() throws Exception {
714 return new Shard(name, peerAddresses, datastoreContext, schemaContext);
719 public ShardDataTree getDataStore() {
724 ShardStats getShardMBean() {