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