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 java.io.IOException;
34 import java.util.Arrays;
35 import java.util.Collection;
36 import java.util.Collections;
37 import java.util.HashMap;
39 import java.util.Optional;
40 import java.util.OptionalLong;
41 import java.util.concurrent.TimeUnit;
42 import org.eclipse.jdt.annotation.NonNull;
43 import org.eclipse.jdt.annotation.Nullable;
44 import org.opendaylight.controller.cluster.access.ABIVersion;
45 import org.opendaylight.controller.cluster.access.commands.ConnectClientRequest;
46 import org.opendaylight.controller.cluster.access.commands.ConnectClientSuccess;
47 import org.opendaylight.controller.cluster.access.commands.LocalHistoryRequest;
48 import org.opendaylight.controller.cluster.access.commands.NotLeaderException;
49 import org.opendaylight.controller.cluster.access.commands.OutOfSequenceEnvelopeException;
50 import org.opendaylight.controller.cluster.access.commands.TransactionRequest;
51 import org.opendaylight.controller.cluster.access.concepts.ClientIdentifier;
52 import org.opendaylight.controller.cluster.access.concepts.FrontendIdentifier;
53 import org.opendaylight.controller.cluster.access.concepts.LocalHistoryIdentifier;
54 import org.opendaylight.controller.cluster.access.concepts.Request;
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.MessageTracker.Error;
68 import org.opendaylight.controller.cluster.common.actor.MeteringBehavior;
69 import org.opendaylight.controller.cluster.datastore.actors.JsonExportActor;
70 import org.opendaylight.controller.cluster.datastore.exceptions.NoShardLeaderException;
71 import org.opendaylight.controller.cluster.datastore.identifiers.ShardIdentifier;
72 import org.opendaylight.controller.cluster.datastore.messages.AbortTransaction;
73 import org.opendaylight.controller.cluster.datastore.messages.ActorInitialized;
74 import org.opendaylight.controller.cluster.datastore.messages.BatchedModifications;
75 import org.opendaylight.controller.cluster.datastore.messages.CanCommitTransaction;
76 import org.opendaylight.controller.cluster.datastore.messages.CloseTransactionChain;
77 import org.opendaylight.controller.cluster.datastore.messages.CommitTransaction;
78 import org.opendaylight.controller.cluster.datastore.messages.CreateTransaction;
79 import org.opendaylight.controller.cluster.datastore.messages.CreateTransactionReply;
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.RequestLeadership;
110 import org.opendaylight.controller.cluster.raft.messages.ServerRemoved;
111 import org.opendaylight.controller.cluster.raft.protobuff.client.messages.Payload;
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.api.schema.tree.DataTree;
115 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataValidationFailedException;
116 import org.opendaylight.yangtools.yang.data.api.schema.tree.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 Shard(final AbstractBuilder<?, ?> builder) {
220 super(builder.getId().toString(), builder.getPeerAddresses(),
221 Optional.of(builder.getDatastoreContext().getShardRaftConfig()), DataStoreVersions.CURRENT_VERSION);
223 this.name = builder.getId().toString();
224 this.shardName = builder.getId().getShardName();
225 this.datastoreContext = builder.getDatastoreContext();
226 this.restoreFromSnapshot = builder.getRestoreFromSnapshot();
227 this.frontendMetadata = new FrontendMetadata(name);
228 this.exportOnRecovery = datastoreContext.getExportOnRecovery();
230 switch (exportOnRecovery) {
232 exportActor = getContext().actorOf(JsonExportActor.props(builder.getSchemaContext(),
233 datastoreContext.getRecoveryExportBaseDir()));
241 setPersistence(datastoreContext.isPersistent());
243 LOG.info("Shard created : {}, persistent : {}", name, datastoreContext.isPersistent());
245 ShardDataTreeChangeListenerPublisherActorProxy treeChangeListenerPublisher =
246 new ShardDataTreeChangeListenerPublisherActorProxy(getContext(), name + "-DTCL-publisher", name);
247 if (builder.getDataTree() != null) {
248 store = new ShardDataTree(this, builder.getSchemaContext(), builder.getDataTree(),
249 treeChangeListenerPublisher, name,
252 store = new ShardDataTree(this, builder.getSchemaContext(), builder.getTreeType(),
253 builder.getDatastoreContext().getStoreRoot(), treeChangeListenerPublisher, name,
257 shardMBean = ShardStats.create(name, datastoreContext.getDataStoreMXBeanType(), this);
259 if (isMetricsCaptureEnabled()) {
260 getContext().become(new MeteringBehavior(this));
263 commitCoordinator = new ShardCommitCoordinator(store, LOG, this.name);
265 setTransactionCommitTimeout();
267 // create a notifier actor for each cluster member
268 roleChangeNotifier = createRoleChangeNotifier(name);
270 appendEntriesReplyTracker = new MessageTracker(AppendEntriesReply.class,
271 getRaftActorContext().getConfigParams().getIsolatedCheckIntervalInMillis());
273 dispatchers = new Dispatchers(context().system().dispatchers());
274 transactionActorFactory = new ShardTransactionActorFactory(store, datastoreContext,
275 dispatchers.getDispatcherPath(Dispatchers.DispatcherType.Transaction),
276 self(), getContext(), shardMBean, builder.getId().getShardName());
278 snapshotCohort = ShardSnapshotCohort.create(getContext(), builder.getId().getMemberName(), store, LOG,
279 this.name, datastoreContext);
281 messageRetrySupport = new ShardTransactionMessageRetrySupport(this);
283 responseMessageSlicer = MessageSlicer.builder().logContext(this.name)
284 .messageSliceSize(datastoreContext.getMaximumMessageSliceSize())
285 .fileBackedStreamFactory(getRaftActorContext().getFileBackedOutputStreamFactory())
286 .expireStateAfterInactivity(2, TimeUnit.MINUTES).build();
288 requestMessageAssembler = MessageAssembler.builder().logContext(this.name)
289 .fileBackedStreamFactory(getRaftActorContext().getFileBackedOutputStreamFactory())
290 .assembledMessageCallback((message, sender) -> self().tell(message, sender))
291 .expireStateAfterInactivity(datastoreContext.getRequestTimeout(), TimeUnit.NANOSECONDS).build();
293 listenerInfoMXBean = new ShardDataTreeListenerInfoMXBeanImpl(name, datastoreContext.getDataStoreMXBeanType(),
295 listenerInfoMXBean.register();
298 private void setTransactionCommitTimeout() {
299 transactionCommitTimeout = TimeUnit.MILLISECONDS.convert(
300 datastoreContext.getShardTransactionCommitTimeoutInSeconds(), TimeUnit.SECONDS) / 2;
303 private Optional<ActorRef> createRoleChangeNotifier(final String shardId) {
304 ActorRef shardRoleChangeNotifier = this.getContext().actorOf(
305 RoleChangeNotifier.getProps(shardId), shardId + "-notifier");
306 return Optional.of(shardRoleChangeNotifier);
310 public final void postStop() throws Exception {
311 LOG.info("Stopping Shard {}", persistenceId());
315 messageRetrySupport.close();
317 if (txCommitTimeoutCheckSchedule != null) {
318 txCommitTimeoutCheckSchedule.cancel();
321 commitCoordinator.abortPendingTransactions("Transaction aborted due to shutdown.", this);
323 shardMBean.unregisterMBean();
324 listenerInfoMXBean.unregister();
328 protected final void handleRecover(final Object message) {
329 LOG.debug("{}: onReceiveRecover: Received message {} from {}", persistenceId(), message.getClass(),
332 super.handleRecover(message);
334 switch (exportOnRecovery) {
336 if (message instanceof SnapshotOffer) {
337 exportActor.tell(new JsonExportActor.ExportSnapshot(store.readCurrentData().get(), name),
338 ActorRef.noSender());
339 } else if (message instanceof ReplicatedLogEntry) {
340 exportActor.tell(new JsonExportActor.ExportJournal((ReplicatedLogEntry) message),
341 ActorRef.noSender());
342 } else if (message instanceof RecoveryCompleted) {
343 exportActor.tell(new JsonExportActor.FinishExport(name), ActorRef.noSender());
344 exportActor.tell(PoisonPill.getInstance(), ActorRef.noSender());
352 if (LOG.isTraceEnabled()) {
353 appendEntriesReplyTracker.begin();
358 // non-final for TestShard
359 protected void handleNonRaftCommand(final Object message) {
360 try (MessageTracker.Context context = appendEntriesReplyTracker.received(message)) {
361 final Optional<Error> maybeError = context.error();
362 if (maybeError.isPresent()) {
363 LOG.trace("{} : AppendEntriesReply failed to arrive at the expected interval {}", persistenceId(),
367 store.resetTransactionBatch();
369 if (message instanceof RequestEnvelope) {
370 handleRequestEnvelope((RequestEnvelope)message);
371 } else if (MessageAssembler.isHandledMessage(message)) {
372 handleRequestAssemblerMessage(message);
373 } else if (message instanceof ConnectClientRequest) {
374 handleConnectClient((ConnectClientRequest)message);
375 } else if (CreateTransaction.isSerializedType(message)) {
376 handleCreateTransaction(message);
377 } else if (message instanceof BatchedModifications) {
378 handleBatchedModifications((BatchedModifications)message);
379 } else if (message instanceof ForwardedReadyTransaction) {
380 handleForwardedReadyTransaction((ForwardedReadyTransaction) message);
381 } else if (message instanceof ReadyLocalTransaction) {
382 handleReadyLocalTransaction((ReadyLocalTransaction)message);
383 } else if (CanCommitTransaction.isSerializedType(message)) {
384 handleCanCommitTransaction(CanCommitTransaction.fromSerializable(message));
385 } else if (CommitTransaction.isSerializedType(message)) {
386 handleCommitTransaction(CommitTransaction.fromSerializable(message));
387 } else if (AbortTransaction.isSerializedType(message)) {
388 handleAbortTransaction(AbortTransaction.fromSerializable(message));
389 } else if (CloseTransactionChain.isSerializedType(message)) {
390 closeTransactionChain(CloseTransactionChain.fromSerializable(message));
391 } else if (message instanceof RegisterDataTreeChangeListener) {
392 treeChangeSupport.onMessage((RegisterDataTreeChangeListener) message, isLeader(), hasLeader());
393 } else if (message instanceof UpdateSchemaContext) {
394 updateSchemaContext((UpdateSchemaContext) message);
395 } else if (message instanceof PeerAddressResolved) {
396 PeerAddressResolved resolved = (PeerAddressResolved) message;
397 setPeerAddress(resolved.getPeerId(), resolved.getPeerAddress());
398 } else if (TX_COMMIT_TIMEOUT_CHECK_MESSAGE.equals(message)) {
399 commitTimeoutCheck();
400 } else if (message instanceof DatastoreContext) {
401 onDatastoreContext((DatastoreContext)message);
402 } else if (message instanceof RegisterRoleChangeListener) {
403 roleChangeNotifier.get().forward(message, context());
404 } else if (message instanceof FollowerInitialSyncUpStatus) {
405 shardMBean.setFollowerInitialSyncStatus(((FollowerInitialSyncUpStatus) message).isInitialSyncDone());
406 context().parent().tell(message, self());
407 } else if (GET_SHARD_MBEAN_MESSAGE.equals(message)) {
408 sender().tell(getShardMBean(), self());
409 } else if (message instanceof GetShardDataTree) {
410 sender().tell(store.getDataTree(), self());
411 } else if (message instanceof ServerRemoved) {
412 context().parent().forward(message, context());
413 } else if (ShardTransactionMessageRetrySupport.TIMER_MESSAGE_CLASS.isInstance(message)) {
414 messageRetrySupport.onTimerMessage(message);
415 } else if (message instanceof DataTreeCohortActorRegistry.CohortRegistryCommand) {
416 store.processCohortRegistryCommand(getSender(),
417 (DataTreeCohortActorRegistry.CohortRegistryCommand) message);
418 } else if (message instanceof MakeLeaderLocal) {
420 } else if (RESUME_NEXT_PENDING_TRANSACTION.equals(message)) {
421 store.resumeNextPendingTransaction();
422 } else if (GetKnownClients.INSTANCE.equals(message)) {
423 handleGetKnownClients();
424 } else if (!responseMessageSlicer.handleMessage(message)) {
425 super.handleNonRaftCommand(message);
430 private void handleRequestAssemblerMessage(final Object message) {
431 dispatchers.getDispatcher(DispatcherType.Serialization).execute(() -> {
432 JavaSerializer.currentSystem().value_$eq((ExtendedActorSystem) context().system());
433 requestMessageAssembler.handleMessage(message, self());
437 @SuppressWarnings("checkstyle:IllegalCatch")
438 private void handleRequestEnvelope(final RequestEnvelope envelope) {
439 final long now = ticker().read();
441 final RequestSuccess<?, ?> success = handleRequest(envelope, now);
442 if (success != null) {
443 final long executionTimeNanos = ticker().read() - now;
444 if (success instanceof SliceableMessage) {
445 dispatchers.getDispatcher(DispatcherType.Serialization).execute(() ->
446 responseMessageSlicer.slice(SliceOptions.builder().identifier(success.getTarget())
447 .message(envelope.newSuccessEnvelope(success, executionTimeNanos))
448 .sendTo(envelope.getMessage().getReplyTo()).replyTo(self())
449 .onFailureCallback(t -> LOG.warn("Error slicing response {}", success, t)).build()));
451 envelope.sendSuccess(success, executionTimeNanos);
454 } catch (RequestException e) {
455 LOG.debug("{}: request {} failed", persistenceId(), envelope, e);
456 envelope.sendFailure(e, ticker().read() - now);
457 } catch (Exception e) {
458 LOG.debug("{}: request {} caused failure", persistenceId(), envelope, e);
459 envelope.sendFailure(new RuntimeRequestException("Request failed to process", e),
460 ticker().read() - now);
464 private void commitTimeoutCheck() {
465 store.checkForExpiredTransactions(transactionCommitTimeout, this::updateAccess);
466 commitCoordinator.checkForExpiredTransactions(transactionCommitTimeout, this);
467 requestMessageAssembler.checkExpiredAssembledMessageState();
470 private OptionalLong updateAccess(final SimpleShardDataTreeCohort cohort) {
471 final FrontendIdentifier frontend = cohort.getIdentifier().getHistoryId().getClientId().getFrontendId();
472 final LeaderFrontendState state = knownFrontends.get(frontend);
474 // Not tell-based protocol, do nothing
475 return OptionalLong.empty();
478 if (isIsolatedLeader()) {
479 // We are isolated and no new request can come through until we emerge from it. We are still updating
480 // liveness of frontend when we see it attempting to communicate. Use the last access timer.
481 return OptionalLong.of(state.getLastSeenTicks());
484 // If this frontend has freshly connected, give it some time to catch up before killing its transactions.
485 return OptionalLong.of(state.getLastConnectTicks());
488 private void disableTracking(final DisableTrackingPayload payload) {
489 final ClientIdentifier clientId = payload.getIdentifier();
490 LOG.debug("{}: disabling tracking of {}", persistenceId(), clientId);
491 frontendMetadata.disableTracking(clientId);
494 final FrontendIdentifier frontendId = clientId.getFrontendId();
495 final LeaderFrontendState frontend = knownFrontends.get(frontendId);
496 if (frontend != null) {
497 if (clientId.equals(frontend.getIdentifier())) {
498 if (!(frontend instanceof LeaderFrontendState.Disabled)) {
499 verify(knownFrontends.replace(frontendId, frontend,
500 new LeaderFrontendState.Disabled(persistenceId(), clientId, store)));
501 LOG.debug("{}: leader state for {} disabled", persistenceId(), clientId);
503 LOG.debug("{}: leader state {} is already disabled", persistenceId(), frontend);
506 LOG.debug("{}: leader state {} does not match {}", persistenceId(), frontend, clientId);
509 LOG.debug("{}: leader state for {} not found", persistenceId(), clientId);
510 knownFrontends.put(frontendId, new LeaderFrontendState.Disabled(persistenceId(), clientId,
516 private void onMakeLeaderLocal() {
517 LOG.debug("{}: onMakeLeaderLocal received", persistenceId());
519 getSender().tell(new Status.Success(null), getSelf());
523 final ActorSelection leader = getLeader();
525 if (leader == null) {
526 // Leader is not present. The cluster is most likely trying to
527 // elect a leader and we should let that run its normal course
529 // TODO we can wait for the election to complete and retry the
530 // request. We can also let the caller retry by sending a flag
531 // in the response indicating the request is "reTryable".
532 getSender().tell(new Failure(
533 new LeadershipTransferFailedException("We cannot initiate leadership transfer to local node. "
534 + "Currently there is no leader for " + persistenceId())),
539 leader.tell(new RequestLeadership(getId(), getSender()), getSelf());
542 // Acquire our frontend tracking handle and verify generation matches
543 private @Nullable LeaderFrontendState findFrontend(final ClientIdentifier clientId) throws RequestException {
544 final LeaderFrontendState existing = knownFrontends.get(clientId.getFrontendId());
545 if (existing != null) {
546 final int cmp = Long.compareUnsigned(existing.getIdentifier().getGeneration(), clientId.getGeneration());
552 LOG.debug("{}: rejecting request from outdated client {}", persistenceId(), clientId);
553 throw new RetiredGenerationException(clientId.getGeneration(),
554 existing.getIdentifier().getGeneration());
557 LOG.info("{}: retiring state {}, outdated by request from client {}", persistenceId(), existing, clientId);
559 knownFrontends.remove(clientId.getFrontendId());
561 LOG.debug("{}: client {} is not yet known", persistenceId(), clientId);
567 private LeaderFrontendState getFrontend(final ClientIdentifier clientId) throws RequestException {
568 final LeaderFrontendState ret = findFrontend(clientId);
573 // TODO: a dedicated exception would be better, but this is technically true, too
574 throw new OutOfSequenceEnvelopeException(0);
577 private static @NonNull ABIVersion selectVersion(final ConnectClientRequest message) {
578 final Range<ABIVersion> clientRange = Range.closed(message.getMinVersion(), message.getMaxVersion());
579 for (ABIVersion v : SUPPORTED_ABIVERSIONS) {
580 if (clientRange.contains(v)) {
585 throw new IllegalArgumentException(String.format(
586 "No common version between backend versions %s and client versions %s", SUPPORTED_ABIVERSIONS,
590 @SuppressWarnings("checkstyle:IllegalCatch")
591 private void handleConnectClient(final ConnectClientRequest message) {
593 final ClientIdentifier clientId = message.getTarget();
594 final LeaderFrontendState existing = findFrontend(clientId);
595 if (existing != null) {
599 if (!isLeader() || !isLeaderActive()) {
600 LOG.info("{}: not currently leader, rejecting request {}. isLeader: {}, isLeaderActive: {},"
601 + "isLeadershipTransferInProgress: {}.",
602 persistenceId(), message, isLeader(), isLeaderActive(), isLeadershipTransferInProgress());
603 throw new NotLeaderException(getSelf());
606 final ABIVersion selectedVersion = selectVersion(message);
607 final LeaderFrontendState frontend;
608 if (existing == null) {
609 frontend = new LeaderFrontendState.Enabled(persistenceId(), clientId, store);
610 knownFrontends.put(clientId.getFrontendId(), frontend);
611 LOG.debug("{}: created state {} for client {}", persistenceId(), frontend, clientId);
616 frontend.reconnect();
617 message.getReplyTo().tell(new ConnectClientSuccess(message.getTarget(), message.getSequence(), getSelf(),
618 ImmutableList.of(), store.getDataTree(), CLIENT_MAX_MESSAGES).toVersion(selectedVersion),
619 ActorRef.noSender());
620 } catch (RequestException | RuntimeException e) {
621 message.getReplyTo().tell(new Failure(e), ActorRef.noSender());
625 private @Nullable RequestSuccess<?, ?> handleRequest(final RequestEnvelope envelope, final long now)
626 throws RequestException {
627 // We are not the leader, hence we want to fail-fast.
628 if (!isLeader() || paused || !isLeaderActive()) {
629 LOG.debug("{}: not currently active leader, rejecting request {}. isLeader: {}, isLeaderActive: {},"
630 + "isLeadershipTransferInProgress: {}, paused: {}",
631 persistenceId(), envelope, isLeader(), isLeaderActive(), isLeadershipTransferInProgress(), paused);
632 throw new NotLeaderException(getSelf());
635 final Request<?, ?> request = envelope.getMessage();
636 if (request instanceof TransactionRequest) {
637 final TransactionRequest<?> txReq = (TransactionRequest<?>)request;
638 final ClientIdentifier clientId = txReq.getTarget().getHistoryId().getClientId();
639 return getFrontend(clientId).handleTransactionRequest(txReq, envelope, now);
640 } else if (request instanceof LocalHistoryRequest) {
641 final LocalHistoryRequest<?> lhReq = (LocalHistoryRequest<?>)request;
642 final ClientIdentifier clientId = lhReq.getTarget().getClientId();
643 return getFrontend(clientId).handleLocalHistoryRequest(lhReq, envelope, now);
645 LOG.warn("{}: rejecting unsupported request {}", persistenceId(), request);
646 throw new UnsupportedRequestException(request);
650 private void handleGetKnownClients() {
651 final ImmutableSet<ClientIdentifier> clients;
653 clients = knownFrontends.values().stream()
654 .map(LeaderFrontendState::getIdentifier)
655 .collect(ImmutableSet.toImmutableSet());
657 clients = frontendMetadata.getClients();
659 sender().tell(new GetKnownClientsReply(clients), self());
662 private boolean hasLeader() {
663 return getLeaderId() != null;
666 final int getPendingTxCommitQueueSize() {
667 return store.getQueueSize();
670 final int getCohortCacheSize() {
671 return commitCoordinator.getCohortCacheSize();
675 protected final Optional<ActorRef> getRoleChangeNotifier() {
676 return roleChangeNotifier;
679 final String getShardName() {
684 protected final LeaderStateChanged newLeaderStateChanged(final String memberId, final String leaderId,
685 final short leaderPayloadVersion) {
686 return isLeader() ? new ShardLeaderStateChanged(memberId, leaderId, store.getDataTree(), leaderPayloadVersion)
687 : new ShardLeaderStateChanged(memberId, leaderId, leaderPayloadVersion);
690 private void onDatastoreContext(final DatastoreContext context) {
691 datastoreContext = verifyNotNull(context);
693 setTransactionCommitTimeout();
695 setPersistence(datastoreContext.isPersistent());
697 updateConfigParams(datastoreContext.getShardRaftConfig());
700 // applyState() will be invoked once consensus is reached on the payload
701 // non-final for mocking
702 void persistPayload(final Identifier id, final Payload payload, final boolean batchHint) {
703 final boolean canSkipPayload = !hasFollowers() && !persistence().isRecoveryApplicable();
704 if (canSkipPayload) {
705 applyState(self(), id, payload);
707 // We are faking the sender
708 persistData(self(), id, payload, batchHint);
712 private void handleCommitTransaction(final CommitTransaction commit) {
713 final TransactionIdentifier txId = commit.getTransactionId();
715 askProtocolEncountered(txId);
716 commitCoordinator.handleCommit(txId, getSender(), this);
718 ActorSelection leader = getLeader();
719 if (leader == null) {
720 messageRetrySupport.addMessageToRetry(commit, getSender(), "Could not commit transaction " + txId);
722 LOG.debug("{}: Forwarding CommitTransaction to leader {}", persistenceId(), leader);
723 leader.forward(commit, getContext());
728 private void handleCanCommitTransaction(final CanCommitTransaction canCommit) {
729 final TransactionIdentifier txId = canCommit.getTransactionId();
730 LOG.debug("{}: Can committing transaction {}", persistenceId(), txId);
733 askProtocolEncountered(txId);
734 commitCoordinator.handleCanCommit(txId, getSender(), this);
736 ActorSelection leader = getLeader();
737 if (leader == null) {
738 messageRetrySupport.addMessageToRetry(canCommit, getSender(),
739 "Could not canCommit transaction " + txId);
741 LOG.debug("{}: Forwarding CanCommitTransaction to leader {}", persistenceId(), leader);
742 leader.forward(canCommit, getContext());
747 @SuppressWarnings("checkstyle:IllegalCatch")
748 private void handleBatchedModificationsLocal(final BatchedModifications batched, final ActorRef sender) {
749 askProtocolEncountered(batched.getTransactionId());
752 commitCoordinator.handleBatchedModifications(batched, sender, this);
753 } catch (Exception e) {
754 LOG.error("{}: Error handling BatchedModifications for Tx {}", persistenceId(),
755 batched.getTransactionId(), e);
756 sender.tell(new Failure(e), getSelf());
760 private void handleBatchedModifications(final BatchedModifications batched) {
761 // This message is sent to prepare the modifications transaction directly on the Shard as an
762 // optimization to avoid the extra overhead of a separate ShardTransaction actor. On the last
763 // BatchedModifications message, the caller sets the ready flag in the message indicating
764 // modifications are complete. The reply contains the cohort actor path (this actor) for the caller
765 // to initiate the 3-phase commit. This also avoids the overhead of sending an additional
766 // ReadyTransaction message.
768 // If we're not the leader then forward to the leader. This is a safety measure - we shouldn't
769 // normally get here if we're not the leader as the front-end (TransactionProxy) should determine
770 // the primary/leader shard. However with timing and caching on the front-end, there's a small
771 // window where it could have a stale leader during leadership transitions.
773 boolean isLeaderActive = isLeaderActive();
774 if (isLeader() && isLeaderActive) {
775 handleBatchedModificationsLocal(batched, getSender());
777 ActorSelection leader = getLeader();
778 if (!isLeaderActive || leader == null) {
779 messageRetrySupport.addMessageToRetry(batched, getSender(),
780 "Could not process BatchedModifications " + batched.getTransactionId());
782 // If this is not the first batch and leadership changed in between batched messages,
783 // we need to reconstruct previous BatchedModifications from the transaction
784 // DataTreeModification, honoring the max batched modification count, and forward all the
785 // previous BatchedModifications to the new leader.
786 Collection<BatchedModifications> newModifications = commitCoordinator
787 .createForwardedBatchedModifications(batched,
788 datastoreContext.getShardBatchedModificationCount());
790 LOG.debug("{}: Forwarding {} BatchedModifications to leader {}", persistenceId(),
791 newModifications.size(), leader);
793 for (BatchedModifications bm : newModifications) {
794 leader.forward(bm, getContext());
800 private boolean failIfIsolatedLeader(final ActorRef sender) {
801 if (isIsolatedLeader()) {
802 sender.tell(new Failure(new NoShardLeaderException(String.format(
803 "Shard %s was the leader but has lost contact with all of its followers. Either all"
804 + " other follower nodes are down or this node is isolated by a network partition.",
805 persistenceId()))), getSelf());
812 protected boolean isIsolatedLeader() {
813 return getRaftState() == RaftState.IsolatedLeader;
816 @SuppressWarnings("checkstyle:IllegalCatch")
817 private void handleReadyLocalTransaction(final ReadyLocalTransaction message) {
818 LOG.debug("{}: handleReadyLocalTransaction for {}", persistenceId(), message.getTransactionId());
820 boolean isLeaderActive = isLeaderActive();
821 if (isLeader() && isLeaderActive) {
823 commitCoordinator.handleReadyLocalTransaction(message, getSender(), this);
824 } catch (Exception e) {
825 LOG.error("{}: Error handling ReadyLocalTransaction for Tx {}", persistenceId(),
826 message.getTransactionId(), e);
827 getSender().tell(new Failure(e), getSelf());
830 ActorSelection leader = getLeader();
831 if (!isLeaderActive || leader == null) {
832 messageRetrySupport.addMessageToRetry(message, getSender(),
833 "Could not process ready local transaction " + message.getTransactionId());
835 LOG.debug("{}: Forwarding ReadyLocalTransaction to leader {}", persistenceId(), leader);
836 message.setRemoteVersion(getCurrentBehavior().getLeaderPayloadVersion());
837 leader.forward(message, getContext());
842 private void handleForwardedReadyTransaction(final ForwardedReadyTransaction forwardedReady) {
843 LOG.debug("{}: handleForwardedReadyTransaction for {}", persistenceId(), forwardedReady.getTransactionId());
845 boolean isLeaderActive = isLeaderActive();
846 if (isLeader() && isLeaderActive) {
847 askProtocolEncountered(forwardedReady.getTransactionId());
848 commitCoordinator.handleForwardedReadyTransaction(forwardedReady, getSender(), this);
850 ActorSelection leader = getLeader();
851 if (!isLeaderActive || leader == null) {
852 messageRetrySupport.addMessageToRetry(forwardedReady, getSender(),
853 "Could not process forwarded ready transaction " + forwardedReady.getTransactionId());
855 LOG.debug("{}: Forwarding ForwardedReadyTransaction to leader {}", persistenceId(), leader);
857 ReadyLocalTransaction readyLocal = new ReadyLocalTransaction(forwardedReady.getTransactionId(),
858 forwardedReady.getTransaction().getSnapshot(), forwardedReady.isDoImmediateCommit(),
859 forwardedReady.getParticipatingShardNames());
860 readyLocal.setRemoteVersion(getCurrentBehavior().getLeaderPayloadVersion());
861 leader.forward(readyLocal, getContext());
866 private void handleAbortTransaction(final AbortTransaction abort) {
867 final TransactionIdentifier transactionId = abort.getTransactionId();
868 askProtocolEncountered(transactionId);
869 doAbortTransaction(transactionId, getSender());
872 final void doAbortTransaction(final Identifier transactionID, final ActorRef sender) {
873 commitCoordinator.handleAbort(transactionID, sender, this);
876 private void handleCreateTransaction(final Object message) {
878 createTransaction(CreateTransaction.fromSerializable(message));
879 } else if (getLeader() != null) {
880 getLeader().forward(message, getContext());
882 getSender().tell(new Failure(new NoShardLeaderException(
883 "Could not create a shard transaction", persistenceId())), getSelf());
887 private void closeTransactionChain(final CloseTransactionChain closeTransactionChain) {
889 final LocalHistoryIdentifier id = closeTransactionChain.getIdentifier();
890 askProtocolEncountered(id.getClientId());
891 store.closeTransactionChain(id);
892 } else if (getLeader() != null) {
893 getLeader().forward(closeTransactionChain, getContext());
895 LOG.warn("{}: Could not close transaction {}", persistenceId(), closeTransactionChain.getIdentifier());
899 @SuppressWarnings("checkstyle:IllegalCatch")
900 private void createTransaction(final CreateTransaction createTransaction) {
901 askProtocolEncountered(createTransaction.getTransactionId());
904 if (TransactionType.fromInt(createTransaction.getTransactionType()) != TransactionType.READ_ONLY
905 && failIfIsolatedLeader(getSender())) {
909 ActorRef transactionActor = createTransaction(createTransaction.getTransactionType(),
910 createTransaction.getTransactionId());
912 getSender().tell(new CreateTransactionReply(Serialization.serializedActorPath(transactionActor),
913 createTransaction.getTransactionId(), createTransaction.getVersion()).toSerializable(), getSelf());
914 } catch (Exception e) {
915 getSender().tell(new Failure(e), getSelf());
919 private ActorRef createTransaction(final int transactionType, final TransactionIdentifier transactionId) {
920 LOG.debug("{}: Creating transaction : {} ", persistenceId(), transactionId);
921 return transactionActorFactory.newShardTransaction(TransactionType.fromInt(transactionType),
925 // Called on leader only
926 private void askProtocolEncountered(final TransactionIdentifier transactionId) {
927 askProtocolEncountered(transactionId.getHistoryId().getClientId());
930 // Called on leader only
931 private void askProtocolEncountered(final ClientIdentifier clientId) {
932 final FrontendIdentifier frontend = clientId.getFrontendId();
933 final LeaderFrontendState state = knownFrontends.get(frontend);
934 if (!(state instanceof LeaderFrontendState.Disabled)) {
935 LOG.debug("{}: encountered ask-based client {}, disabling transaction tracking", persistenceId(), clientId);
936 if (knownFrontends.isEmpty()) {
937 knownFrontends = new HashMap<>();
939 knownFrontends.put(frontend, new LeaderFrontendState.Disabled(persistenceId(), clientId, getDataStore()));
941 persistPayload(clientId, DisableTrackingPayload.create(clientId,
942 datastoreContext.getInitialPayloadSerializedBufferCapacity()), false);
946 private void updateSchemaContext(final UpdateSchemaContext message) {
947 updateSchemaContext(message.getEffectiveModelContext());
951 void updateSchemaContext(final @NonNull EffectiveModelContext schemaContext) {
952 store.updateSchemaContext(schemaContext);
955 private boolean isMetricsCaptureEnabled() {
956 CommonConfig config = new CommonConfig(getContext().system().settings().config());
957 return config.isMetricCaptureEnabled();
961 protected final RaftActorSnapshotCohort getRaftActorSnapshotCohort() {
962 return snapshotCohort;
966 protected final RaftActorRecoveryCohort getRaftActorRecoveryCohort() {
967 if (restoreFromSnapshot == null) {
968 return ShardRecoveryCoordinator.create(store, persistenceId(), LOG);
971 return ShardRecoveryCoordinator.forSnapshot(store, persistenceId(), LOG, restoreFromSnapshot.getSnapshot());
975 // non-final for testing
976 protected void onRecoveryComplete() {
977 restoreFromSnapshot = null;
979 //notify shard manager
980 getContext().parent().tell(new ActorInitialized(), getSelf());
982 // Being paranoid here - this method should only be called once but just in case...
983 if (txCommitTimeoutCheckSchedule == null) {
984 // Schedule a message to be periodically sent to check if the current in-progress
985 // transaction should be expired and aborted.
986 FiniteDuration period = FiniteDuration.create(transactionCommitTimeout / 3, TimeUnit.MILLISECONDS);
987 txCommitTimeoutCheckSchedule = getContext().system().scheduler().schedule(
988 period, period, getSelf(),
989 TX_COMMIT_TIMEOUT_CHECK_MESSAGE, getContext().dispatcher(), ActorRef.noSender());
994 protected final void applyState(final ActorRef clientActor, final Identifier identifier, final Object data) {
995 if (data instanceof Payload) {
996 if (data instanceof DisableTrackingPayload) {
997 disableTracking((DisableTrackingPayload) data);
1002 store.applyReplicatedPayload(identifier, (Payload)data);
1003 } catch (DataValidationFailedException | IOException e) {
1004 LOG.error("{}: Error applying replica {}", persistenceId(), identifier, e);
1007 LOG.error("{}: Unknown state for {} received {}", persistenceId(), identifier, data);
1012 protected final void onStateChanged() {
1013 boolean isLeader = isLeader();
1014 boolean hasLeader = hasLeader();
1015 treeChangeSupport.onLeadershipChange(isLeader, hasLeader);
1017 // If this actor is no longer the leader close all the transaction chains
1019 if (LOG.isDebugEnabled()) {
1021 "{}: onStateChanged: Closing all transaction chains because shard {} is no longer the leader",
1022 persistenceId(), getId());
1026 store.purgeLeaderState();
1029 if (hasLeader && !isIsolatedLeader()) {
1030 messageRetrySupport.retryMessages();
1035 protected final void onLeaderChanged(final String oldLeader, final String newLeader) {
1036 shardMBean.incrementLeadershipChangeCount();
1040 if (!knownFrontends.isEmpty()) {
1041 LOG.debug("{}: removing frontend state for {}", persistenceId(), knownFrontends.keySet());
1042 knownFrontends = ImmutableMap.of();
1045 requestMessageAssembler.close();
1048 // No leader anywhere, nothing else to do
1052 // Another leader was elected. If we were the previous leader and had pending transactions, convert
1053 // them to transaction messages and send to the new leader.
1054 ActorSelection leader = getLeader();
1055 if (leader != null) {
1056 // Clears all pending transactions and converts them to messages to be forwarded to a new leader.
1057 Collection<?> messagesToForward = commitCoordinator.convertPendingTransactionsToMessages(
1058 datastoreContext.getShardBatchedModificationCount());
1060 if (!messagesToForward.isEmpty()) {
1061 LOG.debug("{}: Forwarding {} pending transaction messages to leader {}", persistenceId(),
1062 messagesToForward.size(), leader);
1064 for (Object message : messagesToForward) {
1065 LOG.debug("{}: Forwarding pending transaction message {}", persistenceId(), message);
1067 leader.tell(message, self());
1071 commitCoordinator.abortPendingTransactions("The transacton was aborted due to inflight leadership "
1072 + "change and the leader address isn't available.", this);
1075 // We have become the leader, we need to reconstruct frontend state
1076 knownFrontends = verifyNotNull(frontendMetadata.toLeaderState(this));
1077 LOG.debug("{}: became leader with frontend state for {}", persistenceId(), knownFrontends.keySet());
1080 if (!isIsolatedLeader()) {
1081 messageRetrySupport.retryMessages();
1086 protected final void pauseLeader(final Runnable operation) {
1087 LOG.debug("{}: In pauseLeader, operation: {}", persistenceId(), operation);
1090 // Tell-based protocol can replay transaction state, so it is safe to blow it up when we are paused.
1091 if (datastoreContext.isUseTellBasedProtocol()) {
1092 knownFrontends.values().forEach(LeaderFrontendState::retire);
1093 knownFrontends = ImmutableMap.of();
1096 store.setRunOnPendingTransactionsComplete(operation);
1100 protected final void unpauseLeader() {
1101 LOG.debug("{}: In unpauseLeader", persistenceId());
1104 store.setRunOnPendingTransactionsComplete(null);
1106 // Restore tell-based protocol state as if we were becoming the leader
1107 knownFrontends = verifyNotNull(frontendMetadata.toLeaderState(this));
1111 protected final OnDemandRaftState.AbstractBuilder<?, ?> newOnDemandRaftStateBuilder() {
1112 return OnDemandShardState.newBuilder()
1113 .treeChangeListenerActors(treeChangeSupport.getListenerActors())
1114 .commitCohortActors(store.getCohortActors());
1118 public final String persistenceId() {
1123 public final String journalPluginId() {
1124 // This method may be invoked from super constructor (wonderful), hence we also need to handle the case of
1125 // the field being uninitialized because our constructor is not finished.
1126 if (datastoreContext != null && !datastoreContext.isPersistent()) {
1127 return NON_PERSISTENT_JOURNAL_ID;
1129 return super.journalPluginId();
1133 final ShardCommitCoordinator getCommitCoordinator() {
1134 return commitCoordinator;
1137 // non-final for mocking
1138 DatastoreContext getDatastoreContext() {
1139 return datastoreContext;
1143 final ShardDataTree getDataStore() {
1148 // non-final for mocking
1149 ShardStats getShardMBean() {
1153 public static Builder builder() {
1154 return new Builder();
1157 public abstract static class AbstractBuilder<T extends AbstractBuilder<T, S>, S extends Shard> {
1158 private final Class<? extends S> shardClass;
1159 private ShardIdentifier id;
1160 private Map<String, String> peerAddresses = Collections.emptyMap();
1161 private DatastoreContext datastoreContext;
1162 private EffectiveModelContextProvider schemaContextProvider;
1163 private DatastoreSnapshot.ShardSnapshot restoreFromSnapshot;
1164 private DataTree dataTree;
1166 private volatile boolean sealed;
1168 AbstractBuilder(final Class<? extends S> shardClass) {
1169 this.shardClass = shardClass;
1172 final void checkSealed() {
1173 checkState(!sealed, "Builder is already sealed - further modifications are not allowed");
1176 @SuppressWarnings("unchecked")
1181 public T id(final ShardIdentifier newId) {
1187 public T peerAddresses(final Map<String, String> newPeerAddresses) {
1189 this.peerAddresses = newPeerAddresses;
1193 public T datastoreContext(final DatastoreContext newDatastoreContext) {
1195 this.datastoreContext = newDatastoreContext;
1199 public T schemaContextProvider(final EffectiveModelContextProvider newSchemaContextProvider) {
1201 this.schemaContextProvider = requireNonNull(newSchemaContextProvider);
1205 public T restoreFromSnapshot(final DatastoreSnapshot.ShardSnapshot newRestoreFromSnapshot) {
1207 this.restoreFromSnapshot = newRestoreFromSnapshot;
1211 public T dataTree(final DataTree newDataTree) {
1213 this.dataTree = newDataTree;
1217 public ShardIdentifier getId() {
1221 public Map<String, String> getPeerAddresses() {
1222 return peerAddresses;
1225 public DatastoreContext getDatastoreContext() {
1226 return datastoreContext;
1229 public EffectiveModelContext getSchemaContext() {
1230 return verifyNotNull(schemaContextProvider.getEffectiveModelContext());
1233 public DatastoreSnapshot.ShardSnapshot getRestoreFromSnapshot() {
1234 return restoreFromSnapshot;
1237 public DataTree getDataTree() {
1241 public TreeType getTreeType() {
1242 switch (datastoreContext.getLogicalStoreType()) {
1244 return TreeType.CONFIGURATION;
1246 return TreeType.OPERATIONAL;
1248 throw new IllegalStateException("Unhandled logical store type "
1249 + datastoreContext.getLogicalStoreType());
1253 protected void verify() {
1254 requireNonNull(id, "id should not be null");
1255 requireNonNull(peerAddresses, "peerAddresses should not be null");
1256 requireNonNull(datastoreContext, "dataStoreContext should not be null");
1257 requireNonNull(schemaContextProvider, "schemaContextProvider should not be null");
1260 public Props props() {
1263 return Props.create(shardClass, this);
1267 public static class Builder extends AbstractBuilder<Builder, Shard> {
1272 Builder(final Class<? extends Shard> shardClass) {
1278 return Ticker.systemTicker();
1281 void scheduleNextPendingTransaction() {
1282 self().tell(RESUME_NEXT_PENDING_TRANSACTION, ActorRef.noSender());