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;
16 import akka.actor.Status.Failure;
17 import akka.serialization.Serialization;
18 import com.google.common.annotations.VisibleForTesting;
19 import com.google.common.base.Optional;
20 import com.google.common.base.Preconditions;
21 import com.google.common.base.Ticker;
22 import com.google.common.base.Verify;
23 import com.google.common.collect.ImmutableList;
24 import com.google.common.collect.ImmutableMap;
25 import com.google.common.collect.Range;
26 import java.io.IOException;
27 import java.util.Arrays;
28 import java.util.Collection;
29 import java.util.Collections;
31 import java.util.concurrent.TimeUnit;
32 import javax.annotation.Nonnull;
33 import javax.annotation.Nullable;
34 import org.opendaylight.controller.cluster.access.ABIVersion;
35 import org.opendaylight.controller.cluster.access.commands.ConnectClientRequest;
36 import org.opendaylight.controller.cluster.access.commands.ConnectClientSuccess;
37 import org.opendaylight.controller.cluster.access.commands.LocalHistoryRequest;
38 import org.opendaylight.controller.cluster.access.commands.NotLeaderException;
39 import org.opendaylight.controller.cluster.access.commands.TransactionRequest;
40 import org.opendaylight.controller.cluster.access.concepts.ClientIdentifier;
41 import org.opendaylight.controller.cluster.access.concepts.FrontendIdentifier;
42 import org.opendaylight.controller.cluster.access.concepts.LocalHistoryIdentifier;
43 import org.opendaylight.controller.cluster.access.concepts.Request;
44 import org.opendaylight.controller.cluster.access.concepts.RequestEnvelope;
45 import org.opendaylight.controller.cluster.access.concepts.RequestException;
46 import org.opendaylight.controller.cluster.access.concepts.RequestSuccess;
47 import org.opendaylight.controller.cluster.access.concepts.RetiredGenerationException;
48 import org.opendaylight.controller.cluster.access.concepts.RuntimeRequestException;
49 import org.opendaylight.controller.cluster.access.concepts.TransactionIdentifier;
50 import org.opendaylight.controller.cluster.access.concepts.UnsupportedRequestException;
51 import org.opendaylight.controller.cluster.common.actor.CommonConfig;
52 import org.opendaylight.controller.cluster.common.actor.MessageTracker;
53 import org.opendaylight.controller.cluster.common.actor.MessageTracker.Error;
54 import org.opendaylight.controller.cluster.common.actor.MeteringBehavior;
55 import org.opendaylight.controller.cluster.datastore.exceptions.NoShardLeaderException;
56 import org.opendaylight.controller.cluster.datastore.identifiers.ShardIdentifier;
57 import org.opendaylight.controller.cluster.datastore.jmx.mbeans.shard.ShardMBeanFactory;
58 import org.opendaylight.controller.cluster.datastore.jmx.mbeans.shard.ShardStats;
59 import org.opendaylight.controller.cluster.datastore.messages.AbortTransaction;
60 import org.opendaylight.controller.cluster.datastore.messages.ActorInitialized;
61 import org.opendaylight.controller.cluster.datastore.messages.BatchedModifications;
62 import org.opendaylight.controller.cluster.datastore.messages.CanCommitTransaction;
63 import org.opendaylight.controller.cluster.datastore.messages.CloseTransactionChain;
64 import org.opendaylight.controller.cluster.datastore.messages.CommitTransaction;
65 import org.opendaylight.controller.cluster.datastore.messages.CreateTransaction;
66 import org.opendaylight.controller.cluster.datastore.messages.CreateTransactionReply;
67 import org.opendaylight.controller.cluster.datastore.messages.ForwardedReadyTransaction;
68 import org.opendaylight.controller.cluster.datastore.messages.GetShardDataTree;
69 import org.opendaylight.controller.cluster.datastore.messages.MakeLeaderLocal;
70 import org.opendaylight.controller.cluster.datastore.messages.OnDemandShardState;
71 import org.opendaylight.controller.cluster.datastore.messages.PeerAddressResolved;
72 import org.opendaylight.controller.cluster.datastore.messages.PersistAbortTransactionPayload;
73 import org.opendaylight.controller.cluster.datastore.messages.ReadyLocalTransaction;
74 import org.opendaylight.controller.cluster.datastore.messages.RegisterChangeListener;
75 import org.opendaylight.controller.cluster.datastore.messages.RegisterDataTreeChangeListener;
76 import org.opendaylight.controller.cluster.datastore.messages.ShardLeaderStateChanged;
77 import org.opendaylight.controller.cluster.datastore.messages.UpdateSchemaContext;
78 import org.opendaylight.controller.cluster.datastore.persisted.AbortTransactionPayload;
79 import org.opendaylight.controller.cluster.datastore.persisted.DatastoreSnapshot;
80 import org.opendaylight.controller.cluster.datastore.persisted.DatastoreSnapshot.ShardSnapshot;
81 import org.opendaylight.controller.cluster.datastore.utils.Dispatchers;
82 import org.opendaylight.controller.cluster.notifications.LeaderStateChanged;
83 import org.opendaylight.controller.cluster.notifications.RegisterRoleChangeListener;
84 import org.opendaylight.controller.cluster.notifications.RoleChangeNotifier;
85 import org.opendaylight.controller.cluster.raft.LeadershipTransferFailedException;
86 import org.opendaylight.controller.cluster.raft.RaftActor;
87 import org.opendaylight.controller.cluster.raft.RaftActorRecoveryCohort;
88 import org.opendaylight.controller.cluster.raft.RaftActorSnapshotCohort;
89 import org.opendaylight.controller.cluster.raft.RaftState;
90 import org.opendaylight.controller.cluster.raft.base.messages.FollowerInitialSyncUpStatus;
91 import org.opendaylight.controller.cluster.raft.client.messages.OnDemandRaftState;
92 import org.opendaylight.controller.cluster.raft.messages.AppendEntriesReply;
93 import org.opendaylight.controller.cluster.raft.messages.RequestLeadership;
94 import org.opendaylight.controller.cluster.raft.messages.ServerRemoved;
95 import org.opendaylight.controller.cluster.raft.protobuff.client.messages.Payload;
96 import org.opendaylight.yangtools.concepts.Identifier;
97 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataValidationFailedException;
98 import org.opendaylight.yangtools.yang.data.api.schema.tree.TipProducingDataTree;
99 import org.opendaylight.yangtools.yang.data.api.schema.tree.TreeType;
100 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
101 import org.opendaylight.yangtools.yang.model.api.SchemaContextProvider;
102 import scala.concurrent.duration.Duration;
103 import scala.concurrent.duration.FiniteDuration;
106 * A Shard represents a portion of the logical data tree.
109 * Our Shard uses InMemoryDataTree as it's internal representation and delegates all requests it
111 public class Shard extends RaftActor {
114 static final Object TX_COMMIT_TIMEOUT_CHECK_MESSAGE = new Object() {
116 public String toString() {
117 return "txCommitTimeoutCheck";
122 static final Object GET_SHARD_MBEAN_MESSAGE = new Object() {
124 public String toString() {
125 return "getShardMBeanMessage";
129 static final Object RESUME_NEXT_PENDING_TRANSACTION = new Object() {
131 public String toString() {
132 return "resumeNextPendingTransaction";
136 // FIXME: shard names should be encapsulated in their own class and this should be exposed as a constant.
137 public static final String DEFAULT_NAME = "default";
139 private static final Collection<ABIVersion> SUPPORTED_ABIVERSIONS;
142 final ABIVersion[] values = ABIVersion.values();
143 final ABIVersion[] real = Arrays.copyOfRange(values, 1, values.length - 1);
144 SUPPORTED_ABIVERSIONS = ImmutableList.copyOf(real).reverse();
147 // FIXME: make this a dynamic property based on mailbox size and maximum number of clients
148 private static final int CLIENT_MAX_MESSAGES = 1000;
150 // The state of this Shard
151 private final ShardDataTree store;
153 /// The name of this shard
154 private final String name;
156 private final ShardStats shardMBean;
158 private DatastoreContext datastoreContext;
160 private final ShardCommitCoordinator commitCoordinator;
162 private long transactionCommitTimeout;
164 private Cancellable txCommitTimeoutCheckSchedule;
166 private final Optional<ActorRef> roleChangeNotifier;
168 private final MessageTracker appendEntriesReplyTracker;
170 private final ShardTransactionActorFactory transactionActorFactory;
172 private final ShardSnapshotCohort snapshotCohort;
174 private final DataTreeChangeListenerSupport treeChangeSupport = new DataTreeChangeListenerSupport(this);
175 private final DataChangeListenerSupport changeSupport = new DataChangeListenerSupport(this);
178 private ShardSnapshot restoreFromSnapshot;
180 private final ShardTransactionMessageRetrySupport messageRetrySupport;
182 private final FrontendMetadata frontendMetadata;
183 private Map<FrontendIdentifier, LeaderFrontendState> knownFrontends = ImmutableMap.of();
184 private boolean paused;
186 protected Shard(final AbstractBuilder<?, ?> builder) {
187 super(builder.getId().toString(), builder.getPeerAddresses(),
188 Optional.of(builder.getDatastoreContext().getShardRaftConfig()), DataStoreVersions.CURRENT_VERSION);
190 this.name = builder.getId().toString();
191 this.datastoreContext = builder.getDatastoreContext();
192 this.restoreFromSnapshot = builder.getRestoreFromSnapshot();
193 this.frontendMetadata = new FrontendMetadata(name);
195 setPersistence(datastoreContext.isPersistent());
197 LOG.info("Shard created : {}, persistent : {}", name, datastoreContext.isPersistent());
199 ShardDataTreeChangeListenerPublisherActorProxy treeChangeListenerPublisher =
200 new ShardDataTreeChangeListenerPublisherActorProxy(getContext(), name + "-DTCL-publisher", name);
201 ShardDataChangeListenerPublisherActorProxy dataChangeListenerPublisher =
202 new ShardDataChangeListenerPublisherActorProxy(getContext(), name + "-DCL-publisher", name);
203 if (builder.getDataTree() != null) {
204 store = new ShardDataTree(this, builder.getSchemaContext(), builder.getDataTree(),
205 treeChangeListenerPublisher, dataChangeListenerPublisher, name, frontendMetadata);
207 store = new ShardDataTree(this, builder.getSchemaContext(), builder.getTreeType(),
208 builder.getDatastoreContext().getStoreRoot(), treeChangeListenerPublisher,
209 dataChangeListenerPublisher, name, frontendMetadata);
212 shardMBean = ShardMBeanFactory.getShardStatsMBean(name, datastoreContext.getDataStoreMXBeanType(), this);
214 if (isMetricsCaptureEnabled()) {
215 getContext().become(new MeteringBehavior(this));
218 commitCoordinator = new ShardCommitCoordinator(store, LOG, this.name);
220 setTransactionCommitTimeout();
222 // create a notifier actor for each cluster member
223 roleChangeNotifier = createRoleChangeNotifier(name);
225 appendEntriesReplyTracker = new MessageTracker(AppendEntriesReply.class,
226 getRaftActorContext().getConfigParams().getIsolatedCheckIntervalInMillis());
228 transactionActorFactory = new ShardTransactionActorFactory(store, datastoreContext,
229 new Dispatchers(context().system().dispatchers()).getDispatcherPath(Dispatchers.DispatcherType.Transaction),
230 self(), getContext(), shardMBean, builder.getId().getShardName());
232 snapshotCohort = ShardSnapshotCohort.create(getContext(), builder.getId().getMemberName(), store, LOG,
235 messageRetrySupport = new ShardTransactionMessageRetrySupport(this);
238 private void setTransactionCommitTimeout() {
239 transactionCommitTimeout = TimeUnit.MILLISECONDS.convert(
240 datastoreContext.getShardTransactionCommitTimeoutInSeconds(), TimeUnit.SECONDS) / 2;
243 private Optional<ActorRef> createRoleChangeNotifier(final String shardId) {
244 ActorRef shardRoleChangeNotifier = this.getContext().actorOf(
245 RoleChangeNotifier.getProps(shardId), shardId + "-notifier");
246 return Optional.of(shardRoleChangeNotifier);
250 public void postStop() {
251 LOG.info("Stopping Shard {}", persistenceId());
255 messageRetrySupport.close();
257 if (txCommitTimeoutCheckSchedule != null) {
258 txCommitTimeoutCheckSchedule.cancel();
261 commitCoordinator.abortPendingTransactions("Transaction aborted due to shutdown.", this);
263 shardMBean.unregisterMBean();
267 protected void handleRecover(final Object message) {
268 LOG.debug("{}: onReceiveRecover: Received message {} from {}", persistenceId(), message.getClass(),
271 super.handleRecover(message);
272 if (LOG.isTraceEnabled()) {
273 appendEntriesReplyTracker.begin();
277 @SuppressWarnings("checkstyle:IllegalCatch")
279 protected void handleNonRaftCommand(final Object message) {
280 try (MessageTracker.Context context = appendEntriesReplyTracker.received(message)) {
281 final Optional<Error> maybeError = context.error();
282 if (maybeError.isPresent()) {
283 LOG.trace("{} : AppendEntriesReply failed to arrive at the expected interval {}", persistenceId(),
287 store.resetTransactionBatch();
289 if (message instanceof RequestEnvelope) {
290 final long now = ticker().read();
291 final RequestEnvelope envelope = (RequestEnvelope)message;
294 final RequestSuccess<?, ?> success = handleRequest(envelope, now);
295 if (success != null) {
296 envelope.sendSuccess(success, ticker().read() - now);
298 } catch (RequestException e) {
299 LOG.debug("{}: request {} failed", persistenceId(), envelope, e);
300 envelope.sendFailure(e, ticker().read() - now);
301 } catch (Exception e) {
302 LOG.debug("{}: request {} caused failure", persistenceId(), envelope, e);
303 envelope.sendFailure(new RuntimeRequestException("Request failed to process", e),
304 ticker().read() - now);
306 } else if (message instanceof ConnectClientRequest) {
307 handleConnectClient((ConnectClientRequest)message);
308 } else if (CreateTransaction.isSerializedType(message)) {
309 handleCreateTransaction(message);
310 } else if (message instanceof BatchedModifications) {
311 handleBatchedModifications((BatchedModifications)message);
312 } else if (message instanceof ForwardedReadyTransaction) {
313 handleForwardedReadyTransaction((ForwardedReadyTransaction) message);
314 } else if (message instanceof ReadyLocalTransaction) {
315 handleReadyLocalTransaction((ReadyLocalTransaction)message);
316 } else if (CanCommitTransaction.isSerializedType(message)) {
317 handleCanCommitTransaction(CanCommitTransaction.fromSerializable(message));
318 } else if (CommitTransaction.isSerializedType(message)) {
319 handleCommitTransaction(CommitTransaction.fromSerializable(message));
320 } else if (AbortTransaction.isSerializedType(message)) {
321 handleAbortTransaction(AbortTransaction.fromSerializable(message));
322 } else if (CloseTransactionChain.isSerializedType(message)) {
323 closeTransactionChain(CloseTransactionChain.fromSerializable(message));
324 } else if (message instanceof RegisterChangeListener) {
325 changeSupport.onMessage((RegisterChangeListener) message, isLeader(), hasLeader());
326 } else if (message instanceof RegisterDataTreeChangeListener) {
327 treeChangeSupport.onMessage((RegisterDataTreeChangeListener) message, isLeader(), hasLeader());
328 } else if (message instanceof UpdateSchemaContext) {
329 updateSchemaContext((UpdateSchemaContext) message);
330 } else if (message instanceof PeerAddressResolved) {
331 PeerAddressResolved resolved = (PeerAddressResolved) message;
332 setPeerAddress(resolved.getPeerId(), resolved.getPeerAddress());
333 } else if (TX_COMMIT_TIMEOUT_CHECK_MESSAGE.equals(message)) {
334 store.checkForExpiredTransactions(transactionCommitTimeout);
335 commitCoordinator.checkForExpiredTransactions(transactionCommitTimeout, this);
336 } else if (message instanceof DatastoreContext) {
337 onDatastoreContext((DatastoreContext)message);
338 } else if (message instanceof RegisterRoleChangeListener) {
339 roleChangeNotifier.get().forward(message, context());
340 } else if (message instanceof FollowerInitialSyncUpStatus) {
341 shardMBean.setFollowerInitialSyncStatus(((FollowerInitialSyncUpStatus) message).isInitialSyncDone());
342 context().parent().tell(message, self());
343 } else if (GET_SHARD_MBEAN_MESSAGE.equals(message)) {
344 sender().tell(getShardMBean(), self());
345 } else if (message instanceof GetShardDataTree) {
346 sender().tell(store.getDataTree(), self());
347 } else if (message instanceof ServerRemoved) {
348 context().parent().forward(message, context());
349 } else if (ShardTransactionMessageRetrySupport.TIMER_MESSAGE_CLASS.isInstance(message)) {
350 messageRetrySupport.onTimerMessage(message);
351 } else if (message instanceof DataTreeCohortActorRegistry.CohortRegistryCommand) {
352 store.processCohortRegistryCommand(getSender(),
353 (DataTreeCohortActorRegistry.CohortRegistryCommand) message);
354 } else if (message instanceof PersistAbortTransactionPayload) {
355 final TransactionIdentifier txId = ((PersistAbortTransactionPayload) message).getTransactionId();
356 persistPayload(txId, AbortTransactionPayload.create(txId), true);
357 } else if (message instanceof MakeLeaderLocal) {
359 } else if (RESUME_NEXT_PENDING_TRANSACTION.equals(message)) {
360 store.resumeNextPendingTransaction();
362 super.handleNonRaftCommand(message);
367 private void onMakeLeaderLocal() {
368 LOG.debug("{}: onMakeLeaderLocal received", persistenceId());
370 getSender().tell(new Status.Success(null), getSelf());
374 final ActorSelection leader = getLeader();
376 if (leader == null) {
377 // Leader is not present. The cluster is most likely trying to
378 // elect a leader and we should let that run its normal course
380 // TODO we can wait for the election to complete and retry the
381 // request. We can also let the caller retry by sending a flag
382 // in the response indicating the request is "reTryable".
383 getSender().tell(new Failure(
384 new LeadershipTransferFailedException("We cannot initiate leadership transfer to local node. "
385 + "Currently there is no leader for " + persistenceId())),
390 leader.tell(new RequestLeadership(getId(), getSender()), getSelf());
393 // Acquire our frontend tracking handle and verify generation matches
394 private LeaderFrontendState getFrontend(final ClientIdentifier clientId) throws RequestException {
395 final LeaderFrontendState existing = knownFrontends.get(clientId.getFrontendId());
396 if (existing != null) {
397 final int cmp = Long.compareUnsigned(existing.getIdentifier().getGeneration(), clientId.getGeneration());
402 LOG.debug("{}: rejecting request from outdated client {}", persistenceId(), clientId);
403 throw new RetiredGenerationException(existing.getIdentifier().getGeneration());
406 LOG.info("{}: retiring state {}, outdated by request from client {}", persistenceId(), existing, clientId);
408 knownFrontends.remove(clientId.getFrontendId());
410 LOG.debug("{}: client {} is not yet known", persistenceId(), clientId);
413 final LeaderFrontendState ret = new LeaderFrontendState(persistenceId(), clientId, store);
414 knownFrontends.put(clientId.getFrontendId(), ret);
415 LOG.debug("{}: created state {} for client {}", persistenceId(), ret, clientId);
419 private static @Nonnull ABIVersion selectVersion(final ConnectClientRequest message) {
420 final Range<ABIVersion> clientRange = Range.closed(message.getMinVersion(), message.getMaxVersion());
421 for (ABIVersion v : SUPPORTED_ABIVERSIONS) {
422 if (clientRange.contains(v)) {
427 throw new IllegalArgumentException(String.format(
428 "No common version between backend versions %s and client versions %s", SUPPORTED_ABIVERSIONS,
432 @SuppressWarnings("checkstyle:IllegalCatch")
433 private void handleConnectClient(final ConnectClientRequest message) {
435 if (!isLeader() || !isLeaderActive()) {
436 LOG.info("{}: not currently leader, rejecting request {}. isLeader: {}, isLeaderActive: {},"
437 + "isLeadershipTransferInProgress: {}.",
438 persistenceId(), message, isLeader(), isLeaderActive(), isLeadershipTransferInProgress());
439 throw new NotLeaderException(getSelf());
442 final ABIVersion selectedVersion = selectVersion(message);
443 final LeaderFrontendState frontend = getFrontend(message.getTarget());
444 frontend.reconnect();
445 message.getReplyTo().tell(new ConnectClientSuccess(message.getTarget(), message.getSequence(), getSelf(),
446 ImmutableList.of(), store.getDataTree(), CLIENT_MAX_MESSAGES).toVersion(selectedVersion),
447 ActorRef.noSender());
448 } catch (RequestException | RuntimeException e) {
449 message.getReplyTo().tell(new Failure(e), ActorRef.noSender());
453 private @Nullable RequestSuccess<?, ?> handleRequest(final RequestEnvelope envelope, final long now)
454 throws RequestException {
455 // We are not the leader, hence we want to fail-fast.
456 if (!isLeader() || paused || !isLeaderActive()) {
457 LOG.debug("{}: not currently active leader, rejecting request {}. isLeader: {}, isLeaderActive: {},"
458 + "isLeadershipTransferInProgress: {}, paused: {}",
459 persistenceId(), envelope, isLeader(), isLeaderActive(), isLeadershipTransferInProgress(), paused);
460 throw new NotLeaderException(getSelf());
463 final Request<?, ?> request = envelope.getMessage();
464 if (request instanceof TransactionRequest) {
465 final TransactionRequest<?> txReq = (TransactionRequest<?>)request;
466 final ClientIdentifier clientId = txReq.getTarget().getHistoryId().getClientId();
467 return getFrontend(clientId).handleTransactionRequest(txReq, envelope, now);
468 } else if (request instanceof LocalHistoryRequest) {
469 final LocalHistoryRequest<?> lhReq = (LocalHistoryRequest<?>)request;
470 final ClientIdentifier clientId = lhReq.getTarget().getClientId();
471 return getFrontend(clientId).handleLocalHistoryRequest(lhReq, envelope, now);
473 LOG.warn("{}: rejecting unsupported request {}", persistenceId(), request);
474 throw new UnsupportedRequestException(request);
478 private boolean hasLeader() {
479 return getLeaderId() != null;
482 public int getPendingTxCommitQueueSize() {
483 return store.getQueueSize();
486 public int getCohortCacheSize() {
487 return commitCoordinator.getCohortCacheSize();
491 protected Optional<ActorRef> getRoleChangeNotifier() {
492 return roleChangeNotifier;
496 protected LeaderStateChanged newLeaderStateChanged(final String memberId, final String leaderId,
497 final short leaderPayloadVersion) {
498 return isLeader() ? new ShardLeaderStateChanged(memberId, leaderId, store.getDataTree(), leaderPayloadVersion)
499 : new ShardLeaderStateChanged(memberId, leaderId, leaderPayloadVersion);
502 protected void onDatastoreContext(final DatastoreContext context) {
503 datastoreContext = context;
505 setTransactionCommitTimeout();
507 setPersistence(datastoreContext.isPersistent());
509 updateConfigParams(datastoreContext.getShardRaftConfig());
512 // applyState() will be invoked once consensus is reached on the payload
513 void persistPayload(final Identifier id, final Payload payload, final boolean batchHint) {
514 boolean canSkipPayload = !hasFollowers() && !persistence().isRecoveryApplicable();
515 if (canSkipPayload) {
516 applyState(self(), id, payload);
518 // We are faking the sender
519 persistData(self(), id, payload, batchHint);
523 private void handleCommitTransaction(final CommitTransaction commit) {
525 commitCoordinator.handleCommit(commit.getTransactionId(), getSender(), this);
527 ActorSelection leader = getLeader();
528 if (leader == null) {
529 messageRetrySupport.addMessageToRetry(commit, getSender(),
530 "Could not commit transaction " + commit.getTransactionId());
532 LOG.debug("{}: Forwarding CommitTransaction to leader {}", persistenceId(), leader);
533 leader.forward(commit, getContext());
538 private void handleCanCommitTransaction(final CanCommitTransaction canCommit) {
539 LOG.debug("{}: Can committing transaction {}", persistenceId(), canCommit.getTransactionId());
542 commitCoordinator.handleCanCommit(canCommit.getTransactionId(), getSender(), this);
544 ActorSelection leader = getLeader();
545 if (leader == null) {
546 messageRetrySupport.addMessageToRetry(canCommit, getSender(),
547 "Could not canCommit transaction " + canCommit.getTransactionId());
549 LOG.debug("{}: Forwarding CanCommitTransaction to leader {}", persistenceId(), leader);
550 leader.forward(canCommit, getContext());
555 @SuppressWarnings("checkstyle:IllegalCatch")
556 protected void handleBatchedModificationsLocal(final BatchedModifications batched, final ActorRef sender) {
558 commitCoordinator.handleBatchedModifications(batched, sender, this);
559 } catch (Exception e) {
560 LOG.error("{}: Error handling BatchedModifications for Tx {}", persistenceId(),
561 batched.getTransactionId(), e);
562 sender.tell(new Failure(e), getSelf());
566 private void handleBatchedModifications(final BatchedModifications batched) {
567 // This message is sent to prepare the modifications transaction directly on the Shard as an
568 // optimization to avoid the extra overhead of a separate ShardTransaction actor. On the last
569 // BatchedModifications message, the caller sets the ready flag in the message indicating
570 // modifications are complete. The reply contains the cohort actor path (this actor) for the caller
571 // to initiate the 3-phase commit. This also avoids the overhead of sending an additional
572 // ReadyTransaction message.
574 // If we're not the leader then forward to the leader. This is a safety measure - we shouldn't
575 // normally get here if we're not the leader as the front-end (TransactionProxy) should determine
576 // the primary/leader shard. However with timing and caching on the front-end, there's a small
577 // window where it could have a stale leader during leadership transitions.
579 boolean isLeaderActive = isLeaderActive();
580 if (isLeader() && isLeaderActive) {
581 handleBatchedModificationsLocal(batched, getSender());
583 ActorSelection leader = getLeader();
584 if (!isLeaderActive || leader == null) {
585 messageRetrySupport.addMessageToRetry(batched, getSender(),
586 "Could not commit transaction " + batched.getTransactionId());
588 // If this is not the first batch and leadership changed in between batched messages,
589 // we need to reconstruct previous BatchedModifications from the transaction
590 // DataTreeModification, honoring the max batched modification count, and forward all the
591 // previous BatchedModifications to the new leader.
592 Collection<BatchedModifications> newModifications = commitCoordinator
593 .createForwardedBatchedModifications(batched,
594 datastoreContext.getShardBatchedModificationCount());
596 LOG.debug("{}: Forwarding {} BatchedModifications to leader {}", persistenceId(),
597 newModifications.size(), leader);
599 for (BatchedModifications bm : newModifications) {
600 leader.forward(bm, getContext());
606 private boolean failIfIsolatedLeader(final ActorRef sender) {
607 if (isIsolatedLeader()) {
608 sender.tell(new Failure(new NoShardLeaderException(String.format(
609 "Shard %s was the leader but has lost contact with all of its followers. Either all"
610 + " other follower nodes are down or this node is isolated by a network partition.",
611 persistenceId()))), getSelf());
618 protected boolean isIsolatedLeader() {
619 return getRaftState() == RaftState.IsolatedLeader;
622 @SuppressWarnings("checkstyle:IllegalCatch")
623 private void handleReadyLocalTransaction(final ReadyLocalTransaction message) {
624 LOG.debug("{}: handleReadyLocalTransaction for {}", persistenceId(), message.getTransactionId());
626 boolean isLeaderActive = isLeaderActive();
627 if (isLeader() && isLeaderActive) {
629 commitCoordinator.handleReadyLocalTransaction(message, getSender(), this);
630 } catch (Exception e) {
631 LOG.error("{}: Error handling ReadyLocalTransaction for Tx {}", persistenceId(),
632 message.getTransactionId(), e);
633 getSender().tell(new Failure(e), getSelf());
636 ActorSelection leader = getLeader();
637 if (!isLeaderActive || leader == null) {
638 messageRetrySupport.addMessageToRetry(message, getSender(),
639 "Could not commit transaction " + message.getTransactionId());
641 LOG.debug("{}: Forwarding ReadyLocalTransaction to leader {}", persistenceId(), leader);
642 message.setRemoteVersion(getCurrentBehavior().getLeaderPayloadVersion());
643 leader.forward(message, getContext());
648 private void handleForwardedReadyTransaction(final ForwardedReadyTransaction forwardedReady) {
649 LOG.debug("{}: handleForwardedReadyTransaction for {}", persistenceId(), forwardedReady.getTransactionId());
651 boolean isLeaderActive = isLeaderActive();
652 if (isLeader() && isLeaderActive) {
653 commitCoordinator.handleForwardedReadyTransaction(forwardedReady, getSender(), this);
655 ActorSelection leader = getLeader();
656 if (!isLeaderActive || leader == null) {
657 messageRetrySupport.addMessageToRetry(forwardedReady, getSender(),
658 "Could not commit transaction " + forwardedReady.getTransactionId());
660 LOG.debug("{}: Forwarding ForwardedReadyTransaction to leader {}", persistenceId(), leader);
662 ReadyLocalTransaction readyLocal = new ReadyLocalTransaction(forwardedReady.getTransactionId(),
663 forwardedReady.getTransaction().getSnapshot(), forwardedReady.isDoImmediateCommit());
664 readyLocal.setRemoteVersion(getCurrentBehavior().getLeaderPayloadVersion());
665 leader.forward(readyLocal, getContext());
670 private void handleAbortTransaction(final AbortTransaction abort) {
671 doAbortTransaction(abort.getTransactionId(), getSender());
674 void doAbortTransaction(final Identifier transactionID, final ActorRef sender) {
675 commitCoordinator.handleAbort(transactionID, sender, this);
678 private void handleCreateTransaction(final Object message) {
680 createTransaction(CreateTransaction.fromSerializable(message));
681 } else if (getLeader() != null) {
682 getLeader().forward(message, getContext());
684 getSender().tell(new Failure(new NoShardLeaderException(
685 "Could not create a shard transaction", persistenceId())), getSelf());
689 private void closeTransactionChain(final CloseTransactionChain closeTransactionChain) {
690 final LocalHistoryIdentifier id = closeTransactionChain.getIdentifier();
691 store.closeTransactionChain(id, null);
692 store.purgeTransactionChain(id, null);
695 @SuppressWarnings("checkstyle:IllegalCatch")
696 private void createTransaction(final CreateTransaction createTransaction) {
698 if (TransactionType.fromInt(createTransaction.getTransactionType()) != TransactionType.READ_ONLY
699 && failIfIsolatedLeader(getSender())) {
703 ActorRef transactionActor = createTransaction(createTransaction.getTransactionType(),
704 createTransaction.getTransactionId());
706 getSender().tell(new CreateTransactionReply(Serialization.serializedActorPath(transactionActor),
707 createTransaction.getTransactionId(), createTransaction.getVersion()).toSerializable(), getSelf());
708 } catch (Exception e) {
709 getSender().tell(new Failure(e), getSelf());
713 private ActorRef createTransaction(final int transactionType, final TransactionIdentifier transactionId) {
714 LOG.debug("{}: Creating transaction : {} ", persistenceId(), transactionId);
715 return transactionActorFactory.newShardTransaction(TransactionType.fromInt(transactionType),
719 private void updateSchemaContext(final UpdateSchemaContext message) {
720 updateSchemaContext(message.getSchemaContext());
724 void updateSchemaContext(final SchemaContext schemaContext) {
725 store.updateSchemaContext(schemaContext);
728 private boolean isMetricsCaptureEnabled() {
729 CommonConfig config = new CommonConfig(getContext().system().settings().config());
730 return config.isMetricCaptureEnabled();
735 public RaftActorSnapshotCohort getRaftActorSnapshotCohort() {
736 return snapshotCohort;
741 protected RaftActorRecoveryCohort getRaftActorRecoveryCohort() {
742 return new ShardRecoveryCoordinator(store,
743 restoreFromSnapshot != null ? restoreFromSnapshot.getSnapshot() : null, persistenceId(), LOG);
747 protected void onRecoveryComplete() {
748 restoreFromSnapshot = null;
750 //notify shard manager
751 getContext().parent().tell(new ActorInitialized(), getSelf());
753 // Being paranoid here - this method should only be called once but just in case...
754 if (txCommitTimeoutCheckSchedule == null) {
755 // Schedule a message to be periodically sent to check if the current in-progress
756 // transaction should be expired and aborted.
757 FiniteDuration period = Duration.create(transactionCommitTimeout / 3, TimeUnit.MILLISECONDS);
758 txCommitTimeoutCheckSchedule = getContext().system().scheduler().schedule(
759 period, period, getSelf(),
760 TX_COMMIT_TIMEOUT_CHECK_MESSAGE, getContext().dispatcher(), ActorRef.noSender());
765 protected void applyState(final ActorRef clientActor, final Identifier identifier, final Object data) {
766 if (data instanceof Payload) {
768 store.applyReplicatedPayload(identifier, (Payload)data);
769 } catch (DataValidationFailedException | IOException e) {
770 LOG.error("{}: Error applying replica {}", persistenceId(), identifier, e);
773 LOG.error("{}: Unknown state for {} received {}", persistenceId(), identifier, data);
778 protected void onStateChanged() {
779 boolean isLeader = isLeader();
780 boolean hasLeader = hasLeader();
781 changeSupport.onLeadershipChange(isLeader, hasLeader);
782 treeChangeSupport.onLeadershipChange(isLeader, hasLeader);
784 // If this actor is no longer the leader close all the transaction chains
786 if (LOG.isDebugEnabled()) {
788 "{}: onStateChanged: Closing all transaction chains because shard {} is no longer the leader",
789 persistenceId(), getId());
793 store.purgeLeaderState();
796 if (hasLeader && !isIsolatedLeader()) {
797 messageRetrySupport.retryMessages();
802 protected void onLeaderChanged(final String oldLeader, final String newLeader) {
803 shardMBean.incrementLeadershipChangeCount();
807 if (!knownFrontends.isEmpty()) {
808 LOG.debug("{}: removing frontend state for {}", persistenceId(), knownFrontends.keySet());
809 knownFrontends = ImmutableMap.of();
813 // No leader anywhere, nothing else to do
817 // Another leader was elected. If we were the previous leader and had pending transactions, convert
818 // them to transaction messages and send to the new leader.
819 ActorSelection leader = getLeader();
820 if (leader != null) {
821 Collection<?> messagesToForward = convertPendingTransactionsToMessages();
823 if (!messagesToForward.isEmpty()) {
824 LOG.debug("{}: Forwarding {} pending transaction messages to leader {}", persistenceId(),
825 messagesToForward.size(), leader);
827 for (Object message : messagesToForward) {
828 leader.tell(message, self());
832 commitCoordinator.abortPendingTransactions("The transacton was aborted due to inflight leadership "
833 + "change and the leader address isn't available.", this);
836 // We have become the leader, we need to reconstruct frontend state
837 knownFrontends = Verify.verifyNotNull(frontendMetadata.toLeaderState(this));
838 LOG.debug("{}: became leader with frontend state for {}", persistenceId(), knownFrontends.keySet());
841 if (!isIsolatedLeader()) {
842 messageRetrySupport.retryMessages();
847 * Clears all pending transactions and converts them to messages to be forwarded to a new leader.
849 * @return the converted messages
851 public Collection<?> convertPendingTransactionsToMessages() {
852 return commitCoordinator.convertPendingTransactionsToMessages(
853 datastoreContext.getShardBatchedModificationCount());
857 protected void pauseLeader(final Runnable operation) {
858 LOG.debug("{}: In pauseLeader, operation: {}", persistenceId(), operation);
861 // Tell-based protocol can replay transaction state, so it is safe to blow it up when we are paused.
862 knownFrontends.values().forEach(LeaderFrontendState::retire);
863 knownFrontends = ImmutableMap.of();
865 store.setRunOnPendingTransactionsComplete(operation);
869 protected void unpauseLeader() {
870 LOG.debug("{}: In unpauseLeader", persistenceId());
873 store.setRunOnPendingTransactionsComplete(null);
875 // Restore tell-based protocol state as if we were becoming the leader
876 knownFrontends = Verify.verifyNotNull(frontendMetadata.toLeaderState(this));
880 protected OnDemandRaftState.AbstractBuilder<?> newOnDemandRaftStateBuilder() {
881 return OnDemandShardState.newBuilder().treeChangeListenerActors(treeChangeSupport.getListenerActors())
882 .dataChangeListenerActors(changeSupport.getListenerActors())
883 .commitCohortActors(store.getCohortActors());
887 public String persistenceId() {
892 ShardCommitCoordinator getCommitCoordinator() {
893 return commitCoordinator;
896 public DatastoreContext getDatastoreContext() {
897 return datastoreContext;
901 public ShardDataTree getDataStore() {
906 ShardStats getShardMBean() {
910 public static Builder builder() {
911 return new Builder();
914 public abstract static class AbstractBuilder<T extends AbstractBuilder<T, S>, S extends Shard> {
915 private final Class<S> shardClass;
916 private ShardIdentifier id;
917 private Map<String, String> peerAddresses = Collections.emptyMap();
918 private DatastoreContext datastoreContext;
919 private SchemaContextProvider schemaContextProvider;
920 private DatastoreSnapshot.ShardSnapshot restoreFromSnapshot;
921 private TipProducingDataTree dataTree;
922 private volatile boolean sealed;
924 protected AbstractBuilder(final Class<S> shardClass) {
925 this.shardClass = shardClass;
928 protected void checkSealed() {
929 Preconditions.checkState(!sealed, "Builder isalready sealed - further modifications are not allowed");
932 @SuppressWarnings("unchecked")
937 public T id(final ShardIdentifier newId) {
943 public T peerAddresses(final Map<String, String> newPeerAddresses) {
945 this.peerAddresses = newPeerAddresses;
949 public T datastoreContext(final DatastoreContext newDatastoreContext) {
951 this.datastoreContext = newDatastoreContext;
955 public T schemaContextProvider(final SchemaContextProvider schemaContextProvider) {
957 this.schemaContextProvider = Preconditions.checkNotNull(schemaContextProvider);
961 public T restoreFromSnapshot(final DatastoreSnapshot.ShardSnapshot newRestoreFromSnapshot) {
963 this.restoreFromSnapshot = newRestoreFromSnapshot;
967 public T dataTree(final TipProducingDataTree newDataTree) {
969 this.dataTree = newDataTree;
973 public ShardIdentifier getId() {
977 public Map<String, String> getPeerAddresses() {
978 return peerAddresses;
981 public DatastoreContext getDatastoreContext() {
982 return datastoreContext;
985 public SchemaContext getSchemaContext() {
986 return Verify.verifyNotNull(schemaContextProvider.getSchemaContext());
989 public DatastoreSnapshot.ShardSnapshot getRestoreFromSnapshot() {
990 return restoreFromSnapshot;
993 public TipProducingDataTree getDataTree() {
997 public TreeType getTreeType() {
998 switch (datastoreContext.getLogicalStoreType()) {
1000 return TreeType.CONFIGURATION;
1002 return TreeType.OPERATIONAL;
1004 throw new IllegalStateException("Unhandled logical store type "
1005 + datastoreContext.getLogicalStoreType());
1009 protected void verify() {
1010 Preconditions.checkNotNull(id, "id should not be null");
1011 Preconditions.checkNotNull(peerAddresses, "peerAddresses should not be null");
1012 Preconditions.checkNotNull(datastoreContext, "dataStoreContext should not be null");
1013 Preconditions.checkNotNull(schemaContextProvider, "schemaContextProvider should not be null");
1016 public Props props() {
1019 return Props.create(shardClass, this);
1023 public static class Builder extends AbstractBuilder<Builder, Shard> {
1030 return Ticker.systemTicker();
1033 void scheduleNextPendingTransaction() {
1034 self().tell(RESUME_NEXT_PENDING_TRANSACTION, ActorRef.noSender());