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.Optional;
23 import com.google.common.base.Preconditions;
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.concurrent.TimeUnit;
36 import javax.annotation.Nonnull;
37 import javax.annotation.Nullable;
38 import org.opendaylight.controller.cluster.access.ABIVersion;
39 import org.opendaylight.controller.cluster.access.commands.ConnectClientRequest;
40 import org.opendaylight.controller.cluster.access.commands.ConnectClientSuccess;
41 import org.opendaylight.controller.cluster.access.commands.LocalHistoryRequest;
42 import org.opendaylight.controller.cluster.access.commands.NotLeaderException;
43 import org.opendaylight.controller.cluster.access.commands.OutOfSequenceEnvelopeException;
44 import org.opendaylight.controller.cluster.access.commands.TransactionRequest;
45 import org.opendaylight.controller.cluster.access.concepts.ClientIdentifier;
46 import org.opendaylight.controller.cluster.access.concepts.FrontendIdentifier;
47 import org.opendaylight.controller.cluster.access.concepts.LocalHistoryIdentifier;
48 import org.opendaylight.controller.cluster.access.concepts.Request;
49 import org.opendaylight.controller.cluster.access.concepts.RequestEnvelope;
50 import org.opendaylight.controller.cluster.access.concepts.RequestException;
51 import org.opendaylight.controller.cluster.access.concepts.RequestSuccess;
52 import org.opendaylight.controller.cluster.access.concepts.RetiredGenerationException;
53 import org.opendaylight.controller.cluster.access.concepts.RuntimeRequestException;
54 import org.opendaylight.controller.cluster.access.concepts.SliceableMessage;
55 import org.opendaylight.controller.cluster.access.concepts.TransactionIdentifier;
56 import org.opendaylight.controller.cluster.access.concepts.UnsupportedRequestException;
57 import org.opendaylight.controller.cluster.common.actor.CommonConfig;
58 import org.opendaylight.controller.cluster.common.actor.Dispatchers;
59 import org.opendaylight.controller.cluster.common.actor.Dispatchers.DispatcherType;
60 import org.opendaylight.controller.cluster.common.actor.MessageTracker;
61 import org.opendaylight.controller.cluster.common.actor.MessageTracker.Error;
62 import org.opendaylight.controller.cluster.common.actor.MeteringBehavior;
63 import org.opendaylight.controller.cluster.datastore.exceptions.NoShardLeaderException;
64 import org.opendaylight.controller.cluster.datastore.identifiers.ShardIdentifier;
65 import org.opendaylight.controller.cluster.datastore.jmx.mbeans.shard.ShardDataTreeListenerInfoMXBeanImpl;
66 import org.opendaylight.controller.cluster.datastore.jmx.mbeans.shard.ShardMBeanFactory;
67 import org.opendaylight.controller.cluster.datastore.jmx.mbeans.shard.ShardStats;
68 import org.opendaylight.controller.cluster.datastore.messages.AbortTransaction;
69 import org.opendaylight.controller.cluster.datastore.messages.ActorInitialized;
70 import org.opendaylight.controller.cluster.datastore.messages.BatchedModifications;
71 import org.opendaylight.controller.cluster.datastore.messages.CanCommitTransaction;
72 import org.opendaylight.controller.cluster.datastore.messages.CloseTransactionChain;
73 import org.opendaylight.controller.cluster.datastore.messages.CommitTransaction;
74 import org.opendaylight.controller.cluster.datastore.messages.CreateTransaction;
75 import org.opendaylight.controller.cluster.datastore.messages.CreateTransactionReply;
76 import org.opendaylight.controller.cluster.datastore.messages.ForwardedReadyTransaction;
77 import org.opendaylight.controller.cluster.datastore.messages.GetShardDataTree;
78 import org.opendaylight.controller.cluster.datastore.messages.MakeLeaderLocal;
79 import org.opendaylight.controller.cluster.datastore.messages.OnDemandShardState;
80 import org.opendaylight.controller.cluster.datastore.messages.PeerAddressResolved;
81 import org.opendaylight.controller.cluster.datastore.messages.ReadyLocalTransaction;
82 import org.opendaylight.controller.cluster.datastore.messages.RegisterDataTreeChangeListener;
83 import org.opendaylight.controller.cluster.datastore.messages.ShardLeaderStateChanged;
84 import org.opendaylight.controller.cluster.datastore.messages.UpdateSchemaContext;
85 import org.opendaylight.controller.cluster.datastore.persisted.DatastoreSnapshot;
86 import org.opendaylight.controller.cluster.datastore.persisted.DatastoreSnapshot.ShardSnapshot;
87 import org.opendaylight.controller.cluster.datastore.persisted.DisableTrackingPayload;
88 import org.opendaylight.controller.cluster.messaging.MessageAssembler;
89 import org.opendaylight.controller.cluster.messaging.MessageSlicer;
90 import org.opendaylight.controller.cluster.messaging.SliceOptions;
91 import org.opendaylight.controller.cluster.notifications.LeaderStateChanged;
92 import org.opendaylight.controller.cluster.notifications.RegisterRoleChangeListener;
93 import org.opendaylight.controller.cluster.notifications.RoleChangeNotifier;
94 import org.opendaylight.controller.cluster.raft.LeadershipTransferFailedException;
95 import org.opendaylight.controller.cluster.raft.RaftActor;
96 import org.opendaylight.controller.cluster.raft.RaftActorRecoveryCohort;
97 import org.opendaylight.controller.cluster.raft.RaftActorSnapshotCohort;
98 import org.opendaylight.controller.cluster.raft.RaftState;
99 import org.opendaylight.controller.cluster.raft.base.messages.FollowerInitialSyncUpStatus;
100 import org.opendaylight.controller.cluster.raft.client.messages.OnDemandRaftState;
101 import org.opendaylight.controller.cluster.raft.messages.AppendEntriesReply;
102 import org.opendaylight.controller.cluster.raft.messages.RequestLeadership;
103 import org.opendaylight.controller.cluster.raft.messages.ServerRemoved;
104 import org.opendaylight.controller.cluster.raft.protobuff.client.messages.Payload;
105 import org.opendaylight.yangtools.concepts.Identifier;
106 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTree;
107 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataValidationFailedException;
108 import org.opendaylight.yangtools.yang.data.api.schema.tree.TreeType;
109 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
110 import org.opendaylight.yangtools.yang.model.api.SchemaContextProvider;
111 import scala.concurrent.duration.FiniteDuration;
114 * A Shard represents a portion of the logical data tree.
117 * Our Shard uses InMemoryDataTree as it's internal representation and delegates all requests it
119 public class Shard extends RaftActor {
122 static final Object TX_COMMIT_TIMEOUT_CHECK_MESSAGE = new Object() {
124 public String toString() {
125 return "txCommitTimeoutCheck";
130 static final Object GET_SHARD_MBEAN_MESSAGE = new Object() {
132 public String toString() {
133 return "getShardMBeanMessage";
137 static final Object RESUME_NEXT_PENDING_TRANSACTION = new Object() {
139 public String toString() {
140 return "resumeNextPendingTransaction";
144 // FIXME: shard names should be encapsulated in their own class and this should be exposed as a constant.
145 public static final String DEFAULT_NAME = "default";
147 private static final Collection<ABIVersion> SUPPORTED_ABIVERSIONS;
150 final ABIVersion[] values = ABIVersion.values();
151 final ABIVersion[] real = Arrays.copyOfRange(values, 1, values.length - 1);
152 SUPPORTED_ABIVERSIONS = ImmutableList.copyOf(real).reverse();
155 // FIXME: make this a dynamic property based on mailbox size and maximum number of clients
156 private static final int CLIENT_MAX_MESSAGES = 1000;
158 // The state of this Shard
159 private final ShardDataTree store;
161 /// The name of this shard
162 private final String name;
164 private final String shardName;
166 private final ShardStats shardMBean;
168 private final ShardDataTreeListenerInfoMXBeanImpl listenerInfoMXBean;
170 private DatastoreContext datastoreContext;
172 private final ShardCommitCoordinator commitCoordinator;
174 private long transactionCommitTimeout;
176 private Cancellable txCommitTimeoutCheckSchedule;
178 private final Optional<ActorRef> roleChangeNotifier;
180 private final MessageTracker appendEntriesReplyTracker;
182 private final ShardTransactionActorFactory transactionActorFactory;
184 private final ShardSnapshotCohort snapshotCohort;
186 private final DataTreeChangeListenerSupport treeChangeSupport = new DataTreeChangeListenerSupport(this);
188 private ShardSnapshot restoreFromSnapshot;
190 private final ShardTransactionMessageRetrySupport messageRetrySupport;
192 private final FrontendMetadata frontendMetadata;
193 private Map<FrontendIdentifier, LeaderFrontendState> knownFrontends = ImmutableMap.of();
194 private boolean paused;
196 private final MessageSlicer responseMessageSlicer;
197 private final Dispatchers dispatchers;
199 private final MessageAssembler requestMessageAssembler;
201 protected Shard(final AbstractBuilder<?, ?> builder) {
202 super(builder.getId().toString(), builder.getPeerAddresses(),
203 Optional.of(builder.getDatastoreContext().getShardRaftConfig()), DataStoreVersions.CURRENT_VERSION);
205 this.name = builder.getId().toString();
206 this.shardName = builder.getId().getShardName();
207 this.datastoreContext = builder.getDatastoreContext();
208 this.restoreFromSnapshot = builder.getRestoreFromSnapshot();
209 this.frontendMetadata = new FrontendMetadata(name);
211 setPersistence(datastoreContext.isPersistent());
213 LOG.info("Shard created : {}, persistent : {}", name, datastoreContext.isPersistent());
215 ShardDataTreeChangeListenerPublisherActorProxy treeChangeListenerPublisher =
216 new ShardDataTreeChangeListenerPublisherActorProxy(getContext(), name + "-DTCL-publisher", name);
217 if (builder.getDataTree() != null) {
218 store = new ShardDataTree(this, builder.getSchemaContext(), builder.getDataTree(),
219 treeChangeListenerPublisher, name, frontendMetadata);
221 store = new ShardDataTree(this, builder.getSchemaContext(), builder.getTreeType(),
222 builder.getDatastoreContext().getStoreRoot(), treeChangeListenerPublisher, name, frontendMetadata);
225 shardMBean = ShardMBeanFactory.getShardStatsMBean(name, datastoreContext.getDataStoreMXBeanType(), this);
227 if (isMetricsCaptureEnabled()) {
228 getContext().become(new MeteringBehavior(this));
231 commitCoordinator = new ShardCommitCoordinator(store, LOG, this.name);
233 setTransactionCommitTimeout();
235 // create a notifier actor for each cluster member
236 roleChangeNotifier = createRoleChangeNotifier(name);
238 appendEntriesReplyTracker = new MessageTracker(AppendEntriesReply.class,
239 getRaftActorContext().getConfigParams().getIsolatedCheckIntervalInMillis());
241 dispatchers = new Dispatchers(context().system().dispatchers());
242 transactionActorFactory = new ShardTransactionActorFactory(store, datastoreContext,
243 dispatchers.getDispatcherPath(Dispatchers.DispatcherType.Transaction),
244 self(), getContext(), shardMBean, builder.getId().getShardName());
246 snapshotCohort = ShardSnapshotCohort.create(getContext(), builder.getId().getMemberName(), store, LOG,
249 messageRetrySupport = new ShardTransactionMessageRetrySupport(this);
251 responseMessageSlicer = MessageSlicer.builder().logContext(this.name)
252 .messageSliceSize(datastoreContext.getMaximumMessageSliceSize())
253 .fileBackedStreamFactory(getRaftActorContext().getFileBackedOutputStreamFactory())
254 .expireStateAfterInactivity(2, TimeUnit.MINUTES).build();
256 requestMessageAssembler = MessageAssembler.builder().logContext(this.name)
257 .fileBackedStreamFactory(getRaftActorContext().getFileBackedOutputStreamFactory())
258 .assembledMessageCallback((message, sender) -> self().tell(message, sender))
259 .expireStateAfterInactivity(datastoreContext.getRequestTimeout(), TimeUnit.NANOSECONDS).build();
261 listenerInfoMXBean = new ShardDataTreeListenerInfoMXBeanImpl(name, datastoreContext.getDataStoreMXBeanType(),
263 listenerInfoMXBean.register();
266 private void setTransactionCommitTimeout() {
267 transactionCommitTimeout = TimeUnit.MILLISECONDS.convert(
268 datastoreContext.getShardTransactionCommitTimeoutInSeconds(), TimeUnit.SECONDS) / 2;
271 private Optional<ActorRef> createRoleChangeNotifier(final String shardId) {
272 ActorRef shardRoleChangeNotifier = this.getContext().actorOf(
273 RoleChangeNotifier.getProps(shardId), shardId + "-notifier");
274 return Optional.of(shardRoleChangeNotifier);
278 public void postStop() {
279 LOG.info("Stopping Shard {}", persistenceId());
283 messageRetrySupport.close();
285 if (txCommitTimeoutCheckSchedule != null) {
286 txCommitTimeoutCheckSchedule.cancel();
289 commitCoordinator.abortPendingTransactions("Transaction aborted due to shutdown.", this);
291 shardMBean.unregisterMBean();
292 listenerInfoMXBean.unregister();
296 protected void handleRecover(final Object message) {
297 LOG.debug("{}: onReceiveRecover: Received message {} from {}", persistenceId(), message.getClass(),
300 super.handleRecover(message);
301 if (LOG.isTraceEnabled()) {
302 appendEntriesReplyTracker.begin();
307 protected void handleNonRaftCommand(final Object message) {
308 try (MessageTracker.Context context = appendEntriesReplyTracker.received(message)) {
309 final Optional<Error> maybeError = context.error();
310 if (maybeError.isPresent()) {
311 LOG.trace("{} : AppendEntriesReply failed to arrive at the expected interval {}", persistenceId(),
315 store.resetTransactionBatch();
317 if (message instanceof RequestEnvelope) {
318 handleRequestEnvelope((RequestEnvelope)message);
319 } else if (MessageAssembler.isHandledMessage(message)) {
320 handleRequestAssemblerMessage(message);
321 } else if (message instanceof ConnectClientRequest) {
322 handleConnectClient((ConnectClientRequest)message);
323 } else if (CreateTransaction.isSerializedType(message)) {
324 handleCreateTransaction(message);
325 } else if (message instanceof BatchedModifications) {
326 handleBatchedModifications((BatchedModifications)message);
327 } else if (message instanceof ForwardedReadyTransaction) {
328 handleForwardedReadyTransaction((ForwardedReadyTransaction) message);
329 } else if (message instanceof ReadyLocalTransaction) {
330 handleReadyLocalTransaction((ReadyLocalTransaction)message);
331 } else if (CanCommitTransaction.isSerializedType(message)) {
332 handleCanCommitTransaction(CanCommitTransaction.fromSerializable(message));
333 } else if (CommitTransaction.isSerializedType(message)) {
334 handleCommitTransaction(CommitTransaction.fromSerializable(message));
335 } else if (AbortTransaction.isSerializedType(message)) {
336 handleAbortTransaction(AbortTransaction.fromSerializable(message));
337 } else if (CloseTransactionChain.isSerializedType(message)) {
338 closeTransactionChain(CloseTransactionChain.fromSerializable(message));
339 } else if (message instanceof RegisterDataTreeChangeListener) {
340 treeChangeSupport.onMessage((RegisterDataTreeChangeListener) message, isLeader(), hasLeader());
341 } else if (message instanceof UpdateSchemaContext) {
342 updateSchemaContext((UpdateSchemaContext) message);
343 } else if (message instanceof PeerAddressResolved) {
344 PeerAddressResolved resolved = (PeerAddressResolved) message;
345 setPeerAddress(resolved.getPeerId(), resolved.getPeerAddress());
346 } else if (TX_COMMIT_TIMEOUT_CHECK_MESSAGE.equals(message)) {
347 commitTimeoutCheck();
348 } else if (message instanceof DatastoreContext) {
349 onDatastoreContext((DatastoreContext)message);
350 } else if (message instanceof RegisterRoleChangeListener) {
351 roleChangeNotifier.get().forward(message, context());
352 } else if (message instanceof FollowerInitialSyncUpStatus) {
353 shardMBean.setFollowerInitialSyncStatus(((FollowerInitialSyncUpStatus) message).isInitialSyncDone());
354 context().parent().tell(message, self());
355 } else if (GET_SHARD_MBEAN_MESSAGE.equals(message)) {
356 sender().tell(getShardMBean(), self());
357 } else if (message instanceof GetShardDataTree) {
358 sender().tell(store.getDataTree(), self());
359 } else if (message instanceof ServerRemoved) {
360 context().parent().forward(message, context());
361 } else if (ShardTransactionMessageRetrySupport.TIMER_MESSAGE_CLASS.isInstance(message)) {
362 messageRetrySupport.onTimerMessage(message);
363 } else if (message instanceof DataTreeCohortActorRegistry.CohortRegistryCommand) {
364 store.processCohortRegistryCommand(getSender(),
365 (DataTreeCohortActorRegistry.CohortRegistryCommand) message);
366 } else if (message instanceof MakeLeaderLocal) {
368 } else if (RESUME_NEXT_PENDING_TRANSACTION.equals(message)) {
369 store.resumeNextPendingTransaction();
370 } else if (!responseMessageSlicer.handleMessage(message)) {
371 super.handleNonRaftCommand(message);
376 private void handleRequestAssemblerMessage(final Object message) {
377 dispatchers.getDispatcher(DispatcherType.Serialization).execute(() -> {
378 JavaSerializer.currentSystem().value_$eq((ExtendedActorSystem) context().system());
379 requestMessageAssembler.handleMessage(message, self());
383 @SuppressWarnings("checkstyle:IllegalCatch")
384 private void handleRequestEnvelope(final RequestEnvelope envelope) {
385 final long now = ticker().read();
387 final RequestSuccess<?, ?> success = handleRequest(envelope, now);
388 if (success != null) {
389 final long executionTimeNanos = ticker().read() - now;
390 if (success instanceof SliceableMessage) {
391 dispatchers.getDispatcher(DispatcherType.Serialization).execute(() ->
392 responseMessageSlicer.slice(SliceOptions.builder().identifier(success.getTarget())
393 .message(envelope.newSuccessEnvelope(success, executionTimeNanos))
394 .sendTo(envelope.getMessage().getReplyTo()).replyTo(self())
395 .onFailureCallback(t -> LOG.warn("Error slicing response {}", success, t)).build()));
397 envelope.sendSuccess(success, executionTimeNanos);
400 } catch (RequestException e) {
401 LOG.debug("{}: request {} failed", persistenceId(), envelope, e);
402 envelope.sendFailure(e, ticker().read() - now);
403 } catch (Exception e) {
404 LOG.debug("{}: request {} caused failure", persistenceId(), envelope, e);
405 envelope.sendFailure(new RuntimeRequestException("Request failed to process", e),
406 ticker().read() - now);
410 private void commitTimeoutCheck() {
411 store.checkForExpiredTransactions(transactionCommitTimeout, this::updateAccess);
412 commitCoordinator.checkForExpiredTransactions(transactionCommitTimeout, this);
413 requestMessageAssembler.checkExpiredAssembledMessageState();
416 private Optional<Long> updateAccess(final SimpleShardDataTreeCohort cohort) {
417 final FrontendIdentifier frontend = cohort.getIdentifier().getHistoryId().getClientId().getFrontendId();
418 final LeaderFrontendState state = knownFrontends.get(frontend);
420 // Not tell-based protocol, do nothing
421 return Optional.absent();
424 if (isIsolatedLeader()) {
425 // We are isolated and no new request can come through until we emerge from it. We are still updating
426 // liveness of frontend when we see it attempting to communicate. Use the last access timer.
427 return Optional.of(state.getLastSeenTicks());
430 // If this frontend has freshly connected, give it some time to catch up before killing its transactions.
431 return Optional.of(state.getLastConnectTicks());
434 private void disableTracking(final DisableTrackingPayload payload) {
435 final ClientIdentifier clientId = payload.getIdentifier();
436 LOG.debug("{}: disabling tracking of {}", persistenceId(), clientId);
437 frontendMetadata.disableTracking(clientId);
440 final FrontendIdentifier frontendId = clientId.getFrontendId();
441 final LeaderFrontendState frontend = knownFrontends.get(frontendId);
442 if (frontend != null) {
443 if (clientId.equals(frontend.getIdentifier())) {
444 if (!(frontend instanceof LeaderFrontendState.Disabled)) {
445 verify(knownFrontends.replace(frontendId, frontend,
446 new LeaderFrontendState.Disabled(persistenceId(), clientId, store)));
447 LOG.debug("{}: leader state for {} disabled", persistenceId(), clientId);
449 LOG.debug("{}: leader state {} is already disabled", persistenceId(), frontend);
452 LOG.debug("{}: leader state {} does not match {}", persistenceId(), frontend, clientId);
455 LOG.debug("{}: leader state for {} not found", persistenceId(), clientId);
456 knownFrontends.put(frontendId, new LeaderFrontendState.Disabled(persistenceId(), clientId,
462 private void onMakeLeaderLocal() {
463 LOG.debug("{}: onMakeLeaderLocal received", persistenceId());
465 getSender().tell(new Status.Success(null), getSelf());
469 final ActorSelection leader = getLeader();
471 if (leader == null) {
472 // Leader is not present. The cluster is most likely trying to
473 // elect a leader and we should let that run its normal course
475 // TODO we can wait for the election to complete and retry the
476 // request. We can also let the caller retry by sending a flag
477 // in the response indicating the request is "reTryable".
478 getSender().tell(new Failure(
479 new LeadershipTransferFailedException("We cannot initiate leadership transfer to local node. "
480 + "Currently there is no leader for " + persistenceId())),
485 leader.tell(new RequestLeadership(getId(), getSender()), getSelf());
488 // Acquire our frontend tracking handle and verify generation matches
490 private LeaderFrontendState findFrontend(final ClientIdentifier clientId) throws RequestException {
491 final LeaderFrontendState existing = knownFrontends.get(clientId.getFrontendId());
492 if (existing != null) {
493 final int cmp = Long.compareUnsigned(existing.getIdentifier().getGeneration(), clientId.getGeneration());
499 LOG.debug("{}: rejecting request from outdated client {}", persistenceId(), clientId);
500 throw new RetiredGenerationException(clientId.getGeneration(),
501 existing.getIdentifier().getGeneration());
504 LOG.info("{}: retiring state {}, outdated by request from client {}", persistenceId(), existing, clientId);
506 knownFrontends.remove(clientId.getFrontendId());
508 LOG.debug("{}: client {} is not yet known", persistenceId(), clientId);
514 private LeaderFrontendState getFrontend(final ClientIdentifier clientId) throws RequestException {
515 final LeaderFrontendState ret = findFrontend(clientId);
520 // TODO: a dedicated exception would be better, but this is technically true, too
521 throw new OutOfSequenceEnvelopeException(0);
525 private static ABIVersion selectVersion(final ConnectClientRequest message) {
526 final Range<ABIVersion> clientRange = Range.closed(message.getMinVersion(), message.getMaxVersion());
527 for (ABIVersion v : SUPPORTED_ABIVERSIONS) {
528 if (clientRange.contains(v)) {
533 throw new IllegalArgumentException(String.format(
534 "No common version between backend versions %s and client versions %s", SUPPORTED_ABIVERSIONS,
538 @SuppressWarnings("checkstyle:IllegalCatch")
539 private void handleConnectClient(final ConnectClientRequest message) {
541 final ClientIdentifier clientId = message.getTarget();
542 final LeaderFrontendState existing = findFrontend(clientId);
543 if (existing != null) {
547 if (!isLeader() || !isLeaderActive()) {
548 LOG.info("{}: not currently leader, rejecting request {}. isLeader: {}, isLeaderActive: {},"
549 + "isLeadershipTransferInProgress: {}.",
550 persistenceId(), message, isLeader(), isLeaderActive(), isLeadershipTransferInProgress());
551 throw new NotLeaderException(getSelf());
554 final ABIVersion selectedVersion = selectVersion(message);
555 final LeaderFrontendState frontend;
556 if (existing == null) {
557 frontend = new LeaderFrontendState.Enabled(persistenceId(), clientId, store);
558 knownFrontends.put(clientId.getFrontendId(), frontend);
559 LOG.debug("{}: created state {} for client {}", persistenceId(), frontend, clientId);
564 frontend.reconnect();
565 message.getReplyTo().tell(new ConnectClientSuccess(message.getTarget(), message.getSequence(), getSelf(),
566 ImmutableList.of(), store.getDataTree(), CLIENT_MAX_MESSAGES).toVersion(selectedVersion),
567 ActorRef.noSender());
568 } catch (RequestException | RuntimeException e) {
569 message.getReplyTo().tell(new Failure(e), ActorRef.noSender());
574 private 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());
828 // FIXME: CONTROLLER-1628: stage purge once no transactions are present
829 store.closeTransactionChain(id, null);
830 store.purgeTransactionChain(id, null);
831 } else if (getLeader() != null) {
832 getLeader().forward(closeTransactionChain, getContext());
834 LOG.warn("{}: Could not close transaction {}", persistenceId(), closeTransactionChain.getIdentifier());
838 @SuppressWarnings("checkstyle:IllegalCatch")
839 private void createTransaction(final CreateTransaction createTransaction) {
840 askProtocolEncountered(createTransaction.getTransactionId());
843 if (TransactionType.fromInt(createTransaction.getTransactionType()) != TransactionType.READ_ONLY
844 && failIfIsolatedLeader(getSender())) {
848 ActorRef transactionActor = createTransaction(createTransaction.getTransactionType(),
849 createTransaction.getTransactionId());
851 getSender().tell(new CreateTransactionReply(Serialization.serializedActorPath(transactionActor),
852 createTransaction.getTransactionId(), createTransaction.getVersion()).toSerializable(), getSelf());
853 } catch (Exception e) {
854 getSender().tell(new Failure(e), getSelf());
858 private ActorRef createTransaction(final int transactionType, final TransactionIdentifier transactionId) {
859 LOG.debug("{}: Creating transaction : {} ", persistenceId(), transactionId);
860 return transactionActorFactory.newShardTransaction(TransactionType.fromInt(transactionType),
864 // Called on leader only
865 private void askProtocolEncountered(final TransactionIdentifier transactionId) {
866 askProtocolEncountered(transactionId.getHistoryId().getClientId());
869 // Called on leader only
870 private void askProtocolEncountered(final ClientIdentifier clientId) {
871 final FrontendIdentifier frontend = clientId.getFrontendId();
872 final LeaderFrontendState state = knownFrontends.get(frontend);
873 if (!(state instanceof LeaderFrontendState.Disabled)) {
874 LOG.debug("{}: encountered ask-based client {}, disabling transaction tracking", persistenceId(), clientId);
875 if (knownFrontends.isEmpty()) {
876 knownFrontends = new HashMap<>();
878 knownFrontends.put(frontend, new LeaderFrontendState.Disabled(persistenceId(), clientId, getDataStore()));
880 persistPayload(clientId, DisableTrackingPayload.create(clientId,
881 datastoreContext.getInitialPayloadSerializedBufferCapacity()), false);
885 private void updateSchemaContext(final UpdateSchemaContext message) {
886 updateSchemaContext(message.getSchemaContext());
890 void updateSchemaContext(final SchemaContext schemaContext) {
891 store.updateSchemaContext(schemaContext);
894 private boolean isMetricsCaptureEnabled() {
895 CommonConfig config = new CommonConfig(getContext().system().settings().config());
896 return config.isMetricCaptureEnabled();
901 public RaftActorSnapshotCohort getRaftActorSnapshotCohort() {
902 return snapshotCohort;
907 protected RaftActorRecoveryCohort getRaftActorRecoveryCohort() {
908 if (restoreFromSnapshot == null) {
909 return ShardRecoveryCoordinator.create(store, persistenceId(), LOG);
912 return ShardRecoveryCoordinator.forSnapshot(store, persistenceId(), LOG, restoreFromSnapshot.getSnapshot());
916 protected void onRecoveryComplete() {
917 restoreFromSnapshot = null;
919 //notify shard manager
920 getContext().parent().tell(new ActorInitialized(), getSelf());
922 // Being paranoid here - this method should only be called once but just in case...
923 if (txCommitTimeoutCheckSchedule == null) {
924 // Schedule a message to be periodically sent to check if the current in-progress
925 // transaction should be expired and aborted.
926 FiniteDuration period = FiniteDuration.create(transactionCommitTimeout / 3, TimeUnit.MILLISECONDS);
927 txCommitTimeoutCheckSchedule = getContext().system().scheduler().schedule(
928 period, period, getSelf(),
929 TX_COMMIT_TIMEOUT_CHECK_MESSAGE, getContext().dispatcher(), ActorRef.noSender());
934 protected void applyState(final ActorRef clientActor, final Identifier identifier, final Object data) {
935 if (data instanceof Payload) {
936 if (data instanceof DisableTrackingPayload) {
937 disableTracking((DisableTrackingPayload) data);
942 store.applyReplicatedPayload(identifier, (Payload)data);
943 } catch (DataValidationFailedException | IOException e) {
944 LOG.error("{}: Error applying replica {}", persistenceId(), identifier, e);
947 LOG.error("{}: Unknown state for {} received {}", persistenceId(), identifier, data);
952 protected void onStateChanged() {
953 boolean isLeader = isLeader();
954 boolean hasLeader = hasLeader();
955 treeChangeSupport.onLeadershipChange(isLeader, hasLeader);
957 // If this actor is no longer the leader close all the transaction chains
959 if (LOG.isDebugEnabled()) {
961 "{}: onStateChanged: Closing all transaction chains because shard {} is no longer the leader",
962 persistenceId(), getId());
966 store.purgeLeaderState();
969 if (hasLeader && !isIsolatedLeader()) {
970 messageRetrySupport.retryMessages();
975 protected void onLeaderChanged(final String oldLeader, final String newLeader) {
976 shardMBean.incrementLeadershipChangeCount();
980 if (!knownFrontends.isEmpty()) {
981 LOG.debug("{}: removing frontend state for {}", persistenceId(), knownFrontends.keySet());
982 knownFrontends = ImmutableMap.of();
985 requestMessageAssembler.close();
988 // No leader anywhere, nothing else to do
992 // Another leader was elected. If we were the previous leader and had pending transactions, convert
993 // them to transaction messages and send to the new leader.
994 ActorSelection leader = getLeader();
995 if (leader != null) {
996 Collection<?> messagesToForward = convertPendingTransactionsToMessages();
998 if (!messagesToForward.isEmpty()) {
999 LOG.debug("{}: Forwarding {} pending transaction messages to leader {}", persistenceId(),
1000 messagesToForward.size(), leader);
1002 for (Object message : messagesToForward) {
1003 LOG.debug("{}: Forwarding pending transaction message {}", persistenceId(), message);
1005 leader.tell(message, self());
1009 commitCoordinator.abortPendingTransactions("The transacton was aborted due to inflight leadership "
1010 + "change and the leader address isn't available.", this);
1013 // We have become the leader, we need to reconstruct frontend state
1014 knownFrontends = Verify.verifyNotNull(frontendMetadata.toLeaderState(this));
1015 LOG.debug("{}: became leader with frontend state for {}", persistenceId(), knownFrontends.keySet());
1018 if (!isIsolatedLeader()) {
1019 messageRetrySupport.retryMessages();
1024 * Clears all pending transactions and converts them to messages to be forwarded to a new leader.
1026 * @return the converted messages
1028 public Collection<?> convertPendingTransactionsToMessages() {
1029 return commitCoordinator.convertPendingTransactionsToMessages(
1030 datastoreContext.getShardBatchedModificationCount());
1034 protected void pauseLeader(final Runnable operation) {
1035 LOG.debug("{}: In pauseLeader, operation: {}", persistenceId(), operation);
1038 // Tell-based protocol can replay transaction state, so it is safe to blow it up when we are paused.
1039 if (datastoreContext.isUseTellBasedProtocol()) {
1040 knownFrontends.values().forEach(LeaderFrontendState::retire);
1041 knownFrontends = ImmutableMap.of();
1044 store.setRunOnPendingTransactionsComplete(operation);
1048 protected void unpauseLeader() {
1049 LOG.debug("{}: In unpauseLeader", persistenceId());
1052 store.setRunOnPendingTransactionsComplete(null);
1054 // Restore tell-based protocol state as if we were becoming the leader
1055 knownFrontends = Verify.verifyNotNull(frontendMetadata.toLeaderState(this));
1059 protected OnDemandRaftState.AbstractBuilder<?, ?> newOnDemandRaftStateBuilder() {
1060 return OnDemandShardState.newBuilder().treeChangeListenerActors(treeChangeSupport.getListenerActors())
1061 .commitCohortActors(store.getCohortActors());
1065 public String persistenceId() {
1070 ShardCommitCoordinator getCommitCoordinator() {
1071 return commitCoordinator;
1074 public DatastoreContext getDatastoreContext() {
1075 return datastoreContext;
1079 public ShardDataTree getDataStore() {
1084 ShardStats getShardMBean() {
1088 public static Builder builder() {
1089 return new Builder();
1092 public abstract static class AbstractBuilder<T extends AbstractBuilder<T, S>, S extends Shard> {
1093 private final Class<S> shardClass;
1094 private ShardIdentifier id;
1095 private Map<String, String> peerAddresses = Collections.emptyMap();
1096 private DatastoreContext datastoreContext;
1097 private SchemaContextProvider schemaContextProvider;
1098 private DatastoreSnapshot.ShardSnapshot restoreFromSnapshot;
1099 private DataTree dataTree;
1100 private volatile boolean sealed;
1102 protected AbstractBuilder(final Class<S> shardClass) {
1103 this.shardClass = shardClass;
1106 protected void checkSealed() {
1107 Preconditions.checkState(!sealed, "Builder isalready sealed - further modifications are not allowed");
1110 @SuppressWarnings("unchecked")
1115 public T id(final ShardIdentifier newId) {
1121 public T peerAddresses(final Map<String, String> newPeerAddresses) {
1123 this.peerAddresses = newPeerAddresses;
1127 public T datastoreContext(final DatastoreContext newDatastoreContext) {
1129 this.datastoreContext = newDatastoreContext;
1133 public T schemaContextProvider(final SchemaContextProvider newSchemaContextProvider) {
1135 this.schemaContextProvider = Preconditions.checkNotNull(newSchemaContextProvider);
1139 public T restoreFromSnapshot(final DatastoreSnapshot.ShardSnapshot newRestoreFromSnapshot) {
1141 this.restoreFromSnapshot = newRestoreFromSnapshot;
1145 public T dataTree(final DataTree newDataTree) {
1147 this.dataTree = newDataTree;
1151 public ShardIdentifier getId() {
1155 public Map<String, String> getPeerAddresses() {
1156 return peerAddresses;
1159 public DatastoreContext getDatastoreContext() {
1160 return datastoreContext;
1163 public SchemaContext getSchemaContext() {
1164 return Verify.verifyNotNull(schemaContextProvider.getSchemaContext());
1167 public DatastoreSnapshot.ShardSnapshot getRestoreFromSnapshot() {
1168 return restoreFromSnapshot;
1171 public DataTree getDataTree() {
1175 public TreeType getTreeType() {
1176 switch (datastoreContext.getLogicalStoreType()) {
1178 return TreeType.CONFIGURATION;
1180 return TreeType.OPERATIONAL;
1182 throw new IllegalStateException("Unhandled logical store type "
1183 + datastoreContext.getLogicalStoreType());
1187 protected void verify() {
1188 Preconditions.checkNotNull(id, "id should not be null");
1189 Preconditions.checkNotNull(peerAddresses, "peerAddresses should not be null");
1190 Preconditions.checkNotNull(datastoreContext, "dataStoreContext should not be null");
1191 Preconditions.checkNotNull(schemaContextProvider, "schemaContextProvider should not be null");
1194 public Props props() {
1197 return Props.create(shardClass, this);
1201 public static class Builder extends AbstractBuilder<Builder, Shard> {
1208 return Ticker.systemTicker();
1211 void scheduleNextPendingTransaction() {
1212 self().tell(RESUME_NEXT_PENDING_TRANSACTION, ActorRef.noSender());