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.serialization.Serialization;
16 import com.google.common.annotations.VisibleForTesting;
17 import com.google.common.base.Optional;
18 import com.google.common.base.Preconditions;
19 import com.google.common.base.Ticker;
20 import java.io.IOException;
21 import java.util.Collection;
22 import java.util.Collections;
24 import java.util.concurrent.TimeUnit;
25 import javax.annotation.Nonnull;
26 import org.opendaylight.controller.cluster.access.concepts.TransactionIdentifier;
27 import org.opendaylight.controller.cluster.common.actor.CommonConfig;
28 import org.opendaylight.controller.cluster.common.actor.MessageTracker;
29 import org.opendaylight.controller.cluster.common.actor.MessageTracker.Error;
30 import org.opendaylight.controller.cluster.common.actor.MeteringBehavior;
31 import org.opendaylight.controller.cluster.datastore.exceptions.NoShardLeaderException;
32 import org.opendaylight.controller.cluster.datastore.identifiers.ShardIdentifier;
33 import org.opendaylight.controller.cluster.datastore.jmx.mbeans.shard.ShardMBeanFactory;
34 import org.opendaylight.controller.cluster.datastore.jmx.mbeans.shard.ShardStats;
35 import org.opendaylight.controller.cluster.datastore.messages.AbortTransaction;
36 import org.opendaylight.controller.cluster.datastore.messages.ActorInitialized;
37 import org.opendaylight.controller.cluster.datastore.messages.BatchedModifications;
38 import org.opendaylight.controller.cluster.datastore.messages.CanCommitTransaction;
39 import org.opendaylight.controller.cluster.datastore.messages.CloseTransactionChain;
40 import org.opendaylight.controller.cluster.datastore.messages.CommitTransaction;
41 import org.opendaylight.controller.cluster.datastore.messages.CreateTransaction;
42 import org.opendaylight.controller.cluster.datastore.messages.CreateTransactionReply;
43 import org.opendaylight.controller.cluster.datastore.messages.DatastoreSnapshot;
44 import org.opendaylight.controller.cluster.datastore.messages.DatastoreSnapshot.ShardSnapshot;
45 import org.opendaylight.controller.cluster.datastore.messages.ForwardedReadyTransaction;
46 import org.opendaylight.controller.cluster.datastore.messages.GetShardDataTree;
47 import org.opendaylight.controller.cluster.datastore.messages.PeerAddressResolved;
48 import org.opendaylight.controller.cluster.datastore.messages.ReadyLocalTransaction;
49 import org.opendaylight.controller.cluster.datastore.messages.RegisterChangeListener;
50 import org.opendaylight.controller.cluster.datastore.messages.RegisterDataTreeChangeListener;
51 import org.opendaylight.controller.cluster.datastore.messages.ShardLeaderStateChanged;
52 import org.opendaylight.controller.cluster.datastore.messages.UpdateSchemaContext;
53 import org.opendaylight.controller.cluster.datastore.utils.Dispatchers;
54 import org.opendaylight.controller.cluster.notifications.LeaderStateChanged;
55 import org.opendaylight.controller.cluster.notifications.RegisterRoleChangeListener;
56 import org.opendaylight.controller.cluster.notifications.RoleChangeNotifier;
57 import org.opendaylight.controller.cluster.raft.RaftActor;
58 import org.opendaylight.controller.cluster.raft.RaftActorRecoveryCohort;
59 import org.opendaylight.controller.cluster.raft.RaftActorSnapshotCohort;
60 import org.opendaylight.controller.cluster.raft.RaftState;
61 import org.opendaylight.controller.cluster.raft.base.messages.FollowerInitialSyncUpStatus;
62 import org.opendaylight.controller.cluster.raft.messages.AppendEntriesReply;
63 import org.opendaylight.controller.cluster.raft.messages.ServerRemoved;
64 import org.opendaylight.controller.cluster.raft.protobuff.client.messages.Payload;
65 import org.opendaylight.yangtools.concepts.Identifier;
66 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataValidationFailedException;
67 import org.opendaylight.yangtools.yang.data.api.schema.tree.TipProducingDataTree;
68 import org.opendaylight.yangtools.yang.data.api.schema.tree.TreeType;
69 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
70 import scala.concurrent.duration.Duration;
71 import scala.concurrent.duration.FiniteDuration;
74 * A Shard represents a portion of the logical data tree <br/>
76 * Our Shard uses InMemoryDataTree as it's internal representation and delegates all requests it
79 public class Shard extends RaftActor {
82 static final Object TX_COMMIT_TIMEOUT_CHECK_MESSAGE = new Object() {
84 public String toString() {
85 return "txCommitTimeoutCheck";
90 static final Object GET_SHARD_MBEAN_MESSAGE = new Object() {
92 public String toString() {
93 return "getShardMBeanMessage";
97 // FIXME: shard names should be encapsulated in their own class and this should be exposed as a constant.
98 public static final String DEFAULT_NAME = "default";
100 // The state of this Shard
101 private final ShardDataTree store;
103 /// The name of this shard
104 private final String name;
106 private final ShardStats shardMBean;
108 private DatastoreContext datastoreContext;
110 private final ShardCommitCoordinator commitCoordinator;
112 private long transactionCommitTimeout;
114 private Cancellable txCommitTimeoutCheckSchedule;
116 private final Optional<ActorRef> roleChangeNotifier;
118 private final MessageTracker appendEntriesReplyTracker;
120 private final ShardTransactionActorFactory transactionActorFactory;
122 private final ShardSnapshotCohort snapshotCohort;
124 private final DataTreeChangeListenerSupport treeChangeSupport = new DataTreeChangeListenerSupport(this);
125 private final DataChangeListenerSupport changeSupport = new DataChangeListenerSupport(this);
128 private ShardSnapshot restoreFromSnapshot;
130 private final ShardTransactionMessageRetrySupport messageRetrySupport;
132 private final FrontendMetadata frontendMetadata = new FrontendMetadata();
134 protected Shard(final AbstractBuilder<?, ?> builder) {
135 super(builder.getId().toString(), builder.getPeerAddresses(),
136 Optional.of(builder.getDatastoreContext().getShardRaftConfig()), DataStoreVersions.CURRENT_VERSION);
138 this.name = builder.getId().toString();
139 this.datastoreContext = builder.getDatastoreContext();
140 this.restoreFromSnapshot = builder.getRestoreFromSnapshot();
142 setPersistence(datastoreContext.isPersistent());
144 LOG.info("Shard created : {}, persistent : {}", name, datastoreContext.isPersistent());
146 ShardDataTreeChangeListenerPublisherActorProxy treeChangeListenerPublisher =
147 new ShardDataTreeChangeListenerPublisherActorProxy(getContext(), name + "-DTCL-publisher");
148 ShardDataChangeListenerPublisherActorProxy dataChangeListenerPublisher =
149 new ShardDataChangeListenerPublisherActorProxy(getContext(), name + "-DCL-publisher");
150 if(builder.getDataTree() != null) {
151 store = new ShardDataTree(this, builder.getSchemaContext(), builder.getDataTree(),
152 treeChangeListenerPublisher, dataChangeListenerPublisher, name);
154 store = new ShardDataTree(this, builder.getSchemaContext(), builder.getTreeType(),
155 treeChangeListenerPublisher, dataChangeListenerPublisher, name);
158 shardMBean = ShardMBeanFactory.getShardStatsMBean(name.toString(),
159 datastoreContext.getDataStoreMXBeanType());
160 shardMBean.setShard(this);
162 if (isMetricsCaptureEnabled()) {
163 getContext().become(new MeteringBehavior(this));
166 commitCoordinator = new ShardCommitCoordinator(store, LOG, this.name);
168 setTransactionCommitTimeout();
170 // create a notifier actor for each cluster member
171 roleChangeNotifier = createRoleChangeNotifier(name.toString());
173 appendEntriesReplyTracker = new MessageTracker(AppendEntriesReply.class,
174 getRaftActorContext().getConfigParams().getIsolatedCheckIntervalInMillis());
176 transactionActorFactory = new ShardTransactionActorFactory(store, datastoreContext,
177 new Dispatchers(context().system().dispatchers()).getDispatcherPath(
178 Dispatchers.DispatcherType.Transaction), self(), getContext(), shardMBean);
180 snapshotCohort = ShardSnapshotCohort.create(getContext(), builder.getId().getMemberName(), store, LOG,
183 messageRetrySupport = new ShardTransactionMessageRetrySupport(this);
186 private void setTransactionCommitTimeout() {
187 transactionCommitTimeout = TimeUnit.MILLISECONDS.convert(
188 datastoreContext.getShardTransactionCommitTimeoutInSeconds(), TimeUnit.SECONDS) / 2;
191 private Optional<ActorRef> createRoleChangeNotifier(final String shardId) {
192 ActorRef shardRoleChangeNotifier = this.getContext().actorOf(
193 RoleChangeNotifier.getProps(shardId), shardId + "-notifier");
194 return Optional.of(shardRoleChangeNotifier);
198 public void postStop() {
199 LOG.info("Stopping Shard {}", persistenceId());
203 messageRetrySupport.close();
205 if (txCommitTimeoutCheckSchedule != null) {
206 txCommitTimeoutCheckSchedule.cancel();
209 commitCoordinator.abortPendingTransactions("Transaction aborted due to shutdown.", this);
211 shardMBean.unregisterMBean();
215 protected void handleRecover(final Object message) {
216 LOG.debug("{}: onReceiveRecover: Received message {} from {}", persistenceId(), message.getClass(),
219 super.handleRecover(message);
220 if (LOG.isTraceEnabled()) {
221 appendEntriesReplyTracker.begin();
226 protected void handleNonRaftCommand(final Object message) {
227 try (final MessageTracker.Context context = appendEntriesReplyTracker.received(message)) {
228 final Optional<Error> maybeError = context.error();
229 if (maybeError.isPresent()) {
230 LOG.trace("{} : AppendEntriesReply failed to arrive at the expected interval {}", persistenceId(),
234 if (CreateTransaction.isSerializedType(message)) {
235 handleCreateTransaction(message);
236 } else if (message instanceof BatchedModifications) {
237 handleBatchedModifications((BatchedModifications)message);
238 } else if (message instanceof ForwardedReadyTransaction) {
239 handleForwardedReadyTransaction((ForwardedReadyTransaction) message);
240 } else if (message instanceof ReadyLocalTransaction) {
241 handleReadyLocalTransaction((ReadyLocalTransaction)message);
242 } else if (CanCommitTransaction.isSerializedType(message)) {
243 handleCanCommitTransaction(CanCommitTransaction.fromSerializable(message));
244 } else if (CommitTransaction.isSerializedType(message)) {
245 handleCommitTransaction(CommitTransaction.fromSerializable(message));
246 } else if (AbortTransaction.isSerializedType(message)) {
247 handleAbortTransaction(AbortTransaction.fromSerializable(message));
248 } else if (CloseTransactionChain.isSerializedType(message)) {
249 closeTransactionChain(CloseTransactionChain.fromSerializable(message));
250 } else if (message instanceof RegisterChangeListener) {
251 changeSupport.onMessage((RegisterChangeListener) message, isLeader(), hasLeader());
252 } else if (message instanceof RegisterDataTreeChangeListener) {
253 treeChangeSupport.onMessage((RegisterDataTreeChangeListener) message, isLeader(), hasLeader());
254 } else if (message instanceof UpdateSchemaContext) {
255 updateSchemaContext((UpdateSchemaContext) message);
256 } else if (message instanceof PeerAddressResolved) {
257 PeerAddressResolved resolved = (PeerAddressResolved) message;
258 setPeerAddress(resolved.getPeerId().toString(),
259 resolved.getPeerAddress());
260 } else if (TX_COMMIT_TIMEOUT_CHECK_MESSAGE.equals(message)) {
261 store.checkForExpiredTransactions(transactionCommitTimeout);
262 commitCoordinator.checkForExpiredTransactions(transactionCommitTimeout, this);
263 } else if (message instanceof DatastoreContext) {
264 onDatastoreContext((DatastoreContext)message);
265 } else if (message instanceof RegisterRoleChangeListener){
266 roleChangeNotifier.get().forward(message, context());
267 } else if (message instanceof FollowerInitialSyncUpStatus) {
268 shardMBean.setFollowerInitialSyncStatus(((FollowerInitialSyncUpStatus) message).isInitialSyncDone());
269 context().parent().tell(message, self());
270 } else if (GET_SHARD_MBEAN_MESSAGE.equals(message)){
271 sender().tell(getShardMBean(), self());
272 } else if (message instanceof GetShardDataTree) {
273 sender().tell(store.getDataTree(), self());
274 } else if (message instanceof ServerRemoved){
275 context().parent().forward(message, context());
276 } else if (ShardTransactionMessageRetrySupport.TIMER_MESSAGE_CLASS.isInstance(message)) {
277 messageRetrySupport.onTimerMessage(message);
278 } else if (message instanceof DataTreeCohortActorRegistry.CohortRegistryCommand) {
279 store.processCohortRegistryCommand(getSender(),
280 (DataTreeCohortActorRegistry.CohortRegistryCommand) message);
282 super.handleNonRaftCommand(message);
287 private boolean hasLeader() {
288 return getLeaderId() != null;
291 public int getPendingTxCommitQueueSize() {
292 return store.getQueueSize();
295 public int getCohortCacheSize() {
296 return commitCoordinator.getCohortCacheSize();
300 protected Optional<ActorRef> getRoleChangeNotifier() {
301 return roleChangeNotifier;
305 protected LeaderStateChanged newLeaderStateChanged(final String memberId, final String leaderId, final short leaderPayloadVersion) {
306 return isLeader() ? new ShardLeaderStateChanged(memberId, leaderId, store.getDataTree(), leaderPayloadVersion)
307 : new ShardLeaderStateChanged(memberId, leaderId, leaderPayloadVersion);
310 protected void onDatastoreContext(final DatastoreContext context) {
311 datastoreContext = context;
313 setTransactionCommitTimeout();
315 setPersistence(datastoreContext.isPersistent());
317 updateConfigParams(datastoreContext.getShardRaftConfig());
320 boolean canSkipPayload() {
321 // If we do not have any followers and we are not using persistence we can apply modification to the state
323 return !hasFollowers() && !persistence().isRecoveryApplicable();
326 // applyState() will be invoked once consensus is reached on the payload
327 void persistPayload(final TransactionIdentifier transactionId, final Payload payload) {
328 // We are faking the sender
329 persistData(self(), transactionId, payload);
332 private void handleCommitTransaction(final CommitTransaction commit) {
334 commitCoordinator.handleCommit(commit.getTransactionID(), getSender(), this);
336 ActorSelection leader = getLeader();
337 if (leader == null) {
338 messageRetrySupport.addMessageToRetry(commit, getSender(),
339 "Could not commit transaction " + commit.getTransactionID());
341 LOG.debug("{}: Forwarding CommitTransaction to leader {}", persistenceId(), leader);
342 leader.forward(commit, getContext());
347 private void handleCanCommitTransaction(final CanCommitTransaction canCommit) {
348 LOG.debug("{}: Can committing transaction {}", persistenceId(), canCommit.getTransactionID());
351 commitCoordinator.handleCanCommit(canCommit.getTransactionID(), getSender(), this);
353 ActorSelection leader = getLeader();
354 if (leader == null) {
355 messageRetrySupport.addMessageToRetry(canCommit, getSender(),
356 "Could not canCommit transaction " + canCommit.getTransactionID());
358 LOG.debug("{}: Forwarding CanCommitTransaction to leader {}", persistenceId(), leader);
359 leader.forward(canCommit, getContext());
364 protected void handleBatchedModificationsLocal(final BatchedModifications batched, final ActorRef sender) {
366 commitCoordinator.handleBatchedModifications(batched, sender, this);
367 } catch (Exception e) {
368 LOG.error("{}: Error handling BatchedModifications for Tx {}", persistenceId(),
369 batched.getTransactionID(), e);
370 sender.tell(new akka.actor.Status.Failure(e), getSelf());
374 private void handleBatchedModifications(final BatchedModifications batched) {
375 // This message is sent to prepare the modifications transaction directly on the Shard as an
376 // optimization to avoid the extra overhead of a separate ShardTransaction actor. On the last
377 // BatchedModifications message, the caller sets the ready flag in the message indicating
378 // modifications are complete. The reply contains the cohort actor path (this actor) for the caller
379 // to initiate the 3-phase commit. This also avoids the overhead of sending an additional
380 // ReadyTransaction message.
382 // If we're not the leader then forward to the leader. This is a safety measure - we shouldn't
383 // normally get here if we're not the leader as the front-end (TransactionProxy) should determine
384 // the primary/leader shard. However with timing and caching on the front-end, there's a small
385 // window where it could have a stale leader during leadership transitions.
387 boolean isLeaderActive = isLeaderActive();
388 if (isLeader() && isLeaderActive) {
389 handleBatchedModificationsLocal(batched, getSender());
391 ActorSelection leader = getLeader();
392 if (!isLeaderActive || leader == null) {
393 messageRetrySupport.addMessageToRetry(batched, getSender(),
394 "Could not commit transaction " + batched.getTransactionID());
396 // If this is not the first batch and leadership changed in between batched messages,
397 // we need to reconstruct previous BatchedModifications from the transaction
398 // DataTreeModification, honoring the max batched modification count, and forward all the
399 // previous BatchedModifications to the new leader.
400 Collection<BatchedModifications> newModifications = commitCoordinator.createForwardedBatchedModifications(
401 batched, datastoreContext.getShardBatchedModificationCount());
403 LOG.debug("{}: Forwarding {} BatchedModifications to leader {}", persistenceId(),
404 newModifications.size(), leader);
406 for (BatchedModifications bm : newModifications) {
407 leader.forward(bm, getContext());
413 private boolean failIfIsolatedLeader(final ActorRef sender) {
414 if (isIsolatedLeader()) {
415 sender.tell(new akka.actor.Status.Failure(new NoShardLeaderException(String.format(
416 "Shard %s was the leader but has lost contact with all of its followers. Either all" +
417 " other follower nodes are down or this node is isolated by a network partition.",
418 persistenceId()))), getSelf());
425 protected boolean isIsolatedLeader() {
426 return getRaftState() == RaftState.IsolatedLeader;
429 private void handleReadyLocalTransaction(final ReadyLocalTransaction message) {
430 LOG.debug("{}: handleReadyLocalTransaction for {}", persistenceId(), message.getTransactionID());
432 boolean isLeaderActive = isLeaderActive();
433 if (isLeader() && isLeaderActive) {
435 commitCoordinator.handleReadyLocalTransaction(message, getSender(), this);
436 } catch (Exception e) {
437 LOG.error("{}: Error handling ReadyLocalTransaction for Tx {}", persistenceId(),
438 message.getTransactionID(), e);
439 getSender().tell(new akka.actor.Status.Failure(e), getSelf());
442 ActorSelection leader = getLeader();
443 if (!isLeaderActive || leader == null) {
444 messageRetrySupport.addMessageToRetry(message, getSender(),
445 "Could not commit transaction " + message.getTransactionID());
447 LOG.debug("{}: Forwarding ReadyLocalTransaction to leader {}", persistenceId(), leader);
448 message.setRemoteVersion(getCurrentBehavior().getLeaderPayloadVersion());
449 leader.forward(message, getContext());
454 private void handleForwardedReadyTransaction(final ForwardedReadyTransaction forwardedReady) {
455 LOG.debug("{}: handleForwardedReadyTransaction for {}", persistenceId(), forwardedReady.getTransactionID());
457 boolean isLeaderActive = isLeaderActive();
458 if (isLeader() && isLeaderActive) {
459 commitCoordinator.handleForwardedReadyTransaction(forwardedReady, getSender(), this);
461 ActorSelection leader = getLeader();
462 if (!isLeaderActive || leader == null) {
463 messageRetrySupport.addMessageToRetry(forwardedReady, getSender(),
464 "Could not commit transaction " + forwardedReady.getTransactionID());
466 LOG.debug("{}: Forwarding ForwardedReadyTransaction to leader {}", persistenceId(), leader);
468 ReadyLocalTransaction readyLocal = new ReadyLocalTransaction(forwardedReady.getTransactionID(),
469 forwardedReady.getTransaction().getSnapshot(), forwardedReady.isDoImmediateCommit());
470 readyLocal.setRemoteVersion(getCurrentBehavior().getLeaderPayloadVersion());
471 leader.forward(readyLocal, getContext());
476 private void handleAbortTransaction(final AbortTransaction abort) {
477 doAbortTransaction(abort.getTransactionID(), getSender());
480 void doAbortTransaction(final TransactionIdentifier transactionID, final ActorRef sender) {
481 commitCoordinator.handleAbort(transactionID, sender, this);
484 private void handleCreateTransaction(final Object message) {
486 createTransaction(CreateTransaction.fromSerializable(message));
487 } else if (getLeader() != null) {
488 getLeader().forward(message, getContext());
490 getSender().tell(new akka.actor.Status.Failure(new NoShardLeaderException(
491 "Could not create a shard transaction", persistenceId())), getSelf());
495 private void closeTransactionChain(final CloseTransactionChain closeTransactionChain) {
496 store.closeTransactionChain(closeTransactionChain.getIdentifier());
499 private void createTransaction(final CreateTransaction createTransaction) {
501 if (TransactionType.fromInt(createTransaction.getTransactionType()) != TransactionType.READ_ONLY &&
502 failIfIsolatedLeader(getSender())) {
506 ActorRef transactionActor = createTransaction(createTransaction.getTransactionType(),
507 createTransaction.getTransactionId());
509 getSender().tell(new CreateTransactionReply(Serialization.serializedActorPath(transactionActor),
510 createTransaction.getTransactionId(), createTransaction.getVersion()).toSerializable(), getSelf());
511 } catch (Exception e) {
512 getSender().tell(new akka.actor.Status.Failure(e), getSelf());
516 private ActorRef createTransaction(final int transactionType, final TransactionIdentifier transactionId) {
517 LOG.debug("{}: Creating transaction : {} ", persistenceId(), transactionId);
518 return transactionActorFactory.newShardTransaction(TransactionType.fromInt(transactionType),
522 private void updateSchemaContext(final UpdateSchemaContext message) {
523 updateSchemaContext(message.getSchemaContext());
527 void updateSchemaContext(final SchemaContext schemaContext) {
528 store.updateSchemaContext(schemaContext);
531 private boolean isMetricsCaptureEnabled() {
532 CommonConfig config = new CommonConfig(getContext().system().settings().config());
533 return config.isMetricCaptureEnabled();
538 public RaftActorSnapshotCohort getRaftActorSnapshotCohort() {
539 return snapshotCohort;
544 protected RaftActorRecoveryCohort getRaftActorRecoveryCohort() {
545 return new ShardRecoveryCoordinator(store,
546 restoreFromSnapshot != null ? restoreFromSnapshot.getSnapshot() : null, persistenceId(), LOG);
550 protected void onRecoveryComplete() {
551 restoreFromSnapshot = null;
553 //notify shard manager
554 getContext().parent().tell(new ActorInitialized(), getSelf());
556 // Being paranoid here - this method should only be called once but just in case...
557 if (txCommitTimeoutCheckSchedule == null) {
558 // Schedule a message to be periodically sent to check if the current in-progress
559 // transaction should be expired and aborted.
560 FiniteDuration period = Duration.create(transactionCommitTimeout / 3, TimeUnit.MILLISECONDS);
561 txCommitTimeoutCheckSchedule = getContext().system().scheduler().schedule(
562 period, period, getSelf(),
563 TX_COMMIT_TIMEOUT_CHECK_MESSAGE, getContext().dispatcher(), ActorRef.noSender());
568 protected void applyState(final ActorRef clientActor, final Identifier identifier, final Object data) {
569 if (data instanceof Payload) {
571 store.applyReplicatedPayload(identifier, (Payload)data);
572 } catch (DataValidationFailedException | IOException e) {
573 LOG.error("{}: Error applying replica {}", persistenceId(), identifier, e);
576 LOG.error("{}: Unknown state for {} received {}", persistenceId(), identifier, data);
581 protected void onStateChanged() {
582 boolean isLeader = isLeader();
583 boolean hasLeader = hasLeader();
584 changeSupport.onLeadershipChange(isLeader, hasLeader);
585 treeChangeSupport.onLeadershipChange(isLeader, hasLeader);
587 // If this actor is no longer the leader close all the transaction chains
589 if (LOG.isDebugEnabled()) {
591 "{}: onStateChanged: Closing all transaction chains because shard {} is no longer the leader",
592 persistenceId(), getId());
595 store.closeAllTransactionChains();
598 if (hasLeader && !isIsolatedLeader()) {
599 messageRetrySupport.retryMessages();
604 protected void onLeaderChanged(final String oldLeader, final String newLeader) {
605 shardMBean.incrementLeadershipChangeCount();
607 boolean hasLeader = hasLeader();
608 if (hasLeader && !isLeader()) {
609 // Another leader was elected. If we were the previous leader and had pending transactions, convert
610 // them to transaction messages and send to the new leader.
611 ActorSelection leader = getLeader();
612 if (leader != null) {
613 Collection<?> messagesToForward = commitCoordinator.convertPendingTransactionsToMessages(
614 datastoreContext.getShardBatchedModificationCount());
616 if (!messagesToForward.isEmpty()) {
617 LOG.debug("{}: Forwarding {} pending transaction messages to leader {}", persistenceId(),
618 messagesToForward.size(), leader);
620 for (Object message : messagesToForward) {
621 leader.tell(message, self());
625 commitCoordinator.abortPendingTransactions(
626 "The transacton was aborted due to inflight leadership change and the leader address isn't available.",
631 if (hasLeader && !isIsolatedLeader()) {
632 messageRetrySupport.retryMessages();
637 protected void pauseLeader(final Runnable operation) {
638 LOG.debug("{}: In pauseLeader, operation: {}", persistenceId(), operation);
639 store.setRunOnPendingTransactionsComplete(operation);
643 public String persistenceId() {
648 ShardCommitCoordinator getCommitCoordinator() {
649 return commitCoordinator;
652 public DatastoreContext getDatastoreContext() {
653 return datastoreContext;
657 public ShardDataTree getDataStore() {
662 ShardStats getShardMBean() {
666 public static Builder builder() {
667 return new Builder();
670 public static abstract class AbstractBuilder<T extends AbstractBuilder<T, S>, S extends Shard> {
671 private final Class<S> shardClass;
672 private ShardIdentifier id;
673 private Map<String, String> peerAddresses = Collections.emptyMap();
674 private DatastoreContext datastoreContext;
675 private SchemaContext schemaContext;
676 private DatastoreSnapshot.ShardSnapshot restoreFromSnapshot;
677 private TipProducingDataTree dataTree;
678 private volatile boolean sealed;
680 protected AbstractBuilder(final Class<S> shardClass) {
681 this.shardClass = shardClass;
684 protected void checkSealed() {
685 Preconditions.checkState(!sealed, "Builder isalready sealed - further modifications are not allowed");
688 @SuppressWarnings("unchecked")
693 public T id(final ShardIdentifier id) {
699 public T peerAddresses(final Map<String, String> peerAddresses) {
701 this.peerAddresses = peerAddresses;
705 public T datastoreContext(final DatastoreContext datastoreContext) {
707 this.datastoreContext = datastoreContext;
711 public T schemaContext(final SchemaContext schemaContext) {
713 this.schemaContext = schemaContext;
717 public T restoreFromSnapshot(final DatastoreSnapshot.ShardSnapshot restoreFromSnapshot) {
719 this.restoreFromSnapshot = restoreFromSnapshot;
723 public T dataTree(final TipProducingDataTree dataTree) {
725 this.dataTree = dataTree;
729 public ShardIdentifier getId() {
733 public Map<String, String> getPeerAddresses() {
734 return peerAddresses;
737 public DatastoreContext getDatastoreContext() {
738 return datastoreContext;
741 public SchemaContext getSchemaContext() {
742 return schemaContext;
745 public DatastoreSnapshot.ShardSnapshot getRestoreFromSnapshot() {
746 return restoreFromSnapshot;
749 public TipProducingDataTree getDataTree() {
753 public TreeType getTreeType() {
754 switch (datastoreContext.getLogicalStoreType()) {
756 return TreeType.CONFIGURATION;
758 return TreeType.OPERATIONAL;
761 throw new IllegalStateException("Unhandled logical store type " + datastoreContext.getLogicalStoreType());
764 protected void verify() {
765 Preconditions.checkNotNull(id, "id should not be null");
766 Preconditions.checkNotNull(peerAddresses, "peerAddresses should not be null");
767 Preconditions.checkNotNull(datastoreContext, "dataStoreContext should not be null");
768 Preconditions.checkNotNull(schemaContext, "schemaContext should not be null");
771 public Props props() {
774 return Props.create(shardClass, this);
778 public static class Builder extends AbstractBuilder<Builder, Shard> {
785 return Ticker.systemTicker();