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 org.opendaylight.yangtools.yang.model.api.SchemaContextProvider;
102 import scala.concurrent.duration.Duration;
103 import scala.concurrent.duration.FiniteDuration;
106 * A Shard represents a portion of the logical data tree.
109 * Our Shard uses InMemoryDataTree as it's internal representation and delegates all requests it
111 public class Shard extends RaftActor {
114 static final Object TX_COMMIT_TIMEOUT_CHECK_MESSAGE = new Object() {
116 public String toString() {
117 return "txCommitTimeoutCheck";
122 static final Object GET_SHARD_MBEAN_MESSAGE = new Object() {
124 public String toString() {
125 return "getShardMBeanMessage";
129 static final Object RESUME_NEXT_PENDING_TRANSACTION = new Object() {
131 public String toString() {
132 return "resumeNextPendingTransaction";
136 // FIXME: shard names should be encapsulated in their own class and this should be exposed as a constant.
137 public static final String DEFAULT_NAME = "default";
139 private static final Collection<ABIVersion> SUPPORTED_ABIVERSIONS;
142 final ABIVersion[] values = ABIVersion.values();
143 final ABIVersion[] real = Arrays.copyOfRange(values, 1, values.length - 1);
144 SUPPORTED_ABIVERSIONS = ImmutableList.copyOf(real).reverse();
147 // FIXME: make this a dynamic property based on mailbox size and maximum number of clients
148 private static final int CLIENT_MAX_MESSAGES = 1000;
150 // The state of this Shard
151 private final ShardDataTree store;
153 /// The name of this shard
154 private final String name;
156 private final ShardStats shardMBean;
158 private DatastoreContext datastoreContext;
160 private final ShardCommitCoordinator commitCoordinator;
162 private long transactionCommitTimeout;
164 private Cancellable txCommitTimeoutCheckSchedule;
166 private final Optional<ActorRef> roleChangeNotifier;
168 private final MessageTracker appendEntriesReplyTracker;
170 private final ShardTransactionActorFactory transactionActorFactory;
172 private final ShardSnapshotCohort snapshotCohort;
174 private final DataTreeChangeListenerSupport treeChangeSupport = new DataTreeChangeListenerSupport(this);
175 private final DataChangeListenerSupport changeSupport = new DataChangeListenerSupport(this);
178 private ShardSnapshot restoreFromSnapshot;
180 private final ShardTransactionMessageRetrySupport messageRetrySupport;
182 private final FrontendMetadata frontendMetadata;
183 private Map<FrontendIdentifier, LeaderFrontendState> knownFrontends = ImmutableMap.of();
185 protected Shard(final AbstractBuilder<?, ?> builder) {
186 super(builder.getId().toString(), builder.getPeerAddresses(),
187 Optional.of(builder.getDatastoreContext().getShardRaftConfig()), DataStoreVersions.CURRENT_VERSION);
189 this.name = builder.getId().toString();
190 this.datastoreContext = builder.getDatastoreContext();
191 this.restoreFromSnapshot = builder.getRestoreFromSnapshot();
192 this.frontendMetadata = new FrontendMetadata(name);
194 setPersistence(datastoreContext.isPersistent());
196 LOG.info("Shard created : {}, persistent : {}", name, datastoreContext.isPersistent());
198 ShardDataTreeChangeListenerPublisherActorProxy treeChangeListenerPublisher =
199 new ShardDataTreeChangeListenerPublisherActorProxy(getContext(), name + "-DTCL-publisher", name);
200 ShardDataChangeListenerPublisherActorProxy dataChangeListenerPublisher =
201 new ShardDataChangeListenerPublisherActorProxy(getContext(), name + "-DCL-publisher", name);
202 if (builder.getDataTree() != null) {
203 store = new ShardDataTree(this, builder.getSchemaContext(), builder.getDataTree(),
204 treeChangeListenerPublisher, dataChangeListenerPublisher, name, frontendMetadata);
206 store = new ShardDataTree(this, builder.getSchemaContext(), builder.getTreeType(),
207 builder.getDatastoreContext().getStoreRoot(), treeChangeListenerPublisher,
208 dataChangeListenerPublisher, name, frontendMetadata);
211 shardMBean = ShardMBeanFactory.getShardStatsMBean(name, datastoreContext.getDataStoreMXBeanType(), this);
213 if (isMetricsCaptureEnabled()) {
214 getContext().become(new MeteringBehavior(this));
217 commitCoordinator = new ShardCommitCoordinator(store, LOG, this.name);
219 setTransactionCommitTimeout();
221 // create a notifier actor for each cluster member
222 roleChangeNotifier = createRoleChangeNotifier(name);
224 appendEntriesReplyTracker = new MessageTracker(AppendEntriesReply.class,
225 getRaftActorContext().getConfigParams().getIsolatedCheckIntervalInMillis());
227 transactionActorFactory = new ShardTransactionActorFactory(store, datastoreContext,
228 new Dispatchers(context().system().dispatchers()).getDispatcherPath(Dispatchers.DispatcherType.Transaction),
229 self(), getContext(), shardMBean, builder.getId().getShardName());
231 snapshotCohort = ShardSnapshotCohort.create(getContext(), builder.getId().getMemberName(), store, LOG,
234 messageRetrySupport = new ShardTransactionMessageRetrySupport(this);
237 private void setTransactionCommitTimeout() {
238 transactionCommitTimeout = TimeUnit.MILLISECONDS.convert(
239 datastoreContext.getShardTransactionCommitTimeoutInSeconds(), TimeUnit.SECONDS) / 2;
242 private Optional<ActorRef> createRoleChangeNotifier(final String shardId) {
243 ActorRef shardRoleChangeNotifier = this.getContext().actorOf(
244 RoleChangeNotifier.getProps(shardId), shardId + "-notifier");
245 return Optional.of(shardRoleChangeNotifier);
249 public void postStop() {
250 LOG.info("Stopping Shard {}", persistenceId());
254 messageRetrySupport.close();
256 if (txCommitTimeoutCheckSchedule != null) {
257 txCommitTimeoutCheckSchedule.cancel();
260 commitCoordinator.abortPendingTransactions("Transaction aborted due to shutdown.", this);
262 shardMBean.unregisterMBean();
266 protected void handleRecover(final Object message) {
267 LOG.debug("{}: onReceiveRecover: Received message {} from {}", persistenceId(), message.getClass(),
270 super.handleRecover(message);
271 if (LOG.isTraceEnabled()) {
272 appendEntriesReplyTracker.begin();
276 @SuppressWarnings("checkstyle:IllegalCatch")
278 protected void handleNonRaftCommand(final Object message) {
279 try (MessageTracker.Context context = appendEntriesReplyTracker.received(message)) {
280 final Optional<Error> maybeError = context.error();
281 if (maybeError.isPresent()) {
282 LOG.trace("{} : AppendEntriesReply failed to arrive at the expected interval {}", persistenceId(),
286 store.resetTransactionBatch();
288 if (message instanceof RequestEnvelope) {
289 final long now = ticker().read();
290 final RequestEnvelope envelope = (RequestEnvelope)message;
293 final RequestSuccess<?, ?> success = handleRequest(envelope, now);
294 if (success != null) {
295 envelope.sendSuccess(success, ticker().read() - now);
297 } catch (RequestException e) {
298 LOG.debug("{}: request {} failed", persistenceId(), envelope, e);
299 envelope.sendFailure(e, ticker().read() - now);
300 } catch (Exception e) {
301 LOG.debug("{}: request {} caused failure", persistenceId(), envelope, e);
302 envelope.sendFailure(new RuntimeRequestException("Request failed to process", e),
303 ticker().read() - now);
305 } else if (message instanceof ConnectClientRequest) {
306 handleConnectClient((ConnectClientRequest)message);
307 } else if (CreateTransaction.isSerializedType(message)) {
308 handleCreateTransaction(message);
309 } else if (message instanceof BatchedModifications) {
310 handleBatchedModifications((BatchedModifications)message);
311 } else if (message instanceof ForwardedReadyTransaction) {
312 handleForwardedReadyTransaction((ForwardedReadyTransaction) message);
313 } else if (message instanceof ReadyLocalTransaction) {
314 handleReadyLocalTransaction((ReadyLocalTransaction)message);
315 } else if (CanCommitTransaction.isSerializedType(message)) {
316 handleCanCommitTransaction(CanCommitTransaction.fromSerializable(message));
317 } else if (CommitTransaction.isSerializedType(message)) {
318 handleCommitTransaction(CommitTransaction.fromSerializable(message));
319 } else if (AbortTransaction.isSerializedType(message)) {
320 handleAbortTransaction(AbortTransaction.fromSerializable(message));
321 } else if (CloseTransactionChain.isSerializedType(message)) {
322 closeTransactionChain(CloseTransactionChain.fromSerializable(message));
323 } else if (message instanceof RegisterChangeListener) {
324 changeSupport.onMessage((RegisterChangeListener) message, isLeader(), hasLeader());
325 } else if (message instanceof RegisterDataTreeChangeListener) {
326 treeChangeSupport.onMessage((RegisterDataTreeChangeListener) message, isLeader(), hasLeader());
327 } else if (message instanceof UpdateSchemaContext) {
328 updateSchemaContext((UpdateSchemaContext) message);
329 } else if (message instanceof PeerAddressResolved) {
330 PeerAddressResolved resolved = (PeerAddressResolved) message;
331 setPeerAddress(resolved.getPeerId(), resolved.getPeerAddress());
332 } else if (TX_COMMIT_TIMEOUT_CHECK_MESSAGE.equals(message)) {
333 store.checkForExpiredTransactions(transactionCommitTimeout);
334 commitCoordinator.checkForExpiredTransactions(transactionCommitTimeout, this);
335 } else if (message instanceof DatastoreContext) {
336 onDatastoreContext((DatastoreContext)message);
337 } else if (message instanceof RegisterRoleChangeListener) {
338 roleChangeNotifier.get().forward(message, context());
339 } else if (message instanceof FollowerInitialSyncUpStatus) {
340 shardMBean.setFollowerInitialSyncStatus(((FollowerInitialSyncUpStatus) message).isInitialSyncDone());
341 context().parent().tell(message, self());
342 } else if (GET_SHARD_MBEAN_MESSAGE.equals(message)) {
343 sender().tell(getShardMBean(), self());
344 } else if (message instanceof GetShardDataTree) {
345 sender().tell(store.getDataTree(), self());
346 } else if (message instanceof ServerRemoved) {
347 context().parent().forward(message, context());
348 } else if (ShardTransactionMessageRetrySupport.TIMER_MESSAGE_CLASS.isInstance(message)) {
349 messageRetrySupport.onTimerMessage(message);
350 } else if (message instanceof DataTreeCohortActorRegistry.CohortRegistryCommand) {
351 store.processCohortRegistryCommand(getSender(),
352 (DataTreeCohortActorRegistry.CohortRegistryCommand) message);
353 } else if (message instanceof PersistAbortTransactionPayload) {
354 final TransactionIdentifier txId = ((PersistAbortTransactionPayload) message).getTransactionId();
355 persistPayload(txId, AbortTransactionPayload.create(txId), true);
356 } else if (message instanceof MakeLeaderLocal) {
358 } else if (RESUME_NEXT_PENDING_TRANSACTION.equals(message)) {
359 store.resumeNextPendingTransaction();
361 super.handleNonRaftCommand(message);
366 private void onMakeLeaderLocal() {
367 LOG.debug("{}: onMakeLeaderLocal received", persistenceId());
369 getSender().tell(new Status.Success(null), getSelf());
373 final ActorSelection leader = getLeader();
375 if (leader == null) {
376 // Leader is not present. The cluster is most likely trying to
377 // elect a leader and we should let that run its normal course
379 // TODO we can wait for the election to complete and retry the
380 // request. We can also let the caller retry by sending a flag
381 // in the response indicating the request is "reTryable".
382 getSender().tell(new Failure(
383 new LeadershipTransferFailedException("We cannot initiate leadership transfer to local node. "
384 + "Currently there is no leader for " + persistenceId())),
389 leader.tell(new RequestLeadership(getId(), getSender()), getSelf());
392 // Acquire our frontend tracking handle and verify generation matches
393 private LeaderFrontendState getFrontend(final ClientIdentifier clientId) throws RequestException {
394 final LeaderFrontendState existing = knownFrontends.get(clientId.getFrontendId());
395 if (existing != null) {
396 final int cmp = Long.compareUnsigned(existing.getIdentifier().getGeneration(), clientId.getGeneration());
401 LOG.debug("{}: rejecting request from outdated client {}", persistenceId(), clientId);
402 throw new RetiredGenerationException(existing.getIdentifier().getGeneration());
405 LOG.info("{}: retiring state {}, outdated by request from client {}", persistenceId(), existing, clientId);
407 knownFrontends.remove(clientId.getFrontendId());
409 LOG.debug("{}: client {} is not yet known", persistenceId(), clientId);
412 final LeaderFrontendState ret = new LeaderFrontendState(persistenceId(), clientId, store);
413 knownFrontends.put(clientId.getFrontendId(), ret);
414 LOG.debug("{}: created state {} for client {}", persistenceId(), ret, clientId);
418 private static @Nonnull ABIVersion selectVersion(final ConnectClientRequest message) {
419 final Range<ABIVersion> clientRange = Range.closed(message.getMinVersion(), message.getMaxVersion());
420 for (ABIVersion v : SUPPORTED_ABIVERSIONS) {
421 if (clientRange.contains(v)) {
426 throw new IllegalArgumentException(String.format(
427 "No common version between backend versions %s and client versions %s", SUPPORTED_ABIVERSIONS,
431 @SuppressWarnings("checkstyle:IllegalCatch")
432 private void handleConnectClient(final ConnectClientRequest message) {
434 if (!isLeader() || !isLeaderActive()) {
435 LOG.debug("{}: not currently leader, rejecting request {}", persistenceId(), message);
436 throw new NotLeaderException(getSelf());
439 final ABIVersion selectedVersion = selectVersion(message);
440 final LeaderFrontendState frontend = getFrontend(message.getTarget());
441 frontend.reconnect();
442 message.getReplyTo().tell(new ConnectClientSuccess(message.getTarget(), message.getSequence(), getSelf(),
443 ImmutableList.of(), store.getDataTree(), CLIENT_MAX_MESSAGES).toVersion(selectedVersion),
444 ActorRef.noSender());
445 } catch (RequestException | RuntimeException e) {
446 message.getReplyTo().tell(new Failure(e), ActorRef.noSender());
450 private @Nullable RequestSuccess<?, ?> handleRequest(final RequestEnvelope envelope, final long now)
451 throws RequestException {
452 // We are not the leader, hence we want to fail-fast.
453 if (!isLeader() || !isLeaderActive()) {
454 LOG.debug("{}: not currently leader, rejecting request {}", persistenceId(), envelope);
455 throw new NotLeaderException(getSelf());
458 final Request<?, ?> request = envelope.getMessage();
459 if (request instanceof TransactionRequest) {
460 final TransactionRequest<?> txReq = (TransactionRequest<?>)request;
461 final ClientIdentifier clientId = txReq.getTarget().getHistoryId().getClientId();
462 return getFrontend(clientId).handleTransactionRequest(txReq, envelope, now);
463 } else if (request instanceof LocalHistoryRequest) {
464 final LocalHistoryRequest<?> lhReq = (LocalHistoryRequest<?>)request;
465 final ClientIdentifier clientId = lhReq.getTarget().getClientId();
466 return getFrontend(clientId).handleLocalHistoryRequest(lhReq, envelope, now);
468 LOG.warn("{}: rejecting unsupported request {}", persistenceId(), request);
469 throw new UnsupportedRequestException(request);
473 private boolean hasLeader() {
474 return getLeaderId() != null;
477 public int getPendingTxCommitQueueSize() {
478 return store.getQueueSize();
481 public int getCohortCacheSize() {
482 return commitCoordinator.getCohortCacheSize();
486 protected Optional<ActorRef> getRoleChangeNotifier() {
487 return roleChangeNotifier;
491 protected LeaderStateChanged newLeaderStateChanged(final String memberId, final String leaderId,
492 final short leaderPayloadVersion) {
493 return isLeader() ? new ShardLeaderStateChanged(memberId, leaderId, store.getDataTree(), leaderPayloadVersion)
494 : new ShardLeaderStateChanged(memberId, leaderId, leaderPayloadVersion);
497 protected void onDatastoreContext(final DatastoreContext context) {
498 datastoreContext = context;
500 setTransactionCommitTimeout();
502 setPersistence(datastoreContext.isPersistent());
504 updateConfigParams(datastoreContext.getShardRaftConfig());
507 // applyState() will be invoked once consensus is reached on the payload
508 void persistPayload(final Identifier id, final Payload payload, final boolean batchHint) {
509 boolean canSkipPayload = !hasFollowers() && !persistence().isRecoveryApplicable();
510 if (canSkipPayload) {
511 applyState(self(), id, payload);
513 // We are faking the sender
514 persistData(self(), id, payload, batchHint);
518 private void handleCommitTransaction(final CommitTransaction commit) {
520 commitCoordinator.handleCommit(commit.getTransactionId(), getSender(), this);
522 ActorSelection leader = getLeader();
523 if (leader == null) {
524 messageRetrySupport.addMessageToRetry(commit, getSender(),
525 "Could not commit transaction " + commit.getTransactionId());
527 LOG.debug("{}: Forwarding CommitTransaction to leader {}", persistenceId(), leader);
528 leader.forward(commit, getContext());
533 private void handleCanCommitTransaction(final CanCommitTransaction canCommit) {
534 LOG.debug("{}: Can committing transaction {}", persistenceId(), canCommit.getTransactionId());
537 commitCoordinator.handleCanCommit(canCommit.getTransactionId(), getSender(), this);
539 ActorSelection leader = getLeader();
540 if (leader == null) {
541 messageRetrySupport.addMessageToRetry(canCommit, getSender(),
542 "Could not canCommit transaction " + canCommit.getTransactionId());
544 LOG.debug("{}: Forwarding CanCommitTransaction to leader {}", persistenceId(), leader);
545 leader.forward(canCommit, getContext());
550 @SuppressWarnings("checkstyle:IllegalCatch")
551 protected void handleBatchedModificationsLocal(final BatchedModifications batched, final ActorRef sender) {
553 commitCoordinator.handleBatchedModifications(batched, sender, this);
554 } catch (Exception e) {
555 LOG.error("{}: Error handling BatchedModifications for Tx {}", persistenceId(),
556 batched.getTransactionId(), e);
557 sender.tell(new Failure(e), getSelf());
561 private void handleBatchedModifications(final BatchedModifications batched) {
562 // This message is sent to prepare the modifications transaction directly on the Shard as an
563 // optimization to avoid the extra overhead of a separate ShardTransaction actor. On the last
564 // BatchedModifications message, the caller sets the ready flag in the message indicating
565 // modifications are complete. The reply contains the cohort actor path (this actor) for the caller
566 // to initiate the 3-phase commit. This also avoids the overhead of sending an additional
567 // ReadyTransaction message.
569 // If we're not the leader then forward to the leader. This is a safety measure - we shouldn't
570 // normally get here if we're not the leader as the front-end (TransactionProxy) should determine
571 // the primary/leader shard. However with timing and caching on the front-end, there's a small
572 // window where it could have a stale leader during leadership transitions.
574 boolean isLeaderActive = isLeaderActive();
575 if (isLeader() && isLeaderActive) {
576 handleBatchedModificationsLocal(batched, getSender());
578 ActorSelection leader = getLeader();
579 if (!isLeaderActive || leader == null) {
580 messageRetrySupport.addMessageToRetry(batched, getSender(),
581 "Could not commit transaction " + batched.getTransactionId());
583 // If this is not the first batch and leadership changed in between batched messages,
584 // we need to reconstruct previous BatchedModifications from the transaction
585 // DataTreeModification, honoring the max batched modification count, and forward all the
586 // previous BatchedModifications to the new leader.
587 Collection<BatchedModifications> newModifications = commitCoordinator
588 .createForwardedBatchedModifications(batched,
589 datastoreContext.getShardBatchedModificationCount());
591 LOG.debug("{}: Forwarding {} BatchedModifications to leader {}", persistenceId(),
592 newModifications.size(), leader);
594 for (BatchedModifications bm : newModifications) {
595 leader.forward(bm, getContext());
601 private boolean failIfIsolatedLeader(final ActorRef sender) {
602 if (isIsolatedLeader()) {
603 sender.tell(new Failure(new NoShardLeaderException(String.format(
604 "Shard %s was the leader but has lost contact with all of its followers. Either all"
605 + " other follower nodes are down or this node is isolated by a network partition.",
606 persistenceId()))), getSelf());
613 protected boolean isIsolatedLeader() {
614 return getRaftState() == RaftState.IsolatedLeader;
617 @SuppressWarnings("checkstyle:IllegalCatch")
618 private void handleReadyLocalTransaction(final ReadyLocalTransaction message) {
619 LOG.debug("{}: handleReadyLocalTransaction for {}", persistenceId(), message.getTransactionId());
621 boolean isLeaderActive = isLeaderActive();
622 if (isLeader() && isLeaderActive) {
624 commitCoordinator.handleReadyLocalTransaction(message, getSender(), this);
625 } catch (Exception e) {
626 LOG.error("{}: Error handling ReadyLocalTransaction for Tx {}", persistenceId(),
627 message.getTransactionId(), e);
628 getSender().tell(new Failure(e), getSelf());
631 ActorSelection leader = getLeader();
632 if (!isLeaderActive || leader == null) {
633 messageRetrySupport.addMessageToRetry(message, getSender(),
634 "Could not commit transaction " + message.getTransactionId());
636 LOG.debug("{}: Forwarding ReadyLocalTransaction to leader {}", persistenceId(), leader);
637 message.setRemoteVersion(getCurrentBehavior().getLeaderPayloadVersion());
638 leader.forward(message, getContext());
643 private void handleForwardedReadyTransaction(final ForwardedReadyTransaction forwardedReady) {
644 LOG.debug("{}: handleForwardedReadyTransaction for {}", persistenceId(), forwardedReady.getTransactionId());
646 boolean isLeaderActive = isLeaderActive();
647 if (isLeader() && isLeaderActive) {
648 commitCoordinator.handleForwardedReadyTransaction(forwardedReady, getSender(), this);
650 ActorSelection leader = getLeader();
651 if (!isLeaderActive || leader == null) {
652 messageRetrySupport.addMessageToRetry(forwardedReady, getSender(),
653 "Could not commit transaction " + forwardedReady.getTransactionId());
655 LOG.debug("{}: Forwarding ForwardedReadyTransaction to leader {}", persistenceId(), leader);
657 ReadyLocalTransaction readyLocal = new ReadyLocalTransaction(forwardedReady.getTransactionId(),
658 forwardedReady.getTransaction().getSnapshot(), forwardedReady.isDoImmediateCommit());
659 readyLocal.setRemoteVersion(getCurrentBehavior().getLeaderPayloadVersion());
660 leader.forward(readyLocal, getContext());
665 private void handleAbortTransaction(final AbortTransaction abort) {
666 doAbortTransaction(abort.getTransactionId(), getSender());
669 void doAbortTransaction(final Identifier transactionID, final ActorRef sender) {
670 commitCoordinator.handleAbort(transactionID, sender, this);
673 private void handleCreateTransaction(final Object message) {
675 createTransaction(CreateTransaction.fromSerializable(message));
676 } else if (getLeader() != null) {
677 getLeader().forward(message, getContext());
679 getSender().tell(new Failure(new NoShardLeaderException(
680 "Could not create a shard transaction", persistenceId())), getSelf());
684 private void closeTransactionChain(final CloseTransactionChain closeTransactionChain) {
685 final LocalHistoryIdentifier id = closeTransactionChain.getIdentifier();
686 store.closeTransactionChain(id, null);
687 store.purgeTransactionChain(id, null);
690 @SuppressWarnings("checkstyle:IllegalCatch")
691 private void createTransaction(final CreateTransaction createTransaction) {
693 if (TransactionType.fromInt(createTransaction.getTransactionType()) != TransactionType.READ_ONLY
694 && failIfIsolatedLeader(getSender())) {
698 ActorRef transactionActor = createTransaction(createTransaction.getTransactionType(),
699 createTransaction.getTransactionId());
701 getSender().tell(new CreateTransactionReply(Serialization.serializedActorPath(transactionActor),
702 createTransaction.getTransactionId(), createTransaction.getVersion()).toSerializable(), getSelf());
703 } catch (Exception e) {
704 getSender().tell(new Failure(e), getSelf());
708 private ActorRef createTransaction(final int transactionType, final TransactionIdentifier transactionId) {
709 LOG.debug("{}: Creating transaction : {} ", persistenceId(), transactionId);
710 return transactionActorFactory.newShardTransaction(TransactionType.fromInt(transactionType),
714 private void updateSchemaContext(final UpdateSchemaContext message) {
715 updateSchemaContext(message.getSchemaContext());
719 void updateSchemaContext(final SchemaContext schemaContext) {
720 store.updateSchemaContext(schemaContext);
723 private boolean isMetricsCaptureEnabled() {
724 CommonConfig config = new CommonConfig(getContext().system().settings().config());
725 return config.isMetricCaptureEnabled();
730 public RaftActorSnapshotCohort getRaftActorSnapshotCohort() {
731 return snapshotCohort;
736 protected RaftActorRecoveryCohort getRaftActorRecoveryCohort() {
737 return new ShardRecoveryCoordinator(store,
738 restoreFromSnapshot != null ? restoreFromSnapshot.getSnapshot() : null, persistenceId(), LOG);
742 protected void onRecoveryComplete() {
743 restoreFromSnapshot = null;
745 //notify shard manager
746 getContext().parent().tell(new ActorInitialized(), getSelf());
748 // Being paranoid here - this method should only be called once but just in case...
749 if (txCommitTimeoutCheckSchedule == null) {
750 // Schedule a message to be periodically sent to check if the current in-progress
751 // transaction should be expired and aborted.
752 FiniteDuration period = Duration.create(transactionCommitTimeout / 3, TimeUnit.MILLISECONDS);
753 txCommitTimeoutCheckSchedule = getContext().system().scheduler().schedule(
754 period, period, getSelf(),
755 TX_COMMIT_TIMEOUT_CHECK_MESSAGE, getContext().dispatcher(), ActorRef.noSender());
760 protected void applyState(final ActorRef clientActor, final Identifier identifier, final Object data) {
761 if (data instanceof Payload) {
763 store.applyReplicatedPayload(identifier, (Payload)data);
764 } catch (DataValidationFailedException | IOException e) {
765 LOG.error("{}: Error applying replica {}", persistenceId(), identifier, e);
768 LOG.error("{}: Unknown state for {} received {}", persistenceId(), identifier, data);
773 protected void onStateChanged() {
774 boolean isLeader = isLeader();
775 boolean hasLeader = hasLeader();
776 changeSupport.onLeadershipChange(isLeader, hasLeader);
777 treeChangeSupport.onLeadershipChange(isLeader, hasLeader);
779 // If this actor is no longer the leader close all the transaction chains
781 if (LOG.isDebugEnabled()) {
783 "{}: onStateChanged: Closing all transaction chains because shard {} is no longer the leader",
784 persistenceId(), getId());
787 store.purgeLeaderState();
790 if (hasLeader && !isIsolatedLeader()) {
791 messageRetrySupport.retryMessages();
796 protected void onLeaderChanged(final String oldLeader, final String newLeader) {
797 shardMBean.incrementLeadershipChangeCount();
799 final boolean hasLeader = hasLeader();
801 // No leader implies we are not the leader, lose frontend state if we have any. This also places
802 // an explicit guard so the map will not get modified accidentally.
803 if (!knownFrontends.isEmpty()) {
804 LOG.debug("{}: removing frontend state for {}", persistenceId(), knownFrontends.keySet());
805 knownFrontends = ImmutableMap.of();
811 // Another leader was elected. If we were the previous leader and had pending transactions, convert
812 // them to transaction messages and send to the new leader.
813 ActorSelection leader = getLeader();
814 if (leader != null) {
815 Collection<?> messagesToForward = convertPendingTransactionsToMessages();
817 if (!messagesToForward.isEmpty()) {
818 LOG.debug("{}: Forwarding {} pending transaction messages to leader {}", persistenceId(),
819 messagesToForward.size(), leader);
821 for (Object message : messagesToForward) {
822 leader.tell(message, self());
826 commitCoordinator.abortPendingTransactions("The transacton was aborted due to inflight leadership "
827 + "change and the leader address isn't available.", this);
830 // We have become the leader, we need to reconstruct frontend state
831 knownFrontends = Verify.verifyNotNull(frontendMetadata.toLeaderState(this));
832 LOG.debug("{}: became leader with frontend state for {}", persistenceId(), knownFrontends.keySet());
835 if (!isIsolatedLeader()) {
836 messageRetrySupport.retryMessages();
841 * Clears all pending transactions and converts them to messages to be forwarded to a new leader.
843 * @return the converted messages
845 public Collection<?> convertPendingTransactionsToMessages() {
846 return commitCoordinator.convertPendingTransactionsToMessages(
847 datastoreContext.getShardBatchedModificationCount());
851 protected void pauseLeader(final Runnable operation) {
852 LOG.debug("{}: In pauseLeader, operation: {}", persistenceId(), operation);
853 store.setRunOnPendingTransactionsComplete(operation);
857 protected OnDemandRaftState.AbstractBuilder<?> newOnDemandRaftStateBuilder() {
858 return OnDemandShardState.newBuilder().treeChangeListenerActors(treeChangeSupport.getListenerActors())
859 .dataChangeListenerActors(changeSupport.getListenerActors())
860 .commitCohortActors(store.getCohortActors());
864 public String persistenceId() {
869 ShardCommitCoordinator getCommitCoordinator() {
870 return commitCoordinator;
873 public DatastoreContext getDatastoreContext() {
874 return datastoreContext;
878 public ShardDataTree getDataStore() {
883 ShardStats getShardMBean() {
887 public static Builder builder() {
888 return new Builder();
891 public abstract static class AbstractBuilder<T extends AbstractBuilder<T, S>, S extends Shard> {
892 private final Class<S> shardClass;
893 private ShardIdentifier id;
894 private Map<String, String> peerAddresses = Collections.emptyMap();
895 private DatastoreContext datastoreContext;
896 private SchemaContextProvider schemaContextProvider;
897 private DatastoreSnapshot.ShardSnapshot restoreFromSnapshot;
898 private TipProducingDataTree dataTree;
899 private volatile boolean sealed;
901 protected AbstractBuilder(final Class<S> shardClass) {
902 this.shardClass = shardClass;
905 protected void checkSealed() {
906 Preconditions.checkState(!sealed, "Builder isalready sealed - further modifications are not allowed");
909 @SuppressWarnings("unchecked")
914 public T id(final ShardIdentifier newId) {
920 public T peerAddresses(final Map<String, String> newPeerAddresses) {
922 this.peerAddresses = newPeerAddresses;
926 public T datastoreContext(final DatastoreContext newDatastoreContext) {
928 this.datastoreContext = newDatastoreContext;
932 public T schemaContextProvider(final SchemaContextProvider schemaContextProvider) {
934 this.schemaContextProvider = Preconditions.checkNotNull(schemaContextProvider);
938 public T restoreFromSnapshot(final DatastoreSnapshot.ShardSnapshot newRestoreFromSnapshot) {
940 this.restoreFromSnapshot = newRestoreFromSnapshot;
944 public T dataTree(final TipProducingDataTree newDataTree) {
946 this.dataTree = newDataTree;
950 public ShardIdentifier getId() {
954 public Map<String, String> getPeerAddresses() {
955 return peerAddresses;
958 public DatastoreContext getDatastoreContext() {
959 return datastoreContext;
962 public SchemaContext getSchemaContext() {
963 return Verify.verifyNotNull(schemaContextProvider.getSchemaContext());
966 public DatastoreSnapshot.ShardSnapshot getRestoreFromSnapshot() {
967 return restoreFromSnapshot;
970 public TipProducingDataTree getDataTree() {
974 public TreeType getTreeType() {
975 switch (datastoreContext.getLogicalStoreType()) {
977 return TreeType.CONFIGURATION;
979 return TreeType.OPERATIONAL;
981 throw new IllegalStateException("Unhandled logical store type "
982 + datastoreContext.getLogicalStoreType());
986 protected void verify() {
987 Preconditions.checkNotNull(id, "id should not be null");
988 Preconditions.checkNotNull(peerAddresses, "peerAddresses should not be null");
989 Preconditions.checkNotNull(datastoreContext, "dataStoreContext should not be null");
990 Preconditions.checkNotNull(schemaContextProvider, "schemaContextProvider should not be null");
993 public Props props() {
996 return Props.create(shardClass, this);
1000 public static class Builder extends AbstractBuilder<Builder, Shard> {
1007 return Ticker.systemTicker();
1010 void scheduleNextPendingTransaction() {
1011 self().tell(RESUME_NEXT_PENDING_TRANSACTION, ActorRef.noSender());