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