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.RaftState;
66 import org.opendaylight.controller.cluster.raft.base.messages.FollowerInitialSyncUpStatus;
67 import org.opendaylight.controller.cluster.raft.messages.AppendEntriesReply;
68 import org.opendaylight.controller.cluster.raft.protobuff.client.messages.CompositeModificationByteStringPayload;
69 import org.opendaylight.controller.cluster.raft.protobuff.client.messages.CompositeModificationPayload;
70 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTree;
71 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidate;
72 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataValidationFailedException;
73 import org.opendaylight.yangtools.yang.data.api.schema.tree.ModificationType;
74 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
75 import scala.concurrent.duration.Duration;
76 import scala.concurrent.duration.FiniteDuration;
79 * A Shard represents a portion of the logical data tree <br/>
81 * Our Shard uses InMemoryDataTree as it's internal representation and delegates all requests it
84 public class Shard extends RaftActor {
86 private static final Object TX_COMMIT_TIMEOUT_CHECK_MESSAGE = "txCommitTimeoutCheck";
89 static final Object GET_SHARD_MBEAN_MESSAGE = "getShardMBeanMessage";
92 static final String DEFAULT_NAME = "default";
94 // The state of this Shard
95 private final ShardDataTree store;
97 /// The name of this shard
98 private final String name;
100 private final ShardStats shardMBean;
102 private DatastoreContext datastoreContext;
104 private final ShardCommitCoordinator commitCoordinator;
106 private long transactionCommitTimeout;
108 private Cancellable txCommitTimeoutCheckSchedule;
110 private final Optional<ActorRef> roleChangeNotifier;
112 private final MessageTracker appendEntriesReplyTracker;
114 private final ShardTransactionActorFactory transactionActorFactory;
116 private final ShardSnapshotCohort snapshotCohort;
118 private final DataTreeChangeListenerSupport treeChangeSupport = new DataTreeChangeListenerSupport(this);
119 private final DataChangeListenerSupport changeSupport = new DataChangeListenerSupport(this);
121 protected Shard(final ShardIdentifier name, final Map<String, String> peerAddresses,
122 final DatastoreContext datastoreContext, final SchemaContext schemaContext) {
123 super(name.toString(), new HashMap<>(peerAddresses), Optional.of(datastoreContext.getShardRaftConfig()),
124 DataStoreVersions.CURRENT_VERSION);
126 this.name = name.toString();
127 this.datastoreContext = datastoreContext;
129 setPersistence(datastoreContext.isPersistent());
131 LOG.info("Shard created : {}, persistent : {}", name, datastoreContext.isPersistent());
133 store = new ShardDataTree(schemaContext);
135 shardMBean = ShardMBeanFactory.getShardStatsMBean(name.toString(),
136 datastoreContext.getDataStoreMXBeanType());
137 shardMBean.setShard(this);
139 if (isMetricsCaptureEnabled()) {
140 getContext().become(new MeteringBehavior(this));
143 commitCoordinator = new ShardCommitCoordinator(store,
144 datastoreContext.getShardCommitQueueExpiryTimeoutInMillis(),
145 datastoreContext.getShardTransactionCommitQueueCapacity(), self(), LOG, this.name);
147 setTransactionCommitTimeout();
149 // create a notifier actor for each cluster member
150 roleChangeNotifier = createRoleChangeNotifier(name.toString());
152 appendEntriesReplyTracker = new MessageTracker(AppendEntriesReply.class,
153 getRaftActorContext().getConfigParams().getIsolatedCheckIntervalInMillis());
155 transactionActorFactory = new ShardTransactionActorFactory(store, datastoreContext,
156 new Dispatchers(context().system().dispatchers()).getDispatcherPath(
157 Dispatchers.DispatcherType.Transaction), self(), getContext(), shardMBean);
159 snapshotCohort = new ShardSnapshotCohort(transactionActorFactory, store, LOG, this.name);
164 private void setTransactionCommitTimeout() {
165 transactionCommitTimeout = TimeUnit.MILLISECONDS.convert(
166 datastoreContext.getShardTransactionCommitTimeoutInSeconds(), TimeUnit.SECONDS) / 2;
169 public static Props props(final ShardIdentifier name,
170 final Map<String, String> peerAddresses,
171 final DatastoreContext datastoreContext, final SchemaContext schemaContext) {
172 Preconditions.checkNotNull(name, "name should not be null");
173 Preconditions.checkNotNull(peerAddresses, "peerAddresses should not be null");
174 Preconditions.checkNotNull(datastoreContext, "dataStoreContext should not be null");
175 Preconditions.checkNotNull(schemaContext, "schemaContext should not be null");
177 return Props.create(new ShardCreator(name, peerAddresses, datastoreContext, schemaContext));
180 private Optional<ActorRef> createRoleChangeNotifier(String shardId) {
181 ActorRef shardRoleChangeNotifier = this.getContext().actorOf(
182 RoleChangeNotifier.getProps(shardId), shardId + "-notifier");
183 return Optional.of(shardRoleChangeNotifier);
187 public void postStop() {
188 LOG.info("Stopping Shard {}", persistenceId());
192 if(txCommitTimeoutCheckSchedule != null) {
193 txCommitTimeoutCheckSchedule.cancel();
196 shardMBean.unregisterMBean();
200 public void onReceiveRecover(final Object message) throws Exception {
201 if(LOG.isDebugEnabled()) {
202 LOG.debug("{}: onReceiveRecover: Received message {} from {}", persistenceId(),
203 message.getClass().toString(), getSender());
206 if (message instanceof RecoveryFailure){
207 LOG.error("{}: Recovery failed because of this cause",
208 persistenceId(), ((RecoveryFailure) message).cause());
210 // Even though recovery failed, we still need to finish our recovery, eg send the
211 // ActorInitialized message and start the txCommitTimeoutCheckSchedule.
212 onRecoveryComplete();
214 super.onReceiveRecover(message);
215 if(LOG.isTraceEnabled()) {
216 appendEntriesReplyTracker.begin();
222 public void onReceiveCommand(final Object message) throws Exception {
224 MessageTracker.Context context = appendEntriesReplyTracker.received(message);
226 if(context.error().isPresent()){
227 LOG.trace("{} : AppendEntriesReply failed to arrive at the expected interval {}", persistenceId(),
232 if (CreateTransaction.SERIALIZABLE_CLASS.isInstance(message)) {
233 handleCreateTransaction(message);
234 } else if (BatchedModifications.class.isInstance(message)) {
235 handleBatchedModifications((BatchedModifications)message);
236 } else if (message instanceof ForwardedReadyTransaction) {
237 commitCoordinator.handleForwardedReadyTransaction((ForwardedReadyTransaction) message,
239 } else if (message instanceof ReadyLocalTransaction) {
240 handleReadyLocalTransaction((ReadyLocalTransaction)message);
241 } else if (CanCommitTransaction.SERIALIZABLE_CLASS.isInstance(message)) {
242 handleCanCommitTransaction(CanCommitTransaction.fromSerializable(message));
243 } else if (CommitTransaction.SERIALIZABLE_CLASS.isInstance(message)) {
244 handleCommitTransaction(CommitTransaction.fromSerializable(message));
245 } else if (AbortTransaction.SERIALIZABLE_CLASS.isInstance(message)) {
246 handleAbortTransaction(AbortTransaction.fromSerializable(message));
247 } else if (CloseTransactionChain.SERIALIZABLE_CLASS.isInstance(message)) {
248 closeTransactionChain(CloseTransactionChain.fromSerializable(message));
249 } else if (message instanceof RegisterChangeListener) {
250 changeSupport.onMessage((RegisterChangeListener) message, isLeader());
251 } else if (message instanceof RegisterDataTreeChangeListener) {
252 treeChangeSupport.onMessage((RegisterDataTreeChangeListener) message, isLeader());
253 } else if (message instanceof UpdateSchemaContext) {
254 updateSchemaContext((UpdateSchemaContext) message);
255 } else if (message instanceof PeerAddressResolved) {
256 PeerAddressResolved resolved = (PeerAddressResolved) message;
257 setPeerAddress(resolved.getPeerId().toString(),
258 resolved.getPeerAddress());
259 } else if (message.equals(TX_COMMIT_TIMEOUT_CHECK_MESSAGE)) {
260 handleTransactionCommitTimeoutCheck();
261 } else if(message instanceof DatastoreContext) {
262 onDatastoreContext((DatastoreContext)message);
263 } else if(message instanceof RegisterRoleChangeListener){
264 roleChangeNotifier.get().forward(message, context());
265 } else if (message instanceof FollowerInitialSyncUpStatus) {
266 shardMBean.setFollowerInitialSyncStatus(((FollowerInitialSyncUpStatus) message).isInitialSyncDone());
267 context().parent().tell(message, self());
268 } else if(GET_SHARD_MBEAN_MESSAGE.equals(message)){
269 sender().tell(getShardMBean(), self());
271 super.onReceiveCommand(message);
278 public int getPendingTxCommitQueueSize() {
279 return commitCoordinator.getQueueSize();
283 protected Optional<ActorRef> getRoleChangeNotifier() {
284 return roleChangeNotifier;
288 protected LeaderStateChanged newLeaderStateChanged(String memberId, String leaderId, short leaderPayloadVersion) {
289 return new ShardLeaderStateChanged(memberId, leaderId,
290 isLeader() ? Optional.<DataTree>of(store.getDataTree()) : Optional.<DataTree>absent(),
291 leaderPayloadVersion);
294 private void onDatastoreContext(DatastoreContext context) {
295 datastoreContext = context;
297 commitCoordinator.setQueueCapacity(datastoreContext.getShardTransactionCommitQueueCapacity());
299 setTransactionCommitTimeout();
301 if(datastoreContext.isPersistent() && !persistence().isRecoveryApplicable()) {
302 setPersistence(true);
303 } else if(!datastoreContext.isPersistent() && persistence().isRecoveryApplicable()) {
304 setPersistence(false);
307 updateConfigParams(datastoreContext.getShardRaftConfig());
310 private void handleTransactionCommitTimeoutCheck() {
311 CohortEntry cohortEntry = commitCoordinator.getCurrentCohortEntry();
312 if(cohortEntry != null) {
313 if(cohortEntry.isExpired(transactionCommitTimeout)) {
314 LOG.warn("{}: Current transaction {} has timed out after {} ms - aborting",
315 persistenceId(), cohortEntry.getTransactionID(), transactionCommitTimeout);
317 doAbortTransaction(cohortEntry.getTransactionID(), null);
321 commitCoordinator.cleanupExpiredCohortEntries();
324 private static boolean isEmptyCommit(final DataTreeCandidate candidate) {
325 return ModificationType.UNMODIFIED.equals(candidate.getRootNode().getModificationType());
328 void continueCommit(final CohortEntry cohortEntry) throws Exception {
329 final DataTreeCandidate candidate = cohortEntry.getCohort().getCandidate();
331 // If we do not have any followers and we are not using persistence
332 // or if cohortEntry has no modifications
333 // we can apply modification to the state immediately
334 if ((!hasFollowers() && !persistence().isRecoveryApplicable()) || isEmptyCommit(candidate)) {
335 applyModificationToState(cohortEntry.getReplySender(), cohortEntry.getTransactionID(), candidate);
337 Shard.this.persistData(cohortEntry.getReplySender(), cohortEntry.getTransactionID(),
338 DataTreeCandidatePayload.create(candidate));
342 private void handleCommitTransaction(final CommitTransaction commit) {
343 if(!commitCoordinator.handleCommit(commit.getTransactionID(), getSender(), this)) {
344 shardMBean.incrementFailedTransactionsCount();
348 private void finishCommit(@Nonnull final ActorRef sender, @Nonnull final String transactionID, @Nonnull final CohortEntry cohortEntry) {
349 LOG.debug("{}: Finishing commit for transaction {}", persistenceId(), cohortEntry.getTransactionID());
352 // We block on the future here so we don't have to worry about possibly accessing our
353 // state on a different thread outside of our dispatcher. Also, the data store
354 // currently uses a same thread executor anyway.
355 cohortEntry.getCohort().commit().get();
357 sender.tell(CommitTransactionReply.INSTANCE.toSerializable(), getSelf());
359 shardMBean.incrementCommittedTransactionCount();
360 shardMBean.setLastCommittedTransactionTime(System.currentTimeMillis());
362 } catch (Exception e) {
363 sender.tell(new akka.actor.Status.Failure(e), getSelf());
365 LOG.error("{}, An exception occurred while committing transaction {}", persistenceId(),
367 shardMBean.incrementFailedTransactionsCount();
369 commitCoordinator.currentTransactionComplete(transactionID, true);
373 private void finishCommit(@Nonnull final ActorRef sender, final @Nonnull String transactionID) {
374 // With persistence enabled, this method is called via applyState by the leader strategy
375 // after the commit has been replicated to a majority of the followers.
377 CohortEntry cohortEntry = commitCoordinator.getCohortEntryIfCurrent(transactionID);
378 if (cohortEntry == null) {
379 // The transaction is no longer the current commit. This can happen if the transaction
380 // was aborted prior, most likely due to timeout in the front-end. We need to finish
381 // committing the transaction though since it was successfully persisted and replicated
382 // however we can't use the original cohort b/c it was already preCommitted and may
383 // conflict with the current commit or may have been aborted so we commit with a new
385 cohortEntry = commitCoordinator.getAndRemoveCohortEntry(transactionID);
386 if(cohortEntry != null) {
388 store.applyForeignCandidate(transactionID, cohortEntry.getCohort().getCandidate());
389 } catch (DataValidationFailedException e) {
390 shardMBean.incrementFailedTransactionsCount();
391 LOG.error("{}: Failed to re-apply transaction {}", persistenceId(), transactionID, e);
394 sender.tell(CommitTransactionReply.INSTANCE.toSerializable(), getSelf());
396 // This really shouldn't happen - it likely means that persistence or replication
397 // took so long to complete such that the cohort entry was expired from the cache.
398 IllegalStateException ex = new IllegalStateException(
399 String.format("%s: Could not finish committing transaction %s - no CohortEntry found",
400 persistenceId(), transactionID));
401 LOG.error(ex.getMessage());
402 sender.tell(new akka.actor.Status.Failure(ex), getSelf());
405 finishCommit(sender, transactionID, cohortEntry);
409 private void handleCanCommitTransaction(final CanCommitTransaction canCommit) {
410 LOG.debug("{}: Can committing transaction {}", persistenceId(), canCommit.getTransactionID());
411 commitCoordinator.handleCanCommit(canCommit.getTransactionID(), getSender(), this);
414 private void noLeaderError(String errMessage, Object message) {
415 // TODO: rather than throwing an immediate exception, we could schedule a timer to try again to make
416 // it more resilient in case we're in the process of electing a new leader.
417 getSender().tell(new akka.actor.Status.Failure(new NoShardLeaderException(errMessage, persistenceId())), getSelf());
420 private void handleBatchedModifications(BatchedModifications batched) {
421 // This message is sent to prepare the modifications transaction directly on the Shard as an
422 // optimization to avoid the extra overhead of a separate ShardTransaction actor. On the last
423 // BatchedModifications message, the caller sets the ready flag in the message indicating
424 // modifications are complete. The reply contains the cohort actor path (this actor) for the caller
425 // to initiate the 3-phase commit. This also avoids the overhead of sending an additional
426 // ReadyTransaction message.
428 // If we're not the leader then forward to the leader. This is a safety measure - we shouldn't
429 // normally get here if we're not the leader as the front-end (TransactionProxy) should determine
430 // the primary/leader shard. However with timing and caching on the front-end, there's a small
431 // window where it could have a stale leader during leadership transitions.
434 failIfIsolatedLeader(getSender());
437 commitCoordinator.handleBatchedModifications(batched, getSender(), this);
438 } catch (Exception e) {
439 LOG.error("{}: Error handling BatchedModifications for Tx {}", persistenceId(),
440 batched.getTransactionID(), e);
441 getSender().tell(new akka.actor.Status.Failure(e), getSelf());
444 ActorSelection leader = getLeader();
446 // TODO: what if this is not the first batch and leadership changed in between batched messages?
447 // We could check if the commitCoordinator already has a cached entry and forward all the previous
448 // batched modifications.
449 LOG.debug("{}: Forwarding BatchedModifications to leader {}", persistenceId(), leader);
450 leader.forward(batched, getContext());
452 noLeaderError("Could not commit transaction " + batched.getTransactionID(), batched);
457 private boolean failIfIsolatedLeader(ActorRef sender) {
458 if(getRaftState() == RaftState.IsolatedLeader) {
459 sender.tell(new akka.actor.Status.Failure(new NoShardLeaderException(String.format(
460 "Shard %s was the leader but has lost contact with all of its followers. Either all" +
461 " other follower nodes are down or this node is isolated by a network partition.",
462 persistenceId()))), getSelf());
469 private void handleReadyLocalTransaction(final ReadyLocalTransaction message) {
471 failIfIsolatedLeader(getSender());
474 commitCoordinator.handleReadyLocalTransaction(message, getSender(), this);
475 } catch (Exception e) {
476 LOG.error("{}: Error handling ReadyLocalTransaction for Tx {}", persistenceId(),
477 message.getTransactionID(), e);
478 getSender().tell(new akka.actor.Status.Failure(e), getSelf());
481 ActorSelection leader = getLeader();
482 if (leader != null) {
483 LOG.debug("{}: Forwarding ReadyLocalTransaction to leader {}", persistenceId(), leader);
484 message.setRemoteVersion(getCurrentBehavior().getLeaderPayloadVersion());
485 leader.forward(message, getContext());
487 noLeaderError("Could not commit transaction " + message.getTransactionID(), message);
492 private void handleAbortTransaction(final AbortTransaction abort) {
493 doAbortTransaction(abort.getTransactionID(), getSender());
496 void doAbortTransaction(final String transactionID, final ActorRef sender) {
497 final CohortEntry cohortEntry = commitCoordinator.getCohortEntryIfCurrent(transactionID);
498 if(cohortEntry != null) {
499 LOG.debug("{}: Aborting transaction {}", persistenceId(), transactionID);
501 // We don't remove the cached cohort entry here (ie pass false) in case the Tx was
502 // aborted during replication in which case we may still commit locally if replication
504 commitCoordinator.currentTransactionComplete(transactionID, false);
506 final ListenableFuture<Void> future = cohortEntry.getCohort().abort();
507 final ActorRef self = getSelf();
509 Futures.addCallback(future, new FutureCallback<Void>() {
511 public void onSuccess(final Void v) {
512 shardMBean.incrementAbortTransactionsCount();
515 sender.tell(AbortTransactionReply.INSTANCE.toSerializable(), self);
520 public void onFailure(final Throwable t) {
521 LOG.error("{}: An exception happened during abort", persistenceId(), t);
524 sender.tell(new akka.actor.Status.Failure(t), self);
531 private void handleCreateTransaction(final Object message) {
533 createTransaction(CreateTransaction.fromSerializable(message));
534 } else if (getLeader() != null) {
535 getLeader().forward(message, getContext());
537 getSender().tell(new akka.actor.Status.Failure(new NoShardLeaderException(
538 "Could not create a shard transaction", persistenceId())), getSelf());
542 private void closeTransactionChain(final CloseTransactionChain closeTransactionChain) {
543 store.closeTransactionChain(closeTransactionChain.getTransactionChainId());
546 private ActorRef createTypedTransactionActor(int transactionType,
547 ShardTransactionIdentifier transactionId, String transactionChainId,
548 short clientVersion ) {
550 return transactionActorFactory.newShardTransaction(TransactionType.fromInt(transactionType),
551 transactionId, transactionChainId, clientVersion);
554 private void createTransaction(CreateTransaction createTransaction) {
556 if(TransactionType.fromInt(createTransaction.getTransactionType()) != TransactionType.READ_ONLY &&
557 failIfIsolatedLeader(getSender())) {
561 ActorRef transactionActor = createTransaction(createTransaction.getTransactionType(),
562 createTransaction.getTransactionId(), createTransaction.getTransactionChainId(),
563 createTransaction.getVersion());
565 getSender().tell(new CreateTransactionReply(Serialization.serializedActorPath(transactionActor),
566 createTransaction.getTransactionId()).toSerializable(), getSelf());
567 } catch (Exception e) {
568 getSender().tell(new akka.actor.Status.Failure(e), getSelf());
572 private ActorRef createTransaction(int transactionType, String remoteTransactionId,
573 String transactionChainId, short clientVersion) {
576 ShardTransactionIdentifier transactionId = new ShardTransactionIdentifier(remoteTransactionId);
578 if(LOG.isDebugEnabled()) {
579 LOG.debug("{}: Creating transaction : {} ", persistenceId(), transactionId);
582 ActorRef transactionActor = createTypedTransactionActor(transactionType, transactionId,
583 transactionChainId, clientVersion);
585 return transactionActor;
588 private void commitWithNewTransaction(final Modification modification) {
589 ReadWriteShardDataTreeTransaction tx = store.newReadWriteTransaction(modification.toString(), null);
590 modification.apply(tx.getSnapshot());
592 snapshotCohort.syncCommitTransaction(tx);
593 shardMBean.incrementCommittedTransactionCount();
594 shardMBean.setLastCommittedTransactionTime(System.currentTimeMillis());
595 } catch (Exception e) {
596 shardMBean.incrementFailedTransactionsCount();
597 LOG.error("{}: Failed to commit", persistenceId(), e);
601 private void updateSchemaContext(final UpdateSchemaContext message) {
602 updateSchemaContext(message.getSchemaContext());
606 void updateSchemaContext(final SchemaContext schemaContext) {
607 store.updateSchemaContext(schemaContext);
610 private boolean isMetricsCaptureEnabled() {
611 CommonConfig config = new CommonConfig(getContext().system().settings().config());
612 return config.isMetricCaptureEnabled();
617 public RaftActorSnapshotCohort getRaftActorSnapshotCohort() {
618 return snapshotCohort;
623 protected RaftActorRecoveryCohort getRaftActorRecoveryCohort() {
624 return new ShardRecoveryCoordinator(store, store.getSchemaContext(), persistenceId(), LOG);
628 protected void onRecoveryComplete() {
629 //notify shard manager
630 getContext().parent().tell(new ActorInitialized(), getSelf());
632 // Being paranoid here - this method should only be called once but just in case...
633 if(txCommitTimeoutCheckSchedule == null) {
634 // Schedule a message to be periodically sent to check if the current in-progress
635 // transaction should be expired and aborted.
636 FiniteDuration period = Duration.create(transactionCommitTimeout / 3, TimeUnit.MILLISECONDS);
637 txCommitTimeoutCheckSchedule = getContext().system().scheduler().schedule(
638 period, period, getSelf(),
639 TX_COMMIT_TIMEOUT_CHECK_MESSAGE, getContext().dispatcher(), ActorRef.noSender());
644 protected void applyState(final ActorRef clientActor, final String identifier, final Object data) {
645 if (data instanceof DataTreeCandidatePayload) {
646 if (clientActor == null) {
647 // No clientActor indicates a replica coming from the leader
649 store.applyForeignCandidate(identifier, ((DataTreeCandidatePayload)data).getCandidate());
650 } catch (DataValidationFailedException | IOException e) {
651 LOG.error("{}: Error applying replica {}", persistenceId(), identifier, e);
654 // Replication consensus reached, proceed to commit
655 finishCommit(clientActor, identifier);
657 } else if (data instanceof ModificationPayload) {
659 applyModificationToState(clientActor, identifier, ((ModificationPayload) data).getModification());
660 } catch (ClassNotFoundException | IOException e) {
661 LOG.error("{}: Error extracting ModificationPayload", persistenceId(), e);
663 } else if (data instanceof CompositeModificationPayload) {
664 Object modification = ((CompositeModificationPayload) data).getModification();
666 applyModificationToState(clientActor, identifier, modification);
667 } else if(data instanceof CompositeModificationByteStringPayload ){
668 Object modification = ((CompositeModificationByteStringPayload) data).getModification();
670 applyModificationToState(clientActor, identifier, modification);
672 LOG.error("{}: Unknown state received {} Class loader = {} CompositeNodeMod.ClassLoader = {}",
673 persistenceId(), data, data.getClass().getClassLoader(),
674 CompositeModificationPayload.class.getClassLoader());
678 private void applyModificationToState(ActorRef clientActor, String identifier, Object modification) {
679 if(modification == null) {
681 "{}: modification is null - this is very unexpected, clientActor = {}, identifier = {}",
682 persistenceId(), identifier, clientActor != null ? clientActor.path().toString() : null);
683 } else if(clientActor == null) {
684 // There's no clientActor to which to send a commit reply so we must be applying
685 // replicated state from the leader.
686 commitWithNewTransaction(MutableCompositeModification.fromSerializable(modification));
688 // This must be the OK to commit after replication consensus.
689 finishCommit(clientActor, identifier);
694 protected void onStateChanged() {
695 boolean isLeader = isLeader();
696 changeSupport.onLeadershipChange(isLeader);
697 treeChangeSupport.onLeadershipChange(isLeader);
699 // If this actor is no longer the leader close all the transaction chains
701 if(LOG.isDebugEnabled()) {
703 "{}: onStateChanged: Closing all transaction chains because shard {} is no longer the leader",
704 persistenceId(), getId());
707 store.closeAllTransactionChains();
712 protected void onLeaderChanged(String oldLeader, String newLeader) {
713 shardMBean.incrementLeadershipChangeCount();
717 public String persistenceId() {
722 ShardCommitCoordinator getCommitCoordinator() {
723 return commitCoordinator;
727 private static class ShardCreator implements Creator<Shard> {
729 private static final long serialVersionUID = 1L;
731 final ShardIdentifier name;
732 final Map<String, String> peerAddresses;
733 final DatastoreContext datastoreContext;
734 final SchemaContext schemaContext;
736 ShardCreator(final ShardIdentifier name, final Map<String, String> peerAddresses,
737 final DatastoreContext datastoreContext, final SchemaContext schemaContext) {
739 this.peerAddresses = peerAddresses;
740 this.datastoreContext = datastoreContext;
741 this.schemaContext = schemaContext;
745 public Shard create() throws Exception {
746 return new Shard(name, peerAddresses, datastoreContext, schemaContext);
751 public ShardDataTree getDataStore() {
756 ShardStats getShardMBean() {