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.EffectiveModelContext;
115 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContextProvider;
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,
229 store = new ShardDataTree(this, builder.getSchemaContext(), builder.getTreeType(),
230 builder.getDatastoreContext().getStoreRoot(), treeChangeListenerPublisher, name,
234 shardMBean = ShardMBeanFactory.getShardStatsMBean(name, datastoreContext.getDataStoreMXBeanType(), this);
236 if (isMetricsCaptureEnabled()) {
237 getContext().become(new MeteringBehavior(this));
240 commitCoordinator = new ShardCommitCoordinator(store, LOG, this.name);
242 setTransactionCommitTimeout();
244 // create a notifier actor for each cluster member
245 roleChangeNotifier = createRoleChangeNotifier(name);
247 appendEntriesReplyTracker = new MessageTracker(AppendEntriesReply.class,
248 getRaftActorContext().getConfigParams().getIsolatedCheckIntervalInMillis());
250 dispatchers = new Dispatchers(context().system().dispatchers());
251 transactionActorFactory = new ShardTransactionActorFactory(store, datastoreContext,
252 dispatchers.getDispatcherPath(Dispatchers.DispatcherType.Transaction),
253 self(), getContext(), shardMBean, builder.getId().getShardName());
255 snapshotCohort = ShardSnapshotCohort.create(getContext(), builder.getId().getMemberName(), store, LOG,
258 messageRetrySupport = new ShardTransactionMessageRetrySupport(this);
260 responseMessageSlicer = MessageSlicer.builder().logContext(this.name)
261 .messageSliceSize(datastoreContext.getMaximumMessageSliceSize())
262 .fileBackedStreamFactory(getRaftActorContext().getFileBackedOutputStreamFactory())
263 .expireStateAfterInactivity(2, TimeUnit.MINUTES).build();
265 requestMessageAssembler = MessageAssembler.builder().logContext(this.name)
266 .fileBackedStreamFactory(getRaftActorContext().getFileBackedOutputStreamFactory())
267 .assembledMessageCallback((message, sender) -> self().tell(message, sender))
268 .expireStateAfterInactivity(datastoreContext.getRequestTimeout(), TimeUnit.NANOSECONDS).build();
270 listenerInfoMXBean = new ShardDataTreeListenerInfoMXBeanImpl(name, datastoreContext.getDataStoreMXBeanType(),
272 listenerInfoMXBean.register();
275 private void setTransactionCommitTimeout() {
276 transactionCommitTimeout = TimeUnit.MILLISECONDS.convert(
277 datastoreContext.getShardTransactionCommitTimeoutInSeconds(), TimeUnit.SECONDS) / 2;
280 private Optional<ActorRef> createRoleChangeNotifier(final String shardId) {
281 ActorRef shardRoleChangeNotifier = this.getContext().actorOf(
282 RoleChangeNotifier.getProps(shardId), shardId + "-notifier");
283 return Optional.of(shardRoleChangeNotifier);
287 public void postStop() throws Exception {
288 LOG.info("Stopping Shard {}", persistenceId());
292 messageRetrySupport.close();
294 if (txCommitTimeoutCheckSchedule != null) {
295 txCommitTimeoutCheckSchedule.cancel();
298 commitCoordinator.abortPendingTransactions("Transaction aborted due to shutdown.", this);
300 shardMBean.unregisterMBean();
301 listenerInfoMXBean.unregister();
305 protected void handleRecover(final Object message) {
306 LOG.debug("{}: onReceiveRecover: Received message {} from {}", persistenceId(), message.getClass(),
309 super.handleRecover(message);
310 if (LOG.isTraceEnabled()) {
311 appendEntriesReplyTracker.begin();
316 protected void handleNonRaftCommand(final Object message) {
317 try (MessageTracker.Context context = appendEntriesReplyTracker.received(message)) {
318 final Optional<Error> maybeError = context.error();
319 if (maybeError.isPresent()) {
320 LOG.trace("{} : AppendEntriesReply failed to arrive at the expected interval {}", persistenceId(),
324 store.resetTransactionBatch();
326 if (message instanceof RequestEnvelope) {
327 handleRequestEnvelope((RequestEnvelope)message);
328 } else if (MessageAssembler.isHandledMessage(message)) {
329 handleRequestAssemblerMessage(message);
330 } else if (message instanceof ConnectClientRequest) {
331 handleConnectClient((ConnectClientRequest)message);
332 } else if (CreateTransaction.isSerializedType(message)) {
333 handleCreateTransaction(message);
334 } else if (message instanceof BatchedModifications) {
335 handleBatchedModifications((BatchedModifications)message);
336 } else if (message instanceof ForwardedReadyTransaction) {
337 handleForwardedReadyTransaction((ForwardedReadyTransaction) message);
338 } else if (message instanceof ReadyLocalTransaction) {
339 handleReadyLocalTransaction((ReadyLocalTransaction)message);
340 } else if (CanCommitTransaction.isSerializedType(message)) {
341 handleCanCommitTransaction(CanCommitTransaction.fromSerializable(message));
342 } else if (CommitTransaction.isSerializedType(message)) {
343 handleCommitTransaction(CommitTransaction.fromSerializable(message));
344 } else if (AbortTransaction.isSerializedType(message)) {
345 handleAbortTransaction(AbortTransaction.fromSerializable(message));
346 } else if (CloseTransactionChain.isSerializedType(message)) {
347 closeTransactionChain(CloseTransactionChain.fromSerializable(message));
348 } else if (message instanceof RegisterDataTreeChangeListener) {
349 treeChangeSupport.onMessage((RegisterDataTreeChangeListener) message, isLeader(), hasLeader());
350 } else if (message instanceof UpdateSchemaContext) {
351 updateSchemaContext((UpdateSchemaContext) message);
352 } else if (message instanceof PeerAddressResolved) {
353 PeerAddressResolved resolved = (PeerAddressResolved) message;
354 setPeerAddress(resolved.getPeerId(), resolved.getPeerAddress());
355 } else if (TX_COMMIT_TIMEOUT_CHECK_MESSAGE.equals(message)) {
356 commitTimeoutCheck();
357 } else if (message instanceof DatastoreContext) {
358 onDatastoreContext((DatastoreContext)message);
359 } else if (message instanceof RegisterRoleChangeListener) {
360 roleChangeNotifier.get().forward(message, context());
361 } else if (message instanceof FollowerInitialSyncUpStatus) {
362 shardMBean.setFollowerInitialSyncStatus(((FollowerInitialSyncUpStatus) message).isInitialSyncDone());
363 context().parent().tell(message, self());
364 } else if (GET_SHARD_MBEAN_MESSAGE.equals(message)) {
365 sender().tell(getShardMBean(), self());
366 } else if (message instanceof GetShardDataTree) {
367 sender().tell(store.getDataTree(), self());
368 } else if (message instanceof ServerRemoved) {
369 context().parent().forward(message, context());
370 } else if (ShardTransactionMessageRetrySupport.TIMER_MESSAGE_CLASS.isInstance(message)) {
371 messageRetrySupport.onTimerMessage(message);
372 } else if (message instanceof DataTreeCohortActorRegistry.CohortRegistryCommand) {
373 store.processCohortRegistryCommand(getSender(),
374 (DataTreeCohortActorRegistry.CohortRegistryCommand) message);
375 } else if (message instanceof MakeLeaderLocal) {
377 } else if (RESUME_NEXT_PENDING_TRANSACTION.equals(message)) {
378 store.resumeNextPendingTransaction();
379 } else if (GetKnownClients.INSTANCE.equals(message)) {
380 handleGetKnownClients();
381 } else if (!responseMessageSlicer.handleMessage(message)) {
382 super.handleNonRaftCommand(message);
387 private void handleRequestAssemblerMessage(final Object message) {
388 dispatchers.getDispatcher(DispatcherType.Serialization).execute(() -> {
389 JavaSerializer.currentSystem().value_$eq((ExtendedActorSystem) context().system());
390 requestMessageAssembler.handleMessage(message, self());
394 @SuppressWarnings("checkstyle:IllegalCatch")
395 private void handleRequestEnvelope(final RequestEnvelope envelope) {
396 final long now = ticker().read();
398 final RequestSuccess<?, ?> success = handleRequest(envelope, now);
399 if (success != null) {
400 final long executionTimeNanos = ticker().read() - now;
401 if (success instanceof SliceableMessage) {
402 dispatchers.getDispatcher(DispatcherType.Serialization).execute(() ->
403 responseMessageSlicer.slice(SliceOptions.builder().identifier(success.getTarget())
404 .message(envelope.newSuccessEnvelope(success, executionTimeNanos))
405 .sendTo(envelope.getMessage().getReplyTo()).replyTo(self())
406 .onFailureCallback(t -> LOG.warn("Error slicing response {}", success, t)).build()));
408 envelope.sendSuccess(success, executionTimeNanos);
411 } catch (RequestException e) {
412 LOG.debug("{}: request {} failed", persistenceId(), envelope, e);
413 envelope.sendFailure(e, ticker().read() - now);
414 } catch (Exception e) {
415 LOG.debug("{}: request {} caused failure", persistenceId(), envelope, e);
416 envelope.sendFailure(new RuntimeRequestException("Request failed to process", e),
417 ticker().read() - now);
421 private void commitTimeoutCheck() {
422 store.checkForExpiredTransactions(transactionCommitTimeout, this::updateAccess);
423 commitCoordinator.checkForExpiredTransactions(transactionCommitTimeout, this);
424 requestMessageAssembler.checkExpiredAssembledMessageState();
427 private OptionalLong updateAccess(final SimpleShardDataTreeCohort cohort) {
428 final FrontendIdentifier frontend = cohort.getIdentifier().getHistoryId().getClientId().getFrontendId();
429 final LeaderFrontendState state = knownFrontends.get(frontend);
431 // Not tell-based protocol, do nothing
432 return OptionalLong.empty();
435 if (isIsolatedLeader()) {
436 // We are isolated and no new request can come through until we emerge from it. We are still updating
437 // liveness of frontend when we see it attempting to communicate. Use the last access timer.
438 return OptionalLong.of(state.getLastSeenTicks());
441 // If this frontend has freshly connected, give it some time to catch up before killing its transactions.
442 return OptionalLong.of(state.getLastConnectTicks());
445 private void disableTracking(final DisableTrackingPayload payload) {
446 final ClientIdentifier clientId = payload.getIdentifier();
447 LOG.debug("{}: disabling tracking of {}", persistenceId(), clientId);
448 frontendMetadata.disableTracking(clientId);
451 final FrontendIdentifier frontendId = clientId.getFrontendId();
452 final LeaderFrontendState frontend = knownFrontends.get(frontendId);
453 if (frontend != null) {
454 if (clientId.equals(frontend.getIdentifier())) {
455 if (!(frontend instanceof LeaderFrontendState.Disabled)) {
456 verify(knownFrontends.replace(frontendId, frontend,
457 new LeaderFrontendState.Disabled(persistenceId(), clientId, store)));
458 LOG.debug("{}: leader state for {} disabled", persistenceId(), clientId);
460 LOG.debug("{}: leader state {} is already disabled", persistenceId(), frontend);
463 LOG.debug("{}: leader state {} does not match {}", persistenceId(), frontend, clientId);
466 LOG.debug("{}: leader state for {} not found", persistenceId(), clientId);
467 knownFrontends.put(frontendId, new LeaderFrontendState.Disabled(persistenceId(), clientId,
473 private void onMakeLeaderLocal() {
474 LOG.debug("{}: onMakeLeaderLocal received", persistenceId());
476 getSender().tell(new Status.Success(null), getSelf());
480 final ActorSelection leader = getLeader();
482 if (leader == null) {
483 // Leader is not present. The cluster is most likely trying to
484 // elect a leader and we should let that run its normal course
486 // TODO we can wait for the election to complete and retry the
487 // request. We can also let the caller retry by sending a flag
488 // in the response indicating the request is "reTryable".
489 getSender().tell(new Failure(
490 new LeadershipTransferFailedException("We cannot initiate leadership transfer to local node. "
491 + "Currently there is no leader for " + persistenceId())),
496 leader.tell(new RequestLeadership(getId(), getSender()), getSelf());
499 // Acquire our frontend tracking handle and verify generation matches
500 private @Nullable LeaderFrontendState findFrontend(final ClientIdentifier clientId) throws RequestException {
501 final LeaderFrontendState existing = knownFrontends.get(clientId.getFrontendId());
502 if (existing != null) {
503 final int cmp = Long.compareUnsigned(existing.getIdentifier().getGeneration(), clientId.getGeneration());
509 LOG.debug("{}: rejecting request from outdated client {}", persistenceId(), clientId);
510 throw new RetiredGenerationException(clientId.getGeneration(),
511 existing.getIdentifier().getGeneration());
514 LOG.info("{}: retiring state {}, outdated by request from client {}", persistenceId(), existing, clientId);
516 knownFrontends.remove(clientId.getFrontendId());
518 LOG.debug("{}: client {} is not yet known", persistenceId(), clientId);
524 private LeaderFrontendState getFrontend(final ClientIdentifier clientId) throws RequestException {
525 final LeaderFrontendState ret = findFrontend(clientId);
530 // TODO: a dedicated exception would be better, but this is technically true, too
531 throw new OutOfSequenceEnvelopeException(0);
534 private static @NonNull ABIVersion selectVersion(final ConnectClientRequest message) {
535 final Range<ABIVersion> clientRange = Range.closed(message.getMinVersion(), message.getMaxVersion());
536 for (ABIVersion v : SUPPORTED_ABIVERSIONS) {
537 if (clientRange.contains(v)) {
542 throw new IllegalArgumentException(String.format(
543 "No common version between backend versions %s and client versions %s", SUPPORTED_ABIVERSIONS,
547 @SuppressWarnings("checkstyle:IllegalCatch")
548 private void handleConnectClient(final ConnectClientRequest message) {
550 final ClientIdentifier clientId = message.getTarget();
551 final LeaderFrontendState existing = findFrontend(clientId);
552 if (existing != null) {
556 if (!isLeader() || !isLeaderActive()) {
557 LOG.info("{}: not currently leader, rejecting request {}. isLeader: {}, isLeaderActive: {},"
558 + "isLeadershipTransferInProgress: {}.",
559 persistenceId(), message, isLeader(), isLeaderActive(), isLeadershipTransferInProgress());
560 throw new NotLeaderException(getSelf());
563 final ABIVersion selectedVersion = selectVersion(message);
564 final LeaderFrontendState frontend;
565 if (existing == null) {
566 frontend = new LeaderFrontendState.Enabled(persistenceId(), clientId, store);
567 knownFrontends.put(clientId.getFrontendId(), frontend);
568 LOG.debug("{}: created state {} for client {}", persistenceId(), frontend, clientId);
573 frontend.reconnect();
574 message.getReplyTo().tell(new ConnectClientSuccess(message.getTarget(), message.getSequence(), getSelf(),
575 ImmutableList.of(), store.getDataTree(), CLIENT_MAX_MESSAGES).toVersion(selectedVersion),
576 ActorRef.noSender());
577 } catch (RequestException | RuntimeException e) {
578 message.getReplyTo().tell(new Failure(e), ActorRef.noSender());
582 private @Nullable RequestSuccess<?, ?> handleRequest(final RequestEnvelope envelope, final long now)
583 throws RequestException {
584 // We are not the leader, hence we want to fail-fast.
585 if (!isLeader() || paused || !isLeaderActive()) {
586 LOG.debug("{}: not currently active leader, rejecting request {}. isLeader: {}, isLeaderActive: {},"
587 + "isLeadershipTransferInProgress: {}, paused: {}",
588 persistenceId(), envelope, isLeader(), isLeaderActive(), isLeadershipTransferInProgress(), paused);
589 throw new NotLeaderException(getSelf());
592 final Request<?, ?> request = envelope.getMessage();
593 if (request instanceof TransactionRequest) {
594 final TransactionRequest<?> txReq = (TransactionRequest<?>)request;
595 final ClientIdentifier clientId = txReq.getTarget().getHistoryId().getClientId();
596 return getFrontend(clientId).handleTransactionRequest(txReq, envelope, now);
597 } else if (request instanceof LocalHistoryRequest) {
598 final LocalHistoryRequest<?> lhReq = (LocalHistoryRequest<?>)request;
599 final ClientIdentifier clientId = lhReq.getTarget().getClientId();
600 return getFrontend(clientId).handleLocalHistoryRequest(lhReq, envelope, now);
602 LOG.warn("{}: rejecting unsupported request {}", persistenceId(), request);
603 throw new UnsupportedRequestException(request);
607 private void handleGetKnownClients() {
608 final ImmutableSet<ClientIdentifier> clients;
610 clients = knownFrontends.values().stream()
611 .map(LeaderFrontendState::getIdentifier)
612 .collect(ImmutableSet.toImmutableSet());
614 clients = frontendMetadata.getClients();
616 sender().tell(new GetKnownClientsReply(clients), self());
619 private boolean hasLeader() {
620 return getLeaderId() != null;
623 public int getPendingTxCommitQueueSize() {
624 return store.getQueueSize();
627 public int getCohortCacheSize() {
628 return commitCoordinator.getCohortCacheSize();
632 protected Optional<ActorRef> getRoleChangeNotifier() {
633 return roleChangeNotifier;
636 String getShardName() {
641 protected LeaderStateChanged newLeaderStateChanged(final String memberId, final String leaderId,
642 final short leaderPayloadVersion) {
643 return isLeader() ? new ShardLeaderStateChanged(memberId, leaderId, store.getDataTree(), leaderPayloadVersion)
644 : new ShardLeaderStateChanged(memberId, leaderId, leaderPayloadVersion);
647 protected void onDatastoreContext(final DatastoreContext context) {
648 datastoreContext = context;
650 setTransactionCommitTimeout();
652 setPersistence(datastoreContext.isPersistent());
654 updateConfigParams(datastoreContext.getShardRaftConfig());
657 // applyState() will be invoked once consensus is reached on the payload
658 void persistPayload(final Identifier id, final Payload payload, final boolean batchHint) {
659 boolean canSkipPayload = !hasFollowers() && !persistence().isRecoveryApplicable();
660 if (canSkipPayload) {
661 applyState(self(), id, payload);
663 // We are faking the sender
664 persistData(self(), id, payload, batchHint);
668 private void handleCommitTransaction(final CommitTransaction commit) {
669 final TransactionIdentifier txId = commit.getTransactionId();
671 askProtocolEncountered(txId);
672 commitCoordinator.handleCommit(txId, getSender(), this);
674 ActorSelection leader = getLeader();
675 if (leader == null) {
676 messageRetrySupport.addMessageToRetry(commit, getSender(), "Could not commit transaction " + txId);
678 LOG.debug("{}: Forwarding CommitTransaction to leader {}", persistenceId(), leader);
679 leader.forward(commit, getContext());
684 private void handleCanCommitTransaction(final CanCommitTransaction canCommit) {
685 final TransactionIdentifier txId = canCommit.getTransactionId();
686 LOG.debug("{}: Can committing transaction {}", persistenceId(), txId);
689 askProtocolEncountered(txId);
690 commitCoordinator.handleCanCommit(txId, getSender(), this);
692 ActorSelection leader = getLeader();
693 if (leader == null) {
694 messageRetrySupport.addMessageToRetry(canCommit, getSender(),
695 "Could not canCommit transaction " + txId);
697 LOG.debug("{}: Forwarding CanCommitTransaction to leader {}", persistenceId(), leader);
698 leader.forward(canCommit, getContext());
703 @SuppressWarnings("checkstyle:IllegalCatch")
704 protected void handleBatchedModificationsLocal(final BatchedModifications batched, final ActorRef sender) {
705 askProtocolEncountered(batched.getTransactionId());
708 commitCoordinator.handleBatchedModifications(batched, sender, this);
709 } catch (Exception e) {
710 LOG.error("{}: Error handling BatchedModifications for Tx {}", persistenceId(),
711 batched.getTransactionId(), e);
712 sender.tell(new Failure(e), getSelf());
716 private void handleBatchedModifications(final BatchedModifications batched) {
717 // This message is sent to prepare the modifications transaction directly on the Shard as an
718 // optimization to avoid the extra overhead of a separate ShardTransaction actor. On the last
719 // BatchedModifications message, the caller sets the ready flag in the message indicating
720 // modifications are complete. The reply contains the cohort actor path (this actor) for the caller
721 // to initiate the 3-phase commit. This also avoids the overhead of sending an additional
722 // ReadyTransaction message.
724 // If we're not the leader then forward to the leader. This is a safety measure - we shouldn't
725 // normally get here if we're not the leader as the front-end (TransactionProxy) should determine
726 // the primary/leader shard. However with timing and caching on the front-end, there's a small
727 // window where it could have a stale leader during leadership transitions.
729 boolean isLeaderActive = isLeaderActive();
730 if (isLeader() && isLeaderActive) {
731 handleBatchedModificationsLocal(batched, getSender());
733 ActorSelection leader = getLeader();
734 if (!isLeaderActive || leader == null) {
735 messageRetrySupport.addMessageToRetry(batched, getSender(),
736 "Could not process BatchedModifications " + batched.getTransactionId());
738 // If this is not the first batch and leadership changed in between batched messages,
739 // we need to reconstruct previous BatchedModifications from the transaction
740 // DataTreeModification, honoring the max batched modification count, and forward all the
741 // previous BatchedModifications to the new leader.
742 Collection<BatchedModifications> newModifications = commitCoordinator
743 .createForwardedBatchedModifications(batched,
744 datastoreContext.getShardBatchedModificationCount());
746 LOG.debug("{}: Forwarding {} BatchedModifications to leader {}", persistenceId(),
747 newModifications.size(), leader);
749 for (BatchedModifications bm : newModifications) {
750 leader.forward(bm, getContext());
756 private boolean failIfIsolatedLeader(final ActorRef sender) {
757 if (isIsolatedLeader()) {
758 sender.tell(new Failure(new NoShardLeaderException(String.format(
759 "Shard %s was the leader but has lost contact with all of its followers. Either all"
760 + " other follower nodes are down or this node is isolated by a network partition.",
761 persistenceId()))), getSelf());
768 protected boolean isIsolatedLeader() {
769 return getRaftState() == RaftState.IsolatedLeader;
772 @SuppressWarnings("checkstyle:IllegalCatch")
773 private void handleReadyLocalTransaction(final ReadyLocalTransaction message) {
774 LOG.debug("{}: handleReadyLocalTransaction for {}", persistenceId(), message.getTransactionId());
776 boolean isLeaderActive = isLeaderActive();
777 if (isLeader() && isLeaderActive) {
779 commitCoordinator.handleReadyLocalTransaction(message, getSender(), this);
780 } catch (Exception e) {
781 LOG.error("{}: Error handling ReadyLocalTransaction for Tx {}", persistenceId(),
782 message.getTransactionId(), e);
783 getSender().tell(new Failure(e), getSelf());
786 ActorSelection leader = getLeader();
787 if (!isLeaderActive || leader == null) {
788 messageRetrySupport.addMessageToRetry(message, getSender(),
789 "Could not process ready local transaction " + message.getTransactionId());
791 LOG.debug("{}: Forwarding ReadyLocalTransaction to leader {}", persistenceId(), leader);
792 message.setRemoteVersion(getCurrentBehavior().getLeaderPayloadVersion());
793 leader.forward(message, getContext());
798 private void handleForwardedReadyTransaction(final ForwardedReadyTransaction forwardedReady) {
799 LOG.debug("{}: handleForwardedReadyTransaction for {}", persistenceId(), forwardedReady.getTransactionId());
801 boolean isLeaderActive = isLeaderActive();
802 if (isLeader() && isLeaderActive) {
803 askProtocolEncountered(forwardedReady.getTransactionId());
804 commitCoordinator.handleForwardedReadyTransaction(forwardedReady, getSender(), this);
806 ActorSelection leader = getLeader();
807 if (!isLeaderActive || leader == null) {
808 messageRetrySupport.addMessageToRetry(forwardedReady, getSender(),
809 "Could not process forwarded ready transaction " + forwardedReady.getTransactionId());
811 LOG.debug("{}: Forwarding ForwardedReadyTransaction to leader {}", persistenceId(), leader);
813 ReadyLocalTransaction readyLocal = new ReadyLocalTransaction(forwardedReady.getTransactionId(),
814 forwardedReady.getTransaction().getSnapshot(), forwardedReady.isDoImmediateCommit(),
815 forwardedReady.getParticipatingShardNames());
816 readyLocal.setRemoteVersion(getCurrentBehavior().getLeaderPayloadVersion());
817 leader.forward(readyLocal, getContext());
822 private void handleAbortTransaction(final AbortTransaction abort) {
823 final TransactionIdentifier transactionId = abort.getTransactionId();
824 askProtocolEncountered(transactionId);
825 doAbortTransaction(transactionId, getSender());
828 void doAbortTransaction(final Identifier transactionID, final ActorRef sender) {
829 commitCoordinator.handleAbort(transactionID, sender, this);
832 private void handleCreateTransaction(final Object message) {
834 createTransaction(CreateTransaction.fromSerializable(message));
835 } else if (getLeader() != null) {
836 getLeader().forward(message, getContext());
838 getSender().tell(new Failure(new NoShardLeaderException(
839 "Could not create a shard transaction", persistenceId())), getSelf());
843 private void closeTransactionChain(final CloseTransactionChain closeTransactionChain) {
845 final LocalHistoryIdentifier id = closeTransactionChain.getIdentifier();
846 askProtocolEncountered(id.getClientId());
847 store.closeTransactionChain(id);
848 } else if (getLeader() != null) {
849 getLeader().forward(closeTransactionChain, getContext());
851 LOG.warn("{}: Could not close transaction {}", persistenceId(), closeTransactionChain.getIdentifier());
855 @SuppressWarnings("checkstyle:IllegalCatch")
856 private void createTransaction(final CreateTransaction createTransaction) {
857 askProtocolEncountered(createTransaction.getTransactionId());
860 if (TransactionType.fromInt(createTransaction.getTransactionType()) != TransactionType.READ_ONLY
861 && failIfIsolatedLeader(getSender())) {
865 ActorRef transactionActor = createTransaction(createTransaction.getTransactionType(),
866 createTransaction.getTransactionId());
868 getSender().tell(new CreateTransactionReply(Serialization.serializedActorPath(transactionActor),
869 createTransaction.getTransactionId(), createTransaction.getVersion()).toSerializable(), getSelf());
870 } catch (Exception e) {
871 getSender().tell(new Failure(e), getSelf());
875 private ActorRef createTransaction(final int transactionType, final TransactionIdentifier transactionId) {
876 LOG.debug("{}: Creating transaction : {} ", persistenceId(), transactionId);
877 return transactionActorFactory.newShardTransaction(TransactionType.fromInt(transactionType),
881 // Called on leader only
882 private void askProtocolEncountered(final TransactionIdentifier transactionId) {
883 askProtocolEncountered(transactionId.getHistoryId().getClientId());
886 // Called on leader only
887 private void askProtocolEncountered(final ClientIdentifier clientId) {
888 final FrontendIdentifier frontend = clientId.getFrontendId();
889 final LeaderFrontendState state = knownFrontends.get(frontend);
890 if (!(state instanceof LeaderFrontendState.Disabled)) {
891 LOG.debug("{}: encountered ask-based client {}, disabling transaction tracking", persistenceId(), clientId);
892 if (knownFrontends.isEmpty()) {
893 knownFrontends = new HashMap<>();
895 knownFrontends.put(frontend, new LeaderFrontendState.Disabled(persistenceId(), clientId, getDataStore()));
897 persistPayload(clientId, DisableTrackingPayload.create(clientId,
898 datastoreContext.getInitialPayloadSerializedBufferCapacity()), false);
902 private void updateSchemaContext(final UpdateSchemaContext message) {
903 updateSchemaContext(message.getEffectiveModelContext());
907 void updateSchemaContext(final @NonNull EffectiveModelContext schemaContext) {
908 store.updateSchemaContext(schemaContext);
911 private boolean isMetricsCaptureEnabled() {
912 CommonConfig config = new CommonConfig(getContext().system().settings().config());
913 return config.isMetricCaptureEnabled();
918 public RaftActorSnapshotCohort getRaftActorSnapshotCohort() {
919 return snapshotCohort;
923 protected RaftActorRecoveryCohort getRaftActorRecoveryCohort() {
924 if (restoreFromSnapshot == null) {
925 return ShardRecoveryCoordinator.create(store, persistenceId(), LOG);
928 return ShardRecoveryCoordinator.forSnapshot(store, persistenceId(), LOG, restoreFromSnapshot.getSnapshot());
932 protected void onRecoveryComplete() {
933 restoreFromSnapshot = null;
935 //notify shard manager
936 getContext().parent().tell(new ActorInitialized(), getSelf());
938 // Being paranoid here - this method should only be called once but just in case...
939 if (txCommitTimeoutCheckSchedule == null) {
940 // Schedule a message to be periodically sent to check if the current in-progress
941 // transaction should be expired and aborted.
942 FiniteDuration period = FiniteDuration.create(transactionCommitTimeout / 3, TimeUnit.MILLISECONDS);
943 txCommitTimeoutCheckSchedule = getContext().system().scheduler().schedule(
944 period, period, getSelf(),
945 TX_COMMIT_TIMEOUT_CHECK_MESSAGE, getContext().dispatcher(), ActorRef.noSender());
950 protected void applyState(final ActorRef clientActor, final Identifier identifier, final Object data) {
951 if (data instanceof Payload) {
952 if (data instanceof DisableTrackingPayload) {
953 disableTracking((DisableTrackingPayload) data);
958 store.applyReplicatedPayload(identifier, (Payload)data);
959 } catch (DataValidationFailedException | IOException e) {
960 LOG.error("{}: Error applying replica {}", persistenceId(), identifier, e);
963 LOG.error("{}: Unknown state for {} received {}", persistenceId(), identifier, data);
968 protected void onStateChanged() {
969 boolean isLeader = isLeader();
970 boolean hasLeader = hasLeader();
971 treeChangeSupport.onLeadershipChange(isLeader, hasLeader);
973 // If this actor is no longer the leader close all the transaction chains
975 if (LOG.isDebugEnabled()) {
977 "{}: onStateChanged: Closing all transaction chains because shard {} is no longer the leader",
978 persistenceId(), getId());
982 store.purgeLeaderState();
985 if (hasLeader && !isIsolatedLeader()) {
986 messageRetrySupport.retryMessages();
991 protected void onLeaderChanged(final String oldLeader, final String newLeader) {
992 shardMBean.incrementLeadershipChangeCount();
996 if (!knownFrontends.isEmpty()) {
997 LOG.debug("{}: removing frontend state for {}", persistenceId(), knownFrontends.keySet());
998 knownFrontends = ImmutableMap.of();
1001 requestMessageAssembler.close();
1004 // No leader anywhere, nothing else to do
1008 // Another leader was elected. If we were the previous leader and had pending transactions, convert
1009 // them to transaction messages and send to the new leader.
1010 ActorSelection leader = getLeader();
1011 if (leader != null) {
1012 Collection<?> messagesToForward = convertPendingTransactionsToMessages();
1014 if (!messagesToForward.isEmpty()) {
1015 LOG.debug("{}: Forwarding {} pending transaction messages to leader {}", persistenceId(),
1016 messagesToForward.size(), leader);
1018 for (Object message : messagesToForward) {
1019 LOG.debug("{}: Forwarding pending transaction message {}", persistenceId(), message);
1021 leader.tell(message, self());
1025 commitCoordinator.abortPendingTransactions("The transacton was aborted due to inflight leadership "
1026 + "change and the leader address isn't available.", this);
1029 // We have become the leader, we need to reconstruct frontend state
1030 knownFrontends = Verify.verifyNotNull(frontendMetadata.toLeaderState(this));
1031 LOG.debug("{}: became leader with frontend state for {}", persistenceId(), knownFrontends.keySet());
1034 if (!isIsolatedLeader()) {
1035 messageRetrySupport.retryMessages();
1040 * Clears all pending transactions and converts them to messages to be forwarded to a new leader.
1042 * @return the converted messages
1044 public Collection<?> convertPendingTransactionsToMessages() {
1045 return commitCoordinator.convertPendingTransactionsToMessages(
1046 datastoreContext.getShardBatchedModificationCount());
1050 protected void pauseLeader(final Runnable operation) {
1051 LOG.debug("{}: In pauseLeader, operation: {}", persistenceId(), operation);
1054 // Tell-based protocol can replay transaction state, so it is safe to blow it up when we are paused.
1055 if (datastoreContext.isUseTellBasedProtocol()) {
1056 knownFrontends.values().forEach(LeaderFrontendState::retire);
1057 knownFrontends = ImmutableMap.of();
1060 store.setRunOnPendingTransactionsComplete(operation);
1064 protected void unpauseLeader() {
1065 LOG.debug("{}: In unpauseLeader", persistenceId());
1068 store.setRunOnPendingTransactionsComplete(null);
1070 // Restore tell-based protocol state as if we were becoming the leader
1071 knownFrontends = Verify.verifyNotNull(frontendMetadata.toLeaderState(this));
1075 protected OnDemandRaftState.AbstractBuilder<?, ?> newOnDemandRaftStateBuilder() {
1076 return OnDemandShardState.newBuilder().treeChangeListenerActors(treeChangeSupport.getListenerActors())
1077 .commitCohortActors(store.getCohortActors());
1081 public String persistenceId() {
1086 ShardCommitCoordinator getCommitCoordinator() {
1087 return commitCoordinator;
1090 public DatastoreContext getDatastoreContext() {
1091 return datastoreContext;
1095 public ShardDataTree getDataStore() {
1100 ShardStats getShardMBean() {
1104 public static Builder builder() {
1105 return new Builder();
1108 public abstract static class AbstractBuilder<T extends AbstractBuilder<T, S>, S extends Shard> {
1109 private final Class<? extends S> shardClass;
1110 private ShardIdentifier id;
1111 private Map<String, String> peerAddresses = Collections.emptyMap();
1112 private DatastoreContext datastoreContext;
1113 private EffectiveModelContextProvider schemaContextProvider;
1114 private DatastoreSnapshot.ShardSnapshot restoreFromSnapshot;
1115 private DataTree dataTree;
1117 private volatile boolean sealed;
1119 protected AbstractBuilder(final Class<? extends S> shardClass) {
1120 this.shardClass = shardClass;
1123 protected void checkSealed() {
1124 checkState(!sealed, "Builder isalready sealed - further modifications are not allowed");
1127 @SuppressWarnings("unchecked")
1132 public T id(final ShardIdentifier newId) {
1138 public T peerAddresses(final Map<String, String> newPeerAddresses) {
1140 this.peerAddresses = newPeerAddresses;
1144 public T datastoreContext(final DatastoreContext newDatastoreContext) {
1146 this.datastoreContext = newDatastoreContext;
1150 public T schemaContextProvider(final EffectiveModelContextProvider newSchemaContextProvider) {
1152 this.schemaContextProvider = requireNonNull(newSchemaContextProvider);
1156 public T restoreFromSnapshot(final DatastoreSnapshot.ShardSnapshot newRestoreFromSnapshot) {
1158 this.restoreFromSnapshot = newRestoreFromSnapshot;
1162 public T dataTree(final DataTree newDataTree) {
1164 this.dataTree = newDataTree;
1168 public ShardIdentifier getId() {
1172 public Map<String, String> getPeerAddresses() {
1173 return peerAddresses;
1176 public DatastoreContext getDatastoreContext() {
1177 return datastoreContext;
1180 public EffectiveModelContext getSchemaContext() {
1181 return Verify.verifyNotNull(schemaContextProvider.getEffectiveModelContext());
1184 public DatastoreSnapshot.ShardSnapshot getRestoreFromSnapshot() {
1185 return restoreFromSnapshot;
1188 public DataTree getDataTree() {
1192 public TreeType getTreeType() {
1193 switch (datastoreContext.getLogicalStoreType()) {
1195 return TreeType.CONFIGURATION;
1197 return TreeType.OPERATIONAL;
1199 throw new IllegalStateException("Unhandled logical store type "
1200 + datastoreContext.getLogicalStoreType());
1204 protected void verify() {
1205 requireNonNull(id, "id should not be null");
1206 requireNonNull(peerAddresses, "peerAddresses should not be null");
1207 requireNonNull(datastoreContext, "dataStoreContext should not be null");
1208 requireNonNull(schemaContextProvider, "schemaContextProvider should not be null");
1211 public Props props() {
1214 return Props.create(shardClass, this);
1218 public static class Builder extends AbstractBuilder<Builder, Shard> {
1223 Builder(final Class<? extends Shard> shardClass) {
1229 return Ticker.systemTicker();
1232 void scheduleNextPendingTransaction() {
1233 self().tell(RESUME_NEXT_PENDING_TRANSACTION, ActorRef.noSender());