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