Merge "BUG 2849 : Reduce sending of duplicate replication messages"
[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
378             // or if cohortEntry has no modifications
379             // we can apply modification to the state immediately
380             if((!hasFollowers() && !persistence().isRecoveryApplicable()) || (!cohortEntry.hasModifications())){
381                 applyModificationToState(getSender(), transactionID, cohortEntry.getModification());
382             } else {
383                 Shard.this.persistData(getSender(), transactionID,
384                         new ModificationPayload(cohortEntry.getModification()));
385             }
386         } catch (Exception e) {
387             LOG.error("{} An exception occurred while preCommitting transaction {}",
388                     persistenceId(), cohortEntry.getTransactionID(), e);
389             shardMBean.incrementFailedTransactionsCount();
390             getSender().tell(new akka.actor.Status.Failure(e), getSelf());
391         }
392
393         cohortEntry.updateLastAccessTime();
394     }
395
396     private void finishCommit(@Nonnull final ActorRef sender, final @Nonnull String transactionID) {
397         // With persistence enabled, this method is called via applyState by the leader strategy
398         // after the commit has been replicated to a majority of the followers.
399
400         CohortEntry cohortEntry = commitCoordinator.getCohortEntryIfCurrent(transactionID);
401         if(cohortEntry == null) {
402             // The transaction is no longer the current commit. This can happen if the transaction
403             // was aborted prior, most likely due to timeout in the front-end. We need to finish
404             // committing the transaction though since it was successfully persisted and replicated
405             // however we can't use the original cohort b/c it was already preCommitted and may
406             // conflict with the current commit or may have been aborted so we commit with a new
407             // transaction.
408             cohortEntry = commitCoordinator.getAndRemoveCohortEntry(transactionID);
409             if(cohortEntry != null) {
410                 commitWithNewTransaction(cohortEntry.getModification());
411                 sender.tell(CommitTransactionReply.INSTANCE.toSerializable(), getSelf());
412             } else {
413                 // This really shouldn't happen - it likely means that persistence or replication
414                 // took so long to complete such that the cohort entry was expired from the cache.
415                 IllegalStateException ex = new IllegalStateException(
416                         String.format("%s: Could not finish committing transaction %s - no CohortEntry found",
417                                 persistenceId(), transactionID));
418                 LOG.error(ex.getMessage());
419                 sender.tell(new akka.actor.Status.Failure(ex), getSelf());
420             }
421
422             return;
423         }
424
425         LOG.debug("{}: Finishing commit for transaction {}", persistenceId(), cohortEntry.getTransactionID());
426
427         try {
428             // We block on the future here so we don't have to worry about possibly accessing our
429             // state on a different thread outside of our dispatcher. Also, the data store
430             // currently uses a same thread executor anyway.
431             cohortEntry.getCohort().commit().get();
432
433             sender.tell(CommitTransactionReply.INSTANCE.toSerializable(), getSelf());
434
435             shardMBean.incrementCommittedTransactionCount();
436             shardMBean.setLastCommittedTransactionTime(System.currentTimeMillis());
437
438         } catch (Exception e) {
439             sender.tell(new akka.actor.Status.Failure(e), getSelf());
440
441             LOG.error("{}, An exception occurred while committing transaction {}", persistenceId(),
442                     transactionID, e);
443             shardMBean.incrementFailedTransactionsCount();
444         } finally {
445             commitCoordinator.currentTransactionComplete(transactionID, true);
446         }
447     }
448
449     private void handleCanCommitTransaction(final CanCommitTransaction canCommit) {
450         LOG.debug("{}: Can committing transaction {}", persistenceId(), canCommit.getTransactionID());
451         commitCoordinator.handleCanCommit(canCommit, getSender(), self());
452     }
453
454     private void handleForwardedReadyTransaction(ForwardedReadyTransaction ready) {
455         LOG.debug("{}: Readying transaction {}, client version {}", persistenceId(),
456                 ready.getTransactionID(), ready.getTxnClientVersion());
457
458         // This message is forwarded by the ShardTransaction on ready. We cache the cohort in the
459         // commitCoordinator in preparation for the subsequent three phase commit initiated by
460         // the front-end.
461         commitCoordinator.transactionReady(ready.getTransactionID(), ready.getCohort(),
462                 ready.getModification());
463
464         // Return our actor path as we'll handle the three phase commit, except if the Tx client
465         // version < 1 (Helium-1 version). This means the Tx was initiated by a base Helium version
466         // node. In that case, the subsequent 3-phase commit messages won't contain the
467         // transactionId so to maintain backwards compatibility, we create a separate cohort actor
468         // to provide the compatible behavior.
469         if(ready.getTxnClientVersion() < DataStoreVersions.HELIUM_1_VERSION) {
470             LOG.debug("{}: Creating BackwardsCompatibleThreePhaseCommitCohort", persistenceId());
471             ActorRef replyActorPath = getContext().actorOf(BackwardsCompatibleThreePhaseCommitCohort.props(
472                     ready.getTransactionID()));
473
474             ReadyTransactionReply readyTransactionReply =
475                     new ReadyTransactionReply(Serialization.serializedActorPath(replyActorPath));
476             getSender().tell(ready.isReturnSerialized() ? readyTransactionReply.toSerializable() :
477                     readyTransactionReply, getSelf());
478
479         } else {
480
481             getSender().tell(ready.isReturnSerialized() ? READY_TRANSACTION_REPLY.toSerializable() :
482                     READY_TRANSACTION_REPLY, getSelf());
483         }
484     }
485
486     private void handleAbortTransaction(final AbortTransaction abort) {
487         doAbortTransaction(abort.getTransactionID(), getSender());
488     }
489
490     void doAbortTransaction(final String transactionID, final ActorRef sender) {
491         final CohortEntry cohortEntry = commitCoordinator.getCohortEntryIfCurrent(transactionID);
492         if(cohortEntry != null) {
493             LOG.debug("{}: Aborting transaction {}", persistenceId(), transactionID);
494
495             // We don't remove the cached cohort entry here (ie pass false) in case the Tx was
496             // aborted during replication in which case we may still commit locally if replication
497             // succeeds.
498             commitCoordinator.currentTransactionComplete(transactionID, false);
499
500             final ListenableFuture<Void> future = cohortEntry.getCohort().abort();
501             final ActorRef self = getSelf();
502
503             Futures.addCallback(future, new FutureCallback<Void>() {
504                 @Override
505                 public void onSuccess(final Void v) {
506                     shardMBean.incrementAbortTransactionsCount();
507
508                     if(sender != null) {
509                         sender.tell(AbortTransactionReply.INSTANCE.toSerializable(), self);
510                     }
511                 }
512
513                 @Override
514                 public void onFailure(final Throwable t) {
515                     LOG.error("{}: An exception happened during abort", persistenceId(), t);
516
517                     if(sender != null) {
518                         sender.tell(new akka.actor.Status.Failure(t), self);
519                     }
520                 }
521             });
522         }
523     }
524
525     private void handleCreateTransaction(final Object message) {
526         if (isLeader()) {
527             createTransaction(CreateTransaction.fromSerializable(message));
528         } else if (getLeader() != null) {
529             getLeader().forward(message, getContext());
530         } else {
531             getSender().tell(new akka.actor.Status.Failure(new NoShardLeaderException(String.format(
532                 "Could not find leader for shard %s so transaction cannot be created. This typically happens" +
533                 " when the system is coming up or recovering and a leader is being elected. Try again" +
534                 " later.", persistenceId()))), getSelf());
535         }
536     }
537
538     private void closeTransactionChain(final CloseTransactionChain closeTransactionChain) {
539         DOMStoreTransactionChain chain =
540             transactionChains.remove(closeTransactionChain.getTransactionChainId());
541
542         if(chain != null) {
543             chain.close();
544         }
545     }
546
547     private ActorRef createTypedTransactionActor(int transactionType,
548             ShardTransactionIdentifier transactionId, String transactionChainId,
549             short clientVersion ) {
550
551         DOMStoreTransactionFactory factory = store;
552
553         if(!transactionChainId.isEmpty()) {
554             factory = transactionChains.get(transactionChainId);
555             if(factory == null){
556                 DOMStoreTransactionChain transactionChain = store.createTransactionChain();
557                 transactionChains.put(transactionChainId, transactionChain);
558                 factory = transactionChain;
559             }
560         }
561
562         if(this.schemaContext == null) {
563             throw new IllegalStateException("SchemaContext is not set");
564         }
565
566         if (transactionType == TransactionProxy.TransactionType.WRITE_ONLY.ordinal()) {
567
568             shardMBean.incrementWriteOnlyTransactionCount();
569
570             return createShardTransaction(factory.newWriteOnlyTransaction(), transactionId, clientVersion);
571
572         } else if (transactionType == TransactionProxy.TransactionType.READ_WRITE.ordinal()) {
573
574             shardMBean.incrementReadWriteTransactionCount();
575
576             return createShardTransaction(factory.newReadWriteTransaction(), transactionId, clientVersion);
577
578         } else if (transactionType == TransactionProxy.TransactionType.READ_ONLY.ordinal()) {
579
580             shardMBean.incrementReadOnlyTransactionCount();
581
582             return createShardTransaction(factory.newReadOnlyTransaction(), transactionId, clientVersion);
583
584         } else {
585             throw new IllegalArgumentException(
586                 "Shard="+name + ":CreateTransaction message has unidentified transaction type="
587                     + transactionType);
588         }
589     }
590
591     private ActorRef createShardTransaction(DOMStoreTransaction transaction, ShardTransactionIdentifier transactionId,
592                                             short clientVersion){
593         return getContext().actorOf(
594                 ShardTransaction.props(transaction, getSelf(),
595                         schemaContext, datastoreContext, shardMBean,
596                         transactionId.getRemoteTransactionId(), clientVersion)
597                         .withDispatcher(txnDispatcherPath),
598                 transactionId.toString());
599
600     }
601
602     private void createTransaction(CreateTransaction createTransaction) {
603         try {
604             ActorRef transactionActor = createTransaction(createTransaction.getTransactionType(),
605                 createTransaction.getTransactionId(), createTransaction.getTransactionChainId(),
606                 createTransaction.getVersion());
607
608             getSender().tell(new CreateTransactionReply(Serialization.serializedActorPath(transactionActor),
609                     createTransaction.getTransactionId()).toSerializable(), getSelf());
610         } catch (Exception e) {
611             getSender().tell(new akka.actor.Status.Failure(e), getSelf());
612         }
613     }
614
615     private ActorRef createTransaction(int transactionType, String remoteTransactionId,
616             String transactionChainId, short clientVersion) {
617
618
619         ShardTransactionIdentifier transactionId = new ShardTransactionIdentifier(remoteTransactionId);
620
621         if(LOG.isDebugEnabled()) {
622             LOG.debug("{}: Creating transaction : {} ", persistenceId(), transactionId);
623         }
624
625         ActorRef transactionActor = createTypedTransactionActor(transactionType, transactionId,
626                 transactionChainId, clientVersion);
627
628         return transactionActor;
629     }
630
631     private void syncCommitTransaction(final DOMStoreWriteTransaction transaction)
632         throws ExecutionException, InterruptedException {
633         DOMStoreThreePhaseCommitCohort commitCohort = transaction.ready();
634         commitCohort.preCommit().get();
635         commitCohort.commit().get();
636     }
637
638     private void commitWithNewTransaction(final Modification modification) {
639         DOMStoreWriteTransaction tx = store.newWriteOnlyTransaction();
640         modification.apply(tx);
641         try {
642             syncCommitTransaction(tx);
643             shardMBean.incrementCommittedTransactionCount();
644             shardMBean.setLastCommittedTransactionTime(System.currentTimeMillis());
645         } catch (InterruptedException | ExecutionException e) {
646             shardMBean.incrementFailedTransactionsCount();
647             LOG.error("{}: Failed to commit", persistenceId(), e);
648         }
649     }
650
651     private void updateSchemaContext(final UpdateSchemaContext message) {
652         this.schemaContext = message.getSchemaContext();
653         updateSchemaContext(message.getSchemaContext());
654         store.onGlobalContextUpdated(message.getSchemaContext());
655     }
656
657     @VisibleForTesting
658     void updateSchemaContext(final SchemaContext schemaContext) {
659         store.onGlobalContextUpdated(schemaContext);
660     }
661
662     private void registerChangeListener(final RegisterChangeListener registerChangeListener) {
663
664         LOG.debug("{}: registerDataChangeListener for {}", persistenceId(), registerChangeListener.getPath());
665
666         ListenerRegistration<AsyncDataChangeListener<YangInstanceIdentifier,
667                                                      NormalizedNode<?, ?>>> registration;
668         if(isLeader()) {
669             registration = doChangeListenerRegistration(registerChangeListener);
670         } else {
671             LOG.debug("{}: Shard is not the leader - delaying registration", persistenceId());
672
673             DelayedListenerRegistration delayedReg =
674                     new DelayedListenerRegistration(registerChangeListener);
675             delayedListenerRegistrations.add(delayedReg);
676             registration = delayedReg;
677         }
678
679         ActorRef listenerRegistration = getContext().actorOf(
680                 DataChangeListenerRegistration.props(registration));
681
682         LOG.debug("{}: registerDataChangeListener sending reply, listenerRegistrationPath = {} ",
683                 persistenceId(), listenerRegistration.path());
684
685         getSender().tell(new RegisterChangeListenerReply(listenerRegistration.path()), getSelf());
686     }
687
688     private ListenerRegistration<AsyncDataChangeListener<YangInstanceIdentifier,
689                                                NormalizedNode<?, ?>>> doChangeListenerRegistration(
690             final RegisterChangeListener registerChangeListener) {
691
692         ActorSelection dataChangeListenerPath = getContext().system().actorSelection(
693                 registerChangeListener.getDataChangeListenerPath());
694
695         // Notify the listener if notifications should be enabled or not
696         // If this shard is the leader then it will enable notifications else
697         // it will not
698         dataChangeListenerPath.tell(new EnableNotification(true), getSelf());
699
700         // Now store a reference to the data change listener so it can be notified
701         // at a later point if notifications should be enabled or disabled
702         dataChangeListeners.add(dataChangeListenerPath);
703
704         AsyncDataChangeListener<YangInstanceIdentifier, NormalizedNode<?, ?>> listener =
705                 new DataChangeListenerProxy(dataChangeListenerPath);
706
707         LOG.debug("{}: Registering for path {}", persistenceId(), registerChangeListener.getPath());
708
709         return store.registerChangeListener(registerChangeListener.getPath(), listener,
710                 registerChangeListener.getScope());
711     }
712
713     private boolean isMetricsCaptureEnabled(){
714         CommonConfig config = new CommonConfig(getContext().system().settings().config());
715         return config.isMetricCaptureEnabled();
716     }
717
718     @Override
719     protected
720     void startLogRecoveryBatch(final int maxBatchSize) {
721         currentLogRecoveryBatch = Lists.newArrayListWithCapacity(maxBatchSize);
722
723         if(LOG.isDebugEnabled()) {
724             LOG.debug("{}: starting log recovery batch with max size {}", persistenceId(), maxBatchSize);
725         }
726     }
727
728     @Override
729     protected void appendRecoveredLogEntry(final Payload data) {
730         if(data instanceof ModificationPayload) {
731             try {
732                 currentLogRecoveryBatch.add(((ModificationPayload) data).getModification());
733             } catch (ClassNotFoundException | IOException e) {
734                 LOG.error("{}: Error extracting ModificationPayload", persistenceId(), e);
735             }
736         } else if (data instanceof CompositeModificationPayload) {
737             currentLogRecoveryBatch.add(((CompositeModificationPayload) data).getModification());
738         } else if (data instanceof CompositeModificationByteStringPayload) {
739             currentLogRecoveryBatch.add(((CompositeModificationByteStringPayload) data).getModification());
740         } else {
741             LOG.error("{}: Unknown state received {} during recovery", persistenceId(), data);
742         }
743     }
744
745     @Override
746     protected void applyRecoverySnapshot(final byte[] snapshotBytes) {
747         if(recoveryCoordinator == null) {
748             recoveryCoordinator = new ShardRecoveryCoordinator(persistenceId(), schemaContext,
749                     LOG, name.toString());
750         }
751
752         recoveryCoordinator.submit(snapshotBytes, store.newWriteOnlyTransaction());
753
754         if(LOG.isDebugEnabled()) {
755             LOG.debug("{}: submitted recovery sbapshot", persistenceId());
756         }
757     }
758
759     @Override
760     protected void applyCurrentLogRecoveryBatch() {
761         if(recoveryCoordinator == null) {
762             recoveryCoordinator = new ShardRecoveryCoordinator(persistenceId(), schemaContext,
763                     LOG, name.toString());
764         }
765
766         recoveryCoordinator.submit(currentLogRecoveryBatch, store.newWriteOnlyTransaction());
767
768         if(LOG.isDebugEnabled()) {
769             LOG.debug("{}: submitted log recovery batch with size {}", persistenceId(),
770                     currentLogRecoveryBatch.size());
771         }
772     }
773
774     @Override
775     protected void onRecoveryComplete() {
776         if(recoveryCoordinator != null) {
777             Collection<DOMStoreWriteTransaction> txList = recoveryCoordinator.getTransactions();
778
779             if(LOG.isDebugEnabled()) {
780                 LOG.debug("{}: recovery complete - committing {} Tx's", persistenceId(), txList.size());
781             }
782
783             for(DOMStoreWriteTransaction tx: txList) {
784                 try {
785                     syncCommitTransaction(tx);
786                     shardMBean.incrementCommittedTransactionCount();
787                 } catch (InterruptedException | ExecutionException e) {
788                     shardMBean.incrementFailedTransactionsCount();
789                     LOG.error("{}: Failed to commit", persistenceId(), e);
790                 }
791             }
792         }
793
794         recoveryCoordinator = null;
795         currentLogRecoveryBatch = null;
796         updateJournalStats();
797
798         //notify shard manager
799         getContext().parent().tell(new ActorInitialized(), getSelf());
800
801         // Being paranoid here - this method should only be called once but just in case...
802         if(txCommitTimeoutCheckSchedule == null) {
803             // Schedule a message to be periodically sent to check if the current in-progress
804             // transaction should be expired and aborted.
805             FiniteDuration period = Duration.create(transactionCommitTimeout / 3, TimeUnit.MILLISECONDS);
806             txCommitTimeoutCheckSchedule = getContext().system().scheduler().schedule(
807                     period, period, getSelf(),
808                     TX_COMMIT_TIMEOUT_CHECK_MESSAGE, getContext().dispatcher(), ActorRef.noSender());
809         }
810     }
811
812     @Override
813     protected void applyState(final ActorRef clientActor, final String identifier, final Object data) {
814
815         if(data instanceof ModificationPayload) {
816             try {
817                 applyModificationToState(clientActor, identifier, ((ModificationPayload) data).getModification());
818             } catch (ClassNotFoundException | IOException e) {
819                 LOG.error("{}: Error extracting ModificationPayload", persistenceId(), e);
820             }
821         }
822         else if (data instanceof CompositeModificationPayload) {
823             Object modification = ((CompositeModificationPayload) data).getModification();
824
825             applyModificationToState(clientActor, identifier, modification);
826         } else if(data instanceof CompositeModificationByteStringPayload ){
827             Object modification = ((CompositeModificationByteStringPayload) data).getModification();
828
829             applyModificationToState(clientActor, identifier, modification);
830         } else {
831             LOG.error("{}: Unknown state received {} Class loader = {} CompositeNodeMod.ClassLoader = {}",
832                     persistenceId(), data, data.getClass().getClassLoader(),
833                     CompositeModificationPayload.class.getClassLoader());
834         }
835
836         updateJournalStats();
837
838     }
839
840     private void applyModificationToState(ActorRef clientActor, String identifier, Object modification) {
841         if(modification == null) {
842             LOG.error(
843                     "{}: modification is null - this is very unexpected, clientActor = {}, identifier = {}",
844                     persistenceId(), identifier, clientActor != null ? clientActor.path().toString() : null);
845         } else if(clientActor == null) {
846             // There's no clientActor to which to send a commit reply so we must be applying
847             // replicated state from the leader.
848             commitWithNewTransaction(MutableCompositeModification.fromSerializable(modification));
849         } else {
850             // This must be the OK to commit after replication consensus.
851             finishCommit(clientActor, identifier);
852         }
853     }
854
855     private void updateJournalStats() {
856         ReplicatedLogEntry lastLogEntry = getLastLogEntry();
857
858         if (lastLogEntry != null) {
859             shardMBean.setLastLogIndex(lastLogEntry.getIndex());
860             shardMBean.setLastLogTerm(lastLogEntry.getTerm());
861         }
862
863         shardMBean.setCommitIndex(getCommitIndex());
864         shardMBean.setLastApplied(getLastApplied());
865         shardMBean.setInMemoryJournalDataSize(getRaftActorContext().getReplicatedLog().dataSize());
866     }
867
868     @Override
869     protected void createSnapshot() {
870         // Create a transaction actor. We are really going to treat the transaction as a worker
871         // so that this actor does not get block building the snapshot. THe transaction actor will
872         // after processing the CreateSnapshot message.
873
874         ActorRef createSnapshotTransaction = createTransaction(
875                 TransactionProxy.TransactionType.READ_ONLY.ordinal(),
876                 "createSnapshot" + ++createSnapshotTransactionCounter, "",
877                 DataStoreVersions.CURRENT_VERSION);
878
879         createSnapshotTransaction.tell(CreateSnapshot.INSTANCE, self());
880     }
881
882     @VisibleForTesting
883     @Override
884     protected void applySnapshot(final byte[] snapshotBytes) {
885         // Since this will be done only on Recovery or when this actor is a Follower
886         // we can safely commit everything in here. We not need to worry about event notifications
887         // as they would have already been disabled on the follower
888
889         LOG.info("{}: Applying snapshot", persistenceId());
890         try {
891             DOMStoreWriteTransaction transaction = store.newWriteOnlyTransaction();
892
893             NormalizedNode<?, ?> node = SerializationUtils.deserializeNormalizedNode(snapshotBytes);
894
895             // delete everything first
896             transaction.delete(DATASTORE_ROOT);
897
898             // Add everything from the remote node back
899             transaction.write(DATASTORE_ROOT, node);
900             syncCommitTransaction(transaction);
901         } catch (InterruptedException | ExecutionException e) {
902             LOG.error("{}: An exception occurred when applying snapshot", persistenceId(), e);
903         } finally {
904             LOG.info("{}: Done applying snapshot", persistenceId());
905         }
906     }
907
908     @Override
909     protected void onStateChanged() {
910         boolean isLeader = isLeader();
911         for (ActorSelection dataChangeListener : dataChangeListeners) {
912             dataChangeListener.tell(new EnableNotification(isLeader), getSelf());
913         }
914
915         if(isLeader) {
916             for(DelayedListenerRegistration reg: delayedListenerRegistrations) {
917                 if(!reg.isClosed()) {
918                     reg.setDelegate(doChangeListenerRegistration(reg.getRegisterChangeListener()));
919                 }
920             }
921
922             delayedListenerRegistrations.clear();
923         }
924
925         shardMBean.setRaftState(getRaftState().name());
926         shardMBean.setCurrentTerm(getCurrentTerm());
927
928         // If this actor is no longer the leader close all the transaction chains
929         if(!isLeader){
930             for(Map.Entry<String, DOMStoreTransactionChain> entry : transactionChains.entrySet()){
931                 if(LOG.isDebugEnabled()) {
932                     LOG.debug(
933                         "{}: onStateChanged: Closing transaction chain {} because shard {} is no longer the leader",
934                         persistenceId(), entry.getKey(), getId());
935                 }
936                 entry.getValue().close();
937             }
938
939             transactionChains.clear();
940         }
941     }
942
943     @Override
944     protected DataPersistenceProvider persistence() {
945         return dataPersistenceProvider;
946     }
947
948     @Override protected void onLeaderChanged(final String oldLeader, final String newLeader) {
949         shardMBean.setLeader(newLeader);
950     }
951
952     @Override public String persistenceId() {
953         return this.name.toString();
954     }
955
956     @VisibleForTesting
957     DataPersistenceProvider getDataPersistenceProvider() {
958         return dataPersistenceProvider;
959     }
960
961     private static class ShardCreator implements Creator<Shard> {
962
963         private static final long serialVersionUID = 1L;
964
965         final ShardIdentifier name;
966         final Map<ShardIdentifier, String> peerAddresses;
967         final DatastoreContext datastoreContext;
968         final SchemaContext schemaContext;
969
970         ShardCreator(final ShardIdentifier name, final Map<ShardIdentifier, String> peerAddresses,
971                 final DatastoreContext datastoreContext, final SchemaContext schemaContext) {
972             this.name = name;
973             this.peerAddresses = peerAddresses;
974             this.datastoreContext = datastoreContext;
975             this.schemaContext = schemaContext;
976         }
977
978         @Override
979         public Shard create() throws Exception {
980             return new Shard(name, peerAddresses, datastoreContext, schemaContext);
981         }
982     }
983
984     @VisibleForTesting
985     public InMemoryDOMDataStore getDataStore() {
986         return store;
987     }
988
989     @VisibleForTesting
990     ShardStats getShardMBean() {
991         return shardMBean;
992     }
993
994     private static class DelayedListenerRegistration implements
995         ListenerRegistration<AsyncDataChangeListener<YangInstanceIdentifier, NormalizedNode<?, ?>>> {
996
997         private volatile boolean closed;
998
999         private final RegisterChangeListener registerChangeListener;
1000
1001         private volatile ListenerRegistration<AsyncDataChangeListener<YangInstanceIdentifier,
1002                                                              NormalizedNode<?, ?>>> delegate;
1003
1004         DelayedListenerRegistration(final RegisterChangeListener registerChangeListener) {
1005             this.registerChangeListener = registerChangeListener;
1006         }
1007
1008         void setDelegate( final ListenerRegistration<AsyncDataChangeListener<YangInstanceIdentifier,
1009                                             NormalizedNode<?, ?>>> registration) {
1010             this.delegate = registration;
1011         }
1012
1013         boolean isClosed() {
1014             return closed;
1015         }
1016
1017         RegisterChangeListener getRegisterChangeListener() {
1018             return registerChangeListener;
1019         }
1020
1021         @Override
1022         public AsyncDataChangeListener<YangInstanceIdentifier, NormalizedNode<?, ?>> getInstance() {
1023             return delegate != null ? delegate.getInstance() : null;
1024         }
1025
1026         @Override
1027         public void close() {
1028             closed = true;
1029             if(delegate != null) {
1030                 delegate.close();
1031             }
1032         }
1033     }
1034 }