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.Props;
15 import akka.actor.Status;
16 import akka.actor.Status.Failure;
17 import akka.serialization.Serialization;
18 import com.google.common.annotations.VisibleForTesting;
19 import com.google.common.base.Optional;
20 import com.google.common.base.Preconditions;
21 import com.google.common.base.Ticker;
22 import com.google.common.base.Verify;
23 import com.google.common.collect.ImmutableList;
24 import com.google.common.collect.ImmutableMap;
25 import com.google.common.collect.Range;
26 import java.io.IOException;
27 import java.util.Arrays;
28 import java.util.Collection;
29 import java.util.Collections;
31 import java.util.concurrent.TimeUnit;
32 import javax.annotation.Nonnull;
33 import javax.annotation.Nullable;
34 import org.opendaylight.controller.cluster.access.ABIVersion;
35 import org.opendaylight.controller.cluster.access.commands.ConnectClientRequest;
36 import org.opendaylight.controller.cluster.access.commands.ConnectClientSuccess;
37 import org.opendaylight.controller.cluster.access.commands.LocalHistoryRequest;
38 import org.opendaylight.controller.cluster.access.commands.NotLeaderException;
39 import org.opendaylight.controller.cluster.access.commands.TransactionRequest;
40 import org.opendaylight.controller.cluster.access.concepts.ClientIdentifier;
41 import org.opendaylight.controller.cluster.access.concepts.FrontendIdentifier;
42 import org.opendaylight.controller.cluster.access.concepts.LocalHistoryIdentifier;
43 import org.opendaylight.controller.cluster.access.concepts.Request;
44 import org.opendaylight.controller.cluster.access.concepts.RequestEnvelope;
45 import org.opendaylight.controller.cluster.access.concepts.RequestException;
46 import org.opendaylight.controller.cluster.access.concepts.RequestSuccess;
47 import org.opendaylight.controller.cluster.access.concepts.RetiredGenerationException;
48 import org.opendaylight.controller.cluster.access.concepts.RuntimeRequestException;
49 import org.opendaylight.controller.cluster.access.concepts.TransactionIdentifier;
50 import org.opendaylight.controller.cluster.access.concepts.UnsupportedRequestException;
51 import org.opendaylight.controller.cluster.common.actor.CommonConfig;
52 import org.opendaylight.controller.cluster.common.actor.MessageTracker;
53 import org.opendaylight.controller.cluster.common.actor.MessageTracker.Error;
54 import org.opendaylight.controller.cluster.common.actor.MeteringBehavior;
55 import org.opendaylight.controller.cluster.datastore.exceptions.NoShardLeaderException;
56 import org.opendaylight.controller.cluster.datastore.identifiers.ShardIdentifier;
57 import org.opendaylight.controller.cluster.datastore.jmx.mbeans.shard.ShardMBeanFactory;
58 import org.opendaylight.controller.cluster.datastore.jmx.mbeans.shard.ShardStats;
59 import org.opendaylight.controller.cluster.datastore.messages.AbortTransaction;
60 import org.opendaylight.controller.cluster.datastore.messages.ActorInitialized;
61 import org.opendaylight.controller.cluster.datastore.messages.BatchedModifications;
62 import org.opendaylight.controller.cluster.datastore.messages.CanCommitTransaction;
63 import org.opendaylight.controller.cluster.datastore.messages.CloseTransactionChain;
64 import org.opendaylight.controller.cluster.datastore.messages.CommitTransaction;
65 import org.opendaylight.controller.cluster.datastore.messages.CreateTransaction;
66 import org.opendaylight.controller.cluster.datastore.messages.CreateTransactionReply;
67 import org.opendaylight.controller.cluster.datastore.messages.ForwardedReadyTransaction;
68 import org.opendaylight.controller.cluster.datastore.messages.GetShardDataTree;
69 import org.opendaylight.controller.cluster.datastore.messages.MakeLeaderLocal;
70 import org.opendaylight.controller.cluster.datastore.messages.OnDemandShardState;
71 import org.opendaylight.controller.cluster.datastore.messages.PeerAddressResolved;
72 import org.opendaylight.controller.cluster.datastore.messages.PersistAbortTransactionPayload;
73 import org.opendaylight.controller.cluster.datastore.messages.ReadyLocalTransaction;
74 import org.opendaylight.controller.cluster.datastore.messages.RegisterChangeListener;
75 import org.opendaylight.controller.cluster.datastore.messages.RegisterDataTreeChangeListener;
76 import org.opendaylight.controller.cluster.datastore.messages.ShardLeaderStateChanged;
77 import org.opendaylight.controller.cluster.datastore.messages.UpdateSchemaContext;
78 import org.opendaylight.controller.cluster.datastore.persisted.AbortTransactionPayload;
79 import org.opendaylight.controller.cluster.datastore.persisted.DatastoreSnapshot;
80 import org.opendaylight.controller.cluster.datastore.persisted.DatastoreSnapshot.ShardSnapshot;
81 import org.opendaylight.controller.cluster.datastore.utils.Dispatchers;
82 import org.opendaylight.controller.cluster.notifications.LeaderStateChanged;
83 import org.opendaylight.controller.cluster.notifications.RegisterRoleChangeListener;
84 import org.opendaylight.controller.cluster.notifications.RoleChangeNotifier;
85 import org.opendaylight.controller.cluster.raft.LeadershipTransferFailedException;
86 import org.opendaylight.controller.cluster.raft.RaftActor;
87 import org.opendaylight.controller.cluster.raft.RaftActorRecoveryCohort;
88 import org.opendaylight.controller.cluster.raft.RaftActorSnapshotCohort;
89 import org.opendaylight.controller.cluster.raft.RaftState;
90 import org.opendaylight.controller.cluster.raft.base.messages.FollowerInitialSyncUpStatus;
91 import org.opendaylight.controller.cluster.raft.client.messages.OnDemandRaftState;
92 import org.opendaylight.controller.cluster.raft.messages.AppendEntriesReply;
93 import org.opendaylight.controller.cluster.raft.messages.RequestLeadership;
94 import org.opendaylight.controller.cluster.raft.messages.ServerRemoved;
95 import org.opendaylight.controller.cluster.raft.protobuff.client.messages.Payload;
96 import org.opendaylight.yangtools.concepts.Identifier;
97 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataValidationFailedException;
98 import org.opendaylight.yangtools.yang.data.api.schema.tree.TipProducingDataTree;
99 import org.opendaylight.yangtools.yang.data.api.schema.tree.TreeType;
100 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
101 import scala.concurrent.duration.Duration;
102 import scala.concurrent.duration.FiniteDuration;
105 * A Shard represents a portion of the logical data tree.
108 * Our Shard uses InMemoryDataTree as it's internal representation and delegates all requests it
110 public class Shard extends RaftActor {
113 static final Object TX_COMMIT_TIMEOUT_CHECK_MESSAGE = new Object() {
115 public String toString() {
116 return "txCommitTimeoutCheck";
121 static final Object GET_SHARD_MBEAN_MESSAGE = new Object() {
123 public String toString() {
124 return "getShardMBeanMessage";
128 // FIXME: shard names should be encapsulated in their own class and this should be exposed as a constant.
129 public static final String DEFAULT_NAME = "default";
131 private static final Collection<ABIVersion> SUPPORTED_ABIVERSIONS;
134 final ABIVersion[] values = ABIVersion.values();
135 final ABIVersion[] real = Arrays.copyOfRange(values, 1, values.length - 1);
136 SUPPORTED_ABIVERSIONS = ImmutableList.copyOf(real).reverse();
139 // FIXME: make this a dynamic property based on mailbox size and maximum number of clients
140 private static final int CLIENT_MAX_MESSAGES = 1000;
142 // The state of this Shard
143 private final ShardDataTree store;
145 /// The name of this shard
146 private final String name;
148 private final ShardStats shardMBean;
150 private DatastoreContext datastoreContext;
152 private final ShardCommitCoordinator commitCoordinator;
154 private long transactionCommitTimeout;
156 private Cancellable txCommitTimeoutCheckSchedule;
158 private final Optional<ActorRef> roleChangeNotifier;
160 private final MessageTracker appendEntriesReplyTracker;
162 private final ShardTransactionActorFactory transactionActorFactory;
164 private final ShardSnapshotCohort snapshotCohort;
166 private final DataTreeChangeListenerSupport treeChangeSupport = new DataTreeChangeListenerSupport(this);
167 private final DataChangeListenerSupport changeSupport = new DataChangeListenerSupport(this);
170 private ShardSnapshot restoreFromSnapshot;
172 private final ShardTransactionMessageRetrySupport messageRetrySupport;
174 private final FrontendMetadata frontendMetadata;
175 private Map<FrontendIdentifier, LeaderFrontendState> knownFrontends = ImmutableMap.of();
177 protected Shard(final AbstractBuilder<?, ?> builder) {
178 super(builder.getId().toString(), builder.getPeerAddresses(),
179 Optional.of(builder.getDatastoreContext().getShardRaftConfig()), DataStoreVersions.CURRENT_VERSION);
181 this.name = builder.getId().toString();
182 this.datastoreContext = builder.getDatastoreContext();
183 this.restoreFromSnapshot = builder.getRestoreFromSnapshot();
184 this.frontendMetadata = new FrontendMetadata(name);
186 setPersistence(datastoreContext.isPersistent());
188 LOG.info("Shard created : {}, persistent : {}", name, datastoreContext.isPersistent());
190 ShardDataTreeChangeListenerPublisherActorProxy treeChangeListenerPublisher =
191 new ShardDataTreeChangeListenerPublisherActorProxy(getContext(), name + "-DTCL-publisher", name);
192 ShardDataChangeListenerPublisherActorProxy dataChangeListenerPublisher =
193 new ShardDataChangeListenerPublisherActorProxy(getContext(), name + "-DCL-publisher", name);
194 if (builder.getDataTree() != null) {
195 store = new ShardDataTree(this, builder.getSchemaContext(), builder.getDataTree(),
196 treeChangeListenerPublisher, dataChangeListenerPublisher, name, frontendMetadata);
198 store = new ShardDataTree(this, builder.getSchemaContext(), builder.getTreeType(),
199 builder.getDatastoreContext().getStoreRoot(), treeChangeListenerPublisher,
200 dataChangeListenerPublisher, name, frontendMetadata);
203 shardMBean = ShardMBeanFactory.getShardStatsMBean(name, datastoreContext.getDataStoreMXBeanType(), this);
205 if (isMetricsCaptureEnabled()) {
206 getContext().become(new MeteringBehavior(this));
209 commitCoordinator = new ShardCommitCoordinator(store, LOG, this.name);
211 setTransactionCommitTimeout();
213 // create a notifier actor for each cluster member
214 roleChangeNotifier = createRoleChangeNotifier(name);
216 appendEntriesReplyTracker = new MessageTracker(AppendEntriesReply.class,
217 getRaftActorContext().getConfigParams().getIsolatedCheckIntervalInMillis());
219 transactionActorFactory = new ShardTransactionActorFactory(store, datastoreContext,
220 new Dispatchers(context().system().dispatchers()).getDispatcherPath(Dispatchers.DispatcherType.Transaction),
221 self(), getContext(), shardMBean, builder.getId().getShardName());
223 snapshotCohort = ShardSnapshotCohort.create(getContext(), builder.getId().getMemberName(), store, LOG,
226 messageRetrySupport = new ShardTransactionMessageRetrySupport(this);
229 private void setTransactionCommitTimeout() {
230 transactionCommitTimeout = TimeUnit.MILLISECONDS.convert(
231 datastoreContext.getShardTransactionCommitTimeoutInSeconds(), TimeUnit.SECONDS) / 2;
234 private Optional<ActorRef> createRoleChangeNotifier(final String shardId) {
235 ActorRef shardRoleChangeNotifier = this.getContext().actorOf(
236 RoleChangeNotifier.getProps(shardId), shardId + "-notifier");
237 return Optional.of(shardRoleChangeNotifier);
241 public void postStop() {
242 LOG.info("Stopping Shard {}", persistenceId());
246 messageRetrySupport.close();
248 if (txCommitTimeoutCheckSchedule != null) {
249 txCommitTimeoutCheckSchedule.cancel();
252 commitCoordinator.abortPendingTransactions("Transaction aborted due to shutdown.", this);
254 shardMBean.unregisterMBean();
258 protected void handleRecover(final Object message) {
259 LOG.debug("{}: onReceiveRecover: Received message {} from {}", persistenceId(), message.getClass(),
262 super.handleRecover(message);
263 if (LOG.isTraceEnabled()) {
264 appendEntriesReplyTracker.begin();
268 @SuppressWarnings("checkstyle:IllegalCatch")
270 protected void handleNonRaftCommand(final Object message) {
271 try (MessageTracker.Context context = appendEntriesReplyTracker.received(message)) {
272 final Optional<Error> maybeError = context.error();
273 if (maybeError.isPresent()) {
274 LOG.trace("{} : AppendEntriesReply failed to arrive at the expected interval {}", persistenceId(),
278 if (message instanceof RequestEnvelope) {
279 final long now = ticker().read();
280 final RequestEnvelope envelope = (RequestEnvelope)message;
283 final RequestSuccess<?, ?> success = handleRequest(envelope, now);
284 if (success != null) {
285 envelope.sendSuccess(success, ticker().read() - now);
287 } catch (RequestException e) {
288 LOG.debug("{}: request {} failed", persistenceId(), envelope, e);
289 envelope.sendFailure(e, ticker().read() - now);
290 } catch (Exception e) {
291 LOG.debug("{}: request {} caused failure", persistenceId(), envelope, e);
292 envelope.sendFailure(new RuntimeRequestException("Request failed to process", e),
293 ticker().read() - now);
295 } else if (message instanceof ConnectClientRequest) {
296 handleConnectClient((ConnectClientRequest)message);
297 } else if (CreateTransaction.isSerializedType(message)) {
298 handleCreateTransaction(message);
299 } else if (message instanceof BatchedModifications) {
300 handleBatchedModifications((BatchedModifications)message);
301 } else if (message instanceof ForwardedReadyTransaction) {
302 handleForwardedReadyTransaction((ForwardedReadyTransaction) message);
303 } else if (message instanceof ReadyLocalTransaction) {
304 handleReadyLocalTransaction((ReadyLocalTransaction)message);
305 } else if (CanCommitTransaction.isSerializedType(message)) {
306 handleCanCommitTransaction(CanCommitTransaction.fromSerializable(message));
307 } else if (CommitTransaction.isSerializedType(message)) {
308 handleCommitTransaction(CommitTransaction.fromSerializable(message));
309 } else if (AbortTransaction.isSerializedType(message)) {
310 handleAbortTransaction(AbortTransaction.fromSerializable(message));
311 } else if (CloseTransactionChain.isSerializedType(message)) {
312 closeTransactionChain(CloseTransactionChain.fromSerializable(message));
313 } else if (message instanceof RegisterChangeListener) {
314 changeSupport.onMessage((RegisterChangeListener) message, isLeader(), hasLeader());
315 } else if (message instanceof RegisterDataTreeChangeListener) {
316 treeChangeSupport.onMessage((RegisterDataTreeChangeListener) message, isLeader(), hasLeader());
317 } else if (message instanceof UpdateSchemaContext) {
318 updateSchemaContext((UpdateSchemaContext) message);
319 } else if (message instanceof PeerAddressResolved) {
320 PeerAddressResolved resolved = (PeerAddressResolved) message;
321 setPeerAddress(resolved.getPeerId(), resolved.getPeerAddress());
322 } else if (TX_COMMIT_TIMEOUT_CHECK_MESSAGE.equals(message)) {
323 store.checkForExpiredTransactions(transactionCommitTimeout);
324 commitCoordinator.checkForExpiredTransactions(transactionCommitTimeout, this);
325 } else if (message instanceof DatastoreContext) {
326 onDatastoreContext((DatastoreContext)message);
327 } else if (message instanceof RegisterRoleChangeListener) {
328 roleChangeNotifier.get().forward(message, context());
329 } else if (message instanceof FollowerInitialSyncUpStatus) {
330 shardMBean.setFollowerInitialSyncStatus(((FollowerInitialSyncUpStatus) message).isInitialSyncDone());
331 context().parent().tell(message, self());
332 } else if (GET_SHARD_MBEAN_MESSAGE.equals(message)) {
333 sender().tell(getShardMBean(), self());
334 } else if (message instanceof GetShardDataTree) {
335 sender().tell(store.getDataTree(), self());
336 } else if (message instanceof ServerRemoved) {
337 context().parent().forward(message, context());
338 } else if (ShardTransactionMessageRetrySupport.TIMER_MESSAGE_CLASS.isInstance(message)) {
339 messageRetrySupport.onTimerMessage(message);
340 } else if (message instanceof DataTreeCohortActorRegistry.CohortRegistryCommand) {
341 store.processCohortRegistryCommand(getSender(),
342 (DataTreeCohortActorRegistry.CohortRegistryCommand) message);
343 } else if (message instanceof PersistAbortTransactionPayload) {
344 final TransactionIdentifier txId = ((PersistAbortTransactionPayload) message).getTransactionId();
345 persistPayload(txId, AbortTransactionPayload.create(txId), true);
346 } else if (message instanceof MakeLeaderLocal) {
349 super.handleNonRaftCommand(message);
354 private void onMakeLeaderLocal() {
355 LOG.debug("{}: onMakeLeaderLocal received", persistenceId());
357 getSender().tell(new Status.Success(null), getSelf());
361 final ActorSelection leader = getLeader();
363 if (leader == null) {
364 // Leader is not present. The cluster is most likely trying to
365 // elect a leader and we should let that run its normal course
367 // TODO we can wait for the election to complete and retry the
368 // request. We can also let the caller retry by sending a flag
369 // in the response indicating the request is "reTryable".
370 getSender().tell(new Failure(
371 new LeadershipTransferFailedException("We cannot initiate leadership transfer to local node. "
372 + "Currently there is no leader for " + persistenceId())),
377 leader.tell(new RequestLeadership(getId(), getSender()), getSelf());
380 // Acquire our frontend tracking handle and verify generation matches
381 private LeaderFrontendState getFrontend(final ClientIdentifier clientId) throws RequestException {
382 final LeaderFrontendState existing = knownFrontends.get(clientId.getFrontendId());
383 if (existing != null) {
384 final int cmp = Long.compareUnsigned(existing.getIdentifier().getGeneration(), clientId.getGeneration());
389 LOG.debug("{}: rejecting request from outdated client {}", persistenceId(), clientId);
390 throw new RetiredGenerationException(existing.getIdentifier().getGeneration());
393 LOG.info("{}: retiring state {}, outdated by request from client {}", persistenceId(), existing, clientId);
395 knownFrontends.remove(clientId.getFrontendId());
397 LOG.debug("{}: client {} is not yet known", persistenceId(), clientId);
400 final LeaderFrontendState ret = new LeaderFrontendState(persistenceId(), clientId, store);
401 knownFrontends.put(clientId.getFrontendId(), ret);
402 LOG.debug("{}: created state {} for client {}", persistenceId(), ret, clientId);
406 private static @Nonnull ABIVersion selectVersion(final ConnectClientRequest message) {
407 final Range<ABIVersion> clientRange = Range.closed(message.getMinVersion(), message.getMaxVersion());
408 for (ABIVersion v : SUPPORTED_ABIVERSIONS) {
409 if (clientRange.contains(v)) {
414 throw new IllegalArgumentException(String.format(
415 "No common version between backend versions %s and client versions %s", SUPPORTED_ABIVERSIONS,
419 @SuppressWarnings("checkstyle:IllegalCatch")
420 private void handleConnectClient(final ConnectClientRequest message) {
422 if (!isLeader() || !isLeaderActive()) {
423 LOG.debug("{}: not currently leader, rejecting request {}", persistenceId(), message);
424 throw new NotLeaderException(getSelf());
427 final ABIVersion selectedVersion = selectVersion(message);
428 final LeaderFrontendState frontend = getFrontend(message.getTarget());
429 frontend.reconnect();
430 message.getReplyTo().tell(new ConnectClientSuccess(message.getTarget(), message.getSequence(), getSelf(),
431 ImmutableList.of(), store.getDataTree(), CLIENT_MAX_MESSAGES).toVersion(selectedVersion),
432 ActorRef.noSender());
433 } catch (RequestException | RuntimeException e) {
434 message.getReplyTo().tell(new Failure(e), ActorRef.noSender());
438 private @Nullable RequestSuccess<?, ?> handleRequest(final RequestEnvelope envelope, final long now)
439 throws RequestException {
440 // We are not the leader, hence we want to fail-fast.
441 if (!isLeader() || !isLeaderActive()) {
442 LOG.debug("{}: not currently leader, rejecting request {}", persistenceId(), envelope);
443 throw new NotLeaderException(getSelf());
446 final Request<?, ?> request = envelope.getMessage();
447 if (request instanceof TransactionRequest) {
448 final TransactionRequest<?> txReq = (TransactionRequest<?>)request;
449 final ClientIdentifier clientId = txReq.getTarget().getHistoryId().getClientId();
450 return getFrontend(clientId).handleTransactionRequest(txReq, envelope, now);
451 } else if (request instanceof LocalHistoryRequest) {
452 final LocalHistoryRequest<?> lhReq = (LocalHistoryRequest<?>)request;
453 final ClientIdentifier clientId = lhReq.getTarget().getClientId();
454 return getFrontend(clientId).handleLocalHistoryRequest(lhReq, envelope, now);
456 LOG.warn("{}: rejecting unsupported request {}", persistenceId(), request);
457 throw new UnsupportedRequestException(request);
461 private boolean hasLeader() {
462 return getLeaderId() != null;
465 public int getPendingTxCommitQueueSize() {
466 return store.getQueueSize();
469 public int getCohortCacheSize() {
470 return commitCoordinator.getCohortCacheSize();
474 protected Optional<ActorRef> getRoleChangeNotifier() {
475 return roleChangeNotifier;
479 protected LeaderStateChanged newLeaderStateChanged(final String memberId, final String leaderId,
480 final short leaderPayloadVersion) {
481 return isLeader() ? new ShardLeaderStateChanged(memberId, leaderId, store.getDataTree(), leaderPayloadVersion)
482 : new ShardLeaderStateChanged(memberId, leaderId, leaderPayloadVersion);
485 protected void onDatastoreContext(final DatastoreContext context) {
486 datastoreContext = context;
488 setTransactionCommitTimeout();
490 setPersistence(datastoreContext.isPersistent());
492 updateConfigParams(datastoreContext.getShardRaftConfig());
495 // applyState() will be invoked once consensus is reached on the payload
496 void persistPayload(final Identifier id, final Payload payload, final boolean batchHint) {
497 boolean canSkipPayload = !hasFollowers() && !persistence().isRecoveryApplicable();
498 if (canSkipPayload) {
499 applyState(self(), id, payload);
501 // We are faking the sender
502 persistData(self(), id, payload, batchHint);
506 private void handleCommitTransaction(final CommitTransaction commit) {
508 commitCoordinator.handleCommit(commit.getTransactionId(), getSender(), this);
510 ActorSelection leader = getLeader();
511 if (leader == null) {
512 messageRetrySupport.addMessageToRetry(commit, getSender(),
513 "Could not commit transaction " + commit.getTransactionId());
515 LOG.debug("{}: Forwarding CommitTransaction to leader {}", persistenceId(), leader);
516 leader.forward(commit, getContext());
521 private void handleCanCommitTransaction(final CanCommitTransaction canCommit) {
522 LOG.debug("{}: Can committing transaction {}", persistenceId(), canCommit.getTransactionId());
525 commitCoordinator.handleCanCommit(canCommit.getTransactionId(), getSender(), this);
527 ActorSelection leader = getLeader();
528 if (leader == null) {
529 messageRetrySupport.addMessageToRetry(canCommit, getSender(),
530 "Could not canCommit transaction " + canCommit.getTransactionId());
532 LOG.debug("{}: Forwarding CanCommitTransaction to leader {}", persistenceId(), leader);
533 leader.forward(canCommit, getContext());
538 @SuppressWarnings("checkstyle:IllegalCatch")
539 protected void handleBatchedModificationsLocal(final BatchedModifications batched, final ActorRef sender) {
541 commitCoordinator.handleBatchedModifications(batched, sender, this);
542 } catch (Exception e) {
543 LOG.error("{}: Error handling BatchedModifications for Tx {}", persistenceId(),
544 batched.getTransactionId(), e);
545 sender.tell(new Failure(e), getSelf());
549 private void handleBatchedModifications(final BatchedModifications batched) {
550 // This message is sent to prepare the modifications transaction directly on the Shard as an
551 // optimization to avoid the extra overhead of a separate ShardTransaction actor. On the last
552 // BatchedModifications message, the caller sets the ready flag in the message indicating
553 // modifications are complete. The reply contains the cohort actor path (this actor) for the caller
554 // to initiate the 3-phase commit. This also avoids the overhead of sending an additional
555 // ReadyTransaction message.
557 // If we're not the leader then forward to the leader. This is a safety measure - we shouldn't
558 // normally get here if we're not the leader as the front-end (TransactionProxy) should determine
559 // the primary/leader shard. However with timing and caching on the front-end, there's a small
560 // window where it could have a stale leader during leadership transitions.
562 boolean isLeaderActive = isLeaderActive();
563 if (isLeader() && isLeaderActive) {
564 handleBatchedModificationsLocal(batched, getSender());
566 ActorSelection leader = getLeader();
567 if (!isLeaderActive || leader == null) {
568 messageRetrySupport.addMessageToRetry(batched, getSender(),
569 "Could not commit transaction " + batched.getTransactionId());
571 // If this is not the first batch and leadership changed in between batched messages,
572 // we need to reconstruct previous BatchedModifications from the transaction
573 // DataTreeModification, honoring the max batched modification count, and forward all the
574 // previous BatchedModifications to the new leader.
575 Collection<BatchedModifications> newModifications = commitCoordinator
576 .createForwardedBatchedModifications(batched,
577 datastoreContext.getShardBatchedModificationCount());
579 LOG.debug("{}: Forwarding {} BatchedModifications to leader {}", persistenceId(),
580 newModifications.size(), leader);
582 for (BatchedModifications bm : newModifications) {
583 leader.forward(bm, getContext());
589 private boolean failIfIsolatedLeader(final ActorRef sender) {
590 if (isIsolatedLeader()) {
591 sender.tell(new Failure(new NoShardLeaderException(String.format(
592 "Shard %s was the leader but has lost contact with all of its followers. Either all"
593 + " other follower nodes are down or this node is isolated by a network partition.",
594 persistenceId()))), getSelf());
601 protected boolean isIsolatedLeader() {
602 return getRaftState() == RaftState.IsolatedLeader;
605 @SuppressWarnings("checkstyle:IllegalCatch")
606 private void handleReadyLocalTransaction(final ReadyLocalTransaction message) {
607 LOG.debug("{}: handleReadyLocalTransaction for {}", persistenceId(), message.getTransactionId());
609 boolean isLeaderActive = isLeaderActive();
610 if (isLeader() && isLeaderActive) {
612 commitCoordinator.handleReadyLocalTransaction(message, getSender(), this);
613 } catch (Exception e) {
614 LOG.error("{}: Error handling ReadyLocalTransaction for Tx {}", persistenceId(),
615 message.getTransactionId(), e);
616 getSender().tell(new Failure(e), getSelf());
619 ActorSelection leader = getLeader();
620 if (!isLeaderActive || leader == null) {
621 messageRetrySupport.addMessageToRetry(message, getSender(),
622 "Could not commit transaction " + message.getTransactionId());
624 LOG.debug("{}: Forwarding ReadyLocalTransaction to leader {}", persistenceId(), leader);
625 message.setRemoteVersion(getCurrentBehavior().getLeaderPayloadVersion());
626 leader.forward(message, getContext());
631 private void handleForwardedReadyTransaction(final ForwardedReadyTransaction forwardedReady) {
632 LOG.debug("{}: handleForwardedReadyTransaction for {}", persistenceId(), forwardedReady.getTransactionId());
634 boolean isLeaderActive = isLeaderActive();
635 if (isLeader() && isLeaderActive) {
636 commitCoordinator.handleForwardedReadyTransaction(forwardedReady, getSender(), this);
638 ActorSelection leader = getLeader();
639 if (!isLeaderActive || leader == null) {
640 messageRetrySupport.addMessageToRetry(forwardedReady, getSender(),
641 "Could not commit transaction " + forwardedReady.getTransactionId());
643 LOG.debug("{}: Forwarding ForwardedReadyTransaction to leader {}", persistenceId(), leader);
645 ReadyLocalTransaction readyLocal = new ReadyLocalTransaction(forwardedReady.getTransactionId(),
646 forwardedReady.getTransaction().getSnapshot(), forwardedReady.isDoImmediateCommit());
647 readyLocal.setRemoteVersion(getCurrentBehavior().getLeaderPayloadVersion());
648 leader.forward(readyLocal, getContext());
653 private void handleAbortTransaction(final AbortTransaction abort) {
654 doAbortTransaction(abort.getTransactionId(), getSender());
657 void doAbortTransaction(final Identifier transactionID, final ActorRef sender) {
658 commitCoordinator.handleAbort(transactionID, sender, this);
661 private void handleCreateTransaction(final Object message) {
663 createTransaction(CreateTransaction.fromSerializable(message));
664 } else if (getLeader() != null) {
665 getLeader().forward(message, getContext());
667 getSender().tell(new Failure(new NoShardLeaderException(
668 "Could not create a shard transaction", persistenceId())), getSelf());
672 private void closeTransactionChain(final CloseTransactionChain closeTransactionChain) {
673 final LocalHistoryIdentifier id = closeTransactionChain.getIdentifier();
674 store.closeTransactionChain(id, null);
675 store.purgeTransactionChain(id, null);
678 @SuppressWarnings("checkstyle:IllegalCatch")
679 private void createTransaction(final CreateTransaction createTransaction) {
681 if (TransactionType.fromInt(createTransaction.getTransactionType()) != TransactionType.READ_ONLY
682 && failIfIsolatedLeader(getSender())) {
686 ActorRef transactionActor = createTransaction(createTransaction.getTransactionType(),
687 createTransaction.getTransactionId());
689 getSender().tell(new CreateTransactionReply(Serialization.serializedActorPath(transactionActor),
690 createTransaction.getTransactionId(), createTransaction.getVersion()).toSerializable(), getSelf());
691 } catch (Exception e) {
692 getSender().tell(new Failure(e), getSelf());
696 private ActorRef createTransaction(final int transactionType, final TransactionIdentifier transactionId) {
697 LOG.debug("{}: Creating transaction : {} ", persistenceId(), transactionId);
698 return transactionActorFactory.newShardTransaction(TransactionType.fromInt(transactionType),
702 private void updateSchemaContext(final UpdateSchemaContext message) {
703 updateSchemaContext(message.getSchemaContext());
707 void updateSchemaContext(final SchemaContext schemaContext) {
708 store.updateSchemaContext(schemaContext);
711 private boolean isMetricsCaptureEnabled() {
712 CommonConfig config = new CommonConfig(getContext().system().settings().config());
713 return config.isMetricCaptureEnabled();
718 public RaftActorSnapshotCohort getRaftActorSnapshotCohort() {
719 return snapshotCohort;
724 protected RaftActorRecoveryCohort getRaftActorRecoveryCohort() {
725 return new ShardRecoveryCoordinator(store,
726 restoreFromSnapshot != null ? restoreFromSnapshot.getSnapshot() : null, persistenceId(), LOG);
730 protected void onRecoveryComplete() {
731 restoreFromSnapshot = null;
733 //notify shard manager
734 getContext().parent().tell(new ActorInitialized(), getSelf());
736 // Being paranoid here - this method should only be called once but just in case...
737 if (txCommitTimeoutCheckSchedule == null) {
738 // Schedule a message to be periodically sent to check if the current in-progress
739 // transaction should be expired and aborted.
740 FiniteDuration period = Duration.create(transactionCommitTimeout / 3, TimeUnit.MILLISECONDS);
741 txCommitTimeoutCheckSchedule = getContext().system().scheduler().schedule(
742 period, period, getSelf(),
743 TX_COMMIT_TIMEOUT_CHECK_MESSAGE, getContext().dispatcher(), ActorRef.noSender());
748 protected void applyState(final ActorRef clientActor, final Identifier identifier, final Object data) {
749 if (data instanceof Payload) {
751 store.applyReplicatedPayload(identifier, (Payload)data);
752 } catch (DataValidationFailedException | IOException e) {
753 LOG.error("{}: Error applying replica {}", persistenceId(), identifier, e);
756 LOG.error("{}: Unknown state for {} received {}", persistenceId(), identifier, data);
761 protected void onStateChanged() {
762 boolean isLeader = isLeader();
763 boolean hasLeader = hasLeader();
764 changeSupport.onLeadershipChange(isLeader, hasLeader);
765 treeChangeSupport.onLeadershipChange(isLeader, hasLeader);
767 // If this actor is no longer the leader close all the transaction chains
769 if (LOG.isDebugEnabled()) {
771 "{}: onStateChanged: Closing all transaction chains because shard {} is no longer the leader",
772 persistenceId(), getId());
775 store.purgeLeaderState();
778 if (hasLeader && !isIsolatedLeader()) {
779 messageRetrySupport.retryMessages();
784 protected void onLeaderChanged(final String oldLeader, final String newLeader) {
785 shardMBean.incrementLeadershipChangeCount();
787 final boolean hasLeader = hasLeader();
789 // No leader implies we are not the leader, lose frontend state if we have any. This also places
790 // an explicit guard so the map will not get modified accidentally.
791 if (!knownFrontends.isEmpty()) {
792 LOG.debug("{}: removing frontend state for {}", persistenceId(), knownFrontends.keySet());
793 knownFrontends = ImmutableMap.of();
799 // Another leader was elected. If we were the previous leader and had pending transactions, convert
800 // them to transaction messages and send to the new leader.
801 ActorSelection leader = getLeader();
802 if (leader != null) {
803 Collection<?> messagesToForward = convertPendingTransactionsToMessages();
805 if (!messagesToForward.isEmpty()) {
806 LOG.debug("{}: Forwarding {} pending transaction messages to leader {}", persistenceId(),
807 messagesToForward.size(), leader);
809 for (Object message : messagesToForward) {
810 leader.tell(message, self());
814 commitCoordinator.abortPendingTransactions("The transacton was aborted due to inflight leadership "
815 + "change and the leader address isn't available.", this);
818 // We have become the leader, we need to reconstruct frontend state
819 knownFrontends = Verify.verifyNotNull(frontendMetadata.toLeaderState(this));
820 LOG.debug("{}: became leader with frontend state for {}", persistenceId(), knownFrontends.keySet());
823 if (!isIsolatedLeader()) {
824 messageRetrySupport.retryMessages();
829 * Clears all pending transactions and converts them to messages to be forwarded to a new leader.
831 * @return the converted messages
833 public Collection<?> convertPendingTransactionsToMessages() {
834 return commitCoordinator.convertPendingTransactionsToMessages(
835 datastoreContext.getShardBatchedModificationCount());
839 protected void pauseLeader(final Runnable operation) {
840 LOG.debug("{}: In pauseLeader, operation: {}", persistenceId(), operation);
841 store.setRunOnPendingTransactionsComplete(operation);
845 protected OnDemandRaftState.AbstractBuilder<?> newOnDemandRaftStateBuilder() {
846 return OnDemandShardState.newBuilder().treeChangeListenerActors(treeChangeSupport.getListenerActors())
847 .dataChangeListenerActors(changeSupport.getListenerActors())
848 .commitCohortActors(store.getCohortActors());
852 public String persistenceId() {
857 ShardCommitCoordinator getCommitCoordinator() {
858 return commitCoordinator;
861 public DatastoreContext getDatastoreContext() {
862 return datastoreContext;
866 public ShardDataTree getDataStore() {
871 ShardStats getShardMBean() {
875 public static Builder builder() {
876 return new Builder();
879 public abstract static class AbstractBuilder<T extends AbstractBuilder<T, S>, S extends Shard> {
880 private final Class<S> shardClass;
881 private ShardIdentifier id;
882 private Map<String, String> peerAddresses = Collections.emptyMap();
883 private DatastoreContext datastoreContext;
884 private SchemaContext schemaContext;
885 private DatastoreSnapshot.ShardSnapshot restoreFromSnapshot;
886 private TipProducingDataTree dataTree;
887 private volatile boolean sealed;
889 protected AbstractBuilder(final Class<S> shardClass) {
890 this.shardClass = shardClass;
893 protected void checkSealed() {
894 Preconditions.checkState(!sealed, "Builder isalready sealed - further modifications are not allowed");
897 @SuppressWarnings("unchecked")
902 public T id(final ShardIdentifier newId) {
908 public T peerAddresses(final Map<String, String> newPeerAddresses) {
910 this.peerAddresses = newPeerAddresses;
914 public T datastoreContext(final DatastoreContext newDatastoreContext) {
916 this.datastoreContext = newDatastoreContext;
920 public T schemaContext(final SchemaContext newSchemaContext) {
922 this.schemaContext = newSchemaContext;
926 public T restoreFromSnapshot(final DatastoreSnapshot.ShardSnapshot newRestoreFromSnapshot) {
928 this.restoreFromSnapshot = newRestoreFromSnapshot;
932 public T dataTree(final TipProducingDataTree newDataTree) {
934 this.dataTree = newDataTree;
938 public ShardIdentifier getId() {
942 public Map<String, String> getPeerAddresses() {
943 return peerAddresses;
946 public DatastoreContext getDatastoreContext() {
947 return datastoreContext;
950 public SchemaContext getSchemaContext() {
951 return schemaContext;
954 public DatastoreSnapshot.ShardSnapshot getRestoreFromSnapshot() {
955 return restoreFromSnapshot;
958 public TipProducingDataTree getDataTree() {
962 public TreeType getTreeType() {
963 switch (datastoreContext.getLogicalStoreType()) {
965 return TreeType.CONFIGURATION;
967 return TreeType.OPERATIONAL;
969 throw new IllegalStateException("Unhandled logical store type "
970 + datastoreContext.getLogicalStoreType());
974 protected void verify() {
975 Preconditions.checkNotNull(id, "id should not be null");
976 Preconditions.checkNotNull(peerAddresses, "peerAddresses should not be null");
977 Preconditions.checkNotNull(datastoreContext, "dataStoreContext should not be null");
978 Preconditions.checkNotNull(schemaContext, "schemaContext should not be null");
981 public Props props() {
984 return Props.create(shardClass, this);
988 public static class Builder extends AbstractBuilder<Builder, Shard> {
995 return Ticker.systemTicker();