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.
76 * Our Shard uses InMemoryDataTree as it's internal representation and delegates all requests it
78 public class Shard extends RaftActor {
81 static final Object TX_COMMIT_TIMEOUT_CHECK_MESSAGE = new Object() {
83 public String toString() {
84 return "txCommitTimeoutCheck";
89 static final Object GET_SHARD_MBEAN_MESSAGE = new Object() {
91 public String toString() {
92 return "getShardMBeanMessage";
96 // FIXME: shard names should be encapsulated in their own class and this should be exposed as a constant.
97 public static final String DEFAULT_NAME = "default";
99 // The state of this Shard
100 private final ShardDataTree store;
102 /// The name of this shard
103 private final String name;
105 private final ShardStats shardMBean;
107 private DatastoreContext datastoreContext;
109 private final ShardCommitCoordinator commitCoordinator;
111 private long transactionCommitTimeout;
113 private Cancellable txCommitTimeoutCheckSchedule;
115 private final Optional<ActorRef> roleChangeNotifier;
117 private final MessageTracker appendEntriesReplyTracker;
119 private final ShardTransactionActorFactory transactionActorFactory;
121 private final ShardSnapshotCohort snapshotCohort;
123 private final DataTreeChangeListenerSupport treeChangeSupport = new DataTreeChangeListenerSupport(this);
124 private final DataChangeListenerSupport changeSupport = new DataChangeListenerSupport(this);
127 private ShardSnapshot restoreFromSnapshot;
129 private final ShardTransactionMessageRetrySupport messageRetrySupport;
131 private final FrontendMetadata frontendMetadata = new FrontendMetadata();
133 protected Shard(final AbstractBuilder<?, ?> builder) {
134 super(builder.getId().toString(), builder.getPeerAddresses(),
135 Optional.of(builder.getDatastoreContext().getShardRaftConfig()), DataStoreVersions.CURRENT_VERSION);
137 this.name = builder.getId().toString();
138 this.datastoreContext = builder.getDatastoreContext();
139 this.restoreFromSnapshot = builder.getRestoreFromSnapshot();
141 setPersistence(datastoreContext.isPersistent());
143 LOG.info("Shard created : {}, persistent : {}", name, datastoreContext.isPersistent());
145 ShardDataTreeChangeListenerPublisherActorProxy treeChangeListenerPublisher =
146 new ShardDataTreeChangeListenerPublisherActorProxy(getContext(), name + "-DTCL-publisher");
147 ShardDataChangeListenerPublisherActorProxy dataChangeListenerPublisher =
148 new ShardDataChangeListenerPublisherActorProxy(getContext(), name + "-DCL-publisher");
149 if (builder.getDataTree() != null) {
150 store = new ShardDataTree(this, builder.getSchemaContext(), builder.getDataTree(),
151 treeChangeListenerPublisher, dataChangeListenerPublisher, name);
153 store = new ShardDataTree(this, builder.getSchemaContext(), builder.getTreeType(),
154 treeChangeListenerPublisher, dataChangeListenerPublisher, name);
157 shardMBean = ShardMBeanFactory.getShardStatsMBean(name, datastoreContext.getDataStoreMXBeanType(), this);
159 if (isMetricsCaptureEnabled()) {
160 getContext().become(new MeteringBehavior(this));
163 commitCoordinator = new ShardCommitCoordinator(store, LOG, this.name);
165 setTransactionCommitTimeout();
167 // create a notifier actor for each cluster member
168 roleChangeNotifier = createRoleChangeNotifier(name);
170 appendEntriesReplyTracker = new MessageTracker(AppendEntriesReply.class,
171 getRaftActorContext().getConfigParams().getIsolatedCheckIntervalInMillis());
173 transactionActorFactory = new ShardTransactionActorFactory(store, datastoreContext,
174 new Dispatchers(context().system().dispatchers()).getDispatcherPath(
175 Dispatchers.DispatcherType.Transaction), self(), getContext(), shardMBean);
177 snapshotCohort = ShardSnapshotCohort.create(getContext(), builder.getId().getMemberName(), store, LOG,
180 messageRetrySupport = new ShardTransactionMessageRetrySupport(this);
183 private void setTransactionCommitTimeout() {
184 transactionCommitTimeout = TimeUnit.MILLISECONDS.convert(
185 datastoreContext.getShardTransactionCommitTimeoutInSeconds(), TimeUnit.SECONDS) / 2;
188 private Optional<ActorRef> createRoleChangeNotifier(final String shardId) {
189 ActorRef shardRoleChangeNotifier = this.getContext().actorOf(
190 RoleChangeNotifier.getProps(shardId), shardId + "-notifier");
191 return Optional.of(shardRoleChangeNotifier);
195 public void postStop() {
196 LOG.info("Stopping Shard {}", persistenceId());
200 messageRetrySupport.close();
202 if (txCommitTimeoutCheckSchedule != null) {
203 txCommitTimeoutCheckSchedule.cancel();
206 commitCoordinator.abortPendingTransactions("Transaction aborted due to shutdown.", this);
208 shardMBean.unregisterMBean();
212 protected void handleRecover(final Object message) {
213 LOG.debug("{}: onReceiveRecover: Received message {} from {}", persistenceId(), message.getClass(),
216 super.handleRecover(message);
217 if (LOG.isTraceEnabled()) {
218 appendEntriesReplyTracker.begin();
223 protected void handleNonRaftCommand(final Object message) {
224 try (final MessageTracker.Context context = appendEntriesReplyTracker.received(message)) {
225 final Optional<Error> maybeError = context.error();
226 if (maybeError.isPresent()) {
227 LOG.trace("{} : AppendEntriesReply failed to arrive at the expected interval {}", persistenceId(),
231 if (CreateTransaction.isSerializedType(message)) {
232 handleCreateTransaction(message);
233 } else if (message instanceof BatchedModifications) {
234 handleBatchedModifications((BatchedModifications)message);
235 } else if (message instanceof ForwardedReadyTransaction) {
236 handleForwardedReadyTransaction((ForwardedReadyTransaction) message);
237 } else if (message instanceof ReadyLocalTransaction) {
238 handleReadyLocalTransaction((ReadyLocalTransaction)message);
239 } else if (CanCommitTransaction.isSerializedType(message)) {
240 handleCanCommitTransaction(CanCommitTransaction.fromSerializable(message));
241 } else if (CommitTransaction.isSerializedType(message)) {
242 handleCommitTransaction(CommitTransaction.fromSerializable(message));
243 } else if (AbortTransaction.isSerializedType(message)) {
244 handleAbortTransaction(AbortTransaction.fromSerializable(message));
245 } else if (CloseTransactionChain.isSerializedType(message)) {
246 closeTransactionChain(CloseTransactionChain.fromSerializable(message));
247 } else if (message instanceof RegisterChangeListener) {
248 changeSupport.onMessage((RegisterChangeListener) message, isLeader(), hasLeader());
249 } else if (message instanceof RegisterDataTreeChangeListener) {
250 treeChangeSupport.onMessage((RegisterDataTreeChangeListener) message, isLeader(), hasLeader());
251 } else if (message instanceof UpdateSchemaContext) {
252 updateSchemaContext((UpdateSchemaContext) message);
253 } else if (message instanceof PeerAddressResolved) {
254 PeerAddressResolved resolved = (PeerAddressResolved) message;
255 setPeerAddress(resolved.getPeerId(), resolved.getPeerAddress());
256 } else if (TX_COMMIT_TIMEOUT_CHECK_MESSAGE.equals(message)) {
257 store.checkForExpiredTransactions(transactionCommitTimeout);
258 commitCoordinator.checkForExpiredTransactions(transactionCommitTimeout, this);
259 } else if (message instanceof DatastoreContext) {
260 onDatastoreContext((DatastoreContext)message);
261 } else if (message instanceof RegisterRoleChangeListener) {
262 roleChangeNotifier.get().forward(message, context());
263 } else if (message instanceof FollowerInitialSyncUpStatus) {
264 shardMBean.setFollowerInitialSyncStatus(((FollowerInitialSyncUpStatus) message).isInitialSyncDone());
265 context().parent().tell(message, self());
266 } else if (GET_SHARD_MBEAN_MESSAGE.equals(message)) {
267 sender().tell(getShardMBean(), self());
268 } else if (message instanceof GetShardDataTree) {
269 sender().tell(store.getDataTree(), self());
270 } else if (message instanceof ServerRemoved) {
271 context().parent().forward(message, context());
272 } else if (ShardTransactionMessageRetrySupport.TIMER_MESSAGE_CLASS.isInstance(message)) {
273 messageRetrySupport.onTimerMessage(message);
274 } else if (message instanceof DataTreeCohortActorRegistry.CohortRegistryCommand) {
275 store.processCohortRegistryCommand(getSender(),
276 (DataTreeCohortActorRegistry.CohortRegistryCommand) message);
278 super.handleNonRaftCommand(message);
283 private boolean hasLeader() {
284 return getLeaderId() != null;
287 public int getPendingTxCommitQueueSize() {
288 return store.getQueueSize();
291 public int getCohortCacheSize() {
292 return commitCoordinator.getCohortCacheSize();
296 protected Optional<ActorRef> getRoleChangeNotifier() {
297 return roleChangeNotifier;
301 protected LeaderStateChanged newLeaderStateChanged(final String memberId, final String leaderId,
302 final short leaderPayloadVersion) {
303 return isLeader() ? new ShardLeaderStateChanged(memberId, leaderId, store.getDataTree(), leaderPayloadVersion)
304 : new ShardLeaderStateChanged(memberId, leaderId, leaderPayloadVersion);
307 protected void onDatastoreContext(final DatastoreContext context) {
308 datastoreContext = context;
310 setTransactionCommitTimeout();
312 setPersistence(datastoreContext.isPersistent());
314 updateConfigParams(datastoreContext.getShardRaftConfig());
317 boolean canSkipPayload() {
318 // If we do not have any followers and we are not using persistence we can apply modification to the state
320 return !hasFollowers() && !persistence().isRecoveryApplicable();
323 // applyState() will be invoked once consensus is reached on the payload
324 void persistPayload(final TransactionIdentifier transactionId, final Payload payload) {
325 // We are faking the sender
326 persistData(self(), transactionId, payload);
329 private void handleCommitTransaction(final CommitTransaction commit) {
331 commitCoordinator.handleCommit(commit.getTransactionId(), getSender(), this);
333 ActorSelection leader = getLeader();
334 if (leader == null) {
335 messageRetrySupport.addMessageToRetry(commit, getSender(),
336 "Could not commit transaction " + commit.getTransactionId());
338 LOG.debug("{}: Forwarding CommitTransaction to leader {}", persistenceId(), leader);
339 leader.forward(commit, getContext());
344 private void handleCanCommitTransaction(final CanCommitTransaction canCommit) {
345 LOG.debug("{}: Can committing transaction {}", persistenceId(), canCommit.getTransactionId());
348 commitCoordinator.handleCanCommit(canCommit.getTransactionId(), getSender(), this);
350 ActorSelection leader = getLeader();
351 if (leader == null) {
352 messageRetrySupport.addMessageToRetry(canCommit, getSender(),
353 "Could not canCommit transaction " + canCommit.getTransactionId());
355 LOG.debug("{}: Forwarding CanCommitTransaction to leader {}", persistenceId(), leader);
356 leader.forward(canCommit, getContext());
361 @SuppressWarnings("checkstyle:IllegalCatch")
362 protected void handleBatchedModificationsLocal(final BatchedModifications batched, final ActorRef sender) {
364 commitCoordinator.handleBatchedModifications(batched, sender, this);
365 } catch (Exception e) {
366 LOG.error("{}: Error handling BatchedModifications for Tx {}", persistenceId(),
367 batched.getTransactionId(), e);
368 sender.tell(new akka.actor.Status.Failure(e), getSelf());
372 private void handleBatchedModifications(final BatchedModifications batched) {
373 // This message is sent to prepare the modifications transaction directly on the Shard as an
374 // optimization to avoid the extra overhead of a separate ShardTransaction actor. On the last
375 // BatchedModifications message, the caller sets the ready flag in the message indicating
376 // modifications are complete. The reply contains the cohort actor path (this actor) for the caller
377 // to initiate the 3-phase commit. This also avoids the overhead of sending an additional
378 // ReadyTransaction message.
380 // If we're not the leader then forward to the leader. This is a safety measure - we shouldn't
381 // normally get here if we're not the leader as the front-end (TransactionProxy) should determine
382 // the primary/leader shard. However with timing and caching on the front-end, there's a small
383 // window where it could have a stale leader during leadership transitions.
385 boolean isLeaderActive = isLeaderActive();
386 if (isLeader() && isLeaderActive) {
387 handleBatchedModificationsLocal(batched, getSender());
389 ActorSelection leader = getLeader();
390 if (!isLeaderActive || leader == null) {
391 messageRetrySupport.addMessageToRetry(batched, getSender(),
392 "Could not commit transaction " + batched.getTransactionId());
394 // If this is not the first batch and leadership changed in between batched messages,
395 // we need to reconstruct previous BatchedModifications from the transaction
396 // DataTreeModification, honoring the max batched modification count, and forward all the
397 // previous BatchedModifications to the new leader.
398 Collection<BatchedModifications> newModifications = commitCoordinator
399 .createForwardedBatchedModifications(batched,
400 datastoreContext.getShardBatchedModificationCount());
402 LOG.debug("{}: Forwarding {} BatchedModifications to leader {}", persistenceId(),
403 newModifications.size(), leader);
405 for (BatchedModifications bm : newModifications) {
406 leader.forward(bm, getContext());
412 private boolean failIfIsolatedLeader(final ActorRef sender) {
413 if (isIsolatedLeader()) {
414 sender.tell(new akka.actor.Status.Failure(new NoShardLeaderException(String.format(
415 "Shard %s was the leader but has lost contact with all of its followers. Either all"
416 + " other follower nodes are down or this node is isolated by a network partition.",
417 persistenceId()))), getSelf());
424 protected boolean isIsolatedLeader() {
425 return getRaftState() == RaftState.IsolatedLeader;
428 @SuppressWarnings("checkstyle:IllegalCatch")
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 @SuppressWarnings("checkstyle:IllegalCatch")
500 private void createTransaction(final CreateTransaction createTransaction) {
502 if (TransactionType.fromInt(createTransaction.getTransactionType()) != TransactionType.READ_ONLY
503 && failIfIsolatedLeader(getSender())) {
507 ActorRef transactionActor = createTransaction(createTransaction.getTransactionType(),
508 createTransaction.getTransactionId());
510 getSender().tell(new CreateTransactionReply(Serialization.serializedActorPath(transactionActor),
511 createTransaction.getTransactionId(), createTransaction.getVersion()).toSerializable(), getSelf());
512 } catch (Exception e) {
513 getSender().tell(new akka.actor.Status.Failure(e), getSelf());
517 private ActorRef createTransaction(final int transactionType, final TransactionIdentifier transactionId) {
518 LOG.debug("{}: Creating transaction : {} ", persistenceId(), transactionId);
519 return transactionActorFactory.newShardTransaction(TransactionType.fromInt(transactionType),
523 private void updateSchemaContext(final UpdateSchemaContext message) {
524 updateSchemaContext(message.getSchemaContext());
528 void updateSchemaContext(final SchemaContext schemaContext) {
529 store.updateSchemaContext(schemaContext);
532 private boolean isMetricsCaptureEnabled() {
533 CommonConfig config = new CommonConfig(getContext().system().settings().config());
534 return config.isMetricCaptureEnabled();
539 public RaftActorSnapshotCohort getRaftActorSnapshotCohort() {
540 return snapshotCohort;
545 protected RaftActorRecoveryCohort getRaftActorRecoveryCohort() {
546 return new ShardRecoveryCoordinator(store,
547 restoreFromSnapshot != null ? restoreFromSnapshot.getSnapshot() : null, persistenceId(), LOG);
551 protected void onRecoveryComplete() {
552 restoreFromSnapshot = null;
554 //notify shard manager
555 getContext().parent().tell(new ActorInitialized(), getSelf());
557 // Being paranoid here - this method should only be called once but just in case...
558 if (txCommitTimeoutCheckSchedule == null) {
559 // Schedule a message to be periodically sent to check if the current in-progress
560 // transaction should be expired and aborted.
561 FiniteDuration period = Duration.create(transactionCommitTimeout / 3, TimeUnit.MILLISECONDS);
562 txCommitTimeoutCheckSchedule = getContext().system().scheduler().schedule(
563 period, period, getSelf(),
564 TX_COMMIT_TIMEOUT_CHECK_MESSAGE, getContext().dispatcher(), ActorRef.noSender());
569 protected void applyState(final ActorRef clientActor, final Identifier identifier, final Object data) {
570 if (data instanceof Payload) {
572 store.applyReplicatedPayload(identifier, (Payload)data);
573 } catch (DataValidationFailedException | IOException e) {
574 LOG.error("{}: Error applying replica {}", persistenceId(), identifier, e);
577 LOG.error("{}: Unknown state for {} received {}", persistenceId(), identifier, data);
582 protected void onStateChanged() {
583 boolean isLeader = isLeader();
584 boolean hasLeader = hasLeader();
585 changeSupport.onLeadershipChange(isLeader, hasLeader);
586 treeChangeSupport.onLeadershipChange(isLeader, hasLeader);
588 // If this actor is no longer the leader close all the transaction chains
590 if (LOG.isDebugEnabled()) {
592 "{}: onStateChanged: Closing all transaction chains because shard {} is no longer the leader",
593 persistenceId(), getId());
596 store.closeAllTransactionChains();
599 if (hasLeader && !isIsolatedLeader()) {
600 messageRetrySupport.retryMessages();
605 protected void onLeaderChanged(final String oldLeader, final String newLeader) {
606 shardMBean.incrementLeadershipChangeCount();
608 boolean hasLeader = hasLeader();
609 if (hasLeader && !isLeader()) {
610 // Another leader was elected. If we were the previous leader and had pending transactions, convert
611 // them to transaction messages and send to the new leader.
612 ActorSelection leader = getLeader();
613 if (leader != null) {
614 Collection<?> messagesToForward = convertPendingTransactionsToMessages();
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("The transacton was aborted due to inflight leadership "
626 + "change and the leader address isn't available.", this);
630 if (hasLeader && !isIsolatedLeader()) {
631 messageRetrySupport.retryMessages();
636 * Clears all pending transactions and converts them to messages to be forwarded to a new leader.
638 * @return the converted messages
640 public Collection<?> convertPendingTransactionsToMessages() {
641 return commitCoordinator.convertPendingTransactionsToMessages(
642 datastoreContext.getShardBatchedModificationCount());
646 protected void pauseLeader(final Runnable operation) {
647 LOG.debug("{}: In pauseLeader, operation: {}", persistenceId(), operation);
648 store.setRunOnPendingTransactionsComplete(operation);
652 public String persistenceId() {
657 ShardCommitCoordinator getCommitCoordinator() {
658 return commitCoordinator;
661 public DatastoreContext getDatastoreContext() {
662 return datastoreContext;
666 public ShardDataTree getDataStore() {
671 ShardStats getShardMBean() {
675 public static Builder builder() {
676 return new Builder();
679 public abstract static class AbstractBuilder<T extends AbstractBuilder<T, S>, S extends Shard> {
680 private final Class<S> shardClass;
681 private ShardIdentifier id;
682 private Map<String, String> peerAddresses = Collections.emptyMap();
683 private DatastoreContext datastoreContext;
684 private SchemaContext schemaContext;
685 private DatastoreSnapshot.ShardSnapshot restoreFromSnapshot;
686 private TipProducingDataTree dataTree;
687 private volatile boolean sealed;
689 protected AbstractBuilder(final Class<S> shardClass) {
690 this.shardClass = shardClass;
693 protected void checkSealed() {
694 Preconditions.checkState(!sealed, "Builder isalready sealed - further modifications are not allowed");
697 @SuppressWarnings("unchecked")
702 public T id(final ShardIdentifier newId) {
708 public T peerAddresses(final Map<String, String> newPeerAddresses) {
710 this.peerAddresses = newPeerAddresses;
714 public T datastoreContext(final DatastoreContext newDatastoreContext) {
716 this.datastoreContext = newDatastoreContext;
720 public T schemaContext(final SchemaContext newSchemaContext) {
722 this.schemaContext = newSchemaContext;
726 public T restoreFromSnapshot(final DatastoreSnapshot.ShardSnapshot newRestoreFromSnapshot) {
728 this.restoreFromSnapshot = newRestoreFromSnapshot;
732 public T dataTree(final TipProducingDataTree newDataTree) {
734 this.dataTree = newDataTree;
738 public ShardIdentifier getId() {
742 public Map<String, String> getPeerAddresses() {
743 return peerAddresses;
746 public DatastoreContext getDatastoreContext() {
747 return datastoreContext;
750 public SchemaContext getSchemaContext() {
751 return schemaContext;
754 public DatastoreSnapshot.ShardSnapshot getRestoreFromSnapshot() {
755 return restoreFromSnapshot;
758 public TipProducingDataTree getDataTree() {
762 public TreeType getTreeType() {
763 switch (datastoreContext.getLogicalStoreType()) {
765 return TreeType.CONFIGURATION;
767 return TreeType.OPERATIONAL;
769 throw new IllegalStateException("Unhandled logical store type "
770 + datastoreContext.getLogicalStoreType());
774 protected void verify() {
775 Preconditions.checkNotNull(id, "id should not be null");
776 Preconditions.checkNotNull(peerAddresses, "peerAddresses should not be null");
777 Preconditions.checkNotNull(datastoreContext, "dataStoreContext should not be null");
778 Preconditions.checkNotNull(schemaContext, "schemaContext should not be null");
781 public Props props() {
784 return Props.create(shardClass, this);
788 public static class Builder extends AbstractBuilder<Builder, Shard> {
795 return Ticker.systemTicker();