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.jmx.mbeans.shard.ShardDataTreeListenerInfoMXBeanImpl;
70 import org.opendaylight.controller.cluster.datastore.jmx.mbeans.shard.ShardMBeanFactory;
71 import org.opendaylight.controller.cluster.datastore.jmx.mbeans.shard.ShardStats;
72 import org.opendaylight.controller.cluster.datastore.messages.AbortTransaction;
73 import org.opendaylight.controller.cluster.datastore.messages.ActorInitialized;
74 import org.opendaylight.controller.cluster.datastore.messages.BatchedModifications;
75 import org.opendaylight.controller.cluster.datastore.messages.CanCommitTransaction;
76 import org.opendaylight.controller.cluster.datastore.messages.CloseTransactionChain;
77 import org.opendaylight.controller.cluster.datastore.messages.CommitTransaction;
78 import org.opendaylight.controller.cluster.datastore.messages.CreateTransaction;
79 import org.opendaylight.controller.cluster.datastore.messages.CreateTransactionReply;
80 import org.opendaylight.controller.cluster.datastore.messages.DataTreeChangedReply;
81 import org.opendaylight.controller.cluster.datastore.messages.ForwardedReadyTransaction;
82 import org.opendaylight.controller.cluster.datastore.messages.GetKnownClients;
83 import org.opendaylight.controller.cluster.datastore.messages.GetKnownClientsReply;
84 import org.opendaylight.controller.cluster.datastore.messages.GetShardDataTree;
85 import org.opendaylight.controller.cluster.datastore.messages.MakeLeaderLocal;
86 import org.opendaylight.controller.cluster.datastore.messages.OnDemandShardState;
87 import org.opendaylight.controller.cluster.datastore.messages.PeerAddressResolved;
88 import org.opendaylight.controller.cluster.datastore.messages.ReadyLocalTransaction;
89 import org.opendaylight.controller.cluster.datastore.messages.RegisterDataTreeChangeListener;
90 import org.opendaylight.controller.cluster.datastore.messages.ShardLeaderStateChanged;
91 import org.opendaylight.controller.cluster.datastore.messages.UpdateSchemaContext;
92 import org.opendaylight.controller.cluster.datastore.persisted.DatastoreSnapshot;
93 import org.opendaylight.controller.cluster.datastore.persisted.DatastoreSnapshot.ShardSnapshot;
94 import org.opendaylight.controller.cluster.datastore.persisted.DisableTrackingPayload;
95 import org.opendaylight.controller.cluster.messaging.MessageAssembler;
96 import org.opendaylight.controller.cluster.messaging.MessageSlicer;
97 import org.opendaylight.controller.cluster.messaging.SliceOptions;
98 import org.opendaylight.controller.cluster.notifications.LeaderStateChanged;
99 import org.opendaylight.controller.cluster.notifications.RegisterRoleChangeListener;
100 import org.opendaylight.controller.cluster.notifications.RoleChangeNotifier;
101 import org.opendaylight.controller.cluster.raft.LeadershipTransferFailedException;
102 import org.opendaylight.controller.cluster.raft.RaftActor;
103 import org.opendaylight.controller.cluster.raft.RaftActorRecoveryCohort;
104 import org.opendaylight.controller.cluster.raft.RaftActorSnapshotCohort;
105 import org.opendaylight.controller.cluster.raft.RaftState;
106 import org.opendaylight.controller.cluster.raft.base.messages.FollowerInitialSyncUpStatus;
107 import org.opendaylight.controller.cluster.raft.client.messages.OnDemandRaftState;
108 import org.opendaylight.controller.cluster.raft.messages.AppendEntriesReply;
109 import org.opendaylight.controller.cluster.raft.messages.RequestLeadership;
110 import org.opendaylight.controller.cluster.raft.messages.ServerRemoved;
111 import org.opendaylight.controller.cluster.raft.protobuff.client.messages.Payload;
112 import org.opendaylight.yangtools.concepts.Identifier;
113 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTree;
114 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataValidationFailedException;
115 import org.opendaylight.yangtools.yang.data.api.schema.tree.TreeType;
116 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
117 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContextProvider;
118 import scala.concurrent.duration.FiniteDuration;
121 * A Shard represents a portion of the logical data tree.
124 * Our Shard uses InMemoryDataTree as it's internal representation and delegates all requests it
126 public class Shard extends RaftActor {
129 static final Object TX_COMMIT_TIMEOUT_CHECK_MESSAGE = new Object() {
131 public String toString() {
132 return "txCommitTimeoutCheck";
137 static final Object GET_SHARD_MBEAN_MESSAGE = new Object() {
139 public String toString() {
140 return "getShardMBeanMessage";
144 static final Object RESUME_NEXT_PENDING_TRANSACTION = new Object() {
146 public String toString() {
147 return "resumeNextPendingTransaction";
151 // FIXME: shard names should be encapsulated in their own class and this should be exposed as a constant.
152 public static final String DEFAULT_NAME = "default";
154 private static final Collection<ABIVersion> SUPPORTED_ABIVERSIONS;
156 // Make sure to keep this in sync with the journal configuration in factory-akka.conf
157 public static final String NON_PERSISTENT_JOURNAL_ID = "akka.persistence.non-persistent.journal";
160 final ABIVersion[] values = ABIVersion.values();
161 final ABIVersion[] real = Arrays.copyOfRange(values, 1, values.length - 1);
162 SUPPORTED_ABIVERSIONS = ImmutableList.copyOf(real).reverse();
165 // FIXME: make this a dynamic property based on mailbox size and maximum number of clients
166 private static final int CLIENT_MAX_MESSAGES = 1000;
168 // The state of this Shard
169 private final ShardDataTree store;
171 /// The name of this shard
172 private final String name;
174 private final String shardName;
176 private final ShardStats shardMBean;
178 private final ShardDataTreeListenerInfoMXBeanImpl listenerInfoMXBean;
180 private DatastoreContext datastoreContext;
182 private final ShardCommitCoordinator commitCoordinator;
184 private long transactionCommitTimeout;
186 private Cancellable txCommitTimeoutCheckSchedule;
188 private final Optional<ActorRef> roleChangeNotifier;
190 private final MessageTracker appendEntriesReplyTracker;
192 private final ShardTransactionActorFactory transactionActorFactory;
194 private final ShardSnapshotCohort snapshotCohort;
196 private final DataTreeChangeListenerSupport treeChangeSupport = new DataTreeChangeListenerSupport(this);
198 private ShardSnapshot restoreFromSnapshot;
200 private final ShardTransactionMessageRetrySupport messageRetrySupport;
203 final FrontendMetadata frontendMetadata;
205 private Map<FrontendIdentifier, LeaderFrontendState> knownFrontends = ImmutableMap.of();
206 private boolean paused;
208 private final MessageSlicer responseMessageSlicer;
209 private final Dispatchers dispatchers;
211 private final MessageAssembler requestMessageAssembler;
213 protected Shard(final AbstractBuilder<?, ?> builder) {
214 super(builder.getId().toString(), builder.getPeerAddresses(),
215 Optional.of(builder.getDatastoreContext().getShardRaftConfig()), DataStoreVersions.CURRENT_VERSION);
217 this.name = builder.getId().toString();
218 this.shardName = builder.getId().getShardName();
219 this.datastoreContext = builder.getDatastoreContext();
220 this.restoreFromSnapshot = builder.getRestoreFromSnapshot();
221 this.frontendMetadata = new FrontendMetadata(name);
223 setPersistence(datastoreContext.isPersistent());
225 LOG.info("Shard created : {}, persistent : {}", name, datastoreContext.isPersistent());
227 ShardDataTreeChangeListenerPublisherActorProxy treeChangeListenerPublisher =
228 new ShardDataTreeChangeListenerPublisherActorProxy(getContext(), name + "-DTCL-publisher", name);
229 if (builder.getDataTree() != null) {
230 store = new ShardDataTree(this, builder.getSchemaContext(), builder.getDataTree(),
231 treeChangeListenerPublisher, name,
234 store = new ShardDataTree(this, builder.getSchemaContext(), builder.getTreeType(),
235 builder.getDatastoreContext().getStoreRoot(), treeChangeListenerPublisher, name,
239 shardMBean = ShardMBeanFactory.getShardStatsMBean(name, datastoreContext.getDataStoreMXBeanType(), this);
241 if (isMetricsCaptureEnabled()) {
242 getContext().become(new MeteringBehavior(this));
245 commitCoordinator = new ShardCommitCoordinator(store, LOG, this.name);
247 setTransactionCommitTimeout();
249 // create a notifier actor for each cluster member
250 roleChangeNotifier = createRoleChangeNotifier(name);
252 appendEntriesReplyTracker = new MessageTracker(AppendEntriesReply.class,
253 getRaftActorContext().getConfigParams().getIsolatedCheckIntervalInMillis());
255 dispatchers = new Dispatchers(context().system().dispatchers());
256 transactionActorFactory = new ShardTransactionActorFactory(store, datastoreContext,
257 dispatchers.getDispatcherPath(Dispatchers.DispatcherType.Transaction),
258 self(), getContext(), shardMBean, builder.getId().getShardName());
260 snapshotCohort = ShardSnapshotCohort.create(getContext(), builder.getId().getMemberName(), store, LOG,
261 this.name, datastoreContext);
263 messageRetrySupport = new ShardTransactionMessageRetrySupport(this);
265 responseMessageSlicer = MessageSlicer.builder().logContext(this.name)
266 .messageSliceSize(datastoreContext.getMaximumMessageSliceSize())
267 .fileBackedStreamFactory(getRaftActorContext().getFileBackedOutputStreamFactory())
268 .expireStateAfterInactivity(2, TimeUnit.MINUTES).build();
270 requestMessageAssembler = MessageAssembler.builder().logContext(this.name)
271 .fileBackedStreamFactory(getRaftActorContext().getFileBackedOutputStreamFactory())
272 .assembledMessageCallback((message, sender) -> self().tell(message, sender))
273 .expireStateAfterInactivity(datastoreContext.getRequestTimeout(), TimeUnit.NANOSECONDS).build();
275 listenerInfoMXBean = new ShardDataTreeListenerInfoMXBeanImpl(name, datastoreContext.getDataStoreMXBeanType(),
277 listenerInfoMXBean.register();
280 private void setTransactionCommitTimeout() {
281 transactionCommitTimeout = TimeUnit.MILLISECONDS.convert(
282 datastoreContext.getShardTransactionCommitTimeoutInSeconds(), TimeUnit.SECONDS) / 2;
285 private Optional<ActorRef> createRoleChangeNotifier(final String shardId) {
286 ActorRef shardRoleChangeNotifier = this.getContext().actorOf(
287 RoleChangeNotifier.getProps(shardId), shardId + "-notifier");
288 return Optional.of(shardRoleChangeNotifier);
292 public void postStop() throws Exception {
293 LOG.info("Stopping Shard {}", persistenceId());
297 messageRetrySupport.close();
299 if (txCommitTimeoutCheckSchedule != null) {
300 txCommitTimeoutCheckSchedule.cancel();
303 commitCoordinator.abortPendingTransactions("Transaction aborted due to shutdown.", this);
305 shardMBean.unregisterMBean();
306 listenerInfoMXBean.unregister();
310 protected void handleRecover(final Object message) {
311 LOG.debug("{}: onReceiveRecover: Received message {} from {}", persistenceId(), message.getClass(),
314 super.handleRecover(message);
315 if (LOG.isTraceEnabled()) {
316 appendEntriesReplyTracker.begin();
321 protected void handleNonRaftCommand(final Object message) {
322 try (MessageTracker.Context context = appendEntriesReplyTracker.received(message)) {
323 final Optional<Error> maybeError = context.error();
324 if (maybeError.isPresent()) {
325 LOG.trace("{} : AppendEntriesReply failed to arrive at the expected interval {}", persistenceId(),
329 store.resetTransactionBatch();
331 if (message instanceof RequestEnvelope) {
332 handleRequestEnvelope((RequestEnvelope)message);
333 } else if (MessageAssembler.isHandledMessage(message)) {
334 handleRequestAssemblerMessage(message);
335 } else if (message instanceof ConnectClientRequest) {
336 handleConnectClient((ConnectClientRequest)message);
337 } else if (CreateTransaction.isSerializedType(message)) {
338 handleCreateTransaction(message);
339 } else if (message instanceof BatchedModifications) {
340 handleBatchedModifications((BatchedModifications)message);
341 } else if (message instanceof ForwardedReadyTransaction) {
342 handleForwardedReadyTransaction((ForwardedReadyTransaction) message);
343 } else if (message instanceof ReadyLocalTransaction) {
344 handleReadyLocalTransaction((ReadyLocalTransaction)message);
345 } else if (CanCommitTransaction.isSerializedType(message)) {
346 handleCanCommitTransaction(CanCommitTransaction.fromSerializable(message));
347 } else if (CommitTransaction.isSerializedType(message)) {
348 handleCommitTransaction(CommitTransaction.fromSerializable(message));
349 } else if (AbortTransaction.isSerializedType(message)) {
350 handleAbortTransaction(AbortTransaction.fromSerializable(message));
351 } else if (CloseTransactionChain.isSerializedType(message)) {
352 closeTransactionChain(CloseTransactionChain.fromSerializable(message));
353 } else if (message instanceof DataTreeChangedReply) {
355 } else if (message instanceof RegisterDataTreeChangeListener) {
356 treeChangeSupport.onMessage((RegisterDataTreeChangeListener) message, isLeader(), hasLeader());
357 } else if (message instanceof UpdateSchemaContext) {
358 updateSchemaContext((UpdateSchemaContext) message);
359 } else if (message instanceof PeerAddressResolved) {
360 PeerAddressResolved resolved = (PeerAddressResolved) message;
361 setPeerAddress(resolved.getPeerId(), resolved.getPeerAddress());
362 } else if (TX_COMMIT_TIMEOUT_CHECK_MESSAGE.equals(message)) {
363 commitTimeoutCheck();
364 } else if (message instanceof DatastoreContext) {
365 onDatastoreContext((DatastoreContext)message);
366 } else if (message instanceof RegisterRoleChangeListener) {
367 roleChangeNotifier.get().forward(message, context());
368 } else if (message instanceof FollowerInitialSyncUpStatus) {
369 shardMBean.setFollowerInitialSyncStatus(((FollowerInitialSyncUpStatus) message).isInitialSyncDone());
370 context().parent().tell(message, self());
371 } else if (GET_SHARD_MBEAN_MESSAGE.equals(message)) {
372 sender().tell(getShardMBean(), self());
373 } else if (message instanceof GetShardDataTree) {
374 sender().tell(store.getDataTree(), self());
375 } else if (message instanceof ServerRemoved) {
376 context().parent().forward(message, context());
377 } else if (ShardTransactionMessageRetrySupport.TIMER_MESSAGE_CLASS.isInstance(message)) {
378 messageRetrySupport.onTimerMessage(message);
379 } else if (message instanceof DataTreeCohortActorRegistry.CohortRegistryCommand) {
380 store.processCohortRegistryCommand(getSender(),
381 (DataTreeCohortActorRegistry.CohortRegistryCommand) message);
382 } else if (message instanceof MakeLeaderLocal) {
384 } else if (RESUME_NEXT_PENDING_TRANSACTION.equals(message)) {
385 store.resumeNextPendingTransaction();
386 } else if (GetKnownClients.INSTANCE.equals(message)) {
387 handleGetKnownClients();
388 } else if (!responseMessageSlicer.handleMessage(message)) {
389 super.handleNonRaftCommand(message);
394 private void handleRequestAssemblerMessage(final Object message) {
395 dispatchers.getDispatcher(DispatcherType.Serialization).execute(() -> {
396 JavaSerializer.currentSystem().value_$eq((ExtendedActorSystem) context().system());
397 requestMessageAssembler.handleMessage(message, self());
401 @SuppressWarnings("checkstyle:IllegalCatch")
402 private void handleRequestEnvelope(final RequestEnvelope envelope) {
403 final long now = ticker().read();
405 final RequestSuccess<?, ?> success = handleRequest(envelope, now);
406 if (success != null) {
407 final long executionTimeNanos = ticker().read() - now;
408 if (success instanceof SliceableMessage) {
409 dispatchers.getDispatcher(DispatcherType.Serialization).execute(() ->
410 responseMessageSlicer.slice(SliceOptions.builder().identifier(success.getTarget())
411 .message(envelope.newSuccessEnvelope(success, executionTimeNanos))
412 .sendTo(envelope.getMessage().getReplyTo()).replyTo(self())
413 .onFailureCallback(t -> LOG.warn("Error slicing response {}", success, t)).build()));
415 envelope.sendSuccess(success, executionTimeNanos);
418 } catch (RequestException e) {
419 LOG.debug("{}: request {} failed", persistenceId(), envelope, e);
420 envelope.sendFailure(e, ticker().read() - now);
421 } catch (Exception e) {
422 LOG.debug("{}: request {} caused failure", persistenceId(), envelope, e);
423 envelope.sendFailure(new RuntimeRequestException("Request failed to process", e),
424 ticker().read() - now);
428 private void commitTimeoutCheck() {
429 store.checkForExpiredTransactions(transactionCommitTimeout, this::updateAccess);
430 commitCoordinator.checkForExpiredTransactions(transactionCommitTimeout, this);
431 requestMessageAssembler.checkExpiredAssembledMessageState();
434 private OptionalLong updateAccess(final SimpleShardDataTreeCohort cohort) {
435 final FrontendIdentifier frontend = cohort.getIdentifier().getHistoryId().getClientId().getFrontendId();
436 final LeaderFrontendState state = knownFrontends.get(frontend);
438 // Not tell-based protocol, do nothing
439 return OptionalLong.empty();
442 if (isIsolatedLeader()) {
443 // We are isolated and no new request can come through until we emerge from it. We are still updating
444 // liveness of frontend when we see it attempting to communicate. Use the last access timer.
445 return OptionalLong.of(state.getLastSeenTicks());
448 // If this frontend has freshly connected, give it some time to catch up before killing its transactions.
449 return OptionalLong.of(state.getLastConnectTicks());
452 private void disableTracking(final DisableTrackingPayload payload) {
453 final ClientIdentifier clientId = payload.getIdentifier();
454 LOG.debug("{}: disabling tracking of {}", persistenceId(), clientId);
455 frontendMetadata.disableTracking(clientId);
458 final FrontendIdentifier frontendId = clientId.getFrontendId();
459 final LeaderFrontendState frontend = knownFrontends.get(frontendId);
460 if (frontend != null) {
461 if (clientId.equals(frontend.getIdentifier())) {
462 if (!(frontend instanceof LeaderFrontendState.Disabled)) {
463 verify(knownFrontends.replace(frontendId, frontend,
464 new LeaderFrontendState.Disabled(persistenceId(), clientId, store)));
465 LOG.debug("{}: leader state for {} disabled", persistenceId(), clientId);
467 LOG.debug("{}: leader state {} is already disabled", persistenceId(), frontend);
470 LOG.debug("{}: leader state {} does not match {}", persistenceId(), frontend, clientId);
473 LOG.debug("{}: leader state for {} not found", persistenceId(), clientId);
474 knownFrontends.put(frontendId, new LeaderFrontendState.Disabled(persistenceId(), clientId,
480 private void onMakeLeaderLocal() {
481 LOG.debug("{}: onMakeLeaderLocal received", persistenceId());
483 getSender().tell(new Status.Success(null), getSelf());
487 final ActorSelection leader = getLeader();
489 if (leader == null) {
490 // Leader is not present. The cluster is most likely trying to
491 // elect a leader and we should let that run its normal course
493 // TODO we can wait for the election to complete and retry the
494 // request. We can also let the caller retry by sending a flag
495 // in the response indicating the request is "reTryable".
496 getSender().tell(new Failure(
497 new LeadershipTransferFailedException("We cannot initiate leadership transfer to local node. "
498 + "Currently there is no leader for " + persistenceId())),
503 leader.tell(new RequestLeadership(getId(), getSender()), getSelf());
506 // Acquire our frontend tracking handle and verify generation matches
507 private @Nullable LeaderFrontendState findFrontend(final ClientIdentifier clientId) throws RequestException {
508 final LeaderFrontendState existing = knownFrontends.get(clientId.getFrontendId());
509 if (existing != null) {
510 final int cmp = Long.compareUnsigned(existing.getIdentifier().getGeneration(), clientId.getGeneration());
516 LOG.debug("{}: rejecting request from outdated client {}", persistenceId(), clientId);
517 throw new RetiredGenerationException(clientId.getGeneration(),
518 existing.getIdentifier().getGeneration());
521 LOG.info("{}: retiring state {}, outdated by request from client {}", persistenceId(), existing, clientId);
523 knownFrontends.remove(clientId.getFrontendId());
525 LOG.debug("{}: client {} is not yet known", persistenceId(), clientId);
531 private LeaderFrontendState getFrontend(final ClientIdentifier clientId) throws RequestException {
532 final LeaderFrontendState ret = findFrontend(clientId);
537 // TODO: a dedicated exception would be better, but this is technically true, too
538 throw new OutOfSequenceEnvelopeException(0);
541 private static @NonNull ABIVersion selectVersion(final ConnectClientRequest message) {
542 final Range<ABIVersion> clientRange = Range.closed(message.getMinVersion(), message.getMaxVersion());
543 for (ABIVersion v : SUPPORTED_ABIVERSIONS) {
544 if (clientRange.contains(v)) {
549 throw new IllegalArgumentException(String.format(
550 "No common version between backend versions %s and client versions %s", SUPPORTED_ABIVERSIONS,
554 @SuppressWarnings("checkstyle:IllegalCatch")
555 private void handleConnectClient(final ConnectClientRequest message) {
557 final ClientIdentifier clientId = message.getTarget();
558 final LeaderFrontendState existing = findFrontend(clientId);
559 if (existing != null) {
563 if (!isLeader() || !isLeaderActive()) {
564 LOG.info("{}: not currently leader, rejecting request {}. isLeader: {}, isLeaderActive: {},"
565 + "isLeadershipTransferInProgress: {}.",
566 persistenceId(), message, isLeader(), isLeaderActive(), isLeadershipTransferInProgress());
567 throw new NotLeaderException(getSelf());
570 final ABIVersion selectedVersion = selectVersion(message);
571 final LeaderFrontendState frontend;
572 if (existing == null) {
573 frontend = new LeaderFrontendState.Enabled(persistenceId(), clientId, store);
574 knownFrontends.put(clientId.getFrontendId(), frontend);
575 LOG.debug("{}: created state {} for client {}", persistenceId(), frontend, clientId);
580 frontend.reconnect();
581 message.getReplyTo().tell(new ConnectClientSuccess(message.getTarget(), message.getSequence(), getSelf(),
582 ImmutableList.of(), store.getDataTree(), CLIENT_MAX_MESSAGES).toVersion(selectedVersion),
583 ActorRef.noSender());
584 } catch (RequestException | RuntimeException e) {
585 message.getReplyTo().tell(new Failure(e), ActorRef.noSender());
589 private @Nullable RequestSuccess<?, ?> handleRequest(final RequestEnvelope envelope, final long now)
590 throws RequestException {
591 // We are not the leader, hence we want to fail-fast.
592 if (!isLeader() || paused || !isLeaderActive()) {
593 LOG.debug("{}: not currently active leader, rejecting request {}. isLeader: {}, isLeaderActive: {},"
594 + "isLeadershipTransferInProgress: {}, paused: {}",
595 persistenceId(), envelope, isLeader(), isLeaderActive(), isLeadershipTransferInProgress(), paused);
596 throw new NotLeaderException(getSelf());
599 final Request<?, ?> request = envelope.getMessage();
600 if (request instanceof TransactionRequest) {
601 final TransactionRequest<?> txReq = (TransactionRequest<?>)request;
602 final ClientIdentifier clientId = txReq.getTarget().getHistoryId().getClientId();
603 return getFrontend(clientId).handleTransactionRequest(txReq, envelope, now);
604 } else if (request instanceof LocalHistoryRequest) {
605 final LocalHistoryRequest<?> lhReq = (LocalHistoryRequest<?>)request;
606 final ClientIdentifier clientId = lhReq.getTarget().getClientId();
607 return getFrontend(clientId).handleLocalHistoryRequest(lhReq, envelope, now);
609 LOG.warn("{}: rejecting unsupported request {}", persistenceId(), request);
610 throw new UnsupportedRequestException(request);
614 private void handleGetKnownClients() {
615 final ImmutableSet<ClientIdentifier> clients;
617 clients = knownFrontends.values().stream()
618 .map(LeaderFrontendState::getIdentifier)
619 .collect(ImmutableSet.toImmutableSet());
621 clients = frontendMetadata.getClients();
623 sender().tell(new GetKnownClientsReply(clients), self());
626 private boolean hasLeader() {
627 return getLeaderId() != null;
630 public int getPendingTxCommitQueueSize() {
631 return store.getQueueSize();
634 public int getCohortCacheSize() {
635 return commitCoordinator.getCohortCacheSize();
639 protected Optional<ActorRef> getRoleChangeNotifier() {
640 return roleChangeNotifier;
643 String getShardName() {
648 protected LeaderStateChanged newLeaderStateChanged(final String memberId, final String leaderId,
649 final short leaderPayloadVersion) {
650 return isLeader() ? new ShardLeaderStateChanged(memberId, leaderId, store.getDataTree(), leaderPayloadVersion)
651 : new ShardLeaderStateChanged(memberId, leaderId, leaderPayloadVersion);
654 protected void onDatastoreContext(final DatastoreContext context) {
655 datastoreContext = verifyNotNull(context);
657 setTransactionCommitTimeout();
659 setPersistence(datastoreContext.isPersistent());
661 updateConfigParams(datastoreContext.getShardRaftConfig());
664 // applyState() will be invoked once consensus is reached on the payload
665 void persistPayload(final Identifier id, final Payload payload, final boolean batchHint) {
666 boolean canSkipPayload = !hasFollowers() && !persistence().isRecoveryApplicable();
667 if (canSkipPayload) {
668 applyState(self(), id, payload);
670 // We are faking the sender
671 persistData(self(), id, payload, batchHint);
675 private void handleCommitTransaction(final CommitTransaction commit) {
676 final TransactionIdentifier txId = commit.getTransactionId();
678 askProtocolEncountered(txId);
679 commitCoordinator.handleCommit(txId, getSender(), this);
681 ActorSelection leader = getLeader();
682 if (leader == null) {
683 messageRetrySupport.addMessageToRetry(commit, getSender(), "Could not commit transaction " + txId);
685 LOG.debug("{}: Forwarding CommitTransaction to leader {}", persistenceId(), leader);
686 leader.forward(commit, getContext());
691 private void handleCanCommitTransaction(final CanCommitTransaction canCommit) {
692 final TransactionIdentifier txId = canCommit.getTransactionId();
693 LOG.debug("{}: Can committing transaction {}", persistenceId(), txId);
696 askProtocolEncountered(txId);
697 commitCoordinator.handleCanCommit(txId, getSender(), this);
699 ActorSelection leader = getLeader();
700 if (leader == null) {
701 messageRetrySupport.addMessageToRetry(canCommit, getSender(),
702 "Could not canCommit transaction " + txId);
704 LOG.debug("{}: Forwarding CanCommitTransaction to leader {}", persistenceId(), leader);
705 leader.forward(canCommit, getContext());
710 @SuppressWarnings("checkstyle:IllegalCatch")
711 protected void handleBatchedModificationsLocal(final BatchedModifications batched, final ActorRef sender) {
712 askProtocolEncountered(batched.getTransactionId());
715 commitCoordinator.handleBatchedModifications(batched, sender, this);
716 } catch (Exception e) {
717 LOG.error("{}: Error handling BatchedModifications for Tx {}", persistenceId(),
718 batched.getTransactionId(), e);
719 sender.tell(new Failure(e), getSelf());
723 private void handleBatchedModifications(final BatchedModifications batched) {
724 // This message is sent to prepare the modifications transaction directly on the Shard as an
725 // optimization to avoid the extra overhead of a separate ShardTransaction actor. On the last
726 // BatchedModifications message, the caller sets the ready flag in the message indicating
727 // modifications are complete. The reply contains the cohort actor path (this actor) for the caller
728 // to initiate the 3-phase commit. This also avoids the overhead of sending an additional
729 // ReadyTransaction message.
731 // If we're not the leader then forward to the leader. This is a safety measure - we shouldn't
732 // normally get here if we're not the leader as the front-end (TransactionProxy) should determine
733 // the primary/leader shard. However with timing and caching on the front-end, there's a small
734 // window where it could have a stale leader during leadership transitions.
736 boolean isLeaderActive = isLeaderActive();
737 if (isLeader() && isLeaderActive) {
738 handleBatchedModificationsLocal(batched, getSender());
740 ActorSelection leader = getLeader();
741 if (!isLeaderActive || leader == null) {
742 messageRetrySupport.addMessageToRetry(batched, getSender(),
743 "Could not process BatchedModifications " + batched.getTransactionId());
745 // If this is not the first batch and leadership changed in between batched messages,
746 // we need to reconstruct previous BatchedModifications from the transaction
747 // DataTreeModification, honoring the max batched modification count, and forward all the
748 // previous BatchedModifications to the new leader.
749 Collection<BatchedModifications> newModifications = commitCoordinator
750 .createForwardedBatchedModifications(batched,
751 datastoreContext.getShardBatchedModificationCount());
753 LOG.debug("{}: Forwarding {} BatchedModifications to leader {}", persistenceId(),
754 newModifications.size(), leader);
756 for (BatchedModifications bm : newModifications) {
757 leader.forward(bm, getContext());
763 private boolean failIfIsolatedLeader(final ActorRef sender) {
764 if (isIsolatedLeader()) {
765 sender.tell(new Failure(new NoShardLeaderException(String.format(
766 "Shard %s was the leader but has lost contact with all of its followers. Either all"
767 + " other follower nodes are down or this node is isolated by a network partition.",
768 persistenceId()))), getSelf());
775 protected boolean isIsolatedLeader() {
776 return getRaftState() == RaftState.IsolatedLeader;
779 @SuppressWarnings("checkstyle:IllegalCatch")
780 private void handleReadyLocalTransaction(final ReadyLocalTransaction message) {
781 LOG.debug("{}: handleReadyLocalTransaction for {}", persistenceId(), message.getTransactionId());
783 boolean isLeaderActive = isLeaderActive();
784 if (isLeader() && isLeaderActive) {
786 commitCoordinator.handleReadyLocalTransaction(message, getSender(), this);
787 } catch (Exception e) {
788 LOG.error("{}: Error handling ReadyLocalTransaction for Tx {}", persistenceId(),
789 message.getTransactionId(), e);
790 getSender().tell(new Failure(e), getSelf());
793 ActorSelection leader = getLeader();
794 if (!isLeaderActive || leader == null) {
795 messageRetrySupport.addMessageToRetry(message, getSender(),
796 "Could not process ready local transaction " + message.getTransactionId());
798 LOG.debug("{}: Forwarding ReadyLocalTransaction to leader {}", persistenceId(), leader);
799 message.setRemoteVersion(getCurrentBehavior().getLeaderPayloadVersion());
800 leader.forward(message, getContext());
805 private void handleForwardedReadyTransaction(final ForwardedReadyTransaction forwardedReady) {
806 LOG.debug("{}: handleForwardedReadyTransaction for {}", persistenceId(), forwardedReady.getTransactionId());
808 boolean isLeaderActive = isLeaderActive();
809 if (isLeader() && isLeaderActive) {
810 askProtocolEncountered(forwardedReady.getTransactionId());
811 commitCoordinator.handleForwardedReadyTransaction(forwardedReady, getSender(), this);
813 ActorSelection leader = getLeader();
814 if (!isLeaderActive || leader == null) {
815 messageRetrySupport.addMessageToRetry(forwardedReady, getSender(),
816 "Could not process forwarded ready transaction " + forwardedReady.getTransactionId());
818 LOG.debug("{}: Forwarding ForwardedReadyTransaction to leader {}", persistenceId(), leader);
820 ReadyLocalTransaction readyLocal = new ReadyLocalTransaction(forwardedReady.getTransactionId(),
821 forwardedReady.getTransaction().getSnapshot(), forwardedReady.isDoImmediateCommit(),
822 forwardedReady.getParticipatingShardNames());
823 readyLocal.setRemoteVersion(getCurrentBehavior().getLeaderPayloadVersion());
824 leader.forward(readyLocal, getContext());
829 private void handleAbortTransaction(final AbortTransaction abort) {
830 final TransactionIdentifier transactionId = abort.getTransactionId();
831 askProtocolEncountered(transactionId);
832 doAbortTransaction(transactionId, getSender());
835 void doAbortTransaction(final Identifier transactionID, final ActorRef sender) {
836 commitCoordinator.handleAbort(transactionID, sender, this);
839 private void handleCreateTransaction(final Object message) {
841 createTransaction(CreateTransaction.fromSerializable(message));
842 } else if (getLeader() != null) {
843 getLeader().forward(message, getContext());
845 getSender().tell(new Failure(new NoShardLeaderException(
846 "Could not create a shard transaction", persistenceId())), getSelf());
850 private void closeTransactionChain(final CloseTransactionChain closeTransactionChain) {
852 final LocalHistoryIdentifier id = closeTransactionChain.getIdentifier();
853 askProtocolEncountered(id.getClientId());
854 store.closeTransactionChain(id);
855 } else if (getLeader() != null) {
856 getLeader().forward(closeTransactionChain, getContext());
858 LOG.warn("{}: Could not close transaction {}", persistenceId(), closeTransactionChain.getIdentifier());
862 @SuppressWarnings("checkstyle:IllegalCatch")
863 private void createTransaction(final CreateTransaction createTransaction) {
864 askProtocolEncountered(createTransaction.getTransactionId());
867 if (TransactionType.fromInt(createTransaction.getTransactionType()) != TransactionType.READ_ONLY
868 && failIfIsolatedLeader(getSender())) {
872 ActorRef transactionActor = createTransaction(createTransaction.getTransactionType(),
873 createTransaction.getTransactionId());
875 getSender().tell(new CreateTransactionReply(Serialization.serializedActorPath(transactionActor),
876 createTransaction.getTransactionId(), createTransaction.getVersion()).toSerializable(), getSelf());
877 } catch (Exception e) {
878 getSender().tell(new Failure(e), getSelf());
882 private ActorRef createTransaction(final int transactionType, final TransactionIdentifier transactionId) {
883 LOG.debug("{}: Creating transaction : {} ", persistenceId(), transactionId);
884 return transactionActorFactory.newShardTransaction(TransactionType.fromInt(transactionType),
888 // Called on leader only
889 private void askProtocolEncountered(final TransactionIdentifier transactionId) {
890 askProtocolEncountered(transactionId.getHistoryId().getClientId());
893 // Called on leader only
894 private void askProtocolEncountered(final ClientIdentifier clientId) {
895 final FrontendIdentifier frontend = clientId.getFrontendId();
896 final LeaderFrontendState state = knownFrontends.get(frontend);
897 if (!(state instanceof LeaderFrontendState.Disabled)) {
898 LOG.debug("{}: encountered ask-based client {}, disabling transaction tracking", persistenceId(), clientId);
899 if (knownFrontends.isEmpty()) {
900 knownFrontends = new HashMap<>();
902 knownFrontends.put(frontend, new LeaderFrontendState.Disabled(persistenceId(), clientId, getDataStore()));
904 persistPayload(clientId, DisableTrackingPayload.create(clientId,
905 datastoreContext.getInitialPayloadSerializedBufferCapacity()), false);
909 private void updateSchemaContext(final UpdateSchemaContext message) {
910 updateSchemaContext(message.getEffectiveModelContext());
914 void updateSchemaContext(final @NonNull EffectiveModelContext schemaContext) {
915 store.updateSchemaContext(schemaContext);
918 private boolean isMetricsCaptureEnabled() {
919 CommonConfig config = new CommonConfig(getContext().system().settings().config());
920 return config.isMetricCaptureEnabled();
925 public RaftActorSnapshotCohort getRaftActorSnapshotCohort() {
926 return snapshotCohort;
930 protected RaftActorRecoveryCohort getRaftActorRecoveryCohort() {
931 if (restoreFromSnapshot == null) {
932 return ShardRecoveryCoordinator.create(store, persistenceId(), LOG);
935 return ShardRecoveryCoordinator.forSnapshot(store, persistenceId(), LOG, restoreFromSnapshot.getSnapshot());
939 protected void onRecoveryComplete() {
940 restoreFromSnapshot = null;
942 //notify shard manager
943 getContext().parent().tell(new ActorInitialized(), getSelf());
945 // Being paranoid here - this method should only be called once but just in case...
946 if (txCommitTimeoutCheckSchedule == null) {
947 // Schedule a message to be periodically sent to check if the current in-progress
948 // transaction should be expired and aborted.
949 FiniteDuration period = FiniteDuration.create(transactionCommitTimeout / 3, TimeUnit.MILLISECONDS);
950 txCommitTimeoutCheckSchedule = getContext().system().scheduler().schedule(
951 period, period, getSelf(),
952 TX_COMMIT_TIMEOUT_CHECK_MESSAGE, getContext().dispatcher(), ActorRef.noSender());
957 protected void applyState(final ActorRef clientActor, final Identifier identifier, final Object data) {
958 if (data instanceof Payload) {
959 if (data instanceof DisableTrackingPayload) {
960 disableTracking((DisableTrackingPayload) data);
965 store.applyReplicatedPayload(identifier, (Payload)data);
966 } catch (DataValidationFailedException | IOException e) {
967 LOG.error("{}: Error applying replica {}", persistenceId(), identifier, e);
970 LOG.error("{}: Unknown state for {} received {}", persistenceId(), identifier, data);
975 protected void onStateChanged() {
976 boolean isLeader = isLeader();
977 boolean hasLeader = hasLeader();
978 treeChangeSupport.onLeadershipChange(isLeader, hasLeader);
980 // If this actor is no longer the leader close all the transaction chains
982 if (LOG.isDebugEnabled()) {
984 "{}: onStateChanged: Closing all transaction chains because shard {} is no longer the leader",
985 persistenceId(), getId());
989 store.purgeLeaderState();
992 if (hasLeader && !isIsolatedLeader()) {
993 messageRetrySupport.retryMessages();
998 protected void onLeaderChanged(final String oldLeader, final String newLeader) {
999 shardMBean.incrementLeadershipChangeCount();
1003 if (!knownFrontends.isEmpty()) {
1004 LOG.debug("{}: removing frontend state for {}", persistenceId(), knownFrontends.keySet());
1005 knownFrontends = ImmutableMap.of();
1008 requestMessageAssembler.close();
1011 // No leader anywhere, nothing else to do
1015 // Another leader was elected. If we were the previous leader and had pending transactions, convert
1016 // them to transaction messages and send to the new leader.
1017 ActorSelection leader = getLeader();
1018 if (leader != null) {
1019 Collection<?> messagesToForward = convertPendingTransactionsToMessages();
1021 if (!messagesToForward.isEmpty()) {
1022 LOG.debug("{}: Forwarding {} pending transaction messages to leader {}", persistenceId(),
1023 messagesToForward.size(), leader);
1025 for (Object message : messagesToForward) {
1026 LOG.debug("{}: Forwarding pending transaction message {}", persistenceId(), message);
1028 leader.tell(message, self());
1032 commitCoordinator.abortPendingTransactions("The transacton was aborted due to inflight leadership "
1033 + "change and the leader address isn't available.", this);
1036 // We have become the leader, we need to reconstruct frontend state
1037 knownFrontends = Verify.verifyNotNull(frontendMetadata.toLeaderState(this));
1038 LOG.debug("{}: became leader with frontend state for {}", persistenceId(), knownFrontends.keySet());
1041 if (!isIsolatedLeader()) {
1042 messageRetrySupport.retryMessages();
1047 * Clears all pending transactions and converts them to messages to be forwarded to a new leader.
1049 * @return the converted messages
1051 public Collection<?> convertPendingTransactionsToMessages() {
1052 return commitCoordinator.convertPendingTransactionsToMessages(
1053 datastoreContext.getShardBatchedModificationCount());
1057 protected void pauseLeader(final Runnable operation) {
1058 LOG.debug("{}: In pauseLeader, operation: {}", persistenceId(), operation);
1061 // Tell-based protocol can replay transaction state, so it is safe to blow it up when we are paused.
1062 if (datastoreContext.isUseTellBasedProtocol()) {
1063 knownFrontends.values().forEach(LeaderFrontendState::retire);
1064 knownFrontends = ImmutableMap.of();
1067 store.setRunOnPendingTransactionsComplete(operation);
1071 protected void unpauseLeader() {
1072 LOG.debug("{}: In unpauseLeader", persistenceId());
1075 store.setRunOnPendingTransactionsComplete(null);
1077 // Restore tell-based protocol state as if we were becoming the leader
1078 knownFrontends = Verify.verifyNotNull(frontendMetadata.toLeaderState(this));
1082 protected OnDemandRaftState.AbstractBuilder<?, ?> newOnDemandRaftStateBuilder() {
1083 return OnDemandShardState.newBuilder().treeChangeListenerActors(treeChangeSupport.getListenerActors())
1084 .commitCohortActors(store.getCohortActors());
1088 public String persistenceId() {
1093 public String journalPluginId() {
1094 // This method may be invoked from super constructor (wonderful), hence we also need to handle the case of
1095 // the field being uninitialized because our constructor is not finished.
1096 if (datastoreContext != null && !datastoreContext.isPersistent()) {
1097 return NON_PERSISTENT_JOURNAL_ID;
1099 return super.journalPluginId();
1103 ShardCommitCoordinator getCommitCoordinator() {
1104 return commitCoordinator;
1107 public DatastoreContext getDatastoreContext() {
1108 return datastoreContext;
1112 public ShardDataTree getDataStore() {
1117 ShardStats getShardMBean() {
1121 public static Builder builder() {
1122 return new Builder();
1125 public abstract static class AbstractBuilder<T extends AbstractBuilder<T, S>, S extends Shard> {
1126 private final Class<? extends S> shardClass;
1127 private ShardIdentifier id;
1128 private Map<String, String> peerAddresses = Collections.emptyMap();
1129 private DatastoreContext datastoreContext;
1130 private EffectiveModelContextProvider schemaContextProvider;
1131 private DatastoreSnapshot.ShardSnapshot restoreFromSnapshot;
1132 private DataTree dataTree;
1134 private volatile boolean sealed;
1136 protected AbstractBuilder(final Class<? extends S> shardClass) {
1137 this.shardClass = shardClass;
1140 protected void checkSealed() {
1141 checkState(!sealed, "Builder isalready sealed - further modifications are not allowed");
1144 @SuppressWarnings("unchecked")
1149 public T id(final ShardIdentifier newId) {
1155 public T peerAddresses(final Map<String, String> newPeerAddresses) {
1157 this.peerAddresses = newPeerAddresses;
1161 public T datastoreContext(final DatastoreContext newDatastoreContext) {
1163 this.datastoreContext = newDatastoreContext;
1167 public T schemaContextProvider(final EffectiveModelContextProvider newSchemaContextProvider) {
1169 this.schemaContextProvider = requireNonNull(newSchemaContextProvider);
1173 public T restoreFromSnapshot(final DatastoreSnapshot.ShardSnapshot newRestoreFromSnapshot) {
1175 this.restoreFromSnapshot = newRestoreFromSnapshot;
1179 public T dataTree(final DataTree newDataTree) {
1181 this.dataTree = newDataTree;
1185 public ShardIdentifier getId() {
1189 public Map<String, String> getPeerAddresses() {
1190 return peerAddresses;
1193 public DatastoreContext getDatastoreContext() {
1194 return datastoreContext;
1197 public EffectiveModelContext getSchemaContext() {
1198 return Verify.verifyNotNull(schemaContextProvider.getEffectiveModelContext());
1201 public DatastoreSnapshot.ShardSnapshot getRestoreFromSnapshot() {
1202 return restoreFromSnapshot;
1205 public DataTree getDataTree() {
1209 public TreeType getTreeType() {
1210 switch (datastoreContext.getLogicalStoreType()) {
1212 return TreeType.CONFIGURATION;
1214 return TreeType.OPERATIONAL;
1216 throw new IllegalStateException("Unhandled logical store type "
1217 + datastoreContext.getLogicalStoreType());
1221 protected void verify() {
1222 requireNonNull(id, "id should not be null");
1223 requireNonNull(peerAddresses, "peerAddresses should not be null");
1224 requireNonNull(datastoreContext, "dataStoreContext should not be null");
1225 requireNonNull(schemaContextProvider, "schemaContextProvider should not be null");
1228 public Props props() {
1231 return Props.create(shardClass, this);
1235 public static class Builder extends AbstractBuilder<Builder, Shard> {
1240 Builder(final Class<? extends Shard> shardClass) {
1246 return Ticker.systemTicker();
1249 void scheduleNextPendingTransaction() {
1250 self().tell(RESUME_NEXT_PENDING_TRANSACTION, ActorRef.noSender());