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

©2013 OpenDaylight, A Linux Foundation Collaborative Project. All Rights Reserved.
OpenDaylight is a registered trademark of The OpenDaylight Project, Inc.
Linux Foundation and OpenDaylight are registered trademarks of the Linux Foundation.
Linux is a registered trademark of Linus Torvalds.