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.Failure;
16 import akka.serialization.Serialization;
17 import com.google.common.annotations.VisibleForTesting;
18 import com.google.common.base.Optional;
19 import com.google.common.base.Preconditions;
20 import com.google.common.base.Ticker;
21 import com.google.common.base.Verify;
22 import com.google.common.collect.ImmutableList;
23 import com.google.common.collect.ImmutableMap;
24 import com.google.common.collect.Range;
25 import java.io.IOException;
26 import java.util.Arrays;
27 import java.util.Collection;
28 import java.util.Collections;
30 import java.util.concurrent.TimeUnit;
31 import javax.annotation.Nonnull;
32 import javax.annotation.Nullable;
33 import org.opendaylight.controller.cluster.access.ABIVersion;
34 import org.opendaylight.controller.cluster.access.commands.ConnectClientRequest;
35 import org.opendaylight.controller.cluster.access.commands.ConnectClientSuccess;
36 import org.opendaylight.controller.cluster.access.commands.LocalHistoryRequest;
37 import org.opendaylight.controller.cluster.access.commands.NotLeaderException;
38 import org.opendaylight.controller.cluster.access.commands.TransactionRequest;
39 import org.opendaylight.controller.cluster.access.concepts.ClientIdentifier;
40 import org.opendaylight.controller.cluster.access.concepts.FrontendIdentifier;
41 import org.opendaylight.controller.cluster.access.concepts.LocalHistoryIdentifier;
42 import org.opendaylight.controller.cluster.access.concepts.Request;
43 import org.opendaylight.controller.cluster.access.concepts.RequestEnvelope;
44 import org.opendaylight.controller.cluster.access.concepts.RequestException;
45 import org.opendaylight.controller.cluster.access.concepts.RequestSuccess;
46 import org.opendaylight.controller.cluster.access.concepts.RetiredGenerationException;
47 import org.opendaylight.controller.cluster.access.concepts.RuntimeRequestException;
48 import org.opendaylight.controller.cluster.access.concepts.TransactionIdentifier;
49 import org.opendaylight.controller.cluster.access.concepts.UnsupportedRequestException;
50 import org.opendaylight.controller.cluster.common.actor.CommonConfig;
51 import org.opendaylight.controller.cluster.common.actor.MessageTracker;
52 import org.opendaylight.controller.cluster.common.actor.MessageTracker.Error;
53 import org.opendaylight.controller.cluster.common.actor.MeteringBehavior;
54 import org.opendaylight.controller.cluster.datastore.exceptions.NoShardLeaderException;
55 import org.opendaylight.controller.cluster.datastore.identifiers.ShardIdentifier;
56 import org.opendaylight.controller.cluster.datastore.jmx.mbeans.shard.ShardMBeanFactory;
57 import org.opendaylight.controller.cluster.datastore.jmx.mbeans.shard.ShardStats;
58 import org.opendaylight.controller.cluster.datastore.messages.AbortTransaction;
59 import org.opendaylight.controller.cluster.datastore.messages.ActorInitialized;
60 import org.opendaylight.controller.cluster.datastore.messages.BatchedModifications;
61 import org.opendaylight.controller.cluster.datastore.messages.CanCommitTransaction;
62 import org.opendaylight.controller.cluster.datastore.messages.CloseTransactionChain;
63 import org.opendaylight.controller.cluster.datastore.messages.CommitTransaction;
64 import org.opendaylight.controller.cluster.datastore.messages.CreateTransaction;
65 import org.opendaylight.controller.cluster.datastore.messages.CreateTransactionReply;
66 import org.opendaylight.controller.cluster.datastore.messages.ForwardedReadyTransaction;
67 import org.opendaylight.controller.cluster.datastore.messages.GetShardDataTree;
68 import org.opendaylight.controller.cluster.datastore.messages.OnDemandShardState;
69 import org.opendaylight.controller.cluster.datastore.messages.PeerAddressResolved;
70 import org.opendaylight.controller.cluster.datastore.messages.PersistAbortTransactionPayload;
71 import org.opendaylight.controller.cluster.datastore.messages.ReadyLocalTransaction;
72 import org.opendaylight.controller.cluster.datastore.messages.RegisterChangeListener;
73 import org.opendaylight.controller.cluster.datastore.messages.RegisterDataTreeChangeListener;
74 import org.opendaylight.controller.cluster.datastore.messages.ShardLeaderStateChanged;
75 import org.opendaylight.controller.cluster.datastore.messages.UpdateSchemaContext;
76 import org.opendaylight.controller.cluster.datastore.persisted.AbortTransactionPayload;
77 import org.opendaylight.controller.cluster.datastore.persisted.DatastoreSnapshot;
78 import org.opendaylight.controller.cluster.datastore.persisted.DatastoreSnapshot.ShardSnapshot;
79 import org.opendaylight.controller.cluster.datastore.utils.Dispatchers;
80 import org.opendaylight.controller.cluster.notifications.LeaderStateChanged;
81 import org.opendaylight.controller.cluster.notifications.RegisterRoleChangeListener;
82 import org.opendaylight.controller.cluster.notifications.RoleChangeNotifier;
83 import org.opendaylight.controller.cluster.raft.RaftActor;
84 import org.opendaylight.controller.cluster.raft.RaftActorRecoveryCohort;
85 import org.opendaylight.controller.cluster.raft.RaftActorSnapshotCohort;
86 import org.opendaylight.controller.cluster.raft.RaftState;
87 import org.opendaylight.controller.cluster.raft.base.messages.FollowerInitialSyncUpStatus;
88 import org.opendaylight.controller.cluster.raft.client.messages.OnDemandRaftState;
89 import org.opendaylight.controller.cluster.raft.messages.AppendEntriesReply;
90 import org.opendaylight.controller.cluster.raft.messages.ServerRemoved;
91 import org.opendaylight.controller.cluster.raft.protobuff.client.messages.Payload;
92 import org.opendaylight.yangtools.concepts.Identifier;
93 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataValidationFailedException;
94 import org.opendaylight.yangtools.yang.data.api.schema.tree.TipProducingDataTree;
95 import org.opendaylight.yangtools.yang.data.api.schema.tree.TreeType;
96 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
97 import scala.concurrent.duration.Duration;
98 import scala.concurrent.duration.FiniteDuration;
101 * A Shard represents a portion of the logical data tree.
104 * Our Shard uses InMemoryDataTree as it's internal representation and delegates all requests it
106 public class Shard extends RaftActor {
109 static final Object TX_COMMIT_TIMEOUT_CHECK_MESSAGE = new Object() {
111 public String toString() {
112 return "txCommitTimeoutCheck";
117 static final Object GET_SHARD_MBEAN_MESSAGE = new Object() {
119 public String toString() {
120 return "getShardMBeanMessage";
124 // FIXME: shard names should be encapsulated in their own class and this should be exposed as a constant.
125 public static final String DEFAULT_NAME = "default";
127 private static final Collection<ABIVersion> SUPPORTED_ABIVERSIONS;
130 final ABIVersion[] values = ABIVersion.values();
131 final ABIVersion[] real = Arrays.copyOfRange(values, 1, values.length - 1);
132 SUPPORTED_ABIVERSIONS = ImmutableList.copyOf(real).reverse();
135 // FIXME: make this a dynamic property based on mailbox size and maximum number of clients
136 private static final int CLIENT_MAX_MESSAGES = 1000;
138 // The state of this Shard
139 private final ShardDataTree store;
141 /// The name of this shard
142 private final String name;
144 private final ShardStats shardMBean;
146 private DatastoreContext datastoreContext;
148 private final ShardCommitCoordinator commitCoordinator;
150 private long transactionCommitTimeout;
152 private Cancellable txCommitTimeoutCheckSchedule;
154 private final Optional<ActorRef> roleChangeNotifier;
156 private final MessageTracker appendEntriesReplyTracker;
158 private final ShardTransactionActorFactory transactionActorFactory;
160 private final ShardSnapshotCohort snapshotCohort;
162 private final DataTreeChangeListenerSupport treeChangeSupport = new DataTreeChangeListenerSupport(this);
163 private final DataChangeListenerSupport changeSupport = new DataChangeListenerSupport(this);
166 private ShardSnapshot restoreFromSnapshot;
168 private final ShardTransactionMessageRetrySupport messageRetrySupport;
170 private final FrontendMetadata frontendMetadata;
171 private Map<FrontendIdentifier, LeaderFrontendState> knownFrontends = ImmutableMap.of();
173 protected Shard(final AbstractBuilder<?, ?> builder) {
174 super(builder.getId().toString(), builder.getPeerAddresses(),
175 Optional.of(builder.getDatastoreContext().getShardRaftConfig()), DataStoreVersions.CURRENT_VERSION);
177 this.name = builder.getId().toString();
178 this.datastoreContext = builder.getDatastoreContext();
179 this.restoreFromSnapshot = builder.getRestoreFromSnapshot();
180 this.frontendMetadata = new FrontendMetadata(name);
182 setPersistence(datastoreContext.isPersistent());
184 LOG.info("Shard created : {}, persistent : {}", name, datastoreContext.isPersistent());
186 ShardDataTreeChangeListenerPublisherActorProxy treeChangeListenerPublisher =
187 new ShardDataTreeChangeListenerPublisherActorProxy(getContext(), name + "-DTCL-publisher");
188 ShardDataChangeListenerPublisherActorProxy dataChangeListenerPublisher =
189 new ShardDataChangeListenerPublisherActorProxy(getContext(), name + "-DCL-publisher");
190 if (builder.getDataTree() != null) {
191 store = new ShardDataTree(this, builder.getSchemaContext(), builder.getDataTree(),
192 treeChangeListenerPublisher, dataChangeListenerPublisher, name, frontendMetadata);
194 store = new ShardDataTree(this, builder.getSchemaContext(), builder.getTreeType(),
195 builder.getDatastoreContext().getStoreRoot(), treeChangeListenerPublisher,
196 dataChangeListenerPublisher, name, frontendMetadata);
199 shardMBean = ShardMBeanFactory.getShardStatsMBean(name, datastoreContext.getDataStoreMXBeanType(), this);
201 if (isMetricsCaptureEnabled()) {
202 getContext().become(new MeteringBehavior(this));
205 commitCoordinator = new ShardCommitCoordinator(store, LOG, this.name);
207 setTransactionCommitTimeout();
209 // create a notifier actor for each cluster member
210 roleChangeNotifier = createRoleChangeNotifier(name);
212 appendEntriesReplyTracker = new MessageTracker(AppendEntriesReply.class,
213 getRaftActorContext().getConfigParams().getIsolatedCheckIntervalInMillis());
215 transactionActorFactory = new ShardTransactionActorFactory(store, datastoreContext,
216 new Dispatchers(context().system().dispatchers()).getDispatcherPath(Dispatchers.DispatcherType.Transaction),
217 self(), getContext(), shardMBean, builder.getId().getShardName());
219 snapshotCohort = ShardSnapshotCohort.create(getContext(), builder.getId().getMemberName(), store, LOG,
222 messageRetrySupport = new ShardTransactionMessageRetrySupport(this);
225 private void setTransactionCommitTimeout() {
226 transactionCommitTimeout = TimeUnit.MILLISECONDS.convert(
227 datastoreContext.getShardTransactionCommitTimeoutInSeconds(), TimeUnit.SECONDS) / 2;
230 private Optional<ActorRef> createRoleChangeNotifier(final String shardId) {
231 ActorRef shardRoleChangeNotifier = this.getContext().actorOf(
232 RoleChangeNotifier.getProps(shardId), shardId + "-notifier");
233 return Optional.of(shardRoleChangeNotifier);
237 public void postStop() {
238 LOG.info("Stopping Shard {}", persistenceId());
242 messageRetrySupport.close();
244 if (txCommitTimeoutCheckSchedule != null) {
245 txCommitTimeoutCheckSchedule.cancel();
248 commitCoordinator.abortPendingTransactions("Transaction aborted due to shutdown.", this);
250 shardMBean.unregisterMBean();
254 protected void handleRecover(final Object message) {
255 LOG.debug("{}: onReceiveRecover: Received message {} from {}", persistenceId(), message.getClass(),
258 super.handleRecover(message);
259 if (LOG.isTraceEnabled()) {
260 appendEntriesReplyTracker.begin();
264 @SuppressWarnings("checkstyle:IllegalCatch")
266 protected void handleNonRaftCommand(final Object message) {
267 try (MessageTracker.Context context = appendEntriesReplyTracker.received(message)) {
268 final Optional<Error> maybeError = context.error();
269 if (maybeError.isPresent()) {
270 LOG.trace("{} : AppendEntriesReply failed to arrive at the expected interval {}", persistenceId(),
274 if (message instanceof RequestEnvelope) {
275 final long now = ticker().read();
276 final RequestEnvelope envelope = (RequestEnvelope)message;
279 final RequestSuccess<?, ?> success = handleRequest(envelope, now);
280 if (success != null) {
281 envelope.sendSuccess(success, ticker().read() - now);
283 } catch (RequestException e) {
284 LOG.debug("{}: request {} failed", persistenceId(), envelope, e);
285 envelope.sendFailure(e, ticker().read() - now);
286 } catch (Exception e) {
287 LOG.debug("{}: request {} caused failure", persistenceId(), envelope, e);
288 envelope.sendFailure(new RuntimeRequestException("Request failed to process", e),
289 ticker().read() - now);
291 } else if (message instanceof ConnectClientRequest) {
292 handleConnectClient((ConnectClientRequest)message);
293 } else if (CreateTransaction.isSerializedType(message)) {
294 handleCreateTransaction(message);
295 } else if (message instanceof BatchedModifications) {
296 handleBatchedModifications((BatchedModifications)message);
297 } else if (message instanceof ForwardedReadyTransaction) {
298 handleForwardedReadyTransaction((ForwardedReadyTransaction) message);
299 } else if (message instanceof ReadyLocalTransaction) {
300 handleReadyLocalTransaction((ReadyLocalTransaction)message);
301 } else if (CanCommitTransaction.isSerializedType(message)) {
302 handleCanCommitTransaction(CanCommitTransaction.fromSerializable(message));
303 } else if (CommitTransaction.isSerializedType(message)) {
304 handleCommitTransaction(CommitTransaction.fromSerializable(message));
305 } else if (AbortTransaction.isSerializedType(message)) {
306 handleAbortTransaction(AbortTransaction.fromSerializable(message));
307 } else if (CloseTransactionChain.isSerializedType(message)) {
308 closeTransactionChain(CloseTransactionChain.fromSerializable(message));
309 } else if (message instanceof RegisterChangeListener) {
310 changeSupport.onMessage((RegisterChangeListener) message, isLeader(), hasLeader());
311 } else if (message instanceof RegisterDataTreeChangeListener) {
312 treeChangeSupport.onMessage((RegisterDataTreeChangeListener) message, isLeader(), hasLeader());
313 } else if (message instanceof UpdateSchemaContext) {
314 updateSchemaContext((UpdateSchemaContext) message);
315 } else if (message instanceof PeerAddressResolved) {
316 PeerAddressResolved resolved = (PeerAddressResolved) message;
317 setPeerAddress(resolved.getPeerId(), resolved.getPeerAddress());
318 } else if (TX_COMMIT_TIMEOUT_CHECK_MESSAGE.equals(message)) {
319 store.checkForExpiredTransactions(transactionCommitTimeout);
320 commitCoordinator.checkForExpiredTransactions(transactionCommitTimeout, this);
321 } else if (message instanceof DatastoreContext) {
322 onDatastoreContext((DatastoreContext)message);
323 } else if (message instanceof RegisterRoleChangeListener) {
324 roleChangeNotifier.get().forward(message, context());
325 } else if (message instanceof FollowerInitialSyncUpStatus) {
326 shardMBean.setFollowerInitialSyncStatus(((FollowerInitialSyncUpStatus) message).isInitialSyncDone());
327 context().parent().tell(message, self());
328 } else if (GET_SHARD_MBEAN_MESSAGE.equals(message)) {
329 sender().tell(getShardMBean(), self());
330 } else if (message instanceof GetShardDataTree) {
331 sender().tell(store.getDataTree(), self());
332 } else if (message instanceof ServerRemoved) {
333 context().parent().forward(message, context());
334 } else if (ShardTransactionMessageRetrySupport.TIMER_MESSAGE_CLASS.isInstance(message)) {
335 messageRetrySupport.onTimerMessage(message);
336 } else if (message instanceof DataTreeCohortActorRegistry.CohortRegistryCommand) {
337 store.processCohortRegistryCommand(getSender(),
338 (DataTreeCohortActorRegistry.CohortRegistryCommand) message);
339 } else if (message instanceof PersistAbortTransactionPayload) {
340 final TransactionIdentifier txId = ((PersistAbortTransactionPayload) message).getTransactionId();
341 persistPayload(txId, AbortTransactionPayload.create(txId), true);
343 super.handleNonRaftCommand(message);
348 // Acquire our frontend tracking handle and verify generation matches
349 private LeaderFrontendState getFrontend(final ClientIdentifier clientId) throws RequestException {
350 final LeaderFrontendState existing = knownFrontends.get(clientId.getFrontendId());
351 if (existing != null) {
352 final int cmp = Long.compareUnsigned(existing.getIdentifier().getGeneration(), clientId.getGeneration());
357 LOG.debug("{}: rejecting request from outdated client {}", persistenceId(), clientId);
358 throw new RetiredGenerationException(existing.getIdentifier().getGeneration());
361 LOG.info("{}: retiring state {}, outdated by request from client {}", persistenceId(), existing, clientId);
363 knownFrontends.remove(clientId.getFrontendId());
365 LOG.debug("{}: client {} is not yet known", persistenceId(), clientId);
368 final LeaderFrontendState ret = new LeaderFrontendState(persistenceId(), clientId, store);
369 knownFrontends.put(clientId.getFrontendId(), ret);
370 LOG.debug("{}: created state {} for client {}", persistenceId(), ret, clientId);
374 private static @Nonnull ABIVersion selectVersion(final ConnectClientRequest message) {
375 final Range<ABIVersion> clientRange = Range.closed(message.getMinVersion(), message.getMaxVersion());
376 for (ABIVersion v : SUPPORTED_ABIVERSIONS) {
377 if (clientRange.contains(v)) {
382 throw new IllegalArgumentException(String.format(
383 "No common version between backend versions %s and client versions %s", SUPPORTED_ABIVERSIONS,
387 @SuppressWarnings("checkstyle:IllegalCatch")
388 private void handleConnectClient(final ConnectClientRequest message) {
390 if (!isLeader() || !isLeaderActive()) {
391 LOG.debug("{}: not currently leader, rejecting request {}", persistenceId(), message);
392 throw new NotLeaderException(getSelf());
395 final ABIVersion selectedVersion = selectVersion(message);
396 final LeaderFrontendState frontend = getFrontend(message.getTarget());
397 frontend.reconnect();
398 message.getReplyTo().tell(new ConnectClientSuccess(message.getTarget(), message.getSequence(), getSelf(),
399 ImmutableList.of(), store.getDataTree(), CLIENT_MAX_MESSAGES).toVersion(selectedVersion),
400 ActorRef.noSender());
401 } catch (RequestException | RuntimeException e) {
402 message.getReplyTo().tell(new Failure(e), ActorRef.noSender());
406 private @Nullable RequestSuccess<?, ?> handleRequest(final RequestEnvelope envelope, final long now)
407 throws RequestException {
408 // We are not the leader, hence we want to fail-fast.
409 if (!isLeader() || !isLeaderActive()) {
410 LOG.debug("{}: not currently leader, rejecting request {}", persistenceId(), envelope);
411 throw new NotLeaderException(getSelf());
414 final Request<?, ?> request = envelope.getMessage();
415 if (request instanceof TransactionRequest) {
416 final TransactionRequest<?> txReq = (TransactionRequest<?>)request;
417 final ClientIdentifier clientId = txReq.getTarget().getHistoryId().getClientId();
418 return getFrontend(clientId).handleTransactionRequest(txReq, envelope, now);
419 } else if (request instanceof LocalHistoryRequest) {
420 final LocalHistoryRequest<?> lhReq = (LocalHistoryRequest<?>)request;
421 final ClientIdentifier clientId = lhReq.getTarget().getClientId();
422 return getFrontend(clientId).handleLocalHistoryRequest(lhReq, envelope, now);
424 LOG.debug("{}: rejecting unsupported request {}", persistenceId(), request);
425 throw new UnsupportedRequestException(request);
429 private boolean hasLeader() {
430 return getLeaderId() != null;
433 public int getPendingTxCommitQueueSize() {
434 return store.getQueueSize();
437 public int getCohortCacheSize() {
438 return commitCoordinator.getCohortCacheSize();
442 protected Optional<ActorRef> getRoleChangeNotifier() {
443 return roleChangeNotifier;
447 protected LeaderStateChanged newLeaderStateChanged(final String memberId, final String leaderId,
448 final short leaderPayloadVersion) {
449 return isLeader() ? new ShardLeaderStateChanged(memberId, leaderId, store.getDataTree(), leaderPayloadVersion)
450 : new ShardLeaderStateChanged(memberId, leaderId, leaderPayloadVersion);
453 protected void onDatastoreContext(final DatastoreContext context) {
454 datastoreContext = context;
456 setTransactionCommitTimeout();
458 setPersistence(datastoreContext.isPersistent());
460 updateConfigParams(datastoreContext.getShardRaftConfig());
463 // applyState() will be invoked once consensus is reached on the payload
464 void persistPayload(final Identifier id, final Payload payload, final boolean batchHint) {
465 boolean canSkipPayload = !hasFollowers() && !persistence().isRecoveryApplicable();
466 if (canSkipPayload) {
467 applyState(self(), id, payload);
469 // We are faking the sender
470 persistData(self(), id, payload, batchHint);
474 private void handleCommitTransaction(final CommitTransaction commit) {
476 commitCoordinator.handleCommit(commit.getTransactionId(), getSender(), this);
478 ActorSelection leader = getLeader();
479 if (leader == null) {
480 messageRetrySupport.addMessageToRetry(commit, getSender(),
481 "Could not commit transaction " + commit.getTransactionId());
483 LOG.debug("{}: Forwarding CommitTransaction to leader {}", persistenceId(), leader);
484 leader.forward(commit, getContext());
489 private void handleCanCommitTransaction(final CanCommitTransaction canCommit) {
490 LOG.debug("{}: Can committing transaction {}", persistenceId(), canCommit.getTransactionId());
493 commitCoordinator.handleCanCommit(canCommit.getTransactionId(), getSender(), this);
495 ActorSelection leader = getLeader();
496 if (leader == null) {
497 messageRetrySupport.addMessageToRetry(canCommit, getSender(),
498 "Could not canCommit transaction " + canCommit.getTransactionId());
500 LOG.debug("{}: Forwarding CanCommitTransaction to leader {}", persistenceId(), leader);
501 leader.forward(canCommit, getContext());
506 @SuppressWarnings("checkstyle:IllegalCatch")
507 protected void handleBatchedModificationsLocal(final BatchedModifications batched, final ActorRef sender) {
509 commitCoordinator.handleBatchedModifications(batched, sender, this);
510 } catch (Exception e) {
511 LOG.error("{}: Error handling BatchedModifications for Tx {}", persistenceId(),
512 batched.getTransactionId(), e);
513 sender.tell(new Failure(e), getSelf());
517 private void handleBatchedModifications(final BatchedModifications batched) {
518 // This message is sent to prepare the modifications transaction directly on the Shard as an
519 // optimization to avoid the extra overhead of a separate ShardTransaction actor. On the last
520 // BatchedModifications message, the caller sets the ready flag in the message indicating
521 // modifications are complete. The reply contains the cohort actor path (this actor) for the caller
522 // to initiate the 3-phase commit. This also avoids the overhead of sending an additional
523 // ReadyTransaction message.
525 // If we're not the leader then forward to the leader. This is a safety measure - we shouldn't
526 // normally get here if we're not the leader as the front-end (TransactionProxy) should determine
527 // the primary/leader shard. However with timing and caching on the front-end, there's a small
528 // window where it could have a stale leader during leadership transitions.
530 boolean isLeaderActive = isLeaderActive();
531 if (isLeader() && isLeaderActive) {
532 handleBatchedModificationsLocal(batched, getSender());
534 ActorSelection leader = getLeader();
535 if (!isLeaderActive || leader == null) {
536 messageRetrySupport.addMessageToRetry(batched, getSender(),
537 "Could not commit transaction " + batched.getTransactionId());
539 // If this is not the first batch and leadership changed in between batched messages,
540 // we need to reconstruct previous BatchedModifications from the transaction
541 // DataTreeModification, honoring the max batched modification count, and forward all the
542 // previous BatchedModifications to the new leader.
543 Collection<BatchedModifications> newModifications = commitCoordinator
544 .createForwardedBatchedModifications(batched,
545 datastoreContext.getShardBatchedModificationCount());
547 LOG.debug("{}: Forwarding {} BatchedModifications to leader {}", persistenceId(),
548 newModifications.size(), leader);
550 for (BatchedModifications bm : newModifications) {
551 leader.forward(bm, getContext());
557 private boolean failIfIsolatedLeader(final ActorRef sender) {
558 if (isIsolatedLeader()) {
559 sender.tell(new Failure(new NoShardLeaderException(String.format(
560 "Shard %s was the leader but has lost contact with all of its followers. Either all"
561 + " other follower nodes are down or this node is isolated by a network partition.",
562 persistenceId()))), getSelf());
569 protected boolean isIsolatedLeader() {
570 return getRaftState() == RaftState.IsolatedLeader;
573 @SuppressWarnings("checkstyle:IllegalCatch")
574 private void handleReadyLocalTransaction(final ReadyLocalTransaction message) {
575 LOG.debug("{}: handleReadyLocalTransaction for {}", persistenceId(), message.getTransactionId());
577 boolean isLeaderActive = isLeaderActive();
578 if (isLeader() && isLeaderActive) {
580 commitCoordinator.handleReadyLocalTransaction(message, getSender(), this);
581 } catch (Exception e) {
582 LOG.error("{}: Error handling ReadyLocalTransaction for Tx {}", persistenceId(),
583 message.getTransactionId(), e);
584 getSender().tell(new Failure(e), getSelf());
587 ActorSelection leader = getLeader();
588 if (!isLeaderActive || leader == null) {
589 messageRetrySupport.addMessageToRetry(message, getSender(),
590 "Could not commit transaction " + message.getTransactionId());
592 LOG.debug("{}: Forwarding ReadyLocalTransaction to leader {}", persistenceId(), leader);
593 message.setRemoteVersion(getCurrentBehavior().getLeaderPayloadVersion());
594 leader.forward(message, getContext());
599 private void handleForwardedReadyTransaction(final ForwardedReadyTransaction forwardedReady) {
600 LOG.debug("{}: handleForwardedReadyTransaction for {}", persistenceId(), forwardedReady.getTransactionId());
602 boolean isLeaderActive = isLeaderActive();
603 if (isLeader() && isLeaderActive) {
604 commitCoordinator.handleForwardedReadyTransaction(forwardedReady, getSender(), this);
606 ActorSelection leader = getLeader();
607 if (!isLeaderActive || leader == null) {
608 messageRetrySupport.addMessageToRetry(forwardedReady, getSender(),
609 "Could not commit transaction " + forwardedReady.getTransactionId());
611 LOG.debug("{}: Forwarding ForwardedReadyTransaction to leader {}", persistenceId(), leader);
613 ReadyLocalTransaction readyLocal = new ReadyLocalTransaction(forwardedReady.getTransactionId(),
614 forwardedReady.getTransaction().getSnapshot(), forwardedReady.isDoImmediateCommit());
615 readyLocal.setRemoteVersion(getCurrentBehavior().getLeaderPayloadVersion());
616 leader.forward(readyLocal, getContext());
621 private void handleAbortTransaction(final AbortTransaction abort) {
622 doAbortTransaction(abort.getTransactionId(), getSender());
625 void doAbortTransaction(final Identifier transactionID, final ActorRef sender) {
626 commitCoordinator.handleAbort(transactionID, sender, this);
629 private void handleCreateTransaction(final Object message) {
631 createTransaction(CreateTransaction.fromSerializable(message));
632 } else if (getLeader() != null) {
633 getLeader().forward(message, getContext());
635 getSender().tell(new Failure(new NoShardLeaderException(
636 "Could not create a shard transaction", persistenceId())), getSelf());
640 private void closeTransactionChain(final CloseTransactionChain closeTransactionChain) {
641 final LocalHistoryIdentifier id = closeTransactionChain.getIdentifier();
642 store.closeTransactionChain(id, null);
643 store.purgeTransactionChain(id, null);
646 @SuppressWarnings("checkstyle:IllegalCatch")
647 private void createTransaction(final CreateTransaction createTransaction) {
649 if (TransactionType.fromInt(createTransaction.getTransactionType()) != TransactionType.READ_ONLY
650 && failIfIsolatedLeader(getSender())) {
654 ActorRef transactionActor = createTransaction(createTransaction.getTransactionType(),
655 createTransaction.getTransactionId());
657 getSender().tell(new CreateTransactionReply(Serialization.serializedActorPath(transactionActor),
658 createTransaction.getTransactionId(), createTransaction.getVersion()).toSerializable(), getSelf());
659 } catch (Exception e) {
660 getSender().tell(new Failure(e), getSelf());
664 private ActorRef createTransaction(final int transactionType, final TransactionIdentifier transactionId) {
665 LOG.debug("{}: Creating transaction : {} ", persistenceId(), transactionId);
666 return transactionActorFactory.newShardTransaction(TransactionType.fromInt(transactionType),
670 private void updateSchemaContext(final UpdateSchemaContext message) {
671 updateSchemaContext(message.getSchemaContext());
675 void updateSchemaContext(final SchemaContext schemaContext) {
676 store.updateSchemaContext(schemaContext);
679 private boolean isMetricsCaptureEnabled() {
680 CommonConfig config = new CommonConfig(getContext().system().settings().config());
681 return config.isMetricCaptureEnabled();
686 public RaftActorSnapshotCohort getRaftActorSnapshotCohort() {
687 return snapshotCohort;
692 protected RaftActorRecoveryCohort getRaftActorRecoveryCohort() {
693 return new ShardRecoveryCoordinator(store,
694 restoreFromSnapshot != null ? restoreFromSnapshot.getSnapshot() : null, persistenceId(), LOG);
698 protected void onRecoveryComplete() {
699 restoreFromSnapshot = null;
701 //notify shard manager
702 getContext().parent().tell(new ActorInitialized(), getSelf());
704 // Being paranoid here - this method should only be called once but just in case...
705 if (txCommitTimeoutCheckSchedule == null) {
706 // Schedule a message to be periodically sent to check if the current in-progress
707 // transaction should be expired and aborted.
708 FiniteDuration period = Duration.create(transactionCommitTimeout / 3, TimeUnit.MILLISECONDS);
709 txCommitTimeoutCheckSchedule = getContext().system().scheduler().schedule(
710 period, period, getSelf(),
711 TX_COMMIT_TIMEOUT_CHECK_MESSAGE, getContext().dispatcher(), ActorRef.noSender());
716 protected void applyState(final ActorRef clientActor, final Identifier identifier, final Object data) {
717 if (data instanceof Payload) {
719 store.applyReplicatedPayload(identifier, (Payload)data);
720 } catch (DataValidationFailedException | IOException e) {
721 LOG.error("{}: Error applying replica {}", persistenceId(), identifier, e);
724 LOG.error("{}: Unknown state for {} received {}", persistenceId(), identifier, data);
729 protected void onStateChanged() {
730 boolean isLeader = isLeader();
731 boolean hasLeader = hasLeader();
732 changeSupport.onLeadershipChange(isLeader, hasLeader);
733 treeChangeSupport.onLeadershipChange(isLeader, hasLeader);
735 // If this actor is no longer the leader close all the transaction chains
737 if (LOG.isDebugEnabled()) {
739 "{}: onStateChanged: Closing all transaction chains because shard {} is no longer the leader",
740 persistenceId(), getId());
743 store.purgeLeaderState();
746 if (hasLeader && !isIsolatedLeader()) {
747 messageRetrySupport.retryMessages();
752 protected void onLeaderChanged(final String oldLeader, final String newLeader) {
753 shardMBean.incrementLeadershipChangeCount();
755 final boolean hasLeader = hasLeader();
757 // No leader implies we are not the leader, lose frontend state if we have any. This also places
758 // an explicit guard so the map will not get modified accidentally.
759 if (!knownFrontends.isEmpty()) {
760 LOG.debug("{}: removing frontend state for {}", persistenceId(), knownFrontends.keySet());
761 knownFrontends = ImmutableMap.of();
767 // Another leader was elected. If we were the previous leader and had pending transactions, convert
768 // them to transaction messages and send to the new leader.
769 ActorSelection leader = getLeader();
770 if (leader != null) {
771 Collection<?> messagesToForward = convertPendingTransactionsToMessages();
773 if (!messagesToForward.isEmpty()) {
774 LOG.debug("{}: Forwarding {} pending transaction messages to leader {}", persistenceId(),
775 messagesToForward.size(), leader);
777 for (Object message : messagesToForward) {
778 leader.tell(message, self());
782 commitCoordinator.abortPendingTransactions("The transacton was aborted due to inflight leadership "
783 + "change and the leader address isn't available.", this);
786 // We have become the leader, we need to reconstruct frontend state
787 knownFrontends = Verify.verifyNotNull(frontendMetadata.toLeaderState(this));
788 LOG.debug("{}: became leader with frontend state for {}", persistenceId(), knownFrontends.keySet());
791 if (!isIsolatedLeader()) {
792 messageRetrySupport.retryMessages();
797 * Clears all pending transactions and converts them to messages to be forwarded to a new leader.
799 * @return the converted messages
801 public Collection<?> convertPendingTransactionsToMessages() {
802 return commitCoordinator.convertPendingTransactionsToMessages(
803 datastoreContext.getShardBatchedModificationCount());
807 protected void pauseLeader(final Runnable operation) {
808 LOG.debug("{}: In pauseLeader, operation: {}", persistenceId(), operation);
809 store.setRunOnPendingTransactionsComplete(operation);
813 protected OnDemandRaftState.AbstractBuilder<?> newOnDemandRaftStateBuilder() {
814 return OnDemandShardState.newBuilder().treeChangeListenerActors(treeChangeSupport.getListenerActors())
815 .dataChangeListenerActors(changeSupport.getListenerActors())
816 .commitCohortActors(store.getCohortActors());
820 public String persistenceId() {
825 ShardCommitCoordinator getCommitCoordinator() {
826 return commitCoordinator;
829 public DatastoreContext getDatastoreContext() {
830 return datastoreContext;
834 public ShardDataTree getDataStore() {
839 ShardStats getShardMBean() {
843 public static Builder builder() {
844 return new Builder();
847 public abstract static class AbstractBuilder<T extends AbstractBuilder<T, S>, S extends Shard> {
848 private final Class<S> shardClass;
849 private ShardIdentifier id;
850 private Map<String, String> peerAddresses = Collections.emptyMap();
851 private DatastoreContext datastoreContext;
852 private SchemaContext schemaContext;
853 private DatastoreSnapshot.ShardSnapshot restoreFromSnapshot;
854 private TipProducingDataTree dataTree;
855 private volatile boolean sealed;
857 protected AbstractBuilder(final Class<S> shardClass) {
858 this.shardClass = shardClass;
861 protected void checkSealed() {
862 Preconditions.checkState(!sealed, "Builder isalready sealed - further modifications are not allowed");
865 @SuppressWarnings("unchecked")
870 public T id(final ShardIdentifier newId) {
876 public T peerAddresses(final Map<String, String> newPeerAddresses) {
878 this.peerAddresses = newPeerAddresses;
882 public T datastoreContext(final DatastoreContext newDatastoreContext) {
884 this.datastoreContext = newDatastoreContext;
888 public T schemaContext(final SchemaContext newSchemaContext) {
890 this.schemaContext = newSchemaContext;
894 public T restoreFromSnapshot(final DatastoreSnapshot.ShardSnapshot newRestoreFromSnapshot) {
896 this.restoreFromSnapshot = newRestoreFromSnapshot;
900 public T dataTree(final TipProducingDataTree newDataTree) {
902 this.dataTree = newDataTree;
906 public ShardIdentifier getId() {
910 public Map<String, String> getPeerAddresses() {
911 return peerAddresses;
914 public DatastoreContext getDatastoreContext() {
915 return datastoreContext;
918 public SchemaContext getSchemaContext() {
919 return schemaContext;
922 public DatastoreSnapshot.ShardSnapshot getRestoreFromSnapshot() {
923 return restoreFromSnapshot;
926 public TipProducingDataTree getDataTree() {
930 public TreeType getTreeType() {
931 switch (datastoreContext.getLogicalStoreType()) {
933 return TreeType.CONFIGURATION;
935 return TreeType.OPERATIONAL;
937 throw new IllegalStateException("Unhandled logical store type "
938 + datastoreContext.getLogicalStoreType());
942 protected void verify() {
943 Preconditions.checkNotNull(id, "id should not be null");
944 Preconditions.checkNotNull(peerAddresses, "peerAddresses should not be null");
945 Preconditions.checkNotNull(datastoreContext, "dataStoreContext should not be null");
946 Preconditions.checkNotNull(schemaContext, "schemaContext should not be null");
949 public Props props() {
952 return Props.create(shardClass, this);
956 public static class Builder extends AbstractBuilder<Builder, Shard> {
963 return Ticker.systemTicker();