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