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