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