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