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.ReadyLocalTransaction;
71 import org.opendaylight.controller.cluster.datastore.messages.RegisterChangeListener;
72 import org.opendaylight.controller.cluster.datastore.messages.RegisterDataTreeChangeListener;
73 import org.opendaylight.controller.cluster.datastore.messages.ShardLeaderStateChanged;
74 import org.opendaylight.controller.cluster.datastore.messages.UpdateSchemaContext;
75 import org.opendaylight.controller.cluster.datastore.persisted.DatastoreSnapshot;
76 import org.opendaylight.controller.cluster.datastore.persisted.DatastoreSnapshot.ShardSnapshot;
77 import org.opendaylight.controller.cluster.datastore.utils.Dispatchers;
78 import org.opendaylight.controller.cluster.notifications.LeaderStateChanged;
79 import org.opendaylight.controller.cluster.notifications.RegisterRoleChangeListener;
80 import org.opendaylight.controller.cluster.notifications.RoleChangeNotifier;
81 import org.opendaylight.controller.cluster.raft.RaftActor;
82 import org.opendaylight.controller.cluster.raft.RaftActorRecoveryCohort;
83 import org.opendaylight.controller.cluster.raft.RaftActorSnapshotCohort;
84 import org.opendaylight.controller.cluster.raft.RaftState;
85 import org.opendaylight.controller.cluster.raft.base.messages.FollowerInitialSyncUpStatus;
86 import org.opendaylight.controller.cluster.raft.client.messages.OnDemandRaftState;
87 import org.opendaylight.controller.cluster.raft.messages.AppendEntriesReply;
88 import org.opendaylight.controller.cluster.raft.messages.ServerRemoved;
89 import org.opendaylight.controller.cluster.raft.protobuff.client.messages.Payload;
90 import org.opendaylight.yangtools.concepts.Identifier;
91 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataValidationFailedException;
92 import org.opendaylight.yangtools.yang.data.api.schema.tree.TipProducingDataTree;
93 import org.opendaylight.yangtools.yang.data.api.schema.tree.TreeType;
94 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
95 import scala.concurrent.duration.Duration;
96 import scala.concurrent.duration.FiniteDuration;
99 * A Shard represents a portion of the logical data tree.
102 * Our Shard uses InMemoryDataTree as it's internal representation and delegates all requests it
104 public class Shard extends RaftActor {
107 static final Object TX_COMMIT_TIMEOUT_CHECK_MESSAGE = new Object() {
109 public String toString() {
110 return "txCommitTimeoutCheck";
115 static final Object GET_SHARD_MBEAN_MESSAGE = new Object() {
117 public String toString() {
118 return "getShardMBeanMessage";
122 // FIXME: shard names should be encapsulated in their own class and this should be exposed as a constant.
123 public static final String DEFAULT_NAME = "default";
125 private static final Collection<ABIVersion> SUPPORTED_ABIVERSIONS;
128 final ABIVersion[] values = ABIVersion.values();
129 final ABIVersion[] real = Arrays.copyOfRange(values, 1, values.length - 1);
130 SUPPORTED_ABIVERSIONS = ImmutableList.copyOf(real).reverse();
133 // FIXME: make this a dynamic property based on mailbox size and maximum number of clients
134 private static final int CLIENT_MAX_MESSAGES = 1000;
136 // The state of this Shard
137 private final ShardDataTree store;
139 /// The name of this shard
140 private final String name;
142 private final ShardStats shardMBean;
144 private DatastoreContext datastoreContext;
146 private final ShardCommitCoordinator commitCoordinator;
148 private long transactionCommitTimeout;
150 private Cancellable txCommitTimeoutCheckSchedule;
152 private final Optional<ActorRef> roleChangeNotifier;
154 private final MessageTracker appendEntriesReplyTracker;
156 private final ShardTransactionActorFactory transactionActorFactory;
158 private final ShardSnapshotCohort snapshotCohort;
160 private final DataTreeChangeListenerSupport treeChangeSupport = new DataTreeChangeListenerSupport(this);
161 private final DataChangeListenerSupport changeSupport = new DataChangeListenerSupport(this);
164 private ShardSnapshot restoreFromSnapshot;
166 private final ShardTransactionMessageRetrySupport messageRetrySupport;
168 private final FrontendMetadata frontendMetadata;
169 private Map<FrontendIdentifier, LeaderFrontendState> knownFrontends = ImmutableMap.of();
171 protected Shard(final AbstractBuilder<?, ?> builder) {
172 super(builder.getId().toString(), builder.getPeerAddresses(),
173 Optional.of(builder.getDatastoreContext().getShardRaftConfig()), DataStoreVersions.CURRENT_VERSION);
175 this.name = builder.getId().toString();
176 this.datastoreContext = builder.getDatastoreContext();
177 this.restoreFromSnapshot = builder.getRestoreFromSnapshot();
178 this.frontendMetadata = new FrontendMetadata(name);
180 setPersistence(datastoreContext.isPersistent());
182 LOG.info("Shard created : {}, persistent : {}", name, datastoreContext.isPersistent());
184 ShardDataTreeChangeListenerPublisherActorProxy treeChangeListenerPublisher =
185 new ShardDataTreeChangeListenerPublisherActorProxy(getContext(), name + "-DTCL-publisher");
186 ShardDataChangeListenerPublisherActorProxy dataChangeListenerPublisher =
187 new ShardDataChangeListenerPublisherActorProxy(getContext(), name + "-DCL-publisher");
188 if (builder.getDataTree() != null) {
189 store = new ShardDataTree(this, builder.getSchemaContext(), builder.getDataTree(),
190 treeChangeListenerPublisher, dataChangeListenerPublisher, name, frontendMetadata);
192 store = new ShardDataTree(this, builder.getSchemaContext(), builder.getTreeType(),
193 builder.getDatastoreContext().getStoreRoot(), treeChangeListenerPublisher,
194 dataChangeListenerPublisher, name, frontendMetadata);
197 shardMBean = ShardMBeanFactory.getShardStatsMBean(name, datastoreContext.getDataStoreMXBeanType(), this);
199 if (isMetricsCaptureEnabled()) {
200 getContext().become(new MeteringBehavior(this));
203 commitCoordinator = new ShardCommitCoordinator(store, LOG, this.name);
205 setTransactionCommitTimeout();
207 // create a notifier actor for each cluster member
208 roleChangeNotifier = createRoleChangeNotifier(name);
210 appendEntriesReplyTracker = new MessageTracker(AppendEntriesReply.class,
211 getRaftActorContext().getConfigParams().getIsolatedCheckIntervalInMillis());
213 transactionActorFactory = new ShardTransactionActorFactory(store, datastoreContext,
214 new Dispatchers(context().system().dispatchers()).getDispatcherPath(Dispatchers.DispatcherType.Transaction),
215 self(), getContext(), shardMBean, builder.getId().getShardName());
217 snapshotCohort = ShardSnapshotCohort.create(getContext(), builder.getId().getMemberName(), store, LOG,
220 messageRetrySupport = new ShardTransactionMessageRetrySupport(this);
223 private void setTransactionCommitTimeout() {
224 transactionCommitTimeout = TimeUnit.MILLISECONDS.convert(
225 datastoreContext.getShardTransactionCommitTimeoutInSeconds(), TimeUnit.SECONDS) / 2;
228 private Optional<ActorRef> createRoleChangeNotifier(final String shardId) {
229 ActorRef shardRoleChangeNotifier = this.getContext().actorOf(
230 RoleChangeNotifier.getProps(shardId), shardId + "-notifier");
231 return Optional.of(shardRoleChangeNotifier);
235 public void postStop() {
236 LOG.info("Stopping Shard {}", persistenceId());
240 messageRetrySupport.close();
242 if (txCommitTimeoutCheckSchedule != null) {
243 txCommitTimeoutCheckSchedule.cancel();
246 commitCoordinator.abortPendingTransactions("Transaction aborted due to shutdown.", this);
248 shardMBean.unregisterMBean();
252 protected void handleRecover(final Object message) {
253 LOG.debug("{}: onReceiveRecover: Received message {} from {}", persistenceId(), message.getClass(),
256 super.handleRecover(message);
257 if (LOG.isTraceEnabled()) {
258 appendEntriesReplyTracker.begin();
262 @SuppressWarnings("checkstyle:IllegalCatch")
264 protected void handleNonRaftCommand(final Object message) {
265 try (MessageTracker.Context context = appendEntriesReplyTracker.received(message)) {
266 final Optional<Error> maybeError = context.error();
267 if (maybeError.isPresent()) {
268 LOG.trace("{} : AppendEntriesReply failed to arrive at the expected interval {}", persistenceId(),
272 if (message instanceof RequestEnvelope) {
273 final long now = ticker().read();
274 final RequestEnvelope envelope = (RequestEnvelope)message;
277 final RequestSuccess<?, ?> success = handleRequest(envelope, now);
278 if (success != null) {
279 envelope.sendSuccess(success, ticker().read() - now);
281 } catch (RequestException e) {
282 LOG.debug("{}: request {} failed", persistenceId(), envelope, e);
283 envelope.sendFailure(e, ticker().read() - now);
284 } catch (Exception e) {
285 LOG.debug("{}: request {} caused failure", persistenceId(), envelope, e);
286 envelope.sendFailure(new RuntimeRequestException("Request failed to process", e),
287 ticker().read() - now);
289 } else if (message instanceof ConnectClientRequest) {
290 handleConnectClient((ConnectClientRequest)message);
291 } else if (CreateTransaction.isSerializedType(message)) {
292 handleCreateTransaction(message);
293 } else if (message instanceof BatchedModifications) {
294 handleBatchedModifications((BatchedModifications)message);
295 } else if (message instanceof ForwardedReadyTransaction) {
296 handleForwardedReadyTransaction((ForwardedReadyTransaction) message);
297 } else if (message instanceof ReadyLocalTransaction) {
298 handleReadyLocalTransaction((ReadyLocalTransaction)message);
299 } else if (CanCommitTransaction.isSerializedType(message)) {
300 handleCanCommitTransaction(CanCommitTransaction.fromSerializable(message));
301 } else if (CommitTransaction.isSerializedType(message)) {
302 handleCommitTransaction(CommitTransaction.fromSerializable(message));
303 } else if (AbortTransaction.isSerializedType(message)) {
304 handleAbortTransaction(AbortTransaction.fromSerializable(message));
305 } else if (CloseTransactionChain.isSerializedType(message)) {
306 closeTransactionChain(CloseTransactionChain.fromSerializable(message));
307 } else if (message instanceof RegisterChangeListener) {
308 changeSupport.onMessage((RegisterChangeListener) message, isLeader(), hasLeader());
309 } else if (message instanceof RegisterDataTreeChangeListener) {
310 treeChangeSupport.onMessage((RegisterDataTreeChangeListener) message, isLeader(), hasLeader());
311 } else if (message instanceof UpdateSchemaContext) {
312 updateSchemaContext((UpdateSchemaContext) message);
313 } else if (message instanceof PeerAddressResolved) {
314 PeerAddressResolved resolved = (PeerAddressResolved) message;
315 setPeerAddress(resolved.getPeerId(), resolved.getPeerAddress());
316 } else if (TX_COMMIT_TIMEOUT_CHECK_MESSAGE.equals(message)) {
317 store.checkForExpiredTransactions(transactionCommitTimeout);
318 commitCoordinator.checkForExpiredTransactions(transactionCommitTimeout, this);
319 } else if (message instanceof DatastoreContext) {
320 onDatastoreContext((DatastoreContext)message);
321 } else if (message instanceof RegisterRoleChangeListener) {
322 roleChangeNotifier.get().forward(message, context());
323 } else if (message instanceof FollowerInitialSyncUpStatus) {
324 shardMBean.setFollowerInitialSyncStatus(((FollowerInitialSyncUpStatus) message).isInitialSyncDone());
325 context().parent().tell(message, self());
326 } else if (GET_SHARD_MBEAN_MESSAGE.equals(message)) {
327 sender().tell(getShardMBean(), self());
328 } else if (message instanceof GetShardDataTree) {
329 sender().tell(store.getDataTree(), self());
330 } else if (message instanceof ServerRemoved) {
331 context().parent().forward(message, context());
332 } else if (ShardTransactionMessageRetrySupport.TIMER_MESSAGE_CLASS.isInstance(message)) {
333 messageRetrySupport.onTimerMessage(message);
334 } else if (message instanceof DataTreeCohortActorRegistry.CohortRegistryCommand) {
335 store.processCohortRegistryCommand(getSender(),
336 (DataTreeCohortActorRegistry.CohortRegistryCommand) message);
338 super.handleNonRaftCommand(message);
343 // Acquire our frontend tracking handle and verify generation matches
344 private LeaderFrontendState getFrontend(final ClientIdentifier clientId) throws RequestException {
345 final LeaderFrontendState existing = knownFrontends.get(clientId.getFrontendId());
346 if (existing != null) {
347 final int cmp = Long.compareUnsigned(existing.getIdentifier().getGeneration(), clientId.getGeneration());
352 LOG.debug("{}: rejecting request from outdated client {}", persistenceId(), clientId);
353 throw new RetiredGenerationException(existing.getIdentifier().getGeneration());
356 LOG.info("{}: retiring state {}, outdated by request from client {}", persistenceId(), existing, clientId);
358 knownFrontends.remove(clientId.getFrontendId());
360 LOG.debug("{}: client {} is not yet known", persistenceId(), clientId);
363 final LeaderFrontendState ret = new LeaderFrontendState(persistenceId(), clientId, store);
364 knownFrontends.put(clientId.getFrontendId(), ret);
365 LOG.debug("{}: created state {} for client {}", persistenceId(), ret, clientId);
369 private static @Nonnull ABIVersion selectVersion(final ConnectClientRequest message) {
370 final Range<ABIVersion> clientRange = Range.closed(message.getMinVersion(), message.getMaxVersion());
371 for (ABIVersion v : SUPPORTED_ABIVERSIONS) {
372 if (clientRange.contains(v)) {
377 throw new IllegalArgumentException(String.format(
378 "No common version between backend versions %s and client versions %s", SUPPORTED_ABIVERSIONS,
382 @SuppressWarnings("checkstyle:IllegalCatch")
383 private void handleConnectClient(final ConnectClientRequest message) {
385 if (!isLeader() || !isLeaderActive()) {
386 LOG.debug("{}: not currently leader, rejecting request {}", persistenceId(), message);
387 throw new NotLeaderException(getSelf());
390 final ABIVersion selectedVersion = selectVersion(message);
391 final LeaderFrontendState frontend = getFrontend(message.getTarget());
392 frontend.reconnect();
393 message.getReplyTo().tell(new ConnectClientSuccess(message.getTarget(), message.getSequence(), getSelf(),
394 ImmutableList.of(), store.getDataTree(), CLIENT_MAX_MESSAGES).toVersion(selectedVersion),
395 ActorRef.noSender());
396 } catch (RequestException | RuntimeException e) {
397 message.getReplyTo().tell(new Failure(e), ActorRef.noSender());
401 private @Nullable RequestSuccess<?, ?> handleRequest(final RequestEnvelope envelope, final long now)
402 throws RequestException {
403 // We are not the leader, hence we want to fail-fast.
404 if (!isLeader() || !isLeaderActive()) {
405 LOG.debug("{}: not currently leader, rejecting request {}", persistenceId(), envelope);
406 throw new NotLeaderException(getSelf());
409 final Request<?, ?> request = envelope.getMessage();
410 if (request instanceof TransactionRequest) {
411 final TransactionRequest<?> txReq = (TransactionRequest<?>)request;
412 final ClientIdentifier clientId = txReq.getTarget().getHistoryId().getClientId();
413 return getFrontend(clientId).handleTransactionRequest(txReq, envelope, now);
414 } else if (request instanceof LocalHistoryRequest) {
415 final LocalHistoryRequest<?> lhReq = (LocalHistoryRequest<?>)request;
416 final ClientIdentifier clientId = lhReq.getTarget().getClientId();
417 return getFrontend(clientId).handleLocalHistoryRequest(lhReq, envelope, now);
419 LOG.debug("{}: rejecting unsupported request {}", persistenceId(), request);
420 throw new UnsupportedRequestException(request);
424 private boolean hasLeader() {
425 return getLeaderId() != null;
428 public int getPendingTxCommitQueueSize() {
429 return store.getQueueSize();
432 public int getCohortCacheSize() {
433 return commitCoordinator.getCohortCacheSize();
437 protected Optional<ActorRef> getRoleChangeNotifier() {
438 return roleChangeNotifier;
442 protected LeaderStateChanged newLeaderStateChanged(final String memberId, final String leaderId,
443 final short leaderPayloadVersion) {
444 return isLeader() ? new ShardLeaderStateChanged(memberId, leaderId, store.getDataTree(), leaderPayloadVersion)
445 : new ShardLeaderStateChanged(memberId, leaderId, leaderPayloadVersion);
448 protected void onDatastoreContext(final DatastoreContext context) {
449 datastoreContext = context;
451 setTransactionCommitTimeout();
453 setPersistence(datastoreContext.isPersistent());
455 updateConfigParams(datastoreContext.getShardRaftConfig());
458 // applyState() will be invoked once consensus is reached on the payload
459 void persistPayload(final Identifier id, final Payload payload, final boolean batchHint) {
460 boolean canSkipPayload = !hasFollowers() && !persistence().isRecoveryApplicable();
461 if (canSkipPayload) {
462 applyState(self(), id, payload);
464 // We are faking the sender
465 persistData(self(), id, payload, batchHint);
469 private void handleCommitTransaction(final CommitTransaction commit) {
471 commitCoordinator.handleCommit(commit.getTransactionId(), getSender(), this);
473 ActorSelection leader = getLeader();
474 if (leader == null) {
475 messageRetrySupport.addMessageToRetry(commit, getSender(),
476 "Could not commit transaction " + commit.getTransactionId());
478 LOG.debug("{}: Forwarding CommitTransaction to leader {}", persistenceId(), leader);
479 leader.forward(commit, getContext());
484 private void handleCanCommitTransaction(final CanCommitTransaction canCommit) {
485 LOG.debug("{}: Can committing transaction {}", persistenceId(), canCommit.getTransactionId());
488 commitCoordinator.handleCanCommit(canCommit.getTransactionId(), getSender(), this);
490 ActorSelection leader = getLeader();
491 if (leader == null) {
492 messageRetrySupport.addMessageToRetry(canCommit, getSender(),
493 "Could not canCommit transaction " + canCommit.getTransactionId());
495 LOG.debug("{}: Forwarding CanCommitTransaction to leader {}", persistenceId(), leader);
496 leader.forward(canCommit, getContext());
501 @SuppressWarnings("checkstyle:IllegalCatch")
502 protected void handleBatchedModificationsLocal(final BatchedModifications batched, final ActorRef sender) {
504 commitCoordinator.handleBatchedModifications(batched, sender, this);
505 } catch (Exception e) {
506 LOG.error("{}: Error handling BatchedModifications for Tx {}", persistenceId(),
507 batched.getTransactionId(), e);
508 sender.tell(new Failure(e), getSelf());
512 private void handleBatchedModifications(final BatchedModifications batched) {
513 // This message is sent to prepare the modifications transaction directly on the Shard as an
514 // optimization to avoid the extra overhead of a separate ShardTransaction actor. On the last
515 // BatchedModifications message, the caller sets the ready flag in the message indicating
516 // modifications are complete. The reply contains the cohort actor path (this actor) for the caller
517 // to initiate the 3-phase commit. This also avoids the overhead of sending an additional
518 // ReadyTransaction message.
520 // If we're not the leader then forward to the leader. This is a safety measure - we shouldn't
521 // normally get here if we're not the leader as the front-end (TransactionProxy) should determine
522 // the primary/leader shard. However with timing and caching on the front-end, there's a small
523 // window where it could have a stale leader during leadership transitions.
525 boolean isLeaderActive = isLeaderActive();
526 if (isLeader() && isLeaderActive) {
527 handleBatchedModificationsLocal(batched, getSender());
529 ActorSelection leader = getLeader();
530 if (!isLeaderActive || leader == null) {
531 messageRetrySupport.addMessageToRetry(batched, getSender(),
532 "Could not commit transaction " + batched.getTransactionId());
534 // If this is not the first batch and leadership changed in between batched messages,
535 // we need to reconstruct previous BatchedModifications from the transaction
536 // DataTreeModification, honoring the max batched modification count, and forward all the
537 // previous BatchedModifications to the new leader.
538 Collection<BatchedModifications> newModifications = commitCoordinator
539 .createForwardedBatchedModifications(batched,
540 datastoreContext.getShardBatchedModificationCount());
542 LOG.debug("{}: Forwarding {} BatchedModifications to leader {}", persistenceId(),
543 newModifications.size(), leader);
545 for (BatchedModifications bm : newModifications) {
546 leader.forward(bm, getContext());
552 private boolean failIfIsolatedLeader(final ActorRef sender) {
553 if (isIsolatedLeader()) {
554 sender.tell(new Failure(new NoShardLeaderException(String.format(
555 "Shard %s was the leader but has lost contact with all of its followers. Either all"
556 + " other follower nodes are down or this node is isolated by a network partition.",
557 persistenceId()))), getSelf());
564 protected boolean isIsolatedLeader() {
565 return getRaftState() == RaftState.IsolatedLeader;
568 @SuppressWarnings("checkstyle:IllegalCatch")
569 private void handleReadyLocalTransaction(final ReadyLocalTransaction message) {
570 LOG.debug("{}: handleReadyLocalTransaction for {}", persistenceId(), message.getTransactionId());
572 boolean isLeaderActive = isLeaderActive();
573 if (isLeader() && isLeaderActive) {
575 commitCoordinator.handleReadyLocalTransaction(message, getSender(), this);
576 } catch (Exception e) {
577 LOG.error("{}: Error handling ReadyLocalTransaction for Tx {}", persistenceId(),
578 message.getTransactionId(), e);
579 getSender().tell(new Failure(e), getSelf());
582 ActorSelection leader = getLeader();
583 if (!isLeaderActive || leader == null) {
584 messageRetrySupport.addMessageToRetry(message, getSender(),
585 "Could not commit transaction " + message.getTransactionId());
587 LOG.debug("{}: Forwarding ReadyLocalTransaction to leader {}", persistenceId(), leader);
588 message.setRemoteVersion(getCurrentBehavior().getLeaderPayloadVersion());
589 leader.forward(message, getContext());
594 private void handleForwardedReadyTransaction(final ForwardedReadyTransaction forwardedReady) {
595 LOG.debug("{}: handleForwardedReadyTransaction for {}", persistenceId(), forwardedReady.getTransactionId());
597 boolean isLeaderActive = isLeaderActive();
598 if (isLeader() && isLeaderActive) {
599 commitCoordinator.handleForwardedReadyTransaction(forwardedReady, getSender(), this);
601 ActorSelection leader = getLeader();
602 if (!isLeaderActive || leader == null) {
603 messageRetrySupport.addMessageToRetry(forwardedReady, getSender(),
604 "Could not commit transaction " + forwardedReady.getTransactionId());
606 LOG.debug("{}: Forwarding ForwardedReadyTransaction to leader {}", persistenceId(), leader);
608 ReadyLocalTransaction readyLocal = new ReadyLocalTransaction(forwardedReady.getTransactionId(),
609 forwardedReady.getTransaction().getSnapshot(), forwardedReady.isDoImmediateCommit());
610 readyLocal.setRemoteVersion(getCurrentBehavior().getLeaderPayloadVersion());
611 leader.forward(readyLocal, getContext());
616 private void handleAbortTransaction(final AbortTransaction abort) {
617 doAbortTransaction(abort.getTransactionId(), getSender());
620 void doAbortTransaction(final Identifier transactionID, final ActorRef sender) {
621 commitCoordinator.handleAbort(transactionID, sender, this);
624 private void handleCreateTransaction(final Object message) {
626 createTransaction(CreateTransaction.fromSerializable(message));
627 } else if (getLeader() != null) {
628 getLeader().forward(message, getContext());
630 getSender().tell(new Failure(new NoShardLeaderException(
631 "Could not create a shard transaction", persistenceId())), getSelf());
635 private void closeTransactionChain(final CloseTransactionChain closeTransactionChain) {
636 final LocalHistoryIdentifier id = closeTransactionChain.getIdentifier();
637 store.closeTransactionChain(id, null);
638 store.purgeTransactionChain(id, null);
641 @SuppressWarnings("checkstyle:IllegalCatch")
642 private void createTransaction(final CreateTransaction createTransaction) {
644 if (TransactionType.fromInt(createTransaction.getTransactionType()) != TransactionType.READ_ONLY
645 && failIfIsolatedLeader(getSender())) {
649 ActorRef transactionActor = createTransaction(createTransaction.getTransactionType(),
650 createTransaction.getTransactionId());
652 getSender().tell(new CreateTransactionReply(Serialization.serializedActorPath(transactionActor),
653 createTransaction.getTransactionId(), createTransaction.getVersion()).toSerializable(), getSelf());
654 } catch (Exception e) {
655 getSender().tell(new Failure(e), getSelf());
659 private ActorRef createTransaction(final int transactionType, final TransactionIdentifier transactionId) {
660 LOG.debug("{}: Creating transaction : {} ", persistenceId(), transactionId);
661 return transactionActorFactory.newShardTransaction(TransactionType.fromInt(transactionType),
665 private void updateSchemaContext(final UpdateSchemaContext message) {
666 updateSchemaContext(message.getSchemaContext());
670 void updateSchemaContext(final SchemaContext schemaContext) {
671 store.updateSchemaContext(schemaContext);
674 private boolean isMetricsCaptureEnabled() {
675 CommonConfig config = new CommonConfig(getContext().system().settings().config());
676 return config.isMetricCaptureEnabled();
681 public RaftActorSnapshotCohort getRaftActorSnapshotCohort() {
682 return snapshotCohort;
687 protected RaftActorRecoveryCohort getRaftActorRecoveryCohort() {
688 return new ShardRecoveryCoordinator(store,
689 restoreFromSnapshot != null ? restoreFromSnapshot.getSnapshot() : null, persistenceId(), LOG);
693 protected void onRecoveryComplete() {
694 restoreFromSnapshot = null;
696 //notify shard manager
697 getContext().parent().tell(new ActorInitialized(), getSelf());
699 // Being paranoid here - this method should only be called once but just in case...
700 if (txCommitTimeoutCheckSchedule == null) {
701 // Schedule a message to be periodically sent to check if the current in-progress
702 // transaction should be expired and aborted.
703 FiniteDuration period = Duration.create(transactionCommitTimeout / 3, TimeUnit.MILLISECONDS);
704 txCommitTimeoutCheckSchedule = getContext().system().scheduler().schedule(
705 period, period, getSelf(),
706 TX_COMMIT_TIMEOUT_CHECK_MESSAGE, getContext().dispatcher(), ActorRef.noSender());
711 protected void applyState(final ActorRef clientActor, final Identifier identifier, final Object data) {
712 if (data instanceof Payload) {
714 store.applyReplicatedPayload(identifier, (Payload)data);
715 } catch (DataValidationFailedException | IOException e) {
716 LOG.error("{}: Error applying replica {}", persistenceId(), identifier, e);
719 LOG.error("{}: Unknown state for {} received {}", persistenceId(), identifier, data);
724 protected void onStateChanged() {
725 boolean isLeader = isLeader();
726 boolean hasLeader = hasLeader();
727 changeSupport.onLeadershipChange(isLeader, hasLeader);
728 treeChangeSupport.onLeadershipChange(isLeader, hasLeader);
730 // If this actor is no longer the leader close all the transaction chains
732 if (LOG.isDebugEnabled()) {
734 "{}: onStateChanged: Closing all transaction chains because shard {} is no longer the leader",
735 persistenceId(), getId());
738 store.purgeLeaderState();
741 if (hasLeader && !isIsolatedLeader()) {
742 messageRetrySupport.retryMessages();
747 protected void onLeaderChanged(final String oldLeader, final String newLeader) {
748 shardMBean.incrementLeadershipChangeCount();
750 final boolean hasLeader = hasLeader();
752 // No leader implies we are not the leader, lose frontend state if we have any. This also places
753 // an explicit guard so the map will not get modified accidentally.
754 if (!knownFrontends.isEmpty()) {
755 LOG.debug("{}: removing frontend state for {}", persistenceId(), knownFrontends.keySet());
756 knownFrontends = ImmutableMap.of();
762 // Another leader was elected. If we were the previous leader and had pending transactions, convert
763 // them to transaction messages and send to the new leader.
764 ActorSelection leader = getLeader();
765 if (leader != null) {
766 Collection<?> messagesToForward = convertPendingTransactionsToMessages();
768 if (!messagesToForward.isEmpty()) {
769 LOG.debug("{}: Forwarding {} pending transaction messages to leader {}", persistenceId(),
770 messagesToForward.size(), leader);
772 for (Object message : messagesToForward) {
773 leader.tell(message, self());
777 commitCoordinator.abortPendingTransactions("The transacton was aborted due to inflight leadership "
778 + "change and the leader address isn't available.", this);
781 // We have become the leader, we need to reconstruct frontend state
782 knownFrontends = Verify.verifyNotNull(frontendMetadata.toLeaderState(this));
783 LOG.debug("{}: became leader with frontend state for {}", persistenceId(), knownFrontends.keySet());
786 if (!isIsolatedLeader()) {
787 messageRetrySupport.retryMessages();
792 * Clears all pending transactions and converts them to messages to be forwarded to a new leader.
794 * @return the converted messages
796 public Collection<?> convertPendingTransactionsToMessages() {
797 return commitCoordinator.convertPendingTransactionsToMessages(
798 datastoreContext.getShardBatchedModificationCount());
802 protected void pauseLeader(final Runnable operation) {
803 LOG.debug("{}: In pauseLeader, operation: {}", persistenceId(), operation);
804 store.setRunOnPendingTransactionsComplete(operation);
808 protected OnDemandRaftState.AbstractBuilder<?> newOnDemandRaftStateBuilder() {
809 return OnDemandShardState.newBuilder().treeChangeListenerActors(treeChangeSupport.getListenerActors())
810 .dataChangeListenerActors(changeSupport.getListenerActors())
811 .commitCohortActors(store.getCohortActors());
815 public String persistenceId() {
820 ShardCommitCoordinator getCommitCoordinator() {
821 return commitCoordinator;
824 public DatastoreContext getDatastoreContext() {
825 return datastoreContext;
829 public ShardDataTree getDataStore() {
834 ShardStats getShardMBean() {
838 public static Builder builder() {
839 return new Builder();
842 public abstract static class AbstractBuilder<T extends AbstractBuilder<T, S>, S extends Shard> {
843 private final Class<S> shardClass;
844 private ShardIdentifier id;
845 private Map<String, String> peerAddresses = Collections.emptyMap();
846 private DatastoreContext datastoreContext;
847 private SchemaContext schemaContext;
848 private DatastoreSnapshot.ShardSnapshot restoreFromSnapshot;
849 private TipProducingDataTree dataTree;
850 private volatile boolean sealed;
852 protected AbstractBuilder(final Class<S> shardClass) {
853 this.shardClass = shardClass;
856 protected void checkSealed() {
857 Preconditions.checkState(!sealed, "Builder isalready sealed - further modifications are not allowed");
860 @SuppressWarnings("unchecked")
865 public T id(final ShardIdentifier newId) {
871 public T peerAddresses(final Map<String, String> newPeerAddresses) {
873 this.peerAddresses = newPeerAddresses;
877 public T datastoreContext(final DatastoreContext newDatastoreContext) {
879 this.datastoreContext = newDatastoreContext;
883 public T schemaContext(final SchemaContext newSchemaContext) {
885 this.schemaContext = newSchemaContext;
889 public T restoreFromSnapshot(final DatastoreSnapshot.ShardSnapshot newRestoreFromSnapshot) {
891 this.restoreFromSnapshot = newRestoreFromSnapshot;
895 public T dataTree(final TipProducingDataTree newDataTree) {
897 this.dataTree = newDataTree;
901 public ShardIdentifier getId() {
905 public Map<String, String> getPeerAddresses() {
906 return peerAddresses;
909 public DatastoreContext getDatastoreContext() {
910 return datastoreContext;
913 public SchemaContext getSchemaContext() {
914 return schemaContext;
917 public DatastoreSnapshot.ShardSnapshot getRestoreFromSnapshot() {
918 return restoreFromSnapshot;
921 public TipProducingDataTree getDataTree() {
925 public TreeType getTreeType() {
926 switch (datastoreContext.getLogicalStoreType()) {
928 return TreeType.CONFIGURATION;
930 return TreeType.OPERATIONAL;
932 throw new IllegalStateException("Unhandled logical store type "
933 + datastoreContext.getLogicalStoreType());
937 protected void verify() {
938 Preconditions.checkNotNull(id, "id should not be null");
939 Preconditions.checkNotNull(peerAddresses, "peerAddresses should not be null");
940 Preconditions.checkNotNull(datastoreContext, "dataStoreContext should not be null");
941 Preconditions.checkNotNull(schemaContext, "schemaContext should not be null");
944 public Props props() {
947 return Props.create(shardClass, this);
951 public static class Builder extends AbstractBuilder<Builder, Shard> {
958 return Ticker.systemTicker();