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