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