Migrate ShardDataTree to use OptionalLong
[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 static com.google.common.base.Verify.verify;
11
12 import akka.actor.ActorRef;
13 import akka.actor.ActorSelection;
14 import akka.actor.Cancellable;
15 import akka.actor.ExtendedActorSystem;
16 import akka.actor.Props;
17 import akka.actor.Status;
18 import akka.actor.Status.Failure;
19 import akka.serialization.JavaSerializer;
20 import akka.serialization.Serialization;
21 import com.google.common.annotations.VisibleForTesting;
22 import com.google.common.base.Optional;
23 import com.google.common.base.Preconditions;
24 import com.google.common.base.Ticker;
25 import com.google.common.base.Verify;
26 import com.google.common.collect.ImmutableList;
27 import com.google.common.collect.ImmutableMap;
28 import com.google.common.collect.Range;
29 import java.io.IOException;
30 import java.util.Arrays;
31 import java.util.Collection;
32 import java.util.Collections;
33 import java.util.HashMap;
34 import java.util.Map;
35 import java.util.OptionalLong;
36 import java.util.concurrent.TimeUnit;
37 import org.eclipse.jdt.annotation.NonNull;
38 import org.eclipse.jdt.annotation.Nullable;
39 import org.opendaylight.controller.cluster.access.ABIVersion;
40 import org.opendaylight.controller.cluster.access.commands.ConnectClientRequest;
41 import org.opendaylight.controller.cluster.access.commands.ConnectClientSuccess;
42 import org.opendaylight.controller.cluster.access.commands.LocalHistoryRequest;
43 import org.opendaylight.controller.cluster.access.commands.NotLeaderException;
44 import org.opendaylight.controller.cluster.access.commands.OutOfSequenceEnvelopeException;
45 import org.opendaylight.controller.cluster.access.commands.TransactionRequest;
46 import org.opendaylight.controller.cluster.access.concepts.ClientIdentifier;
47 import org.opendaylight.controller.cluster.access.concepts.FrontendIdentifier;
48 import org.opendaylight.controller.cluster.access.concepts.LocalHistoryIdentifier;
49 import org.opendaylight.controller.cluster.access.concepts.Request;
50 import org.opendaylight.controller.cluster.access.concepts.RequestEnvelope;
51 import org.opendaylight.controller.cluster.access.concepts.RequestException;
52 import org.opendaylight.controller.cluster.access.concepts.RequestSuccess;
53 import org.opendaylight.controller.cluster.access.concepts.RetiredGenerationException;
54 import org.opendaylight.controller.cluster.access.concepts.RuntimeRequestException;
55 import org.opendaylight.controller.cluster.access.concepts.SliceableMessage;
56 import org.opendaylight.controller.cluster.access.concepts.TransactionIdentifier;
57 import org.opendaylight.controller.cluster.access.concepts.UnsupportedRequestException;
58 import org.opendaylight.controller.cluster.common.actor.CommonConfig;
59 import org.opendaylight.controller.cluster.common.actor.Dispatchers;
60 import org.opendaylight.controller.cluster.common.actor.Dispatchers.DispatcherType;
61 import org.opendaylight.controller.cluster.common.actor.MessageTracker;
62 import org.opendaylight.controller.cluster.common.actor.MessageTracker.Error;
63 import org.opendaylight.controller.cluster.common.actor.MeteringBehavior;
64 import org.opendaylight.controller.cluster.datastore.exceptions.NoShardLeaderException;
65 import org.opendaylight.controller.cluster.datastore.identifiers.ShardIdentifier;
66 import org.opendaylight.controller.cluster.datastore.jmx.mbeans.shard.ShardDataTreeListenerInfoMXBeanImpl;
67 import org.opendaylight.controller.cluster.datastore.jmx.mbeans.shard.ShardMBeanFactory;
68 import org.opendaylight.controller.cluster.datastore.jmx.mbeans.shard.ShardStats;
69 import org.opendaylight.controller.cluster.datastore.messages.AbortTransaction;
70 import org.opendaylight.controller.cluster.datastore.messages.ActorInitialized;
71 import org.opendaylight.controller.cluster.datastore.messages.BatchedModifications;
72 import org.opendaylight.controller.cluster.datastore.messages.CanCommitTransaction;
73 import org.opendaylight.controller.cluster.datastore.messages.CloseTransactionChain;
74 import org.opendaylight.controller.cluster.datastore.messages.CommitTransaction;
75 import org.opendaylight.controller.cluster.datastore.messages.CreateTransaction;
76 import org.opendaylight.controller.cluster.datastore.messages.CreateTransactionReply;
77 import org.opendaylight.controller.cluster.datastore.messages.ForwardedReadyTransaction;
78 import org.opendaylight.controller.cluster.datastore.messages.GetShardDataTree;
79 import org.opendaylight.controller.cluster.datastore.messages.MakeLeaderLocal;
80 import org.opendaylight.controller.cluster.datastore.messages.OnDemandShardState;
81 import org.opendaylight.controller.cluster.datastore.messages.PeerAddressResolved;
82 import org.opendaylight.controller.cluster.datastore.messages.ReadyLocalTransaction;
83 import org.opendaylight.controller.cluster.datastore.messages.RegisterDataTreeChangeListener;
84 import org.opendaylight.controller.cluster.datastore.messages.ShardLeaderStateChanged;
85 import org.opendaylight.controller.cluster.datastore.messages.UpdateSchemaContext;
86 import org.opendaylight.controller.cluster.datastore.persisted.DatastoreSnapshot;
87 import org.opendaylight.controller.cluster.datastore.persisted.DatastoreSnapshot.ShardSnapshot;
88 import org.opendaylight.controller.cluster.datastore.persisted.DisableTrackingPayload;
89 import org.opendaylight.controller.cluster.messaging.MessageAssembler;
90 import org.opendaylight.controller.cluster.messaging.MessageSlicer;
91 import org.opendaylight.controller.cluster.messaging.SliceOptions;
92 import org.opendaylight.controller.cluster.notifications.LeaderStateChanged;
93 import org.opendaylight.controller.cluster.notifications.RegisterRoleChangeListener;
94 import org.opendaylight.controller.cluster.notifications.RoleChangeNotifier;
95 import org.opendaylight.controller.cluster.raft.LeadershipTransferFailedException;
96 import org.opendaylight.controller.cluster.raft.RaftActor;
97 import org.opendaylight.controller.cluster.raft.RaftActorRecoveryCohort;
98 import org.opendaylight.controller.cluster.raft.RaftActorSnapshotCohort;
99 import org.opendaylight.controller.cluster.raft.RaftState;
100 import org.opendaylight.controller.cluster.raft.base.messages.FollowerInitialSyncUpStatus;
101 import org.opendaylight.controller.cluster.raft.client.messages.OnDemandRaftState;
102 import org.opendaylight.controller.cluster.raft.messages.AppendEntriesReply;
103 import org.opendaylight.controller.cluster.raft.messages.RequestLeadership;
104 import org.opendaylight.controller.cluster.raft.messages.ServerRemoved;
105 import org.opendaylight.controller.cluster.raft.protobuff.client.messages.Payload;
106 import org.opendaylight.yangtools.concepts.Identifier;
107 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTree;
108 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataValidationFailedException;
109 import org.opendaylight.yangtools.yang.data.api.schema.tree.TreeType;
110 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
111 import org.opendaylight.yangtools.yang.model.api.SchemaContextProvider;
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 java.util.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 MakeLeaderLocal) {
368                 onMakeLeaderLocal();
369             } else if (RESUME_NEXT_PENDING_TRANSACTION.equals(message)) {
370                 store.resumeNextPendingTransaction();
371             } else if (!responseMessageSlicer.handleMessage(message)) {
372                 super.handleNonRaftCommand(message);
373             }
374         }
375     }
376
377     private void handleRequestAssemblerMessage(final Object message) {
378         dispatchers.getDispatcher(DispatcherType.Serialization).execute(() -> {
379             JavaSerializer.currentSystem().value_$eq((ExtendedActorSystem) context().system());
380             requestMessageAssembler.handleMessage(message, self());
381         });
382     }
383
384     @SuppressWarnings("checkstyle:IllegalCatch")
385     private void handleRequestEnvelope(final RequestEnvelope envelope) {
386         final long now = ticker().read();
387         try {
388             final RequestSuccess<?, ?> success = handleRequest(envelope, now);
389             if (success != null) {
390                 final long executionTimeNanos = ticker().read() - now;
391                 if (success instanceof SliceableMessage) {
392                     dispatchers.getDispatcher(DispatcherType.Serialization).execute(() ->
393                         responseMessageSlicer.slice(SliceOptions.builder().identifier(success.getTarget())
394                             .message(envelope.newSuccessEnvelope(success, executionTimeNanos))
395                             .sendTo(envelope.getMessage().getReplyTo()).replyTo(self())
396                             .onFailureCallback(t -> LOG.warn("Error slicing response {}", success, t)).build()));
397                 } else {
398                     envelope.sendSuccess(success, executionTimeNanos);
399                 }
400             }
401         } catch (RequestException e) {
402             LOG.debug("{}: request {} failed", persistenceId(), envelope, e);
403             envelope.sendFailure(e, ticker().read() - now);
404         } catch (Exception e) {
405             LOG.debug("{}: request {} caused failure", persistenceId(), envelope, e);
406             envelope.sendFailure(new RuntimeRequestException("Request failed to process", e),
407                 ticker().read() - now);
408         }
409     }
410
411     private void commitTimeoutCheck() {
412         store.checkForExpiredTransactions(transactionCommitTimeout, this::updateAccess);
413         commitCoordinator.checkForExpiredTransactions(transactionCommitTimeout, this);
414         requestMessageAssembler.checkExpiredAssembledMessageState();
415     }
416
417     private OptionalLong updateAccess(final SimpleShardDataTreeCohort cohort) {
418         final FrontendIdentifier frontend = cohort.getIdentifier().getHistoryId().getClientId().getFrontendId();
419         final LeaderFrontendState state = knownFrontends.get(frontend);
420         if (state == null) {
421             // Not tell-based protocol, do nothing
422             return OptionalLong.empty();
423         }
424
425         if (isIsolatedLeader()) {
426             // We are isolated and no new request can come through until we emerge from it. We are still updating
427             // liveness of frontend when we see it attempting to communicate. Use the last access timer.
428             return OptionalLong.of(state.getLastSeenTicks());
429         }
430
431         // If this frontend has freshly connected, give it some time to catch up before killing its transactions.
432         return OptionalLong.of(state.getLastConnectTicks());
433     }
434
435     private void disableTracking(final DisableTrackingPayload payload) {
436         final ClientIdentifier clientId = payload.getIdentifier();
437         LOG.debug("{}: disabling tracking of {}", persistenceId(), clientId);
438         frontendMetadata.disableTracking(clientId);
439
440         if (isLeader()) {
441             final FrontendIdentifier frontendId = clientId.getFrontendId();
442             final LeaderFrontendState frontend = knownFrontends.get(frontendId);
443             if (frontend != null) {
444                 if (clientId.equals(frontend.getIdentifier())) {
445                     if (!(frontend instanceof LeaderFrontendState.Disabled)) {
446                         verify(knownFrontends.replace(frontendId, frontend,
447                             new LeaderFrontendState.Disabled(persistenceId(), clientId, store)));
448                         LOG.debug("{}: leader state for {} disabled", persistenceId(), clientId);
449                     } else {
450                         LOG.debug("{}: leader state {} is already disabled", persistenceId(), frontend);
451                     }
452                 } else {
453                     LOG.debug("{}: leader state {} does not match {}", persistenceId(), frontend, clientId);
454                 }
455             } else {
456                 LOG.debug("{}: leader state for {} not found", persistenceId(), clientId);
457                 knownFrontends.put(frontendId, new LeaderFrontendState.Disabled(persistenceId(), clientId,
458                     getDataStore()));
459             }
460         }
461     }
462
463     private void onMakeLeaderLocal() {
464         LOG.debug("{}: onMakeLeaderLocal received", persistenceId());
465         if (isLeader()) {
466             getSender().tell(new Status.Success(null), getSelf());
467             return;
468         }
469
470         final ActorSelection leader = getLeader();
471
472         if (leader == null) {
473             // Leader is not present. The cluster is most likely trying to
474             // elect a leader and we should let that run its normal course
475
476             // TODO we can wait for the election to complete and retry the
477             // request. We can also let the caller retry by sending a flag
478             // in the response indicating the request is "reTryable".
479             getSender().tell(new Failure(
480                     new LeadershipTransferFailedException("We cannot initiate leadership transfer to local node. "
481                             + "Currently there is no leader for " + persistenceId())),
482                     getSelf());
483             return;
484         }
485
486         leader.tell(new RequestLeadership(getId(), getSender()), getSelf());
487     }
488
489     // Acquire our frontend tracking handle and verify generation matches
490     private @Nullable LeaderFrontendState findFrontend(final ClientIdentifier clientId) throws RequestException {
491         final LeaderFrontendState existing = knownFrontends.get(clientId.getFrontendId());
492         if (existing != null) {
493             final int cmp = Long.compareUnsigned(existing.getIdentifier().getGeneration(), clientId.getGeneration());
494             if (cmp == 0) {
495                 existing.touch();
496                 return existing;
497             }
498             if (cmp > 0) {
499                 LOG.debug("{}: rejecting request from outdated client {}", persistenceId(), clientId);
500                 throw new RetiredGenerationException(clientId.getGeneration(),
501                     existing.getIdentifier().getGeneration());
502             }
503
504             LOG.info("{}: retiring state {}, outdated by request from client {}", persistenceId(), existing, clientId);
505             existing.retire();
506             knownFrontends.remove(clientId.getFrontendId());
507         } else {
508             LOG.debug("{}: client {} is not yet known", persistenceId(), clientId);
509         }
510
511         return null;
512     }
513
514     private LeaderFrontendState getFrontend(final ClientIdentifier clientId) throws RequestException {
515         final LeaderFrontendState ret = findFrontend(clientId);
516         if (ret != null) {
517             return ret;
518         }
519
520         // TODO: a dedicated exception would be better, but this is technically true, too
521         throw new OutOfSequenceEnvelopeException(0);
522     }
523
524     private static @NonNull ABIVersion selectVersion(final ConnectClientRequest message) {
525         final Range<ABIVersion> clientRange = Range.closed(message.getMinVersion(), message.getMaxVersion());
526         for (ABIVersion v : SUPPORTED_ABIVERSIONS) {
527             if (clientRange.contains(v)) {
528                 return v;
529             }
530         }
531
532         throw new IllegalArgumentException(String.format(
533             "No common version between backend versions %s and client versions %s", SUPPORTED_ABIVERSIONS,
534             clientRange));
535     }
536
537     @SuppressWarnings("checkstyle:IllegalCatch")
538     private void handleConnectClient(final ConnectClientRequest message) {
539         try {
540             final ClientIdentifier clientId = message.getTarget();
541             final LeaderFrontendState existing = findFrontend(clientId);
542             if (existing != null) {
543                 existing.touch();
544             }
545
546             if (!isLeader() || !isLeaderActive()) {
547                 LOG.info("{}: not currently leader, rejecting request {}. isLeader: {}, isLeaderActive: {},"
548                                 + "isLeadershipTransferInProgress: {}.",
549                         persistenceId(), message, isLeader(), isLeaderActive(), isLeadershipTransferInProgress());
550                 throw new NotLeaderException(getSelf());
551             }
552
553             final ABIVersion selectedVersion = selectVersion(message);
554             final LeaderFrontendState frontend;
555             if (existing == null) {
556                 frontend = new LeaderFrontendState.Enabled(persistenceId(), clientId, store);
557                 knownFrontends.put(clientId.getFrontendId(), frontend);
558                 LOG.debug("{}: created state {} for client {}", persistenceId(), frontend, clientId);
559             } else {
560                 frontend = existing;
561             }
562
563             frontend.reconnect();
564             message.getReplyTo().tell(new ConnectClientSuccess(message.getTarget(), message.getSequence(), getSelf(),
565                 ImmutableList.of(), store.getDataTree(), CLIENT_MAX_MESSAGES).toVersion(selectedVersion),
566                 ActorRef.noSender());
567         } catch (RequestException | RuntimeException e) {
568             message.getReplyTo().tell(new Failure(e), ActorRef.noSender());
569         }
570     }
571
572     private @Nullable RequestSuccess<?, ?> handleRequest(final RequestEnvelope envelope, final long now)
573             throws RequestException {
574         // We are not the leader, hence we want to fail-fast.
575         if (!isLeader() || paused || !isLeaderActive()) {
576             LOG.debug("{}: not currently active leader, rejecting request {}. isLeader: {}, isLeaderActive: {},"
577                             + "isLeadershipTransferInProgress: {}, paused: {}",
578                     persistenceId(), envelope, isLeader(), isLeaderActive(), isLeadershipTransferInProgress(), paused);
579             throw new NotLeaderException(getSelf());
580         }
581
582         final Request<?, ?> request = envelope.getMessage();
583         if (request instanceof TransactionRequest) {
584             final TransactionRequest<?> txReq = (TransactionRequest<?>)request;
585             final ClientIdentifier clientId = txReq.getTarget().getHistoryId().getClientId();
586             return getFrontend(clientId).handleTransactionRequest(txReq, envelope, now);
587         } else if (request instanceof LocalHistoryRequest) {
588             final LocalHistoryRequest<?> lhReq = (LocalHistoryRequest<?>)request;
589             final ClientIdentifier clientId = lhReq.getTarget().getClientId();
590             return getFrontend(clientId).handleLocalHistoryRequest(lhReq, envelope, now);
591         } else {
592             LOG.warn("{}: rejecting unsupported request {}", persistenceId(), request);
593             throw new UnsupportedRequestException(request);
594         }
595     }
596
597     private boolean hasLeader() {
598         return getLeaderId() != null;
599     }
600
601     public int getPendingTxCommitQueueSize() {
602         return store.getQueueSize();
603     }
604
605     public int getCohortCacheSize() {
606         return commitCoordinator.getCohortCacheSize();
607     }
608
609     @Override
610     protected Optional<ActorRef> getRoleChangeNotifier() {
611         return roleChangeNotifier;
612     }
613
614     String getShardName() {
615         return shardName;
616     }
617
618     @Override
619     protected LeaderStateChanged newLeaderStateChanged(final String memberId, final String leaderId,
620             final short leaderPayloadVersion) {
621         return isLeader() ? new ShardLeaderStateChanged(memberId, leaderId, store.getDataTree(), leaderPayloadVersion)
622                 : new ShardLeaderStateChanged(memberId, leaderId, leaderPayloadVersion);
623     }
624
625     protected void onDatastoreContext(final DatastoreContext context) {
626         datastoreContext = context;
627
628         setTransactionCommitTimeout();
629
630         setPersistence(datastoreContext.isPersistent());
631
632         updateConfigParams(datastoreContext.getShardRaftConfig());
633     }
634
635     // applyState() will be invoked once consensus is reached on the payload
636     void persistPayload(final Identifier id, final Payload payload, final boolean batchHint) {
637         boolean canSkipPayload = !hasFollowers() && !persistence().isRecoveryApplicable();
638         if (canSkipPayload) {
639             applyState(self(), id, payload);
640         } else {
641             // We are faking the sender
642             persistData(self(), id, payload, batchHint);
643         }
644     }
645
646     private void handleCommitTransaction(final CommitTransaction commit) {
647         final TransactionIdentifier txId = commit.getTransactionId();
648         if (isLeader()) {
649             askProtocolEncountered(txId);
650             commitCoordinator.handleCommit(txId, getSender(), this);
651         } else {
652             ActorSelection leader = getLeader();
653             if (leader == null) {
654                 messageRetrySupport.addMessageToRetry(commit, getSender(), "Could not commit transaction " + txId);
655             } else {
656                 LOG.debug("{}: Forwarding CommitTransaction to leader {}", persistenceId(), leader);
657                 leader.forward(commit, getContext());
658             }
659         }
660     }
661
662     private void handleCanCommitTransaction(final CanCommitTransaction canCommit) {
663         final TransactionIdentifier txId = canCommit.getTransactionId();
664         LOG.debug("{}: Can committing transaction {}", persistenceId(), txId);
665
666         if (isLeader()) {
667             askProtocolEncountered(txId);
668             commitCoordinator.handleCanCommit(txId, getSender(), this);
669         } else {
670             ActorSelection leader = getLeader();
671             if (leader == null) {
672                 messageRetrySupport.addMessageToRetry(canCommit, getSender(),
673                         "Could not canCommit transaction " + txId);
674             } else {
675                 LOG.debug("{}: Forwarding CanCommitTransaction to leader {}", persistenceId(), leader);
676                 leader.forward(canCommit, getContext());
677             }
678         }
679     }
680
681     @SuppressWarnings("checkstyle:IllegalCatch")
682     protected void handleBatchedModificationsLocal(final BatchedModifications batched, final ActorRef sender) {
683         askProtocolEncountered(batched.getTransactionId());
684
685         try {
686             commitCoordinator.handleBatchedModifications(batched, sender, this);
687         } catch (Exception e) {
688             LOG.error("{}: Error handling BatchedModifications for Tx {}", persistenceId(),
689                     batched.getTransactionId(), e);
690             sender.tell(new Failure(e), getSelf());
691         }
692     }
693
694     private void handleBatchedModifications(final BatchedModifications batched) {
695         // This message is sent to prepare the modifications transaction directly on the Shard as an
696         // optimization to avoid the extra overhead of a separate ShardTransaction actor. On the last
697         // BatchedModifications message, the caller sets the ready flag in the message indicating
698         // modifications are complete. The reply contains the cohort actor path (this actor) for the caller
699         // to initiate the 3-phase commit. This also avoids the overhead of sending an additional
700         // ReadyTransaction message.
701
702         // If we're not the leader then forward to the leader. This is a safety measure - we shouldn't
703         // normally get here if we're not the leader as the front-end (TransactionProxy) should determine
704         // the primary/leader shard. However with timing and caching on the front-end, there's a small
705         // window where it could have a stale leader during leadership transitions.
706         //
707         boolean isLeaderActive = isLeaderActive();
708         if (isLeader() && isLeaderActive) {
709             handleBatchedModificationsLocal(batched, getSender());
710         } else {
711             ActorSelection leader = getLeader();
712             if (!isLeaderActive || leader == null) {
713                 messageRetrySupport.addMessageToRetry(batched, getSender(),
714                         "Could not process BatchedModifications " + batched.getTransactionId());
715             } else {
716                 // If this is not the first batch and leadership changed in between batched messages,
717                 // we need to reconstruct previous BatchedModifications from the transaction
718                 // DataTreeModification, honoring the max batched modification count, and forward all the
719                 // previous BatchedModifications to the new leader.
720                 Collection<BatchedModifications> newModifications = commitCoordinator
721                         .createForwardedBatchedModifications(batched,
722                                 datastoreContext.getShardBatchedModificationCount());
723
724                 LOG.debug("{}: Forwarding {} BatchedModifications to leader {}", persistenceId(),
725                         newModifications.size(), leader);
726
727                 for (BatchedModifications bm : newModifications) {
728                     leader.forward(bm, getContext());
729                 }
730             }
731         }
732     }
733
734     private boolean failIfIsolatedLeader(final ActorRef sender) {
735         if (isIsolatedLeader()) {
736             sender.tell(new Failure(new NoShardLeaderException(String.format(
737                     "Shard %s was the leader but has lost contact with all of its followers. Either all"
738                     + " other follower nodes are down or this node is isolated by a network partition.",
739                     persistenceId()))), getSelf());
740             return true;
741         }
742
743         return false;
744     }
745
746     protected boolean isIsolatedLeader() {
747         return getRaftState() == RaftState.IsolatedLeader;
748     }
749
750     @SuppressWarnings("checkstyle:IllegalCatch")
751     private void handleReadyLocalTransaction(final ReadyLocalTransaction message) {
752         LOG.debug("{}: handleReadyLocalTransaction for {}", persistenceId(), message.getTransactionId());
753
754         boolean isLeaderActive = isLeaderActive();
755         if (isLeader() && isLeaderActive) {
756             try {
757                 commitCoordinator.handleReadyLocalTransaction(message, getSender(), this);
758             } catch (Exception e) {
759                 LOG.error("{}: Error handling ReadyLocalTransaction for Tx {}", persistenceId(),
760                         message.getTransactionId(), e);
761                 getSender().tell(new Failure(e), getSelf());
762             }
763         } else {
764             ActorSelection leader = getLeader();
765             if (!isLeaderActive || leader == null) {
766                 messageRetrySupport.addMessageToRetry(message, getSender(),
767                         "Could not process ready local transaction " + message.getTransactionId());
768             } else {
769                 LOG.debug("{}: Forwarding ReadyLocalTransaction to leader {}", persistenceId(), leader);
770                 message.setRemoteVersion(getCurrentBehavior().getLeaderPayloadVersion());
771                 leader.forward(message, getContext());
772             }
773         }
774     }
775
776     private void handleForwardedReadyTransaction(final ForwardedReadyTransaction forwardedReady) {
777         LOG.debug("{}: handleForwardedReadyTransaction for {}", persistenceId(), forwardedReady.getTransactionId());
778
779         boolean isLeaderActive = isLeaderActive();
780         if (isLeader() && isLeaderActive) {
781             askProtocolEncountered(forwardedReady.getTransactionId());
782             commitCoordinator.handleForwardedReadyTransaction(forwardedReady, getSender(), this);
783         } else {
784             ActorSelection leader = getLeader();
785             if (!isLeaderActive || leader == null) {
786                 messageRetrySupport.addMessageToRetry(forwardedReady, getSender(),
787                         "Could not process forwarded ready transaction " + forwardedReady.getTransactionId());
788             } else {
789                 LOG.debug("{}: Forwarding ForwardedReadyTransaction to leader {}", persistenceId(), leader);
790
791                 ReadyLocalTransaction readyLocal = new ReadyLocalTransaction(forwardedReady.getTransactionId(),
792                         forwardedReady.getTransaction().getSnapshot(), forwardedReady.isDoImmediateCommit(),
793                         forwardedReady.getParticipatingShardNames());
794                 readyLocal.setRemoteVersion(getCurrentBehavior().getLeaderPayloadVersion());
795                 leader.forward(readyLocal, getContext());
796             }
797         }
798     }
799
800     private void handleAbortTransaction(final AbortTransaction abort) {
801         final TransactionIdentifier transactionId = abort.getTransactionId();
802         askProtocolEncountered(transactionId);
803         doAbortTransaction(transactionId, getSender());
804     }
805
806     void doAbortTransaction(final Identifier transactionID, final ActorRef sender) {
807         commitCoordinator.handleAbort(transactionID, sender, this);
808     }
809
810     private void handleCreateTransaction(final Object message) {
811         if (isLeader()) {
812             createTransaction(CreateTransaction.fromSerializable(message));
813         } else if (getLeader() != null) {
814             getLeader().forward(message, getContext());
815         } else {
816             getSender().tell(new Failure(new NoShardLeaderException(
817                     "Could not create a shard transaction", persistenceId())), getSelf());
818         }
819     }
820
821     private void closeTransactionChain(final CloseTransactionChain closeTransactionChain) {
822         if (isLeader()) {
823             final LocalHistoryIdentifier id = closeTransactionChain.getIdentifier();
824             askProtocolEncountered(id.getClientId());
825             store.closeTransactionChain(id);
826         } else if (getLeader() != null) {
827             getLeader().forward(closeTransactionChain, getContext());
828         } else {
829             LOG.warn("{}: Could not close transaction {}", persistenceId(), closeTransactionChain.getIdentifier());
830         }
831     }
832
833     @SuppressWarnings("checkstyle:IllegalCatch")
834     private void createTransaction(final CreateTransaction createTransaction) {
835         askProtocolEncountered(createTransaction.getTransactionId());
836
837         try {
838             if (TransactionType.fromInt(createTransaction.getTransactionType()) != TransactionType.READ_ONLY
839                     && failIfIsolatedLeader(getSender())) {
840                 return;
841             }
842
843             ActorRef transactionActor = createTransaction(createTransaction.getTransactionType(),
844                 createTransaction.getTransactionId());
845
846             getSender().tell(new CreateTransactionReply(Serialization.serializedActorPath(transactionActor),
847                     createTransaction.getTransactionId(), createTransaction.getVersion()).toSerializable(), getSelf());
848         } catch (Exception e) {
849             getSender().tell(new Failure(e), getSelf());
850         }
851     }
852
853     private ActorRef createTransaction(final int transactionType, final TransactionIdentifier transactionId) {
854         LOG.debug("{}: Creating transaction : {} ", persistenceId(), transactionId);
855         return transactionActorFactory.newShardTransaction(TransactionType.fromInt(transactionType),
856             transactionId);
857     }
858
859     // Called on leader only
860     private void askProtocolEncountered(final TransactionIdentifier transactionId) {
861         askProtocolEncountered(transactionId.getHistoryId().getClientId());
862     }
863
864     // Called on leader only
865     private void askProtocolEncountered(final ClientIdentifier clientId) {
866         final FrontendIdentifier frontend = clientId.getFrontendId();
867         final LeaderFrontendState state = knownFrontends.get(frontend);
868         if (!(state instanceof LeaderFrontendState.Disabled)) {
869             LOG.debug("{}: encountered ask-based client {}, disabling transaction tracking", persistenceId(), clientId);
870             if (knownFrontends.isEmpty()) {
871                 knownFrontends = new HashMap<>();
872             }
873             knownFrontends.put(frontend, new LeaderFrontendState.Disabled(persistenceId(), clientId, getDataStore()));
874
875             persistPayload(clientId, DisableTrackingPayload.create(clientId,
876                 datastoreContext.getInitialPayloadSerializedBufferCapacity()), false);
877         }
878     }
879
880     private void updateSchemaContext(final UpdateSchemaContext message) {
881         updateSchemaContext(message.getSchemaContext());
882     }
883
884     @VisibleForTesting
885     void updateSchemaContext(final SchemaContext schemaContext) {
886         store.updateSchemaContext(schemaContext);
887     }
888
889     private boolean isMetricsCaptureEnabled() {
890         CommonConfig config = new CommonConfig(getContext().system().settings().config());
891         return config.isMetricCaptureEnabled();
892     }
893
894     @Override
895     @VisibleForTesting
896     public RaftActorSnapshotCohort getRaftActorSnapshotCohort() {
897         return snapshotCohort;
898     }
899
900     @Override
901     protected RaftActorRecoveryCohort getRaftActorRecoveryCohort() {
902         if (restoreFromSnapshot == null) {
903             return ShardRecoveryCoordinator.create(store, persistenceId(), LOG);
904         }
905
906         return ShardRecoveryCoordinator.forSnapshot(store, persistenceId(), LOG, restoreFromSnapshot.getSnapshot());
907     }
908
909     @Override
910     protected void onRecoveryComplete() {
911         restoreFromSnapshot = null;
912
913         //notify shard manager
914         getContext().parent().tell(new ActorInitialized(), getSelf());
915
916         // Being paranoid here - this method should only be called once but just in case...
917         if (txCommitTimeoutCheckSchedule == null) {
918             // Schedule a message to be periodically sent to check if the current in-progress
919             // transaction should be expired and aborted.
920             FiniteDuration period = FiniteDuration.create(transactionCommitTimeout / 3, TimeUnit.MILLISECONDS);
921             txCommitTimeoutCheckSchedule = getContext().system().scheduler().schedule(
922                     period, period, getSelf(),
923                     TX_COMMIT_TIMEOUT_CHECK_MESSAGE, getContext().dispatcher(), ActorRef.noSender());
924         }
925     }
926
927     @Override
928     protected void applyState(final ActorRef clientActor, final Identifier identifier, final Object data) {
929         if (data instanceof Payload) {
930             if (data instanceof DisableTrackingPayload) {
931                 disableTracking((DisableTrackingPayload) data);
932                 return;
933             }
934
935             try {
936                 store.applyReplicatedPayload(identifier, (Payload)data);
937             } catch (DataValidationFailedException | IOException e) {
938                 LOG.error("{}: Error applying replica {}", persistenceId(), identifier, e);
939             }
940         } else {
941             LOG.error("{}: Unknown state for {} received {}", persistenceId(), identifier, data);
942         }
943     }
944
945     @Override
946     protected void onStateChanged() {
947         boolean isLeader = isLeader();
948         boolean hasLeader = hasLeader();
949         treeChangeSupport.onLeadershipChange(isLeader, hasLeader);
950
951         // If this actor is no longer the leader close all the transaction chains
952         if (!isLeader) {
953             if (LOG.isDebugEnabled()) {
954                 LOG.debug(
955                     "{}: onStateChanged: Closing all transaction chains because shard {} is no longer the leader",
956                     persistenceId(), getId());
957             }
958
959             paused = false;
960             store.purgeLeaderState();
961         }
962
963         if (hasLeader && !isIsolatedLeader()) {
964             messageRetrySupport.retryMessages();
965         }
966     }
967
968     @Override
969     protected void onLeaderChanged(final String oldLeader, final String newLeader) {
970         shardMBean.incrementLeadershipChangeCount();
971         paused = false;
972
973         if (!isLeader()) {
974             if (!knownFrontends.isEmpty()) {
975                 LOG.debug("{}: removing frontend state for {}", persistenceId(), knownFrontends.keySet());
976                 knownFrontends = ImmutableMap.of();
977             }
978
979             requestMessageAssembler.close();
980
981             if (!hasLeader()) {
982                 // No leader anywhere, nothing else to do
983                 return;
984             }
985
986             // Another leader was elected. If we were the previous leader and had pending transactions, convert
987             // them to transaction messages and send to the new leader.
988             ActorSelection leader = getLeader();
989             if (leader != null) {
990                 Collection<?> messagesToForward = convertPendingTransactionsToMessages();
991
992                 if (!messagesToForward.isEmpty()) {
993                     LOG.debug("{}: Forwarding {} pending transaction messages to leader {}", persistenceId(),
994                             messagesToForward.size(), leader);
995
996                     for (Object message : messagesToForward) {
997                         LOG.debug("{}: Forwarding pending transaction message {}", persistenceId(), message);
998
999                         leader.tell(message, self());
1000                     }
1001                 }
1002             } else {
1003                 commitCoordinator.abortPendingTransactions("The transacton was aborted due to inflight leadership "
1004                         + "change and the leader address isn't available.", this);
1005             }
1006         } else {
1007             // We have become the leader, we need to reconstruct frontend state
1008             knownFrontends = Verify.verifyNotNull(frontendMetadata.toLeaderState(this));
1009             LOG.debug("{}: became leader with frontend state for {}", persistenceId(), knownFrontends.keySet());
1010         }
1011
1012         if (!isIsolatedLeader()) {
1013             messageRetrySupport.retryMessages();
1014         }
1015     }
1016
1017     /**
1018      * Clears all pending transactions and converts them to messages to be forwarded to a new leader.
1019      *
1020      * @return the converted messages
1021      */
1022     public Collection<?> convertPendingTransactionsToMessages() {
1023         return commitCoordinator.convertPendingTransactionsToMessages(
1024                 datastoreContext.getShardBatchedModificationCount());
1025     }
1026
1027     @Override
1028     protected void pauseLeader(final Runnable operation) {
1029         LOG.debug("{}: In pauseLeader, operation: {}", persistenceId(), operation);
1030         paused = true;
1031
1032         // Tell-based protocol can replay transaction state, so it is safe to blow it up when we are paused.
1033         if (datastoreContext.isUseTellBasedProtocol()) {
1034             knownFrontends.values().forEach(LeaderFrontendState::retire);
1035             knownFrontends = ImmutableMap.of();
1036         }
1037
1038         store.setRunOnPendingTransactionsComplete(operation);
1039     }
1040
1041     @Override
1042     protected void unpauseLeader() {
1043         LOG.debug("{}: In unpauseLeader", persistenceId());
1044         paused = false;
1045
1046         store.setRunOnPendingTransactionsComplete(null);
1047
1048         // Restore tell-based protocol state as if we were becoming the leader
1049         knownFrontends = Verify.verifyNotNull(frontendMetadata.toLeaderState(this));
1050     }
1051
1052     @Override
1053     protected OnDemandRaftState.AbstractBuilder<?, ?> newOnDemandRaftStateBuilder() {
1054         return OnDemandShardState.newBuilder().treeChangeListenerActors(treeChangeSupport.getListenerActors())
1055                 .commitCohortActors(store.getCohortActors());
1056     }
1057
1058     @Override
1059     public String persistenceId() {
1060         return this.name;
1061     }
1062
1063     @VisibleForTesting
1064     ShardCommitCoordinator getCommitCoordinator() {
1065         return commitCoordinator;
1066     }
1067
1068     public DatastoreContext getDatastoreContext() {
1069         return datastoreContext;
1070     }
1071
1072     @VisibleForTesting
1073     public ShardDataTree getDataStore() {
1074         return store;
1075     }
1076
1077     @VisibleForTesting
1078     ShardStats getShardMBean() {
1079         return shardMBean;
1080     }
1081
1082     public static Builder builder() {
1083         return new Builder();
1084     }
1085
1086     public abstract static class AbstractBuilder<T extends AbstractBuilder<T, S>, S extends Shard> {
1087         private final Class<S> shardClass;
1088         private ShardIdentifier id;
1089         private Map<String, String> peerAddresses = Collections.emptyMap();
1090         private DatastoreContext datastoreContext;
1091         private SchemaContextProvider schemaContextProvider;
1092         private DatastoreSnapshot.ShardSnapshot restoreFromSnapshot;
1093         private DataTree dataTree;
1094         private volatile boolean sealed;
1095
1096         protected AbstractBuilder(final Class<S> shardClass) {
1097             this.shardClass = shardClass;
1098         }
1099
1100         protected void checkSealed() {
1101             Preconditions.checkState(!sealed, "Builder isalready sealed - further modifications are not allowed");
1102         }
1103
1104         @SuppressWarnings("unchecked")
1105         private T self() {
1106             return (T) this;
1107         }
1108
1109         public T id(final ShardIdentifier newId) {
1110             checkSealed();
1111             this.id = newId;
1112             return self();
1113         }
1114
1115         public T peerAddresses(final Map<String, String> newPeerAddresses) {
1116             checkSealed();
1117             this.peerAddresses = newPeerAddresses;
1118             return self();
1119         }
1120
1121         public T datastoreContext(final DatastoreContext newDatastoreContext) {
1122             checkSealed();
1123             this.datastoreContext = newDatastoreContext;
1124             return self();
1125         }
1126
1127         public T schemaContextProvider(final SchemaContextProvider newSchemaContextProvider) {
1128             checkSealed();
1129             this.schemaContextProvider = Preconditions.checkNotNull(newSchemaContextProvider);
1130             return self();
1131         }
1132
1133         public T restoreFromSnapshot(final DatastoreSnapshot.ShardSnapshot newRestoreFromSnapshot) {
1134             checkSealed();
1135             this.restoreFromSnapshot = newRestoreFromSnapshot;
1136             return self();
1137         }
1138
1139         public T dataTree(final DataTree newDataTree) {
1140             checkSealed();
1141             this.dataTree = newDataTree;
1142             return self();
1143         }
1144
1145         public ShardIdentifier getId() {
1146             return id;
1147         }
1148
1149         public Map<String, String> getPeerAddresses() {
1150             return peerAddresses;
1151         }
1152
1153         public DatastoreContext getDatastoreContext() {
1154             return datastoreContext;
1155         }
1156
1157         public SchemaContext getSchemaContext() {
1158             return Verify.verifyNotNull(schemaContextProvider.getSchemaContext());
1159         }
1160
1161         public DatastoreSnapshot.ShardSnapshot getRestoreFromSnapshot() {
1162             return restoreFromSnapshot;
1163         }
1164
1165         public DataTree getDataTree() {
1166             return dataTree;
1167         }
1168
1169         public TreeType getTreeType() {
1170             switch (datastoreContext.getLogicalStoreType()) {
1171                 case CONFIGURATION:
1172                     return TreeType.CONFIGURATION;
1173                 case OPERATIONAL:
1174                     return TreeType.OPERATIONAL;
1175                 default:
1176                     throw new IllegalStateException("Unhandled logical store type "
1177                             + datastoreContext.getLogicalStoreType());
1178             }
1179         }
1180
1181         protected void verify() {
1182             Preconditions.checkNotNull(id, "id should not be null");
1183             Preconditions.checkNotNull(peerAddresses, "peerAddresses should not be null");
1184             Preconditions.checkNotNull(datastoreContext, "dataStoreContext should not be null");
1185             Preconditions.checkNotNull(schemaContextProvider, "schemaContextProvider should not be null");
1186         }
1187
1188         public Props props() {
1189             sealed = true;
1190             verify();
1191             return Props.create(shardClass, this);
1192         }
1193     }
1194
1195     public static class Builder extends AbstractBuilder<Builder, Shard> {
1196         Builder() {
1197             super(Shard.class);
1198         }
1199     }
1200
1201     Ticker ticker() {
1202         return Ticker.systemTicker();
1203     }
1204
1205     void scheduleNextPendingTransaction() {
1206         self().tell(RESUME_NEXT_PENDING_TRANSACTION, ActorRef.noSender());
1207     }
1208 }