BUG-8618: record LeaderFrontendState time
[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                 store.checkForExpiredTransactions(transactionCommitTimeout);
333                 commitCoordinator.checkForExpiredTransactions(transactionCommitTimeout, this);
334             } else if (message instanceof DatastoreContext) {
335                 onDatastoreContext((DatastoreContext)message);
336             } else if (message instanceof RegisterRoleChangeListener) {
337                 roleChangeNotifier.get().forward(message, context());
338             } else if (message instanceof FollowerInitialSyncUpStatus) {
339                 shardMBean.setFollowerInitialSyncStatus(((FollowerInitialSyncUpStatus) message).isInitialSyncDone());
340                 context().parent().tell(message, self());
341             } else if (GET_SHARD_MBEAN_MESSAGE.equals(message)) {
342                 sender().tell(getShardMBean(), self());
343             } else if (message instanceof GetShardDataTree) {
344                 sender().tell(store.getDataTree(), self());
345             } else if (message instanceof ServerRemoved) {
346                 context().parent().forward(message, context());
347             } else if (ShardTransactionMessageRetrySupport.TIMER_MESSAGE_CLASS.isInstance(message)) {
348                 messageRetrySupport.onTimerMessage(message);
349             } else if (message instanceof DataTreeCohortActorRegistry.CohortRegistryCommand) {
350                 store.processCohortRegistryCommand(getSender(),
351                         (DataTreeCohortActorRegistry.CohortRegistryCommand) message);
352             } else if (message instanceof PersistAbortTransactionPayload) {
353                 final TransactionIdentifier txId = ((PersistAbortTransactionPayload) message).getTransactionId();
354                 persistPayload(txId, AbortTransactionPayload.create(txId), true);
355             } else if (message instanceof MakeLeaderLocal) {
356                 onMakeLeaderLocal();
357             } else if (RESUME_NEXT_PENDING_TRANSACTION.equals(message)) {
358                 store.resumeNextPendingTransaction();
359             } else if (!responseMessageSlicer.handleMessage(message)) {
360                 super.handleNonRaftCommand(message);
361             }
362         }
363     }
364
365     @SuppressWarnings("checkstyle:IllegalCatch")
366     private void handleRequestEnvelope(final RequestEnvelope envelope) {
367         final long now = ticker().read();
368         try {
369             final RequestSuccess<?, ?> success = handleRequest(envelope, now);
370             if (success != null) {
371                 final long executionTimeNanos = ticker().read() - now;
372                 if (success instanceof SliceableMessage) {
373                     dispatchers.getDispatcher(DispatcherType.Serialization).execute(() ->
374                         responseMessageSlicer.slice(SliceOptions.builder().identifier(success.getTarget())
375                             .message(envelope.newSuccessEnvelope(success, executionTimeNanos))
376                             .sendTo(envelope.getMessage().getReplyTo()).replyTo(self())
377                             .onFailureCallback(t -> {
378                                 LOG.warn("Error slicing response {}", success, t);
379                             }).build()));
380                 } else {
381                     envelope.sendSuccess(success, executionTimeNanos);
382                 }
383             }
384         } catch (RequestException e) {
385             LOG.debug("{}: request {} failed", persistenceId(), envelope, e);
386             envelope.sendFailure(e, ticker().read() - now);
387         } catch (Exception e) {
388             LOG.debug("{}: request {} caused failure", persistenceId(), envelope, e);
389             envelope.sendFailure(new RuntimeRequestException("Request failed to process", e),
390                 ticker().read() - now);
391         }
392     }
393
394     private void onMakeLeaderLocal() {
395         LOG.debug("{}: onMakeLeaderLocal received", persistenceId());
396         if (isLeader()) {
397             getSender().tell(new Status.Success(null), getSelf());
398             return;
399         }
400
401         final ActorSelection leader = getLeader();
402
403         if (leader == null) {
404             // Leader is not present. The cluster is most likely trying to
405             // elect a leader and we should let that run its normal course
406
407             // TODO we can wait for the election to complete and retry the
408             // request. We can also let the caller retry by sending a flag
409             // in the response indicating the request is "reTryable".
410             getSender().tell(new Failure(
411                     new LeadershipTransferFailedException("We cannot initiate leadership transfer to local node. "
412                             + "Currently there is no leader for " + persistenceId())),
413                     getSelf());
414             return;
415         }
416
417         leader.tell(new RequestLeadership(getId(), getSender()), getSelf());
418     }
419
420     // Acquire our frontend tracking handle and verify generation matches
421     @Nullable
422     private LeaderFrontendState findFrontend(final ClientIdentifier clientId) throws RequestException {
423         final LeaderFrontendState existing = knownFrontends.get(clientId.getFrontendId());
424         if (existing != null) {
425             final int cmp = Long.compareUnsigned(existing.getIdentifier().getGeneration(), clientId.getGeneration());
426             if (cmp == 0) {
427                 existing.touch();
428                 return existing;
429             }
430             if (cmp > 0) {
431                 LOG.debug("{}: rejecting request from outdated client {}", persistenceId(), clientId);
432                 throw new RetiredGenerationException(existing.getIdentifier().getGeneration());
433             }
434
435             LOG.info("{}: retiring state {}, outdated by request from client {}", persistenceId(), existing, clientId);
436             existing.retire();
437             knownFrontends.remove(clientId.getFrontendId());
438         } else {
439             LOG.debug("{}: client {} is not yet known", persistenceId(), clientId);
440         }
441
442         return null;
443     }
444
445     private LeaderFrontendState getFrontend(final ClientIdentifier clientId) throws RequestException {
446         final LeaderFrontendState ret = findFrontend(clientId);
447         if (ret != null) {
448             return ret;
449         }
450
451         // TODO: a dedicated exception would be better, but this is technically true, too
452         throw new OutOfSequenceEnvelopeException(0);
453     }
454
455     private static @Nonnull ABIVersion selectVersion(final ConnectClientRequest message) {
456         final Range<ABIVersion> clientRange = Range.closed(message.getMinVersion(), message.getMaxVersion());
457         for (ABIVersion v : SUPPORTED_ABIVERSIONS) {
458             if (clientRange.contains(v)) {
459                 return v;
460             }
461         }
462
463         throw new IllegalArgumentException(String.format(
464             "No common version between backend versions %s and client versions %s", SUPPORTED_ABIVERSIONS,
465             clientRange));
466     }
467
468     @SuppressWarnings("checkstyle:IllegalCatch")
469     private void handleConnectClient(final ConnectClientRequest message) {
470         try {
471             final ClientIdentifier clientId = message.getTarget();
472             final LeaderFrontendState existing = findFrontend(clientId);
473             if (existing != null) {
474                 existing.touch();
475             }
476
477             if (!isLeader() || !isLeaderActive()) {
478                 LOG.info("{}: not currently leader, rejecting request {}. isLeader: {}, isLeaderActive: {},"
479                                 + "isLeadershipTransferInProgress: {}.",
480                         persistenceId(), message, isLeader(), isLeaderActive(), isLeadershipTransferInProgress());
481                 throw new NotLeaderException(getSelf());
482             }
483
484             final ABIVersion selectedVersion = selectVersion(message);
485             final LeaderFrontendState frontend;
486             if (existing == null) {
487                 frontend = new LeaderFrontendState(persistenceId(), clientId, store);
488                 knownFrontends.put(clientId.getFrontendId(), frontend);
489                 LOG.debug("{}: created state {} for client {}", persistenceId(), frontend, clientId);
490             } else {
491                 frontend = existing;
492             }
493
494             frontend.reconnect();
495             message.getReplyTo().tell(new ConnectClientSuccess(message.getTarget(), message.getSequence(), getSelf(),
496                 ImmutableList.of(), store.getDataTree(), CLIENT_MAX_MESSAGES).toVersion(selectedVersion),
497                 ActorRef.noSender());
498         } catch (RequestException | RuntimeException e) {
499             message.getReplyTo().tell(new Failure(e), ActorRef.noSender());
500         }
501     }
502
503     private @Nullable RequestSuccess<?, ?> handleRequest(final RequestEnvelope envelope, final long now)
504             throws RequestException {
505         // We are not the leader, hence we want to fail-fast.
506         if (!isLeader() || paused || !isLeaderActive()) {
507             LOG.debug("{}: not currently active leader, rejecting request {}. isLeader: {}, isLeaderActive: {},"
508                             + "isLeadershipTransferInProgress: {}, paused: {}",
509                     persistenceId(), envelope, isLeader(), isLeaderActive(), isLeadershipTransferInProgress(), paused);
510             throw new NotLeaderException(getSelf());
511         }
512
513         final Request<?, ?> request = envelope.getMessage();
514         if (request instanceof TransactionRequest) {
515             final TransactionRequest<?> txReq = (TransactionRequest<?>)request;
516             final ClientIdentifier clientId = txReq.getTarget().getHistoryId().getClientId();
517             return getFrontend(clientId).handleTransactionRequest(txReq, envelope, now);
518         } else if (request instanceof LocalHistoryRequest) {
519             final LocalHistoryRequest<?> lhReq = (LocalHistoryRequest<?>)request;
520             final ClientIdentifier clientId = lhReq.getTarget().getClientId();
521             return getFrontend(clientId).handleLocalHistoryRequest(lhReq, envelope, now);
522         } else {
523             LOG.warn("{}: rejecting unsupported request {}", persistenceId(), request);
524             throw new UnsupportedRequestException(request);
525         }
526     }
527
528     private boolean hasLeader() {
529         return getLeaderId() != null;
530     }
531
532     public int getPendingTxCommitQueueSize() {
533         return store.getQueueSize();
534     }
535
536     public int getCohortCacheSize() {
537         return commitCoordinator.getCohortCacheSize();
538     }
539
540     @Override
541     protected Optional<ActorRef> getRoleChangeNotifier() {
542         return roleChangeNotifier;
543     }
544
545     @Override
546     protected LeaderStateChanged newLeaderStateChanged(final String memberId, final String leaderId,
547             final short leaderPayloadVersion) {
548         return isLeader() ? new ShardLeaderStateChanged(memberId, leaderId, store.getDataTree(), leaderPayloadVersion)
549                 : new ShardLeaderStateChanged(memberId, leaderId, leaderPayloadVersion);
550     }
551
552     protected void onDatastoreContext(final DatastoreContext context) {
553         datastoreContext = context;
554
555         setTransactionCommitTimeout();
556
557         setPersistence(datastoreContext.isPersistent());
558
559         updateConfigParams(datastoreContext.getShardRaftConfig());
560     }
561
562     // applyState() will be invoked once consensus is reached on the payload
563     void persistPayload(final Identifier id, final Payload payload, final boolean batchHint) {
564         boolean canSkipPayload = !hasFollowers() && !persistence().isRecoveryApplicable();
565         if (canSkipPayload) {
566             applyState(self(), id, payload);
567         } else {
568             // We are faking the sender
569             persistData(self(), id, payload, batchHint);
570         }
571     }
572
573     private void handleCommitTransaction(final CommitTransaction commit) {
574         if (isLeader()) {
575             commitCoordinator.handleCommit(commit.getTransactionId(), getSender(), this);
576         } else {
577             ActorSelection leader = getLeader();
578             if (leader == null) {
579                 messageRetrySupport.addMessageToRetry(commit, getSender(),
580                         "Could not commit transaction " + commit.getTransactionId());
581             } else {
582                 LOG.debug("{}: Forwarding CommitTransaction to leader {}", persistenceId(), leader);
583                 leader.forward(commit, getContext());
584             }
585         }
586     }
587
588     private void handleCanCommitTransaction(final CanCommitTransaction canCommit) {
589         LOG.debug("{}: Can committing transaction {}", persistenceId(), canCommit.getTransactionId());
590
591         if (isLeader()) {
592             commitCoordinator.handleCanCommit(canCommit.getTransactionId(), getSender(), this);
593         } else {
594             ActorSelection leader = getLeader();
595             if (leader == null) {
596                 messageRetrySupport.addMessageToRetry(canCommit, getSender(),
597                         "Could not canCommit transaction " + canCommit.getTransactionId());
598             } else {
599                 LOG.debug("{}: Forwarding CanCommitTransaction to leader {}", persistenceId(), leader);
600                 leader.forward(canCommit, getContext());
601             }
602         }
603     }
604
605     @SuppressWarnings("checkstyle:IllegalCatch")
606     protected void handleBatchedModificationsLocal(final BatchedModifications batched, final ActorRef sender) {
607         try {
608             commitCoordinator.handleBatchedModifications(batched, sender, this);
609         } catch (Exception e) {
610             LOG.error("{}: Error handling BatchedModifications for Tx {}", persistenceId(),
611                     batched.getTransactionId(), e);
612             sender.tell(new Failure(e), getSelf());
613         }
614     }
615
616     private void handleBatchedModifications(final BatchedModifications batched) {
617         // This message is sent to prepare the modifications transaction directly on the Shard as an
618         // optimization to avoid the extra overhead of a separate ShardTransaction actor. On the last
619         // BatchedModifications message, the caller sets the ready flag in the message indicating
620         // modifications are complete. The reply contains the cohort actor path (this actor) for the caller
621         // to initiate the 3-phase commit. This also avoids the overhead of sending an additional
622         // ReadyTransaction message.
623
624         // If we're not the leader then forward to the leader. This is a safety measure - we shouldn't
625         // normally get here if we're not the leader as the front-end (TransactionProxy) should determine
626         // the primary/leader shard. However with timing and caching on the front-end, there's a small
627         // window where it could have a stale leader during leadership transitions.
628         //
629         boolean isLeaderActive = isLeaderActive();
630         if (isLeader() && isLeaderActive) {
631             handleBatchedModificationsLocal(batched, getSender());
632         } else {
633             ActorSelection leader = getLeader();
634             if (!isLeaderActive || leader == null) {
635                 messageRetrySupport.addMessageToRetry(batched, getSender(),
636                         "Could not commit transaction " + batched.getTransactionId());
637             } else {
638                 // If this is not the first batch and leadership changed in between batched messages,
639                 // we need to reconstruct previous BatchedModifications from the transaction
640                 // DataTreeModification, honoring the max batched modification count, and forward all the
641                 // previous BatchedModifications to the new leader.
642                 Collection<BatchedModifications> newModifications = commitCoordinator
643                         .createForwardedBatchedModifications(batched,
644                                 datastoreContext.getShardBatchedModificationCount());
645
646                 LOG.debug("{}: Forwarding {} BatchedModifications to leader {}", persistenceId(),
647                         newModifications.size(), leader);
648
649                 for (BatchedModifications bm : newModifications) {
650                     leader.forward(bm, getContext());
651                 }
652             }
653         }
654     }
655
656     private boolean failIfIsolatedLeader(final ActorRef sender) {
657         if (isIsolatedLeader()) {
658             sender.tell(new Failure(new NoShardLeaderException(String.format(
659                     "Shard %s was the leader but has lost contact with all of its followers. Either all"
660                     + " other follower nodes are down or this node is isolated by a network partition.",
661                     persistenceId()))), getSelf());
662             return true;
663         }
664
665         return false;
666     }
667
668     protected boolean isIsolatedLeader() {
669         return getRaftState() == RaftState.IsolatedLeader;
670     }
671
672     @SuppressWarnings("checkstyle:IllegalCatch")
673     private void handleReadyLocalTransaction(final ReadyLocalTransaction message) {
674         LOG.debug("{}: handleReadyLocalTransaction for {}", persistenceId(), message.getTransactionId());
675
676         boolean isLeaderActive = isLeaderActive();
677         if (isLeader() && isLeaderActive) {
678             try {
679                 commitCoordinator.handleReadyLocalTransaction(message, getSender(), this);
680             } catch (Exception e) {
681                 LOG.error("{}: Error handling ReadyLocalTransaction for Tx {}", persistenceId(),
682                         message.getTransactionId(), e);
683                 getSender().tell(new Failure(e), getSelf());
684             }
685         } else {
686             ActorSelection leader = getLeader();
687             if (!isLeaderActive || leader == null) {
688                 messageRetrySupport.addMessageToRetry(message, getSender(),
689                         "Could not commit transaction " + message.getTransactionId());
690             } else {
691                 LOG.debug("{}: Forwarding ReadyLocalTransaction to leader {}", persistenceId(), leader);
692                 message.setRemoteVersion(getCurrentBehavior().getLeaderPayloadVersion());
693                 leader.forward(message, getContext());
694             }
695         }
696     }
697
698     private void handleForwardedReadyTransaction(final ForwardedReadyTransaction forwardedReady) {
699         LOG.debug("{}: handleForwardedReadyTransaction for {}", persistenceId(), forwardedReady.getTransactionId());
700
701         boolean isLeaderActive = isLeaderActive();
702         if (isLeader() && isLeaderActive) {
703             commitCoordinator.handleForwardedReadyTransaction(forwardedReady, getSender(), this);
704         } else {
705             ActorSelection leader = getLeader();
706             if (!isLeaderActive || leader == null) {
707                 messageRetrySupport.addMessageToRetry(forwardedReady, getSender(),
708                         "Could not commit transaction " + forwardedReady.getTransactionId());
709             } else {
710                 LOG.debug("{}: Forwarding ForwardedReadyTransaction to leader {}", persistenceId(), leader);
711
712                 ReadyLocalTransaction readyLocal = new ReadyLocalTransaction(forwardedReady.getTransactionId(),
713                         forwardedReady.getTransaction().getSnapshot(), forwardedReady.isDoImmediateCommit());
714                 readyLocal.setRemoteVersion(getCurrentBehavior().getLeaderPayloadVersion());
715                 leader.forward(readyLocal, getContext());
716             }
717         }
718     }
719
720     private void handleAbortTransaction(final AbortTransaction abort) {
721         doAbortTransaction(abort.getTransactionId(), getSender());
722     }
723
724     void doAbortTransaction(final Identifier transactionID, final ActorRef sender) {
725         commitCoordinator.handleAbort(transactionID, sender, this);
726     }
727
728     private void handleCreateTransaction(final Object message) {
729         if (isLeader()) {
730             createTransaction(CreateTransaction.fromSerializable(message));
731         } else if (getLeader() != null) {
732             getLeader().forward(message, getContext());
733         } else {
734             getSender().tell(new Failure(new NoShardLeaderException(
735                     "Could not create a shard transaction", persistenceId())), getSelf());
736         }
737     }
738
739     private void closeTransactionChain(final CloseTransactionChain closeTransactionChain) {
740         final LocalHistoryIdentifier id = closeTransactionChain.getIdentifier();
741         store.closeTransactionChain(id, null);
742         store.purgeTransactionChain(id, null);
743     }
744
745     @SuppressWarnings("checkstyle:IllegalCatch")
746     private void createTransaction(final CreateTransaction createTransaction) {
747         try {
748             if (TransactionType.fromInt(createTransaction.getTransactionType()) != TransactionType.READ_ONLY
749                     && failIfIsolatedLeader(getSender())) {
750                 return;
751             }
752
753             ActorRef transactionActor = createTransaction(createTransaction.getTransactionType(),
754                 createTransaction.getTransactionId());
755
756             getSender().tell(new CreateTransactionReply(Serialization.serializedActorPath(transactionActor),
757                     createTransaction.getTransactionId(), createTransaction.getVersion()).toSerializable(), getSelf());
758         } catch (Exception e) {
759             getSender().tell(new Failure(e), getSelf());
760         }
761     }
762
763     private ActorRef createTransaction(final int transactionType, final TransactionIdentifier transactionId) {
764         LOG.debug("{}: Creating transaction : {} ", persistenceId(), transactionId);
765         return transactionActorFactory.newShardTransaction(TransactionType.fromInt(transactionType),
766             transactionId);
767     }
768
769     private void updateSchemaContext(final UpdateSchemaContext message) {
770         updateSchemaContext(message.getSchemaContext());
771     }
772
773     @VisibleForTesting
774     void updateSchemaContext(final SchemaContext schemaContext) {
775         store.updateSchemaContext(schemaContext);
776     }
777
778     private boolean isMetricsCaptureEnabled() {
779         CommonConfig config = new CommonConfig(getContext().system().settings().config());
780         return config.isMetricCaptureEnabled();
781     }
782
783     @Override
784     @VisibleForTesting
785     public RaftActorSnapshotCohort getRaftActorSnapshotCohort() {
786         return snapshotCohort;
787     }
788
789     @Override
790     @Nonnull
791     protected RaftActorRecoveryCohort getRaftActorRecoveryCohort() {
792         return new ShardRecoveryCoordinator(store,
793             restoreFromSnapshot != null ? restoreFromSnapshot.getSnapshot() : null, persistenceId(), LOG);
794     }
795
796     @Override
797     protected void onRecoveryComplete() {
798         restoreFromSnapshot = null;
799
800         //notify shard manager
801         getContext().parent().tell(new ActorInitialized(), getSelf());
802
803         // Being paranoid here - this method should only be called once but just in case...
804         if (txCommitTimeoutCheckSchedule == null) {
805             // Schedule a message to be periodically sent to check if the current in-progress
806             // transaction should be expired and aborted.
807             FiniteDuration period = Duration.create(transactionCommitTimeout / 3, TimeUnit.MILLISECONDS);
808             txCommitTimeoutCheckSchedule = getContext().system().scheduler().schedule(
809                     period, period, getSelf(),
810                     TX_COMMIT_TIMEOUT_CHECK_MESSAGE, getContext().dispatcher(), ActorRef.noSender());
811         }
812     }
813
814     @Override
815     protected void applyState(final ActorRef clientActor, final Identifier identifier, final Object data) {
816         if (data instanceof Payload) {
817             try {
818                 store.applyReplicatedPayload(identifier, (Payload)data);
819             } catch (DataValidationFailedException | IOException e) {
820                 LOG.error("{}: Error applying replica {}", persistenceId(), identifier, e);
821             }
822         } else {
823             LOG.error("{}: Unknown state for {} received {}", persistenceId(), identifier, data);
824         }
825     }
826
827     @Override
828     protected void onStateChanged() {
829         boolean isLeader = isLeader();
830         boolean hasLeader = hasLeader();
831         changeSupport.onLeadershipChange(isLeader, hasLeader);
832         treeChangeSupport.onLeadershipChange(isLeader, hasLeader);
833
834         // If this actor is no longer the leader close all the transaction chains
835         if (!isLeader) {
836             if (LOG.isDebugEnabled()) {
837                 LOG.debug(
838                     "{}: onStateChanged: Closing all transaction chains because shard {} is no longer the leader",
839                     persistenceId(), getId());
840             }
841
842             paused = false;
843             store.purgeLeaderState();
844         }
845
846         if (hasLeader && !isIsolatedLeader()) {
847             messageRetrySupport.retryMessages();
848         }
849     }
850
851     @Override
852     protected void onLeaderChanged(final String oldLeader, final String newLeader) {
853         shardMBean.incrementLeadershipChangeCount();
854         paused = false;
855
856         if (!isLeader()) {
857             if (!knownFrontends.isEmpty()) {
858                 LOG.debug("{}: removing frontend state for {}", persistenceId(), knownFrontends.keySet());
859                 knownFrontends = ImmutableMap.of();
860             }
861
862             if (!hasLeader()) {
863                 // No leader anywhere, nothing else to do
864                 return;
865             }
866
867             // Another leader was elected. If we were the previous leader and had pending transactions, convert
868             // them to transaction messages and send to the new leader.
869             ActorSelection leader = getLeader();
870             if (leader != null) {
871                 Collection<?> messagesToForward = convertPendingTransactionsToMessages();
872
873                 if (!messagesToForward.isEmpty()) {
874                     LOG.debug("{}: Forwarding {} pending transaction messages to leader {}", persistenceId(),
875                             messagesToForward.size(), leader);
876
877                     for (Object message : messagesToForward) {
878                         leader.tell(message, self());
879                     }
880                 }
881             } else {
882                 commitCoordinator.abortPendingTransactions("The transacton was aborted due to inflight leadership "
883                         + "change and the leader address isn't available.", this);
884             }
885         } else {
886             // We have become the leader, we need to reconstruct frontend state
887             knownFrontends = Verify.verifyNotNull(frontendMetadata.toLeaderState(this));
888             LOG.debug("{}: became leader with frontend state for {}", persistenceId(), knownFrontends.keySet());
889         }
890
891         if (!isIsolatedLeader()) {
892             messageRetrySupport.retryMessages();
893         }
894     }
895
896     /**
897      * Clears all pending transactions and converts them to messages to be forwarded to a new leader.
898      *
899      * @return the converted messages
900      */
901     public Collection<?> convertPendingTransactionsToMessages() {
902         return commitCoordinator.convertPendingTransactionsToMessages(
903                 datastoreContext.getShardBatchedModificationCount());
904     }
905
906     @Override
907     protected void pauseLeader(final Runnable operation) {
908         LOG.debug("{}: In pauseLeader, operation: {}", persistenceId(), operation);
909         paused = true;
910
911         // Tell-based protocol can replay transaction state, so it is safe to blow it up when we are paused.
912         knownFrontends.values().forEach(LeaderFrontendState::retire);
913         knownFrontends = ImmutableMap.of();
914
915         store.setRunOnPendingTransactionsComplete(operation);
916     }
917
918     @Override
919     protected void unpauseLeader() {
920         LOG.debug("{}: In unpauseLeader", persistenceId());
921         paused = false;
922
923         store.setRunOnPendingTransactionsComplete(null);
924
925         // Restore tell-based protocol state as if we were becoming the leader
926         knownFrontends = Verify.verifyNotNull(frontendMetadata.toLeaderState(this));
927     }
928
929     @Override
930     protected OnDemandRaftState.AbstractBuilder<?> newOnDemandRaftStateBuilder() {
931         return OnDemandShardState.newBuilder().treeChangeListenerActors(treeChangeSupport.getListenerActors())
932                 .dataChangeListenerActors(changeSupport.getListenerActors())
933                 .commitCohortActors(store.getCohortActors());
934     }
935
936     @Override
937     public String persistenceId() {
938         return this.name;
939     }
940
941     @VisibleForTesting
942     ShardCommitCoordinator getCommitCoordinator() {
943         return commitCoordinator;
944     }
945
946     public DatastoreContext getDatastoreContext() {
947         return datastoreContext;
948     }
949
950     @VisibleForTesting
951     public ShardDataTree getDataStore() {
952         return store;
953     }
954
955     @VisibleForTesting
956     ShardStats getShardMBean() {
957         return shardMBean;
958     }
959
960     public static Builder builder() {
961         return new Builder();
962     }
963
964     public abstract static class AbstractBuilder<T extends AbstractBuilder<T, S>, S extends Shard> {
965         private final Class<S> shardClass;
966         private ShardIdentifier id;
967         private Map<String, String> peerAddresses = Collections.emptyMap();
968         private DatastoreContext datastoreContext;
969         private SchemaContextProvider schemaContextProvider;
970         private DatastoreSnapshot.ShardSnapshot restoreFromSnapshot;
971         private TipProducingDataTree dataTree;
972         private volatile boolean sealed;
973
974         protected AbstractBuilder(final Class<S> shardClass) {
975             this.shardClass = shardClass;
976         }
977
978         protected void checkSealed() {
979             Preconditions.checkState(!sealed, "Builder isalready sealed - further modifications are not allowed");
980         }
981
982         @SuppressWarnings("unchecked")
983         private T self() {
984             return (T) this;
985         }
986
987         public T id(final ShardIdentifier newId) {
988             checkSealed();
989             this.id = newId;
990             return self();
991         }
992
993         public T peerAddresses(final Map<String, String> newPeerAddresses) {
994             checkSealed();
995             this.peerAddresses = newPeerAddresses;
996             return self();
997         }
998
999         public T datastoreContext(final DatastoreContext newDatastoreContext) {
1000             checkSealed();
1001             this.datastoreContext = newDatastoreContext;
1002             return self();
1003         }
1004
1005         public T schemaContextProvider(final SchemaContextProvider schemaContextProvider) {
1006             checkSealed();
1007             this.schemaContextProvider = Preconditions.checkNotNull(schemaContextProvider);
1008             return self();
1009         }
1010
1011         public T restoreFromSnapshot(final DatastoreSnapshot.ShardSnapshot newRestoreFromSnapshot) {
1012             checkSealed();
1013             this.restoreFromSnapshot = newRestoreFromSnapshot;
1014             return self();
1015         }
1016
1017         public T dataTree(final TipProducingDataTree newDataTree) {
1018             checkSealed();
1019             this.dataTree = newDataTree;
1020             return self();
1021         }
1022
1023         public ShardIdentifier getId() {
1024             return id;
1025         }
1026
1027         public Map<String, String> getPeerAddresses() {
1028             return peerAddresses;
1029         }
1030
1031         public DatastoreContext getDatastoreContext() {
1032             return datastoreContext;
1033         }
1034
1035         public SchemaContext getSchemaContext() {
1036             return Verify.verifyNotNull(schemaContextProvider.getSchemaContext());
1037         }
1038
1039         public DatastoreSnapshot.ShardSnapshot getRestoreFromSnapshot() {
1040             return restoreFromSnapshot;
1041         }
1042
1043         public TipProducingDataTree getDataTree() {
1044             return dataTree;
1045         }
1046
1047         public TreeType getTreeType() {
1048             switch (datastoreContext.getLogicalStoreType()) {
1049                 case CONFIGURATION:
1050                     return TreeType.CONFIGURATION;
1051                 case OPERATIONAL:
1052                     return TreeType.OPERATIONAL;
1053                 default:
1054                     throw new IllegalStateException("Unhandled logical store type "
1055                             + datastoreContext.getLogicalStoreType());
1056             }
1057         }
1058
1059         protected void verify() {
1060             Preconditions.checkNotNull(id, "id should not be null");
1061             Preconditions.checkNotNull(peerAddresses, "peerAddresses should not be null");
1062             Preconditions.checkNotNull(datastoreContext, "dataStoreContext should not be null");
1063             Preconditions.checkNotNull(schemaContextProvider, "schemaContextProvider should not be null");
1064         }
1065
1066         public Props props() {
1067             sealed = true;
1068             verify();
1069             return Props.create(shardClass, this);
1070         }
1071     }
1072
1073     public static class Builder extends AbstractBuilder<Builder, Shard> {
1074         private Builder() {
1075             super(Shard.class);
1076         }
1077     }
1078
1079     Ticker ticker() {
1080         return Ticker.systemTicker();
1081     }
1082
1083     void scheduleNextPendingTransaction() {
1084         self().tell(RESUME_NEXT_PENDING_TRANSACTION, ActorRef.noSender());
1085     }
1086 }