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.info("{}: not currently leader, rejecting request {}. isLeader: {}, isLeaderActive: {},"
436 + "isLeadershipTransferInProgress: {}.",
437 persistenceId(), message, isLeader(), isLeaderActive(), isLeadershipTransferInProgress());
438 throw new NotLeaderException(getSelf());
441 final ABIVersion selectedVersion = selectVersion(message);
442 final LeaderFrontendState frontend = getFrontend(message.getTarget());
443 frontend.reconnect();
444 message.getReplyTo().tell(new ConnectClientSuccess(message.getTarget(), message.getSequence(), getSelf(),
445 ImmutableList.of(), store.getDataTree(), CLIENT_MAX_MESSAGES).toVersion(selectedVersion),
446 ActorRef.noSender());
447 } catch (RequestException | RuntimeException e) {
448 message.getReplyTo().tell(new Failure(e), ActorRef.noSender());
452 private @Nullable RequestSuccess<?, ?> handleRequest(final RequestEnvelope envelope, final long now)
453 throws RequestException {
454 // We are not the leader, hence we want to fail-fast.
455 if (!isLeader() || !isLeaderActive()) {
456 LOG.info("{}: not currently leader, rejecting request {}. isLeader: {}, isLeaderActive: {},"
457 + "isLeadershipTransferInProgress: {}.",
458 persistenceId(), envelope, isLeader(), isLeaderActive(), isLeadershipTransferInProgress());
459 throw new NotLeaderException(getSelf());
462 final Request<?, ?> request = envelope.getMessage();
463 if (request instanceof TransactionRequest) {
464 final TransactionRequest<?> txReq = (TransactionRequest<?>)request;
465 final ClientIdentifier clientId = txReq.getTarget().getHistoryId().getClientId();
466 return getFrontend(clientId).handleTransactionRequest(txReq, envelope, now);
467 } else if (request instanceof LocalHistoryRequest) {
468 final LocalHistoryRequest<?> lhReq = (LocalHistoryRequest<?>)request;
469 final ClientIdentifier clientId = lhReq.getTarget().getClientId();
470 return getFrontend(clientId).handleLocalHistoryRequest(lhReq, envelope, now);
472 LOG.warn("{}: rejecting unsupported request {}", persistenceId(), request);
473 throw new UnsupportedRequestException(request);
477 private boolean hasLeader() {
478 return getLeaderId() != null;
481 public int getPendingTxCommitQueueSize() {
482 return store.getQueueSize();
485 public int getCohortCacheSize() {
486 return commitCoordinator.getCohortCacheSize();
490 protected Optional<ActorRef> getRoleChangeNotifier() {
491 return roleChangeNotifier;
495 protected LeaderStateChanged newLeaderStateChanged(final String memberId, final String leaderId,
496 final short leaderPayloadVersion) {
497 return isLeader() ? new ShardLeaderStateChanged(memberId, leaderId, store.getDataTree(), leaderPayloadVersion)
498 : new ShardLeaderStateChanged(memberId, leaderId, leaderPayloadVersion);
501 protected void onDatastoreContext(final DatastoreContext context) {
502 datastoreContext = context;
504 setTransactionCommitTimeout();
506 setPersistence(datastoreContext.isPersistent());
508 updateConfigParams(datastoreContext.getShardRaftConfig());
511 // applyState() will be invoked once consensus is reached on the payload
512 void persistPayload(final Identifier id, final Payload payload, final boolean batchHint) {
513 boolean canSkipPayload = !hasFollowers() && !persistence().isRecoveryApplicable();
514 if (canSkipPayload) {
515 applyState(self(), id, payload);
517 // We are faking the sender
518 persistData(self(), id, payload, batchHint);
522 private void handleCommitTransaction(final CommitTransaction commit) {
524 commitCoordinator.handleCommit(commit.getTransactionId(), getSender(), this);
526 ActorSelection leader = getLeader();
527 if (leader == null) {
528 messageRetrySupport.addMessageToRetry(commit, getSender(),
529 "Could not commit transaction " + commit.getTransactionId());
531 LOG.debug("{}: Forwarding CommitTransaction to leader {}", persistenceId(), leader);
532 leader.forward(commit, getContext());
537 private void handleCanCommitTransaction(final CanCommitTransaction canCommit) {
538 LOG.debug("{}: Can committing transaction {}", persistenceId(), canCommit.getTransactionId());
541 commitCoordinator.handleCanCommit(canCommit.getTransactionId(), getSender(), this);
543 ActorSelection leader = getLeader();
544 if (leader == null) {
545 messageRetrySupport.addMessageToRetry(canCommit, getSender(),
546 "Could not canCommit transaction " + canCommit.getTransactionId());
548 LOG.debug("{}: Forwarding CanCommitTransaction to leader {}", persistenceId(), leader);
549 leader.forward(canCommit, getContext());
554 @SuppressWarnings("checkstyle:IllegalCatch")
555 protected void handleBatchedModificationsLocal(final BatchedModifications batched, final ActorRef sender) {
557 commitCoordinator.handleBatchedModifications(batched, sender, this);
558 } catch (Exception e) {
559 LOG.error("{}: Error handling BatchedModifications for Tx {}", persistenceId(),
560 batched.getTransactionId(), e);
561 sender.tell(new Failure(e), getSelf());
565 private void handleBatchedModifications(final BatchedModifications batched) {
566 // This message is sent to prepare the modifications transaction directly on the Shard as an
567 // optimization to avoid the extra overhead of a separate ShardTransaction actor. On the last
568 // BatchedModifications message, the caller sets the ready flag in the message indicating
569 // modifications are complete. The reply contains the cohort actor path (this actor) for the caller
570 // to initiate the 3-phase commit. This also avoids the overhead of sending an additional
571 // ReadyTransaction message.
573 // If we're not the leader then forward to the leader. This is a safety measure - we shouldn't
574 // normally get here if we're not the leader as the front-end (TransactionProxy) should determine
575 // the primary/leader shard. However with timing and caching on the front-end, there's a small
576 // window where it could have a stale leader during leadership transitions.
578 boolean isLeaderActive = isLeaderActive();
579 if (isLeader() && isLeaderActive) {
580 handleBatchedModificationsLocal(batched, getSender());
582 ActorSelection leader = getLeader();
583 if (!isLeaderActive || leader == null) {
584 messageRetrySupport.addMessageToRetry(batched, getSender(),
585 "Could not commit transaction " + batched.getTransactionId());
587 // If this is not the first batch and leadership changed in between batched messages,
588 // we need to reconstruct previous BatchedModifications from the transaction
589 // DataTreeModification, honoring the max batched modification count, and forward all the
590 // previous BatchedModifications to the new leader.
591 Collection<BatchedModifications> newModifications = commitCoordinator
592 .createForwardedBatchedModifications(batched,
593 datastoreContext.getShardBatchedModificationCount());
595 LOG.debug("{}: Forwarding {} BatchedModifications to leader {}", persistenceId(),
596 newModifications.size(), leader);
598 for (BatchedModifications bm : newModifications) {
599 leader.forward(bm, getContext());
605 private boolean failIfIsolatedLeader(final ActorRef sender) {
606 if (isIsolatedLeader()) {
607 sender.tell(new Failure(new NoShardLeaderException(String.format(
608 "Shard %s was the leader but has lost contact with all of its followers. Either all"
609 + " other follower nodes are down or this node is isolated by a network partition.",
610 persistenceId()))), getSelf());
617 protected boolean isIsolatedLeader() {
618 return getRaftState() == RaftState.IsolatedLeader;
621 @SuppressWarnings("checkstyle:IllegalCatch")
622 private void handleReadyLocalTransaction(final ReadyLocalTransaction message) {
623 LOG.debug("{}: handleReadyLocalTransaction for {}", persistenceId(), message.getTransactionId());
625 boolean isLeaderActive = isLeaderActive();
626 if (isLeader() && isLeaderActive) {
628 commitCoordinator.handleReadyLocalTransaction(message, getSender(), this);
629 } catch (Exception e) {
630 LOG.error("{}: Error handling ReadyLocalTransaction for Tx {}", persistenceId(),
631 message.getTransactionId(), e);
632 getSender().tell(new Failure(e), getSelf());
635 ActorSelection leader = getLeader();
636 if (!isLeaderActive || leader == null) {
637 messageRetrySupport.addMessageToRetry(message, getSender(),
638 "Could not commit transaction " + message.getTransactionId());
640 LOG.debug("{}: Forwarding ReadyLocalTransaction to leader {}", persistenceId(), leader);
641 message.setRemoteVersion(getCurrentBehavior().getLeaderPayloadVersion());
642 leader.forward(message, getContext());
647 private void handleForwardedReadyTransaction(final ForwardedReadyTransaction forwardedReady) {
648 LOG.debug("{}: handleForwardedReadyTransaction for {}", persistenceId(), forwardedReady.getTransactionId());
650 boolean isLeaderActive = isLeaderActive();
651 if (isLeader() && isLeaderActive) {
652 commitCoordinator.handleForwardedReadyTransaction(forwardedReady, getSender(), this);
654 ActorSelection leader = getLeader();
655 if (!isLeaderActive || leader == null) {
656 messageRetrySupport.addMessageToRetry(forwardedReady, getSender(),
657 "Could not commit transaction " + forwardedReady.getTransactionId());
659 LOG.debug("{}: Forwarding ForwardedReadyTransaction to leader {}", persistenceId(), leader);
661 ReadyLocalTransaction readyLocal = new ReadyLocalTransaction(forwardedReady.getTransactionId(),
662 forwardedReady.getTransaction().getSnapshot(), forwardedReady.isDoImmediateCommit());
663 readyLocal.setRemoteVersion(getCurrentBehavior().getLeaderPayloadVersion());
664 leader.forward(readyLocal, getContext());
669 private void handleAbortTransaction(final AbortTransaction abort) {
670 doAbortTransaction(abort.getTransactionId(), getSender());
673 void doAbortTransaction(final Identifier transactionID, final ActorRef sender) {
674 commitCoordinator.handleAbort(transactionID, sender, this);
677 private void handleCreateTransaction(final Object message) {
679 createTransaction(CreateTransaction.fromSerializable(message));
680 } else if (getLeader() != null) {
681 getLeader().forward(message, getContext());
683 getSender().tell(new Failure(new NoShardLeaderException(
684 "Could not create a shard transaction", persistenceId())), getSelf());
688 private void closeTransactionChain(final CloseTransactionChain closeTransactionChain) {
689 final LocalHistoryIdentifier id = closeTransactionChain.getIdentifier();
690 store.closeTransactionChain(id, null);
691 store.purgeTransactionChain(id, null);
694 @SuppressWarnings("checkstyle:IllegalCatch")
695 private void createTransaction(final CreateTransaction createTransaction) {
697 if (TransactionType.fromInt(createTransaction.getTransactionType()) != TransactionType.READ_ONLY
698 && failIfIsolatedLeader(getSender())) {
702 ActorRef transactionActor = createTransaction(createTransaction.getTransactionType(),
703 createTransaction.getTransactionId());
705 getSender().tell(new CreateTransactionReply(Serialization.serializedActorPath(transactionActor),
706 createTransaction.getTransactionId(), createTransaction.getVersion()).toSerializable(), getSelf());
707 } catch (Exception e) {
708 getSender().tell(new Failure(e), getSelf());
712 private ActorRef createTransaction(final int transactionType, final TransactionIdentifier transactionId) {
713 LOG.debug("{}: Creating transaction : {} ", persistenceId(), transactionId);
714 return transactionActorFactory.newShardTransaction(TransactionType.fromInt(transactionType),
718 private void updateSchemaContext(final UpdateSchemaContext message) {
719 updateSchemaContext(message.getSchemaContext());
723 void updateSchemaContext(final SchemaContext schemaContext) {
724 store.updateSchemaContext(schemaContext);
727 private boolean isMetricsCaptureEnabled() {
728 CommonConfig config = new CommonConfig(getContext().system().settings().config());
729 return config.isMetricCaptureEnabled();
734 public RaftActorSnapshotCohort getRaftActorSnapshotCohort() {
735 return snapshotCohort;
740 protected RaftActorRecoveryCohort getRaftActorRecoveryCohort() {
741 return new ShardRecoveryCoordinator(store,
742 restoreFromSnapshot != null ? restoreFromSnapshot.getSnapshot() : null, persistenceId(), LOG);
746 protected void onRecoveryComplete() {
747 restoreFromSnapshot = null;
749 //notify shard manager
750 getContext().parent().tell(new ActorInitialized(), getSelf());
752 // Being paranoid here - this method should only be called once but just in case...
753 if (txCommitTimeoutCheckSchedule == null) {
754 // Schedule a message to be periodically sent to check if the current in-progress
755 // transaction should be expired and aborted.
756 FiniteDuration period = Duration.create(transactionCommitTimeout / 3, TimeUnit.MILLISECONDS);
757 txCommitTimeoutCheckSchedule = getContext().system().scheduler().schedule(
758 period, period, getSelf(),
759 TX_COMMIT_TIMEOUT_CHECK_MESSAGE, getContext().dispatcher(), ActorRef.noSender());
764 protected void applyState(final ActorRef clientActor, final Identifier identifier, final Object data) {
765 if (data instanceof Payload) {
767 store.applyReplicatedPayload(identifier, (Payload)data);
768 } catch (DataValidationFailedException | IOException e) {
769 LOG.error("{}: Error applying replica {}", persistenceId(), identifier, e);
772 LOG.error("{}: Unknown state for {} received {}", persistenceId(), identifier, data);
777 protected void onStateChanged() {
778 boolean isLeader = isLeader();
779 boolean hasLeader = hasLeader();
780 changeSupport.onLeadershipChange(isLeader, hasLeader);
781 treeChangeSupport.onLeadershipChange(isLeader, hasLeader);
783 // If this actor is no longer the leader close all the transaction chains
785 if (LOG.isDebugEnabled()) {
787 "{}: onStateChanged: Closing all transaction chains because shard {} is no longer the leader",
788 persistenceId(), getId());
791 store.purgeLeaderState();
794 if (hasLeader && !isIsolatedLeader()) {
795 messageRetrySupport.retryMessages();
800 protected void onLeaderChanged(final String oldLeader, final String newLeader) {
801 shardMBean.incrementLeadershipChangeCount();
803 final boolean hasLeader = hasLeader();
805 // No leader implies we are not the leader, lose frontend state if we have any. This also places
806 // an explicit guard so the map will not get modified accidentally.
807 if (!knownFrontends.isEmpty()) {
808 LOG.debug("{}: removing frontend state for {}", persistenceId(), knownFrontends.keySet());
809 knownFrontends = ImmutableMap.of();
815 // Another leader was elected. If we were the previous leader and had pending transactions, convert
816 // them to transaction messages and send to the new leader.
817 ActorSelection leader = getLeader();
818 if (leader != null) {
819 Collection<?> messagesToForward = convertPendingTransactionsToMessages();
821 if (!messagesToForward.isEmpty()) {
822 LOG.debug("{}: Forwarding {} pending transaction messages to leader {}", persistenceId(),
823 messagesToForward.size(), leader);
825 for (Object message : messagesToForward) {
826 leader.tell(message, self());
830 commitCoordinator.abortPendingTransactions("The transacton was aborted due to inflight leadership "
831 + "change and the leader address isn't available.", this);
834 // We have become the leader, we need to reconstruct frontend state
835 knownFrontends = Verify.verifyNotNull(frontendMetadata.toLeaderState(this));
836 LOG.debug("{}: became leader with frontend state for {}", persistenceId(), knownFrontends.keySet());
839 if (!isIsolatedLeader()) {
840 messageRetrySupport.retryMessages();
845 * Clears all pending transactions and converts them to messages to be forwarded to a new leader.
847 * @return the converted messages
849 public Collection<?> convertPendingTransactionsToMessages() {
850 return commitCoordinator.convertPendingTransactionsToMessages(
851 datastoreContext.getShardBatchedModificationCount());
855 protected void pauseLeader(final Runnable operation) {
856 LOG.debug("{}: In pauseLeader, operation: {}", persistenceId(), operation);
857 store.setRunOnPendingTransactionsComplete(operation);
861 protected OnDemandRaftState.AbstractBuilder<?> newOnDemandRaftStateBuilder() {
862 return OnDemandShardState.newBuilder().treeChangeListenerActors(treeChangeSupport.getListenerActors())
863 .dataChangeListenerActors(changeSupport.getListenerActors())
864 .commitCohortActors(store.getCohortActors());
868 public String persistenceId() {
873 ShardCommitCoordinator getCommitCoordinator() {
874 return commitCoordinator;
877 public DatastoreContext getDatastoreContext() {
878 return datastoreContext;
882 public ShardDataTree getDataStore() {
887 ShardStats getShardMBean() {
891 public static Builder builder() {
892 return new Builder();
895 public abstract static class AbstractBuilder<T extends AbstractBuilder<T, S>, S extends Shard> {
896 private final Class<S> shardClass;
897 private ShardIdentifier id;
898 private Map<String, String> peerAddresses = Collections.emptyMap();
899 private DatastoreContext datastoreContext;
900 private SchemaContextProvider schemaContextProvider;
901 private DatastoreSnapshot.ShardSnapshot restoreFromSnapshot;
902 private TipProducingDataTree dataTree;
903 private volatile boolean sealed;
905 protected AbstractBuilder(final Class<S> shardClass) {
906 this.shardClass = shardClass;
909 protected void checkSealed() {
910 Preconditions.checkState(!sealed, "Builder isalready sealed - further modifications are not allowed");
913 @SuppressWarnings("unchecked")
918 public T id(final ShardIdentifier newId) {
924 public T peerAddresses(final Map<String, String> newPeerAddresses) {
926 this.peerAddresses = newPeerAddresses;
930 public T datastoreContext(final DatastoreContext newDatastoreContext) {
932 this.datastoreContext = newDatastoreContext;
936 public T schemaContextProvider(final SchemaContextProvider schemaContextProvider) {
938 this.schemaContextProvider = Preconditions.checkNotNull(schemaContextProvider);
942 public T restoreFromSnapshot(final DatastoreSnapshot.ShardSnapshot newRestoreFromSnapshot) {
944 this.restoreFromSnapshot = newRestoreFromSnapshot;
948 public T dataTree(final TipProducingDataTree newDataTree) {
950 this.dataTree = newDataTree;
954 public ShardIdentifier getId() {
958 public Map<String, String> getPeerAddresses() {
959 return peerAddresses;
962 public DatastoreContext getDatastoreContext() {
963 return datastoreContext;
966 public SchemaContext getSchemaContext() {
967 return Verify.verifyNotNull(schemaContextProvider.getSchemaContext());
970 public DatastoreSnapshot.ShardSnapshot getRestoreFromSnapshot() {
971 return restoreFromSnapshot;
974 public TipProducingDataTree getDataTree() {
978 public TreeType getTreeType() {
979 switch (datastoreContext.getLogicalStoreType()) {
981 return TreeType.CONFIGURATION;
983 return TreeType.OPERATIONAL;
985 throw new IllegalStateException("Unhandled logical store type "
986 + datastoreContext.getLogicalStoreType());
990 protected void verify() {
991 Preconditions.checkNotNull(id, "id should not be null");
992 Preconditions.checkNotNull(peerAddresses, "peerAddresses should not be null");
993 Preconditions.checkNotNull(datastoreContext, "dataStoreContext should not be null");
994 Preconditions.checkNotNull(schemaContextProvider, "schemaContextProvider should not be null");
997 public Props props() {
1000 return Props.create(shardClass, this);
1004 public static class Builder extends AbstractBuilder<Builder, Shard> {
1011 return Ticker.systemTicker();
1014 void scheduleNextPendingTransaction() {
1015 self().tell(RESUME_NEXT_PENDING_TRANSACTION, ActorRef.noSender());