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