2 * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
4 * This program and the accompanying materials are made available under the
5 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6 * and is available at http://www.eclipse.org/legal/epl-v10.html
9 package org.opendaylight.controller.cluster.datastore;
11 import akka.actor.ActorRef;
12 import akka.actor.ActorSelection;
13 import akka.actor.Cancellable;
14 import akka.actor.Props;
15 import akka.actor.Status;
16 import akka.actor.Status.Failure;
17 import akka.serialization.Serialization;
18 import com.google.common.annotations.VisibleForTesting;
19 import com.google.common.base.Optional;
20 import com.google.common.base.Preconditions;
21 import com.google.common.base.Ticker;
22 import com.google.common.base.Verify;
23 import com.google.common.collect.ImmutableList;
24 import com.google.common.collect.ImmutableMap;
25 import com.google.common.collect.Range;
26 import java.io.IOException;
27 import java.util.Arrays;
28 import java.util.Collection;
29 import java.util.Collections;
31 import java.util.concurrent.TimeUnit;
32 import javax.annotation.Nonnull;
33 import javax.annotation.Nullable;
34 import org.opendaylight.controller.cluster.access.ABIVersion;
35 import org.opendaylight.controller.cluster.access.commands.ConnectClientRequest;
36 import org.opendaylight.controller.cluster.access.commands.ConnectClientSuccess;
37 import org.opendaylight.controller.cluster.access.commands.LocalHistoryRequest;
38 import org.opendaylight.controller.cluster.access.commands.NotLeaderException;
39 import org.opendaylight.controller.cluster.access.commands.TransactionRequest;
40 import org.opendaylight.controller.cluster.access.concepts.ClientIdentifier;
41 import org.opendaylight.controller.cluster.access.concepts.FrontendIdentifier;
42 import org.opendaylight.controller.cluster.access.concepts.LocalHistoryIdentifier;
43 import org.opendaylight.controller.cluster.access.concepts.Request;
44 import org.opendaylight.controller.cluster.access.concepts.RequestEnvelope;
45 import org.opendaylight.controller.cluster.access.concepts.RequestException;
46 import org.opendaylight.controller.cluster.access.concepts.RequestSuccess;
47 import org.opendaylight.controller.cluster.access.concepts.RetiredGenerationException;
48 import org.opendaylight.controller.cluster.access.concepts.RuntimeRequestException;
49 import org.opendaylight.controller.cluster.access.concepts.TransactionIdentifier;
50 import org.opendaylight.controller.cluster.access.concepts.UnsupportedRequestException;
51 import org.opendaylight.controller.cluster.common.actor.CommonConfig;
52 import org.opendaylight.controller.cluster.common.actor.MessageTracker;
53 import org.opendaylight.controller.cluster.common.actor.MessageTracker.Error;
54 import org.opendaylight.controller.cluster.common.actor.MeteringBehavior;
55 import org.opendaylight.controller.cluster.datastore.exceptions.NoShardLeaderException;
56 import org.opendaylight.controller.cluster.datastore.identifiers.ShardIdentifier;
57 import org.opendaylight.controller.cluster.datastore.jmx.mbeans.shard.ShardMBeanFactory;
58 import org.opendaylight.controller.cluster.datastore.jmx.mbeans.shard.ShardStats;
59 import org.opendaylight.controller.cluster.datastore.messages.AbortTransaction;
60 import org.opendaylight.controller.cluster.datastore.messages.ActorInitialized;
61 import org.opendaylight.controller.cluster.datastore.messages.BatchedModifications;
62 import org.opendaylight.controller.cluster.datastore.messages.CanCommitTransaction;
63 import org.opendaylight.controller.cluster.datastore.messages.CloseTransactionChain;
64 import org.opendaylight.controller.cluster.datastore.messages.CommitTransaction;
65 import org.opendaylight.controller.cluster.datastore.messages.CreateTransaction;
66 import org.opendaylight.controller.cluster.datastore.messages.CreateTransactionReply;
67 import org.opendaylight.controller.cluster.datastore.messages.ForwardedReadyTransaction;
68 import org.opendaylight.controller.cluster.datastore.messages.GetShardDataTree;
69 import org.opendaylight.controller.cluster.datastore.messages.MakeLeaderLocal;
70 import org.opendaylight.controller.cluster.datastore.messages.OnDemandShardState;
71 import org.opendaylight.controller.cluster.datastore.messages.PeerAddressResolved;
72 import org.opendaylight.controller.cluster.datastore.messages.PersistAbortTransactionPayload;
73 import org.opendaylight.controller.cluster.datastore.messages.ReadyLocalTransaction;
74 import org.opendaylight.controller.cluster.datastore.messages.RegisterChangeListener;
75 import org.opendaylight.controller.cluster.datastore.messages.RegisterDataTreeChangeListener;
76 import org.opendaylight.controller.cluster.datastore.messages.ShardLeaderStateChanged;
77 import org.opendaylight.controller.cluster.datastore.messages.UpdateSchemaContext;
78 import org.opendaylight.controller.cluster.datastore.persisted.AbortTransactionPayload;
79 import org.opendaylight.controller.cluster.datastore.persisted.DatastoreSnapshot;
80 import org.opendaylight.controller.cluster.datastore.persisted.DatastoreSnapshot.ShardSnapshot;
81 import org.opendaylight.controller.cluster.datastore.utils.Dispatchers;
82 import org.opendaylight.controller.cluster.notifications.LeaderStateChanged;
83 import org.opendaylight.controller.cluster.notifications.RegisterRoleChangeListener;
84 import org.opendaylight.controller.cluster.notifications.RoleChangeNotifier;
85 import org.opendaylight.controller.cluster.raft.LeadershipTransferFailedException;
86 import org.opendaylight.controller.cluster.raft.RaftActor;
87 import org.opendaylight.controller.cluster.raft.RaftActorRecoveryCohort;
88 import org.opendaylight.controller.cluster.raft.RaftActorSnapshotCohort;
89 import org.opendaylight.controller.cluster.raft.RaftState;
90 import org.opendaylight.controller.cluster.raft.base.messages.FollowerInitialSyncUpStatus;
91 import org.opendaylight.controller.cluster.raft.client.messages.OnDemandRaftState;
92 import org.opendaylight.controller.cluster.raft.messages.AppendEntriesReply;
93 import org.opendaylight.controller.cluster.raft.messages.RequestLeadership;
94 import org.opendaylight.controller.cluster.raft.messages.ServerRemoved;
95 import org.opendaylight.controller.cluster.raft.protobuff.client.messages.Payload;
96 import org.opendaylight.yangtools.concepts.Identifier;
97 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataValidationFailedException;
98 import org.opendaylight.yangtools.yang.data.api.schema.tree.TipProducingDataTree;
99 import org.opendaylight.yangtools.yang.data.api.schema.tree.TreeType;
100 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
101 import scala.concurrent.duration.Duration;
102 import scala.concurrent.duration.FiniteDuration;
105 * A Shard represents a portion of the logical data tree.
108 * Our Shard uses InMemoryDataTree as it's internal representation and delegates all requests it
110 public class Shard extends RaftActor {
113 static final Object TX_COMMIT_TIMEOUT_CHECK_MESSAGE = new Object() {
115 public String toString() {
116 return "txCommitTimeoutCheck";
121 static final Object GET_SHARD_MBEAN_MESSAGE = new Object() {
123 public String toString() {
124 return "getShardMBeanMessage";
128 static final Object RESUME_NEXT_PENDING_TRANSACTION = new Object() {
130 public String toString() {
131 return "resumeNextPendingTransaction";
135 // FIXME: shard names should be encapsulated in their own class and this should be exposed as a constant.
136 public static final String DEFAULT_NAME = "default";
138 private static final Collection<ABIVersion> SUPPORTED_ABIVERSIONS;
141 final ABIVersion[] values = ABIVersion.values();
142 final ABIVersion[] real = Arrays.copyOfRange(values, 1, values.length - 1);
143 SUPPORTED_ABIVERSIONS = ImmutableList.copyOf(real).reverse();
146 // FIXME: make this a dynamic property based on mailbox size and maximum number of clients
147 private static final int CLIENT_MAX_MESSAGES = 1000;
149 // The state of this Shard
150 private final ShardDataTree store;
152 /// The name of this shard
153 private final String name;
155 private final ShardStats shardMBean;
157 private DatastoreContext datastoreContext;
159 private final ShardCommitCoordinator commitCoordinator;
161 private long transactionCommitTimeout;
163 private Cancellable txCommitTimeoutCheckSchedule;
165 private final Optional<ActorRef> roleChangeNotifier;
167 private final MessageTracker appendEntriesReplyTracker;
169 private final ShardTransactionActorFactory transactionActorFactory;
171 private final ShardSnapshotCohort snapshotCohort;
173 private final DataTreeChangeListenerSupport treeChangeSupport = new DataTreeChangeListenerSupport(this);
174 private final DataChangeListenerSupport changeSupport = new DataChangeListenerSupport(this);
177 private ShardSnapshot restoreFromSnapshot;
179 private final ShardTransactionMessageRetrySupport messageRetrySupport;
181 private final FrontendMetadata frontendMetadata;
182 private Map<FrontendIdentifier, LeaderFrontendState> knownFrontends = ImmutableMap.of();
184 protected Shard(final AbstractBuilder<?, ?> builder) {
185 super(builder.getId().toString(), builder.getPeerAddresses(),
186 Optional.of(builder.getDatastoreContext().getShardRaftConfig()), DataStoreVersions.CURRENT_VERSION);
188 this.name = builder.getId().toString();
189 this.datastoreContext = builder.getDatastoreContext();
190 this.restoreFromSnapshot = builder.getRestoreFromSnapshot();
191 this.frontendMetadata = new FrontendMetadata(name);
193 setPersistence(datastoreContext.isPersistent());
195 LOG.info("Shard created : {}, persistent : {}", name, datastoreContext.isPersistent());
197 ShardDataTreeChangeListenerPublisherActorProxy treeChangeListenerPublisher =
198 new ShardDataTreeChangeListenerPublisherActorProxy(getContext(), name + "-DTCL-publisher", name);
199 ShardDataChangeListenerPublisherActorProxy dataChangeListenerPublisher =
200 new ShardDataChangeListenerPublisherActorProxy(getContext(), name + "-DCL-publisher", name);
201 if (builder.getDataTree() != null) {
202 store = new ShardDataTree(this, builder.getSchemaContext(), builder.getDataTree(),
203 treeChangeListenerPublisher, dataChangeListenerPublisher, name, frontendMetadata);
205 store = new ShardDataTree(this, builder.getSchemaContext(), builder.getTreeType(),
206 builder.getDatastoreContext().getStoreRoot(), treeChangeListenerPublisher,
207 dataChangeListenerPublisher, name, frontendMetadata);
210 shardMBean = ShardMBeanFactory.getShardStatsMBean(name, datastoreContext.getDataStoreMXBeanType(), this);
212 if (isMetricsCaptureEnabled()) {
213 getContext().become(new MeteringBehavior(this));
216 commitCoordinator = new ShardCommitCoordinator(store, LOG, this.name);
218 setTransactionCommitTimeout();
220 // create a notifier actor for each cluster member
221 roleChangeNotifier = createRoleChangeNotifier(name);
223 appendEntriesReplyTracker = new MessageTracker(AppendEntriesReply.class,
224 getRaftActorContext().getConfigParams().getIsolatedCheckIntervalInMillis());
226 transactionActorFactory = new ShardTransactionActorFactory(store, datastoreContext,
227 new Dispatchers(context().system().dispatchers()).getDispatcherPath(Dispatchers.DispatcherType.Transaction),
228 self(), getContext(), shardMBean, builder.getId().getShardName());
230 snapshotCohort = ShardSnapshotCohort.create(getContext(), builder.getId().getMemberName(), store, LOG,
233 messageRetrySupport = new ShardTransactionMessageRetrySupport(this);
236 private void setTransactionCommitTimeout() {
237 transactionCommitTimeout = TimeUnit.MILLISECONDS.convert(
238 datastoreContext.getShardTransactionCommitTimeoutInSeconds(), TimeUnit.SECONDS) / 2;
241 private Optional<ActorRef> createRoleChangeNotifier(final String shardId) {
242 ActorRef shardRoleChangeNotifier = this.getContext().actorOf(
243 RoleChangeNotifier.getProps(shardId), shardId + "-notifier");
244 return Optional.of(shardRoleChangeNotifier);
248 public void postStop() {
249 LOG.info("Stopping Shard {}", persistenceId());
253 messageRetrySupport.close();
255 if (txCommitTimeoutCheckSchedule != null) {
256 txCommitTimeoutCheckSchedule.cancel();
259 commitCoordinator.abortPendingTransactions("Transaction aborted due to shutdown.", this);
261 shardMBean.unregisterMBean();
265 protected void handleRecover(final Object message) {
266 LOG.debug("{}: onReceiveRecover: Received message {} from {}", persistenceId(), message.getClass(),
269 super.handleRecover(message);
270 if (LOG.isTraceEnabled()) {
271 appendEntriesReplyTracker.begin();
275 @SuppressWarnings("checkstyle:IllegalCatch")
277 protected void handleNonRaftCommand(final Object message) {
278 try (MessageTracker.Context context = appendEntriesReplyTracker.received(message)) {
279 final Optional<Error> maybeError = context.error();
280 if (maybeError.isPresent()) {
281 LOG.trace("{} : AppendEntriesReply failed to arrive at the expected interval {}", persistenceId(),
285 store.resetTransactionBatch();
287 if (message instanceof RequestEnvelope) {
288 final long now = ticker().read();
289 final RequestEnvelope envelope = (RequestEnvelope)message;
292 final RequestSuccess<?, ?> success = handleRequest(envelope, now);
293 if (success != null) {
294 envelope.sendSuccess(success, ticker().read() - now);
296 } catch (RequestException e) {
297 LOG.debug("{}: request {} failed", persistenceId(), envelope, e);
298 envelope.sendFailure(e, ticker().read() - now);
299 } catch (Exception e) {
300 LOG.debug("{}: request {} caused failure", persistenceId(), envelope, e);
301 envelope.sendFailure(new RuntimeRequestException("Request failed to process", e),
302 ticker().read() - now);
304 } else if (message instanceof ConnectClientRequest) {
305 handleConnectClient((ConnectClientRequest)message);
306 } else if (CreateTransaction.isSerializedType(message)) {
307 handleCreateTransaction(message);
308 } else if (message instanceof BatchedModifications) {
309 handleBatchedModifications((BatchedModifications)message);
310 } else if (message instanceof ForwardedReadyTransaction) {
311 handleForwardedReadyTransaction((ForwardedReadyTransaction) message);
312 } else if (message instanceof ReadyLocalTransaction) {
313 handleReadyLocalTransaction((ReadyLocalTransaction)message);
314 } else if (CanCommitTransaction.isSerializedType(message)) {
315 handleCanCommitTransaction(CanCommitTransaction.fromSerializable(message));
316 } else if (CommitTransaction.isSerializedType(message)) {
317 handleCommitTransaction(CommitTransaction.fromSerializable(message));
318 } else if (AbortTransaction.isSerializedType(message)) {
319 handleAbortTransaction(AbortTransaction.fromSerializable(message));
320 } else if (CloseTransactionChain.isSerializedType(message)) {
321 closeTransactionChain(CloseTransactionChain.fromSerializable(message));
322 } else if (message instanceof RegisterChangeListener) {
323 changeSupport.onMessage((RegisterChangeListener) message, isLeader(), hasLeader());
324 } else if (message instanceof RegisterDataTreeChangeListener) {
325 treeChangeSupport.onMessage((RegisterDataTreeChangeListener) message, isLeader(), hasLeader());
326 } else if (message instanceof UpdateSchemaContext) {
327 updateSchemaContext((UpdateSchemaContext) message);
328 } else if (message instanceof PeerAddressResolved) {
329 PeerAddressResolved resolved = (PeerAddressResolved) message;
330 setPeerAddress(resolved.getPeerId(), resolved.getPeerAddress());
331 } else if (TX_COMMIT_TIMEOUT_CHECK_MESSAGE.equals(message)) {
332 store.checkForExpiredTransactions(transactionCommitTimeout);
333 commitCoordinator.checkForExpiredTransactions(transactionCommitTimeout, this);
334 } else if (message instanceof DatastoreContext) {
335 onDatastoreContext((DatastoreContext)message);
336 } else if (message instanceof RegisterRoleChangeListener) {
337 roleChangeNotifier.get().forward(message, context());
338 } else if (message instanceof FollowerInitialSyncUpStatus) {
339 shardMBean.setFollowerInitialSyncStatus(((FollowerInitialSyncUpStatus) message).isInitialSyncDone());
340 context().parent().tell(message, self());
341 } else if (GET_SHARD_MBEAN_MESSAGE.equals(message)) {
342 sender().tell(getShardMBean(), self());
343 } else if (message instanceof GetShardDataTree) {
344 sender().tell(store.getDataTree(), self());
345 } else if (message instanceof ServerRemoved) {
346 context().parent().forward(message, context());
347 } else if (ShardTransactionMessageRetrySupport.TIMER_MESSAGE_CLASS.isInstance(message)) {
348 messageRetrySupport.onTimerMessage(message);
349 } else if (message instanceof DataTreeCohortActorRegistry.CohortRegistryCommand) {
350 store.processCohortRegistryCommand(getSender(),
351 (DataTreeCohortActorRegistry.CohortRegistryCommand) message);
352 } else if (message instanceof PersistAbortTransactionPayload) {
353 final TransactionIdentifier txId = ((PersistAbortTransactionPayload) message).getTransactionId();
354 persistPayload(txId, AbortTransactionPayload.create(txId), true);
355 } else if (message instanceof MakeLeaderLocal) {
357 } else if (RESUME_NEXT_PENDING_TRANSACTION.equals(message)) {
358 store.resumeNextPendingTransaction();
360 super.handleNonRaftCommand(message);
365 private void onMakeLeaderLocal() {
366 LOG.debug("{}: onMakeLeaderLocal received", persistenceId());
368 getSender().tell(new Status.Success(null), getSelf());
372 final ActorSelection leader = getLeader();
374 if (leader == null) {
375 // Leader is not present. The cluster is most likely trying to
376 // elect a leader and we should let that run its normal course
378 // TODO we can wait for the election to complete and retry the
379 // request. We can also let the caller retry by sending a flag
380 // in the response indicating the request is "reTryable".
381 getSender().tell(new Failure(
382 new LeadershipTransferFailedException("We cannot initiate leadership transfer to local node. "
383 + "Currently there is no leader for " + persistenceId())),
388 leader.tell(new RequestLeadership(getId(), getSender()), getSelf());
391 // Acquire our frontend tracking handle and verify generation matches
392 private LeaderFrontendState getFrontend(final ClientIdentifier clientId) throws RequestException {
393 final LeaderFrontendState existing = knownFrontends.get(clientId.getFrontendId());
394 if (existing != null) {
395 final int cmp = Long.compareUnsigned(existing.getIdentifier().getGeneration(), clientId.getGeneration());
400 LOG.debug("{}: rejecting request from outdated client {}", persistenceId(), clientId);
401 throw new RetiredGenerationException(existing.getIdentifier().getGeneration());
404 LOG.info("{}: retiring state {}, outdated by request from client {}", persistenceId(), existing, clientId);
406 knownFrontends.remove(clientId.getFrontendId());
408 LOG.debug("{}: client {} is not yet known", persistenceId(), clientId);
411 final LeaderFrontendState ret = new LeaderFrontendState(persistenceId(), clientId, store);
412 knownFrontends.put(clientId.getFrontendId(), ret);
413 LOG.debug("{}: created state {} for client {}", persistenceId(), ret, clientId);
417 private static @Nonnull ABIVersion selectVersion(final ConnectClientRequest message) {
418 final Range<ABIVersion> clientRange = Range.closed(message.getMinVersion(), message.getMaxVersion());
419 for (ABIVersion v : SUPPORTED_ABIVERSIONS) {
420 if (clientRange.contains(v)) {
425 throw new IllegalArgumentException(String.format(
426 "No common version between backend versions %s and client versions %s", SUPPORTED_ABIVERSIONS,
430 @SuppressWarnings("checkstyle:IllegalCatch")
431 private void handleConnectClient(final ConnectClientRequest message) {
433 if (!isLeader() || !isLeaderActive()) {
434 LOG.debug("{}: not currently leader, rejecting request {}", persistenceId(), message);
435 throw new NotLeaderException(getSelf());
438 final ABIVersion selectedVersion = selectVersion(message);
439 final LeaderFrontendState frontend = getFrontend(message.getTarget());
440 frontend.reconnect();
441 message.getReplyTo().tell(new ConnectClientSuccess(message.getTarget(), message.getSequence(), getSelf(),
442 ImmutableList.of(), store.getDataTree(), CLIENT_MAX_MESSAGES).toVersion(selectedVersion),
443 ActorRef.noSender());
444 } catch (RequestException | RuntimeException e) {
445 message.getReplyTo().tell(new Failure(e), ActorRef.noSender());
449 private @Nullable RequestSuccess<?, ?> handleRequest(final RequestEnvelope envelope, final long now)
450 throws RequestException {
451 // We are not the leader, hence we want to fail-fast.
452 if (!isLeader() || !isLeaderActive()) {
453 LOG.debug("{}: not currently leader, rejecting request {}", persistenceId(), envelope);
454 throw new NotLeaderException(getSelf());
457 final Request<?, ?> request = envelope.getMessage();
458 if (request instanceof TransactionRequest) {
459 final TransactionRequest<?> txReq = (TransactionRequest<?>)request;
460 final ClientIdentifier clientId = txReq.getTarget().getHistoryId().getClientId();
461 return getFrontend(clientId).handleTransactionRequest(txReq, envelope, now);
462 } else if (request instanceof LocalHistoryRequest) {
463 final LocalHistoryRequest<?> lhReq = (LocalHistoryRequest<?>)request;
464 final ClientIdentifier clientId = lhReq.getTarget().getClientId();
465 return getFrontend(clientId).handleLocalHistoryRequest(lhReq, envelope, now);
467 LOG.warn("{}: rejecting unsupported request {}", persistenceId(), request);
468 throw new UnsupportedRequestException(request);
472 private boolean hasLeader() {
473 return getLeaderId() != null;
476 public int getPendingTxCommitQueueSize() {
477 return store.getQueueSize();
480 public int getCohortCacheSize() {
481 return commitCoordinator.getCohortCacheSize();
485 protected Optional<ActorRef> getRoleChangeNotifier() {
486 return roleChangeNotifier;
490 protected LeaderStateChanged newLeaderStateChanged(final String memberId, final String leaderId,
491 final short leaderPayloadVersion) {
492 return isLeader() ? new ShardLeaderStateChanged(memberId, leaderId, store.getDataTree(), leaderPayloadVersion)
493 : new ShardLeaderStateChanged(memberId, leaderId, leaderPayloadVersion);
496 protected void onDatastoreContext(final DatastoreContext context) {
497 datastoreContext = context;
499 setTransactionCommitTimeout();
501 setPersistence(datastoreContext.isPersistent());
503 updateConfigParams(datastoreContext.getShardRaftConfig());
506 // applyState() will be invoked once consensus is reached on the payload
507 void persistPayload(final Identifier id, final Payload payload, final boolean batchHint) {
508 boolean canSkipPayload = !hasFollowers() && !persistence().isRecoveryApplicable();
509 if (canSkipPayload) {
510 applyState(self(), id, payload);
512 // We are faking the sender
513 persistData(self(), id, payload, batchHint);
517 private void handleCommitTransaction(final CommitTransaction commit) {
519 commitCoordinator.handleCommit(commit.getTransactionId(), getSender(), this);
521 ActorSelection leader = getLeader();
522 if (leader == null) {
523 messageRetrySupport.addMessageToRetry(commit, getSender(),
524 "Could not commit transaction " + commit.getTransactionId());
526 LOG.debug("{}: Forwarding CommitTransaction to leader {}", persistenceId(), leader);
527 leader.forward(commit, getContext());
532 private void handleCanCommitTransaction(final CanCommitTransaction canCommit) {
533 LOG.debug("{}: Can committing transaction {}", persistenceId(), canCommit.getTransactionId());
536 commitCoordinator.handleCanCommit(canCommit.getTransactionId(), getSender(), this);
538 ActorSelection leader = getLeader();
539 if (leader == null) {
540 messageRetrySupport.addMessageToRetry(canCommit, getSender(),
541 "Could not canCommit transaction " + canCommit.getTransactionId());
543 LOG.debug("{}: Forwarding CanCommitTransaction to leader {}", persistenceId(), leader);
544 leader.forward(canCommit, getContext());
549 @SuppressWarnings("checkstyle:IllegalCatch")
550 protected void handleBatchedModificationsLocal(final BatchedModifications batched, final ActorRef sender) {
552 commitCoordinator.handleBatchedModifications(batched, sender, this);
553 } catch (Exception e) {
554 LOG.error("{}: Error handling BatchedModifications for Tx {}", persistenceId(),
555 batched.getTransactionId(), e);
556 sender.tell(new Failure(e), getSelf());
560 private void handleBatchedModifications(final BatchedModifications batched) {
561 // This message is sent to prepare the modifications transaction directly on the Shard as an
562 // optimization to avoid the extra overhead of a separate ShardTransaction actor. On the last
563 // BatchedModifications message, the caller sets the ready flag in the message indicating
564 // modifications are complete. The reply contains the cohort actor path (this actor) for the caller
565 // to initiate the 3-phase commit. This also avoids the overhead of sending an additional
566 // ReadyTransaction message.
568 // If we're not the leader then forward to the leader. This is a safety measure - we shouldn't
569 // normally get here if we're not the leader as the front-end (TransactionProxy) should determine
570 // the primary/leader shard. However with timing and caching on the front-end, there's a small
571 // window where it could have a stale leader during leadership transitions.
573 boolean isLeaderActive = isLeaderActive();
574 if (isLeader() && isLeaderActive) {
575 handleBatchedModificationsLocal(batched, getSender());
577 ActorSelection leader = getLeader();
578 if (!isLeaderActive || leader == null) {
579 messageRetrySupport.addMessageToRetry(batched, getSender(),
580 "Could not commit transaction " + batched.getTransactionId());
582 // If this is not the first batch and leadership changed in between batched messages,
583 // we need to reconstruct previous BatchedModifications from the transaction
584 // DataTreeModification, honoring the max batched modification count, and forward all the
585 // previous BatchedModifications to the new leader.
586 Collection<BatchedModifications> newModifications = commitCoordinator
587 .createForwardedBatchedModifications(batched,
588 datastoreContext.getShardBatchedModificationCount());
590 LOG.debug("{}: Forwarding {} BatchedModifications to leader {}", persistenceId(),
591 newModifications.size(), leader);
593 for (BatchedModifications bm : newModifications) {
594 leader.forward(bm, getContext());
600 private boolean failIfIsolatedLeader(final ActorRef sender) {
601 if (isIsolatedLeader()) {
602 sender.tell(new Failure(new NoShardLeaderException(String.format(
603 "Shard %s was the leader but has lost contact with all of its followers. Either all"
604 + " other follower nodes are down or this node is isolated by a network partition.",
605 persistenceId()))), getSelf());
612 protected boolean isIsolatedLeader() {
613 return getRaftState() == RaftState.IsolatedLeader;
616 @SuppressWarnings("checkstyle:IllegalCatch")
617 private void handleReadyLocalTransaction(final ReadyLocalTransaction message) {
618 LOG.debug("{}: handleReadyLocalTransaction for {}", persistenceId(), message.getTransactionId());
620 boolean isLeaderActive = isLeaderActive();
621 if (isLeader() && isLeaderActive) {
623 commitCoordinator.handleReadyLocalTransaction(message, getSender(), this);
624 } catch (Exception e) {
625 LOG.error("{}: Error handling ReadyLocalTransaction for Tx {}", persistenceId(),
626 message.getTransactionId(), e);
627 getSender().tell(new Failure(e), getSelf());
630 ActorSelection leader = getLeader();
631 if (!isLeaderActive || leader == null) {
632 messageRetrySupport.addMessageToRetry(message, getSender(),
633 "Could not commit transaction " + message.getTransactionId());
635 LOG.debug("{}: Forwarding ReadyLocalTransaction to leader {}", persistenceId(), leader);
636 message.setRemoteVersion(getCurrentBehavior().getLeaderPayloadVersion());
637 leader.forward(message, getContext());
642 private void handleForwardedReadyTransaction(final ForwardedReadyTransaction forwardedReady) {
643 LOG.debug("{}: handleForwardedReadyTransaction for {}", persistenceId(), forwardedReady.getTransactionId());
645 boolean isLeaderActive = isLeaderActive();
646 if (isLeader() && isLeaderActive) {
647 commitCoordinator.handleForwardedReadyTransaction(forwardedReady, getSender(), this);
649 ActorSelection leader = getLeader();
650 if (!isLeaderActive || leader == null) {
651 messageRetrySupport.addMessageToRetry(forwardedReady, getSender(),
652 "Could not commit transaction " + forwardedReady.getTransactionId());
654 LOG.debug("{}: Forwarding ForwardedReadyTransaction to leader {}", persistenceId(), leader);
656 ReadyLocalTransaction readyLocal = new ReadyLocalTransaction(forwardedReady.getTransactionId(),
657 forwardedReady.getTransaction().getSnapshot(), forwardedReady.isDoImmediateCommit());
658 readyLocal.setRemoteVersion(getCurrentBehavior().getLeaderPayloadVersion());
659 leader.forward(readyLocal, getContext());
664 private void handleAbortTransaction(final AbortTransaction abort) {
665 doAbortTransaction(abort.getTransactionId(), getSender());
668 void doAbortTransaction(final Identifier transactionID, final ActorRef sender) {
669 commitCoordinator.handleAbort(transactionID, sender, this);
672 private void handleCreateTransaction(final Object message) {
674 createTransaction(CreateTransaction.fromSerializable(message));
675 } else if (getLeader() != null) {
676 getLeader().forward(message, getContext());
678 getSender().tell(new Failure(new NoShardLeaderException(
679 "Could not create a shard transaction", persistenceId())), getSelf());
683 private void closeTransactionChain(final CloseTransactionChain closeTransactionChain) {
684 final LocalHistoryIdentifier id = closeTransactionChain.getIdentifier();
685 store.closeTransactionChain(id, null);
686 store.purgeTransactionChain(id, null);
689 @SuppressWarnings("checkstyle:IllegalCatch")
690 private void createTransaction(final CreateTransaction createTransaction) {
692 if (TransactionType.fromInt(createTransaction.getTransactionType()) != TransactionType.READ_ONLY
693 && failIfIsolatedLeader(getSender())) {
697 ActorRef transactionActor = createTransaction(createTransaction.getTransactionType(),
698 createTransaction.getTransactionId());
700 getSender().tell(new CreateTransactionReply(Serialization.serializedActorPath(transactionActor),
701 createTransaction.getTransactionId(), createTransaction.getVersion()).toSerializable(), getSelf());
702 } catch (Exception e) {
703 getSender().tell(new Failure(e), getSelf());
707 private ActorRef createTransaction(final int transactionType, final TransactionIdentifier transactionId) {
708 LOG.debug("{}: Creating transaction : {} ", persistenceId(), transactionId);
709 return transactionActorFactory.newShardTransaction(TransactionType.fromInt(transactionType),
713 private void updateSchemaContext(final UpdateSchemaContext message) {
714 updateSchemaContext(message.getSchemaContext());
718 void updateSchemaContext(final SchemaContext schemaContext) {
719 store.updateSchemaContext(schemaContext);
722 private boolean isMetricsCaptureEnabled() {
723 CommonConfig config = new CommonConfig(getContext().system().settings().config());
724 return config.isMetricCaptureEnabled();
729 public RaftActorSnapshotCohort getRaftActorSnapshotCohort() {
730 return snapshotCohort;
735 protected RaftActorRecoveryCohort getRaftActorRecoveryCohort() {
736 return new ShardRecoveryCoordinator(store,
737 restoreFromSnapshot != null ? restoreFromSnapshot.getSnapshot() : null, persistenceId(), LOG);
741 protected void onRecoveryComplete() {
742 restoreFromSnapshot = null;
744 //notify shard manager
745 getContext().parent().tell(new ActorInitialized(), getSelf());
747 // Being paranoid here - this method should only be called once but just in case...
748 if (txCommitTimeoutCheckSchedule == null) {
749 // Schedule a message to be periodically sent to check if the current in-progress
750 // transaction should be expired and aborted.
751 FiniteDuration period = Duration.create(transactionCommitTimeout / 3, TimeUnit.MILLISECONDS);
752 txCommitTimeoutCheckSchedule = getContext().system().scheduler().schedule(
753 period, period, getSelf(),
754 TX_COMMIT_TIMEOUT_CHECK_MESSAGE, getContext().dispatcher(), ActorRef.noSender());
759 protected void applyState(final ActorRef clientActor, final Identifier identifier, final Object data) {
760 if (data instanceof Payload) {
762 store.applyReplicatedPayload(identifier, (Payload)data);
763 } catch (DataValidationFailedException | IOException e) {
764 LOG.error("{}: Error applying replica {}", persistenceId(), identifier, e);
767 LOG.error("{}: Unknown state for {} received {}", persistenceId(), identifier, data);
772 protected void onStateChanged() {
773 boolean isLeader = isLeader();
774 boolean hasLeader = hasLeader();
775 changeSupport.onLeadershipChange(isLeader, hasLeader);
776 treeChangeSupport.onLeadershipChange(isLeader, hasLeader);
778 // If this actor is no longer the leader close all the transaction chains
780 if (LOG.isDebugEnabled()) {
782 "{}: onStateChanged: Closing all transaction chains because shard {} is no longer the leader",
783 persistenceId(), getId());
786 store.purgeLeaderState();
789 if (hasLeader && !isIsolatedLeader()) {
790 messageRetrySupport.retryMessages();
795 protected void onLeaderChanged(final String oldLeader, final String newLeader) {
796 shardMBean.incrementLeadershipChangeCount();
798 final boolean hasLeader = hasLeader();
800 // No leader implies we are not the leader, lose frontend state if we have any. This also places
801 // an explicit guard so the map will not get modified accidentally.
802 if (!knownFrontends.isEmpty()) {
803 LOG.debug("{}: removing frontend state for {}", persistenceId(), knownFrontends.keySet());
804 knownFrontends = ImmutableMap.of();
810 // Another leader was elected. If we were the previous leader and had pending transactions, convert
811 // them to transaction messages and send to the new leader.
812 ActorSelection leader = getLeader();
813 if (leader != null) {
814 Collection<?> messagesToForward = convertPendingTransactionsToMessages();
816 if (!messagesToForward.isEmpty()) {
817 LOG.debug("{}: Forwarding {} pending transaction messages to leader {}", persistenceId(),
818 messagesToForward.size(), leader);
820 for (Object message : messagesToForward) {
821 leader.tell(message, self());
825 commitCoordinator.abortPendingTransactions("The transacton was aborted due to inflight leadership "
826 + "change and the leader address isn't available.", this);
829 // We have become the leader, we need to reconstruct frontend state
830 knownFrontends = Verify.verifyNotNull(frontendMetadata.toLeaderState(this));
831 LOG.debug("{}: became leader with frontend state for {}", persistenceId(), knownFrontends.keySet());
834 if (!isIsolatedLeader()) {
835 messageRetrySupport.retryMessages();
840 * Clears all pending transactions and converts them to messages to be forwarded to a new leader.
842 * @return the converted messages
844 public Collection<?> convertPendingTransactionsToMessages() {
845 return commitCoordinator.convertPendingTransactionsToMessages(
846 datastoreContext.getShardBatchedModificationCount());
850 protected void pauseLeader(final Runnable operation) {
851 LOG.debug("{}: In pauseLeader, operation: {}", persistenceId(), operation);
852 store.setRunOnPendingTransactionsComplete(operation);
856 protected OnDemandRaftState.AbstractBuilder<?> newOnDemandRaftStateBuilder() {
857 return OnDemandShardState.newBuilder().treeChangeListenerActors(treeChangeSupport.getListenerActors())
858 .dataChangeListenerActors(changeSupport.getListenerActors())
859 .commitCohortActors(store.getCohortActors());
863 public String persistenceId() {
868 ShardCommitCoordinator getCommitCoordinator() {
869 return commitCoordinator;
872 public DatastoreContext getDatastoreContext() {
873 return datastoreContext;
877 public ShardDataTree getDataStore() {
882 ShardStats getShardMBean() {
886 public static Builder builder() {
887 return new Builder();
890 public abstract static class AbstractBuilder<T extends AbstractBuilder<T, S>, S extends Shard> {
891 private final Class<S> shardClass;
892 private ShardIdentifier id;
893 private Map<String, String> peerAddresses = Collections.emptyMap();
894 private DatastoreContext datastoreContext;
895 private SchemaContext schemaContext;
896 private DatastoreSnapshot.ShardSnapshot restoreFromSnapshot;
897 private TipProducingDataTree dataTree;
898 private volatile boolean sealed;
900 protected AbstractBuilder(final Class<S> shardClass) {
901 this.shardClass = shardClass;
904 protected void checkSealed() {
905 Preconditions.checkState(!sealed, "Builder isalready sealed - further modifications are not allowed");
908 @SuppressWarnings("unchecked")
913 public T id(final ShardIdentifier newId) {
919 public T peerAddresses(final Map<String, String> newPeerAddresses) {
921 this.peerAddresses = newPeerAddresses;
925 public T datastoreContext(final DatastoreContext newDatastoreContext) {
927 this.datastoreContext = newDatastoreContext;
931 public T schemaContext(final SchemaContext newSchemaContext) {
933 this.schemaContext = newSchemaContext;
937 public T restoreFromSnapshot(final DatastoreSnapshot.ShardSnapshot newRestoreFromSnapshot) {
939 this.restoreFromSnapshot = newRestoreFromSnapshot;
943 public T dataTree(final TipProducingDataTree newDataTree) {
945 this.dataTree = newDataTree;
949 public ShardIdentifier getId() {
953 public Map<String, String> getPeerAddresses() {
954 return peerAddresses;
957 public DatastoreContext getDatastoreContext() {
958 return datastoreContext;
961 public SchemaContext getSchemaContext() {
962 return schemaContext;
965 public DatastoreSnapshot.ShardSnapshot getRestoreFromSnapshot() {
966 return restoreFromSnapshot;
969 public TipProducingDataTree getDataTree() {
973 public TreeType getTreeType() {
974 switch (datastoreContext.getLogicalStoreType()) {
976 return TreeType.CONFIGURATION;
978 return TreeType.OPERATIONAL;
980 throw new IllegalStateException("Unhandled logical store type "
981 + datastoreContext.getLogicalStoreType());
985 protected void verify() {
986 Preconditions.checkNotNull(id, "id should not be null");
987 Preconditions.checkNotNull(peerAddresses, "peerAddresses should not be null");
988 Preconditions.checkNotNull(datastoreContext, "dataStoreContext should not be null");
989 Preconditions.checkNotNull(schemaContext, "schemaContext should not be null");
992 public Props props() {
995 return Props.create(shardClass, this);
999 public static class Builder extends AbstractBuilder<Builder, Shard> {
1006 return Ticker.systemTicker();
1009 void scheduleNextPendingTransaction() {
1010 self().tell(RESUME_NEXT_PENDING_TRANSACTION, ActorRef.noSender());