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 static com.google.common.base.Verify.verify;
13 import akka.actor.ActorRef;
14 import akka.actor.ActorSelection;
15 import akka.actor.Cancellable;
16 import akka.actor.ExtendedActorSystem;
17 import akka.actor.Props;
18 import akka.actor.Status;
19 import akka.actor.Status.Failure;
20 import akka.serialization.JavaSerializer;
21 import akka.serialization.Serialization;
22 import com.google.common.annotations.VisibleForTesting;
23 import com.google.common.base.Optional;
24 import com.google.common.base.Preconditions;
25 import com.google.common.base.Ticker;
26 import com.google.common.base.Verify;
27 import com.google.common.collect.ImmutableList;
28 import com.google.common.collect.ImmutableMap;
29 import com.google.common.collect.Range;
30 import java.io.IOException;
31 import java.util.Arrays;
32 import java.util.Collection;
33 import java.util.Collections;
35 import java.util.concurrent.TimeUnit;
36 import javax.annotation.Nonnull;
37 import javax.annotation.Nullable;
38 import org.opendaylight.controller.cluster.access.ABIVersion;
39 import org.opendaylight.controller.cluster.access.commands.ConnectClientRequest;
40 import org.opendaylight.controller.cluster.access.commands.ConnectClientSuccess;
41 import org.opendaylight.controller.cluster.access.commands.LocalHistoryRequest;
42 import org.opendaylight.controller.cluster.access.commands.NotLeaderException;
43 import org.opendaylight.controller.cluster.access.commands.OutOfSequenceEnvelopeException;
44 import org.opendaylight.controller.cluster.access.commands.TransactionRequest;
45 import org.opendaylight.controller.cluster.access.concepts.ClientIdentifier;
46 import org.opendaylight.controller.cluster.access.concepts.FrontendIdentifier;
47 import org.opendaylight.controller.cluster.access.concepts.LocalHistoryIdentifier;
48 import org.opendaylight.controller.cluster.access.concepts.Request;
49 import org.opendaylight.controller.cluster.access.concepts.RequestEnvelope;
50 import org.opendaylight.controller.cluster.access.concepts.RequestException;
51 import org.opendaylight.controller.cluster.access.concepts.RequestSuccess;
52 import org.opendaylight.controller.cluster.access.concepts.RetiredGenerationException;
53 import org.opendaylight.controller.cluster.access.concepts.RuntimeRequestException;
54 import org.opendaylight.controller.cluster.access.concepts.SliceableMessage;
55 import org.opendaylight.controller.cluster.access.concepts.TransactionIdentifier;
56 import org.opendaylight.controller.cluster.access.concepts.UnsupportedRequestException;
57 import org.opendaylight.controller.cluster.common.actor.CommonConfig;
58 import org.opendaylight.controller.cluster.common.actor.Dispatchers;
59 import org.opendaylight.controller.cluster.common.actor.Dispatchers.DispatcherType;
60 import org.opendaylight.controller.cluster.common.actor.MessageTracker;
61 import org.opendaylight.controller.cluster.common.actor.MessageTracker.Error;
62 import org.opendaylight.controller.cluster.common.actor.MeteringBehavior;
63 import org.opendaylight.controller.cluster.datastore.exceptions.NoShardLeaderException;
64 import org.opendaylight.controller.cluster.datastore.identifiers.ShardIdentifier;
65 import org.opendaylight.controller.cluster.datastore.jmx.mbeans.shard.ShardDataTreeListenerInfoMXBeanImpl;
66 import org.opendaylight.controller.cluster.datastore.jmx.mbeans.shard.ShardMBeanFactory;
67 import org.opendaylight.controller.cluster.datastore.jmx.mbeans.shard.ShardStats;
68 import org.opendaylight.controller.cluster.datastore.messages.AbortTransaction;
69 import org.opendaylight.controller.cluster.datastore.messages.ActorInitialized;
70 import org.opendaylight.controller.cluster.datastore.messages.BatchedModifications;
71 import org.opendaylight.controller.cluster.datastore.messages.CanCommitTransaction;
72 import org.opendaylight.controller.cluster.datastore.messages.CloseTransactionChain;
73 import org.opendaylight.controller.cluster.datastore.messages.CommitTransaction;
74 import org.opendaylight.controller.cluster.datastore.messages.CreateTransaction;
75 import org.opendaylight.controller.cluster.datastore.messages.CreateTransactionReply;
76 import org.opendaylight.controller.cluster.datastore.messages.ForwardedReadyTransaction;
77 import org.opendaylight.controller.cluster.datastore.messages.GetShardDataTree;
78 import org.opendaylight.controller.cluster.datastore.messages.MakeLeaderLocal;
79 import org.opendaylight.controller.cluster.datastore.messages.OnDemandShardState;
80 import org.opendaylight.controller.cluster.datastore.messages.PeerAddressResolved;
81 import org.opendaylight.controller.cluster.datastore.messages.PersistAbortTransactionPayload;
82 import org.opendaylight.controller.cluster.datastore.messages.ReadyLocalTransaction;
83 import org.opendaylight.controller.cluster.datastore.messages.RegisterDataTreeChangeListener;
84 import org.opendaylight.controller.cluster.datastore.messages.ShardLeaderStateChanged;
85 import org.opendaylight.controller.cluster.datastore.messages.UpdateSchemaContext;
86 import org.opendaylight.controller.cluster.datastore.persisted.AbortTransactionPayload;
87 import org.opendaylight.controller.cluster.datastore.persisted.DatastoreSnapshot;
88 import org.opendaylight.controller.cluster.datastore.persisted.DatastoreSnapshot.ShardSnapshot;
89 import org.opendaylight.controller.cluster.datastore.persisted.DisableTrackingPayload;
90 import org.opendaylight.controller.cluster.datastore.persisted.PurgeTransactionPayload;
91 import org.opendaylight.controller.cluster.messaging.MessageAssembler;
92 import org.opendaylight.controller.cluster.messaging.MessageSlicer;
93 import org.opendaylight.controller.cluster.messaging.SliceOptions;
94 import org.opendaylight.controller.cluster.notifications.LeaderStateChanged;
95 import org.opendaylight.controller.cluster.notifications.RegisterRoleChangeListener;
96 import org.opendaylight.controller.cluster.notifications.RoleChangeNotifier;
97 import org.opendaylight.controller.cluster.raft.LeadershipTransferFailedException;
98 import org.opendaylight.controller.cluster.raft.RaftActor;
99 import org.opendaylight.controller.cluster.raft.RaftActorRecoveryCohort;
100 import org.opendaylight.controller.cluster.raft.RaftActorSnapshotCohort;
101 import org.opendaylight.controller.cluster.raft.RaftState;
102 import org.opendaylight.controller.cluster.raft.base.messages.FollowerInitialSyncUpStatus;
103 import org.opendaylight.controller.cluster.raft.client.messages.OnDemandRaftState;
104 import org.opendaylight.controller.cluster.raft.messages.AppendEntriesReply;
105 import org.opendaylight.controller.cluster.raft.messages.RequestLeadership;
106 import org.opendaylight.controller.cluster.raft.messages.ServerRemoved;
107 import org.opendaylight.controller.cluster.raft.protobuff.client.messages.Payload;
108 import org.opendaylight.yangtools.concepts.Identifier;
109 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTree;
110 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataValidationFailedException;
111 import org.opendaylight.yangtools.yang.data.api.schema.tree.TreeType;
112 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
113 import org.opendaylight.yangtools.yang.model.api.SchemaContextProvider;
114 import scala.concurrent.duration.Duration;
115 import scala.concurrent.duration.FiniteDuration;
118 * A Shard represents a portion of the logical data tree.
121 * Our Shard uses InMemoryDataTree as it's internal representation and delegates all requests it
123 public class Shard extends RaftActor {
126 static final Object TX_COMMIT_TIMEOUT_CHECK_MESSAGE = new Object() {
128 public String toString() {
129 return "txCommitTimeoutCheck";
134 static final Object GET_SHARD_MBEAN_MESSAGE = new Object() {
136 public String toString() {
137 return "getShardMBeanMessage";
141 static final Object RESUME_NEXT_PENDING_TRANSACTION = new Object() {
143 public String toString() {
144 return "resumeNextPendingTransaction";
148 // FIXME: shard names should be encapsulated in their own class and this should be exposed as a constant.
149 public static final String DEFAULT_NAME = "default";
151 private static final Collection<ABIVersion> SUPPORTED_ABIVERSIONS;
154 final ABIVersion[] values = ABIVersion.values();
155 final ABIVersion[] real = Arrays.copyOfRange(values, 1, values.length - 1);
156 SUPPORTED_ABIVERSIONS = ImmutableList.copyOf(real).reverse();
159 // FIXME: make this a dynamic property based on mailbox size and maximum number of clients
160 private static final int CLIENT_MAX_MESSAGES = 1000;
162 // The state of this Shard
163 private final ShardDataTree store;
165 /// The name of this shard
166 private final String name;
168 private final String shardName;
170 private final ShardStats shardMBean;
172 private final ShardDataTreeListenerInfoMXBeanImpl listenerInfoMXBean;
174 private DatastoreContext datastoreContext;
176 private final ShardCommitCoordinator commitCoordinator;
178 private long transactionCommitTimeout;
180 private Cancellable txCommitTimeoutCheckSchedule;
182 private final Optional<ActorRef> roleChangeNotifier;
184 private final MessageTracker appendEntriesReplyTracker;
186 private final ShardTransactionActorFactory transactionActorFactory;
188 private final ShardSnapshotCohort snapshotCohort;
190 private final DataTreeChangeListenerSupport treeChangeSupport = new DataTreeChangeListenerSupport(this);
192 private ShardSnapshot restoreFromSnapshot;
194 private final ShardTransactionMessageRetrySupport messageRetrySupport;
196 private final FrontendMetadata frontendMetadata;
197 private Map<FrontendIdentifier, LeaderFrontendState> knownFrontends = ImmutableMap.of();
198 private boolean paused;
200 private final MessageSlicer responseMessageSlicer;
201 private final Dispatchers dispatchers;
203 private final MessageAssembler requestMessageAssembler;
205 protected Shard(final AbstractBuilder<?, ?> builder) {
206 super(builder.getId().toString(), builder.getPeerAddresses(),
207 Optional.of(builder.getDatastoreContext().getShardRaftConfig()), DataStoreVersions.CURRENT_VERSION);
209 this.name = builder.getId().toString();
210 this.shardName = builder.getId().getShardName();
211 this.datastoreContext = builder.getDatastoreContext();
212 this.restoreFromSnapshot = builder.getRestoreFromSnapshot();
213 this.frontendMetadata = new FrontendMetadata(name);
215 setPersistence(datastoreContext.isPersistent());
217 LOG.info("Shard created : {}, persistent : {}", name, datastoreContext.isPersistent());
219 ShardDataTreeChangeListenerPublisherActorProxy treeChangeListenerPublisher =
220 new ShardDataTreeChangeListenerPublisherActorProxy(getContext(), name + "-DTCL-publisher", name);
221 if (builder.getDataTree() != null) {
222 store = new ShardDataTree(this, builder.getSchemaContext(), builder.getDataTree(),
223 treeChangeListenerPublisher, name, frontendMetadata);
225 store = new ShardDataTree(this, builder.getSchemaContext(), builder.getTreeType(),
226 builder.getDatastoreContext().getStoreRoot(), treeChangeListenerPublisher, name, frontendMetadata);
229 shardMBean = ShardMBeanFactory.getShardStatsMBean(name, datastoreContext.getDataStoreMXBeanType(), this);
231 if (isMetricsCaptureEnabled()) {
232 getContext().become(new MeteringBehavior(this));
235 commitCoordinator = new ShardCommitCoordinator(store, LOG, this.name);
237 setTransactionCommitTimeout();
239 // create a notifier actor for each cluster member
240 roleChangeNotifier = createRoleChangeNotifier(name);
242 appendEntriesReplyTracker = new MessageTracker(AppendEntriesReply.class,
243 getRaftActorContext().getConfigParams().getIsolatedCheckIntervalInMillis());
245 dispatchers = new Dispatchers(context().system().dispatchers());
246 transactionActorFactory = new ShardTransactionActorFactory(store, datastoreContext,
247 dispatchers.getDispatcherPath(Dispatchers.DispatcherType.Transaction),
248 self(), getContext(), shardMBean, builder.getId().getShardName());
250 snapshotCohort = ShardSnapshotCohort.create(getContext(), builder.getId().getMemberName(), store, LOG,
253 messageRetrySupport = new ShardTransactionMessageRetrySupport(this);
255 responseMessageSlicer = MessageSlicer.builder().logContext(this.name)
256 .messageSliceSize(datastoreContext.getMaximumMessageSliceSize())
257 .fileBackedStreamFactory(getRaftActorContext().getFileBackedOutputStreamFactory())
258 .expireStateAfterInactivity(2, TimeUnit.MINUTES).build();
260 requestMessageAssembler = MessageAssembler.builder().logContext(this.name)
261 .fileBackedStreamFactory(getRaftActorContext().getFileBackedOutputStreamFactory())
262 .assembledMessageCallback((message, sender) -> self().tell(message, sender))
263 .expireStateAfterInactivity(datastoreContext.getRequestTimeout(), TimeUnit.NANOSECONDS).build();
265 listenerInfoMXBean = new ShardDataTreeListenerInfoMXBeanImpl(name, datastoreContext.getDataStoreMXBeanType(),
267 listenerInfoMXBean.register();
270 private void setTransactionCommitTimeout() {
271 transactionCommitTimeout = TimeUnit.MILLISECONDS.convert(
272 datastoreContext.getShardTransactionCommitTimeoutInSeconds(), TimeUnit.SECONDS) / 2;
275 private Optional<ActorRef> createRoleChangeNotifier(final String shardId) {
276 ActorRef shardRoleChangeNotifier = this.getContext().actorOf(
277 RoleChangeNotifier.getProps(shardId), shardId + "-notifier");
278 return Optional.of(shardRoleChangeNotifier);
282 public void postStop() {
283 LOG.info("Stopping Shard {}", persistenceId());
287 messageRetrySupport.close();
289 if (txCommitTimeoutCheckSchedule != null) {
290 txCommitTimeoutCheckSchedule.cancel();
293 commitCoordinator.abortPendingTransactions("Transaction aborted due to shutdown.", this);
295 shardMBean.unregisterMBean();
296 listenerInfoMXBean.unregister();
300 protected void handleRecover(final Object message) {
301 LOG.debug("{}: onReceiveRecover: Received message {} from {}", persistenceId(), message.getClass(),
304 super.handleRecover(message);
305 if (LOG.isTraceEnabled()) {
306 appendEntriesReplyTracker.begin();
311 protected void handleNonRaftCommand(final Object message) {
312 try (MessageTracker.Context context = appendEntriesReplyTracker.received(message)) {
313 final Optional<Error> maybeError = context.error();
314 if (maybeError.isPresent()) {
315 LOG.trace("{} : AppendEntriesReply failed to arrive at the expected interval {}", persistenceId(),
319 store.resetTransactionBatch();
321 if (message instanceof RequestEnvelope) {
322 handleRequestEnvelope((RequestEnvelope)message);
323 } else if (MessageAssembler.isHandledMessage(message)) {
324 handleRequestAssemblerMessage(message);
325 } else if (message instanceof ConnectClientRequest) {
326 handleConnectClient((ConnectClientRequest)message);
327 } else if (CreateTransaction.isSerializedType(message)) {
328 handleCreateTransaction(message);
329 } else if (message instanceof BatchedModifications) {
330 handleBatchedModifications((BatchedModifications)message);
331 } else if (message instanceof ForwardedReadyTransaction) {
332 handleForwardedReadyTransaction((ForwardedReadyTransaction) message);
333 } else if (message instanceof ReadyLocalTransaction) {
334 handleReadyLocalTransaction((ReadyLocalTransaction)message);
335 } else if (CanCommitTransaction.isSerializedType(message)) {
336 handleCanCommitTransaction(CanCommitTransaction.fromSerializable(message));
337 } else if (CommitTransaction.isSerializedType(message)) {
338 handleCommitTransaction(CommitTransaction.fromSerializable(message));
339 } else if (AbortTransaction.isSerializedType(message)) {
340 handleAbortTransaction(AbortTransaction.fromSerializable(message));
341 } else if (CloseTransactionChain.isSerializedType(message)) {
342 closeTransactionChain(CloseTransactionChain.fromSerializable(message));
343 } else if (message instanceof RegisterDataTreeChangeListener) {
344 treeChangeSupport.onMessage((RegisterDataTreeChangeListener) message, isLeader(), hasLeader());
345 } else if (message instanceof UpdateSchemaContext) {
346 updateSchemaContext((UpdateSchemaContext) message);
347 } else if (message instanceof PeerAddressResolved) {
348 PeerAddressResolved resolved = (PeerAddressResolved) message;
349 setPeerAddress(resolved.getPeerId(), resolved.getPeerAddress());
350 } else if (TX_COMMIT_TIMEOUT_CHECK_MESSAGE.equals(message)) {
351 commitTimeoutCheck();
352 } else if (message instanceof DatastoreContext) {
353 onDatastoreContext((DatastoreContext)message);
354 } else if (message instanceof RegisterRoleChangeListener) {
355 roleChangeNotifier.get().forward(message, context());
356 } else if (message instanceof FollowerInitialSyncUpStatus) {
357 shardMBean.setFollowerInitialSyncStatus(((FollowerInitialSyncUpStatus) message).isInitialSyncDone());
358 context().parent().tell(message, self());
359 } else if (GET_SHARD_MBEAN_MESSAGE.equals(message)) {
360 sender().tell(getShardMBean(), self());
361 } else if (message instanceof GetShardDataTree) {
362 sender().tell(store.getDataTree(), self());
363 } else if (message instanceof ServerRemoved) {
364 context().parent().forward(message, context());
365 } else if (ShardTransactionMessageRetrySupport.TIMER_MESSAGE_CLASS.isInstance(message)) {
366 messageRetrySupport.onTimerMessage(message);
367 } else if (message instanceof DataTreeCohortActorRegistry.CohortRegistryCommand) {
368 store.processCohortRegistryCommand(getSender(),
369 (DataTreeCohortActorRegistry.CohortRegistryCommand) message);
370 } else if (message instanceof PersistAbortTransactionPayload) {
371 final TransactionIdentifier txId = ((PersistAbortTransactionPayload) message).getTransactionId();
372 persistPayload(txId, AbortTransactionPayload.create(txId,
373 datastoreContext.getInitialPayloadSerializedBufferCapacity()), true);
374 persistPayload(txId, PurgeTransactionPayload.create(txId,
375 datastoreContext.getInitialPayloadSerializedBufferCapacity()), false);
376 } else if (message instanceof MakeLeaderLocal) {
378 } else if (RESUME_NEXT_PENDING_TRANSACTION.equals(message)) {
379 store.resumeNextPendingTransaction();
380 } else if (!responseMessageSlicer.handleMessage(message)) {
381 super.handleNonRaftCommand(message);
386 private void handleRequestAssemblerMessage(final Object message) {
387 dispatchers.getDispatcher(DispatcherType.Serialization).execute(() -> {
388 JavaSerializer.currentSystem().value_$eq((ExtendedActorSystem) context().system());
389 requestMessageAssembler.handleMessage(message, self());
393 @SuppressWarnings("checkstyle:IllegalCatch")
394 private void handleRequestEnvelope(final RequestEnvelope envelope) {
395 final long now = ticker().read();
397 final RequestSuccess<?, ?> success = handleRequest(envelope, now);
398 if (success != null) {
399 final long executionTimeNanos = ticker().read() - now;
400 if (success instanceof SliceableMessage) {
401 dispatchers.getDispatcher(DispatcherType.Serialization).execute(() ->
402 responseMessageSlicer.slice(SliceOptions.builder().identifier(success.getTarget())
403 .message(envelope.newSuccessEnvelope(success, executionTimeNanos))
404 .sendTo(envelope.getMessage().getReplyTo()).replyTo(self())
405 .onFailureCallback(t -> LOG.warn("Error slicing response {}", success, t)).build()));
407 envelope.sendSuccess(success, executionTimeNanos);
410 } catch (RequestException e) {
411 LOG.debug("{}: request {} failed", persistenceId(), envelope, e);
412 envelope.sendFailure(e, ticker().read() - now);
413 } catch (Exception e) {
414 LOG.debug("{}: request {} caused failure", persistenceId(), envelope, e);
415 envelope.sendFailure(new RuntimeRequestException("Request failed to process", e),
416 ticker().read() - now);
420 private void commitTimeoutCheck() {
421 store.checkForExpiredTransactions(transactionCommitTimeout, this::updateAccess);
422 commitCoordinator.checkForExpiredTransactions(transactionCommitTimeout, this);
423 requestMessageAssembler.checkExpiredAssembledMessageState();
426 private Optional<Long> updateAccess(final SimpleShardDataTreeCohort cohort) {
427 final FrontendIdentifier frontend = cohort.getIdentifier().getHistoryId().getClientId().getFrontendId();
428 final LeaderFrontendState state = knownFrontends.get(frontend);
430 // Not tell-based protocol, do nothing
431 return Optional.absent();
434 if (isIsolatedLeader()) {
435 // We are isolated and no new request can come through until we emerge from it. We are still updating
436 // liveness of frontend when we see it attempting to communicate. Use the last access timer.
437 return Optional.of(state.getLastSeenTicks());
440 // If this frontend has freshly connected, give it some time to catch up before killing its transactions.
441 return Optional.of(state.getLastConnectTicks());
444 private void disableTracking(final DisableTrackingPayload payload) {
445 final ClientIdentifier clientId = payload.getIdentifier();
446 LOG.debug("{}: disabling tracking of {}", persistenceId(), clientId);
447 frontendMetadata.disableTracking(clientId);
450 final FrontendIdentifier frontendId = clientId.getFrontendId();
451 final LeaderFrontendState frontend = knownFrontends.get(frontendId);
452 if (frontend != null) {
453 if (clientId.equals(frontend.getIdentifier())) {
454 if (!(frontend instanceof LeaderFrontendState.Disabled)) {
455 verify(knownFrontends.replace(frontendId, frontend,
456 new LeaderFrontendState.Disabled(persistenceId(), clientId, store)));
457 LOG.debug("{}: leader state for {} disabled", persistenceId(), clientId);
459 LOG.debug("{}: leader state {} is already disabled", persistenceId(), frontend);
462 LOG.debug("{}: leader state {} does not match {}", persistenceId(), frontend, clientId);
465 LOG.debug("{}: leader state for {} not found", persistenceId(), clientId);
470 private void onMakeLeaderLocal() {
471 LOG.debug("{}: onMakeLeaderLocal received", persistenceId());
473 getSender().tell(new Status.Success(null), getSelf());
477 final ActorSelection leader = getLeader();
479 if (leader == null) {
480 // Leader is not present. The cluster is most likely trying to
481 // elect a leader and we should let that run its normal course
483 // TODO we can wait for the election to complete and retry the
484 // request. We can also let the caller retry by sending a flag
485 // in the response indicating the request is "reTryable".
486 getSender().tell(new Failure(
487 new LeadershipTransferFailedException("We cannot initiate leadership transfer to local node. "
488 + "Currently there is no leader for " + persistenceId())),
493 leader.tell(new RequestLeadership(getId(), getSender()), getSelf());
496 // Acquire our frontend tracking handle and verify generation matches
498 private LeaderFrontendState findFrontend(final ClientIdentifier clientId) throws RequestException {
499 final LeaderFrontendState existing = knownFrontends.get(clientId.getFrontendId());
500 if (existing != null) {
501 final int cmp = Long.compareUnsigned(existing.getIdentifier().getGeneration(), clientId.getGeneration());
507 LOG.debug("{}: rejecting request from outdated client {}", persistenceId(), clientId);
508 throw new RetiredGenerationException(clientId.getGeneration(),
509 existing.getIdentifier().getGeneration());
512 LOG.info("{}: retiring state {}, outdated by request from client {}", persistenceId(), existing, clientId);
514 knownFrontends.remove(clientId.getFrontendId());
516 LOG.debug("{}: client {} is not yet known", persistenceId(), clientId);
522 private LeaderFrontendState getFrontend(final ClientIdentifier clientId) throws RequestException {
523 final LeaderFrontendState ret = findFrontend(clientId);
528 // TODO: a dedicated exception would be better, but this is technically true, too
529 throw new OutOfSequenceEnvelopeException(0);
533 private static ABIVersion selectVersion(final ConnectClientRequest message) {
534 final Range<ABIVersion> clientRange = Range.closed(message.getMinVersion(), message.getMaxVersion());
535 for (ABIVersion v : SUPPORTED_ABIVERSIONS) {
536 if (clientRange.contains(v)) {
541 throw new IllegalArgumentException(String.format(
542 "No common version between backend versions %s and client versions %s", SUPPORTED_ABIVERSIONS,
546 @SuppressWarnings("checkstyle:IllegalCatch")
547 private void handleConnectClient(final ConnectClientRequest message) {
549 final ClientIdentifier clientId = message.getTarget();
550 final LeaderFrontendState existing = findFrontend(clientId);
551 if (existing != null) {
555 if (!isLeader() || !isLeaderActive()) {
556 LOG.info("{}: not currently leader, rejecting request {}. isLeader: {}, isLeaderActive: {},"
557 + "isLeadershipTransferInProgress: {}.",
558 persistenceId(), message, isLeader(), isLeaderActive(), isLeadershipTransferInProgress());
559 throw new NotLeaderException(getSelf());
562 final ABIVersion selectedVersion = selectVersion(message);
563 final LeaderFrontendState frontend;
564 if (existing == null) {
565 frontend = new LeaderFrontendState.Enabled(persistenceId(), clientId, store);
566 knownFrontends.put(clientId.getFrontendId(), frontend);
567 LOG.debug("{}: created state {} for client {}", persistenceId(), frontend, clientId);
572 frontend.reconnect();
573 message.getReplyTo().tell(new ConnectClientSuccess(message.getTarget(), message.getSequence(), getSelf(),
574 ImmutableList.of(), store.getDataTree(), CLIENT_MAX_MESSAGES).toVersion(selectedVersion),
575 ActorRef.noSender());
576 } catch (RequestException | RuntimeException e) {
577 message.getReplyTo().tell(new Failure(e), ActorRef.noSender());
582 private RequestSuccess<?, ?> handleRequest(final RequestEnvelope envelope, final long now)
583 throws RequestException {
584 // We are not the leader, hence we want to fail-fast.
585 if (!isLeader() || paused || !isLeaderActive()) {
586 LOG.debug("{}: not currently active leader, rejecting request {}. isLeader: {}, isLeaderActive: {},"
587 + "isLeadershipTransferInProgress: {}, paused: {}",
588 persistenceId(), envelope, isLeader(), isLeaderActive(), isLeadershipTransferInProgress(), paused);
589 throw new NotLeaderException(getSelf());
592 final Request<?, ?> request = envelope.getMessage();
593 if (request instanceof TransactionRequest) {
594 final TransactionRequest<?> txReq = (TransactionRequest<?>)request;
595 final ClientIdentifier clientId = txReq.getTarget().getHistoryId().getClientId();
596 return getFrontend(clientId).handleTransactionRequest(txReq, envelope, now);
597 } else if (request instanceof LocalHistoryRequest) {
598 final LocalHistoryRequest<?> lhReq = (LocalHistoryRequest<?>)request;
599 final ClientIdentifier clientId = lhReq.getTarget().getClientId();
600 return getFrontend(clientId).handleLocalHistoryRequest(lhReq, envelope, now);
602 LOG.warn("{}: rejecting unsupported request {}", persistenceId(), request);
603 throw new UnsupportedRequestException(request);
607 private boolean hasLeader() {
608 return getLeaderId() != null;
611 public int getPendingTxCommitQueueSize() {
612 return store.getQueueSize();
615 public int getCohortCacheSize() {
616 return commitCoordinator.getCohortCacheSize();
620 protected Optional<ActorRef> getRoleChangeNotifier() {
621 return roleChangeNotifier;
624 String getShardName() {
629 protected LeaderStateChanged newLeaderStateChanged(final String memberId, final String leaderId,
630 final short leaderPayloadVersion) {
631 return isLeader() ? new ShardLeaderStateChanged(memberId, leaderId, store.getDataTree(), leaderPayloadVersion)
632 : new ShardLeaderStateChanged(memberId, leaderId, leaderPayloadVersion);
635 protected void onDatastoreContext(final DatastoreContext context) {
636 datastoreContext = context;
638 setTransactionCommitTimeout();
640 setPersistence(datastoreContext.isPersistent());
642 updateConfigParams(datastoreContext.getShardRaftConfig());
645 // applyState() will be invoked once consensus is reached on the payload
646 void persistPayload(final Identifier id, final Payload payload, final boolean batchHint) {
647 boolean canSkipPayload = !hasFollowers() && !persistence().isRecoveryApplicable();
648 if (canSkipPayload) {
649 applyState(self(), id, payload);
651 // We are faking the sender
652 persistData(self(), id, payload, batchHint);
656 private void handleCommitTransaction(final CommitTransaction commit) {
657 final TransactionIdentifier txId = commit.getTransactionId();
659 askProtocolEncountered(txId);
660 commitCoordinator.handleCommit(txId, getSender(), this);
662 ActorSelection leader = getLeader();
663 if (leader == null) {
664 messageRetrySupport.addMessageToRetry(commit, getSender(), "Could not commit transaction " + txId);
666 LOG.debug("{}: Forwarding CommitTransaction to leader {}", persistenceId(), leader);
667 leader.forward(commit, getContext());
672 private void handleCanCommitTransaction(final CanCommitTransaction canCommit) {
673 final TransactionIdentifier txId = canCommit.getTransactionId();
674 LOG.debug("{}: Can committing transaction {}", persistenceId(), txId);
677 askProtocolEncountered(txId);
678 commitCoordinator.handleCanCommit(txId, getSender(), this);
680 ActorSelection leader = getLeader();
681 if (leader == null) {
682 messageRetrySupport.addMessageToRetry(canCommit, getSender(),
683 "Could not canCommit transaction " + txId);
685 LOG.debug("{}: Forwarding CanCommitTransaction to leader {}", persistenceId(), leader);
686 leader.forward(canCommit, getContext());
691 @SuppressWarnings("checkstyle:IllegalCatch")
692 protected void handleBatchedModificationsLocal(final BatchedModifications batched, final ActorRef sender) {
693 askProtocolEncountered(batched.getTransactionId());
696 commitCoordinator.handleBatchedModifications(batched, sender, this);
697 } catch (Exception e) {
698 LOG.error("{}: Error handling BatchedModifications for Tx {}", persistenceId(),
699 batched.getTransactionId(), e);
700 sender.tell(new Failure(e), getSelf());
704 private void handleBatchedModifications(final BatchedModifications batched) {
705 // This message is sent to prepare the modifications transaction directly on the Shard as an
706 // optimization to avoid the extra overhead of a separate ShardTransaction actor. On the last
707 // BatchedModifications message, the caller sets the ready flag in the message indicating
708 // modifications are complete. The reply contains the cohort actor path (this actor) for the caller
709 // to initiate the 3-phase commit. This also avoids the overhead of sending an additional
710 // ReadyTransaction message.
712 // If we're not the leader then forward to the leader. This is a safety measure - we shouldn't
713 // normally get here if we're not the leader as the front-end (TransactionProxy) should determine
714 // the primary/leader shard. However with timing and caching on the front-end, there's a small
715 // window where it could have a stale leader during leadership transitions.
717 boolean isLeaderActive = isLeaderActive();
718 if (isLeader() && isLeaderActive) {
719 handleBatchedModificationsLocal(batched, getSender());
721 ActorSelection leader = getLeader();
722 if (!isLeaderActive || leader == null) {
723 messageRetrySupport.addMessageToRetry(batched, getSender(),
724 "Could not process BatchedModifications " + batched.getTransactionId());
726 // If this is not the first batch and leadership changed in between batched messages,
727 // we need to reconstruct previous BatchedModifications from the transaction
728 // DataTreeModification, honoring the max batched modification count, and forward all the
729 // previous BatchedModifications to the new leader.
730 Collection<BatchedModifications> newModifications = commitCoordinator
731 .createForwardedBatchedModifications(batched,
732 datastoreContext.getShardBatchedModificationCount());
734 LOG.debug("{}: Forwarding {} BatchedModifications to leader {}", persistenceId(),
735 newModifications.size(), leader);
737 for (BatchedModifications bm : newModifications) {
738 leader.forward(bm, getContext());
744 private boolean failIfIsolatedLeader(final ActorRef sender) {
745 if (isIsolatedLeader()) {
746 sender.tell(new Failure(new NoShardLeaderException(String.format(
747 "Shard %s was the leader but has lost contact with all of its followers. Either all"
748 + " other follower nodes are down or this node is isolated by a network partition.",
749 persistenceId()))), getSelf());
756 protected boolean isIsolatedLeader() {
757 return getRaftState() == RaftState.IsolatedLeader;
760 @SuppressWarnings("checkstyle:IllegalCatch")
761 private void handleReadyLocalTransaction(final ReadyLocalTransaction message) {
762 LOG.debug("{}: handleReadyLocalTransaction for {}", persistenceId(), message.getTransactionId());
764 boolean isLeaderActive = isLeaderActive();
765 if (isLeader() && isLeaderActive) {
767 commitCoordinator.handleReadyLocalTransaction(message, getSender(), this);
768 } catch (Exception e) {
769 LOG.error("{}: Error handling ReadyLocalTransaction for Tx {}", persistenceId(),
770 message.getTransactionId(), e);
771 getSender().tell(new Failure(e), getSelf());
774 ActorSelection leader = getLeader();
775 if (!isLeaderActive || leader == null) {
776 messageRetrySupport.addMessageToRetry(message, getSender(),
777 "Could not process ready local transaction " + message.getTransactionId());
779 LOG.debug("{}: Forwarding ReadyLocalTransaction to leader {}", persistenceId(), leader);
780 message.setRemoteVersion(getCurrentBehavior().getLeaderPayloadVersion());
781 leader.forward(message, getContext());
786 private void handleForwardedReadyTransaction(final ForwardedReadyTransaction forwardedReady) {
787 LOG.debug("{}: handleForwardedReadyTransaction for {}", persistenceId(), forwardedReady.getTransactionId());
789 boolean isLeaderActive = isLeaderActive();
790 if (isLeader() && isLeaderActive) {
791 askProtocolEncountered(forwardedReady.getTransactionId());
792 commitCoordinator.handleForwardedReadyTransaction(forwardedReady, getSender(), this);
794 ActorSelection leader = getLeader();
795 if (!isLeaderActive || leader == null) {
796 messageRetrySupport.addMessageToRetry(forwardedReady, getSender(),
797 "Could not process forwarded ready transaction " + forwardedReady.getTransactionId());
799 LOG.debug("{}: Forwarding ForwardedReadyTransaction to leader {}", persistenceId(), leader);
801 ReadyLocalTransaction readyLocal = new ReadyLocalTransaction(forwardedReady.getTransactionId(),
802 forwardedReady.getTransaction().getSnapshot(), forwardedReady.isDoImmediateCommit(),
803 forwardedReady.getParticipatingShardNames());
804 readyLocal.setRemoteVersion(getCurrentBehavior().getLeaderPayloadVersion());
805 leader.forward(readyLocal, getContext());
810 private void handleAbortTransaction(final AbortTransaction abort) {
811 final TransactionIdentifier transactionId = abort.getTransactionId();
812 askProtocolEncountered(transactionId);
813 doAbortTransaction(transactionId, getSender());
816 void doAbortTransaction(final Identifier transactionID, final ActorRef sender) {
817 commitCoordinator.handleAbort(transactionID, sender, this);
820 private void handleCreateTransaction(final Object message) {
822 createTransaction(CreateTransaction.fromSerializable(message));
823 } else if (getLeader() != null) {
824 getLeader().forward(message, getContext());
826 getSender().tell(new Failure(new NoShardLeaderException(
827 "Could not create a shard transaction", persistenceId())), getSelf());
831 private void closeTransactionChain(final CloseTransactionChain closeTransactionChain) {
833 final LocalHistoryIdentifier id = closeTransactionChain.getIdentifier();
834 askProtocolEncountered(id.getClientId());
836 // FIXME: CONTROLLER-1628: stage purge once no transactions are present
837 store.closeTransactionChain(id, null);
838 store.purgeTransactionChain(id, null);
839 } else if (getLeader() != null) {
840 getLeader().forward(closeTransactionChain, getContext());
842 LOG.warn("{}: Could not close transaction {}", persistenceId(), closeTransactionChain.getIdentifier());
846 @SuppressWarnings("checkstyle:IllegalCatch")
847 private void createTransaction(final CreateTransaction createTransaction) {
848 askProtocolEncountered(createTransaction.getTransactionId());
851 if (TransactionType.fromInt(createTransaction.getTransactionType()) != TransactionType.READ_ONLY
852 && failIfIsolatedLeader(getSender())) {
856 ActorRef transactionActor = createTransaction(createTransaction.getTransactionType(),
857 createTransaction.getTransactionId());
859 getSender().tell(new CreateTransactionReply(Serialization.serializedActorPath(transactionActor),
860 createTransaction.getTransactionId(), createTransaction.getVersion()).toSerializable(), getSelf());
861 } catch (Exception e) {
862 getSender().tell(new Failure(e), getSelf());
866 private ActorRef createTransaction(final int transactionType, final TransactionIdentifier transactionId) {
867 LOG.debug("{}: Creating transaction : {} ", persistenceId(), transactionId);
868 return transactionActorFactory.newShardTransaction(TransactionType.fromInt(transactionType),
872 // Called on leader only
873 private void askProtocolEncountered(final TransactionIdentifier transactionId) {
874 askProtocolEncountered(transactionId.getHistoryId().getClientId());
877 // Called on leader only
878 private void askProtocolEncountered(final ClientIdentifier clientId) {
879 final LeaderFrontendState state = knownFrontends.get(clientId.getFrontendId());
880 if (state instanceof LeaderFrontendState.Enabled) {
881 LOG.debug("{}: encountered ask-based client {}, disabling transaction tracking", persistenceId(), clientId);
882 persistPayload(clientId, DisableTrackingPayload.create(clientId,
883 datastoreContext.getInitialPayloadSerializedBufferCapacity()), false);
887 private void updateSchemaContext(final UpdateSchemaContext message) {
888 updateSchemaContext(message.getSchemaContext());
892 void updateSchemaContext(final SchemaContext schemaContext) {
893 store.updateSchemaContext(schemaContext);
896 private boolean isMetricsCaptureEnabled() {
897 CommonConfig config = new CommonConfig(getContext().system().settings().config());
898 return config.isMetricCaptureEnabled();
903 public RaftActorSnapshotCohort getRaftActorSnapshotCohort() {
904 return snapshotCohort;
909 protected RaftActorRecoveryCohort getRaftActorRecoveryCohort() {
910 if (restoreFromSnapshot == null) {
911 return ShardRecoveryCoordinator.create(store, persistenceId(), LOG);
914 return ShardRecoveryCoordinator.forSnapshot(store, persistenceId(), LOG, restoreFromSnapshot.getSnapshot());
918 protected void onRecoveryComplete() {
919 restoreFromSnapshot = null;
921 //notify shard manager
922 getContext().parent().tell(new ActorInitialized(), getSelf());
924 // Being paranoid here - this method should only be called once but just in case...
925 if (txCommitTimeoutCheckSchedule == null) {
926 // Schedule a message to be periodically sent to check if the current in-progress
927 // transaction should be expired and aborted.
928 FiniteDuration period = Duration.create(transactionCommitTimeout / 3, TimeUnit.MILLISECONDS);
929 txCommitTimeoutCheckSchedule = getContext().system().scheduler().schedule(
930 period, period, getSelf(),
931 TX_COMMIT_TIMEOUT_CHECK_MESSAGE, getContext().dispatcher(), ActorRef.noSender());
936 protected void applyState(final ActorRef clientActor, final Identifier identifier, final Object data) {
937 if (data instanceof Payload) {
938 if (data instanceof DisableTrackingPayload) {
939 disableTracking((DisableTrackingPayload) data);
944 store.applyReplicatedPayload(identifier, (Payload)data);
945 } catch (DataValidationFailedException | IOException e) {
946 LOG.error("{}: Error applying replica {}", persistenceId(), identifier, e);
949 LOG.error("{}: Unknown state for {} received {}", persistenceId(), identifier, data);
954 protected void onStateChanged() {
955 boolean isLeader = isLeader();
956 boolean hasLeader = hasLeader();
957 treeChangeSupport.onLeadershipChange(isLeader, hasLeader);
959 // If this actor is no longer the leader close all the transaction chains
961 if (LOG.isDebugEnabled()) {
963 "{}: onStateChanged: Closing all transaction chains because shard {} is no longer the leader",
964 persistenceId(), getId());
968 store.purgeLeaderState();
971 if (hasLeader && !isIsolatedLeader()) {
972 messageRetrySupport.retryMessages();
977 protected void onLeaderChanged(final String oldLeader, final String newLeader) {
978 shardMBean.incrementLeadershipChangeCount();
982 if (!knownFrontends.isEmpty()) {
983 LOG.debug("{}: removing frontend state for {}", persistenceId(), knownFrontends.keySet());
984 knownFrontends = ImmutableMap.of();
987 requestMessageAssembler.close();
990 // No leader anywhere, nothing else to do
994 // Another leader was elected. If we were the previous leader and had pending transactions, convert
995 // them to transaction messages and send to the new leader.
996 ActorSelection leader = getLeader();
997 if (leader != null) {
998 Collection<?> messagesToForward = convertPendingTransactionsToMessages();
1000 if (!messagesToForward.isEmpty()) {
1001 LOG.debug("{}: Forwarding {} pending transaction messages to leader {}", persistenceId(),
1002 messagesToForward.size(), leader);
1004 for (Object message : messagesToForward) {
1005 LOG.debug("{}: Forwarding pending transaction message {}", persistenceId(), message);
1007 leader.tell(message, self());
1011 commitCoordinator.abortPendingTransactions("The transacton was aborted due to inflight leadership "
1012 + "change and the leader address isn't available.", this);
1015 // We have become the leader, we need to reconstruct frontend state
1016 knownFrontends = Verify.verifyNotNull(frontendMetadata.toLeaderState(this));
1017 LOG.debug("{}: became leader with frontend state for {}", persistenceId(), knownFrontends.keySet());
1020 if (!isIsolatedLeader()) {
1021 messageRetrySupport.retryMessages();
1026 * Clears all pending transactions and converts them to messages to be forwarded to a new leader.
1028 * @return the converted messages
1030 public Collection<?> convertPendingTransactionsToMessages() {
1031 return commitCoordinator.convertPendingTransactionsToMessages(
1032 datastoreContext.getShardBatchedModificationCount());
1036 protected void pauseLeader(final Runnable operation) {
1037 LOG.debug("{}: In pauseLeader, operation: {}", persistenceId(), operation);
1040 // Tell-based protocol can replay transaction state, so it is safe to blow it up when we are paused.
1041 knownFrontends.values().forEach(LeaderFrontendState::retire);
1042 knownFrontends = ImmutableMap.of();
1044 store.setRunOnPendingTransactionsComplete(operation);
1048 protected void unpauseLeader() {
1049 LOG.debug("{}: In unpauseLeader", persistenceId());
1052 store.setRunOnPendingTransactionsComplete(null);
1054 // Restore tell-based protocol state as if we were becoming the leader
1055 knownFrontends = Verify.verifyNotNull(frontendMetadata.toLeaderState(this));
1059 protected OnDemandRaftState.AbstractBuilder<?, ?> newOnDemandRaftStateBuilder() {
1060 return OnDemandShardState.newBuilder().treeChangeListenerActors(treeChangeSupport.getListenerActors())
1061 .commitCohortActors(store.getCohortActors());
1065 public String persistenceId() {
1070 ShardCommitCoordinator getCommitCoordinator() {
1071 return commitCoordinator;
1074 public DatastoreContext getDatastoreContext() {
1075 return datastoreContext;
1079 public ShardDataTree getDataStore() {
1084 ShardStats getShardMBean() {
1088 public static Builder builder() {
1089 return new Builder();
1092 public abstract static class AbstractBuilder<T extends AbstractBuilder<T, S>, S extends Shard> {
1093 private final Class<S> shardClass;
1094 private ShardIdentifier id;
1095 private Map<String, String> peerAddresses = Collections.emptyMap();
1096 private DatastoreContext datastoreContext;
1097 private SchemaContextProvider schemaContextProvider;
1098 private DatastoreSnapshot.ShardSnapshot restoreFromSnapshot;
1099 private DataTree dataTree;
1100 private volatile boolean sealed;
1102 protected AbstractBuilder(final Class<S> shardClass) {
1103 this.shardClass = shardClass;
1106 protected void checkSealed() {
1107 Preconditions.checkState(!sealed, "Builder isalready sealed - further modifications are not allowed");
1110 @SuppressWarnings("unchecked")
1115 public T id(final ShardIdentifier newId) {
1121 public T peerAddresses(final Map<String, String> newPeerAddresses) {
1123 this.peerAddresses = newPeerAddresses;
1127 public T datastoreContext(final DatastoreContext newDatastoreContext) {
1129 this.datastoreContext = newDatastoreContext;
1133 public T schemaContextProvider(final SchemaContextProvider newSchemaContextProvider) {
1135 this.schemaContextProvider = Preconditions.checkNotNull(newSchemaContextProvider);
1139 public T restoreFromSnapshot(final DatastoreSnapshot.ShardSnapshot newRestoreFromSnapshot) {
1141 this.restoreFromSnapshot = newRestoreFromSnapshot;
1145 public T dataTree(final DataTree newDataTree) {
1147 this.dataTree = newDataTree;
1151 public ShardIdentifier getId() {
1155 public Map<String, String> getPeerAddresses() {
1156 return peerAddresses;
1159 public DatastoreContext getDatastoreContext() {
1160 return datastoreContext;
1163 public SchemaContext getSchemaContext() {
1164 return Verify.verifyNotNull(schemaContextProvider.getSchemaContext());
1167 public DatastoreSnapshot.ShardSnapshot getRestoreFromSnapshot() {
1168 return restoreFromSnapshot;
1171 public DataTree getDataTree() {
1175 public TreeType getTreeType() {
1176 switch (datastoreContext.getLogicalStoreType()) {
1178 return TreeType.CONFIGURATION;
1180 return TreeType.OPERATIONAL;
1182 throw new IllegalStateException("Unhandled logical store type "
1183 + datastoreContext.getLogicalStoreType());
1187 protected void verify() {
1188 Preconditions.checkNotNull(id, "id should not be null");
1189 Preconditions.checkNotNull(peerAddresses, "peerAddresses should not be null");
1190 Preconditions.checkNotNull(datastoreContext, "dataStoreContext should not be null");
1191 Preconditions.checkNotNull(schemaContextProvider, "schemaContextProvider should not be null");
1194 public Props props() {
1197 return Props.create(shardClass, this);
1201 public static class Builder extends AbstractBuilder<Builder, Shard> {
1208 return Ticker.systemTicker();
1211 void scheduleNextPendingTransaction() {
1212 self().tell(RESUME_NEXT_PENDING_TRANSACTION, ActorRef.noSender());