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