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 java.util.Objects.requireNonNull;
14 import akka.actor.ActorRef;
15 import akka.actor.ActorSelection;
16 import akka.actor.Cancellable;
17 import akka.actor.ExtendedActorSystem;
18 import akka.actor.Props;
19 import akka.actor.Status;
20 import akka.actor.Status.Failure;
21 import akka.serialization.JavaSerializer;
22 import akka.serialization.Serialization;
23 import com.google.common.annotations.VisibleForTesting;
24 import com.google.common.base.Ticker;
25 import com.google.common.base.Verify;
26 import com.google.common.collect.ImmutableList;
27 import com.google.common.collect.ImmutableMap;
28 import com.google.common.collect.ImmutableSet;
29 import com.google.common.collect.Range;
30 import java.io.IOException;
31 import java.util.Arrays;
32 import java.util.Collection;
33 import java.util.Collections;
34 import java.util.HashMap;
36 import java.util.Optional;
37 import java.util.OptionalLong;
38 import java.util.concurrent.TimeUnit;
39 import org.eclipse.jdt.annotation.NonNull;
40 import org.eclipse.jdt.annotation.Nullable;
41 import org.opendaylight.controller.cluster.access.ABIVersion;
42 import org.opendaylight.controller.cluster.access.commands.ConnectClientRequest;
43 import org.opendaylight.controller.cluster.access.commands.ConnectClientSuccess;
44 import org.opendaylight.controller.cluster.access.commands.LocalHistoryRequest;
45 import org.opendaylight.controller.cluster.access.commands.NotLeaderException;
46 import org.opendaylight.controller.cluster.access.commands.OutOfSequenceEnvelopeException;
47 import org.opendaylight.controller.cluster.access.commands.TransactionRequest;
48 import org.opendaylight.controller.cluster.access.concepts.ClientIdentifier;
49 import org.opendaylight.controller.cluster.access.concepts.FrontendIdentifier;
50 import org.opendaylight.controller.cluster.access.concepts.LocalHistoryIdentifier;
51 import org.opendaylight.controller.cluster.access.concepts.Request;
52 import org.opendaylight.controller.cluster.access.concepts.RequestEnvelope;
53 import org.opendaylight.controller.cluster.access.concepts.RequestException;
54 import org.opendaylight.controller.cluster.access.concepts.RequestSuccess;
55 import org.opendaylight.controller.cluster.access.concepts.RetiredGenerationException;
56 import org.opendaylight.controller.cluster.access.concepts.RuntimeRequestException;
57 import org.opendaylight.controller.cluster.access.concepts.SliceableMessage;
58 import org.opendaylight.controller.cluster.access.concepts.TransactionIdentifier;
59 import org.opendaylight.controller.cluster.access.concepts.UnsupportedRequestException;
60 import org.opendaylight.controller.cluster.common.actor.CommonConfig;
61 import org.opendaylight.controller.cluster.common.actor.Dispatchers;
62 import org.opendaylight.controller.cluster.common.actor.Dispatchers.DispatcherType;
63 import org.opendaylight.controller.cluster.common.actor.MessageTracker;
64 import org.opendaylight.controller.cluster.common.actor.MessageTracker.Error;
65 import org.opendaylight.controller.cluster.common.actor.MeteringBehavior;
66 import org.opendaylight.controller.cluster.datastore.exceptions.NoShardLeaderException;
67 import org.opendaylight.controller.cluster.datastore.identifiers.ShardIdentifier;
68 import org.opendaylight.controller.cluster.datastore.jmx.mbeans.shard.ShardDataTreeListenerInfoMXBeanImpl;
69 import org.opendaylight.controller.cluster.datastore.jmx.mbeans.shard.ShardMBeanFactory;
70 import org.opendaylight.controller.cluster.datastore.jmx.mbeans.shard.ShardStats;
71 import org.opendaylight.controller.cluster.datastore.messages.AbortTransaction;
72 import org.opendaylight.controller.cluster.datastore.messages.ActorInitialized;
73 import org.opendaylight.controller.cluster.datastore.messages.BatchedModifications;
74 import org.opendaylight.controller.cluster.datastore.messages.CanCommitTransaction;
75 import org.opendaylight.controller.cluster.datastore.messages.CloseTransactionChain;
76 import org.opendaylight.controller.cluster.datastore.messages.CommitTransaction;
77 import org.opendaylight.controller.cluster.datastore.messages.CreateTransaction;
78 import org.opendaylight.controller.cluster.datastore.messages.CreateTransactionReply;
79 import org.opendaylight.controller.cluster.datastore.messages.ForwardedReadyTransaction;
80 import org.opendaylight.controller.cluster.datastore.messages.GetKnownClients;
81 import org.opendaylight.controller.cluster.datastore.messages.GetKnownClientsReply;
82 import org.opendaylight.controller.cluster.datastore.messages.GetShardDataTree;
83 import org.opendaylight.controller.cluster.datastore.messages.MakeLeaderLocal;
84 import org.opendaylight.controller.cluster.datastore.messages.OnDemandShardState;
85 import org.opendaylight.controller.cluster.datastore.messages.PeerAddressResolved;
86 import org.opendaylight.controller.cluster.datastore.messages.ReadyLocalTransaction;
87 import org.opendaylight.controller.cluster.datastore.messages.RegisterDataTreeChangeListener;
88 import org.opendaylight.controller.cluster.datastore.messages.ShardLeaderStateChanged;
89 import org.opendaylight.controller.cluster.datastore.messages.UpdateSchemaContext;
90 import org.opendaylight.controller.cluster.datastore.persisted.DatastoreSnapshot;
91 import org.opendaylight.controller.cluster.datastore.persisted.DatastoreSnapshot.ShardSnapshot;
92 import org.opendaylight.controller.cluster.datastore.persisted.DisableTrackingPayload;
93 import org.opendaylight.controller.cluster.messaging.MessageAssembler;
94 import org.opendaylight.controller.cluster.messaging.MessageSlicer;
95 import org.opendaylight.controller.cluster.messaging.SliceOptions;
96 import org.opendaylight.controller.cluster.notifications.LeaderStateChanged;
97 import org.opendaylight.controller.cluster.notifications.RegisterRoleChangeListener;
98 import org.opendaylight.controller.cluster.notifications.RoleChangeNotifier;
99 import org.opendaylight.controller.cluster.raft.LeadershipTransferFailedException;
100 import org.opendaylight.controller.cluster.raft.RaftActor;
101 import org.opendaylight.controller.cluster.raft.RaftActorRecoveryCohort;
102 import org.opendaylight.controller.cluster.raft.RaftActorSnapshotCohort;
103 import org.opendaylight.controller.cluster.raft.RaftState;
104 import org.opendaylight.controller.cluster.raft.base.messages.FollowerInitialSyncUpStatus;
105 import org.opendaylight.controller.cluster.raft.client.messages.OnDemandRaftState;
106 import org.opendaylight.controller.cluster.raft.messages.AppendEntriesReply;
107 import org.opendaylight.controller.cluster.raft.messages.RequestLeadership;
108 import org.opendaylight.controller.cluster.raft.messages.ServerRemoved;
109 import org.opendaylight.controller.cluster.raft.protobuff.client.messages.Payload;
110 import org.opendaylight.yangtools.concepts.Identifier;
111 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTree;
112 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataValidationFailedException;
113 import org.opendaylight.yangtools.yang.data.api.schema.tree.TreeType;
114 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
115 import org.opendaylight.yangtools.yang.model.api.SchemaContextProvider;
116 import scala.concurrent.duration.FiniteDuration;
119 * A Shard represents a portion of the logical data tree.
122 * Our Shard uses InMemoryDataTree as it's internal representation and delegates all requests it
124 public class Shard extends RaftActor {
127 static final Object TX_COMMIT_TIMEOUT_CHECK_MESSAGE = new Object() {
129 public String toString() {
130 return "txCommitTimeoutCheck";
135 static final Object GET_SHARD_MBEAN_MESSAGE = new Object() {
137 public String toString() {
138 return "getShardMBeanMessage";
142 static final Object RESUME_NEXT_PENDING_TRANSACTION = new Object() {
144 public String toString() {
145 return "resumeNextPendingTransaction";
149 // FIXME: shard names should be encapsulated in their own class and this should be exposed as a constant.
150 public static final String DEFAULT_NAME = "default";
152 private static final Collection<ABIVersion> SUPPORTED_ABIVERSIONS;
155 final ABIVersion[] values = ABIVersion.values();
156 final ABIVersion[] real = Arrays.copyOfRange(values, 1, values.length - 1);
157 SUPPORTED_ABIVERSIONS = ImmutableList.copyOf(real).reverse();
160 // FIXME: make this a dynamic property based on mailbox size and maximum number of clients
161 private static final int CLIENT_MAX_MESSAGES = 1000;
163 // The state of this Shard
164 private final ShardDataTree store;
166 /// The name of this shard
167 private final String name;
169 private final String shardName;
171 private final ShardStats shardMBean;
173 private final ShardDataTreeListenerInfoMXBeanImpl listenerInfoMXBean;
175 private DatastoreContext datastoreContext;
177 private final ShardCommitCoordinator commitCoordinator;
179 private long transactionCommitTimeout;
181 private Cancellable txCommitTimeoutCheckSchedule;
183 private final Optional<ActorRef> roleChangeNotifier;
185 private final MessageTracker appendEntriesReplyTracker;
187 private final ShardTransactionActorFactory transactionActorFactory;
189 private final ShardSnapshotCohort snapshotCohort;
191 private final DataTreeChangeListenerSupport treeChangeSupport = new DataTreeChangeListenerSupport(this);
193 private ShardSnapshot restoreFromSnapshot;
195 private final ShardTransactionMessageRetrySupport messageRetrySupport;
198 final FrontendMetadata frontendMetadata;
200 private Map<FrontendIdentifier, LeaderFrontendState> knownFrontends = ImmutableMap.of();
201 private boolean paused;
203 private final MessageSlicer responseMessageSlicer;
204 private final Dispatchers dispatchers;
206 private final MessageAssembler requestMessageAssembler;
208 protected Shard(final AbstractBuilder<?, ?> builder) {
209 super(builder.getId().toString(), builder.getPeerAddresses(),
210 Optional.of(builder.getDatastoreContext().getShardRaftConfig()), DataStoreVersions.CURRENT_VERSION);
212 this.name = builder.getId().toString();
213 this.shardName = builder.getId().getShardName();
214 this.datastoreContext = builder.getDatastoreContext();
215 this.restoreFromSnapshot = builder.getRestoreFromSnapshot();
216 this.frontendMetadata = new FrontendMetadata(name);
218 setPersistence(datastoreContext.isPersistent());
220 LOG.info("Shard created : {}, persistent : {}", name, datastoreContext.isPersistent());
222 ShardDataTreeChangeListenerPublisherActorProxy treeChangeListenerPublisher =
223 new ShardDataTreeChangeListenerPublisherActorProxy(getContext(), name + "-DTCL-publisher", name);
224 if (builder.getDataTree() != null) {
225 store = new ShardDataTree(this, builder.getSchemaContext(), builder.getDataTree(),
226 treeChangeListenerPublisher, name, frontendMetadata);
228 store = new ShardDataTree(this, builder.getSchemaContext(), builder.getTreeType(),
229 builder.getDatastoreContext().getStoreRoot(), treeChangeListenerPublisher, name, frontendMetadata);
232 shardMBean = ShardMBeanFactory.getShardStatsMBean(name, datastoreContext.getDataStoreMXBeanType(), this);
234 if (isMetricsCaptureEnabled()) {
235 getContext().become(new MeteringBehavior(this));
238 commitCoordinator = new ShardCommitCoordinator(store, LOG, this.name);
240 setTransactionCommitTimeout();
242 // create a notifier actor for each cluster member
243 roleChangeNotifier = createRoleChangeNotifier(name);
245 appendEntriesReplyTracker = new MessageTracker(AppendEntriesReply.class,
246 getRaftActorContext().getConfigParams().getIsolatedCheckIntervalInMillis());
248 dispatchers = new Dispatchers(context().system().dispatchers());
249 transactionActorFactory = new ShardTransactionActorFactory(store, datastoreContext,
250 dispatchers.getDispatcherPath(Dispatchers.DispatcherType.Transaction),
251 self(), getContext(), shardMBean, builder.getId().getShardName());
253 snapshotCohort = ShardSnapshotCohort.create(getContext(), builder.getId().getMemberName(), store, LOG,
256 messageRetrySupport = new ShardTransactionMessageRetrySupport(this);
258 responseMessageSlicer = MessageSlicer.builder().logContext(this.name)
259 .messageSliceSize(datastoreContext.getMaximumMessageSliceSize())
260 .fileBackedStreamFactory(getRaftActorContext().getFileBackedOutputStreamFactory())
261 .expireStateAfterInactivity(2, TimeUnit.MINUTES).build();
263 requestMessageAssembler = MessageAssembler.builder().logContext(this.name)
264 .fileBackedStreamFactory(getRaftActorContext().getFileBackedOutputStreamFactory())
265 .assembledMessageCallback((message, sender) -> self().tell(message, sender))
266 .expireStateAfterInactivity(datastoreContext.getRequestTimeout(), TimeUnit.NANOSECONDS).build();
268 listenerInfoMXBean = new ShardDataTreeListenerInfoMXBeanImpl(name, datastoreContext.getDataStoreMXBeanType(),
270 listenerInfoMXBean.register();
273 private void setTransactionCommitTimeout() {
274 transactionCommitTimeout = TimeUnit.MILLISECONDS.convert(
275 datastoreContext.getShardTransactionCommitTimeoutInSeconds(), TimeUnit.SECONDS) / 2;
278 private Optional<ActorRef> createRoleChangeNotifier(final String shardId) {
279 ActorRef shardRoleChangeNotifier = this.getContext().actorOf(
280 RoleChangeNotifier.getProps(shardId), shardId + "-notifier");
281 return Optional.of(shardRoleChangeNotifier);
285 public void postStop() throws Exception {
286 LOG.info("Stopping Shard {}", persistenceId());
290 messageRetrySupport.close();
292 if (txCommitTimeoutCheckSchedule != null) {
293 txCommitTimeoutCheckSchedule.cancel();
296 commitCoordinator.abortPendingTransactions("Transaction aborted due to shutdown.", this);
298 shardMBean.unregisterMBean();
299 listenerInfoMXBean.unregister();
303 protected void handleRecover(final Object message) {
304 LOG.debug("{}: onReceiveRecover: Received message {} from {}", persistenceId(), message.getClass(),
307 super.handleRecover(message);
308 if (LOG.isTraceEnabled()) {
309 appendEntriesReplyTracker.begin();
314 protected void handleNonRaftCommand(final Object message) {
315 try (MessageTracker.Context context = appendEntriesReplyTracker.received(message)) {
316 final Optional<Error> maybeError = context.error();
317 if (maybeError.isPresent()) {
318 LOG.trace("{} : AppendEntriesReply failed to arrive at the expected interval {}", persistenceId(),
322 store.resetTransactionBatch();
324 if (message instanceof RequestEnvelope) {
325 handleRequestEnvelope((RequestEnvelope)message);
326 } else if (MessageAssembler.isHandledMessage(message)) {
327 handleRequestAssemblerMessage(message);
328 } else if (message instanceof ConnectClientRequest) {
329 handleConnectClient((ConnectClientRequest)message);
330 } else if (CreateTransaction.isSerializedType(message)) {
331 handleCreateTransaction(message);
332 } else if (message instanceof BatchedModifications) {
333 handleBatchedModifications((BatchedModifications)message);
334 } else if (message instanceof ForwardedReadyTransaction) {
335 handleForwardedReadyTransaction((ForwardedReadyTransaction) message);
336 } else if (message instanceof ReadyLocalTransaction) {
337 handleReadyLocalTransaction((ReadyLocalTransaction)message);
338 } else if (CanCommitTransaction.isSerializedType(message)) {
339 handleCanCommitTransaction(CanCommitTransaction.fromSerializable(message));
340 } else if (CommitTransaction.isSerializedType(message)) {
341 handleCommitTransaction(CommitTransaction.fromSerializable(message));
342 } else if (AbortTransaction.isSerializedType(message)) {
343 handleAbortTransaction(AbortTransaction.fromSerializable(message));
344 } else if (CloseTransactionChain.isSerializedType(message)) {
345 closeTransactionChain(CloseTransactionChain.fromSerializable(message));
346 } else if (message instanceof RegisterDataTreeChangeListener) {
347 treeChangeSupport.onMessage((RegisterDataTreeChangeListener) message, isLeader(), hasLeader());
348 } else if (message instanceof UpdateSchemaContext) {
349 updateSchemaContext((UpdateSchemaContext) message);
350 } else if (message instanceof PeerAddressResolved) {
351 PeerAddressResolved resolved = (PeerAddressResolved) message;
352 setPeerAddress(resolved.getPeerId(), resolved.getPeerAddress());
353 } else if (TX_COMMIT_TIMEOUT_CHECK_MESSAGE.equals(message)) {
354 commitTimeoutCheck();
355 } else if (message instanceof DatastoreContext) {
356 onDatastoreContext((DatastoreContext)message);
357 } else if (message instanceof RegisterRoleChangeListener) {
358 roleChangeNotifier.get().forward(message, context());
359 } else if (message instanceof FollowerInitialSyncUpStatus) {
360 shardMBean.setFollowerInitialSyncStatus(((FollowerInitialSyncUpStatus) message).isInitialSyncDone());
361 context().parent().tell(message, self());
362 } else if (GET_SHARD_MBEAN_MESSAGE.equals(message)) {
363 sender().tell(getShardMBean(), self());
364 } else if (message instanceof GetShardDataTree) {
365 sender().tell(store.getDataTree(), self());
366 } else if (message instanceof ServerRemoved) {
367 context().parent().forward(message, context());
368 } else if (ShardTransactionMessageRetrySupport.TIMER_MESSAGE_CLASS.isInstance(message)) {
369 messageRetrySupport.onTimerMessage(message);
370 } else if (message instanceof DataTreeCohortActorRegistry.CohortRegistryCommand) {
371 store.processCohortRegistryCommand(getSender(),
372 (DataTreeCohortActorRegistry.CohortRegistryCommand) message);
373 } else if (message instanceof MakeLeaderLocal) {
375 } else if (RESUME_NEXT_PENDING_TRANSACTION.equals(message)) {
376 store.resumeNextPendingTransaction();
377 } else if (GetKnownClients.INSTANCE.equals(message)) {
378 handleGetKnownClients();
379 } else if (!responseMessageSlicer.handleMessage(message)) {
380 super.handleNonRaftCommand(message);
385 private void handleRequestAssemblerMessage(final Object message) {
386 dispatchers.getDispatcher(DispatcherType.Serialization).execute(() -> {
387 JavaSerializer.currentSystem().value_$eq((ExtendedActorSystem) context().system());
388 requestMessageAssembler.handleMessage(message, self());
392 @SuppressWarnings("checkstyle:IllegalCatch")
393 private void handleRequestEnvelope(final RequestEnvelope envelope) {
394 final long now = ticker().read();
396 final RequestSuccess<?, ?> success = handleRequest(envelope, now);
397 if (success != null) {
398 final long executionTimeNanos = ticker().read() - now;
399 if (success instanceof SliceableMessage) {
400 dispatchers.getDispatcher(DispatcherType.Serialization).execute(() ->
401 responseMessageSlicer.slice(SliceOptions.builder().identifier(success.getTarget())
402 .message(envelope.newSuccessEnvelope(success, executionTimeNanos))
403 .sendTo(envelope.getMessage().getReplyTo()).replyTo(self())
404 .onFailureCallback(t -> LOG.warn("Error slicing response {}", success, t)).build()));
406 envelope.sendSuccess(success, executionTimeNanos);
409 } catch (RequestException e) {
410 LOG.debug("{}: request {} failed", persistenceId(), envelope, e);
411 envelope.sendFailure(e, ticker().read() - now);
412 } catch (Exception e) {
413 LOG.debug("{}: request {} caused failure", persistenceId(), envelope, e);
414 envelope.sendFailure(new RuntimeRequestException("Request failed to process", e),
415 ticker().read() - now);
419 private void commitTimeoutCheck() {
420 store.checkForExpiredTransactions(transactionCommitTimeout, this::updateAccess);
421 commitCoordinator.checkForExpiredTransactions(transactionCommitTimeout, this);
422 requestMessageAssembler.checkExpiredAssembledMessageState();
425 private OptionalLong updateAccess(final SimpleShardDataTreeCohort cohort) {
426 final FrontendIdentifier frontend = cohort.getIdentifier().getHistoryId().getClientId().getFrontendId();
427 final LeaderFrontendState state = knownFrontends.get(frontend);
429 // Not tell-based protocol, do nothing
430 return OptionalLong.empty();
433 if (isIsolatedLeader()) {
434 // We are isolated and no new request can come through until we emerge from it. We are still updating
435 // liveness of frontend when we see it attempting to communicate. Use the last access timer.
436 return OptionalLong.of(state.getLastSeenTicks());
439 // If this frontend has freshly connected, give it some time to catch up before killing its transactions.
440 return OptionalLong.of(state.getLastConnectTicks());
443 private void disableTracking(final DisableTrackingPayload payload) {
444 final ClientIdentifier clientId = payload.getIdentifier();
445 LOG.debug("{}: disabling tracking of {}", persistenceId(), clientId);
446 frontendMetadata.disableTracking(clientId);
449 final FrontendIdentifier frontendId = clientId.getFrontendId();
450 final LeaderFrontendState frontend = knownFrontends.get(frontendId);
451 if (frontend != null) {
452 if (clientId.equals(frontend.getIdentifier())) {
453 if (!(frontend instanceof LeaderFrontendState.Disabled)) {
454 verify(knownFrontends.replace(frontendId, frontend,
455 new LeaderFrontendState.Disabled(persistenceId(), clientId, store)));
456 LOG.debug("{}: leader state for {} disabled", persistenceId(), clientId);
458 LOG.debug("{}: leader state {} is already disabled", persistenceId(), frontend);
461 LOG.debug("{}: leader state {} does not match {}", persistenceId(), frontend, clientId);
464 LOG.debug("{}: leader state for {} not found", persistenceId(), clientId);
465 knownFrontends.put(frontendId, new LeaderFrontendState.Disabled(persistenceId(), clientId,
471 private void onMakeLeaderLocal() {
472 LOG.debug("{}: onMakeLeaderLocal received", persistenceId());
474 getSender().tell(new Status.Success(null), getSelf());
478 final ActorSelection leader = getLeader();
480 if (leader == null) {
481 // Leader is not present. The cluster is most likely trying to
482 // elect a leader and we should let that run its normal course
484 // TODO we can wait for the election to complete and retry the
485 // request. We can also let the caller retry by sending a flag
486 // in the response indicating the request is "reTryable".
487 getSender().tell(new Failure(
488 new LeadershipTransferFailedException("We cannot initiate leadership transfer to local node. "
489 + "Currently there is no leader for " + persistenceId())),
494 leader.tell(new RequestLeadership(getId(), getSender()), getSelf());
497 // Acquire our frontend tracking handle and verify generation matches
498 private @Nullable LeaderFrontendState findFrontend(final ClientIdentifier clientId) throws RequestException {
499 final LeaderFrontendState existing = knownFrontends.get(clientId.getFrontendId());
500 if (existing != null) {
501 final int cmp = Long.compareUnsigned(existing.getIdentifier().getGeneration(), clientId.getGeneration());
507 LOG.debug("{}: rejecting request from outdated client {}", persistenceId(), clientId);
508 throw new RetiredGenerationException(clientId.getGeneration(),
509 existing.getIdentifier().getGeneration());
512 LOG.info("{}: retiring state {}, outdated by request from client {}", persistenceId(), existing, clientId);
514 knownFrontends.remove(clientId.getFrontendId());
516 LOG.debug("{}: client {} is not yet known", persistenceId(), clientId);
522 private LeaderFrontendState getFrontend(final ClientIdentifier clientId) throws RequestException {
523 final LeaderFrontendState ret = findFrontend(clientId);
528 // TODO: a dedicated exception would be better, but this is technically true, too
529 throw new OutOfSequenceEnvelopeException(0);
532 private static @NonNull ABIVersion selectVersion(final ConnectClientRequest message) {
533 final Range<ABIVersion> clientRange = Range.closed(message.getMinVersion(), message.getMaxVersion());
534 for (ABIVersion v : SUPPORTED_ABIVERSIONS) {
535 if (clientRange.contains(v)) {
540 throw new IllegalArgumentException(String.format(
541 "No common version between backend versions %s and client versions %s", SUPPORTED_ABIVERSIONS,
545 @SuppressWarnings("checkstyle:IllegalCatch")
546 private void handleConnectClient(final ConnectClientRequest message) {
548 final ClientIdentifier clientId = message.getTarget();
549 final LeaderFrontendState existing = findFrontend(clientId);
550 if (existing != null) {
554 if (!isLeader() || !isLeaderActive()) {
555 LOG.info("{}: not currently leader, rejecting request {}. isLeader: {}, isLeaderActive: {},"
556 + "isLeadershipTransferInProgress: {}.",
557 persistenceId(), message, isLeader(), isLeaderActive(), isLeadershipTransferInProgress());
558 throw new NotLeaderException(getSelf());
561 final ABIVersion selectedVersion = selectVersion(message);
562 final LeaderFrontendState frontend;
563 if (existing == null) {
564 frontend = new LeaderFrontendState.Enabled(persistenceId(), clientId, store);
565 knownFrontends.put(clientId.getFrontendId(), frontend);
566 LOG.debug("{}: created state {} for client {}", persistenceId(), frontend, clientId);
571 frontend.reconnect();
572 message.getReplyTo().tell(new ConnectClientSuccess(message.getTarget(), message.getSequence(), getSelf(),
573 ImmutableList.of(), store.getDataTree(), CLIENT_MAX_MESSAGES).toVersion(selectedVersion),
574 ActorRef.noSender());
575 } catch (RequestException | RuntimeException e) {
576 message.getReplyTo().tell(new Failure(e), ActorRef.noSender());
580 private @Nullable RequestSuccess<?, ?> handleRequest(final RequestEnvelope envelope, final long now)
581 throws RequestException {
582 // We are not the leader, hence we want to fail-fast.
583 if (!isLeader() || paused || !isLeaderActive()) {
584 LOG.debug("{}: not currently active leader, rejecting request {}. isLeader: {}, isLeaderActive: {},"
585 + "isLeadershipTransferInProgress: {}, paused: {}",
586 persistenceId(), envelope, isLeader(), isLeaderActive(), isLeadershipTransferInProgress(), paused);
587 throw new NotLeaderException(getSelf());
590 final Request<?, ?> request = envelope.getMessage();
591 if (request instanceof TransactionRequest) {
592 final TransactionRequest<?> txReq = (TransactionRequest<?>)request;
593 final ClientIdentifier clientId = txReq.getTarget().getHistoryId().getClientId();
594 return getFrontend(clientId).handleTransactionRequest(txReq, envelope, now);
595 } else if (request instanceof LocalHistoryRequest) {
596 final LocalHistoryRequest<?> lhReq = (LocalHistoryRequest<?>)request;
597 final ClientIdentifier clientId = lhReq.getTarget().getClientId();
598 return getFrontend(clientId).handleLocalHistoryRequest(lhReq, envelope, now);
600 LOG.warn("{}: rejecting unsupported request {}", persistenceId(), request);
601 throw new UnsupportedRequestException(request);
605 private void handleGetKnownClients() {
606 final ImmutableSet<ClientIdentifier> clients;
608 clients = knownFrontends.values().stream()
609 .map(LeaderFrontendState::getIdentifier)
610 .collect(ImmutableSet.toImmutableSet());
612 clients = frontendMetadata.getClients();
614 sender().tell(new GetKnownClientsReply(clients), self());
617 private boolean hasLeader() {
618 return getLeaderId() != null;
621 public int getPendingTxCommitQueueSize() {
622 return store.getQueueSize();
625 public int getCohortCacheSize() {
626 return commitCoordinator.getCohortCacheSize();
630 protected Optional<ActorRef> getRoleChangeNotifier() {
631 return roleChangeNotifier;
634 String getShardName() {
639 protected LeaderStateChanged newLeaderStateChanged(final String memberId, final String leaderId,
640 final short leaderPayloadVersion) {
641 return isLeader() ? new ShardLeaderStateChanged(memberId, leaderId, store.getDataTree(), leaderPayloadVersion)
642 : new ShardLeaderStateChanged(memberId, leaderId, leaderPayloadVersion);
645 protected void onDatastoreContext(final DatastoreContext context) {
646 datastoreContext = context;
648 setTransactionCommitTimeout();
650 setPersistence(datastoreContext.isPersistent());
652 updateConfigParams(datastoreContext.getShardRaftConfig());
655 // applyState() will be invoked once consensus is reached on the payload
656 void persistPayload(final Identifier id, final Payload payload, final boolean batchHint) {
657 boolean canSkipPayload = !hasFollowers() && !persistence().isRecoveryApplicable();
658 if (canSkipPayload) {
659 applyState(self(), id, payload);
661 // We are faking the sender
662 persistData(self(), id, payload, batchHint);
666 private void handleCommitTransaction(final CommitTransaction commit) {
667 final TransactionIdentifier txId = commit.getTransactionId();
669 askProtocolEncountered(txId);
670 commitCoordinator.handleCommit(txId, getSender(), this);
672 ActorSelection leader = getLeader();
673 if (leader == null) {
674 messageRetrySupport.addMessageToRetry(commit, getSender(), "Could not commit transaction " + txId);
676 LOG.debug("{}: Forwarding CommitTransaction to leader {}", persistenceId(), leader);
677 leader.forward(commit, getContext());
682 private void handleCanCommitTransaction(final CanCommitTransaction canCommit) {
683 final TransactionIdentifier txId = canCommit.getTransactionId();
684 LOG.debug("{}: Can committing transaction {}", persistenceId(), txId);
687 askProtocolEncountered(txId);
688 commitCoordinator.handleCanCommit(txId, getSender(), this);
690 ActorSelection leader = getLeader();
691 if (leader == null) {
692 messageRetrySupport.addMessageToRetry(canCommit, getSender(),
693 "Could not canCommit transaction " + txId);
695 LOG.debug("{}: Forwarding CanCommitTransaction to leader {}", persistenceId(), leader);
696 leader.forward(canCommit, getContext());
701 @SuppressWarnings("checkstyle:IllegalCatch")
702 protected void handleBatchedModificationsLocal(final BatchedModifications batched, final ActorRef sender) {
703 askProtocolEncountered(batched.getTransactionId());
706 commitCoordinator.handleBatchedModifications(batched, sender, this);
707 } catch (Exception e) {
708 LOG.error("{}: Error handling BatchedModifications for Tx {}", persistenceId(),
709 batched.getTransactionId(), e);
710 sender.tell(new Failure(e), getSelf());
714 private void handleBatchedModifications(final BatchedModifications batched) {
715 // This message is sent to prepare the modifications transaction directly on the Shard as an
716 // optimization to avoid the extra overhead of a separate ShardTransaction actor. On the last
717 // BatchedModifications message, the caller sets the ready flag in the message indicating
718 // modifications are complete. The reply contains the cohort actor path (this actor) for the caller
719 // to initiate the 3-phase commit. This also avoids the overhead of sending an additional
720 // ReadyTransaction message.
722 // If we're not the leader then forward to the leader. This is a safety measure - we shouldn't
723 // normally get here if we're not the leader as the front-end (TransactionProxy) should determine
724 // the primary/leader shard. However with timing and caching on the front-end, there's a small
725 // window where it could have a stale leader during leadership transitions.
727 boolean isLeaderActive = isLeaderActive();
728 if (isLeader() && isLeaderActive) {
729 handleBatchedModificationsLocal(batched, getSender());
731 ActorSelection leader = getLeader();
732 if (!isLeaderActive || leader == null) {
733 messageRetrySupport.addMessageToRetry(batched, getSender(),
734 "Could not process BatchedModifications " + batched.getTransactionId());
736 // If this is not the first batch and leadership changed in between batched messages,
737 // we need to reconstruct previous BatchedModifications from the transaction
738 // DataTreeModification, honoring the max batched modification count, and forward all the
739 // previous BatchedModifications to the new leader.
740 Collection<BatchedModifications> newModifications = commitCoordinator
741 .createForwardedBatchedModifications(batched,
742 datastoreContext.getShardBatchedModificationCount());
744 LOG.debug("{}: Forwarding {} BatchedModifications to leader {}", persistenceId(),
745 newModifications.size(), leader);
747 for (BatchedModifications bm : newModifications) {
748 leader.forward(bm, getContext());
754 private boolean failIfIsolatedLeader(final ActorRef sender) {
755 if (isIsolatedLeader()) {
756 sender.tell(new Failure(new NoShardLeaderException(String.format(
757 "Shard %s was the leader but has lost contact with all of its followers. Either all"
758 + " other follower nodes are down or this node is isolated by a network partition.",
759 persistenceId()))), getSelf());
766 protected boolean isIsolatedLeader() {
767 return getRaftState() == RaftState.IsolatedLeader;
770 @SuppressWarnings("checkstyle:IllegalCatch")
771 private void handleReadyLocalTransaction(final ReadyLocalTransaction message) {
772 LOG.debug("{}: handleReadyLocalTransaction for {}", persistenceId(), message.getTransactionId());
774 boolean isLeaderActive = isLeaderActive();
775 if (isLeader() && isLeaderActive) {
777 commitCoordinator.handleReadyLocalTransaction(message, getSender(), this);
778 } catch (Exception e) {
779 LOG.error("{}: Error handling ReadyLocalTransaction for Tx {}", persistenceId(),
780 message.getTransactionId(), e);
781 getSender().tell(new Failure(e), getSelf());
784 ActorSelection leader = getLeader();
785 if (!isLeaderActive || leader == null) {
786 messageRetrySupport.addMessageToRetry(message, getSender(),
787 "Could not process ready local transaction " + message.getTransactionId());
789 LOG.debug("{}: Forwarding ReadyLocalTransaction to leader {}", persistenceId(), leader);
790 message.setRemoteVersion(getCurrentBehavior().getLeaderPayloadVersion());
791 leader.forward(message, getContext());
796 private void handleForwardedReadyTransaction(final ForwardedReadyTransaction forwardedReady) {
797 LOG.debug("{}: handleForwardedReadyTransaction for {}", persistenceId(), forwardedReady.getTransactionId());
799 boolean isLeaderActive = isLeaderActive();
800 if (isLeader() && isLeaderActive) {
801 askProtocolEncountered(forwardedReady.getTransactionId());
802 commitCoordinator.handleForwardedReadyTransaction(forwardedReady, getSender(), this);
804 ActorSelection leader = getLeader();
805 if (!isLeaderActive || leader == null) {
806 messageRetrySupport.addMessageToRetry(forwardedReady, getSender(),
807 "Could not process forwarded ready transaction " + forwardedReady.getTransactionId());
809 LOG.debug("{}: Forwarding ForwardedReadyTransaction to leader {}", persistenceId(), leader);
811 ReadyLocalTransaction readyLocal = new ReadyLocalTransaction(forwardedReady.getTransactionId(),
812 forwardedReady.getTransaction().getSnapshot(), forwardedReady.isDoImmediateCommit(),
813 forwardedReady.getParticipatingShardNames());
814 readyLocal.setRemoteVersion(getCurrentBehavior().getLeaderPayloadVersion());
815 leader.forward(readyLocal, getContext());
820 private void handleAbortTransaction(final AbortTransaction abort) {
821 final TransactionIdentifier transactionId = abort.getTransactionId();
822 askProtocolEncountered(transactionId);
823 doAbortTransaction(transactionId, getSender());
826 void doAbortTransaction(final Identifier transactionID, final ActorRef sender) {
827 commitCoordinator.handleAbort(transactionID, sender, this);
830 private void handleCreateTransaction(final Object message) {
832 createTransaction(CreateTransaction.fromSerializable(message));
833 } else if (getLeader() != null) {
834 getLeader().forward(message, getContext());
836 getSender().tell(new Failure(new NoShardLeaderException(
837 "Could not create a shard transaction", persistenceId())), getSelf());
841 private void closeTransactionChain(final CloseTransactionChain closeTransactionChain) {
843 final LocalHistoryIdentifier id = closeTransactionChain.getIdentifier();
844 askProtocolEncountered(id.getClientId());
845 store.closeTransactionChain(id);
846 } else if (getLeader() != null) {
847 getLeader().forward(closeTransactionChain, getContext());
849 LOG.warn("{}: Could not close transaction {}", persistenceId(), closeTransactionChain.getIdentifier());
853 @SuppressWarnings("checkstyle:IllegalCatch")
854 private void createTransaction(final CreateTransaction createTransaction) {
855 askProtocolEncountered(createTransaction.getTransactionId());
858 if (TransactionType.fromInt(createTransaction.getTransactionType()) != TransactionType.READ_ONLY
859 && failIfIsolatedLeader(getSender())) {
863 ActorRef transactionActor = createTransaction(createTransaction.getTransactionType(),
864 createTransaction.getTransactionId());
866 getSender().tell(new CreateTransactionReply(Serialization.serializedActorPath(transactionActor),
867 createTransaction.getTransactionId(), createTransaction.getVersion()).toSerializable(), getSelf());
868 } catch (Exception e) {
869 getSender().tell(new Failure(e), getSelf());
873 private ActorRef createTransaction(final int transactionType, final TransactionIdentifier transactionId) {
874 LOG.debug("{}: Creating transaction : {} ", persistenceId(), transactionId);
875 return transactionActorFactory.newShardTransaction(TransactionType.fromInt(transactionType),
879 // Called on leader only
880 private void askProtocolEncountered(final TransactionIdentifier transactionId) {
881 askProtocolEncountered(transactionId.getHistoryId().getClientId());
884 // Called on leader only
885 private void askProtocolEncountered(final ClientIdentifier clientId) {
886 final FrontendIdentifier frontend = clientId.getFrontendId();
887 final LeaderFrontendState state = knownFrontends.get(frontend);
888 if (!(state instanceof LeaderFrontendState.Disabled)) {
889 LOG.debug("{}: encountered ask-based client {}, disabling transaction tracking", persistenceId(), clientId);
890 if (knownFrontends.isEmpty()) {
891 knownFrontends = new HashMap<>();
893 knownFrontends.put(frontend, new LeaderFrontendState.Disabled(persistenceId(), clientId, getDataStore()));
895 persistPayload(clientId, DisableTrackingPayload.create(clientId,
896 datastoreContext.getInitialPayloadSerializedBufferCapacity()), false);
900 private void updateSchemaContext(final UpdateSchemaContext message) {
901 updateSchemaContext(message.getSchemaContext());
905 void updateSchemaContext(final SchemaContext schemaContext) {
906 store.updateSchemaContext(schemaContext);
909 private boolean isMetricsCaptureEnabled() {
910 CommonConfig config = new CommonConfig(getContext().system().settings().config());
911 return config.isMetricCaptureEnabled();
916 public RaftActorSnapshotCohort getRaftActorSnapshotCohort() {
917 return snapshotCohort;
921 protected RaftActorRecoveryCohort getRaftActorRecoveryCohort() {
922 if (restoreFromSnapshot == null) {
923 return ShardRecoveryCoordinator.create(store, persistenceId(), LOG);
926 return ShardRecoveryCoordinator.forSnapshot(store, persistenceId(), LOG, restoreFromSnapshot.getSnapshot());
930 protected void onRecoveryComplete() {
931 restoreFromSnapshot = null;
933 //notify shard manager
934 getContext().parent().tell(new ActorInitialized(), getSelf());
936 // Being paranoid here - this method should only be called once but just in case...
937 if (txCommitTimeoutCheckSchedule == null) {
938 // Schedule a message to be periodically sent to check if the current in-progress
939 // transaction should be expired and aborted.
940 FiniteDuration period = FiniteDuration.create(transactionCommitTimeout / 3, TimeUnit.MILLISECONDS);
941 txCommitTimeoutCheckSchedule = getContext().system().scheduler().schedule(
942 period, period, getSelf(),
943 TX_COMMIT_TIMEOUT_CHECK_MESSAGE, getContext().dispatcher(), ActorRef.noSender());
948 protected void applyState(final ActorRef clientActor, final Identifier identifier, final Object data) {
949 if (data instanceof Payload) {
950 if (data instanceof DisableTrackingPayload) {
951 disableTracking((DisableTrackingPayload) data);
956 store.applyReplicatedPayload(identifier, (Payload)data);
957 } catch (DataValidationFailedException | IOException e) {
958 LOG.error("{}: Error applying replica {}", persistenceId(), identifier, e);
961 LOG.error("{}: Unknown state for {} received {}", persistenceId(), identifier, data);
966 protected void onStateChanged() {
967 boolean isLeader = isLeader();
968 boolean hasLeader = hasLeader();
969 treeChangeSupport.onLeadershipChange(isLeader, hasLeader);
971 // If this actor is no longer the leader close all the transaction chains
973 if (LOG.isDebugEnabled()) {
975 "{}: onStateChanged: Closing all transaction chains because shard {} is no longer the leader",
976 persistenceId(), getId());
980 store.purgeLeaderState();
983 if (hasLeader && !isIsolatedLeader()) {
984 messageRetrySupport.retryMessages();
989 protected void onLeaderChanged(final String oldLeader, final String newLeader) {
990 shardMBean.incrementLeadershipChangeCount();
994 if (!knownFrontends.isEmpty()) {
995 LOG.debug("{}: removing frontend state for {}", persistenceId(), knownFrontends.keySet());
996 knownFrontends = ImmutableMap.of();
999 requestMessageAssembler.close();
1002 // No leader anywhere, nothing else to do
1006 // Another leader was elected. If we were the previous leader and had pending transactions, convert
1007 // them to transaction messages and send to the new leader.
1008 ActorSelection leader = getLeader();
1009 if (leader != null) {
1010 Collection<?> messagesToForward = convertPendingTransactionsToMessages();
1012 if (!messagesToForward.isEmpty()) {
1013 LOG.debug("{}: Forwarding {} pending transaction messages to leader {}", persistenceId(),
1014 messagesToForward.size(), leader);
1016 for (Object message : messagesToForward) {
1017 LOG.debug("{}: Forwarding pending transaction message {}", persistenceId(), message);
1019 leader.tell(message, self());
1023 commitCoordinator.abortPendingTransactions("The transacton was aborted due to inflight leadership "
1024 + "change and the leader address isn't available.", this);
1027 // We have become the leader, we need to reconstruct frontend state
1028 knownFrontends = Verify.verifyNotNull(frontendMetadata.toLeaderState(this));
1029 LOG.debug("{}: became leader with frontend state for {}", persistenceId(), knownFrontends.keySet());
1032 if (!isIsolatedLeader()) {
1033 messageRetrySupport.retryMessages();
1038 * Clears all pending transactions and converts them to messages to be forwarded to a new leader.
1040 * @return the converted messages
1042 public Collection<?> convertPendingTransactionsToMessages() {
1043 return commitCoordinator.convertPendingTransactionsToMessages(
1044 datastoreContext.getShardBatchedModificationCount());
1048 protected void pauseLeader(final Runnable operation) {
1049 LOG.debug("{}: In pauseLeader, operation: {}", persistenceId(), operation);
1052 // Tell-based protocol can replay transaction state, so it is safe to blow it up when we are paused.
1053 if (datastoreContext.isUseTellBasedProtocol()) {
1054 knownFrontends.values().forEach(LeaderFrontendState::retire);
1055 knownFrontends = ImmutableMap.of();
1058 store.setRunOnPendingTransactionsComplete(operation);
1062 protected void unpauseLeader() {
1063 LOG.debug("{}: In unpauseLeader", persistenceId());
1066 store.setRunOnPendingTransactionsComplete(null);
1068 // Restore tell-based protocol state as if we were becoming the leader
1069 knownFrontends = Verify.verifyNotNull(frontendMetadata.toLeaderState(this));
1073 protected OnDemandRaftState.AbstractBuilder<?, ?> newOnDemandRaftStateBuilder() {
1074 return OnDemandShardState.newBuilder().treeChangeListenerActors(treeChangeSupport.getListenerActors())
1075 .commitCohortActors(store.getCohortActors());
1079 public String persistenceId() {
1084 ShardCommitCoordinator getCommitCoordinator() {
1085 return commitCoordinator;
1088 public DatastoreContext getDatastoreContext() {
1089 return datastoreContext;
1093 public ShardDataTree getDataStore() {
1098 ShardStats getShardMBean() {
1102 public static Builder builder() {
1103 return new Builder();
1106 public abstract static class AbstractBuilder<T extends AbstractBuilder<T, S>, S extends Shard> {
1107 private final Class<? extends S> shardClass;
1108 private ShardIdentifier id;
1109 private Map<String, String> peerAddresses = Collections.emptyMap();
1110 private DatastoreContext datastoreContext;
1111 private SchemaContextProvider schemaContextProvider;
1112 private DatastoreSnapshot.ShardSnapshot restoreFromSnapshot;
1113 private DataTree dataTree;
1115 private volatile boolean sealed;
1117 protected AbstractBuilder(final Class<? extends S> shardClass) {
1118 this.shardClass = shardClass;
1121 protected void checkSealed() {
1122 checkState(!sealed, "Builder isalready sealed - further modifications are not allowed");
1125 @SuppressWarnings("unchecked")
1130 public T id(final ShardIdentifier newId) {
1136 public T peerAddresses(final Map<String, String> newPeerAddresses) {
1138 this.peerAddresses = newPeerAddresses;
1142 public T datastoreContext(final DatastoreContext newDatastoreContext) {
1144 this.datastoreContext = newDatastoreContext;
1148 public T schemaContextProvider(final SchemaContextProvider newSchemaContextProvider) {
1150 this.schemaContextProvider = requireNonNull(newSchemaContextProvider);
1154 public T restoreFromSnapshot(final DatastoreSnapshot.ShardSnapshot newRestoreFromSnapshot) {
1156 this.restoreFromSnapshot = newRestoreFromSnapshot;
1160 public T dataTree(final DataTree newDataTree) {
1162 this.dataTree = newDataTree;
1166 public ShardIdentifier getId() {
1170 public Map<String, String> getPeerAddresses() {
1171 return peerAddresses;
1174 public DatastoreContext getDatastoreContext() {
1175 return datastoreContext;
1178 public SchemaContext getSchemaContext() {
1179 return Verify.verifyNotNull(schemaContextProvider.getSchemaContext());
1182 public DatastoreSnapshot.ShardSnapshot getRestoreFromSnapshot() {
1183 return restoreFromSnapshot;
1186 public DataTree getDataTree() {
1190 public TreeType getTreeType() {
1191 switch (datastoreContext.getLogicalStoreType()) {
1193 return TreeType.CONFIGURATION;
1195 return TreeType.OPERATIONAL;
1197 throw new IllegalStateException("Unhandled logical store type "
1198 + datastoreContext.getLogicalStoreType());
1202 protected void verify() {
1203 requireNonNull(id, "id should not be null");
1204 requireNonNull(peerAddresses, "peerAddresses should not be null");
1205 requireNonNull(datastoreContext, "dataStoreContext should not be null");
1206 requireNonNull(schemaContextProvider, "schemaContextProvider should not be null");
1209 public Props props() {
1212 return Props.create(shardClass, this);
1216 public static class Builder extends AbstractBuilder<Builder, Shard> {
1221 Builder(final Class<? extends Shard> shardClass) {
1227 return Ticker.systemTicker();
1230 void scheduleNextPendingTransaction() {
1231 self().tell(RESUME_NEXT_PENDING_TRANSACTION, ActorRef.noSender());