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