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 akka.actor.ActorRef;
11 import akka.actor.ActorSelection;
12 import akka.actor.Cancellable;
13 import akka.actor.ExtendedActorSystem;
14 import akka.actor.Props;
15 import akka.actor.Status;
16 import akka.actor.Status.Failure;
17 import akka.serialization.JavaSerializer;
18 import akka.serialization.Serialization;
19 import com.google.common.annotations.VisibleForTesting;
20 import com.google.common.base.Optional;
21 import com.google.common.base.Preconditions;
22 import com.google.common.base.Ticker;
23 import com.google.common.base.Verify;
24 import com.google.common.collect.ImmutableList;
25 import com.google.common.collect.ImmutableMap;
26 import com.google.common.collect.Range;
27 import java.io.IOException;
28 import java.util.Arrays;
29 import java.util.Collection;
30 import java.util.Collections;
32 import java.util.concurrent.TimeUnit;
33 import org.eclipse.jdt.annotation.NonNull;
34 import org.eclipse.jdt.annotation.Nullable;
35 import org.opendaylight.controller.cluster.access.ABIVersion;
36 import org.opendaylight.controller.cluster.access.commands.ConnectClientRequest;
37 import org.opendaylight.controller.cluster.access.commands.ConnectClientSuccess;
38 import org.opendaylight.controller.cluster.access.commands.LocalHistoryRequest;
39 import org.opendaylight.controller.cluster.access.commands.NotLeaderException;
40 import org.opendaylight.controller.cluster.access.commands.OutOfSequenceEnvelopeException;
41 import org.opendaylight.controller.cluster.access.commands.TransactionRequest;
42 import org.opendaylight.controller.cluster.access.concepts.ClientIdentifier;
43 import org.opendaylight.controller.cluster.access.concepts.FrontendIdentifier;
44 import org.opendaylight.controller.cluster.access.concepts.LocalHistoryIdentifier;
45 import org.opendaylight.controller.cluster.access.concepts.Request;
46 import org.opendaylight.controller.cluster.access.concepts.RequestEnvelope;
47 import org.opendaylight.controller.cluster.access.concepts.RequestException;
48 import org.opendaylight.controller.cluster.access.concepts.RequestSuccess;
49 import org.opendaylight.controller.cluster.access.concepts.RetiredGenerationException;
50 import org.opendaylight.controller.cluster.access.concepts.RuntimeRequestException;
51 import org.opendaylight.controller.cluster.access.concepts.SliceableMessage;
52 import org.opendaylight.controller.cluster.access.concepts.TransactionIdentifier;
53 import org.opendaylight.controller.cluster.access.concepts.UnsupportedRequestException;
54 import org.opendaylight.controller.cluster.common.actor.CommonConfig;
55 import org.opendaylight.controller.cluster.common.actor.Dispatchers;
56 import org.opendaylight.controller.cluster.common.actor.Dispatchers.DispatcherType;
57 import org.opendaylight.controller.cluster.common.actor.MessageTracker;
58 import org.opendaylight.controller.cluster.common.actor.MessageTracker.Error;
59 import org.opendaylight.controller.cluster.common.actor.MeteringBehavior;
60 import org.opendaylight.controller.cluster.datastore.exceptions.NoShardLeaderException;
61 import org.opendaylight.controller.cluster.datastore.identifiers.ShardIdentifier;
62 import org.opendaylight.controller.cluster.datastore.jmx.mbeans.shard.ShardDataTreeListenerInfoMXBeanImpl;
63 import org.opendaylight.controller.cluster.datastore.jmx.mbeans.shard.ShardMBeanFactory;
64 import org.opendaylight.controller.cluster.datastore.jmx.mbeans.shard.ShardStats;
65 import org.opendaylight.controller.cluster.datastore.messages.AbortTransaction;
66 import org.opendaylight.controller.cluster.datastore.messages.ActorInitialized;
67 import org.opendaylight.controller.cluster.datastore.messages.BatchedModifications;
68 import org.opendaylight.controller.cluster.datastore.messages.CanCommitTransaction;
69 import org.opendaylight.controller.cluster.datastore.messages.CloseTransactionChain;
70 import org.opendaylight.controller.cluster.datastore.messages.CommitTransaction;
71 import org.opendaylight.controller.cluster.datastore.messages.CreateTransaction;
72 import org.opendaylight.controller.cluster.datastore.messages.CreateTransactionReply;
73 import org.opendaylight.controller.cluster.datastore.messages.ForwardedReadyTransaction;
74 import org.opendaylight.controller.cluster.datastore.messages.GetShardDataTree;
75 import org.opendaylight.controller.cluster.datastore.messages.MakeLeaderLocal;
76 import org.opendaylight.controller.cluster.datastore.messages.OnDemandShardState;
77 import org.opendaylight.controller.cluster.datastore.messages.PeerAddressResolved;
78 import org.opendaylight.controller.cluster.datastore.messages.PersistAbortTransactionPayload;
79 import org.opendaylight.controller.cluster.datastore.messages.ReadyLocalTransaction;
80 import org.opendaylight.controller.cluster.datastore.messages.RegisterDataTreeChangeListener;
81 import org.opendaylight.controller.cluster.datastore.messages.ShardLeaderStateChanged;
82 import org.opendaylight.controller.cluster.datastore.messages.UpdateSchemaContext;
83 import org.opendaylight.controller.cluster.datastore.persisted.AbortTransactionPayload;
84 import org.opendaylight.controller.cluster.datastore.persisted.DatastoreSnapshot;
85 import org.opendaylight.controller.cluster.datastore.persisted.DatastoreSnapshot.ShardSnapshot;
86 import org.opendaylight.controller.cluster.datastore.persisted.PurgeTransactionPayload;
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.FiniteDuration;
113 * A Shard represents a portion of the logical data tree.
116 * Our Shard uses InMemoryDataTree as it's internal representation and delegates all requests it
118 public class Shard extends RaftActor {
121 static final Object TX_COMMIT_TIMEOUT_CHECK_MESSAGE = new Object() {
123 public String toString() {
124 return "txCommitTimeoutCheck";
129 static final Object GET_SHARD_MBEAN_MESSAGE = new Object() {
131 public String toString() {
132 return "getShardMBeanMessage";
136 static final Object RESUME_NEXT_PENDING_TRANSACTION = new Object() {
138 public String toString() {
139 return "resumeNextPendingTransaction";
143 // FIXME: shard names should be encapsulated in their own class and this should be exposed as a constant.
144 public static final String DEFAULT_NAME = "default";
146 private static final Collection<ABIVersion> SUPPORTED_ABIVERSIONS;
149 final ABIVersion[] values = ABIVersion.values();
150 final ABIVersion[] real = Arrays.copyOfRange(values, 1, values.length - 1);
151 SUPPORTED_ABIVERSIONS = ImmutableList.copyOf(real).reverse();
154 // FIXME: make this a dynamic property based on mailbox size and maximum number of clients
155 private static final int CLIENT_MAX_MESSAGES = 1000;
157 // The state of this Shard
158 private final ShardDataTree store;
160 /// The name of this shard
161 private final String name;
163 private final String shardName;
165 private final ShardStats shardMBean;
167 private final ShardDataTreeListenerInfoMXBeanImpl listenerInfoMXBean;
169 private DatastoreContext datastoreContext;
171 private final ShardCommitCoordinator commitCoordinator;
173 private long transactionCommitTimeout;
175 private Cancellable txCommitTimeoutCheckSchedule;
177 private final Optional<ActorRef> roleChangeNotifier;
179 private final MessageTracker appendEntriesReplyTracker;
181 private final ShardTransactionActorFactory transactionActorFactory;
183 private final ShardSnapshotCohort snapshotCohort;
185 private final DataTreeChangeListenerSupport treeChangeSupport = new DataTreeChangeListenerSupport(this);
187 private ShardSnapshot restoreFromSnapshot;
189 private final ShardTransactionMessageRetrySupport messageRetrySupport;
191 private final FrontendMetadata frontendMetadata;
192 private Map<FrontendIdentifier, LeaderFrontendState> knownFrontends = ImmutableMap.of();
193 private boolean paused;
195 private final MessageSlicer responseMessageSlicer;
196 private final Dispatchers dispatchers;
198 private final MessageAssembler requestMessageAssembler;
200 protected Shard(final AbstractBuilder<?, ?> builder) {
201 super(builder.getId().toString(), builder.getPeerAddresses(),
202 Optional.of(builder.getDatastoreContext().getShardRaftConfig()), DataStoreVersions.CURRENT_VERSION);
204 this.name = builder.getId().toString();
205 this.shardName = builder.getId().getShardName();
206 this.datastoreContext = builder.getDatastoreContext();
207 this.restoreFromSnapshot = builder.getRestoreFromSnapshot();
208 this.frontendMetadata = new FrontendMetadata(name);
210 setPersistence(datastoreContext.isPersistent());
212 LOG.info("Shard created : {}, persistent : {}", name, datastoreContext.isPersistent());
214 ShardDataTreeChangeListenerPublisherActorProxy treeChangeListenerPublisher =
215 new ShardDataTreeChangeListenerPublisherActorProxy(getContext(), name + "-DTCL-publisher", name);
216 if (builder.getDataTree() != null) {
217 store = new ShardDataTree(this, builder.getSchemaContext(), builder.getDataTree(),
218 treeChangeListenerPublisher, name, frontendMetadata);
220 store = new ShardDataTree(this, builder.getSchemaContext(), builder.getTreeType(),
221 builder.getDatastoreContext().getStoreRoot(), treeChangeListenerPublisher, name, frontendMetadata);
224 shardMBean = ShardMBeanFactory.getShardStatsMBean(name, datastoreContext.getDataStoreMXBeanType(), this);
226 if (isMetricsCaptureEnabled()) {
227 getContext().become(new MeteringBehavior(this));
230 commitCoordinator = new ShardCommitCoordinator(store, LOG, this.name);
232 setTransactionCommitTimeout();
234 // create a notifier actor for each cluster member
235 roleChangeNotifier = createRoleChangeNotifier(name);
237 appendEntriesReplyTracker = new MessageTracker(AppendEntriesReply.class,
238 getRaftActorContext().getConfigParams().getIsolatedCheckIntervalInMillis());
240 dispatchers = new Dispatchers(context().system().dispatchers());
241 transactionActorFactory = new ShardTransactionActorFactory(store, datastoreContext,
242 dispatchers.getDispatcherPath(Dispatchers.DispatcherType.Transaction),
243 self(), getContext(), shardMBean, builder.getId().getShardName());
245 snapshotCohort = ShardSnapshotCohort.create(getContext(), builder.getId().getMemberName(), store, LOG,
248 messageRetrySupport = new ShardTransactionMessageRetrySupport(this);
250 responseMessageSlicer = MessageSlicer.builder().logContext(this.name)
251 .messageSliceSize(datastoreContext.getMaximumMessageSliceSize())
252 .fileBackedStreamFactory(getRaftActorContext().getFileBackedOutputStreamFactory())
253 .expireStateAfterInactivity(2, TimeUnit.MINUTES).build();
255 requestMessageAssembler = MessageAssembler.builder().logContext(this.name)
256 .fileBackedStreamFactory(getRaftActorContext().getFileBackedOutputStreamFactory())
257 .assembledMessageCallback((message, sender) -> self().tell(message, sender))
258 .expireStateAfterInactivity(datastoreContext.getRequestTimeout(), TimeUnit.NANOSECONDS).build();
260 listenerInfoMXBean = new ShardDataTreeListenerInfoMXBeanImpl(name, datastoreContext.getDataStoreMXBeanType(),
262 listenerInfoMXBean.register();
265 private void setTransactionCommitTimeout() {
266 transactionCommitTimeout = TimeUnit.MILLISECONDS.convert(
267 datastoreContext.getShardTransactionCommitTimeoutInSeconds(), TimeUnit.SECONDS) / 2;
270 private Optional<ActorRef> createRoleChangeNotifier(final String shardId) {
271 ActorRef shardRoleChangeNotifier = this.getContext().actorOf(
272 RoleChangeNotifier.getProps(shardId), shardId + "-notifier");
273 return Optional.of(shardRoleChangeNotifier);
277 public void postStop() {
278 LOG.info("Stopping Shard {}", persistenceId());
282 messageRetrySupport.close();
284 if (txCommitTimeoutCheckSchedule != null) {
285 txCommitTimeoutCheckSchedule.cancel();
288 commitCoordinator.abortPendingTransactions("Transaction aborted due to shutdown.", this);
290 shardMBean.unregisterMBean();
291 listenerInfoMXBean.unregister();
295 protected void handleRecover(final Object message) {
296 LOG.debug("{}: onReceiveRecover: Received message {} from {}", persistenceId(), message.getClass(),
299 super.handleRecover(message);
300 if (LOG.isTraceEnabled()) {
301 appendEntriesReplyTracker.begin();
306 protected void handleNonRaftCommand(final Object message) {
307 try (MessageTracker.Context context = appendEntriesReplyTracker.received(message)) {
308 final Optional<Error> maybeError = context.error();
309 if (maybeError.isPresent()) {
310 LOG.trace("{} : AppendEntriesReply failed to arrive at the expected interval {}", persistenceId(),
314 store.resetTransactionBatch();
316 if (message instanceof RequestEnvelope) {
317 handleRequestEnvelope((RequestEnvelope)message);
318 } else if (MessageAssembler.isHandledMessage(message)) {
319 handleRequestAssemblerMessage(message);
320 } else if (message instanceof ConnectClientRequest) {
321 handleConnectClient((ConnectClientRequest)message);
322 } else if (CreateTransaction.isSerializedType(message)) {
323 handleCreateTransaction(message);
324 } else if (message instanceof BatchedModifications) {
325 handleBatchedModifications((BatchedModifications)message);
326 } else if (message instanceof ForwardedReadyTransaction) {
327 handleForwardedReadyTransaction((ForwardedReadyTransaction) message);
328 } else if (message instanceof ReadyLocalTransaction) {
329 handleReadyLocalTransaction((ReadyLocalTransaction)message);
330 } else if (CanCommitTransaction.isSerializedType(message)) {
331 handleCanCommitTransaction(CanCommitTransaction.fromSerializable(message));
332 } else if (CommitTransaction.isSerializedType(message)) {
333 handleCommitTransaction(CommitTransaction.fromSerializable(message));
334 } else if (AbortTransaction.isSerializedType(message)) {
335 handleAbortTransaction(AbortTransaction.fromSerializable(message));
336 } else if (CloseTransactionChain.isSerializedType(message)) {
337 closeTransactionChain(CloseTransactionChain.fromSerializable(message));
338 } else if (message instanceof RegisterDataTreeChangeListener) {
339 treeChangeSupport.onMessage((RegisterDataTreeChangeListener) message, isLeader(), hasLeader());
340 } else if (message instanceof UpdateSchemaContext) {
341 updateSchemaContext((UpdateSchemaContext) message);
342 } else if (message instanceof PeerAddressResolved) {
343 PeerAddressResolved resolved = (PeerAddressResolved) message;
344 setPeerAddress(resolved.getPeerId(), resolved.getPeerAddress());
345 } else if (TX_COMMIT_TIMEOUT_CHECK_MESSAGE.equals(message)) {
346 commitTimeoutCheck();
347 } else if (message instanceof DatastoreContext) {
348 onDatastoreContext((DatastoreContext)message);
349 } else if (message instanceof RegisterRoleChangeListener) {
350 roleChangeNotifier.get().forward(message, context());
351 } else if (message instanceof FollowerInitialSyncUpStatus) {
352 shardMBean.setFollowerInitialSyncStatus(((FollowerInitialSyncUpStatus) message).isInitialSyncDone());
353 context().parent().tell(message, self());
354 } else if (GET_SHARD_MBEAN_MESSAGE.equals(message)) {
355 sender().tell(getShardMBean(), self());
356 } else if (message instanceof GetShardDataTree) {
357 sender().tell(store.getDataTree(), self());
358 } else if (message instanceof ServerRemoved) {
359 context().parent().forward(message, context());
360 } else if (ShardTransactionMessageRetrySupport.TIMER_MESSAGE_CLASS.isInstance(message)) {
361 messageRetrySupport.onTimerMessage(message);
362 } else if (message instanceof DataTreeCohortActorRegistry.CohortRegistryCommand) {
363 store.processCohortRegistryCommand(getSender(),
364 (DataTreeCohortActorRegistry.CohortRegistryCommand) message);
365 } else if (message instanceof PersistAbortTransactionPayload) {
366 final TransactionIdentifier txId = ((PersistAbortTransactionPayload) message).getTransactionId();
367 persistPayload(txId, AbortTransactionPayload.create(txId,
368 datastoreContext.getInitialPayloadSerializedBufferCapacity()), true);
369 persistPayload(txId, PurgeTransactionPayload.create(txId,
370 datastoreContext.getInitialPayloadSerializedBufferCapacity()), false);
371 } else if (message instanceof MakeLeaderLocal) {
373 } else if (RESUME_NEXT_PENDING_TRANSACTION.equals(message)) {
374 store.resumeNextPendingTransaction();
375 } else if (!responseMessageSlicer.handleMessage(message)) {
376 super.handleNonRaftCommand(message);
381 private void handleRequestAssemblerMessage(final Object message) {
382 dispatchers.getDispatcher(DispatcherType.Serialization).execute(() -> {
383 JavaSerializer.currentSystem().value_$eq((ExtendedActorSystem) context().system());
384 requestMessageAssembler.handleMessage(message, self());
388 @SuppressWarnings("checkstyle:IllegalCatch")
389 private void handleRequestEnvelope(final RequestEnvelope envelope) {
390 final long now = ticker().read();
392 final RequestSuccess<?, ?> success = handleRequest(envelope, now);
393 if (success != null) {
394 final long executionTimeNanos = ticker().read() - now;
395 if (success instanceof SliceableMessage) {
396 dispatchers.getDispatcher(DispatcherType.Serialization).execute(() ->
397 responseMessageSlicer.slice(SliceOptions.builder().identifier(success.getTarget())
398 .message(envelope.newSuccessEnvelope(success, executionTimeNanos))
399 .sendTo(envelope.getMessage().getReplyTo()).replyTo(self())
400 .onFailureCallback(t -> LOG.warn("Error slicing response {}", success, t)).build()));
402 envelope.sendSuccess(success, executionTimeNanos);
405 } catch (RequestException e) {
406 LOG.debug("{}: request {} failed", persistenceId(), envelope, e);
407 envelope.sendFailure(e, ticker().read() - now);
408 } catch (Exception e) {
409 LOG.debug("{}: request {} caused failure", persistenceId(), envelope, e);
410 envelope.sendFailure(new RuntimeRequestException("Request failed to process", e),
411 ticker().read() - now);
415 private void commitTimeoutCheck() {
416 store.checkForExpiredTransactions(transactionCommitTimeout, this::updateAccess);
417 commitCoordinator.checkForExpiredTransactions(transactionCommitTimeout, this);
418 requestMessageAssembler.checkExpiredAssembledMessageState();
421 private Optional<Long> updateAccess(final SimpleShardDataTreeCohort cohort) {
422 final FrontendIdentifier frontend = cohort.getIdentifier().getHistoryId().getClientId().getFrontendId();
423 final LeaderFrontendState state = knownFrontends.get(frontend);
425 // Not tell-based protocol, do nothing
426 return Optional.absent();
429 if (isIsolatedLeader()) {
430 // We are isolated and no new request can come through until we emerge from it. We are still updating
431 // liveness of frontend when we see it attempting to communicate. Use the last access timer.
432 return Optional.of(state.getLastSeenTicks());
435 // If this frontend has freshly connected, give it some time to catch up before killing its transactions.
436 return Optional.of(state.getLastConnectTicks());
439 private void onMakeLeaderLocal() {
440 LOG.debug("{}: onMakeLeaderLocal received", persistenceId());
442 getSender().tell(new Status.Success(null), getSelf());
446 final ActorSelection leader = getLeader();
448 if (leader == null) {
449 // Leader is not present. The cluster is most likely trying to
450 // elect a leader and we should let that run its normal course
452 // TODO we can wait for the election to complete and retry the
453 // request. We can also let the caller retry by sending a flag
454 // in the response indicating the request is "reTryable".
455 getSender().tell(new Failure(
456 new LeadershipTransferFailedException("We cannot initiate leadership transfer to local node. "
457 + "Currently there is no leader for " + persistenceId())),
462 leader.tell(new RequestLeadership(getId(), getSender()), getSelf());
465 // Acquire our frontend tracking handle and verify generation matches
466 private @Nullable LeaderFrontendState findFrontend(final ClientIdentifier clientId) throws RequestException {
467 final LeaderFrontendState existing = knownFrontends.get(clientId.getFrontendId());
468 if (existing != null) {
469 final int cmp = Long.compareUnsigned(existing.getIdentifier().getGeneration(), clientId.getGeneration());
475 LOG.debug("{}: rejecting request from outdated client {}", persistenceId(), clientId);
476 throw new RetiredGenerationException(clientId.getGeneration(),
477 existing.getIdentifier().getGeneration());
480 LOG.info("{}: retiring state {}, outdated by request from client {}", persistenceId(), existing, clientId);
482 knownFrontends.remove(clientId.getFrontendId());
484 LOG.debug("{}: client {} is not yet known", persistenceId(), clientId);
490 private LeaderFrontendState getFrontend(final ClientIdentifier clientId) throws RequestException {
491 final LeaderFrontendState ret = findFrontend(clientId);
496 // TODO: a dedicated exception would be better, but this is technically true, too
497 throw new OutOfSequenceEnvelopeException(0);
500 private static @NonNull ABIVersion selectVersion(final ConnectClientRequest message) {
501 final Range<ABIVersion> clientRange = Range.closed(message.getMinVersion(), message.getMaxVersion());
502 for (ABIVersion v : SUPPORTED_ABIVERSIONS) {
503 if (clientRange.contains(v)) {
508 throw new IllegalArgumentException(String.format(
509 "No common version between backend versions %s and client versions %s", SUPPORTED_ABIVERSIONS,
513 @SuppressWarnings("checkstyle:IllegalCatch")
514 private void handleConnectClient(final ConnectClientRequest message) {
516 final ClientIdentifier clientId = message.getTarget();
517 final LeaderFrontendState existing = findFrontend(clientId);
518 if (existing != null) {
522 if (!isLeader() || !isLeaderActive()) {
523 LOG.info("{}: not currently leader, rejecting request {}. isLeader: {}, isLeaderActive: {},"
524 + "isLeadershipTransferInProgress: {}.",
525 persistenceId(), message, isLeader(), isLeaderActive(), isLeadershipTransferInProgress());
526 throw new NotLeaderException(getSelf());
529 final ABIVersion selectedVersion = selectVersion(message);
530 final LeaderFrontendState frontend;
531 if (existing == null) {
532 frontend = new LeaderFrontendState(persistenceId(), clientId, store);
533 knownFrontends.put(clientId.getFrontendId(), frontend);
534 LOG.debug("{}: created state {} for client {}", persistenceId(), frontend, clientId);
539 frontend.reconnect();
540 message.getReplyTo().tell(new ConnectClientSuccess(message.getTarget(), message.getSequence(), getSelf(),
541 ImmutableList.of(), store.getDataTree(), CLIENT_MAX_MESSAGES).toVersion(selectedVersion),
542 ActorRef.noSender());
543 } catch (RequestException | RuntimeException e) {
544 message.getReplyTo().tell(new Failure(e), ActorRef.noSender());
548 private @Nullable RequestSuccess<?, ?> handleRequest(final RequestEnvelope envelope, final long now)
549 throws RequestException {
550 // We are not the leader, hence we want to fail-fast.
551 if (!isLeader() || paused || !isLeaderActive()) {
552 LOG.debug("{}: not currently active leader, rejecting request {}. isLeader: {}, isLeaderActive: {},"
553 + "isLeadershipTransferInProgress: {}, paused: {}",
554 persistenceId(), envelope, isLeader(), isLeaderActive(), isLeadershipTransferInProgress(), paused);
555 throw new NotLeaderException(getSelf());
558 final Request<?, ?> request = envelope.getMessage();
559 if (request instanceof TransactionRequest) {
560 final TransactionRequest<?> txReq = (TransactionRequest<?>)request;
561 final ClientIdentifier clientId = txReq.getTarget().getHistoryId().getClientId();
562 return getFrontend(clientId).handleTransactionRequest(txReq, envelope, now);
563 } else if (request instanceof LocalHistoryRequest) {
564 final LocalHistoryRequest<?> lhReq = (LocalHistoryRequest<?>)request;
565 final ClientIdentifier clientId = lhReq.getTarget().getClientId();
566 return getFrontend(clientId).handleLocalHistoryRequest(lhReq, envelope, now);
568 LOG.warn("{}: rejecting unsupported request {}", persistenceId(), request);
569 throw new UnsupportedRequestException(request);
573 private boolean hasLeader() {
574 return getLeaderId() != null;
577 public int getPendingTxCommitQueueSize() {
578 return store.getQueueSize();
581 public int getCohortCacheSize() {
582 return commitCoordinator.getCohortCacheSize();
586 protected Optional<ActorRef> getRoleChangeNotifier() {
587 return roleChangeNotifier;
590 String getShardName() {
595 protected LeaderStateChanged newLeaderStateChanged(final String memberId, final String leaderId,
596 final short leaderPayloadVersion) {
597 return isLeader() ? new ShardLeaderStateChanged(memberId, leaderId, store.getDataTree(), leaderPayloadVersion)
598 : new ShardLeaderStateChanged(memberId, leaderId, leaderPayloadVersion);
601 protected void onDatastoreContext(final DatastoreContext context) {
602 datastoreContext = context;
604 setTransactionCommitTimeout();
606 setPersistence(datastoreContext.isPersistent());
608 updateConfigParams(datastoreContext.getShardRaftConfig());
611 // applyState() will be invoked once consensus is reached on the payload
612 void persistPayload(final Identifier id, final Payload payload, final boolean batchHint) {
613 boolean canSkipPayload = !hasFollowers() && !persistence().isRecoveryApplicable();
614 if (canSkipPayload) {
615 applyState(self(), id, payload);
617 // We are faking the sender
618 persistData(self(), id, payload, batchHint);
622 private void handleCommitTransaction(final CommitTransaction commit) {
624 commitCoordinator.handleCommit(commit.getTransactionId(), getSender(), this);
626 ActorSelection leader = getLeader();
627 if (leader == null) {
628 messageRetrySupport.addMessageToRetry(commit, getSender(),
629 "Could not commit transaction " + commit.getTransactionId());
631 LOG.debug("{}: Forwarding CommitTransaction to leader {}", persistenceId(), leader);
632 leader.forward(commit, getContext());
637 private void handleCanCommitTransaction(final CanCommitTransaction canCommit) {
638 LOG.debug("{}: Can committing transaction {}", persistenceId(), canCommit.getTransactionId());
641 commitCoordinator.handleCanCommit(canCommit.getTransactionId(), getSender(), this);
643 ActorSelection leader = getLeader();
644 if (leader == null) {
645 messageRetrySupport.addMessageToRetry(canCommit, getSender(),
646 "Could not canCommit transaction " + canCommit.getTransactionId());
648 LOG.debug("{}: Forwarding CanCommitTransaction to leader {}", persistenceId(), leader);
649 leader.forward(canCommit, getContext());
654 @SuppressWarnings("checkstyle:IllegalCatch")
655 protected void handleBatchedModificationsLocal(final BatchedModifications batched, final ActorRef sender) {
657 commitCoordinator.handleBatchedModifications(batched, sender, this);
658 } catch (Exception e) {
659 LOG.error("{}: Error handling BatchedModifications for Tx {}", persistenceId(),
660 batched.getTransactionId(), e);
661 sender.tell(new Failure(e), getSelf());
665 private void handleBatchedModifications(final BatchedModifications batched) {
666 // This message is sent to prepare the modifications transaction directly on the Shard as an
667 // optimization to avoid the extra overhead of a separate ShardTransaction actor. On the last
668 // BatchedModifications message, the caller sets the ready flag in the message indicating
669 // modifications are complete. The reply contains the cohort actor path (this actor) for the caller
670 // to initiate the 3-phase commit. This also avoids the overhead of sending an additional
671 // ReadyTransaction message.
673 // If we're not the leader then forward to the leader. This is a safety measure - we shouldn't
674 // normally get here if we're not the leader as the front-end (TransactionProxy) should determine
675 // the primary/leader shard. However with timing and caching on the front-end, there's a small
676 // window where it could have a stale leader during leadership transitions.
678 boolean isLeaderActive = isLeaderActive();
679 if (isLeader() && isLeaderActive) {
680 handleBatchedModificationsLocal(batched, getSender());
682 ActorSelection leader = getLeader();
683 if (!isLeaderActive || leader == null) {
684 messageRetrySupport.addMessageToRetry(batched, getSender(),
685 "Could not process BatchedModifications " + batched.getTransactionId());
687 // If this is not the first batch and leadership changed in between batched messages,
688 // we need to reconstruct previous BatchedModifications from the transaction
689 // DataTreeModification, honoring the max batched modification count, and forward all the
690 // previous BatchedModifications to the new leader.
691 Collection<BatchedModifications> newModifications = commitCoordinator
692 .createForwardedBatchedModifications(batched,
693 datastoreContext.getShardBatchedModificationCount());
695 LOG.debug("{}: Forwarding {} BatchedModifications to leader {}", persistenceId(),
696 newModifications.size(), leader);
698 for (BatchedModifications bm : newModifications) {
699 leader.forward(bm, getContext());
705 private boolean failIfIsolatedLeader(final ActorRef sender) {
706 if (isIsolatedLeader()) {
707 sender.tell(new Failure(new NoShardLeaderException(String.format(
708 "Shard %s was the leader but has lost contact with all of its followers. Either all"
709 + " other follower nodes are down or this node is isolated by a network partition.",
710 persistenceId()))), getSelf());
717 protected boolean isIsolatedLeader() {
718 return getRaftState() == RaftState.IsolatedLeader;
721 @SuppressWarnings("checkstyle:IllegalCatch")
722 private void handleReadyLocalTransaction(final ReadyLocalTransaction message) {
723 LOG.debug("{}: handleReadyLocalTransaction for {}", persistenceId(), message.getTransactionId());
725 boolean isLeaderActive = isLeaderActive();
726 if (isLeader() && isLeaderActive) {
728 commitCoordinator.handleReadyLocalTransaction(message, getSender(), this);
729 } catch (Exception e) {
730 LOG.error("{}: Error handling ReadyLocalTransaction for Tx {}", persistenceId(),
731 message.getTransactionId(), e);
732 getSender().tell(new Failure(e), getSelf());
735 ActorSelection leader = getLeader();
736 if (!isLeaderActive || leader == null) {
737 messageRetrySupport.addMessageToRetry(message, getSender(),
738 "Could not process ready local transaction " + message.getTransactionId());
740 LOG.debug("{}: Forwarding ReadyLocalTransaction to leader {}", persistenceId(), leader);
741 message.setRemoteVersion(getCurrentBehavior().getLeaderPayloadVersion());
742 leader.forward(message, getContext());
747 private void handleForwardedReadyTransaction(final ForwardedReadyTransaction forwardedReady) {
748 LOG.debug("{}: handleForwardedReadyTransaction for {}", persistenceId(), forwardedReady.getTransactionId());
750 boolean isLeaderActive = isLeaderActive();
751 if (isLeader() && isLeaderActive) {
752 commitCoordinator.handleForwardedReadyTransaction(forwardedReady, getSender(), this);
754 ActorSelection leader = getLeader();
755 if (!isLeaderActive || leader == null) {
756 messageRetrySupport.addMessageToRetry(forwardedReady, getSender(),
757 "Could not process forwarded ready transaction " + forwardedReady.getTransactionId());
759 LOG.debug("{}: Forwarding ForwardedReadyTransaction to leader {}", persistenceId(), leader);
761 ReadyLocalTransaction readyLocal = new ReadyLocalTransaction(forwardedReady.getTransactionId(),
762 forwardedReady.getTransaction().getSnapshot(), forwardedReady.isDoImmediateCommit(),
763 forwardedReady.getParticipatingShardNames());
764 readyLocal.setRemoteVersion(getCurrentBehavior().getLeaderPayloadVersion());
765 leader.forward(readyLocal, getContext());
770 private void handleAbortTransaction(final AbortTransaction abort) {
771 doAbortTransaction(abort.getTransactionId(), getSender());
774 void doAbortTransaction(final Identifier transactionID, final ActorRef sender) {
775 commitCoordinator.handleAbort(transactionID, sender, this);
778 private void handleCreateTransaction(final Object message) {
780 createTransaction(CreateTransaction.fromSerializable(message));
781 } else if (getLeader() != null) {
782 getLeader().forward(message, getContext());
784 getSender().tell(new Failure(new NoShardLeaderException(
785 "Could not create a shard transaction", persistenceId())), getSelf());
789 private void closeTransactionChain(final CloseTransactionChain closeTransactionChain) {
791 final LocalHistoryIdentifier id = closeTransactionChain.getIdentifier();
792 // FIXME: CONTROLLER-1628: stage purge once no transactions are present
793 store.closeTransactionChain(id, null);
794 store.purgeTransactionChain(id, null);
795 } else if (getLeader() != null) {
796 getLeader().forward(closeTransactionChain, getContext());
798 LOG.warn("{}: Could not close transaction {}", persistenceId(), closeTransactionChain.getIdentifier());
802 @SuppressWarnings("checkstyle:IllegalCatch")
803 private void createTransaction(final CreateTransaction createTransaction) {
805 if (TransactionType.fromInt(createTransaction.getTransactionType()) != TransactionType.READ_ONLY
806 && failIfIsolatedLeader(getSender())) {
810 ActorRef transactionActor = createTransaction(createTransaction.getTransactionType(),
811 createTransaction.getTransactionId());
813 getSender().tell(new CreateTransactionReply(Serialization.serializedActorPath(transactionActor),
814 createTransaction.getTransactionId(), createTransaction.getVersion()).toSerializable(), getSelf());
815 } catch (Exception e) {
816 getSender().tell(new Failure(e), getSelf());
820 private ActorRef createTransaction(final int transactionType, final TransactionIdentifier transactionId) {
821 LOG.debug("{}: Creating transaction : {} ", persistenceId(), transactionId);
822 return transactionActorFactory.newShardTransaction(TransactionType.fromInt(transactionType),
826 private void updateSchemaContext(final UpdateSchemaContext message) {
827 updateSchemaContext(message.getSchemaContext());
831 void updateSchemaContext(final SchemaContext schemaContext) {
832 store.updateSchemaContext(schemaContext);
835 private boolean isMetricsCaptureEnabled() {
836 CommonConfig config = new CommonConfig(getContext().system().settings().config());
837 return config.isMetricCaptureEnabled();
842 public RaftActorSnapshotCohort getRaftActorSnapshotCohort() {
843 return snapshotCohort;
847 protected RaftActorRecoveryCohort getRaftActorRecoveryCohort() {
848 if (restoreFromSnapshot == null) {
849 return ShardRecoveryCoordinator.create(store, persistenceId(), LOG);
852 return ShardRecoveryCoordinator.forSnapshot(store, persistenceId(), LOG, restoreFromSnapshot.getSnapshot());
856 protected void onRecoveryComplete() {
857 restoreFromSnapshot = null;
859 //notify shard manager
860 getContext().parent().tell(new ActorInitialized(), getSelf());
862 // Being paranoid here - this method should only be called once but just in case...
863 if (txCommitTimeoutCheckSchedule == null) {
864 // Schedule a message to be periodically sent to check if the current in-progress
865 // transaction should be expired and aborted.
866 FiniteDuration period = FiniteDuration.create(transactionCommitTimeout / 3, TimeUnit.MILLISECONDS);
867 txCommitTimeoutCheckSchedule = getContext().system().scheduler().schedule(
868 period, period, getSelf(),
869 TX_COMMIT_TIMEOUT_CHECK_MESSAGE, getContext().dispatcher(), ActorRef.noSender());
874 protected void applyState(final ActorRef clientActor, final Identifier identifier, final Object data) {
875 if (data instanceof Payload) {
877 store.applyReplicatedPayload(identifier, (Payload)data);
878 } catch (DataValidationFailedException | IOException e) {
879 LOG.error("{}: Error applying replica {}", persistenceId(), identifier, e);
882 LOG.error("{}: Unknown state for {} received {}", persistenceId(), identifier, data);
887 protected void onStateChanged() {
888 boolean isLeader = isLeader();
889 boolean hasLeader = hasLeader();
890 treeChangeSupport.onLeadershipChange(isLeader, hasLeader);
892 // If this actor is no longer the leader close all the transaction chains
894 if (LOG.isDebugEnabled()) {
896 "{}: onStateChanged: Closing all transaction chains because shard {} is no longer the leader",
897 persistenceId(), getId());
901 store.purgeLeaderState();
904 if (hasLeader && !isIsolatedLeader()) {
905 messageRetrySupport.retryMessages();
910 protected void onLeaderChanged(final String oldLeader, final String newLeader) {
911 shardMBean.incrementLeadershipChangeCount();
915 if (!knownFrontends.isEmpty()) {
916 LOG.debug("{}: removing frontend state for {}", persistenceId(), knownFrontends.keySet());
917 knownFrontends = ImmutableMap.of();
920 requestMessageAssembler.close();
923 // No leader anywhere, nothing else to do
927 // Another leader was elected. If we were the previous leader and had pending transactions, convert
928 // them to transaction messages and send to the new leader.
929 ActorSelection leader = getLeader();
930 if (leader != null) {
931 Collection<?> messagesToForward = convertPendingTransactionsToMessages();
933 if (!messagesToForward.isEmpty()) {
934 LOG.debug("{}: Forwarding {} pending transaction messages to leader {}", persistenceId(),
935 messagesToForward.size(), leader);
937 for (Object message : messagesToForward) {
938 LOG.debug("{}: Forwarding pending transaction message {}", persistenceId(), message);
940 leader.tell(message, self());
944 commitCoordinator.abortPendingTransactions("The transacton was aborted due to inflight leadership "
945 + "change and the leader address isn't available.", this);
948 // We have become the leader, we need to reconstruct frontend state
949 knownFrontends = Verify.verifyNotNull(frontendMetadata.toLeaderState(this));
950 LOG.debug("{}: became leader with frontend state for {}", persistenceId(), knownFrontends.keySet());
953 if (!isIsolatedLeader()) {
954 messageRetrySupport.retryMessages();
959 * Clears all pending transactions and converts them to messages to be forwarded to a new leader.
961 * @return the converted messages
963 public Collection<?> convertPendingTransactionsToMessages() {
964 return commitCoordinator.convertPendingTransactionsToMessages(
965 datastoreContext.getShardBatchedModificationCount());
969 protected void pauseLeader(final Runnable operation) {
970 LOG.debug("{}: In pauseLeader, operation: {}", persistenceId(), operation);
973 // Tell-based protocol can replay transaction state, so it is safe to blow it up when we are paused.
974 knownFrontends.values().forEach(LeaderFrontendState::retire);
975 knownFrontends = ImmutableMap.of();
977 store.setRunOnPendingTransactionsComplete(operation);
981 protected void unpauseLeader() {
982 LOG.debug("{}: In unpauseLeader", persistenceId());
985 store.setRunOnPendingTransactionsComplete(null);
987 // Restore tell-based protocol state as if we were becoming the leader
988 knownFrontends = Verify.verifyNotNull(frontendMetadata.toLeaderState(this));
992 protected OnDemandRaftState.AbstractBuilder<?, ?> newOnDemandRaftStateBuilder() {
993 return OnDemandShardState.newBuilder().treeChangeListenerActors(treeChangeSupport.getListenerActors())
994 .commitCohortActors(store.getCohortActors());
998 public String persistenceId() {
1003 ShardCommitCoordinator getCommitCoordinator() {
1004 return commitCoordinator;
1007 public DatastoreContext getDatastoreContext() {
1008 return datastoreContext;
1012 public ShardDataTree getDataStore() {
1017 ShardStats getShardMBean() {
1021 public static Builder builder() {
1022 return new Builder();
1025 public abstract static class AbstractBuilder<T extends AbstractBuilder<T, S>, S extends Shard> {
1026 private final Class<S> shardClass;
1027 private ShardIdentifier id;
1028 private Map<String, String> peerAddresses = Collections.emptyMap();
1029 private DatastoreContext datastoreContext;
1030 private SchemaContextProvider schemaContextProvider;
1031 private DatastoreSnapshot.ShardSnapshot restoreFromSnapshot;
1032 private DataTree dataTree;
1033 private volatile boolean sealed;
1035 protected AbstractBuilder(final Class<S> shardClass) {
1036 this.shardClass = shardClass;
1039 protected void checkSealed() {
1040 Preconditions.checkState(!sealed, "Builder isalready sealed - further modifications are not allowed");
1043 @SuppressWarnings("unchecked")
1048 public T id(final ShardIdentifier newId) {
1054 public T peerAddresses(final Map<String, String> newPeerAddresses) {
1056 this.peerAddresses = newPeerAddresses;
1060 public T datastoreContext(final DatastoreContext newDatastoreContext) {
1062 this.datastoreContext = newDatastoreContext;
1066 public T schemaContextProvider(final SchemaContextProvider newSchemaContextProvider) {
1068 this.schemaContextProvider = Preconditions.checkNotNull(newSchemaContextProvider);
1072 public T restoreFromSnapshot(final DatastoreSnapshot.ShardSnapshot newRestoreFromSnapshot) {
1074 this.restoreFromSnapshot = newRestoreFromSnapshot;
1078 public T dataTree(final DataTree newDataTree) {
1080 this.dataTree = newDataTree;
1084 public ShardIdentifier getId() {
1088 public Map<String, String> getPeerAddresses() {
1089 return peerAddresses;
1092 public DatastoreContext getDatastoreContext() {
1093 return datastoreContext;
1096 public SchemaContext getSchemaContext() {
1097 return Verify.verifyNotNull(schemaContextProvider.getSchemaContext());
1100 public DatastoreSnapshot.ShardSnapshot getRestoreFromSnapshot() {
1101 return restoreFromSnapshot;
1104 public DataTree getDataTree() {
1108 public TreeType getTreeType() {
1109 switch (datastoreContext.getLogicalStoreType()) {
1111 return TreeType.CONFIGURATION;
1113 return TreeType.OPERATIONAL;
1115 throw new IllegalStateException("Unhandled logical store type "
1116 + datastoreContext.getLogicalStoreType());
1120 protected void verify() {
1121 Preconditions.checkNotNull(id, "id should not be null");
1122 Preconditions.checkNotNull(peerAddresses, "peerAddresses should not be null");
1123 Preconditions.checkNotNull(datastoreContext, "dataStoreContext should not be null");
1124 Preconditions.checkNotNull(schemaContextProvider, "schemaContextProvider should not be null");
1127 public Props props() {
1130 return Props.create(shardClass, this);
1134 public static class Builder extends AbstractBuilder<Builder, Shard> {
1141 return Ticker.systemTicker();
1144 void scheduleNextPendingTransaction() {
1145 self().tell(RESUME_NEXT_PENDING_TRANSACTION, ActorRef.noSender());