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