26f18bd932ec27ef81de5d08428d70b03ff9ef60
[controller.git] / opendaylight / md-sal / sal-distributed-datastore / src / main / java / org / opendaylight / controller / cluster / datastore / Shard.java
1 /*
2  * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
3  *
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
7  */
8
9 package org.opendaylight.controller.cluster.datastore;
10
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.collect.ImmutableList;
22 import com.google.common.collect.Range;
23 import java.io.IOException;
24 import java.util.Arrays;
25 import java.util.Collection;
26 import java.util.Collections;
27 import java.util.HashMap;
28 import java.util.Map;
29 import java.util.concurrent.TimeUnit;
30 import javax.annotation.Nonnull;
31 import javax.annotation.Nullable;
32 import org.opendaylight.controller.cluster.access.ABIVersion;
33 import org.opendaylight.controller.cluster.access.commands.ConnectClientRequest;
34 import org.opendaylight.controller.cluster.access.commands.ConnectClientSuccess;
35 import org.opendaylight.controller.cluster.access.commands.LocalHistoryRequest;
36 import org.opendaylight.controller.cluster.access.commands.NotLeaderException;
37 import org.opendaylight.controller.cluster.access.commands.TransactionRequest;
38 import org.opendaylight.controller.cluster.access.concepts.ClientIdentifier;
39 import org.opendaylight.controller.cluster.access.concepts.FrontendIdentifier;
40 import org.opendaylight.controller.cluster.access.concepts.Request;
41 import org.opendaylight.controller.cluster.access.concepts.RequestEnvelope;
42 import org.opendaylight.controller.cluster.access.concepts.RequestException;
43 import org.opendaylight.controller.cluster.access.concepts.RequestSuccess;
44 import org.opendaylight.controller.cluster.access.concepts.RetiredGenerationException;
45 import org.opendaylight.controller.cluster.access.concepts.RuntimeRequestException;
46 import org.opendaylight.controller.cluster.access.concepts.TransactionIdentifier;
47 import org.opendaylight.controller.cluster.access.concepts.UnsupportedRequestException;
48 import org.opendaylight.controller.cluster.common.actor.CommonConfig;
49 import org.opendaylight.controller.cluster.common.actor.MessageTracker;
50 import org.opendaylight.controller.cluster.common.actor.MessageTracker.Error;
51 import org.opendaylight.controller.cluster.common.actor.MeteringBehavior;
52 import org.opendaylight.controller.cluster.datastore.exceptions.NoShardLeaderException;
53 import org.opendaylight.controller.cluster.datastore.identifiers.ShardIdentifier;
54 import org.opendaylight.controller.cluster.datastore.jmx.mbeans.shard.ShardMBeanFactory;
55 import org.opendaylight.controller.cluster.datastore.jmx.mbeans.shard.ShardStats;
56 import org.opendaylight.controller.cluster.datastore.messages.AbortTransaction;
57 import org.opendaylight.controller.cluster.datastore.messages.ActorInitialized;
58 import org.opendaylight.controller.cluster.datastore.messages.BatchedModifications;
59 import org.opendaylight.controller.cluster.datastore.messages.CanCommitTransaction;
60 import org.opendaylight.controller.cluster.datastore.messages.CloseTransactionChain;
61 import org.opendaylight.controller.cluster.datastore.messages.CommitTransaction;
62 import org.opendaylight.controller.cluster.datastore.messages.CreateTransaction;
63 import org.opendaylight.controller.cluster.datastore.messages.CreateTransactionReply;
64 import org.opendaylight.controller.cluster.datastore.messages.DatastoreSnapshot;
65 import org.opendaylight.controller.cluster.datastore.messages.DatastoreSnapshot.ShardSnapshot;
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.PeerAddressResolved;
69 import org.opendaylight.controller.cluster.datastore.messages.ReadyLocalTransaction;
70 import org.opendaylight.controller.cluster.datastore.messages.RegisterChangeListener;
71 import org.opendaylight.controller.cluster.datastore.messages.RegisterDataTreeChangeListener;
72 import org.opendaylight.controller.cluster.datastore.messages.ShardLeaderStateChanged;
73 import org.opendaylight.controller.cluster.datastore.messages.UpdateSchemaContext;
74 import org.opendaylight.controller.cluster.datastore.utils.Dispatchers;
75 import org.opendaylight.controller.cluster.notifications.LeaderStateChanged;
76 import org.opendaylight.controller.cluster.notifications.RegisterRoleChangeListener;
77 import org.opendaylight.controller.cluster.notifications.RoleChangeNotifier;
78 import org.opendaylight.controller.cluster.raft.RaftActor;
79 import org.opendaylight.controller.cluster.raft.RaftActorRecoveryCohort;
80 import org.opendaylight.controller.cluster.raft.RaftActorSnapshotCohort;
81 import org.opendaylight.controller.cluster.raft.RaftState;
82 import org.opendaylight.controller.cluster.raft.base.messages.FollowerInitialSyncUpStatus;
83 import org.opendaylight.controller.cluster.raft.messages.AppendEntriesReply;
84 import org.opendaylight.controller.cluster.raft.messages.ServerRemoved;
85 import org.opendaylight.controller.cluster.raft.protobuff.client.messages.Payload;
86 import org.opendaylight.yangtools.concepts.Identifier;
87 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataValidationFailedException;
88 import org.opendaylight.yangtools.yang.data.api.schema.tree.TipProducingDataTree;
89 import org.opendaylight.yangtools.yang.data.api.schema.tree.TreeType;
90 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
91 import scala.concurrent.duration.Duration;
92 import scala.concurrent.duration.FiniteDuration;
93
94 /**
95  * A Shard represents a portion of the logical data tree.
96  *
97  * <p>
98  * Our Shard uses InMemoryDataTree as it's internal representation and delegates all requests it
99  */
100 public class Shard extends RaftActor {
101
102     @VisibleForTesting
103     static final Object TX_COMMIT_TIMEOUT_CHECK_MESSAGE = new Object() {
104         @Override
105         public String toString() {
106             return "txCommitTimeoutCheck";
107         }
108     };
109
110     @VisibleForTesting
111     static final Object GET_SHARD_MBEAN_MESSAGE = new Object() {
112         @Override
113         public String toString() {
114             return "getShardMBeanMessage";
115         }
116     };
117
118     // FIXME: shard names should be encapsulated in their own class and this should be exposed as a constant.
119     public static final String DEFAULT_NAME = "default";
120
121     private static final Collection<ABIVersion> SUPPORTED_ABIVERSIONS;
122
123     static {
124         final ABIVersion[] values = ABIVersion.values();
125         final ABIVersion[] real = Arrays.copyOfRange(values, 1, values.length - 1);
126         SUPPORTED_ABIVERSIONS = ImmutableList.copyOf(real).reverse();
127     }
128
129     // FIXME: make this a dynamic property based on mailbox size and maximum number of clients
130     private static final int CLIENT_MAX_MESSAGES = 1000;
131
132     // The state of this Shard
133     private final ShardDataTree store;
134
135     /// The name of this shard
136     private final String name;
137
138     private final ShardStats shardMBean;
139
140     private DatastoreContext datastoreContext;
141
142     private final ShardCommitCoordinator commitCoordinator;
143
144     private long transactionCommitTimeout;
145
146     private Cancellable txCommitTimeoutCheckSchedule;
147
148     private final Optional<ActorRef> roleChangeNotifier;
149
150     private final MessageTracker appendEntriesReplyTracker;
151
152     private final ShardTransactionActorFactory transactionActorFactory;
153
154     private final ShardSnapshotCohort snapshotCohort;
155
156     private final DataTreeChangeListenerSupport treeChangeSupport = new DataTreeChangeListenerSupport(this);
157     private final DataChangeListenerSupport changeSupport = new DataChangeListenerSupport(this);
158
159
160     private ShardSnapshot restoreFromSnapshot;
161
162     private final ShardTransactionMessageRetrySupport messageRetrySupport;
163
164     private final FrontendMetadata frontendMetadata = new FrontendMetadata();
165     private final Map<FrontendIdentifier, LeaderFrontendState> knownFrontends = new HashMap<>();
166
167     protected Shard(final AbstractBuilder<?, ?> builder) {
168         super(builder.getId().toString(), builder.getPeerAddresses(),
169                 Optional.of(builder.getDatastoreContext().getShardRaftConfig()), DataStoreVersions.CURRENT_VERSION);
170
171         this.name = builder.getId().toString();
172         this.datastoreContext = builder.getDatastoreContext();
173         this.restoreFromSnapshot = builder.getRestoreFromSnapshot();
174
175         setPersistence(datastoreContext.isPersistent());
176
177         LOG.info("Shard created : {}, persistent : {}", name, datastoreContext.isPersistent());
178
179         ShardDataTreeChangeListenerPublisherActorProxy treeChangeListenerPublisher =
180                 new ShardDataTreeChangeListenerPublisherActorProxy(getContext(), name + "-DTCL-publisher");
181         ShardDataChangeListenerPublisherActorProxy dataChangeListenerPublisher =
182                 new ShardDataChangeListenerPublisherActorProxy(getContext(), name + "-DCL-publisher");
183         if (builder.getDataTree() != null) {
184             store = new ShardDataTree(this, builder.getSchemaContext(), builder.getDataTree(),
185                     treeChangeListenerPublisher, dataChangeListenerPublisher, name);
186         } else {
187             store = new ShardDataTree(this, builder.getSchemaContext(), builder.getTreeType(),
188                     treeChangeListenerPublisher, dataChangeListenerPublisher, name);
189         }
190
191         shardMBean = ShardMBeanFactory.getShardStatsMBean(name, datastoreContext.getDataStoreMXBeanType(), this);
192
193         if (isMetricsCaptureEnabled()) {
194             getContext().become(new MeteringBehavior(this));
195         }
196
197         commitCoordinator = new ShardCommitCoordinator(store, LOG, this.name);
198
199         setTransactionCommitTimeout();
200
201         // create a notifier actor for each cluster member
202         roleChangeNotifier = createRoleChangeNotifier(name);
203
204         appendEntriesReplyTracker = new MessageTracker(AppendEntriesReply.class,
205                 getRaftActorContext().getConfigParams().getIsolatedCheckIntervalInMillis());
206
207         transactionActorFactory = new ShardTransactionActorFactory(store, datastoreContext,
208                 new Dispatchers(context().system().dispatchers()).getDispatcherPath(
209                         Dispatchers.DispatcherType.Transaction), self(), getContext(), shardMBean);
210
211         snapshotCohort = ShardSnapshotCohort.create(getContext(), builder.getId().getMemberName(), store, LOG,
212             this.name);
213
214         messageRetrySupport = new ShardTransactionMessageRetrySupport(this);
215     }
216
217     private void setTransactionCommitTimeout() {
218         transactionCommitTimeout = TimeUnit.MILLISECONDS.convert(
219                 datastoreContext.getShardTransactionCommitTimeoutInSeconds(), TimeUnit.SECONDS) / 2;
220     }
221
222     private Optional<ActorRef> createRoleChangeNotifier(final String shardId) {
223         ActorRef shardRoleChangeNotifier = this.getContext().actorOf(
224             RoleChangeNotifier.getProps(shardId), shardId + "-notifier");
225         return Optional.of(shardRoleChangeNotifier);
226     }
227
228     @Override
229     public void postStop() {
230         LOG.info("Stopping Shard {}", persistenceId());
231
232         super.postStop();
233
234         messageRetrySupport.close();
235
236         if (txCommitTimeoutCheckSchedule != null) {
237             txCommitTimeoutCheckSchedule.cancel();
238         }
239
240         commitCoordinator.abortPendingTransactions("Transaction aborted due to shutdown.", this);
241
242         shardMBean.unregisterMBean();
243     }
244
245     @Override
246     protected void handleRecover(final Object message) {
247         LOG.debug("{}: onReceiveRecover: Received message {} from {}", persistenceId(), message.getClass(),
248             getSender());
249
250         super.handleRecover(message);
251         if (LOG.isTraceEnabled()) {
252             appendEntriesReplyTracker.begin();
253         }
254     }
255
256     @SuppressWarnings("checkstyle:IllegalCatch")
257     @Override
258     protected void handleNonRaftCommand(final Object message) {
259         try (final MessageTracker.Context context = appendEntriesReplyTracker.received(message)) {
260             final Optional<Error> maybeError = context.error();
261             if (maybeError.isPresent()) {
262                 LOG.trace("{} : AppendEntriesReply failed to arrive at the expected interval {}", persistenceId(),
263                     maybeError.get());
264             }
265
266             if (message instanceof RequestEnvelope) {
267                 final RequestEnvelope envelope = (RequestEnvelope)message;
268                 try {
269                     final RequestSuccess<?, ?> success = handleRequest(envelope);
270                     if (success != null) {
271                         envelope.sendSuccess(success);
272                     }
273                 } catch (RequestException e) {
274                     LOG.debug("{}: request {} failed", persistenceId(), envelope, e);
275                     envelope.sendFailure(e);
276                 } catch (Exception e) {
277                     LOG.debug("{}: request {} caused failure", persistenceId(), envelope, e);
278                     envelope.sendFailure(new RuntimeRequestException("Request failed to process", e));
279                 }
280             } else if (message instanceof ConnectClientRequest) {
281                 handleConnectClient((ConnectClientRequest)message);
282             } else if (CreateTransaction.isSerializedType(message)) {
283                 handleCreateTransaction(message);
284             } else if (message instanceof BatchedModifications) {
285                 handleBatchedModifications((BatchedModifications)message);
286             } else if (message instanceof ForwardedReadyTransaction) {
287                 handleForwardedReadyTransaction((ForwardedReadyTransaction) message);
288             } else if (message instanceof ReadyLocalTransaction) {
289                 handleReadyLocalTransaction((ReadyLocalTransaction)message);
290             } else if (CanCommitTransaction.isSerializedType(message)) {
291                 handleCanCommitTransaction(CanCommitTransaction.fromSerializable(message));
292             } else if (CommitTransaction.isSerializedType(message)) {
293                 handleCommitTransaction(CommitTransaction.fromSerializable(message));
294             } else if (AbortTransaction.isSerializedType(message)) {
295                 handleAbortTransaction(AbortTransaction.fromSerializable(message));
296             } else if (CloseTransactionChain.isSerializedType(message)) {
297                 closeTransactionChain(CloseTransactionChain.fromSerializable(message));
298             } else if (message instanceof RegisterChangeListener) {
299                 changeSupport.onMessage((RegisterChangeListener) message, isLeader(), hasLeader());
300             } else if (message instanceof RegisterDataTreeChangeListener) {
301                 treeChangeSupport.onMessage((RegisterDataTreeChangeListener) message, isLeader(), hasLeader());
302             } else if (message instanceof UpdateSchemaContext) {
303                 updateSchemaContext((UpdateSchemaContext) message);
304             } else if (message instanceof PeerAddressResolved) {
305                 PeerAddressResolved resolved = (PeerAddressResolved) message;
306                 setPeerAddress(resolved.getPeerId(), resolved.getPeerAddress());
307             } else if (TX_COMMIT_TIMEOUT_CHECK_MESSAGE.equals(message)) {
308                 store.checkForExpiredTransactions(transactionCommitTimeout);
309                 commitCoordinator.checkForExpiredTransactions(transactionCommitTimeout, this);
310             } else if (message instanceof DatastoreContext) {
311                 onDatastoreContext((DatastoreContext)message);
312             } else if (message instanceof RegisterRoleChangeListener) {
313                 roleChangeNotifier.get().forward(message, context());
314             } else if (message instanceof FollowerInitialSyncUpStatus) {
315                 shardMBean.setFollowerInitialSyncStatus(((FollowerInitialSyncUpStatus) message).isInitialSyncDone());
316                 context().parent().tell(message, self());
317             } else if (GET_SHARD_MBEAN_MESSAGE.equals(message)) {
318                 sender().tell(getShardMBean(), self());
319             } else if (message instanceof GetShardDataTree) {
320                 sender().tell(store.getDataTree(), self());
321             } else if (message instanceof ServerRemoved) {
322                 context().parent().forward(message, context());
323             } else if (ShardTransactionMessageRetrySupport.TIMER_MESSAGE_CLASS.isInstance(message)) {
324                 messageRetrySupport.onTimerMessage(message);
325             } else if (message instanceof DataTreeCohortActorRegistry.CohortRegistryCommand) {
326                 store.processCohortRegistryCommand(getSender(),
327                         (DataTreeCohortActorRegistry.CohortRegistryCommand) message);
328             } else {
329                 super.handleNonRaftCommand(message);
330             }
331         }
332     }
333
334     // Acquire our frontend tracking handle and verify generation matches
335     private LeaderFrontendState getFrontend(final ClientIdentifier clientId) throws RequestException {
336         final LeaderFrontendState existing = knownFrontends.get(clientId.getFrontendId());
337         if (existing != null) {
338             final int cmp = Long.compareUnsigned(existing.getIdentifier().getGeneration(), clientId.getGeneration());
339             if (cmp == 0) {
340                 return existing;
341             }
342             if (cmp > 0) {
343                 LOG.debug("{}: rejecting request from outdated client {}", persistenceId(), clientId);
344                 throw new RetiredGenerationException(existing.getIdentifier().getGeneration());
345             }
346
347             LOG.info("{}: retiring state {}, outdated by request from client {}", persistenceId(), existing, clientId);
348             existing.retire();
349             knownFrontends.remove(clientId.getFrontendId());
350         } else {
351             LOG.debug("{}: client {} is not yet known", persistenceId(), clientId);
352         }
353
354         final LeaderFrontendState ret = new LeaderFrontendState(persistenceId(), clientId, store);
355         knownFrontends.put(clientId.getFrontendId(), ret);
356         LOG.debug("{}: created state {} for client {}", persistenceId(), ret, clientId);
357         return ret;
358     }
359
360     private static @Nonnull ABIVersion selectVersion(final ConnectClientRequest message) {
361         final Range<ABIVersion> clientRange = Range.closed(message.getMinVersion(), message.getMaxVersion());
362         for (ABIVersion v : SUPPORTED_ABIVERSIONS) {
363             if (clientRange.contains(v)) {
364                 return v;
365             }
366         }
367
368         throw new IllegalArgumentException(String.format(
369             "No common version between backend versions %s and client versions %s", SUPPORTED_ABIVERSIONS,
370             clientRange));
371     }
372
373     @SuppressWarnings("checkstyle:IllegalCatch")
374     private void handleConnectClient(final ConnectClientRequest message) {
375         try {
376             if (!isLeader() || !isLeaderActive()) {
377                 LOG.debug("{}: not currently leader, rejecting request {}", persistenceId(), message);
378                 throw new NotLeaderException(getSelf());
379             }
380
381             final ABIVersion selectedVersion = selectVersion(message);
382             final LeaderFrontendState frontend = getFrontend(message.getTarget());
383             frontend.reconnect();
384             message.getReplyTo().tell(new ConnectClientSuccess(message.getTarget(), message.getSequence(), getSelf(),
385                 ImmutableList.of(), store.getDataTree(), CLIENT_MAX_MESSAGES).toVersion(selectedVersion),
386                 ActorRef.noSender());
387         } catch (RequestException | RuntimeException e) {
388             message.getReplyTo().tell(new Failure(e), ActorRef.noSender());
389         }
390     }
391
392     private @Nullable RequestSuccess<?, ?> handleRequest(final RequestEnvelope envelope) throws RequestException {
393         // We are not the leader, hence we want to fail-fast.
394         if (!isLeader() || !isLeaderActive()) {
395             LOG.debug("{}: not currently leader, rejecting request {}", persistenceId(), envelope);
396             throw new NotLeaderException(getSelf());
397         }
398
399         final Request<?, ?> request = envelope.getMessage();
400         if (request instanceof TransactionRequest) {
401             final TransactionRequest<?> txReq = (TransactionRequest<?>)request;
402             final ClientIdentifier clientId = txReq.getTarget().getHistoryId().getClientId();
403             return getFrontend(clientId).handleTransactionRequest(txReq, envelope);
404         } else if (request instanceof LocalHistoryRequest) {
405             final LocalHistoryRequest<?> lhReq = (LocalHistoryRequest<?>)request;
406             final ClientIdentifier clientId = lhReq.getTarget().getClientId();
407             return getFrontend(clientId).handleLocalHistoryRequest(lhReq, envelope);
408         } else {
409             LOG.debug("{}: rejecting unsupported request {}", persistenceId(), request);
410             throw new UnsupportedRequestException(request);
411         }
412     }
413
414     private boolean hasLeader() {
415         return getLeaderId() != null;
416     }
417
418     public int getPendingTxCommitQueueSize() {
419         return store.getQueueSize();
420     }
421
422     public int getCohortCacheSize() {
423         return commitCoordinator.getCohortCacheSize();
424     }
425
426     @Override
427     protected Optional<ActorRef> getRoleChangeNotifier() {
428         return roleChangeNotifier;
429     }
430
431     @Override
432     protected LeaderStateChanged newLeaderStateChanged(final String memberId, final String leaderId,
433             final short leaderPayloadVersion) {
434         return isLeader() ? new ShardLeaderStateChanged(memberId, leaderId, store.getDataTree(), leaderPayloadVersion)
435                 : new ShardLeaderStateChanged(memberId, leaderId, leaderPayloadVersion);
436     }
437
438     protected void onDatastoreContext(final DatastoreContext context) {
439         datastoreContext = context;
440
441         setTransactionCommitTimeout();
442
443         setPersistence(datastoreContext.isPersistent());
444
445         updateConfigParams(datastoreContext.getShardRaftConfig());
446     }
447
448     boolean canSkipPayload() {
449         // If we do not have any followers and we are not using persistence we can apply modification to the state
450         // immediately
451         return !hasFollowers() && !persistence().isRecoveryApplicable();
452     }
453
454     // applyState() will be invoked once consensus is reached on the payload
455     void persistPayload(final TransactionIdentifier transactionId, final Payload payload) {
456         // We are faking the sender
457         persistData(self(), transactionId, payload);
458     }
459
460     private void handleCommitTransaction(final CommitTransaction commit) {
461         if (isLeader()) {
462             commitCoordinator.handleCommit(commit.getTransactionId(), getSender(), this);
463         } else {
464             ActorSelection leader = getLeader();
465             if (leader == null) {
466                 messageRetrySupport.addMessageToRetry(commit, getSender(),
467                         "Could not commit transaction " + commit.getTransactionId());
468             } else {
469                 LOG.debug("{}: Forwarding CommitTransaction to leader {}", persistenceId(), leader);
470                 leader.forward(commit, getContext());
471             }
472         }
473     }
474
475     private void handleCanCommitTransaction(final CanCommitTransaction canCommit) {
476         LOG.debug("{}: Can committing transaction {}", persistenceId(), canCommit.getTransactionId());
477
478         if (isLeader()) {
479             commitCoordinator.handleCanCommit(canCommit.getTransactionId(), getSender(), this);
480         } else {
481             ActorSelection leader = getLeader();
482             if (leader == null) {
483                 messageRetrySupport.addMessageToRetry(canCommit, getSender(),
484                         "Could not canCommit transaction " + canCommit.getTransactionId());
485             } else {
486                 LOG.debug("{}: Forwarding CanCommitTransaction to leader {}", persistenceId(), leader);
487                 leader.forward(canCommit, getContext());
488             }
489         }
490     }
491
492     @SuppressWarnings("checkstyle:IllegalCatch")
493     protected void handleBatchedModificationsLocal(final BatchedModifications batched, final ActorRef sender) {
494         try {
495             commitCoordinator.handleBatchedModifications(batched, sender, this);
496         } catch (Exception e) {
497             LOG.error("{}: Error handling BatchedModifications for Tx {}", persistenceId(),
498                     batched.getTransactionId(), e);
499             sender.tell(new Failure(e), getSelf());
500         }
501     }
502
503     private void handleBatchedModifications(final BatchedModifications batched) {
504         // This message is sent to prepare the modifications transaction directly on the Shard as an
505         // optimization to avoid the extra overhead of a separate ShardTransaction actor. On the last
506         // BatchedModifications message, the caller sets the ready flag in the message indicating
507         // modifications are complete. The reply contains the cohort actor path (this actor) for the caller
508         // to initiate the 3-phase commit. This also avoids the overhead of sending an additional
509         // ReadyTransaction message.
510
511         // If we're not the leader then forward to the leader. This is a safety measure - we shouldn't
512         // normally get here if we're not the leader as the front-end (TransactionProxy) should determine
513         // the primary/leader shard. However with timing and caching on the front-end, there's a small
514         // window where it could have a stale leader during leadership transitions.
515         //
516         boolean isLeaderActive = isLeaderActive();
517         if (isLeader() && isLeaderActive) {
518             handleBatchedModificationsLocal(batched, getSender());
519         } else {
520             ActorSelection leader = getLeader();
521             if (!isLeaderActive || leader == null) {
522                 messageRetrySupport.addMessageToRetry(batched, getSender(),
523                         "Could not commit transaction " + batched.getTransactionId());
524             } else {
525                 // If this is not the first batch and leadership changed in between batched messages,
526                 // we need to reconstruct previous BatchedModifications from the transaction
527                 // DataTreeModification, honoring the max batched modification count, and forward all the
528                 // previous BatchedModifications to the new leader.
529                 Collection<BatchedModifications> newModifications = commitCoordinator
530                         .createForwardedBatchedModifications(batched,
531                                 datastoreContext.getShardBatchedModificationCount());
532
533                 LOG.debug("{}: Forwarding {} BatchedModifications to leader {}", persistenceId(),
534                         newModifications.size(), leader);
535
536                 for (BatchedModifications bm : newModifications) {
537                     leader.forward(bm, getContext());
538                 }
539             }
540         }
541     }
542
543     private boolean failIfIsolatedLeader(final ActorRef sender) {
544         if (isIsolatedLeader()) {
545             sender.tell(new Failure(new NoShardLeaderException(String.format(
546                     "Shard %s was the leader but has lost contact with all of its followers. Either all"
547                     + " other follower nodes are down or this node is isolated by a network partition.",
548                     persistenceId()))), getSelf());
549             return true;
550         }
551
552         return false;
553     }
554
555     protected boolean isIsolatedLeader() {
556         return getRaftState() == RaftState.IsolatedLeader;
557     }
558
559     @SuppressWarnings("checkstyle:IllegalCatch")
560     private void handleReadyLocalTransaction(final ReadyLocalTransaction message) {
561         LOG.debug("{}: handleReadyLocalTransaction for {}", persistenceId(), message.getTransactionId());
562
563         boolean isLeaderActive = isLeaderActive();
564         if (isLeader() && isLeaderActive) {
565             try {
566                 commitCoordinator.handleReadyLocalTransaction(message, getSender(), this);
567             } catch (Exception e) {
568                 LOG.error("{}: Error handling ReadyLocalTransaction for Tx {}", persistenceId(),
569                         message.getTransactionId(), e);
570                 getSender().tell(new Failure(e), getSelf());
571             }
572         } else {
573             ActorSelection leader = getLeader();
574             if (!isLeaderActive || leader == null) {
575                 messageRetrySupport.addMessageToRetry(message, getSender(),
576                         "Could not commit transaction " + message.getTransactionId());
577             } else {
578                 LOG.debug("{}: Forwarding ReadyLocalTransaction to leader {}", persistenceId(), leader);
579                 message.setRemoteVersion(getCurrentBehavior().getLeaderPayloadVersion());
580                 leader.forward(message, getContext());
581             }
582         }
583     }
584
585     private void handleForwardedReadyTransaction(final ForwardedReadyTransaction forwardedReady) {
586         LOG.debug("{}: handleForwardedReadyTransaction for {}", persistenceId(), forwardedReady.getTransactionId());
587
588         boolean isLeaderActive = isLeaderActive();
589         if (isLeader() && isLeaderActive) {
590             commitCoordinator.handleForwardedReadyTransaction(forwardedReady, getSender(), this);
591         } else {
592             ActorSelection leader = getLeader();
593             if (!isLeaderActive || leader == null) {
594                 messageRetrySupport.addMessageToRetry(forwardedReady, getSender(),
595                         "Could not commit transaction " + forwardedReady.getTransactionId());
596             } else {
597                 LOG.debug("{}: Forwarding ForwardedReadyTransaction to leader {}", persistenceId(), leader);
598
599                 ReadyLocalTransaction readyLocal = new ReadyLocalTransaction(forwardedReady.getTransactionId(),
600                         forwardedReady.getTransaction().getSnapshot(), forwardedReady.isDoImmediateCommit());
601                 readyLocal.setRemoteVersion(getCurrentBehavior().getLeaderPayloadVersion());
602                 leader.forward(readyLocal, getContext());
603             }
604         }
605     }
606
607     private void handleAbortTransaction(final AbortTransaction abort) {
608         doAbortTransaction(abort.getTransactionId(), getSender());
609     }
610
611     void doAbortTransaction(final TransactionIdentifier transactionID, final ActorRef sender) {
612         commitCoordinator.handleAbort(transactionID, sender, this);
613     }
614
615     private void handleCreateTransaction(final Object message) {
616         if (isLeader()) {
617             createTransaction(CreateTransaction.fromSerializable(message));
618         } else if (getLeader() != null) {
619             getLeader().forward(message, getContext());
620         } else {
621             getSender().tell(new Failure(new NoShardLeaderException(
622                     "Could not create a shard transaction", persistenceId())), getSelf());
623         }
624     }
625
626     private void closeTransactionChain(final CloseTransactionChain closeTransactionChain) {
627         store.closeTransactionChain(closeTransactionChain.getIdentifier());
628     }
629
630     @SuppressWarnings("checkstyle:IllegalCatch")
631     private void createTransaction(final CreateTransaction createTransaction) {
632         try {
633             if (TransactionType.fromInt(createTransaction.getTransactionType()) != TransactionType.READ_ONLY
634                     && failIfIsolatedLeader(getSender())) {
635                 return;
636             }
637
638             ActorRef transactionActor = createTransaction(createTransaction.getTransactionType(),
639                 createTransaction.getTransactionId());
640
641             getSender().tell(new CreateTransactionReply(Serialization.serializedActorPath(transactionActor),
642                     createTransaction.getTransactionId(), createTransaction.getVersion()).toSerializable(), getSelf());
643         } catch (Exception e) {
644             getSender().tell(new Failure(e), getSelf());
645         }
646     }
647
648     private ActorRef createTransaction(final int transactionType, final TransactionIdentifier transactionId) {
649         LOG.debug("{}: Creating transaction : {} ", persistenceId(), transactionId);
650         return transactionActorFactory.newShardTransaction(TransactionType.fromInt(transactionType),
651             transactionId);
652     }
653
654     private void updateSchemaContext(final UpdateSchemaContext message) {
655         updateSchemaContext(message.getSchemaContext());
656     }
657
658     @VisibleForTesting
659     void updateSchemaContext(final SchemaContext schemaContext) {
660         store.updateSchemaContext(schemaContext);
661     }
662
663     private boolean isMetricsCaptureEnabled() {
664         CommonConfig config = new CommonConfig(getContext().system().settings().config());
665         return config.isMetricCaptureEnabled();
666     }
667
668     @Override
669     @VisibleForTesting
670     public RaftActorSnapshotCohort getRaftActorSnapshotCohort() {
671         return snapshotCohort;
672     }
673
674     @Override
675     @Nonnull
676     protected RaftActorRecoveryCohort getRaftActorRecoveryCohort() {
677         return new ShardRecoveryCoordinator(store,
678             restoreFromSnapshot != null ? restoreFromSnapshot.getSnapshot() : null, persistenceId(), LOG);
679     }
680
681     @Override
682     protected void onRecoveryComplete() {
683         restoreFromSnapshot = null;
684
685         //notify shard manager
686         getContext().parent().tell(new ActorInitialized(), getSelf());
687
688         // Being paranoid here - this method should only be called once but just in case...
689         if (txCommitTimeoutCheckSchedule == null) {
690             // Schedule a message to be periodically sent to check if the current in-progress
691             // transaction should be expired and aborted.
692             FiniteDuration period = Duration.create(transactionCommitTimeout / 3, TimeUnit.MILLISECONDS);
693             txCommitTimeoutCheckSchedule = getContext().system().scheduler().schedule(
694                     period, period, getSelf(),
695                     TX_COMMIT_TIMEOUT_CHECK_MESSAGE, getContext().dispatcher(), ActorRef.noSender());
696         }
697     }
698
699     @Override
700     protected void applyState(final ActorRef clientActor, final Identifier identifier, final Object data) {
701         if (data instanceof Payload) {
702             try {
703                 store.applyReplicatedPayload(identifier, (Payload)data);
704             } catch (DataValidationFailedException | IOException e) {
705                 LOG.error("{}: Error applying replica {}", persistenceId(), identifier, e);
706             }
707         } else {
708             LOG.error("{}: Unknown state for {} received {}", persistenceId(), identifier, data);
709         }
710     }
711
712     @Override
713     protected void onStateChanged() {
714         boolean isLeader = isLeader();
715         boolean hasLeader = hasLeader();
716         changeSupport.onLeadershipChange(isLeader, hasLeader);
717         treeChangeSupport.onLeadershipChange(isLeader, hasLeader);
718
719         // If this actor is no longer the leader close all the transaction chains
720         if (!isLeader) {
721             if (LOG.isDebugEnabled()) {
722                 LOG.debug(
723                     "{}: onStateChanged: Closing all transaction chains because shard {} is no longer the leader",
724                     persistenceId(), getId());
725             }
726
727             store.closeAllTransactionChains();
728         }
729
730         if (hasLeader && !isIsolatedLeader()) {
731             messageRetrySupport.retryMessages();
732         }
733     }
734
735     @Override
736     protected void onLeaderChanged(final String oldLeader, final String newLeader) {
737         shardMBean.incrementLeadershipChangeCount();
738
739         boolean hasLeader = hasLeader();
740         if (hasLeader && !isLeader()) {
741             // Another leader was elected. If we were the previous leader and had pending transactions, convert
742             // them to transaction messages and send to the new leader.
743             ActorSelection leader = getLeader();
744             if (leader != null) {
745                 Collection<?> messagesToForward = convertPendingTransactionsToMessages();
746
747                 if (!messagesToForward.isEmpty()) {
748                     LOG.debug("{}: Forwarding {} pending transaction messages to leader {}", persistenceId(),
749                             messagesToForward.size(), leader);
750
751                     for (Object message : messagesToForward) {
752                         leader.tell(message, self());
753                     }
754                 }
755             } else {
756                 commitCoordinator.abortPendingTransactions("The transacton was aborted due to inflight leadership "
757                         + "change and the leader address isn't available.", this);
758             }
759         }
760
761         if (hasLeader && !isIsolatedLeader()) {
762             messageRetrySupport.retryMessages();
763         }
764     }
765
766     /**
767      * Clears all pending transactions and converts them to messages to be forwarded to a new leader.
768      *
769      * @return the converted messages
770      */
771     public Collection<?> convertPendingTransactionsToMessages() {
772         return commitCoordinator.convertPendingTransactionsToMessages(
773                 datastoreContext.getShardBatchedModificationCount());
774     }
775
776     @Override
777     protected void pauseLeader(final Runnable operation) {
778         LOG.debug("{}: In pauseLeader, operation: {}", persistenceId(), operation);
779         store.setRunOnPendingTransactionsComplete(operation);
780     }
781
782     @Override
783     public String persistenceId() {
784         return this.name;
785     }
786
787     @VisibleForTesting
788     ShardCommitCoordinator getCommitCoordinator() {
789         return commitCoordinator;
790     }
791
792     public DatastoreContext getDatastoreContext() {
793         return datastoreContext;
794     }
795
796     @VisibleForTesting
797     public ShardDataTree getDataStore() {
798         return store;
799     }
800
801     @VisibleForTesting
802     ShardStats getShardMBean() {
803         return shardMBean;
804     }
805
806     public static Builder builder() {
807         return new Builder();
808     }
809
810     public abstract static class AbstractBuilder<T extends AbstractBuilder<T, S>, S extends Shard> {
811         private final Class<S> shardClass;
812         private ShardIdentifier id;
813         private Map<String, String> peerAddresses = Collections.emptyMap();
814         private DatastoreContext datastoreContext;
815         private SchemaContext schemaContext;
816         private DatastoreSnapshot.ShardSnapshot restoreFromSnapshot;
817         private TipProducingDataTree dataTree;
818         private volatile boolean sealed;
819
820         protected AbstractBuilder(final Class<S> shardClass) {
821             this.shardClass = shardClass;
822         }
823
824         protected void checkSealed() {
825             Preconditions.checkState(!sealed, "Builder isalready sealed - further modifications are not allowed");
826         }
827
828         @SuppressWarnings("unchecked")
829         private T self() {
830             return (T) this;
831         }
832
833         public T id(final ShardIdentifier newId) {
834             checkSealed();
835             this.id = newId;
836             return self();
837         }
838
839         public T peerAddresses(final Map<String, String> newPeerAddresses) {
840             checkSealed();
841             this.peerAddresses = newPeerAddresses;
842             return self();
843         }
844
845         public T datastoreContext(final DatastoreContext newDatastoreContext) {
846             checkSealed();
847             this.datastoreContext = newDatastoreContext;
848             return self();
849         }
850
851         public T schemaContext(final SchemaContext newSchemaContext) {
852             checkSealed();
853             this.schemaContext = newSchemaContext;
854             return self();
855         }
856
857         public T restoreFromSnapshot(final DatastoreSnapshot.ShardSnapshot newRestoreFromSnapshot) {
858             checkSealed();
859             this.restoreFromSnapshot = newRestoreFromSnapshot;
860             return self();
861         }
862
863         public T dataTree(final TipProducingDataTree newDataTree) {
864             checkSealed();
865             this.dataTree = newDataTree;
866             return self();
867         }
868
869         public ShardIdentifier getId() {
870             return id;
871         }
872
873         public Map<String, String> getPeerAddresses() {
874             return peerAddresses;
875         }
876
877         public DatastoreContext getDatastoreContext() {
878             return datastoreContext;
879         }
880
881         public SchemaContext getSchemaContext() {
882             return schemaContext;
883         }
884
885         public DatastoreSnapshot.ShardSnapshot getRestoreFromSnapshot() {
886             return restoreFromSnapshot;
887         }
888
889         public TipProducingDataTree getDataTree() {
890             return dataTree;
891         }
892
893         public TreeType getTreeType() {
894             switch (datastoreContext.getLogicalStoreType()) {
895                 case CONFIGURATION:
896                     return TreeType.CONFIGURATION;
897                 case OPERATIONAL:
898                     return TreeType.OPERATIONAL;
899                 default:
900                     throw new IllegalStateException("Unhandled logical store type "
901                             + datastoreContext.getLogicalStoreType());
902             }
903         }
904
905         protected void verify() {
906             Preconditions.checkNotNull(id, "id should not be null");
907             Preconditions.checkNotNull(peerAddresses, "peerAddresses should not be null");
908             Preconditions.checkNotNull(datastoreContext, "dataStoreContext should not be null");
909             Preconditions.checkNotNull(schemaContext, "schemaContext should not be null");
910         }
911
912         public Props props() {
913             sealed = true;
914             verify();
915             return Props.create(shardClass, this);
916         }
917     }
918
919     public static class Builder extends AbstractBuilder<Builder, Shard> {
920         private Builder() {
921             super(Shard.class);
922         }
923     }
924
925     Ticker ticker() {
926         return Ticker.systemTicker();
927     }
928 }