Snapshot and journal export on recovery
[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.base.Verify;
30 import com.google.common.collect.ImmutableList;
31 import com.google.common.collect.ImmutableMap;
32 import com.google.common.collect.ImmutableSet;
33 import com.google.common.collect.Range;
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.ForwardedReadyTransaction;
82 import org.opendaylight.controller.cluster.datastore.messages.GetKnownClients;
83 import org.opendaylight.controller.cluster.datastore.messages.GetKnownClientsReply;
84 import org.opendaylight.controller.cluster.datastore.messages.GetShardDataTree;
85 import org.opendaylight.controller.cluster.datastore.messages.MakeLeaderLocal;
86 import org.opendaylight.controller.cluster.datastore.messages.OnDemandShardState;
87 import org.opendaylight.controller.cluster.datastore.messages.PeerAddressResolved;
88 import org.opendaylight.controller.cluster.datastore.messages.ReadyLocalTransaction;
89 import org.opendaylight.controller.cluster.datastore.messages.RegisterDataTreeChangeListener;
90 import org.opendaylight.controller.cluster.datastore.messages.ShardLeaderStateChanged;
91 import org.opendaylight.controller.cluster.datastore.messages.UpdateSchemaContext;
92 import org.opendaylight.controller.cluster.datastore.persisted.DatastoreSnapshot;
93 import org.opendaylight.controller.cluster.datastore.persisted.DatastoreSnapshot.ShardSnapshot;
94 import org.opendaylight.controller.cluster.datastore.persisted.DisableTrackingPayload;
95 import org.opendaylight.controller.cluster.messaging.MessageAssembler;
96 import org.opendaylight.controller.cluster.messaging.MessageSlicer;
97 import org.opendaylight.controller.cluster.messaging.SliceOptions;
98 import org.opendaylight.controller.cluster.notifications.LeaderStateChanged;
99 import org.opendaylight.controller.cluster.notifications.RegisterRoleChangeListener;
100 import org.opendaylight.controller.cluster.notifications.RoleChangeNotifier;
101 import org.opendaylight.controller.cluster.raft.LeadershipTransferFailedException;
102 import org.opendaylight.controller.cluster.raft.RaftActor;
103 import org.opendaylight.controller.cluster.raft.RaftActorRecoveryCohort;
104 import org.opendaylight.controller.cluster.raft.RaftActorSnapshotCohort;
105 import org.opendaylight.controller.cluster.raft.RaftState;
106 import org.opendaylight.controller.cluster.raft.ReplicatedLogEntry;
107 import org.opendaylight.controller.cluster.raft.base.messages.FollowerInitialSyncUpStatus;
108 import org.opendaylight.controller.cluster.raft.client.messages.OnDemandRaftState;
109 import org.opendaylight.controller.cluster.raft.messages.AppendEntriesReply;
110 import org.opendaylight.controller.cluster.raft.messages.RequestLeadership;
111 import org.opendaylight.controller.cluster.raft.messages.ServerRemoved;
112 import org.opendaylight.controller.cluster.raft.protobuff.client.messages.Payload;
113 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.distributed.datastore.provider.rev140612.DataStoreProperties.ExportOnRecovery;
114 import org.opendaylight.yangtools.concepts.Identifier;
115 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTree;
116 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataValidationFailedException;
117 import org.opendaylight.yangtools.yang.data.api.schema.tree.TreeType;
118 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
119 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContextProvider;
120 import scala.concurrent.duration.FiniteDuration;
121
122 /**
123  * A Shard represents a portion of the logical data tree.
124  *
125  * <p>
126  * Our Shard uses InMemoryDataTree as it's internal representation and delegates all requests it
127  */
128 public class Shard extends RaftActor {
129
130     @VisibleForTesting
131     static final Object TX_COMMIT_TIMEOUT_CHECK_MESSAGE = new Object() {
132         @Override
133         public String toString() {
134             return "txCommitTimeoutCheck";
135         }
136     };
137
138     @VisibleForTesting
139     static final Object GET_SHARD_MBEAN_MESSAGE = new Object() {
140         @Override
141         public String toString() {
142             return "getShardMBeanMessage";
143         }
144     };
145
146     static final Object RESUME_NEXT_PENDING_TRANSACTION = new Object() {
147         @Override
148         public String toString() {
149             return "resumeNextPendingTransaction";
150         }
151     };
152
153     // FIXME: shard names should be encapsulated in their own class and this should be exposed as a constant.
154     public static final String DEFAULT_NAME = "default";
155
156     private static final Collection<ABIVersion> SUPPORTED_ABIVERSIONS;
157
158     // Make sure to keep this in sync with the journal configuration in factory-akka.conf
159     public static final String NON_PERSISTENT_JOURNAL_ID = "akka.persistence.non-persistent.journal";
160
161     static {
162         final ABIVersion[] values = ABIVersion.values();
163         final ABIVersion[] real = Arrays.copyOfRange(values, 1, values.length - 1);
164         SUPPORTED_ABIVERSIONS = ImmutableList.copyOf(real).reverse();
165     }
166
167     // FIXME: make this a dynamic property based on mailbox size and maximum number of clients
168     private static final int CLIENT_MAX_MESSAGES = 1000;
169
170     // The state of this Shard
171     private final ShardDataTree store;
172
173     /// The name of this shard
174     private final String name;
175
176     private final String shardName;
177
178     private final ShardStats shardMBean;
179
180     private final ShardDataTreeListenerInfoMXBeanImpl listenerInfoMXBean;
181
182     private DatastoreContext datastoreContext;
183
184     private final ShardCommitCoordinator commitCoordinator;
185
186     private long transactionCommitTimeout;
187
188     private Cancellable txCommitTimeoutCheckSchedule;
189
190     private final Optional<ActorRef> roleChangeNotifier;
191
192     private final MessageTracker appendEntriesReplyTracker;
193
194     private final ShardTransactionActorFactory transactionActorFactory;
195
196     private final ShardSnapshotCohort snapshotCohort;
197
198     private final DataTreeChangeListenerSupport treeChangeSupport = new DataTreeChangeListenerSupport(this);
199
200     private ShardSnapshot restoreFromSnapshot;
201
202     private final ShardTransactionMessageRetrySupport messageRetrySupport;
203
204     @VisibleForTesting
205     final FrontendMetadata frontendMetadata;
206
207     private Map<FrontendIdentifier, LeaderFrontendState> knownFrontends = ImmutableMap.of();
208     private boolean paused;
209
210     private final MessageSlicer responseMessageSlicer;
211     private final Dispatchers dispatchers;
212
213     private final MessageAssembler requestMessageAssembler;
214
215     private final ExportOnRecovery exportOnRecovery;
216
217     private final ActorRef exportActor;
218
219     protected Shard(final AbstractBuilder<?, ?> builder) {
220         super(builder.getId().toString(), builder.getPeerAddresses(),
221                 Optional.of(builder.getDatastoreContext().getShardRaftConfig()), DataStoreVersions.CURRENT_VERSION);
222
223         this.name = builder.getId().toString();
224         this.shardName = builder.getId().getShardName();
225         this.datastoreContext = builder.getDatastoreContext();
226         this.restoreFromSnapshot = builder.getRestoreFromSnapshot();
227         this.frontendMetadata = new FrontendMetadata(name);
228         this.exportOnRecovery = datastoreContext.getExportOnRecovery();
229
230         switch (exportOnRecovery) {
231             case Json:
232                 exportActor = getContext().actorOf(JsonExportActor.props(builder.getSchemaContext(),
233                         datastoreContext.getRecoveryExportBaseDir()));
234                 break;
235             case Off:
236             default:
237                 exportActor = null;
238                 break;
239         }
240
241         setPersistence(datastoreContext.isPersistent());
242
243         LOG.info("Shard created : {}, persistent : {}", name, datastoreContext.isPersistent());
244
245         ShardDataTreeChangeListenerPublisherActorProxy treeChangeListenerPublisher =
246                 new ShardDataTreeChangeListenerPublisherActorProxy(getContext(), name + "-DTCL-publisher", name);
247         if (builder.getDataTree() != null) {
248             store = new ShardDataTree(this, builder.getSchemaContext(), builder.getDataTree(),
249                     treeChangeListenerPublisher, name,
250                     frontendMetadata);
251         } else {
252             store = new ShardDataTree(this, builder.getSchemaContext(), builder.getTreeType(),
253                     builder.getDatastoreContext().getStoreRoot(), treeChangeListenerPublisher, name,
254                     frontendMetadata);
255         }
256
257         shardMBean = ShardStats.create(name, datastoreContext.getDataStoreMXBeanType(), this);
258
259         if (isMetricsCaptureEnabled()) {
260             getContext().become(new MeteringBehavior(this));
261         }
262
263         commitCoordinator = new ShardCommitCoordinator(store, LOG, this.name);
264
265         setTransactionCommitTimeout();
266
267         // create a notifier actor for each cluster member
268         roleChangeNotifier = createRoleChangeNotifier(name);
269
270         appendEntriesReplyTracker = new MessageTracker(AppendEntriesReply.class,
271                 getRaftActorContext().getConfigParams().getIsolatedCheckIntervalInMillis());
272
273         dispatchers = new Dispatchers(context().system().dispatchers());
274         transactionActorFactory = new ShardTransactionActorFactory(store, datastoreContext,
275             dispatchers.getDispatcherPath(Dispatchers.DispatcherType.Transaction),
276                 self(), getContext(), shardMBean, builder.getId().getShardName());
277
278         snapshotCohort = ShardSnapshotCohort.create(getContext(), builder.getId().getMemberName(), store, LOG,
279             this.name, datastoreContext);
280
281         messageRetrySupport = new ShardTransactionMessageRetrySupport(this);
282
283         responseMessageSlicer = MessageSlicer.builder().logContext(this.name)
284                 .messageSliceSize(datastoreContext.getMaximumMessageSliceSize())
285                 .fileBackedStreamFactory(getRaftActorContext().getFileBackedOutputStreamFactory())
286                 .expireStateAfterInactivity(2, TimeUnit.MINUTES).build();
287
288         requestMessageAssembler = MessageAssembler.builder().logContext(this.name)
289                 .fileBackedStreamFactory(getRaftActorContext().getFileBackedOutputStreamFactory())
290                 .assembledMessageCallback((message, sender) -> self().tell(message, sender))
291                 .expireStateAfterInactivity(datastoreContext.getRequestTimeout(), TimeUnit.NANOSECONDS).build();
292
293         listenerInfoMXBean = new ShardDataTreeListenerInfoMXBeanImpl(name, datastoreContext.getDataStoreMXBeanType(),
294                 self());
295         listenerInfoMXBean.register();
296     }
297
298     private void setTransactionCommitTimeout() {
299         transactionCommitTimeout = TimeUnit.MILLISECONDS.convert(
300                 datastoreContext.getShardTransactionCommitTimeoutInSeconds(), TimeUnit.SECONDS) / 2;
301     }
302
303     private Optional<ActorRef> createRoleChangeNotifier(final String shardId) {
304         ActorRef shardRoleChangeNotifier = this.getContext().actorOf(
305             RoleChangeNotifier.getProps(shardId), shardId + "-notifier");
306         return Optional.of(shardRoleChangeNotifier);
307     }
308
309     @Override
310     public void postStop() throws Exception {
311         LOG.info("Stopping Shard {}", persistenceId());
312
313         super.postStop();
314
315         messageRetrySupport.close();
316
317         if (txCommitTimeoutCheckSchedule != null) {
318             txCommitTimeoutCheckSchedule.cancel();
319         }
320
321         commitCoordinator.abortPendingTransactions("Transaction aborted due to shutdown.", this);
322
323         shardMBean.unregisterMBean();
324         listenerInfoMXBean.unregister();
325     }
326
327     @Override
328     protected void handleRecover(final Object message) {
329         LOG.debug("{}: onReceiveRecover: Received message {} from {}", persistenceId(), message.getClass(),
330             getSender());
331
332         super.handleRecover(message);
333
334         switch (exportOnRecovery) {
335             case Json:
336                 if (message instanceof SnapshotOffer) {
337                     exportActor.tell(new JsonExportActor.ExportSnapshot(store.readCurrentData().get(), name),
338                             ActorRef.noSender());
339                 } else if (message instanceof ReplicatedLogEntry) {
340                     exportActor.tell(new JsonExportActor.ExportJournal((ReplicatedLogEntry) message),
341                             ActorRef.noSender());
342                 } else if (message instanceof RecoveryCompleted) {
343                     exportActor.tell(new JsonExportActor.FinishExport(name), ActorRef.noSender());
344                     exportActor.tell(PoisonPill.getInstance(), ActorRef.noSender());
345                 }
346                 break;
347             case Off:
348             default:
349                 break;
350         }
351
352         if (LOG.isTraceEnabled()) {
353             appendEntriesReplyTracker.begin();
354         }
355     }
356
357     @Override
358     protected void handleNonRaftCommand(final Object message) {
359         try (MessageTracker.Context context = appendEntriesReplyTracker.received(message)) {
360             final Optional<Error> maybeError = context.error();
361             if (maybeError.isPresent()) {
362                 LOG.trace("{} : AppendEntriesReply failed to arrive at the expected interval {}", persistenceId(),
363                     maybeError.get());
364             }
365
366             store.resetTransactionBatch();
367
368             if (message instanceof RequestEnvelope) {
369                 handleRequestEnvelope((RequestEnvelope)message);
370             } else if (MessageAssembler.isHandledMessage(message)) {
371                 handleRequestAssemblerMessage(message);
372             } else if (message instanceof ConnectClientRequest) {
373                 handleConnectClient((ConnectClientRequest)message);
374             } else if (CreateTransaction.isSerializedType(message)) {
375                 handleCreateTransaction(message);
376             } else if (message instanceof BatchedModifications) {
377                 handleBatchedModifications((BatchedModifications)message);
378             } else if (message instanceof ForwardedReadyTransaction) {
379                 handleForwardedReadyTransaction((ForwardedReadyTransaction) message);
380             } else if (message instanceof ReadyLocalTransaction) {
381                 handleReadyLocalTransaction((ReadyLocalTransaction)message);
382             } else if (CanCommitTransaction.isSerializedType(message)) {
383                 handleCanCommitTransaction(CanCommitTransaction.fromSerializable(message));
384             } else if (CommitTransaction.isSerializedType(message)) {
385                 handleCommitTransaction(CommitTransaction.fromSerializable(message));
386             } else if (AbortTransaction.isSerializedType(message)) {
387                 handleAbortTransaction(AbortTransaction.fromSerializable(message));
388             } else if (CloseTransactionChain.isSerializedType(message)) {
389                 closeTransactionChain(CloseTransactionChain.fromSerializable(message));
390             } else if (message instanceof RegisterDataTreeChangeListener) {
391                 treeChangeSupport.onMessage((RegisterDataTreeChangeListener) message, isLeader(), hasLeader());
392             } else if (message instanceof UpdateSchemaContext) {
393                 updateSchemaContext((UpdateSchemaContext) message);
394             } else if (message instanceof PeerAddressResolved) {
395                 PeerAddressResolved resolved = (PeerAddressResolved) message;
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     public int getPendingTxCommitQueueSize() {
666         return store.getQueueSize();
667     }
668
669     public int getCohortCacheSize() {
670         return commitCoordinator.getCohortCacheSize();
671     }
672
673     @Override
674     protected Optional<ActorRef> getRoleChangeNotifier() {
675         return roleChangeNotifier;
676     }
677
678     String getShardName() {
679         return shardName;
680     }
681
682     @Override
683     protected 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     protected 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     void persistPayload(final Identifier id, final Payload payload, final boolean batchHint) {
701         boolean canSkipPayload = !hasFollowers() && !persistence().isRecoveryApplicable();
702         if (canSkipPayload) {
703             applyState(self(), id, payload);
704         } else {
705             // We are faking the sender
706             persistData(self(), id, payload, batchHint);
707         }
708     }
709
710     private void handleCommitTransaction(final CommitTransaction commit) {
711         final TransactionIdentifier txId = commit.getTransactionId();
712         if (isLeader()) {
713             askProtocolEncountered(txId);
714             commitCoordinator.handleCommit(txId, getSender(), this);
715         } else {
716             ActorSelection leader = getLeader();
717             if (leader == null) {
718                 messageRetrySupport.addMessageToRetry(commit, getSender(), "Could not commit transaction " + txId);
719             } else {
720                 LOG.debug("{}: Forwarding CommitTransaction to leader {}", persistenceId(), leader);
721                 leader.forward(commit, getContext());
722             }
723         }
724     }
725
726     private void handleCanCommitTransaction(final CanCommitTransaction canCommit) {
727         final TransactionIdentifier txId = canCommit.getTransactionId();
728         LOG.debug("{}: Can committing transaction {}", persistenceId(), txId);
729
730         if (isLeader()) {
731             askProtocolEncountered(txId);
732             commitCoordinator.handleCanCommit(txId, getSender(), this);
733         } else {
734             ActorSelection leader = getLeader();
735             if (leader == null) {
736                 messageRetrySupport.addMessageToRetry(canCommit, getSender(),
737                         "Could not canCommit transaction " + txId);
738             } else {
739                 LOG.debug("{}: Forwarding CanCommitTransaction to leader {}", persistenceId(), leader);
740                 leader.forward(canCommit, getContext());
741             }
742         }
743     }
744
745     @SuppressWarnings("checkstyle:IllegalCatch")
746     protected void handleBatchedModificationsLocal(final BatchedModifications batched, final ActorRef sender) {
747         askProtocolEncountered(batched.getTransactionId());
748
749         try {
750             commitCoordinator.handleBatchedModifications(batched, sender, this);
751         } catch (Exception e) {
752             LOG.error("{}: Error handling BatchedModifications for Tx {}", persistenceId(),
753                     batched.getTransactionId(), e);
754             sender.tell(new Failure(e), getSelf());
755         }
756     }
757
758     private void handleBatchedModifications(final BatchedModifications batched) {
759         // This message is sent to prepare the modifications transaction directly on the Shard as an
760         // optimization to avoid the extra overhead of a separate ShardTransaction actor. On the last
761         // BatchedModifications message, the caller sets the ready flag in the message indicating
762         // modifications are complete. The reply contains the cohort actor path (this actor) for the caller
763         // to initiate the 3-phase commit. This also avoids the overhead of sending an additional
764         // ReadyTransaction message.
765
766         // If we're not the leader then forward to the leader. This is a safety measure - we shouldn't
767         // normally get here if we're not the leader as the front-end (TransactionProxy) should determine
768         // the primary/leader shard. However with timing and caching on the front-end, there's a small
769         // window where it could have a stale leader during leadership transitions.
770         //
771         boolean isLeaderActive = isLeaderActive();
772         if (isLeader() && isLeaderActive) {
773             handleBatchedModificationsLocal(batched, getSender());
774         } else {
775             ActorSelection leader = getLeader();
776             if (!isLeaderActive || leader == null) {
777                 messageRetrySupport.addMessageToRetry(batched, getSender(),
778                         "Could not process BatchedModifications " + batched.getTransactionId());
779             } else {
780                 // If this is not the first batch and leadership changed in between batched messages,
781                 // we need to reconstruct previous BatchedModifications from the transaction
782                 // DataTreeModification, honoring the max batched modification count, and forward all the
783                 // previous BatchedModifications to the new leader.
784                 Collection<BatchedModifications> newModifications = commitCoordinator
785                         .createForwardedBatchedModifications(batched,
786                                 datastoreContext.getShardBatchedModificationCount());
787
788                 LOG.debug("{}: Forwarding {} BatchedModifications to leader {}", persistenceId(),
789                         newModifications.size(), leader);
790
791                 for (BatchedModifications bm : newModifications) {
792                     leader.forward(bm, getContext());
793                 }
794             }
795         }
796     }
797
798     private boolean failIfIsolatedLeader(final ActorRef sender) {
799         if (isIsolatedLeader()) {
800             sender.tell(new Failure(new NoShardLeaderException(String.format(
801                     "Shard %s was the leader but has lost contact with all of its followers. Either all"
802                     + " other follower nodes are down or this node is isolated by a network partition.",
803                     persistenceId()))), getSelf());
804             return true;
805         }
806
807         return false;
808     }
809
810     protected boolean isIsolatedLeader() {
811         return getRaftState() == RaftState.IsolatedLeader;
812     }
813
814     @SuppressWarnings("checkstyle:IllegalCatch")
815     private void handleReadyLocalTransaction(final ReadyLocalTransaction message) {
816         LOG.debug("{}: handleReadyLocalTransaction for {}", persistenceId(), message.getTransactionId());
817
818         boolean isLeaderActive = isLeaderActive();
819         if (isLeader() && isLeaderActive) {
820             try {
821                 commitCoordinator.handleReadyLocalTransaction(message, getSender(), this);
822             } catch (Exception e) {
823                 LOG.error("{}: Error handling ReadyLocalTransaction for Tx {}", persistenceId(),
824                         message.getTransactionId(), e);
825                 getSender().tell(new Failure(e), getSelf());
826             }
827         } else {
828             ActorSelection leader = getLeader();
829             if (!isLeaderActive || leader == null) {
830                 messageRetrySupport.addMessageToRetry(message, getSender(),
831                         "Could not process ready local transaction " + message.getTransactionId());
832             } else {
833                 LOG.debug("{}: Forwarding ReadyLocalTransaction to leader {}", persistenceId(), leader);
834                 message.setRemoteVersion(getCurrentBehavior().getLeaderPayloadVersion());
835                 leader.forward(message, getContext());
836             }
837         }
838     }
839
840     private void handleForwardedReadyTransaction(final ForwardedReadyTransaction forwardedReady) {
841         LOG.debug("{}: handleForwardedReadyTransaction for {}", persistenceId(), forwardedReady.getTransactionId());
842
843         boolean isLeaderActive = isLeaderActive();
844         if (isLeader() && isLeaderActive) {
845             askProtocolEncountered(forwardedReady.getTransactionId());
846             commitCoordinator.handleForwardedReadyTransaction(forwardedReady, getSender(), this);
847         } else {
848             ActorSelection leader = getLeader();
849             if (!isLeaderActive || leader == null) {
850                 messageRetrySupport.addMessageToRetry(forwardedReady, getSender(),
851                         "Could not process forwarded ready transaction " + forwardedReady.getTransactionId());
852             } else {
853                 LOG.debug("{}: Forwarding ForwardedReadyTransaction to leader {}", persistenceId(), leader);
854
855                 ReadyLocalTransaction readyLocal = new ReadyLocalTransaction(forwardedReady.getTransactionId(),
856                         forwardedReady.getTransaction().getSnapshot(), forwardedReady.isDoImmediateCommit(),
857                         forwardedReady.getParticipatingShardNames());
858                 readyLocal.setRemoteVersion(getCurrentBehavior().getLeaderPayloadVersion());
859                 leader.forward(readyLocal, getContext());
860             }
861         }
862     }
863
864     private void handleAbortTransaction(final AbortTransaction abort) {
865         final TransactionIdentifier transactionId = abort.getTransactionId();
866         askProtocolEncountered(transactionId);
867         doAbortTransaction(transactionId, getSender());
868     }
869
870     void doAbortTransaction(final Identifier transactionID, final ActorRef sender) {
871         commitCoordinator.handleAbort(transactionID, sender, this);
872     }
873
874     private void handleCreateTransaction(final Object message) {
875         if (isLeader()) {
876             createTransaction(CreateTransaction.fromSerializable(message));
877         } else if (getLeader() != null) {
878             getLeader().forward(message, getContext());
879         } else {
880             getSender().tell(new Failure(new NoShardLeaderException(
881                     "Could not create a shard transaction", persistenceId())), getSelf());
882         }
883     }
884
885     private void closeTransactionChain(final CloseTransactionChain closeTransactionChain) {
886         if (isLeader()) {
887             final LocalHistoryIdentifier id = closeTransactionChain.getIdentifier();
888             askProtocolEncountered(id.getClientId());
889             store.closeTransactionChain(id);
890         } else if (getLeader() != null) {
891             getLeader().forward(closeTransactionChain, getContext());
892         } else {
893             LOG.warn("{}: Could not close transaction {}", persistenceId(), closeTransactionChain.getIdentifier());
894         }
895     }
896
897     @SuppressWarnings("checkstyle:IllegalCatch")
898     private void createTransaction(final CreateTransaction createTransaction) {
899         askProtocolEncountered(createTransaction.getTransactionId());
900
901         try {
902             if (TransactionType.fromInt(createTransaction.getTransactionType()) != TransactionType.READ_ONLY
903                     && failIfIsolatedLeader(getSender())) {
904                 return;
905             }
906
907             ActorRef transactionActor = createTransaction(createTransaction.getTransactionType(),
908                 createTransaction.getTransactionId());
909
910             getSender().tell(new CreateTransactionReply(Serialization.serializedActorPath(transactionActor),
911                     createTransaction.getTransactionId(), createTransaction.getVersion()).toSerializable(), getSelf());
912         } catch (Exception e) {
913             getSender().tell(new Failure(e), getSelf());
914         }
915     }
916
917     private ActorRef createTransaction(final int transactionType, final TransactionIdentifier transactionId) {
918         LOG.debug("{}: Creating transaction : {} ", persistenceId(), transactionId);
919         return transactionActorFactory.newShardTransaction(TransactionType.fromInt(transactionType),
920             transactionId);
921     }
922
923     // Called on leader only
924     private void askProtocolEncountered(final TransactionIdentifier transactionId) {
925         askProtocolEncountered(transactionId.getHistoryId().getClientId());
926     }
927
928     // Called on leader only
929     private void askProtocolEncountered(final ClientIdentifier clientId) {
930         final FrontendIdentifier frontend = clientId.getFrontendId();
931         final LeaderFrontendState state = knownFrontends.get(frontend);
932         if (!(state instanceof LeaderFrontendState.Disabled)) {
933             LOG.debug("{}: encountered ask-based client {}, disabling transaction tracking", persistenceId(), clientId);
934             if (knownFrontends.isEmpty()) {
935                 knownFrontends = new HashMap<>();
936             }
937             knownFrontends.put(frontend, new LeaderFrontendState.Disabled(persistenceId(), clientId, getDataStore()));
938
939             persistPayload(clientId, DisableTrackingPayload.create(clientId,
940                 datastoreContext.getInitialPayloadSerializedBufferCapacity()), false);
941         }
942     }
943
944     private void updateSchemaContext(final UpdateSchemaContext message) {
945         updateSchemaContext(message.getEffectiveModelContext());
946     }
947
948     @VisibleForTesting
949     void updateSchemaContext(final @NonNull EffectiveModelContext schemaContext) {
950         store.updateSchemaContext(schemaContext);
951     }
952
953     private boolean isMetricsCaptureEnabled() {
954         CommonConfig config = new CommonConfig(getContext().system().settings().config());
955         return config.isMetricCaptureEnabled();
956     }
957
958     @Override
959     @VisibleForTesting
960     public RaftActorSnapshotCohort getRaftActorSnapshotCohort() {
961         return snapshotCohort;
962     }
963
964     @Override
965     protected RaftActorRecoveryCohort getRaftActorRecoveryCohort() {
966         if (restoreFromSnapshot == null) {
967             return ShardRecoveryCoordinator.create(store, persistenceId(), LOG);
968         }
969
970         return ShardRecoveryCoordinator.forSnapshot(store, persistenceId(), LOG, restoreFromSnapshot.getSnapshot());
971     }
972
973     @Override
974     protected void onRecoveryComplete() {
975         restoreFromSnapshot = null;
976
977         //notify shard manager
978         getContext().parent().tell(new ActorInitialized(), getSelf());
979
980         // Being paranoid here - this method should only be called once but just in case...
981         if (txCommitTimeoutCheckSchedule == null) {
982             // Schedule a message to be periodically sent to check if the current in-progress
983             // transaction should be expired and aborted.
984             FiniteDuration period = FiniteDuration.create(transactionCommitTimeout / 3, TimeUnit.MILLISECONDS);
985             txCommitTimeoutCheckSchedule = getContext().system().scheduler().schedule(
986                     period, period, getSelf(),
987                     TX_COMMIT_TIMEOUT_CHECK_MESSAGE, getContext().dispatcher(), ActorRef.noSender());
988         }
989     }
990
991     @Override
992     protected void applyState(final ActorRef clientActor, final Identifier identifier, final Object data) {
993         if (data instanceof Payload) {
994             if (data instanceof DisableTrackingPayload) {
995                 disableTracking((DisableTrackingPayload) data);
996                 return;
997             }
998
999             try {
1000                 store.applyReplicatedPayload(identifier, (Payload)data);
1001             } catch (DataValidationFailedException | IOException e) {
1002                 LOG.error("{}: Error applying replica {}", persistenceId(), identifier, e);
1003             }
1004         } else {
1005             LOG.error("{}: Unknown state for {} received {}", persistenceId(), identifier, data);
1006         }
1007     }
1008
1009     @Override
1010     protected void onStateChanged() {
1011         boolean isLeader = isLeader();
1012         boolean hasLeader = hasLeader();
1013         treeChangeSupport.onLeadershipChange(isLeader, hasLeader);
1014
1015         // If this actor is no longer the leader close all the transaction chains
1016         if (!isLeader) {
1017             if (LOG.isDebugEnabled()) {
1018                 LOG.debug(
1019                     "{}: onStateChanged: Closing all transaction chains because shard {} is no longer the leader",
1020                     persistenceId(), getId());
1021             }
1022
1023             paused = false;
1024             store.purgeLeaderState();
1025         }
1026
1027         if (hasLeader && !isIsolatedLeader()) {
1028             messageRetrySupport.retryMessages();
1029         }
1030     }
1031
1032     @Override
1033     protected void onLeaderChanged(final String oldLeader, final String newLeader) {
1034         shardMBean.incrementLeadershipChangeCount();
1035         paused = false;
1036
1037         if (!isLeader()) {
1038             if (!knownFrontends.isEmpty()) {
1039                 LOG.debug("{}: removing frontend state for {}", persistenceId(), knownFrontends.keySet());
1040                 knownFrontends = ImmutableMap.of();
1041             }
1042
1043             requestMessageAssembler.close();
1044
1045             if (!hasLeader()) {
1046                 // No leader anywhere, nothing else to do
1047                 return;
1048             }
1049
1050             // Another leader was elected. If we were the previous leader and had pending transactions, convert
1051             // them to transaction messages and send to the new leader.
1052             ActorSelection leader = getLeader();
1053             if (leader != null) {
1054                 Collection<?> messagesToForward = convertPendingTransactionsToMessages();
1055
1056                 if (!messagesToForward.isEmpty()) {
1057                     LOG.debug("{}: Forwarding {} pending transaction messages to leader {}", persistenceId(),
1058                             messagesToForward.size(), leader);
1059
1060                     for (Object message : messagesToForward) {
1061                         LOG.debug("{}: Forwarding pending transaction message {}", persistenceId(), message);
1062
1063                         leader.tell(message, self());
1064                     }
1065                 }
1066             } else {
1067                 commitCoordinator.abortPendingTransactions("The transacton was aborted due to inflight leadership "
1068                         + "change and the leader address isn't available.", this);
1069             }
1070         } else {
1071             // We have become the leader, we need to reconstruct frontend state
1072             knownFrontends = Verify.verifyNotNull(frontendMetadata.toLeaderState(this));
1073             LOG.debug("{}: became leader with frontend state for {}", persistenceId(), knownFrontends.keySet());
1074         }
1075
1076         if (!isIsolatedLeader()) {
1077             messageRetrySupport.retryMessages();
1078         }
1079     }
1080
1081     /**
1082      * Clears all pending transactions and converts them to messages to be forwarded to a new leader.
1083      *
1084      * @return the converted messages
1085      */
1086     public Collection<?> convertPendingTransactionsToMessages() {
1087         return commitCoordinator.convertPendingTransactionsToMessages(
1088                 datastoreContext.getShardBatchedModificationCount());
1089     }
1090
1091     @Override
1092     protected 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 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 = Verify.verifyNotNull(frontendMetadata.toLeaderState(this));
1114     }
1115
1116     @Override
1117     protected OnDemandRaftState.AbstractBuilder<?, ?> newOnDemandRaftStateBuilder() {
1118         return OnDemandShardState.newBuilder().treeChangeListenerActors(treeChangeSupport.getListenerActors())
1119                 .commitCohortActors(store.getCohortActors());
1120     }
1121
1122     @Override
1123     public String persistenceId() {
1124         return this.name;
1125     }
1126
1127     @Override
1128     public String journalPluginId() {
1129         // This method may be invoked from super constructor (wonderful), hence we also need to handle the case of
1130         // the field being uninitialized because our constructor is not finished.
1131         if (datastoreContext != null && !datastoreContext.isPersistent()) {
1132             return NON_PERSISTENT_JOURNAL_ID;
1133         }
1134         return super.journalPluginId();
1135     }
1136
1137     @VisibleForTesting
1138     ShardCommitCoordinator getCommitCoordinator() {
1139         return commitCoordinator;
1140     }
1141
1142     public DatastoreContext getDatastoreContext() {
1143         return datastoreContext;
1144     }
1145
1146     @VisibleForTesting
1147     public ShardDataTree getDataStore() {
1148         return store;
1149     }
1150
1151     @VisibleForTesting
1152     ShardStats getShardMBean() {
1153         return shardMBean;
1154     }
1155
1156     public static Builder builder() {
1157         return new Builder();
1158     }
1159
1160     public abstract static class AbstractBuilder<T extends AbstractBuilder<T, S>, S extends Shard> {
1161         private final Class<? extends S> shardClass;
1162         private ShardIdentifier id;
1163         private Map<String, String> peerAddresses = Collections.emptyMap();
1164         private DatastoreContext datastoreContext;
1165         private EffectiveModelContextProvider schemaContextProvider;
1166         private DatastoreSnapshot.ShardSnapshot restoreFromSnapshot;
1167         private DataTree dataTree;
1168
1169         private volatile boolean sealed;
1170
1171         protected AbstractBuilder(final Class<? extends S> shardClass) {
1172             this.shardClass = shardClass;
1173         }
1174
1175         protected void checkSealed() {
1176             checkState(!sealed, "Builder isalready sealed - further modifications are not allowed");
1177         }
1178
1179         @SuppressWarnings("unchecked")
1180         private T self() {
1181             return (T) this;
1182         }
1183
1184         public T id(final ShardIdentifier newId) {
1185             checkSealed();
1186             this.id = newId;
1187             return self();
1188         }
1189
1190         public T peerAddresses(final Map<String, String> newPeerAddresses) {
1191             checkSealed();
1192             this.peerAddresses = newPeerAddresses;
1193             return self();
1194         }
1195
1196         public T datastoreContext(final DatastoreContext newDatastoreContext) {
1197             checkSealed();
1198             this.datastoreContext = newDatastoreContext;
1199             return self();
1200         }
1201
1202         public T schemaContextProvider(final EffectiveModelContextProvider newSchemaContextProvider) {
1203             checkSealed();
1204             this.schemaContextProvider = requireNonNull(newSchemaContextProvider);
1205             return self();
1206         }
1207
1208         public T restoreFromSnapshot(final DatastoreSnapshot.ShardSnapshot newRestoreFromSnapshot) {
1209             checkSealed();
1210             this.restoreFromSnapshot = newRestoreFromSnapshot;
1211             return self();
1212         }
1213
1214         public T dataTree(final DataTree newDataTree) {
1215             checkSealed();
1216             this.dataTree = newDataTree;
1217             return self();
1218         }
1219
1220         public ShardIdentifier getId() {
1221             return id;
1222         }
1223
1224         public Map<String, String> getPeerAddresses() {
1225             return peerAddresses;
1226         }
1227
1228         public DatastoreContext getDatastoreContext() {
1229             return datastoreContext;
1230         }
1231
1232         public EffectiveModelContext getSchemaContext() {
1233             return Verify.verifyNotNull(schemaContextProvider.getEffectiveModelContext());
1234         }
1235
1236         public DatastoreSnapshot.ShardSnapshot getRestoreFromSnapshot() {
1237             return restoreFromSnapshot;
1238         }
1239
1240         public DataTree getDataTree() {
1241             return dataTree;
1242         }
1243
1244         public TreeType getTreeType() {
1245             switch (datastoreContext.getLogicalStoreType()) {
1246                 case CONFIGURATION:
1247                     return TreeType.CONFIGURATION;
1248                 case OPERATIONAL:
1249                     return TreeType.OPERATIONAL;
1250                 default:
1251                     throw new IllegalStateException("Unhandled logical store type "
1252                             + datastoreContext.getLogicalStoreType());
1253             }
1254         }
1255
1256         protected void verify() {
1257             requireNonNull(id, "id should not be null");
1258             requireNonNull(peerAddresses, "peerAddresses should not be null");
1259             requireNonNull(datastoreContext, "dataStoreContext should not be null");
1260             requireNonNull(schemaContextProvider, "schemaContextProvider should not be null");
1261         }
1262
1263         public Props props() {
1264             sealed = true;
1265             verify();
1266             return Props.create(shardClass, this);
1267         }
1268     }
1269
1270     public static class Builder extends AbstractBuilder<Builder, Shard> {
1271         Builder() {
1272             this(Shard.class);
1273         }
1274
1275         Builder(final Class<? extends Shard> shardClass) {
1276             super(shardClass);
1277         }
1278     }
1279
1280     Ticker ticker() {
1281         return Ticker.systemTicker();
1282     }
1283
1284     void scheduleNextPendingTransaction() {
1285         self().tell(RESUME_NEXT_PENDING_TRANSACTION, ActorRef.noSender());
1286     }
1287 }