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.Preconditions.checkState;
11 import static com.google.common.base.Verify.verify;
12 import static com.google.common.base.Verify.verifyNotNull;
13 import static java.util.Objects.requireNonNull;
15 import akka.actor.ActorRef;
16 import akka.actor.ActorSelection;
17 import akka.actor.Cancellable;
18 import akka.actor.ExtendedActorSystem;
19 import akka.actor.Props;
20 import akka.actor.Status;
21 import akka.actor.Status.Failure;
22 import akka.serialization.JavaSerializer;
23 import akka.serialization.Serialization;
24 import com.google.common.annotations.VisibleForTesting;
25 import com.google.common.base.Ticker;
26 import com.google.common.base.Verify;
27 import com.google.common.collect.ImmutableList;
28 import com.google.common.collect.ImmutableMap;
29 import com.google.common.collect.ImmutableSet;
30 import com.google.common.collect.Range;
31 import java.io.IOException;
32 import java.util.Arrays;
33 import java.util.Collection;
34 import java.util.Collections;
35 import java.util.HashMap;
37 import java.util.Optional;
38 import java.util.OptionalLong;
39 import java.util.concurrent.TimeUnit;
40 import org.eclipse.jdt.annotation.NonNull;
41 import org.eclipse.jdt.annotation.Nullable;
42 import org.opendaylight.controller.cluster.access.ABIVersion;
43 import org.opendaylight.controller.cluster.access.commands.ConnectClientRequest;
44 import org.opendaylight.controller.cluster.access.commands.ConnectClientSuccess;
45 import org.opendaylight.controller.cluster.access.commands.LocalHistoryRequest;
46 import org.opendaylight.controller.cluster.access.commands.NotLeaderException;
47 import org.opendaylight.controller.cluster.access.commands.OutOfSequenceEnvelopeException;
48 import org.opendaylight.controller.cluster.access.commands.TransactionRequest;
49 import org.opendaylight.controller.cluster.access.concepts.ClientIdentifier;
50 import org.opendaylight.controller.cluster.access.concepts.FrontendIdentifier;
51 import org.opendaylight.controller.cluster.access.concepts.LocalHistoryIdentifier;
52 import org.opendaylight.controller.cluster.access.concepts.Request;
53 import org.opendaylight.controller.cluster.access.concepts.RequestEnvelope;
54 import org.opendaylight.controller.cluster.access.concepts.RequestException;
55 import org.opendaylight.controller.cluster.access.concepts.RequestSuccess;
56 import org.opendaylight.controller.cluster.access.concepts.RetiredGenerationException;
57 import org.opendaylight.controller.cluster.access.concepts.RuntimeRequestException;
58 import org.opendaylight.controller.cluster.access.concepts.SliceableMessage;
59 import org.opendaylight.controller.cluster.access.concepts.TransactionIdentifier;
60 import org.opendaylight.controller.cluster.access.concepts.UnsupportedRequestException;
61 import org.opendaylight.controller.cluster.common.actor.CommonConfig;
62 import org.opendaylight.controller.cluster.common.actor.Dispatchers;
63 import org.opendaylight.controller.cluster.common.actor.Dispatchers.DispatcherType;
64 import org.opendaylight.controller.cluster.common.actor.MessageTracker;
65 import org.opendaylight.controller.cluster.common.actor.MessageTracker.Error;
66 import org.opendaylight.controller.cluster.common.actor.MeteringBehavior;
67 import org.opendaylight.controller.cluster.datastore.exceptions.NoShardLeaderException;
68 import org.opendaylight.controller.cluster.datastore.identifiers.ShardIdentifier;
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.GetKnownClients;
79 import org.opendaylight.controller.cluster.datastore.messages.GetKnownClientsReply;
80 import org.opendaylight.controller.cluster.datastore.messages.GetShardDataTree;
81 import org.opendaylight.controller.cluster.datastore.messages.MakeLeaderLocal;
82 import org.opendaylight.controller.cluster.datastore.messages.OnDemandShardState;
83 import org.opendaylight.controller.cluster.datastore.messages.PeerAddressResolved;
84 import org.opendaylight.controller.cluster.datastore.messages.ReadyLocalTransaction;
85 import org.opendaylight.controller.cluster.datastore.messages.RegisterDataTreeChangeListener;
86 import org.opendaylight.controller.cluster.datastore.messages.ShardLeaderStateChanged;
87 import org.opendaylight.controller.cluster.datastore.messages.UpdateSchemaContext;
88 import org.opendaylight.controller.cluster.datastore.persisted.DatastoreSnapshot;
89 import org.opendaylight.controller.cluster.datastore.persisted.DatastoreSnapshot.ShardSnapshot;
90 import org.opendaylight.controller.cluster.datastore.persisted.DisableTrackingPayload;
91 import org.opendaylight.controller.cluster.messaging.MessageAssembler;
92 import org.opendaylight.controller.cluster.messaging.MessageSlicer;
93 import org.opendaylight.controller.cluster.messaging.SliceOptions;
94 import org.opendaylight.controller.cluster.notifications.LeaderStateChanged;
95 import org.opendaylight.controller.cluster.notifications.RegisterRoleChangeListener;
96 import org.opendaylight.controller.cluster.notifications.RoleChangeNotifier;
97 import org.opendaylight.controller.cluster.raft.LeadershipTransferFailedException;
98 import org.opendaylight.controller.cluster.raft.RaftActor;
99 import org.opendaylight.controller.cluster.raft.RaftActorRecoveryCohort;
100 import org.opendaylight.controller.cluster.raft.RaftActorSnapshotCohort;
101 import org.opendaylight.controller.cluster.raft.RaftState;
102 import org.opendaylight.controller.cluster.raft.base.messages.FollowerInitialSyncUpStatus;
103 import org.opendaylight.controller.cluster.raft.client.messages.OnDemandRaftState;
104 import org.opendaylight.controller.cluster.raft.messages.AppendEntriesReply;
105 import org.opendaylight.controller.cluster.raft.messages.RequestLeadership;
106 import org.opendaylight.controller.cluster.raft.messages.ServerRemoved;
107 import org.opendaylight.controller.cluster.raft.protobuff.client.messages.Payload;
108 import org.opendaylight.yangtools.concepts.Identifier;
109 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTree;
110 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataValidationFailedException;
111 import org.opendaylight.yangtools.yang.data.api.schema.tree.TreeType;
112 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
113 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContextProvider;
114 import scala.concurrent.duration.FiniteDuration;
117 * A Shard represents a portion of the logical data tree.
120 * Our Shard uses InMemoryDataTree as it's internal representation and delegates all requests it
122 public class Shard extends RaftActor {
125 static final Object TX_COMMIT_TIMEOUT_CHECK_MESSAGE = new Object() {
127 public String toString() {
128 return "txCommitTimeoutCheck";
133 static final Object GET_SHARD_MBEAN_MESSAGE = new Object() {
135 public String toString() {
136 return "getShardMBeanMessage";
140 static final Object RESUME_NEXT_PENDING_TRANSACTION = new Object() {
142 public String toString() {
143 return "resumeNextPendingTransaction";
147 // FIXME: shard names should be encapsulated in their own class and this should be exposed as a constant.
148 public static final String DEFAULT_NAME = "default";
150 private static final Collection<ABIVersion> SUPPORTED_ABIVERSIONS;
152 // Make sure to keep this in sync with the journal configuration in factory-akka.conf
153 public static final String NON_PERSISTENT_JOURNAL_ID = "akka.persistence.non-persistent.journal";
156 final ABIVersion[] values = ABIVersion.values();
157 final ABIVersion[] real = Arrays.copyOfRange(values, 1, values.length - 1);
158 SUPPORTED_ABIVERSIONS = ImmutableList.copyOf(real).reverse();
161 // FIXME: make this a dynamic property based on mailbox size and maximum number of clients
162 private static final int CLIENT_MAX_MESSAGES = 1000;
164 // The state of this Shard
165 private final ShardDataTree store;
167 /// The name of this shard
168 private final String name;
170 private final String shardName;
172 private final ShardStats shardMBean;
174 private final ShardDataTreeListenerInfoMXBeanImpl listenerInfoMXBean;
176 private DatastoreContext datastoreContext;
178 private final ShardCommitCoordinator commitCoordinator;
180 private long transactionCommitTimeout;
182 private Cancellable txCommitTimeoutCheckSchedule;
184 private final Optional<ActorRef> roleChangeNotifier;
186 private final MessageTracker appendEntriesReplyTracker;
188 private final ShardTransactionActorFactory transactionActorFactory;
190 private final ShardSnapshotCohort snapshotCohort;
192 private final DataTreeChangeListenerSupport treeChangeSupport = new DataTreeChangeListenerSupport(this);
194 private ShardSnapshot restoreFromSnapshot;
196 private final ShardTransactionMessageRetrySupport messageRetrySupport;
199 final FrontendMetadata frontendMetadata;
201 private Map<FrontendIdentifier, LeaderFrontendState> knownFrontends = ImmutableMap.of();
202 private boolean paused;
204 private final MessageSlicer responseMessageSlicer;
205 private final Dispatchers dispatchers;
207 private final MessageAssembler requestMessageAssembler;
209 protected Shard(final AbstractBuilder<?, ?> builder) {
210 super(builder.getId().toString(), builder.getPeerAddresses(),
211 Optional.of(builder.getDatastoreContext().getShardRaftConfig()), DataStoreVersions.CURRENT_VERSION);
213 this.name = builder.getId().toString();
214 this.shardName = builder.getId().getShardName();
215 this.datastoreContext = builder.getDatastoreContext();
216 this.restoreFromSnapshot = builder.getRestoreFromSnapshot();
217 this.frontendMetadata = new FrontendMetadata(name);
219 setPersistence(datastoreContext.isPersistent());
221 LOG.info("Shard created : {}, persistent : {}", name, datastoreContext.isPersistent());
223 ShardDataTreeChangeListenerPublisherActorProxy treeChangeListenerPublisher =
224 new ShardDataTreeChangeListenerPublisherActorProxy(getContext(), name + "-DTCL-publisher", name);
225 if (builder.getDataTree() != null) {
226 store = new ShardDataTree(this, builder.getSchemaContext(), builder.getDataTree(),
227 treeChangeListenerPublisher, name,
230 store = new ShardDataTree(this, builder.getSchemaContext(), builder.getTreeType(),
231 builder.getDatastoreContext().getStoreRoot(), treeChangeListenerPublisher, name,
235 shardMBean = ShardStats.create(name, datastoreContext.getDataStoreMXBeanType(), this);
237 if (isMetricsCaptureEnabled()) {
238 getContext().become(new MeteringBehavior(this));
241 commitCoordinator = new ShardCommitCoordinator(store, LOG, this.name);
243 setTransactionCommitTimeout();
245 // create a notifier actor for each cluster member
246 roleChangeNotifier = createRoleChangeNotifier(name);
248 appendEntriesReplyTracker = new MessageTracker(AppendEntriesReply.class,
249 getRaftActorContext().getConfigParams().getIsolatedCheckIntervalInMillis());
251 dispatchers = new Dispatchers(context().system().dispatchers());
252 transactionActorFactory = new ShardTransactionActorFactory(store, datastoreContext,
253 dispatchers.getDispatcherPath(Dispatchers.DispatcherType.Transaction),
254 self(), getContext(), shardMBean, builder.getId().getShardName());
256 snapshotCohort = ShardSnapshotCohort.create(getContext(), builder.getId().getMemberName(), store, LOG,
257 this.name, datastoreContext);
259 messageRetrySupport = new ShardTransactionMessageRetrySupport(this);
261 responseMessageSlicer = MessageSlicer.builder().logContext(this.name)
262 .messageSliceSize(datastoreContext.getMaximumMessageSliceSize())
263 .fileBackedStreamFactory(getRaftActorContext().getFileBackedOutputStreamFactory())
264 .expireStateAfterInactivity(2, TimeUnit.MINUTES).build();
266 requestMessageAssembler = MessageAssembler.builder().logContext(this.name)
267 .fileBackedStreamFactory(getRaftActorContext().getFileBackedOutputStreamFactory())
268 .assembledMessageCallback((message, sender) -> self().tell(message, sender))
269 .expireStateAfterInactivity(datastoreContext.getRequestTimeout(), TimeUnit.NANOSECONDS).build();
271 listenerInfoMXBean = new ShardDataTreeListenerInfoMXBeanImpl(name, datastoreContext.getDataStoreMXBeanType(),
273 listenerInfoMXBean.register();
276 private void setTransactionCommitTimeout() {
277 transactionCommitTimeout = TimeUnit.MILLISECONDS.convert(
278 datastoreContext.getShardTransactionCommitTimeoutInSeconds(), TimeUnit.SECONDS) / 2;
281 private Optional<ActorRef> createRoleChangeNotifier(final String shardId) {
282 ActorRef shardRoleChangeNotifier = this.getContext().actorOf(
283 RoleChangeNotifier.getProps(shardId), shardId + "-notifier");
284 return Optional.of(shardRoleChangeNotifier);
288 public void postStop() throws Exception {
289 LOG.info("Stopping Shard {}", persistenceId());
293 messageRetrySupport.close();
295 if (txCommitTimeoutCheckSchedule != null) {
296 txCommitTimeoutCheckSchedule.cancel();
299 commitCoordinator.abortPendingTransactions("Transaction aborted due to shutdown.", this);
301 shardMBean.unregisterMBean();
302 listenerInfoMXBean.unregister();
306 protected void handleRecover(final Object message) {
307 LOG.debug("{}: onReceiveRecover: Received message {} from {}", persistenceId(), message.getClass(),
310 super.handleRecover(message);
311 if (LOG.isTraceEnabled()) {
312 appendEntriesReplyTracker.begin();
317 protected void handleNonRaftCommand(final Object message) {
318 try (MessageTracker.Context context = appendEntriesReplyTracker.received(message)) {
319 final Optional<Error> maybeError = context.error();
320 if (maybeError.isPresent()) {
321 LOG.trace("{} : AppendEntriesReply failed to arrive at the expected interval {}", persistenceId(),
325 store.resetTransactionBatch();
327 if (message instanceof RequestEnvelope) {
328 handleRequestEnvelope((RequestEnvelope)message);
329 } else if (MessageAssembler.isHandledMessage(message)) {
330 handleRequestAssemblerMessage(message);
331 } else if (message instanceof ConnectClientRequest) {
332 handleConnectClient((ConnectClientRequest)message);
333 } else if (CreateTransaction.isSerializedType(message)) {
334 handleCreateTransaction(message);
335 } else if (message instanceof BatchedModifications) {
336 handleBatchedModifications((BatchedModifications)message);
337 } else if (message instanceof ForwardedReadyTransaction) {
338 handleForwardedReadyTransaction((ForwardedReadyTransaction) message);
339 } else if (message instanceof ReadyLocalTransaction) {
340 handleReadyLocalTransaction((ReadyLocalTransaction)message);
341 } else if (CanCommitTransaction.isSerializedType(message)) {
342 handleCanCommitTransaction(CanCommitTransaction.fromSerializable(message));
343 } else if (CommitTransaction.isSerializedType(message)) {
344 handleCommitTransaction(CommitTransaction.fromSerializable(message));
345 } else if (AbortTransaction.isSerializedType(message)) {
346 handleAbortTransaction(AbortTransaction.fromSerializable(message));
347 } else if (CloseTransactionChain.isSerializedType(message)) {
348 closeTransactionChain(CloseTransactionChain.fromSerializable(message));
349 } else if (message instanceof RegisterDataTreeChangeListener) {
350 treeChangeSupport.onMessage((RegisterDataTreeChangeListener) message, isLeader(), hasLeader());
351 } else if (message instanceof UpdateSchemaContext) {
352 updateSchemaContext((UpdateSchemaContext) message);
353 } else if (message instanceof PeerAddressResolved) {
354 PeerAddressResolved resolved = (PeerAddressResolved) message;
355 setPeerAddress(resolved.getPeerId(), resolved.getPeerAddress());
356 } else if (TX_COMMIT_TIMEOUT_CHECK_MESSAGE.equals(message)) {
357 commitTimeoutCheck();
358 } else if (message instanceof DatastoreContext) {
359 onDatastoreContext((DatastoreContext)message);
360 } else if (message instanceof RegisterRoleChangeListener) {
361 roleChangeNotifier.get().forward(message, context());
362 } else if (message instanceof FollowerInitialSyncUpStatus) {
363 shardMBean.setFollowerInitialSyncStatus(((FollowerInitialSyncUpStatus) message).isInitialSyncDone());
364 context().parent().tell(message, self());
365 } else if (GET_SHARD_MBEAN_MESSAGE.equals(message)) {
366 sender().tell(getShardMBean(), self());
367 } else if (message instanceof GetShardDataTree) {
368 sender().tell(store.getDataTree(), self());
369 } else if (message instanceof ServerRemoved) {
370 context().parent().forward(message, context());
371 } else if (ShardTransactionMessageRetrySupport.TIMER_MESSAGE_CLASS.isInstance(message)) {
372 messageRetrySupport.onTimerMessage(message);
373 } else if (message instanceof DataTreeCohortActorRegistry.CohortRegistryCommand) {
374 store.processCohortRegistryCommand(getSender(),
375 (DataTreeCohortActorRegistry.CohortRegistryCommand) message);
376 } else if (message instanceof MakeLeaderLocal) {
378 } else if (RESUME_NEXT_PENDING_TRANSACTION.equals(message)) {
379 store.resumeNextPendingTransaction();
380 } else if (GetKnownClients.INSTANCE.equals(message)) {
381 handleGetKnownClients();
382 } else if (!responseMessageSlicer.handleMessage(message)) {
383 super.handleNonRaftCommand(message);
388 private void handleRequestAssemblerMessage(final Object message) {
389 dispatchers.getDispatcher(DispatcherType.Serialization).execute(() -> {
390 JavaSerializer.currentSystem().value_$eq((ExtendedActorSystem) context().system());
391 requestMessageAssembler.handleMessage(message, self());
395 @SuppressWarnings("checkstyle:IllegalCatch")
396 private void handleRequestEnvelope(final RequestEnvelope envelope) {
397 final long now = ticker().read();
399 final RequestSuccess<?, ?> success = handleRequest(envelope, now);
400 if (success != null) {
401 final long executionTimeNanos = ticker().read() - now;
402 if (success instanceof SliceableMessage) {
403 dispatchers.getDispatcher(DispatcherType.Serialization).execute(() ->
404 responseMessageSlicer.slice(SliceOptions.builder().identifier(success.getTarget())
405 .message(envelope.newSuccessEnvelope(success, executionTimeNanos))
406 .sendTo(envelope.getMessage().getReplyTo()).replyTo(self())
407 .onFailureCallback(t -> LOG.warn("Error slicing response {}", success, t)).build()));
409 envelope.sendSuccess(success, executionTimeNanos);
412 } catch (RequestException e) {
413 LOG.debug("{}: request {} failed", persistenceId(), envelope, e);
414 envelope.sendFailure(e, ticker().read() - now);
415 } catch (Exception e) {
416 LOG.debug("{}: request {} caused failure", persistenceId(), envelope, e);
417 envelope.sendFailure(new RuntimeRequestException("Request failed to process", e),
418 ticker().read() - now);
422 private void commitTimeoutCheck() {
423 store.checkForExpiredTransactions(transactionCommitTimeout, this::updateAccess);
424 commitCoordinator.checkForExpiredTransactions(transactionCommitTimeout, this);
425 requestMessageAssembler.checkExpiredAssembledMessageState();
428 private OptionalLong updateAccess(final SimpleShardDataTreeCohort cohort) {
429 final FrontendIdentifier frontend = cohort.getIdentifier().getHistoryId().getClientId().getFrontendId();
430 final LeaderFrontendState state = knownFrontends.get(frontend);
432 // Not tell-based protocol, do nothing
433 return OptionalLong.empty();
436 if (isIsolatedLeader()) {
437 // We are isolated and no new request can come through until we emerge from it. We are still updating
438 // liveness of frontend when we see it attempting to communicate. Use the last access timer.
439 return OptionalLong.of(state.getLastSeenTicks());
442 // If this frontend has freshly connected, give it some time to catch up before killing its transactions.
443 return OptionalLong.of(state.getLastConnectTicks());
446 private void disableTracking(final DisableTrackingPayload payload) {
447 final ClientIdentifier clientId = payload.getIdentifier();
448 LOG.debug("{}: disabling tracking of {}", persistenceId(), clientId);
449 frontendMetadata.disableTracking(clientId);
452 final FrontendIdentifier frontendId = clientId.getFrontendId();
453 final LeaderFrontendState frontend = knownFrontends.get(frontendId);
454 if (frontend != null) {
455 if (clientId.equals(frontend.getIdentifier())) {
456 if (!(frontend instanceof LeaderFrontendState.Disabled)) {
457 verify(knownFrontends.replace(frontendId, frontend,
458 new LeaderFrontendState.Disabled(persistenceId(), clientId, store)));
459 LOG.debug("{}: leader state for {} disabled", persistenceId(), clientId);
461 LOG.debug("{}: leader state {} is already disabled", persistenceId(), frontend);
464 LOG.debug("{}: leader state {} does not match {}", persistenceId(), frontend, clientId);
467 LOG.debug("{}: leader state for {} not found", persistenceId(), clientId);
468 knownFrontends.put(frontendId, new LeaderFrontendState.Disabled(persistenceId(), clientId,
474 private void onMakeLeaderLocal() {
475 LOG.debug("{}: onMakeLeaderLocal received", persistenceId());
477 getSender().tell(new Status.Success(null), getSelf());
481 final ActorSelection leader = getLeader();
483 if (leader == null) {
484 // Leader is not present. The cluster is most likely trying to
485 // elect a leader and we should let that run its normal course
487 // TODO we can wait for the election to complete and retry the
488 // request. We can also let the caller retry by sending a flag
489 // in the response indicating the request is "reTryable".
490 getSender().tell(new Failure(
491 new LeadershipTransferFailedException("We cannot initiate leadership transfer to local node. "
492 + "Currently there is no leader for " + persistenceId())),
497 leader.tell(new RequestLeadership(getId(), getSender()), getSelf());
500 // Acquire our frontend tracking handle and verify generation matches
501 private @Nullable LeaderFrontendState findFrontend(final ClientIdentifier clientId) throws RequestException {
502 final LeaderFrontendState existing = knownFrontends.get(clientId.getFrontendId());
503 if (existing != null) {
504 final int cmp = Long.compareUnsigned(existing.getIdentifier().getGeneration(), clientId.getGeneration());
510 LOG.debug("{}: rejecting request from outdated client {}", persistenceId(), clientId);
511 throw new RetiredGenerationException(clientId.getGeneration(),
512 existing.getIdentifier().getGeneration());
515 LOG.info("{}: retiring state {}, outdated by request from client {}", persistenceId(), existing, clientId);
517 knownFrontends.remove(clientId.getFrontendId());
519 LOG.debug("{}: client {} is not yet known", persistenceId(), clientId);
525 private LeaderFrontendState getFrontend(final ClientIdentifier clientId) throws RequestException {
526 final LeaderFrontendState ret = findFrontend(clientId);
531 // TODO: a dedicated exception would be better, but this is technically true, too
532 throw new OutOfSequenceEnvelopeException(0);
535 private static @NonNull ABIVersion selectVersion(final ConnectClientRequest message) {
536 final Range<ABIVersion> clientRange = Range.closed(message.getMinVersion(), message.getMaxVersion());
537 for (ABIVersion v : SUPPORTED_ABIVERSIONS) {
538 if (clientRange.contains(v)) {
543 throw new IllegalArgumentException(String.format(
544 "No common version between backend versions %s and client versions %s", SUPPORTED_ABIVERSIONS,
548 @SuppressWarnings("checkstyle:IllegalCatch")
549 private void handleConnectClient(final ConnectClientRequest message) {
551 final ClientIdentifier clientId = message.getTarget();
552 final LeaderFrontendState existing = findFrontend(clientId);
553 if (existing != null) {
557 if (!isLeader() || !isLeaderActive()) {
558 LOG.info("{}: not currently leader, rejecting request {}. isLeader: {}, isLeaderActive: {},"
559 + "isLeadershipTransferInProgress: {}.",
560 persistenceId(), message, isLeader(), isLeaderActive(), isLeadershipTransferInProgress());
561 throw new NotLeaderException(getSelf());
564 final ABIVersion selectedVersion = selectVersion(message);
565 final LeaderFrontendState frontend;
566 if (existing == null) {
567 frontend = new LeaderFrontendState.Enabled(persistenceId(), clientId, store);
568 knownFrontends.put(clientId.getFrontendId(), frontend);
569 LOG.debug("{}: created state {} for client {}", persistenceId(), frontend, clientId);
574 frontend.reconnect();
575 message.getReplyTo().tell(new ConnectClientSuccess(message.getTarget(), message.getSequence(), getSelf(),
576 ImmutableList.of(), store.getDataTree(), CLIENT_MAX_MESSAGES).toVersion(selectedVersion),
577 ActorRef.noSender());
578 } catch (RequestException | RuntimeException e) {
579 message.getReplyTo().tell(new Failure(e), ActorRef.noSender());
583 private @Nullable RequestSuccess<?, ?> handleRequest(final RequestEnvelope envelope, final long now)
584 throws RequestException {
585 // We are not the leader, hence we want to fail-fast.
586 if (!isLeader() || paused || !isLeaderActive()) {
587 LOG.debug("{}: not currently active leader, rejecting request {}. isLeader: {}, isLeaderActive: {},"
588 + "isLeadershipTransferInProgress: {}, paused: {}",
589 persistenceId(), envelope, isLeader(), isLeaderActive(), isLeadershipTransferInProgress(), paused);
590 throw new NotLeaderException(getSelf());
593 final Request<?, ?> request = envelope.getMessage();
594 if (request instanceof TransactionRequest) {
595 final TransactionRequest<?> txReq = (TransactionRequest<?>)request;
596 final ClientIdentifier clientId = txReq.getTarget().getHistoryId().getClientId();
597 return getFrontend(clientId).handleTransactionRequest(txReq, envelope, now);
598 } else if (request instanceof LocalHistoryRequest) {
599 final LocalHistoryRequest<?> lhReq = (LocalHistoryRequest<?>)request;
600 final ClientIdentifier clientId = lhReq.getTarget().getClientId();
601 return getFrontend(clientId).handleLocalHistoryRequest(lhReq, envelope, now);
603 LOG.warn("{}: rejecting unsupported request {}", persistenceId(), request);
604 throw new UnsupportedRequestException(request);
608 private void handleGetKnownClients() {
609 final ImmutableSet<ClientIdentifier> clients;
611 clients = knownFrontends.values().stream()
612 .map(LeaderFrontendState::getIdentifier)
613 .collect(ImmutableSet.toImmutableSet());
615 clients = frontendMetadata.getClients();
617 sender().tell(new GetKnownClientsReply(clients), self());
620 private boolean hasLeader() {
621 return getLeaderId() != null;
624 public int getPendingTxCommitQueueSize() {
625 return store.getQueueSize();
628 public int getCohortCacheSize() {
629 return commitCoordinator.getCohortCacheSize();
633 protected Optional<ActorRef> getRoleChangeNotifier() {
634 return roleChangeNotifier;
637 String getShardName() {
642 protected LeaderStateChanged newLeaderStateChanged(final String memberId, final String leaderId,
643 final short leaderPayloadVersion) {
644 return isLeader() ? new ShardLeaderStateChanged(memberId, leaderId, store.getDataTree(), leaderPayloadVersion)
645 : new ShardLeaderStateChanged(memberId, leaderId, leaderPayloadVersion);
648 protected void onDatastoreContext(final DatastoreContext context) {
649 datastoreContext = verifyNotNull(context);
651 setTransactionCommitTimeout();
653 setPersistence(datastoreContext.isPersistent());
655 updateConfigParams(datastoreContext.getShardRaftConfig());
658 // applyState() will be invoked once consensus is reached on the payload
659 void persistPayload(final Identifier id, final Payload payload, final boolean batchHint) {
660 boolean canSkipPayload = !hasFollowers() && !persistence().isRecoveryApplicable();
661 if (canSkipPayload) {
662 applyState(self(), id, payload);
664 // We are faking the sender
665 persistData(self(), id, payload, batchHint);
669 private void handleCommitTransaction(final CommitTransaction commit) {
670 final TransactionIdentifier txId = commit.getTransactionId();
672 askProtocolEncountered(txId);
673 commitCoordinator.handleCommit(txId, getSender(), this);
675 ActorSelection leader = getLeader();
676 if (leader == null) {
677 messageRetrySupport.addMessageToRetry(commit, getSender(), "Could not commit transaction " + txId);
679 LOG.debug("{}: Forwarding CommitTransaction to leader {}", persistenceId(), leader);
680 leader.forward(commit, getContext());
685 private void handleCanCommitTransaction(final CanCommitTransaction canCommit) {
686 final TransactionIdentifier txId = canCommit.getTransactionId();
687 LOG.debug("{}: Can committing transaction {}", persistenceId(), txId);
690 askProtocolEncountered(txId);
691 commitCoordinator.handleCanCommit(txId, getSender(), this);
693 ActorSelection leader = getLeader();
694 if (leader == null) {
695 messageRetrySupport.addMessageToRetry(canCommit, getSender(),
696 "Could not canCommit transaction " + txId);
698 LOG.debug("{}: Forwarding CanCommitTransaction to leader {}", persistenceId(), leader);
699 leader.forward(canCommit, getContext());
704 @SuppressWarnings("checkstyle:IllegalCatch")
705 protected void handleBatchedModificationsLocal(final BatchedModifications batched, final ActorRef sender) {
706 askProtocolEncountered(batched.getTransactionId());
709 commitCoordinator.handleBatchedModifications(batched, sender, this);
710 } catch (Exception e) {
711 LOG.error("{}: Error handling BatchedModifications for Tx {}", persistenceId(),
712 batched.getTransactionId(), e);
713 sender.tell(new Failure(e), getSelf());
717 private void handleBatchedModifications(final BatchedModifications batched) {
718 // This message is sent to prepare the modifications transaction directly on the Shard as an
719 // optimization to avoid the extra overhead of a separate ShardTransaction actor. On the last
720 // BatchedModifications message, the caller sets the ready flag in the message indicating
721 // modifications are complete. The reply contains the cohort actor path (this actor) for the caller
722 // to initiate the 3-phase commit. This also avoids the overhead of sending an additional
723 // ReadyTransaction message.
725 // If we're not the leader then forward to the leader. This is a safety measure - we shouldn't
726 // normally get here if we're not the leader as the front-end (TransactionProxy) should determine
727 // the primary/leader shard. However with timing and caching on the front-end, there's a small
728 // window where it could have a stale leader during leadership transitions.
730 boolean isLeaderActive = isLeaderActive();
731 if (isLeader() && isLeaderActive) {
732 handleBatchedModificationsLocal(batched, getSender());
734 ActorSelection leader = getLeader();
735 if (!isLeaderActive || leader == null) {
736 messageRetrySupport.addMessageToRetry(batched, getSender(),
737 "Could not process BatchedModifications " + batched.getTransactionId());
739 // If this is not the first batch and leadership changed in between batched messages,
740 // we need to reconstruct previous BatchedModifications from the transaction
741 // DataTreeModification, honoring the max batched modification count, and forward all the
742 // previous BatchedModifications to the new leader.
743 Collection<BatchedModifications> newModifications = commitCoordinator
744 .createForwardedBatchedModifications(batched,
745 datastoreContext.getShardBatchedModificationCount());
747 LOG.debug("{}: Forwarding {} BatchedModifications to leader {}", persistenceId(),
748 newModifications.size(), leader);
750 for (BatchedModifications bm : newModifications) {
751 leader.forward(bm, getContext());
757 private boolean failIfIsolatedLeader(final ActorRef sender) {
758 if (isIsolatedLeader()) {
759 sender.tell(new Failure(new NoShardLeaderException(String.format(
760 "Shard %s was the leader but has lost contact with all of its followers. Either all"
761 + " other follower nodes are down or this node is isolated by a network partition.",
762 persistenceId()))), getSelf());
769 protected boolean isIsolatedLeader() {
770 return getRaftState() == RaftState.IsolatedLeader;
773 @SuppressWarnings("checkstyle:IllegalCatch")
774 private void handleReadyLocalTransaction(final ReadyLocalTransaction message) {
775 LOG.debug("{}: handleReadyLocalTransaction for {}", persistenceId(), message.getTransactionId());
777 boolean isLeaderActive = isLeaderActive();
778 if (isLeader() && isLeaderActive) {
780 commitCoordinator.handleReadyLocalTransaction(message, getSender(), this);
781 } catch (Exception e) {
782 LOG.error("{}: Error handling ReadyLocalTransaction for Tx {}", persistenceId(),
783 message.getTransactionId(), e);
784 getSender().tell(new Failure(e), getSelf());
787 ActorSelection leader = getLeader();
788 if (!isLeaderActive || leader == null) {
789 messageRetrySupport.addMessageToRetry(message, getSender(),
790 "Could not process ready local transaction " + message.getTransactionId());
792 LOG.debug("{}: Forwarding ReadyLocalTransaction to leader {}", persistenceId(), leader);
793 message.setRemoteVersion(getCurrentBehavior().getLeaderPayloadVersion());
794 leader.forward(message, getContext());
799 private void handleForwardedReadyTransaction(final ForwardedReadyTransaction forwardedReady) {
800 LOG.debug("{}: handleForwardedReadyTransaction for {}", persistenceId(), forwardedReady.getTransactionId());
802 boolean isLeaderActive = isLeaderActive();
803 if (isLeader() && isLeaderActive) {
804 askProtocolEncountered(forwardedReady.getTransactionId());
805 commitCoordinator.handleForwardedReadyTransaction(forwardedReady, getSender(), this);
807 ActorSelection leader = getLeader();
808 if (!isLeaderActive || leader == null) {
809 messageRetrySupport.addMessageToRetry(forwardedReady, getSender(),
810 "Could not process forwarded ready transaction " + forwardedReady.getTransactionId());
812 LOG.debug("{}: Forwarding ForwardedReadyTransaction to leader {}", persistenceId(), leader);
814 ReadyLocalTransaction readyLocal = new ReadyLocalTransaction(forwardedReady.getTransactionId(),
815 forwardedReady.getTransaction().getSnapshot(), forwardedReady.isDoImmediateCommit(),
816 forwardedReady.getParticipatingShardNames());
817 readyLocal.setRemoteVersion(getCurrentBehavior().getLeaderPayloadVersion());
818 leader.forward(readyLocal, getContext());
823 private void handleAbortTransaction(final AbortTransaction abort) {
824 final TransactionIdentifier transactionId = abort.getTransactionId();
825 askProtocolEncountered(transactionId);
826 doAbortTransaction(transactionId, getSender());
829 void doAbortTransaction(final Identifier transactionID, final ActorRef sender) {
830 commitCoordinator.handleAbort(transactionID, sender, this);
833 private void handleCreateTransaction(final Object message) {
835 createTransaction(CreateTransaction.fromSerializable(message));
836 } else if (getLeader() != null) {
837 getLeader().forward(message, getContext());
839 getSender().tell(new Failure(new NoShardLeaderException(
840 "Could not create a shard transaction", persistenceId())), getSelf());
844 private void closeTransactionChain(final CloseTransactionChain closeTransactionChain) {
846 final LocalHistoryIdentifier id = closeTransactionChain.getIdentifier();
847 askProtocolEncountered(id.getClientId());
848 store.closeTransactionChain(id);
849 } else if (getLeader() != null) {
850 getLeader().forward(closeTransactionChain, getContext());
852 LOG.warn("{}: Could not close transaction {}", persistenceId(), closeTransactionChain.getIdentifier());
856 @SuppressWarnings("checkstyle:IllegalCatch")
857 private void createTransaction(final CreateTransaction createTransaction) {
858 askProtocolEncountered(createTransaction.getTransactionId());
861 if (TransactionType.fromInt(createTransaction.getTransactionType()) != TransactionType.READ_ONLY
862 && failIfIsolatedLeader(getSender())) {
866 ActorRef transactionActor = createTransaction(createTransaction.getTransactionType(),
867 createTransaction.getTransactionId());
869 getSender().tell(new CreateTransactionReply(Serialization.serializedActorPath(transactionActor),
870 createTransaction.getTransactionId(), createTransaction.getVersion()).toSerializable(), getSelf());
871 } catch (Exception e) {
872 getSender().tell(new Failure(e), getSelf());
876 private ActorRef createTransaction(final int transactionType, final TransactionIdentifier transactionId) {
877 LOG.debug("{}: Creating transaction : {} ", persistenceId(), transactionId);
878 return transactionActorFactory.newShardTransaction(TransactionType.fromInt(transactionType),
882 // Called on leader only
883 private void askProtocolEncountered(final TransactionIdentifier transactionId) {
884 askProtocolEncountered(transactionId.getHistoryId().getClientId());
887 // Called on leader only
888 private void askProtocolEncountered(final ClientIdentifier clientId) {
889 final FrontendIdentifier frontend = clientId.getFrontendId();
890 final LeaderFrontendState state = knownFrontends.get(frontend);
891 if (!(state instanceof LeaderFrontendState.Disabled)) {
892 LOG.debug("{}: encountered ask-based client {}, disabling transaction tracking", persistenceId(), clientId);
893 if (knownFrontends.isEmpty()) {
894 knownFrontends = new HashMap<>();
896 knownFrontends.put(frontend, new LeaderFrontendState.Disabled(persistenceId(), clientId, getDataStore()));
898 persistPayload(clientId, DisableTrackingPayload.create(clientId,
899 datastoreContext.getInitialPayloadSerializedBufferCapacity()), false);
903 private void updateSchemaContext(final UpdateSchemaContext message) {
904 updateSchemaContext(message.getEffectiveModelContext());
908 void updateSchemaContext(final @NonNull EffectiveModelContext schemaContext) {
909 store.updateSchemaContext(schemaContext);
912 private boolean isMetricsCaptureEnabled() {
913 CommonConfig config = new CommonConfig(getContext().system().settings().config());
914 return config.isMetricCaptureEnabled();
919 public RaftActorSnapshotCohort getRaftActorSnapshotCohort() {
920 return snapshotCohort;
924 protected RaftActorRecoveryCohort getRaftActorRecoveryCohort() {
925 if (restoreFromSnapshot == null) {
926 return ShardRecoveryCoordinator.create(store, persistenceId(), LOG);
929 return ShardRecoveryCoordinator.forSnapshot(store, persistenceId(), LOG, restoreFromSnapshot.getSnapshot());
933 protected void onRecoveryComplete() {
934 restoreFromSnapshot = null;
936 //notify shard manager
937 getContext().parent().tell(new ActorInitialized(), getSelf());
939 // Being paranoid here - this method should only be called once but just in case...
940 if (txCommitTimeoutCheckSchedule == null) {
941 // Schedule a message to be periodically sent to check if the current in-progress
942 // transaction should be expired and aborted.
943 FiniteDuration period = FiniteDuration.create(transactionCommitTimeout / 3, TimeUnit.MILLISECONDS);
944 txCommitTimeoutCheckSchedule = getContext().system().scheduler().schedule(
945 period, period, getSelf(),
946 TX_COMMIT_TIMEOUT_CHECK_MESSAGE, getContext().dispatcher(), ActorRef.noSender());
951 protected void applyState(final ActorRef clientActor, final Identifier identifier, final Object data) {
952 if (data instanceof Payload) {
953 if (data instanceof DisableTrackingPayload) {
954 disableTracking((DisableTrackingPayload) data);
959 store.applyReplicatedPayload(identifier, (Payload)data);
960 } catch (DataValidationFailedException | IOException e) {
961 LOG.error("{}: Error applying replica {}", persistenceId(), identifier, e);
964 LOG.error("{}: Unknown state for {} received {}", persistenceId(), identifier, data);
969 protected void onStateChanged() {
970 boolean isLeader = isLeader();
971 boolean hasLeader = hasLeader();
972 treeChangeSupport.onLeadershipChange(isLeader, hasLeader);
974 // If this actor is no longer the leader close all the transaction chains
976 if (LOG.isDebugEnabled()) {
978 "{}: onStateChanged: Closing all transaction chains because shard {} is no longer the leader",
979 persistenceId(), getId());
983 store.purgeLeaderState();
986 if (hasLeader && !isIsolatedLeader()) {
987 messageRetrySupport.retryMessages();
992 protected void onLeaderChanged(final String oldLeader, final String newLeader) {
993 shardMBean.incrementLeadershipChangeCount();
997 if (!knownFrontends.isEmpty()) {
998 LOG.debug("{}: removing frontend state for {}", persistenceId(), knownFrontends.keySet());
999 knownFrontends = ImmutableMap.of();
1002 requestMessageAssembler.close();
1005 // No leader anywhere, nothing else to do
1009 // Another leader was elected. If we were the previous leader and had pending transactions, convert
1010 // them to transaction messages and send to the new leader.
1011 ActorSelection leader = getLeader();
1012 if (leader != null) {
1013 Collection<?> messagesToForward = convertPendingTransactionsToMessages();
1015 if (!messagesToForward.isEmpty()) {
1016 LOG.debug("{}: Forwarding {} pending transaction messages to leader {}", persistenceId(),
1017 messagesToForward.size(), leader);
1019 for (Object message : messagesToForward) {
1020 LOG.debug("{}: Forwarding pending transaction message {}", persistenceId(), message);
1022 leader.tell(message, self());
1026 commitCoordinator.abortPendingTransactions("The transacton was aborted due to inflight leadership "
1027 + "change and the leader address isn't available.", this);
1030 // We have become the leader, we need to reconstruct frontend state
1031 knownFrontends = Verify.verifyNotNull(frontendMetadata.toLeaderState(this));
1032 LOG.debug("{}: became leader with frontend state for {}", persistenceId(), knownFrontends.keySet());
1035 if (!isIsolatedLeader()) {
1036 messageRetrySupport.retryMessages();
1041 * Clears all pending transactions and converts them to messages to be forwarded to a new leader.
1043 * @return the converted messages
1045 public Collection<?> convertPendingTransactionsToMessages() {
1046 return commitCoordinator.convertPendingTransactionsToMessages(
1047 datastoreContext.getShardBatchedModificationCount());
1051 protected void pauseLeader(final Runnable operation) {
1052 LOG.debug("{}: In pauseLeader, operation: {}", persistenceId(), operation);
1055 // Tell-based protocol can replay transaction state, so it is safe to blow it up when we are paused.
1056 if (datastoreContext.isUseTellBasedProtocol()) {
1057 knownFrontends.values().forEach(LeaderFrontendState::retire);
1058 knownFrontends = ImmutableMap.of();
1061 store.setRunOnPendingTransactionsComplete(operation);
1065 protected void unpauseLeader() {
1066 LOG.debug("{}: In unpauseLeader", persistenceId());
1069 store.setRunOnPendingTransactionsComplete(null);
1071 // Restore tell-based protocol state as if we were becoming the leader
1072 knownFrontends = Verify.verifyNotNull(frontendMetadata.toLeaderState(this));
1076 protected OnDemandRaftState.AbstractBuilder<?, ?> newOnDemandRaftStateBuilder() {
1077 return OnDemandShardState.newBuilder().treeChangeListenerActors(treeChangeSupport.getListenerActors())
1078 .commitCohortActors(store.getCohortActors());
1082 public String persistenceId() {
1087 public String journalPluginId() {
1088 // This method may be invoked from super constructor (wonderful), hence we also need to handle the case of
1089 // the field being uninitialized because our constructor is not finished.
1090 if (datastoreContext != null && !datastoreContext.isPersistent()) {
1091 return NON_PERSISTENT_JOURNAL_ID;
1093 return super.journalPluginId();
1097 ShardCommitCoordinator getCommitCoordinator() {
1098 return commitCoordinator;
1101 public DatastoreContext getDatastoreContext() {
1102 return datastoreContext;
1106 public ShardDataTree getDataStore() {
1111 ShardStats getShardMBean() {
1115 public static Builder builder() {
1116 return new Builder();
1119 public abstract static class AbstractBuilder<T extends AbstractBuilder<T, S>, S extends Shard> {
1120 private final Class<? extends S> shardClass;
1121 private ShardIdentifier id;
1122 private Map<String, String> peerAddresses = Collections.emptyMap();
1123 private DatastoreContext datastoreContext;
1124 private EffectiveModelContextProvider schemaContextProvider;
1125 private DatastoreSnapshot.ShardSnapshot restoreFromSnapshot;
1126 private DataTree dataTree;
1128 private volatile boolean sealed;
1130 protected AbstractBuilder(final Class<? extends S> shardClass) {
1131 this.shardClass = shardClass;
1134 protected void checkSealed() {
1135 checkState(!sealed, "Builder isalready sealed - further modifications are not allowed");
1138 @SuppressWarnings("unchecked")
1143 public T id(final ShardIdentifier newId) {
1149 public T peerAddresses(final Map<String, String> newPeerAddresses) {
1151 this.peerAddresses = newPeerAddresses;
1155 public T datastoreContext(final DatastoreContext newDatastoreContext) {
1157 this.datastoreContext = newDatastoreContext;
1161 public T schemaContextProvider(final EffectiveModelContextProvider newSchemaContextProvider) {
1163 this.schemaContextProvider = requireNonNull(newSchemaContextProvider);
1167 public T restoreFromSnapshot(final DatastoreSnapshot.ShardSnapshot newRestoreFromSnapshot) {
1169 this.restoreFromSnapshot = newRestoreFromSnapshot;
1173 public T dataTree(final DataTree newDataTree) {
1175 this.dataTree = newDataTree;
1179 public ShardIdentifier getId() {
1183 public Map<String, String> getPeerAddresses() {
1184 return peerAddresses;
1187 public DatastoreContext getDatastoreContext() {
1188 return datastoreContext;
1191 public EffectiveModelContext getSchemaContext() {
1192 return Verify.verifyNotNull(schemaContextProvider.getEffectiveModelContext());
1195 public DatastoreSnapshot.ShardSnapshot getRestoreFromSnapshot() {
1196 return restoreFromSnapshot;
1199 public DataTree getDataTree() {
1203 public TreeType getTreeType() {
1204 switch (datastoreContext.getLogicalStoreType()) {
1206 return TreeType.CONFIGURATION;
1208 return TreeType.OPERATIONAL;
1210 throw new IllegalStateException("Unhandled logical store type "
1211 + datastoreContext.getLogicalStoreType());
1215 protected void verify() {
1216 requireNonNull(id, "id should not be null");
1217 requireNonNull(peerAddresses, "peerAddresses should not be null");
1218 requireNonNull(datastoreContext, "dataStoreContext should not be null");
1219 requireNonNull(schemaContextProvider, "schemaContextProvider should not be null");
1222 public Props props() {
1225 return Props.create(shardClass, this);
1229 public static class Builder extends AbstractBuilder<Builder, Shard> {
1234 Builder(final Class<? extends Shard> shardClass) {
1240 return Ticker.systemTicker();
1243 void scheduleNextPendingTransaction() {
1244 self().tell(RESUME_NEXT_PENDING_TRANSACTION, ActorRef.noSender());