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.messaging.MessageAssembler;
87 import org.opendaylight.controller.cluster.messaging.MessageSlicer;
88 import org.opendaylight.controller.cluster.messaging.SliceOptions;
89 import org.opendaylight.controller.cluster.notifications.LeaderStateChanged;
90 import org.opendaylight.controller.cluster.notifications.RegisterRoleChangeListener;
91 import org.opendaylight.controller.cluster.notifications.RoleChangeNotifier;
92 import org.opendaylight.controller.cluster.raft.LeadershipTransferFailedException;
93 import org.opendaylight.controller.cluster.raft.RaftActor;
94 import org.opendaylight.controller.cluster.raft.RaftActorRecoveryCohort;
95 import org.opendaylight.controller.cluster.raft.RaftActorSnapshotCohort;
96 import org.opendaylight.controller.cluster.raft.RaftState;
97 import org.opendaylight.controller.cluster.raft.base.messages.FollowerInitialSyncUpStatus;
98 import org.opendaylight.controller.cluster.raft.client.messages.OnDemandRaftState;
99 import org.opendaylight.controller.cluster.raft.messages.AppendEntriesReply;
100 import org.opendaylight.controller.cluster.raft.messages.RequestLeadership;
101 import org.opendaylight.controller.cluster.raft.messages.ServerRemoved;
102 import org.opendaylight.controller.cluster.raft.protobuff.client.messages.Payload;
103 import org.opendaylight.yangtools.concepts.Identifier;
104 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTree;
105 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataValidationFailedException;
106 import org.opendaylight.yangtools.yang.data.api.schema.tree.TreeType;
107 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
108 import org.opendaylight.yangtools.yang.model.api.SchemaContextProvider;
109 import scala.concurrent.duration.FiniteDuration;
112 * A Shard represents a portion of the logical data tree.
115 * Our Shard uses InMemoryDataTree as it's internal representation and delegates all requests it
117 public class Shard extends RaftActor {
120 static final Object TX_COMMIT_TIMEOUT_CHECK_MESSAGE = new Object() {
122 public String toString() {
123 return "txCommitTimeoutCheck";
128 static final Object GET_SHARD_MBEAN_MESSAGE = new Object() {
130 public String toString() {
131 return "getShardMBeanMessage";
135 static final Object RESUME_NEXT_PENDING_TRANSACTION = new Object() {
137 public String toString() {
138 return "resumeNextPendingTransaction";
142 // FIXME: shard names should be encapsulated in their own class and this should be exposed as a constant.
143 public static final String DEFAULT_NAME = "default";
145 private static final Collection<ABIVersion> SUPPORTED_ABIVERSIONS;
148 final ABIVersion[] values = ABIVersion.values();
149 final ABIVersion[] real = Arrays.copyOfRange(values, 1, values.length - 1);
150 SUPPORTED_ABIVERSIONS = ImmutableList.copyOf(real).reverse();
153 // FIXME: make this a dynamic property based on mailbox size and maximum number of clients
154 private static final int CLIENT_MAX_MESSAGES = 1000;
156 // The state of this Shard
157 private final ShardDataTree store;
159 /// The name of this shard
160 private final String name;
162 private final String shardName;
164 private final ShardStats shardMBean;
166 private final ShardDataTreeListenerInfoMXBeanImpl listenerInfoMXBean;
168 private DatastoreContext datastoreContext;
170 private final ShardCommitCoordinator commitCoordinator;
172 private long transactionCommitTimeout;
174 private Cancellable txCommitTimeoutCheckSchedule;
176 private final Optional<ActorRef> roleChangeNotifier;
178 private final MessageTracker appendEntriesReplyTracker;
180 private final ShardTransactionActorFactory transactionActorFactory;
182 private final ShardSnapshotCohort snapshotCohort;
184 private final DataTreeChangeListenerSupport treeChangeSupport = new DataTreeChangeListenerSupport(this);
186 private ShardSnapshot restoreFromSnapshot;
188 private final ShardTransactionMessageRetrySupport messageRetrySupport;
190 private final FrontendMetadata frontendMetadata;
191 private Map<FrontendIdentifier, LeaderFrontendState> knownFrontends = ImmutableMap.of();
192 private boolean paused;
194 private final MessageSlicer responseMessageSlicer;
195 private final Dispatchers dispatchers;
197 private final MessageAssembler requestMessageAssembler;
199 protected Shard(final AbstractBuilder<?, ?> builder) {
200 super(builder.getId().toString(), builder.getPeerAddresses(),
201 Optional.of(builder.getDatastoreContext().getShardRaftConfig()), DataStoreVersions.CURRENT_VERSION);
203 this.name = builder.getId().toString();
204 this.shardName = builder.getId().getShardName();
205 this.datastoreContext = builder.getDatastoreContext();
206 this.restoreFromSnapshot = builder.getRestoreFromSnapshot();
207 this.frontendMetadata = new FrontendMetadata(name);
209 setPersistence(datastoreContext.isPersistent());
211 LOG.info("Shard created : {}, persistent : {}", name, datastoreContext.isPersistent());
213 ShardDataTreeChangeListenerPublisherActorProxy treeChangeListenerPublisher =
214 new ShardDataTreeChangeListenerPublisherActorProxy(getContext(), name + "-DTCL-publisher", name);
215 if (builder.getDataTree() != null) {
216 store = new ShardDataTree(this, builder.getSchemaContext(), builder.getDataTree(),
217 treeChangeListenerPublisher, name, frontendMetadata);
219 store = new ShardDataTree(this, builder.getSchemaContext(), builder.getTreeType(),
220 builder.getDatastoreContext().getStoreRoot(), treeChangeListenerPublisher, name, frontendMetadata);
223 shardMBean = ShardMBeanFactory.getShardStatsMBean(name, datastoreContext.getDataStoreMXBeanType(), this);
225 if (isMetricsCaptureEnabled()) {
226 getContext().become(new MeteringBehavior(this));
229 commitCoordinator = new ShardCommitCoordinator(store, LOG, this.name);
231 setTransactionCommitTimeout();
233 // create a notifier actor for each cluster member
234 roleChangeNotifier = createRoleChangeNotifier(name);
236 appendEntriesReplyTracker = new MessageTracker(AppendEntriesReply.class,
237 getRaftActorContext().getConfigParams().getIsolatedCheckIntervalInMillis());
239 dispatchers = new Dispatchers(context().system().dispatchers());
240 transactionActorFactory = new ShardTransactionActorFactory(store, datastoreContext,
241 dispatchers.getDispatcherPath(Dispatchers.DispatcherType.Transaction),
242 self(), getContext(), shardMBean, builder.getId().getShardName());
244 snapshotCohort = ShardSnapshotCohort.create(getContext(), builder.getId().getMemberName(), store, LOG,
247 messageRetrySupport = new ShardTransactionMessageRetrySupport(this);
249 responseMessageSlicer = MessageSlicer.builder().logContext(this.name)
250 .messageSliceSize(datastoreContext.getMaximumMessageSliceSize())
251 .fileBackedStreamFactory(getRaftActorContext().getFileBackedOutputStreamFactory())
252 .expireStateAfterInactivity(2, TimeUnit.MINUTES).build();
254 requestMessageAssembler = MessageAssembler.builder().logContext(this.name)
255 .fileBackedStreamFactory(getRaftActorContext().getFileBackedOutputStreamFactory())
256 .assembledMessageCallback((message, sender) -> self().tell(message, sender))
257 .expireStateAfterInactivity(datastoreContext.getRequestTimeout(), TimeUnit.NANOSECONDS).build();
259 listenerInfoMXBean = new ShardDataTreeListenerInfoMXBeanImpl(name, datastoreContext.getDataStoreMXBeanType(),
261 listenerInfoMXBean.register();
264 private void setTransactionCommitTimeout() {
265 transactionCommitTimeout = TimeUnit.MILLISECONDS.convert(
266 datastoreContext.getShardTransactionCommitTimeoutInSeconds(), TimeUnit.SECONDS) / 2;
269 private Optional<ActorRef> createRoleChangeNotifier(final String shardId) {
270 ActorRef shardRoleChangeNotifier = this.getContext().actorOf(
271 RoleChangeNotifier.getProps(shardId), shardId + "-notifier");
272 return Optional.of(shardRoleChangeNotifier);
276 public void postStop() {
277 LOG.info("Stopping Shard {}", persistenceId());
281 messageRetrySupport.close();
283 if (txCommitTimeoutCheckSchedule != null) {
284 txCommitTimeoutCheckSchedule.cancel();
287 commitCoordinator.abortPendingTransactions("Transaction aborted due to shutdown.", this);
289 shardMBean.unregisterMBean();
290 listenerInfoMXBean.unregister();
294 protected void handleRecover(final Object message) {
295 LOG.debug("{}: onReceiveRecover: Received message {} from {}", persistenceId(), message.getClass(),
298 super.handleRecover(message);
299 if (LOG.isTraceEnabled()) {
300 appendEntriesReplyTracker.begin();
305 protected void handleNonRaftCommand(final Object message) {
306 try (MessageTracker.Context context = appendEntriesReplyTracker.received(message)) {
307 final Optional<Error> maybeError = context.error();
308 if (maybeError.isPresent()) {
309 LOG.trace("{} : AppendEntriesReply failed to arrive at the expected interval {}", persistenceId(),
313 store.resetTransactionBatch();
315 if (message instanceof RequestEnvelope) {
316 handleRequestEnvelope((RequestEnvelope)message);
317 } else if (MessageAssembler.isHandledMessage(message)) {
318 handleRequestAssemblerMessage(message);
319 } else if (message instanceof ConnectClientRequest) {
320 handleConnectClient((ConnectClientRequest)message);
321 } else if (CreateTransaction.isSerializedType(message)) {
322 handleCreateTransaction(message);
323 } else if (message instanceof BatchedModifications) {
324 handleBatchedModifications((BatchedModifications)message);
325 } else if (message instanceof ForwardedReadyTransaction) {
326 handleForwardedReadyTransaction((ForwardedReadyTransaction) message);
327 } else if (message instanceof ReadyLocalTransaction) {
328 handleReadyLocalTransaction((ReadyLocalTransaction)message);
329 } else if (CanCommitTransaction.isSerializedType(message)) {
330 handleCanCommitTransaction(CanCommitTransaction.fromSerializable(message));
331 } else if (CommitTransaction.isSerializedType(message)) {
332 handleCommitTransaction(CommitTransaction.fromSerializable(message));
333 } else if (AbortTransaction.isSerializedType(message)) {
334 handleAbortTransaction(AbortTransaction.fromSerializable(message));
335 } else if (CloseTransactionChain.isSerializedType(message)) {
336 closeTransactionChain(CloseTransactionChain.fromSerializable(message));
337 } else if (message instanceof RegisterDataTreeChangeListener) {
338 treeChangeSupport.onMessage((RegisterDataTreeChangeListener) message, isLeader(), hasLeader());
339 } else if (message instanceof UpdateSchemaContext) {
340 updateSchemaContext((UpdateSchemaContext) message);
341 } else if (message instanceof PeerAddressResolved) {
342 PeerAddressResolved resolved = (PeerAddressResolved) message;
343 setPeerAddress(resolved.getPeerId(), resolved.getPeerAddress());
344 } else if (TX_COMMIT_TIMEOUT_CHECK_MESSAGE.equals(message)) {
345 commitTimeoutCheck();
346 } else if (message instanceof DatastoreContext) {
347 onDatastoreContext((DatastoreContext)message);
348 } else if (message instanceof RegisterRoleChangeListener) {
349 roleChangeNotifier.get().forward(message, context());
350 } else if (message instanceof FollowerInitialSyncUpStatus) {
351 shardMBean.setFollowerInitialSyncStatus(((FollowerInitialSyncUpStatus) message).isInitialSyncDone());
352 context().parent().tell(message, self());
353 } else if (GET_SHARD_MBEAN_MESSAGE.equals(message)) {
354 sender().tell(getShardMBean(), self());
355 } else if (message instanceof GetShardDataTree) {
356 sender().tell(store.getDataTree(), self());
357 } else if (message instanceof ServerRemoved) {
358 context().parent().forward(message, context());
359 } else if (ShardTransactionMessageRetrySupport.TIMER_MESSAGE_CLASS.isInstance(message)) {
360 messageRetrySupport.onTimerMessage(message);
361 } else if (message instanceof DataTreeCohortActorRegistry.CohortRegistryCommand) {
362 store.processCohortRegistryCommand(getSender(),
363 (DataTreeCohortActorRegistry.CohortRegistryCommand) message);
364 } else if (message instanceof PersistAbortTransactionPayload) {
365 final TransactionIdentifier txId = ((PersistAbortTransactionPayload) message).getTransactionId();
366 persistPayload(txId, AbortTransactionPayload.create(
367 txId, datastoreContext.getInitialPayloadSerializedBufferCapacity()), true);
368 store.purgeTransaction(txId, null);
369 } else if (message instanceof MakeLeaderLocal) {
371 } else if (RESUME_NEXT_PENDING_TRANSACTION.equals(message)) {
372 store.resumeNextPendingTransaction();
373 } else if (!responseMessageSlicer.handleMessage(message)) {
374 super.handleNonRaftCommand(message);
379 private void handleRequestAssemblerMessage(final Object message) {
380 dispatchers.getDispatcher(DispatcherType.Serialization).execute(() -> {
381 JavaSerializer.currentSystem().value_$eq((ExtendedActorSystem) context().system());
382 requestMessageAssembler.handleMessage(message, self());
386 @SuppressWarnings("checkstyle:IllegalCatch")
387 private void handleRequestEnvelope(final RequestEnvelope envelope) {
388 final long now = ticker().read();
390 final RequestSuccess<?, ?> success = handleRequest(envelope, now);
391 if (success != null) {
392 final long executionTimeNanos = ticker().read() - now;
393 if (success instanceof SliceableMessage) {
394 dispatchers.getDispatcher(DispatcherType.Serialization).execute(() ->
395 responseMessageSlicer.slice(SliceOptions.builder().identifier(success.getTarget())
396 .message(envelope.newSuccessEnvelope(success, executionTimeNanos))
397 .sendTo(envelope.getMessage().getReplyTo()).replyTo(self())
398 .onFailureCallback(t -> LOG.warn("Error slicing response {}", success, t)).build()));
400 envelope.sendSuccess(success, executionTimeNanos);
403 } catch (RequestException e) {
404 LOG.debug("{}: request {} failed", persistenceId(), envelope, e);
405 envelope.sendFailure(e, ticker().read() - now);
406 } catch (Exception e) {
407 LOG.debug("{}: request {} caused failure", persistenceId(), envelope, e);
408 envelope.sendFailure(new RuntimeRequestException("Request failed to process", e),
409 ticker().read() - now);
413 private void commitTimeoutCheck() {
414 store.checkForExpiredTransactions(transactionCommitTimeout, this::updateAccess);
415 commitCoordinator.checkForExpiredTransactions(transactionCommitTimeout, this);
416 requestMessageAssembler.checkExpiredAssembledMessageState();
419 private Optional<Long> updateAccess(final SimpleShardDataTreeCohort cohort) {
420 final FrontendIdentifier frontend = cohort.getIdentifier().getHistoryId().getClientId().getFrontendId();
421 final LeaderFrontendState state = knownFrontends.get(frontend);
423 // Not tell-based protocol, do nothing
424 return Optional.absent();
427 if (isIsolatedLeader()) {
428 // We are isolated and no new request can come through until we emerge from it. We are still updating
429 // liveness of frontend when we see it attempting to communicate. Use the last access timer.
430 return Optional.of(state.getLastSeenTicks());
433 // If this frontend has freshly connected, give it some time to catch up before killing its transactions.
434 return Optional.of(state.getLastConnectTicks());
437 private void onMakeLeaderLocal() {
438 LOG.debug("{}: onMakeLeaderLocal received", persistenceId());
440 getSender().tell(new Status.Success(null), getSelf());
444 final ActorSelection leader = getLeader();
446 if (leader == null) {
447 // Leader is not present. The cluster is most likely trying to
448 // elect a leader and we should let that run its normal course
450 // TODO we can wait for the election to complete and retry the
451 // request. We can also let the caller retry by sending a flag
452 // in the response indicating the request is "reTryable".
453 getSender().tell(new Failure(
454 new LeadershipTransferFailedException("We cannot initiate leadership transfer to local node. "
455 + "Currently there is no leader for " + persistenceId())),
460 leader.tell(new RequestLeadership(getId(), getSender()), getSelf());
463 // Acquire our frontend tracking handle and verify generation matches
464 private @Nullable LeaderFrontendState findFrontend(final ClientIdentifier clientId) throws RequestException {
465 final LeaderFrontendState existing = knownFrontends.get(clientId.getFrontendId());
466 if (existing != null) {
467 final int cmp = Long.compareUnsigned(existing.getIdentifier().getGeneration(), clientId.getGeneration());
473 LOG.debug("{}: rejecting request from outdated client {}", persistenceId(), clientId);
474 throw new RetiredGenerationException(clientId.getGeneration(),
475 existing.getIdentifier().getGeneration());
478 LOG.info("{}: retiring state {}, outdated by request from client {}", persistenceId(), existing, clientId);
480 knownFrontends.remove(clientId.getFrontendId());
482 LOG.debug("{}: client {} is not yet known", persistenceId(), clientId);
488 private LeaderFrontendState getFrontend(final ClientIdentifier clientId) throws RequestException {
489 final LeaderFrontendState ret = findFrontend(clientId);
494 // TODO: a dedicated exception would be better, but this is technically true, too
495 throw new OutOfSequenceEnvelopeException(0);
498 private static @NonNull ABIVersion selectVersion(final ConnectClientRequest message) {
499 final Range<ABIVersion> clientRange = Range.closed(message.getMinVersion(), message.getMaxVersion());
500 for (ABIVersion v : SUPPORTED_ABIVERSIONS) {
501 if (clientRange.contains(v)) {
506 throw new IllegalArgumentException(String.format(
507 "No common version between backend versions %s and client versions %s", SUPPORTED_ABIVERSIONS,
511 @SuppressWarnings("checkstyle:IllegalCatch")
512 private void handleConnectClient(final ConnectClientRequest message) {
514 final ClientIdentifier clientId = message.getTarget();
515 final LeaderFrontendState existing = findFrontend(clientId);
516 if (existing != null) {
520 if (!isLeader() || !isLeaderActive()) {
521 LOG.info("{}: not currently leader, rejecting request {}. isLeader: {}, isLeaderActive: {},"
522 + "isLeadershipTransferInProgress: {}.",
523 persistenceId(), message, isLeader(), isLeaderActive(), isLeadershipTransferInProgress());
524 throw new NotLeaderException(getSelf());
527 final ABIVersion selectedVersion = selectVersion(message);
528 final LeaderFrontendState frontend;
529 if (existing == null) {
530 frontend = new LeaderFrontendState(persistenceId(), clientId, store);
531 knownFrontends.put(clientId.getFrontendId(), frontend);
532 LOG.debug("{}: created state {} for client {}", persistenceId(), frontend, clientId);
537 frontend.reconnect();
538 message.getReplyTo().tell(new ConnectClientSuccess(message.getTarget(), message.getSequence(), getSelf(),
539 ImmutableList.of(), store.getDataTree(), CLIENT_MAX_MESSAGES).toVersion(selectedVersion),
540 ActorRef.noSender());
541 } catch (RequestException | RuntimeException e) {
542 message.getReplyTo().tell(new Failure(e), ActorRef.noSender());
546 private @Nullable RequestSuccess<?, ?> handleRequest(final RequestEnvelope envelope, final long now)
547 throws RequestException {
548 // We are not the leader, hence we want to fail-fast.
549 if (!isLeader() || paused || !isLeaderActive()) {
550 LOG.debug("{}: not currently active leader, rejecting request {}. isLeader: {}, isLeaderActive: {},"
551 + "isLeadershipTransferInProgress: {}, paused: {}",
552 persistenceId(), envelope, isLeader(), isLeaderActive(), isLeadershipTransferInProgress(), paused);
553 throw new NotLeaderException(getSelf());
556 final Request<?, ?> request = envelope.getMessage();
557 if (request instanceof TransactionRequest) {
558 final TransactionRequest<?> txReq = (TransactionRequest<?>)request;
559 final ClientIdentifier clientId = txReq.getTarget().getHistoryId().getClientId();
560 return getFrontend(clientId).handleTransactionRequest(txReq, envelope, now);
561 } else if (request instanceof LocalHistoryRequest) {
562 final LocalHistoryRequest<?> lhReq = (LocalHistoryRequest<?>)request;
563 final ClientIdentifier clientId = lhReq.getTarget().getClientId();
564 return getFrontend(clientId).handleLocalHistoryRequest(lhReq, envelope, now);
566 LOG.warn("{}: rejecting unsupported request {}", persistenceId(), request);
567 throw new UnsupportedRequestException(request);
571 private boolean hasLeader() {
572 return getLeaderId() != null;
575 public int getPendingTxCommitQueueSize() {
576 return store.getQueueSize();
579 public int getCohortCacheSize() {
580 return commitCoordinator.getCohortCacheSize();
584 protected Optional<ActorRef> getRoleChangeNotifier() {
585 return roleChangeNotifier;
588 String getShardName() {
593 protected LeaderStateChanged newLeaderStateChanged(final String memberId, final String leaderId,
594 final short leaderPayloadVersion) {
595 return isLeader() ? new ShardLeaderStateChanged(memberId, leaderId, store.getDataTree(), leaderPayloadVersion)
596 : new ShardLeaderStateChanged(memberId, leaderId, leaderPayloadVersion);
599 protected void onDatastoreContext(final DatastoreContext context) {
600 datastoreContext = context;
602 setTransactionCommitTimeout();
604 setPersistence(datastoreContext.isPersistent());
606 updateConfigParams(datastoreContext.getShardRaftConfig());
609 // applyState() will be invoked once consensus is reached on the payload
610 void persistPayload(final Identifier id, final Payload payload, final boolean batchHint) {
611 boolean canSkipPayload = !hasFollowers() && !persistence().isRecoveryApplicable();
612 if (canSkipPayload) {
613 applyState(self(), id, payload);
615 // We are faking the sender
616 persistData(self(), id, payload, batchHint);
620 private void handleCommitTransaction(final CommitTransaction commit) {
622 commitCoordinator.handleCommit(commit.getTransactionId(), getSender(), this);
624 ActorSelection leader = getLeader();
625 if (leader == null) {
626 messageRetrySupport.addMessageToRetry(commit, getSender(),
627 "Could not commit transaction " + commit.getTransactionId());
629 LOG.debug("{}: Forwarding CommitTransaction to leader {}", persistenceId(), leader);
630 leader.forward(commit, getContext());
635 private void handleCanCommitTransaction(final CanCommitTransaction canCommit) {
636 LOG.debug("{}: Can committing transaction {}", persistenceId(), canCommit.getTransactionId());
639 commitCoordinator.handleCanCommit(canCommit.getTransactionId(), getSender(), this);
641 ActorSelection leader = getLeader();
642 if (leader == null) {
643 messageRetrySupport.addMessageToRetry(canCommit, getSender(),
644 "Could not canCommit transaction " + canCommit.getTransactionId());
646 LOG.debug("{}: Forwarding CanCommitTransaction to leader {}", persistenceId(), leader);
647 leader.forward(canCommit, getContext());
652 @SuppressWarnings("checkstyle:IllegalCatch")
653 protected void handleBatchedModificationsLocal(final BatchedModifications batched, final ActorRef sender) {
655 commitCoordinator.handleBatchedModifications(batched, sender, this);
656 } catch (Exception e) {
657 LOG.error("{}: Error handling BatchedModifications for Tx {}", persistenceId(),
658 batched.getTransactionId(), e);
659 sender.tell(new Failure(e), getSelf());
663 private void handleBatchedModifications(final BatchedModifications batched) {
664 // This message is sent to prepare the modifications transaction directly on the Shard as an
665 // optimization to avoid the extra overhead of a separate ShardTransaction actor. On the last
666 // BatchedModifications message, the caller sets the ready flag in the message indicating
667 // modifications are complete. The reply contains the cohort actor path (this actor) for the caller
668 // to initiate the 3-phase commit. This also avoids the overhead of sending an additional
669 // ReadyTransaction message.
671 // If we're not the leader then forward to the leader. This is a safety measure - we shouldn't
672 // normally get here if we're not the leader as the front-end (TransactionProxy) should determine
673 // the primary/leader shard. However with timing and caching on the front-end, there's a small
674 // window where it could have a stale leader during leadership transitions.
676 boolean isLeaderActive = isLeaderActive();
677 if (isLeader() && isLeaderActive) {
678 handleBatchedModificationsLocal(batched, getSender());
680 ActorSelection leader = getLeader();
681 if (!isLeaderActive || leader == null) {
682 messageRetrySupport.addMessageToRetry(batched, getSender(),
683 "Could not process BatchedModifications " + batched.getTransactionId());
685 // If this is not the first batch and leadership changed in between batched messages,
686 // we need to reconstruct previous BatchedModifications from the transaction
687 // DataTreeModification, honoring the max batched modification count, and forward all the
688 // previous BatchedModifications to the new leader.
689 Collection<BatchedModifications> newModifications = commitCoordinator
690 .createForwardedBatchedModifications(batched,
691 datastoreContext.getShardBatchedModificationCount());
693 LOG.debug("{}: Forwarding {} BatchedModifications to leader {}", persistenceId(),
694 newModifications.size(), leader);
696 for (BatchedModifications bm : newModifications) {
697 leader.forward(bm, getContext());
703 private boolean failIfIsolatedLeader(final ActorRef sender) {
704 if (isIsolatedLeader()) {
705 sender.tell(new Failure(new NoShardLeaderException(String.format(
706 "Shard %s was the leader but has lost contact with all of its followers. Either all"
707 + " other follower nodes are down or this node is isolated by a network partition.",
708 persistenceId()))), getSelf());
715 protected boolean isIsolatedLeader() {
716 return getRaftState() == RaftState.IsolatedLeader;
719 @SuppressWarnings("checkstyle:IllegalCatch")
720 private void handleReadyLocalTransaction(final ReadyLocalTransaction message) {
721 LOG.debug("{}: handleReadyLocalTransaction for {}", persistenceId(), message.getTransactionId());
723 boolean isLeaderActive = isLeaderActive();
724 if (isLeader() && isLeaderActive) {
726 commitCoordinator.handleReadyLocalTransaction(message, getSender(), this);
727 } catch (Exception e) {
728 LOG.error("{}: Error handling ReadyLocalTransaction for Tx {}", persistenceId(),
729 message.getTransactionId(), e);
730 getSender().tell(new Failure(e), getSelf());
733 ActorSelection leader = getLeader();
734 if (!isLeaderActive || leader == null) {
735 messageRetrySupport.addMessageToRetry(message, getSender(),
736 "Could not process ready local transaction " + message.getTransactionId());
738 LOG.debug("{}: Forwarding ReadyLocalTransaction to leader {}", persistenceId(), leader);
739 message.setRemoteVersion(getCurrentBehavior().getLeaderPayloadVersion());
740 leader.forward(message, getContext());
745 private void handleForwardedReadyTransaction(final ForwardedReadyTransaction forwardedReady) {
746 LOG.debug("{}: handleForwardedReadyTransaction for {}", persistenceId(), forwardedReady.getTransactionId());
748 boolean isLeaderActive = isLeaderActive();
749 if (isLeader() && isLeaderActive) {
750 commitCoordinator.handleForwardedReadyTransaction(forwardedReady, getSender(), this);
752 ActorSelection leader = getLeader();
753 if (!isLeaderActive || leader == null) {
754 messageRetrySupport.addMessageToRetry(forwardedReady, getSender(),
755 "Could not process forwarded ready transaction " + forwardedReady.getTransactionId());
757 LOG.debug("{}: Forwarding ForwardedReadyTransaction to leader {}", persistenceId(), leader);
759 ReadyLocalTransaction readyLocal = new ReadyLocalTransaction(forwardedReady.getTransactionId(),
760 forwardedReady.getTransaction().getSnapshot(), forwardedReady.isDoImmediateCommit(),
761 forwardedReady.getParticipatingShardNames());
762 readyLocal.setRemoteVersion(getCurrentBehavior().getLeaderPayloadVersion());
763 leader.forward(readyLocal, getContext());
768 private void handleAbortTransaction(final AbortTransaction abort) {
769 doAbortTransaction(abort.getTransactionId(), getSender());
772 void doAbortTransaction(final Identifier transactionID, final ActorRef sender) {
773 commitCoordinator.handleAbort(transactionID, sender, this);
776 private void handleCreateTransaction(final Object message) {
778 createTransaction(CreateTransaction.fromSerializable(message));
779 } else if (getLeader() != null) {
780 getLeader().forward(message, getContext());
782 getSender().tell(new Failure(new NoShardLeaderException(
783 "Could not create a shard transaction", persistenceId())), getSelf());
787 private void closeTransactionChain(final CloseTransactionChain closeTransactionChain) {
789 final LocalHistoryIdentifier id = closeTransactionChain.getIdentifier();
790 // FIXME: CONTROLLER-1628: stage purge once no transactions are present
791 store.closeTransactionChain(id, null);
792 store.purgeTransactionChain(id, null);
793 } else if (getLeader() != null) {
794 getLeader().forward(closeTransactionChain, getContext());
796 LOG.warn("{}: Could not close transaction {}", persistenceId(), closeTransactionChain.getIdentifier());
800 @SuppressWarnings("checkstyle:IllegalCatch")
801 private void createTransaction(final CreateTransaction createTransaction) {
803 if (TransactionType.fromInt(createTransaction.getTransactionType()) != TransactionType.READ_ONLY
804 && failIfIsolatedLeader(getSender())) {
808 ActorRef transactionActor = createTransaction(createTransaction.getTransactionType(),
809 createTransaction.getTransactionId());
811 getSender().tell(new CreateTransactionReply(Serialization.serializedActorPath(transactionActor),
812 createTransaction.getTransactionId(), createTransaction.getVersion()).toSerializable(), getSelf());
813 } catch (Exception e) {
814 getSender().tell(new Failure(e), getSelf());
818 private ActorRef createTransaction(final int transactionType, final TransactionIdentifier transactionId) {
819 LOG.debug("{}: Creating transaction : {} ", persistenceId(), transactionId);
820 return transactionActorFactory.newShardTransaction(TransactionType.fromInt(transactionType),
824 private void updateSchemaContext(final UpdateSchemaContext message) {
825 updateSchemaContext(message.getSchemaContext());
829 void updateSchemaContext(final SchemaContext schemaContext) {
830 store.updateSchemaContext(schemaContext);
833 private boolean isMetricsCaptureEnabled() {
834 CommonConfig config = new CommonConfig(getContext().system().settings().config());
835 return config.isMetricCaptureEnabled();
840 public RaftActorSnapshotCohort getRaftActorSnapshotCohort() {
841 return snapshotCohort;
845 protected RaftActorRecoveryCohort getRaftActorRecoveryCohort() {
846 if (restoreFromSnapshot == null) {
847 return ShardRecoveryCoordinator.create(store, persistenceId(), LOG);
850 return ShardRecoveryCoordinator.forSnapshot(store, persistenceId(), LOG, restoreFromSnapshot.getSnapshot());
854 protected void onRecoveryComplete() {
855 restoreFromSnapshot = null;
857 //notify shard manager
858 getContext().parent().tell(new ActorInitialized(), getSelf());
860 // Being paranoid here - this method should only be called once but just in case...
861 if (txCommitTimeoutCheckSchedule == null) {
862 // Schedule a message to be periodically sent to check if the current in-progress
863 // transaction should be expired and aborted.
864 FiniteDuration period = FiniteDuration.create(transactionCommitTimeout / 3, TimeUnit.MILLISECONDS);
865 txCommitTimeoutCheckSchedule = getContext().system().scheduler().schedule(
866 period, period, getSelf(),
867 TX_COMMIT_TIMEOUT_CHECK_MESSAGE, getContext().dispatcher(), ActorRef.noSender());
872 protected void applyState(final ActorRef clientActor, final Identifier identifier, final Object data) {
873 if (data instanceof Payload) {
875 store.applyReplicatedPayload(identifier, (Payload)data);
876 } catch (DataValidationFailedException | IOException e) {
877 LOG.error("{}: Error applying replica {}", persistenceId(), identifier, e);
880 LOG.error("{}: Unknown state for {} received {}", persistenceId(), identifier, data);
885 protected void onStateChanged() {
886 boolean isLeader = isLeader();
887 boolean hasLeader = hasLeader();
888 treeChangeSupport.onLeadershipChange(isLeader, hasLeader);
890 // If this actor is no longer the leader close all the transaction chains
892 if (LOG.isDebugEnabled()) {
894 "{}: onStateChanged: Closing all transaction chains because shard {} is no longer the leader",
895 persistenceId(), getId());
899 store.purgeLeaderState();
902 if (hasLeader && !isIsolatedLeader()) {
903 messageRetrySupport.retryMessages();
908 protected void onLeaderChanged(final String oldLeader, final String newLeader) {
909 shardMBean.incrementLeadershipChangeCount();
913 if (!knownFrontends.isEmpty()) {
914 LOG.debug("{}: removing frontend state for {}", persistenceId(), knownFrontends.keySet());
915 knownFrontends = ImmutableMap.of();
918 requestMessageAssembler.close();
921 // No leader anywhere, nothing else to do
925 // Another leader was elected. If we were the previous leader and had pending transactions, convert
926 // them to transaction messages and send to the new leader.
927 ActorSelection leader = getLeader();
928 if (leader != null) {
929 Collection<?> messagesToForward = convertPendingTransactionsToMessages();
931 if (!messagesToForward.isEmpty()) {
932 LOG.debug("{}: Forwarding {} pending transaction messages to leader {}", persistenceId(),
933 messagesToForward.size(), leader);
935 for (Object message : messagesToForward) {
936 LOG.debug("{}: Forwarding pending transaction message {}", persistenceId(), message);
938 leader.tell(message, self());
942 commitCoordinator.abortPendingTransactions("The transacton was aborted due to inflight leadership "
943 + "change and the leader address isn't available.", this);
946 // We have become the leader, we need to reconstruct frontend state
947 knownFrontends = Verify.verifyNotNull(frontendMetadata.toLeaderState(this));
948 LOG.debug("{}: became leader with frontend state for {}", persistenceId(), knownFrontends.keySet());
951 if (!isIsolatedLeader()) {
952 messageRetrySupport.retryMessages();
957 * Clears all pending transactions and converts them to messages to be forwarded to a new leader.
959 * @return the converted messages
961 public Collection<?> convertPendingTransactionsToMessages() {
962 return commitCoordinator.convertPendingTransactionsToMessages(
963 datastoreContext.getShardBatchedModificationCount());
967 protected void pauseLeader(final Runnable operation) {
968 LOG.debug("{}: In pauseLeader, operation: {}", persistenceId(), operation);
971 // Tell-based protocol can replay transaction state, so it is safe to blow it up when we are paused.
972 knownFrontends.values().forEach(LeaderFrontendState::retire);
973 knownFrontends = ImmutableMap.of();
975 store.setRunOnPendingTransactionsComplete(operation);
979 protected void unpauseLeader() {
980 LOG.debug("{}: In unpauseLeader", persistenceId());
983 store.setRunOnPendingTransactionsComplete(null);
985 // Restore tell-based protocol state as if we were becoming the leader
986 knownFrontends = Verify.verifyNotNull(frontendMetadata.toLeaderState(this));
990 protected OnDemandRaftState.AbstractBuilder<?, ?> newOnDemandRaftStateBuilder() {
991 return OnDemandShardState.newBuilder().treeChangeListenerActors(treeChangeSupport.getListenerActors())
992 .commitCohortActors(store.getCohortActors());
996 public String persistenceId() {
1001 ShardCommitCoordinator getCommitCoordinator() {
1002 return commitCoordinator;
1005 public DatastoreContext getDatastoreContext() {
1006 return datastoreContext;
1010 public ShardDataTree getDataStore() {
1015 ShardStats getShardMBean() {
1019 public static Builder builder() {
1020 return new Builder();
1023 public abstract static class AbstractBuilder<T extends AbstractBuilder<T, S>, S extends Shard> {
1024 private final Class<S> shardClass;
1025 private ShardIdentifier id;
1026 private Map<String, String> peerAddresses = Collections.emptyMap();
1027 private DatastoreContext datastoreContext;
1028 private SchemaContextProvider schemaContextProvider;
1029 private DatastoreSnapshot.ShardSnapshot restoreFromSnapshot;
1030 private DataTree dataTree;
1031 private volatile boolean sealed;
1033 protected AbstractBuilder(final Class<S> shardClass) {
1034 this.shardClass = shardClass;
1037 protected void checkSealed() {
1038 Preconditions.checkState(!sealed, "Builder isalready sealed - further modifications are not allowed");
1041 @SuppressWarnings("unchecked")
1046 public T id(final ShardIdentifier newId) {
1052 public T peerAddresses(final Map<String, String> newPeerAddresses) {
1054 this.peerAddresses = newPeerAddresses;
1058 public T datastoreContext(final DatastoreContext newDatastoreContext) {
1060 this.datastoreContext = newDatastoreContext;
1064 public T schemaContextProvider(final SchemaContextProvider newSchemaContextProvider) {
1066 this.schemaContextProvider = Preconditions.checkNotNull(newSchemaContextProvider);
1070 public T restoreFromSnapshot(final DatastoreSnapshot.ShardSnapshot newRestoreFromSnapshot) {
1072 this.restoreFromSnapshot = newRestoreFromSnapshot;
1076 public T dataTree(final DataTree newDataTree) {
1078 this.dataTree = newDataTree;
1082 public ShardIdentifier getId() {
1086 public Map<String, String> getPeerAddresses() {
1087 return peerAddresses;
1090 public DatastoreContext getDatastoreContext() {
1091 return datastoreContext;
1094 public SchemaContext getSchemaContext() {
1095 return Verify.verifyNotNull(schemaContextProvider.getSchemaContext());
1098 public DatastoreSnapshot.ShardSnapshot getRestoreFromSnapshot() {
1099 return restoreFromSnapshot;
1102 public DataTree getDataTree() {
1106 public TreeType getTreeType() {
1107 switch (datastoreContext.getLogicalStoreType()) {
1109 return TreeType.CONFIGURATION;
1111 return TreeType.OPERATIONAL;
1113 throw new IllegalStateException("Unhandled logical store type "
1114 + datastoreContext.getLogicalStoreType());
1118 protected void verify() {
1119 Preconditions.checkNotNull(id, "id should not be null");
1120 Preconditions.checkNotNull(peerAddresses, "peerAddresses should not be null");
1121 Preconditions.checkNotNull(datastoreContext, "dataStoreContext should not be null");
1122 Preconditions.checkNotNull(schemaContextProvider, "schemaContextProvider should not be null");
1125 public Props props() {
1128 return Props.create(shardClass, this);
1132 public static class Builder extends AbstractBuilder<Builder, Shard> {
1139 return Ticker.systemTicker();
1142 void scheduleNextPendingTransaction() {
1143 self().tell(RESUME_NEXT_PENDING_TRANSACTION, ActorRef.noSender());