2 * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
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
9 package org.opendaylight.controller.cluster.datastore;
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;
82 import java.util.concurrent.ExecutionException;
83 import java.util.concurrent.TimeUnit;
84 import javax.annotation.Nonnull;
87 * A Shard represents a portion of the logical data tree <br/>
89 * Our Shard uses InMemoryDataStore as it's internal representation and delegates all requests it
92 public class Shard extends RaftActor {
94 private static final Object COMMIT_TRANSACTION_REPLY = new CommitTransactionReply().toSerializable();
96 private static final Object TX_COMMIT_TIMEOUT_CHECK_MESSAGE = "txCommitTimeoutCheck";
98 public static final String DEFAULT_NAME = "default";
100 // The state of this Shard
101 private final InMemoryDOMDataStore store;
103 private final LoggingAdapter LOG =
104 Logging.getLogger(getContext().system(), this);
106 // By default persistent will be true and can be turned off using the system
107 // property shard.persistent
108 private final boolean persistent;
110 /// The name of this shard
111 private final ShardIdentifier name;
113 private final ShardStats shardMBean;
115 private final List<ActorSelection> dataChangeListeners = new ArrayList<>();
117 private final DatastoreContext datastoreContext;
119 private SchemaContext schemaContext;
121 private ActorRef createSnapshotTransaction;
123 private int createSnapshotTransactionCounter;
125 private final ShardCommitCoordinator commitCoordinator;
127 private final long transactionCommitTimeout;
129 private Cancellable txCommitTimeoutCheckSchedule;
132 * Coordinates persistence recovery on startup.
134 private ShardRecoveryCoordinator recoveryCoordinator;
135 private List<Object> currentLogRecoveryBatch;
137 private final Map<String, DOMStoreTransactionChain> transactionChains = new HashMap<>();
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()));
145 this.datastoreContext = datastoreContext;
146 this.schemaContext = schemaContext;
148 String setting = System.getProperty("shard.persistent");
150 this.persistent = !"false".equals(setting);
152 LOG.info("Shard created : {} persistent : {}", name, persistent);
154 store = InMemoryDOMDataStoreFactory.create(name.toString(), null,
155 datastoreContext.getDataStoreProperties());
157 if(schemaContext != null) {
158 store.onGlobalContextUpdated(schemaContext);
161 shardMBean = ShardMBeanFactory.getShardStatsMBean(name.toString(),
162 datastoreContext.getDataStoreMXBeanType());
163 shardMBean.setDataStoreExecutor(store.getDomStoreExecutor());
164 shardMBean.setNotificationManager(store.getDataChangeListenerNotificationManager());
166 if (isMetricsCaptureEnabled()) {
167 getContext().become(new MeteringBehavior(this));
170 commitCoordinator = new ShardCommitCoordinator(TimeUnit.SECONDS.convert(1, TimeUnit.MINUTES),
171 datastoreContext.getShardTransactionCommitQueueCapacity());
173 transactionCommitTimeout = TimeUnit.MILLISECONDS.convert(
174 datastoreContext.getShardTransactionCommitTimeoutInSeconds(), TimeUnit.SECONDS);
177 private static Map<String, String> mapPeerAddresses(
178 Map<ShardIdentifier, String> peerAddresses) {
179 Map<String, String> map = new HashMap<>();
181 for (Map.Entry<ShardIdentifier, String> entry : peerAddresses
183 map.put(entry.getKey().toString(), entry.getValue());
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");
197 return Props.create(new ShardCreator(name, peerAddresses, datastoreContext, schemaContext));
201 public void postStop() {
204 if(txCommitTimeoutCheckSchedule != null) {
205 txCommitTimeoutCheckSchedule.cancel();
210 public void onReceiveRecover(Object message) {
211 if(LOG.isDebugEnabled()) {
212 LOG.debug("onReceiveRecover: Received message {} from {}",
213 message.getClass().toString(),
217 if (message instanceof RecoveryFailure){
218 LOG.error(((RecoveryFailure) message).cause(), "Recovery failed because of this cause");
220 super.onReceiveRecover(message);
225 public void onReceiveCommand(Object message) {
226 if(LOG.isDebugEnabled()) {
227 LOG.debug("onReceiveCommand: Received message {} from {}", message, getSender());
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();
255 super.onReceiveCommand(message);
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);
267 doAbortTransaction(cohortEntry.getTransactionID(), null);
272 private void handleCommitTransaction(CommitTransaction commit) {
273 final String transactionID = commit.getTransactionID();
275 LOG.debug("Committing transaction {}", transactionID);
277 // Get the current in-progress cohort entry in the commitCoordinator if it corresponds to
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",
286 LOG.error(ex.getMessage());
287 shardMBean.incrementFailedTransactionsCount();
288 getSender().tell(new akka.actor.Status.Failure(ex), getSelf());
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.
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();
304 Shard.this.persistData(getSender(), transactionID,
305 new CompositeModificationPayload(cohortEntry.getModification().toSerializable()));
307 Shard.this.finishCommit(getSender(), transactionID);
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());
316 cohortEntry.updateLastAccessTime();
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.
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
331 cohortEntry = commitCoordinator.getAndRemoveCohortEntry(transactionID);
332 if(cohortEntry != null) {
333 commitWithNewTransaction(cohortEntry.getModification());
334 sender.tell(COMMIT_TRANSACTION_REPLY, getSelf());
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",
341 LOG.error(ex.getMessage());
342 sender.tell(new akka.actor.Status.Failure(ex), getSelf());
348 LOG.debug("Finishing commit for transaction {}", cohortEntry.getTransactionID());
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();
356 sender.tell(COMMIT_TRANSACTION_REPLY, getSelf());
358 shardMBean.incrementCommittedTransactionCount();
359 shardMBean.setLastCommittedTransactionTime(System.currentTimeMillis());
361 } catch (InterruptedException | ExecutionException e) {
362 sender.tell(new akka.actor.Status.Failure(e), getSelf());
364 LOG.error(e, "An exception occurred while committing transaction {}", transactionID);
365 shardMBean.incrementFailedTransactionsCount();
368 commitCoordinator.currentTransactionComplete(transactionID, true);
371 private void handleCanCommitTransaction(CanCommitTransaction canCommit) {
372 LOG.debug("Can committing transaction {}", canCommit.getTransactionID());
373 commitCoordinator.handleCanCommit(canCommit, getSender(), self());
376 private void handleForwardedReadyTransaction(ForwardedReadyTransaction ready) {
377 LOG.debug("Readying transaction {}", ready.getTransactionID());
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
382 commitCoordinator.transactionReady(ready.getTransactionID(), ready.getCohort(),
383 ready.getModification());
385 // Return our actor path as we'll handle the three phase commit.
386 getSender().tell(new ReadyTransactionReply(Serialization.serializedActorPath(self())).
387 toSerializable(), getSelf());
390 private void handleAbortTransaction(AbortTransaction abort) {
391 doAbortTransaction(abort.getTransactionID(), getSender());
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);
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
402 commitCoordinator.currentTransactionComplete(transactionID, false);
404 final ListenableFuture<Void> future = cohortEntry.getCohort().abort();
405 final ActorRef self = getSelf();
407 Futures.addCallback(future, new FutureCallback<Void>() {
409 public void onSuccess(Void v) {
410 shardMBean.incrementAbortTransactionsCount();
413 sender.tell(new AbortTransactionReply().toSerializable(), self);
418 public void onFailure(Throwable t) {
419 LOG.error(t, "An exception happened during abort");
422 sender.tell(new akka.actor.Status.Failure(t), self);
429 private void handleCreateTransaction(Object message) {
431 createTransaction(CreateTransaction.fromSerializable(message));
432 } else if (getLeader() != null) {
433 getLeader().forward(message, getContext());
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());
442 private void handleReadDataReply(Object message) {
443 // This must be for install snapshot. Don't want to open this up and trigger
446 self().tell(new CaptureSnapshotReply(ReadDataReply.getNormalizedNodeByteString(message)),
449 createSnapshotTransaction = null;
451 // Send a PoisonPill instead of sending close transaction because we do not really need
453 getSender().tell(PoisonPill.getInstance(), self());
456 private void closeTransactionChain(CloseTransactionChain closeTransactionChain) {
457 DOMStoreTransactionChain chain =
458 transactionChains.remove(closeTransactionChain.getTransactionChainId());
465 private ActorRef createTypedTransactionActor(
467 ShardTransactionIdentifier transactionId,
468 String transactionChainId ) {
470 DOMStoreTransactionFactory factory = store;
472 if(!transactionChainId.isEmpty()) {
473 factory = transactionChains.get(transactionChainId);
475 DOMStoreTransactionChain transactionChain = store.createTransactionChain();
476 transactionChains.put(transactionChainId, transactionChain);
477 factory = transactionChain;
481 if(this.schemaContext == null){
482 throw new NullPointerException("schemaContext should not be null");
485 if (transactionType == TransactionProxy.TransactionType.READ_ONLY.ordinal()) {
487 shardMBean.incrementReadOnlyTransactionCount();
489 return getContext().actorOf(
490 ShardTransaction.props(factory.newReadOnlyTransaction(), getSelf(),
491 schemaContext,datastoreContext, shardMBean,
492 transactionId.getRemoteTransactionId()), transactionId.toString());
494 } else if (transactionType == TransactionProxy.TransactionType.READ_WRITE.ordinal()) {
496 shardMBean.incrementReadWriteTransactionCount();
498 return getContext().actorOf(
499 ShardTransaction.props(factory.newReadWriteTransaction(), getSelf(),
500 schemaContext, datastoreContext, shardMBean,
501 transactionId.getRemoteTransactionId()), transactionId.toString());
504 } else if (transactionType == TransactionProxy.TransactionType.WRITE_ONLY.ordinal()) {
506 shardMBean.incrementWriteOnlyTransactionCount();
508 return getContext().actorOf(
509 ShardTransaction.props(factory.newWriteOnlyTransaction(), getSelf(),
510 schemaContext, datastoreContext, shardMBean,
511 transactionId.getRemoteTransactionId()), transactionId.toString());
513 throw new IllegalArgumentException(
514 "Shard="+name + ":CreateTransaction message has unidentified transaction type="
519 private void createTransaction(CreateTransaction createTransaction) {
520 createTransaction(createTransaction.getTransactionType(),
521 createTransaction.getTransactionId(), createTransaction.getTransactionChainId());
524 private ActorRef createTransaction(int transactionType, String remoteTransactionId, String transactionChainId) {
526 ShardTransactionIdentifier transactionId =
527 ShardTransactionIdentifier.builder()
528 .remoteTransactionId(remoteTransactionId)
530 if(LOG.isDebugEnabled()) {
531 LOG.debug("Creating transaction : {} ", transactionId);
533 ActorRef transactionActor =
534 createTypedTransactionActor(transactionType, transactionId, transactionChainId);
537 .tell(new CreateTransactionReply(
538 Serialization.serializedActorPath(transactionActor),
539 remoteTransactionId).toSerializable(),
542 return transactionActor;
545 private void syncCommitTransaction(DOMStoreWriteTransaction transaction)
546 throws ExecutionException, InterruptedException {
547 DOMStoreThreePhaseCommitCohort commitCohort = transaction.ready();
548 commitCohort.preCommit().get();
549 commitCohort.commit().get();
552 private void commitWithNewTransaction(Modification modification) {
553 DOMStoreWriteTransaction tx = store.newWriteOnlyTransaction();
554 modification.apply(tx);
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");
565 private void updateSchemaContext(UpdateSchemaContext message) {
566 this.schemaContext = message.getSchemaContext();
567 updateSchemaContext(message.getSchemaContext());
568 store.onGlobalContextUpdated(message.getSchemaContext());
571 @VisibleForTesting void updateSchemaContext(SchemaContext schemaContext) {
572 store.onGlobalContextUpdated(schemaContext);
575 private void registerChangeListener(
576 RegisterChangeListener registerChangeListener) {
578 if(LOG.isDebugEnabled()) {
579 LOG.debug("registerDataChangeListener for {}", registerChangeListener
584 ActorSelection dataChangeListenerPath = getContext()
585 .system().actorSelection(
586 registerChangeListener.getDataChangeListenerPath());
589 // Notify the listener if notifications should be enabled or not
590 // If this shard is the leader then it will enable notifications else
592 dataChangeListenerPath
593 .tell(new EnableNotification(isLeader()), getSelf());
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);
599 AsyncDataChangeListener<YangInstanceIdentifier, NormalizedNode<?, ?>>
600 listener = new DataChangeListenerProxy(schemaContext, dataChangeListenerPath);
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));
609 if(LOG.isDebugEnabled()) {
611 "registerDataChangeListener sending reply, listenerRegistrationPath = {} "
612 , listenerRegistration.path().toString());
616 .tell(new RegisterChangeListenerReply(listenerRegistration.path()),
620 private boolean isMetricsCaptureEnabled(){
621 CommonConfig config = new CommonConfig(getContext().system().settings().config());
622 return config.isMetricCaptureEnabled();
627 void startLogRecoveryBatch(int maxBatchSize) {
628 currentLogRecoveryBatch = Lists.newArrayListWithCapacity(maxBatchSize);
630 if(LOG.isDebugEnabled()) {
631 LOG.debug("{} : starting log recovery batch with max size {}", persistenceId(), maxBatchSize);
636 protected void appendRecoveredLogEntry(Payload data) {
637 if (data instanceof CompositeModificationPayload) {
638 currentLogRecoveryBatch.add(((CompositeModificationPayload) data).getModification());
640 LOG.error("Unknown state received {} during recovery", data);
645 protected void applyRecoverySnapshot(ByteString snapshot) {
646 if(recoveryCoordinator == null) {
647 recoveryCoordinator = new ShardRecoveryCoordinator(persistenceId(), schemaContext);
650 recoveryCoordinator.submit(snapshot, store.newWriteOnlyTransaction());
652 if(LOG.isDebugEnabled()) {
653 LOG.debug("{} : submitted recovery sbapshot", persistenceId());
658 protected void applyCurrentLogRecoveryBatch() {
659 if(recoveryCoordinator == null) {
660 recoveryCoordinator = new ShardRecoveryCoordinator(persistenceId(), schemaContext);
663 recoveryCoordinator.submit(currentLogRecoveryBatch, store.newWriteOnlyTransaction());
665 if(LOG.isDebugEnabled()) {
666 LOG.debug("{} : submitted log recovery batch with size {}", persistenceId(),
667 currentLogRecoveryBatch.size());
672 protected void onRecoveryComplete() {
673 if(recoveryCoordinator != null) {
674 Collection<DOMStoreWriteTransaction> txList = recoveryCoordinator.getTransactions();
676 if(LOG.isDebugEnabled()) {
677 LOG.debug("{} : recovery complete - committing {} Tx's", persistenceId(), txList.size());
680 for(DOMStoreWriteTransaction tx: txList) {
682 syncCommitTransaction(tx);
683 shardMBean.incrementCommittedTransactionCount();
684 } catch (InterruptedException | ExecutionException e) {
685 shardMBean.incrementFailedTransactionsCount();
686 LOG.error(e, "Failed to commit");
691 recoveryCoordinator = null;
692 currentLogRecoveryBatch = null;
693 updateJournalStats();
695 //notify shard manager
696 getContext().parent().tell(new ActorInitialized(), getSelf());
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());
707 protected void applyState(ActorRef clientActor, String identifier, Object data) {
709 if (data instanceof CompositeModificationPayload) {
710 Object modification = ((CompositeModificationPayload) data).getModification();
712 if(modification == null) {
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));
722 // This must be the OK to commit after replication consensus.
723 finishCommit(clientActor, identifier);
726 LOG.error("Unknown state received {} Class loader = {} CompositeNodeMod.ClassLoader = {}",
727 data, data.getClass().getClassLoader(),
728 CompositeModificationPayload.class.getClassLoader());
731 updateJournalStats();
735 private void updateJournalStats() {
736 ReplicatedLogEntry lastLogEntry = getLastLogEntry();
738 if (lastLogEntry != null) {
739 shardMBean.setLastLogIndex(lastLogEntry.getIndex());
740 shardMBean.setLastLogTerm(lastLogEntry.getTerm());
743 shardMBean.setCommitIndex(getCommitIndex());
744 shardMBean.setLastApplied(getLastApplied());
748 protected void createSnapshot() {
749 if (createSnapshotTransaction == null) {
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, "");
757 createSnapshotTransaction.tell(
758 new ReadData(YangInstanceIdentifier.builder().build()).toSerializable(), self());
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
770 LOG.info("Applying snapshot");
772 DOMStoreWriteTransaction transaction = store.newWriteOnlyTransaction();
773 NormalizedNodeMessages.Node serializedNode = NormalizedNodeMessages.Node.parseFrom(snapshot);
774 NormalizedNode<?, ?> node = new NormalizedNodeToNodeCodec(schemaContext)
775 .decode(serializedNode);
777 // delete everything first
778 transaction.delete(YangInstanceIdentifier.builder().build());
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");
786 LOG.info("Done applying snapshot");
790 @Override protected void onStateChanged() {
791 for (ActorSelection dataChangeListener : dataChangeListeners) {
793 .tell(new EnableNotification(isLeader()), getSelf());
796 shardMBean.setRaftState(getRaftState().name());
797 shardMBean.setCurrentTerm(getCurrentTerm());
799 // If this actor is no longer the leader close all the transaction chains
801 for(Map.Entry<String, DOMStoreTransactionChain> entry : transactionChains.entrySet()){
802 if(LOG.isDebugEnabled()) {
804 "onStateChanged: Closing transaction chain {} because shard {} is no longer the leader",
805 entry.getKey(), getId());
807 entry.getValue().close();
810 transactionChains.clear();
814 @Override protected void onLeaderChanged(String oldLeader, String newLeader) {
815 shardMBean.setLeader(newLeader);
818 @Override public String persistenceId() {
819 return this.name.toString();
822 private static class ShardCreator implements Creator<Shard> {
824 private static final long serialVersionUID = 1L;
826 final ShardIdentifier name;
827 final Map<ShardIdentifier, String> peerAddresses;
828 final DatastoreContext datastoreContext;
829 final SchemaContext schemaContext;
831 ShardCreator(ShardIdentifier name, Map<ShardIdentifier, String> peerAddresses,
832 DatastoreContext datastoreContext, SchemaContext schemaContext) {
834 this.peerAddresses = peerAddresses;
835 this.datastoreContext = datastoreContext;
836 this.schemaContext = schemaContext;
840 public Shard create() throws Exception {
841 return new Shard(name, peerAddresses, datastoreContext, schemaContext);
846 InMemoryDOMDataStore getDataStore() {
851 ShardStats getShardMBean() {