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