Simplify code using Java 8 features
[controller.git] / opendaylight / md-sal / sal-distributed-datastore / src / main / java / org / opendaylight / controller / cluster / datastore / Shard.java
1 /*
2  * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
3  *
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
7  */
8
9 package org.opendaylight.controller.cluster.datastore;
10
11 import akka.actor.ActorRef;
12 import akka.actor.ActorSelection;
13 import akka.actor.Cancellable;
14 import akka.actor.ExtendedActorSystem;
15 import akka.actor.Props;
16 import akka.actor.Status;
17 import akka.actor.Status.Failure;
18 import akka.serialization.JavaSerializer;
19 import akka.serialization.Serialization;
20 import com.google.common.annotations.VisibleForTesting;
21 import com.google.common.base.Optional;
22 import com.google.common.base.Preconditions;
23 import com.google.common.base.Ticker;
24 import com.google.common.base.Verify;
25 import com.google.common.collect.ImmutableList;
26 import com.google.common.collect.ImmutableMap;
27 import com.google.common.collect.Range;
28 import java.io.IOException;
29 import java.util.Arrays;
30 import java.util.Collection;
31 import java.util.Collections;
32 import java.util.Map;
33 import java.util.concurrent.TimeUnit;
34 import javax.annotation.Nonnull;
35 import javax.annotation.Nullable;
36 import org.opendaylight.controller.cluster.access.ABIVersion;
37 import org.opendaylight.controller.cluster.access.commands.ConnectClientRequest;
38 import org.opendaylight.controller.cluster.access.commands.ConnectClientSuccess;
39 import org.opendaylight.controller.cluster.access.commands.LocalHistoryRequest;
40 import org.opendaylight.controller.cluster.access.commands.NotLeaderException;
41 import org.opendaylight.controller.cluster.access.commands.OutOfSequenceEnvelopeException;
42 import org.opendaylight.controller.cluster.access.commands.TransactionRequest;
43 import org.opendaylight.controller.cluster.access.concepts.ClientIdentifier;
44 import org.opendaylight.controller.cluster.access.concepts.FrontendIdentifier;
45 import org.opendaylight.controller.cluster.access.concepts.LocalHistoryIdentifier;
46 import org.opendaylight.controller.cluster.access.concepts.Request;
47 import org.opendaylight.controller.cluster.access.concepts.RequestEnvelope;
48 import org.opendaylight.controller.cluster.access.concepts.RequestException;
49 import org.opendaylight.controller.cluster.access.concepts.RequestSuccess;
50 import org.opendaylight.controller.cluster.access.concepts.RetiredGenerationException;
51 import org.opendaylight.controller.cluster.access.concepts.RuntimeRequestException;
52 import org.opendaylight.controller.cluster.access.concepts.SliceableMessage;
53 import org.opendaylight.controller.cluster.access.concepts.TransactionIdentifier;
54 import org.opendaylight.controller.cluster.access.concepts.UnsupportedRequestException;
55 import org.opendaylight.controller.cluster.common.actor.CommonConfig;
56 import org.opendaylight.controller.cluster.common.actor.Dispatchers;
57 import org.opendaylight.controller.cluster.common.actor.Dispatchers.DispatcherType;
58 import org.opendaylight.controller.cluster.common.actor.MessageTracker;
59 import org.opendaylight.controller.cluster.common.actor.MessageTracker.Error;
60 import org.opendaylight.controller.cluster.common.actor.MeteringBehavior;
61 import org.opendaylight.controller.cluster.datastore.exceptions.NoShardLeaderException;
62 import org.opendaylight.controller.cluster.datastore.identifiers.ShardIdentifier;
63 import org.opendaylight.controller.cluster.datastore.jmx.mbeans.shard.ShardDataTreeListenerInfoMXBeanImpl;
64 import org.opendaylight.controller.cluster.datastore.jmx.mbeans.shard.ShardMBeanFactory;
65 import org.opendaylight.controller.cluster.datastore.jmx.mbeans.shard.ShardStats;
66 import org.opendaylight.controller.cluster.datastore.messages.AbortTransaction;
67 import org.opendaylight.controller.cluster.datastore.messages.ActorInitialized;
68 import org.opendaylight.controller.cluster.datastore.messages.BatchedModifications;
69 import org.opendaylight.controller.cluster.datastore.messages.CanCommitTransaction;
70 import org.opendaylight.controller.cluster.datastore.messages.CloseTransactionChain;
71 import org.opendaylight.controller.cluster.datastore.messages.CommitTransaction;
72 import org.opendaylight.controller.cluster.datastore.messages.CreateTransaction;
73 import org.opendaylight.controller.cluster.datastore.messages.CreateTransactionReply;
74 import org.opendaylight.controller.cluster.datastore.messages.ForwardedReadyTransaction;
75 import org.opendaylight.controller.cluster.datastore.messages.GetShardDataTree;
76 import org.opendaylight.controller.cluster.datastore.messages.MakeLeaderLocal;
77 import org.opendaylight.controller.cluster.datastore.messages.OnDemandShardState;
78 import org.opendaylight.controller.cluster.datastore.messages.PeerAddressResolved;
79 import org.opendaylight.controller.cluster.datastore.messages.PersistAbortTransactionPayload;
80 import org.opendaylight.controller.cluster.datastore.messages.ReadyLocalTransaction;
81 import org.opendaylight.controller.cluster.datastore.messages.RegisterDataTreeChangeListener;
82 import org.opendaylight.controller.cluster.datastore.messages.ShardLeaderStateChanged;
83 import org.opendaylight.controller.cluster.datastore.messages.UpdateSchemaContext;
84 import org.opendaylight.controller.cluster.datastore.persisted.AbortTransactionPayload;
85 import org.opendaylight.controller.cluster.datastore.persisted.DatastoreSnapshot;
86 import org.opendaylight.controller.cluster.datastore.persisted.DatastoreSnapshot.ShardSnapshot;
87 import org.opendaylight.controller.cluster.messaging.MessageAssembler;
88 import org.opendaylight.controller.cluster.messaging.MessageSlicer;
89 import org.opendaylight.controller.cluster.messaging.SliceOptions;
90 import org.opendaylight.controller.cluster.notifications.LeaderStateChanged;
91 import org.opendaylight.controller.cluster.notifications.RegisterRoleChangeListener;
92 import org.opendaylight.controller.cluster.notifications.RoleChangeNotifier;
93 import org.opendaylight.controller.cluster.raft.LeadershipTransferFailedException;
94 import org.opendaylight.controller.cluster.raft.RaftActor;
95 import org.opendaylight.controller.cluster.raft.RaftActorRecoveryCohort;
96 import org.opendaylight.controller.cluster.raft.RaftActorSnapshotCohort;
97 import org.opendaylight.controller.cluster.raft.RaftState;
98 import org.opendaylight.controller.cluster.raft.base.messages.FollowerInitialSyncUpStatus;
99 import org.opendaylight.controller.cluster.raft.client.messages.OnDemandRaftState;
100 import org.opendaylight.controller.cluster.raft.messages.AppendEntriesReply;
101 import org.opendaylight.controller.cluster.raft.messages.RequestLeadership;
102 import org.opendaylight.controller.cluster.raft.messages.ServerRemoved;
103 import org.opendaylight.controller.cluster.raft.protobuff.client.messages.Payload;
104 import org.opendaylight.yangtools.concepts.Identifier;
105 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTree;
106 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataValidationFailedException;
107 import org.opendaylight.yangtools.yang.data.api.schema.tree.TreeType;
108 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
109 import org.opendaylight.yangtools.yang.model.api.SchemaContextProvider;
110 import scala.concurrent.duration.Duration;
111 import scala.concurrent.duration.FiniteDuration;
112
113 /**
114  * A Shard represents a portion of the logical data tree.
115  *
116  * <p>
117  * Our Shard uses InMemoryDataTree as it's internal representation and delegates all requests it
118  */
119 public class Shard extends RaftActor {
120
121     @VisibleForTesting
122     static final Object TX_COMMIT_TIMEOUT_CHECK_MESSAGE = new Object() {
123         @Override
124         public String toString() {
125             return "txCommitTimeoutCheck";
126         }
127     };
128
129     @VisibleForTesting
130     static final Object GET_SHARD_MBEAN_MESSAGE = new Object() {
131         @Override
132         public String toString() {
133             return "getShardMBeanMessage";
134         }
135     };
136
137     static final Object RESUME_NEXT_PENDING_TRANSACTION = new Object() {
138         @Override
139         public String toString() {
140             return "resumeNextPendingTransaction";
141         }
142     };
143
144     // FIXME: shard names should be encapsulated in their own class and this should be exposed as a constant.
145     public static final String DEFAULT_NAME = "default";
146
147     private static final Collection<ABIVersion> SUPPORTED_ABIVERSIONS;
148
149     static {
150         final ABIVersion[] values = ABIVersion.values();
151         final ABIVersion[] real = Arrays.copyOfRange(values, 1, values.length - 1);
152         SUPPORTED_ABIVERSIONS = ImmutableList.copyOf(real).reverse();
153     }
154
155     // FIXME: make this a dynamic property based on mailbox size and maximum number of clients
156     private static final int CLIENT_MAX_MESSAGES = 1000;
157
158     // The state of this Shard
159     private final ShardDataTree store;
160
161     /// The name of this shard
162     private final String name;
163
164     private final String shardName;
165
166     private final ShardStats shardMBean;
167
168     private final ShardDataTreeListenerInfoMXBeanImpl listenerInfoMXBean;
169
170     private DatastoreContext datastoreContext;
171
172     private final ShardCommitCoordinator commitCoordinator;
173
174     private long transactionCommitTimeout;
175
176     private Cancellable txCommitTimeoutCheckSchedule;
177
178     private final Optional<ActorRef> roleChangeNotifier;
179
180     private final MessageTracker appendEntriesReplyTracker;
181
182     private final ShardTransactionActorFactory transactionActorFactory;
183
184     private final ShardSnapshotCohort snapshotCohort;
185
186     private final DataTreeChangeListenerSupport treeChangeSupport = new DataTreeChangeListenerSupport(this);
187
188     private ShardSnapshot restoreFromSnapshot;
189
190     private final ShardTransactionMessageRetrySupport messageRetrySupport;
191
192     private final FrontendMetadata frontendMetadata;
193     private Map<FrontendIdentifier, LeaderFrontendState> knownFrontends = ImmutableMap.of();
194     private boolean paused;
195
196     private final MessageSlicer responseMessageSlicer;
197     private final Dispatchers dispatchers;
198
199     private final MessageAssembler requestMessageAssembler;
200
201     protected Shard(final AbstractBuilder<?, ?> builder) {
202         super(builder.getId().toString(), builder.getPeerAddresses(),
203                 Optional.of(builder.getDatastoreContext().getShardRaftConfig()), DataStoreVersions.CURRENT_VERSION);
204
205         this.name = builder.getId().toString();
206         this.shardName = builder.getId().getShardName();
207         this.datastoreContext = builder.getDatastoreContext();
208         this.restoreFromSnapshot = builder.getRestoreFromSnapshot();
209         this.frontendMetadata = new FrontendMetadata(name);
210
211         setPersistence(datastoreContext.isPersistent());
212
213         LOG.info("Shard created : {}, persistent : {}", name, datastoreContext.isPersistent());
214
215         ShardDataTreeChangeListenerPublisherActorProxy treeChangeListenerPublisher =
216                 new ShardDataTreeChangeListenerPublisherActorProxy(getContext(), name + "-DTCL-publisher", name);
217         if (builder.getDataTree() != null) {
218             store = new ShardDataTree(this, builder.getSchemaContext(), builder.getDataTree(),
219                     treeChangeListenerPublisher, name, frontendMetadata);
220         } else {
221             store = new ShardDataTree(this, builder.getSchemaContext(), builder.getTreeType(),
222                     builder.getDatastoreContext().getStoreRoot(), treeChangeListenerPublisher, name, frontendMetadata);
223         }
224
225         shardMBean = ShardMBeanFactory.getShardStatsMBean(name, datastoreContext.getDataStoreMXBeanType(), this);
226
227         if (isMetricsCaptureEnabled()) {
228             getContext().become(new MeteringBehavior(this));
229         }
230
231         commitCoordinator = new ShardCommitCoordinator(store, LOG, this.name);
232
233         setTransactionCommitTimeout();
234
235         // create a notifier actor for each cluster member
236         roleChangeNotifier = createRoleChangeNotifier(name);
237
238         appendEntriesReplyTracker = new MessageTracker(AppendEntriesReply.class,
239                 getRaftActorContext().getConfigParams().getIsolatedCheckIntervalInMillis());
240
241         dispatchers = new Dispatchers(context().system().dispatchers());
242         transactionActorFactory = new ShardTransactionActorFactory(store, datastoreContext,
243             dispatchers.getDispatcherPath(Dispatchers.DispatcherType.Transaction),
244                 self(), getContext(), shardMBean, builder.getId().getShardName());
245
246         snapshotCohort = ShardSnapshotCohort.create(getContext(), builder.getId().getMemberName(), store, LOG,
247             this.name);
248
249         messageRetrySupport = new ShardTransactionMessageRetrySupport(this);
250
251         responseMessageSlicer = MessageSlicer.builder().logContext(this.name)
252                 .messageSliceSize(datastoreContext.getMaximumMessageSliceSize())
253                 .fileBackedStreamFactory(getRaftActorContext().getFileBackedOutputStreamFactory())
254                 .expireStateAfterInactivity(2, TimeUnit.MINUTES).build();
255
256         requestMessageAssembler = MessageAssembler.builder().logContext(this.name)
257                 .fileBackedStreamFactory(getRaftActorContext().getFileBackedOutputStreamFactory())
258                 .assembledMessageCallback((message, sender) -> self().tell(message, sender))
259                 .expireStateAfterInactivity(datastoreContext.getRequestTimeout(), TimeUnit.NANOSECONDS).build();
260
261         listenerInfoMXBean = new ShardDataTreeListenerInfoMXBeanImpl(name, datastoreContext.getDataStoreMXBeanType(),
262                 self());
263         listenerInfoMXBean.register();
264     }
265
266     private void setTransactionCommitTimeout() {
267         transactionCommitTimeout = TimeUnit.MILLISECONDS.convert(
268                 datastoreContext.getShardTransactionCommitTimeoutInSeconds(), TimeUnit.SECONDS) / 2;
269     }
270
271     private Optional<ActorRef> createRoleChangeNotifier(final String shardId) {
272         ActorRef shardRoleChangeNotifier = this.getContext().actorOf(
273             RoleChangeNotifier.getProps(shardId), shardId + "-notifier");
274         return Optional.of(shardRoleChangeNotifier);
275     }
276
277     @Override
278     public void postStop() {
279         LOG.info("Stopping Shard {}", persistenceId());
280
281         super.postStop();
282
283         messageRetrySupport.close();
284
285         if (txCommitTimeoutCheckSchedule != null) {
286             txCommitTimeoutCheckSchedule.cancel();
287         }
288
289         commitCoordinator.abortPendingTransactions("Transaction aborted due to shutdown.", this);
290
291         shardMBean.unregisterMBean();
292         listenerInfoMXBean.unregister();
293     }
294
295     @Override
296     protected void handleRecover(final Object message) {
297         LOG.debug("{}: onReceiveRecover: Received message {} from {}", persistenceId(), message.getClass(),
298             getSender());
299
300         super.handleRecover(message);
301         if (LOG.isTraceEnabled()) {
302             appendEntriesReplyTracker.begin();
303         }
304     }
305
306     @Override
307     protected void handleNonRaftCommand(final Object message) {
308         try (MessageTracker.Context context = appendEntriesReplyTracker.received(message)) {
309             final Optional<Error> maybeError = context.error();
310             if (maybeError.isPresent()) {
311                 LOG.trace("{} : AppendEntriesReply failed to arrive at the expected interval {}", persistenceId(),
312                     maybeError.get());
313             }
314
315             store.resetTransactionBatch();
316
317             if (message instanceof RequestEnvelope) {
318                 handleRequestEnvelope((RequestEnvelope)message);
319             } else if (MessageAssembler.isHandledMessage(message)) {
320                 handleRequestAssemblerMessage(message);
321             } else if (message instanceof ConnectClientRequest) {
322                 handleConnectClient((ConnectClientRequest)message);
323             } else if (CreateTransaction.isSerializedType(message)) {
324                 handleCreateTransaction(message);
325             } else if (message instanceof BatchedModifications) {
326                 handleBatchedModifications((BatchedModifications)message);
327             } else if (message instanceof ForwardedReadyTransaction) {
328                 handleForwardedReadyTransaction((ForwardedReadyTransaction) message);
329             } else if (message instanceof ReadyLocalTransaction) {
330                 handleReadyLocalTransaction((ReadyLocalTransaction)message);
331             } else if (CanCommitTransaction.isSerializedType(message)) {
332                 handleCanCommitTransaction(CanCommitTransaction.fromSerializable(message));
333             } else if (CommitTransaction.isSerializedType(message)) {
334                 handleCommitTransaction(CommitTransaction.fromSerializable(message));
335             } else if (AbortTransaction.isSerializedType(message)) {
336                 handleAbortTransaction(AbortTransaction.fromSerializable(message));
337             } else if (CloseTransactionChain.isSerializedType(message)) {
338                 closeTransactionChain(CloseTransactionChain.fromSerializable(message));
339             } else if (message instanceof RegisterDataTreeChangeListener) {
340                 treeChangeSupport.onMessage((RegisterDataTreeChangeListener) message, isLeader(), hasLeader());
341             } else if (message instanceof UpdateSchemaContext) {
342                 updateSchemaContext((UpdateSchemaContext) message);
343             } else if (message instanceof PeerAddressResolved) {
344                 PeerAddressResolved resolved = (PeerAddressResolved) message;
345                 setPeerAddress(resolved.getPeerId(), resolved.getPeerAddress());
346             } else if (TX_COMMIT_TIMEOUT_CHECK_MESSAGE.equals(message)) {
347                 commitTimeoutCheck();
348             } else if (message instanceof DatastoreContext) {
349                 onDatastoreContext((DatastoreContext)message);
350             } else if (message instanceof RegisterRoleChangeListener) {
351                 roleChangeNotifier.get().forward(message, context());
352             } else if (message instanceof FollowerInitialSyncUpStatus) {
353                 shardMBean.setFollowerInitialSyncStatus(((FollowerInitialSyncUpStatus) message).isInitialSyncDone());
354                 context().parent().tell(message, self());
355             } else if (GET_SHARD_MBEAN_MESSAGE.equals(message)) {
356                 sender().tell(getShardMBean(), self());
357             } else if (message instanceof GetShardDataTree) {
358                 sender().tell(store.getDataTree(), self());
359             } else if (message instanceof ServerRemoved) {
360                 context().parent().forward(message, context());
361             } else if (ShardTransactionMessageRetrySupport.TIMER_MESSAGE_CLASS.isInstance(message)) {
362                 messageRetrySupport.onTimerMessage(message);
363             } else if (message instanceof DataTreeCohortActorRegistry.CohortRegistryCommand) {
364                 store.processCohortRegistryCommand(getSender(),
365                         (DataTreeCohortActorRegistry.CohortRegistryCommand) message);
366             } else if (message instanceof PersistAbortTransactionPayload) {
367                 final TransactionIdentifier txId = ((PersistAbortTransactionPayload) message).getTransactionId();
368                 persistPayload(txId, AbortTransactionPayload.create(txId), true);
369             } else if (message instanceof MakeLeaderLocal) {
370                 onMakeLeaderLocal();
371             } else if (RESUME_NEXT_PENDING_TRANSACTION.equals(message)) {
372                 store.resumeNextPendingTransaction();
373             } else if (!responseMessageSlicer.handleMessage(message)) {
374                 super.handleNonRaftCommand(message);
375             }
376         }
377     }
378
379     private void handleRequestAssemblerMessage(final Object message) {
380         dispatchers.getDispatcher(DispatcherType.Serialization).execute(() -> {
381             JavaSerializer.currentSystem().value_$eq((ExtendedActorSystem) context().system());
382             requestMessageAssembler.handleMessage(message, self());
383         });
384     }
385
386     @SuppressWarnings("checkstyle:IllegalCatch")
387     private void handleRequestEnvelope(final RequestEnvelope envelope) {
388         final long now = ticker().read();
389         try {
390             final RequestSuccess<?, ?> success = handleRequest(envelope, now);
391             if (success != null) {
392                 final long executionTimeNanos = ticker().read() - now;
393                 if (success instanceof SliceableMessage) {
394                     dispatchers.getDispatcher(DispatcherType.Serialization).execute(() ->
395                         responseMessageSlicer.slice(SliceOptions.builder().identifier(success.getTarget())
396                             .message(envelope.newSuccessEnvelope(success, executionTimeNanos))
397                             .sendTo(envelope.getMessage().getReplyTo()).replyTo(self())
398                             .onFailureCallback(t -> LOG.warn("Error slicing response {}", success, t)).build()));
399                 } else {
400                     envelope.sendSuccess(success, executionTimeNanos);
401                 }
402             }
403         } catch (RequestException e) {
404             LOG.debug("{}: request {} failed", persistenceId(), envelope, e);
405             envelope.sendFailure(e, ticker().read() - now);
406         } catch (Exception e) {
407             LOG.debug("{}: request {} caused failure", persistenceId(), envelope, e);
408             envelope.sendFailure(new RuntimeRequestException("Request failed to process", e),
409                 ticker().read() - now);
410         }
411     }
412
413     private void commitTimeoutCheck() {
414         store.checkForExpiredTransactions(transactionCommitTimeout, this::updateAccess);
415         commitCoordinator.checkForExpiredTransactions(transactionCommitTimeout, this);
416         requestMessageAssembler.checkExpiredAssembledMessageState();
417     }
418
419     private Optional<Long> updateAccess(final SimpleShardDataTreeCohort cohort) {
420         final FrontendIdentifier frontend = cohort.getIdentifier().getHistoryId().getClientId().getFrontendId();
421         final LeaderFrontendState state = knownFrontends.get(frontend);
422         if (state == null) {
423             // Not tell-based protocol, do nothing
424             return Optional.absent();
425         }
426
427         if (isIsolatedLeader()) {
428             // We are isolated and no new request can come through until we emerge from it. We are still updating
429             // liveness of frontend when we see it attempting to communicate. Use the last access timer.
430             return Optional.of(state.getLastSeenTicks());
431         }
432
433         // If this frontend has freshly connected, give it some time to catch up before killing its transactions.
434         return Optional.of(state.getLastConnectTicks());
435     }
436
437     private void onMakeLeaderLocal() {
438         LOG.debug("{}: onMakeLeaderLocal received", persistenceId());
439         if (isLeader()) {
440             getSender().tell(new Status.Success(null), getSelf());
441             return;
442         }
443
444         final ActorSelection leader = getLeader();
445
446         if (leader == null) {
447             // Leader is not present. The cluster is most likely trying to
448             // elect a leader and we should let that run its normal course
449
450             // TODO we can wait for the election to complete and retry the
451             // request. We can also let the caller retry by sending a flag
452             // in the response indicating the request is "reTryable".
453             getSender().tell(new Failure(
454                     new LeadershipTransferFailedException("We cannot initiate leadership transfer to local node. "
455                             + "Currently there is no leader for " + persistenceId())),
456                     getSelf());
457             return;
458         }
459
460         leader.tell(new RequestLeadership(getId(), getSender()), getSelf());
461     }
462
463     // Acquire our frontend tracking handle and verify generation matches
464     @Nullable
465     private LeaderFrontendState findFrontend(final ClientIdentifier clientId) throws RequestException {
466         final LeaderFrontendState existing = knownFrontends.get(clientId.getFrontendId());
467         if (existing != null) {
468             final int cmp = Long.compareUnsigned(existing.getIdentifier().getGeneration(), clientId.getGeneration());
469             if (cmp == 0) {
470                 existing.touch();
471                 return existing;
472             }
473             if (cmp > 0) {
474                 LOG.debug("{}: rejecting request from outdated client {}", persistenceId(), clientId);
475                 throw new RetiredGenerationException(clientId.getGeneration(),
476                     existing.getIdentifier().getGeneration());
477             }
478
479             LOG.info("{}: retiring state {}, outdated by request from client {}", persistenceId(), existing, clientId);
480             existing.retire();
481             knownFrontends.remove(clientId.getFrontendId());
482         } else {
483             LOG.debug("{}: client {} is not yet known", persistenceId(), clientId);
484         }
485
486         return null;
487     }
488
489     private LeaderFrontendState getFrontend(final ClientIdentifier clientId) throws RequestException {
490         final LeaderFrontendState ret = findFrontend(clientId);
491         if (ret != null) {
492             return ret;
493         }
494
495         // TODO: a dedicated exception would be better, but this is technically true, too
496         throw new OutOfSequenceEnvelopeException(0);
497     }
498
499     @Nonnull
500     private static ABIVersion selectVersion(final ConnectClientRequest message) {
501         final Range<ABIVersion> clientRange = Range.closed(message.getMinVersion(), message.getMaxVersion());
502         for (ABIVersion v : SUPPORTED_ABIVERSIONS) {
503             if (clientRange.contains(v)) {
504                 return v;
505             }
506         }
507
508         throw new IllegalArgumentException(String.format(
509             "No common version between backend versions %s and client versions %s", SUPPORTED_ABIVERSIONS,
510             clientRange));
511     }
512
513     @SuppressWarnings("checkstyle:IllegalCatch")
514     private void handleConnectClient(final ConnectClientRequest message) {
515         try {
516             final ClientIdentifier clientId = message.getTarget();
517             final LeaderFrontendState existing = findFrontend(clientId);
518             if (existing != null) {
519                 existing.touch();
520             }
521
522             if (!isLeader() || !isLeaderActive()) {
523                 LOG.info("{}: not currently leader, rejecting request {}. isLeader: {}, isLeaderActive: {},"
524                                 + "isLeadershipTransferInProgress: {}.",
525                         persistenceId(), message, isLeader(), isLeaderActive(), isLeadershipTransferInProgress());
526                 throw new NotLeaderException(getSelf());
527             }
528
529             final ABIVersion selectedVersion = selectVersion(message);
530             final LeaderFrontendState frontend;
531             if (existing == null) {
532                 frontend = new LeaderFrontendState(persistenceId(), clientId, store);
533                 knownFrontends.put(clientId.getFrontendId(), frontend);
534                 LOG.debug("{}: created state {} for client {}", persistenceId(), frontend, clientId);
535             } else {
536                 frontend = existing;
537             }
538
539             frontend.reconnect();
540             message.getReplyTo().tell(new ConnectClientSuccess(message.getTarget(), message.getSequence(), getSelf(),
541                 ImmutableList.of(), store.getDataTree(), CLIENT_MAX_MESSAGES).toVersion(selectedVersion),
542                 ActorRef.noSender());
543         } catch (RequestException | RuntimeException e) {
544             message.getReplyTo().tell(new Failure(e), ActorRef.noSender());
545         }
546     }
547
548     @Nullable
549     private RequestSuccess<?, ?> handleRequest(final RequestEnvelope envelope, final long now)
550             throws RequestException {
551         // We are not the leader, hence we want to fail-fast.
552         if (!isLeader() || paused || !isLeaderActive()) {
553             LOG.debug("{}: not currently active leader, rejecting request {}. isLeader: {}, isLeaderActive: {},"
554                             + "isLeadershipTransferInProgress: {}, paused: {}",
555                     persistenceId(), envelope, isLeader(), isLeaderActive(), isLeadershipTransferInProgress(), paused);
556             throw new NotLeaderException(getSelf());
557         }
558
559         final Request<?, ?> request = envelope.getMessage();
560         if (request instanceof TransactionRequest) {
561             final TransactionRequest<?> txReq = (TransactionRequest<?>)request;
562             final ClientIdentifier clientId = txReq.getTarget().getHistoryId().getClientId();
563             return getFrontend(clientId).handleTransactionRequest(txReq, envelope, now);
564         } else if (request instanceof LocalHistoryRequest) {
565             final LocalHistoryRequest<?> lhReq = (LocalHistoryRequest<?>)request;
566             final ClientIdentifier clientId = lhReq.getTarget().getClientId();
567             return getFrontend(clientId).handleLocalHistoryRequest(lhReq, envelope, now);
568         } else {
569             LOG.warn("{}: rejecting unsupported request {}", persistenceId(), request);
570             throw new UnsupportedRequestException(request);
571         }
572     }
573
574     private boolean hasLeader() {
575         return getLeaderId() != null;
576     }
577
578     public int getPendingTxCommitQueueSize() {
579         return store.getQueueSize();
580     }
581
582     public int getCohortCacheSize() {
583         return commitCoordinator.getCohortCacheSize();
584     }
585
586     @Override
587     protected Optional<ActorRef> getRoleChangeNotifier() {
588         return roleChangeNotifier;
589     }
590
591     String getShardName() {
592         return shardName;
593     }
594
595     @Override
596     protected LeaderStateChanged newLeaderStateChanged(final String memberId, final String leaderId,
597             final short leaderPayloadVersion) {
598         return isLeader() ? new ShardLeaderStateChanged(memberId, leaderId, store.getDataTree(), leaderPayloadVersion)
599                 : new ShardLeaderStateChanged(memberId, leaderId, leaderPayloadVersion);
600     }
601
602     protected void onDatastoreContext(final DatastoreContext context) {
603         datastoreContext = context;
604
605         setTransactionCommitTimeout();
606
607         setPersistence(datastoreContext.isPersistent());
608
609         updateConfigParams(datastoreContext.getShardRaftConfig());
610     }
611
612     // applyState() will be invoked once consensus is reached on the payload
613     void persistPayload(final Identifier id, final Payload payload, final boolean batchHint) {
614         boolean canSkipPayload = !hasFollowers() && !persistence().isRecoveryApplicable();
615         if (canSkipPayload) {
616             applyState(self(), id, payload);
617         } else {
618             // We are faking the sender
619             persistData(self(), id, payload, batchHint);
620         }
621     }
622
623     private void handleCommitTransaction(final CommitTransaction commit) {
624         if (isLeader()) {
625             commitCoordinator.handleCommit(commit.getTransactionId(), getSender(), this);
626         } else {
627             ActorSelection leader = getLeader();
628             if (leader == null) {
629                 messageRetrySupport.addMessageToRetry(commit, getSender(),
630                         "Could not commit transaction " + commit.getTransactionId());
631             } else {
632                 LOG.debug("{}: Forwarding CommitTransaction to leader {}", persistenceId(), leader);
633                 leader.forward(commit, getContext());
634             }
635         }
636     }
637
638     private void handleCanCommitTransaction(final CanCommitTransaction canCommit) {
639         LOG.debug("{}: Can committing transaction {}", persistenceId(), canCommit.getTransactionId());
640
641         if (isLeader()) {
642             commitCoordinator.handleCanCommit(canCommit.getTransactionId(), getSender(), this);
643         } else {
644             ActorSelection leader = getLeader();
645             if (leader == null) {
646                 messageRetrySupport.addMessageToRetry(canCommit, getSender(),
647                         "Could not canCommit transaction " + canCommit.getTransactionId());
648             } else {
649                 LOG.debug("{}: Forwarding CanCommitTransaction to leader {}", persistenceId(), leader);
650                 leader.forward(canCommit, getContext());
651             }
652         }
653     }
654
655     @SuppressWarnings("checkstyle:IllegalCatch")
656     protected void handleBatchedModificationsLocal(final BatchedModifications batched, final ActorRef sender) {
657         try {
658             commitCoordinator.handleBatchedModifications(batched, sender, this);
659         } catch (Exception e) {
660             LOG.error("{}: Error handling BatchedModifications for Tx {}", persistenceId(),
661                     batched.getTransactionId(), e);
662             sender.tell(new Failure(e), getSelf());
663         }
664     }
665
666     private void handleBatchedModifications(final BatchedModifications batched) {
667         // This message is sent to prepare the modifications transaction directly on the Shard as an
668         // optimization to avoid the extra overhead of a separate ShardTransaction actor. On the last
669         // BatchedModifications message, the caller sets the ready flag in the message indicating
670         // modifications are complete. The reply contains the cohort actor path (this actor) for the caller
671         // to initiate the 3-phase commit. This also avoids the overhead of sending an additional
672         // ReadyTransaction message.
673
674         // If we're not the leader then forward to the leader. This is a safety measure - we shouldn't
675         // normally get here if we're not the leader as the front-end (TransactionProxy) should determine
676         // the primary/leader shard. However with timing and caching on the front-end, there's a small
677         // window where it could have a stale leader during leadership transitions.
678         //
679         boolean isLeaderActive = isLeaderActive();
680         if (isLeader() && isLeaderActive) {
681             handleBatchedModificationsLocal(batched, getSender());
682         } else {
683             ActorSelection leader = getLeader();
684             if (!isLeaderActive || leader == null) {
685                 messageRetrySupport.addMessageToRetry(batched, getSender(),
686                         "Could not process BatchedModifications " + batched.getTransactionId());
687             } else {
688                 // If this is not the first batch and leadership changed in between batched messages,
689                 // we need to reconstruct previous BatchedModifications from the transaction
690                 // DataTreeModification, honoring the max batched modification count, and forward all the
691                 // previous BatchedModifications to the new leader.
692                 Collection<BatchedModifications> newModifications = commitCoordinator
693                         .createForwardedBatchedModifications(batched,
694                                 datastoreContext.getShardBatchedModificationCount());
695
696                 LOG.debug("{}: Forwarding {} BatchedModifications to leader {}", persistenceId(),
697                         newModifications.size(), leader);
698
699                 for (BatchedModifications bm : newModifications) {
700                     leader.forward(bm, getContext());
701                 }
702             }
703         }
704     }
705
706     private boolean failIfIsolatedLeader(final ActorRef sender) {
707         if (isIsolatedLeader()) {
708             sender.tell(new Failure(new NoShardLeaderException(String.format(
709                     "Shard %s was the leader but has lost contact with all of its followers. Either all"
710                     + " other follower nodes are down or this node is isolated by a network partition.",
711                     persistenceId()))), getSelf());
712             return true;
713         }
714
715         return false;
716     }
717
718     protected boolean isIsolatedLeader() {
719         return getRaftState() == RaftState.IsolatedLeader;
720     }
721
722     @SuppressWarnings("checkstyle:IllegalCatch")
723     private void handleReadyLocalTransaction(final ReadyLocalTransaction message) {
724         LOG.debug("{}: handleReadyLocalTransaction for {}", persistenceId(), message.getTransactionId());
725
726         boolean isLeaderActive = isLeaderActive();
727         if (isLeader() && isLeaderActive) {
728             try {
729                 commitCoordinator.handleReadyLocalTransaction(message, getSender(), this);
730             } catch (Exception e) {
731                 LOG.error("{}: Error handling ReadyLocalTransaction for Tx {}", persistenceId(),
732                         message.getTransactionId(), e);
733                 getSender().tell(new Failure(e), getSelf());
734             }
735         } else {
736             ActorSelection leader = getLeader();
737             if (!isLeaderActive || leader == null) {
738                 messageRetrySupport.addMessageToRetry(message, getSender(),
739                         "Could not process ready local transaction " + message.getTransactionId());
740             } else {
741                 LOG.debug("{}: Forwarding ReadyLocalTransaction to leader {}", persistenceId(), leader);
742                 message.setRemoteVersion(getCurrentBehavior().getLeaderPayloadVersion());
743                 leader.forward(message, getContext());
744             }
745         }
746     }
747
748     private void handleForwardedReadyTransaction(final ForwardedReadyTransaction forwardedReady) {
749         LOG.debug("{}: handleForwardedReadyTransaction for {}", persistenceId(), forwardedReady.getTransactionId());
750
751         boolean isLeaderActive = isLeaderActive();
752         if (isLeader() && isLeaderActive) {
753             commitCoordinator.handleForwardedReadyTransaction(forwardedReady, getSender(), this);
754         } else {
755             ActorSelection leader = getLeader();
756             if (!isLeaderActive || leader == null) {
757                 messageRetrySupport.addMessageToRetry(forwardedReady, getSender(),
758                         "Could not process forwarded ready transaction " + forwardedReady.getTransactionId());
759             } else {
760                 LOG.debug("{}: Forwarding ForwardedReadyTransaction to leader {}", persistenceId(), leader);
761
762                 ReadyLocalTransaction readyLocal = new ReadyLocalTransaction(forwardedReady.getTransactionId(),
763                         forwardedReady.getTransaction().getSnapshot(), forwardedReady.isDoImmediateCommit(),
764                         forwardedReady.getParticipatingShardNames());
765                 readyLocal.setRemoteVersion(getCurrentBehavior().getLeaderPayloadVersion());
766                 leader.forward(readyLocal, getContext());
767             }
768         }
769     }
770
771     private void handleAbortTransaction(final AbortTransaction abort) {
772         doAbortTransaction(abort.getTransactionId(), getSender());
773     }
774
775     void doAbortTransaction(final Identifier transactionID, final ActorRef sender) {
776         commitCoordinator.handleAbort(transactionID, sender, this);
777     }
778
779     private void handleCreateTransaction(final Object message) {
780         if (isLeader()) {
781             createTransaction(CreateTransaction.fromSerializable(message));
782         } else if (getLeader() != null) {
783             getLeader().forward(message, getContext());
784         } else {
785             getSender().tell(new Failure(new NoShardLeaderException(
786                     "Could not create a shard transaction", persistenceId())), getSelf());
787         }
788     }
789
790     private void closeTransactionChain(final CloseTransactionChain closeTransactionChain) {
791         final LocalHistoryIdentifier id = closeTransactionChain.getIdentifier();
792         store.closeTransactionChain(id, null);
793         store.purgeTransactionChain(id, null);
794     }
795
796     @SuppressWarnings("checkstyle:IllegalCatch")
797     private void createTransaction(final CreateTransaction createTransaction) {
798         try {
799             if (TransactionType.fromInt(createTransaction.getTransactionType()) != TransactionType.READ_ONLY
800                     && failIfIsolatedLeader(getSender())) {
801                 return;
802             }
803
804             ActorRef transactionActor = createTransaction(createTransaction.getTransactionType(),
805                 createTransaction.getTransactionId());
806
807             getSender().tell(new CreateTransactionReply(Serialization.serializedActorPath(transactionActor),
808                     createTransaction.getTransactionId(), createTransaction.getVersion()).toSerializable(), getSelf());
809         } catch (Exception e) {
810             getSender().tell(new Failure(e), getSelf());
811         }
812     }
813
814     private ActorRef createTransaction(final int transactionType, final TransactionIdentifier transactionId) {
815         LOG.debug("{}: Creating transaction : {} ", persistenceId(), transactionId);
816         return transactionActorFactory.newShardTransaction(TransactionType.fromInt(transactionType),
817             transactionId);
818     }
819
820     private void updateSchemaContext(final UpdateSchemaContext message) {
821         updateSchemaContext(message.getSchemaContext());
822     }
823
824     @VisibleForTesting
825     void updateSchemaContext(final SchemaContext schemaContext) {
826         store.updateSchemaContext(schemaContext);
827     }
828
829     private boolean isMetricsCaptureEnabled() {
830         CommonConfig config = new CommonConfig(getContext().system().settings().config());
831         return config.isMetricCaptureEnabled();
832     }
833
834     @Override
835     @VisibleForTesting
836     public RaftActorSnapshotCohort getRaftActorSnapshotCohort() {
837         return snapshotCohort;
838     }
839
840     @Override
841     @Nonnull
842     protected RaftActorRecoveryCohort getRaftActorRecoveryCohort() {
843         if (restoreFromSnapshot == null) {
844             return ShardRecoveryCoordinator.create(store, persistenceId(), LOG);
845         }
846
847         return ShardRecoveryCoordinator.forSnapshot(store, persistenceId(), LOG, restoreFromSnapshot.getSnapshot());
848     }
849
850     @Override
851     protected void onRecoveryComplete() {
852         restoreFromSnapshot = null;
853
854         //notify shard manager
855         getContext().parent().tell(new ActorInitialized(), getSelf());
856
857         // Being paranoid here - this method should only be called once but just in case...
858         if (txCommitTimeoutCheckSchedule == null) {
859             // Schedule a message to be periodically sent to check if the current in-progress
860             // transaction should be expired and aborted.
861             FiniteDuration period = Duration.create(transactionCommitTimeout / 3, TimeUnit.MILLISECONDS);
862             txCommitTimeoutCheckSchedule = getContext().system().scheduler().schedule(
863                     period, period, getSelf(),
864                     TX_COMMIT_TIMEOUT_CHECK_MESSAGE, getContext().dispatcher(), ActorRef.noSender());
865         }
866     }
867
868     @Override
869     protected void applyState(final ActorRef clientActor, final Identifier identifier, final Object data) {
870         if (data instanceof Payload) {
871             try {
872                 store.applyReplicatedPayload(identifier, (Payload)data);
873             } catch (DataValidationFailedException | IOException e) {
874                 LOG.error("{}: Error applying replica {}", persistenceId(), identifier, e);
875             }
876         } else {
877             LOG.error("{}: Unknown state for {} received {}", persistenceId(), identifier, data);
878         }
879     }
880
881     @Override
882     protected void onStateChanged() {
883         boolean isLeader = isLeader();
884         boolean hasLeader = hasLeader();
885         treeChangeSupport.onLeadershipChange(isLeader, hasLeader);
886
887         // If this actor is no longer the leader close all the transaction chains
888         if (!isLeader) {
889             if (LOG.isDebugEnabled()) {
890                 LOG.debug(
891                     "{}: onStateChanged: Closing all transaction chains because shard {} is no longer the leader",
892                     persistenceId(), getId());
893             }
894
895             paused = false;
896             store.purgeLeaderState();
897         }
898
899         if (hasLeader && !isIsolatedLeader()) {
900             messageRetrySupport.retryMessages();
901         }
902     }
903
904     @Override
905     protected void onLeaderChanged(final String oldLeader, final String newLeader) {
906         shardMBean.incrementLeadershipChangeCount();
907         paused = false;
908
909         if (!isLeader()) {
910             if (!knownFrontends.isEmpty()) {
911                 LOG.debug("{}: removing frontend state for {}", persistenceId(), knownFrontends.keySet());
912                 knownFrontends = ImmutableMap.of();
913             }
914
915             requestMessageAssembler.close();
916
917             if (!hasLeader()) {
918                 // No leader anywhere, nothing else to do
919                 return;
920             }
921
922             // Another leader was elected. If we were the previous leader and had pending transactions, convert
923             // them to transaction messages and send to the new leader.
924             ActorSelection leader = getLeader();
925             if (leader != null) {
926                 Collection<?> messagesToForward = convertPendingTransactionsToMessages();
927
928                 if (!messagesToForward.isEmpty()) {
929                     LOG.debug("{}: Forwarding {} pending transaction messages to leader {}", persistenceId(),
930                             messagesToForward.size(), leader);
931
932                     for (Object message : messagesToForward) {
933                         LOG.debug("{}: Forwarding pending transaction message {}", persistenceId(), message);
934
935                         leader.tell(message, self());
936                     }
937                 }
938             } else {
939                 commitCoordinator.abortPendingTransactions("The transacton was aborted due to inflight leadership "
940                         + "change and the leader address isn't available.", this);
941             }
942         } else {
943             // We have become the leader, we need to reconstruct frontend state
944             knownFrontends = Verify.verifyNotNull(frontendMetadata.toLeaderState(this));
945             LOG.debug("{}: became leader with frontend state for {}", persistenceId(), knownFrontends.keySet());
946         }
947
948         if (!isIsolatedLeader()) {
949             messageRetrySupport.retryMessages();
950         }
951     }
952
953     /**
954      * Clears all pending transactions and converts them to messages to be forwarded to a new leader.
955      *
956      * @return the converted messages
957      */
958     public Collection<?> convertPendingTransactionsToMessages() {
959         return commitCoordinator.convertPendingTransactionsToMessages(
960                 datastoreContext.getShardBatchedModificationCount());
961     }
962
963     @Override
964     protected void pauseLeader(final Runnable operation) {
965         LOG.debug("{}: In pauseLeader, operation: {}", persistenceId(), operation);
966         paused = true;
967
968         // Tell-based protocol can replay transaction state, so it is safe to blow it up when we are paused.
969         knownFrontends.values().forEach(LeaderFrontendState::retire);
970         knownFrontends = ImmutableMap.of();
971
972         store.setRunOnPendingTransactionsComplete(operation);
973     }
974
975     @Override
976     protected void unpauseLeader() {
977         LOG.debug("{}: In unpauseLeader", persistenceId());
978         paused = false;
979
980         store.setRunOnPendingTransactionsComplete(null);
981
982         // Restore tell-based protocol state as if we were becoming the leader
983         knownFrontends = Verify.verifyNotNull(frontendMetadata.toLeaderState(this));
984     }
985
986     @Override
987     protected OnDemandRaftState.AbstractBuilder<?, ?> newOnDemandRaftStateBuilder() {
988         return OnDemandShardState.newBuilder().treeChangeListenerActors(treeChangeSupport.getListenerActors())
989                 .commitCohortActors(store.getCohortActors());
990     }
991
992     @Override
993     public String persistenceId() {
994         return this.name;
995     }
996
997     @VisibleForTesting
998     ShardCommitCoordinator getCommitCoordinator() {
999         return commitCoordinator;
1000     }
1001
1002     public DatastoreContext getDatastoreContext() {
1003         return datastoreContext;
1004     }
1005
1006     @VisibleForTesting
1007     public ShardDataTree getDataStore() {
1008         return store;
1009     }
1010
1011     @VisibleForTesting
1012     ShardStats getShardMBean() {
1013         return shardMBean;
1014     }
1015
1016     public static Builder builder() {
1017         return new Builder();
1018     }
1019
1020     public abstract static class AbstractBuilder<T extends AbstractBuilder<T, S>, S extends Shard> {
1021         private final Class<S> shardClass;
1022         private ShardIdentifier id;
1023         private Map<String, String> peerAddresses = Collections.emptyMap();
1024         private DatastoreContext datastoreContext;
1025         private SchemaContextProvider schemaContextProvider;
1026         private DatastoreSnapshot.ShardSnapshot restoreFromSnapshot;
1027         private DataTree dataTree;
1028         private volatile boolean sealed;
1029
1030         protected AbstractBuilder(final Class<S> shardClass) {
1031             this.shardClass = shardClass;
1032         }
1033
1034         protected void checkSealed() {
1035             Preconditions.checkState(!sealed, "Builder isalready sealed - further modifications are not allowed");
1036         }
1037
1038         @SuppressWarnings("unchecked")
1039         private T self() {
1040             return (T) this;
1041         }
1042
1043         public T id(final ShardIdentifier newId) {
1044             checkSealed();
1045             this.id = newId;
1046             return self();
1047         }
1048
1049         public T peerAddresses(final Map<String, String> newPeerAddresses) {
1050             checkSealed();
1051             this.peerAddresses = newPeerAddresses;
1052             return self();
1053         }
1054
1055         public T datastoreContext(final DatastoreContext newDatastoreContext) {
1056             checkSealed();
1057             this.datastoreContext = newDatastoreContext;
1058             return self();
1059         }
1060
1061         public T schemaContextProvider(final SchemaContextProvider newSchemaContextProvider) {
1062             checkSealed();
1063             this.schemaContextProvider = Preconditions.checkNotNull(newSchemaContextProvider);
1064             return self();
1065         }
1066
1067         public T restoreFromSnapshot(final DatastoreSnapshot.ShardSnapshot newRestoreFromSnapshot) {
1068             checkSealed();
1069             this.restoreFromSnapshot = newRestoreFromSnapshot;
1070             return self();
1071         }
1072
1073         public T dataTree(final DataTree newDataTree) {
1074             checkSealed();
1075             this.dataTree = newDataTree;
1076             return self();
1077         }
1078
1079         public ShardIdentifier getId() {
1080             return id;
1081         }
1082
1083         public Map<String, String> getPeerAddresses() {
1084             return peerAddresses;
1085         }
1086
1087         public DatastoreContext getDatastoreContext() {
1088             return datastoreContext;
1089         }
1090
1091         public SchemaContext getSchemaContext() {
1092             return Verify.verifyNotNull(schemaContextProvider.getSchemaContext());
1093         }
1094
1095         public DatastoreSnapshot.ShardSnapshot getRestoreFromSnapshot() {
1096             return restoreFromSnapshot;
1097         }
1098
1099         public DataTree getDataTree() {
1100             return dataTree;
1101         }
1102
1103         public TreeType getTreeType() {
1104             switch (datastoreContext.getLogicalStoreType()) {
1105                 case CONFIGURATION:
1106                     return TreeType.CONFIGURATION;
1107                 case OPERATIONAL:
1108                     return TreeType.OPERATIONAL;
1109                 default:
1110                     throw new IllegalStateException("Unhandled logical store type "
1111                             + datastoreContext.getLogicalStoreType());
1112             }
1113         }
1114
1115         protected void verify() {
1116             Preconditions.checkNotNull(id, "id should not be null");
1117             Preconditions.checkNotNull(peerAddresses, "peerAddresses should not be null");
1118             Preconditions.checkNotNull(datastoreContext, "dataStoreContext should not be null");
1119             Preconditions.checkNotNull(schemaContextProvider, "schemaContextProvider should not be null");
1120         }
1121
1122         public Props props() {
1123             sealed = true;
1124             verify();
1125             return Props.create(shardClass, this);
1126         }
1127     }
1128
1129     public static class Builder extends AbstractBuilder<Builder, Shard> {
1130         Builder() {
1131             super(Shard.class);
1132         }
1133     }
1134
1135     Ticker ticker() {
1136         return Ticker.systemTicker();
1137     }
1138
1139     void scheduleNextPendingTransaction() {
1140         self().tell(RESUME_NEXT_PENDING_TRANSACTION, ActorRef.noSender());
1141     }
1142 }