2 * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
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
9 package org.opendaylight.controller.cluster.datastore;
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;
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;
115 * A Shard represents a portion of the logical data tree.
118 * Our Shard uses InMemoryDataTree as it's internal representation and delegates all requests it
120 public class Shard extends RaftActor {
123 static final Object TX_COMMIT_TIMEOUT_CHECK_MESSAGE = new Object() {
125 public String toString() {
126 return "txCommitTimeoutCheck";
131 static final Object GET_SHARD_MBEAN_MESSAGE = new Object() {
133 public String toString() {
134 return "getShardMBeanMessage";
138 static final Object RESUME_NEXT_PENDING_TRANSACTION = new Object() {
140 public String toString() {
141 return "resumeNextPendingTransaction";
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";
148 private static final Collection<ABIVersion> SUPPORTED_ABIVERSIONS;
151 final ABIVersion[] values = ABIVersion.values();
152 final ABIVersion[] real = Arrays.copyOfRange(values, 1, values.length - 1);
153 SUPPORTED_ABIVERSIONS = ImmutableList.copyOf(real).reverse();
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;
159 // The state of this Shard
160 private final ShardDataTree store;
162 /// The name of this shard
163 private final String name;
165 private final ShardStats shardMBean;
167 private final ShardDataTreeListenerInfoMXBeanImpl listenerInfoMXBean;
169 private DatastoreContext datastoreContext;
171 private final ShardCommitCoordinator commitCoordinator;
173 private long transactionCommitTimeout;
175 private Cancellable txCommitTimeoutCheckSchedule;
177 private final Optional<ActorRef> roleChangeNotifier;
179 private final MessageTracker appendEntriesReplyTracker;
181 private final ShardTransactionActorFactory transactionActorFactory;
183 private final ShardSnapshotCohort snapshotCohort;
185 private final DataTreeChangeListenerSupport treeChangeSupport = new DataTreeChangeListenerSupport(this);
186 private final DataChangeListenerSupport changeSupport = new DataChangeListenerSupport(this);
189 private ShardSnapshot restoreFromSnapshot;
191 private final ShardTransactionMessageRetrySupport messageRetrySupport;
193 private final FrontendMetadata frontendMetadata;
194 private Map<FrontendIdentifier, LeaderFrontendState> knownFrontends = ImmutableMap.of();
195 private boolean paused;
197 private final MessageSlicer responseMessageSlicer;
198 private final Dispatchers dispatchers;
200 private final MessageAssembler requestMessageAssembler;
202 protected Shard(final AbstractBuilder<?, ?> builder) {
203 super(builder.getId().toString(), builder.getPeerAddresses(),
204 Optional.of(builder.getDatastoreContext().getShardRaftConfig()), DataStoreVersions.CURRENT_VERSION);
206 this.name = builder.getId().toString();
207 this.datastoreContext = builder.getDatastoreContext();
208 this.restoreFromSnapshot = builder.getRestoreFromSnapshot();
209 this.frontendMetadata = new FrontendMetadata(name);
211 setPersistence(datastoreContext.isPersistent());
213 LOG.info("Shard created : {}, persistent : {}", name, datastoreContext.isPersistent());
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);
223 store = new ShardDataTree(this, builder.getSchemaContext(), builder.getTreeType(),
224 builder.getDatastoreContext().getStoreRoot(), treeChangeListenerPublisher,
225 dataChangeListenerPublisher, name, frontendMetadata);
228 shardMBean = ShardMBeanFactory.getShardStatsMBean(name, datastoreContext.getDataStoreMXBeanType(), this);
230 if (isMetricsCaptureEnabled()) {
231 getContext().become(new MeteringBehavior(this));
234 commitCoordinator = new ShardCommitCoordinator(store, LOG, this.name);
236 setTransactionCommitTimeout();
238 // create a notifier actor for each cluster member
239 roleChangeNotifier = createRoleChangeNotifier(name);
241 appendEntriesReplyTracker = new MessageTracker(AppendEntriesReply.class,
242 getRaftActorContext().getConfigParams().getIsolatedCheckIntervalInMillis());
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());
249 snapshotCohort = ShardSnapshotCohort.create(getContext(), builder.getId().getMemberName(), store, LOG,
252 messageRetrySupport = new ShardTransactionMessageRetrySupport(this);
254 responseMessageSlicer = MessageSlicer.builder().logContext(this.name)
255 .messageSliceSize(datastoreContext.getMaximumMessageSliceSize())
256 .fileBackedStreamFactory(getRaftActorContext().getFileBackedOutputStreamFactory())
257 .expireStateAfterInactivity(2, TimeUnit.MINUTES).build();
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();
264 listenerInfoMXBean = new ShardDataTreeListenerInfoMXBeanImpl(name, datastoreContext.getDataStoreMXBeanType(),
266 listenerInfoMXBean.register();
269 private void setTransactionCommitTimeout() {
270 transactionCommitTimeout = TimeUnit.MILLISECONDS.convert(
271 datastoreContext.getShardTransactionCommitTimeoutInSeconds(), TimeUnit.SECONDS) / 2;
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);
281 public void postStop() {
282 LOG.info("Stopping Shard {}", persistenceId());
286 messageRetrySupport.close();
288 if (txCommitTimeoutCheckSchedule != null) {
289 txCommitTimeoutCheckSchedule.cancel();
292 commitCoordinator.abortPendingTransactions("Transaction aborted due to shutdown.", this);
294 shardMBean.unregisterMBean();
295 listenerInfoMXBean.unregister();
299 protected void handleRecover(final Object message) {
300 LOG.debug("{}: onReceiveRecover: Received message {} from {}", persistenceId(), message.getClass(),
303 super.handleRecover(message);
304 if (LOG.isTraceEnabled()) {
305 appendEntriesReplyTracker.begin();
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(),
318 store.resetTransactionBatch();
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) {
376 } else if (RESUME_NEXT_PENDING_TRANSACTION.equals(message)) {
377 store.resumeNextPendingTransaction();
378 } else if (!responseMessageSlicer.handleMessage(message)) {
379 super.handleNonRaftCommand(message);
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());
391 @SuppressWarnings("checkstyle:IllegalCatch")
392 private void handleRequestEnvelope(final RequestEnvelope envelope) {
393 final long now = ticker().read();
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);
407 envelope.sendSuccess(success, executionTimeNanos);
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);
420 private void commitTimeoutCheck() {
421 store.checkForExpiredTransactions(transactionCommitTimeout, this::updateAccess);
422 commitCoordinator.checkForExpiredTransactions(transactionCommitTimeout, this);
423 requestMessageAssembler.checkExpiredAssembledMessageState();
426 private Optional<Long> updateAccess(final SimpleShardDataTreeCohort cohort) {
427 final FrontendIdentifier frontend = cohort.getIdentifier().getHistoryId().getClientId().getFrontendId();
428 final LeaderFrontendState state = knownFrontends.get(frontend);
430 // Not tell-based protocol, do nothing
431 return Optional.absent();
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());
440 // If this frontend has freshly connected, give it some time to catch up before killing its transactions.
441 return Optional.of(state.getLastConnectTicks());
444 private void onMakeLeaderLocal() {
445 LOG.debug("{}: onMakeLeaderLocal received", persistenceId());
447 getSender().tell(new Status.Success(null), getSelf());
451 final ActorSelection leader = getLeader();
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
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())),
467 leader.tell(new RequestLeadership(getId(), getSender()), getSelf());
470 // Acquire our frontend tracking handle and verify generation matches
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());
481 LOG.debug("{}: rejecting request from outdated client {}", persistenceId(), clientId);
482 throw new RetiredGenerationException(existing.getIdentifier().getGeneration());
485 LOG.info("{}: retiring state {}, outdated by request from client {}", persistenceId(), existing, clientId);
487 knownFrontends.remove(clientId.getFrontendId());
489 LOG.debug("{}: client {} is not yet known", persistenceId(), clientId);
495 private LeaderFrontendState getFrontend(final ClientIdentifier clientId) throws RequestException {
496 final LeaderFrontendState ret = findFrontend(clientId);
501 // TODO: a dedicated exception would be better, but this is technically true, too
502 throw new OutOfSequenceEnvelopeException(0);
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)) {
513 throw new IllegalArgumentException(String.format(
514 "No common version between backend versions %s and client versions %s", SUPPORTED_ABIVERSIONS,
518 @SuppressWarnings("checkstyle:IllegalCatch")
519 private void handleConnectClient(final ConnectClientRequest message) {
521 final ClientIdentifier clientId = message.getTarget();
522 final LeaderFrontendState existing = findFrontend(clientId);
523 if (existing != null) {
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());
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);
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());
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());
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);
573 LOG.warn("{}: rejecting unsupported request {}", persistenceId(), request);
574 throw new UnsupportedRequestException(request);
578 private boolean hasLeader() {
579 return getLeaderId() != null;
582 public int getPendingTxCommitQueueSize() {
583 return store.getQueueSize();
586 public int getCohortCacheSize() {
587 return commitCoordinator.getCohortCacheSize();
591 protected Optional<ActorRef> getRoleChangeNotifier() {
592 return roleChangeNotifier;
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);
602 protected void onDatastoreContext(final DatastoreContext context) {
603 datastoreContext = context;
605 setTransactionCommitTimeout();
607 setPersistence(datastoreContext.isPersistent());
609 updateConfigParams(datastoreContext.getShardRaftConfig());
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);
618 // We are faking the sender
619 persistData(self(), id, payload, batchHint);
623 private void handleCommitTransaction(final CommitTransaction commit) {
625 commitCoordinator.handleCommit(commit.getTransactionId(), getSender(), this);
627 ActorSelection leader = getLeader();
628 if (leader == null) {
629 messageRetrySupport.addMessageToRetry(commit, getSender(),
630 "Could not commit transaction " + commit.getTransactionId());
632 LOG.debug("{}: Forwarding CommitTransaction to leader {}", persistenceId(), leader);
633 leader.forward(commit, getContext());
638 private void handleCanCommitTransaction(final CanCommitTransaction canCommit) {
639 LOG.debug("{}: Can committing transaction {}", persistenceId(), canCommit.getTransactionId());
642 commitCoordinator.handleCanCommit(canCommit.getTransactionId(), getSender(), this);
644 ActorSelection leader = getLeader();
645 if (leader == null) {
646 messageRetrySupport.addMessageToRetry(canCommit, getSender(),
647 "Could not canCommit transaction " + canCommit.getTransactionId());
649 LOG.debug("{}: Forwarding CanCommitTransaction to leader {}", persistenceId(), leader);
650 leader.forward(canCommit, getContext());
655 @SuppressWarnings("checkstyle:IllegalCatch")
656 protected void handleBatchedModificationsLocal(final BatchedModifications batched, final ActorRef sender) {
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());
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.
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.
679 boolean isLeaderActive = isLeaderActive();
680 if (isLeader() && isLeaderActive) {
681 handleBatchedModificationsLocal(batched, getSender());
683 ActorSelection leader = getLeader();
684 if (!isLeaderActive || leader == null) {
685 messageRetrySupport.addMessageToRetry(batched, getSender(),
686 "Could not commit transaction " + batched.getTransactionId());
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());
696 LOG.debug("{}: Forwarding {} BatchedModifications to leader {}", persistenceId(),
697 newModifications.size(), leader);
699 for (BatchedModifications bm : newModifications) {
700 leader.forward(bm, getContext());
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());
718 protected boolean isIsolatedLeader() {
719 return getRaftState() == RaftState.IsolatedLeader;
722 @SuppressWarnings("checkstyle:IllegalCatch")
723 private void handleReadyLocalTransaction(final ReadyLocalTransaction message) {
724 LOG.debug("{}: handleReadyLocalTransaction for {}", persistenceId(), message.getTransactionId());
726 boolean isLeaderActive = isLeaderActive();
727 if (isLeader() && isLeaderActive) {
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());
736 ActorSelection leader = getLeader();
737 if (!isLeaderActive || leader == null) {
738 messageRetrySupport.addMessageToRetry(message, getSender(),
739 "Could not commit transaction " + message.getTransactionId());
741 LOG.debug("{}: Forwarding ReadyLocalTransaction to leader {}", persistenceId(), leader);
742 message.setRemoteVersion(getCurrentBehavior().getLeaderPayloadVersion());
743 leader.forward(message, getContext());
748 private void handleForwardedReadyTransaction(final ForwardedReadyTransaction forwardedReady) {
749 LOG.debug("{}: handleForwardedReadyTransaction for {}", persistenceId(), forwardedReady.getTransactionId());
751 boolean isLeaderActive = isLeaderActive();
752 if (isLeader() && isLeaderActive) {
753 commitCoordinator.handleForwardedReadyTransaction(forwardedReady, getSender(), this);
755 ActorSelection leader = getLeader();
756 if (!isLeaderActive || leader == null) {
757 messageRetrySupport.addMessageToRetry(forwardedReady, getSender(),
758 "Could not commit transaction " + forwardedReady.getTransactionId());
760 LOG.debug("{}: Forwarding ForwardedReadyTransaction to leader {}", persistenceId(), leader);
762 ReadyLocalTransaction readyLocal = new ReadyLocalTransaction(forwardedReady.getTransactionId(),
763 forwardedReady.getTransaction().getSnapshot(), forwardedReady.isDoImmediateCommit());
764 readyLocal.setRemoteVersion(getCurrentBehavior().getLeaderPayloadVersion());
765 leader.forward(readyLocal, getContext());
770 private void handleAbortTransaction(final AbortTransaction abort) {
771 doAbortTransaction(abort.getTransactionId(), getSender());
774 void doAbortTransaction(final Identifier transactionID, final ActorRef sender) {
775 commitCoordinator.handleAbort(transactionID, sender, this);
778 private void handleCreateTransaction(final Object message) {
780 createTransaction(CreateTransaction.fromSerializable(message));
781 } else if (getLeader() != null) {
782 getLeader().forward(message, getContext());
784 getSender().tell(new Failure(new NoShardLeaderException(
785 "Could not create a shard transaction", persistenceId())), getSelf());
789 private void closeTransactionChain(final CloseTransactionChain closeTransactionChain) {
790 final LocalHistoryIdentifier id = closeTransactionChain.getIdentifier();
791 store.closeTransactionChain(id, null);
792 store.purgeTransactionChain(id, null);
795 @SuppressWarnings("checkstyle:IllegalCatch")
796 private void createTransaction(final CreateTransaction createTransaction) {
798 if (TransactionType.fromInt(createTransaction.getTransactionType()) != TransactionType.READ_ONLY
799 && failIfIsolatedLeader(getSender())) {
803 ActorRef transactionActor = createTransaction(createTransaction.getTransactionType(),
804 createTransaction.getTransactionId());
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());
813 private ActorRef createTransaction(final int transactionType, final TransactionIdentifier transactionId) {
814 LOG.debug("{}: Creating transaction : {} ", persistenceId(), transactionId);
815 return transactionActorFactory.newShardTransaction(TransactionType.fromInt(transactionType),
819 private void updateSchemaContext(final UpdateSchemaContext message) {
820 updateSchemaContext(message.getSchemaContext());
824 void updateSchemaContext(final SchemaContext schemaContext) {
825 store.updateSchemaContext(schemaContext);
828 private boolean isMetricsCaptureEnabled() {
829 CommonConfig config = new CommonConfig(getContext().system().settings().config());
830 return config.isMetricCaptureEnabled();
835 public RaftActorSnapshotCohort getRaftActorSnapshotCohort() {
836 return snapshotCohort;
841 protected RaftActorRecoveryCohort getRaftActorRecoveryCohort() {
842 return new ShardRecoveryCoordinator(store,
843 restoreFromSnapshot != null ? restoreFromSnapshot.getSnapshot() : null, persistenceId(), LOG);
847 protected void onRecoveryComplete() {
848 restoreFromSnapshot = null;
850 //notify shard manager
851 getContext().parent().tell(new ActorInitialized(), getSelf());
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());
865 protected void applyState(final ActorRef clientActor, final Identifier identifier, final Object data) {
866 if (data instanceof Payload) {
868 store.applyReplicatedPayload(identifier, (Payload)data);
869 } catch (DataValidationFailedException | IOException e) {
870 LOG.error("{}: Error applying replica {}", persistenceId(), identifier, e);
873 LOG.error("{}: Unknown state for {} received {}", persistenceId(), identifier, data);
878 protected void onStateChanged() {
879 boolean isLeader = isLeader();
880 boolean hasLeader = hasLeader();
881 changeSupport.onLeadershipChange(isLeader, hasLeader);
882 treeChangeSupport.onLeadershipChange(isLeader, hasLeader);
884 // If this actor is no longer the leader close all the transaction chains
886 if (LOG.isDebugEnabled()) {
888 "{}: onStateChanged: Closing all transaction chains because shard {} is no longer the leader",
889 persistenceId(), getId());
893 store.purgeLeaderState();
896 if (hasLeader && !isIsolatedLeader()) {
897 messageRetrySupport.retryMessages();
902 protected void onLeaderChanged(final String oldLeader, final String newLeader) {
903 shardMBean.incrementLeadershipChangeCount();
907 if (!knownFrontends.isEmpty()) {
908 LOG.debug("{}: removing frontend state for {}", persistenceId(), knownFrontends.keySet());
909 knownFrontends = ImmutableMap.of();
912 requestMessageAssembler.close();
915 // No leader anywhere, nothing else to do
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();
925 if (!messagesToForward.isEmpty()) {
926 LOG.debug("{}: Forwarding {} pending transaction messages to leader {}", persistenceId(),
927 messagesToForward.size(), leader);
929 for (Object message : messagesToForward) {
930 leader.tell(message, self());
934 commitCoordinator.abortPendingTransactions("The transacton was aborted due to inflight leadership "
935 + "change and the leader address isn't available.", this);
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());
943 if (!isIsolatedLeader()) {
944 messageRetrySupport.retryMessages();
949 * Clears all pending transactions and converts them to messages to be forwarded to a new leader.
951 * @return the converted messages
953 public Collection<?> convertPendingTransactionsToMessages() {
954 return commitCoordinator.convertPendingTransactionsToMessages(
955 datastoreContext.getShardBatchedModificationCount());
959 protected void pauseLeader(final Runnable operation) {
960 LOG.debug("{}: In pauseLeader, operation: {}", persistenceId(), operation);
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();
967 store.setRunOnPendingTransactionsComplete(operation);
971 protected void unpauseLeader() {
972 LOG.debug("{}: In unpauseLeader", persistenceId());
975 store.setRunOnPendingTransactionsComplete(null);
977 // Restore tell-based protocol state as if we were becoming the leader
978 knownFrontends = Verify.verifyNotNull(frontendMetadata.toLeaderState(this));
982 protected OnDemandRaftState.AbstractBuilder<?, ?> newOnDemandRaftStateBuilder() {
983 return OnDemandShardState.newBuilder().treeChangeListenerActors(treeChangeSupport.getListenerActors())
984 .dataChangeListenerActors(changeSupport.getListenerActors())
985 .commitCohortActors(store.getCohortActors());
989 public String persistenceId() {
994 ShardCommitCoordinator getCommitCoordinator() {
995 return commitCoordinator;
998 public DatastoreContext getDatastoreContext() {
999 return datastoreContext;
1003 public ShardDataTree getDataStore() {
1008 ShardStats getShardMBean() {
1012 public static Builder builder() {
1013 return new Builder();
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;
1026 protected AbstractBuilder(final Class<S> shardClass) {
1027 this.shardClass = shardClass;
1030 protected void checkSealed() {
1031 Preconditions.checkState(!sealed, "Builder isalready sealed - further modifications are not allowed");
1034 @SuppressWarnings("unchecked")
1039 public T id(final ShardIdentifier newId) {
1045 public T peerAddresses(final Map<String, String> newPeerAddresses) {
1047 this.peerAddresses = newPeerAddresses;
1051 public T datastoreContext(final DatastoreContext newDatastoreContext) {
1053 this.datastoreContext = newDatastoreContext;
1057 public T schemaContextProvider(final SchemaContextProvider schemaContextProvider) {
1059 this.schemaContextProvider = Preconditions.checkNotNull(schemaContextProvider);
1063 public T restoreFromSnapshot(final DatastoreSnapshot.ShardSnapshot newRestoreFromSnapshot) {
1065 this.restoreFromSnapshot = newRestoreFromSnapshot;
1069 public T dataTree(final TipProducingDataTree newDataTree) {
1071 this.dataTree = newDataTree;
1075 public ShardIdentifier getId() {
1079 public Map<String, String> getPeerAddresses() {
1080 return peerAddresses;
1083 public DatastoreContext getDatastoreContext() {
1084 return datastoreContext;
1087 public SchemaContext getSchemaContext() {
1088 return Verify.verifyNotNull(schemaContextProvider.getSchemaContext());
1091 public DatastoreSnapshot.ShardSnapshot getRestoreFromSnapshot() {
1092 return restoreFromSnapshot;
1095 public TipProducingDataTree getDataTree() {
1099 public TreeType getTreeType() {
1100 switch (datastoreContext.getLogicalStoreType()) {
1102 return TreeType.CONFIGURATION;
1104 return TreeType.OPERATIONAL;
1106 throw new IllegalStateException("Unhandled logical store type "
1107 + datastoreContext.getLogicalStoreType());
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");
1118 public Props props() {
1121 return Props.create(shardClass, this);
1125 public static class Builder extends AbstractBuilder<Builder, Shard> {
1132 return Ticker.systemTicker();
1135 void scheduleNextPendingTransaction() {
1136 self().tell(RESUME_NEXT_PENDING_TRANSACTION, ActorRef.noSender());