c6f05ca70e7e857c1d0b84d0d095cbcf368e71e6
[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.serialization.Serialization;
16 import com.google.common.annotations.VisibleForTesting;
17 import com.google.common.base.Optional;
18 import com.google.common.base.Preconditions;
19 import com.google.common.base.Ticker;
20 import java.io.IOException;
21 import java.util.Collection;
22 import java.util.Collections;
23 import java.util.Map;
24 import java.util.concurrent.TimeUnit;
25 import javax.annotation.Nonnull;
26 import org.opendaylight.controller.cluster.access.concepts.TransactionIdentifier;
27 import org.opendaylight.controller.cluster.common.actor.CommonConfig;
28 import org.opendaylight.controller.cluster.common.actor.MessageTracker;
29 import org.opendaylight.controller.cluster.common.actor.MessageTracker.Error;
30 import org.opendaylight.controller.cluster.common.actor.MeteringBehavior;
31 import org.opendaylight.controller.cluster.datastore.exceptions.NoShardLeaderException;
32 import org.opendaylight.controller.cluster.datastore.identifiers.ShardIdentifier;
33 import org.opendaylight.controller.cluster.datastore.jmx.mbeans.shard.ShardMBeanFactory;
34 import org.opendaylight.controller.cluster.datastore.jmx.mbeans.shard.ShardStats;
35 import org.opendaylight.controller.cluster.datastore.messages.AbortTransaction;
36 import org.opendaylight.controller.cluster.datastore.messages.ActorInitialized;
37 import org.opendaylight.controller.cluster.datastore.messages.BatchedModifications;
38 import org.opendaylight.controller.cluster.datastore.messages.CanCommitTransaction;
39 import org.opendaylight.controller.cluster.datastore.messages.CloseTransactionChain;
40 import org.opendaylight.controller.cluster.datastore.messages.CommitTransaction;
41 import org.opendaylight.controller.cluster.datastore.messages.CreateTransaction;
42 import org.opendaylight.controller.cluster.datastore.messages.CreateTransactionReply;
43 import org.opendaylight.controller.cluster.datastore.messages.DatastoreSnapshot;
44 import org.opendaylight.controller.cluster.datastore.messages.DatastoreSnapshot.ShardSnapshot;
45 import org.opendaylight.controller.cluster.datastore.messages.ForwardedReadyTransaction;
46 import org.opendaylight.controller.cluster.datastore.messages.GetShardDataTree;
47 import org.opendaylight.controller.cluster.datastore.messages.OnDemandShardState;
48 import org.opendaylight.controller.cluster.datastore.messages.PeerAddressResolved;
49 import org.opendaylight.controller.cluster.datastore.messages.ReadyLocalTransaction;
50 import org.opendaylight.controller.cluster.datastore.messages.RegisterChangeListener;
51 import org.opendaylight.controller.cluster.datastore.messages.RegisterDataTreeChangeListener;
52 import org.opendaylight.controller.cluster.datastore.messages.ShardLeaderStateChanged;
53 import org.opendaylight.controller.cluster.datastore.messages.UpdateSchemaContext;
54 import org.opendaylight.controller.cluster.datastore.utils.Dispatchers;
55 import org.opendaylight.controller.cluster.notifications.LeaderStateChanged;
56 import org.opendaylight.controller.cluster.notifications.RegisterRoleChangeListener;
57 import org.opendaylight.controller.cluster.notifications.RoleChangeNotifier;
58 import org.opendaylight.controller.cluster.raft.RaftActor;
59 import org.opendaylight.controller.cluster.raft.RaftActorRecoveryCohort;
60 import org.opendaylight.controller.cluster.raft.RaftActorSnapshotCohort;
61 import org.opendaylight.controller.cluster.raft.RaftState;
62 import org.opendaylight.controller.cluster.raft.base.messages.FollowerInitialSyncUpStatus;
63 import org.opendaylight.controller.cluster.raft.client.messages.OnDemandRaftState;
64 import org.opendaylight.controller.cluster.raft.messages.AppendEntriesReply;
65 import org.opendaylight.controller.cluster.raft.messages.ServerRemoved;
66 import org.opendaylight.controller.cluster.raft.protobuff.client.messages.Payload;
67 import org.opendaylight.yangtools.concepts.Identifier;
68 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataValidationFailedException;
69 import org.opendaylight.yangtools.yang.data.api.schema.tree.TipProducingDataTree;
70 import org.opendaylight.yangtools.yang.data.api.schema.tree.TreeType;
71 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
72 import scala.concurrent.duration.Duration;
73 import scala.concurrent.duration.FiniteDuration;
74
75 /**
76  * A Shard represents a portion of the logical data tree <br/>
77  * <p>
78  * Our Shard uses InMemoryDataTree as it's internal representation and delegates all requests it
79  * </p>
80  */
81 public class Shard extends RaftActor {
82
83     @VisibleForTesting
84     static final Object TX_COMMIT_TIMEOUT_CHECK_MESSAGE = new Object() {
85         @Override
86         public String toString() {
87             return "txCommitTimeoutCheck";
88         }
89     };
90
91     @VisibleForTesting
92     static final Object GET_SHARD_MBEAN_MESSAGE = new Object() {
93         @Override
94         public String toString() {
95             return "getShardMBeanMessage";
96         }
97     };
98
99     // FIXME: shard names should be encapsulated in their own class and this should be exposed as a constant.
100     public static final String DEFAULT_NAME = "default";
101
102     // The state of this Shard
103     private final ShardDataTree store;
104
105     /// The name of this shard
106     private final String name;
107
108     private final ShardStats shardMBean;
109
110     private DatastoreContext datastoreContext;
111
112     private final ShardCommitCoordinator commitCoordinator;
113
114     private long transactionCommitTimeout;
115
116     private Cancellable txCommitTimeoutCheckSchedule;
117
118     private final Optional<ActorRef> roleChangeNotifier;
119
120     private final MessageTracker appendEntriesReplyTracker;
121
122     private final ShardTransactionActorFactory transactionActorFactory;
123
124     private final ShardSnapshotCohort snapshotCohort;
125
126     private final DataTreeChangeListenerSupport treeChangeSupport = new DataTreeChangeListenerSupport(this);
127     private final DataChangeListenerSupport changeSupport = new DataChangeListenerSupport(this);
128
129
130     private ShardSnapshot restoreFromSnapshot;
131
132     private final ShardTransactionMessageRetrySupport messageRetrySupport;
133
134     private final FrontendMetadata frontendMetadata = new FrontendMetadata();
135
136     protected Shard(final AbstractBuilder<?, ?> builder) {
137         super(builder.getId().toString(), builder.getPeerAddresses(),
138                 Optional.of(builder.getDatastoreContext().getShardRaftConfig()), DataStoreVersions.CURRENT_VERSION);
139
140         this.name = builder.getId().toString();
141         this.datastoreContext = builder.getDatastoreContext();
142         this.restoreFromSnapshot = builder.getRestoreFromSnapshot();
143
144         setPersistence(datastoreContext.isPersistent());
145
146         LOG.info("Shard created : {}, persistent : {}", name, datastoreContext.isPersistent());
147
148         ShardDataTreeChangeListenerPublisherActorProxy treeChangeListenerPublisher =
149                 new ShardDataTreeChangeListenerPublisherActorProxy(getContext(), name + "-DTCL-publisher");
150         ShardDataChangeListenerPublisherActorProxy dataChangeListenerPublisher =
151                 new ShardDataChangeListenerPublisherActorProxy(getContext(), name + "-DCL-publisher");
152         if(builder.getDataTree() != null) {
153             store = new ShardDataTree(this, builder.getSchemaContext(), builder.getDataTree(),
154                     treeChangeListenerPublisher, dataChangeListenerPublisher, name);
155         } else {
156             store = new ShardDataTree(this, builder.getSchemaContext(), builder.getTreeType(),
157                     treeChangeListenerPublisher, dataChangeListenerPublisher, name);
158         }
159
160         shardMBean = ShardMBeanFactory.getShardStatsMBean(name.toString(),
161                 datastoreContext.getDataStoreMXBeanType());
162         shardMBean.setShard(this);
163
164         if (isMetricsCaptureEnabled()) {
165             getContext().become(new MeteringBehavior(this));
166         }
167
168         commitCoordinator = new ShardCommitCoordinator(store, LOG, this.name);
169
170         setTransactionCommitTimeout();
171
172         // create a notifier actor for each cluster member
173         roleChangeNotifier = createRoleChangeNotifier(name.toString());
174
175         appendEntriesReplyTracker = new MessageTracker(AppendEntriesReply.class,
176                 getRaftActorContext().getConfigParams().getIsolatedCheckIntervalInMillis());
177
178         transactionActorFactory = new ShardTransactionActorFactory(store, datastoreContext,
179                 new Dispatchers(context().system().dispatchers()).getDispatcherPath(
180                         Dispatchers.DispatcherType.Transaction), self(), getContext(), shardMBean);
181
182         snapshotCohort = ShardSnapshotCohort.create(getContext(), builder.getId().getMemberName(), store, LOG,
183             this.name);
184
185         messageRetrySupport = new ShardTransactionMessageRetrySupport(this);
186     }
187
188     private void setTransactionCommitTimeout() {
189         transactionCommitTimeout = TimeUnit.MILLISECONDS.convert(
190                 datastoreContext.getShardTransactionCommitTimeoutInSeconds(), TimeUnit.SECONDS) / 2;
191     }
192
193     private Optional<ActorRef> createRoleChangeNotifier(final String shardId) {
194         ActorRef shardRoleChangeNotifier = this.getContext().actorOf(
195             RoleChangeNotifier.getProps(shardId), shardId + "-notifier");
196         return Optional.of(shardRoleChangeNotifier);
197     }
198
199     @Override
200     public void postStop() {
201         LOG.info("Stopping Shard {}", persistenceId());
202
203         super.postStop();
204
205         messageRetrySupport.close();
206
207         if (txCommitTimeoutCheckSchedule != null) {
208             txCommitTimeoutCheckSchedule.cancel();
209         }
210
211         commitCoordinator.abortPendingTransactions("Transaction aborted due to shutdown.", this);
212
213         shardMBean.unregisterMBean();
214     }
215
216     @Override
217     protected void handleRecover(final Object message) {
218         LOG.debug("{}: onReceiveRecover: Received message {} from {}", persistenceId(), message.getClass(),
219             getSender());
220
221         super.handleRecover(message);
222         if (LOG.isTraceEnabled()) {
223             appendEntriesReplyTracker.begin();
224         }
225     }
226
227     @Override
228     protected void handleNonRaftCommand(final Object message) {
229         try (final MessageTracker.Context context = appendEntriesReplyTracker.received(message)) {
230             final Optional<Error> maybeError = context.error();
231             if (maybeError.isPresent()) {
232                 LOG.trace("{} : AppendEntriesReply failed to arrive at the expected interval {}", persistenceId(),
233                     maybeError.get());
234             }
235
236             if (CreateTransaction.isSerializedType(message)) {
237                 handleCreateTransaction(message);
238             } else if (message instanceof BatchedModifications) {
239                 handleBatchedModifications((BatchedModifications)message);
240             } else if (message instanceof ForwardedReadyTransaction) {
241                 handleForwardedReadyTransaction((ForwardedReadyTransaction) message);
242             } else if (message instanceof ReadyLocalTransaction) {
243                 handleReadyLocalTransaction((ReadyLocalTransaction)message);
244             } else if (CanCommitTransaction.isSerializedType(message)) {
245                 handleCanCommitTransaction(CanCommitTransaction.fromSerializable(message));
246             } else if (CommitTransaction.isSerializedType(message)) {
247                 handleCommitTransaction(CommitTransaction.fromSerializable(message));
248             } else if (AbortTransaction.isSerializedType(message)) {
249                 handleAbortTransaction(AbortTransaction.fromSerializable(message));
250             } else if (CloseTransactionChain.isSerializedType(message)) {
251                 closeTransactionChain(CloseTransactionChain.fromSerializable(message));
252             } else if (message instanceof RegisterChangeListener) {
253                 changeSupport.onMessage((RegisterChangeListener) message, isLeader(), hasLeader());
254             } else if (message instanceof RegisterDataTreeChangeListener) {
255                 treeChangeSupport.onMessage((RegisterDataTreeChangeListener) message, isLeader(), hasLeader());
256             } else if (message instanceof UpdateSchemaContext) {
257                 updateSchemaContext((UpdateSchemaContext) message);
258             } else if (message instanceof PeerAddressResolved) {
259                 PeerAddressResolved resolved = (PeerAddressResolved) message;
260                 setPeerAddress(resolved.getPeerId().toString(),
261                         resolved.getPeerAddress());
262             } else if (TX_COMMIT_TIMEOUT_CHECK_MESSAGE.equals(message)) {
263                 store.checkForExpiredTransactions(transactionCommitTimeout);
264                 commitCoordinator.checkForExpiredTransactions(transactionCommitTimeout, this);
265             } else if (message instanceof DatastoreContext) {
266                 onDatastoreContext((DatastoreContext)message);
267             } else if (message instanceof RegisterRoleChangeListener){
268                 roleChangeNotifier.get().forward(message, context());
269             } else if (message instanceof FollowerInitialSyncUpStatus) {
270                 shardMBean.setFollowerInitialSyncStatus(((FollowerInitialSyncUpStatus) message).isInitialSyncDone());
271                 context().parent().tell(message, self());
272             } else if (GET_SHARD_MBEAN_MESSAGE.equals(message)){
273                 sender().tell(getShardMBean(), self());
274             } else if (message instanceof GetShardDataTree) {
275                 sender().tell(store.getDataTree(), self());
276             } else if (message instanceof ServerRemoved){
277                 context().parent().forward(message, context());
278             } else if (ShardTransactionMessageRetrySupport.TIMER_MESSAGE_CLASS.isInstance(message)) {
279                 messageRetrySupport.onTimerMessage(message);
280             } else if (message instanceof DataTreeCohortActorRegistry.CohortRegistryCommand) {
281                 store.processCohortRegistryCommand(getSender(),
282                         (DataTreeCohortActorRegistry.CohortRegistryCommand) message);
283             } else {
284                 super.handleNonRaftCommand(message);
285             }
286         }
287     }
288
289     private boolean hasLeader() {
290         return getLeaderId() != null;
291     }
292
293     public int getPendingTxCommitQueueSize() {
294         return store.getQueueSize();
295     }
296
297     public int getCohortCacheSize() {
298         return commitCoordinator.getCohortCacheSize();
299     }
300
301     @Override
302     protected Optional<ActorRef> getRoleChangeNotifier() {
303         return roleChangeNotifier;
304     }
305
306     @Override
307     protected LeaderStateChanged newLeaderStateChanged(final String memberId, final String leaderId, final short leaderPayloadVersion) {
308         return isLeader() ? new ShardLeaderStateChanged(memberId, leaderId, store.getDataTree(), leaderPayloadVersion)
309                 : new ShardLeaderStateChanged(memberId, leaderId, leaderPayloadVersion);
310     }
311
312     protected void onDatastoreContext(final DatastoreContext context) {
313         datastoreContext = context;
314
315         setTransactionCommitTimeout();
316
317         setPersistence(datastoreContext.isPersistent());
318
319         updateConfigParams(datastoreContext.getShardRaftConfig());
320     }
321
322     boolean canSkipPayload() {
323         // If we do not have any followers and we are not using persistence we can apply modification to the state
324         // immediately
325         return !hasFollowers() && !persistence().isRecoveryApplicable();
326     }
327
328     // applyState() will be invoked once consensus is reached on the payload
329     void persistPayload(final TransactionIdentifier transactionId, final Payload payload) {
330         // We are faking the sender
331         persistData(self(), transactionId, payload);
332     }
333
334     private void handleCommitTransaction(final CommitTransaction commit) {
335         if (isLeader()) {
336             commitCoordinator.handleCommit(commit.getTransactionID(), getSender(), this);
337         } else {
338             ActorSelection leader = getLeader();
339             if (leader == null) {
340                 messageRetrySupport.addMessageToRetry(commit, getSender(),
341                         "Could not commit transaction " + commit.getTransactionID());
342             } else {
343                 LOG.debug("{}: Forwarding CommitTransaction to leader {}", persistenceId(), leader);
344                 leader.forward(commit, getContext());
345             }
346         }
347     }
348
349     private void handleCanCommitTransaction(final CanCommitTransaction canCommit) {
350         LOG.debug("{}: Can committing transaction {}", persistenceId(), canCommit.getTransactionID());
351
352         if (isLeader()) {
353         commitCoordinator.handleCanCommit(canCommit.getTransactionID(), getSender(), this);
354         } else {
355             ActorSelection leader = getLeader();
356             if (leader == null) {
357                 messageRetrySupport.addMessageToRetry(canCommit, getSender(),
358                         "Could not canCommit transaction " + canCommit.getTransactionID());
359             } else {
360                 LOG.debug("{}: Forwarding CanCommitTransaction to leader {}", persistenceId(), leader);
361                 leader.forward(canCommit, getContext());
362             }
363         }
364     }
365
366     protected void handleBatchedModificationsLocal(final BatchedModifications batched, final ActorRef sender) {
367         try {
368             commitCoordinator.handleBatchedModifications(batched, sender, this);
369         } catch (Exception e) {
370             LOG.error("{}: Error handling BatchedModifications for Tx {}", persistenceId(),
371                     batched.getTransactionID(), e);
372             sender.tell(new akka.actor.Status.Failure(e), getSelf());
373         }
374     }
375
376     private void handleBatchedModifications(final BatchedModifications batched) {
377         // This message is sent to prepare the modifications transaction directly on the Shard as an
378         // optimization to avoid the extra overhead of a separate ShardTransaction actor. On the last
379         // BatchedModifications message, the caller sets the ready flag in the message indicating
380         // modifications are complete. The reply contains the cohort actor path (this actor) for the caller
381         // to initiate the 3-phase commit. This also avoids the overhead of sending an additional
382         // ReadyTransaction message.
383
384         // If we're not the leader then forward to the leader. This is a safety measure - we shouldn't
385         // normally get here if we're not the leader as the front-end (TransactionProxy) should determine
386         // the primary/leader shard. However with timing and caching on the front-end, there's a small
387         // window where it could have a stale leader during leadership transitions.
388         //
389         boolean isLeaderActive = isLeaderActive();
390         if (isLeader() && isLeaderActive) {
391             handleBatchedModificationsLocal(batched, getSender());
392         } else {
393             ActorSelection leader = getLeader();
394             if (!isLeaderActive || leader == null) {
395                 messageRetrySupport.addMessageToRetry(batched, getSender(),
396                         "Could not commit transaction " + batched.getTransactionID());
397             } else {
398                 // If this is not the first batch and leadership changed in between batched messages,
399                 // we need to reconstruct previous BatchedModifications from the transaction
400                 // DataTreeModification, honoring the max batched modification count, and forward all the
401                 // previous BatchedModifications to the new leader.
402                 Collection<BatchedModifications> newModifications = commitCoordinator.createForwardedBatchedModifications(
403                         batched, datastoreContext.getShardBatchedModificationCount());
404
405                 LOG.debug("{}: Forwarding {} BatchedModifications to leader {}", persistenceId(),
406                         newModifications.size(), leader);
407
408                 for (BatchedModifications bm : newModifications) {
409                     leader.forward(bm, getContext());
410                 }
411             }
412         }
413     }
414
415     private boolean failIfIsolatedLeader(final ActorRef sender) {
416         if (isIsolatedLeader()) {
417             sender.tell(new akka.actor.Status.Failure(new NoShardLeaderException(String.format(
418                     "Shard %s was the leader but has lost contact with all of its followers. Either all" +
419                     " other follower nodes are down or this node is isolated by a network partition.",
420                     persistenceId()))), getSelf());
421             return true;
422         }
423
424         return false;
425     }
426
427     protected boolean isIsolatedLeader() {
428         return getRaftState() == RaftState.IsolatedLeader;
429     }
430
431     private void handleReadyLocalTransaction(final ReadyLocalTransaction message) {
432         LOG.debug("{}: handleReadyLocalTransaction for {}", persistenceId(), message.getTransactionID());
433
434         boolean isLeaderActive = isLeaderActive();
435         if (isLeader() && isLeaderActive) {
436             try {
437                 commitCoordinator.handleReadyLocalTransaction(message, getSender(), this);
438             } catch (Exception e) {
439                 LOG.error("{}: Error handling ReadyLocalTransaction for Tx {}", persistenceId(),
440                         message.getTransactionID(), e);
441                 getSender().tell(new akka.actor.Status.Failure(e), getSelf());
442             }
443         } else {
444             ActorSelection leader = getLeader();
445             if (!isLeaderActive || leader == null) {
446                 messageRetrySupport.addMessageToRetry(message, getSender(),
447                         "Could not commit transaction " + message.getTransactionID());
448             } else {
449                 LOG.debug("{}: Forwarding ReadyLocalTransaction to leader {}", persistenceId(), leader);
450                 message.setRemoteVersion(getCurrentBehavior().getLeaderPayloadVersion());
451                 leader.forward(message, getContext());
452             }
453         }
454     }
455
456     private void handleForwardedReadyTransaction(final ForwardedReadyTransaction forwardedReady) {
457         LOG.debug("{}: handleForwardedReadyTransaction for {}", persistenceId(), forwardedReady.getTransactionID());
458
459         boolean isLeaderActive = isLeaderActive();
460         if (isLeader() && isLeaderActive) {
461             commitCoordinator.handleForwardedReadyTransaction(forwardedReady, getSender(), this);
462         } else {
463             ActorSelection leader = getLeader();
464             if (!isLeaderActive || leader == null) {
465                 messageRetrySupport.addMessageToRetry(forwardedReady, getSender(),
466                         "Could not commit transaction " + forwardedReady.getTransactionID());
467             } else {
468                 LOG.debug("{}: Forwarding ForwardedReadyTransaction to leader {}", persistenceId(), leader);
469
470                 ReadyLocalTransaction readyLocal = new ReadyLocalTransaction(forwardedReady.getTransactionID(),
471                         forwardedReady.getTransaction().getSnapshot(), forwardedReady.isDoImmediateCommit());
472                 readyLocal.setRemoteVersion(getCurrentBehavior().getLeaderPayloadVersion());
473                 leader.forward(readyLocal, getContext());
474             }
475         }
476     }
477
478     private void handleAbortTransaction(final AbortTransaction abort) {
479         doAbortTransaction(abort.getTransactionID(), getSender());
480     }
481
482     void doAbortTransaction(final TransactionIdentifier transactionID, final ActorRef sender) {
483         commitCoordinator.handleAbort(transactionID, sender, this);
484     }
485
486     private void handleCreateTransaction(final Object message) {
487         if (isLeader()) {
488             createTransaction(CreateTransaction.fromSerializable(message));
489         } else if (getLeader() != null) {
490             getLeader().forward(message, getContext());
491         } else {
492             getSender().tell(new akka.actor.Status.Failure(new NoShardLeaderException(
493                     "Could not create a shard transaction", persistenceId())), getSelf());
494         }
495     }
496
497     private void closeTransactionChain(final CloseTransactionChain closeTransactionChain) {
498         store.closeTransactionChain(closeTransactionChain.getIdentifier());
499     }
500
501     private void createTransaction(final CreateTransaction createTransaction) {
502         try {
503             if (TransactionType.fromInt(createTransaction.getTransactionType()) != TransactionType.READ_ONLY &&
504                     failIfIsolatedLeader(getSender())) {
505                 return;
506             }
507
508             ActorRef transactionActor = createTransaction(createTransaction.getTransactionType(),
509                 createTransaction.getTransactionId());
510
511             getSender().tell(new CreateTransactionReply(Serialization.serializedActorPath(transactionActor),
512                     createTransaction.getTransactionId(), createTransaction.getVersion()).toSerializable(), getSelf());
513         } catch (Exception e) {
514             getSender().tell(new akka.actor.Status.Failure(e), getSelf());
515         }
516     }
517
518     private ActorRef createTransaction(final int transactionType, final TransactionIdentifier transactionId) {
519         LOG.debug("{}: Creating transaction : {} ", persistenceId(), transactionId);
520         return transactionActorFactory.newShardTransaction(TransactionType.fromInt(transactionType),
521             transactionId);
522     }
523
524     private void updateSchemaContext(final UpdateSchemaContext message) {
525         updateSchemaContext(message.getSchemaContext());
526     }
527
528     @VisibleForTesting
529     void updateSchemaContext(final SchemaContext schemaContext) {
530         store.updateSchemaContext(schemaContext);
531     }
532
533     private boolean isMetricsCaptureEnabled() {
534         CommonConfig config = new CommonConfig(getContext().system().settings().config());
535         return config.isMetricCaptureEnabled();
536     }
537
538     @Override
539     @VisibleForTesting
540     public RaftActorSnapshotCohort getRaftActorSnapshotCohort() {
541         return snapshotCohort;
542     }
543
544     @Override
545     @Nonnull
546     protected RaftActorRecoveryCohort getRaftActorRecoveryCohort() {
547         return new ShardRecoveryCoordinator(store,
548             restoreFromSnapshot != null ? restoreFromSnapshot.getSnapshot() : null, persistenceId(), LOG);
549     }
550
551     @Override
552     protected void onRecoveryComplete() {
553         restoreFromSnapshot = null;
554
555         //notify shard manager
556         getContext().parent().tell(new ActorInitialized(), getSelf());
557
558         // Being paranoid here - this method should only be called once but just in case...
559         if (txCommitTimeoutCheckSchedule == null) {
560             // Schedule a message to be periodically sent to check if the current in-progress
561             // transaction should be expired and aborted.
562             FiniteDuration period = Duration.create(transactionCommitTimeout / 3, TimeUnit.MILLISECONDS);
563             txCommitTimeoutCheckSchedule = getContext().system().scheduler().schedule(
564                     period, period, getSelf(),
565                     TX_COMMIT_TIMEOUT_CHECK_MESSAGE, getContext().dispatcher(), ActorRef.noSender());
566         }
567     }
568
569     @Override
570     protected void applyState(final ActorRef clientActor, final Identifier identifier, final Object data) {
571         if (data instanceof Payload) {
572             try {
573                 store.applyReplicatedPayload(identifier, (Payload)data);
574             } catch (DataValidationFailedException | IOException e) {
575                 LOG.error("{}: Error applying replica {}", persistenceId(), identifier, e);
576             }
577         } else {
578             LOG.error("{}: Unknown state for {} received {}", persistenceId(), identifier, data);
579         }
580     }
581
582     @Override
583     protected void onStateChanged() {
584         boolean isLeader = isLeader();
585         boolean hasLeader = hasLeader();
586         changeSupport.onLeadershipChange(isLeader, hasLeader);
587         treeChangeSupport.onLeadershipChange(isLeader, hasLeader);
588
589         // If this actor is no longer the leader close all the transaction chains
590         if (!isLeader) {
591             if (LOG.isDebugEnabled()) {
592                 LOG.debug(
593                     "{}: onStateChanged: Closing all transaction chains because shard {} is no longer the leader",
594                     persistenceId(), getId());
595             }
596
597             store.closeAllTransactionChains();
598         }
599
600         if (hasLeader && !isIsolatedLeader()) {
601             messageRetrySupport.retryMessages();
602         }
603     }
604
605     @Override
606     protected void onLeaderChanged(final String oldLeader, final String newLeader) {
607         shardMBean.incrementLeadershipChangeCount();
608
609         boolean hasLeader = hasLeader();
610         if (hasLeader && !isLeader()) {
611             // Another leader was elected. If we were the previous leader and had pending transactions, convert
612             // them to transaction messages and send to the new leader.
613             ActorSelection leader = getLeader();
614             if (leader != null) {
615                 Collection<?> messagesToForward = convertPendingTransactionsToMessages();
616
617                 if (!messagesToForward.isEmpty()) {
618                     LOG.debug("{}: Forwarding {} pending transaction messages to leader {}", persistenceId(),
619                             messagesToForward.size(), leader);
620
621                     for (Object message : messagesToForward) {
622                         leader.tell(message, self());
623                     }
624                 }
625             } else {
626                 commitCoordinator.abortPendingTransactions(
627                         "The transacton was aborted due to inflight leadership change and the leader address isn't available.",
628                         this);
629             }
630         }
631
632         if (hasLeader && !isIsolatedLeader()) {
633             messageRetrySupport.retryMessages();
634         }
635     }
636
637     /**
638      * Clears all pending transactions and converts them to messages to be forwarded to a new leader.
639      *
640      * @return the converted messages
641      */
642     public Collection<?> convertPendingTransactionsToMessages() {
643         return commitCoordinator.convertPendingTransactionsToMessages(datastoreContext.getShardBatchedModificationCount());
644     }
645
646     @Override
647     protected void pauseLeader(final Runnable operation) {
648         LOG.debug("{}: In pauseLeader, operation: {}", persistenceId(), operation);
649         store.setRunOnPendingTransactionsComplete(operation);
650     }
651
652     @Override
653     protected OnDemandRaftState.AbstractBuilder<?> newOnDemandRaftStateBuilder() {
654         return OnDemandShardState.newBuilder().treeChangeListenerActors(treeChangeSupport.getListenerActors())
655                 .dataChangeListenerActors(changeSupport.getListenerActors())
656                 .commitCohortActors(store.getCohortActors());
657     }
658
659     @Override
660     public String persistenceId() {
661         return this.name;
662     }
663
664     @VisibleForTesting
665     ShardCommitCoordinator getCommitCoordinator() {
666         return commitCoordinator;
667     }
668
669     public DatastoreContext getDatastoreContext() {
670         return datastoreContext;
671     }
672
673     @VisibleForTesting
674     public ShardDataTree getDataStore() {
675         return store;
676     }
677
678     @VisibleForTesting
679     ShardStats getShardMBean() {
680         return shardMBean;
681     }
682
683     public static Builder builder() {
684         return new Builder();
685     }
686
687     public static abstract class AbstractBuilder<T extends AbstractBuilder<T, S>, S extends Shard> {
688         private final Class<S> shardClass;
689         private ShardIdentifier id;
690         private Map<String, String> peerAddresses = Collections.emptyMap();
691         private DatastoreContext datastoreContext;
692         private SchemaContext schemaContext;
693         private DatastoreSnapshot.ShardSnapshot restoreFromSnapshot;
694         private TipProducingDataTree dataTree;
695         private volatile boolean sealed;
696
697         protected AbstractBuilder(final Class<S> shardClass) {
698             this.shardClass = shardClass;
699         }
700
701         protected void checkSealed() {
702             Preconditions.checkState(!sealed, "Builder isalready sealed - further modifications are not allowed");
703         }
704
705         @SuppressWarnings("unchecked")
706         private T self() {
707             return (T) this;
708         }
709
710         public T id(final ShardIdentifier id) {
711             checkSealed();
712             this.id = id;
713             return self();
714         }
715
716         public T peerAddresses(final Map<String, String> peerAddresses) {
717             checkSealed();
718             this.peerAddresses = peerAddresses;
719             return self();
720         }
721
722         public T datastoreContext(final DatastoreContext datastoreContext) {
723             checkSealed();
724             this.datastoreContext = datastoreContext;
725             return self();
726         }
727
728         public T schemaContext(final SchemaContext schemaContext) {
729             checkSealed();
730             this.schemaContext = schemaContext;
731             return self();
732         }
733
734         public T restoreFromSnapshot(final DatastoreSnapshot.ShardSnapshot restoreFromSnapshot) {
735             checkSealed();
736             this.restoreFromSnapshot = restoreFromSnapshot;
737             return self();
738         }
739
740         public T dataTree(final TipProducingDataTree dataTree) {
741             checkSealed();
742             this.dataTree = dataTree;
743             return self();
744         }
745
746         public ShardIdentifier getId() {
747             return id;
748         }
749
750         public Map<String, String> getPeerAddresses() {
751             return peerAddresses;
752         }
753
754         public DatastoreContext getDatastoreContext() {
755             return datastoreContext;
756         }
757
758         public SchemaContext getSchemaContext() {
759             return schemaContext;
760         }
761
762         public DatastoreSnapshot.ShardSnapshot getRestoreFromSnapshot() {
763             return restoreFromSnapshot;
764         }
765
766         public TipProducingDataTree getDataTree() {
767             return dataTree;
768         }
769
770         public TreeType getTreeType() {
771             switch (datastoreContext.getLogicalStoreType()) {
772             case CONFIGURATION:
773                 return TreeType.CONFIGURATION;
774             case OPERATIONAL:
775                 return TreeType.OPERATIONAL;
776             }
777
778             throw new IllegalStateException("Unhandled logical store type " + datastoreContext.getLogicalStoreType());
779         }
780
781         protected void verify() {
782             Preconditions.checkNotNull(id, "id should not be null");
783             Preconditions.checkNotNull(peerAddresses, "peerAddresses should not be null");
784             Preconditions.checkNotNull(datastoreContext, "dataStoreContext should not be null");
785             Preconditions.checkNotNull(schemaContext, "schemaContext should not be null");
786         }
787
788         public Props props() {
789             sealed = true;
790             verify();
791             return Props.create(shardClass, this);
792         }
793     }
794
795     public static class Builder extends AbstractBuilder<Builder, Shard> {
796         private Builder() {
797             super(Shard.class);
798         }
799     }
800
801     Ticker ticker() {
802         return Ticker.systemTicker();
803     }
804 }