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