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