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
8 package org.opendaylight.controller.cluster.datastore;
10 import static com.google.common.base.Preconditions.checkState;
11 import static com.google.common.base.Verify.verify;
12 import static com.google.common.base.Verify.verifyNotNull;
13 import static java.util.Objects.requireNonNull;
15 import akka.actor.ActorRef;
16 import akka.actor.ActorSelection;
17 import akka.actor.Cancellable;
18 import akka.actor.ExtendedActorSystem;
19 import akka.actor.PoisonPill;
20 import akka.actor.Props;
21 import akka.actor.Status;
22 import akka.actor.Status.Failure;
23 import akka.persistence.RecoveryCompleted;
24 import akka.persistence.SnapshotOffer;
25 import akka.serialization.JavaSerializer;
26 import akka.serialization.Serialization;
27 import com.google.common.annotations.VisibleForTesting;
28 import com.google.common.base.Ticker;
29 import com.google.common.collect.ImmutableList;
30 import com.google.common.collect.ImmutableMap;
31 import com.google.common.collect.ImmutableSet;
32 import com.google.common.collect.Range;
33 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
34 import java.io.IOException;
35 import java.util.Arrays;
36 import java.util.Collection;
37 import java.util.Collections;
38 import java.util.HashMap;
40 import java.util.Optional;
41 import java.util.OptionalLong;
42 import java.util.concurrent.TimeUnit;
43 import org.eclipse.jdt.annotation.NonNull;
44 import org.eclipse.jdt.annotation.Nullable;
45 import org.opendaylight.controller.cluster.access.ABIVersion;
46 import org.opendaylight.controller.cluster.access.commands.ConnectClientRequest;
47 import org.opendaylight.controller.cluster.access.commands.ConnectClientSuccess;
48 import org.opendaylight.controller.cluster.access.commands.LocalHistoryRequest;
49 import org.opendaylight.controller.cluster.access.commands.NotLeaderException;
50 import org.opendaylight.controller.cluster.access.commands.OutOfSequenceEnvelopeException;
51 import org.opendaylight.controller.cluster.access.commands.TransactionRequest;
52 import org.opendaylight.controller.cluster.access.concepts.ClientIdentifier;
53 import org.opendaylight.controller.cluster.access.concepts.FrontendIdentifier;
54 import org.opendaylight.controller.cluster.access.concepts.LocalHistoryIdentifier;
55 import org.opendaylight.controller.cluster.access.concepts.RequestEnvelope;
56 import org.opendaylight.controller.cluster.access.concepts.RequestException;
57 import org.opendaylight.controller.cluster.access.concepts.RequestSuccess;
58 import org.opendaylight.controller.cluster.access.concepts.RetiredGenerationException;
59 import org.opendaylight.controller.cluster.access.concepts.RuntimeRequestException;
60 import org.opendaylight.controller.cluster.access.concepts.SliceableMessage;
61 import org.opendaylight.controller.cluster.access.concepts.TransactionIdentifier;
62 import org.opendaylight.controller.cluster.access.concepts.UnsupportedRequestException;
63 import org.opendaylight.controller.cluster.common.actor.CommonConfig;
64 import org.opendaylight.controller.cluster.common.actor.Dispatchers;
65 import org.opendaylight.controller.cluster.common.actor.Dispatchers.DispatcherType;
66 import org.opendaylight.controller.cluster.common.actor.MessageTracker;
67 import org.opendaylight.controller.cluster.common.actor.MeteringBehavior;
68 import org.opendaylight.controller.cluster.datastore.actors.JsonExportActor;
69 import org.opendaylight.controller.cluster.datastore.exceptions.NoShardLeaderException;
70 import org.opendaylight.controller.cluster.datastore.identifiers.ShardIdentifier;
71 import org.opendaylight.controller.cluster.datastore.messages.AbortTransaction;
72 import org.opendaylight.controller.cluster.datastore.messages.ActorInitialized;
73 import org.opendaylight.controller.cluster.datastore.messages.BatchedModifications;
74 import org.opendaylight.controller.cluster.datastore.messages.CanCommitTransaction;
75 import org.opendaylight.controller.cluster.datastore.messages.CloseTransactionChain;
76 import org.opendaylight.controller.cluster.datastore.messages.CommitTransaction;
77 import org.opendaylight.controller.cluster.datastore.messages.CreateTransaction;
78 import org.opendaylight.controller.cluster.datastore.messages.CreateTransactionReply;
79 import org.opendaylight.controller.cluster.datastore.messages.DataTreeChangedReply;
80 import org.opendaylight.controller.cluster.datastore.messages.ForwardedReadyTransaction;
81 import org.opendaylight.controller.cluster.datastore.messages.GetKnownClients;
82 import org.opendaylight.controller.cluster.datastore.messages.GetKnownClientsReply;
83 import org.opendaylight.controller.cluster.datastore.messages.GetShardDataTree;
84 import org.opendaylight.controller.cluster.datastore.messages.MakeLeaderLocal;
85 import org.opendaylight.controller.cluster.datastore.messages.OnDemandShardState;
86 import org.opendaylight.controller.cluster.datastore.messages.PeerAddressResolved;
87 import org.opendaylight.controller.cluster.datastore.messages.ReadyLocalTransaction;
88 import org.opendaylight.controller.cluster.datastore.messages.RegisterDataTreeChangeListener;
89 import org.opendaylight.controller.cluster.datastore.messages.ShardLeaderStateChanged;
90 import org.opendaylight.controller.cluster.datastore.messages.UpdateSchemaContext;
91 import org.opendaylight.controller.cluster.datastore.persisted.DatastoreSnapshot;
92 import org.opendaylight.controller.cluster.datastore.persisted.DatastoreSnapshot.ShardSnapshot;
93 import org.opendaylight.controller.cluster.datastore.persisted.DisableTrackingPayload;
94 import org.opendaylight.controller.cluster.messaging.MessageAssembler;
95 import org.opendaylight.controller.cluster.messaging.MessageSlicer;
96 import org.opendaylight.controller.cluster.messaging.SliceOptions;
97 import org.opendaylight.controller.cluster.notifications.LeaderStateChanged;
98 import org.opendaylight.controller.cluster.notifications.RegisterRoleChangeListener;
99 import org.opendaylight.controller.cluster.notifications.RoleChangeNotifier;
100 import org.opendaylight.controller.cluster.raft.LeadershipTransferFailedException;
101 import org.opendaylight.controller.cluster.raft.RaftActor;
102 import org.opendaylight.controller.cluster.raft.RaftActorRecoveryCohort;
103 import org.opendaylight.controller.cluster.raft.RaftActorSnapshotCohort;
104 import org.opendaylight.controller.cluster.raft.RaftState;
105 import org.opendaylight.controller.cluster.raft.ReplicatedLogEntry;
106 import org.opendaylight.controller.cluster.raft.base.messages.FollowerInitialSyncUpStatus;
107 import org.opendaylight.controller.cluster.raft.client.messages.OnDemandRaftState;
108 import org.opendaylight.controller.cluster.raft.messages.AppendEntriesReply;
109 import org.opendaylight.controller.cluster.raft.messages.Payload;
110 import org.opendaylight.controller.cluster.raft.messages.RequestLeadership;
111 import org.opendaylight.controller.cluster.raft.messages.ServerRemoved;
112 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.distributed.datastore.provider.rev140612.DataStoreProperties.ExportOnRecovery;
113 import org.opendaylight.yangtools.concepts.Identifier;
114 import org.opendaylight.yangtools.yang.data.tree.api.DataTree;
115 import org.opendaylight.yangtools.yang.data.tree.api.DataValidationFailedException;
116 import org.opendaylight.yangtools.yang.data.tree.api.TreeType;
117 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
118 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContextProvider;
119 import scala.concurrent.duration.FiniteDuration;
122 * A Shard represents a portion of the logical data tree.
125 * Our Shard uses InMemoryDataTree as it's internal representation and delegates all requests it
127 // FIXME: non-final for testing?
128 public class Shard extends RaftActor {
131 static final Object TX_COMMIT_TIMEOUT_CHECK_MESSAGE = new Object() {
133 public String toString() {
134 return "txCommitTimeoutCheck";
139 static final Object GET_SHARD_MBEAN_MESSAGE = new Object() {
141 public String toString() {
142 return "getShardMBeanMessage";
146 static final Object RESUME_NEXT_PENDING_TRANSACTION = new Object() {
148 public String toString() {
149 return "resumeNextPendingTransaction";
153 // FIXME: shard names should be encapsulated in their own class and this should be exposed as a constant.
154 public static final String DEFAULT_NAME = "default";
156 private static final Collection<ABIVersion> SUPPORTED_ABIVERSIONS;
158 // Make sure to keep this in sync with the journal configuration in factory-akka.conf
159 public static final String NON_PERSISTENT_JOURNAL_ID = "akka.persistence.non-persistent.journal";
162 final ABIVersion[] values = ABIVersion.values();
163 final ABIVersion[] real = Arrays.copyOfRange(values, 1, values.length - 1);
164 SUPPORTED_ABIVERSIONS = ImmutableList.copyOf(real).reverse();
167 // FIXME: make this a dynamic property based on mailbox size and maximum number of clients
168 private static final int CLIENT_MAX_MESSAGES = 1000;
170 // The state of this Shard
171 private final ShardDataTree store;
173 /// The name of this shard
174 private final String name;
176 private final String shardName;
178 private final ShardStats shardMBean;
180 private final ShardDataTreeListenerInfoMXBeanImpl listenerInfoMXBean;
182 private DatastoreContext datastoreContext;
184 private final ShardCommitCoordinator commitCoordinator;
186 private long transactionCommitTimeout;
188 private Cancellable txCommitTimeoutCheckSchedule;
190 private final Optional<ActorRef> roleChangeNotifier;
192 private final MessageTracker appendEntriesReplyTracker;
194 private final ShardTransactionActorFactory transactionActorFactory;
196 private final ShardSnapshotCohort snapshotCohort;
198 private final DataTreeChangeListenerSupport treeChangeSupport = new DataTreeChangeListenerSupport(this);
200 private ShardSnapshot restoreFromSnapshot;
202 private final ShardTransactionMessageRetrySupport messageRetrySupport;
205 final FrontendMetadata frontendMetadata;
207 private Map<FrontendIdentifier, LeaderFrontendState> knownFrontends = ImmutableMap.of();
208 private boolean paused;
210 private final MessageSlicer responseMessageSlicer;
211 private final Dispatchers dispatchers;
213 private final MessageAssembler requestMessageAssembler;
215 private final ExportOnRecovery exportOnRecovery;
217 private final ActorRef exportActor;
219 @SuppressFBWarnings(value = "MC_OVERRIDABLE_METHOD_CALL_IN_CONSTRUCTOR", justification = "Akka class design")
220 Shard(final AbstractBuilder<?, ?> builder) {
221 super(builder.getId().toString(), builder.getPeerAddresses(),
222 Optional.of(builder.getDatastoreContext().getShardRaftConfig()), DataStoreVersions.CURRENT_VERSION);
224 name = builder.getId().toString();
225 shardName = builder.getId().getShardName();
226 datastoreContext = builder.getDatastoreContext();
227 restoreFromSnapshot = builder.getRestoreFromSnapshot();
228 frontendMetadata = new FrontendMetadata(name);
229 exportOnRecovery = datastoreContext.getExportOnRecovery();
231 exportActor = switch (exportOnRecovery) {
232 case Json -> getContext().actorOf(JsonExportActor.props(builder.getSchemaContext(),
233 datastoreContext.getRecoveryExportBaseDir()));
237 setPersistence(datastoreContext.isPersistent());
239 LOG.info("Shard created : {}, persistent : {}", name, datastoreContext.isPersistent());
241 ShardDataTreeChangeListenerPublisherActorProxy treeChangeListenerPublisher =
242 new ShardDataTreeChangeListenerPublisherActorProxy(getContext(), name + "-DTCL-publisher", name);
243 if (builder.getDataTree() != null) {
244 store = new ShardDataTree(this, builder.getSchemaContext(), builder.getDataTree(),
245 treeChangeListenerPublisher, name,
248 store = new ShardDataTree(this, builder.getSchemaContext(), builder.getTreeType(),
249 builder.getDatastoreContext().getStoreRoot(), treeChangeListenerPublisher, name,
253 shardMBean = ShardStats.create(name, datastoreContext.getDataStoreMXBeanType(), this);
255 if (isMetricsCaptureEnabled()) {
256 getContext().become(new MeteringBehavior(this));
259 commitCoordinator = new ShardCommitCoordinator(store, LOG, name);
261 setTransactionCommitTimeout();
263 // create a notifier actor for each cluster member
264 roleChangeNotifier = createRoleChangeNotifier(name);
266 appendEntriesReplyTracker = new MessageTracker(AppendEntriesReply.class,
267 getRaftActorContext().getConfigParams().getIsolatedCheckIntervalInMillis());
269 dispatchers = new Dispatchers(context().system().dispatchers());
270 transactionActorFactory = new ShardTransactionActorFactory(store, datastoreContext,
271 dispatchers.getDispatcherPath(Dispatchers.DispatcherType.Transaction),
272 self(), getContext(), shardMBean, builder.getId().getShardName());
274 snapshotCohort = ShardSnapshotCohort.create(getContext(), builder.getId().getMemberName(), store, LOG,
275 name, datastoreContext);
277 messageRetrySupport = new ShardTransactionMessageRetrySupport(this);
279 responseMessageSlicer = MessageSlicer.builder().logContext(name)
280 .messageSliceSize(datastoreContext.getMaximumMessageSliceSize())
281 .fileBackedStreamFactory(getRaftActorContext().getFileBackedOutputStreamFactory())
282 .expireStateAfterInactivity(2, TimeUnit.MINUTES).build();
284 requestMessageAssembler = MessageAssembler.builder().logContext(name)
285 .fileBackedStreamFactory(getRaftActorContext().getFileBackedOutputStreamFactory())
286 .assembledMessageCallback((message, sender) -> self().tell(message, sender))
287 .expireStateAfterInactivity(datastoreContext.getRequestTimeout(), TimeUnit.NANOSECONDS).build();
289 listenerInfoMXBean = new ShardDataTreeListenerInfoMXBeanImpl(name, datastoreContext.getDataStoreMXBeanType(),
291 listenerInfoMXBean.register();
294 private void setTransactionCommitTimeout() {
295 transactionCommitTimeout = TimeUnit.MILLISECONDS.convert(
296 datastoreContext.getShardTransactionCommitTimeoutInSeconds(), TimeUnit.SECONDS) / 2;
299 private Optional<ActorRef> createRoleChangeNotifier(final String shardId) {
300 ActorRef shardRoleChangeNotifier = getContext().actorOf(
301 RoleChangeNotifier.getProps(shardId), shardId + "-notifier");
302 return Optional.of(shardRoleChangeNotifier);
306 public final void postStop() throws Exception {
307 LOG.info("Stopping Shard {}", persistenceId());
311 messageRetrySupport.close();
313 if (txCommitTimeoutCheckSchedule != null) {
314 txCommitTimeoutCheckSchedule.cancel();
317 commitCoordinator.abortPendingTransactions("Transaction aborted due to shutdown.", this);
319 shardMBean.unregisterMBean();
320 listenerInfoMXBean.unregister();
324 protected final void handleRecover(final Object message) {
325 LOG.debug("{}: onReceiveRecover: Received message {} from {}", persistenceId(), message.getClass(),
328 super.handleRecover(message);
330 switch (exportOnRecovery) {
332 if (message instanceof SnapshotOffer) {
333 exportActor.tell(new JsonExportActor.ExportSnapshot(store.readCurrentData().orElseThrow(), name),
334 ActorRef.noSender());
335 } else if (message instanceof ReplicatedLogEntry replicatedLogEntry) {
336 exportActor.tell(new JsonExportActor.ExportJournal(replicatedLogEntry), ActorRef.noSender());
337 } else if (message instanceof RecoveryCompleted) {
338 exportActor.tell(new JsonExportActor.FinishExport(name), ActorRef.noSender());
339 exportActor.tell(PoisonPill.getInstance(), ActorRef.noSender());
347 if (LOG.isTraceEnabled()) {
348 appendEntriesReplyTracker.begin();
353 // non-final for TestShard
354 protected void handleNonRaftCommand(final Object message) {
355 try (var context = appendEntriesReplyTracker.received(message)) {
356 final var maybeError = context.error();
357 if (maybeError.isPresent()) {
358 LOG.trace("{} : AppendEntriesReply failed to arrive at the expected interval {}", persistenceId(),
359 maybeError.orElseThrow());
362 store.resetTransactionBatch();
364 if (message instanceof RequestEnvelope request) {
365 handleRequestEnvelope(request);
366 } else if (MessageAssembler.isHandledMessage(message)) {
367 handleRequestAssemblerMessage(message);
368 } else if (message instanceof ConnectClientRequest request) {
369 handleConnectClient(request);
370 } else if (CreateTransaction.isSerializedType(message)) {
371 handleCreateTransaction(message);
372 } else if (message instanceof BatchedModifications request) {
373 handleBatchedModifications(request);
374 } else if (message instanceof ForwardedReadyTransaction request) {
375 handleForwardedReadyTransaction(request);
376 } else if (message instanceof ReadyLocalTransaction request) {
377 handleReadyLocalTransaction(request);
378 } else if (CanCommitTransaction.isSerializedType(message)) {
379 handleCanCommitTransaction(CanCommitTransaction.fromSerializable(message));
380 } else if (CommitTransaction.isSerializedType(message)) {
381 handleCommitTransaction(CommitTransaction.fromSerializable(message));
382 } else if (AbortTransaction.isSerializedType(message)) {
383 handleAbortTransaction(AbortTransaction.fromSerializable(message));
384 } else if (CloseTransactionChain.isSerializedType(message)) {
385 closeTransactionChain(CloseTransactionChain.fromSerializable(message));
386 } else if (message instanceof DataTreeChangedReply) {
388 } else if (message instanceof RegisterDataTreeChangeListener request) {
389 treeChangeSupport.onMessage(request, isLeader(), hasLeader());
390 } else if (message instanceof UpdateSchemaContext request) {
391 updateSchemaContext(request);
392 } else if (message instanceof PeerAddressResolved resolved) {
393 setPeerAddress(resolved.getPeerId(), resolved.getPeerAddress());
394 } else if (TX_COMMIT_TIMEOUT_CHECK_MESSAGE.equals(message)) {
395 commitTimeoutCheck();
396 } else if (message instanceof DatastoreContext request) {
397 onDatastoreContext(request);
398 } else if (message instanceof RegisterRoleChangeListener) {
399 roleChangeNotifier.orElseThrow().forward(message, context());
400 } else if (message instanceof FollowerInitialSyncUpStatus request) {
401 shardMBean.setFollowerInitialSyncStatus(request.isInitialSyncDone());
402 context().parent().tell(message, self());
403 } else if (GET_SHARD_MBEAN_MESSAGE.equals(message)) {
404 sender().tell(getShardMBean(), self());
405 } else if (message instanceof GetShardDataTree) {
406 sender().tell(store.getDataTree(), self());
407 } else if (message instanceof ServerRemoved) {
408 context().parent().forward(message, context());
409 } else if (ShardTransactionMessageRetrySupport.TIMER_MESSAGE_CLASS.isInstance(message)) {
410 messageRetrySupport.onTimerMessage(message);
411 } else if (message instanceof DataTreeCohortActorRegistry.CohortRegistryCommand request) {
412 store.processCohortRegistryCommand(getSender(), request);
413 } else if (message instanceof MakeLeaderLocal) {
415 } else if (RESUME_NEXT_PENDING_TRANSACTION.equals(message)) {
416 store.resumeNextPendingTransaction();
417 } else if (GetKnownClients.INSTANCE.equals(message)) {
418 handleGetKnownClients();
419 } else if (!responseMessageSlicer.handleMessage(message)) {
420 super.handleNonRaftCommand(message);
425 private void handleRequestAssemblerMessage(final Object message) {
426 dispatchers.getDispatcher(DispatcherType.Serialization).execute(() -> {
427 JavaSerializer.currentSystem().value_$eq((ExtendedActorSystem) context().system());
428 requestMessageAssembler.handleMessage(message, self());
432 @SuppressWarnings("checkstyle:IllegalCatch")
433 private void handleRequestEnvelope(final RequestEnvelope envelope) {
434 final long now = ticker().read();
436 final RequestSuccess<?, ?> success = handleRequest(envelope, now);
437 if (success != null) {
438 final long executionTimeNanos = ticker().read() - now;
439 if (success instanceof SliceableMessage) {
440 dispatchers.getDispatcher(DispatcherType.Serialization).execute(() ->
441 responseMessageSlicer.slice(SliceOptions.builder().identifier(success.getTarget())
442 .message(envelope.newSuccessEnvelope(success, executionTimeNanos))
443 .sendTo(envelope.getMessage().getReplyTo()).replyTo(self())
444 .onFailureCallback(t -> LOG.warn("Error slicing response {}", success, t)).build()));
446 envelope.sendSuccess(success, executionTimeNanos);
449 } catch (RequestException e) {
450 LOG.debug("{}: request {} failed", persistenceId(), envelope, e);
451 envelope.sendFailure(e, ticker().read() - now);
452 } catch (Exception e) {
453 LOG.debug("{}: request {} caused failure", persistenceId(), envelope, e);
454 envelope.sendFailure(new RuntimeRequestException("Request failed to process", e),
455 ticker().read() - now);
459 private void commitTimeoutCheck() {
460 store.checkForExpiredTransactions(transactionCommitTimeout, this::updateAccess);
461 commitCoordinator.checkForExpiredTransactions(transactionCommitTimeout, this);
462 requestMessageAssembler.checkExpiredAssembledMessageState();
465 private OptionalLong updateAccess(final SimpleShardDataTreeCohort cohort) {
466 final FrontendIdentifier frontend = cohort.getIdentifier().getHistoryId().getClientId().getFrontendId();
467 final LeaderFrontendState state = knownFrontends.get(frontend);
469 // Not tell-based protocol, do nothing
470 return OptionalLong.empty();
473 if (isIsolatedLeader()) {
474 // We are isolated and no new request can come through until we emerge from it. We are still updating
475 // liveness of frontend when we see it attempting to communicate. Use the last access timer.
476 return OptionalLong.of(state.getLastSeenTicks());
479 // If this frontend has freshly connected, give it some time to catch up before killing its transactions.
480 return OptionalLong.of(state.getLastConnectTicks());
483 private void disableTracking(final DisableTrackingPayload payload) {
484 final ClientIdentifier clientId = payload.getIdentifier();
485 LOG.debug("{}: disabling tracking of {}", persistenceId(), clientId);
486 frontendMetadata.disableTracking(clientId);
489 final FrontendIdentifier frontendId = clientId.getFrontendId();
490 final LeaderFrontendState frontend = knownFrontends.get(frontendId);
491 if (frontend != null) {
492 if (clientId.equals(frontend.getIdentifier())) {
493 if (!(frontend instanceof LeaderFrontendState.Disabled)) {
494 verify(knownFrontends.replace(frontendId, frontend,
495 new LeaderFrontendState.Disabled(persistenceId(), clientId, store)));
496 LOG.debug("{}: leader state for {} disabled", persistenceId(), clientId);
498 LOG.debug("{}: leader state {} is already disabled", persistenceId(), frontend);
501 LOG.debug("{}: leader state {} does not match {}", persistenceId(), frontend, clientId);
504 LOG.debug("{}: leader state for {} not found", persistenceId(), clientId);
505 knownFrontends.put(frontendId, new LeaderFrontendState.Disabled(persistenceId(), clientId,
511 private void onMakeLeaderLocal() {
512 LOG.debug("{}: onMakeLeaderLocal received", persistenceId());
514 getSender().tell(new Status.Success(null), getSelf());
518 final ActorSelection leader = getLeader();
520 if (leader == null) {
521 // Leader is not present. The cluster is most likely trying to
522 // elect a leader and we should let that run its normal course
524 // TODO we can wait for the election to complete and retry the
525 // request. We can also let the caller retry by sending a flag
526 // in the response indicating the request is "reTryable".
527 getSender().tell(new Failure(
528 new LeadershipTransferFailedException("We cannot initiate leadership transfer to local node. "
529 + "Currently there is no leader for " + persistenceId())),
534 leader.tell(new RequestLeadership(getId(), getSender()), getSelf());
537 // Acquire our frontend tracking handle and verify generation matches
538 private @Nullable LeaderFrontendState findFrontend(final ClientIdentifier clientId) throws RequestException {
539 final LeaderFrontendState existing = knownFrontends.get(clientId.getFrontendId());
540 if (existing != null) {
541 final int cmp = Long.compareUnsigned(existing.getIdentifier().getGeneration(), clientId.getGeneration());
547 LOG.debug("{}: rejecting request from outdated client {}", persistenceId(), clientId);
548 throw new RetiredGenerationException(clientId.getGeneration(),
549 existing.getIdentifier().getGeneration());
552 LOG.info("{}: retiring state {}, outdated by request from client {}", persistenceId(), existing, clientId);
554 knownFrontends.remove(clientId.getFrontendId());
556 LOG.debug("{}: client {} is not yet known", persistenceId(), clientId);
562 private LeaderFrontendState getFrontend(final ClientIdentifier clientId) throws RequestException {
563 final LeaderFrontendState ret = findFrontend(clientId);
568 // TODO: a dedicated exception would be better, but this is technically true, too
569 throw new OutOfSequenceEnvelopeException(0);
572 private static @NonNull ABIVersion selectVersion(final ConnectClientRequest message) {
573 final Range<ABIVersion> clientRange = Range.closed(message.getMinVersion(), message.getMaxVersion());
574 for (ABIVersion v : SUPPORTED_ABIVERSIONS) {
575 if (clientRange.contains(v)) {
580 throw new IllegalArgumentException(String.format(
581 "No common version between backend versions %s and client versions %s", SUPPORTED_ABIVERSIONS,
585 @SuppressWarnings("checkstyle:IllegalCatch")
586 private void handleConnectClient(final ConnectClientRequest message) {
588 final ClientIdentifier clientId = message.getTarget();
589 final LeaderFrontendState existing = findFrontend(clientId);
590 if (existing != null) {
594 if (!isLeader() || !isLeaderActive()) {
595 LOG.info("{}: not currently leader, rejecting request {}. isLeader: {}, isLeaderActive: {},"
596 + "isLeadershipTransferInProgress: {}.",
597 persistenceId(), message, isLeader(), isLeaderActive(), isLeadershipTransferInProgress());
598 throw new NotLeaderException(getSelf());
601 final ABIVersion selectedVersion = selectVersion(message);
602 final LeaderFrontendState frontend;
603 if (existing == null) {
604 frontend = new LeaderFrontendState.Enabled(persistenceId(), clientId, store);
605 knownFrontends.put(clientId.getFrontendId(), frontend);
606 LOG.debug("{}: created state {} for client {}", persistenceId(), frontend, clientId);
611 frontend.reconnect();
612 message.getReplyTo().tell(new ConnectClientSuccess(message.getTarget(), message.getSequence(), getSelf(),
613 ImmutableList.of(), store.getDataTree(), CLIENT_MAX_MESSAGES).toVersion(selectedVersion),
614 ActorRef.noSender());
615 } catch (RequestException | RuntimeException e) {
616 message.getReplyTo().tell(new Failure(e), ActorRef.noSender());
620 private @Nullable RequestSuccess<?, ?> handleRequest(final RequestEnvelope envelope, final long now)
621 throws RequestException {
622 // We are not the leader, hence we want to fail-fast.
623 if (!isLeader() || paused || !isLeaderActive()) {
624 LOG.debug("{}: not currently active leader, rejecting request {}. isLeader: {}, isLeaderActive: {},"
625 + "isLeadershipTransferInProgress: {}, paused: {}",
626 persistenceId(), envelope, isLeader(), isLeaderActive(), isLeadershipTransferInProgress(), paused);
627 throw new NotLeaderException(getSelf());
630 final var request = envelope.getMessage();
631 if (request instanceof TransactionRequest<?> txReq) {
632 final var clientId = txReq.getTarget().getHistoryId().getClientId();
633 return getFrontend(clientId).handleTransactionRequest(txReq, envelope, now);
634 } else if (request instanceof LocalHistoryRequest<?> lhReq) {
635 final var clientId = lhReq.getTarget().getClientId();
636 return getFrontend(clientId).handleLocalHistoryRequest(lhReq, envelope, now);
638 LOG.warn("{}: rejecting unsupported request {}", persistenceId(), request);
639 throw new UnsupportedRequestException(request);
643 private void handleGetKnownClients() {
644 final ImmutableSet<ClientIdentifier> clients;
646 clients = knownFrontends.values().stream()
647 .map(LeaderFrontendState::getIdentifier)
648 .collect(ImmutableSet.toImmutableSet());
650 clients = frontendMetadata.getClients();
652 sender().tell(new GetKnownClientsReply(clients), self());
655 private boolean hasLeader() {
656 return getLeaderId() != null;
659 final int getPendingTxCommitQueueSize() {
660 return store.getQueueSize();
663 final int getCohortCacheSize() {
664 return commitCoordinator.getCohortCacheSize();
668 protected final Optional<ActorRef> getRoleChangeNotifier() {
669 return roleChangeNotifier;
672 final String getShardName() {
677 protected final LeaderStateChanged newLeaderStateChanged(final String memberId, final String leaderId,
678 final short leaderPayloadVersion) {
679 return isLeader() ? new ShardLeaderStateChanged(memberId, leaderId, store.getDataTree(), leaderPayloadVersion)
680 : new ShardLeaderStateChanged(memberId, leaderId, leaderPayloadVersion);
683 private void onDatastoreContext(final DatastoreContext context) {
684 datastoreContext = verifyNotNull(context);
686 setTransactionCommitTimeout();
688 setPersistence(datastoreContext.isPersistent());
690 updateConfigParams(datastoreContext.getShardRaftConfig());
693 // applyState() will be invoked once consensus is reached on the payload
694 // non-final for mocking
695 void persistPayload(final Identifier id, final Payload payload, final boolean batchHint) {
696 final boolean canSkipPayload = !hasFollowers() && !persistence().isRecoveryApplicable();
697 if (canSkipPayload) {
698 applyState(self(), id, payload);
700 // We are faking the sender
701 persistData(self(), id, payload, batchHint);
705 private void handleCommitTransaction(final CommitTransaction commit) {
706 final TransactionIdentifier txId = commit.getTransactionId();
708 askProtocolEncountered(txId);
709 commitCoordinator.handleCommit(txId, getSender(), this);
711 ActorSelection leader = getLeader();
712 if (leader == null) {
713 messageRetrySupport.addMessageToRetry(commit, getSender(), "Could not commit transaction " + txId);
715 LOG.debug("{}: Forwarding CommitTransaction to leader {}", persistenceId(), leader);
716 leader.forward(commit, getContext());
721 private void handleCanCommitTransaction(final CanCommitTransaction canCommit) {
722 final TransactionIdentifier txId = canCommit.getTransactionId();
723 LOG.debug("{}: Can committing transaction {}", persistenceId(), txId);
726 askProtocolEncountered(txId);
727 commitCoordinator.handleCanCommit(txId, getSender(), this);
729 ActorSelection leader = getLeader();
730 if (leader == null) {
731 messageRetrySupport.addMessageToRetry(canCommit, getSender(),
732 "Could not canCommit transaction " + txId);
734 LOG.debug("{}: Forwarding CanCommitTransaction to leader {}", persistenceId(), leader);
735 leader.forward(canCommit, getContext());
740 @SuppressWarnings("checkstyle:IllegalCatch")
741 private void handleBatchedModificationsLocal(final BatchedModifications batched, final ActorRef sender) {
742 askProtocolEncountered(batched.getTransactionId());
745 commitCoordinator.handleBatchedModifications(batched, sender, this);
746 } catch (Exception e) {
747 LOG.error("{}: Error handling BatchedModifications for Tx {}", persistenceId(),
748 batched.getTransactionId(), e);
749 sender.tell(new Failure(e), getSelf());
753 private void handleBatchedModifications(final BatchedModifications batched) {
754 // This message is sent to prepare the modifications transaction directly on the Shard as an
755 // optimization to avoid the extra overhead of a separate ShardTransaction actor. On the last
756 // BatchedModifications message, the caller sets the ready flag in the message indicating
757 // modifications are complete. The reply contains the cohort actor path (this actor) for the caller
758 // to initiate the 3-phase commit. This also avoids the overhead of sending an additional
759 // ReadyTransaction message.
761 // If we're not the leader then forward to the leader. This is a safety measure - we shouldn't
762 // normally get here if we're not the leader as the front-end (TransactionProxy) should determine
763 // the primary/leader shard. However with timing and caching on the front-end, there's a small
764 // window where it could have a stale leader during leadership transitions.
766 boolean isLeaderActive = isLeaderActive();
767 if (isLeader() && isLeaderActive) {
768 handleBatchedModificationsLocal(batched, getSender());
770 ActorSelection leader = getLeader();
771 if (!isLeaderActive || leader == null) {
772 messageRetrySupport.addMessageToRetry(batched, getSender(),
773 "Could not process BatchedModifications " + batched.getTransactionId());
775 // If this is not the first batch and leadership changed in between batched messages,
776 // we need to reconstruct previous BatchedModifications from the transaction
777 // DataTreeModification, honoring the max batched modification count, and forward all the
778 // previous BatchedModifications to the new leader.
779 Collection<BatchedModifications> newModifications = commitCoordinator
780 .createForwardedBatchedModifications(batched,
781 datastoreContext.getShardBatchedModificationCount());
783 LOG.debug("{}: Forwarding {} BatchedModifications to leader {}", persistenceId(),
784 newModifications.size(), leader);
786 for (BatchedModifications bm : newModifications) {
787 leader.forward(bm, getContext());
793 private boolean failIfIsolatedLeader(final ActorRef sender) {
794 if (isIsolatedLeader()) {
795 sender.tell(new Failure(new NoShardLeaderException(String.format(
796 "Shard %s was the leader but has lost contact with all of its followers. Either all"
797 + " other follower nodes are down or this node is isolated by a network partition.",
798 persistenceId()))), getSelf());
805 protected boolean isIsolatedLeader() {
806 return getRaftState() == RaftState.IsolatedLeader;
809 @SuppressWarnings("checkstyle:IllegalCatch")
810 private void handleReadyLocalTransaction(final ReadyLocalTransaction message) {
811 final TransactionIdentifier txId = message.getTransactionId();
812 LOG.debug("{}: handleReadyLocalTransaction for {}", persistenceId(), txId);
814 boolean isLeaderActive = isLeaderActive();
815 if (isLeader() && isLeaderActive) {
816 askProtocolEncountered(txId);
818 commitCoordinator.handleReadyLocalTransaction(message, getSender(), this);
819 } catch (Exception e) {
820 LOG.error("{}: Error handling ReadyLocalTransaction for Tx {}", persistenceId(), txId, e);
821 getSender().tell(new Failure(e), getSelf());
824 ActorSelection leader = getLeader();
825 if (!isLeaderActive || leader == null) {
826 messageRetrySupport.addMessageToRetry(message, getSender(),
827 "Could not process ready local transaction " + txId);
829 LOG.debug("{}: Forwarding ReadyLocalTransaction to leader {}", persistenceId(), leader);
830 message.setRemoteVersion(getCurrentBehavior().getLeaderPayloadVersion());
831 leader.forward(message, getContext());
836 private void handleForwardedReadyTransaction(final ForwardedReadyTransaction forwardedReady) {
837 LOG.debug("{}: handleForwardedReadyTransaction for {}", persistenceId(), forwardedReady.getTransactionId());
839 boolean isLeaderActive = isLeaderActive();
840 if (isLeader() && isLeaderActive) {
841 askProtocolEncountered(forwardedReady.getTransactionId());
842 commitCoordinator.handleForwardedReadyTransaction(forwardedReady, getSender(), this);
844 ActorSelection leader = getLeader();
845 if (!isLeaderActive || leader == null) {
846 messageRetrySupport.addMessageToRetry(forwardedReady, getSender(),
847 "Could not process forwarded ready transaction " + forwardedReady.getTransactionId());
849 LOG.debug("{}: Forwarding ForwardedReadyTransaction to leader {}", persistenceId(), leader);
851 ReadyLocalTransaction readyLocal = new ReadyLocalTransaction(forwardedReady.getTransactionId(),
852 forwardedReady.getTransaction().getSnapshot(), forwardedReady.isDoImmediateCommit(),
853 forwardedReady.getParticipatingShardNames());
854 readyLocal.setRemoteVersion(getCurrentBehavior().getLeaderPayloadVersion());
855 leader.forward(readyLocal, getContext());
860 private void handleAbortTransaction(final AbortTransaction abort) {
861 final TransactionIdentifier transactionId = abort.getTransactionId();
862 askProtocolEncountered(transactionId);
863 doAbortTransaction(transactionId, getSender());
866 final void doAbortTransaction(final Identifier transactionID, final ActorRef sender) {
867 commitCoordinator.handleAbort(transactionID, sender, this);
870 private void handleCreateTransaction(final Object message) {
872 createTransaction(CreateTransaction.fromSerializable(message));
873 } else if (getLeader() != null) {
874 getLeader().forward(message, getContext());
876 getSender().tell(new Failure(new NoShardLeaderException(
877 "Could not create a shard transaction", persistenceId())), getSelf());
881 private void closeTransactionChain(final CloseTransactionChain closeTransactionChain) {
883 final LocalHistoryIdentifier id = closeTransactionChain.getIdentifier();
884 askProtocolEncountered(id.getClientId());
885 store.closeTransactionChain(id);
886 } else if (getLeader() != null) {
887 getLeader().forward(closeTransactionChain, getContext());
889 LOG.warn("{}: Could not close transaction {}", persistenceId(), closeTransactionChain.getIdentifier());
893 @SuppressWarnings("checkstyle:IllegalCatch")
894 private void createTransaction(final CreateTransaction createTransaction) {
895 askProtocolEncountered(createTransaction.getTransactionId());
898 if (TransactionType.fromInt(createTransaction.getTransactionType()) != TransactionType.READ_ONLY
899 && failIfIsolatedLeader(getSender())) {
903 ActorRef transactionActor = createTransaction(createTransaction.getTransactionType(),
904 createTransaction.getTransactionId());
906 getSender().tell(new CreateTransactionReply(Serialization.serializedActorPath(transactionActor),
907 createTransaction.getTransactionId(), createTransaction.getVersion()).toSerializable(), getSelf());
908 } catch (Exception e) {
909 getSender().tell(new Failure(e), getSelf());
913 private ActorRef createTransaction(final int transactionType, final TransactionIdentifier transactionId) {
914 LOG.debug("{}: Creating transaction : {} ", persistenceId(), transactionId);
915 return transactionActorFactory.newShardTransaction(TransactionType.fromInt(transactionType),
919 // Called on leader only
920 private void askProtocolEncountered(final TransactionIdentifier transactionId) {
921 askProtocolEncountered(transactionId.getHistoryId().getClientId());
924 // Called on leader only
925 private void askProtocolEncountered(final ClientIdentifier clientId) {
926 final FrontendIdentifier frontend = clientId.getFrontendId();
927 final LeaderFrontendState state = knownFrontends.get(frontend);
928 if (!(state instanceof LeaderFrontendState.Disabled)) {
929 LOG.debug("{}: encountered ask-based client {}, disabling transaction tracking", persistenceId(), clientId);
930 if (knownFrontends.isEmpty()) {
931 knownFrontends = new HashMap<>();
933 knownFrontends.put(frontend, new LeaderFrontendState.Disabled(persistenceId(), clientId, getDataStore()));
935 persistPayload(clientId, DisableTrackingPayload.create(clientId,
936 datastoreContext.getInitialPayloadSerializedBufferCapacity()), false);
940 private void updateSchemaContext(final UpdateSchemaContext message) {
941 updateSchemaContext(message.getEffectiveModelContext());
945 void updateSchemaContext(final @NonNull EffectiveModelContext schemaContext) {
946 store.updateSchemaContext(schemaContext);
949 private boolean isMetricsCaptureEnabled() {
950 CommonConfig config = new CommonConfig(getContext().system().settings().config());
951 return config.isMetricCaptureEnabled();
955 protected final RaftActorSnapshotCohort getRaftActorSnapshotCohort() {
956 return snapshotCohort;
960 protected final RaftActorRecoveryCohort getRaftActorRecoveryCohort() {
961 if (restoreFromSnapshot == null) {
962 return ShardRecoveryCoordinator.create(store, persistenceId(), LOG);
965 return ShardRecoveryCoordinator.forSnapshot(store, persistenceId(), LOG, restoreFromSnapshot.getSnapshot());
969 // non-final for testing
970 protected void onRecoveryComplete() {
971 restoreFromSnapshot = null;
973 //notify shard manager
974 getContext().parent().tell(new ActorInitialized(), getSelf());
976 // Being paranoid here - this method should only be called once but just in case...
977 if (txCommitTimeoutCheckSchedule == null) {
978 // Schedule a message to be periodically sent to check if the current in-progress
979 // transaction should be expired and aborted.
980 FiniteDuration period = FiniteDuration.create(transactionCommitTimeout / 3, TimeUnit.MILLISECONDS);
981 txCommitTimeoutCheckSchedule = getContext().system().scheduler().schedule(
982 period, period, getSelf(),
983 TX_COMMIT_TIMEOUT_CHECK_MESSAGE, getContext().dispatcher(), ActorRef.noSender());
988 protected final void applyState(final ActorRef clientActor, final Identifier identifier, final Object data) {
989 if (data instanceof Payload payload) {
990 if (payload instanceof DisableTrackingPayload disableTracking) {
991 disableTracking(disableTracking);
996 store.applyReplicatedPayload(identifier, payload);
997 } catch (DataValidationFailedException | IOException e) {
998 LOG.error("{}: Error applying replica {}", persistenceId(), identifier, e);
1001 LOG.error("{}: Unknown state for {} received {}", persistenceId(), identifier, data);
1006 protected final void onStateChanged() {
1007 boolean isLeader = isLeader();
1008 boolean hasLeader = hasLeader();
1009 treeChangeSupport.onLeadershipChange(isLeader, hasLeader);
1011 // If this actor is no longer the leader close all the transaction chains
1013 if (LOG.isDebugEnabled()) {
1015 "{}: onStateChanged: Closing all transaction chains because shard {} is no longer the leader",
1016 persistenceId(), getId());
1020 store.purgeLeaderState();
1023 if (hasLeader && !isIsolatedLeader()) {
1024 messageRetrySupport.retryMessages();
1029 protected final void onLeaderChanged(final String oldLeader, final String newLeader) {
1030 shardMBean.incrementLeadershipChangeCount();
1034 if (!knownFrontends.isEmpty()) {
1035 LOG.debug("{}: removing frontend state for {}", persistenceId(), knownFrontends.keySet());
1036 knownFrontends = ImmutableMap.of();
1039 requestMessageAssembler.close();
1042 // No leader anywhere, nothing else to do
1046 // Another leader was elected. If we were the previous leader and had pending transactions, convert
1047 // them to transaction messages and send to the new leader.
1048 ActorSelection leader = getLeader();
1049 if (leader != null) {
1050 // Clears all pending transactions and converts them to messages to be forwarded to a new leader.
1051 Collection<?> messagesToForward = commitCoordinator.convertPendingTransactionsToMessages(
1052 datastoreContext.getShardBatchedModificationCount());
1054 if (!messagesToForward.isEmpty()) {
1055 LOG.debug("{}: Forwarding {} pending transaction messages to leader {}", persistenceId(),
1056 messagesToForward.size(), leader);
1058 for (Object message : messagesToForward) {
1059 LOG.debug("{}: Forwarding pending transaction message {}", persistenceId(), message);
1061 leader.tell(message, self());
1065 commitCoordinator.abortPendingTransactions("The transacton was aborted due to inflight leadership "
1066 + "change and the leader address isn't available.", this);
1069 // We have become the leader, we need to reconstruct frontend state
1070 knownFrontends = verifyNotNull(frontendMetadata.toLeaderState(this));
1071 LOG.debug("{}: became leader with frontend state for {}", persistenceId(), knownFrontends.keySet());
1074 if (!isIsolatedLeader()) {
1075 messageRetrySupport.retryMessages();
1080 protected final void pauseLeader(final Runnable operation) {
1081 LOG.debug("{}: In pauseLeader, operation: {}", persistenceId(), operation);
1084 // Tell-based protocol can replay transaction state, so it is safe to blow it up when we are paused.
1085 knownFrontends.values().forEach(LeaderFrontendState::retire);
1086 knownFrontends = ImmutableMap.of();
1088 store.setRunOnPendingTransactionsComplete(operation);
1092 protected final void unpauseLeader() {
1093 LOG.debug("{}: In unpauseLeader", persistenceId());
1096 store.setRunOnPendingTransactionsComplete(null);
1098 // Restore tell-based protocol state as if we were becoming the leader
1099 knownFrontends = verifyNotNull(frontendMetadata.toLeaderState(this));
1103 protected final OnDemandRaftState.AbstractBuilder<?, ?> newOnDemandRaftStateBuilder() {
1104 return OnDemandShardState.newBuilder()
1105 .treeChangeListenerActors(treeChangeSupport.getListenerActors())
1106 .commitCohortActors(store.getCohortActors());
1110 public final String persistenceId() {
1115 public final String journalPluginId() {
1116 // This method may be invoked from super constructor (wonderful), hence we also need to handle the case of
1117 // the field being uninitialized because our constructor is not finished.
1118 if (datastoreContext != null && !datastoreContext.isPersistent()) {
1119 return NON_PERSISTENT_JOURNAL_ID;
1121 return super.journalPluginId();
1125 final ShardCommitCoordinator getCommitCoordinator() {
1126 return commitCoordinator;
1129 // non-final for mocking
1130 DatastoreContext getDatastoreContext() {
1131 return datastoreContext;
1135 final ShardDataTree getDataStore() {
1140 // non-final for mocking
1141 ShardStats getShardMBean() {
1145 public static Builder builder() {
1146 return new Builder();
1149 public abstract static class AbstractBuilder<T extends AbstractBuilder<T, S>, S extends Shard> {
1150 private final Class<? extends S> shardClass;
1151 private ShardIdentifier id;
1152 private Map<String, String> peerAddresses = Collections.emptyMap();
1153 private DatastoreContext datastoreContext;
1154 private EffectiveModelContextProvider schemaContextProvider;
1155 private DatastoreSnapshot.ShardSnapshot restoreFromSnapshot;
1156 private DataTree dataTree;
1158 private volatile boolean sealed;
1160 AbstractBuilder(final Class<? extends S> shardClass) {
1161 this.shardClass = shardClass;
1164 final void checkSealed() {
1165 checkState(!sealed, "Builder is already sealed - further modifications are not allowed");
1168 @SuppressWarnings("unchecked")
1173 public T id(final ShardIdentifier newId) {
1179 public T peerAddresses(final Map<String, String> newPeerAddresses) {
1181 peerAddresses = newPeerAddresses;
1185 public T datastoreContext(final DatastoreContext newDatastoreContext) {
1187 datastoreContext = newDatastoreContext;
1191 public T schemaContextProvider(final EffectiveModelContextProvider newSchemaContextProvider) {
1193 schemaContextProvider = requireNonNull(newSchemaContextProvider);
1197 public T restoreFromSnapshot(final DatastoreSnapshot.ShardSnapshot newRestoreFromSnapshot) {
1199 restoreFromSnapshot = newRestoreFromSnapshot;
1203 public T dataTree(final DataTree newDataTree) {
1205 dataTree = newDataTree;
1209 public ShardIdentifier getId() {
1213 public Map<String, String> getPeerAddresses() {
1214 return peerAddresses;
1217 public DatastoreContext getDatastoreContext() {
1218 return datastoreContext;
1221 public EffectiveModelContext getSchemaContext() {
1222 return verifyNotNull(schemaContextProvider.getEffectiveModelContext());
1225 public DatastoreSnapshot.ShardSnapshot getRestoreFromSnapshot() {
1226 return restoreFromSnapshot;
1229 public DataTree getDataTree() {
1233 public TreeType getTreeType() {
1234 return switch (datastoreContext.getLogicalStoreType()) {
1235 case CONFIGURATION -> TreeType.CONFIGURATION;
1236 case OPERATIONAL -> TreeType.OPERATIONAL;
1240 protected void verify() {
1241 requireNonNull(id, "id should not be null");
1242 requireNonNull(peerAddresses, "peerAddresses should not be null");
1243 requireNonNull(datastoreContext, "dataStoreContext should not be null");
1244 requireNonNull(schemaContextProvider, "schemaContextProvider should not be null");
1247 public Props props() {
1250 return Props.create(shardClass, this);
1254 public static class Builder extends AbstractBuilder<Builder, Shard> {
1259 Builder(final Class<? extends Shard> shardClass) {
1265 return Ticker.systemTicker();
1268 void scheduleNextPendingTransaction() {
1269 self().tell(RESUME_NEXT_PENDING_TRANSACTION, ActorRef.noSender());