Add MXBean to report shard registered DTCL/DCL info
[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     private static @Nonnull ABIVersion selectVersion(final ConnectClientRequest message) {
506         final Range<ABIVersion> clientRange = Range.closed(message.getMinVersion(), message.getMaxVersion());
507         for (ABIVersion v : SUPPORTED_ABIVERSIONS) {
508             if (clientRange.contains(v)) {
509                 return v;
510             }
511         }
512
513         throw new IllegalArgumentException(String.format(
514             "No common version between backend versions %s and client versions %s", SUPPORTED_ABIVERSIONS,
515             clientRange));
516     }
517
518     @SuppressWarnings("checkstyle:IllegalCatch")
519     private void handleConnectClient(final ConnectClientRequest message) {
520         try {
521             final ClientIdentifier clientId = message.getTarget();
522             final LeaderFrontendState existing = findFrontend(clientId);
523             if (existing != null) {
524                 existing.touch();
525             }
526
527             if (!isLeader() || !isLeaderActive()) {
528                 LOG.info("{}: not currently leader, rejecting request {}. isLeader: {}, isLeaderActive: {},"
529                                 + "isLeadershipTransferInProgress: {}.",
530                         persistenceId(), message, isLeader(), isLeaderActive(), isLeadershipTransferInProgress());
531                 throw new NotLeaderException(getSelf());
532             }
533
534             final ABIVersion selectedVersion = selectVersion(message);
535             final LeaderFrontendState frontend;
536             if (existing == null) {
537                 frontend = new LeaderFrontendState(persistenceId(), clientId, store);
538                 knownFrontends.put(clientId.getFrontendId(), frontend);
539                 LOG.debug("{}: created state {} for client {}", persistenceId(), frontend, clientId);
540             } else {
541                 frontend = existing;
542             }
543
544             frontend.reconnect();
545             message.getReplyTo().tell(new ConnectClientSuccess(message.getTarget(), message.getSequence(), getSelf(),
546                 ImmutableList.of(), store.getDataTree(), CLIENT_MAX_MESSAGES).toVersion(selectedVersion),
547                 ActorRef.noSender());
548         } catch (RequestException | RuntimeException e) {
549             message.getReplyTo().tell(new Failure(e), ActorRef.noSender());
550         }
551     }
552
553     private @Nullable RequestSuccess<?, ?> handleRequest(final RequestEnvelope envelope, final long now)
554             throws RequestException {
555         // We are not the leader, hence we want to fail-fast.
556         if (!isLeader() || paused || !isLeaderActive()) {
557             LOG.debug("{}: not currently active leader, rejecting request {}. isLeader: {}, isLeaderActive: {},"
558                             + "isLeadershipTransferInProgress: {}, paused: {}",
559                     persistenceId(), envelope, isLeader(), isLeaderActive(), isLeadershipTransferInProgress(), paused);
560             throw new NotLeaderException(getSelf());
561         }
562
563         final Request<?, ?> request = envelope.getMessage();
564         if (request instanceof TransactionRequest) {
565             final TransactionRequest<?> txReq = (TransactionRequest<?>)request;
566             final ClientIdentifier clientId = txReq.getTarget().getHistoryId().getClientId();
567             return getFrontend(clientId).handleTransactionRequest(txReq, envelope, now);
568         } else if (request instanceof LocalHistoryRequest) {
569             final LocalHistoryRequest<?> lhReq = (LocalHistoryRequest<?>)request;
570             final ClientIdentifier clientId = lhReq.getTarget().getClientId();
571             return getFrontend(clientId).handleLocalHistoryRequest(lhReq, envelope, now);
572         } else {
573             LOG.warn("{}: rejecting unsupported request {}", persistenceId(), request);
574             throw new UnsupportedRequestException(request);
575         }
576     }
577
578     private boolean hasLeader() {
579         return getLeaderId() != null;
580     }
581
582     public int getPendingTxCommitQueueSize() {
583         return store.getQueueSize();
584     }
585
586     public int getCohortCacheSize() {
587         return commitCoordinator.getCohortCacheSize();
588     }
589
590     @Override
591     protected Optional<ActorRef> getRoleChangeNotifier() {
592         return roleChangeNotifier;
593     }
594
595     @Override
596     protected LeaderStateChanged newLeaderStateChanged(final String memberId, final String leaderId,
597             final short leaderPayloadVersion) {
598         return isLeader() ? new ShardLeaderStateChanged(memberId, leaderId, store.getDataTree(), leaderPayloadVersion)
599                 : new ShardLeaderStateChanged(memberId, leaderId, leaderPayloadVersion);
600     }
601
602     protected void onDatastoreContext(final DatastoreContext context) {
603         datastoreContext = context;
604
605         setTransactionCommitTimeout();
606
607         setPersistence(datastoreContext.isPersistent());
608
609         updateConfigParams(datastoreContext.getShardRaftConfig());
610     }
611
612     // applyState() will be invoked once consensus is reached on the payload
613     void persistPayload(final Identifier id, final Payload payload, final boolean batchHint) {
614         boolean canSkipPayload = !hasFollowers() && !persistence().isRecoveryApplicable();
615         if (canSkipPayload) {
616             applyState(self(), id, payload);
617         } else {
618             // We are faking the sender
619             persistData(self(), id, payload, batchHint);
620         }
621     }
622
623     private void handleCommitTransaction(final CommitTransaction commit) {
624         if (isLeader()) {
625             commitCoordinator.handleCommit(commit.getTransactionId(), getSender(), this);
626         } else {
627             ActorSelection leader = getLeader();
628             if (leader == null) {
629                 messageRetrySupport.addMessageToRetry(commit, getSender(),
630                         "Could not commit transaction " + commit.getTransactionId());
631             } else {
632                 LOG.debug("{}: Forwarding CommitTransaction to leader {}", persistenceId(), leader);
633                 leader.forward(commit, getContext());
634             }
635         }
636     }
637
638     private void handleCanCommitTransaction(final CanCommitTransaction canCommit) {
639         LOG.debug("{}: Can committing transaction {}", persistenceId(), canCommit.getTransactionId());
640
641         if (isLeader()) {
642             commitCoordinator.handleCanCommit(canCommit.getTransactionId(), getSender(), this);
643         } else {
644             ActorSelection leader = getLeader();
645             if (leader == null) {
646                 messageRetrySupport.addMessageToRetry(canCommit, getSender(),
647                         "Could not canCommit transaction " + canCommit.getTransactionId());
648             } else {
649                 LOG.debug("{}: Forwarding CanCommitTransaction to leader {}", persistenceId(), leader);
650                 leader.forward(canCommit, getContext());
651             }
652         }
653     }
654
655     @SuppressWarnings("checkstyle:IllegalCatch")
656     protected void handleBatchedModificationsLocal(final BatchedModifications batched, final ActorRef sender) {
657         try {
658             commitCoordinator.handleBatchedModifications(batched, sender, this);
659         } catch (Exception e) {
660             LOG.error("{}: Error handling BatchedModifications for Tx {}", persistenceId(),
661                     batched.getTransactionId(), e);
662             sender.tell(new Failure(e), getSelf());
663         }
664     }
665
666     private void handleBatchedModifications(final BatchedModifications batched) {
667         // This message is sent to prepare the modifications transaction directly on the Shard as an
668         // optimization to avoid the extra overhead of a separate ShardTransaction actor. On the last
669         // BatchedModifications message, the caller sets the ready flag in the message indicating
670         // modifications are complete. The reply contains the cohort actor path (this actor) for the caller
671         // to initiate the 3-phase commit. This also avoids the overhead of sending an additional
672         // ReadyTransaction message.
673
674         // If we're not the leader then forward to the leader. This is a safety measure - we shouldn't
675         // normally get here if we're not the leader as the front-end (TransactionProxy) should determine
676         // the primary/leader shard. However with timing and caching on the front-end, there's a small
677         // window where it could have a stale leader during leadership transitions.
678         //
679         boolean isLeaderActive = isLeaderActive();
680         if (isLeader() && isLeaderActive) {
681             handleBatchedModificationsLocal(batched, getSender());
682         } else {
683             ActorSelection leader = getLeader();
684             if (!isLeaderActive || leader == null) {
685                 messageRetrySupport.addMessageToRetry(batched, getSender(),
686                         "Could not commit transaction " + batched.getTransactionId());
687             } else {
688                 // If this is not the first batch and leadership changed in between batched messages,
689                 // we need to reconstruct previous BatchedModifications from the transaction
690                 // DataTreeModification, honoring the max batched modification count, and forward all the
691                 // previous BatchedModifications to the new leader.
692                 Collection<BatchedModifications> newModifications = commitCoordinator
693                         .createForwardedBatchedModifications(batched,
694                                 datastoreContext.getShardBatchedModificationCount());
695
696                 LOG.debug("{}: Forwarding {} BatchedModifications to leader {}", persistenceId(),
697                         newModifications.size(), leader);
698
699                 for (BatchedModifications bm : newModifications) {
700                     leader.forward(bm, getContext());
701                 }
702             }
703         }
704     }
705
706     private boolean failIfIsolatedLeader(final ActorRef sender) {
707         if (isIsolatedLeader()) {
708             sender.tell(new Failure(new NoShardLeaderException(String.format(
709                     "Shard %s was the leader but has lost contact with all of its followers. Either all"
710                     + " other follower nodes are down or this node is isolated by a network partition.",
711                     persistenceId()))), getSelf());
712             return true;
713         }
714
715         return false;
716     }
717
718     protected boolean isIsolatedLeader() {
719         return getRaftState() == RaftState.IsolatedLeader;
720     }
721
722     @SuppressWarnings("checkstyle:IllegalCatch")
723     private void handleReadyLocalTransaction(final ReadyLocalTransaction message) {
724         LOG.debug("{}: handleReadyLocalTransaction for {}", persistenceId(), message.getTransactionId());
725
726         boolean isLeaderActive = isLeaderActive();
727         if (isLeader() && isLeaderActive) {
728             try {
729                 commitCoordinator.handleReadyLocalTransaction(message, getSender(), this);
730             } catch (Exception e) {
731                 LOG.error("{}: Error handling ReadyLocalTransaction for Tx {}", persistenceId(),
732                         message.getTransactionId(), e);
733                 getSender().tell(new Failure(e), getSelf());
734             }
735         } else {
736             ActorSelection leader = getLeader();
737             if (!isLeaderActive || leader == null) {
738                 messageRetrySupport.addMessageToRetry(message, getSender(),
739                         "Could not commit transaction " + message.getTransactionId());
740             } else {
741                 LOG.debug("{}: Forwarding ReadyLocalTransaction to leader {}", persistenceId(), leader);
742                 message.setRemoteVersion(getCurrentBehavior().getLeaderPayloadVersion());
743                 leader.forward(message, getContext());
744             }
745         }
746     }
747
748     private void handleForwardedReadyTransaction(final ForwardedReadyTransaction forwardedReady) {
749         LOG.debug("{}: handleForwardedReadyTransaction for {}", persistenceId(), forwardedReady.getTransactionId());
750
751         boolean isLeaderActive = isLeaderActive();
752         if (isLeader() && isLeaderActive) {
753             commitCoordinator.handleForwardedReadyTransaction(forwardedReady, getSender(), this);
754         } else {
755             ActorSelection leader = getLeader();
756             if (!isLeaderActive || leader == null) {
757                 messageRetrySupport.addMessageToRetry(forwardedReady, getSender(),
758                         "Could not commit transaction " + forwardedReady.getTransactionId());
759             } else {
760                 LOG.debug("{}: Forwarding ForwardedReadyTransaction to leader {}", persistenceId(), leader);
761
762                 ReadyLocalTransaction readyLocal = new ReadyLocalTransaction(forwardedReady.getTransactionId(),
763                         forwardedReady.getTransaction().getSnapshot(), forwardedReady.isDoImmediateCommit());
764                 readyLocal.setRemoteVersion(getCurrentBehavior().getLeaderPayloadVersion());
765                 leader.forward(readyLocal, getContext());
766             }
767         }
768     }
769
770     private void handleAbortTransaction(final AbortTransaction abort) {
771         doAbortTransaction(abort.getTransactionId(), getSender());
772     }
773
774     void doAbortTransaction(final Identifier transactionID, final ActorRef sender) {
775         commitCoordinator.handleAbort(transactionID, sender, this);
776     }
777
778     private void handleCreateTransaction(final Object message) {
779         if (isLeader()) {
780             createTransaction(CreateTransaction.fromSerializable(message));
781         } else if (getLeader() != null) {
782             getLeader().forward(message, getContext());
783         } else {
784             getSender().tell(new Failure(new NoShardLeaderException(
785                     "Could not create a shard transaction", persistenceId())), getSelf());
786         }
787     }
788
789     private void closeTransactionChain(final CloseTransactionChain closeTransactionChain) {
790         final LocalHistoryIdentifier id = closeTransactionChain.getIdentifier();
791         store.closeTransactionChain(id, null);
792         store.purgeTransactionChain(id, null);
793     }
794
795     @SuppressWarnings("checkstyle:IllegalCatch")
796     private void createTransaction(final CreateTransaction createTransaction) {
797         try {
798             if (TransactionType.fromInt(createTransaction.getTransactionType()) != TransactionType.READ_ONLY
799                     && failIfIsolatedLeader(getSender())) {
800                 return;
801             }
802
803             ActorRef transactionActor = createTransaction(createTransaction.getTransactionType(),
804                 createTransaction.getTransactionId());
805
806             getSender().tell(new CreateTransactionReply(Serialization.serializedActorPath(transactionActor),
807                     createTransaction.getTransactionId(), createTransaction.getVersion()).toSerializable(), getSelf());
808         } catch (Exception e) {
809             getSender().tell(new Failure(e), getSelf());
810         }
811     }
812
813     private ActorRef createTransaction(final int transactionType, final TransactionIdentifier transactionId) {
814         LOG.debug("{}: Creating transaction : {} ", persistenceId(), transactionId);
815         return transactionActorFactory.newShardTransaction(TransactionType.fromInt(transactionType),
816             transactionId);
817     }
818
819     private void updateSchemaContext(final UpdateSchemaContext message) {
820         updateSchemaContext(message.getSchemaContext());
821     }
822
823     @VisibleForTesting
824     void updateSchemaContext(final SchemaContext schemaContext) {
825         store.updateSchemaContext(schemaContext);
826     }
827
828     private boolean isMetricsCaptureEnabled() {
829         CommonConfig config = new CommonConfig(getContext().system().settings().config());
830         return config.isMetricCaptureEnabled();
831     }
832
833     @Override
834     @VisibleForTesting
835     public RaftActorSnapshotCohort getRaftActorSnapshotCohort() {
836         return snapshotCohort;
837     }
838
839     @Override
840     @Nonnull
841     protected RaftActorRecoveryCohort getRaftActorRecoveryCohort() {
842         return new ShardRecoveryCoordinator(store,
843             restoreFromSnapshot != null ? restoreFromSnapshot.getSnapshot() : null, persistenceId(), LOG);
844     }
845
846     @Override
847     protected void onRecoveryComplete() {
848         restoreFromSnapshot = null;
849
850         //notify shard manager
851         getContext().parent().tell(new ActorInitialized(), getSelf());
852
853         // Being paranoid here - this method should only be called once but just in case...
854         if (txCommitTimeoutCheckSchedule == null) {
855             // Schedule a message to be periodically sent to check if the current in-progress
856             // transaction should be expired and aborted.
857             FiniteDuration period = Duration.create(transactionCommitTimeout / 3, TimeUnit.MILLISECONDS);
858             txCommitTimeoutCheckSchedule = getContext().system().scheduler().schedule(
859                     period, period, getSelf(),
860                     TX_COMMIT_TIMEOUT_CHECK_MESSAGE, getContext().dispatcher(), ActorRef.noSender());
861         }
862     }
863
864     @Override
865     protected void applyState(final ActorRef clientActor, final Identifier identifier, final Object data) {
866         if (data instanceof Payload) {
867             try {
868                 store.applyReplicatedPayload(identifier, (Payload)data);
869             } catch (DataValidationFailedException | IOException e) {
870                 LOG.error("{}: Error applying replica {}", persistenceId(), identifier, e);
871             }
872         } else {
873             LOG.error("{}: Unknown state for {} received {}", persistenceId(), identifier, data);
874         }
875     }
876
877     @Override
878     protected void onStateChanged() {
879         boolean isLeader = isLeader();
880         boolean hasLeader = hasLeader();
881         changeSupport.onLeadershipChange(isLeader, hasLeader);
882         treeChangeSupport.onLeadershipChange(isLeader, hasLeader);
883
884         // If this actor is no longer the leader close all the transaction chains
885         if (!isLeader) {
886             if (LOG.isDebugEnabled()) {
887                 LOG.debug(
888                     "{}: onStateChanged: Closing all transaction chains because shard {} is no longer the leader",
889                     persistenceId(), getId());
890             }
891
892             paused = false;
893             store.purgeLeaderState();
894         }
895
896         if (hasLeader && !isIsolatedLeader()) {
897             messageRetrySupport.retryMessages();
898         }
899     }
900
901     @Override
902     protected void onLeaderChanged(final String oldLeader, final String newLeader) {
903         shardMBean.incrementLeadershipChangeCount();
904         paused = false;
905
906         if (!isLeader()) {
907             if (!knownFrontends.isEmpty()) {
908                 LOG.debug("{}: removing frontend state for {}", persistenceId(), knownFrontends.keySet());
909                 knownFrontends = ImmutableMap.of();
910             }
911
912             requestMessageAssembler.close();
913
914             if (!hasLeader()) {
915                 // No leader anywhere, nothing else to do
916                 return;
917             }
918
919             // Another leader was elected. If we were the previous leader and had pending transactions, convert
920             // them to transaction messages and send to the new leader.
921             ActorSelection leader = getLeader();
922             if (leader != null) {
923                 Collection<?> messagesToForward = convertPendingTransactionsToMessages();
924
925                 if (!messagesToForward.isEmpty()) {
926                     LOG.debug("{}: Forwarding {} pending transaction messages to leader {}", persistenceId(),
927                             messagesToForward.size(), leader);
928
929                     for (Object message : messagesToForward) {
930                         leader.tell(message, self());
931                     }
932                 }
933             } else {
934                 commitCoordinator.abortPendingTransactions("The transacton was aborted due to inflight leadership "
935                         + "change and the leader address isn't available.", this);
936             }
937         } else {
938             // We have become the leader, we need to reconstruct frontend state
939             knownFrontends = Verify.verifyNotNull(frontendMetadata.toLeaderState(this));
940             LOG.debug("{}: became leader with frontend state for {}", persistenceId(), knownFrontends.keySet());
941         }
942
943         if (!isIsolatedLeader()) {
944             messageRetrySupport.retryMessages();
945         }
946     }
947
948     /**
949      * Clears all pending transactions and converts them to messages to be forwarded to a new leader.
950      *
951      * @return the converted messages
952      */
953     public Collection<?> convertPendingTransactionsToMessages() {
954         return commitCoordinator.convertPendingTransactionsToMessages(
955                 datastoreContext.getShardBatchedModificationCount());
956     }
957
958     @Override
959     protected void pauseLeader(final Runnable operation) {
960         LOG.debug("{}: In pauseLeader, operation: {}", persistenceId(), operation);
961         paused = true;
962
963         // Tell-based protocol can replay transaction state, so it is safe to blow it up when we are paused.
964         knownFrontends.values().forEach(LeaderFrontendState::retire);
965         knownFrontends = ImmutableMap.of();
966
967         store.setRunOnPendingTransactionsComplete(operation);
968     }
969
970     @Override
971     protected void unpauseLeader() {
972         LOG.debug("{}: In unpauseLeader", persistenceId());
973         paused = false;
974
975         store.setRunOnPendingTransactionsComplete(null);
976
977         // Restore tell-based protocol state as if we were becoming the leader
978         knownFrontends = Verify.verifyNotNull(frontendMetadata.toLeaderState(this));
979     }
980
981     @Override
982     protected OnDemandRaftState.AbstractBuilder<?, ?> newOnDemandRaftStateBuilder() {
983         return OnDemandShardState.newBuilder().treeChangeListenerActors(treeChangeSupport.getListenerActors())
984                 .dataChangeListenerActors(changeSupport.getListenerActors())
985                 .commitCohortActors(store.getCohortActors());
986     }
987
988     @Override
989     public String persistenceId() {
990         return this.name;
991     }
992
993     @VisibleForTesting
994     ShardCommitCoordinator getCommitCoordinator() {
995         return commitCoordinator;
996     }
997
998     public DatastoreContext getDatastoreContext() {
999         return datastoreContext;
1000     }
1001
1002     @VisibleForTesting
1003     public ShardDataTree getDataStore() {
1004         return store;
1005     }
1006
1007     @VisibleForTesting
1008     ShardStats getShardMBean() {
1009         return shardMBean;
1010     }
1011
1012     public static Builder builder() {
1013         return new Builder();
1014     }
1015
1016     public abstract static class AbstractBuilder<T extends AbstractBuilder<T, S>, S extends Shard> {
1017         private final Class<S> shardClass;
1018         private ShardIdentifier id;
1019         private Map<String, String> peerAddresses = Collections.emptyMap();
1020         private DatastoreContext datastoreContext;
1021         private SchemaContextProvider schemaContextProvider;
1022         private DatastoreSnapshot.ShardSnapshot restoreFromSnapshot;
1023         private TipProducingDataTree dataTree;
1024         private volatile boolean sealed;
1025
1026         protected AbstractBuilder(final Class<S> shardClass) {
1027             this.shardClass = shardClass;
1028         }
1029
1030         protected void checkSealed() {
1031             Preconditions.checkState(!sealed, "Builder isalready sealed - further modifications are not allowed");
1032         }
1033
1034         @SuppressWarnings("unchecked")
1035         private T self() {
1036             return (T) this;
1037         }
1038
1039         public T id(final ShardIdentifier newId) {
1040             checkSealed();
1041             this.id = newId;
1042             return self();
1043         }
1044
1045         public T peerAddresses(final Map<String, String> newPeerAddresses) {
1046             checkSealed();
1047             this.peerAddresses = newPeerAddresses;
1048             return self();
1049         }
1050
1051         public T datastoreContext(final DatastoreContext newDatastoreContext) {
1052             checkSealed();
1053             this.datastoreContext = newDatastoreContext;
1054             return self();
1055         }
1056
1057         public T schemaContextProvider(final SchemaContextProvider schemaContextProvider) {
1058             checkSealed();
1059             this.schemaContextProvider = Preconditions.checkNotNull(schemaContextProvider);
1060             return self();
1061         }
1062
1063         public T restoreFromSnapshot(final DatastoreSnapshot.ShardSnapshot newRestoreFromSnapshot) {
1064             checkSealed();
1065             this.restoreFromSnapshot = newRestoreFromSnapshot;
1066             return self();
1067         }
1068
1069         public T dataTree(final TipProducingDataTree newDataTree) {
1070             checkSealed();
1071             this.dataTree = newDataTree;
1072             return self();
1073         }
1074
1075         public ShardIdentifier getId() {
1076             return id;
1077         }
1078
1079         public Map<String, String> getPeerAddresses() {
1080             return peerAddresses;
1081         }
1082
1083         public DatastoreContext getDatastoreContext() {
1084             return datastoreContext;
1085         }
1086
1087         public SchemaContext getSchemaContext() {
1088             return Verify.verifyNotNull(schemaContextProvider.getSchemaContext());
1089         }
1090
1091         public DatastoreSnapshot.ShardSnapshot getRestoreFromSnapshot() {
1092             return restoreFromSnapshot;
1093         }
1094
1095         public TipProducingDataTree getDataTree() {
1096             return dataTree;
1097         }
1098
1099         public TreeType getTreeType() {
1100             switch (datastoreContext.getLogicalStoreType()) {
1101                 case CONFIGURATION:
1102                     return TreeType.CONFIGURATION;
1103                 case OPERATIONAL:
1104                     return TreeType.OPERATIONAL;
1105                 default:
1106                     throw new IllegalStateException("Unhandled logical store type "
1107                             + datastoreContext.getLogicalStoreType());
1108             }
1109         }
1110
1111         protected void verify() {
1112             Preconditions.checkNotNull(id, "id should not be null");
1113             Preconditions.checkNotNull(peerAddresses, "peerAddresses should not be null");
1114             Preconditions.checkNotNull(datastoreContext, "dataStoreContext should not be null");
1115             Preconditions.checkNotNull(schemaContextProvider, "schemaContextProvider should not be null");
1116         }
1117
1118         public Props props() {
1119             sealed = true;
1120             verify();
1121             return Props.create(shardClass, this);
1122         }
1123     }
1124
1125     public static class Builder extends AbstractBuilder<Builder, Shard> {
1126         private Builder() {
1127             super(Shard.class);
1128         }
1129     }
1130
1131     Ticker ticker() {
1132         return Ticker.systemTicker();
1133     }
1134
1135     void scheduleNextPendingTransaction() {
1136         self().tell(RESUME_NEXT_PENDING_TRANSACTION, ActorRef.noSender());
1137     }
1138 }

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