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.OutOfSequenceEnvelopeException;
40 import org.opendaylight.controller.cluster.access.commands.TransactionRequest;
41 import org.opendaylight.controller.cluster.access.concepts.ClientIdentifier;
42 import org.opendaylight.controller.cluster.access.concepts.FrontendIdentifier;
43 import org.opendaylight.controller.cluster.access.concepts.LocalHistoryIdentifier;
44 import org.opendaylight.controller.cluster.access.concepts.Request;
45 import org.opendaylight.controller.cluster.access.concepts.RequestEnvelope;
46 import org.opendaylight.controller.cluster.access.concepts.RequestException;
47 import org.opendaylight.controller.cluster.access.concepts.RequestSuccess;
48 import org.opendaylight.controller.cluster.access.concepts.RetiredGenerationException;
49 import org.opendaylight.controller.cluster.access.concepts.RuntimeRequestException;
50 import org.opendaylight.controller.cluster.access.concepts.TransactionIdentifier;
51 import org.opendaylight.controller.cluster.access.concepts.UnsupportedRequestException;
52 import org.opendaylight.controller.cluster.common.actor.CommonConfig;
53 import org.opendaylight.controller.cluster.common.actor.MessageTracker;
54 import org.opendaylight.controller.cluster.common.actor.MessageTracker.Error;
55 import org.opendaylight.controller.cluster.common.actor.MeteringBehavior;
56 import org.opendaylight.controller.cluster.datastore.exceptions.NoShardLeaderException;
57 import org.opendaylight.controller.cluster.datastore.identifiers.ShardIdentifier;
58 import org.opendaylight.controller.cluster.datastore.jmx.mbeans.shard.ShardMBeanFactory;
59 import org.opendaylight.controller.cluster.datastore.jmx.mbeans.shard.ShardStats;
60 import org.opendaylight.controller.cluster.datastore.messages.AbortTransaction;
61 import org.opendaylight.controller.cluster.datastore.messages.ActorInitialized;
62 import org.opendaylight.controller.cluster.datastore.messages.BatchedModifications;
63 import org.opendaylight.controller.cluster.datastore.messages.CanCommitTransaction;
64 import org.opendaylight.controller.cluster.datastore.messages.CloseTransactionChain;
65 import org.opendaylight.controller.cluster.datastore.messages.CommitTransaction;
66 import org.opendaylight.controller.cluster.datastore.messages.CreateTransaction;
67 import org.opendaylight.controller.cluster.datastore.messages.CreateTransactionReply;
68 import org.opendaylight.controller.cluster.datastore.messages.ForwardedReadyTransaction;
69 import org.opendaylight.controller.cluster.datastore.messages.GetShardDataTree;
70 import org.opendaylight.controller.cluster.datastore.messages.MakeLeaderLocal;
71 import org.opendaylight.controller.cluster.datastore.messages.OnDemandShardState;
72 import org.opendaylight.controller.cluster.datastore.messages.PeerAddressResolved;
73 import org.opendaylight.controller.cluster.datastore.messages.PersistAbortTransactionPayload;
74 import org.opendaylight.controller.cluster.datastore.messages.ReadyLocalTransaction;
75 import org.opendaylight.controller.cluster.datastore.messages.RegisterChangeListener;
76 import org.opendaylight.controller.cluster.datastore.messages.RegisterDataTreeChangeListener;
77 import org.opendaylight.controller.cluster.datastore.messages.ShardLeaderStateChanged;
78 import org.opendaylight.controller.cluster.datastore.messages.UpdateSchemaContext;
79 import org.opendaylight.controller.cluster.datastore.persisted.AbortTransactionPayload;
80 import org.opendaylight.controller.cluster.datastore.persisted.DatastoreSnapshot;
81 import org.opendaylight.controller.cluster.datastore.persisted.DatastoreSnapshot.ShardSnapshot;
82 import org.opendaylight.controller.cluster.datastore.utils.Dispatchers;
83 import org.opendaylight.controller.cluster.notifications.LeaderStateChanged;
84 import org.opendaylight.controller.cluster.notifications.RegisterRoleChangeListener;
85 import org.opendaylight.controller.cluster.notifications.RoleChangeNotifier;
86 import org.opendaylight.controller.cluster.raft.LeadershipTransferFailedException;
87 import org.opendaylight.controller.cluster.raft.RaftActor;
88 import org.opendaylight.controller.cluster.raft.RaftActorRecoveryCohort;
89 import org.opendaylight.controller.cluster.raft.RaftActorSnapshotCohort;
90 import org.opendaylight.controller.cluster.raft.RaftState;
91 import org.opendaylight.controller.cluster.raft.base.messages.FollowerInitialSyncUpStatus;
92 import org.opendaylight.controller.cluster.raft.client.messages.OnDemandRaftState;
93 import org.opendaylight.controller.cluster.raft.messages.AppendEntriesReply;
94 import org.opendaylight.controller.cluster.raft.messages.RequestLeadership;
95 import org.opendaylight.controller.cluster.raft.messages.ServerRemoved;
96 import org.opendaylight.controller.cluster.raft.protobuff.client.messages.Payload;
97 import org.opendaylight.yangtools.concepts.Identifier;
98 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataValidationFailedException;
99 import org.opendaylight.yangtools.yang.data.api.schema.tree.TipProducingDataTree;
100 import org.opendaylight.yangtools.yang.data.api.schema.tree.TreeType;
101 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
102 import org.opendaylight.yangtools.yang.model.api.SchemaContextProvider;
103 import scala.concurrent.duration.Duration;
104 import scala.concurrent.duration.FiniteDuration;
107 * A Shard represents a portion of the logical data tree.
110 * Our Shard uses InMemoryDataTree as it's internal representation and delegates all requests it
112 public class Shard extends RaftActor {
115 static final Object TX_COMMIT_TIMEOUT_CHECK_MESSAGE = new Object() {
117 public String toString() {
118 return "txCommitTimeoutCheck";
123 static final Object GET_SHARD_MBEAN_MESSAGE = new Object() {
125 public String toString() {
126 return "getShardMBeanMessage";
130 static final Object RESUME_NEXT_PENDING_TRANSACTION = new Object() {
132 public String toString() {
133 return "resumeNextPendingTransaction";
137 // FIXME: shard names should be encapsulated in their own class and this should be exposed as a constant.
138 public static final String DEFAULT_NAME = "default";
140 private static final Collection<ABIVersion> SUPPORTED_ABIVERSIONS;
143 final ABIVersion[] values = ABIVersion.values();
144 final ABIVersion[] real = Arrays.copyOfRange(values, 1, values.length - 1);
145 SUPPORTED_ABIVERSIONS = ImmutableList.copyOf(real).reverse();
148 // FIXME: make this a dynamic property based on mailbox size and maximum number of clients
149 private static final int CLIENT_MAX_MESSAGES = 1000;
151 // The state of this Shard
152 private final ShardDataTree store;
154 /// The name of this shard
155 private final String name;
157 private final ShardStats shardMBean;
159 private DatastoreContext datastoreContext;
161 private final ShardCommitCoordinator commitCoordinator;
163 private long transactionCommitTimeout;
165 private Cancellable txCommitTimeoutCheckSchedule;
167 private final Optional<ActorRef> roleChangeNotifier;
169 private final MessageTracker appendEntriesReplyTracker;
171 private final ShardTransactionActorFactory transactionActorFactory;
173 private final ShardSnapshotCohort snapshotCohort;
175 private final DataTreeChangeListenerSupport treeChangeSupport = new DataTreeChangeListenerSupport(this);
176 private final DataChangeListenerSupport changeSupport = new DataChangeListenerSupport(this);
179 private ShardSnapshot restoreFromSnapshot;
181 private final ShardTransactionMessageRetrySupport messageRetrySupport;
183 private final FrontendMetadata frontendMetadata;
184 private Map<FrontendIdentifier, LeaderFrontendState> knownFrontends = ImmutableMap.of();
185 private boolean paused;
187 protected Shard(final AbstractBuilder<?, ?> builder) {
188 super(builder.getId().toString(), builder.getPeerAddresses(),
189 Optional.of(builder.getDatastoreContext().getShardRaftConfig()), DataStoreVersions.CURRENT_VERSION);
191 this.name = builder.getId().toString();
192 this.datastoreContext = builder.getDatastoreContext();
193 this.restoreFromSnapshot = builder.getRestoreFromSnapshot();
194 this.frontendMetadata = new FrontendMetadata(name);
196 setPersistence(datastoreContext.isPersistent());
198 LOG.info("Shard created : {}, persistent : {}", name, datastoreContext.isPersistent());
200 ShardDataTreeChangeListenerPublisherActorProxy treeChangeListenerPublisher =
201 new ShardDataTreeChangeListenerPublisherActorProxy(getContext(), name + "-DTCL-publisher", name);
202 ShardDataChangeListenerPublisherActorProxy dataChangeListenerPublisher =
203 new ShardDataChangeListenerPublisherActorProxy(getContext(), name + "-DCL-publisher", name);
204 if (builder.getDataTree() != null) {
205 store = new ShardDataTree(this, builder.getSchemaContext(), builder.getDataTree(),
206 treeChangeListenerPublisher, dataChangeListenerPublisher, name, frontendMetadata);
208 store = new ShardDataTree(this, builder.getSchemaContext(), builder.getTreeType(),
209 builder.getDatastoreContext().getStoreRoot(), treeChangeListenerPublisher,
210 dataChangeListenerPublisher, name, frontendMetadata);
213 shardMBean = ShardMBeanFactory.getShardStatsMBean(name, datastoreContext.getDataStoreMXBeanType(), this);
215 if (isMetricsCaptureEnabled()) {
216 getContext().become(new MeteringBehavior(this));
219 commitCoordinator = new ShardCommitCoordinator(store, LOG, this.name);
221 setTransactionCommitTimeout();
223 // create a notifier actor for each cluster member
224 roleChangeNotifier = createRoleChangeNotifier(name);
226 appendEntriesReplyTracker = new MessageTracker(AppendEntriesReply.class,
227 getRaftActorContext().getConfigParams().getIsolatedCheckIntervalInMillis());
229 transactionActorFactory = new ShardTransactionActorFactory(store, datastoreContext,
230 new Dispatchers(context().system().dispatchers()).getDispatcherPath(Dispatchers.DispatcherType.Transaction),
231 self(), getContext(), shardMBean, builder.getId().getShardName());
233 snapshotCohort = ShardSnapshotCohort.create(getContext(), builder.getId().getMemberName(), store, LOG,
236 messageRetrySupport = new ShardTransactionMessageRetrySupport(this);
239 private void setTransactionCommitTimeout() {
240 transactionCommitTimeout = TimeUnit.MILLISECONDS.convert(
241 datastoreContext.getShardTransactionCommitTimeoutInSeconds(), TimeUnit.SECONDS) / 2;
244 private Optional<ActorRef> createRoleChangeNotifier(final String shardId) {
245 ActorRef shardRoleChangeNotifier = this.getContext().actorOf(
246 RoleChangeNotifier.getProps(shardId), shardId + "-notifier");
247 return Optional.of(shardRoleChangeNotifier);
251 public void postStop() {
252 LOG.info("Stopping Shard {}", persistenceId());
256 messageRetrySupport.close();
258 if (txCommitTimeoutCheckSchedule != null) {
259 txCommitTimeoutCheckSchedule.cancel();
262 commitCoordinator.abortPendingTransactions("Transaction aborted due to shutdown.", this);
264 shardMBean.unregisterMBean();
268 protected void handleRecover(final Object message) {
269 LOG.debug("{}: onReceiveRecover: Received message {} from {}", persistenceId(), message.getClass(),
272 super.handleRecover(message);
273 if (LOG.isTraceEnabled()) {
274 appendEntriesReplyTracker.begin();
278 @SuppressWarnings("checkstyle:IllegalCatch")
280 protected void handleNonRaftCommand(final Object message) {
281 try (MessageTracker.Context context = appendEntriesReplyTracker.received(message)) {
282 final Optional<Error> maybeError = context.error();
283 if (maybeError.isPresent()) {
284 LOG.trace("{} : AppendEntriesReply failed to arrive at the expected interval {}", persistenceId(),
288 store.resetTransactionBatch();
290 if (message instanceof RequestEnvelope) {
291 final long now = ticker().read();
292 final RequestEnvelope envelope = (RequestEnvelope)message;
295 final RequestSuccess<?, ?> success = handleRequest(envelope, now);
296 if (success != null) {
297 envelope.sendSuccess(success, ticker().read() - now);
299 } catch (RequestException e) {
300 LOG.debug("{}: request {} failed", persistenceId(), envelope, e);
301 envelope.sendFailure(e, ticker().read() - now);
302 } catch (Exception e) {
303 LOG.debug("{}: request {} caused failure", persistenceId(), envelope, e);
304 envelope.sendFailure(new RuntimeRequestException("Request failed to process", e),
305 ticker().read() - now);
307 } else if (message instanceof ConnectClientRequest) {
308 handleConnectClient((ConnectClientRequest)message);
309 } else if (CreateTransaction.isSerializedType(message)) {
310 handleCreateTransaction(message);
311 } else if (message instanceof BatchedModifications) {
312 handleBatchedModifications((BatchedModifications)message);
313 } else if (message instanceof ForwardedReadyTransaction) {
314 handleForwardedReadyTransaction((ForwardedReadyTransaction) message);
315 } else if (message instanceof ReadyLocalTransaction) {
316 handleReadyLocalTransaction((ReadyLocalTransaction)message);
317 } else if (CanCommitTransaction.isSerializedType(message)) {
318 handleCanCommitTransaction(CanCommitTransaction.fromSerializable(message));
319 } else if (CommitTransaction.isSerializedType(message)) {
320 handleCommitTransaction(CommitTransaction.fromSerializable(message));
321 } else if (AbortTransaction.isSerializedType(message)) {
322 handleAbortTransaction(AbortTransaction.fromSerializable(message));
323 } else if (CloseTransactionChain.isSerializedType(message)) {
324 closeTransactionChain(CloseTransactionChain.fromSerializable(message));
325 } else if (message instanceof RegisterChangeListener) {
326 changeSupport.onMessage((RegisterChangeListener) message, isLeader(), hasLeader());
327 } else if (message instanceof RegisterDataTreeChangeListener) {
328 treeChangeSupport.onMessage((RegisterDataTreeChangeListener) message, isLeader(), hasLeader());
329 } else if (message instanceof UpdateSchemaContext) {
330 updateSchemaContext((UpdateSchemaContext) message);
331 } else if (message instanceof PeerAddressResolved) {
332 PeerAddressResolved resolved = (PeerAddressResolved) message;
333 setPeerAddress(resolved.getPeerId(), resolved.getPeerAddress());
334 } else if (TX_COMMIT_TIMEOUT_CHECK_MESSAGE.equals(message)) {
335 commitTimeoutCheck();
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 commitTimeoutCheck() {
368 store.checkForExpiredTransactions(transactionCommitTimeout, this::updateAccess);
369 commitCoordinator.checkForExpiredTransactions(transactionCommitTimeout, this);
372 private Optional<Long> updateAccess(final SimpleShardDataTreeCohort cohort) {
373 final FrontendIdentifier frontend = cohort.getIdentifier().getHistoryId().getClientId().getFrontendId();
374 // If this frontend has freshly connected, give it some time to catch up before killing its transactions.
375 final LeaderFrontendState state = knownFrontends.get(frontend);
376 return state == null ? Optional.absent() : Optional.of(state.getLastConnectTicks());
379 private void onMakeLeaderLocal() {
380 LOG.debug("{}: onMakeLeaderLocal received", persistenceId());
382 getSender().tell(new Status.Success(null), getSelf());
386 final ActorSelection leader = getLeader();
388 if (leader == null) {
389 // Leader is not present. The cluster is most likely trying to
390 // elect a leader and we should let that run its normal course
392 // TODO we can wait for the election to complete and retry the
393 // request. We can also let the caller retry by sending a flag
394 // in the response indicating the request is "reTryable".
395 getSender().tell(new Failure(
396 new LeadershipTransferFailedException("We cannot initiate leadership transfer to local node. "
397 + "Currently there is no leader for " + persistenceId())),
402 leader.tell(new RequestLeadership(getId(), getSender()), getSelf());
405 // Acquire our frontend tracking handle and verify generation matches
407 private LeaderFrontendState findFrontend(final ClientIdentifier clientId) throws RequestException {
408 final LeaderFrontendState existing = knownFrontends.get(clientId.getFrontendId());
409 if (existing != null) {
410 final int cmp = Long.compareUnsigned(existing.getIdentifier().getGeneration(), clientId.getGeneration());
416 LOG.debug("{}: rejecting request from outdated client {}", persistenceId(), clientId);
417 throw new RetiredGenerationException(existing.getIdentifier().getGeneration());
420 LOG.info("{}: retiring state {}, outdated by request from client {}", persistenceId(), existing, clientId);
422 knownFrontends.remove(clientId.getFrontendId());
424 LOG.debug("{}: client {} is not yet known", persistenceId(), clientId);
430 private LeaderFrontendState getFrontend(final ClientIdentifier clientId) throws RequestException {
431 final LeaderFrontendState ret = findFrontend(clientId);
436 // TODO: a dedicated exception would be better, but this is technically true, too
437 throw new OutOfSequenceEnvelopeException(0);
440 private static @Nonnull ABIVersion selectVersion(final ConnectClientRequest message) {
441 final Range<ABIVersion> clientRange = Range.closed(message.getMinVersion(), message.getMaxVersion());
442 for (ABIVersion v : SUPPORTED_ABIVERSIONS) {
443 if (clientRange.contains(v)) {
448 throw new IllegalArgumentException(String.format(
449 "No common version between backend versions %s and client versions %s", SUPPORTED_ABIVERSIONS,
453 @SuppressWarnings("checkstyle:IllegalCatch")
454 private void handleConnectClient(final ConnectClientRequest message) {
456 final ClientIdentifier clientId = message.getTarget();
457 final LeaderFrontendState existing = findFrontend(clientId);
458 if (existing != null) {
462 if (!isLeader() || !isLeaderActive()) {
463 LOG.info("{}: not currently leader, rejecting request {}. isLeader: {}, isLeaderActive: {},"
464 + "isLeadershipTransferInProgress: {}.",
465 persistenceId(), message, isLeader(), isLeaderActive(), isLeadershipTransferInProgress());
466 throw new NotLeaderException(getSelf());
469 final ABIVersion selectedVersion = selectVersion(message);
470 final LeaderFrontendState frontend;
471 if (existing == null) {
472 frontend = new LeaderFrontendState(persistenceId(), clientId, store);
473 knownFrontends.put(clientId.getFrontendId(), frontend);
474 LOG.debug("{}: created state {} for client {}", persistenceId(), frontend, clientId);
479 frontend.reconnect();
480 message.getReplyTo().tell(new ConnectClientSuccess(message.getTarget(), message.getSequence(), getSelf(),
481 ImmutableList.of(), store.getDataTree(), CLIENT_MAX_MESSAGES).toVersion(selectedVersion),
482 ActorRef.noSender());
483 } catch (RequestException | RuntimeException e) {
484 message.getReplyTo().tell(new Failure(e), ActorRef.noSender());
488 private @Nullable RequestSuccess<?, ?> handleRequest(final RequestEnvelope envelope, final long now)
489 throws RequestException {
490 // We are not the leader, hence we want to fail-fast.
491 if (!isLeader() || paused || !isLeaderActive()) {
492 LOG.debug("{}: not currently active leader, rejecting request {}. isLeader: {}, isLeaderActive: {},"
493 + "isLeadershipTransferInProgress: {}, paused: {}",
494 persistenceId(), envelope, isLeader(), isLeaderActive(), isLeadershipTransferInProgress(), paused);
495 throw new NotLeaderException(getSelf());
498 final Request<?, ?> request = envelope.getMessage();
499 if (request instanceof TransactionRequest) {
500 final TransactionRequest<?> txReq = (TransactionRequest<?>)request;
501 final ClientIdentifier clientId = txReq.getTarget().getHistoryId().getClientId();
502 return getFrontend(clientId).handleTransactionRequest(txReq, envelope, now);
503 } else if (request instanceof LocalHistoryRequest) {
504 final LocalHistoryRequest<?> lhReq = (LocalHistoryRequest<?>)request;
505 final ClientIdentifier clientId = lhReq.getTarget().getClientId();
506 return getFrontend(clientId).handleLocalHistoryRequest(lhReq, envelope, now);
508 LOG.warn("{}: rejecting unsupported request {}", persistenceId(), request);
509 throw new UnsupportedRequestException(request);
513 private boolean hasLeader() {
514 return getLeaderId() != null;
517 public int getPendingTxCommitQueueSize() {
518 return store.getQueueSize();
521 public int getCohortCacheSize() {
522 return commitCoordinator.getCohortCacheSize();
526 protected Optional<ActorRef> getRoleChangeNotifier() {
527 return roleChangeNotifier;
531 protected LeaderStateChanged newLeaderStateChanged(final String memberId, final String leaderId,
532 final short leaderPayloadVersion) {
533 return isLeader() ? new ShardLeaderStateChanged(memberId, leaderId, store.getDataTree(), leaderPayloadVersion)
534 : new ShardLeaderStateChanged(memberId, leaderId, leaderPayloadVersion);
537 protected void onDatastoreContext(final DatastoreContext context) {
538 datastoreContext = context;
540 setTransactionCommitTimeout();
542 setPersistence(datastoreContext.isPersistent());
544 updateConfigParams(datastoreContext.getShardRaftConfig());
547 // applyState() will be invoked once consensus is reached on the payload
548 void persistPayload(final Identifier id, final Payload payload, final boolean batchHint) {
549 boolean canSkipPayload = !hasFollowers() && !persistence().isRecoveryApplicable();
550 if (canSkipPayload) {
551 applyState(self(), id, payload);
553 // We are faking the sender
554 persistData(self(), id, payload, batchHint);
558 private void handleCommitTransaction(final CommitTransaction commit) {
560 commitCoordinator.handleCommit(commit.getTransactionId(), getSender(), this);
562 ActorSelection leader = getLeader();
563 if (leader == null) {
564 messageRetrySupport.addMessageToRetry(commit, getSender(),
565 "Could not commit transaction " + commit.getTransactionId());
567 LOG.debug("{}: Forwarding CommitTransaction to leader {}", persistenceId(), leader);
568 leader.forward(commit, getContext());
573 private void handleCanCommitTransaction(final CanCommitTransaction canCommit) {
574 LOG.debug("{}: Can committing transaction {}", persistenceId(), canCommit.getTransactionId());
577 commitCoordinator.handleCanCommit(canCommit.getTransactionId(), getSender(), this);
579 ActorSelection leader = getLeader();
580 if (leader == null) {
581 messageRetrySupport.addMessageToRetry(canCommit, getSender(),
582 "Could not canCommit transaction " + canCommit.getTransactionId());
584 LOG.debug("{}: Forwarding CanCommitTransaction to leader {}", persistenceId(), leader);
585 leader.forward(canCommit, getContext());
590 @SuppressWarnings("checkstyle:IllegalCatch")
591 protected void handleBatchedModificationsLocal(final BatchedModifications batched, final ActorRef sender) {
593 commitCoordinator.handleBatchedModifications(batched, sender, this);
594 } catch (Exception e) {
595 LOG.error("{}: Error handling BatchedModifications for Tx {}", persistenceId(),
596 batched.getTransactionId(), e);
597 sender.tell(new Failure(e), getSelf());
601 private void handleBatchedModifications(final BatchedModifications batched) {
602 // This message is sent to prepare the modifications transaction directly on the Shard as an
603 // optimization to avoid the extra overhead of a separate ShardTransaction actor. On the last
604 // BatchedModifications message, the caller sets the ready flag in the message indicating
605 // modifications are complete. The reply contains the cohort actor path (this actor) for the caller
606 // to initiate the 3-phase commit. This also avoids the overhead of sending an additional
607 // ReadyTransaction message.
609 // If we're not the leader then forward to the leader. This is a safety measure - we shouldn't
610 // normally get here if we're not the leader as the front-end (TransactionProxy) should determine
611 // the primary/leader shard. However with timing and caching on the front-end, there's a small
612 // window where it could have a stale leader during leadership transitions.
614 boolean isLeaderActive = isLeaderActive();
615 if (isLeader() && isLeaderActive) {
616 handleBatchedModificationsLocal(batched, getSender());
618 ActorSelection leader = getLeader();
619 if (!isLeaderActive || leader == null) {
620 messageRetrySupport.addMessageToRetry(batched, getSender(),
621 "Could not commit transaction " + batched.getTransactionId());
623 // If this is not the first batch and leadership changed in between batched messages,
624 // we need to reconstruct previous BatchedModifications from the transaction
625 // DataTreeModification, honoring the max batched modification count, and forward all the
626 // previous BatchedModifications to the new leader.
627 Collection<BatchedModifications> newModifications = commitCoordinator
628 .createForwardedBatchedModifications(batched,
629 datastoreContext.getShardBatchedModificationCount());
631 LOG.debug("{}: Forwarding {} BatchedModifications to leader {}", persistenceId(),
632 newModifications.size(), leader);
634 for (BatchedModifications bm : newModifications) {
635 leader.forward(bm, getContext());
641 private boolean failIfIsolatedLeader(final ActorRef sender) {
642 if (isIsolatedLeader()) {
643 sender.tell(new Failure(new NoShardLeaderException(String.format(
644 "Shard %s was the leader but has lost contact with all of its followers. Either all"
645 + " other follower nodes are down or this node is isolated by a network partition.",
646 persistenceId()))), getSelf());
653 protected boolean isIsolatedLeader() {
654 return getRaftState() == RaftState.IsolatedLeader;
657 @SuppressWarnings("checkstyle:IllegalCatch")
658 private void handleReadyLocalTransaction(final ReadyLocalTransaction message) {
659 LOG.debug("{}: handleReadyLocalTransaction for {}", persistenceId(), message.getTransactionId());
661 boolean isLeaderActive = isLeaderActive();
662 if (isLeader() && isLeaderActive) {
664 commitCoordinator.handleReadyLocalTransaction(message, getSender(), this);
665 } catch (Exception e) {
666 LOG.error("{}: Error handling ReadyLocalTransaction for Tx {}", persistenceId(),
667 message.getTransactionId(), e);
668 getSender().tell(new Failure(e), getSelf());
671 ActorSelection leader = getLeader();
672 if (!isLeaderActive || leader == null) {
673 messageRetrySupport.addMessageToRetry(message, getSender(),
674 "Could not commit transaction " + message.getTransactionId());
676 LOG.debug("{}: Forwarding ReadyLocalTransaction to leader {}", persistenceId(), leader);
677 message.setRemoteVersion(getCurrentBehavior().getLeaderPayloadVersion());
678 leader.forward(message, getContext());
683 private void handleForwardedReadyTransaction(final ForwardedReadyTransaction forwardedReady) {
684 LOG.debug("{}: handleForwardedReadyTransaction for {}", persistenceId(), forwardedReady.getTransactionId());
686 boolean isLeaderActive = isLeaderActive();
687 if (isLeader() && isLeaderActive) {
688 commitCoordinator.handleForwardedReadyTransaction(forwardedReady, getSender(), this);
690 ActorSelection leader = getLeader();
691 if (!isLeaderActive || leader == null) {
692 messageRetrySupport.addMessageToRetry(forwardedReady, getSender(),
693 "Could not commit transaction " + forwardedReady.getTransactionId());
695 LOG.debug("{}: Forwarding ForwardedReadyTransaction to leader {}", persistenceId(), leader);
697 ReadyLocalTransaction readyLocal = new ReadyLocalTransaction(forwardedReady.getTransactionId(),
698 forwardedReady.getTransaction().getSnapshot(), forwardedReady.isDoImmediateCommit());
699 readyLocal.setRemoteVersion(getCurrentBehavior().getLeaderPayloadVersion());
700 leader.forward(readyLocal, getContext());
705 private void handleAbortTransaction(final AbortTransaction abort) {
706 doAbortTransaction(abort.getTransactionId(), getSender());
709 void doAbortTransaction(final Identifier transactionID, final ActorRef sender) {
710 commitCoordinator.handleAbort(transactionID, sender, this);
713 private void handleCreateTransaction(final Object message) {
715 createTransaction(CreateTransaction.fromSerializable(message));
716 } else if (getLeader() != null) {
717 getLeader().forward(message, getContext());
719 getSender().tell(new Failure(new NoShardLeaderException(
720 "Could not create a shard transaction", persistenceId())), getSelf());
724 private void closeTransactionChain(final CloseTransactionChain closeTransactionChain) {
725 final LocalHistoryIdentifier id = closeTransactionChain.getIdentifier();
726 store.closeTransactionChain(id, null);
727 store.purgeTransactionChain(id, null);
730 @SuppressWarnings("checkstyle:IllegalCatch")
731 private void createTransaction(final CreateTransaction createTransaction) {
733 if (TransactionType.fromInt(createTransaction.getTransactionType()) != TransactionType.READ_ONLY
734 && failIfIsolatedLeader(getSender())) {
738 ActorRef transactionActor = createTransaction(createTransaction.getTransactionType(),
739 createTransaction.getTransactionId());
741 getSender().tell(new CreateTransactionReply(Serialization.serializedActorPath(transactionActor),
742 createTransaction.getTransactionId(), createTransaction.getVersion()).toSerializable(), getSelf());
743 } catch (Exception e) {
744 getSender().tell(new Failure(e), getSelf());
748 private ActorRef createTransaction(final int transactionType, final TransactionIdentifier transactionId) {
749 LOG.debug("{}: Creating transaction : {} ", persistenceId(), transactionId);
750 return transactionActorFactory.newShardTransaction(TransactionType.fromInt(transactionType),
754 private void updateSchemaContext(final UpdateSchemaContext message) {
755 updateSchemaContext(message.getSchemaContext());
759 void updateSchemaContext(final SchemaContext schemaContext) {
760 store.updateSchemaContext(schemaContext);
763 private boolean isMetricsCaptureEnabled() {
764 CommonConfig config = new CommonConfig(getContext().system().settings().config());
765 return config.isMetricCaptureEnabled();
770 public RaftActorSnapshotCohort getRaftActorSnapshotCohort() {
771 return snapshotCohort;
776 protected RaftActorRecoveryCohort getRaftActorRecoveryCohort() {
777 return new ShardRecoveryCoordinator(store,
778 restoreFromSnapshot != null ? restoreFromSnapshot.getSnapshot() : null, persistenceId(), LOG);
782 protected void onRecoveryComplete() {
783 restoreFromSnapshot = null;
785 //notify shard manager
786 getContext().parent().tell(new ActorInitialized(), getSelf());
788 // Being paranoid here - this method should only be called once but just in case...
789 if (txCommitTimeoutCheckSchedule == null) {
790 // Schedule a message to be periodically sent to check if the current in-progress
791 // transaction should be expired and aborted.
792 FiniteDuration period = Duration.create(transactionCommitTimeout / 3, TimeUnit.MILLISECONDS);
793 txCommitTimeoutCheckSchedule = getContext().system().scheduler().schedule(
794 period, period, getSelf(),
795 TX_COMMIT_TIMEOUT_CHECK_MESSAGE, getContext().dispatcher(), ActorRef.noSender());
800 protected void applyState(final ActorRef clientActor, final Identifier identifier, final Object data) {
801 if (data instanceof Payload) {
803 store.applyReplicatedPayload(identifier, (Payload)data);
804 } catch (DataValidationFailedException | IOException e) {
805 LOG.error("{}: Error applying replica {}", persistenceId(), identifier, e);
808 LOG.error("{}: Unknown state for {} received {}", persistenceId(), identifier, data);
813 protected void onStateChanged() {
814 boolean isLeader = isLeader();
815 boolean hasLeader = hasLeader();
816 changeSupport.onLeadershipChange(isLeader, hasLeader);
817 treeChangeSupport.onLeadershipChange(isLeader, hasLeader);
819 // If this actor is no longer the leader close all the transaction chains
821 if (LOG.isDebugEnabled()) {
823 "{}: onStateChanged: Closing all transaction chains because shard {} is no longer the leader",
824 persistenceId(), getId());
828 store.purgeLeaderState();
831 if (hasLeader && !isIsolatedLeader()) {
832 messageRetrySupport.retryMessages();
837 protected void onLeaderChanged(final String oldLeader, final String newLeader) {
838 shardMBean.incrementLeadershipChangeCount();
842 if (!knownFrontends.isEmpty()) {
843 LOG.debug("{}: removing frontend state for {}", persistenceId(), knownFrontends.keySet());
844 knownFrontends = ImmutableMap.of();
848 // No leader anywhere, nothing else to do
852 // Another leader was elected. If we were the previous leader and had pending transactions, convert
853 // them to transaction messages and send to the new leader.
854 ActorSelection leader = getLeader();
855 if (leader != null) {
856 Collection<?> messagesToForward = convertPendingTransactionsToMessages();
858 if (!messagesToForward.isEmpty()) {
859 LOG.debug("{}: Forwarding {} pending transaction messages to leader {}", persistenceId(),
860 messagesToForward.size(), leader);
862 for (Object message : messagesToForward) {
863 leader.tell(message, self());
867 commitCoordinator.abortPendingTransactions("The transacton was aborted due to inflight leadership "
868 + "change and the leader address isn't available.", this);
871 // We have become the leader, we need to reconstruct frontend state
872 knownFrontends = Verify.verifyNotNull(frontendMetadata.toLeaderState(this));
873 LOG.debug("{}: became leader with frontend state for {}", persistenceId(), knownFrontends.keySet());
876 if (!isIsolatedLeader()) {
877 messageRetrySupport.retryMessages();
882 * Clears all pending transactions and converts them to messages to be forwarded to a new leader.
884 * @return the converted messages
886 public Collection<?> convertPendingTransactionsToMessages() {
887 return commitCoordinator.convertPendingTransactionsToMessages(
888 datastoreContext.getShardBatchedModificationCount());
892 protected void pauseLeader(final Runnable operation) {
893 LOG.debug("{}: In pauseLeader, operation: {}", persistenceId(), operation);
896 // Tell-based protocol can replay transaction state, so it is safe to blow it up when we are paused.
897 knownFrontends.values().forEach(LeaderFrontendState::retire);
898 knownFrontends = ImmutableMap.of();
900 store.setRunOnPendingTransactionsComplete(operation);
904 protected void unpauseLeader() {
905 LOG.debug("{}: In unpauseLeader", persistenceId());
908 store.setRunOnPendingTransactionsComplete(null);
910 // Restore tell-based protocol state as if we were becoming the leader
911 knownFrontends = Verify.verifyNotNull(frontendMetadata.toLeaderState(this));
915 protected OnDemandRaftState.AbstractBuilder<?> newOnDemandRaftStateBuilder() {
916 return OnDemandShardState.newBuilder().treeChangeListenerActors(treeChangeSupport.getListenerActors())
917 .dataChangeListenerActors(changeSupport.getListenerActors())
918 .commitCohortActors(store.getCohortActors());
922 public String persistenceId() {
927 ShardCommitCoordinator getCommitCoordinator() {
928 return commitCoordinator;
931 public DatastoreContext getDatastoreContext() {
932 return datastoreContext;
936 public ShardDataTree getDataStore() {
941 ShardStats getShardMBean() {
945 public static Builder builder() {
946 return new Builder();
949 public abstract static class AbstractBuilder<T extends AbstractBuilder<T, S>, S extends Shard> {
950 private final Class<S> shardClass;
951 private ShardIdentifier id;
952 private Map<String, String> peerAddresses = Collections.emptyMap();
953 private DatastoreContext datastoreContext;
954 private SchemaContextProvider schemaContextProvider;
955 private DatastoreSnapshot.ShardSnapshot restoreFromSnapshot;
956 private TipProducingDataTree dataTree;
957 private volatile boolean sealed;
959 protected AbstractBuilder(final Class<S> shardClass) {
960 this.shardClass = shardClass;
963 protected void checkSealed() {
964 Preconditions.checkState(!sealed, "Builder isalready sealed - further modifications are not allowed");
967 @SuppressWarnings("unchecked")
972 public T id(final ShardIdentifier newId) {
978 public T peerAddresses(final Map<String, String> newPeerAddresses) {
980 this.peerAddresses = newPeerAddresses;
984 public T datastoreContext(final DatastoreContext newDatastoreContext) {
986 this.datastoreContext = newDatastoreContext;
990 public T schemaContextProvider(final SchemaContextProvider schemaContextProvider) {
992 this.schemaContextProvider = Preconditions.checkNotNull(schemaContextProvider);
996 public T restoreFromSnapshot(final DatastoreSnapshot.ShardSnapshot newRestoreFromSnapshot) {
998 this.restoreFromSnapshot = newRestoreFromSnapshot;
1002 public T dataTree(final TipProducingDataTree newDataTree) {
1004 this.dataTree = newDataTree;
1008 public ShardIdentifier getId() {
1012 public Map<String, String> getPeerAddresses() {
1013 return peerAddresses;
1016 public DatastoreContext getDatastoreContext() {
1017 return datastoreContext;
1020 public SchemaContext getSchemaContext() {
1021 return Verify.verifyNotNull(schemaContextProvider.getSchemaContext());
1024 public DatastoreSnapshot.ShardSnapshot getRestoreFromSnapshot() {
1025 return restoreFromSnapshot;
1028 public TipProducingDataTree getDataTree() {
1032 public TreeType getTreeType() {
1033 switch (datastoreContext.getLogicalStoreType()) {
1035 return TreeType.CONFIGURATION;
1037 return TreeType.OPERATIONAL;
1039 throw new IllegalStateException("Unhandled logical store type "
1040 + datastoreContext.getLogicalStoreType());
1044 protected void verify() {
1045 Preconditions.checkNotNull(id, "id should not be null");
1046 Preconditions.checkNotNull(peerAddresses, "peerAddresses should not be null");
1047 Preconditions.checkNotNull(datastoreContext, "dataStoreContext should not be null");
1048 Preconditions.checkNotNull(schemaContextProvider, "schemaContextProvider should not be null");
1051 public Props props() {
1054 return Props.create(shardClass, this);
1058 public static class Builder extends AbstractBuilder<Builder, Shard> {
1065 return Ticker.systemTicker();
1068 void scheduleNextPendingTransaction() {
1069 self().tell(RESUME_NEXT_PENDING_TRANSACTION, ActorRef.noSender());