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 String shardName;
166 private final ShardStats shardMBean;
168 private final ShardDataTreeListenerInfoMXBeanImpl listenerInfoMXBean;
170 private DatastoreContext datastoreContext;
172 private final ShardCommitCoordinator commitCoordinator;
174 private long transactionCommitTimeout;
176 private Cancellable txCommitTimeoutCheckSchedule;
178 private final Optional<ActorRef> roleChangeNotifier;
180 private final MessageTracker appendEntriesReplyTracker;
182 private final ShardTransactionActorFactory transactionActorFactory;
184 private final ShardSnapshotCohort snapshotCohort;
186 private final DataTreeChangeListenerSupport treeChangeSupport = new DataTreeChangeListenerSupport(this);
188 private ShardSnapshot restoreFromSnapshot;
190 private final ShardTransactionMessageRetrySupport messageRetrySupport;
192 private final FrontendMetadata frontendMetadata;
193 private Map<FrontendIdentifier, LeaderFrontendState> knownFrontends = ImmutableMap.of();
194 private boolean paused;
196 private final MessageSlicer responseMessageSlicer;
197 private final Dispatchers dispatchers;
199 private final MessageAssembler requestMessageAssembler;
201 protected Shard(final AbstractBuilder<?, ?> builder) {
202 super(builder.getId().toString(), builder.getPeerAddresses(),
203 Optional.of(builder.getDatastoreContext().getShardRaftConfig()), DataStoreVersions.CURRENT_VERSION);
205 this.name = builder.getId().toString();
206 this.shardName = builder.getId().getShardName();
207 this.datastoreContext = builder.getDatastoreContext();
208 this.restoreFromSnapshot = builder.getRestoreFromSnapshot();
209 this.frontendMetadata = new FrontendMetadata(name);
211 setPersistence(datastoreContext.isPersistent());
213 LOG.info("Shard created : {}, persistent : {}", name, datastoreContext.isPersistent());
215 ShardDataTreeChangeListenerPublisherActorProxy treeChangeListenerPublisher =
216 new ShardDataTreeChangeListenerPublisherActorProxy(getContext(), name + "-DTCL-publisher", name);
217 if (builder.getDataTree() != null) {
218 store = new ShardDataTree(this, builder.getSchemaContext(), builder.getDataTree(),
219 treeChangeListenerPublisher, name, frontendMetadata);
221 store = new ShardDataTree(this, builder.getSchemaContext(), builder.getTreeType(),
222 builder.getDatastoreContext().getStoreRoot(), treeChangeListenerPublisher, name, frontendMetadata);
225 shardMBean = ShardMBeanFactory.getShardStatsMBean(name, datastoreContext.getDataStoreMXBeanType(), this);
227 if (isMetricsCaptureEnabled()) {
228 getContext().become(new MeteringBehavior(this));
231 commitCoordinator = new ShardCommitCoordinator(store, LOG, this.name);
233 setTransactionCommitTimeout();
235 // create a notifier actor for each cluster member
236 roleChangeNotifier = createRoleChangeNotifier(name);
238 appendEntriesReplyTracker = new MessageTracker(AppendEntriesReply.class,
239 getRaftActorContext().getConfigParams().getIsolatedCheckIntervalInMillis());
241 dispatchers = new Dispatchers(context().system().dispatchers());
242 transactionActorFactory = new ShardTransactionActorFactory(store, datastoreContext,
243 dispatchers.getDispatcherPath(Dispatchers.DispatcherType.Transaction),
244 self(), getContext(), shardMBean, builder.getId().getShardName());
246 snapshotCohort = ShardSnapshotCohort.create(getContext(), builder.getId().getMemberName(), store, LOG,
249 messageRetrySupport = new ShardTransactionMessageRetrySupport(this);
251 responseMessageSlicer = MessageSlicer.builder().logContext(this.name)
252 .messageSliceSize(datastoreContext.getMaximumMessageSliceSize())
253 .fileBackedStreamFactory(getRaftActorContext().getFileBackedOutputStreamFactory())
254 .expireStateAfterInactivity(2, TimeUnit.MINUTES).build();
256 requestMessageAssembler = MessageAssembler.builder().logContext(this.name)
257 .fileBackedStreamFactory(getRaftActorContext().getFileBackedOutputStreamFactory())
258 .assembledMessageCallback((message, sender) -> self().tell(message, sender))
259 .expireStateAfterInactivity(datastoreContext.getRequestTimeout(), TimeUnit.NANOSECONDS).build();
261 listenerInfoMXBean = new ShardDataTreeListenerInfoMXBeanImpl(name, datastoreContext.getDataStoreMXBeanType(),
263 listenerInfoMXBean.register();
266 private void setTransactionCommitTimeout() {
267 transactionCommitTimeout = TimeUnit.MILLISECONDS.convert(
268 datastoreContext.getShardTransactionCommitTimeoutInSeconds(), TimeUnit.SECONDS) / 2;
271 private Optional<ActorRef> createRoleChangeNotifier(final String shardId) {
272 ActorRef shardRoleChangeNotifier = this.getContext().actorOf(
273 RoleChangeNotifier.getProps(shardId), shardId + "-notifier");
274 return Optional.of(shardRoleChangeNotifier);
278 public void postStop() {
279 LOG.info("Stopping Shard {}", persistenceId());
283 messageRetrySupport.close();
285 if (txCommitTimeoutCheckSchedule != null) {
286 txCommitTimeoutCheckSchedule.cancel();
289 commitCoordinator.abortPendingTransactions("Transaction aborted due to shutdown.", this);
291 shardMBean.unregisterMBean();
292 listenerInfoMXBean.unregister();
296 protected void handleRecover(final Object message) {
297 LOG.debug("{}: onReceiveRecover: Received message {} from {}", persistenceId(), message.getClass(),
300 super.handleRecover(message);
301 if (LOG.isTraceEnabled()) {
302 appendEntriesReplyTracker.begin();
307 protected void handleNonRaftCommand(final Object message) {
308 try (MessageTracker.Context context = appendEntriesReplyTracker.received(message)) {
309 final Optional<Error> maybeError = context.error();
310 if (maybeError.isPresent()) {
311 LOG.trace("{} : AppendEntriesReply failed to arrive at the expected interval {}", persistenceId(),
315 store.resetTransactionBatch();
317 if (message instanceof RequestEnvelope) {
318 handleRequestEnvelope((RequestEnvelope)message);
319 } else if (MessageAssembler.isHandledMessage(message)) {
320 handleRequestAssemblerMessage(message);
321 } else if (message instanceof ConnectClientRequest) {
322 handleConnectClient((ConnectClientRequest)message);
323 } else if (CreateTransaction.isSerializedType(message)) {
324 handleCreateTransaction(message);
325 } else if (message instanceof BatchedModifications) {
326 handleBatchedModifications((BatchedModifications)message);
327 } else if (message instanceof ForwardedReadyTransaction) {
328 handleForwardedReadyTransaction((ForwardedReadyTransaction) message);
329 } else if (message instanceof ReadyLocalTransaction) {
330 handleReadyLocalTransaction((ReadyLocalTransaction)message);
331 } else if (CanCommitTransaction.isSerializedType(message)) {
332 handleCanCommitTransaction(CanCommitTransaction.fromSerializable(message));
333 } else if (CommitTransaction.isSerializedType(message)) {
334 handleCommitTransaction(CommitTransaction.fromSerializable(message));
335 } else if (AbortTransaction.isSerializedType(message)) {
336 handleAbortTransaction(AbortTransaction.fromSerializable(message));
337 } else if (CloseTransactionChain.isSerializedType(message)) {
338 closeTransactionChain(CloseTransactionChain.fromSerializable(message));
339 } else if (message instanceof RegisterDataTreeChangeListener) {
340 treeChangeSupport.onMessage((RegisterDataTreeChangeListener) message, isLeader(), hasLeader());
341 } else if (message instanceof UpdateSchemaContext) {
342 updateSchemaContext((UpdateSchemaContext) message);
343 } else if (message instanceof PeerAddressResolved) {
344 PeerAddressResolved resolved = (PeerAddressResolved) message;
345 setPeerAddress(resolved.getPeerId(), resolved.getPeerAddress());
346 } else if (TX_COMMIT_TIMEOUT_CHECK_MESSAGE.equals(message)) {
347 commitTimeoutCheck();
348 } else if (message instanceof DatastoreContext) {
349 onDatastoreContext((DatastoreContext)message);
350 } else if (message instanceof RegisterRoleChangeListener) {
351 roleChangeNotifier.get().forward(message, context());
352 } else if (message instanceof FollowerInitialSyncUpStatus) {
353 shardMBean.setFollowerInitialSyncStatus(((FollowerInitialSyncUpStatus) message).isInitialSyncDone());
354 context().parent().tell(message, self());
355 } else if (GET_SHARD_MBEAN_MESSAGE.equals(message)) {
356 sender().tell(getShardMBean(), self());
357 } else if (message instanceof GetShardDataTree) {
358 sender().tell(store.getDataTree(), self());
359 } else if (message instanceof ServerRemoved) {
360 context().parent().forward(message, context());
361 } else if (ShardTransactionMessageRetrySupport.TIMER_MESSAGE_CLASS.isInstance(message)) {
362 messageRetrySupport.onTimerMessage(message);
363 } else if (message instanceof DataTreeCohortActorRegistry.CohortRegistryCommand) {
364 store.processCohortRegistryCommand(getSender(),
365 (DataTreeCohortActorRegistry.CohortRegistryCommand) message);
366 } else if (message instanceof PersistAbortTransactionPayload) {
367 final TransactionIdentifier txId = ((PersistAbortTransactionPayload) message).getTransactionId();
368 persistPayload(txId, AbortTransactionPayload.create(
369 txId, datastoreContext.getInitialPayloadSerializedBufferCapacity()), true);
370 store.purgeTransaction(txId, null);
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
467 private LeaderFrontendState findFrontend(final ClientIdentifier clientId) throws RequestException {
468 final LeaderFrontendState existing = knownFrontends.get(clientId.getFrontendId());
469 if (existing != null) {
470 final int cmp = Long.compareUnsigned(existing.getIdentifier().getGeneration(), clientId.getGeneration());
476 LOG.debug("{}: rejecting request from outdated client {}", persistenceId(), clientId);
477 throw new RetiredGenerationException(clientId.getGeneration(),
478 existing.getIdentifier().getGeneration());
481 LOG.info("{}: retiring state {}, outdated by request from client {}", persistenceId(), existing, clientId);
483 knownFrontends.remove(clientId.getFrontendId());
485 LOG.debug("{}: client {} is not yet known", persistenceId(), clientId);
491 private LeaderFrontendState getFrontend(final ClientIdentifier clientId) throws RequestException {
492 final LeaderFrontendState ret = findFrontend(clientId);
497 // TODO: a dedicated exception would be better, but this is technically true, too
498 throw new OutOfSequenceEnvelopeException(0);
502 private static ABIVersion selectVersion(final ConnectClientRequest message) {
503 final Range<ABIVersion> clientRange = Range.closed(message.getMinVersion(), message.getMaxVersion());
504 for (ABIVersion v : SUPPORTED_ABIVERSIONS) {
505 if (clientRange.contains(v)) {
510 throw new IllegalArgumentException(String.format(
511 "No common version between backend versions %s and client versions %s", SUPPORTED_ABIVERSIONS,
515 @SuppressWarnings("checkstyle:IllegalCatch")
516 private void handleConnectClient(final ConnectClientRequest message) {
518 final ClientIdentifier clientId = message.getTarget();
519 final LeaderFrontendState existing = findFrontend(clientId);
520 if (existing != null) {
524 if (!isLeader() || !isLeaderActive()) {
525 LOG.info("{}: not currently leader, rejecting request {}. isLeader: {}, isLeaderActive: {},"
526 + "isLeadershipTransferInProgress: {}.",
527 persistenceId(), message, isLeader(), isLeaderActive(), isLeadershipTransferInProgress());
528 throw new NotLeaderException(getSelf());
531 final ABIVersion selectedVersion = selectVersion(message);
532 final LeaderFrontendState frontend;
533 if (existing == null) {
534 frontend = new LeaderFrontendState(persistenceId(), clientId, store);
535 knownFrontends.put(clientId.getFrontendId(), frontend);
536 LOG.debug("{}: created state {} for client {}", persistenceId(), frontend, clientId);
541 frontend.reconnect();
542 message.getReplyTo().tell(new ConnectClientSuccess(message.getTarget(), message.getSequence(), getSelf(),
543 ImmutableList.of(), store.getDataTree(), CLIENT_MAX_MESSAGES).toVersion(selectedVersion),
544 ActorRef.noSender());
545 } catch (RequestException | RuntimeException e) {
546 message.getReplyTo().tell(new Failure(e), ActorRef.noSender());
551 private RequestSuccess<?, ?> handleRequest(final RequestEnvelope envelope, final long now)
552 throws RequestException {
553 // We are not the leader, hence we want to fail-fast.
554 if (!isLeader() || paused || !isLeaderActive()) {
555 LOG.debug("{}: not currently active leader, rejecting request {}. isLeader: {}, isLeaderActive: {},"
556 + "isLeadershipTransferInProgress: {}, paused: {}",
557 persistenceId(), envelope, isLeader(), isLeaderActive(), isLeadershipTransferInProgress(), paused);
558 throw new NotLeaderException(getSelf());
561 final Request<?, ?> request = envelope.getMessage();
562 if (request instanceof TransactionRequest) {
563 final TransactionRequest<?> txReq = (TransactionRequest<?>)request;
564 final ClientIdentifier clientId = txReq.getTarget().getHistoryId().getClientId();
565 return getFrontend(clientId).handleTransactionRequest(txReq, envelope, now);
566 } else if (request instanceof LocalHistoryRequest) {
567 final LocalHistoryRequest<?> lhReq = (LocalHistoryRequest<?>)request;
568 final ClientIdentifier clientId = lhReq.getTarget().getClientId();
569 return getFrontend(clientId).handleLocalHistoryRequest(lhReq, envelope, now);
571 LOG.warn("{}: rejecting unsupported request {}", persistenceId(), request);
572 throw new UnsupportedRequestException(request);
576 private boolean hasLeader() {
577 return getLeaderId() != null;
580 public int getPendingTxCommitQueueSize() {
581 return store.getQueueSize();
584 public int getCohortCacheSize() {
585 return commitCoordinator.getCohortCacheSize();
589 protected Optional<ActorRef> getRoleChangeNotifier() {
590 return roleChangeNotifier;
593 String getShardName() {
598 protected LeaderStateChanged newLeaderStateChanged(final String memberId, final String leaderId,
599 final short leaderPayloadVersion) {
600 return isLeader() ? new ShardLeaderStateChanged(memberId, leaderId, store.getDataTree(), leaderPayloadVersion)
601 : new ShardLeaderStateChanged(memberId, leaderId, leaderPayloadVersion);
604 protected void onDatastoreContext(final DatastoreContext context) {
605 datastoreContext = context;
607 setTransactionCommitTimeout();
609 setPersistence(datastoreContext.isPersistent());
611 updateConfigParams(datastoreContext.getShardRaftConfig());
614 // applyState() will be invoked once consensus is reached on the payload
615 void persistPayload(final Identifier id, final Payload payload, final boolean batchHint) {
616 boolean canSkipPayload = !hasFollowers() && !persistence().isRecoveryApplicable();
617 if (canSkipPayload) {
618 applyState(self(), id, payload);
620 // We are faking the sender
621 persistData(self(), id, payload, batchHint);
625 private void handleCommitTransaction(final CommitTransaction commit) {
627 commitCoordinator.handleCommit(commit.getTransactionId(), getSender(), this);
629 ActorSelection leader = getLeader();
630 if (leader == null) {
631 messageRetrySupport.addMessageToRetry(commit, getSender(),
632 "Could not commit transaction " + commit.getTransactionId());
634 LOG.debug("{}: Forwarding CommitTransaction to leader {}", persistenceId(), leader);
635 leader.forward(commit, getContext());
640 private void handleCanCommitTransaction(final CanCommitTransaction canCommit) {
641 LOG.debug("{}: Can committing transaction {}", persistenceId(), canCommit.getTransactionId());
644 commitCoordinator.handleCanCommit(canCommit.getTransactionId(), getSender(), this);
646 ActorSelection leader = getLeader();
647 if (leader == null) {
648 messageRetrySupport.addMessageToRetry(canCommit, getSender(),
649 "Could not canCommit transaction " + canCommit.getTransactionId());
651 LOG.debug("{}: Forwarding CanCommitTransaction to leader {}", persistenceId(), leader);
652 leader.forward(canCommit, getContext());
657 @SuppressWarnings("checkstyle:IllegalCatch")
658 protected void handleBatchedModificationsLocal(final BatchedModifications batched, final ActorRef sender) {
660 commitCoordinator.handleBatchedModifications(batched, sender, this);
661 } catch (Exception e) {
662 LOG.error("{}: Error handling BatchedModifications for Tx {}", persistenceId(),
663 batched.getTransactionId(), e);
664 sender.tell(new Failure(e), getSelf());
668 private void handleBatchedModifications(final BatchedModifications batched) {
669 // This message is sent to prepare the modifications transaction directly on the Shard as an
670 // optimization to avoid the extra overhead of a separate ShardTransaction actor. On the last
671 // BatchedModifications message, the caller sets the ready flag in the message indicating
672 // modifications are complete. The reply contains the cohort actor path (this actor) for the caller
673 // to initiate the 3-phase commit. This also avoids the overhead of sending an additional
674 // ReadyTransaction message.
676 // If we're not the leader then forward to the leader. This is a safety measure - we shouldn't
677 // normally get here if we're not the leader as the front-end (TransactionProxy) should determine
678 // the primary/leader shard. However with timing and caching on the front-end, there's a small
679 // window where it could have a stale leader during leadership transitions.
681 boolean isLeaderActive = isLeaderActive();
682 if (isLeader() && isLeaderActive) {
683 handleBatchedModificationsLocal(batched, getSender());
685 ActorSelection leader = getLeader();
686 if (!isLeaderActive || leader == null) {
687 messageRetrySupport.addMessageToRetry(batched, getSender(),
688 "Could not process BatchedModifications " + batched.getTransactionId());
690 // If this is not the first batch and leadership changed in between batched messages,
691 // we need to reconstruct previous BatchedModifications from the transaction
692 // DataTreeModification, honoring the max batched modification count, and forward all the
693 // previous BatchedModifications to the new leader.
694 Collection<BatchedModifications> newModifications = commitCoordinator
695 .createForwardedBatchedModifications(batched,
696 datastoreContext.getShardBatchedModificationCount());
698 LOG.debug("{}: Forwarding {} BatchedModifications to leader {}", persistenceId(),
699 newModifications.size(), leader);
701 for (BatchedModifications bm : newModifications) {
702 leader.forward(bm, getContext());
708 private boolean failIfIsolatedLeader(final ActorRef sender) {
709 if (isIsolatedLeader()) {
710 sender.tell(new Failure(new NoShardLeaderException(String.format(
711 "Shard %s was the leader but has lost contact with all of its followers. Either all"
712 + " other follower nodes are down or this node is isolated by a network partition.",
713 persistenceId()))), getSelf());
720 protected boolean isIsolatedLeader() {
721 return getRaftState() == RaftState.IsolatedLeader;
724 @SuppressWarnings("checkstyle:IllegalCatch")
725 private void handleReadyLocalTransaction(final ReadyLocalTransaction message) {
726 LOG.debug("{}: handleReadyLocalTransaction for {}", persistenceId(), message.getTransactionId());
728 boolean isLeaderActive = isLeaderActive();
729 if (isLeader() && isLeaderActive) {
731 commitCoordinator.handleReadyLocalTransaction(message, getSender(), this);
732 } catch (Exception e) {
733 LOG.error("{}: Error handling ReadyLocalTransaction for Tx {}", persistenceId(),
734 message.getTransactionId(), e);
735 getSender().tell(new Failure(e), getSelf());
738 ActorSelection leader = getLeader();
739 if (!isLeaderActive || leader == null) {
740 messageRetrySupport.addMessageToRetry(message, getSender(),
741 "Could not process ready local transaction " + message.getTransactionId());
743 LOG.debug("{}: Forwarding ReadyLocalTransaction to leader {}", persistenceId(), leader);
744 message.setRemoteVersion(getCurrentBehavior().getLeaderPayloadVersion());
745 leader.forward(message, getContext());
750 private void handleForwardedReadyTransaction(final ForwardedReadyTransaction forwardedReady) {
751 LOG.debug("{}: handleForwardedReadyTransaction for {}", persistenceId(), forwardedReady.getTransactionId());
753 boolean isLeaderActive = isLeaderActive();
754 if (isLeader() && isLeaderActive) {
755 commitCoordinator.handleForwardedReadyTransaction(forwardedReady, getSender(), this);
757 ActorSelection leader = getLeader();
758 if (!isLeaderActive || leader == null) {
759 messageRetrySupport.addMessageToRetry(forwardedReady, getSender(),
760 "Could not process forwarded ready transaction " + forwardedReady.getTransactionId());
762 LOG.debug("{}: Forwarding ForwardedReadyTransaction to leader {}", persistenceId(), leader);
764 ReadyLocalTransaction readyLocal = new ReadyLocalTransaction(forwardedReady.getTransactionId(),
765 forwardedReady.getTransaction().getSnapshot(), forwardedReady.isDoImmediateCommit(),
766 forwardedReady.getParticipatingShardNames());
767 readyLocal.setRemoteVersion(getCurrentBehavior().getLeaderPayloadVersion());
768 leader.forward(readyLocal, getContext());
773 private void handleAbortTransaction(final AbortTransaction abort) {
774 doAbortTransaction(abort.getTransactionId(), getSender());
777 void doAbortTransaction(final Identifier transactionID, final ActorRef sender) {
778 commitCoordinator.handleAbort(transactionID, sender, this);
781 private void handleCreateTransaction(final Object message) {
783 createTransaction(CreateTransaction.fromSerializable(message));
784 } else if (getLeader() != null) {
785 getLeader().forward(message, getContext());
787 getSender().tell(new Failure(new NoShardLeaderException(
788 "Could not create a shard transaction", persistenceId())), getSelf());
792 private void closeTransactionChain(final CloseTransactionChain closeTransactionChain) {
793 final LocalHistoryIdentifier id = closeTransactionChain.getIdentifier();
794 store.closeTransactionChain(id, null);
795 store.purgeTransactionChain(id, null);
798 @SuppressWarnings("checkstyle:IllegalCatch")
799 private void createTransaction(final CreateTransaction createTransaction) {
801 if (TransactionType.fromInt(createTransaction.getTransactionType()) != TransactionType.READ_ONLY
802 && failIfIsolatedLeader(getSender())) {
806 ActorRef transactionActor = createTransaction(createTransaction.getTransactionType(),
807 createTransaction.getTransactionId());
809 getSender().tell(new CreateTransactionReply(Serialization.serializedActorPath(transactionActor),
810 createTransaction.getTransactionId(), createTransaction.getVersion()).toSerializable(), getSelf());
811 } catch (Exception e) {
812 getSender().tell(new Failure(e), getSelf());
816 private ActorRef createTransaction(final int transactionType, final TransactionIdentifier transactionId) {
817 LOG.debug("{}: Creating transaction : {} ", persistenceId(), transactionId);
818 return transactionActorFactory.newShardTransaction(TransactionType.fromInt(transactionType),
822 private void updateSchemaContext(final UpdateSchemaContext message) {
823 updateSchemaContext(message.getSchemaContext());
827 void updateSchemaContext(final SchemaContext schemaContext) {
828 store.updateSchemaContext(schemaContext);
831 private boolean isMetricsCaptureEnabled() {
832 CommonConfig config = new CommonConfig(getContext().system().settings().config());
833 return config.isMetricCaptureEnabled();
838 public RaftActorSnapshotCohort getRaftActorSnapshotCohort() {
839 return snapshotCohort;
844 protected RaftActorRecoveryCohort getRaftActorRecoveryCohort() {
845 if (restoreFromSnapshot == null) {
846 return ShardRecoveryCoordinator.create(store, persistenceId(), LOG);
849 return ShardRecoveryCoordinator.forSnapshot(store, persistenceId(), LOG, restoreFromSnapshot.getSnapshot());
853 protected void onRecoveryComplete() {
854 restoreFromSnapshot = null;
856 //notify shard manager
857 getContext().parent().tell(new ActorInitialized(), getSelf());
859 // Being paranoid here - this method should only be called once but just in case...
860 if (txCommitTimeoutCheckSchedule == null) {
861 // Schedule a message to be periodically sent to check if the current in-progress
862 // transaction should be expired and aborted.
863 FiniteDuration period = Duration.create(transactionCommitTimeout / 3, TimeUnit.MILLISECONDS);
864 txCommitTimeoutCheckSchedule = getContext().system().scheduler().schedule(
865 period, period, getSelf(),
866 TX_COMMIT_TIMEOUT_CHECK_MESSAGE, getContext().dispatcher(), ActorRef.noSender());
871 protected void applyState(final ActorRef clientActor, final Identifier identifier, final Object data) {
872 if (data instanceof Payload) {
874 store.applyReplicatedPayload(identifier, (Payload)data);
875 } catch (DataValidationFailedException | IOException e) {
876 LOG.error("{}: Error applying replica {}", persistenceId(), identifier, e);
879 LOG.error("{}: Unknown state for {} received {}", persistenceId(), identifier, data);
884 protected void onStateChanged() {
885 boolean isLeader = isLeader();
886 boolean hasLeader = hasLeader();
887 treeChangeSupport.onLeadershipChange(isLeader, hasLeader);
889 // If this actor is no longer the leader close all the transaction chains
891 if (LOG.isDebugEnabled()) {
893 "{}: onStateChanged: Closing all transaction chains because shard {} is no longer the leader",
894 persistenceId(), getId());
898 store.purgeLeaderState();
901 if (hasLeader && !isIsolatedLeader()) {
902 messageRetrySupport.retryMessages();
907 protected void onLeaderChanged(final String oldLeader, final String newLeader) {
908 shardMBean.incrementLeadershipChangeCount();
912 if (!knownFrontends.isEmpty()) {
913 LOG.debug("{}: removing frontend state for {}", persistenceId(), knownFrontends.keySet());
914 knownFrontends = ImmutableMap.of();
917 requestMessageAssembler.close();
920 // No leader anywhere, nothing else to do
924 // Another leader was elected. If we were the previous leader and had pending transactions, convert
925 // them to transaction messages and send to the new leader.
926 ActorSelection leader = getLeader();
927 if (leader != null) {
928 Collection<?> messagesToForward = convertPendingTransactionsToMessages();
930 if (!messagesToForward.isEmpty()) {
931 LOG.debug("{}: Forwarding {} pending transaction messages to leader {}", persistenceId(),
932 messagesToForward.size(), leader);
934 for (Object message : messagesToForward) {
935 LOG.debug("{}: Forwarding pending transaction message {}", persistenceId(), message);
937 leader.tell(message, self());
941 commitCoordinator.abortPendingTransactions("The transacton was aborted due to inflight leadership "
942 + "change and the leader address isn't available.", this);
945 // We have become the leader, we need to reconstruct frontend state
946 knownFrontends = Verify.verifyNotNull(frontendMetadata.toLeaderState(this));
947 LOG.debug("{}: became leader with frontend state for {}", persistenceId(), knownFrontends.keySet());
950 if (!isIsolatedLeader()) {
951 messageRetrySupport.retryMessages();
956 * Clears all pending transactions and converts them to messages to be forwarded to a new leader.
958 * @return the converted messages
960 public Collection<?> convertPendingTransactionsToMessages() {
961 return commitCoordinator.convertPendingTransactionsToMessages(
962 datastoreContext.getShardBatchedModificationCount());
966 protected void pauseLeader(final Runnable operation) {
967 LOG.debug("{}: In pauseLeader, operation: {}", persistenceId(), operation);
970 // Tell-based protocol can replay transaction state, so it is safe to blow it up when we are paused.
971 knownFrontends.values().forEach(LeaderFrontendState::retire);
972 knownFrontends = ImmutableMap.of();
974 store.setRunOnPendingTransactionsComplete(operation);
978 protected void unpauseLeader() {
979 LOG.debug("{}: In unpauseLeader", persistenceId());
982 store.setRunOnPendingTransactionsComplete(null);
984 // Restore tell-based protocol state as if we were becoming the leader
985 knownFrontends = Verify.verifyNotNull(frontendMetadata.toLeaderState(this));
989 protected OnDemandRaftState.AbstractBuilder<?, ?> newOnDemandRaftStateBuilder() {
990 return OnDemandShardState.newBuilder().treeChangeListenerActors(treeChangeSupport.getListenerActors())
991 .commitCohortActors(store.getCohortActors());
995 public String persistenceId() {
1000 ShardCommitCoordinator getCommitCoordinator() {
1001 return commitCoordinator;
1004 public DatastoreContext getDatastoreContext() {
1005 return datastoreContext;
1009 public ShardDataTree getDataStore() {
1014 ShardStats getShardMBean() {
1018 public static Builder builder() {
1019 return new Builder();
1022 public abstract static class AbstractBuilder<T extends AbstractBuilder<T, S>, S extends Shard> {
1023 private final Class<S> shardClass;
1024 private ShardIdentifier id;
1025 private Map<String, String> peerAddresses = Collections.emptyMap();
1026 private DatastoreContext datastoreContext;
1027 private SchemaContextProvider schemaContextProvider;
1028 private DatastoreSnapshot.ShardSnapshot restoreFromSnapshot;
1029 private DataTree dataTree;
1030 private volatile boolean sealed;
1032 protected AbstractBuilder(final Class<S> shardClass) {
1033 this.shardClass = shardClass;
1036 protected void checkSealed() {
1037 Preconditions.checkState(!sealed, "Builder isalready sealed - further modifications are not allowed");
1040 @SuppressWarnings("unchecked")
1045 public T id(final ShardIdentifier newId) {
1051 public T peerAddresses(final Map<String, String> newPeerAddresses) {
1053 this.peerAddresses = newPeerAddresses;
1057 public T datastoreContext(final DatastoreContext newDatastoreContext) {
1059 this.datastoreContext = newDatastoreContext;
1063 public T schemaContextProvider(final SchemaContextProvider newSchemaContextProvider) {
1065 this.schemaContextProvider = Preconditions.checkNotNull(newSchemaContextProvider);
1069 public T restoreFromSnapshot(final DatastoreSnapshot.ShardSnapshot newRestoreFromSnapshot) {
1071 this.restoreFromSnapshot = newRestoreFromSnapshot;
1075 public T dataTree(final DataTree newDataTree) {
1077 this.dataTree = newDataTree;
1081 public ShardIdentifier getId() {
1085 public Map<String, String> getPeerAddresses() {
1086 return peerAddresses;
1089 public DatastoreContext getDatastoreContext() {
1090 return datastoreContext;
1093 public SchemaContext getSchemaContext() {
1094 return Verify.verifyNotNull(schemaContextProvider.getSchemaContext());
1097 public DatastoreSnapshot.ShardSnapshot getRestoreFromSnapshot() {
1098 return restoreFromSnapshot;
1101 public DataTree getDataTree() {
1105 public TreeType getTreeType() {
1106 switch (datastoreContext.getLogicalStoreType()) {
1108 return TreeType.CONFIGURATION;
1110 return TreeType.OPERATIONAL;
1112 throw new IllegalStateException("Unhandled logical store type "
1113 + datastoreContext.getLogicalStoreType());
1117 protected void verify() {
1118 Preconditions.checkNotNull(id, "id should not be null");
1119 Preconditions.checkNotNull(peerAddresses, "peerAddresses should not be null");
1120 Preconditions.checkNotNull(datastoreContext, "dataStoreContext should not be null");
1121 Preconditions.checkNotNull(schemaContextProvider, "schemaContextProvider should not be null");
1124 public Props props() {
1127 return Props.create(shardClass, this);
1131 public static class Builder extends AbstractBuilder<Builder, Shard> {
1138 return Ticker.systemTicker();
1141 void scheduleNextPendingTransaction() {
1142 self().tell(RESUME_NEXT_PENDING_TRANSACTION, ActorRef.noSender());