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.actor.Status.Failure;
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 com.google.common.base.Ticker;
21 import com.google.common.collect.ImmutableList;
22 import com.google.common.collect.Range;
23 import java.io.IOException;
24 import java.util.Arrays;
25 import java.util.Collection;
26 import java.util.Collections;
27 import java.util.HashMap;
29 import java.util.concurrent.TimeUnit;
30 import javax.annotation.Nonnull;
31 import javax.annotation.Nullable;
32 import org.opendaylight.controller.cluster.access.ABIVersion;
33 import org.opendaylight.controller.cluster.access.commands.ConnectClientRequest;
34 import org.opendaylight.controller.cluster.access.commands.ConnectClientSuccess;
35 import org.opendaylight.controller.cluster.access.commands.LocalHistoryRequest;
36 import org.opendaylight.controller.cluster.access.commands.NotLeaderException;
37 import org.opendaylight.controller.cluster.access.commands.TransactionRequest;
38 import org.opendaylight.controller.cluster.access.concepts.ClientIdentifier;
39 import org.opendaylight.controller.cluster.access.concepts.FrontendIdentifier;
40 import org.opendaylight.controller.cluster.access.concepts.Request;
41 import org.opendaylight.controller.cluster.access.concepts.RequestEnvelope;
42 import org.opendaylight.controller.cluster.access.concepts.RequestException;
43 import org.opendaylight.controller.cluster.access.concepts.RequestSuccess;
44 import org.opendaylight.controller.cluster.access.concepts.RetiredGenerationException;
45 import org.opendaylight.controller.cluster.access.concepts.RuntimeRequestException;
46 import org.opendaylight.controller.cluster.access.concepts.TransactionIdentifier;
47 import org.opendaylight.controller.cluster.access.concepts.UnsupportedRequestException;
48 import org.opendaylight.controller.cluster.common.actor.CommonConfig;
49 import org.opendaylight.controller.cluster.common.actor.MessageTracker;
50 import org.opendaylight.controller.cluster.common.actor.MessageTracker.Error;
51 import org.opendaylight.controller.cluster.common.actor.MeteringBehavior;
52 import org.opendaylight.controller.cluster.datastore.exceptions.NoShardLeaderException;
53 import org.opendaylight.controller.cluster.datastore.identifiers.ShardIdentifier;
54 import org.opendaylight.controller.cluster.datastore.jmx.mbeans.shard.ShardMBeanFactory;
55 import org.opendaylight.controller.cluster.datastore.jmx.mbeans.shard.ShardStats;
56 import org.opendaylight.controller.cluster.datastore.messages.AbortTransaction;
57 import org.opendaylight.controller.cluster.datastore.messages.ActorInitialized;
58 import org.opendaylight.controller.cluster.datastore.messages.BatchedModifications;
59 import org.opendaylight.controller.cluster.datastore.messages.CanCommitTransaction;
60 import org.opendaylight.controller.cluster.datastore.messages.CloseTransactionChain;
61 import org.opendaylight.controller.cluster.datastore.messages.CommitTransaction;
62 import org.opendaylight.controller.cluster.datastore.messages.CreateTransaction;
63 import org.opendaylight.controller.cluster.datastore.messages.CreateTransactionReply;
64 import org.opendaylight.controller.cluster.datastore.messages.DatastoreSnapshot;
65 import org.opendaylight.controller.cluster.datastore.messages.DatastoreSnapshot.ShardSnapshot;
66 import org.opendaylight.controller.cluster.datastore.messages.ForwardedReadyTransaction;
67 import org.opendaylight.controller.cluster.datastore.messages.GetShardDataTree;
68 import org.opendaylight.controller.cluster.datastore.messages.PeerAddressResolved;
69 import org.opendaylight.controller.cluster.datastore.messages.ReadyLocalTransaction;
70 import org.opendaylight.controller.cluster.datastore.messages.RegisterChangeListener;
71 import org.opendaylight.controller.cluster.datastore.messages.RegisterDataTreeChangeListener;
72 import org.opendaylight.controller.cluster.datastore.messages.ShardLeaderStateChanged;
73 import org.opendaylight.controller.cluster.datastore.messages.UpdateSchemaContext;
74 import org.opendaylight.controller.cluster.datastore.utils.Dispatchers;
75 import org.opendaylight.controller.cluster.notifications.LeaderStateChanged;
76 import org.opendaylight.controller.cluster.notifications.RegisterRoleChangeListener;
77 import org.opendaylight.controller.cluster.notifications.RoleChangeNotifier;
78 import org.opendaylight.controller.cluster.raft.RaftActor;
79 import org.opendaylight.controller.cluster.raft.RaftActorRecoveryCohort;
80 import org.opendaylight.controller.cluster.raft.RaftActorSnapshotCohort;
81 import org.opendaylight.controller.cluster.raft.RaftState;
82 import org.opendaylight.controller.cluster.raft.base.messages.FollowerInitialSyncUpStatus;
83 import org.opendaylight.controller.cluster.raft.messages.AppendEntriesReply;
84 import org.opendaylight.controller.cluster.raft.messages.ServerRemoved;
85 import org.opendaylight.controller.cluster.raft.protobuff.client.messages.Payload;
86 import org.opendaylight.yangtools.concepts.Identifier;
87 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataValidationFailedException;
88 import org.opendaylight.yangtools.yang.data.api.schema.tree.TipProducingDataTree;
89 import org.opendaylight.yangtools.yang.data.api.schema.tree.TreeType;
90 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
91 import scala.concurrent.duration.Duration;
92 import scala.concurrent.duration.FiniteDuration;
95 * A Shard represents a portion of the logical data tree.
97 * Our Shard uses InMemoryDataTree as it's internal representation and delegates all requests it
99 public class Shard extends RaftActor {
102 static final Object TX_COMMIT_TIMEOUT_CHECK_MESSAGE = new Object() {
104 public String toString() {
105 return "txCommitTimeoutCheck";
110 static final Object GET_SHARD_MBEAN_MESSAGE = new Object() {
112 public String toString() {
113 return "getShardMBeanMessage";
117 // FIXME: shard names should be encapsulated in their own class and this should be exposed as a constant.
118 public static final String DEFAULT_NAME = "default";
120 private static final Collection<ABIVersion> SUPPORTED_ABIVERSIONS;
123 final ABIVersion[] values = ABIVersion.values();
124 final ABIVersion[] real = Arrays.copyOfRange(values, 1, values.length - 1);
125 SUPPORTED_ABIVERSIONS = ImmutableList.copyOf(real).reverse();
128 // FIXME: make this a dynamic property based on mailbox size and maximum number of clients
129 private static final int CLIENT_MAX_MESSAGES = 1000;
131 // The state of this Shard
132 private final ShardDataTree store;
134 /// The name of this shard
135 private final String name;
137 private final ShardStats shardMBean;
139 private DatastoreContext datastoreContext;
141 private final ShardCommitCoordinator commitCoordinator;
143 private long transactionCommitTimeout;
145 private Cancellable txCommitTimeoutCheckSchedule;
147 private final Optional<ActorRef> roleChangeNotifier;
149 private final MessageTracker appendEntriesReplyTracker;
151 private final ShardTransactionActorFactory transactionActorFactory;
153 private final ShardSnapshotCohort snapshotCohort;
155 private final DataTreeChangeListenerSupport treeChangeSupport = new DataTreeChangeListenerSupport(this);
156 private final DataChangeListenerSupport changeSupport = new DataChangeListenerSupport(this);
159 private ShardSnapshot restoreFromSnapshot;
161 private final ShardTransactionMessageRetrySupport messageRetrySupport;
163 private final FrontendMetadata frontendMetadata = new FrontendMetadata();
164 private final Map<FrontendIdentifier, LeaderFrontendState> knownFrontends = new HashMap<>();
166 protected Shard(final AbstractBuilder<?, ?> builder) {
167 super(builder.getId().toString(), builder.getPeerAddresses(),
168 Optional.of(builder.getDatastoreContext().getShardRaftConfig()), DataStoreVersions.CURRENT_VERSION);
170 this.name = builder.getId().toString();
171 this.datastoreContext = builder.getDatastoreContext();
172 this.restoreFromSnapshot = builder.getRestoreFromSnapshot();
174 setPersistence(datastoreContext.isPersistent());
176 LOG.info("Shard created : {}, persistent : {}", name, datastoreContext.isPersistent());
178 ShardDataTreeChangeListenerPublisherActorProxy treeChangeListenerPublisher =
179 new ShardDataTreeChangeListenerPublisherActorProxy(getContext(), name + "-DTCL-publisher");
180 ShardDataChangeListenerPublisherActorProxy dataChangeListenerPublisher =
181 new ShardDataChangeListenerPublisherActorProxy(getContext(), name + "-DCL-publisher");
182 if (builder.getDataTree() != null) {
183 store = new ShardDataTree(this, builder.getSchemaContext(), builder.getDataTree(),
184 treeChangeListenerPublisher, dataChangeListenerPublisher, name);
186 store = new ShardDataTree(this, builder.getSchemaContext(), builder.getTreeType(),
187 treeChangeListenerPublisher, dataChangeListenerPublisher, name);
190 shardMBean = ShardMBeanFactory.getShardStatsMBean(name, datastoreContext.getDataStoreMXBeanType(), this);
192 if (isMetricsCaptureEnabled()) {
193 getContext().become(new MeteringBehavior(this));
196 commitCoordinator = new ShardCommitCoordinator(store, LOG, this.name);
198 setTransactionCommitTimeout();
200 // create a notifier actor for each cluster member
201 roleChangeNotifier = createRoleChangeNotifier(name);
203 appendEntriesReplyTracker = new MessageTracker(AppendEntriesReply.class,
204 getRaftActorContext().getConfigParams().getIsolatedCheckIntervalInMillis());
206 transactionActorFactory = new ShardTransactionActorFactory(store, datastoreContext,
207 new Dispatchers(context().system().dispatchers()).getDispatcherPath(
208 Dispatchers.DispatcherType.Transaction), self(), getContext(), shardMBean);
210 snapshotCohort = ShardSnapshotCohort.create(getContext(), builder.getId().getMemberName(), store, LOG,
213 messageRetrySupport = new ShardTransactionMessageRetrySupport(this);
216 private void setTransactionCommitTimeout() {
217 transactionCommitTimeout = TimeUnit.MILLISECONDS.convert(
218 datastoreContext.getShardTransactionCommitTimeoutInSeconds(), TimeUnit.SECONDS) / 2;
221 private Optional<ActorRef> createRoleChangeNotifier(final String shardId) {
222 ActorRef shardRoleChangeNotifier = this.getContext().actorOf(
223 RoleChangeNotifier.getProps(shardId), shardId + "-notifier");
224 return Optional.of(shardRoleChangeNotifier);
228 public void postStop() {
229 LOG.info("Stopping Shard {}", persistenceId());
233 messageRetrySupport.close();
235 if (txCommitTimeoutCheckSchedule != null) {
236 txCommitTimeoutCheckSchedule.cancel();
239 commitCoordinator.abortPendingTransactions("Transaction aborted due to shutdown.", this);
241 shardMBean.unregisterMBean();
245 protected void handleRecover(final Object message) {
246 LOG.debug("{}: onReceiveRecover: Received message {} from {}", persistenceId(), message.getClass(),
249 super.handleRecover(message);
250 if (LOG.isTraceEnabled()) {
251 appendEntriesReplyTracker.begin();
255 @SuppressWarnings("checkstyle:IllegalCatch")
257 protected void handleNonRaftCommand(final Object message) {
258 try (final MessageTracker.Context context = appendEntriesReplyTracker.received(message)) {
259 final Optional<Error> maybeError = context.error();
260 if (maybeError.isPresent()) {
261 LOG.trace("{} : AppendEntriesReply failed to arrive at the expected interval {}", persistenceId(),
265 if (message instanceof RequestEnvelope) {
266 final RequestEnvelope envelope = (RequestEnvelope)message;
268 final RequestSuccess<?, ?> success = handleRequest(envelope);
269 if (success != null) {
270 envelope.sendSuccess(success);
272 } catch (RequestException e) {
273 LOG.debug("{}: request {} failed", persistenceId(), envelope, e);
274 envelope.sendFailure(e);
275 } catch (Exception e) {
276 LOG.debug("{}: request {} caused failure", persistenceId(), envelope, e);
277 envelope.sendFailure(new RuntimeRequestException("Request failed to process", e));
279 } else if (message instanceof ConnectClientRequest) {
280 handleConnectClient((ConnectClientRequest)message);
281 } else if (CreateTransaction.isSerializedType(message)) {
282 handleCreateTransaction(message);
283 } else if (message instanceof BatchedModifications) {
284 handleBatchedModifications((BatchedModifications)message);
285 } else if (message instanceof ForwardedReadyTransaction) {
286 handleForwardedReadyTransaction((ForwardedReadyTransaction) message);
287 } else if (message instanceof ReadyLocalTransaction) {
288 handleReadyLocalTransaction((ReadyLocalTransaction)message);
289 } else if (CanCommitTransaction.isSerializedType(message)) {
290 handleCanCommitTransaction(CanCommitTransaction.fromSerializable(message));
291 } else if (CommitTransaction.isSerializedType(message)) {
292 handleCommitTransaction(CommitTransaction.fromSerializable(message));
293 } else if (AbortTransaction.isSerializedType(message)) {
294 handleAbortTransaction(AbortTransaction.fromSerializable(message));
295 } else if (CloseTransactionChain.isSerializedType(message)) {
296 closeTransactionChain(CloseTransactionChain.fromSerializable(message));
297 } else if (message instanceof RegisterChangeListener) {
298 changeSupport.onMessage((RegisterChangeListener) message, isLeader(), hasLeader());
299 } else if (message instanceof RegisterDataTreeChangeListener) {
300 treeChangeSupport.onMessage((RegisterDataTreeChangeListener) message, isLeader(), hasLeader());
301 } else if (message instanceof UpdateSchemaContext) {
302 updateSchemaContext((UpdateSchemaContext) message);
303 } else if (message instanceof PeerAddressResolved) {
304 PeerAddressResolved resolved = (PeerAddressResolved) message;
305 setPeerAddress(resolved.getPeerId(), resolved.getPeerAddress());
306 } else if (TX_COMMIT_TIMEOUT_CHECK_MESSAGE.equals(message)) {
307 store.checkForExpiredTransactions(transactionCommitTimeout);
308 commitCoordinator.checkForExpiredTransactions(transactionCommitTimeout, this);
309 } else if (message instanceof DatastoreContext) {
310 onDatastoreContext((DatastoreContext)message);
311 } else if (message instanceof RegisterRoleChangeListener) {
312 roleChangeNotifier.get().forward(message, context());
313 } else if (message instanceof FollowerInitialSyncUpStatus) {
314 shardMBean.setFollowerInitialSyncStatus(((FollowerInitialSyncUpStatus) message).isInitialSyncDone());
315 context().parent().tell(message, self());
316 } else if (GET_SHARD_MBEAN_MESSAGE.equals(message)) {
317 sender().tell(getShardMBean(), self());
318 } else if (message instanceof GetShardDataTree) {
319 sender().tell(store.getDataTree(), self());
320 } else if (message instanceof ServerRemoved) {
321 context().parent().forward(message, context());
322 } else if (ShardTransactionMessageRetrySupport.TIMER_MESSAGE_CLASS.isInstance(message)) {
323 messageRetrySupport.onTimerMessage(message);
324 } else if (message instanceof DataTreeCohortActorRegistry.CohortRegistryCommand) {
325 store.processCohortRegistryCommand(getSender(),
326 (DataTreeCohortActorRegistry.CohortRegistryCommand) message);
328 super.handleNonRaftCommand(message);
333 // Acquire our frontend tracking handle and verify generation matches
334 private LeaderFrontendState getFrontend(final ClientIdentifier clientId) throws RequestException {
335 final LeaderFrontendState existing = knownFrontends.get(clientId.getFrontendId());
336 if (existing != null) {
337 final int cmp = Long.compareUnsigned(existing.getIdentifier().getGeneration(), clientId.getGeneration());
342 LOG.debug("{}: rejecting request from outdated client {}", persistenceId(), clientId);
343 throw new RetiredGenerationException(existing.getIdentifier().getGeneration());
346 LOG.info("{}: retiring state {}, outdated by request from client {}", persistenceId(), existing, clientId);
348 knownFrontends.remove(clientId.getFrontendId());
350 LOG.debug("{}: client {} is not yet known", persistenceId(), clientId);
353 final LeaderFrontendState ret = new LeaderFrontendState(persistenceId(), clientId, store);
354 knownFrontends.put(clientId.getFrontendId(), ret);
355 LOG.debug("{}: created state {} for client {}", persistenceId(), ret, clientId);
359 private static @Nonnull ABIVersion selectVersion(final ConnectClientRequest message) {
360 final Range<ABIVersion> clientRange = Range.closed(message.getMinVersion(), message.getMaxVersion());
361 for (ABIVersion v : SUPPORTED_ABIVERSIONS) {
362 if (clientRange.contains(v)) {
367 throw new IllegalArgumentException(String.format(
368 "No common version between backend versions %s and client versions %s", SUPPORTED_ABIVERSIONS,
372 @SuppressWarnings("checkstyle:IllegalCatch")
373 private void handleConnectClient(final ConnectClientRequest message) {
375 if (!isLeader() || !isLeaderActive()) {
376 LOG.debug("{}: not currently leader, rejecting request {}", persistenceId(), message);
377 throw new NotLeaderException(getSelf());
380 final ABIVersion selectedVersion = selectVersion(message);
381 final LeaderFrontendState frontend = getFrontend(message.getTarget());
382 frontend.reconnect();
383 message.getReplyTo().tell(new ConnectClientSuccess(message.getTarget(), message.getSequence(), getSelf(),
384 ImmutableList.of(), store.getDataTree(), CLIENT_MAX_MESSAGES).toVersion(selectedVersion),
385 ActorRef.noSender());
386 } catch (RequestException | RuntimeException e) {
387 message.getReplyTo().tell(new Failure(e), ActorRef.noSender());
391 private @Nullable RequestSuccess<?, ?> handleRequest(final RequestEnvelope envelope) throws RequestException {
392 // We are not the leader, hence we want to fail-fast.
393 if (!isLeader() || !isLeaderActive()) {
394 LOG.debug("{}: not currently leader, rejecting request {}", persistenceId(), envelope);
395 throw new NotLeaderException(getSelf());
398 final Request<?, ?> request = envelope.getMessage();
399 if (request instanceof TransactionRequest) {
400 final TransactionRequest<?> txReq = (TransactionRequest<?>)request;
401 final ClientIdentifier clientId = txReq.getTarget().getHistoryId().getClientId();
402 return getFrontend(clientId).handleTransactionRequest(txReq, envelope);
403 } else if (request instanceof LocalHistoryRequest) {
404 final LocalHistoryRequest<?> lhReq = (LocalHistoryRequest<?>)request;
405 final ClientIdentifier clientId = lhReq.getTarget().getClientId();
406 return getFrontend(clientId).handleLocalHistoryRequest(lhReq, envelope);
408 LOG.debug("{}: rejecting unsupported request {}", persistenceId(), request);
409 throw new UnsupportedRequestException(request);
413 private boolean hasLeader() {
414 return getLeaderId() != null;
417 public int getPendingTxCommitQueueSize() {
418 return store.getQueueSize();
421 public int getCohortCacheSize() {
422 return commitCoordinator.getCohortCacheSize();
426 protected Optional<ActorRef> getRoleChangeNotifier() {
427 return roleChangeNotifier;
431 protected LeaderStateChanged newLeaderStateChanged(final String memberId, final String leaderId,
432 final short leaderPayloadVersion) {
433 return isLeader() ? new ShardLeaderStateChanged(memberId, leaderId, store.getDataTree(), leaderPayloadVersion)
434 : new ShardLeaderStateChanged(memberId, leaderId, leaderPayloadVersion);
437 protected void onDatastoreContext(final DatastoreContext context) {
438 datastoreContext = context;
440 setTransactionCommitTimeout();
442 setPersistence(datastoreContext.isPersistent());
444 updateConfigParams(datastoreContext.getShardRaftConfig());
447 boolean canSkipPayload() {
448 // If we do not have any followers and we are not using persistence we can apply modification to the state
450 return !hasFollowers() && !persistence().isRecoveryApplicable();
453 // applyState() will be invoked once consensus is reached on the payload
454 void persistPayload(final TransactionIdentifier transactionId, final Payload payload) {
455 // We are faking the sender
456 persistData(self(), transactionId, payload);
459 private void handleCommitTransaction(final CommitTransaction commit) {
461 commitCoordinator.handleCommit(commit.getTransactionId(), getSender(), this);
463 ActorSelection leader = getLeader();
464 if (leader == null) {
465 messageRetrySupport.addMessageToRetry(commit, getSender(),
466 "Could not commit transaction " + commit.getTransactionId());
468 LOG.debug("{}: Forwarding CommitTransaction to leader {}", persistenceId(), leader);
469 leader.forward(commit, getContext());
474 private void handleCanCommitTransaction(final CanCommitTransaction canCommit) {
475 LOG.debug("{}: Can committing transaction {}", persistenceId(), canCommit.getTransactionId());
478 commitCoordinator.handleCanCommit(canCommit.getTransactionId(), getSender(), this);
480 ActorSelection leader = getLeader();
481 if (leader == null) {
482 messageRetrySupport.addMessageToRetry(canCommit, getSender(),
483 "Could not canCommit transaction " + canCommit.getTransactionId());
485 LOG.debug("{}: Forwarding CanCommitTransaction to leader {}", persistenceId(), leader);
486 leader.forward(canCommit, getContext());
491 @SuppressWarnings("checkstyle:IllegalCatch")
492 protected void handleBatchedModificationsLocal(final BatchedModifications batched, final ActorRef sender) {
494 commitCoordinator.handleBatchedModifications(batched, sender, this);
495 } catch (Exception e) {
496 LOG.error("{}: Error handling BatchedModifications for Tx {}", persistenceId(),
497 batched.getTransactionId(), e);
498 sender.tell(new Failure(e), getSelf());
502 private void handleBatchedModifications(final BatchedModifications batched) {
503 // This message is sent to prepare the modifications transaction directly on the Shard as an
504 // optimization to avoid the extra overhead of a separate ShardTransaction actor. On the last
505 // BatchedModifications message, the caller sets the ready flag in the message indicating
506 // modifications are complete. The reply contains the cohort actor path (this actor) for the caller
507 // to initiate the 3-phase commit. This also avoids the overhead of sending an additional
508 // ReadyTransaction message.
510 // If we're not the leader then forward to the leader. This is a safety measure - we shouldn't
511 // normally get here if we're not the leader as the front-end (TransactionProxy) should determine
512 // the primary/leader shard. However with timing and caching on the front-end, there's a small
513 // window where it could have a stale leader during leadership transitions.
515 boolean isLeaderActive = isLeaderActive();
516 if (isLeader() && isLeaderActive) {
517 handleBatchedModificationsLocal(batched, getSender());
519 ActorSelection leader = getLeader();
520 if (!isLeaderActive || leader == null) {
521 messageRetrySupport.addMessageToRetry(batched, getSender(),
522 "Could not commit transaction " + batched.getTransactionId());
524 // If this is not the first batch and leadership changed in between batched messages,
525 // we need to reconstruct previous BatchedModifications from the transaction
526 // DataTreeModification, honoring the max batched modification count, and forward all the
527 // previous BatchedModifications to the new leader.
528 Collection<BatchedModifications> newModifications = commitCoordinator
529 .createForwardedBatchedModifications(batched,
530 datastoreContext.getShardBatchedModificationCount());
532 LOG.debug("{}: Forwarding {} BatchedModifications to leader {}", persistenceId(),
533 newModifications.size(), leader);
535 for (BatchedModifications bm : newModifications) {
536 leader.forward(bm, getContext());
542 private boolean failIfIsolatedLeader(final ActorRef sender) {
543 if (isIsolatedLeader()) {
544 sender.tell(new Failure(new NoShardLeaderException(String.format(
545 "Shard %s was the leader but has lost contact with all of its followers. Either all"
546 + " other follower nodes are down or this node is isolated by a network partition.",
547 persistenceId()))), getSelf());
554 protected boolean isIsolatedLeader() {
555 return getRaftState() == RaftState.IsolatedLeader;
558 @SuppressWarnings("checkstyle:IllegalCatch")
559 private void handleReadyLocalTransaction(final ReadyLocalTransaction message) {
560 LOG.debug("{}: handleReadyLocalTransaction for {}", persistenceId(), message.getTransactionId());
562 boolean isLeaderActive = isLeaderActive();
563 if (isLeader() && isLeaderActive) {
565 commitCoordinator.handleReadyLocalTransaction(message, getSender(), this);
566 } catch (Exception e) {
567 LOG.error("{}: Error handling ReadyLocalTransaction for Tx {}", persistenceId(),
568 message.getTransactionId(), e);
569 getSender().tell(new Failure(e), getSelf());
572 ActorSelection leader = getLeader();
573 if (!isLeaderActive || leader == null) {
574 messageRetrySupport.addMessageToRetry(message, getSender(),
575 "Could not commit transaction " + message.getTransactionId());
577 LOG.debug("{}: Forwarding ReadyLocalTransaction to leader {}", persistenceId(), leader);
578 message.setRemoteVersion(getCurrentBehavior().getLeaderPayloadVersion());
579 leader.forward(message, getContext());
584 private void handleForwardedReadyTransaction(final ForwardedReadyTransaction forwardedReady) {
585 LOG.debug("{}: handleForwardedReadyTransaction for {}", persistenceId(), forwardedReady.getTransactionId());
587 boolean isLeaderActive = isLeaderActive();
588 if (isLeader() && isLeaderActive) {
589 commitCoordinator.handleForwardedReadyTransaction(forwardedReady, getSender(), this);
591 ActorSelection leader = getLeader();
592 if (!isLeaderActive || leader == null) {
593 messageRetrySupport.addMessageToRetry(forwardedReady, getSender(),
594 "Could not commit transaction " + forwardedReady.getTransactionId());
596 LOG.debug("{}: Forwarding ForwardedReadyTransaction to leader {}", persistenceId(), leader);
598 ReadyLocalTransaction readyLocal = new ReadyLocalTransaction(forwardedReady.getTransactionId(),
599 forwardedReady.getTransaction().getSnapshot(), forwardedReady.isDoImmediateCommit());
600 readyLocal.setRemoteVersion(getCurrentBehavior().getLeaderPayloadVersion());
601 leader.forward(readyLocal, getContext());
606 private void handleAbortTransaction(final AbortTransaction abort) {
607 doAbortTransaction(abort.getTransactionId(), getSender());
610 void doAbortTransaction(final TransactionIdentifier transactionID, final ActorRef sender) {
611 commitCoordinator.handleAbort(transactionID, sender, this);
614 private void handleCreateTransaction(final Object message) {
616 createTransaction(CreateTransaction.fromSerializable(message));
617 } else if (getLeader() != null) {
618 getLeader().forward(message, getContext());
620 getSender().tell(new Failure(new NoShardLeaderException(
621 "Could not create a shard transaction", persistenceId())), getSelf());
625 private void closeTransactionChain(final CloseTransactionChain closeTransactionChain) {
626 store.closeTransactionChain(closeTransactionChain.getIdentifier());
629 @SuppressWarnings("checkstyle:IllegalCatch")
630 private void createTransaction(final CreateTransaction createTransaction) {
632 if (TransactionType.fromInt(createTransaction.getTransactionType()) != TransactionType.READ_ONLY
633 && failIfIsolatedLeader(getSender())) {
637 ActorRef transactionActor = createTransaction(createTransaction.getTransactionType(),
638 createTransaction.getTransactionId());
640 getSender().tell(new CreateTransactionReply(Serialization.serializedActorPath(transactionActor),
641 createTransaction.getTransactionId(), createTransaction.getVersion()).toSerializable(), getSelf());
642 } catch (Exception e) {
643 getSender().tell(new Failure(e), getSelf());
647 private ActorRef createTransaction(final int transactionType, final TransactionIdentifier transactionId) {
648 LOG.debug("{}: Creating transaction : {} ", persistenceId(), transactionId);
649 return transactionActorFactory.newShardTransaction(TransactionType.fromInt(transactionType),
653 private void updateSchemaContext(final UpdateSchemaContext message) {
654 updateSchemaContext(message.getSchemaContext());
658 void updateSchemaContext(final SchemaContext schemaContext) {
659 store.updateSchemaContext(schemaContext);
662 private boolean isMetricsCaptureEnabled() {
663 CommonConfig config = new CommonConfig(getContext().system().settings().config());
664 return config.isMetricCaptureEnabled();
669 public RaftActorSnapshotCohort getRaftActorSnapshotCohort() {
670 return snapshotCohort;
675 protected RaftActorRecoveryCohort getRaftActorRecoveryCohort() {
676 return new ShardRecoveryCoordinator(store,
677 restoreFromSnapshot != null ? restoreFromSnapshot.getSnapshot() : null, persistenceId(), LOG);
681 protected void onRecoveryComplete() {
682 restoreFromSnapshot = null;
684 //notify shard manager
685 getContext().parent().tell(new ActorInitialized(), getSelf());
687 // Being paranoid here - this method should only be called once but just in case...
688 if (txCommitTimeoutCheckSchedule == null) {
689 // Schedule a message to be periodically sent to check if the current in-progress
690 // transaction should be expired and aborted.
691 FiniteDuration period = Duration.create(transactionCommitTimeout / 3, TimeUnit.MILLISECONDS);
692 txCommitTimeoutCheckSchedule = getContext().system().scheduler().schedule(
693 period, period, getSelf(),
694 TX_COMMIT_TIMEOUT_CHECK_MESSAGE, getContext().dispatcher(), ActorRef.noSender());
699 protected void applyState(final ActorRef clientActor, final Identifier identifier, final Object data) {
700 if (data instanceof Payload) {
702 store.applyReplicatedPayload(identifier, (Payload)data);
703 } catch (DataValidationFailedException | IOException e) {
704 LOG.error("{}: Error applying replica {}", persistenceId(), identifier, e);
707 LOG.error("{}: Unknown state for {} received {}", persistenceId(), identifier, data);
712 protected void onStateChanged() {
713 boolean isLeader = isLeader();
714 boolean hasLeader = hasLeader();
715 changeSupport.onLeadershipChange(isLeader, hasLeader);
716 treeChangeSupport.onLeadershipChange(isLeader, hasLeader);
718 // If this actor is no longer the leader close all the transaction chains
720 if (LOG.isDebugEnabled()) {
722 "{}: onStateChanged: Closing all transaction chains because shard {} is no longer the leader",
723 persistenceId(), getId());
726 store.closeAllTransactionChains();
729 if (hasLeader && !isIsolatedLeader()) {
730 messageRetrySupport.retryMessages();
735 protected void onLeaderChanged(final String oldLeader, final String newLeader) {
736 shardMBean.incrementLeadershipChangeCount();
738 boolean hasLeader = hasLeader();
739 if (hasLeader && !isLeader()) {
740 // Another leader was elected. If we were the previous leader and had pending transactions, convert
741 // them to transaction messages and send to the new leader.
742 ActorSelection leader = getLeader();
743 if (leader != null) {
744 Collection<?> messagesToForward = convertPendingTransactionsToMessages();
746 if (!messagesToForward.isEmpty()) {
747 LOG.debug("{}: Forwarding {} pending transaction messages to leader {}", persistenceId(),
748 messagesToForward.size(), leader);
750 for (Object message : messagesToForward) {
751 leader.tell(message, self());
755 commitCoordinator.abortPendingTransactions("The transacton was aborted due to inflight leadership "
756 + "change and the leader address isn't available.", this);
760 if (hasLeader && !isIsolatedLeader()) {
761 messageRetrySupport.retryMessages();
766 * Clears all pending transactions and converts them to messages to be forwarded to a new leader.
768 * @return the converted messages
770 public Collection<?> convertPendingTransactionsToMessages() {
771 return commitCoordinator.convertPendingTransactionsToMessages(
772 datastoreContext.getShardBatchedModificationCount());
776 protected void pauseLeader(final Runnable operation) {
777 LOG.debug("{}: In pauseLeader, operation: {}", persistenceId(), operation);
778 store.setRunOnPendingTransactionsComplete(operation);
782 public String persistenceId() {
787 ShardCommitCoordinator getCommitCoordinator() {
788 return commitCoordinator;
791 public DatastoreContext getDatastoreContext() {
792 return datastoreContext;
796 public ShardDataTree getDataStore() {
801 ShardStats getShardMBean() {
805 public static Builder builder() {
806 return new Builder();
809 public abstract static class AbstractBuilder<T extends AbstractBuilder<T, S>, S extends Shard> {
810 private final Class<S> shardClass;
811 private ShardIdentifier id;
812 private Map<String, String> peerAddresses = Collections.emptyMap();
813 private DatastoreContext datastoreContext;
814 private SchemaContext schemaContext;
815 private DatastoreSnapshot.ShardSnapshot restoreFromSnapshot;
816 private TipProducingDataTree dataTree;
817 private volatile boolean sealed;
819 protected AbstractBuilder(final Class<S> shardClass) {
820 this.shardClass = shardClass;
823 protected void checkSealed() {
824 Preconditions.checkState(!sealed, "Builder isalready sealed - further modifications are not allowed");
827 @SuppressWarnings("unchecked")
832 public T id(final ShardIdentifier newId) {
838 public T peerAddresses(final Map<String, String> newPeerAddresses) {
840 this.peerAddresses = newPeerAddresses;
844 public T datastoreContext(final DatastoreContext newDatastoreContext) {
846 this.datastoreContext = newDatastoreContext;
850 public T schemaContext(final SchemaContext newSchemaContext) {
852 this.schemaContext = newSchemaContext;
856 public T restoreFromSnapshot(final DatastoreSnapshot.ShardSnapshot newRestoreFromSnapshot) {
858 this.restoreFromSnapshot = newRestoreFromSnapshot;
862 public T dataTree(final TipProducingDataTree newDataTree) {
864 this.dataTree = newDataTree;
868 public ShardIdentifier getId() {
872 public Map<String, String> getPeerAddresses() {
873 return peerAddresses;
876 public DatastoreContext getDatastoreContext() {
877 return datastoreContext;
880 public SchemaContext getSchemaContext() {
881 return schemaContext;
884 public DatastoreSnapshot.ShardSnapshot getRestoreFromSnapshot() {
885 return restoreFromSnapshot;
888 public TipProducingDataTree getDataTree() {
892 public TreeType getTreeType() {
893 switch (datastoreContext.getLogicalStoreType()) {
895 return TreeType.CONFIGURATION;
897 return TreeType.OPERATIONAL;
899 throw new IllegalStateException("Unhandled logical store type "
900 + datastoreContext.getLogicalStoreType());
904 protected void verify() {
905 Preconditions.checkNotNull(id, "id should not be null");
906 Preconditions.checkNotNull(peerAddresses, "peerAddresses should not be null");
907 Preconditions.checkNotNull(datastoreContext, "dataStoreContext should not be null");
908 Preconditions.checkNotNull(schemaContext, "schemaContext should not be null");
911 public Props props() {
914 return Props.create(shardClass, this);
918 public static class Builder extends AbstractBuilder<Builder, Shard> {
925 return Ticker.systemTicker();