Address comments in https://git.opendaylight.org/gerrit/#/c/18392/
[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.japi.Creator;
16 import akka.persistence.RecoveryFailure;
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.util.concurrent.FutureCallback;
22 import com.google.common.util.concurrent.Futures;
23 import com.google.common.util.concurrent.ListenableFuture;
24 import java.io.IOException;
25 import java.util.HashMap;
26 import java.util.Map;
27 import java.util.concurrent.TimeUnit;
28 import javax.annotation.Nonnull;
29 import org.opendaylight.controller.cluster.common.actor.CommonConfig;
30 import org.opendaylight.controller.cluster.common.actor.MeteringBehavior;
31 import org.opendaylight.controller.cluster.datastore.ShardCommitCoordinator.CohortEntry;
32 import org.opendaylight.controller.cluster.datastore.exceptions.NoShardLeaderException;
33 import org.opendaylight.controller.cluster.datastore.identifiers.ShardIdentifier;
34 import org.opendaylight.controller.cluster.datastore.identifiers.ShardTransactionIdentifier;
35 import org.opendaylight.controller.cluster.datastore.jmx.mbeans.shard.ShardMBeanFactory;
36 import org.opendaylight.controller.cluster.datastore.jmx.mbeans.shard.ShardStats;
37 import org.opendaylight.controller.cluster.datastore.messages.AbortTransaction;
38 import org.opendaylight.controller.cluster.datastore.messages.AbortTransactionReply;
39 import org.opendaylight.controller.cluster.datastore.messages.ActorInitialized;
40 import org.opendaylight.controller.cluster.datastore.messages.BatchedModifications;
41 import org.opendaylight.controller.cluster.datastore.messages.CanCommitTransaction;
42 import org.opendaylight.controller.cluster.datastore.messages.CloseTransactionChain;
43 import org.opendaylight.controller.cluster.datastore.messages.CommitTransaction;
44 import org.opendaylight.controller.cluster.datastore.messages.CommitTransactionReply;
45 import org.opendaylight.controller.cluster.datastore.messages.CreateTransaction;
46 import org.opendaylight.controller.cluster.datastore.messages.CreateTransactionReply;
47 import org.opendaylight.controller.cluster.datastore.messages.ForwardedReadyTransaction;
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.modification.Modification;
55 import org.opendaylight.controller.cluster.datastore.modification.ModificationPayload;
56 import org.opendaylight.controller.cluster.datastore.modification.MutableCompositeModification;
57 import org.opendaylight.controller.cluster.datastore.utils.Dispatchers;
58 import org.opendaylight.controller.cluster.datastore.utils.MessageTracker;
59 import org.opendaylight.controller.cluster.notifications.LeaderStateChanged;
60 import org.opendaylight.controller.cluster.notifications.RegisterRoleChangeListener;
61 import org.opendaylight.controller.cluster.notifications.RoleChangeNotifier;
62 import org.opendaylight.controller.cluster.raft.RaftActor;
63 import org.opendaylight.controller.cluster.raft.RaftActorRecoveryCohort;
64 import org.opendaylight.controller.cluster.raft.RaftActorSnapshotCohort;
65 import org.opendaylight.controller.cluster.raft.base.messages.FollowerInitialSyncUpStatus;
66 import org.opendaylight.controller.cluster.raft.messages.AppendEntriesReply;
67 import org.opendaylight.controller.cluster.raft.protobuff.client.messages.CompositeModificationByteStringPayload;
68 import org.opendaylight.controller.cluster.raft.protobuff.client.messages.CompositeModificationPayload;
69 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTree;
70 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidate;
71 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataValidationFailedException;
72 import org.opendaylight.yangtools.yang.data.api.schema.tree.ModificationType;
73 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
74 import scala.concurrent.duration.Duration;
75 import scala.concurrent.duration.FiniteDuration;
76
77 /**
78  * A Shard represents a portion of the logical data tree <br/>
79  * <p>
80  * Our Shard uses InMemoryDataTree as it's internal representation and delegates all requests it
81  * </p>
82  */
83 public class Shard extends RaftActor {
84
85     private static final Object TX_COMMIT_TIMEOUT_CHECK_MESSAGE = "txCommitTimeoutCheck";
86
87     @VisibleForTesting
88     static final Object GET_SHARD_MBEAN_MESSAGE = "getShardMBeanMessage";
89
90     @VisibleForTesting
91     static final String DEFAULT_NAME = "default";
92
93     // The state of this Shard
94     private final ShardDataTree store;
95
96     /// The name of this shard
97     private final String name;
98
99     private final ShardStats shardMBean;
100
101     private DatastoreContext datastoreContext;
102
103     private final ShardCommitCoordinator commitCoordinator;
104
105     private long transactionCommitTimeout;
106
107     private Cancellable txCommitTimeoutCheckSchedule;
108
109     private final Optional<ActorRef> roleChangeNotifier;
110
111     private final MessageTracker appendEntriesReplyTracker;
112
113     private final ShardTransactionActorFactory transactionActorFactory;
114
115     private final ShardSnapshotCohort snapshotCohort;
116
117     private final DataTreeChangeListenerSupport treeChangeSupport = new DataTreeChangeListenerSupport(this);
118     private final DataChangeListenerSupport changeSupport = new DataChangeListenerSupport(this);
119
120     protected Shard(final ShardIdentifier name, final Map<String, String> peerAddresses,
121             final DatastoreContext datastoreContext, final SchemaContext schemaContext) {
122         super(name.toString(), new HashMap<>(peerAddresses), Optional.of(datastoreContext.getShardRaftConfig()),
123                 DataStoreVersions.CURRENT_VERSION);
124
125         this.name = name.toString();
126         this.datastoreContext = datastoreContext;
127
128         setPersistence(datastoreContext.isPersistent());
129
130         LOG.info("Shard created : {}, persistent : {}", name, datastoreContext.isPersistent());
131
132         store = new ShardDataTree(schemaContext);
133
134         shardMBean = ShardMBeanFactory.getShardStatsMBean(name.toString(),
135                 datastoreContext.getDataStoreMXBeanType());
136         shardMBean.setShardActor(getSelf());
137
138         if (isMetricsCaptureEnabled()) {
139             getContext().become(new MeteringBehavior(this));
140         }
141
142         commitCoordinator = new ShardCommitCoordinator(store,
143                 datastoreContext.getShardCommitQueueExpiryTimeoutInMillis(),
144                 datastoreContext.getShardTransactionCommitQueueCapacity(), self(), LOG, this.name);
145
146         setTransactionCommitTimeout();
147
148         // create a notifier actor for each cluster member
149         roleChangeNotifier = createRoleChangeNotifier(name.toString());
150
151         appendEntriesReplyTracker = new MessageTracker(AppendEntriesReply.class,
152                 getRaftActorContext().getConfigParams().getIsolatedCheckIntervalInMillis());
153
154         transactionActorFactory = new ShardTransactionActorFactory(store, datastoreContext,
155                 new Dispatchers(context().system().dispatchers()).getDispatcherPath(
156                         Dispatchers.DispatcherType.Transaction), self(), getContext(), shardMBean);
157
158         snapshotCohort = new ShardSnapshotCohort(transactionActorFactory, store, LOG, this.name);
159     }
160
161     private void setTransactionCommitTimeout() {
162         transactionCommitTimeout = TimeUnit.MILLISECONDS.convert(
163                 datastoreContext.getShardTransactionCommitTimeoutInSeconds(), TimeUnit.SECONDS) / 2;
164     }
165
166     public static Props props(final ShardIdentifier name,
167         final Map<String, String> peerAddresses,
168         final DatastoreContext datastoreContext, final SchemaContext schemaContext) {
169         Preconditions.checkNotNull(name, "name should not be null");
170         Preconditions.checkNotNull(peerAddresses, "peerAddresses should not be null");
171         Preconditions.checkNotNull(datastoreContext, "dataStoreContext should not be null");
172         Preconditions.checkNotNull(schemaContext, "schemaContext should not be null");
173
174         return Props.create(new ShardCreator(name, peerAddresses, datastoreContext, schemaContext));
175     }
176
177     private Optional<ActorRef> createRoleChangeNotifier(String shardId) {
178         ActorRef shardRoleChangeNotifier = this.getContext().actorOf(
179             RoleChangeNotifier.getProps(shardId), shardId + "-notifier");
180         return Optional.of(shardRoleChangeNotifier);
181     }
182
183     @Override
184     public void postStop() {
185         LOG.info("Stopping Shard {}", persistenceId());
186
187         super.postStop();
188
189         if(txCommitTimeoutCheckSchedule != null) {
190             txCommitTimeoutCheckSchedule.cancel();
191         }
192
193         shardMBean.unregisterMBean();
194     }
195
196     @Override
197     public void onReceiveRecover(final Object message) throws Exception {
198         if(LOG.isDebugEnabled()) {
199             LOG.debug("{}: onReceiveRecover: Received message {} from {}", persistenceId(),
200                 message.getClass().toString(), getSender());
201         }
202
203         if (message instanceof RecoveryFailure){
204             LOG.error("{}: Recovery failed because of this cause",
205                     persistenceId(), ((RecoveryFailure) message).cause());
206
207             // Even though recovery failed, we still need to finish our recovery, eg send the
208             // ActorInitialized message and start the txCommitTimeoutCheckSchedule.
209             onRecoveryComplete();
210         } else {
211             super.onReceiveRecover(message);
212             if(LOG.isTraceEnabled()) {
213                 appendEntriesReplyTracker.begin();
214             }
215         }
216     }
217
218     @Override
219     public void onReceiveCommand(final Object message) throws Exception {
220
221         MessageTracker.Context context = appendEntriesReplyTracker.received(message);
222
223         if(context.error().isPresent()){
224             LOG.trace("{} : AppendEntriesReply failed to arrive at the expected interval {}", persistenceId(),
225                     context.error());
226         }
227
228         try {
229             if (CreateTransaction.SERIALIZABLE_CLASS.isInstance(message)) {
230                 handleCreateTransaction(message);
231             } else if (BatchedModifications.class.isInstance(message)) {
232                 handleBatchedModifications((BatchedModifications)message);
233             } else if (message instanceof ForwardedReadyTransaction) {
234                 commitCoordinator.handleForwardedReadyTransaction((ForwardedReadyTransaction) message,
235                         getSender(), this);
236             } else if (message instanceof ReadyLocalTransaction) {
237                 handleReadyLocalTransaction((ReadyLocalTransaction)message);
238             } else if (CanCommitTransaction.SERIALIZABLE_CLASS.isInstance(message)) {
239                 handleCanCommitTransaction(CanCommitTransaction.fromSerializable(message));
240             } else if (CommitTransaction.SERIALIZABLE_CLASS.isInstance(message)) {
241                 handleCommitTransaction(CommitTransaction.fromSerializable(message));
242             } else if (AbortTransaction.SERIALIZABLE_CLASS.isInstance(message)) {
243                 handleAbortTransaction(AbortTransaction.fromSerializable(message));
244             } else if (CloseTransactionChain.SERIALIZABLE_CLASS.isInstance(message)) {
245                 closeTransactionChain(CloseTransactionChain.fromSerializable(message));
246             } else if (message instanceof RegisterChangeListener) {
247                 changeSupport.onMessage((RegisterChangeListener) message, isLeader());
248             } else if (message instanceof RegisterDataTreeChangeListener) {
249                 treeChangeSupport.onMessage((RegisterDataTreeChangeListener) message, isLeader());
250             } else if (message instanceof UpdateSchemaContext) {
251                 updateSchemaContext((UpdateSchemaContext) message);
252             } else if (message instanceof PeerAddressResolved) {
253                 PeerAddressResolved resolved = (PeerAddressResolved) message;
254                 setPeerAddress(resolved.getPeerId().toString(),
255                         resolved.getPeerAddress());
256             } else if (message.equals(TX_COMMIT_TIMEOUT_CHECK_MESSAGE)) {
257                 handleTransactionCommitTimeoutCheck();
258             } else if(message instanceof DatastoreContext) {
259                 onDatastoreContext((DatastoreContext)message);
260             } else if(message instanceof RegisterRoleChangeListener){
261                 roleChangeNotifier.get().forward(message, context());
262             } else if (message instanceof FollowerInitialSyncUpStatus) {
263                 shardMBean.setFollowerInitialSyncStatus(((FollowerInitialSyncUpStatus) message).isInitialSyncDone());
264                 context().parent().tell(message, self());
265             } else if(GET_SHARD_MBEAN_MESSAGE.equals(message)){
266                 sender().tell(getShardMBean(), self());
267             } else {
268                 super.onReceiveCommand(message);
269             }
270         } finally {
271             context.done();
272         }
273     }
274
275     @Override
276     protected Optional<ActorRef> getRoleChangeNotifier() {
277         return roleChangeNotifier;
278     }
279
280     @Override
281     protected LeaderStateChanged newLeaderStateChanged(String memberId, String leaderId) {
282         return new ShardLeaderStateChanged(memberId, leaderId,
283                 isLeader() ? Optional.<DataTree>of(store.getDataTree()) : Optional.<DataTree>absent());
284     }
285
286     private void onDatastoreContext(DatastoreContext context) {
287         datastoreContext = context;
288
289         commitCoordinator.setQueueCapacity(datastoreContext.getShardTransactionCommitQueueCapacity());
290
291         setTransactionCommitTimeout();
292
293         if(datastoreContext.isPersistent() && !persistence().isRecoveryApplicable()) {
294             setPersistence(true);
295         } else if(!datastoreContext.isPersistent() && persistence().isRecoveryApplicable()) {
296             setPersistence(false);
297         }
298
299         updateConfigParams(datastoreContext.getShardRaftConfig());
300     }
301
302     private void handleTransactionCommitTimeoutCheck() {
303         CohortEntry cohortEntry = commitCoordinator.getCurrentCohortEntry();
304         if(cohortEntry != null) {
305             if(cohortEntry.isExpired(transactionCommitTimeout)) {
306                 LOG.warn("{}: Current transaction {} has timed out after {} ms - aborting",
307                         persistenceId(), cohortEntry.getTransactionID(), transactionCommitTimeout);
308
309                 doAbortTransaction(cohortEntry.getTransactionID(), null);
310             }
311         }
312
313         commitCoordinator.cleanupExpiredCohortEntries();
314     }
315
316     private static boolean isEmptyCommit(final DataTreeCandidate candidate) {
317         return ModificationType.UNMODIFIED.equals(candidate.getRootNode().getModificationType());
318     }
319
320     void continueCommit(final CohortEntry cohortEntry) throws Exception {
321         final DataTreeCandidate candidate = cohortEntry.getCohort().getCandidate();
322
323         // If we do not have any followers and we are not using persistence
324         // or if cohortEntry has no modifications
325         // we can apply modification to the state immediately
326         if ((!hasFollowers() && !persistence().isRecoveryApplicable()) || isEmptyCommit(candidate)) {
327             applyModificationToState(cohortEntry.getReplySender(), cohortEntry.getTransactionID(), candidate);
328         } else {
329             Shard.this.persistData(cohortEntry.getReplySender(), cohortEntry.getTransactionID(),
330                 DataTreeCandidatePayload.create(candidate));
331         }
332     }
333
334     private void handleCommitTransaction(final CommitTransaction commit) {
335         if(!commitCoordinator.handleCommit(commit.getTransactionID(), getSender(), this)) {
336             shardMBean.incrementFailedTransactionsCount();
337         }
338     }
339
340     private void finishCommit(@Nonnull final ActorRef sender, @Nonnull final String transactionID, @Nonnull final CohortEntry cohortEntry) {
341         LOG.debug("{}: Finishing commit for transaction {}", persistenceId(), cohortEntry.getTransactionID());
342
343         try {
344             // We block on the future here so we don't have to worry about possibly accessing our
345             // state on a different thread outside of our dispatcher. Also, the data store
346             // currently uses a same thread executor anyway.
347             cohortEntry.getCohort().commit().get();
348
349             sender.tell(CommitTransactionReply.INSTANCE.toSerializable(), getSelf());
350
351             shardMBean.incrementCommittedTransactionCount();
352             shardMBean.setLastCommittedTransactionTime(System.currentTimeMillis());
353
354         } catch (Exception e) {
355             sender.tell(new akka.actor.Status.Failure(e), getSelf());
356
357             LOG.error("{}, An exception occurred while committing transaction {}", persistenceId(),
358                     transactionID, e);
359             shardMBean.incrementFailedTransactionsCount();
360         } finally {
361             commitCoordinator.currentTransactionComplete(transactionID, true);
362         }
363     }
364
365     private void finishCommit(@Nonnull final ActorRef sender, final @Nonnull String transactionID) {
366         // With persistence enabled, this method is called via applyState by the leader strategy
367         // after the commit has been replicated to a majority of the followers.
368
369         CohortEntry cohortEntry = commitCoordinator.getCohortEntryIfCurrent(transactionID);
370         if (cohortEntry == null) {
371             // The transaction is no longer the current commit. This can happen if the transaction
372             // was aborted prior, most likely due to timeout in the front-end. We need to finish
373             // committing the transaction though since it was successfully persisted and replicated
374             // however we can't use the original cohort b/c it was already preCommitted and may
375             // conflict with the current commit or may have been aborted so we commit with a new
376             // transaction.
377             cohortEntry = commitCoordinator.getAndRemoveCohortEntry(transactionID);
378             if(cohortEntry != null) {
379                 try {
380                     store.applyForeignCandidate(transactionID, cohortEntry.getCohort().getCandidate());
381                 } catch (DataValidationFailedException e) {
382                     shardMBean.incrementFailedTransactionsCount();
383                     LOG.error("{}: Failed to re-apply transaction {}", persistenceId(), transactionID, e);
384                 }
385
386                 sender.tell(CommitTransactionReply.INSTANCE.toSerializable(), getSelf());
387             } else {
388                 // This really shouldn't happen - it likely means that persistence or replication
389                 // took so long to complete such that the cohort entry was expired from the cache.
390                 IllegalStateException ex = new IllegalStateException(
391                         String.format("%s: Could not finish committing transaction %s - no CohortEntry found",
392                                 persistenceId(), transactionID));
393                 LOG.error(ex.getMessage());
394                 sender.tell(new akka.actor.Status.Failure(ex), getSelf());
395             }
396         } else {
397             finishCommit(sender, transactionID, cohortEntry);
398         }
399     }
400
401     private void handleCanCommitTransaction(final CanCommitTransaction canCommit) {
402         LOG.debug("{}: Can committing transaction {}", persistenceId(), canCommit.getTransactionID());
403         commitCoordinator.handleCanCommit(canCommit.getTransactionID(), getSender(), this);
404     }
405
406     private void noLeaderError(Object message) {
407         // TODO: rather than throwing an immediate exception, we could schedule a timer to try again to make
408         // it more resilient in case we're in the process of electing a new leader.
409         getSender().tell(new akka.actor.Status.Failure(new NoShardLeaderException(String.format(
410             "Could not find the leader for shard %s. This typically happens" +
411             " when the system is coming up or recovering and a leader is being elected. Try again" +
412             " later.", persistenceId()))), getSelf());
413     }
414
415     private void handleBatchedModifications(BatchedModifications batched) {
416         // This message is sent to prepare the modifications transaction directly on the Shard as an
417         // optimization to avoid the extra overhead of a separate ShardTransaction actor. On the last
418         // BatchedModifications message, the caller sets the ready flag in the message indicating
419         // modifications are complete. The reply contains the cohort actor path (this actor) for the caller
420         // to initiate the 3-phase commit. This also avoids the overhead of sending an additional
421         // ReadyTransaction message.
422
423         // If we're not the leader then forward to the leader. This is a safety measure - we shouldn't
424         // normally get here if we're not the leader as the front-end (TransactionProxy) should determine
425         // the primary/leader shard. However with timing and caching on the front-end, there's a small
426         // window where it could have a stale leader during leadership transitions.
427         //
428         if(isLeader()) {
429             try {
430                 commitCoordinator.handleBatchedModifications(batched, getSender(), this);
431             } catch (Exception e) {
432                 LOG.error("{}: Error handling BatchedModifications for Tx {}", persistenceId(),
433                         batched.getTransactionID(), e);
434                 getSender().tell(new akka.actor.Status.Failure(e), getSelf());
435             }
436         } else {
437             ActorSelection leader = getLeader();
438             if(leader != null) {
439                 // TODO: what if this is not the first batch and leadership changed in between batched messages?
440                 // We could check if the commitCoordinator already has a cached entry and forward all the previous
441                 // batched modifications.
442                 LOG.debug("{}: Forwarding BatchedModifications to leader {}", persistenceId(), leader);
443                 leader.forward(batched, getContext());
444             } else {
445                 noLeaderError(batched);
446             }
447         }
448     }
449
450     private void handleReadyLocalTransaction(final ReadyLocalTransaction message) {
451         if (isLeader()) {
452             try {
453                 commitCoordinator.handleReadyLocalTransaction(message, getSender(), this);
454             } catch (Exception e) {
455                 LOG.error("{}: Error handling LocalModifications for Tx {}", persistenceId(),
456                         message.getTransactionID(), e);
457                 getSender().tell(new akka.actor.Status.Failure(e), getSelf());
458             }
459         } else {
460             ActorSelection leader = getLeader();
461             if (leader != null) {
462                 LOG.debug("{}: Forwarding LocalModifications to leader {}", persistenceId(), leader);
463                 leader.forward(message, getContext());
464             } else {
465                 noLeaderError(message);
466             }
467         }
468     }
469
470     private void handleAbortTransaction(final AbortTransaction abort) {
471         doAbortTransaction(abort.getTransactionID(), getSender());
472     }
473
474     void doAbortTransaction(final String transactionID, final ActorRef sender) {
475         final CohortEntry cohortEntry = commitCoordinator.getCohortEntryIfCurrent(transactionID);
476         if(cohortEntry != null) {
477             LOG.debug("{}: Aborting transaction {}", persistenceId(), transactionID);
478
479             // We don't remove the cached cohort entry here (ie pass false) in case the Tx was
480             // aborted during replication in which case we may still commit locally if replication
481             // succeeds.
482             commitCoordinator.currentTransactionComplete(transactionID, false);
483
484             final ListenableFuture<Void> future = cohortEntry.getCohort().abort();
485             final ActorRef self = getSelf();
486
487             Futures.addCallback(future, new FutureCallback<Void>() {
488                 @Override
489                 public void onSuccess(final Void v) {
490                     shardMBean.incrementAbortTransactionsCount();
491
492                     if(sender != null) {
493                         sender.tell(AbortTransactionReply.INSTANCE.toSerializable(), self);
494                     }
495                 }
496
497                 @Override
498                 public void onFailure(final Throwable t) {
499                     LOG.error("{}: An exception happened during abort", persistenceId(), t);
500
501                     if(sender != null) {
502                         sender.tell(new akka.actor.Status.Failure(t), self);
503                     }
504                 }
505             });
506         }
507     }
508
509     private void handleCreateTransaction(final Object message) {
510         if (isLeader()) {
511             createTransaction(CreateTransaction.fromSerializable(message));
512         } else if (getLeader() != null) {
513             getLeader().forward(message, getContext());
514         } else {
515             getSender().tell(new akka.actor.Status.Failure(new NoShardLeaderException(String.format(
516                 "Could not find leader for shard %s so transaction cannot be created. This typically happens" +
517                 " when the system is coming up or recovering and a leader is being elected. Try again" +
518                 " later.", persistenceId()))), getSelf());
519         }
520     }
521
522     private void closeTransactionChain(final CloseTransactionChain closeTransactionChain) {
523         store.closeTransactionChain(closeTransactionChain.getTransactionChainId());
524     }
525
526     private ActorRef createTypedTransactionActor(int transactionType,
527             ShardTransactionIdentifier transactionId, String transactionChainId,
528             short clientVersion ) {
529
530         return transactionActorFactory.newShardTransaction(TransactionType.fromInt(transactionType),
531                 transactionId, transactionChainId, clientVersion);
532     }
533
534     private void createTransaction(CreateTransaction createTransaction) {
535         try {
536             ActorRef transactionActor = createTransaction(createTransaction.getTransactionType(),
537                 createTransaction.getTransactionId(), createTransaction.getTransactionChainId(),
538                 createTransaction.getVersion());
539
540             getSender().tell(new CreateTransactionReply(Serialization.serializedActorPath(transactionActor),
541                     createTransaction.getTransactionId()).toSerializable(), getSelf());
542         } catch (Exception e) {
543             getSender().tell(new akka.actor.Status.Failure(e), getSelf());
544         }
545     }
546
547     private ActorRef createTransaction(int transactionType, String remoteTransactionId,
548             String transactionChainId, short clientVersion) {
549
550
551         ShardTransactionIdentifier transactionId = new ShardTransactionIdentifier(remoteTransactionId);
552
553         if(LOG.isDebugEnabled()) {
554             LOG.debug("{}: Creating transaction : {} ", persistenceId(), transactionId);
555         }
556
557         ActorRef transactionActor = createTypedTransactionActor(transactionType, transactionId,
558                 transactionChainId, clientVersion);
559
560         return transactionActor;
561     }
562
563     private void commitWithNewTransaction(final Modification modification) {
564         ReadWriteShardDataTreeTransaction tx = store.newReadWriteTransaction(modification.toString(), null);
565         modification.apply(tx.getSnapshot());
566         try {
567             snapshotCohort.syncCommitTransaction(tx);
568             shardMBean.incrementCommittedTransactionCount();
569             shardMBean.setLastCommittedTransactionTime(System.currentTimeMillis());
570         } catch (Exception e) {
571             shardMBean.incrementFailedTransactionsCount();
572             LOG.error("{}: Failed to commit", persistenceId(), e);
573         }
574     }
575
576     private void updateSchemaContext(final UpdateSchemaContext message) {
577         updateSchemaContext(message.getSchemaContext());
578     }
579
580     @VisibleForTesting
581     void updateSchemaContext(final SchemaContext schemaContext) {
582         store.updateSchemaContext(schemaContext);
583     }
584
585     private boolean isMetricsCaptureEnabled() {
586         CommonConfig config = new CommonConfig(getContext().system().settings().config());
587         return config.isMetricCaptureEnabled();
588     }
589
590     @Override
591     protected RaftActorSnapshotCohort getRaftActorSnapshotCohort() {
592         return snapshotCohort;
593     }
594
595     @Override
596     @Nonnull
597     protected RaftActorRecoveryCohort getRaftActorRecoveryCohort() {
598         return new ShardRecoveryCoordinator(store, persistenceId(), LOG);
599     }
600
601     @Override
602     protected void onRecoveryComplete() {
603         store.recoveryDone();
604         //notify shard manager
605         getContext().parent().tell(new ActorInitialized(), getSelf());
606
607         // Being paranoid here - this method should only be called once but just in case...
608         if(txCommitTimeoutCheckSchedule == null) {
609             // Schedule a message to be periodically sent to check if the current in-progress
610             // transaction should be expired and aborted.
611             FiniteDuration period = Duration.create(transactionCommitTimeout / 3, TimeUnit.MILLISECONDS);
612             txCommitTimeoutCheckSchedule = getContext().system().scheduler().schedule(
613                     period, period, getSelf(),
614                     TX_COMMIT_TIMEOUT_CHECK_MESSAGE, getContext().dispatcher(), ActorRef.noSender());
615         }
616     }
617
618     @Override
619     protected void applyState(final ActorRef clientActor, final String identifier, final Object data) {
620         if (data instanceof DataTreeCandidatePayload) {
621             if (clientActor == null) {
622                 // No clientActor indicates a replica coming from the leader
623                 try {
624                     store.applyForeignCandidate(identifier, ((DataTreeCandidatePayload)data).getCandidate());
625                 } catch (DataValidationFailedException | IOException e) {
626                     LOG.error("{}: Error applying replica {}", persistenceId(), identifier, e);
627                 }
628             } else {
629                 // Replication consensus reached, proceed to commit
630                 finishCommit(clientActor, identifier);
631             }
632         } else if (data instanceof ModificationPayload) {
633             try {
634                 applyModificationToState(clientActor, identifier, ((ModificationPayload) data).getModification());
635             } catch (ClassNotFoundException | IOException e) {
636                 LOG.error("{}: Error extracting ModificationPayload", persistenceId(), e);
637             }
638         } else if (data instanceof CompositeModificationPayload) {
639             Object modification = ((CompositeModificationPayload) data).getModification();
640
641             applyModificationToState(clientActor, identifier, modification);
642         } else if(data instanceof CompositeModificationByteStringPayload ){
643             Object modification = ((CompositeModificationByteStringPayload) data).getModification();
644
645             applyModificationToState(clientActor, identifier, modification);
646         } else {
647             LOG.error("{}: Unknown state received {} Class loader = {} CompositeNodeMod.ClassLoader = {}",
648                     persistenceId(), data, data.getClass().getClassLoader(),
649                     CompositeModificationPayload.class.getClassLoader());
650         }
651     }
652
653     private void applyModificationToState(ActorRef clientActor, String identifier, Object modification) {
654         if(modification == null) {
655             LOG.error(
656                     "{}: modification is null - this is very unexpected, clientActor = {}, identifier = {}",
657                     persistenceId(), identifier, clientActor != null ? clientActor.path().toString() : null);
658         } else if(clientActor == null) {
659             // There's no clientActor to which to send a commit reply so we must be applying
660             // replicated state from the leader.
661             commitWithNewTransaction(MutableCompositeModification.fromSerializable(modification));
662         } else {
663             // This must be the OK to commit after replication consensus.
664             finishCommit(clientActor, identifier);
665         }
666     }
667
668     @Override
669     protected void onStateChanged() {
670         boolean isLeader = isLeader();
671         changeSupport.onLeadershipChange(isLeader);
672         treeChangeSupport.onLeadershipChange(isLeader);
673
674         // If this actor is no longer the leader close all the transaction chains
675         if (!isLeader) {
676             if(LOG.isDebugEnabled()) {
677                 LOG.debug(
678                     "{}: onStateChanged: Closing all transaction chains because shard {} is no longer the leader",
679                     persistenceId(), getId());
680             }
681
682             store.closeAllTransactionChains();
683         }
684     }
685
686     @Override
687     protected void onLeaderChanged(String oldLeader, String newLeader) {
688         shardMBean.incrementLeadershipChangeCount();
689     }
690
691     @Override
692     public String persistenceId() {
693         return this.name;
694     }
695
696     @VisibleForTesting
697     ShardCommitCoordinator getCommitCoordinator() {
698         return commitCoordinator;
699     }
700
701
702     private static class ShardCreator implements Creator<Shard> {
703
704         private static final long serialVersionUID = 1L;
705
706         final ShardIdentifier name;
707         final Map<String, String> peerAddresses;
708         final DatastoreContext datastoreContext;
709         final SchemaContext schemaContext;
710
711         ShardCreator(final ShardIdentifier name, final Map<String, String> peerAddresses,
712                 final DatastoreContext datastoreContext, final SchemaContext schemaContext) {
713             this.name = name;
714             this.peerAddresses = peerAddresses;
715             this.datastoreContext = datastoreContext;
716             this.schemaContext = schemaContext;
717         }
718
719         @Override
720         public Shard create() throws Exception {
721             return new Shard(name, peerAddresses, datastoreContext, schemaContext);
722         }
723     }
724
725     @VisibleForTesting
726     public ShardDataTree getDataStore() {
727         return store;
728     }
729
730     @VisibleForTesting
731     ShardStats getShardMBean() {
732         return shardMBean;
733     }
734 }