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