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