Remove PersistAbortTransactionPayload
[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.concurrent.TimeUnit;
36 import org.eclipse.jdt.annotation.NonNull;
37 import org.eclipse.jdt.annotation.Nullable;
38 import org.opendaylight.controller.cluster.access.ABIVersion;
39 import org.opendaylight.controller.cluster.access.commands.ConnectClientRequest;
40 import org.opendaylight.controller.cluster.access.commands.ConnectClientSuccess;
41 import org.opendaylight.controller.cluster.access.commands.LocalHistoryRequest;
42 import org.opendaylight.controller.cluster.access.commands.NotLeaderException;
43 import org.opendaylight.controller.cluster.access.commands.OutOfSequenceEnvelopeException;
44 import org.opendaylight.controller.cluster.access.commands.TransactionRequest;
45 import org.opendaylight.controller.cluster.access.concepts.ClientIdentifier;
46 import org.opendaylight.controller.cluster.access.concepts.FrontendIdentifier;
47 import org.opendaylight.controller.cluster.access.concepts.LocalHistoryIdentifier;
48 import org.opendaylight.controller.cluster.access.concepts.Request;
49 import org.opendaylight.controller.cluster.access.concepts.RequestEnvelope;
50 import org.opendaylight.controller.cluster.access.concepts.RequestException;
51 import org.opendaylight.controller.cluster.access.concepts.RequestSuccess;
52 import org.opendaylight.controller.cluster.access.concepts.RetiredGenerationException;
53 import org.opendaylight.controller.cluster.access.concepts.RuntimeRequestException;
54 import org.opendaylight.controller.cluster.access.concepts.SliceableMessage;
55 import org.opendaylight.controller.cluster.access.concepts.TransactionIdentifier;
56 import org.opendaylight.controller.cluster.access.concepts.UnsupportedRequestException;
57 import org.opendaylight.controller.cluster.common.actor.CommonConfig;
58 import org.opendaylight.controller.cluster.common.actor.Dispatchers;
59 import org.opendaylight.controller.cluster.common.actor.Dispatchers.DispatcherType;
60 import org.opendaylight.controller.cluster.common.actor.MessageTracker;
61 import org.opendaylight.controller.cluster.common.actor.MessageTracker.Error;
62 import org.opendaylight.controller.cluster.common.actor.MeteringBehavior;
63 import org.opendaylight.controller.cluster.datastore.exceptions.NoShardLeaderException;
64 import org.opendaylight.controller.cluster.datastore.identifiers.ShardIdentifier;
65 import org.opendaylight.controller.cluster.datastore.jmx.mbeans.shard.ShardDataTreeListenerInfoMXBeanImpl;
66 import org.opendaylight.controller.cluster.datastore.jmx.mbeans.shard.ShardMBeanFactory;
67 import org.opendaylight.controller.cluster.datastore.jmx.mbeans.shard.ShardStats;
68 import org.opendaylight.controller.cluster.datastore.messages.AbortTransaction;
69 import org.opendaylight.controller.cluster.datastore.messages.ActorInitialized;
70 import org.opendaylight.controller.cluster.datastore.messages.BatchedModifications;
71 import org.opendaylight.controller.cluster.datastore.messages.CanCommitTransaction;
72 import org.opendaylight.controller.cluster.datastore.messages.CloseTransactionChain;
73 import org.opendaylight.controller.cluster.datastore.messages.CommitTransaction;
74 import org.opendaylight.controller.cluster.datastore.messages.CreateTransaction;
75 import org.opendaylight.controller.cluster.datastore.messages.CreateTransactionReply;
76 import org.opendaylight.controller.cluster.datastore.messages.ForwardedReadyTransaction;
77 import org.opendaylight.controller.cluster.datastore.messages.GetShardDataTree;
78 import org.opendaylight.controller.cluster.datastore.messages.MakeLeaderLocal;
79 import org.opendaylight.controller.cluster.datastore.messages.OnDemandShardState;
80 import org.opendaylight.controller.cluster.datastore.messages.PeerAddressResolved;
81 import org.opendaylight.controller.cluster.datastore.messages.ReadyLocalTransaction;
82 import org.opendaylight.controller.cluster.datastore.messages.RegisterDataTreeChangeListener;
83 import org.opendaylight.controller.cluster.datastore.messages.ShardLeaderStateChanged;
84 import org.opendaylight.controller.cluster.datastore.messages.UpdateSchemaContext;
85 import org.opendaylight.controller.cluster.datastore.persisted.DatastoreSnapshot;
86 import org.opendaylight.controller.cluster.datastore.persisted.DatastoreSnapshot.ShardSnapshot;
87 import org.opendaylight.controller.cluster.datastore.persisted.DisableTrackingPayload;
88 import org.opendaylight.controller.cluster.messaging.MessageAssembler;
89 import org.opendaylight.controller.cluster.messaging.MessageSlicer;
90 import org.opendaylight.controller.cluster.messaging.SliceOptions;
91 import org.opendaylight.controller.cluster.notifications.LeaderStateChanged;
92 import org.opendaylight.controller.cluster.notifications.RegisterRoleChangeListener;
93 import org.opendaylight.controller.cluster.notifications.RoleChangeNotifier;
94 import org.opendaylight.controller.cluster.raft.LeadershipTransferFailedException;
95 import org.opendaylight.controller.cluster.raft.RaftActor;
96 import org.opendaylight.controller.cluster.raft.RaftActorRecoveryCohort;
97 import org.opendaylight.controller.cluster.raft.RaftActorSnapshotCohort;
98 import org.opendaylight.controller.cluster.raft.RaftState;
99 import org.opendaylight.controller.cluster.raft.base.messages.FollowerInitialSyncUpStatus;
100 import org.opendaylight.controller.cluster.raft.client.messages.OnDemandRaftState;
101 import org.opendaylight.controller.cluster.raft.messages.AppendEntriesReply;
102 import org.opendaylight.controller.cluster.raft.messages.RequestLeadership;
103 import org.opendaylight.controller.cluster.raft.messages.ServerRemoved;
104 import org.opendaylight.controller.cluster.raft.protobuff.client.messages.Payload;
105 import org.opendaylight.yangtools.concepts.Identifier;
106 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTree;
107 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataValidationFailedException;
108 import org.opendaylight.yangtools.yang.data.api.schema.tree.TreeType;
109 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
110 import org.opendaylight.yangtools.yang.model.api.SchemaContextProvider;
111 import scala.concurrent.duration.FiniteDuration;
112
113 /**
114  * A Shard represents a portion of the logical data tree.
115  *
116  * <p>
117  * Our Shard uses InMemoryDataTree as it's internal representation and delegates all requests it
118  */
119 public class Shard extends RaftActor {
120
121     @VisibleForTesting
122     static final Object TX_COMMIT_TIMEOUT_CHECK_MESSAGE = new Object() {
123         @Override
124         public String toString() {
125             return "txCommitTimeoutCheck";
126         }
127     };
128
129     @VisibleForTesting
130     static final Object GET_SHARD_MBEAN_MESSAGE = new Object() {
131         @Override
132         public String toString() {
133             return "getShardMBeanMessage";
134         }
135     };
136
137     static final Object RESUME_NEXT_PENDING_TRANSACTION = new Object() {
138         @Override
139         public String toString() {
140             return "resumeNextPendingTransaction";
141         }
142     };
143
144     // FIXME: shard names should be encapsulated in their own class and this should be exposed as a constant.
145     public static final String DEFAULT_NAME = "default";
146
147     private static final Collection<ABIVersion> SUPPORTED_ABIVERSIONS;
148
149     static {
150         final ABIVersion[] values = ABIVersion.values();
151         final ABIVersion[] real = Arrays.copyOfRange(values, 1, values.length - 1);
152         SUPPORTED_ABIVERSIONS = ImmutableList.copyOf(real).reverse();
153     }
154
155     // FIXME: make this a dynamic property based on mailbox size and maximum number of clients
156     private static final int CLIENT_MAX_MESSAGES = 1000;
157
158     // The state of this Shard
159     private final ShardDataTree store;
160
161     /// The name of this shard
162     private final String name;
163
164     private final String shardName;
165
166     private final ShardStats shardMBean;
167
168     private final ShardDataTreeListenerInfoMXBeanImpl listenerInfoMXBean;
169
170     private DatastoreContext datastoreContext;
171
172     private final ShardCommitCoordinator commitCoordinator;
173
174     private long transactionCommitTimeout;
175
176     private Cancellable txCommitTimeoutCheckSchedule;
177
178     private final Optional<ActorRef> roleChangeNotifier;
179
180     private final MessageTracker appendEntriesReplyTracker;
181
182     private final ShardTransactionActorFactory transactionActorFactory;
183
184     private final ShardSnapshotCohort snapshotCohort;
185
186     private final DataTreeChangeListenerSupport treeChangeSupport = new DataTreeChangeListenerSupport(this);
187
188     private ShardSnapshot restoreFromSnapshot;
189
190     private final ShardTransactionMessageRetrySupport messageRetrySupport;
191
192     private final FrontendMetadata frontendMetadata;
193     private Map<FrontendIdentifier, LeaderFrontendState> knownFrontends = ImmutableMap.of();
194     private boolean paused;
195
196     private final MessageSlicer responseMessageSlicer;
197     private final Dispatchers dispatchers;
198
199     private final MessageAssembler requestMessageAssembler;
200
201     protected Shard(final AbstractBuilder<?, ?> builder) {
202         super(builder.getId().toString(), builder.getPeerAddresses(),
203                 Optional.of(builder.getDatastoreContext().getShardRaftConfig()), DataStoreVersions.CURRENT_VERSION);
204
205         this.name = builder.getId().toString();
206         this.shardName = builder.getId().getShardName();
207         this.datastoreContext = builder.getDatastoreContext();
208         this.restoreFromSnapshot = builder.getRestoreFromSnapshot();
209         this.frontendMetadata = new FrontendMetadata(name);
210
211         setPersistence(datastoreContext.isPersistent());
212
213         LOG.info("Shard created : {}, persistent : {}", name, datastoreContext.isPersistent());
214
215         ShardDataTreeChangeListenerPublisherActorProxy treeChangeListenerPublisher =
216                 new ShardDataTreeChangeListenerPublisherActorProxy(getContext(), name + "-DTCL-publisher", name);
217         if (builder.getDataTree() != null) {
218             store = new ShardDataTree(this, builder.getSchemaContext(), builder.getDataTree(),
219                     treeChangeListenerPublisher, name, frontendMetadata);
220         } else {
221             store = new ShardDataTree(this, builder.getSchemaContext(), builder.getTreeType(),
222                     builder.getDatastoreContext().getStoreRoot(), treeChangeListenerPublisher, name, frontendMetadata);
223         }
224
225         shardMBean = ShardMBeanFactory.getShardStatsMBean(name, datastoreContext.getDataStoreMXBeanType(), this);
226
227         if (isMetricsCaptureEnabled()) {
228             getContext().become(new MeteringBehavior(this));
229         }
230
231         commitCoordinator = new ShardCommitCoordinator(store, LOG, this.name);
232
233         setTransactionCommitTimeout();
234
235         // create a notifier actor for each cluster member
236         roleChangeNotifier = createRoleChangeNotifier(name);
237
238         appendEntriesReplyTracker = new MessageTracker(AppendEntriesReply.class,
239                 getRaftActorContext().getConfigParams().getIsolatedCheckIntervalInMillis());
240
241         dispatchers = new Dispatchers(context().system().dispatchers());
242         transactionActorFactory = new ShardTransactionActorFactory(store, datastoreContext,
243             dispatchers.getDispatcherPath(Dispatchers.DispatcherType.Transaction),
244                 self(), getContext(), shardMBean, builder.getId().getShardName());
245
246         snapshotCohort = ShardSnapshotCohort.create(getContext(), builder.getId().getMemberName(), store, LOG,
247             this.name);
248
249         messageRetrySupport = new ShardTransactionMessageRetrySupport(this);
250
251         responseMessageSlicer = MessageSlicer.builder().logContext(this.name)
252                 .messageSliceSize(datastoreContext.getMaximumMessageSliceSize())
253                 .fileBackedStreamFactory(getRaftActorContext().getFileBackedOutputStreamFactory())
254                 .expireStateAfterInactivity(2, TimeUnit.MINUTES).build();
255
256         requestMessageAssembler = MessageAssembler.builder().logContext(this.name)
257                 .fileBackedStreamFactory(getRaftActorContext().getFileBackedOutputStreamFactory())
258                 .assembledMessageCallback((message, sender) -> self().tell(message, sender))
259                 .expireStateAfterInactivity(datastoreContext.getRequestTimeout(), TimeUnit.NANOSECONDS).build();
260
261         listenerInfoMXBean = new ShardDataTreeListenerInfoMXBeanImpl(name, datastoreContext.getDataStoreMXBeanType(),
262                 self());
263         listenerInfoMXBean.register();
264     }
265
266     private void setTransactionCommitTimeout() {
267         transactionCommitTimeout = TimeUnit.MILLISECONDS.convert(
268                 datastoreContext.getShardTransactionCommitTimeoutInSeconds(), TimeUnit.SECONDS) / 2;
269     }
270
271     private Optional<ActorRef> createRoleChangeNotifier(final String shardId) {
272         ActorRef shardRoleChangeNotifier = this.getContext().actorOf(
273             RoleChangeNotifier.getProps(shardId), shardId + "-notifier");
274         return Optional.of(shardRoleChangeNotifier);
275     }
276
277     @Override
278     public void postStop() {
279         LOG.info("Stopping Shard {}", persistenceId());
280
281         super.postStop();
282
283         messageRetrySupport.close();
284
285         if (txCommitTimeoutCheckSchedule != null) {
286             txCommitTimeoutCheckSchedule.cancel();
287         }
288
289         commitCoordinator.abortPendingTransactions("Transaction aborted due to shutdown.", this);
290
291         shardMBean.unregisterMBean();
292         listenerInfoMXBean.unregister();
293     }
294
295     @Override
296     protected void handleRecover(final Object message) {
297         LOG.debug("{}: onReceiveRecover: Received message {} from {}", persistenceId(), message.getClass(),
298             getSender());
299
300         super.handleRecover(message);
301         if (LOG.isTraceEnabled()) {
302             appendEntriesReplyTracker.begin();
303         }
304     }
305
306     @Override
307     protected void handleNonRaftCommand(final Object message) {
308         try (MessageTracker.Context context = appendEntriesReplyTracker.received(message)) {
309             final Optional<Error> maybeError = context.error();
310             if (maybeError.isPresent()) {
311                 LOG.trace("{} : AppendEntriesReply failed to arrive at the expected interval {}", persistenceId(),
312                     maybeError.get());
313             }
314
315             store.resetTransactionBatch();
316
317             if (message instanceof RequestEnvelope) {
318                 handleRequestEnvelope((RequestEnvelope)message);
319             } else if (MessageAssembler.isHandledMessage(message)) {
320                 handleRequestAssemblerMessage(message);
321             } else if (message instanceof ConnectClientRequest) {
322                 handleConnectClient((ConnectClientRequest)message);
323             } else if (CreateTransaction.isSerializedType(message)) {
324                 handleCreateTransaction(message);
325             } else if (message instanceof BatchedModifications) {
326                 handleBatchedModifications((BatchedModifications)message);
327             } else if (message instanceof ForwardedReadyTransaction) {
328                 handleForwardedReadyTransaction((ForwardedReadyTransaction) message);
329             } else if (message instanceof ReadyLocalTransaction) {
330                 handleReadyLocalTransaction((ReadyLocalTransaction)message);
331             } else if (CanCommitTransaction.isSerializedType(message)) {
332                 handleCanCommitTransaction(CanCommitTransaction.fromSerializable(message));
333             } else if (CommitTransaction.isSerializedType(message)) {
334                 handleCommitTransaction(CommitTransaction.fromSerializable(message));
335             } else if (AbortTransaction.isSerializedType(message)) {
336                 handleAbortTransaction(AbortTransaction.fromSerializable(message));
337             } else if (CloseTransactionChain.isSerializedType(message)) {
338                 closeTransactionChain(CloseTransactionChain.fromSerializable(message));
339             } else if (message instanceof RegisterDataTreeChangeListener) {
340                 treeChangeSupport.onMessage((RegisterDataTreeChangeListener) message, isLeader(), hasLeader());
341             } else if (message instanceof UpdateSchemaContext) {
342                 updateSchemaContext((UpdateSchemaContext) message);
343             } else if (message instanceof PeerAddressResolved) {
344                 PeerAddressResolved resolved = (PeerAddressResolved) message;
345                 setPeerAddress(resolved.getPeerId(), resolved.getPeerAddress());
346             } else if (TX_COMMIT_TIMEOUT_CHECK_MESSAGE.equals(message)) {
347                 commitTimeoutCheck();
348             } else if (message instanceof DatastoreContext) {
349                 onDatastoreContext((DatastoreContext)message);
350             } else if (message instanceof RegisterRoleChangeListener) {
351                 roleChangeNotifier.get().forward(message, context());
352             } else if (message instanceof FollowerInitialSyncUpStatus) {
353                 shardMBean.setFollowerInitialSyncStatus(((FollowerInitialSyncUpStatus) message).isInitialSyncDone());
354                 context().parent().tell(message, self());
355             } else if (GET_SHARD_MBEAN_MESSAGE.equals(message)) {
356                 sender().tell(getShardMBean(), self());
357             } else if (message instanceof GetShardDataTree) {
358                 sender().tell(store.getDataTree(), self());
359             } else if (message instanceof ServerRemoved) {
360                 context().parent().forward(message, context());
361             } else if (ShardTransactionMessageRetrySupport.TIMER_MESSAGE_CLASS.isInstance(message)) {
362                 messageRetrySupport.onTimerMessage(message);
363             } else if (message instanceof DataTreeCohortActorRegistry.CohortRegistryCommand) {
364                 store.processCohortRegistryCommand(getSender(),
365                         (DataTreeCohortActorRegistry.CohortRegistryCommand) message);
366             } else if (message instanceof MakeLeaderLocal) {
367                 onMakeLeaderLocal();
368             } else if (RESUME_NEXT_PENDING_TRANSACTION.equals(message)) {
369                 store.resumeNextPendingTransaction();
370             } else if (!responseMessageSlicer.handleMessage(message)) {
371                 super.handleNonRaftCommand(message);
372             }
373         }
374     }
375
376     private void handleRequestAssemblerMessage(final Object message) {
377         dispatchers.getDispatcher(DispatcherType.Serialization).execute(() -> {
378             JavaSerializer.currentSystem().value_$eq((ExtendedActorSystem) context().system());
379             requestMessageAssembler.handleMessage(message, self());
380         });
381     }
382
383     @SuppressWarnings("checkstyle:IllegalCatch")
384     private void handleRequestEnvelope(final RequestEnvelope envelope) {
385         final long now = ticker().read();
386         try {
387             final RequestSuccess<?, ?> success = handleRequest(envelope, now);
388             if (success != null) {
389                 final long executionTimeNanos = ticker().read() - now;
390                 if (success instanceof SliceableMessage) {
391                     dispatchers.getDispatcher(DispatcherType.Serialization).execute(() ->
392                         responseMessageSlicer.slice(SliceOptions.builder().identifier(success.getTarget())
393                             .message(envelope.newSuccessEnvelope(success, executionTimeNanos))
394                             .sendTo(envelope.getMessage().getReplyTo()).replyTo(self())
395                             .onFailureCallback(t -> LOG.warn("Error slicing response {}", success, t)).build()));
396                 } else {
397                     envelope.sendSuccess(success, executionTimeNanos);
398                 }
399             }
400         } catch (RequestException e) {
401             LOG.debug("{}: request {} failed", persistenceId(), envelope, e);
402             envelope.sendFailure(e, ticker().read() - now);
403         } catch (Exception e) {
404             LOG.debug("{}: request {} caused failure", persistenceId(), envelope, e);
405             envelope.sendFailure(new RuntimeRequestException("Request failed to process", e),
406                 ticker().read() - now);
407         }
408     }
409
410     private void commitTimeoutCheck() {
411         store.checkForExpiredTransactions(transactionCommitTimeout, this::updateAccess);
412         commitCoordinator.checkForExpiredTransactions(transactionCommitTimeout, this);
413         requestMessageAssembler.checkExpiredAssembledMessageState();
414     }
415
416     private Optional<Long> updateAccess(final SimpleShardDataTreeCohort cohort) {
417         final FrontendIdentifier frontend = cohort.getIdentifier().getHistoryId().getClientId().getFrontendId();
418         final LeaderFrontendState state = knownFrontends.get(frontend);
419         if (state == null) {
420             // Not tell-based protocol, do nothing
421             return Optional.absent();
422         }
423
424         if (isIsolatedLeader()) {
425             // We are isolated and no new request can come through until we emerge from it. We are still updating
426             // liveness of frontend when we see it attempting to communicate. Use the last access timer.
427             return Optional.of(state.getLastSeenTicks());
428         }
429
430         // If this frontend has freshly connected, give it some time to catch up before killing its transactions.
431         return Optional.of(state.getLastConnectTicks());
432     }
433
434     private void disableTracking(final DisableTrackingPayload payload) {
435         final ClientIdentifier clientId = payload.getIdentifier();
436         LOG.debug("{}: disabling tracking of {}", persistenceId(), clientId);
437         frontendMetadata.disableTracking(clientId);
438
439         if (isLeader()) {
440             final FrontendIdentifier frontendId = clientId.getFrontendId();
441             final LeaderFrontendState frontend = knownFrontends.get(frontendId);
442             if (frontend != null) {
443                 if (clientId.equals(frontend.getIdentifier())) {
444                     if (!(frontend instanceof LeaderFrontendState.Disabled)) {
445                         verify(knownFrontends.replace(frontendId, frontend,
446                             new LeaderFrontendState.Disabled(persistenceId(), clientId, store)));
447                         LOG.debug("{}: leader state for {} disabled", persistenceId(), clientId);
448                     } else {
449                         LOG.debug("{}: leader state {} is already disabled", persistenceId(), frontend);
450                     }
451                 } else {
452                     LOG.debug("{}: leader state {} does not match {}", persistenceId(), frontend, clientId);
453                 }
454             } else {
455                 LOG.debug("{}: leader state for {} not found", persistenceId(), clientId);
456                 knownFrontends.put(frontendId, new LeaderFrontendState.Disabled(persistenceId(), clientId,
457                     getDataStore()));
458             }
459         }
460     }
461
462     private void onMakeLeaderLocal() {
463         LOG.debug("{}: onMakeLeaderLocal received", persistenceId());
464         if (isLeader()) {
465             getSender().tell(new Status.Success(null), getSelf());
466             return;
467         }
468
469         final ActorSelection leader = getLeader();
470
471         if (leader == null) {
472             // Leader is not present. The cluster is most likely trying to
473             // elect a leader and we should let that run its normal course
474
475             // TODO we can wait for the election to complete and retry the
476             // request. We can also let the caller retry by sending a flag
477             // in the response indicating the request is "reTryable".
478             getSender().tell(new Failure(
479                     new LeadershipTransferFailedException("We cannot initiate leadership transfer to local node. "
480                             + "Currently there is no leader for " + persistenceId())),
481                     getSelf());
482             return;
483         }
484
485         leader.tell(new RequestLeadership(getId(), getSender()), getSelf());
486     }
487
488     // Acquire our frontend tracking handle and verify generation matches
489     private @Nullable LeaderFrontendState findFrontend(final ClientIdentifier clientId) throws RequestException {
490         final LeaderFrontendState existing = knownFrontends.get(clientId.getFrontendId());
491         if (existing != null) {
492             final int cmp = Long.compareUnsigned(existing.getIdentifier().getGeneration(), clientId.getGeneration());
493             if (cmp == 0) {
494                 existing.touch();
495                 return existing;
496             }
497             if (cmp > 0) {
498                 LOG.debug("{}: rejecting request from outdated client {}", persistenceId(), clientId);
499                 throw new RetiredGenerationException(clientId.getGeneration(),
500                     existing.getIdentifier().getGeneration());
501             }
502
503             LOG.info("{}: retiring state {}, outdated by request from client {}", persistenceId(), existing, clientId);
504             existing.retire();
505             knownFrontends.remove(clientId.getFrontendId());
506         } else {
507             LOG.debug("{}: client {} is not yet known", persistenceId(), clientId);
508         }
509
510         return null;
511     }
512
513     private LeaderFrontendState getFrontend(final ClientIdentifier clientId) throws RequestException {
514         final LeaderFrontendState ret = findFrontend(clientId);
515         if (ret != null) {
516             return ret;
517         }
518
519         // TODO: a dedicated exception would be better, but this is technically true, too
520         throw new OutOfSequenceEnvelopeException(0);
521     }
522
523     private static @NonNull ABIVersion selectVersion(final ConnectClientRequest message) {
524         final Range<ABIVersion> clientRange = Range.closed(message.getMinVersion(), message.getMaxVersion());
525         for (ABIVersion v : SUPPORTED_ABIVERSIONS) {
526             if (clientRange.contains(v)) {
527                 return v;
528             }
529         }
530
531         throw new IllegalArgumentException(String.format(
532             "No common version between backend versions %s and client versions %s", SUPPORTED_ABIVERSIONS,
533             clientRange));
534     }
535
536     @SuppressWarnings("checkstyle:IllegalCatch")
537     private void handleConnectClient(final ConnectClientRequest message) {
538         try {
539             final ClientIdentifier clientId = message.getTarget();
540             final LeaderFrontendState existing = findFrontend(clientId);
541             if (existing != null) {
542                 existing.touch();
543             }
544
545             if (!isLeader() || !isLeaderActive()) {
546                 LOG.info("{}: not currently leader, rejecting request {}. isLeader: {}, isLeaderActive: {},"
547                                 + "isLeadershipTransferInProgress: {}.",
548                         persistenceId(), message, isLeader(), isLeaderActive(), isLeadershipTransferInProgress());
549                 throw new NotLeaderException(getSelf());
550             }
551
552             final ABIVersion selectedVersion = selectVersion(message);
553             final LeaderFrontendState frontend;
554             if (existing == null) {
555                 frontend = new LeaderFrontendState.Enabled(persistenceId(), clientId, store);
556                 knownFrontends.put(clientId.getFrontendId(), frontend);
557                 LOG.debug("{}: created state {} for client {}", persistenceId(), frontend, clientId);
558             } else {
559                 frontend = existing;
560             }
561
562             frontend.reconnect();
563             message.getReplyTo().tell(new ConnectClientSuccess(message.getTarget(), message.getSequence(), getSelf(),
564                 ImmutableList.of(), store.getDataTree(), CLIENT_MAX_MESSAGES).toVersion(selectedVersion),
565                 ActorRef.noSender());
566         } catch (RequestException | RuntimeException e) {
567             message.getReplyTo().tell(new Failure(e), ActorRef.noSender());
568         }
569     }
570
571     private @Nullable RequestSuccess<?, ?> handleRequest(final RequestEnvelope envelope, final long now)
572             throws RequestException {
573         // We are not the leader, hence we want to fail-fast.
574         if (!isLeader() || paused || !isLeaderActive()) {
575             LOG.debug("{}: not currently active leader, rejecting request {}. isLeader: {}, isLeaderActive: {},"
576                             + "isLeadershipTransferInProgress: {}, paused: {}",
577                     persistenceId(), envelope, isLeader(), isLeaderActive(), isLeadershipTransferInProgress(), paused);
578             throw new NotLeaderException(getSelf());
579         }
580
581         final Request<?, ?> request = envelope.getMessage();
582         if (request instanceof TransactionRequest) {
583             final TransactionRequest<?> txReq = (TransactionRequest<?>)request;
584             final ClientIdentifier clientId = txReq.getTarget().getHistoryId().getClientId();
585             return getFrontend(clientId).handleTransactionRequest(txReq, envelope, now);
586         } else if (request instanceof LocalHistoryRequest) {
587             final LocalHistoryRequest<?> lhReq = (LocalHistoryRequest<?>)request;
588             final ClientIdentifier clientId = lhReq.getTarget().getClientId();
589             return getFrontend(clientId).handleLocalHistoryRequest(lhReq, envelope, now);
590         } else {
591             LOG.warn("{}: rejecting unsupported request {}", persistenceId(), request);
592             throw new UnsupportedRequestException(request);
593         }
594     }
595
596     private boolean hasLeader() {
597         return getLeaderId() != null;
598     }
599
600     public int getPendingTxCommitQueueSize() {
601         return store.getQueueSize();
602     }
603
604     public int getCohortCacheSize() {
605         return commitCoordinator.getCohortCacheSize();
606     }
607
608     @Override
609     protected Optional<ActorRef> getRoleChangeNotifier() {
610         return roleChangeNotifier;
611     }
612
613     String getShardName() {
614         return shardName;
615     }
616
617     @Override
618     protected LeaderStateChanged newLeaderStateChanged(final String memberId, final String leaderId,
619             final short leaderPayloadVersion) {
620         return isLeader() ? new ShardLeaderStateChanged(memberId, leaderId, store.getDataTree(), leaderPayloadVersion)
621                 : new ShardLeaderStateChanged(memberId, leaderId, leaderPayloadVersion);
622     }
623
624     protected void onDatastoreContext(final DatastoreContext context) {
625         datastoreContext = context;
626
627         setTransactionCommitTimeout();
628
629         setPersistence(datastoreContext.isPersistent());
630
631         updateConfigParams(datastoreContext.getShardRaftConfig());
632     }
633
634     // applyState() will be invoked once consensus is reached on the payload
635     void persistPayload(final Identifier id, final Payload payload, final boolean batchHint) {
636         boolean canSkipPayload = !hasFollowers() && !persistence().isRecoveryApplicable();
637         if (canSkipPayload) {
638             applyState(self(), id, payload);
639         } else {
640             // We are faking the sender
641             persistData(self(), id, payload, batchHint);
642         }
643     }
644
645     private void handleCommitTransaction(final CommitTransaction commit) {
646         final TransactionIdentifier txId = commit.getTransactionId();
647         if (isLeader()) {
648             askProtocolEncountered(txId);
649             commitCoordinator.handleCommit(txId, getSender(), this);
650         } else {
651             ActorSelection leader = getLeader();
652             if (leader == null) {
653                 messageRetrySupport.addMessageToRetry(commit, getSender(), "Could not commit transaction " + txId);
654             } else {
655                 LOG.debug("{}: Forwarding CommitTransaction to leader {}", persistenceId(), leader);
656                 leader.forward(commit, getContext());
657             }
658         }
659     }
660
661     private void handleCanCommitTransaction(final CanCommitTransaction canCommit) {
662         final TransactionIdentifier txId = canCommit.getTransactionId();
663         LOG.debug("{}: Can committing transaction {}", persistenceId(), txId);
664
665         if (isLeader()) {
666             askProtocolEncountered(txId);
667             commitCoordinator.handleCanCommit(txId, getSender(), this);
668         } else {
669             ActorSelection leader = getLeader();
670             if (leader == null) {
671                 messageRetrySupport.addMessageToRetry(canCommit, getSender(),
672                         "Could not canCommit transaction " + txId);
673             } else {
674                 LOG.debug("{}: Forwarding CanCommitTransaction to leader {}", persistenceId(), leader);
675                 leader.forward(canCommit, getContext());
676             }
677         }
678     }
679
680     @SuppressWarnings("checkstyle:IllegalCatch")
681     protected void handleBatchedModificationsLocal(final BatchedModifications batched, final ActorRef sender) {
682         askProtocolEncountered(batched.getTransactionId());
683
684         try {
685             commitCoordinator.handleBatchedModifications(batched, sender, this);
686         } catch (Exception e) {
687             LOG.error("{}: Error handling BatchedModifications for Tx {}", persistenceId(),
688                     batched.getTransactionId(), e);
689             sender.tell(new Failure(e), getSelf());
690         }
691     }
692
693     private void handleBatchedModifications(final BatchedModifications batched) {
694         // This message is sent to prepare the modifications transaction directly on the Shard as an
695         // optimization to avoid the extra overhead of a separate ShardTransaction actor. On the last
696         // BatchedModifications message, the caller sets the ready flag in the message indicating
697         // modifications are complete. The reply contains the cohort actor path (this actor) for the caller
698         // to initiate the 3-phase commit. This also avoids the overhead of sending an additional
699         // ReadyTransaction message.
700
701         // If we're not the leader then forward to the leader. This is a safety measure - we shouldn't
702         // normally get here if we're not the leader as the front-end (TransactionProxy) should determine
703         // the primary/leader shard. However with timing and caching on the front-end, there's a small
704         // window where it could have a stale leader during leadership transitions.
705         //
706         boolean isLeaderActive = isLeaderActive();
707         if (isLeader() && isLeaderActive) {
708             handleBatchedModificationsLocal(batched, getSender());
709         } else {
710             ActorSelection leader = getLeader();
711             if (!isLeaderActive || leader == null) {
712                 messageRetrySupport.addMessageToRetry(batched, getSender(),
713                         "Could not process BatchedModifications " + batched.getTransactionId());
714             } else {
715                 // If this is not the first batch and leadership changed in between batched messages,
716                 // we need to reconstruct previous BatchedModifications from the transaction
717                 // DataTreeModification, honoring the max batched modification count, and forward all the
718                 // previous BatchedModifications to the new leader.
719                 Collection<BatchedModifications> newModifications = commitCoordinator
720                         .createForwardedBatchedModifications(batched,
721                                 datastoreContext.getShardBatchedModificationCount());
722
723                 LOG.debug("{}: Forwarding {} BatchedModifications to leader {}", persistenceId(),
724                         newModifications.size(), leader);
725
726                 for (BatchedModifications bm : newModifications) {
727                     leader.forward(bm, getContext());
728                 }
729             }
730         }
731     }
732
733     private boolean failIfIsolatedLeader(final ActorRef sender) {
734         if (isIsolatedLeader()) {
735             sender.tell(new Failure(new NoShardLeaderException(String.format(
736                     "Shard %s was the leader but has lost contact with all of its followers. Either all"
737                     + " other follower nodes are down or this node is isolated by a network partition.",
738                     persistenceId()))), getSelf());
739             return true;
740         }
741
742         return false;
743     }
744
745     protected boolean isIsolatedLeader() {
746         return getRaftState() == RaftState.IsolatedLeader;
747     }
748
749     @SuppressWarnings("checkstyle:IllegalCatch")
750     private void handleReadyLocalTransaction(final ReadyLocalTransaction message) {
751         LOG.debug("{}: handleReadyLocalTransaction for {}", persistenceId(), message.getTransactionId());
752
753         boolean isLeaderActive = isLeaderActive();
754         if (isLeader() && isLeaderActive) {
755             try {
756                 commitCoordinator.handleReadyLocalTransaction(message, getSender(), this);
757             } catch (Exception e) {
758                 LOG.error("{}: Error handling ReadyLocalTransaction for Tx {}", persistenceId(),
759                         message.getTransactionId(), e);
760                 getSender().tell(new Failure(e), getSelf());
761             }
762         } else {
763             ActorSelection leader = getLeader();
764             if (!isLeaderActive || leader == null) {
765                 messageRetrySupport.addMessageToRetry(message, getSender(),
766                         "Could not process ready local transaction " + message.getTransactionId());
767             } else {
768                 LOG.debug("{}: Forwarding ReadyLocalTransaction to leader {}", persistenceId(), leader);
769                 message.setRemoteVersion(getCurrentBehavior().getLeaderPayloadVersion());
770                 leader.forward(message, getContext());
771             }
772         }
773     }
774
775     private void handleForwardedReadyTransaction(final ForwardedReadyTransaction forwardedReady) {
776         LOG.debug("{}: handleForwardedReadyTransaction for {}", persistenceId(), forwardedReady.getTransactionId());
777
778         boolean isLeaderActive = isLeaderActive();
779         if (isLeader() && isLeaderActive) {
780             askProtocolEncountered(forwardedReady.getTransactionId());
781             commitCoordinator.handleForwardedReadyTransaction(forwardedReady, getSender(), this);
782         } else {
783             ActorSelection leader = getLeader();
784             if (!isLeaderActive || leader == null) {
785                 messageRetrySupport.addMessageToRetry(forwardedReady, getSender(),
786                         "Could not process forwarded ready transaction " + forwardedReady.getTransactionId());
787             } else {
788                 LOG.debug("{}: Forwarding ForwardedReadyTransaction to leader {}", persistenceId(), leader);
789
790                 ReadyLocalTransaction readyLocal = new ReadyLocalTransaction(forwardedReady.getTransactionId(),
791                         forwardedReady.getTransaction().getSnapshot(), forwardedReady.isDoImmediateCommit(),
792                         forwardedReady.getParticipatingShardNames());
793                 readyLocal.setRemoteVersion(getCurrentBehavior().getLeaderPayloadVersion());
794                 leader.forward(readyLocal, getContext());
795             }
796         }
797     }
798
799     private void handleAbortTransaction(final AbortTransaction abort) {
800         final TransactionIdentifier transactionId = abort.getTransactionId();
801         askProtocolEncountered(transactionId);
802         doAbortTransaction(transactionId, getSender());
803     }
804
805     void doAbortTransaction(final Identifier transactionID, final ActorRef sender) {
806         commitCoordinator.handleAbort(transactionID, sender, this);
807     }
808
809     private void handleCreateTransaction(final Object message) {
810         if (isLeader()) {
811             createTransaction(CreateTransaction.fromSerializable(message));
812         } else if (getLeader() != null) {
813             getLeader().forward(message, getContext());
814         } else {
815             getSender().tell(new Failure(new NoShardLeaderException(
816                     "Could not create a shard transaction", persistenceId())), getSelf());
817         }
818     }
819
820     private void closeTransactionChain(final CloseTransactionChain closeTransactionChain) {
821         if (isLeader()) {
822             final LocalHistoryIdentifier id = closeTransactionChain.getIdentifier();
823             askProtocolEncountered(id.getClientId());
824
825             // FIXME: CONTROLLER-1628: stage purge once no transactions are present
826             store.closeTransactionChain(id, null);
827             store.purgeTransactionChain(id, null);
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<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         private volatile boolean sealed;
1097
1098         protected AbstractBuilder(final Class<S> shardClass) {
1099             this.shardClass = shardClass;
1100         }
1101
1102         protected void checkSealed() {
1103             Preconditions.checkState(!sealed, "Builder isalready sealed - further modifications are not allowed");
1104         }
1105
1106         @SuppressWarnings("unchecked")
1107         private T self() {
1108             return (T) this;
1109         }
1110
1111         public T id(final ShardIdentifier newId) {
1112             checkSealed();
1113             this.id = newId;
1114             return self();
1115         }
1116
1117         public T peerAddresses(final Map<String, String> newPeerAddresses) {
1118             checkSealed();
1119             this.peerAddresses = newPeerAddresses;
1120             return self();
1121         }
1122
1123         public T datastoreContext(final DatastoreContext newDatastoreContext) {
1124             checkSealed();
1125             this.datastoreContext = newDatastoreContext;
1126             return self();
1127         }
1128
1129         public T schemaContextProvider(final SchemaContextProvider newSchemaContextProvider) {
1130             checkSealed();
1131             this.schemaContextProvider = Preconditions.checkNotNull(newSchemaContextProvider);
1132             return self();
1133         }
1134
1135         public T restoreFromSnapshot(final DatastoreSnapshot.ShardSnapshot newRestoreFromSnapshot) {
1136             checkSealed();
1137             this.restoreFromSnapshot = newRestoreFromSnapshot;
1138             return self();
1139         }
1140
1141         public T dataTree(final DataTree newDataTree) {
1142             checkSealed();
1143             this.dataTree = newDataTree;
1144             return self();
1145         }
1146
1147         public ShardIdentifier getId() {
1148             return id;
1149         }
1150
1151         public Map<String, String> getPeerAddresses() {
1152             return peerAddresses;
1153         }
1154
1155         public DatastoreContext getDatastoreContext() {
1156             return datastoreContext;
1157         }
1158
1159         public SchemaContext getSchemaContext() {
1160             return Verify.verifyNotNull(schemaContextProvider.getSchemaContext());
1161         }
1162
1163         public DatastoreSnapshot.ShardSnapshot getRestoreFromSnapshot() {
1164             return restoreFromSnapshot;
1165         }
1166
1167         public DataTree getDataTree() {
1168             return dataTree;
1169         }
1170
1171         public TreeType getTreeType() {
1172             switch (datastoreContext.getLogicalStoreType()) {
1173                 case CONFIGURATION:
1174                     return TreeType.CONFIGURATION;
1175                 case OPERATIONAL:
1176                     return TreeType.OPERATIONAL;
1177                 default:
1178                     throw new IllegalStateException("Unhandled logical store type "
1179                             + datastoreContext.getLogicalStoreType());
1180             }
1181         }
1182
1183         protected void verify() {
1184             Preconditions.checkNotNull(id, "id should not be null");
1185             Preconditions.checkNotNull(peerAddresses, "peerAddresses should not be null");
1186             Preconditions.checkNotNull(datastoreContext, "dataStoreContext should not be null");
1187             Preconditions.checkNotNull(schemaContextProvider, "schemaContextProvider should not be null");
1188         }
1189
1190         public Props props() {
1191             sealed = true;
1192             verify();
1193             return Props.create(shardClass, this);
1194         }
1195     }
1196
1197     public static class Builder extends AbstractBuilder<Builder, Shard> {
1198         Builder() {
1199             super(Shard.class);
1200         }
1201     }
1202
1203     Ticker ticker() {
1204         return Ticker.systemTicker();
1205     }
1206
1207     void scheduleNextPendingTransaction() {
1208         self().tell(RESUME_NEXT_PENDING_TRANSACTION, ActorRef.noSender());
1209     }
1210 }