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