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