Lower Shard.DEFAULT_NAME visibility
[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     @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 CompositeModificationByteStringPayload(cohortEntry.getModification().toSerializable()));
332             }
333         } catch (InterruptedException | ExecutionException 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(COMMIT_TRANSACTION_REPLY, 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(COMMIT_TRANSACTION_REPLY, 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() < CreateTransaction.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(new AbortTransactionReply().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.getNormalizedNodeByteString(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, int clientVersion ) {
505
506         DOMStoreTransactionFactory factory = store;
507
508         if(!transactionChainId.isEmpty()) {
509             factory = transactionChains.get(transactionChainId);
510             if(factory == null){
511                 DOMStoreTransactionChain transactionChain = store.createTransactionChain();
512                 transactionChains.put(transactionChainId, transactionChain);
513                 factory = transactionChain;
514             }
515         }
516
517         if(this.schemaContext == null) {
518             throw new IllegalStateException("SchemaContext is not set");
519         }
520
521         if (transactionType == TransactionProxy.TransactionType.READ_ONLY.ordinal()) {
522
523             shardMBean.incrementReadOnlyTransactionCount();
524
525             return getContext().actorOf(
526                 ShardTransaction.props(factory.newReadOnlyTransaction(), getSelf(),
527                         schemaContext,datastoreContext, shardMBean,
528                         transactionId.getRemoteTransactionId(), clientVersion),
529                         transactionId.toString());
530
531         } else if (transactionType == TransactionProxy.TransactionType.READ_WRITE.ordinal()) {
532
533             shardMBean.incrementReadWriteTransactionCount();
534
535             return getContext().actorOf(
536                 ShardTransaction.props(factory.newReadWriteTransaction(), getSelf(),
537                         schemaContext, datastoreContext, shardMBean,
538                         transactionId.getRemoteTransactionId(), clientVersion),
539                         transactionId.toString());
540
541
542         } else if (transactionType == TransactionProxy.TransactionType.WRITE_ONLY.ordinal()) {
543
544             shardMBean.incrementWriteOnlyTransactionCount();
545
546             return getContext().actorOf(
547                 ShardTransaction.props(factory.newWriteOnlyTransaction(), getSelf(),
548                         schemaContext, datastoreContext, shardMBean,
549                         transactionId.getRemoteTransactionId(), clientVersion),
550                         transactionId.toString());
551         } else {
552             throw new IllegalArgumentException(
553                 "Shard="+name + ":CreateTransaction message has unidentified transaction type="
554                     + transactionType);
555         }
556     }
557
558     private void createTransaction(CreateTransaction createTransaction) {
559         try {
560             ActorRef transactionActor = createTransaction(createTransaction.getTransactionType(),
561                 createTransaction.getTransactionId(), createTransaction.getTransactionChainId(),
562                 createTransaction.getVersion());
563
564             getSender().tell(new CreateTransactionReply(Serialization.serializedActorPath(transactionActor),
565                     createTransaction.getTransactionId()).toSerializable(), getSelf());
566         } catch (Exception e) {
567             getSender().tell(new akka.actor.Status.Failure(e), getSelf());
568         }
569     }
570
571     private ActorRef createTransaction(int transactionType, String remoteTransactionId,
572             String transactionChainId, int clientVersion) {
573
574         ShardTransactionIdentifier transactionId =
575             ShardTransactionIdentifier.builder()
576                 .remoteTransactionId(remoteTransactionId)
577                 .build();
578
579         if(LOG.isDebugEnabled()) {
580             LOG.debug("Creating transaction : {} ", transactionId);
581         }
582
583         ActorRef transactionActor = createTypedTransactionActor(transactionType, transactionId,
584                 transactionChainId, clientVersion);
585
586         return transactionActor;
587     }
588
589     private void syncCommitTransaction(final DOMStoreWriteTransaction transaction)
590         throws ExecutionException, InterruptedException {
591         DOMStoreThreePhaseCommitCohort commitCohort = transaction.ready();
592         commitCohort.preCommit().get();
593         commitCohort.commit().get();
594     }
595
596     private void commitWithNewTransaction(final Modification modification) {
597         DOMStoreWriteTransaction tx = store.newWriteOnlyTransaction();
598         modification.apply(tx);
599         try {
600             syncCommitTransaction(tx);
601             shardMBean.incrementCommittedTransactionCount();
602             shardMBean.setLastCommittedTransactionTime(System.currentTimeMillis());
603         } catch (InterruptedException | ExecutionException e) {
604             shardMBean.incrementFailedTransactionsCount();
605             LOG.error(e, "Failed to commit");
606         }
607     }
608
609     private void updateSchemaContext(final UpdateSchemaContext message) {
610         this.schemaContext = message.getSchemaContext();
611         updateSchemaContext(message.getSchemaContext());
612         store.onGlobalContextUpdated(message.getSchemaContext());
613     }
614
615     @VisibleForTesting
616     void updateSchemaContext(final SchemaContext schemaContext) {
617         store.onGlobalContextUpdated(schemaContext);
618     }
619
620     private void registerChangeListener(final RegisterChangeListener registerChangeListener) {
621
622         LOG.debug("registerDataChangeListener for {}", registerChangeListener.getPath());
623
624         ListenerRegistration<AsyncDataChangeListener<YangInstanceIdentifier,
625                                                      NormalizedNode<?, ?>>> registration;
626         if(isLeader()) {
627             registration = doChangeListenerRegistration(registerChangeListener);
628         } else {
629             LOG.debug("Shard is not the leader - delaying registration");
630
631             DelayedListenerRegistration delayedReg =
632                     new DelayedListenerRegistration(registerChangeListener);
633             delayedListenerRegistrations.add(delayedReg);
634             registration = delayedReg;
635         }
636
637         ActorRef listenerRegistration = getContext().actorOf(
638                 DataChangeListenerRegistration.props(registration));
639
640         LOG.debug("registerDataChangeListener sending reply, listenerRegistrationPath = {} ",
641                     listenerRegistration.path());
642
643         getSender().tell(new RegisterChangeListenerReply(listenerRegistration.path()), getSelf());
644     }
645
646     private ListenerRegistration<AsyncDataChangeListener<YangInstanceIdentifier,
647                                                NormalizedNode<?, ?>>> doChangeListenerRegistration(
648             final RegisterChangeListener registerChangeListener) {
649
650         ActorSelection dataChangeListenerPath = getContext().system().actorSelection(
651                 registerChangeListener.getDataChangeListenerPath());
652
653         // Notify the listener if notifications should be enabled or not
654         // If this shard is the leader then it will enable notifications else
655         // it will not
656         dataChangeListenerPath.tell(new EnableNotification(true), getSelf());
657
658         // Now store a reference to the data change listener so it can be notified
659         // at a later point if notifications should be enabled or disabled
660         dataChangeListeners.add(dataChangeListenerPath);
661
662         AsyncDataChangeListener<YangInstanceIdentifier, NormalizedNode<?, ?>> listener =
663                 new DataChangeListenerProxy(schemaContext, dataChangeListenerPath);
664
665         LOG.debug("Registering for path {}", registerChangeListener.getPath());
666
667         return store.registerChangeListener(registerChangeListener.getPath(), listener,
668                 registerChangeListener.getScope());
669     }
670
671     private boolean isMetricsCaptureEnabled(){
672         CommonConfig config = new CommonConfig(getContext().system().settings().config());
673         return config.isMetricCaptureEnabled();
674     }
675
676     @Override
677     protected
678     void startLogRecoveryBatch(final int maxBatchSize) {
679         currentLogRecoveryBatch = Lists.newArrayListWithCapacity(maxBatchSize);
680
681         if(LOG.isDebugEnabled()) {
682             LOG.debug("{} : starting log recovery batch with max size {}", persistenceId(), maxBatchSize);
683         }
684     }
685
686     @Override
687     protected void appendRecoveredLogEntry(final Payload data) {
688         if (data instanceof CompositeModificationPayload) {
689             currentLogRecoveryBatch.add(((CompositeModificationPayload) data).getModification());
690         } else if (data instanceof CompositeModificationByteStringPayload) {
691             currentLogRecoveryBatch.add(((CompositeModificationByteStringPayload) data).getModification());
692         } else {
693             LOG.error("Unknown state received {} during recovery", data);
694         }
695     }
696
697     @Override
698     protected void applyRecoverySnapshot(final ByteString snapshot) {
699         if(recoveryCoordinator == null) {
700             recoveryCoordinator = new ShardRecoveryCoordinator(persistenceId(), schemaContext);
701         }
702
703         recoveryCoordinator.submit(snapshot, store.newWriteOnlyTransaction());
704
705         if(LOG.isDebugEnabled()) {
706             LOG.debug("{} : submitted recovery sbapshot", persistenceId());
707         }
708     }
709
710     @Override
711     protected void applyCurrentLogRecoveryBatch() {
712         if(recoveryCoordinator == null) {
713             recoveryCoordinator = new ShardRecoveryCoordinator(persistenceId(), schemaContext);
714         }
715
716         recoveryCoordinator.submit(currentLogRecoveryBatch, store.newWriteOnlyTransaction());
717
718         if(LOG.isDebugEnabled()) {
719             LOG.debug("{} : submitted log recovery batch with size {}", persistenceId(),
720                     currentLogRecoveryBatch.size());
721         }
722     }
723
724     @Override
725     protected void onRecoveryComplete() {
726         if(recoveryCoordinator != null) {
727             Collection<DOMStoreWriteTransaction> txList = recoveryCoordinator.getTransactions();
728
729             if(LOG.isDebugEnabled()) {
730                 LOG.debug("{} : recovery complete - committing {} Tx's", persistenceId(), txList.size());
731             }
732
733             for(DOMStoreWriteTransaction tx: txList) {
734                 try {
735                     syncCommitTransaction(tx);
736                     shardMBean.incrementCommittedTransactionCount();
737                 } catch (InterruptedException | ExecutionException e) {
738                     shardMBean.incrementFailedTransactionsCount();
739                     LOG.error(e, "Failed to commit");
740                 }
741             }
742         }
743
744         recoveryCoordinator = null;
745         currentLogRecoveryBatch = null;
746         updateJournalStats();
747
748         //notify shard manager
749         getContext().parent().tell(new ActorInitialized(), getSelf());
750
751         // Being paranoid here - this method should only be called once but just in case...
752         if(txCommitTimeoutCheckSchedule == null) {
753             // Schedule a message to be periodically sent to check if the current in-progress
754             // transaction should be expired and aborted.
755             FiniteDuration period = Duration.create(transactionCommitTimeout / 3, TimeUnit.MILLISECONDS);
756             txCommitTimeoutCheckSchedule = getContext().system().scheduler().schedule(
757                     period, period, getSelf(),
758                     TX_COMMIT_TIMEOUT_CHECK_MESSAGE, getContext().dispatcher(), ActorRef.noSender());
759         }
760     }
761
762     @Override
763     protected void applyState(final ActorRef clientActor, final String identifier, final Object data) {
764
765         if (data instanceof CompositeModificationPayload) {
766             Object modification = ((CompositeModificationPayload) data).getModification();
767
768             applyModificationToState(clientActor, identifier, modification);
769         } else if(data instanceof CompositeModificationByteStringPayload ){
770             Object modification = ((CompositeModificationByteStringPayload) data).getModification();
771
772             applyModificationToState(clientActor, identifier, modification);
773
774         } else {
775             LOG.error("Unknown state received {} Class loader = {} CompositeNodeMod.ClassLoader = {}",
776                     data, data.getClass().getClassLoader(),
777                     CompositeModificationPayload.class.getClassLoader());
778         }
779
780         updateJournalStats();
781
782     }
783
784     private void applyModificationToState(ActorRef clientActor, String identifier, Object modification) {
785         if(modification == null) {
786             LOG.error(
787                     "modification is null - this is very unexpected, clientActor = {}, identifier = {}",
788                     identifier, clientActor != null ? clientActor.path().toString() : null);
789         } else if(clientActor == null) {
790             // There's no clientActor to which to send a commit reply so we must be applying
791             // replicated state from the leader.
792             commitWithNewTransaction(MutableCompositeModification.fromSerializable(
793                     modification, schemaContext));
794         } else {
795             // This must be the OK to commit after replication consensus.
796             finishCommit(clientActor, identifier);
797         }
798     }
799
800     private void updateJournalStats() {
801         ReplicatedLogEntry lastLogEntry = getLastLogEntry();
802
803         if (lastLogEntry != null) {
804             shardMBean.setLastLogIndex(lastLogEntry.getIndex());
805             shardMBean.setLastLogTerm(lastLogEntry.getTerm());
806         }
807
808         shardMBean.setCommitIndex(getCommitIndex());
809         shardMBean.setLastApplied(getLastApplied());
810         shardMBean.setInMemoryJournalDataSize(getRaftActorContext().getReplicatedLog().dataSize());
811     }
812
813     @Override
814     protected void createSnapshot() {
815         if (createSnapshotTransaction == null) {
816
817             // Create a transaction. We are really going to treat the transaction as a worker
818             // so that this actor does not get block building the snapshot
819             createSnapshotTransaction = createTransaction(
820                 TransactionProxy.TransactionType.READ_ONLY.ordinal(),
821                 "createSnapshot" + ++createSnapshotTransactionCounter, "",
822                 CreateTransaction.CURRENT_VERSION);
823
824             createSnapshotTransaction.tell(
825                 new ReadData(YangInstanceIdentifier.builder().build()).toSerializable(), self());
826
827         }
828     }
829
830     @VisibleForTesting
831     @Override
832     protected void applySnapshot(final ByteString snapshot) {
833         // Since this will be done only on Recovery or when this actor is a Follower
834         // we can safely commit everything in here. We not need to worry about event notifications
835         // as they would have already been disabled on the follower
836
837         LOG.info("Applying snapshot");
838         try {
839             DOMStoreWriteTransaction transaction = store.newWriteOnlyTransaction();
840             NormalizedNodeMessages.Node serializedNode = NormalizedNodeMessages.Node.parseFrom(snapshot);
841             NormalizedNode<?, ?> node = new NormalizedNodeToNodeCodec(schemaContext)
842                 .decode(serializedNode);
843
844             // delete everything first
845             transaction.delete(YangInstanceIdentifier.builder().build());
846
847             // Add everything from the remote node back
848             transaction.write(YangInstanceIdentifier.builder().build(), node);
849             syncCommitTransaction(transaction);
850         } catch (InvalidProtocolBufferException | InterruptedException | ExecutionException e) {
851             LOG.error(e, "An exception occurred when applying snapshot");
852         } finally {
853             LOG.info("Done applying snapshot");
854         }
855     }
856
857     @Override
858     protected void onStateChanged() {
859         boolean isLeader = isLeader();
860         for (ActorSelection dataChangeListener : dataChangeListeners) {
861             dataChangeListener.tell(new EnableNotification(isLeader), getSelf());
862         }
863
864         if(isLeader) {
865             for(DelayedListenerRegistration reg: delayedListenerRegistrations) {
866                 if(!reg.isClosed()) {
867                     reg.setDelegate(doChangeListenerRegistration(reg.getRegisterChangeListener()));
868                 }
869             }
870
871             delayedListenerRegistrations.clear();
872         }
873
874         shardMBean.setRaftState(getRaftState().name());
875         shardMBean.setCurrentTerm(getCurrentTerm());
876
877         // If this actor is no longer the leader close all the transaction chains
878         if(!isLeader){
879             for(Map.Entry<String, DOMStoreTransactionChain> entry : transactionChains.entrySet()){
880                 if(LOG.isDebugEnabled()) {
881                     LOG.debug(
882                         "onStateChanged: Closing transaction chain {} because shard {} is no longer the leader",
883                         entry.getKey(), getId());
884                 }
885                 entry.getValue().close();
886             }
887
888             transactionChains.clear();
889         }
890     }
891
892     @Override
893     protected DataPersistenceProvider persistence() {
894         return dataPersistenceProvider;
895     }
896
897     @Override protected void onLeaderChanged(final String oldLeader, final String newLeader) {
898         shardMBean.setLeader(newLeader);
899     }
900
901     @Override public String persistenceId() {
902         return this.name.toString();
903     }
904
905     @VisibleForTesting
906     DataPersistenceProvider getDataPersistenceProvider() {
907         return dataPersistenceProvider;
908     }
909
910     private static class ShardCreator implements Creator<Shard> {
911
912         private static final long serialVersionUID = 1L;
913
914         final ShardIdentifier name;
915         final Map<ShardIdentifier, String> peerAddresses;
916         final DatastoreContext datastoreContext;
917         final SchemaContext schemaContext;
918
919         ShardCreator(final ShardIdentifier name, final Map<ShardIdentifier, String> peerAddresses,
920                 final DatastoreContext datastoreContext, final SchemaContext schemaContext) {
921             this.name = name;
922             this.peerAddresses = peerAddresses;
923             this.datastoreContext = datastoreContext;
924             this.schemaContext = schemaContext;
925         }
926
927         @Override
928         public Shard create() throws Exception {
929             return new Shard(name, peerAddresses, datastoreContext, schemaContext);
930         }
931     }
932
933     @VisibleForTesting
934     InMemoryDOMDataStore getDataStore() {
935         return store;
936     }
937
938     @VisibleForTesting
939     ShardStats getShardMBean() {
940         return shardMBean;
941     }
942
943     private static class DelayedListenerRegistration implements
944         ListenerRegistration<AsyncDataChangeListener<YangInstanceIdentifier, NormalizedNode<?, ?>>> {
945
946         private volatile boolean closed;
947
948         private final RegisterChangeListener registerChangeListener;
949
950         private volatile ListenerRegistration<AsyncDataChangeListener<YangInstanceIdentifier,
951                                                              NormalizedNode<?, ?>>> delegate;
952
953         DelayedListenerRegistration(final RegisterChangeListener registerChangeListener) {
954             this.registerChangeListener = registerChangeListener;
955         }
956
957         void setDelegate( final ListenerRegistration<AsyncDataChangeListener<YangInstanceIdentifier,
958                                             NormalizedNode<?, ?>>> registration) {
959             this.delegate = registration;
960         }
961
962         boolean isClosed() {
963             return closed;
964         }
965
966         RegisterChangeListener getRegisterChangeListener() {
967             return registerChangeListener;
968         }
969
970         @Override
971         public AsyncDataChangeListener<YangInstanceIdentifier, NormalizedNode<?, ?>> getInstance() {
972             return delegate != null ? delegate.getInstance() : null;
973         }
974
975         @Override
976         public void close() {
977             closed = true;
978             if(delegate != null) {
979                 delegate.close();
980             }
981         }
982     }
983 }