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