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