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