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

©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.