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