2 * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
4 * This program and the accompanying materials are made available under the
5 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6 * and is available at http://www.eclipse.org/legal/epl-v10.html
8 package org.opendaylight.controller.cluster.datastore;
10 import static com.google.common.base.Verify.verify;
12 import akka.actor.ActorRef;
13 import akka.actor.ActorSelection;
14 import akka.actor.Cancellable;
15 import akka.actor.ExtendedActorSystem;
16 import akka.actor.Props;
17 import akka.actor.Status;
18 import akka.actor.Status.Failure;
19 import akka.serialization.JavaSerializer;
20 import akka.serialization.Serialization;
21 import com.google.common.annotations.VisibleForTesting;
22 import com.google.common.base.Preconditions;
23 import com.google.common.base.Ticker;
24 import com.google.common.base.Verify;
25 import com.google.common.collect.ImmutableList;
26 import com.google.common.collect.ImmutableMap;
27 import com.google.common.collect.Range;
28 import java.io.IOException;
29 import java.util.Arrays;
30 import java.util.Collection;
31 import java.util.Collections;
32 import java.util.HashMap;
34 import java.util.Optional;
35 import java.util.OptionalLong;
36 import java.util.concurrent.TimeUnit;
37 import org.eclipse.jdt.annotation.NonNull;
38 import org.eclipse.jdt.annotation.Nullable;
39 import org.opendaylight.controller.cluster.access.ABIVersion;
40 import org.opendaylight.controller.cluster.access.commands.ConnectClientRequest;
41 import org.opendaylight.controller.cluster.access.commands.ConnectClientSuccess;
42 import org.opendaylight.controller.cluster.access.commands.LocalHistoryRequest;
43 import org.opendaylight.controller.cluster.access.commands.NotLeaderException;
44 import org.opendaylight.controller.cluster.access.commands.OutOfSequenceEnvelopeException;
45 import org.opendaylight.controller.cluster.access.commands.TransactionRequest;
46 import org.opendaylight.controller.cluster.access.concepts.ClientIdentifier;
47 import org.opendaylight.controller.cluster.access.concepts.FrontendIdentifier;
48 import org.opendaylight.controller.cluster.access.concepts.LocalHistoryIdentifier;
49 import org.opendaylight.controller.cluster.access.concepts.Request;
50 import org.opendaylight.controller.cluster.access.concepts.RequestEnvelope;
51 import org.opendaylight.controller.cluster.access.concepts.RequestException;
52 import org.opendaylight.controller.cluster.access.concepts.RequestSuccess;
53 import org.opendaylight.controller.cluster.access.concepts.RetiredGenerationException;
54 import org.opendaylight.controller.cluster.access.concepts.RuntimeRequestException;
55 import org.opendaylight.controller.cluster.access.concepts.SliceableMessage;
56 import org.opendaylight.controller.cluster.access.concepts.TransactionIdentifier;
57 import org.opendaylight.controller.cluster.access.concepts.UnsupportedRequestException;
58 import org.opendaylight.controller.cluster.common.actor.CommonConfig;
59 import org.opendaylight.controller.cluster.common.actor.Dispatchers;
60 import org.opendaylight.controller.cluster.common.actor.Dispatchers.DispatcherType;
61 import org.opendaylight.controller.cluster.common.actor.MessageTracker;
62 import org.opendaylight.controller.cluster.common.actor.MessageTracker.Error;
63 import org.opendaylight.controller.cluster.common.actor.MeteringBehavior;
64 import org.opendaylight.controller.cluster.datastore.exceptions.NoShardLeaderException;
65 import org.opendaylight.controller.cluster.datastore.identifiers.ShardIdentifier;
66 import org.opendaylight.controller.cluster.datastore.jmx.mbeans.shard.ShardDataTreeListenerInfoMXBeanImpl;
67 import org.opendaylight.controller.cluster.datastore.jmx.mbeans.shard.ShardMBeanFactory;
68 import org.opendaylight.controller.cluster.datastore.jmx.mbeans.shard.ShardStats;
69 import org.opendaylight.controller.cluster.datastore.messages.AbortTransaction;
70 import org.opendaylight.controller.cluster.datastore.messages.ActorInitialized;
71 import org.opendaylight.controller.cluster.datastore.messages.BatchedModifications;
72 import org.opendaylight.controller.cluster.datastore.messages.CanCommitTransaction;
73 import org.opendaylight.controller.cluster.datastore.messages.CloseTransactionChain;
74 import org.opendaylight.controller.cluster.datastore.messages.CommitTransaction;
75 import org.opendaylight.controller.cluster.datastore.messages.CreateTransaction;
76 import org.opendaylight.controller.cluster.datastore.messages.CreateTransactionReply;
77 import org.opendaylight.controller.cluster.datastore.messages.ForwardedReadyTransaction;
78 import org.opendaylight.controller.cluster.datastore.messages.GetShardDataTree;
79 import org.opendaylight.controller.cluster.datastore.messages.MakeLeaderLocal;
80 import org.opendaylight.controller.cluster.datastore.messages.OnDemandShardState;
81 import org.opendaylight.controller.cluster.datastore.messages.PeerAddressResolved;
82 import org.opendaylight.controller.cluster.datastore.messages.ReadyLocalTransaction;
83 import org.opendaylight.controller.cluster.datastore.messages.RegisterDataTreeChangeListener;
84 import org.opendaylight.controller.cluster.datastore.messages.ShardLeaderStateChanged;
85 import org.opendaylight.controller.cluster.datastore.messages.UpdateSchemaContext;
86 import org.opendaylight.controller.cluster.datastore.persisted.DatastoreSnapshot;
87 import org.opendaylight.controller.cluster.datastore.persisted.DatastoreSnapshot.ShardSnapshot;
88 import org.opendaylight.controller.cluster.datastore.persisted.DisableTrackingPayload;
89 import org.opendaylight.controller.cluster.messaging.MessageAssembler;
90 import org.opendaylight.controller.cluster.messaging.MessageSlicer;
91 import org.opendaylight.controller.cluster.messaging.SliceOptions;
92 import org.opendaylight.controller.cluster.notifications.LeaderStateChanged;
93 import org.opendaylight.controller.cluster.notifications.RegisterRoleChangeListener;
94 import org.opendaylight.controller.cluster.notifications.RoleChangeNotifier;
95 import org.opendaylight.controller.cluster.raft.LeadershipTransferFailedException;
96 import org.opendaylight.controller.cluster.raft.RaftActor;
97 import org.opendaylight.controller.cluster.raft.RaftActorRecoveryCohort;
98 import org.opendaylight.controller.cluster.raft.RaftActorSnapshotCohort;
99 import org.opendaylight.controller.cluster.raft.RaftState;
100 import org.opendaylight.controller.cluster.raft.base.messages.FollowerInitialSyncUpStatus;
101 import org.opendaylight.controller.cluster.raft.client.messages.OnDemandRaftState;
102 import org.opendaylight.controller.cluster.raft.messages.AppendEntriesReply;
103 import org.opendaylight.controller.cluster.raft.messages.RequestLeadership;
104 import org.opendaylight.controller.cluster.raft.messages.ServerRemoved;
105 import org.opendaylight.controller.cluster.raft.protobuff.client.messages.Payload;
106 import org.opendaylight.yangtools.concepts.Identifier;
107 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTree;
108 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataValidationFailedException;
109 import org.opendaylight.yangtools.yang.data.api.schema.tree.TreeType;
110 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
111 import org.opendaylight.yangtools.yang.model.api.SchemaContextProvider;
112 import scala.concurrent.duration.FiniteDuration;
115 * A Shard represents a portion of the logical data tree.
118 * Our Shard uses InMemoryDataTree as it's internal representation and delegates all requests it
120 public class Shard extends RaftActor {
123 static final Object TX_COMMIT_TIMEOUT_CHECK_MESSAGE = new Object() {
125 public String toString() {
126 return "txCommitTimeoutCheck";
131 static final Object GET_SHARD_MBEAN_MESSAGE = new Object() {
133 public String toString() {
134 return "getShardMBeanMessage";
138 static final Object RESUME_NEXT_PENDING_TRANSACTION = new Object() {
140 public String toString() {
141 return "resumeNextPendingTransaction";
145 // FIXME: shard names should be encapsulated in their own class and this should be exposed as a constant.
146 public static final String DEFAULT_NAME = "default";
148 private static final Collection<ABIVersion> SUPPORTED_ABIVERSIONS;
151 final ABIVersion[] values = ABIVersion.values();
152 final ABIVersion[] real = Arrays.copyOfRange(values, 1, values.length - 1);
153 SUPPORTED_ABIVERSIONS = ImmutableList.copyOf(real).reverse();
156 // FIXME: make this a dynamic property based on mailbox size and maximum number of clients
157 private static final int CLIENT_MAX_MESSAGES = 1000;
159 // The state of this Shard
160 private final ShardDataTree store;
162 /// The name of this shard
163 private final String name;
165 private final String shardName;
167 private final ShardStats shardMBean;
169 private final ShardDataTreeListenerInfoMXBeanImpl listenerInfoMXBean;
171 private DatastoreContext datastoreContext;
173 private final ShardCommitCoordinator commitCoordinator;
175 private long transactionCommitTimeout;
177 private Cancellable txCommitTimeoutCheckSchedule;
179 private final Optional<ActorRef> roleChangeNotifier;
181 private final MessageTracker appendEntriesReplyTracker;
183 private final ShardTransactionActorFactory transactionActorFactory;
185 private final ShardSnapshotCohort snapshotCohort;
187 private final DataTreeChangeListenerSupport treeChangeSupport = new DataTreeChangeListenerSupport(this);
189 private ShardSnapshot restoreFromSnapshot;
191 private final ShardTransactionMessageRetrySupport messageRetrySupport;
194 final FrontendMetadata frontendMetadata;
196 private Map<FrontendIdentifier, LeaderFrontendState> knownFrontends = ImmutableMap.of();
197 private boolean paused;
199 private final MessageSlicer responseMessageSlicer;
200 private final Dispatchers dispatchers;
202 private final MessageAssembler requestMessageAssembler;
204 protected Shard(final AbstractBuilder<?, ?> builder) {
205 super(builder.getId().toString(), builder.getPeerAddresses(),
206 Optional.of(builder.getDatastoreContext().getShardRaftConfig()), DataStoreVersions.CURRENT_VERSION);
208 this.name = builder.getId().toString();
209 this.shardName = builder.getId().getShardName();
210 this.datastoreContext = builder.getDatastoreContext();
211 this.restoreFromSnapshot = builder.getRestoreFromSnapshot();
212 this.frontendMetadata = new FrontendMetadata(name);
214 setPersistence(datastoreContext.isPersistent());
216 LOG.info("Shard created : {}, persistent : {}", name, datastoreContext.isPersistent());
218 ShardDataTreeChangeListenerPublisherActorProxy treeChangeListenerPublisher =
219 new ShardDataTreeChangeListenerPublisherActorProxy(getContext(), name + "-DTCL-publisher", name);
220 if (builder.getDataTree() != null) {
221 store = new ShardDataTree(this, builder.getSchemaContext(), builder.getDataTree(),
222 treeChangeListenerPublisher, name, frontendMetadata);
224 store = new ShardDataTree(this, builder.getSchemaContext(), builder.getTreeType(),
225 builder.getDatastoreContext().getStoreRoot(), treeChangeListenerPublisher, name, frontendMetadata);
228 shardMBean = ShardMBeanFactory.getShardStatsMBean(name, datastoreContext.getDataStoreMXBeanType(), this);
230 if (isMetricsCaptureEnabled()) {
231 getContext().become(new MeteringBehavior(this));
234 commitCoordinator = new ShardCommitCoordinator(store, LOG, this.name);
236 setTransactionCommitTimeout();
238 // create a notifier actor for each cluster member
239 roleChangeNotifier = createRoleChangeNotifier(name);
241 appendEntriesReplyTracker = new MessageTracker(AppendEntriesReply.class,
242 getRaftActorContext().getConfigParams().getIsolatedCheckIntervalInMillis());
244 dispatchers = new Dispatchers(context().system().dispatchers());
245 transactionActorFactory = new ShardTransactionActorFactory(store, datastoreContext,
246 dispatchers.getDispatcherPath(Dispatchers.DispatcherType.Transaction),
247 self(), getContext(), shardMBean, builder.getId().getShardName());
249 snapshotCohort = ShardSnapshotCohort.create(getContext(), builder.getId().getMemberName(), store, LOG,
252 messageRetrySupport = new ShardTransactionMessageRetrySupport(this);
254 responseMessageSlicer = MessageSlicer.builder().logContext(this.name)
255 .messageSliceSize(datastoreContext.getMaximumMessageSliceSize())
256 .fileBackedStreamFactory(getRaftActorContext().getFileBackedOutputStreamFactory())
257 .expireStateAfterInactivity(2, TimeUnit.MINUTES).build();
259 requestMessageAssembler = MessageAssembler.builder().logContext(this.name)
260 .fileBackedStreamFactory(getRaftActorContext().getFileBackedOutputStreamFactory())
261 .assembledMessageCallback((message, sender) -> self().tell(message, sender))
262 .expireStateAfterInactivity(datastoreContext.getRequestTimeout(), TimeUnit.NANOSECONDS).build();
264 listenerInfoMXBean = new ShardDataTreeListenerInfoMXBeanImpl(name, datastoreContext.getDataStoreMXBeanType(),
266 listenerInfoMXBean.register();
269 private void setTransactionCommitTimeout() {
270 transactionCommitTimeout = TimeUnit.MILLISECONDS.convert(
271 datastoreContext.getShardTransactionCommitTimeoutInSeconds(), TimeUnit.SECONDS) / 2;
274 private Optional<ActorRef> createRoleChangeNotifier(final String shardId) {
275 ActorRef shardRoleChangeNotifier = this.getContext().actorOf(
276 RoleChangeNotifier.getProps(shardId), shardId + "-notifier");
277 return Optional.of(shardRoleChangeNotifier);
281 public void postStop() {
282 LOG.info("Stopping Shard {}", persistenceId());
286 messageRetrySupport.close();
288 if (txCommitTimeoutCheckSchedule != null) {
289 txCommitTimeoutCheckSchedule.cancel();
292 commitCoordinator.abortPendingTransactions("Transaction aborted due to shutdown.", this);
294 shardMBean.unregisterMBean();
295 listenerInfoMXBean.unregister();
299 protected void handleRecover(final Object message) {
300 LOG.debug("{}: onReceiveRecover: Received message {} from {}", persistenceId(), message.getClass(),
303 super.handleRecover(message);
304 if (LOG.isTraceEnabled()) {
305 appendEntriesReplyTracker.begin();
310 protected void handleNonRaftCommand(final Object message) {
311 try (MessageTracker.Context context = appendEntriesReplyTracker.received(message)) {
312 final Optional<Error> maybeError = context.error();
313 if (maybeError.isPresent()) {
314 LOG.trace("{} : AppendEntriesReply failed to arrive at the expected interval {}", persistenceId(),
318 store.resetTransactionBatch();
320 if (message instanceof RequestEnvelope) {
321 handleRequestEnvelope((RequestEnvelope)message);
322 } else if (MessageAssembler.isHandledMessage(message)) {
323 handleRequestAssemblerMessage(message);
324 } else if (message instanceof ConnectClientRequest) {
325 handleConnectClient((ConnectClientRequest)message);
326 } else if (CreateTransaction.isSerializedType(message)) {
327 handleCreateTransaction(message);
328 } else if (message instanceof BatchedModifications) {
329 handleBatchedModifications((BatchedModifications)message);
330 } else if (message instanceof ForwardedReadyTransaction) {
331 handleForwardedReadyTransaction((ForwardedReadyTransaction) message);
332 } else if (message instanceof ReadyLocalTransaction) {
333 handleReadyLocalTransaction((ReadyLocalTransaction)message);
334 } else if (CanCommitTransaction.isSerializedType(message)) {
335 handleCanCommitTransaction(CanCommitTransaction.fromSerializable(message));
336 } else if (CommitTransaction.isSerializedType(message)) {
337 handleCommitTransaction(CommitTransaction.fromSerializable(message));
338 } else if (AbortTransaction.isSerializedType(message)) {
339 handleAbortTransaction(AbortTransaction.fromSerializable(message));
340 } else if (CloseTransactionChain.isSerializedType(message)) {
341 closeTransactionChain(CloseTransactionChain.fromSerializable(message));
342 } else if (message instanceof RegisterDataTreeChangeListener) {
343 treeChangeSupport.onMessage((RegisterDataTreeChangeListener) message, isLeader(), hasLeader());
344 } else if (message instanceof UpdateSchemaContext) {
345 updateSchemaContext((UpdateSchemaContext) message);
346 } else if (message instanceof PeerAddressResolved) {
347 PeerAddressResolved resolved = (PeerAddressResolved) message;
348 setPeerAddress(resolved.getPeerId(), resolved.getPeerAddress());
349 } else if (TX_COMMIT_TIMEOUT_CHECK_MESSAGE.equals(message)) {
350 commitTimeoutCheck();
351 } else if (message instanceof DatastoreContext) {
352 onDatastoreContext((DatastoreContext)message);
353 } else if (message instanceof RegisterRoleChangeListener) {
354 roleChangeNotifier.get().forward(message, context());
355 } else if (message instanceof FollowerInitialSyncUpStatus) {
356 shardMBean.setFollowerInitialSyncStatus(((FollowerInitialSyncUpStatus) message).isInitialSyncDone());
357 context().parent().tell(message, self());
358 } else if (GET_SHARD_MBEAN_MESSAGE.equals(message)) {
359 sender().tell(getShardMBean(), self());
360 } else if (message instanceof GetShardDataTree) {
361 sender().tell(store.getDataTree(), self());
362 } else if (message instanceof ServerRemoved) {
363 context().parent().forward(message, context());
364 } else if (ShardTransactionMessageRetrySupport.TIMER_MESSAGE_CLASS.isInstance(message)) {
365 messageRetrySupport.onTimerMessage(message);
366 } else if (message instanceof DataTreeCohortActorRegistry.CohortRegistryCommand) {
367 store.processCohortRegistryCommand(getSender(),
368 (DataTreeCohortActorRegistry.CohortRegistryCommand) message);
369 } else if (message instanceof MakeLeaderLocal) {
371 } else if (RESUME_NEXT_PENDING_TRANSACTION.equals(message)) {
372 store.resumeNextPendingTransaction();
373 } else if (!responseMessageSlicer.handleMessage(message)) {
374 super.handleNonRaftCommand(message);
379 private void handleRequestAssemblerMessage(final Object message) {
380 dispatchers.getDispatcher(DispatcherType.Serialization).execute(() -> {
381 JavaSerializer.currentSystem().value_$eq((ExtendedActorSystem) context().system());
382 requestMessageAssembler.handleMessage(message, self());
386 @SuppressWarnings("checkstyle:IllegalCatch")
387 private void handleRequestEnvelope(final RequestEnvelope envelope) {
388 final long now = ticker().read();
390 final RequestSuccess<?, ?> success = handleRequest(envelope, now);
391 if (success != null) {
392 final long executionTimeNanos = ticker().read() - now;
393 if (success instanceof SliceableMessage) {
394 dispatchers.getDispatcher(DispatcherType.Serialization).execute(() ->
395 responseMessageSlicer.slice(SliceOptions.builder().identifier(success.getTarget())
396 .message(envelope.newSuccessEnvelope(success, executionTimeNanos))
397 .sendTo(envelope.getMessage().getReplyTo()).replyTo(self())
398 .onFailureCallback(t -> LOG.warn("Error slicing response {}", success, t)).build()));
400 envelope.sendSuccess(success, executionTimeNanos);
403 } catch (RequestException e) {
404 LOG.debug("{}: request {} failed", persistenceId(), envelope, e);
405 envelope.sendFailure(e, ticker().read() - now);
406 } catch (Exception e) {
407 LOG.debug("{}: request {} caused failure", persistenceId(), envelope, e);
408 envelope.sendFailure(new RuntimeRequestException("Request failed to process", e),
409 ticker().read() - now);
413 private void commitTimeoutCheck() {
414 store.checkForExpiredTransactions(transactionCommitTimeout, this::updateAccess);
415 commitCoordinator.checkForExpiredTransactions(transactionCommitTimeout, this);
416 requestMessageAssembler.checkExpiredAssembledMessageState();
419 private OptionalLong updateAccess(final SimpleShardDataTreeCohort cohort) {
420 final FrontendIdentifier frontend = cohort.getIdentifier().getHistoryId().getClientId().getFrontendId();
421 final LeaderFrontendState state = knownFrontends.get(frontend);
423 // Not tell-based protocol, do nothing
424 return OptionalLong.empty();
427 if (isIsolatedLeader()) {
428 // We are isolated and no new request can come through until we emerge from it. We are still updating
429 // liveness of frontend when we see it attempting to communicate. Use the last access timer.
430 return OptionalLong.of(state.getLastSeenTicks());
433 // If this frontend has freshly connected, give it some time to catch up before killing its transactions.
434 return OptionalLong.of(state.getLastConnectTicks());
437 private void disableTracking(final DisableTrackingPayload payload) {
438 final ClientIdentifier clientId = payload.getIdentifier();
439 LOG.debug("{}: disabling tracking of {}", persistenceId(), clientId);
440 frontendMetadata.disableTracking(clientId);
443 final FrontendIdentifier frontendId = clientId.getFrontendId();
444 final LeaderFrontendState frontend = knownFrontends.get(frontendId);
445 if (frontend != null) {
446 if (clientId.equals(frontend.getIdentifier())) {
447 if (!(frontend instanceof LeaderFrontendState.Disabled)) {
448 verify(knownFrontends.replace(frontendId, frontend,
449 new LeaderFrontendState.Disabled(persistenceId(), clientId, store)));
450 LOG.debug("{}: leader state for {} disabled", persistenceId(), clientId);
452 LOG.debug("{}: leader state {} is already disabled", persistenceId(), frontend);
455 LOG.debug("{}: leader state {} does not match {}", persistenceId(), frontend, clientId);
458 LOG.debug("{}: leader state for {} not found", persistenceId(), clientId);
459 knownFrontends.put(frontendId, new LeaderFrontendState.Disabled(persistenceId(), clientId,
465 private void onMakeLeaderLocal() {
466 LOG.debug("{}: onMakeLeaderLocal received", persistenceId());
468 getSender().tell(new Status.Success(null), getSelf());
472 final ActorSelection leader = getLeader();
474 if (leader == null) {
475 // Leader is not present. The cluster is most likely trying to
476 // elect a leader and we should let that run its normal course
478 // TODO we can wait for the election to complete and retry the
479 // request. We can also let the caller retry by sending a flag
480 // in the response indicating the request is "reTryable".
481 getSender().tell(new Failure(
482 new LeadershipTransferFailedException("We cannot initiate leadership transfer to local node. "
483 + "Currently there is no leader for " + persistenceId())),
488 leader.tell(new RequestLeadership(getId(), getSender()), getSelf());
491 // Acquire our frontend tracking handle and verify generation matches
492 private @Nullable LeaderFrontendState findFrontend(final ClientIdentifier clientId) throws RequestException {
493 final LeaderFrontendState existing = knownFrontends.get(clientId.getFrontendId());
494 if (existing != null) {
495 final int cmp = Long.compareUnsigned(existing.getIdentifier().getGeneration(), clientId.getGeneration());
501 LOG.debug("{}: rejecting request from outdated client {}", persistenceId(), clientId);
502 throw new RetiredGenerationException(clientId.getGeneration(),
503 existing.getIdentifier().getGeneration());
506 LOG.info("{}: retiring state {}, outdated by request from client {}", persistenceId(), existing, clientId);
508 knownFrontends.remove(clientId.getFrontendId());
510 LOG.debug("{}: client {} is not yet known", persistenceId(), clientId);
516 private LeaderFrontendState getFrontend(final ClientIdentifier clientId) throws RequestException {
517 final LeaderFrontendState ret = findFrontend(clientId);
522 // TODO: a dedicated exception would be better, but this is technically true, too
523 throw new OutOfSequenceEnvelopeException(0);
526 private static @NonNull ABIVersion selectVersion(final ConnectClientRequest message) {
527 final Range<ABIVersion> clientRange = Range.closed(message.getMinVersion(), message.getMaxVersion());
528 for (ABIVersion v : SUPPORTED_ABIVERSIONS) {
529 if (clientRange.contains(v)) {
534 throw new IllegalArgumentException(String.format(
535 "No common version between backend versions %s and client versions %s", SUPPORTED_ABIVERSIONS,
539 @SuppressWarnings("checkstyle:IllegalCatch")
540 private void handleConnectClient(final ConnectClientRequest message) {
542 final ClientIdentifier clientId = message.getTarget();
543 final LeaderFrontendState existing = findFrontend(clientId);
544 if (existing != null) {
548 if (!isLeader() || !isLeaderActive()) {
549 LOG.info("{}: not currently leader, rejecting request {}. isLeader: {}, isLeaderActive: {},"
550 + "isLeadershipTransferInProgress: {}.",
551 persistenceId(), message, isLeader(), isLeaderActive(), isLeadershipTransferInProgress());
552 throw new NotLeaderException(getSelf());
555 final ABIVersion selectedVersion = selectVersion(message);
556 final LeaderFrontendState frontend;
557 if (existing == null) {
558 frontend = new LeaderFrontendState.Enabled(persistenceId(), clientId, store);
559 knownFrontends.put(clientId.getFrontendId(), frontend);
560 LOG.debug("{}: created state {} for client {}", persistenceId(), frontend, clientId);
565 frontend.reconnect();
566 message.getReplyTo().tell(new ConnectClientSuccess(message.getTarget(), message.getSequence(), getSelf(),
567 ImmutableList.of(), store.getDataTree(), CLIENT_MAX_MESSAGES).toVersion(selectedVersion),
568 ActorRef.noSender());
569 } catch (RequestException | RuntimeException e) {
570 message.getReplyTo().tell(new Failure(e), ActorRef.noSender());
574 private @Nullable RequestSuccess<?, ?> handleRequest(final RequestEnvelope envelope, final long now)
575 throws RequestException {
576 // We are not the leader, hence we want to fail-fast.
577 if (!isLeader() || paused || !isLeaderActive()) {
578 LOG.debug("{}: not currently active leader, rejecting request {}. isLeader: {}, isLeaderActive: {},"
579 + "isLeadershipTransferInProgress: {}, paused: {}",
580 persistenceId(), envelope, isLeader(), isLeaderActive(), isLeadershipTransferInProgress(), paused);
581 throw new NotLeaderException(getSelf());
584 final Request<?, ?> request = envelope.getMessage();
585 if (request instanceof TransactionRequest) {
586 final TransactionRequest<?> txReq = (TransactionRequest<?>)request;
587 final ClientIdentifier clientId = txReq.getTarget().getHistoryId().getClientId();
588 return getFrontend(clientId).handleTransactionRequest(txReq, envelope, now);
589 } else if (request instanceof LocalHistoryRequest) {
590 final LocalHistoryRequest<?> lhReq = (LocalHistoryRequest<?>)request;
591 final ClientIdentifier clientId = lhReq.getTarget().getClientId();
592 return getFrontend(clientId).handleLocalHistoryRequest(lhReq, envelope, now);
594 LOG.warn("{}: rejecting unsupported request {}", persistenceId(), request);
595 throw new UnsupportedRequestException(request);
599 private boolean hasLeader() {
600 return getLeaderId() != null;
603 public int getPendingTxCommitQueueSize() {
604 return store.getQueueSize();
607 public int getCohortCacheSize() {
608 return commitCoordinator.getCohortCacheSize();
612 protected Optional<ActorRef> getRoleChangeNotifier() {
613 return roleChangeNotifier;
616 String getShardName() {
621 protected LeaderStateChanged newLeaderStateChanged(final String memberId, final String leaderId,
622 final short leaderPayloadVersion) {
623 return isLeader() ? new ShardLeaderStateChanged(memberId, leaderId, store.getDataTree(), leaderPayloadVersion)
624 : new ShardLeaderStateChanged(memberId, leaderId, leaderPayloadVersion);
627 protected void onDatastoreContext(final DatastoreContext context) {
628 datastoreContext = context;
630 setTransactionCommitTimeout();
632 setPersistence(datastoreContext.isPersistent());
634 updateConfigParams(datastoreContext.getShardRaftConfig());
637 // applyState() will be invoked once consensus is reached on the payload
638 void persistPayload(final Identifier id, final Payload payload, final boolean batchHint) {
639 boolean canSkipPayload = !hasFollowers() && !persistence().isRecoveryApplicable();
640 if (canSkipPayload) {
641 applyState(self(), id, payload);
643 // We are faking the sender
644 persistData(self(), id, payload, batchHint);
648 private void handleCommitTransaction(final CommitTransaction commit) {
649 final TransactionIdentifier txId = commit.getTransactionId();
651 askProtocolEncountered(txId);
652 commitCoordinator.handleCommit(txId, getSender(), this);
654 ActorSelection leader = getLeader();
655 if (leader == null) {
656 messageRetrySupport.addMessageToRetry(commit, getSender(), "Could not commit transaction " + txId);
658 LOG.debug("{}: Forwarding CommitTransaction to leader {}", persistenceId(), leader);
659 leader.forward(commit, getContext());
664 private void handleCanCommitTransaction(final CanCommitTransaction canCommit) {
665 final TransactionIdentifier txId = canCommit.getTransactionId();
666 LOG.debug("{}: Can committing transaction {}", persistenceId(), txId);
669 askProtocolEncountered(txId);
670 commitCoordinator.handleCanCommit(txId, getSender(), this);
672 ActorSelection leader = getLeader();
673 if (leader == null) {
674 messageRetrySupport.addMessageToRetry(canCommit, getSender(),
675 "Could not canCommit transaction " + txId);
677 LOG.debug("{}: Forwarding CanCommitTransaction to leader {}", persistenceId(), leader);
678 leader.forward(canCommit, getContext());
683 @SuppressWarnings("checkstyle:IllegalCatch")
684 protected void handleBatchedModificationsLocal(final BatchedModifications batched, final ActorRef sender) {
685 askProtocolEncountered(batched.getTransactionId());
688 commitCoordinator.handleBatchedModifications(batched, sender, this);
689 } catch (Exception e) {
690 LOG.error("{}: Error handling BatchedModifications for Tx {}", persistenceId(),
691 batched.getTransactionId(), e);
692 sender.tell(new Failure(e), getSelf());
696 private void handleBatchedModifications(final BatchedModifications batched) {
697 // This message is sent to prepare the modifications transaction directly on the Shard as an
698 // optimization to avoid the extra overhead of a separate ShardTransaction actor. On the last
699 // BatchedModifications message, the caller sets the ready flag in the message indicating
700 // modifications are complete. The reply contains the cohort actor path (this actor) for the caller
701 // to initiate the 3-phase commit. This also avoids the overhead of sending an additional
702 // ReadyTransaction message.
704 // If we're not the leader then forward to the leader. This is a safety measure - we shouldn't
705 // normally get here if we're not the leader as the front-end (TransactionProxy) should determine
706 // the primary/leader shard. However with timing and caching on the front-end, there's a small
707 // window where it could have a stale leader during leadership transitions.
709 boolean isLeaderActive = isLeaderActive();
710 if (isLeader() && isLeaderActive) {
711 handleBatchedModificationsLocal(batched, getSender());
713 ActorSelection leader = getLeader();
714 if (!isLeaderActive || leader == null) {
715 messageRetrySupport.addMessageToRetry(batched, getSender(),
716 "Could not process BatchedModifications " + batched.getTransactionId());
718 // If this is not the first batch and leadership changed in between batched messages,
719 // we need to reconstruct previous BatchedModifications from the transaction
720 // DataTreeModification, honoring the max batched modification count, and forward all the
721 // previous BatchedModifications to the new leader.
722 Collection<BatchedModifications> newModifications = commitCoordinator
723 .createForwardedBatchedModifications(batched,
724 datastoreContext.getShardBatchedModificationCount());
726 LOG.debug("{}: Forwarding {} BatchedModifications to leader {}", persistenceId(),
727 newModifications.size(), leader);
729 for (BatchedModifications bm : newModifications) {
730 leader.forward(bm, getContext());
736 private boolean failIfIsolatedLeader(final ActorRef sender) {
737 if (isIsolatedLeader()) {
738 sender.tell(new Failure(new NoShardLeaderException(String.format(
739 "Shard %s was the leader but has lost contact with all of its followers. Either all"
740 + " other follower nodes are down or this node is isolated by a network partition.",
741 persistenceId()))), getSelf());
748 protected boolean isIsolatedLeader() {
749 return getRaftState() == RaftState.IsolatedLeader;
752 @SuppressWarnings("checkstyle:IllegalCatch")
753 private void handleReadyLocalTransaction(final ReadyLocalTransaction message) {
754 LOG.debug("{}: handleReadyLocalTransaction for {}", persistenceId(), message.getTransactionId());
756 boolean isLeaderActive = isLeaderActive();
757 if (isLeader() && isLeaderActive) {
759 commitCoordinator.handleReadyLocalTransaction(message, getSender(), this);
760 } catch (Exception e) {
761 LOG.error("{}: Error handling ReadyLocalTransaction for Tx {}", persistenceId(),
762 message.getTransactionId(), e);
763 getSender().tell(new Failure(e), getSelf());
766 ActorSelection leader = getLeader();
767 if (!isLeaderActive || leader == null) {
768 messageRetrySupport.addMessageToRetry(message, getSender(),
769 "Could not process ready local transaction " + message.getTransactionId());
771 LOG.debug("{}: Forwarding ReadyLocalTransaction to leader {}", persistenceId(), leader);
772 message.setRemoteVersion(getCurrentBehavior().getLeaderPayloadVersion());
773 leader.forward(message, getContext());
778 private void handleForwardedReadyTransaction(final ForwardedReadyTransaction forwardedReady) {
779 LOG.debug("{}: handleForwardedReadyTransaction for {}", persistenceId(), forwardedReady.getTransactionId());
781 boolean isLeaderActive = isLeaderActive();
782 if (isLeader() && isLeaderActive) {
783 askProtocolEncountered(forwardedReady.getTransactionId());
784 commitCoordinator.handleForwardedReadyTransaction(forwardedReady, getSender(), this);
786 ActorSelection leader = getLeader();
787 if (!isLeaderActive || leader == null) {
788 messageRetrySupport.addMessageToRetry(forwardedReady, getSender(),
789 "Could not process forwarded ready transaction " + forwardedReady.getTransactionId());
791 LOG.debug("{}: Forwarding ForwardedReadyTransaction to leader {}", persistenceId(), leader);
793 ReadyLocalTransaction readyLocal = new ReadyLocalTransaction(forwardedReady.getTransactionId(),
794 forwardedReady.getTransaction().getSnapshot(), forwardedReady.isDoImmediateCommit(),
795 forwardedReady.getParticipatingShardNames());
796 readyLocal.setRemoteVersion(getCurrentBehavior().getLeaderPayloadVersion());
797 leader.forward(readyLocal, getContext());
802 private void handleAbortTransaction(final AbortTransaction abort) {
803 final TransactionIdentifier transactionId = abort.getTransactionId();
804 askProtocolEncountered(transactionId);
805 doAbortTransaction(transactionId, getSender());
808 void doAbortTransaction(final Identifier transactionID, final ActorRef sender) {
809 commitCoordinator.handleAbort(transactionID, sender, this);
812 private void handleCreateTransaction(final Object message) {
814 createTransaction(CreateTransaction.fromSerializable(message));
815 } else if (getLeader() != null) {
816 getLeader().forward(message, getContext());
818 getSender().tell(new Failure(new NoShardLeaderException(
819 "Could not create a shard transaction", persistenceId())), getSelf());
823 private void closeTransactionChain(final CloseTransactionChain closeTransactionChain) {
825 final LocalHistoryIdentifier id = closeTransactionChain.getIdentifier();
826 askProtocolEncountered(id.getClientId());
827 store.closeTransactionChain(id);
828 } else if (getLeader() != null) {
829 getLeader().forward(closeTransactionChain, getContext());
831 LOG.warn("{}: Could not close transaction {}", persistenceId(), closeTransactionChain.getIdentifier());
835 @SuppressWarnings("checkstyle:IllegalCatch")
836 private void createTransaction(final CreateTransaction createTransaction) {
837 askProtocolEncountered(createTransaction.getTransactionId());
840 if (TransactionType.fromInt(createTransaction.getTransactionType()) != TransactionType.READ_ONLY
841 && failIfIsolatedLeader(getSender())) {
845 ActorRef transactionActor = createTransaction(createTransaction.getTransactionType(),
846 createTransaction.getTransactionId());
848 getSender().tell(new CreateTransactionReply(Serialization.serializedActorPath(transactionActor),
849 createTransaction.getTransactionId(), createTransaction.getVersion()).toSerializable(), getSelf());
850 } catch (Exception e) {
851 getSender().tell(new Failure(e), getSelf());
855 private ActorRef createTransaction(final int transactionType, final TransactionIdentifier transactionId) {
856 LOG.debug("{}: Creating transaction : {} ", persistenceId(), transactionId);
857 return transactionActorFactory.newShardTransaction(TransactionType.fromInt(transactionType),
861 // Called on leader only
862 private void askProtocolEncountered(final TransactionIdentifier transactionId) {
863 askProtocolEncountered(transactionId.getHistoryId().getClientId());
866 // Called on leader only
867 private void askProtocolEncountered(final ClientIdentifier clientId) {
868 final FrontendIdentifier frontend = clientId.getFrontendId();
869 final LeaderFrontendState state = knownFrontends.get(frontend);
870 if (!(state instanceof LeaderFrontendState.Disabled)) {
871 LOG.debug("{}: encountered ask-based client {}, disabling transaction tracking", persistenceId(), clientId);
872 if (knownFrontends.isEmpty()) {
873 knownFrontends = new HashMap<>();
875 knownFrontends.put(frontend, new LeaderFrontendState.Disabled(persistenceId(), clientId, getDataStore()));
877 persistPayload(clientId, DisableTrackingPayload.create(clientId,
878 datastoreContext.getInitialPayloadSerializedBufferCapacity()), false);
882 private void updateSchemaContext(final UpdateSchemaContext message) {
883 updateSchemaContext(message.getSchemaContext());
887 void updateSchemaContext(final SchemaContext schemaContext) {
888 store.updateSchemaContext(schemaContext);
891 private boolean isMetricsCaptureEnabled() {
892 CommonConfig config = new CommonConfig(getContext().system().settings().config());
893 return config.isMetricCaptureEnabled();
898 public RaftActorSnapshotCohort getRaftActorSnapshotCohort() {
899 return snapshotCohort;
903 protected RaftActorRecoveryCohort getRaftActorRecoveryCohort() {
904 if (restoreFromSnapshot == null) {
905 return ShardRecoveryCoordinator.create(store, persistenceId(), LOG);
908 return ShardRecoveryCoordinator.forSnapshot(store, persistenceId(), LOG, restoreFromSnapshot.getSnapshot());
912 protected void onRecoveryComplete() {
913 restoreFromSnapshot = null;
915 //notify shard manager
916 getContext().parent().tell(new ActorInitialized(), getSelf());
918 // Being paranoid here - this method should only be called once but just in case...
919 if (txCommitTimeoutCheckSchedule == null) {
920 // Schedule a message to be periodically sent to check if the current in-progress
921 // transaction should be expired and aborted.
922 FiniteDuration period = FiniteDuration.create(transactionCommitTimeout / 3, TimeUnit.MILLISECONDS);
923 txCommitTimeoutCheckSchedule = getContext().system().scheduler().schedule(
924 period, period, getSelf(),
925 TX_COMMIT_TIMEOUT_CHECK_MESSAGE, getContext().dispatcher(), ActorRef.noSender());
930 protected void applyState(final ActorRef clientActor, final Identifier identifier, final Object data) {
931 if (data instanceof Payload) {
932 if (data instanceof DisableTrackingPayload) {
933 disableTracking((DisableTrackingPayload) data);
938 store.applyReplicatedPayload(identifier, (Payload)data);
939 } catch (DataValidationFailedException | IOException e) {
940 LOG.error("{}: Error applying replica {}", persistenceId(), identifier, e);
943 LOG.error("{}: Unknown state for {} received {}", persistenceId(), identifier, data);
948 protected void onStateChanged() {
949 boolean isLeader = isLeader();
950 boolean hasLeader = hasLeader();
951 treeChangeSupport.onLeadershipChange(isLeader, hasLeader);
953 // If this actor is no longer the leader close all the transaction chains
955 if (LOG.isDebugEnabled()) {
957 "{}: onStateChanged: Closing all transaction chains because shard {} is no longer the leader",
958 persistenceId(), getId());
962 store.purgeLeaderState();
965 if (hasLeader && !isIsolatedLeader()) {
966 messageRetrySupport.retryMessages();
971 protected void onLeaderChanged(final String oldLeader, final String newLeader) {
972 shardMBean.incrementLeadershipChangeCount();
976 if (!knownFrontends.isEmpty()) {
977 LOG.debug("{}: removing frontend state for {}", persistenceId(), knownFrontends.keySet());
978 knownFrontends = ImmutableMap.of();
981 requestMessageAssembler.close();
984 // No leader anywhere, nothing else to do
988 // Another leader was elected. If we were the previous leader and had pending transactions, convert
989 // them to transaction messages and send to the new leader.
990 ActorSelection leader = getLeader();
991 if (leader != null) {
992 Collection<?> messagesToForward = convertPendingTransactionsToMessages();
994 if (!messagesToForward.isEmpty()) {
995 LOG.debug("{}: Forwarding {} pending transaction messages to leader {}", persistenceId(),
996 messagesToForward.size(), leader);
998 for (Object message : messagesToForward) {
999 LOG.debug("{}: Forwarding pending transaction message {}", persistenceId(), message);
1001 leader.tell(message, self());
1005 commitCoordinator.abortPendingTransactions("The transacton was aborted due to inflight leadership "
1006 + "change and the leader address isn't available.", this);
1009 // We have become the leader, we need to reconstruct frontend state
1010 knownFrontends = Verify.verifyNotNull(frontendMetadata.toLeaderState(this));
1011 LOG.debug("{}: became leader with frontend state for {}", persistenceId(), knownFrontends.keySet());
1014 if (!isIsolatedLeader()) {
1015 messageRetrySupport.retryMessages();
1020 * Clears all pending transactions and converts them to messages to be forwarded to a new leader.
1022 * @return the converted messages
1024 public Collection<?> convertPendingTransactionsToMessages() {
1025 return commitCoordinator.convertPendingTransactionsToMessages(
1026 datastoreContext.getShardBatchedModificationCount());
1030 protected void pauseLeader(final Runnable operation) {
1031 LOG.debug("{}: In pauseLeader, operation: {}", persistenceId(), operation);
1034 // Tell-based protocol can replay transaction state, so it is safe to blow it up when we are paused.
1035 if (datastoreContext.isUseTellBasedProtocol()) {
1036 knownFrontends.values().forEach(LeaderFrontendState::retire);
1037 knownFrontends = ImmutableMap.of();
1040 store.setRunOnPendingTransactionsComplete(operation);
1044 protected void unpauseLeader() {
1045 LOG.debug("{}: In unpauseLeader", persistenceId());
1048 store.setRunOnPendingTransactionsComplete(null);
1050 // Restore tell-based protocol state as if we were becoming the leader
1051 knownFrontends = Verify.verifyNotNull(frontendMetadata.toLeaderState(this));
1055 protected OnDemandRaftState.AbstractBuilder<?, ?> newOnDemandRaftStateBuilder() {
1056 return OnDemandShardState.newBuilder().treeChangeListenerActors(treeChangeSupport.getListenerActors())
1057 .commitCohortActors(store.getCohortActors());
1061 public String persistenceId() {
1066 ShardCommitCoordinator getCommitCoordinator() {
1067 return commitCoordinator;
1070 public DatastoreContext getDatastoreContext() {
1071 return datastoreContext;
1075 public ShardDataTree getDataStore() {
1080 ShardStats getShardMBean() {
1084 public static Builder builder() {
1085 return new Builder();
1088 public abstract static class AbstractBuilder<T extends AbstractBuilder<T, S>, S extends Shard> {
1089 private final Class<? extends S> shardClass;
1090 private ShardIdentifier id;
1091 private Map<String, String> peerAddresses = Collections.emptyMap();
1092 private DatastoreContext datastoreContext;
1093 private SchemaContextProvider schemaContextProvider;
1094 private DatastoreSnapshot.ShardSnapshot restoreFromSnapshot;
1095 private DataTree dataTree;
1097 private volatile boolean sealed;
1099 protected AbstractBuilder(final Class<? extends S> shardClass) {
1100 this.shardClass = shardClass;
1103 protected void checkSealed() {
1104 Preconditions.checkState(!sealed, "Builder isalready sealed - further modifications are not allowed");
1107 @SuppressWarnings("unchecked")
1112 public T id(final ShardIdentifier newId) {
1118 public T peerAddresses(final Map<String, String> newPeerAddresses) {
1120 this.peerAddresses = newPeerAddresses;
1124 public T datastoreContext(final DatastoreContext newDatastoreContext) {
1126 this.datastoreContext = newDatastoreContext;
1130 public T schemaContextProvider(final SchemaContextProvider newSchemaContextProvider) {
1132 this.schemaContextProvider = Preconditions.checkNotNull(newSchemaContextProvider);
1136 public T restoreFromSnapshot(final DatastoreSnapshot.ShardSnapshot newRestoreFromSnapshot) {
1138 this.restoreFromSnapshot = newRestoreFromSnapshot;
1142 public T dataTree(final DataTree newDataTree) {
1144 this.dataTree = newDataTree;
1148 public ShardIdentifier getId() {
1152 public Map<String, String> getPeerAddresses() {
1153 return peerAddresses;
1156 public DatastoreContext getDatastoreContext() {
1157 return datastoreContext;
1160 public SchemaContext getSchemaContext() {
1161 return Verify.verifyNotNull(schemaContextProvider.getSchemaContext());
1164 public DatastoreSnapshot.ShardSnapshot getRestoreFromSnapshot() {
1165 return restoreFromSnapshot;
1168 public DataTree getDataTree() {
1172 public TreeType getTreeType() {
1173 switch (datastoreContext.getLogicalStoreType()) {
1175 return TreeType.CONFIGURATION;
1177 return TreeType.OPERATIONAL;
1179 throw new IllegalStateException("Unhandled logical store type "
1180 + datastoreContext.getLogicalStoreType());
1184 protected void verify() {
1185 Preconditions.checkNotNull(id, "id should not be null");
1186 Preconditions.checkNotNull(peerAddresses, "peerAddresses should not be null");
1187 Preconditions.checkNotNull(datastoreContext, "dataStoreContext should not be null");
1188 Preconditions.checkNotNull(schemaContextProvider, "schemaContextProvider should not be null");
1191 public Props props() {
1194 return Props.create(shardClass, this);
1198 public static class Builder extends AbstractBuilder<Builder, Shard> {
1203 Builder(Class<? extends Shard> shardClass) {
1209 return Ticker.systemTicker();
1212 void scheduleNextPendingTransaction() {
1213 self().tell(RESUME_NEXT_PENDING_TRANSACTION, ActorRef.noSender());