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