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.persistence.RecoveryFailure;
16 import akka.serialization.Serialization;
17 import com.google.common.annotations.VisibleForTesting;
18 import com.google.common.base.Optional;
19 import com.google.common.base.Preconditions;
20 import java.io.IOException;
21 import java.util.Collections;
23 import java.util.concurrent.TimeUnit;
24 import javax.annotation.Nonnull;
25 import org.opendaylight.controller.cluster.common.actor.CommonConfig;
26 import org.opendaylight.controller.cluster.common.actor.MeteringBehavior;
27 import org.opendaylight.controller.cluster.datastore.ShardCommitCoordinator.CohortEntry;
28 import org.opendaylight.controller.cluster.datastore.exceptions.NoShardLeaderException;
29 import org.opendaylight.controller.cluster.datastore.identifiers.ShardIdentifier;
30 import org.opendaylight.controller.cluster.datastore.identifiers.ShardTransactionIdentifier;
31 import org.opendaylight.controller.cluster.datastore.jmx.mbeans.shard.ShardMBeanFactory;
32 import org.opendaylight.controller.cluster.datastore.jmx.mbeans.shard.ShardStats;
33 import org.opendaylight.controller.cluster.datastore.messages.AbortTransaction;
34 import org.opendaylight.controller.cluster.datastore.messages.ActorInitialized;
35 import org.opendaylight.controller.cluster.datastore.messages.BatchedModifications;
36 import org.opendaylight.controller.cluster.datastore.messages.CanCommitTransaction;
37 import org.opendaylight.controller.cluster.datastore.messages.CloseTransactionChain;
38 import org.opendaylight.controller.cluster.datastore.messages.CommitTransaction;
39 import org.opendaylight.controller.cluster.datastore.messages.CommitTransactionReply;
40 import org.opendaylight.controller.cluster.datastore.messages.CreateTransaction;
41 import org.opendaylight.controller.cluster.datastore.messages.CreateTransactionReply;
42 import org.opendaylight.controller.cluster.datastore.messages.DatastoreSnapshot;
43 import org.opendaylight.controller.cluster.datastore.messages.DatastoreSnapshot.ShardSnapshot;
44 import org.opendaylight.controller.cluster.datastore.messages.ForwardedReadyTransaction;
45 import org.opendaylight.controller.cluster.datastore.messages.GetShardDataTree;
46 import org.opendaylight.controller.cluster.datastore.messages.PeerAddressResolved;
47 import org.opendaylight.controller.cluster.datastore.messages.ReadyLocalTransaction;
48 import org.opendaylight.controller.cluster.datastore.messages.RegisterChangeListener;
49 import org.opendaylight.controller.cluster.datastore.messages.RegisterDataTreeChangeListener;
50 import org.opendaylight.controller.cluster.datastore.messages.ShardLeaderStateChanged;
51 import org.opendaylight.controller.cluster.datastore.messages.UpdateSchemaContext;
52 import org.opendaylight.controller.cluster.datastore.modification.Modification;
53 import org.opendaylight.controller.cluster.datastore.modification.ModificationPayload;
54 import org.opendaylight.controller.cluster.datastore.modification.MutableCompositeModification;
55 import org.opendaylight.controller.cluster.datastore.utils.Dispatchers;
56 import org.opendaylight.controller.cluster.datastore.utils.MessageTracker;
57 import org.opendaylight.controller.cluster.notifications.LeaderStateChanged;
58 import org.opendaylight.controller.cluster.notifications.RegisterRoleChangeListener;
59 import org.opendaylight.controller.cluster.notifications.RoleChangeNotifier;
60 import org.opendaylight.controller.cluster.raft.RaftActor;
61 import org.opendaylight.controller.cluster.raft.RaftActorRecoveryCohort;
62 import org.opendaylight.controller.cluster.raft.RaftActorSnapshotCohort;
63 import org.opendaylight.controller.cluster.raft.RaftState;
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.messages.ServerRemoved;
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.data.api.schema.tree.TreeType;
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 protected 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);
122 private ShardSnapshot restoreFromSnapshot;
124 private final ShardTransactionMessageRetrySupport messageRetrySupport;
126 protected Shard(AbstractBuilder<?, ?> builder) {
127 super(builder.getId().toString(), builder.getPeerAddresses(),
128 Optional.of(builder.getDatastoreContext().getShardRaftConfig()), DataStoreVersions.CURRENT_VERSION);
130 this.name = builder.getId().toString();
131 this.datastoreContext = builder.getDatastoreContext();
132 this.restoreFromSnapshot = builder.getRestoreFromSnapshot();
134 setPersistence(datastoreContext.isPersistent());
136 LOG.info("Shard created : {}, persistent : {}", name, datastoreContext.isPersistent());
138 store = new ShardDataTree(builder.getSchemaContext(), builder.getTreeType());
140 shardMBean = ShardMBeanFactory.getShardStatsMBean(name.toString(),
141 datastoreContext.getDataStoreMXBeanType());
142 shardMBean.setShard(this);
144 if (isMetricsCaptureEnabled()) {
145 getContext().become(new MeteringBehavior(this));
148 commitCoordinator = new ShardCommitCoordinator(store,
149 datastoreContext.getShardCommitQueueExpiryTimeoutInMillis(),
150 datastoreContext.getShardTransactionCommitQueueCapacity(), LOG, this.name);
152 setTransactionCommitTimeout();
154 // create a notifier actor for each cluster member
155 roleChangeNotifier = createRoleChangeNotifier(name.toString());
157 appendEntriesReplyTracker = new MessageTracker(AppendEntriesReply.class,
158 getRaftActorContext().getConfigParams().getIsolatedCheckIntervalInMillis());
160 transactionActorFactory = new ShardTransactionActorFactory(store, datastoreContext,
161 new Dispatchers(context().system().dispatchers()).getDispatcherPath(
162 Dispatchers.DispatcherType.Transaction), self(), getContext(), shardMBean);
164 snapshotCohort = new ShardSnapshotCohort(transactionActorFactory, store, LOG, this.name);
166 messageRetrySupport = new ShardTransactionMessageRetrySupport(this);
169 private void setTransactionCommitTimeout() {
170 transactionCommitTimeout = TimeUnit.MILLISECONDS.convert(
171 datastoreContext.getShardTransactionCommitTimeoutInSeconds(), TimeUnit.SECONDS) / 2;
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 messageRetrySupport.close();
188 if(txCommitTimeoutCheckSchedule != null) {
189 txCommitTimeoutCheckSchedule.cancel();
192 commitCoordinator.abortPendingTransactions("Transaction aborted due to shutdown.", this);
194 shardMBean.unregisterMBean();
198 public void onReceiveRecover(final Object message) throws Exception {
199 if(LOG.isDebugEnabled()) {
200 LOG.debug("{}: onReceiveRecover: Received message {} from {}", persistenceId(),
201 message.getClass().toString(), getSender());
204 if (message instanceof RecoveryFailure){
205 LOG.error("{}: Recovery failed because of this cause",
206 persistenceId(), ((RecoveryFailure) message).cause());
208 // Even though recovery failed, we still need to finish our recovery, eg send the
209 // ActorInitialized message and start the txCommitTimeoutCheckSchedule.
210 onRecoveryComplete();
212 super.onReceiveRecover(message);
213 if(LOG.isTraceEnabled()) {
214 appendEntriesReplyTracker.begin();
220 public void onReceiveCommand(final Object message) throws Exception {
222 MessageTracker.Context context = appendEntriesReplyTracker.received(message);
224 if(context.error().isPresent()){
225 LOG.trace("{} : AppendEntriesReply failed to arrive at the expected interval {}", persistenceId(),
230 if (CreateTransaction.SERIALIZABLE_CLASS.isInstance(message)) {
231 handleCreateTransaction(message);
232 } else if (BatchedModifications.class.isInstance(message)) {
233 handleBatchedModifications((BatchedModifications)message);
234 } else if (message instanceof ForwardedReadyTransaction) {
235 handleForwardedReadyTransaction((ForwardedReadyTransaction) message);
236 } else if (message instanceof ReadyLocalTransaction) {
237 handleReadyLocalTransaction((ReadyLocalTransaction)message);
238 } else if (CanCommitTransaction.SERIALIZABLE_CLASS.isInstance(message)) {
239 handleCanCommitTransaction(CanCommitTransaction.fromSerializable(message));
240 } else if (CommitTransaction.SERIALIZABLE_CLASS.isInstance(message)) {
241 handleCommitTransaction(CommitTransaction.fromSerializable(message));
242 } else if (AbortTransaction.SERIALIZABLE_CLASS.isInstance(message)) {
243 handleAbortTransaction(AbortTransaction.fromSerializable(message));
244 } else if (CloseTransactionChain.SERIALIZABLE_CLASS.isInstance(message)) {
245 closeTransactionChain(CloseTransactionChain.fromSerializable(message));
246 } else if (message instanceof RegisterChangeListener) {
247 changeSupport.onMessage((RegisterChangeListener) message, isLeader(), hasLeader());
248 } else if (message instanceof RegisterDataTreeChangeListener) {
249 treeChangeSupport.onMessage((RegisterDataTreeChangeListener) message, isLeader(), hasLeader());
250 } else if (message instanceof UpdateSchemaContext) {
251 updateSchemaContext((UpdateSchemaContext) message);
252 } else if (message instanceof PeerAddressResolved) {
253 PeerAddressResolved resolved = (PeerAddressResolved) message;
254 setPeerAddress(resolved.getPeerId().toString(),
255 resolved.getPeerAddress());
256 } else if (message.equals(TX_COMMIT_TIMEOUT_CHECK_MESSAGE)) {
257 commitCoordinator.checkForExpiredTransactions(transactionCommitTimeout, this);
258 } else if(message instanceof DatastoreContext) {
259 onDatastoreContext((DatastoreContext)message);
260 } else if(message instanceof RegisterRoleChangeListener){
261 roleChangeNotifier.get().forward(message, context());
262 } else if (message instanceof FollowerInitialSyncUpStatus) {
263 shardMBean.setFollowerInitialSyncStatus(((FollowerInitialSyncUpStatus) message).isInitialSyncDone());
264 context().parent().tell(message, self());
265 } else if(GET_SHARD_MBEAN_MESSAGE.equals(message)){
266 sender().tell(getShardMBean(), self());
267 } else if(message instanceof GetShardDataTree) {
268 sender().tell(store.getDataTree(), self());
269 } else if(message instanceof ServerRemoved){
270 context().parent().forward(message, context());
271 } else if(ShardTransactionMessageRetrySupport.TIMER_MESSAGE_CLASS.isInstance(message)) {
272 messageRetrySupport.onTimerMessage(message);
274 super.onReceiveCommand(message);
281 private boolean hasLeader() {
282 return getLeaderId() != null;
285 public int getPendingTxCommitQueueSize() {
286 return commitCoordinator.getQueueSize();
289 public int getCohortCacheSize() {
290 return commitCoordinator.getCohortCacheSize();
294 protected Optional<ActorRef> getRoleChangeNotifier() {
295 return roleChangeNotifier;
299 protected LeaderStateChanged newLeaderStateChanged(String memberId, String leaderId, short leaderPayloadVersion) {
300 return new ShardLeaderStateChanged(memberId, leaderId,
301 isLeader() ? Optional.<DataTree>of(store.getDataTree()) : Optional.<DataTree>absent(),
302 leaderPayloadVersion);
305 protected void onDatastoreContext(DatastoreContext context) {
306 datastoreContext = context;
308 commitCoordinator.setQueueCapacity(datastoreContext.getShardTransactionCommitQueueCapacity());
310 setTransactionCommitTimeout();
312 if(datastoreContext.isPersistent() && !persistence().isRecoveryApplicable()) {
313 setPersistence(true);
314 } else if(!datastoreContext.isPersistent() && persistence().isRecoveryApplicable()) {
315 setPersistence(false);
318 updateConfigParams(datastoreContext.getShardRaftConfig());
321 private static boolean isEmptyCommit(final DataTreeCandidate candidate) {
322 return ModificationType.UNMODIFIED.equals(candidate.getRootNode().getModificationType());
325 void continueCommit(final CohortEntry cohortEntry) {
326 final DataTreeCandidate candidate = cohortEntry.getCandidate();
328 // If we do not have any followers and we are not using persistence
329 // or if cohortEntry has no modifications
330 // we can apply modification to the state immediately
331 if ((!hasFollowers() && !persistence().isRecoveryApplicable()) || isEmptyCommit(candidate)) {
332 applyModificationToState(cohortEntry.getReplySender(), cohortEntry.getTransactionID(), candidate);
334 Shard.this.persistData(cohortEntry.getReplySender(), cohortEntry.getTransactionID(),
335 DataTreeCandidatePayload.create(candidate));
339 private void handleCommitTransaction(final CommitTransaction commit) {
340 if(!commitCoordinator.handleCommit(commit.getTransactionID(), getSender(), this)) {
341 shardMBean.incrementFailedTransactionsCount();
345 private void finishCommit(@Nonnull final ActorRef sender, @Nonnull final String transactionID, @Nonnull final CohortEntry cohortEntry) {
346 LOG.debug("{}: Finishing commit for transaction {}", persistenceId(), cohortEntry.getTransactionID());
349 cohortEntry.commit();
351 sender.tell(CommitTransactionReply.INSTANCE.toSerializable(), getSelf());
353 shardMBean.incrementCommittedTransactionCount();
354 shardMBean.setLastCommittedTransactionTime(System.currentTimeMillis());
356 } catch (Exception e) {
357 sender.tell(new akka.actor.Status.Failure(e), getSelf());
359 LOG.error("{}, An exception occurred while committing transaction {}", persistenceId(),
361 shardMBean.incrementFailedTransactionsCount();
363 commitCoordinator.currentTransactionComplete(transactionID, true);
367 private void finishCommit(@Nonnull final ActorRef sender, final @Nonnull String transactionID) {
368 // With persistence enabled, this method is called via applyState by the leader strategy
369 // after the commit has been replicated to a majority of the followers.
371 CohortEntry cohortEntry = commitCoordinator.getCohortEntryIfCurrent(transactionID);
372 if (cohortEntry == null) {
373 // The transaction is no longer the current commit. This can happen if the transaction
374 // was aborted prior, most likely due to timeout in the front-end. We need to finish
375 // committing the transaction though since it was successfully persisted and replicated
376 // however we can't use the original cohort b/c it was already preCommitted and may
377 // conflict with the current commit or may have been aborted so we commit with a new
379 cohortEntry = commitCoordinator.getAndRemoveCohortEntry(transactionID);
380 if(cohortEntry != null) {
382 store.applyForeignCandidate(transactionID, cohortEntry.getCandidate());
383 } catch (DataValidationFailedException e) {
384 shardMBean.incrementFailedTransactionsCount();
385 LOG.error("{}: Failed to re-apply transaction {}", persistenceId(), transactionID, e);
388 sender.tell(CommitTransactionReply.INSTANCE.toSerializable(), getSelf());
390 // This really shouldn't happen - it likely means that persistence or replication
391 // took so long to complete such that the cohort entry was expired from the cache.
392 IllegalStateException ex = new IllegalStateException(
393 String.format("%s: Could not finish committing transaction %s - no CohortEntry found",
394 persistenceId(), transactionID));
395 LOG.error(ex.getMessage());
396 sender.tell(new akka.actor.Status.Failure(ex), getSelf());
399 finishCommit(sender, transactionID, cohortEntry);
403 private void handleCanCommitTransaction(final CanCommitTransaction canCommit) {
404 LOG.debug("{}: Can committing transaction {}", persistenceId(), canCommit.getTransactionID());
405 commitCoordinator.handleCanCommit(canCommit.getTransactionID(), getSender(), this);
408 protected void handleBatchedModificationsLocal(BatchedModifications batched, ActorRef sender) {
410 commitCoordinator.handleBatchedModifications(batched, sender, this);
411 } catch (Exception e) {
412 LOG.error("{}: Error handling BatchedModifications for Tx {}", persistenceId(),
413 batched.getTransactionID(), e);
414 sender.tell(new akka.actor.Status.Failure(e), getSelf());
418 private void handleBatchedModifications(BatchedModifications batched) {
419 // This message is sent to prepare the modifications transaction directly on the Shard as an
420 // optimization to avoid the extra overhead of a separate ShardTransaction actor. On the last
421 // BatchedModifications message, the caller sets the ready flag in the message indicating
422 // modifications are complete. The reply contains the cohort actor path (this actor) for the caller
423 // to initiate the 3-phase commit. This also avoids the overhead of sending an additional
424 // ReadyTransaction message.
426 // If we're not the leader then forward to the leader. This is a safety measure - we shouldn't
427 // normally get here if we're not the leader as the front-end (TransactionProxy) should determine
428 // the primary/leader shard. However with timing and caching on the front-end, there's a small
429 // window where it could have a stale leader during leadership transitions.
431 boolean isLeaderActive = isLeaderActive();
432 if (isLeader() && isLeaderActive) {
433 handleBatchedModificationsLocal(batched, getSender());
435 ActorSelection leader = getLeader();
436 if (!isLeaderActive || leader == null) {
437 messageRetrySupport.addMessageToRetry(batched, getSender(),
438 "Could not commit transaction " + batched.getTransactionID());
440 // TODO: what if this is not the first batch and leadership changed in between batched messages?
441 // We could check if the commitCoordinator already has a cached entry and forward all the previous
442 // batched modifications.
443 LOG.debug("{}: Forwarding BatchedModifications to leader {}", persistenceId(), leader);
444 leader.forward(batched, getContext());
449 private boolean failIfIsolatedLeader(ActorRef sender) {
450 if(isIsolatedLeader()) {
451 sender.tell(new akka.actor.Status.Failure(new NoShardLeaderException(String.format(
452 "Shard %s was the leader but has lost contact with all of its followers. Either all" +
453 " other follower nodes are down or this node is isolated by a network partition.",
454 persistenceId()))), getSelf());
461 protected boolean isIsolatedLeader() {
462 return getRaftState() == RaftState.IsolatedLeader;
465 private void handleReadyLocalTransaction(final ReadyLocalTransaction message) {
466 LOG.debug("{}: handleReadyLocalTransaction for {}", persistenceId(), message.getTransactionID());
468 boolean isLeaderActive = isLeaderActive();
469 if (isLeader() && isLeaderActive) {
471 commitCoordinator.handleReadyLocalTransaction(message, getSender(), this);
472 } catch (Exception e) {
473 LOG.error("{}: Error handling ReadyLocalTransaction for Tx {}", persistenceId(),
474 message.getTransactionID(), e);
475 getSender().tell(new akka.actor.Status.Failure(e), getSelf());
478 ActorSelection leader = getLeader();
479 if (!isLeaderActive || leader == null) {
480 messageRetrySupport.addMessageToRetry(message, getSender(),
481 "Could not commit transaction " + message.getTransactionID());
483 LOG.debug("{}: Forwarding ReadyLocalTransaction to leader {}", persistenceId(), leader);
484 message.setRemoteVersion(getCurrentBehavior().getLeaderPayloadVersion());
485 leader.forward(message, getContext());
490 private void handleForwardedReadyTransaction(ForwardedReadyTransaction forwardedReady) {
491 LOG.debug("{}: handleForwardedReadyTransaction for {}", persistenceId(), forwardedReady.getTransactionID());
493 boolean isLeaderActive = isLeaderActive();
494 if (isLeader() && isLeaderActive) {
495 commitCoordinator.handleForwardedReadyTransaction(forwardedReady, getSender(), this);
497 ActorSelection leader = getLeader();
498 if (!isLeaderActive || leader == null) {
499 messageRetrySupport.addMessageToRetry(forwardedReady, getSender(),
500 "Could not commit transaction " + forwardedReady.getTransactionID());
502 LOG.debug("{}: Forwarding ForwardedReadyTransaction to leader {}", persistenceId(), leader);
504 ReadyLocalTransaction readyLocal = new ReadyLocalTransaction(forwardedReady.getTransactionID(),
505 forwardedReady.getTransaction().getSnapshot(), forwardedReady.isDoImmediateCommit());
506 readyLocal.setRemoteVersion(getCurrentBehavior().getLeaderPayloadVersion());
507 leader.forward(readyLocal, getContext());
512 private void handleAbortTransaction(final AbortTransaction abort) {
513 doAbortTransaction(abort.getTransactionID(), getSender());
516 void doAbortTransaction(final String transactionID, final ActorRef sender) {
517 commitCoordinator.handleAbort(transactionID, sender, this);
520 private void handleCreateTransaction(final Object message) {
522 createTransaction(CreateTransaction.fromSerializable(message));
523 } else if (getLeader() != null) {
524 getLeader().forward(message, getContext());
526 getSender().tell(new akka.actor.Status.Failure(new NoShardLeaderException(
527 "Could not create a shard transaction", persistenceId())), getSelf());
531 private void closeTransactionChain(final CloseTransactionChain closeTransactionChain) {
532 store.closeTransactionChain(closeTransactionChain.getTransactionChainId());
535 private ActorRef createTypedTransactionActor(int transactionType,
536 ShardTransactionIdentifier transactionId, String transactionChainId,
537 short clientVersion ) {
539 return transactionActorFactory.newShardTransaction(TransactionType.fromInt(transactionType),
540 transactionId, transactionChainId, clientVersion);
543 private void createTransaction(CreateTransaction createTransaction) {
545 if(TransactionType.fromInt(createTransaction.getTransactionType()) != TransactionType.READ_ONLY &&
546 failIfIsolatedLeader(getSender())) {
550 ActorRef transactionActor = createTransaction(createTransaction.getTransactionType(),
551 createTransaction.getTransactionId(), createTransaction.getTransactionChainId(),
552 createTransaction.getVersion());
554 getSender().tell(new CreateTransactionReply(Serialization.serializedActorPath(transactionActor),
555 createTransaction.getTransactionId()).toSerializable(), getSelf());
556 } catch (Exception e) {
557 getSender().tell(new akka.actor.Status.Failure(e), getSelf());
561 private ActorRef createTransaction(int transactionType, String remoteTransactionId,
562 String transactionChainId, short clientVersion) {
565 ShardTransactionIdentifier transactionId = new ShardTransactionIdentifier(remoteTransactionId);
567 if(LOG.isDebugEnabled()) {
568 LOG.debug("{}: Creating transaction : {} ", persistenceId(), transactionId);
571 ActorRef transactionActor = createTypedTransactionActor(transactionType, transactionId,
572 transactionChainId, clientVersion);
574 return transactionActor;
577 private void commitWithNewTransaction(final Modification modification) {
578 ReadWriteShardDataTreeTransaction tx = store.newReadWriteTransaction(modification.toString(), null);
579 modification.apply(tx.getSnapshot());
581 snapshotCohort.syncCommitTransaction(tx);
582 shardMBean.incrementCommittedTransactionCount();
583 shardMBean.setLastCommittedTransactionTime(System.currentTimeMillis());
584 } catch (Exception e) {
585 shardMBean.incrementFailedTransactionsCount();
586 LOG.error("{}: Failed to commit", persistenceId(), e);
590 private void updateSchemaContext(final UpdateSchemaContext message) {
591 updateSchemaContext(message.getSchemaContext());
595 void updateSchemaContext(final SchemaContext schemaContext) {
596 store.updateSchemaContext(schemaContext);
599 private boolean isMetricsCaptureEnabled() {
600 CommonConfig config = new CommonConfig(getContext().system().settings().config());
601 return config.isMetricCaptureEnabled();
606 public RaftActorSnapshotCohort getRaftActorSnapshotCohort() {
607 return snapshotCohort;
612 protected RaftActorRecoveryCohort getRaftActorRecoveryCohort() {
613 return new ShardRecoveryCoordinator(store, store.getSchemaContext(),
614 restoreFromSnapshot != null ? restoreFromSnapshot.getSnapshot() : null, persistenceId(), LOG);
618 protected void onRecoveryComplete() {
619 restoreFromSnapshot = null;
621 //notify shard manager
622 getContext().parent().tell(new ActorInitialized(), getSelf());
624 // Being paranoid here - this method should only be called once but just in case...
625 if(txCommitTimeoutCheckSchedule == null) {
626 // Schedule a message to be periodically sent to check if the current in-progress
627 // transaction should be expired and aborted.
628 FiniteDuration period = Duration.create(transactionCommitTimeout / 3, TimeUnit.MILLISECONDS);
629 txCommitTimeoutCheckSchedule = getContext().system().scheduler().schedule(
630 period, period, getSelf(),
631 TX_COMMIT_TIMEOUT_CHECK_MESSAGE, getContext().dispatcher(), ActorRef.noSender());
636 protected void applyState(final ActorRef clientActor, final String identifier, final Object data) {
637 if (data instanceof DataTreeCandidatePayload) {
638 if (clientActor == null) {
639 // No clientActor indicates a replica coming from the leader
641 store.applyForeignCandidate(identifier, ((DataTreeCandidatePayload)data).getCandidate());
642 } catch (DataValidationFailedException | IOException e) {
643 LOG.error("{}: Error applying replica {}", persistenceId(), identifier, e);
646 // Replication consensus reached, proceed to commit
647 finishCommit(clientActor, identifier);
649 } else if (data instanceof ModificationPayload) {
651 applyModificationToState(clientActor, identifier, ((ModificationPayload) data).getModification());
652 } catch (ClassNotFoundException | IOException e) {
653 LOG.error("{}: Error extracting ModificationPayload", persistenceId(), e);
655 } else if (data instanceof CompositeModificationPayload) {
656 Object modification = ((CompositeModificationPayload) data).getModification();
658 applyModificationToState(clientActor, identifier, modification);
659 } else if(data instanceof CompositeModificationByteStringPayload ){
660 Object modification = ((CompositeModificationByteStringPayload) data).getModification();
662 applyModificationToState(clientActor, identifier, modification);
664 LOG.error("{}: Unknown state received {} Class loader = {} CompositeNodeMod.ClassLoader = {}",
665 persistenceId(), data, data.getClass().getClassLoader(),
666 CompositeModificationPayload.class.getClassLoader());
670 private void applyModificationToState(ActorRef clientActor, String identifier, Object modification) {
671 if(modification == null) {
673 "{}: modification is null - this is very unexpected, clientActor = {}, identifier = {}",
674 persistenceId(), identifier, clientActor != null ? clientActor.path().toString() : null);
675 } else if(clientActor == null) {
676 // There's no clientActor to which to send a commit reply so we must be applying
677 // replicated state from the leader.
678 commitWithNewTransaction(MutableCompositeModification.fromSerializable(modification));
680 // This must be the OK to commit after replication consensus.
681 finishCommit(clientActor, identifier);
686 protected void onStateChanged() {
687 boolean isLeader = isLeader();
688 boolean hasLeader = hasLeader();
689 changeSupport.onLeadershipChange(isLeader, hasLeader);
690 treeChangeSupport.onLeadershipChange(isLeader, hasLeader);
692 // If this actor is no longer the leader close all the transaction chains
694 if(LOG.isDebugEnabled()) {
696 "{}: onStateChanged: Closing all transaction chains because shard {} is no longer the leader",
697 persistenceId(), getId());
700 store.closeAllTransactionChains();
702 commitCoordinator.abortPendingTransactions(
703 "The transacton was aborted due to inflight leadership change.", this);
706 if(hasLeader && !isIsolatedLeader()) {
707 messageRetrySupport.retryMessages();
712 protected void onLeaderChanged(String oldLeader, String newLeader) {
713 shardMBean.incrementLeadershipChangeCount();
715 if(hasLeader() && !isIsolatedLeader()) {
716 messageRetrySupport.retryMessages();
721 protected void pauseLeader(Runnable operation) {
722 LOG.debug("{}: In pauseLeader, operation: {}", persistenceId(), operation);
723 commitCoordinator.setRunOnPendingTransactionsComplete(operation);
727 public String persistenceId() {
732 ShardCommitCoordinator getCommitCoordinator() {
733 return commitCoordinator;
736 public DatastoreContext getDatastoreContext() {
737 return datastoreContext;
741 public ShardDataTree getDataStore() {
746 ShardStats getShardMBean() {
750 public static Builder builder() {
751 return new Builder();
754 public static abstract class AbstractBuilder<T extends AbstractBuilder<T, S>, S extends Shard> {
755 private final Class<S> shardClass;
756 private ShardIdentifier id;
757 private Map<String, String> peerAddresses = Collections.emptyMap();
758 private DatastoreContext datastoreContext;
759 private SchemaContext schemaContext;
760 private DatastoreSnapshot.ShardSnapshot restoreFromSnapshot;
761 private volatile boolean sealed;
763 protected AbstractBuilder(Class<S> shardClass) {
764 this.shardClass = shardClass;
767 protected void checkSealed() {
768 Preconditions.checkState(!sealed, "Builder isalready sealed - further modifications are not allowed");
771 @SuppressWarnings("unchecked")
776 public T id(ShardIdentifier id) {
782 public T peerAddresses(Map<String, String> peerAddresses) {
784 this.peerAddresses = peerAddresses;
788 public T datastoreContext(DatastoreContext datastoreContext) {
790 this.datastoreContext = datastoreContext;
794 public T schemaContext(SchemaContext schemaContext) {
796 this.schemaContext = schemaContext;
800 public T restoreFromSnapshot(DatastoreSnapshot.ShardSnapshot restoreFromSnapshot) {
802 this.restoreFromSnapshot = restoreFromSnapshot;
806 public ShardIdentifier getId() {
810 public Map<String, String> getPeerAddresses() {
811 return peerAddresses;
814 public DatastoreContext getDatastoreContext() {
815 return datastoreContext;
818 public SchemaContext getSchemaContext() {
819 return schemaContext;
822 public DatastoreSnapshot.ShardSnapshot getRestoreFromSnapshot() {
823 return restoreFromSnapshot;
826 public TreeType getTreeType() {
827 switch (datastoreContext.getLogicalStoreType()) {
829 return TreeType.CONFIGURATION;
831 return TreeType.OPERATIONAL;
834 throw new IllegalStateException("Unhandled logical store type " + datastoreContext.getLogicalStoreType());
837 protected void verify() {
838 Preconditions.checkNotNull(id, "id should not be null");
839 Preconditions.checkNotNull(peerAddresses, "peerAddresses should not be null");
840 Preconditions.checkNotNull(datastoreContext, "dataStoreContext should not be null");
841 Preconditions.checkNotNull(schemaContext, "schemaContext should not be null");
844 public Props props() {
847 return Props.create(shardClass, this);
851 public static class Builder extends AbstractBuilder<Builder, Shard> {