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
9 package org.opendaylight.controller.cluster.datastore;
11 import akka.actor.ActorRef;
12 import akka.actor.ActorSelection;
13 import akka.actor.Cancellable;
14 import akka.actor.ExtendedActorSystem;
15 import akka.actor.Props;
16 import akka.actor.Status;
17 import akka.actor.Status.Failure;
18 import akka.serialization.JavaSerializer;
19 import akka.serialization.Serialization;
20 import com.google.common.annotations.VisibleForTesting;
21 import com.google.common.base.Optional;
22 import com.google.common.base.Preconditions;
23 import com.google.common.base.Ticker;
24 import com.google.common.base.Verify;
25 import com.google.common.collect.ImmutableList;
26 import com.google.common.collect.ImmutableMap;
27 import com.google.common.collect.Range;
28 import java.io.IOException;
29 import java.util.Arrays;
30 import java.util.Collection;
31 import java.util.Collections;
33 import java.util.concurrent.TimeUnit;
34 import javax.annotation.Nonnull;
35 import javax.annotation.Nullable;
36 import org.opendaylight.controller.cluster.access.ABIVersion;
37 import org.opendaylight.controller.cluster.access.commands.ConnectClientRequest;
38 import org.opendaylight.controller.cluster.access.commands.ConnectClientSuccess;
39 import org.opendaylight.controller.cluster.access.commands.LocalHistoryRequest;
40 import org.opendaylight.controller.cluster.access.commands.NotLeaderException;
41 import org.opendaylight.controller.cluster.access.commands.OutOfSequenceEnvelopeException;
42 import org.opendaylight.controller.cluster.access.commands.TransactionRequest;
43 import org.opendaylight.controller.cluster.access.concepts.ClientIdentifier;
44 import org.opendaylight.controller.cluster.access.concepts.FrontendIdentifier;
45 import org.opendaylight.controller.cluster.access.concepts.LocalHistoryIdentifier;
46 import org.opendaylight.controller.cluster.access.concepts.Request;
47 import org.opendaylight.controller.cluster.access.concepts.RequestEnvelope;
48 import org.opendaylight.controller.cluster.access.concepts.RequestException;
49 import org.opendaylight.controller.cluster.access.concepts.RequestSuccess;
50 import org.opendaylight.controller.cluster.access.concepts.RetiredGenerationException;
51 import org.opendaylight.controller.cluster.access.concepts.RuntimeRequestException;
52 import org.opendaylight.controller.cluster.access.concepts.SliceableMessage;
53 import org.opendaylight.controller.cluster.access.concepts.TransactionIdentifier;
54 import org.opendaylight.controller.cluster.access.concepts.UnsupportedRequestException;
55 import org.opendaylight.controller.cluster.common.actor.CommonConfig;
56 import org.opendaylight.controller.cluster.common.actor.Dispatchers;
57 import org.opendaylight.controller.cluster.common.actor.Dispatchers.DispatcherType;
58 import org.opendaylight.controller.cluster.common.actor.MessageTracker;
59 import org.opendaylight.controller.cluster.common.actor.MessageTracker.Error;
60 import org.opendaylight.controller.cluster.common.actor.MeteringBehavior;
61 import org.opendaylight.controller.cluster.datastore.exceptions.NoShardLeaderException;
62 import org.opendaylight.controller.cluster.datastore.identifiers.ShardIdentifier;
63 import org.opendaylight.controller.cluster.datastore.jmx.mbeans.shard.ShardDataTreeListenerInfoMXBeanImpl;
64 import org.opendaylight.controller.cluster.datastore.jmx.mbeans.shard.ShardMBeanFactory;
65 import org.opendaylight.controller.cluster.datastore.jmx.mbeans.shard.ShardStats;
66 import org.opendaylight.controller.cluster.datastore.messages.AbortTransaction;
67 import org.opendaylight.controller.cluster.datastore.messages.ActorInitialized;
68 import org.opendaylight.controller.cluster.datastore.messages.BatchedModifications;
69 import org.opendaylight.controller.cluster.datastore.messages.CanCommitTransaction;
70 import org.opendaylight.controller.cluster.datastore.messages.CloseTransactionChain;
71 import org.opendaylight.controller.cluster.datastore.messages.CommitTransaction;
72 import org.opendaylight.controller.cluster.datastore.messages.CreateTransaction;
73 import org.opendaylight.controller.cluster.datastore.messages.CreateTransactionReply;
74 import org.opendaylight.controller.cluster.datastore.messages.ForwardedReadyTransaction;
75 import org.opendaylight.controller.cluster.datastore.messages.GetShardDataTree;
76 import org.opendaylight.controller.cluster.datastore.messages.MakeLeaderLocal;
77 import org.opendaylight.controller.cluster.datastore.messages.OnDemandShardState;
78 import org.opendaylight.controller.cluster.datastore.messages.PeerAddressResolved;
79 import org.opendaylight.controller.cluster.datastore.messages.PersistAbortTransactionPayload;
80 import org.opendaylight.controller.cluster.datastore.messages.ReadyLocalTransaction;
81 import org.opendaylight.controller.cluster.datastore.messages.RegisterDataTreeChangeListener;
82 import org.opendaylight.controller.cluster.datastore.messages.ShardLeaderStateChanged;
83 import org.opendaylight.controller.cluster.datastore.messages.UpdateSchemaContext;
84 import org.opendaylight.controller.cluster.datastore.persisted.AbortTransactionPayload;
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.PurgeTransactionPayload;
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.Duration;
112 import scala.concurrent.duration.FiniteDuration;
115 * A Shard represents a portion of the logical data tree.
118 * Our Shard uses InMemoryDataTree as it's internal representation and delegates all requests it
120 public class Shard extends RaftActor {
123 static final Object TX_COMMIT_TIMEOUT_CHECK_MESSAGE = new Object() {
125 public String toString() {
126 return "txCommitTimeoutCheck";
131 static final Object GET_SHARD_MBEAN_MESSAGE = new Object() {
133 public String toString() {
134 return "getShardMBeanMessage";
138 static final Object RESUME_NEXT_PENDING_TRANSACTION = new Object() {
140 public String toString() {
141 return "resumeNextPendingTransaction";
145 // FIXME: shard names should be encapsulated in their own class and this should be exposed as a constant.
146 public static final String DEFAULT_NAME = "default";
148 private static final Collection<ABIVersion> SUPPORTED_ABIVERSIONS;
151 final ABIVersion[] values = ABIVersion.values();
152 final ABIVersion[] real = Arrays.copyOfRange(values, 1, values.length - 1);
153 SUPPORTED_ABIVERSIONS = ImmutableList.copyOf(real).reverse();
156 // FIXME: make this a dynamic property based on mailbox size and maximum number of clients
157 private static final int CLIENT_MAX_MESSAGES = 1000;
159 // The state of this Shard
160 private final ShardDataTree store;
162 /// The name of this shard
163 private final String name;
165 private final String shardName;
167 private final ShardStats shardMBean;
169 private final ShardDataTreeListenerInfoMXBeanImpl listenerInfoMXBean;
171 private DatastoreContext datastoreContext;
173 private final ShardCommitCoordinator commitCoordinator;
175 private long transactionCommitTimeout;
177 private Cancellable txCommitTimeoutCheckSchedule;
179 private final Optional<ActorRef> roleChangeNotifier;
181 private final MessageTracker appendEntriesReplyTracker;
183 private final ShardTransactionActorFactory transactionActorFactory;
185 private final ShardSnapshotCohort snapshotCohort;
187 private final DataTreeChangeListenerSupport treeChangeSupport = new DataTreeChangeListenerSupport(this);
189 private ShardSnapshot restoreFromSnapshot;
191 private final ShardTransactionMessageRetrySupport messageRetrySupport;
193 private final FrontendMetadata frontendMetadata;
194 private Map<FrontendIdentifier, LeaderFrontendState> knownFrontends = ImmutableMap.of();
195 private boolean paused;
197 private final MessageSlicer responseMessageSlicer;
198 private final Dispatchers dispatchers;
200 private final MessageAssembler requestMessageAssembler;
202 protected Shard(final AbstractBuilder<?, ?> builder) {
203 super(builder.getId().toString(), builder.getPeerAddresses(),
204 Optional.of(builder.getDatastoreContext().getShardRaftConfig()), DataStoreVersions.CURRENT_VERSION);
206 this.name = builder.getId().toString();
207 this.shardName = builder.getId().getShardName();
208 this.datastoreContext = builder.getDatastoreContext();
209 this.restoreFromSnapshot = builder.getRestoreFromSnapshot();
210 this.frontendMetadata = new FrontendMetadata(name);
212 setPersistence(datastoreContext.isPersistent());
214 LOG.info("Shard created : {}, persistent : {}", name, datastoreContext.isPersistent());
216 ShardDataTreeChangeListenerPublisherActorProxy treeChangeListenerPublisher =
217 new ShardDataTreeChangeListenerPublisherActorProxy(getContext(), name + "-DTCL-publisher", name);
218 if (builder.getDataTree() != null) {
219 store = new ShardDataTree(this, builder.getSchemaContext(), builder.getDataTree(),
220 treeChangeListenerPublisher, name, frontendMetadata);
222 store = new ShardDataTree(this, builder.getSchemaContext(), builder.getTreeType(),
223 builder.getDatastoreContext().getStoreRoot(), treeChangeListenerPublisher, name, frontendMetadata);
226 shardMBean = ShardMBeanFactory.getShardStatsMBean(name, datastoreContext.getDataStoreMXBeanType(), this);
228 if (isMetricsCaptureEnabled()) {
229 getContext().become(new MeteringBehavior(this));
232 commitCoordinator = new ShardCommitCoordinator(store, LOG, this.name);
234 setTransactionCommitTimeout();
236 // create a notifier actor for each cluster member
237 roleChangeNotifier = createRoleChangeNotifier(name);
239 appendEntriesReplyTracker = new MessageTracker(AppendEntriesReply.class,
240 getRaftActorContext().getConfigParams().getIsolatedCheckIntervalInMillis());
242 dispatchers = new Dispatchers(context().system().dispatchers());
243 transactionActorFactory = new ShardTransactionActorFactory(store, datastoreContext,
244 dispatchers.getDispatcherPath(Dispatchers.DispatcherType.Transaction),
245 self(), getContext(), shardMBean, builder.getId().getShardName());
247 snapshotCohort = ShardSnapshotCohort.create(getContext(), builder.getId().getMemberName(), store, LOG,
250 messageRetrySupport = new ShardTransactionMessageRetrySupport(this);
252 responseMessageSlicer = MessageSlicer.builder().logContext(this.name)
253 .messageSliceSize(datastoreContext.getMaximumMessageSliceSize())
254 .fileBackedStreamFactory(getRaftActorContext().getFileBackedOutputStreamFactory())
255 .expireStateAfterInactivity(2, TimeUnit.MINUTES).build();
257 requestMessageAssembler = MessageAssembler.builder().logContext(this.name)
258 .fileBackedStreamFactory(getRaftActorContext().getFileBackedOutputStreamFactory())
259 .assembledMessageCallback((message, sender) -> self().tell(message, sender))
260 .expireStateAfterInactivity(datastoreContext.getRequestTimeout(), TimeUnit.NANOSECONDS).build();
262 listenerInfoMXBean = new ShardDataTreeListenerInfoMXBeanImpl(name, datastoreContext.getDataStoreMXBeanType(),
264 listenerInfoMXBean.register();
267 private void setTransactionCommitTimeout() {
268 transactionCommitTimeout = TimeUnit.MILLISECONDS.convert(
269 datastoreContext.getShardTransactionCommitTimeoutInSeconds(), TimeUnit.SECONDS) / 2;
272 private Optional<ActorRef> createRoleChangeNotifier(final String shardId) {
273 ActorRef shardRoleChangeNotifier = this.getContext().actorOf(
274 RoleChangeNotifier.getProps(shardId), shardId + "-notifier");
275 return Optional.of(shardRoleChangeNotifier);
279 public void postStop() {
280 LOG.info("Stopping Shard {}", persistenceId());
284 messageRetrySupport.close();
286 if (txCommitTimeoutCheckSchedule != null) {
287 txCommitTimeoutCheckSchedule.cancel();
290 commitCoordinator.abortPendingTransactions("Transaction aborted due to shutdown.", this);
292 shardMBean.unregisterMBean();
293 listenerInfoMXBean.unregister();
297 protected void handleRecover(final Object message) {
298 LOG.debug("{}: onReceiveRecover: Received message {} from {}", persistenceId(), message.getClass(),
301 super.handleRecover(message);
302 if (LOG.isTraceEnabled()) {
303 appendEntriesReplyTracker.begin();
308 protected void handleNonRaftCommand(final Object message) {
309 try (MessageTracker.Context context = appendEntriesReplyTracker.received(message)) {
310 final Optional<Error> maybeError = context.error();
311 if (maybeError.isPresent()) {
312 LOG.trace("{} : AppendEntriesReply failed to arrive at the expected interval {}", persistenceId(),
316 store.resetTransactionBatch();
318 if (message instanceof RequestEnvelope) {
319 handleRequestEnvelope((RequestEnvelope)message);
320 } else if (MessageAssembler.isHandledMessage(message)) {
321 handleRequestAssemblerMessage(message);
322 } else if (message instanceof ConnectClientRequest) {
323 handleConnectClient((ConnectClientRequest)message);
324 } else if (CreateTransaction.isSerializedType(message)) {
325 handleCreateTransaction(message);
326 } else if (message instanceof BatchedModifications) {
327 handleBatchedModifications((BatchedModifications)message);
328 } else if (message instanceof ForwardedReadyTransaction) {
329 handleForwardedReadyTransaction((ForwardedReadyTransaction) message);
330 } else if (message instanceof ReadyLocalTransaction) {
331 handleReadyLocalTransaction((ReadyLocalTransaction)message);
332 } else if (CanCommitTransaction.isSerializedType(message)) {
333 handleCanCommitTransaction(CanCommitTransaction.fromSerializable(message));
334 } else if (CommitTransaction.isSerializedType(message)) {
335 handleCommitTransaction(CommitTransaction.fromSerializable(message));
336 } else if (AbortTransaction.isSerializedType(message)) {
337 handleAbortTransaction(AbortTransaction.fromSerializable(message));
338 } else if (CloseTransactionChain.isSerializedType(message)) {
339 closeTransactionChain(CloseTransactionChain.fromSerializable(message));
340 } else if (message instanceof RegisterDataTreeChangeListener) {
341 treeChangeSupport.onMessage((RegisterDataTreeChangeListener) message, isLeader(), hasLeader());
342 } else if (message instanceof UpdateSchemaContext) {
343 updateSchemaContext((UpdateSchemaContext) message);
344 } else if (message instanceof PeerAddressResolved) {
345 PeerAddressResolved resolved = (PeerAddressResolved) message;
346 setPeerAddress(resolved.getPeerId(), resolved.getPeerAddress());
347 } else if (TX_COMMIT_TIMEOUT_CHECK_MESSAGE.equals(message)) {
348 commitTimeoutCheck();
349 } else if (message instanceof DatastoreContext) {
350 onDatastoreContext((DatastoreContext)message);
351 } else if (message instanceof RegisterRoleChangeListener) {
352 roleChangeNotifier.get().forward(message, context());
353 } else if (message instanceof FollowerInitialSyncUpStatus) {
354 shardMBean.setFollowerInitialSyncStatus(((FollowerInitialSyncUpStatus) message).isInitialSyncDone());
355 context().parent().tell(message, self());
356 } else if (GET_SHARD_MBEAN_MESSAGE.equals(message)) {
357 sender().tell(getShardMBean(), self());
358 } else if (message instanceof GetShardDataTree) {
359 sender().tell(store.getDataTree(), self());
360 } else if (message instanceof ServerRemoved) {
361 context().parent().forward(message, context());
362 } else if (ShardTransactionMessageRetrySupport.TIMER_MESSAGE_CLASS.isInstance(message)) {
363 messageRetrySupport.onTimerMessage(message);
364 } else if (message instanceof DataTreeCohortActorRegistry.CohortRegistryCommand) {
365 store.processCohortRegistryCommand(getSender(),
366 (DataTreeCohortActorRegistry.CohortRegistryCommand) message);
367 } else if (message instanceof PersistAbortTransactionPayload) {
368 final TransactionIdentifier txId = ((PersistAbortTransactionPayload) message).getTransactionId();
369 persistPayload(txId, AbortTransactionPayload.create(txId,
370 datastoreContext.getInitialPayloadSerializedBufferCapacity()), true);
371 persistPayload(txId, PurgeTransactionPayload.create(txId,
372 datastoreContext.getInitialPayloadSerializedBufferCapacity()), false);
373 } else if (message instanceof MakeLeaderLocal) {
375 } else if (RESUME_NEXT_PENDING_TRANSACTION.equals(message)) {
376 store.resumeNextPendingTransaction();
377 } else if (!responseMessageSlicer.handleMessage(message)) {
378 super.handleNonRaftCommand(message);
383 private void handleRequestAssemblerMessage(final Object message) {
384 dispatchers.getDispatcher(DispatcherType.Serialization).execute(() -> {
385 JavaSerializer.currentSystem().value_$eq((ExtendedActorSystem) context().system());
386 requestMessageAssembler.handleMessage(message, self());
390 @SuppressWarnings("checkstyle:IllegalCatch")
391 private void handleRequestEnvelope(final RequestEnvelope envelope) {
392 final long now = ticker().read();
394 final RequestSuccess<?, ?> success = handleRequest(envelope, now);
395 if (success != null) {
396 final long executionTimeNanos = ticker().read() - now;
397 if (success instanceof SliceableMessage) {
398 dispatchers.getDispatcher(DispatcherType.Serialization).execute(() ->
399 responseMessageSlicer.slice(SliceOptions.builder().identifier(success.getTarget())
400 .message(envelope.newSuccessEnvelope(success, executionTimeNanos))
401 .sendTo(envelope.getMessage().getReplyTo()).replyTo(self())
402 .onFailureCallback(t -> LOG.warn("Error slicing response {}", success, t)).build()));
404 envelope.sendSuccess(success, executionTimeNanos);
407 } catch (RequestException e) {
408 LOG.debug("{}: request {} failed", persistenceId(), envelope, e);
409 envelope.sendFailure(e, ticker().read() - now);
410 } catch (Exception e) {
411 LOG.debug("{}: request {} caused failure", persistenceId(), envelope, e);
412 envelope.sendFailure(new RuntimeRequestException("Request failed to process", e),
413 ticker().read() - now);
417 private void commitTimeoutCheck() {
418 store.checkForExpiredTransactions(transactionCommitTimeout, this::updateAccess);
419 commitCoordinator.checkForExpiredTransactions(transactionCommitTimeout, this);
420 requestMessageAssembler.checkExpiredAssembledMessageState();
423 private Optional<Long> updateAccess(final SimpleShardDataTreeCohort cohort) {
424 final FrontendIdentifier frontend = cohort.getIdentifier().getHistoryId().getClientId().getFrontendId();
425 final LeaderFrontendState state = knownFrontends.get(frontend);
427 // Not tell-based protocol, do nothing
428 return Optional.absent();
431 if (isIsolatedLeader()) {
432 // We are isolated and no new request can come through until we emerge from it. We are still updating
433 // liveness of frontend when we see it attempting to communicate. Use the last access timer.
434 return Optional.of(state.getLastSeenTicks());
437 // If this frontend has freshly connected, give it some time to catch up before killing its transactions.
438 return Optional.of(state.getLastConnectTicks());
441 private void onMakeLeaderLocal() {
442 LOG.debug("{}: onMakeLeaderLocal received", persistenceId());
444 getSender().tell(new Status.Success(null), getSelf());
448 final ActorSelection leader = getLeader();
450 if (leader == null) {
451 // Leader is not present. The cluster is most likely trying to
452 // elect a leader and we should let that run its normal course
454 // TODO we can wait for the election to complete and retry the
455 // request. We can also let the caller retry by sending a flag
456 // in the response indicating the request is "reTryable".
457 getSender().tell(new Failure(
458 new LeadershipTransferFailedException("We cannot initiate leadership transfer to local node. "
459 + "Currently there is no leader for " + persistenceId())),
464 leader.tell(new RequestLeadership(getId(), getSender()), getSelf());
467 // Acquire our frontend tracking handle and verify generation matches
469 private LeaderFrontendState findFrontend(final ClientIdentifier clientId) throws RequestException {
470 final LeaderFrontendState existing = knownFrontends.get(clientId.getFrontendId());
471 if (existing != null) {
472 final int cmp = Long.compareUnsigned(existing.getIdentifier().getGeneration(), clientId.getGeneration());
478 LOG.debug("{}: rejecting request from outdated client {}", persistenceId(), clientId);
479 throw new RetiredGenerationException(clientId.getGeneration(),
480 existing.getIdentifier().getGeneration());
483 LOG.info("{}: retiring state {}, outdated by request from client {}", persistenceId(), existing, clientId);
485 knownFrontends.remove(clientId.getFrontendId());
487 LOG.debug("{}: client {} is not yet known", persistenceId(), clientId);
493 private LeaderFrontendState getFrontend(final ClientIdentifier clientId) throws RequestException {
494 final LeaderFrontendState ret = findFrontend(clientId);
499 // TODO: a dedicated exception would be better, but this is technically true, too
500 throw new OutOfSequenceEnvelopeException(0);
504 private static ABIVersion selectVersion(final ConnectClientRequest message) {
505 final Range<ABIVersion> clientRange = Range.closed(message.getMinVersion(), message.getMaxVersion());
506 for (ABIVersion v : SUPPORTED_ABIVERSIONS) {
507 if (clientRange.contains(v)) {
512 throw new IllegalArgumentException(String.format(
513 "No common version between backend versions %s and client versions %s", SUPPORTED_ABIVERSIONS,
517 @SuppressWarnings("checkstyle:IllegalCatch")
518 private void handleConnectClient(final ConnectClientRequest message) {
520 final ClientIdentifier clientId = message.getTarget();
521 final LeaderFrontendState existing = findFrontend(clientId);
522 if (existing != null) {
526 if (!isLeader() || !isLeaderActive()) {
527 LOG.info("{}: not currently leader, rejecting request {}. isLeader: {}, isLeaderActive: {},"
528 + "isLeadershipTransferInProgress: {}.",
529 persistenceId(), message, isLeader(), isLeaderActive(), isLeadershipTransferInProgress());
530 throw new NotLeaderException(getSelf());
533 final ABIVersion selectedVersion = selectVersion(message);
534 final LeaderFrontendState frontend;
535 if (existing == null) {
536 frontend = new LeaderFrontendState(persistenceId(), clientId, store);
537 knownFrontends.put(clientId.getFrontendId(), frontend);
538 LOG.debug("{}: created state {} for client {}", persistenceId(), frontend, clientId);
543 frontend.reconnect();
544 message.getReplyTo().tell(new ConnectClientSuccess(message.getTarget(), message.getSequence(), getSelf(),
545 ImmutableList.of(), store.getDataTree(), CLIENT_MAX_MESSAGES).toVersion(selectedVersion),
546 ActorRef.noSender());
547 } catch (RequestException | RuntimeException e) {
548 message.getReplyTo().tell(new Failure(e), ActorRef.noSender());
553 private RequestSuccess<?, ?> handleRequest(final RequestEnvelope envelope, final long now)
554 throws RequestException {
555 // We are not the leader, hence we want to fail-fast.
556 if (!isLeader() || paused || !isLeaderActive()) {
557 LOG.debug("{}: not currently active leader, rejecting request {}. isLeader: {}, isLeaderActive: {},"
558 + "isLeadershipTransferInProgress: {}, paused: {}",
559 persistenceId(), envelope, isLeader(), isLeaderActive(), isLeadershipTransferInProgress(), paused);
560 throw new NotLeaderException(getSelf());
563 final Request<?, ?> request = envelope.getMessage();
564 if (request instanceof TransactionRequest) {
565 final TransactionRequest<?> txReq = (TransactionRequest<?>)request;
566 final ClientIdentifier clientId = txReq.getTarget().getHistoryId().getClientId();
567 return getFrontend(clientId).handleTransactionRequest(txReq, envelope, now);
568 } else if (request instanceof LocalHistoryRequest) {
569 final LocalHistoryRequest<?> lhReq = (LocalHistoryRequest<?>)request;
570 final ClientIdentifier clientId = lhReq.getTarget().getClientId();
571 return getFrontend(clientId).handleLocalHistoryRequest(lhReq, envelope, now);
573 LOG.warn("{}: rejecting unsupported request {}", persistenceId(), request);
574 throw new UnsupportedRequestException(request);
578 private boolean hasLeader() {
579 return getLeaderId() != null;
582 public int getPendingTxCommitQueueSize() {
583 return store.getQueueSize();
586 public int getCohortCacheSize() {
587 return commitCoordinator.getCohortCacheSize();
591 protected Optional<ActorRef> getRoleChangeNotifier() {
592 return roleChangeNotifier;
595 String getShardName() {
600 protected LeaderStateChanged newLeaderStateChanged(final String memberId, final String leaderId,
601 final short leaderPayloadVersion) {
602 return isLeader() ? new ShardLeaderStateChanged(memberId, leaderId, store.getDataTree(), leaderPayloadVersion)
603 : new ShardLeaderStateChanged(memberId, leaderId, leaderPayloadVersion);
606 protected void onDatastoreContext(final DatastoreContext context) {
607 datastoreContext = context;
609 setTransactionCommitTimeout();
611 setPersistence(datastoreContext.isPersistent());
613 updateConfigParams(datastoreContext.getShardRaftConfig());
616 // applyState() will be invoked once consensus is reached on the payload
617 void persistPayload(final Identifier id, final Payload payload, final boolean batchHint) {
618 boolean canSkipPayload = !hasFollowers() && !persistence().isRecoveryApplicable();
619 if (canSkipPayload) {
620 applyState(self(), id, payload);
622 // We are faking the sender
623 persistData(self(), id, payload, batchHint);
627 private void handleCommitTransaction(final CommitTransaction commit) {
629 commitCoordinator.handleCommit(commit.getTransactionId(), getSender(), this);
631 ActorSelection leader = getLeader();
632 if (leader == null) {
633 messageRetrySupport.addMessageToRetry(commit, getSender(),
634 "Could not commit transaction " + commit.getTransactionId());
636 LOG.debug("{}: Forwarding CommitTransaction to leader {}", persistenceId(), leader);
637 leader.forward(commit, getContext());
642 private void handleCanCommitTransaction(final CanCommitTransaction canCommit) {
643 LOG.debug("{}: Can committing transaction {}", persistenceId(), canCommit.getTransactionId());
646 commitCoordinator.handleCanCommit(canCommit.getTransactionId(), getSender(), this);
648 ActorSelection leader = getLeader();
649 if (leader == null) {
650 messageRetrySupport.addMessageToRetry(canCommit, getSender(),
651 "Could not canCommit transaction " + canCommit.getTransactionId());
653 LOG.debug("{}: Forwarding CanCommitTransaction to leader {}", persistenceId(), leader);
654 leader.forward(canCommit, getContext());
659 @SuppressWarnings("checkstyle:IllegalCatch")
660 protected void handleBatchedModificationsLocal(final BatchedModifications batched, final ActorRef sender) {
662 commitCoordinator.handleBatchedModifications(batched, sender, this);
663 } catch (Exception e) {
664 LOG.error("{}: Error handling BatchedModifications for Tx {}", persistenceId(),
665 batched.getTransactionId(), e);
666 sender.tell(new Failure(e), getSelf());
670 private void handleBatchedModifications(final BatchedModifications batched) {
671 // This message is sent to prepare the modifications transaction directly on the Shard as an
672 // optimization to avoid the extra overhead of a separate ShardTransaction actor. On the last
673 // BatchedModifications message, the caller sets the ready flag in the message indicating
674 // modifications are complete. The reply contains the cohort actor path (this actor) for the caller
675 // to initiate the 3-phase commit. This also avoids the overhead of sending an additional
676 // ReadyTransaction message.
678 // If we're not the leader then forward to the leader. This is a safety measure - we shouldn't
679 // normally get here if we're not the leader as the front-end (TransactionProxy) should determine
680 // the primary/leader shard. However with timing and caching on the front-end, there's a small
681 // window where it could have a stale leader during leadership transitions.
683 boolean isLeaderActive = isLeaderActive();
684 if (isLeader() && isLeaderActive) {
685 handleBatchedModificationsLocal(batched, getSender());
687 ActorSelection leader = getLeader();
688 if (!isLeaderActive || leader == null) {
689 messageRetrySupport.addMessageToRetry(batched, getSender(),
690 "Could not process BatchedModifications " + batched.getTransactionId());
692 // If this is not the first batch and leadership changed in between batched messages,
693 // we need to reconstruct previous BatchedModifications from the transaction
694 // DataTreeModification, honoring the max batched modification count, and forward all the
695 // previous BatchedModifications to the new leader.
696 Collection<BatchedModifications> newModifications = commitCoordinator
697 .createForwardedBatchedModifications(batched,
698 datastoreContext.getShardBatchedModificationCount());
700 LOG.debug("{}: Forwarding {} BatchedModifications to leader {}", persistenceId(),
701 newModifications.size(), leader);
703 for (BatchedModifications bm : newModifications) {
704 leader.forward(bm, getContext());
710 private boolean failIfIsolatedLeader(final ActorRef sender) {
711 if (isIsolatedLeader()) {
712 sender.tell(new Failure(new NoShardLeaderException(String.format(
713 "Shard %s was the leader but has lost contact with all of its followers. Either all"
714 + " other follower nodes are down or this node is isolated by a network partition.",
715 persistenceId()))), getSelf());
722 protected boolean isIsolatedLeader() {
723 return getRaftState() == RaftState.IsolatedLeader;
726 @SuppressWarnings("checkstyle:IllegalCatch")
727 private void handleReadyLocalTransaction(final ReadyLocalTransaction message) {
728 LOG.debug("{}: handleReadyLocalTransaction for {}", persistenceId(), message.getTransactionId());
730 boolean isLeaderActive = isLeaderActive();
731 if (isLeader() && isLeaderActive) {
733 commitCoordinator.handleReadyLocalTransaction(message, getSender(), this);
734 } catch (Exception e) {
735 LOG.error("{}: Error handling ReadyLocalTransaction for Tx {}", persistenceId(),
736 message.getTransactionId(), e);
737 getSender().tell(new Failure(e), getSelf());
740 ActorSelection leader = getLeader();
741 if (!isLeaderActive || leader == null) {
742 messageRetrySupport.addMessageToRetry(message, getSender(),
743 "Could not process ready local transaction " + message.getTransactionId());
745 LOG.debug("{}: Forwarding ReadyLocalTransaction to leader {}", persistenceId(), leader);
746 message.setRemoteVersion(getCurrentBehavior().getLeaderPayloadVersion());
747 leader.forward(message, getContext());
752 private void handleForwardedReadyTransaction(final ForwardedReadyTransaction forwardedReady) {
753 LOG.debug("{}: handleForwardedReadyTransaction for {}", persistenceId(), forwardedReady.getTransactionId());
755 boolean isLeaderActive = isLeaderActive();
756 if (isLeader() && isLeaderActive) {
757 commitCoordinator.handleForwardedReadyTransaction(forwardedReady, getSender(), this);
759 ActorSelection leader = getLeader();
760 if (!isLeaderActive || leader == null) {
761 messageRetrySupport.addMessageToRetry(forwardedReady, getSender(),
762 "Could not process forwarded ready transaction " + forwardedReady.getTransactionId());
764 LOG.debug("{}: Forwarding ForwardedReadyTransaction to leader {}", persistenceId(), leader);
766 ReadyLocalTransaction readyLocal = new ReadyLocalTransaction(forwardedReady.getTransactionId(),
767 forwardedReady.getTransaction().getSnapshot(), forwardedReady.isDoImmediateCommit(),
768 forwardedReady.getParticipatingShardNames());
769 readyLocal.setRemoteVersion(getCurrentBehavior().getLeaderPayloadVersion());
770 leader.forward(readyLocal, getContext());
775 private void handleAbortTransaction(final AbortTransaction abort) {
776 doAbortTransaction(abort.getTransactionId(), getSender());
779 void doAbortTransaction(final Identifier transactionID, final ActorRef sender) {
780 commitCoordinator.handleAbort(transactionID, sender, this);
783 private void handleCreateTransaction(final Object message) {
785 createTransaction(CreateTransaction.fromSerializable(message));
786 } else if (getLeader() != null) {
787 getLeader().forward(message, getContext());
789 getSender().tell(new Failure(new NoShardLeaderException(
790 "Could not create a shard transaction", persistenceId())), getSelf());
794 private void closeTransactionChain(final CloseTransactionChain closeTransactionChain) {
795 final LocalHistoryIdentifier id = closeTransactionChain.getIdentifier();
796 store.closeTransactionChain(id, null);
797 store.purgeTransactionChain(id, null);
800 @SuppressWarnings("checkstyle:IllegalCatch")
801 private void createTransaction(final CreateTransaction createTransaction) {
803 if (TransactionType.fromInt(createTransaction.getTransactionType()) != TransactionType.READ_ONLY
804 && failIfIsolatedLeader(getSender())) {
808 ActorRef transactionActor = createTransaction(createTransaction.getTransactionType(),
809 createTransaction.getTransactionId());
811 getSender().tell(new CreateTransactionReply(Serialization.serializedActorPath(transactionActor),
812 createTransaction.getTransactionId(), createTransaction.getVersion()).toSerializable(), getSelf());
813 } catch (Exception e) {
814 getSender().tell(new Failure(e), getSelf());
818 private ActorRef createTransaction(final int transactionType, final TransactionIdentifier transactionId) {
819 LOG.debug("{}: Creating transaction : {} ", persistenceId(), transactionId);
820 return transactionActorFactory.newShardTransaction(TransactionType.fromInt(transactionType),
824 private void updateSchemaContext(final UpdateSchemaContext message) {
825 updateSchemaContext(message.getSchemaContext());
829 void updateSchemaContext(final SchemaContext schemaContext) {
830 store.updateSchemaContext(schemaContext);
833 private boolean isMetricsCaptureEnabled() {
834 CommonConfig config = new CommonConfig(getContext().system().settings().config());
835 return config.isMetricCaptureEnabled();
840 public RaftActorSnapshotCohort getRaftActorSnapshotCohort() {
841 return snapshotCohort;
846 protected RaftActorRecoveryCohort getRaftActorRecoveryCohort() {
847 if (restoreFromSnapshot == null) {
848 return ShardRecoveryCoordinator.create(store, persistenceId(), LOG);
851 return ShardRecoveryCoordinator.forSnapshot(store, persistenceId(), LOG, restoreFromSnapshot.getSnapshot());
855 protected void onRecoveryComplete() {
856 restoreFromSnapshot = null;
858 //notify shard manager
859 getContext().parent().tell(new ActorInitialized(), getSelf());
861 // Being paranoid here - this method should only be called once but just in case...
862 if (txCommitTimeoutCheckSchedule == null) {
863 // Schedule a message to be periodically sent to check if the current in-progress
864 // transaction should be expired and aborted.
865 FiniteDuration period = Duration.create(transactionCommitTimeout / 3, TimeUnit.MILLISECONDS);
866 txCommitTimeoutCheckSchedule = getContext().system().scheduler().schedule(
867 period, period, getSelf(),
868 TX_COMMIT_TIMEOUT_CHECK_MESSAGE, getContext().dispatcher(), ActorRef.noSender());
873 protected void applyState(final ActorRef clientActor, final Identifier identifier, final Object data) {
874 if (data instanceof Payload) {
876 store.applyReplicatedPayload(identifier, (Payload)data);
877 } catch (DataValidationFailedException | IOException e) {
878 LOG.error("{}: Error applying replica {}", persistenceId(), identifier, e);
881 LOG.error("{}: Unknown state for {} received {}", persistenceId(), identifier, data);
886 protected void onStateChanged() {
887 boolean isLeader = isLeader();
888 boolean hasLeader = hasLeader();
889 treeChangeSupport.onLeadershipChange(isLeader, hasLeader);
891 // If this actor is no longer the leader close all the transaction chains
893 if (LOG.isDebugEnabled()) {
895 "{}: onStateChanged: Closing all transaction chains because shard {} is no longer the leader",
896 persistenceId(), getId());
900 store.purgeLeaderState();
903 if (hasLeader && !isIsolatedLeader()) {
904 messageRetrySupport.retryMessages();
909 protected void onLeaderChanged(final String oldLeader, final String newLeader) {
910 shardMBean.incrementLeadershipChangeCount();
914 if (!knownFrontends.isEmpty()) {
915 LOG.debug("{}: removing frontend state for {}", persistenceId(), knownFrontends.keySet());
916 knownFrontends = ImmutableMap.of();
919 requestMessageAssembler.close();
922 // No leader anywhere, nothing else to do
926 // Another leader was elected. If we were the previous leader and had pending transactions, convert
927 // them to transaction messages and send to the new leader.
928 ActorSelection leader = getLeader();
929 if (leader != null) {
930 Collection<?> messagesToForward = convertPendingTransactionsToMessages();
932 if (!messagesToForward.isEmpty()) {
933 LOG.debug("{}: Forwarding {} pending transaction messages to leader {}", persistenceId(),
934 messagesToForward.size(), leader);
936 for (Object message : messagesToForward) {
937 LOG.debug("{}: Forwarding pending transaction message {}", persistenceId(), message);
939 leader.tell(message, self());
943 commitCoordinator.abortPendingTransactions("The transacton was aborted due to inflight leadership "
944 + "change and the leader address isn't available.", this);
947 // We have become the leader, we need to reconstruct frontend state
948 knownFrontends = Verify.verifyNotNull(frontendMetadata.toLeaderState(this));
949 LOG.debug("{}: became leader with frontend state for {}", persistenceId(), knownFrontends.keySet());
952 if (!isIsolatedLeader()) {
953 messageRetrySupport.retryMessages();
958 * Clears all pending transactions and converts them to messages to be forwarded to a new leader.
960 * @return the converted messages
962 public Collection<?> convertPendingTransactionsToMessages() {
963 return commitCoordinator.convertPendingTransactionsToMessages(
964 datastoreContext.getShardBatchedModificationCount());
968 protected void pauseLeader(final Runnable operation) {
969 LOG.debug("{}: In pauseLeader, operation: {}", persistenceId(), operation);
972 // Tell-based protocol can replay transaction state, so it is safe to blow it up when we are paused.
973 knownFrontends.values().forEach(LeaderFrontendState::retire);
974 knownFrontends = ImmutableMap.of();
976 store.setRunOnPendingTransactionsComplete(operation);
980 protected void unpauseLeader() {
981 LOG.debug("{}: In unpauseLeader", persistenceId());
984 store.setRunOnPendingTransactionsComplete(null);
986 // Restore tell-based protocol state as if we were becoming the leader
987 knownFrontends = Verify.verifyNotNull(frontendMetadata.toLeaderState(this));
991 protected OnDemandRaftState.AbstractBuilder<?, ?> newOnDemandRaftStateBuilder() {
992 return OnDemandShardState.newBuilder().treeChangeListenerActors(treeChangeSupport.getListenerActors())
993 .commitCohortActors(store.getCohortActors());
997 public String persistenceId() {
1002 ShardCommitCoordinator getCommitCoordinator() {
1003 return commitCoordinator;
1006 public DatastoreContext getDatastoreContext() {
1007 return datastoreContext;
1011 public ShardDataTree getDataStore() {
1016 ShardStats getShardMBean() {
1020 public static Builder builder() {
1021 return new Builder();
1024 public abstract static class AbstractBuilder<T extends AbstractBuilder<T, S>, S extends Shard> {
1025 private final Class<S> shardClass;
1026 private ShardIdentifier id;
1027 private Map<String, String> peerAddresses = Collections.emptyMap();
1028 private DatastoreContext datastoreContext;
1029 private SchemaContextProvider schemaContextProvider;
1030 private DatastoreSnapshot.ShardSnapshot restoreFromSnapshot;
1031 private DataTree dataTree;
1032 private volatile boolean sealed;
1034 protected AbstractBuilder(final Class<S> shardClass) {
1035 this.shardClass = shardClass;
1038 protected void checkSealed() {
1039 Preconditions.checkState(!sealed, "Builder isalready sealed - further modifications are not allowed");
1042 @SuppressWarnings("unchecked")
1047 public T id(final ShardIdentifier newId) {
1053 public T peerAddresses(final Map<String, String> newPeerAddresses) {
1055 this.peerAddresses = newPeerAddresses;
1059 public T datastoreContext(final DatastoreContext newDatastoreContext) {
1061 this.datastoreContext = newDatastoreContext;
1065 public T schemaContextProvider(final SchemaContextProvider newSchemaContextProvider) {
1067 this.schemaContextProvider = Preconditions.checkNotNull(newSchemaContextProvider);
1071 public T restoreFromSnapshot(final DatastoreSnapshot.ShardSnapshot newRestoreFromSnapshot) {
1073 this.restoreFromSnapshot = newRestoreFromSnapshot;
1077 public T dataTree(final DataTree newDataTree) {
1079 this.dataTree = newDataTree;
1083 public ShardIdentifier getId() {
1087 public Map<String, String> getPeerAddresses() {
1088 return peerAddresses;
1091 public DatastoreContext getDatastoreContext() {
1092 return datastoreContext;
1095 public SchemaContext getSchemaContext() {
1096 return Verify.verifyNotNull(schemaContextProvider.getSchemaContext());
1099 public DatastoreSnapshot.ShardSnapshot getRestoreFromSnapshot() {
1100 return restoreFromSnapshot;
1103 public DataTree getDataTree() {
1107 public TreeType getTreeType() {
1108 switch (datastoreContext.getLogicalStoreType()) {
1110 return TreeType.CONFIGURATION;
1112 return TreeType.OPERATIONAL;
1114 throw new IllegalStateException("Unhandled logical store type "
1115 + datastoreContext.getLogicalStoreType());
1119 protected void verify() {
1120 Preconditions.checkNotNull(id, "id should not be null");
1121 Preconditions.checkNotNull(peerAddresses, "peerAddresses should not be null");
1122 Preconditions.checkNotNull(datastoreContext, "dataStoreContext should not be null");
1123 Preconditions.checkNotNull(schemaContextProvider, "schemaContextProvider should not be null");
1126 public Props props() {
1129 return Props.create(shardClass, this);
1133 public static class Builder extends AbstractBuilder<Builder, Shard> {
1140 return Ticker.systemTicker();
1143 void scheduleNextPendingTransaction() {
1144 self().tell(RESUME_NEXT_PENDING_TRANSACTION, ActorRef.noSender());