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