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