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

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