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