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