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