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.
98 * Our Shard uses InMemoryDataTree as it's internal representation and delegates all requests it
100 public class Shard extends RaftActor {
103 static final Object TX_COMMIT_TIMEOUT_CHECK_MESSAGE = new Object() {
105 public String toString() {
106 return "txCommitTimeoutCheck";
111 static final Object GET_SHARD_MBEAN_MESSAGE = new Object() {
113 public String toString() {
114 return "getShardMBeanMessage";
118 // FIXME: shard names should be encapsulated in their own class and this should be exposed as a constant.
119 public static final String DEFAULT_NAME = "default";
121 private static final Collection<ABIVersion> SUPPORTED_ABIVERSIONS;
124 final ABIVersion[] values = ABIVersion.values();
125 final ABIVersion[] real = Arrays.copyOfRange(values, 1, values.length - 1);
126 SUPPORTED_ABIVERSIONS = ImmutableList.copyOf(real).reverse();
129 // FIXME: make this a dynamic property based on mailbox size and maximum number of clients
130 private static final int CLIENT_MAX_MESSAGES = 1000;
132 // The state of this Shard
133 private final ShardDataTree store;
135 /// The name of this shard
136 private final String name;
138 private final ShardStats shardMBean;
140 private DatastoreContext datastoreContext;
142 private final ShardCommitCoordinator commitCoordinator;
144 private long transactionCommitTimeout;
146 private Cancellable txCommitTimeoutCheckSchedule;
148 private final Optional<ActorRef> roleChangeNotifier;
150 private final MessageTracker appendEntriesReplyTracker;
152 private final ShardTransactionActorFactory transactionActorFactory;
154 private final ShardSnapshotCohort snapshotCohort;
156 private final DataTreeChangeListenerSupport treeChangeSupport = new DataTreeChangeListenerSupport(this);
157 private final DataChangeListenerSupport changeSupport = new DataChangeListenerSupport(this);
160 private ShardSnapshot restoreFromSnapshot;
162 private final ShardTransactionMessageRetrySupport messageRetrySupport;
164 private final FrontendMetadata frontendMetadata = new FrontendMetadata();
165 private final Map<FrontendIdentifier, LeaderFrontendState> knownFrontends = new HashMap<>();
167 protected Shard(final AbstractBuilder<?, ?> builder) {
168 super(builder.getId().toString(), builder.getPeerAddresses(),
169 Optional.of(builder.getDatastoreContext().getShardRaftConfig()), DataStoreVersions.CURRENT_VERSION);
171 this.name = builder.getId().toString();
172 this.datastoreContext = builder.getDatastoreContext();
173 this.restoreFromSnapshot = builder.getRestoreFromSnapshot();
175 setPersistence(datastoreContext.isPersistent());
177 LOG.info("Shard created : {}, persistent : {}", name, datastoreContext.isPersistent());
179 ShardDataTreeChangeListenerPublisherActorProxy treeChangeListenerPublisher =
180 new ShardDataTreeChangeListenerPublisherActorProxy(getContext(), name + "-DTCL-publisher");
181 ShardDataChangeListenerPublisherActorProxy dataChangeListenerPublisher =
182 new ShardDataChangeListenerPublisherActorProxy(getContext(), name + "-DCL-publisher");
183 if (builder.getDataTree() != null) {
184 store = new ShardDataTree(this, builder.getSchemaContext(), builder.getDataTree(),
185 treeChangeListenerPublisher, dataChangeListenerPublisher, name);
187 store = new ShardDataTree(this, builder.getSchemaContext(), builder.getTreeType(),
188 treeChangeListenerPublisher, dataChangeListenerPublisher, name);
191 shardMBean = ShardMBeanFactory.getShardStatsMBean(name, datastoreContext.getDataStoreMXBeanType(), this);
193 if (isMetricsCaptureEnabled()) {
194 getContext().become(new MeteringBehavior(this));
197 commitCoordinator = new ShardCommitCoordinator(store, LOG, this.name);
199 setTransactionCommitTimeout();
201 // create a notifier actor for each cluster member
202 roleChangeNotifier = createRoleChangeNotifier(name);
204 appendEntriesReplyTracker = new MessageTracker(AppendEntriesReply.class,
205 getRaftActorContext().getConfigParams().getIsolatedCheckIntervalInMillis());
207 transactionActorFactory = new ShardTransactionActorFactory(store, datastoreContext,
208 new Dispatchers(context().system().dispatchers()).getDispatcherPath(
209 Dispatchers.DispatcherType.Transaction), self(), getContext(), shardMBean);
211 snapshotCohort = ShardSnapshotCohort.create(getContext(), builder.getId().getMemberName(), store, LOG,
214 messageRetrySupport = new ShardTransactionMessageRetrySupport(this);
217 private void setTransactionCommitTimeout() {
218 transactionCommitTimeout = TimeUnit.MILLISECONDS.convert(
219 datastoreContext.getShardTransactionCommitTimeoutInSeconds(), TimeUnit.SECONDS) / 2;
222 private Optional<ActorRef> createRoleChangeNotifier(final String shardId) {
223 ActorRef shardRoleChangeNotifier = this.getContext().actorOf(
224 RoleChangeNotifier.getProps(shardId), shardId + "-notifier");
225 return Optional.of(shardRoleChangeNotifier);
229 public void postStop() {
230 LOG.info("Stopping Shard {}", persistenceId());
234 messageRetrySupport.close();
236 if (txCommitTimeoutCheckSchedule != null) {
237 txCommitTimeoutCheckSchedule.cancel();
240 commitCoordinator.abortPendingTransactions("Transaction aborted due to shutdown.", this);
242 shardMBean.unregisterMBean();
246 protected void handleRecover(final Object message) {
247 LOG.debug("{}: onReceiveRecover: Received message {} from {}", persistenceId(), message.getClass(),
250 super.handleRecover(message);
251 if (LOG.isTraceEnabled()) {
252 appendEntriesReplyTracker.begin();
256 @SuppressWarnings("checkstyle:IllegalCatch")
258 protected void handleNonRaftCommand(final Object message) {
259 try (final MessageTracker.Context context = appendEntriesReplyTracker.received(message)) {
260 final Optional<Error> maybeError = context.error();
261 if (maybeError.isPresent()) {
262 LOG.trace("{} : AppendEntriesReply failed to arrive at the expected interval {}", persistenceId(),
266 if (message instanceof RequestEnvelope) {
267 final RequestEnvelope envelope = (RequestEnvelope)message;
269 final RequestSuccess<?, ?> success = handleRequest(envelope);
270 if (success != null) {
271 envelope.sendSuccess(success);
273 } catch (RequestException e) {
274 LOG.debug("{}: request {} failed", persistenceId(), envelope, e);
275 envelope.sendFailure(e);
276 } catch (Exception e) {
277 LOG.debug("{}: request {} caused failure", persistenceId(), envelope, e);
278 envelope.sendFailure(new RuntimeRequestException("Request failed to process", e));
280 } else if (message instanceof ConnectClientRequest) {
281 handleConnectClient((ConnectClientRequest)message);
282 } else if (CreateTransaction.isSerializedType(message)) {
283 handleCreateTransaction(message);
284 } else if (message instanceof BatchedModifications) {
285 handleBatchedModifications((BatchedModifications)message);
286 } else if (message instanceof ForwardedReadyTransaction) {
287 handleForwardedReadyTransaction((ForwardedReadyTransaction) message);
288 } else if (message instanceof ReadyLocalTransaction) {
289 handleReadyLocalTransaction((ReadyLocalTransaction)message);
290 } else if (CanCommitTransaction.isSerializedType(message)) {
291 handleCanCommitTransaction(CanCommitTransaction.fromSerializable(message));
292 } else if (CommitTransaction.isSerializedType(message)) {
293 handleCommitTransaction(CommitTransaction.fromSerializable(message));
294 } else if (AbortTransaction.isSerializedType(message)) {
295 handleAbortTransaction(AbortTransaction.fromSerializable(message));
296 } else if (CloseTransactionChain.isSerializedType(message)) {
297 closeTransactionChain(CloseTransactionChain.fromSerializable(message));
298 } else if (message instanceof RegisterChangeListener) {
299 changeSupport.onMessage((RegisterChangeListener) message, isLeader(), hasLeader());
300 } else if (message instanceof RegisterDataTreeChangeListener) {
301 treeChangeSupport.onMessage((RegisterDataTreeChangeListener) message, isLeader(), hasLeader());
302 } else if (message instanceof UpdateSchemaContext) {
303 updateSchemaContext((UpdateSchemaContext) message);
304 } else if (message instanceof PeerAddressResolved) {
305 PeerAddressResolved resolved = (PeerAddressResolved) message;
306 setPeerAddress(resolved.getPeerId(), resolved.getPeerAddress());
307 } else if (TX_COMMIT_TIMEOUT_CHECK_MESSAGE.equals(message)) {
308 store.checkForExpiredTransactions(transactionCommitTimeout);
309 commitCoordinator.checkForExpiredTransactions(transactionCommitTimeout, this);
310 } else if (message instanceof DatastoreContext) {
311 onDatastoreContext((DatastoreContext)message);
312 } else if (message instanceof RegisterRoleChangeListener) {
313 roleChangeNotifier.get().forward(message, context());
314 } else if (message instanceof FollowerInitialSyncUpStatus) {
315 shardMBean.setFollowerInitialSyncStatus(((FollowerInitialSyncUpStatus) message).isInitialSyncDone());
316 context().parent().tell(message, self());
317 } else if (GET_SHARD_MBEAN_MESSAGE.equals(message)) {
318 sender().tell(getShardMBean(), self());
319 } else if (message instanceof GetShardDataTree) {
320 sender().tell(store.getDataTree(), self());
321 } else if (message instanceof ServerRemoved) {
322 context().parent().forward(message, context());
323 } else if (ShardTransactionMessageRetrySupport.TIMER_MESSAGE_CLASS.isInstance(message)) {
324 messageRetrySupport.onTimerMessage(message);
325 } else if (message instanceof DataTreeCohortActorRegistry.CohortRegistryCommand) {
326 store.processCohortRegistryCommand(getSender(),
327 (DataTreeCohortActorRegistry.CohortRegistryCommand) message);
329 super.handleNonRaftCommand(message);
334 // Acquire our frontend tracking handle and verify generation matches
335 private LeaderFrontendState getFrontend(final ClientIdentifier clientId) throws RequestException {
336 final LeaderFrontendState existing = knownFrontends.get(clientId.getFrontendId());
337 if (existing != null) {
338 final int cmp = Long.compareUnsigned(existing.getIdentifier().getGeneration(), clientId.getGeneration());
343 LOG.debug("{}: rejecting request from outdated client {}", persistenceId(), clientId);
344 throw new RetiredGenerationException(existing.getIdentifier().getGeneration());
347 LOG.info("{}: retiring state {}, outdated by request from client {}", persistenceId(), existing, clientId);
349 knownFrontends.remove(clientId.getFrontendId());
351 LOG.debug("{}: client {} is not yet known", persistenceId(), clientId);
354 final LeaderFrontendState ret = new LeaderFrontendState(persistenceId(), clientId, store);
355 knownFrontends.put(clientId.getFrontendId(), ret);
356 LOG.debug("{}: created state {} for client {}", persistenceId(), ret, clientId);
360 private static @Nonnull ABIVersion selectVersion(final ConnectClientRequest message) {
361 final Range<ABIVersion> clientRange = Range.closed(message.getMinVersion(), message.getMaxVersion());
362 for (ABIVersion v : SUPPORTED_ABIVERSIONS) {
363 if (clientRange.contains(v)) {
368 throw new IllegalArgumentException(String.format(
369 "No common version between backend versions %s and client versions %s", SUPPORTED_ABIVERSIONS,
373 @SuppressWarnings("checkstyle:IllegalCatch")
374 private void handleConnectClient(final ConnectClientRequest message) {
376 if (!isLeader() || !isLeaderActive()) {
377 LOG.debug("{}: not currently leader, rejecting request {}", persistenceId(), message);
378 throw new NotLeaderException(getSelf());
381 final ABIVersion selectedVersion = selectVersion(message);
382 final LeaderFrontendState frontend = getFrontend(message.getTarget());
383 frontend.reconnect();
384 message.getReplyTo().tell(new ConnectClientSuccess(message.getTarget(), message.getSequence(), getSelf(),
385 ImmutableList.of(), store.getDataTree(), CLIENT_MAX_MESSAGES).toVersion(selectedVersion),
386 ActorRef.noSender());
387 } catch (RequestException | RuntimeException e) {
388 message.getReplyTo().tell(new Failure(e), ActorRef.noSender());
392 private @Nullable RequestSuccess<?, ?> handleRequest(final RequestEnvelope envelope) throws RequestException {
393 // We are not the leader, hence we want to fail-fast.
394 if (!isLeader() || !isLeaderActive()) {
395 LOG.debug("{}: not currently leader, rejecting request {}", persistenceId(), envelope);
396 throw new NotLeaderException(getSelf());
399 final Request<?, ?> request = envelope.getMessage();
400 if (request instanceof TransactionRequest) {
401 final TransactionRequest<?> txReq = (TransactionRequest<?>)request;
402 final ClientIdentifier clientId = txReq.getTarget().getHistoryId().getClientId();
403 return getFrontend(clientId).handleTransactionRequest(txReq, envelope);
404 } else if (request instanceof LocalHistoryRequest) {
405 final LocalHistoryRequest<?> lhReq = (LocalHistoryRequest<?>)request;
406 final ClientIdentifier clientId = lhReq.getTarget().getClientId();
407 return getFrontend(clientId).handleLocalHistoryRequest(lhReq, envelope);
409 LOG.debug("{}: rejecting unsupported request {}", persistenceId(), request);
410 throw new UnsupportedRequestException(request);
414 private boolean hasLeader() {
415 return getLeaderId() != null;
418 public int getPendingTxCommitQueueSize() {
419 return store.getQueueSize();
422 public int getCohortCacheSize() {
423 return commitCoordinator.getCohortCacheSize();
427 protected Optional<ActorRef> getRoleChangeNotifier() {
428 return roleChangeNotifier;
432 protected LeaderStateChanged newLeaderStateChanged(final String memberId, final String leaderId,
433 final short leaderPayloadVersion) {
434 return isLeader() ? new ShardLeaderStateChanged(memberId, leaderId, store.getDataTree(), leaderPayloadVersion)
435 : new ShardLeaderStateChanged(memberId, leaderId, leaderPayloadVersion);
438 protected void onDatastoreContext(final DatastoreContext context) {
439 datastoreContext = context;
441 setTransactionCommitTimeout();
443 setPersistence(datastoreContext.isPersistent());
445 updateConfigParams(datastoreContext.getShardRaftConfig());
448 boolean canSkipPayload() {
449 // If we do not have any followers and we are not using persistence we can apply modification to the state
451 return !hasFollowers() && !persistence().isRecoveryApplicable();
454 // applyState() will be invoked once consensus is reached on the payload
455 void persistPayload(final TransactionIdentifier transactionId, final Payload payload) {
456 // We are faking the sender
457 persistData(self(), transactionId, payload);
460 private void handleCommitTransaction(final CommitTransaction commit) {
462 commitCoordinator.handleCommit(commit.getTransactionId(), getSender(), this);
464 ActorSelection leader = getLeader();
465 if (leader == null) {
466 messageRetrySupport.addMessageToRetry(commit, getSender(),
467 "Could not commit transaction " + commit.getTransactionId());
469 LOG.debug("{}: Forwarding CommitTransaction to leader {}", persistenceId(), leader);
470 leader.forward(commit, getContext());
475 private void handleCanCommitTransaction(final CanCommitTransaction canCommit) {
476 LOG.debug("{}: Can committing transaction {}", persistenceId(), canCommit.getTransactionId());
479 commitCoordinator.handleCanCommit(canCommit.getTransactionId(), getSender(), this);
481 ActorSelection leader = getLeader();
482 if (leader == null) {
483 messageRetrySupport.addMessageToRetry(canCommit, getSender(),
484 "Could not canCommit transaction " + canCommit.getTransactionId());
486 LOG.debug("{}: Forwarding CanCommitTransaction to leader {}", persistenceId(), leader);
487 leader.forward(canCommit, getContext());
492 @SuppressWarnings("checkstyle:IllegalCatch")
493 protected void handleBatchedModificationsLocal(final BatchedModifications batched, final ActorRef sender) {
495 commitCoordinator.handleBatchedModifications(batched, sender, this);
496 } catch (Exception e) {
497 LOG.error("{}: Error handling BatchedModifications for Tx {}", persistenceId(),
498 batched.getTransactionId(), e);
499 sender.tell(new Failure(e), getSelf());
503 private void handleBatchedModifications(final BatchedModifications batched) {
504 // This message is sent to prepare the modifications transaction directly on the Shard as an
505 // optimization to avoid the extra overhead of a separate ShardTransaction actor. On the last
506 // BatchedModifications message, the caller sets the ready flag in the message indicating
507 // modifications are complete. The reply contains the cohort actor path (this actor) for the caller
508 // to initiate the 3-phase commit. This also avoids the overhead of sending an additional
509 // ReadyTransaction message.
511 // If we're not the leader then forward to the leader. This is a safety measure - we shouldn't
512 // normally get here if we're not the leader as the front-end (TransactionProxy) should determine
513 // the primary/leader shard. However with timing and caching on the front-end, there's a small
514 // window where it could have a stale leader during leadership transitions.
516 boolean isLeaderActive = isLeaderActive();
517 if (isLeader() && isLeaderActive) {
518 handleBatchedModificationsLocal(batched, getSender());
520 ActorSelection leader = getLeader();
521 if (!isLeaderActive || leader == null) {
522 messageRetrySupport.addMessageToRetry(batched, getSender(),
523 "Could not commit transaction " + batched.getTransactionId());
525 // If this is not the first batch and leadership changed in between batched messages,
526 // we need to reconstruct previous BatchedModifications from the transaction
527 // DataTreeModification, honoring the max batched modification count, and forward all the
528 // previous BatchedModifications to the new leader.
529 Collection<BatchedModifications> newModifications = commitCoordinator
530 .createForwardedBatchedModifications(batched,
531 datastoreContext.getShardBatchedModificationCount());
533 LOG.debug("{}: Forwarding {} BatchedModifications to leader {}", persistenceId(),
534 newModifications.size(), leader);
536 for (BatchedModifications bm : newModifications) {
537 leader.forward(bm, getContext());
543 private boolean failIfIsolatedLeader(final ActorRef sender) {
544 if (isIsolatedLeader()) {
545 sender.tell(new Failure(new NoShardLeaderException(String.format(
546 "Shard %s was the leader but has lost contact with all of its followers. Either all"
547 + " other follower nodes are down or this node is isolated by a network partition.",
548 persistenceId()))), getSelf());
555 protected boolean isIsolatedLeader() {
556 return getRaftState() == RaftState.IsolatedLeader;
559 @SuppressWarnings("checkstyle:IllegalCatch")
560 private void handleReadyLocalTransaction(final ReadyLocalTransaction message) {
561 LOG.debug("{}: handleReadyLocalTransaction for {}", persistenceId(), message.getTransactionId());
563 boolean isLeaderActive = isLeaderActive();
564 if (isLeader() && isLeaderActive) {
566 commitCoordinator.handleReadyLocalTransaction(message, getSender(), this);
567 } catch (Exception e) {
568 LOG.error("{}: Error handling ReadyLocalTransaction for Tx {}", persistenceId(),
569 message.getTransactionId(), e);
570 getSender().tell(new Failure(e), getSelf());
573 ActorSelection leader = getLeader();
574 if (!isLeaderActive || leader == null) {
575 messageRetrySupport.addMessageToRetry(message, getSender(),
576 "Could not commit transaction " + message.getTransactionId());
578 LOG.debug("{}: Forwarding ReadyLocalTransaction to leader {}", persistenceId(), leader);
579 message.setRemoteVersion(getCurrentBehavior().getLeaderPayloadVersion());
580 leader.forward(message, getContext());
585 private void handleForwardedReadyTransaction(final ForwardedReadyTransaction forwardedReady) {
586 LOG.debug("{}: handleForwardedReadyTransaction for {}", persistenceId(), forwardedReady.getTransactionId());
588 boolean isLeaderActive = isLeaderActive();
589 if (isLeader() && isLeaderActive) {
590 commitCoordinator.handleForwardedReadyTransaction(forwardedReady, getSender(), this);
592 ActorSelection leader = getLeader();
593 if (!isLeaderActive || leader == null) {
594 messageRetrySupport.addMessageToRetry(forwardedReady, getSender(),
595 "Could not commit transaction " + forwardedReady.getTransactionId());
597 LOG.debug("{}: Forwarding ForwardedReadyTransaction to leader {}", persistenceId(), leader);
599 ReadyLocalTransaction readyLocal = new ReadyLocalTransaction(forwardedReady.getTransactionId(),
600 forwardedReady.getTransaction().getSnapshot(), forwardedReady.isDoImmediateCommit());
601 readyLocal.setRemoteVersion(getCurrentBehavior().getLeaderPayloadVersion());
602 leader.forward(readyLocal, getContext());
607 private void handleAbortTransaction(final AbortTransaction abort) {
608 doAbortTransaction(abort.getTransactionId(), getSender());
611 void doAbortTransaction(final TransactionIdentifier transactionID, final ActorRef sender) {
612 commitCoordinator.handleAbort(transactionID, sender, this);
615 private void handleCreateTransaction(final Object message) {
617 createTransaction(CreateTransaction.fromSerializable(message));
618 } else if (getLeader() != null) {
619 getLeader().forward(message, getContext());
621 getSender().tell(new Failure(new NoShardLeaderException(
622 "Could not create a shard transaction", persistenceId())), getSelf());
626 private void closeTransactionChain(final CloseTransactionChain closeTransactionChain) {
627 store.closeTransactionChain(closeTransactionChain.getIdentifier());
630 @SuppressWarnings("checkstyle:IllegalCatch")
631 private void createTransaction(final CreateTransaction createTransaction) {
633 if (TransactionType.fromInt(createTransaction.getTransactionType()) != TransactionType.READ_ONLY
634 && failIfIsolatedLeader(getSender())) {
638 ActorRef transactionActor = createTransaction(createTransaction.getTransactionType(),
639 createTransaction.getTransactionId());
641 getSender().tell(new CreateTransactionReply(Serialization.serializedActorPath(transactionActor),
642 createTransaction.getTransactionId(), createTransaction.getVersion()).toSerializable(), getSelf());
643 } catch (Exception e) {
644 getSender().tell(new Failure(e), getSelf());
648 private ActorRef createTransaction(final int transactionType, final TransactionIdentifier transactionId) {
649 LOG.debug("{}: Creating transaction : {} ", persistenceId(), transactionId);
650 return transactionActorFactory.newShardTransaction(TransactionType.fromInt(transactionType),
654 private void updateSchemaContext(final UpdateSchemaContext message) {
655 updateSchemaContext(message.getSchemaContext());
659 void updateSchemaContext(final SchemaContext schemaContext) {
660 store.updateSchemaContext(schemaContext);
663 private boolean isMetricsCaptureEnabled() {
664 CommonConfig config = new CommonConfig(getContext().system().settings().config());
665 return config.isMetricCaptureEnabled();
670 public RaftActorSnapshotCohort getRaftActorSnapshotCohort() {
671 return snapshotCohort;
676 protected RaftActorRecoveryCohort getRaftActorRecoveryCohort() {
677 return new ShardRecoveryCoordinator(store,
678 restoreFromSnapshot != null ? restoreFromSnapshot.getSnapshot() : null, persistenceId(), LOG);
682 protected void onRecoveryComplete() {
683 restoreFromSnapshot = null;
685 //notify shard manager
686 getContext().parent().tell(new ActorInitialized(), getSelf());
688 // Being paranoid here - this method should only be called once but just in case...
689 if (txCommitTimeoutCheckSchedule == null) {
690 // Schedule a message to be periodically sent to check if the current in-progress
691 // transaction should be expired and aborted.
692 FiniteDuration period = Duration.create(transactionCommitTimeout / 3, TimeUnit.MILLISECONDS);
693 txCommitTimeoutCheckSchedule = getContext().system().scheduler().schedule(
694 period, period, getSelf(),
695 TX_COMMIT_TIMEOUT_CHECK_MESSAGE, getContext().dispatcher(), ActorRef.noSender());
700 protected void applyState(final ActorRef clientActor, final Identifier identifier, final Object data) {
701 if (data instanceof Payload) {
703 store.applyReplicatedPayload(identifier, (Payload)data);
704 } catch (DataValidationFailedException | IOException e) {
705 LOG.error("{}: Error applying replica {}", persistenceId(), identifier, e);
708 LOG.error("{}: Unknown state for {} received {}", persistenceId(), identifier, data);
713 protected void onStateChanged() {
714 boolean isLeader = isLeader();
715 boolean hasLeader = hasLeader();
716 changeSupport.onLeadershipChange(isLeader, hasLeader);
717 treeChangeSupport.onLeadershipChange(isLeader, hasLeader);
719 // If this actor is no longer the leader close all the transaction chains
721 if (LOG.isDebugEnabled()) {
723 "{}: onStateChanged: Closing all transaction chains because shard {} is no longer the leader",
724 persistenceId(), getId());
727 store.closeAllTransactionChains();
730 if (hasLeader && !isIsolatedLeader()) {
731 messageRetrySupport.retryMessages();
736 protected void onLeaderChanged(final String oldLeader, final String newLeader) {
737 shardMBean.incrementLeadershipChangeCount();
739 boolean hasLeader = hasLeader();
740 if (hasLeader && !isLeader()) {
741 // Another leader was elected. If we were the previous leader and had pending transactions, convert
742 // them to transaction messages and send to the new leader.
743 ActorSelection leader = getLeader();
744 if (leader != null) {
745 Collection<?> messagesToForward = convertPendingTransactionsToMessages();
747 if (!messagesToForward.isEmpty()) {
748 LOG.debug("{}: Forwarding {} pending transaction messages to leader {}", persistenceId(),
749 messagesToForward.size(), leader);
751 for (Object message : messagesToForward) {
752 leader.tell(message, self());
756 commitCoordinator.abortPendingTransactions("The transacton was aborted due to inflight leadership "
757 + "change and the leader address isn't available.", this);
761 if (hasLeader && !isIsolatedLeader()) {
762 messageRetrySupport.retryMessages();
767 * Clears all pending transactions and converts them to messages to be forwarded to a new leader.
769 * @return the converted messages
771 public Collection<?> convertPendingTransactionsToMessages() {
772 return commitCoordinator.convertPendingTransactionsToMessages(
773 datastoreContext.getShardBatchedModificationCount());
777 protected void pauseLeader(final Runnable operation) {
778 LOG.debug("{}: In pauseLeader, operation: {}", persistenceId(), operation);
779 store.setRunOnPendingTransactionsComplete(operation);
783 public String persistenceId() {
788 ShardCommitCoordinator getCommitCoordinator() {
789 return commitCoordinator;
792 public DatastoreContext getDatastoreContext() {
793 return datastoreContext;
797 public ShardDataTree getDataStore() {
802 ShardStats getShardMBean() {
806 public static Builder builder() {
807 return new Builder();
810 public abstract static class AbstractBuilder<T extends AbstractBuilder<T, S>, S extends Shard> {
811 private final Class<S> shardClass;
812 private ShardIdentifier id;
813 private Map<String, String> peerAddresses = Collections.emptyMap();
814 private DatastoreContext datastoreContext;
815 private SchemaContext schemaContext;
816 private DatastoreSnapshot.ShardSnapshot restoreFromSnapshot;
817 private TipProducingDataTree dataTree;
818 private volatile boolean sealed;
820 protected AbstractBuilder(final Class<S> shardClass) {
821 this.shardClass = shardClass;
824 protected void checkSealed() {
825 Preconditions.checkState(!sealed, "Builder isalready sealed - further modifications are not allowed");
828 @SuppressWarnings("unchecked")
833 public T id(final ShardIdentifier newId) {
839 public T peerAddresses(final Map<String, String> newPeerAddresses) {
841 this.peerAddresses = newPeerAddresses;
845 public T datastoreContext(final DatastoreContext newDatastoreContext) {
847 this.datastoreContext = newDatastoreContext;
851 public T schemaContext(final SchemaContext newSchemaContext) {
853 this.schemaContext = newSchemaContext;
857 public T restoreFromSnapshot(final DatastoreSnapshot.ShardSnapshot newRestoreFromSnapshot) {
859 this.restoreFromSnapshot = newRestoreFromSnapshot;
863 public T dataTree(final TipProducingDataTree newDataTree) {
865 this.dataTree = newDataTree;
869 public ShardIdentifier getId() {
873 public Map<String, String> getPeerAddresses() {
874 return peerAddresses;
877 public DatastoreContext getDatastoreContext() {
878 return datastoreContext;
881 public SchemaContext getSchemaContext() {
882 return schemaContext;
885 public DatastoreSnapshot.ShardSnapshot getRestoreFromSnapshot() {
886 return restoreFromSnapshot;
889 public TipProducingDataTree getDataTree() {
893 public TreeType getTreeType() {
894 switch (datastoreContext.getLogicalStoreType()) {
896 return TreeType.CONFIGURATION;
898 return TreeType.OPERATIONAL;
900 throw new IllegalStateException("Unhandled logical store type "
901 + datastoreContext.getLogicalStoreType());
905 protected void verify() {
906 Preconditions.checkNotNull(id, "id should not be null");
907 Preconditions.checkNotNull(peerAddresses, "peerAddresses should not be null");
908 Preconditions.checkNotNull(datastoreContext, "dataStoreContext should not be null");
909 Preconditions.checkNotNull(schemaContext, "schemaContext should not be null");
912 public Props props() {
915 return Props.create(shardClass, this);
919 public static class Builder extends AbstractBuilder<Builder, Shard> {
926 return Ticker.systemTicker();