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