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.Range;
29 import java.io.IOException;
30 import java.util.Arrays;
31 import java.util.Collection;
32 import java.util.Collections;
33 import java.util.HashMap;
35 import java.util.Optional;
36 import java.util.OptionalLong;
37 import java.util.concurrent.TimeUnit;
38 import org.eclipse.jdt.annotation.NonNull;
39 import org.eclipse.jdt.annotation.Nullable;
40 import org.opendaylight.controller.cluster.access.ABIVersion;
41 import org.opendaylight.controller.cluster.access.commands.ConnectClientRequest;
42 import org.opendaylight.controller.cluster.access.commands.ConnectClientSuccess;
43 import org.opendaylight.controller.cluster.access.commands.LocalHistoryRequest;
44 import org.opendaylight.controller.cluster.access.commands.NotLeaderException;
45 import org.opendaylight.controller.cluster.access.commands.OutOfSequenceEnvelopeException;
46 import org.opendaylight.controller.cluster.access.commands.TransactionRequest;
47 import org.opendaylight.controller.cluster.access.concepts.ClientIdentifier;
48 import org.opendaylight.controller.cluster.access.concepts.FrontendIdentifier;
49 import org.opendaylight.controller.cluster.access.concepts.LocalHistoryIdentifier;
50 import org.opendaylight.controller.cluster.access.concepts.Request;
51 import org.opendaylight.controller.cluster.access.concepts.RequestEnvelope;
52 import org.opendaylight.controller.cluster.access.concepts.RequestException;
53 import org.opendaylight.controller.cluster.access.concepts.RequestSuccess;
54 import org.opendaylight.controller.cluster.access.concepts.RetiredGenerationException;
55 import org.opendaylight.controller.cluster.access.concepts.RuntimeRequestException;
56 import org.opendaylight.controller.cluster.access.concepts.SliceableMessage;
57 import org.opendaylight.controller.cluster.access.concepts.TransactionIdentifier;
58 import org.opendaylight.controller.cluster.access.concepts.UnsupportedRequestException;
59 import org.opendaylight.controller.cluster.common.actor.CommonConfig;
60 import org.opendaylight.controller.cluster.common.actor.Dispatchers;
61 import org.opendaylight.controller.cluster.common.actor.Dispatchers.DispatcherType;
62 import org.opendaylight.controller.cluster.common.actor.MessageTracker;
63 import org.opendaylight.controller.cluster.common.actor.MessageTracker.Error;
64 import org.opendaylight.controller.cluster.common.actor.MeteringBehavior;
65 import org.opendaylight.controller.cluster.datastore.exceptions.NoShardLeaderException;
66 import org.opendaylight.controller.cluster.datastore.identifiers.ShardIdentifier;
67 import org.opendaylight.controller.cluster.datastore.jmx.mbeans.shard.ShardDataTreeListenerInfoMXBeanImpl;
68 import org.opendaylight.controller.cluster.datastore.jmx.mbeans.shard.ShardMBeanFactory;
69 import org.opendaylight.controller.cluster.datastore.jmx.mbeans.shard.ShardStats;
70 import org.opendaylight.controller.cluster.datastore.messages.AbortTransaction;
71 import org.opendaylight.controller.cluster.datastore.messages.ActorInitialized;
72 import org.opendaylight.controller.cluster.datastore.messages.BatchedModifications;
73 import org.opendaylight.controller.cluster.datastore.messages.CanCommitTransaction;
74 import org.opendaylight.controller.cluster.datastore.messages.CloseTransactionChain;
75 import org.opendaylight.controller.cluster.datastore.messages.CommitTransaction;
76 import org.opendaylight.controller.cluster.datastore.messages.CreateTransaction;
77 import org.opendaylight.controller.cluster.datastore.messages.CreateTransactionReply;
78 import org.opendaylight.controller.cluster.datastore.messages.ForwardedReadyTransaction;
79 import org.opendaylight.controller.cluster.datastore.messages.GetShardDataTree;
80 import org.opendaylight.controller.cluster.datastore.messages.MakeLeaderLocal;
81 import org.opendaylight.controller.cluster.datastore.messages.OnDemandShardState;
82 import org.opendaylight.controller.cluster.datastore.messages.PeerAddressResolved;
83 import org.opendaylight.controller.cluster.datastore.messages.ReadyLocalTransaction;
84 import org.opendaylight.controller.cluster.datastore.messages.RegisterDataTreeChangeListener;
85 import org.opendaylight.controller.cluster.datastore.messages.ShardLeaderStateChanged;
86 import org.opendaylight.controller.cluster.datastore.messages.UpdateSchemaContext;
87 import org.opendaylight.controller.cluster.datastore.persisted.DatastoreSnapshot;
88 import org.opendaylight.controller.cluster.datastore.persisted.DatastoreSnapshot.ShardSnapshot;
89 import org.opendaylight.controller.cluster.datastore.persisted.DisableTrackingPayload;
90 import org.opendaylight.controller.cluster.messaging.MessageAssembler;
91 import org.opendaylight.controller.cluster.messaging.MessageSlicer;
92 import org.opendaylight.controller.cluster.messaging.SliceOptions;
93 import org.opendaylight.controller.cluster.notifications.LeaderStateChanged;
94 import org.opendaylight.controller.cluster.notifications.RegisterRoleChangeListener;
95 import org.opendaylight.controller.cluster.notifications.RoleChangeNotifier;
96 import org.opendaylight.controller.cluster.raft.LeadershipTransferFailedException;
97 import org.opendaylight.controller.cluster.raft.RaftActor;
98 import org.opendaylight.controller.cluster.raft.RaftActorRecoveryCohort;
99 import org.opendaylight.controller.cluster.raft.RaftActorSnapshotCohort;
100 import org.opendaylight.controller.cluster.raft.RaftState;
101 import org.opendaylight.controller.cluster.raft.base.messages.FollowerInitialSyncUpStatus;
102 import org.opendaylight.controller.cluster.raft.client.messages.OnDemandRaftState;
103 import org.opendaylight.controller.cluster.raft.messages.AppendEntriesReply;
104 import org.opendaylight.controller.cluster.raft.messages.RequestLeadership;
105 import org.opendaylight.controller.cluster.raft.messages.ServerRemoved;
106 import org.opendaylight.controller.cluster.raft.protobuff.client.messages.Payload;
107 import org.opendaylight.yangtools.concepts.Identifier;
108 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTree;
109 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataValidationFailedException;
110 import org.opendaylight.yangtools.yang.data.api.schema.tree.TreeType;
111 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
112 import org.opendaylight.yangtools.yang.model.api.SchemaContextProvider;
113 import scala.concurrent.duration.FiniteDuration;
116 * A Shard represents a portion of the logical data tree.
119 * Our Shard uses InMemoryDataTree as it's internal representation and delegates all requests it
121 public class Shard extends RaftActor {
124 static final Object TX_COMMIT_TIMEOUT_CHECK_MESSAGE = new Object() {
126 public String toString() {
127 return "txCommitTimeoutCheck";
132 static final Object GET_SHARD_MBEAN_MESSAGE = new Object() {
134 public String toString() {
135 return "getShardMBeanMessage";
139 static final Object RESUME_NEXT_PENDING_TRANSACTION = new Object() {
141 public String toString() {
142 return "resumeNextPendingTransaction";
146 // FIXME: shard names should be encapsulated in their own class and this should be exposed as a constant.
147 public static final String DEFAULT_NAME = "default";
149 private static final Collection<ABIVersion> SUPPORTED_ABIVERSIONS;
152 final ABIVersion[] values = ABIVersion.values();
153 final ABIVersion[] real = Arrays.copyOfRange(values, 1, values.length - 1);
154 SUPPORTED_ABIVERSIONS = ImmutableList.copyOf(real).reverse();
157 // FIXME: make this a dynamic property based on mailbox size and maximum number of clients
158 private static final int CLIENT_MAX_MESSAGES = 1000;
160 // The state of this Shard
161 private final ShardDataTree store;
163 /// The name of this shard
164 private final String name;
166 private final String shardName;
168 private final ShardStats shardMBean;
170 private final ShardDataTreeListenerInfoMXBeanImpl listenerInfoMXBean;
172 private DatastoreContext datastoreContext;
174 private final ShardCommitCoordinator commitCoordinator;
176 private long transactionCommitTimeout;
178 private Cancellable txCommitTimeoutCheckSchedule;
180 private final Optional<ActorRef> roleChangeNotifier;
182 private final MessageTracker appendEntriesReplyTracker;
184 private final ShardTransactionActorFactory transactionActorFactory;
186 private final ShardSnapshotCohort snapshotCohort;
188 private final DataTreeChangeListenerSupport treeChangeSupport = new DataTreeChangeListenerSupport(this);
190 private ShardSnapshot restoreFromSnapshot;
192 private final ShardTransactionMessageRetrySupport messageRetrySupport;
195 final FrontendMetadata frontendMetadata;
197 private Map<FrontendIdentifier, LeaderFrontendState> knownFrontends = ImmutableMap.of();
198 private boolean paused;
200 private final MessageSlicer responseMessageSlicer;
201 private final Dispatchers dispatchers;
203 private final MessageAssembler requestMessageAssembler;
205 protected Shard(final AbstractBuilder<?, ?> builder) {
206 super(builder.getId().toString(), builder.getPeerAddresses(),
207 Optional.of(builder.getDatastoreContext().getShardRaftConfig()), DataStoreVersions.CURRENT_VERSION);
209 this.name = builder.getId().toString();
210 this.shardName = builder.getId().getShardName();
211 this.datastoreContext = builder.getDatastoreContext();
212 this.restoreFromSnapshot = builder.getRestoreFromSnapshot();
213 this.frontendMetadata = new FrontendMetadata(name);
215 setPersistence(datastoreContext.isPersistent());
217 LOG.info("Shard created : {}, persistent : {}", name, datastoreContext.isPersistent());
219 ShardDataTreeChangeListenerPublisherActorProxy treeChangeListenerPublisher =
220 new ShardDataTreeChangeListenerPublisherActorProxy(getContext(), name + "-DTCL-publisher", name);
221 if (builder.getDataTree() != null) {
222 store = new ShardDataTree(this, builder.getSchemaContext(), builder.getDataTree(),
223 treeChangeListenerPublisher, name, frontendMetadata);
225 store = new ShardDataTree(this, builder.getSchemaContext(), builder.getTreeType(),
226 builder.getDatastoreContext().getStoreRoot(), treeChangeListenerPublisher, name, frontendMetadata);
229 shardMBean = ShardMBeanFactory.getShardStatsMBean(name, datastoreContext.getDataStoreMXBeanType(), this);
231 if (isMetricsCaptureEnabled()) {
232 getContext().become(new MeteringBehavior(this));
235 commitCoordinator = new ShardCommitCoordinator(store, LOG, this.name);
237 setTransactionCommitTimeout();
239 // create a notifier actor for each cluster member
240 roleChangeNotifier = createRoleChangeNotifier(name);
242 appendEntriesReplyTracker = new MessageTracker(AppendEntriesReply.class,
243 getRaftActorContext().getConfigParams().getIsolatedCheckIntervalInMillis());
245 dispatchers = new Dispatchers(context().system().dispatchers());
246 transactionActorFactory = new ShardTransactionActorFactory(store, datastoreContext,
247 dispatchers.getDispatcherPath(Dispatchers.DispatcherType.Transaction),
248 self(), getContext(), shardMBean, builder.getId().getShardName());
250 snapshotCohort = ShardSnapshotCohort.create(getContext(), builder.getId().getMemberName(), store, LOG,
253 messageRetrySupport = new ShardTransactionMessageRetrySupport(this);
255 responseMessageSlicer = MessageSlicer.builder().logContext(this.name)
256 .messageSliceSize(datastoreContext.getMaximumMessageSliceSize())
257 .fileBackedStreamFactory(getRaftActorContext().getFileBackedOutputStreamFactory())
258 .expireStateAfterInactivity(2, TimeUnit.MINUTES).build();
260 requestMessageAssembler = MessageAssembler.builder().logContext(this.name)
261 .fileBackedStreamFactory(getRaftActorContext().getFileBackedOutputStreamFactory())
262 .assembledMessageCallback((message, sender) -> self().tell(message, sender))
263 .expireStateAfterInactivity(datastoreContext.getRequestTimeout(), TimeUnit.NANOSECONDS).build();
265 listenerInfoMXBean = new ShardDataTreeListenerInfoMXBeanImpl(name, datastoreContext.getDataStoreMXBeanType(),
267 listenerInfoMXBean.register();
270 private void setTransactionCommitTimeout() {
271 transactionCommitTimeout = TimeUnit.MILLISECONDS.convert(
272 datastoreContext.getShardTransactionCommitTimeoutInSeconds(), TimeUnit.SECONDS) / 2;
275 private Optional<ActorRef> createRoleChangeNotifier(final String shardId) {
276 ActorRef shardRoleChangeNotifier = this.getContext().actorOf(
277 RoleChangeNotifier.getProps(shardId), shardId + "-notifier");
278 return Optional.of(shardRoleChangeNotifier);
282 public void postStop() throws Exception {
283 LOG.info("Stopping Shard {}", persistenceId());
287 messageRetrySupport.close();
289 if (txCommitTimeoutCheckSchedule != null) {
290 txCommitTimeoutCheckSchedule.cancel();
293 commitCoordinator.abortPendingTransactions("Transaction aborted due to shutdown.", this);
295 shardMBean.unregisterMBean();
296 listenerInfoMXBean.unregister();
300 protected void handleRecover(final Object message) {
301 LOG.debug("{}: onReceiveRecover: Received message {} from {}", persistenceId(), message.getClass(),
304 super.handleRecover(message);
305 if (LOG.isTraceEnabled()) {
306 appendEntriesReplyTracker.begin();
311 protected void handleNonRaftCommand(final Object message) {
312 try (MessageTracker.Context context = appendEntriesReplyTracker.received(message)) {
313 final Optional<Error> maybeError = context.error();
314 if (maybeError.isPresent()) {
315 LOG.trace("{} : AppendEntriesReply failed to arrive at the expected interval {}", persistenceId(),
319 store.resetTransactionBatch();
321 if (message instanceof RequestEnvelope) {
322 handleRequestEnvelope((RequestEnvelope)message);
323 } else if (MessageAssembler.isHandledMessage(message)) {
324 handleRequestAssemblerMessage(message);
325 } else if (message instanceof ConnectClientRequest) {
326 handleConnectClient((ConnectClientRequest)message);
327 } else if (CreateTransaction.isSerializedType(message)) {
328 handleCreateTransaction(message);
329 } else if (message instanceof BatchedModifications) {
330 handleBatchedModifications((BatchedModifications)message);
331 } else if (message instanceof ForwardedReadyTransaction) {
332 handleForwardedReadyTransaction((ForwardedReadyTransaction) message);
333 } else if (message instanceof ReadyLocalTransaction) {
334 handleReadyLocalTransaction((ReadyLocalTransaction)message);
335 } else if (CanCommitTransaction.isSerializedType(message)) {
336 handleCanCommitTransaction(CanCommitTransaction.fromSerializable(message));
337 } else if (CommitTransaction.isSerializedType(message)) {
338 handleCommitTransaction(CommitTransaction.fromSerializable(message));
339 } else if (AbortTransaction.isSerializedType(message)) {
340 handleAbortTransaction(AbortTransaction.fromSerializable(message));
341 } else if (CloseTransactionChain.isSerializedType(message)) {
342 closeTransactionChain(CloseTransactionChain.fromSerializable(message));
343 } else if (message instanceof RegisterDataTreeChangeListener) {
344 treeChangeSupport.onMessage((RegisterDataTreeChangeListener) message, isLeader(), hasLeader());
345 } else if (message instanceof UpdateSchemaContext) {
346 updateSchemaContext((UpdateSchemaContext) message);
347 } else if (message instanceof PeerAddressResolved) {
348 PeerAddressResolved resolved = (PeerAddressResolved) message;
349 setPeerAddress(resolved.getPeerId(), resolved.getPeerAddress());
350 } else if (TX_COMMIT_TIMEOUT_CHECK_MESSAGE.equals(message)) {
351 commitTimeoutCheck();
352 } else if (message instanceof DatastoreContext) {
353 onDatastoreContext((DatastoreContext)message);
354 } else if (message instanceof RegisterRoleChangeListener) {
355 roleChangeNotifier.get().forward(message, context());
356 } else if (message instanceof FollowerInitialSyncUpStatus) {
357 shardMBean.setFollowerInitialSyncStatus(((FollowerInitialSyncUpStatus) message).isInitialSyncDone());
358 context().parent().tell(message, self());
359 } else if (GET_SHARD_MBEAN_MESSAGE.equals(message)) {
360 sender().tell(getShardMBean(), self());
361 } else if (message instanceof GetShardDataTree) {
362 sender().tell(store.getDataTree(), self());
363 } else if (message instanceof ServerRemoved) {
364 context().parent().forward(message, context());
365 } else if (ShardTransactionMessageRetrySupport.TIMER_MESSAGE_CLASS.isInstance(message)) {
366 messageRetrySupport.onTimerMessage(message);
367 } else if (message instanceof DataTreeCohortActorRegistry.CohortRegistryCommand) {
368 store.processCohortRegistryCommand(getSender(),
369 (DataTreeCohortActorRegistry.CohortRegistryCommand) message);
370 } else if (message instanceof MakeLeaderLocal) {
372 } else if (RESUME_NEXT_PENDING_TRANSACTION.equals(message)) {
373 store.resumeNextPendingTransaction();
374 } else if (!responseMessageSlicer.handleMessage(message)) {
375 super.handleNonRaftCommand(message);
380 private void handleRequestAssemblerMessage(final Object message) {
381 dispatchers.getDispatcher(DispatcherType.Serialization).execute(() -> {
382 JavaSerializer.currentSystem().value_$eq((ExtendedActorSystem) context().system());
383 requestMessageAssembler.handleMessage(message, self());
387 @SuppressWarnings("checkstyle:IllegalCatch")
388 private void handleRequestEnvelope(final RequestEnvelope envelope) {
389 final long now = ticker().read();
391 final RequestSuccess<?, ?> success = handleRequest(envelope, now);
392 if (success != null) {
393 final long executionTimeNanos = ticker().read() - now;
394 if (success instanceof SliceableMessage) {
395 dispatchers.getDispatcher(DispatcherType.Serialization).execute(() ->
396 responseMessageSlicer.slice(SliceOptions.builder().identifier(success.getTarget())
397 .message(envelope.newSuccessEnvelope(success, executionTimeNanos))
398 .sendTo(envelope.getMessage().getReplyTo()).replyTo(self())
399 .onFailureCallback(t -> LOG.warn("Error slicing response {}", success, t)).build()));
401 envelope.sendSuccess(success, executionTimeNanos);
404 } catch (RequestException e) {
405 LOG.debug("{}: request {} failed", persistenceId(), envelope, e);
406 envelope.sendFailure(e, ticker().read() - now);
407 } catch (Exception e) {
408 LOG.debug("{}: request {} caused failure", persistenceId(), envelope, e);
409 envelope.sendFailure(new RuntimeRequestException("Request failed to process", e),
410 ticker().read() - now);
414 private void commitTimeoutCheck() {
415 store.checkForExpiredTransactions(transactionCommitTimeout, this::updateAccess);
416 commitCoordinator.checkForExpiredTransactions(transactionCommitTimeout, this);
417 requestMessageAssembler.checkExpiredAssembledMessageState();
420 private OptionalLong updateAccess(final SimpleShardDataTreeCohort cohort) {
421 final FrontendIdentifier frontend = cohort.getIdentifier().getHistoryId().getClientId().getFrontendId();
422 final LeaderFrontendState state = knownFrontends.get(frontend);
424 // Not tell-based protocol, do nothing
425 return OptionalLong.empty();
428 if (isIsolatedLeader()) {
429 // We are isolated and no new request can come through until we emerge from it. We are still updating
430 // liveness of frontend when we see it attempting to communicate. Use the last access timer.
431 return OptionalLong.of(state.getLastSeenTicks());
434 // If this frontend has freshly connected, give it some time to catch up before killing its transactions.
435 return OptionalLong.of(state.getLastConnectTicks());
438 private void disableTracking(final DisableTrackingPayload payload) {
439 final ClientIdentifier clientId = payload.getIdentifier();
440 LOG.debug("{}: disabling tracking of {}", persistenceId(), clientId);
441 frontendMetadata.disableTracking(clientId);
444 final FrontendIdentifier frontendId = clientId.getFrontendId();
445 final LeaderFrontendState frontend = knownFrontends.get(frontendId);
446 if (frontend != null) {
447 if (clientId.equals(frontend.getIdentifier())) {
448 if (!(frontend instanceof LeaderFrontendState.Disabled)) {
449 verify(knownFrontends.replace(frontendId, frontend,
450 new LeaderFrontendState.Disabled(persistenceId(), clientId, store)));
451 LOG.debug("{}: leader state for {} disabled", persistenceId(), clientId);
453 LOG.debug("{}: leader state {} is already disabled", persistenceId(), frontend);
456 LOG.debug("{}: leader state {} does not match {}", persistenceId(), frontend, clientId);
459 LOG.debug("{}: leader state for {} not found", persistenceId(), clientId);
460 knownFrontends.put(frontendId, new LeaderFrontendState.Disabled(persistenceId(), clientId,
466 private void onMakeLeaderLocal() {
467 LOG.debug("{}: onMakeLeaderLocal received", persistenceId());
469 getSender().tell(new Status.Success(null), getSelf());
473 final ActorSelection leader = getLeader();
475 if (leader == null) {
476 // Leader is not present. The cluster is most likely trying to
477 // elect a leader and we should let that run its normal course
479 // TODO we can wait for the election to complete and retry the
480 // request. We can also let the caller retry by sending a flag
481 // in the response indicating the request is "reTryable".
482 getSender().tell(new Failure(
483 new LeadershipTransferFailedException("We cannot initiate leadership transfer to local node. "
484 + "Currently there is no leader for " + persistenceId())),
489 leader.tell(new RequestLeadership(getId(), getSender()), getSelf());
492 // Acquire our frontend tracking handle and verify generation matches
493 private @Nullable LeaderFrontendState findFrontend(final ClientIdentifier clientId) throws RequestException {
494 final LeaderFrontendState existing = knownFrontends.get(clientId.getFrontendId());
495 if (existing != null) {
496 final int cmp = Long.compareUnsigned(existing.getIdentifier().getGeneration(), clientId.getGeneration());
502 LOG.debug("{}: rejecting request from outdated client {}", persistenceId(), clientId);
503 throw new RetiredGenerationException(clientId.getGeneration(),
504 existing.getIdentifier().getGeneration());
507 LOG.info("{}: retiring state {}, outdated by request from client {}", persistenceId(), existing, clientId);
509 knownFrontends.remove(clientId.getFrontendId());
511 LOG.debug("{}: client {} is not yet known", persistenceId(), clientId);
517 private LeaderFrontendState getFrontend(final ClientIdentifier clientId) throws RequestException {
518 final LeaderFrontendState ret = findFrontend(clientId);
523 // TODO: a dedicated exception would be better, but this is technically true, too
524 throw new OutOfSequenceEnvelopeException(0);
527 private static @NonNull ABIVersion selectVersion(final ConnectClientRequest message) {
528 final Range<ABIVersion> clientRange = Range.closed(message.getMinVersion(), message.getMaxVersion());
529 for (ABIVersion v : SUPPORTED_ABIVERSIONS) {
530 if (clientRange.contains(v)) {
535 throw new IllegalArgumentException(String.format(
536 "No common version between backend versions %s and client versions %s", SUPPORTED_ABIVERSIONS,
540 @SuppressWarnings("checkstyle:IllegalCatch")
541 private void handleConnectClient(final ConnectClientRequest message) {
543 final ClientIdentifier clientId = message.getTarget();
544 final LeaderFrontendState existing = findFrontend(clientId);
545 if (existing != null) {
549 if (!isLeader() || !isLeaderActive()) {
550 LOG.info("{}: not currently leader, rejecting request {}. isLeader: {}, isLeaderActive: {},"
551 + "isLeadershipTransferInProgress: {}.",
552 persistenceId(), message, isLeader(), isLeaderActive(), isLeadershipTransferInProgress());
553 throw new NotLeaderException(getSelf());
556 final ABIVersion selectedVersion = selectVersion(message);
557 final LeaderFrontendState frontend;
558 if (existing == null) {
559 frontend = new LeaderFrontendState.Enabled(persistenceId(), clientId, store);
560 knownFrontends.put(clientId.getFrontendId(), frontend);
561 LOG.debug("{}: created state {} for client {}", persistenceId(), frontend, clientId);
566 frontend.reconnect();
567 message.getReplyTo().tell(new ConnectClientSuccess(message.getTarget(), message.getSequence(), getSelf(),
568 ImmutableList.of(), store.getDataTree(), CLIENT_MAX_MESSAGES).toVersion(selectedVersion),
569 ActorRef.noSender());
570 } catch (RequestException | RuntimeException e) {
571 message.getReplyTo().tell(new Failure(e), ActorRef.noSender());
575 private @Nullable RequestSuccess<?, ?> handleRequest(final RequestEnvelope envelope, final long now)
576 throws RequestException {
577 // We are not the leader, hence we want to fail-fast.
578 if (!isLeader() || paused || !isLeaderActive()) {
579 LOG.debug("{}: not currently active leader, rejecting request {}. isLeader: {}, isLeaderActive: {},"
580 + "isLeadershipTransferInProgress: {}, paused: {}",
581 persistenceId(), envelope, isLeader(), isLeaderActive(), isLeadershipTransferInProgress(), paused);
582 throw new NotLeaderException(getSelf());
585 final Request<?, ?> request = envelope.getMessage();
586 if (request instanceof TransactionRequest) {
587 final TransactionRequest<?> txReq = (TransactionRequest<?>)request;
588 final ClientIdentifier clientId = txReq.getTarget().getHistoryId().getClientId();
589 return getFrontend(clientId).handleTransactionRequest(txReq, envelope, now);
590 } else if (request instanceof LocalHistoryRequest) {
591 final LocalHistoryRequest<?> lhReq = (LocalHistoryRequest<?>)request;
592 final ClientIdentifier clientId = lhReq.getTarget().getClientId();
593 return getFrontend(clientId).handleLocalHistoryRequest(lhReq, envelope, now);
595 LOG.warn("{}: rejecting unsupported request {}", persistenceId(), request);
596 throw new UnsupportedRequestException(request);
600 private boolean hasLeader() {
601 return getLeaderId() != null;
604 public int getPendingTxCommitQueueSize() {
605 return store.getQueueSize();
608 public int getCohortCacheSize() {
609 return commitCoordinator.getCohortCacheSize();
613 protected Optional<ActorRef> getRoleChangeNotifier() {
614 return roleChangeNotifier;
617 String getShardName() {
622 protected LeaderStateChanged newLeaderStateChanged(final String memberId, final String leaderId,
623 final short leaderPayloadVersion) {
624 return isLeader() ? new ShardLeaderStateChanged(memberId, leaderId, store.getDataTree(), leaderPayloadVersion)
625 : new ShardLeaderStateChanged(memberId, leaderId, leaderPayloadVersion);
628 protected void onDatastoreContext(final DatastoreContext context) {
629 datastoreContext = context;
631 setTransactionCommitTimeout();
633 setPersistence(datastoreContext.isPersistent());
635 updateConfigParams(datastoreContext.getShardRaftConfig());
638 // applyState() will be invoked once consensus is reached on the payload
639 void persistPayload(final Identifier id, final Payload payload, final boolean batchHint) {
640 boolean canSkipPayload = !hasFollowers() && !persistence().isRecoveryApplicable();
641 if (canSkipPayload) {
642 applyState(self(), id, payload);
644 // We are faking the sender
645 persistData(self(), id, payload, batchHint);
649 private void handleCommitTransaction(final CommitTransaction commit) {
650 final TransactionIdentifier txId = commit.getTransactionId();
652 askProtocolEncountered(txId);
653 commitCoordinator.handleCommit(txId, getSender(), this);
655 ActorSelection leader = getLeader();
656 if (leader == null) {
657 messageRetrySupport.addMessageToRetry(commit, getSender(), "Could not commit transaction " + txId);
659 LOG.debug("{}: Forwarding CommitTransaction to leader {}", persistenceId(), leader);
660 leader.forward(commit, getContext());
665 private void handleCanCommitTransaction(final CanCommitTransaction canCommit) {
666 final TransactionIdentifier txId = canCommit.getTransactionId();
667 LOG.debug("{}: Can committing transaction {}", persistenceId(), txId);
670 askProtocolEncountered(txId);
671 commitCoordinator.handleCanCommit(txId, getSender(), this);
673 ActorSelection leader = getLeader();
674 if (leader == null) {
675 messageRetrySupport.addMessageToRetry(canCommit, getSender(),
676 "Could not canCommit transaction " + txId);
678 LOG.debug("{}: Forwarding CanCommitTransaction to leader {}", persistenceId(), leader);
679 leader.forward(canCommit, getContext());
684 @SuppressWarnings("checkstyle:IllegalCatch")
685 protected void handleBatchedModificationsLocal(final BatchedModifications batched, final ActorRef sender) {
686 askProtocolEncountered(batched.getTransactionId());
689 commitCoordinator.handleBatchedModifications(batched, sender, this);
690 } catch (Exception e) {
691 LOG.error("{}: Error handling BatchedModifications for Tx {}", persistenceId(),
692 batched.getTransactionId(), e);
693 sender.tell(new Failure(e), getSelf());
697 private void handleBatchedModifications(final BatchedModifications batched) {
698 // This message is sent to prepare the modifications transaction directly on the Shard as an
699 // optimization to avoid the extra overhead of a separate ShardTransaction actor. On the last
700 // BatchedModifications message, the caller sets the ready flag in the message indicating
701 // modifications are complete. The reply contains the cohort actor path (this actor) for the caller
702 // to initiate the 3-phase commit. This also avoids the overhead of sending an additional
703 // ReadyTransaction message.
705 // If we're not the leader then forward to the leader. This is a safety measure - we shouldn't
706 // normally get here if we're not the leader as the front-end (TransactionProxy) should determine
707 // the primary/leader shard. However with timing and caching on the front-end, there's a small
708 // window where it could have a stale leader during leadership transitions.
710 boolean isLeaderActive = isLeaderActive();
711 if (isLeader() && isLeaderActive) {
712 handleBatchedModificationsLocal(batched, getSender());
714 ActorSelection leader = getLeader();
715 if (!isLeaderActive || leader == null) {
716 messageRetrySupport.addMessageToRetry(batched, getSender(),
717 "Could not process BatchedModifications " + batched.getTransactionId());
719 // If this is not the first batch and leadership changed in between batched messages,
720 // we need to reconstruct previous BatchedModifications from the transaction
721 // DataTreeModification, honoring the max batched modification count, and forward all the
722 // previous BatchedModifications to the new leader.
723 Collection<BatchedModifications> newModifications = commitCoordinator
724 .createForwardedBatchedModifications(batched,
725 datastoreContext.getShardBatchedModificationCount());
727 LOG.debug("{}: Forwarding {} BatchedModifications to leader {}", persistenceId(),
728 newModifications.size(), leader);
730 for (BatchedModifications bm : newModifications) {
731 leader.forward(bm, getContext());
737 private boolean failIfIsolatedLeader(final ActorRef sender) {
738 if (isIsolatedLeader()) {
739 sender.tell(new Failure(new NoShardLeaderException(String.format(
740 "Shard %s was the leader but has lost contact with all of its followers. Either all"
741 + " other follower nodes are down or this node is isolated by a network partition.",
742 persistenceId()))), getSelf());
749 protected boolean isIsolatedLeader() {
750 return getRaftState() == RaftState.IsolatedLeader;
753 @SuppressWarnings("checkstyle:IllegalCatch")
754 private void handleReadyLocalTransaction(final ReadyLocalTransaction message) {
755 LOG.debug("{}: handleReadyLocalTransaction for {}", persistenceId(), message.getTransactionId());
757 boolean isLeaderActive = isLeaderActive();
758 if (isLeader() && isLeaderActive) {
760 commitCoordinator.handleReadyLocalTransaction(message, getSender(), this);
761 } catch (Exception e) {
762 LOG.error("{}: Error handling ReadyLocalTransaction for Tx {}", persistenceId(),
763 message.getTransactionId(), e);
764 getSender().tell(new Failure(e), getSelf());
767 ActorSelection leader = getLeader();
768 if (!isLeaderActive || leader == null) {
769 messageRetrySupport.addMessageToRetry(message, getSender(),
770 "Could not process ready local transaction " + message.getTransactionId());
772 LOG.debug("{}: Forwarding ReadyLocalTransaction to leader {}", persistenceId(), leader);
773 message.setRemoteVersion(getCurrentBehavior().getLeaderPayloadVersion());
774 leader.forward(message, getContext());
779 private void handleForwardedReadyTransaction(final ForwardedReadyTransaction forwardedReady) {
780 LOG.debug("{}: handleForwardedReadyTransaction for {}", persistenceId(), forwardedReady.getTransactionId());
782 boolean isLeaderActive = isLeaderActive();
783 if (isLeader() && isLeaderActive) {
784 askProtocolEncountered(forwardedReady.getTransactionId());
785 commitCoordinator.handleForwardedReadyTransaction(forwardedReady, getSender(), this);
787 ActorSelection leader = getLeader();
788 if (!isLeaderActive || leader == null) {
789 messageRetrySupport.addMessageToRetry(forwardedReady, getSender(),
790 "Could not process forwarded ready transaction " + forwardedReady.getTransactionId());
792 LOG.debug("{}: Forwarding ForwardedReadyTransaction to leader {}", persistenceId(), leader);
794 ReadyLocalTransaction readyLocal = new ReadyLocalTransaction(forwardedReady.getTransactionId(),
795 forwardedReady.getTransaction().getSnapshot(), forwardedReady.isDoImmediateCommit(),
796 forwardedReady.getParticipatingShardNames());
797 readyLocal.setRemoteVersion(getCurrentBehavior().getLeaderPayloadVersion());
798 leader.forward(readyLocal, getContext());
803 private void handleAbortTransaction(final AbortTransaction abort) {
804 final TransactionIdentifier transactionId = abort.getTransactionId();
805 askProtocolEncountered(transactionId);
806 doAbortTransaction(transactionId, getSender());
809 void doAbortTransaction(final Identifier transactionID, final ActorRef sender) {
810 commitCoordinator.handleAbort(transactionID, sender, this);
813 private void handleCreateTransaction(final Object message) {
815 createTransaction(CreateTransaction.fromSerializable(message));
816 } else if (getLeader() != null) {
817 getLeader().forward(message, getContext());
819 getSender().tell(new Failure(new NoShardLeaderException(
820 "Could not create a shard transaction", persistenceId())), getSelf());
824 private void closeTransactionChain(final CloseTransactionChain closeTransactionChain) {
826 final LocalHistoryIdentifier id = closeTransactionChain.getIdentifier();
827 askProtocolEncountered(id.getClientId());
828 store.closeTransactionChain(id);
829 } else if (getLeader() != null) {
830 getLeader().forward(closeTransactionChain, getContext());
832 LOG.warn("{}: Could not close transaction {}", persistenceId(), closeTransactionChain.getIdentifier());
836 @SuppressWarnings("checkstyle:IllegalCatch")
837 private void createTransaction(final CreateTransaction createTransaction) {
838 askProtocolEncountered(createTransaction.getTransactionId());
841 if (TransactionType.fromInt(createTransaction.getTransactionType()) != TransactionType.READ_ONLY
842 && failIfIsolatedLeader(getSender())) {
846 ActorRef transactionActor = createTransaction(createTransaction.getTransactionType(),
847 createTransaction.getTransactionId());
849 getSender().tell(new CreateTransactionReply(Serialization.serializedActorPath(transactionActor),
850 createTransaction.getTransactionId(), createTransaction.getVersion()).toSerializable(), getSelf());
851 } catch (Exception e) {
852 getSender().tell(new Failure(e), getSelf());
856 private ActorRef createTransaction(final int transactionType, final TransactionIdentifier transactionId) {
857 LOG.debug("{}: Creating transaction : {} ", persistenceId(), transactionId);
858 return transactionActorFactory.newShardTransaction(TransactionType.fromInt(transactionType),
862 // Called on leader only
863 private void askProtocolEncountered(final TransactionIdentifier transactionId) {
864 askProtocolEncountered(transactionId.getHistoryId().getClientId());
867 // Called on leader only
868 private void askProtocolEncountered(final ClientIdentifier clientId) {
869 final FrontendIdentifier frontend = clientId.getFrontendId();
870 final LeaderFrontendState state = knownFrontends.get(frontend);
871 if (!(state instanceof LeaderFrontendState.Disabled)) {
872 LOG.debug("{}: encountered ask-based client {}, disabling transaction tracking", persistenceId(), clientId);
873 if (knownFrontends.isEmpty()) {
874 knownFrontends = new HashMap<>();
876 knownFrontends.put(frontend, new LeaderFrontendState.Disabled(persistenceId(), clientId, getDataStore()));
878 persistPayload(clientId, DisableTrackingPayload.create(clientId,
879 datastoreContext.getInitialPayloadSerializedBufferCapacity()), false);
883 private void updateSchemaContext(final UpdateSchemaContext message) {
884 updateSchemaContext(message.getSchemaContext());
888 void updateSchemaContext(final SchemaContext schemaContext) {
889 store.updateSchemaContext(schemaContext);
892 private boolean isMetricsCaptureEnabled() {
893 CommonConfig config = new CommonConfig(getContext().system().settings().config());
894 return config.isMetricCaptureEnabled();
899 public RaftActorSnapshotCohort getRaftActorSnapshotCohort() {
900 return snapshotCohort;
904 protected RaftActorRecoveryCohort getRaftActorRecoveryCohort() {
905 if (restoreFromSnapshot == null) {
906 return ShardRecoveryCoordinator.create(store, persistenceId(), LOG);
909 return ShardRecoveryCoordinator.forSnapshot(store, persistenceId(), LOG, restoreFromSnapshot.getSnapshot());
913 protected void onRecoveryComplete() {
914 restoreFromSnapshot = null;
916 //notify shard manager
917 getContext().parent().tell(new ActorInitialized(), getSelf());
919 // Being paranoid here - this method should only be called once but just in case...
920 if (txCommitTimeoutCheckSchedule == null) {
921 // Schedule a message to be periodically sent to check if the current in-progress
922 // transaction should be expired and aborted.
923 FiniteDuration period = FiniteDuration.create(transactionCommitTimeout / 3, TimeUnit.MILLISECONDS);
924 txCommitTimeoutCheckSchedule = getContext().system().scheduler().schedule(
925 period, period, getSelf(),
926 TX_COMMIT_TIMEOUT_CHECK_MESSAGE, getContext().dispatcher(), ActorRef.noSender());
931 protected void applyState(final ActorRef clientActor, final Identifier identifier, final Object data) {
932 if (data instanceof Payload) {
933 if (data instanceof DisableTrackingPayload) {
934 disableTracking((DisableTrackingPayload) data);
939 store.applyReplicatedPayload(identifier, (Payload)data);
940 } catch (DataValidationFailedException | IOException e) {
941 LOG.error("{}: Error applying replica {}", persistenceId(), identifier, e);
944 LOG.error("{}: Unknown state for {} received {}", persistenceId(), identifier, data);
949 protected void onStateChanged() {
950 boolean isLeader = isLeader();
951 boolean hasLeader = hasLeader();
952 treeChangeSupport.onLeadershipChange(isLeader, hasLeader);
954 // If this actor is no longer the leader close all the transaction chains
956 if (LOG.isDebugEnabled()) {
958 "{}: onStateChanged: Closing all transaction chains because shard {} is no longer the leader",
959 persistenceId(), getId());
963 store.purgeLeaderState();
966 if (hasLeader && !isIsolatedLeader()) {
967 messageRetrySupport.retryMessages();
972 protected void onLeaderChanged(final String oldLeader, final String newLeader) {
973 shardMBean.incrementLeadershipChangeCount();
977 if (!knownFrontends.isEmpty()) {
978 LOG.debug("{}: removing frontend state for {}", persistenceId(), knownFrontends.keySet());
979 knownFrontends = ImmutableMap.of();
982 requestMessageAssembler.close();
985 // No leader anywhere, nothing else to do
989 // Another leader was elected. If we were the previous leader and had pending transactions, convert
990 // them to transaction messages and send to the new leader.
991 ActorSelection leader = getLeader();
992 if (leader != null) {
993 Collection<?> messagesToForward = convertPendingTransactionsToMessages();
995 if (!messagesToForward.isEmpty()) {
996 LOG.debug("{}: Forwarding {} pending transaction messages to leader {}", persistenceId(),
997 messagesToForward.size(), leader);
999 for (Object message : messagesToForward) {
1000 LOG.debug("{}: Forwarding pending transaction message {}", persistenceId(), message);
1002 leader.tell(message, self());
1006 commitCoordinator.abortPendingTransactions("The transacton was aborted due to inflight leadership "
1007 + "change and the leader address isn't available.", this);
1010 // We have become the leader, we need to reconstruct frontend state
1011 knownFrontends = Verify.verifyNotNull(frontendMetadata.toLeaderState(this));
1012 LOG.debug("{}: became leader with frontend state for {}", persistenceId(), knownFrontends.keySet());
1015 if (!isIsolatedLeader()) {
1016 messageRetrySupport.retryMessages();
1021 * Clears all pending transactions and converts them to messages to be forwarded to a new leader.
1023 * @return the converted messages
1025 public Collection<?> convertPendingTransactionsToMessages() {
1026 return commitCoordinator.convertPendingTransactionsToMessages(
1027 datastoreContext.getShardBatchedModificationCount());
1031 protected void pauseLeader(final Runnable operation) {
1032 LOG.debug("{}: In pauseLeader, operation: {}", persistenceId(), operation);
1035 // Tell-based protocol can replay transaction state, so it is safe to blow it up when we are paused.
1036 if (datastoreContext.isUseTellBasedProtocol()) {
1037 knownFrontends.values().forEach(LeaderFrontendState::retire);
1038 knownFrontends = ImmutableMap.of();
1041 store.setRunOnPendingTransactionsComplete(operation);
1045 protected void unpauseLeader() {
1046 LOG.debug("{}: In unpauseLeader", persistenceId());
1049 store.setRunOnPendingTransactionsComplete(null);
1051 // Restore tell-based protocol state as if we were becoming the leader
1052 knownFrontends = Verify.verifyNotNull(frontendMetadata.toLeaderState(this));
1056 protected OnDemandRaftState.AbstractBuilder<?, ?> newOnDemandRaftStateBuilder() {
1057 return OnDemandShardState.newBuilder().treeChangeListenerActors(treeChangeSupport.getListenerActors())
1058 .commitCohortActors(store.getCohortActors());
1062 public String persistenceId() {
1067 ShardCommitCoordinator getCommitCoordinator() {
1068 return commitCoordinator;
1071 public DatastoreContext getDatastoreContext() {
1072 return datastoreContext;
1076 public ShardDataTree getDataStore() {
1081 ShardStats getShardMBean() {
1085 public static Builder builder() {
1086 return new Builder();
1089 public abstract static class AbstractBuilder<T extends AbstractBuilder<T, S>, S extends Shard> {
1090 private final Class<? extends S> shardClass;
1091 private ShardIdentifier id;
1092 private Map<String, String> peerAddresses = Collections.emptyMap();
1093 private DatastoreContext datastoreContext;
1094 private SchemaContextProvider schemaContextProvider;
1095 private DatastoreSnapshot.ShardSnapshot restoreFromSnapshot;
1096 private DataTree dataTree;
1098 private volatile boolean sealed;
1100 protected AbstractBuilder(final Class<? extends S> shardClass) {
1101 this.shardClass = shardClass;
1104 protected void checkSealed() {
1105 checkState(!sealed, "Builder isalready sealed - further modifications are not allowed");
1108 @SuppressWarnings("unchecked")
1113 public T id(final ShardIdentifier newId) {
1119 public T peerAddresses(final Map<String, String> newPeerAddresses) {
1121 this.peerAddresses = newPeerAddresses;
1125 public T datastoreContext(final DatastoreContext newDatastoreContext) {
1127 this.datastoreContext = newDatastoreContext;
1131 public T schemaContextProvider(final SchemaContextProvider newSchemaContextProvider) {
1133 this.schemaContextProvider = requireNonNull(newSchemaContextProvider);
1137 public T restoreFromSnapshot(final DatastoreSnapshot.ShardSnapshot newRestoreFromSnapshot) {
1139 this.restoreFromSnapshot = newRestoreFromSnapshot;
1143 public T dataTree(final DataTree newDataTree) {
1145 this.dataTree = newDataTree;
1149 public ShardIdentifier getId() {
1153 public Map<String, String> getPeerAddresses() {
1154 return peerAddresses;
1157 public DatastoreContext getDatastoreContext() {
1158 return datastoreContext;
1161 public SchemaContext getSchemaContext() {
1162 return Verify.verifyNotNull(schemaContextProvider.getSchemaContext());
1165 public DatastoreSnapshot.ShardSnapshot getRestoreFromSnapshot() {
1166 return restoreFromSnapshot;
1169 public DataTree getDataTree() {
1173 public TreeType getTreeType() {
1174 switch (datastoreContext.getLogicalStoreType()) {
1176 return TreeType.CONFIGURATION;
1178 return TreeType.OPERATIONAL;
1180 throw new IllegalStateException("Unhandled logical store type "
1181 + datastoreContext.getLogicalStoreType());
1185 protected void verify() {
1186 requireNonNull(id, "id should not be null");
1187 requireNonNull(peerAddresses, "peerAddresses should not be null");
1188 requireNonNull(datastoreContext, "dataStoreContext should not be null");
1189 requireNonNull(schemaContextProvider, "schemaContextProvider should not be null");
1192 public Props props() {
1195 return Props.create(shardClass, this);
1199 public static class Builder extends AbstractBuilder<Builder, Shard> {
1204 Builder(final Class<? extends Shard> shardClass) {
1210 return Ticker.systemTicker();
1213 void scheduleNextPendingTransaction() {
1214 self().tell(RESUME_NEXT_PENDING_TRANSACTION, ActorRef.noSender());