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.messaging.MessageAssembler;
88 import org.opendaylight.controller.cluster.messaging.MessageSlicer;
89 import org.opendaylight.controller.cluster.messaging.SliceOptions;
90 import org.opendaylight.controller.cluster.notifications.LeaderStateChanged;
91 import org.opendaylight.controller.cluster.notifications.RegisterRoleChangeListener;
92 import org.opendaylight.controller.cluster.notifications.RoleChangeNotifier;
93 import org.opendaylight.controller.cluster.raft.LeadershipTransferFailedException;
94 import org.opendaylight.controller.cluster.raft.RaftActor;
95 import org.opendaylight.controller.cluster.raft.RaftActorRecoveryCohort;
96 import org.opendaylight.controller.cluster.raft.RaftActorSnapshotCohort;
97 import org.opendaylight.controller.cluster.raft.RaftState;
98 import org.opendaylight.controller.cluster.raft.base.messages.FollowerInitialSyncUpStatus;
99 import org.opendaylight.controller.cluster.raft.client.messages.OnDemandRaftState;
100 import org.opendaylight.controller.cluster.raft.messages.AppendEntriesReply;
101 import org.opendaylight.controller.cluster.raft.messages.RequestLeadership;
102 import org.opendaylight.controller.cluster.raft.messages.ServerRemoved;
103 import org.opendaylight.controller.cluster.raft.protobuff.client.messages.Payload;
104 import org.opendaylight.yangtools.concepts.Identifier;
105 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTree;
106 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataValidationFailedException;
107 import org.opendaylight.yangtools.yang.data.api.schema.tree.TreeType;
108 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
109 import org.opendaylight.yangtools.yang.model.api.SchemaContextProvider;
110 import scala.concurrent.duration.Duration;
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 ShardStats shardMBean;
166 private final ShardDataTreeListenerInfoMXBeanImpl listenerInfoMXBean;
168 private DatastoreContext datastoreContext;
170 private final ShardCommitCoordinator commitCoordinator;
172 private long transactionCommitTimeout;
174 private Cancellable txCommitTimeoutCheckSchedule;
176 private final Optional<ActorRef> roleChangeNotifier;
178 private final MessageTracker appendEntriesReplyTracker;
180 private final ShardTransactionActorFactory transactionActorFactory;
182 private final ShardSnapshotCohort snapshotCohort;
184 private final DataTreeChangeListenerSupport treeChangeSupport = new DataTreeChangeListenerSupport(this);
186 private ShardSnapshot restoreFromSnapshot;
188 private final ShardTransactionMessageRetrySupport messageRetrySupport;
190 private final FrontendMetadata frontendMetadata;
191 private Map<FrontendIdentifier, LeaderFrontendState> knownFrontends = ImmutableMap.of();
192 private boolean paused;
194 private final MessageSlicer responseMessageSlicer;
195 private final Dispatchers dispatchers;
197 private final MessageAssembler requestMessageAssembler;
199 protected Shard(final AbstractBuilder<?, ?> builder) {
200 super(builder.getId().toString(), builder.getPeerAddresses(),
201 Optional.of(builder.getDatastoreContext().getShardRaftConfig()), DataStoreVersions.CURRENT_VERSION);
203 this.name = builder.getId().toString();
204 this.datastoreContext = builder.getDatastoreContext();
205 this.restoreFromSnapshot = builder.getRestoreFromSnapshot();
206 this.frontendMetadata = new FrontendMetadata(name);
208 setPersistence(datastoreContext.isPersistent());
210 LOG.info("Shard created : {}, persistent : {}", name, datastoreContext.isPersistent());
212 ShardDataTreeChangeListenerPublisherActorProxy treeChangeListenerPublisher =
213 new ShardDataTreeChangeListenerPublisherActorProxy(getContext(), name + "-DTCL-publisher", name);
214 if (builder.getDataTree() != null) {
215 store = new ShardDataTree(this, builder.getSchemaContext(), builder.getDataTree(),
216 treeChangeListenerPublisher, name, frontendMetadata);
218 store = new ShardDataTree(this, builder.getSchemaContext(), builder.getTreeType(),
219 builder.getDatastoreContext().getStoreRoot(), treeChangeListenerPublisher, name, frontendMetadata);
222 shardMBean = ShardMBeanFactory.getShardStatsMBean(name, datastoreContext.getDataStoreMXBeanType(), this);
224 if (isMetricsCaptureEnabled()) {
225 getContext().become(new MeteringBehavior(this));
228 commitCoordinator = new ShardCommitCoordinator(store, LOG, this.name);
230 setTransactionCommitTimeout();
232 // create a notifier actor for each cluster member
233 roleChangeNotifier = createRoleChangeNotifier(name);
235 appendEntriesReplyTracker = new MessageTracker(AppendEntriesReply.class,
236 getRaftActorContext().getConfigParams().getIsolatedCheckIntervalInMillis());
238 dispatchers = new Dispatchers(context().system().dispatchers());
239 transactionActorFactory = new ShardTransactionActorFactory(store, datastoreContext,
240 dispatchers.getDispatcherPath(Dispatchers.DispatcherType.Transaction),
241 self(), getContext(), shardMBean, builder.getId().getShardName());
243 snapshotCohort = ShardSnapshotCohort.create(getContext(), builder.getId().getMemberName(), store, LOG,
246 messageRetrySupport = new ShardTransactionMessageRetrySupport(this);
248 responseMessageSlicer = MessageSlicer.builder().logContext(this.name)
249 .messageSliceSize(datastoreContext.getMaximumMessageSliceSize())
250 .fileBackedStreamFactory(getRaftActorContext().getFileBackedOutputStreamFactory())
251 .expireStateAfterInactivity(2, TimeUnit.MINUTES).build();
253 requestMessageAssembler = MessageAssembler.builder().logContext(this.name)
254 .fileBackedStreamFactory(getRaftActorContext().getFileBackedOutputStreamFactory())
255 .assembledMessageCallback((message, sender) -> self().tell(message, sender))
256 .expireStateAfterInactivity(datastoreContext.getRequestTimeout(), TimeUnit.NANOSECONDS).build();
258 listenerInfoMXBean = new ShardDataTreeListenerInfoMXBeanImpl(name, datastoreContext.getDataStoreMXBeanType(),
260 listenerInfoMXBean.register();
263 private void setTransactionCommitTimeout() {
264 transactionCommitTimeout = TimeUnit.MILLISECONDS.convert(
265 datastoreContext.getShardTransactionCommitTimeoutInSeconds(), TimeUnit.SECONDS) / 2;
268 private Optional<ActorRef> createRoleChangeNotifier(final String shardId) {
269 ActorRef shardRoleChangeNotifier = this.getContext().actorOf(
270 RoleChangeNotifier.getProps(shardId), shardId + "-notifier");
271 return Optional.of(shardRoleChangeNotifier);
275 public void postStop() {
276 LOG.info("Stopping Shard {}", persistenceId());
280 messageRetrySupport.close();
282 if (txCommitTimeoutCheckSchedule != null) {
283 txCommitTimeoutCheckSchedule.cancel();
286 commitCoordinator.abortPendingTransactions("Transaction aborted due to shutdown.", this);
288 shardMBean.unregisterMBean();
289 listenerInfoMXBean.unregister();
293 protected void handleRecover(final Object message) {
294 LOG.debug("{}: onReceiveRecover: Received message {} from {}", persistenceId(), message.getClass(),
297 super.handleRecover(message);
298 if (LOG.isTraceEnabled()) {
299 appendEntriesReplyTracker.begin();
304 protected void handleNonRaftCommand(final Object message) {
305 try (MessageTracker.Context context = appendEntriesReplyTracker.received(message)) {
306 final Optional<Error> maybeError = context.error();
307 if (maybeError.isPresent()) {
308 LOG.trace("{} : AppendEntriesReply failed to arrive at the expected interval {}", persistenceId(),
312 store.resetTransactionBatch();
314 if (message instanceof RequestEnvelope) {
315 handleRequestEnvelope((RequestEnvelope)message);
316 } else if (MessageAssembler.isHandledMessage(message)) {
317 handleRequestAssemblerMessage(message);
318 } else if (message instanceof ConnectClientRequest) {
319 handleConnectClient((ConnectClientRequest)message);
320 } else if (CreateTransaction.isSerializedType(message)) {
321 handleCreateTransaction(message);
322 } else if (message instanceof BatchedModifications) {
323 handleBatchedModifications((BatchedModifications)message);
324 } else if (message instanceof ForwardedReadyTransaction) {
325 handleForwardedReadyTransaction((ForwardedReadyTransaction) message);
326 } else if (message instanceof ReadyLocalTransaction) {
327 handleReadyLocalTransaction((ReadyLocalTransaction)message);
328 } else if (CanCommitTransaction.isSerializedType(message)) {
329 handleCanCommitTransaction(CanCommitTransaction.fromSerializable(message));
330 } else if (CommitTransaction.isSerializedType(message)) {
331 handleCommitTransaction(CommitTransaction.fromSerializable(message));
332 } else if (AbortTransaction.isSerializedType(message)) {
333 handleAbortTransaction(AbortTransaction.fromSerializable(message));
334 } else if (CloseTransactionChain.isSerializedType(message)) {
335 closeTransactionChain(CloseTransactionChain.fromSerializable(message));
336 } else if (message instanceof RegisterDataTreeChangeListener) {
337 treeChangeSupport.onMessage((RegisterDataTreeChangeListener) message, isLeader(), hasLeader());
338 } else if (message instanceof UpdateSchemaContext) {
339 updateSchemaContext((UpdateSchemaContext) message);
340 } else if (message instanceof PeerAddressResolved) {
341 PeerAddressResolved resolved = (PeerAddressResolved) message;
342 setPeerAddress(resolved.getPeerId(), resolved.getPeerAddress());
343 } else if (TX_COMMIT_TIMEOUT_CHECK_MESSAGE.equals(message)) {
344 commitTimeoutCheck();
345 } else if (message instanceof DatastoreContext) {
346 onDatastoreContext((DatastoreContext)message);
347 } else if (message instanceof RegisterRoleChangeListener) {
348 roleChangeNotifier.get().forward(message, context());
349 } else if (message instanceof FollowerInitialSyncUpStatus) {
350 shardMBean.setFollowerInitialSyncStatus(((FollowerInitialSyncUpStatus) message).isInitialSyncDone());
351 context().parent().tell(message, self());
352 } else if (GET_SHARD_MBEAN_MESSAGE.equals(message)) {
353 sender().tell(getShardMBean(), self());
354 } else if (message instanceof GetShardDataTree) {
355 sender().tell(store.getDataTree(), self());
356 } else if (message instanceof ServerRemoved) {
357 context().parent().forward(message, context());
358 } else if (ShardTransactionMessageRetrySupport.TIMER_MESSAGE_CLASS.isInstance(message)) {
359 messageRetrySupport.onTimerMessage(message);
360 } else if (message instanceof DataTreeCohortActorRegistry.CohortRegistryCommand) {
361 store.processCohortRegistryCommand(getSender(),
362 (DataTreeCohortActorRegistry.CohortRegistryCommand) message);
363 } else if (message instanceof PersistAbortTransactionPayload) {
364 final TransactionIdentifier txId = ((PersistAbortTransactionPayload) message).getTransactionId();
365 persistPayload(txId, AbortTransactionPayload.create(txId), true);
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 -> {
396 LOG.warn("Error slicing response {}", success, t);
399 envelope.sendSuccess(success, executionTimeNanos);
402 } catch (RequestException e) {
403 LOG.debug("{}: request {} failed", persistenceId(), envelope, e);
404 envelope.sendFailure(e, ticker().read() - now);
405 } catch (Exception e) {
406 LOG.debug("{}: request {} caused failure", persistenceId(), envelope, e);
407 envelope.sendFailure(new RuntimeRequestException("Request failed to process", e),
408 ticker().read() - now);
412 private void commitTimeoutCheck() {
413 store.checkForExpiredTransactions(transactionCommitTimeout, this::updateAccess);
414 commitCoordinator.checkForExpiredTransactions(transactionCommitTimeout, this);
415 requestMessageAssembler.checkExpiredAssembledMessageState();
418 private Optional<Long> updateAccess(final SimpleShardDataTreeCohort cohort) {
419 final FrontendIdentifier frontend = cohort.getIdentifier().getHistoryId().getClientId().getFrontendId();
420 final LeaderFrontendState state = knownFrontends.get(frontend);
422 // Not tell-based protocol, do nothing
423 return Optional.absent();
426 if (isIsolatedLeader()) {
427 // We are isolated and no new request can come through until we emerge from it. We are still updating
428 // liveness of frontend when we see it attempting to communicate. Use the last access timer.
429 return Optional.of(state.getLastSeenTicks());
432 // If this frontend has freshly connected, give it some time to catch up before killing its transactions.
433 return Optional.of(state.getLastConnectTicks());
436 private void onMakeLeaderLocal() {
437 LOG.debug("{}: onMakeLeaderLocal received", persistenceId());
439 getSender().tell(new Status.Success(null), getSelf());
443 final ActorSelection leader = getLeader();
445 if (leader == null) {
446 // Leader is not present. The cluster is most likely trying to
447 // elect a leader and we should let that run its normal course
449 // TODO we can wait for the election to complete and retry the
450 // request. We can also let the caller retry by sending a flag
451 // in the response indicating the request is "reTryable".
452 getSender().tell(new Failure(
453 new LeadershipTransferFailedException("We cannot initiate leadership transfer to local node. "
454 + "Currently there is no leader for " + persistenceId())),
459 leader.tell(new RequestLeadership(getId(), getSender()), getSelf());
462 // Acquire our frontend tracking handle and verify generation matches
464 private LeaderFrontendState findFrontend(final ClientIdentifier clientId) throws RequestException {
465 final LeaderFrontendState existing = knownFrontends.get(clientId.getFrontendId());
466 if (existing != null) {
467 final int cmp = Long.compareUnsigned(existing.getIdentifier().getGeneration(), clientId.getGeneration());
473 LOG.debug("{}: rejecting request from outdated client {}", persistenceId(), clientId);
474 throw new RetiredGenerationException(existing.getIdentifier().getGeneration());
477 LOG.info("{}: retiring state {}, outdated by request from client {}", persistenceId(), existing, clientId);
479 knownFrontends.remove(clientId.getFrontendId());
481 LOG.debug("{}: client {} is not yet known", persistenceId(), clientId);
487 private LeaderFrontendState getFrontend(final ClientIdentifier clientId) throws RequestException {
488 final LeaderFrontendState ret = findFrontend(clientId);
493 // TODO: a dedicated exception would be better, but this is technically true, too
494 throw new OutOfSequenceEnvelopeException(0);
498 private static ABIVersion selectVersion(final ConnectClientRequest message) {
499 final Range<ABIVersion> clientRange = Range.closed(message.getMinVersion(), message.getMaxVersion());
500 for (ABIVersion v : SUPPORTED_ABIVERSIONS) {
501 if (clientRange.contains(v)) {
506 throw new IllegalArgumentException(String.format(
507 "No common version between backend versions %s and client versions %s", SUPPORTED_ABIVERSIONS,
511 @SuppressWarnings("checkstyle:IllegalCatch")
512 private void handleConnectClient(final ConnectClientRequest message) {
514 final ClientIdentifier clientId = message.getTarget();
515 final LeaderFrontendState existing = findFrontend(clientId);
516 if (existing != null) {
520 if (!isLeader() || !isLeaderActive()) {
521 LOG.info("{}: not currently leader, rejecting request {}. isLeader: {}, isLeaderActive: {},"
522 + "isLeadershipTransferInProgress: {}.",
523 persistenceId(), message, isLeader(), isLeaderActive(), isLeadershipTransferInProgress());
524 throw new NotLeaderException(getSelf());
527 final ABIVersion selectedVersion = selectVersion(message);
528 final LeaderFrontendState frontend;
529 if (existing == null) {
530 frontend = new LeaderFrontendState(persistenceId(), clientId, store);
531 knownFrontends.put(clientId.getFrontendId(), frontend);
532 LOG.debug("{}: created state {} for client {}", persistenceId(), frontend, clientId);
537 frontend.reconnect();
538 message.getReplyTo().tell(new ConnectClientSuccess(message.getTarget(), message.getSequence(), getSelf(),
539 ImmutableList.of(), store.getDataTree(), CLIENT_MAX_MESSAGES).toVersion(selectedVersion),
540 ActorRef.noSender());
541 } catch (RequestException | RuntimeException e) {
542 message.getReplyTo().tell(new Failure(e), ActorRef.noSender());
547 private RequestSuccess<?, ?> handleRequest(final RequestEnvelope envelope, final long now)
548 throws RequestException {
549 // We are not the leader, hence we want to fail-fast.
550 if (!isLeader() || paused || !isLeaderActive()) {
551 LOG.debug("{}: not currently active leader, rejecting request {}. isLeader: {}, isLeaderActive: {},"
552 + "isLeadershipTransferInProgress: {}, paused: {}",
553 persistenceId(), envelope, isLeader(), isLeaderActive(), isLeadershipTransferInProgress(), paused);
554 throw new NotLeaderException(getSelf());
557 final Request<?, ?> request = envelope.getMessage();
558 if (request instanceof TransactionRequest) {
559 final TransactionRequest<?> txReq = (TransactionRequest<?>)request;
560 final ClientIdentifier clientId = txReq.getTarget().getHistoryId().getClientId();
561 return getFrontend(clientId).handleTransactionRequest(txReq, envelope, now);
562 } else if (request instanceof LocalHistoryRequest) {
563 final LocalHistoryRequest<?> lhReq = (LocalHistoryRequest<?>)request;
564 final ClientIdentifier clientId = lhReq.getTarget().getClientId();
565 return getFrontend(clientId).handleLocalHistoryRequest(lhReq, envelope, now);
567 LOG.warn("{}: rejecting unsupported request {}", persistenceId(), request);
568 throw new UnsupportedRequestException(request);
572 private boolean hasLeader() {
573 return getLeaderId() != null;
576 public int getPendingTxCommitQueueSize() {
577 return store.getQueueSize();
580 public int getCohortCacheSize() {
581 return commitCoordinator.getCohortCacheSize();
585 protected Optional<ActorRef> getRoleChangeNotifier() {
586 return roleChangeNotifier;
590 protected LeaderStateChanged newLeaderStateChanged(final String memberId, final String leaderId,
591 final short leaderPayloadVersion) {
592 return isLeader() ? new ShardLeaderStateChanged(memberId, leaderId, store.getDataTree(), leaderPayloadVersion)
593 : new ShardLeaderStateChanged(memberId, leaderId, leaderPayloadVersion);
596 protected void onDatastoreContext(final DatastoreContext context) {
597 datastoreContext = context;
599 setTransactionCommitTimeout();
601 setPersistence(datastoreContext.isPersistent());
603 updateConfigParams(datastoreContext.getShardRaftConfig());
606 // applyState() will be invoked once consensus is reached on the payload
607 void persistPayload(final Identifier id, final Payload payload, final boolean batchHint) {
608 boolean canSkipPayload = !hasFollowers() && !persistence().isRecoveryApplicable();
609 if (canSkipPayload) {
610 applyState(self(), id, payload);
612 // We are faking the sender
613 persistData(self(), id, payload, batchHint);
617 private void handleCommitTransaction(final CommitTransaction commit) {
619 commitCoordinator.handleCommit(commit.getTransactionId(), getSender(), this);
621 ActorSelection leader = getLeader();
622 if (leader == null) {
623 messageRetrySupport.addMessageToRetry(commit, getSender(),
624 "Could not commit transaction " + commit.getTransactionId());
626 LOG.debug("{}: Forwarding CommitTransaction to leader {}", persistenceId(), leader);
627 leader.forward(commit, getContext());
632 private void handleCanCommitTransaction(final CanCommitTransaction canCommit) {
633 LOG.debug("{}: Can committing transaction {}", persistenceId(), canCommit.getTransactionId());
636 commitCoordinator.handleCanCommit(canCommit.getTransactionId(), getSender(), this);
638 ActorSelection leader = getLeader();
639 if (leader == null) {
640 messageRetrySupport.addMessageToRetry(canCommit, getSender(),
641 "Could not canCommit transaction " + canCommit.getTransactionId());
643 LOG.debug("{}: Forwarding CanCommitTransaction to leader {}", persistenceId(), leader);
644 leader.forward(canCommit, getContext());
649 @SuppressWarnings("checkstyle:IllegalCatch")
650 protected void handleBatchedModificationsLocal(final BatchedModifications batched, final ActorRef sender) {
652 commitCoordinator.handleBatchedModifications(batched, sender, this);
653 } catch (Exception e) {
654 LOG.error("{}: Error handling BatchedModifications for Tx {}", persistenceId(),
655 batched.getTransactionId(), e);
656 sender.tell(new Failure(e), getSelf());
660 private void handleBatchedModifications(final BatchedModifications batched) {
661 // This message is sent to prepare the modifications transaction directly on the Shard as an
662 // optimization to avoid the extra overhead of a separate ShardTransaction actor. On the last
663 // BatchedModifications message, the caller sets the ready flag in the message indicating
664 // modifications are complete. The reply contains the cohort actor path (this actor) for the caller
665 // to initiate the 3-phase commit. This also avoids the overhead of sending an additional
666 // ReadyTransaction message.
668 // If we're not the leader then forward to the leader. This is a safety measure - we shouldn't
669 // normally get here if we're not the leader as the front-end (TransactionProxy) should determine
670 // the primary/leader shard. However with timing and caching on the front-end, there's a small
671 // window where it could have a stale leader during leadership transitions.
673 boolean isLeaderActive = isLeaderActive();
674 if (isLeader() && isLeaderActive) {
675 handleBatchedModificationsLocal(batched, getSender());
677 ActorSelection leader = getLeader();
678 if (!isLeaderActive || leader == null) {
679 messageRetrySupport.addMessageToRetry(batched, getSender(),
680 "Could not process BatchedModifications " + batched.getTransactionId());
682 // If this is not the first batch and leadership changed in between batched messages,
683 // we need to reconstruct previous BatchedModifications from the transaction
684 // DataTreeModification, honoring the max batched modification count, and forward all the
685 // previous BatchedModifications to the new leader.
686 Collection<BatchedModifications> newModifications = commitCoordinator
687 .createForwardedBatchedModifications(batched,
688 datastoreContext.getShardBatchedModificationCount());
690 LOG.debug("{}: Forwarding {} BatchedModifications to leader {}", persistenceId(),
691 newModifications.size(), leader);
693 for (BatchedModifications bm : newModifications) {
694 leader.forward(bm, getContext());
700 private boolean failIfIsolatedLeader(final ActorRef sender) {
701 if (isIsolatedLeader()) {
702 sender.tell(new Failure(new NoShardLeaderException(String.format(
703 "Shard %s was the leader but has lost contact with all of its followers. Either all"
704 + " other follower nodes are down or this node is isolated by a network partition.",
705 persistenceId()))), getSelf());
712 protected boolean isIsolatedLeader() {
713 return getRaftState() == RaftState.IsolatedLeader;
716 @SuppressWarnings("checkstyle:IllegalCatch")
717 private void handleReadyLocalTransaction(final ReadyLocalTransaction message) {
718 LOG.debug("{}: handleReadyLocalTransaction for {}", persistenceId(), message.getTransactionId());
720 boolean isLeaderActive = isLeaderActive();
721 if (isLeader() && isLeaderActive) {
723 commitCoordinator.handleReadyLocalTransaction(message, getSender(), this);
724 } catch (Exception e) {
725 LOG.error("{}: Error handling ReadyLocalTransaction for Tx {}", persistenceId(),
726 message.getTransactionId(), e);
727 getSender().tell(new Failure(e), getSelf());
730 ActorSelection leader = getLeader();
731 if (!isLeaderActive || leader == null) {
732 messageRetrySupport.addMessageToRetry(message, getSender(),
733 "Could not process ready local transaction " + message.getTransactionId());
735 LOG.debug("{}: Forwarding ReadyLocalTransaction to leader {}", persistenceId(), leader);
736 message.setRemoteVersion(getCurrentBehavior().getLeaderPayloadVersion());
737 leader.forward(message, getContext());
742 private void handleForwardedReadyTransaction(final ForwardedReadyTransaction forwardedReady) {
743 LOG.debug("{}: handleForwardedReadyTransaction for {}", persistenceId(), forwardedReady.getTransactionId());
745 boolean isLeaderActive = isLeaderActive();
746 if (isLeader() && isLeaderActive) {
747 commitCoordinator.handleForwardedReadyTransaction(forwardedReady, getSender(), this);
749 ActorSelection leader = getLeader();
750 if (!isLeaderActive || leader == null) {
751 messageRetrySupport.addMessageToRetry(forwardedReady, getSender(),
752 "Could not process forwarded ready transaction " + forwardedReady.getTransactionId());
754 LOG.debug("{}: Forwarding ForwardedReadyTransaction to leader {}", persistenceId(), leader);
756 ReadyLocalTransaction readyLocal = new ReadyLocalTransaction(forwardedReady.getTransactionId(),
757 forwardedReady.getTransaction().getSnapshot(), forwardedReady.isDoImmediateCommit());
758 readyLocal.setRemoteVersion(getCurrentBehavior().getLeaderPayloadVersion());
759 leader.forward(readyLocal, getContext());
764 private void handleAbortTransaction(final AbortTransaction abort) {
765 doAbortTransaction(abort.getTransactionId(), getSender());
768 void doAbortTransaction(final Identifier transactionID, final ActorRef sender) {
769 commitCoordinator.handleAbort(transactionID, sender, this);
772 private void handleCreateTransaction(final Object message) {
774 createTransaction(CreateTransaction.fromSerializable(message));
775 } else if (getLeader() != null) {
776 getLeader().forward(message, getContext());
778 getSender().tell(new Failure(new NoShardLeaderException(
779 "Could not create a shard transaction", persistenceId())), getSelf());
783 private void closeTransactionChain(final CloseTransactionChain closeTransactionChain) {
784 final LocalHistoryIdentifier id = closeTransactionChain.getIdentifier();
785 store.closeTransactionChain(id, null);
786 store.purgeTransactionChain(id, null);
789 @SuppressWarnings("checkstyle:IllegalCatch")
790 private void createTransaction(final CreateTransaction createTransaction) {
792 if (TransactionType.fromInt(createTransaction.getTransactionType()) != TransactionType.READ_ONLY
793 && failIfIsolatedLeader(getSender())) {
797 ActorRef transactionActor = createTransaction(createTransaction.getTransactionType(),
798 createTransaction.getTransactionId());
800 getSender().tell(new CreateTransactionReply(Serialization.serializedActorPath(transactionActor),
801 createTransaction.getTransactionId(), createTransaction.getVersion()).toSerializable(), getSelf());
802 } catch (Exception e) {
803 getSender().tell(new Failure(e), getSelf());
807 private ActorRef createTransaction(final int transactionType, final TransactionIdentifier transactionId) {
808 LOG.debug("{}: Creating transaction : {} ", persistenceId(), transactionId);
809 return transactionActorFactory.newShardTransaction(TransactionType.fromInt(transactionType),
813 private void updateSchemaContext(final UpdateSchemaContext message) {
814 updateSchemaContext(message.getSchemaContext());
818 void updateSchemaContext(final SchemaContext schemaContext) {
819 store.updateSchemaContext(schemaContext);
822 private boolean isMetricsCaptureEnabled() {
823 CommonConfig config = new CommonConfig(getContext().system().settings().config());
824 return config.isMetricCaptureEnabled();
829 public RaftActorSnapshotCohort getRaftActorSnapshotCohort() {
830 return snapshotCohort;
835 protected RaftActorRecoveryCohort getRaftActorRecoveryCohort() {
836 if (restoreFromSnapshot == null) {
837 return ShardRecoveryCoordinator.create(store, persistenceId(), LOG);
840 return ShardRecoveryCoordinator.forSnapshot(store, persistenceId(), LOG, restoreFromSnapshot.getSnapshot());
844 protected void onRecoveryComplete() {
845 restoreFromSnapshot = null;
847 //notify shard manager
848 getContext().parent().tell(new ActorInitialized(), getSelf());
850 // Being paranoid here - this method should only be called once but just in case...
851 if (txCommitTimeoutCheckSchedule == null) {
852 // Schedule a message to be periodically sent to check if the current in-progress
853 // transaction should be expired and aborted.
854 FiniteDuration period = Duration.create(transactionCommitTimeout / 3, TimeUnit.MILLISECONDS);
855 txCommitTimeoutCheckSchedule = getContext().system().scheduler().schedule(
856 period, period, getSelf(),
857 TX_COMMIT_TIMEOUT_CHECK_MESSAGE, getContext().dispatcher(), ActorRef.noSender());
862 protected void applyState(final ActorRef clientActor, final Identifier identifier, final Object data) {
863 if (data instanceof Payload) {
865 store.applyReplicatedPayload(identifier, (Payload)data);
866 } catch (DataValidationFailedException | IOException e) {
867 LOG.error("{}: Error applying replica {}", persistenceId(), identifier, e);
870 LOG.error("{}: Unknown state for {} received {}", persistenceId(), identifier, data);
875 protected void onStateChanged() {
876 boolean isLeader = isLeader();
877 boolean hasLeader = hasLeader();
878 treeChangeSupport.onLeadershipChange(isLeader, hasLeader);
880 // If this actor is no longer the leader close all the transaction chains
882 if (LOG.isDebugEnabled()) {
884 "{}: onStateChanged: Closing all transaction chains because shard {} is no longer the leader",
885 persistenceId(), getId());
889 store.purgeLeaderState();
892 if (hasLeader && !isIsolatedLeader()) {
893 messageRetrySupport.retryMessages();
898 protected void onLeaderChanged(final String oldLeader, final String newLeader) {
899 shardMBean.incrementLeadershipChangeCount();
903 if (!knownFrontends.isEmpty()) {
904 LOG.debug("{}: removing frontend state for {}", persistenceId(), knownFrontends.keySet());
905 knownFrontends = ImmutableMap.of();
908 requestMessageAssembler.close();
911 // No leader anywhere, nothing else to do
915 // Another leader was elected. If we were the previous leader and had pending transactions, convert
916 // them to transaction messages and send to the new leader.
917 ActorSelection leader = getLeader();
918 if (leader != null) {
919 Collection<?> messagesToForward = convertPendingTransactionsToMessages();
921 if (!messagesToForward.isEmpty()) {
922 LOG.debug("{}: Forwarding {} pending transaction messages to leader {}", persistenceId(),
923 messagesToForward.size(), leader);
925 for (Object message : messagesToForward) {
926 leader.tell(message, self());
930 commitCoordinator.abortPendingTransactions("The transacton was aborted due to inflight leadership "
931 + "change and the leader address isn't available.", this);
934 // We have become the leader, we need to reconstruct frontend state
935 knownFrontends = Verify.verifyNotNull(frontendMetadata.toLeaderState(this));
936 LOG.debug("{}: became leader with frontend state for {}", persistenceId(), knownFrontends.keySet());
939 if (!isIsolatedLeader()) {
940 messageRetrySupport.retryMessages();
945 * Clears all pending transactions and converts them to messages to be forwarded to a new leader.
947 * @return the converted messages
949 public Collection<?> convertPendingTransactionsToMessages() {
950 return commitCoordinator.convertPendingTransactionsToMessages(
951 datastoreContext.getShardBatchedModificationCount());
955 protected void pauseLeader(final Runnable operation) {
956 LOG.debug("{}: In pauseLeader, operation: {}", persistenceId(), operation);
959 // Tell-based protocol can replay transaction state, so it is safe to blow it up when we are paused.
960 knownFrontends.values().forEach(LeaderFrontendState::retire);
961 knownFrontends = ImmutableMap.of();
963 store.setRunOnPendingTransactionsComplete(operation);
967 protected void unpauseLeader() {
968 LOG.debug("{}: In unpauseLeader", persistenceId());
971 store.setRunOnPendingTransactionsComplete(null);
973 // Restore tell-based protocol state as if we were becoming the leader
974 knownFrontends = Verify.verifyNotNull(frontendMetadata.toLeaderState(this));
978 protected OnDemandRaftState.AbstractBuilder<?, ?> newOnDemandRaftStateBuilder() {
979 return OnDemandShardState.newBuilder().treeChangeListenerActors(treeChangeSupport.getListenerActors())
980 .commitCohortActors(store.getCohortActors());
984 public String persistenceId() {
989 ShardCommitCoordinator getCommitCoordinator() {
990 return commitCoordinator;
993 public DatastoreContext getDatastoreContext() {
994 return datastoreContext;
998 public ShardDataTree getDataStore() {
1003 ShardStats getShardMBean() {
1007 public static Builder builder() {
1008 return new Builder();
1011 public abstract static class AbstractBuilder<T extends AbstractBuilder<T, S>, S extends Shard> {
1012 private final Class<S> shardClass;
1013 private ShardIdentifier id;
1014 private Map<String, String> peerAddresses = Collections.emptyMap();
1015 private DatastoreContext datastoreContext;
1016 private SchemaContextProvider schemaContextProvider;
1017 private DatastoreSnapshot.ShardSnapshot restoreFromSnapshot;
1018 private DataTree dataTree;
1019 private volatile boolean sealed;
1021 protected AbstractBuilder(final Class<S> shardClass) {
1022 this.shardClass = shardClass;
1025 protected void checkSealed() {
1026 Preconditions.checkState(!sealed, "Builder isalready sealed - further modifications are not allowed");
1029 @SuppressWarnings("unchecked")
1034 public T id(final ShardIdentifier newId) {
1040 public T peerAddresses(final Map<String, String> newPeerAddresses) {
1042 this.peerAddresses = newPeerAddresses;
1046 public T datastoreContext(final DatastoreContext newDatastoreContext) {
1048 this.datastoreContext = newDatastoreContext;
1052 public T schemaContextProvider(final SchemaContextProvider newSchemaContextProvider) {
1054 this.schemaContextProvider = Preconditions.checkNotNull(newSchemaContextProvider);
1058 public T restoreFromSnapshot(final DatastoreSnapshot.ShardSnapshot newRestoreFromSnapshot) {
1060 this.restoreFromSnapshot = newRestoreFromSnapshot;
1064 public T dataTree(final DataTree newDataTree) {
1066 this.dataTree = newDataTree;
1070 public ShardIdentifier getId() {
1074 public Map<String, String> getPeerAddresses() {
1075 return peerAddresses;
1078 public DatastoreContext getDatastoreContext() {
1079 return datastoreContext;
1082 public SchemaContext getSchemaContext() {
1083 return Verify.verifyNotNull(schemaContextProvider.getSchemaContext());
1086 public DatastoreSnapshot.ShardSnapshot getRestoreFromSnapshot() {
1087 return restoreFromSnapshot;
1090 public DataTree getDataTree() {
1094 public TreeType getTreeType() {
1095 switch (datastoreContext.getLogicalStoreType()) {
1097 return TreeType.CONFIGURATION;
1099 return TreeType.OPERATIONAL;
1101 throw new IllegalStateException("Unhandled logical store type "
1102 + datastoreContext.getLogicalStoreType());
1106 protected void verify() {
1107 Preconditions.checkNotNull(id, "id should not be null");
1108 Preconditions.checkNotNull(peerAddresses, "peerAddresses should not be null");
1109 Preconditions.checkNotNull(datastoreContext, "dataStoreContext should not be null");
1110 Preconditions.checkNotNull(schemaContextProvider, "schemaContextProvider should not be null");
1113 public Props props() {
1116 return Props.create(shardClass, this);
1120 public static class Builder extends AbstractBuilder<Builder, Shard> {
1127 return Ticker.systemTicker();
1130 void scheduleNextPendingTransaction() {
1131 self().tell(RESUME_NEXT_PENDING_TRANSACTION, ActorRef.noSender());