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