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