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