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