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