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
8 package org.opendaylight.controller.cluster.datastore;
10 import static com.google.common.base.Verify.verify;
12 import akka.actor.ActorRef;
13 import akka.actor.ActorSelection;
14 import akka.actor.Cancellable;
15 import akka.actor.ExtendedActorSystem;
16 import akka.actor.Props;
17 import akka.actor.Status;
18 import akka.actor.Status.Failure;
19 import akka.serialization.JavaSerializer;
20 import akka.serialization.Serialization;
21 import com.google.common.annotations.VisibleForTesting;
22 import com.google.common.base.Optional;
23 import com.google.common.base.Preconditions;
24 import com.google.common.base.Ticker;
25 import com.google.common.base.Verify;
26 import com.google.common.collect.ImmutableList;
27 import com.google.common.collect.ImmutableMap;
28 import com.google.common.collect.Range;
29 import java.io.IOException;
30 import java.util.Arrays;
31 import java.util.Collection;
32 import java.util.Collections;
33 import java.util.HashMap;
35 import java.util.OptionalLong;
36 import java.util.concurrent.TimeUnit;
37 import org.eclipse.jdt.annotation.NonNull;
38 import org.eclipse.jdt.annotation.Nullable;
39 import org.opendaylight.controller.cluster.access.ABIVersion;
40 import org.opendaylight.controller.cluster.access.commands.ConnectClientRequest;
41 import org.opendaylight.controller.cluster.access.commands.ConnectClientSuccess;
42 import org.opendaylight.controller.cluster.access.commands.LocalHistoryRequest;
43 import org.opendaylight.controller.cluster.access.commands.NotLeaderException;
44 import org.opendaylight.controller.cluster.access.commands.OutOfSequenceEnvelopeException;
45 import org.opendaylight.controller.cluster.access.commands.TransactionRequest;
46 import org.opendaylight.controller.cluster.access.concepts.ClientIdentifier;
47 import org.opendaylight.controller.cluster.access.concepts.FrontendIdentifier;
48 import org.opendaylight.controller.cluster.access.concepts.LocalHistoryIdentifier;
49 import org.opendaylight.controller.cluster.access.concepts.Request;
50 import org.opendaylight.controller.cluster.access.concepts.RequestEnvelope;
51 import org.opendaylight.controller.cluster.access.concepts.RequestException;
52 import org.opendaylight.controller.cluster.access.concepts.RequestSuccess;
53 import org.opendaylight.controller.cluster.access.concepts.RetiredGenerationException;
54 import org.opendaylight.controller.cluster.access.concepts.RuntimeRequestException;
55 import org.opendaylight.controller.cluster.access.concepts.SliceableMessage;
56 import org.opendaylight.controller.cluster.access.concepts.TransactionIdentifier;
57 import org.opendaylight.controller.cluster.access.concepts.UnsupportedRequestException;
58 import org.opendaylight.controller.cluster.common.actor.CommonConfig;
59 import org.opendaylight.controller.cluster.common.actor.Dispatchers;
60 import org.opendaylight.controller.cluster.common.actor.Dispatchers.DispatcherType;
61 import org.opendaylight.controller.cluster.common.actor.MessageTracker;
62 import org.opendaylight.controller.cluster.common.actor.MessageTracker.Error;
63 import org.opendaylight.controller.cluster.common.actor.MeteringBehavior;
64 import org.opendaylight.controller.cluster.datastore.exceptions.NoShardLeaderException;
65 import org.opendaylight.controller.cluster.datastore.identifiers.ShardIdentifier;
66 import org.opendaylight.controller.cluster.datastore.jmx.mbeans.shard.ShardDataTreeListenerInfoMXBeanImpl;
67 import org.opendaylight.controller.cluster.datastore.jmx.mbeans.shard.ShardMBeanFactory;
68 import org.opendaylight.controller.cluster.datastore.jmx.mbeans.shard.ShardStats;
69 import org.opendaylight.controller.cluster.datastore.messages.AbortTransaction;
70 import org.opendaylight.controller.cluster.datastore.messages.ActorInitialized;
71 import org.opendaylight.controller.cluster.datastore.messages.BatchedModifications;
72 import org.opendaylight.controller.cluster.datastore.messages.CanCommitTransaction;
73 import org.opendaylight.controller.cluster.datastore.messages.CloseTransactionChain;
74 import org.opendaylight.controller.cluster.datastore.messages.CommitTransaction;
75 import org.opendaylight.controller.cluster.datastore.messages.CreateTransaction;
76 import org.opendaylight.controller.cluster.datastore.messages.CreateTransactionReply;
77 import org.opendaylight.controller.cluster.datastore.messages.ForwardedReadyTransaction;
78 import org.opendaylight.controller.cluster.datastore.messages.GetShardDataTree;
79 import org.opendaylight.controller.cluster.datastore.messages.MakeLeaderLocal;
80 import org.opendaylight.controller.cluster.datastore.messages.OnDemandShardState;
81 import org.opendaylight.controller.cluster.datastore.messages.PeerAddressResolved;
82 import org.opendaylight.controller.cluster.datastore.messages.ReadyLocalTransaction;
83 import org.opendaylight.controller.cluster.datastore.messages.RegisterDataTreeChangeListener;
84 import org.opendaylight.controller.cluster.datastore.messages.ShardLeaderStateChanged;
85 import org.opendaylight.controller.cluster.datastore.messages.UpdateSchemaContext;
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.datastore.persisted.DisableTrackingPayload;
89 import org.opendaylight.controller.cluster.messaging.MessageAssembler;
90 import org.opendaylight.controller.cluster.messaging.MessageSlicer;
91 import org.opendaylight.controller.cluster.messaging.SliceOptions;
92 import org.opendaylight.controller.cluster.notifications.LeaderStateChanged;
93 import org.opendaylight.controller.cluster.notifications.RegisterRoleChangeListener;
94 import org.opendaylight.controller.cluster.notifications.RoleChangeNotifier;
95 import org.opendaylight.controller.cluster.raft.LeadershipTransferFailedException;
96 import org.opendaylight.controller.cluster.raft.RaftActor;
97 import org.opendaylight.controller.cluster.raft.RaftActorRecoveryCohort;
98 import org.opendaylight.controller.cluster.raft.RaftActorSnapshotCohort;
99 import org.opendaylight.controller.cluster.raft.RaftState;
100 import org.opendaylight.controller.cluster.raft.base.messages.FollowerInitialSyncUpStatus;
101 import org.opendaylight.controller.cluster.raft.client.messages.OnDemandRaftState;
102 import org.opendaylight.controller.cluster.raft.messages.AppendEntriesReply;
103 import org.opendaylight.controller.cluster.raft.messages.RequestLeadership;
104 import org.opendaylight.controller.cluster.raft.messages.ServerRemoved;
105 import org.opendaylight.controller.cluster.raft.protobuff.client.messages.Payload;
106 import org.opendaylight.yangtools.concepts.Identifier;
107 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTree;
108 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataValidationFailedException;
109 import org.opendaylight.yangtools.yang.data.api.schema.tree.TreeType;
110 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
111 import org.opendaylight.yangtools.yang.model.api.SchemaContextProvider;
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 String shardName;
167 private final ShardStats shardMBean;
169 private final ShardDataTreeListenerInfoMXBeanImpl listenerInfoMXBean;
171 private DatastoreContext datastoreContext;
173 private final ShardCommitCoordinator commitCoordinator;
175 private long transactionCommitTimeout;
177 private Cancellable txCommitTimeoutCheckSchedule;
179 private final Optional<ActorRef> roleChangeNotifier;
181 private final MessageTracker appendEntriesReplyTracker;
183 private final ShardTransactionActorFactory transactionActorFactory;
185 private final ShardSnapshotCohort snapshotCohort;
187 private final DataTreeChangeListenerSupport treeChangeSupport = new DataTreeChangeListenerSupport(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.shardName = builder.getId().getShardName();
208 this.datastoreContext = builder.getDatastoreContext();
209 this.restoreFromSnapshot = builder.getRestoreFromSnapshot();
210 this.frontendMetadata = new FrontendMetadata(name);
212 setPersistence(datastoreContext.isPersistent());
214 LOG.info("Shard created : {}, persistent : {}", name, datastoreContext.isPersistent());
216 ShardDataTreeChangeListenerPublisherActorProxy treeChangeListenerPublisher =
217 new ShardDataTreeChangeListenerPublisherActorProxy(getContext(), name + "-DTCL-publisher", name);
218 if (builder.getDataTree() != null) {
219 store = new ShardDataTree(this, builder.getSchemaContext(), builder.getDataTree(),
220 treeChangeListenerPublisher, name, frontendMetadata);
222 store = new ShardDataTree(this, builder.getSchemaContext(), builder.getTreeType(),
223 builder.getDatastoreContext().getStoreRoot(), treeChangeListenerPublisher, name, frontendMetadata);
226 shardMBean = ShardMBeanFactory.getShardStatsMBean(name, datastoreContext.getDataStoreMXBeanType(), this);
228 if (isMetricsCaptureEnabled()) {
229 getContext().become(new MeteringBehavior(this));
232 commitCoordinator = new ShardCommitCoordinator(store, LOG, this.name);
234 setTransactionCommitTimeout();
236 // create a notifier actor for each cluster member
237 roleChangeNotifier = createRoleChangeNotifier(name);
239 appendEntriesReplyTracker = new MessageTracker(AppendEntriesReply.class,
240 getRaftActorContext().getConfigParams().getIsolatedCheckIntervalInMillis());
242 dispatchers = new Dispatchers(context().system().dispatchers());
243 transactionActorFactory = new ShardTransactionActorFactory(store, datastoreContext,
244 dispatchers.getDispatcherPath(Dispatchers.DispatcherType.Transaction),
245 self(), getContext(), shardMBean, builder.getId().getShardName());
247 snapshotCohort = ShardSnapshotCohort.create(getContext(), builder.getId().getMemberName(), store, LOG,
250 messageRetrySupport = new ShardTransactionMessageRetrySupport(this);
252 responseMessageSlicer = MessageSlicer.builder().logContext(this.name)
253 .messageSliceSize(datastoreContext.getMaximumMessageSliceSize())
254 .fileBackedStreamFactory(getRaftActorContext().getFileBackedOutputStreamFactory())
255 .expireStateAfterInactivity(2, TimeUnit.MINUTES).build();
257 requestMessageAssembler = MessageAssembler.builder().logContext(this.name)
258 .fileBackedStreamFactory(getRaftActorContext().getFileBackedOutputStreamFactory())
259 .assembledMessageCallback((message, sender) -> self().tell(message, sender))
260 .expireStateAfterInactivity(datastoreContext.getRequestTimeout(), TimeUnit.NANOSECONDS).build();
262 listenerInfoMXBean = new ShardDataTreeListenerInfoMXBeanImpl(name, datastoreContext.getDataStoreMXBeanType(),
264 listenerInfoMXBean.register();
267 private void setTransactionCommitTimeout() {
268 transactionCommitTimeout = TimeUnit.MILLISECONDS.convert(
269 datastoreContext.getShardTransactionCommitTimeoutInSeconds(), TimeUnit.SECONDS) / 2;
272 private Optional<ActorRef> createRoleChangeNotifier(final String shardId) {
273 ActorRef shardRoleChangeNotifier = this.getContext().actorOf(
274 RoleChangeNotifier.getProps(shardId), shardId + "-notifier");
275 return Optional.of(shardRoleChangeNotifier);
279 public void postStop() {
280 LOG.info("Stopping Shard {}", persistenceId());
284 messageRetrySupport.close();
286 if (txCommitTimeoutCheckSchedule != null) {
287 txCommitTimeoutCheckSchedule.cancel();
290 commitCoordinator.abortPendingTransactions("Transaction aborted due to shutdown.", this);
292 shardMBean.unregisterMBean();
293 listenerInfoMXBean.unregister();
297 protected void handleRecover(final Object message) {
298 LOG.debug("{}: onReceiveRecover: Received message {} from {}", persistenceId(), message.getClass(),
301 super.handleRecover(message);
302 if (LOG.isTraceEnabled()) {
303 appendEntriesReplyTracker.begin();
308 protected void handleNonRaftCommand(final Object message) {
309 try (MessageTracker.Context context = appendEntriesReplyTracker.received(message)) {
310 final java.util.Optional<Error> maybeError = context.error();
311 if (maybeError.isPresent()) {
312 LOG.trace("{} : AppendEntriesReply failed to arrive at the expected interval {}", persistenceId(),
316 store.resetTransactionBatch();
318 if (message instanceof RequestEnvelope) {
319 handleRequestEnvelope((RequestEnvelope)message);
320 } else if (MessageAssembler.isHandledMessage(message)) {
321 handleRequestAssemblerMessage(message);
322 } else if (message instanceof ConnectClientRequest) {
323 handleConnectClient((ConnectClientRequest)message);
324 } else if (CreateTransaction.isSerializedType(message)) {
325 handleCreateTransaction(message);
326 } else if (message instanceof BatchedModifications) {
327 handleBatchedModifications((BatchedModifications)message);
328 } else if (message instanceof ForwardedReadyTransaction) {
329 handleForwardedReadyTransaction((ForwardedReadyTransaction) message);
330 } else if (message instanceof ReadyLocalTransaction) {
331 handleReadyLocalTransaction((ReadyLocalTransaction)message);
332 } else if (CanCommitTransaction.isSerializedType(message)) {
333 handleCanCommitTransaction(CanCommitTransaction.fromSerializable(message));
334 } else if (CommitTransaction.isSerializedType(message)) {
335 handleCommitTransaction(CommitTransaction.fromSerializable(message));
336 } else if (AbortTransaction.isSerializedType(message)) {
337 handleAbortTransaction(AbortTransaction.fromSerializable(message));
338 } else if (CloseTransactionChain.isSerializedType(message)) {
339 closeTransactionChain(CloseTransactionChain.fromSerializable(message));
340 } else if (message instanceof RegisterDataTreeChangeListener) {
341 treeChangeSupport.onMessage((RegisterDataTreeChangeListener) message, isLeader(), hasLeader());
342 } else if (message instanceof UpdateSchemaContext) {
343 updateSchemaContext((UpdateSchemaContext) message);
344 } else if (message instanceof PeerAddressResolved) {
345 PeerAddressResolved resolved = (PeerAddressResolved) message;
346 setPeerAddress(resolved.getPeerId(), resolved.getPeerAddress());
347 } else if (TX_COMMIT_TIMEOUT_CHECK_MESSAGE.equals(message)) {
348 commitTimeoutCheck();
349 } else if (message instanceof DatastoreContext) {
350 onDatastoreContext((DatastoreContext)message);
351 } else if (message instanceof RegisterRoleChangeListener) {
352 roleChangeNotifier.get().forward(message, context());
353 } else if (message instanceof FollowerInitialSyncUpStatus) {
354 shardMBean.setFollowerInitialSyncStatus(((FollowerInitialSyncUpStatus) message).isInitialSyncDone());
355 context().parent().tell(message, self());
356 } else if (GET_SHARD_MBEAN_MESSAGE.equals(message)) {
357 sender().tell(getShardMBean(), self());
358 } else if (message instanceof GetShardDataTree) {
359 sender().tell(store.getDataTree(), self());
360 } else if (message instanceof ServerRemoved) {
361 context().parent().forward(message, context());
362 } else if (ShardTransactionMessageRetrySupport.TIMER_MESSAGE_CLASS.isInstance(message)) {
363 messageRetrySupport.onTimerMessage(message);
364 } else if (message instanceof DataTreeCohortActorRegistry.CohortRegistryCommand) {
365 store.processCohortRegistryCommand(getSender(),
366 (DataTreeCohortActorRegistry.CohortRegistryCommand) message);
367 } else if (message instanceof MakeLeaderLocal) {
369 } else if (RESUME_NEXT_PENDING_TRANSACTION.equals(message)) {
370 store.resumeNextPendingTransaction();
371 } else if (!responseMessageSlicer.handleMessage(message)) {
372 super.handleNonRaftCommand(message);
377 private void handleRequestAssemblerMessage(final Object message) {
378 dispatchers.getDispatcher(DispatcherType.Serialization).execute(() -> {
379 JavaSerializer.currentSystem().value_$eq((ExtendedActorSystem) context().system());
380 requestMessageAssembler.handleMessage(message, self());
384 @SuppressWarnings("checkstyle:IllegalCatch")
385 private void handleRequestEnvelope(final RequestEnvelope envelope) {
386 final long now = ticker().read();
388 final RequestSuccess<?, ?> success = handleRequest(envelope, now);
389 if (success != null) {
390 final long executionTimeNanos = ticker().read() - now;
391 if (success instanceof SliceableMessage) {
392 dispatchers.getDispatcher(DispatcherType.Serialization).execute(() ->
393 responseMessageSlicer.slice(SliceOptions.builder().identifier(success.getTarget())
394 .message(envelope.newSuccessEnvelope(success, executionTimeNanos))
395 .sendTo(envelope.getMessage().getReplyTo()).replyTo(self())
396 .onFailureCallback(t -> LOG.warn("Error slicing response {}", success, t)).build()));
398 envelope.sendSuccess(success, executionTimeNanos);
401 } catch (RequestException e) {
402 LOG.debug("{}: request {} failed", persistenceId(), envelope, e);
403 envelope.sendFailure(e, ticker().read() - now);
404 } catch (Exception e) {
405 LOG.debug("{}: request {} caused failure", persistenceId(), envelope, e);
406 envelope.sendFailure(new RuntimeRequestException("Request failed to process", e),
407 ticker().read() - now);
411 private void commitTimeoutCheck() {
412 store.checkForExpiredTransactions(transactionCommitTimeout, this::updateAccess);
413 commitCoordinator.checkForExpiredTransactions(transactionCommitTimeout, this);
414 requestMessageAssembler.checkExpiredAssembledMessageState();
417 private OptionalLong updateAccess(final SimpleShardDataTreeCohort cohort) {
418 final FrontendIdentifier frontend = cohort.getIdentifier().getHistoryId().getClientId().getFrontendId();
419 final LeaderFrontendState state = knownFrontends.get(frontend);
421 // Not tell-based protocol, do nothing
422 return OptionalLong.empty();
425 if (isIsolatedLeader()) {
426 // We are isolated and no new request can come through until we emerge from it. We are still updating
427 // liveness of frontend when we see it attempting to communicate. Use the last access timer.
428 return OptionalLong.of(state.getLastSeenTicks());
431 // If this frontend has freshly connected, give it some time to catch up before killing its transactions.
432 return OptionalLong.of(state.getLastConnectTicks());
435 private void disableTracking(final DisableTrackingPayload payload) {
436 final ClientIdentifier clientId = payload.getIdentifier();
437 LOG.debug("{}: disabling tracking of {}", persistenceId(), clientId);
438 frontendMetadata.disableTracking(clientId);
441 final FrontendIdentifier frontendId = clientId.getFrontendId();
442 final LeaderFrontendState frontend = knownFrontends.get(frontendId);
443 if (frontend != null) {
444 if (clientId.equals(frontend.getIdentifier())) {
445 if (!(frontend instanceof LeaderFrontendState.Disabled)) {
446 verify(knownFrontends.replace(frontendId, frontend,
447 new LeaderFrontendState.Disabled(persistenceId(), clientId, store)));
448 LOG.debug("{}: leader state for {} disabled", persistenceId(), clientId);
450 LOG.debug("{}: leader state {} is already disabled", persistenceId(), frontend);
453 LOG.debug("{}: leader state {} does not match {}", persistenceId(), frontend, clientId);
456 LOG.debug("{}: leader state for {} not found", persistenceId(), clientId);
457 knownFrontends.put(frontendId, new LeaderFrontendState.Disabled(persistenceId(), clientId,
463 private void onMakeLeaderLocal() {
464 LOG.debug("{}: onMakeLeaderLocal received", persistenceId());
466 getSender().tell(new Status.Success(null), getSelf());
470 final ActorSelection leader = getLeader();
472 if (leader == null) {
473 // Leader is not present. The cluster is most likely trying to
474 // elect a leader and we should let that run its normal course
476 // TODO we can wait for the election to complete and retry the
477 // request. We can also let the caller retry by sending a flag
478 // in the response indicating the request is "reTryable".
479 getSender().tell(new Failure(
480 new LeadershipTransferFailedException("We cannot initiate leadership transfer to local node. "
481 + "Currently there is no leader for " + persistenceId())),
486 leader.tell(new RequestLeadership(getId(), getSender()), getSelf());
489 // Acquire our frontend tracking handle and verify generation matches
490 private @Nullable LeaderFrontendState findFrontend(final ClientIdentifier clientId) throws RequestException {
491 final LeaderFrontendState existing = knownFrontends.get(clientId.getFrontendId());
492 if (existing != null) {
493 final int cmp = Long.compareUnsigned(existing.getIdentifier().getGeneration(), clientId.getGeneration());
499 LOG.debug("{}: rejecting request from outdated client {}", persistenceId(), clientId);
500 throw new RetiredGenerationException(clientId.getGeneration(),
501 existing.getIdentifier().getGeneration());
504 LOG.info("{}: retiring state {}, outdated by request from client {}", persistenceId(), existing, clientId);
506 knownFrontends.remove(clientId.getFrontendId());
508 LOG.debug("{}: client {} is not yet known", persistenceId(), clientId);
514 private LeaderFrontendState getFrontend(final ClientIdentifier clientId) throws RequestException {
515 final LeaderFrontendState ret = findFrontend(clientId);
520 // TODO: a dedicated exception would be better, but this is technically true, too
521 throw new OutOfSequenceEnvelopeException(0);
524 private static @NonNull ABIVersion selectVersion(final ConnectClientRequest message) {
525 final Range<ABIVersion> clientRange = Range.closed(message.getMinVersion(), message.getMaxVersion());
526 for (ABIVersion v : SUPPORTED_ABIVERSIONS) {
527 if (clientRange.contains(v)) {
532 throw new IllegalArgumentException(String.format(
533 "No common version between backend versions %s and client versions %s", SUPPORTED_ABIVERSIONS,
537 @SuppressWarnings("checkstyle:IllegalCatch")
538 private void handleConnectClient(final ConnectClientRequest message) {
540 final ClientIdentifier clientId = message.getTarget();
541 final LeaderFrontendState existing = findFrontend(clientId);
542 if (existing != null) {
546 if (!isLeader() || !isLeaderActive()) {
547 LOG.info("{}: not currently leader, rejecting request {}. isLeader: {}, isLeaderActive: {},"
548 + "isLeadershipTransferInProgress: {}.",
549 persistenceId(), message, isLeader(), isLeaderActive(), isLeadershipTransferInProgress());
550 throw new NotLeaderException(getSelf());
553 final ABIVersion selectedVersion = selectVersion(message);
554 final LeaderFrontendState frontend;
555 if (existing == null) {
556 frontend = new LeaderFrontendState.Enabled(persistenceId(), clientId, store);
557 knownFrontends.put(clientId.getFrontendId(), frontend);
558 LOG.debug("{}: created state {} for client {}", persistenceId(), frontend, clientId);
563 frontend.reconnect();
564 message.getReplyTo().tell(new ConnectClientSuccess(message.getTarget(), message.getSequence(), getSelf(),
565 ImmutableList.of(), store.getDataTree(), CLIENT_MAX_MESSAGES).toVersion(selectedVersion),
566 ActorRef.noSender());
567 } catch (RequestException | RuntimeException e) {
568 message.getReplyTo().tell(new Failure(e), ActorRef.noSender());
572 private @Nullable RequestSuccess<?, ?> handleRequest(final RequestEnvelope envelope, final long now)
573 throws RequestException {
574 // We are not the leader, hence we want to fail-fast.
575 if (!isLeader() || paused || !isLeaderActive()) {
576 LOG.debug("{}: not currently active leader, rejecting request {}. isLeader: {}, isLeaderActive: {},"
577 + "isLeadershipTransferInProgress: {}, paused: {}",
578 persistenceId(), envelope, isLeader(), isLeaderActive(), isLeadershipTransferInProgress(), paused);
579 throw new NotLeaderException(getSelf());
582 final Request<?, ?> request = envelope.getMessage();
583 if (request instanceof TransactionRequest) {
584 final TransactionRequest<?> txReq = (TransactionRequest<?>)request;
585 final ClientIdentifier clientId = txReq.getTarget().getHistoryId().getClientId();
586 return getFrontend(clientId).handleTransactionRequest(txReq, envelope, now);
587 } else if (request instanceof LocalHistoryRequest) {
588 final LocalHistoryRequest<?> lhReq = (LocalHistoryRequest<?>)request;
589 final ClientIdentifier clientId = lhReq.getTarget().getClientId();
590 return getFrontend(clientId).handleLocalHistoryRequest(lhReq, envelope, now);
592 LOG.warn("{}: rejecting unsupported request {}", persistenceId(), request);
593 throw new UnsupportedRequestException(request);
597 private boolean hasLeader() {
598 return getLeaderId() != null;
601 public int getPendingTxCommitQueueSize() {
602 return store.getQueueSize();
605 public int getCohortCacheSize() {
606 return commitCoordinator.getCohortCacheSize();
610 protected Optional<ActorRef> getRoleChangeNotifier() {
611 return roleChangeNotifier;
614 String getShardName() {
619 protected LeaderStateChanged newLeaderStateChanged(final String memberId, final String leaderId,
620 final short leaderPayloadVersion) {
621 return isLeader() ? new ShardLeaderStateChanged(memberId, leaderId, store.getDataTree(), leaderPayloadVersion)
622 : new ShardLeaderStateChanged(memberId, leaderId, leaderPayloadVersion);
625 protected void onDatastoreContext(final DatastoreContext context) {
626 datastoreContext = context;
628 setTransactionCommitTimeout();
630 setPersistence(datastoreContext.isPersistent());
632 updateConfigParams(datastoreContext.getShardRaftConfig());
635 // applyState() will be invoked once consensus is reached on the payload
636 void persistPayload(final Identifier id, final Payload payload, final boolean batchHint) {
637 boolean canSkipPayload = !hasFollowers() && !persistence().isRecoveryApplicable();
638 if (canSkipPayload) {
639 applyState(self(), id, payload);
641 // We are faking the sender
642 persistData(self(), id, payload, batchHint);
646 private void handleCommitTransaction(final CommitTransaction commit) {
647 final TransactionIdentifier txId = commit.getTransactionId();
649 askProtocolEncountered(txId);
650 commitCoordinator.handleCommit(txId, getSender(), this);
652 ActorSelection leader = getLeader();
653 if (leader == null) {
654 messageRetrySupport.addMessageToRetry(commit, getSender(), "Could not commit transaction " + txId);
656 LOG.debug("{}: Forwarding CommitTransaction to leader {}", persistenceId(), leader);
657 leader.forward(commit, getContext());
662 private void handleCanCommitTransaction(final CanCommitTransaction canCommit) {
663 final TransactionIdentifier txId = canCommit.getTransactionId();
664 LOG.debug("{}: Can committing transaction {}", persistenceId(), txId);
667 askProtocolEncountered(txId);
668 commitCoordinator.handleCanCommit(txId, getSender(), this);
670 ActorSelection leader = getLeader();
671 if (leader == null) {
672 messageRetrySupport.addMessageToRetry(canCommit, getSender(),
673 "Could not canCommit transaction " + txId);
675 LOG.debug("{}: Forwarding CanCommitTransaction to leader {}", persistenceId(), leader);
676 leader.forward(canCommit, getContext());
681 @SuppressWarnings("checkstyle:IllegalCatch")
682 protected void handleBatchedModificationsLocal(final BatchedModifications batched, final ActorRef sender) {
683 askProtocolEncountered(batched.getTransactionId());
686 commitCoordinator.handleBatchedModifications(batched, sender, this);
687 } catch (Exception e) {
688 LOG.error("{}: Error handling BatchedModifications for Tx {}", persistenceId(),
689 batched.getTransactionId(), e);
690 sender.tell(new Failure(e), getSelf());
694 private void handleBatchedModifications(final BatchedModifications batched) {
695 // This message is sent to prepare the modifications transaction directly on the Shard as an
696 // optimization to avoid the extra overhead of a separate ShardTransaction actor. On the last
697 // BatchedModifications message, the caller sets the ready flag in the message indicating
698 // modifications are complete. The reply contains the cohort actor path (this actor) for the caller
699 // to initiate the 3-phase commit. This also avoids the overhead of sending an additional
700 // ReadyTransaction message.
702 // If we're not the leader then forward to the leader. This is a safety measure - we shouldn't
703 // normally get here if we're not the leader as the front-end (TransactionProxy) should determine
704 // the primary/leader shard. However with timing and caching on the front-end, there's a small
705 // window where it could have a stale leader during leadership transitions.
707 boolean isLeaderActive = isLeaderActive();
708 if (isLeader() && isLeaderActive) {
709 handleBatchedModificationsLocal(batched, getSender());
711 ActorSelection leader = getLeader();
712 if (!isLeaderActive || leader == null) {
713 messageRetrySupport.addMessageToRetry(batched, getSender(),
714 "Could not process BatchedModifications " + batched.getTransactionId());
716 // If this is not the first batch and leadership changed in between batched messages,
717 // we need to reconstruct previous BatchedModifications from the transaction
718 // DataTreeModification, honoring the max batched modification count, and forward all the
719 // previous BatchedModifications to the new leader.
720 Collection<BatchedModifications> newModifications = commitCoordinator
721 .createForwardedBatchedModifications(batched,
722 datastoreContext.getShardBatchedModificationCount());
724 LOG.debug("{}: Forwarding {} BatchedModifications to leader {}", persistenceId(),
725 newModifications.size(), leader);
727 for (BatchedModifications bm : newModifications) {
728 leader.forward(bm, getContext());
734 private boolean failIfIsolatedLeader(final ActorRef sender) {
735 if (isIsolatedLeader()) {
736 sender.tell(new Failure(new NoShardLeaderException(String.format(
737 "Shard %s was the leader but has lost contact with all of its followers. Either all"
738 + " other follower nodes are down or this node is isolated by a network partition.",
739 persistenceId()))), getSelf());
746 protected boolean isIsolatedLeader() {
747 return getRaftState() == RaftState.IsolatedLeader;
750 @SuppressWarnings("checkstyle:IllegalCatch")
751 private void handleReadyLocalTransaction(final ReadyLocalTransaction message) {
752 LOG.debug("{}: handleReadyLocalTransaction for {}", persistenceId(), message.getTransactionId());
754 boolean isLeaderActive = isLeaderActive();
755 if (isLeader() && isLeaderActive) {
757 commitCoordinator.handleReadyLocalTransaction(message, getSender(), this);
758 } catch (Exception e) {
759 LOG.error("{}: Error handling ReadyLocalTransaction for Tx {}", persistenceId(),
760 message.getTransactionId(), e);
761 getSender().tell(new Failure(e), getSelf());
764 ActorSelection leader = getLeader();
765 if (!isLeaderActive || leader == null) {
766 messageRetrySupport.addMessageToRetry(message, getSender(),
767 "Could not process ready local transaction " + message.getTransactionId());
769 LOG.debug("{}: Forwarding ReadyLocalTransaction to leader {}", persistenceId(), leader);
770 message.setRemoteVersion(getCurrentBehavior().getLeaderPayloadVersion());
771 leader.forward(message, getContext());
776 private void handleForwardedReadyTransaction(final ForwardedReadyTransaction forwardedReady) {
777 LOG.debug("{}: handleForwardedReadyTransaction for {}", persistenceId(), forwardedReady.getTransactionId());
779 boolean isLeaderActive = isLeaderActive();
780 if (isLeader() && isLeaderActive) {
781 askProtocolEncountered(forwardedReady.getTransactionId());
782 commitCoordinator.handleForwardedReadyTransaction(forwardedReady, getSender(), this);
784 ActorSelection leader = getLeader();
785 if (!isLeaderActive || leader == null) {
786 messageRetrySupport.addMessageToRetry(forwardedReady, getSender(),
787 "Could not process forwarded ready transaction " + forwardedReady.getTransactionId());
789 LOG.debug("{}: Forwarding ForwardedReadyTransaction to leader {}", persistenceId(), leader);
791 ReadyLocalTransaction readyLocal = new ReadyLocalTransaction(forwardedReady.getTransactionId(),
792 forwardedReady.getTransaction().getSnapshot(), forwardedReady.isDoImmediateCommit(),
793 forwardedReady.getParticipatingShardNames());
794 readyLocal.setRemoteVersion(getCurrentBehavior().getLeaderPayloadVersion());
795 leader.forward(readyLocal, getContext());
800 private void handleAbortTransaction(final AbortTransaction abort) {
801 final TransactionIdentifier transactionId = abort.getTransactionId();
802 askProtocolEncountered(transactionId);
803 doAbortTransaction(transactionId, getSender());
806 void doAbortTransaction(final Identifier transactionID, final ActorRef sender) {
807 commitCoordinator.handleAbort(transactionID, sender, this);
810 private void handleCreateTransaction(final Object message) {
812 createTransaction(CreateTransaction.fromSerializable(message));
813 } else if (getLeader() != null) {
814 getLeader().forward(message, getContext());
816 getSender().tell(new Failure(new NoShardLeaderException(
817 "Could not create a shard transaction", persistenceId())), getSelf());
821 private void closeTransactionChain(final CloseTransactionChain closeTransactionChain) {
823 final LocalHistoryIdentifier id = closeTransactionChain.getIdentifier();
824 askProtocolEncountered(id.getClientId());
825 store.closeTransactionChain(id);
826 } else if (getLeader() != null) {
827 getLeader().forward(closeTransactionChain, getContext());
829 LOG.warn("{}: Could not close transaction {}", persistenceId(), closeTransactionChain.getIdentifier());
833 @SuppressWarnings("checkstyle:IllegalCatch")
834 private void createTransaction(final CreateTransaction createTransaction) {
835 askProtocolEncountered(createTransaction.getTransactionId());
838 if (TransactionType.fromInt(createTransaction.getTransactionType()) != TransactionType.READ_ONLY
839 && failIfIsolatedLeader(getSender())) {
843 ActorRef transactionActor = createTransaction(createTransaction.getTransactionType(),
844 createTransaction.getTransactionId());
846 getSender().tell(new CreateTransactionReply(Serialization.serializedActorPath(transactionActor),
847 createTransaction.getTransactionId(), createTransaction.getVersion()).toSerializable(), getSelf());
848 } catch (Exception e) {
849 getSender().tell(new Failure(e), getSelf());
853 private ActorRef createTransaction(final int transactionType, final TransactionIdentifier transactionId) {
854 LOG.debug("{}: Creating transaction : {} ", persistenceId(), transactionId);
855 return transactionActorFactory.newShardTransaction(TransactionType.fromInt(transactionType),
859 // Called on leader only
860 private void askProtocolEncountered(final TransactionIdentifier transactionId) {
861 askProtocolEncountered(transactionId.getHistoryId().getClientId());
864 // Called on leader only
865 private void askProtocolEncountered(final ClientIdentifier clientId) {
866 final FrontendIdentifier frontend = clientId.getFrontendId();
867 final LeaderFrontendState state = knownFrontends.get(frontend);
868 if (!(state instanceof LeaderFrontendState.Disabled)) {
869 LOG.debug("{}: encountered ask-based client {}, disabling transaction tracking", persistenceId(), clientId);
870 if (knownFrontends.isEmpty()) {
871 knownFrontends = new HashMap<>();
873 knownFrontends.put(frontend, new LeaderFrontendState.Disabled(persistenceId(), clientId, getDataStore()));
875 persistPayload(clientId, DisableTrackingPayload.create(clientId,
876 datastoreContext.getInitialPayloadSerializedBufferCapacity()), false);
880 private void updateSchemaContext(final UpdateSchemaContext message) {
881 updateSchemaContext(message.getSchemaContext());
885 void updateSchemaContext(final SchemaContext schemaContext) {
886 store.updateSchemaContext(schemaContext);
889 private boolean isMetricsCaptureEnabled() {
890 CommonConfig config = new CommonConfig(getContext().system().settings().config());
891 return config.isMetricCaptureEnabled();
896 public RaftActorSnapshotCohort getRaftActorSnapshotCohort() {
897 return snapshotCohort;
901 protected RaftActorRecoveryCohort getRaftActorRecoveryCohort() {
902 if (restoreFromSnapshot == null) {
903 return ShardRecoveryCoordinator.create(store, persistenceId(), LOG);
906 return ShardRecoveryCoordinator.forSnapshot(store, persistenceId(), LOG, restoreFromSnapshot.getSnapshot());
910 protected void onRecoveryComplete() {
911 restoreFromSnapshot = null;
913 //notify shard manager
914 getContext().parent().tell(new ActorInitialized(), getSelf());
916 // Being paranoid here - this method should only be called once but just in case...
917 if (txCommitTimeoutCheckSchedule == null) {
918 // Schedule a message to be periodically sent to check if the current in-progress
919 // transaction should be expired and aborted.
920 FiniteDuration period = FiniteDuration.create(transactionCommitTimeout / 3, TimeUnit.MILLISECONDS);
921 txCommitTimeoutCheckSchedule = getContext().system().scheduler().schedule(
922 period, period, getSelf(),
923 TX_COMMIT_TIMEOUT_CHECK_MESSAGE, getContext().dispatcher(), ActorRef.noSender());
928 protected void applyState(final ActorRef clientActor, final Identifier identifier, final Object data) {
929 if (data instanceof Payload) {
930 if (data instanceof DisableTrackingPayload) {
931 disableTracking((DisableTrackingPayload) data);
936 store.applyReplicatedPayload(identifier, (Payload)data);
937 } catch (DataValidationFailedException | IOException e) {
938 LOG.error("{}: Error applying replica {}", persistenceId(), identifier, e);
941 LOG.error("{}: Unknown state for {} received {}", persistenceId(), identifier, data);
946 protected void onStateChanged() {
947 boolean isLeader = isLeader();
948 boolean hasLeader = hasLeader();
949 treeChangeSupport.onLeadershipChange(isLeader, hasLeader);
951 // If this actor is no longer the leader close all the transaction chains
953 if (LOG.isDebugEnabled()) {
955 "{}: onStateChanged: Closing all transaction chains because shard {} is no longer the leader",
956 persistenceId(), getId());
960 store.purgeLeaderState();
963 if (hasLeader && !isIsolatedLeader()) {
964 messageRetrySupport.retryMessages();
969 protected void onLeaderChanged(final String oldLeader, final String newLeader) {
970 shardMBean.incrementLeadershipChangeCount();
974 if (!knownFrontends.isEmpty()) {
975 LOG.debug("{}: removing frontend state for {}", persistenceId(), knownFrontends.keySet());
976 knownFrontends = ImmutableMap.of();
979 requestMessageAssembler.close();
982 // No leader anywhere, nothing else to do
986 // Another leader was elected. If we were the previous leader and had pending transactions, convert
987 // them to transaction messages and send to the new leader.
988 ActorSelection leader = getLeader();
989 if (leader != null) {
990 Collection<?> messagesToForward = convertPendingTransactionsToMessages();
992 if (!messagesToForward.isEmpty()) {
993 LOG.debug("{}: Forwarding {} pending transaction messages to leader {}", persistenceId(),
994 messagesToForward.size(), leader);
996 for (Object message : messagesToForward) {
997 LOG.debug("{}: Forwarding pending transaction message {}", persistenceId(), message);
999 leader.tell(message, self());
1003 commitCoordinator.abortPendingTransactions("The transacton was aborted due to inflight leadership "
1004 + "change and the leader address isn't available.", this);
1007 // We have become the leader, we need to reconstruct frontend state
1008 knownFrontends = Verify.verifyNotNull(frontendMetadata.toLeaderState(this));
1009 LOG.debug("{}: became leader with frontend state for {}", persistenceId(), knownFrontends.keySet());
1012 if (!isIsolatedLeader()) {
1013 messageRetrySupport.retryMessages();
1018 * Clears all pending transactions and converts them to messages to be forwarded to a new leader.
1020 * @return the converted messages
1022 public Collection<?> convertPendingTransactionsToMessages() {
1023 return commitCoordinator.convertPendingTransactionsToMessages(
1024 datastoreContext.getShardBatchedModificationCount());
1028 protected void pauseLeader(final Runnable operation) {
1029 LOG.debug("{}: In pauseLeader, operation: {}", persistenceId(), operation);
1032 // Tell-based protocol can replay transaction state, so it is safe to blow it up when we are paused.
1033 if (datastoreContext.isUseTellBasedProtocol()) {
1034 knownFrontends.values().forEach(LeaderFrontendState::retire);
1035 knownFrontends = ImmutableMap.of();
1038 store.setRunOnPendingTransactionsComplete(operation);
1042 protected void unpauseLeader() {
1043 LOG.debug("{}: In unpauseLeader", persistenceId());
1046 store.setRunOnPendingTransactionsComplete(null);
1048 // Restore tell-based protocol state as if we were becoming the leader
1049 knownFrontends = Verify.verifyNotNull(frontendMetadata.toLeaderState(this));
1053 protected OnDemandRaftState.AbstractBuilder<?, ?> newOnDemandRaftStateBuilder() {
1054 return OnDemandShardState.newBuilder().treeChangeListenerActors(treeChangeSupport.getListenerActors())
1055 .commitCohortActors(store.getCohortActors());
1059 public String persistenceId() {
1064 ShardCommitCoordinator getCommitCoordinator() {
1065 return commitCoordinator;
1068 public DatastoreContext getDatastoreContext() {
1069 return datastoreContext;
1073 public ShardDataTree getDataStore() {
1078 ShardStats getShardMBean() {
1082 public static Builder builder() {
1083 return new Builder();
1086 public abstract static class AbstractBuilder<T extends AbstractBuilder<T, S>, S extends Shard> {
1087 private final Class<S> shardClass;
1088 private ShardIdentifier id;
1089 private Map<String, String> peerAddresses = Collections.emptyMap();
1090 private DatastoreContext datastoreContext;
1091 private SchemaContextProvider schemaContextProvider;
1092 private DatastoreSnapshot.ShardSnapshot restoreFromSnapshot;
1093 private DataTree dataTree;
1094 private volatile boolean sealed;
1096 protected AbstractBuilder(final Class<S> shardClass) {
1097 this.shardClass = shardClass;
1100 protected void checkSealed() {
1101 Preconditions.checkState(!sealed, "Builder isalready sealed - further modifications are not allowed");
1104 @SuppressWarnings("unchecked")
1109 public T id(final ShardIdentifier newId) {
1115 public T peerAddresses(final Map<String, String> newPeerAddresses) {
1117 this.peerAddresses = newPeerAddresses;
1121 public T datastoreContext(final DatastoreContext newDatastoreContext) {
1123 this.datastoreContext = newDatastoreContext;
1127 public T schemaContextProvider(final SchemaContextProvider newSchemaContextProvider) {
1129 this.schemaContextProvider = Preconditions.checkNotNull(newSchemaContextProvider);
1133 public T restoreFromSnapshot(final DatastoreSnapshot.ShardSnapshot newRestoreFromSnapshot) {
1135 this.restoreFromSnapshot = newRestoreFromSnapshot;
1139 public T dataTree(final DataTree newDataTree) {
1141 this.dataTree = newDataTree;
1145 public ShardIdentifier getId() {
1149 public Map<String, String> getPeerAddresses() {
1150 return peerAddresses;
1153 public DatastoreContext getDatastoreContext() {
1154 return datastoreContext;
1157 public SchemaContext getSchemaContext() {
1158 return Verify.verifyNotNull(schemaContextProvider.getSchemaContext());
1161 public DatastoreSnapshot.ShardSnapshot getRestoreFromSnapshot() {
1162 return restoreFromSnapshot;
1165 public DataTree getDataTree() {
1169 public TreeType getTreeType() {
1170 switch (datastoreContext.getLogicalStoreType()) {
1172 return TreeType.CONFIGURATION;
1174 return TreeType.OPERATIONAL;
1176 throw new IllegalStateException("Unhandled logical store type "
1177 + datastoreContext.getLogicalStoreType());
1181 protected void verify() {
1182 Preconditions.checkNotNull(id, "id should not be null");
1183 Preconditions.checkNotNull(peerAddresses, "peerAddresses should not be null");
1184 Preconditions.checkNotNull(datastoreContext, "dataStoreContext should not be null");
1185 Preconditions.checkNotNull(schemaContextProvider, "schemaContextProvider should not be null");
1188 public Props props() {
1191 return Props.create(shardClass, this);
1195 public static class Builder extends AbstractBuilder<Builder, Shard> {
1202 return Ticker.systemTicker();
1205 void scheduleNextPendingTransaction() {
1206 self().tell(RESUME_NEXT_PENDING_TRANSACTION, ActorRef.noSender());