CDS: Move DataChangeListener into a support 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.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                 BatchedModificationsReply reply = commitCoordinator.handleTransactionModifications(batched);
451                 sender().tell(reply, self());
452             } catch (Exception e) {
453                 LOG.error("{}: Error handling BatchedModifications for Tx {}", persistenceId(),
454                         batched.getTransactionID(), e);
455                 getSender().tell(new akka.actor.Status.Failure(e), getSelf());
456             }
457         } else {
458             ActorSelection leader = getLeader();
459             if(leader != null) {
460                 // TODO: what if this is not the first batch and leadership changed in between batched messages?
461                 // We could check if the commitCoordinator already has a cached entry and forward all the previous
462                 // batched modifications.
463                 LOG.debug("{}: Forwarding BatchedModifications to leader {}", persistenceId(), leader);
464                 leader.forward(batched, getContext());
465             } else {
466                 // TODO: rather than throwing an immediate exception, we could schedule a timer to try again to make
467                 // it more resilient in case we're in the process of electing a new leader.
468                 getSender().tell(new akka.actor.Status.Failure(new NoShardLeaderException(String.format(
469                     "Could not find the leader for shard %s. This typically happens" +
470                     " when the system is coming up or recovering and a leader is being elected. Try again" +
471                     " later.", persistenceId()))), getSelf());
472             }
473         }
474     }
475
476     private void handleForwardedReadyTransaction(ForwardedReadyTransaction ready) {
477         LOG.debug("{}: Readying transaction {}, client version {}", persistenceId(),
478                 ready.getTransactionID(), ready.getTxnClientVersion());
479
480         // This message is forwarded by the ShardTransaction on ready. We cache the cohort in the
481         // commitCoordinator in preparation for the subsequent three phase commit initiated by
482         // the front-end.
483         commitCoordinator.transactionReady(ready.getTransactionID(), ready.getCohort(),
484                 (MutableCompositeModification) ready.getModification());
485
486         // Return our actor path as we'll handle the three phase commit, except if the Tx client
487         // version < 1 (Helium-1 version). This means the Tx was initiated by a base Helium version
488         // node. In that case, the subsequent 3-phase commit messages won't contain the
489         // transactionId so to maintain backwards compatibility, we create a separate cohort actor
490         // to provide the compatible behavior.
491         if(ready.getTxnClientVersion() < DataStoreVersions.HELIUM_1_VERSION) {
492             LOG.debug("{}: Creating BackwardsCompatibleThreePhaseCommitCohort", persistenceId());
493             ActorRef replyActorPath = getContext().actorOf(BackwardsCompatibleThreePhaseCommitCohort.props(
494                     ready.getTransactionID()));
495
496             ReadyTransactionReply readyTransactionReply =
497                     new ReadyTransactionReply(Serialization.serializedActorPath(replyActorPath));
498             getSender().tell(ready.isReturnSerialized() ? readyTransactionReply.toSerializable() :
499                     readyTransactionReply, getSelf());
500
501         } else {
502
503             getSender().tell(ready.isReturnSerialized() ? READY_TRANSACTION_REPLY.toSerializable() :
504                     READY_TRANSACTION_REPLY, getSelf());
505         }
506     }
507
508     private void handleAbortTransaction(final AbortTransaction abort) {
509         doAbortTransaction(abort.getTransactionID(), getSender());
510     }
511
512     void doAbortTransaction(final String transactionID, final ActorRef sender) {
513         final CohortEntry cohortEntry = commitCoordinator.getCohortEntryIfCurrent(transactionID);
514         if(cohortEntry != null) {
515             LOG.debug("{}: Aborting transaction {}", persistenceId(), transactionID);
516
517             // We don't remove the cached cohort entry here (ie pass false) in case the Tx was
518             // aborted during replication in which case we may still commit locally if replication
519             // succeeds.
520             commitCoordinator.currentTransactionComplete(transactionID, false);
521
522             final ListenableFuture<Void> future = cohortEntry.getCohort().abort();
523             final ActorRef self = getSelf();
524
525             Futures.addCallback(future, new FutureCallback<Void>() {
526                 @Override
527                 public void onSuccess(final Void v) {
528                     shardMBean.incrementAbortTransactionsCount();
529
530                     if(sender != null) {
531                         sender.tell(AbortTransactionReply.INSTANCE.toSerializable(), self);
532                     }
533                 }
534
535                 @Override
536                 public void onFailure(final Throwable t) {
537                     LOG.error("{}: An exception happened during abort", persistenceId(), t);
538
539                     if(sender != null) {
540                         sender.tell(new akka.actor.Status.Failure(t), self);
541                     }
542                 }
543             });
544         }
545     }
546
547     private void handleCreateTransaction(final Object message) {
548         if (isLeader()) {
549             createTransaction(CreateTransaction.fromSerializable(message));
550         } else if (getLeader() != null) {
551             getLeader().forward(message, getContext());
552         } else {
553             getSender().tell(new akka.actor.Status.Failure(new NoShardLeaderException(String.format(
554                 "Could not find leader for shard %s so transaction cannot be created. This typically happens" +
555                 " when the system is coming up or recovering and a leader is being elected. Try again" +
556                 " later.", persistenceId()))), getSelf());
557         }
558     }
559
560     private void closeTransactionChain(final CloseTransactionChain closeTransactionChain) {
561         transactionFactory.closeTransactionChain(closeTransactionChain.getTransactionChainId());
562     }
563
564     private ActorRef createTypedTransactionActor(int transactionType,
565             ShardTransactionIdentifier transactionId, String transactionChainId,
566             short clientVersion ) {
567
568         DOMStoreTransaction transaction = transactionFactory.newTransaction(
569                 TransactionProxy.TransactionType.fromInt(transactionType), transactionId.toString(),
570                 transactionChainId);
571
572         return createShardTransaction(transaction, transactionId, clientVersion);
573     }
574
575     private ActorRef createShardTransaction(DOMStoreTransaction transaction, ShardTransactionIdentifier transactionId,
576                                             short clientVersion){
577         return getContext().actorOf(
578                 ShardTransaction.props(transaction, getSelf(),
579                         schemaContext, datastoreContext, shardMBean,
580                         transactionId.getRemoteTransactionId(), clientVersion)
581                         .withDispatcher(txnDispatcherPath),
582                 transactionId.toString());
583
584     }
585
586     private void createTransaction(CreateTransaction createTransaction) {
587         try {
588             ActorRef transactionActor = createTransaction(createTransaction.getTransactionType(),
589                 createTransaction.getTransactionId(), createTransaction.getTransactionChainId(),
590                 createTransaction.getVersion());
591
592             getSender().tell(new CreateTransactionReply(Serialization.serializedActorPath(transactionActor),
593                     createTransaction.getTransactionId()).toSerializable(), getSelf());
594         } catch (Exception e) {
595             getSender().tell(new akka.actor.Status.Failure(e), getSelf());
596         }
597     }
598
599     private ActorRef createTransaction(int transactionType, String remoteTransactionId,
600             String transactionChainId, short clientVersion) {
601
602
603         ShardTransactionIdentifier transactionId = new ShardTransactionIdentifier(remoteTransactionId);
604
605         if(LOG.isDebugEnabled()) {
606             LOG.debug("{}: Creating transaction : {} ", persistenceId(), transactionId);
607         }
608
609         ActorRef transactionActor = createTypedTransactionActor(transactionType, transactionId,
610                 transactionChainId, clientVersion);
611
612         return transactionActor;
613     }
614
615     private void syncCommitTransaction(final DOMStoreWriteTransaction transaction)
616         throws ExecutionException, InterruptedException {
617         DOMStoreThreePhaseCommitCohort commitCohort = transaction.ready();
618         commitCohort.preCommit().get();
619         commitCohort.commit().get();
620     }
621
622     private void commitWithNewTransaction(final Modification modification) {
623         DOMStoreWriteTransaction tx = store.newWriteOnlyTransaction();
624         modification.apply(tx);
625         try {
626             syncCommitTransaction(tx);
627             shardMBean.incrementCommittedTransactionCount();
628             shardMBean.setLastCommittedTransactionTime(System.currentTimeMillis());
629         } catch (InterruptedException | ExecutionException e) {
630             shardMBean.incrementFailedTransactionsCount();
631             LOG.error("{}: Failed to commit", persistenceId(), e);
632         }
633     }
634
635     private void updateSchemaContext(final UpdateSchemaContext message) {
636         this.schemaContext = message.getSchemaContext();
637         updateSchemaContext(message.getSchemaContext());
638         store.onGlobalContextUpdated(message.getSchemaContext());
639     }
640
641     @VisibleForTesting
642     void updateSchemaContext(final SchemaContext schemaContext) {
643         store.onGlobalContextUpdated(schemaContext);
644     }
645
646     private boolean isMetricsCaptureEnabled() {
647         CommonConfig config = new CommonConfig(getContext().system().settings().config());
648         return config.isMetricCaptureEnabled();
649     }
650
651     @Override
652     protected
653     void startLogRecoveryBatch(final int maxBatchSize) {
654         recoveryCoordinator.startLogRecoveryBatch(maxBatchSize);
655     }
656
657     @Override
658     protected void appendRecoveredLogEntry(final Payload data) {
659         recoveryCoordinator.appendRecoveredLogPayload(data);
660     }
661
662     @Override
663     protected void applyRecoverySnapshot(final byte[] snapshotBytes) {
664         recoveryCoordinator.applyRecoveredSnapshot(snapshotBytes);
665     }
666
667     @Override
668     protected void applyCurrentLogRecoveryBatch() {
669         recoveryCoordinator.applyCurrentLogRecoveryBatch();
670     }
671
672     @Override
673     protected void onRecoveryComplete() {
674         recoveryCoordinator = null;
675
676         //notify shard manager
677         getContext().parent().tell(new ActorInitialized(), getSelf());
678
679         // Being paranoid here - this method should only be called once but just in case...
680         if(txCommitTimeoutCheckSchedule == null) {
681             // Schedule a message to be periodically sent to check if the current in-progress
682             // transaction should be expired and aborted.
683             FiniteDuration period = Duration.create(transactionCommitTimeout / 3, TimeUnit.MILLISECONDS);
684             txCommitTimeoutCheckSchedule = getContext().system().scheduler().schedule(
685                     period, period, getSelf(),
686                     TX_COMMIT_TIMEOUT_CHECK_MESSAGE, getContext().dispatcher(), ActorRef.noSender());
687         }
688     }
689
690     @Override
691     protected void applyState(final ActorRef clientActor, final String identifier, final Object data) {
692
693         if(data instanceof ModificationPayload) {
694             try {
695                 applyModificationToState(clientActor, identifier, ((ModificationPayload) data).getModification());
696             } catch (ClassNotFoundException | IOException e) {
697                 LOG.error("{}: Error extracting ModificationPayload", persistenceId(), e);
698             }
699         }
700         else if (data instanceof CompositeModificationPayload) {
701             Object modification = ((CompositeModificationPayload) data).getModification();
702
703             applyModificationToState(clientActor, identifier, modification);
704         } else if(data instanceof CompositeModificationByteStringPayload ){
705             Object modification = ((CompositeModificationByteStringPayload) data).getModification();
706
707             applyModificationToState(clientActor, identifier, modification);
708         } else {
709             LOG.error("{}: Unknown state received {} Class loader = {} CompositeNodeMod.ClassLoader = {}",
710                     persistenceId(), data, data.getClass().getClassLoader(),
711                     CompositeModificationPayload.class.getClassLoader());
712         }
713     }
714
715     private void applyModificationToState(ActorRef clientActor, String identifier, Object modification) {
716         if(modification == null) {
717             LOG.error(
718                     "{}: modification is null - this is very unexpected, clientActor = {}, identifier = {}",
719                     persistenceId(), identifier, clientActor != null ? clientActor.path().toString() : null);
720         } else if(clientActor == null) {
721             // There's no clientActor to which to send a commit reply so we must be applying
722             // replicated state from the leader.
723             commitWithNewTransaction(MutableCompositeModification.fromSerializable(modification));
724         } else {
725             // This must be the OK to commit after replication consensus.
726             finishCommit(clientActor, identifier);
727         }
728     }
729
730     @Override
731     protected void createSnapshot() {
732         // Create a transaction actor. We are really going to treat the transaction as a worker
733         // so that this actor does not get block building the snapshot. THe transaction actor will
734         // after processing the CreateSnapshot message.
735
736         ActorRef createSnapshotTransaction = createTransaction(
737                 TransactionProxy.TransactionType.READ_ONLY.ordinal(),
738                 "createSnapshot" + ++createSnapshotTransactionCounter, "",
739                 DataStoreVersions.CURRENT_VERSION);
740
741         createSnapshotTransaction.tell(CreateSnapshot.INSTANCE, self());
742     }
743
744     @VisibleForTesting
745     @Override
746     protected void applySnapshot(final byte[] snapshotBytes) {
747         // Since this will be done only on Recovery or when this actor is a Follower
748         // we can safely commit everything in here. We not need to worry about event notifications
749         // as they would have already been disabled on the follower
750
751         LOG.info("{}: Applying snapshot", persistenceId());
752         try {
753             DOMStoreWriteTransaction transaction = store.newWriteOnlyTransaction();
754
755             NormalizedNode<?, ?> node = SerializationUtils.deserializeNormalizedNode(snapshotBytes);
756
757             // delete everything first
758             transaction.delete(DATASTORE_ROOT);
759
760             // Add everything from the remote node back
761             transaction.write(DATASTORE_ROOT, node);
762             syncCommitTransaction(transaction);
763         } catch (InterruptedException | ExecutionException e) {
764             LOG.error("{}: An exception occurred when applying snapshot", persistenceId(), e);
765         } finally {
766             LOG.info("{}: Done applying snapshot", persistenceId());
767         }
768     }
769
770     @Override
771     protected void onStateChanged() {
772         boolean isLeader = isLeader();
773         changeSupport.onLeadershipChange(isLeader);
774         treeChangeSupport.onLeadershipChange(isLeader);
775
776         // If this actor is no longer the leader close all the transaction chains
777         if (!isLeader) {
778             if(LOG.isDebugEnabled()) {
779                 LOG.debug(
780                     "{}: onStateChanged: Closing all transaction chains because shard {} is no longer the leader",
781                     persistenceId(), getId());
782             }
783
784             transactionFactory.closeAllTransactionChains();
785         }
786     }
787
788     @Override
789     public String persistenceId() {
790         return this.name;
791     }
792
793     @VisibleForTesting
794     ShardCommitCoordinator getCommitCoordinator() {
795         return commitCoordinator;
796     }
797
798
799     private static class ShardCreator implements Creator<Shard> {
800
801         private static final long serialVersionUID = 1L;
802
803         final ShardIdentifier name;
804         final Map<String, String> peerAddresses;
805         final DatastoreContext datastoreContext;
806         final SchemaContext schemaContext;
807
808         ShardCreator(final ShardIdentifier name, final Map<String, String> peerAddresses,
809                 final DatastoreContext datastoreContext, final SchemaContext schemaContext) {
810             this.name = name;
811             this.peerAddresses = peerAddresses;
812             this.datastoreContext = datastoreContext;
813             this.schemaContext = schemaContext;
814         }
815
816         @Override
817         public Shard create() throws Exception {
818             return new Shard(name, peerAddresses, datastoreContext, schemaContext);
819         }
820     }
821
822     @VisibleForTesting
823     public InMemoryDOMDataStore getDataStore() {
824         return store;
825     }
826
827     @VisibleForTesting
828     ShardStats getShardMBean() {
829         return shardMBean;
830     }
831 }