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.AbortTransaction;
38 import org.opendaylight.controller.cluster.datastore.messages.AbortTransactionReply;
39 import org.opendaylight.controller.cluster.datastore.messages.ActorInitialized;
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;
78 import javax.annotation.Nonnull;
79 import java.util.ArrayList;
80 import java.util.Collection;
81 import java.util.HashMap;
82 import java.util.List;
84 import java.util.concurrent.ExecutionException;
85 import java.util.concurrent.TimeUnit;
88 * A Shard represents a portion of the logical data tree <br/>
90 * Our Shard uses InMemoryDataStore as it's internal representation and delegates all requests it
93 public class Shard extends RaftActor {
95 private static final Object COMMIT_TRANSACTION_REPLY = new CommitTransactionReply().toSerializable();
97 private static final Object TX_COMMIT_TIMEOUT_CHECK_MESSAGE = "txCommitTimeoutCheck";
99 public static final String DEFAULT_NAME = "default";
101 // The state of this Shard
102 private final InMemoryDOMDataStore store;
104 private final LoggingAdapter LOG =
105 Logging.getLogger(getContext().system(), this);
107 // By default persistent will be true and can be turned off using the system
108 // property shard.persistent
109 private final boolean persistent;
111 /// The name of this shard
112 private final ShardIdentifier name;
114 private final ShardStats shardMBean;
116 private final List<ActorSelection> dataChangeListeners = new ArrayList<>();
118 private final DatastoreContext datastoreContext;
120 private SchemaContext schemaContext;
122 private ActorRef createSnapshotTransaction;
124 private int createSnapshotTransactionCounter;
126 private final ShardCommitCoordinator commitCoordinator;
128 private final long transactionCommitTimeout;
130 private Cancellable txCommitTimeoutCheckSchedule;
133 * Coordinates persistence recovery on startup.
135 private ShardRecoveryCoordinator recoveryCoordinator;
136 private List<Object> currentLogRecoveryBatch;
138 private final Map<String, DOMStoreTransactionChain> transactionChains = new HashMap<>();
140 protected Shard(ShardIdentifier name, Map<ShardIdentifier, String> peerAddresses,
141 DatastoreContext datastoreContext, SchemaContext schemaContext) {
142 super(name.toString(), mapPeerAddresses(peerAddresses),
143 Optional.of(datastoreContext.getShardRaftConfig()));
146 this.datastoreContext = datastoreContext;
147 this.schemaContext = schemaContext;
149 String setting = System.getProperty("shard.persistent");
151 this.persistent = !"false".equals(setting);
153 LOG.info("Shard created : {} persistent : {}", name, persistent);
155 store = InMemoryDOMDataStoreFactory.create(name.toString(), null,
156 datastoreContext.getDataStoreProperties());
158 if(schemaContext != null) {
159 store.onGlobalContextUpdated(schemaContext);
162 shardMBean = ShardMBeanFactory.getShardStatsMBean(name.toString(),
163 datastoreContext.getDataStoreMXBeanType());
164 shardMBean.setDataStoreExecutor(store.getDomStoreExecutor());
165 shardMBean.setNotificationManager(store.getDataChangeListenerNotificationManager());
167 if (isMetricsCaptureEnabled()) {
168 getContext().become(new MeteringBehavior(this));
171 commitCoordinator = new ShardCommitCoordinator(TimeUnit.SECONDS.convert(1, TimeUnit.MINUTES),
172 datastoreContext.getShardTransactionCommitQueueCapacity());
174 transactionCommitTimeout = TimeUnit.MILLISECONDS.convert(
175 datastoreContext.getShardTransactionCommitTimeoutInSeconds(), TimeUnit.SECONDS);
178 private static Map<String, String> mapPeerAddresses(
179 Map<ShardIdentifier, String> peerAddresses) {
180 Map<String, String> map = new HashMap<>();
182 for (Map.Entry<ShardIdentifier, String> entry : peerAddresses
184 map.put(entry.getKey().toString(), entry.getValue());
190 public static Props props(final ShardIdentifier name,
191 final Map<ShardIdentifier, String> peerAddresses,
192 DatastoreContext datastoreContext, SchemaContext schemaContext) {
193 Preconditions.checkNotNull(name, "name should not be null");
194 Preconditions.checkNotNull(peerAddresses, "peerAddresses should not be null");
195 Preconditions.checkNotNull(datastoreContext, "dataStoreContext should not be null");
196 Preconditions.checkNotNull(schemaContext, "schemaContext should not be null");
198 return Props.create(new ShardCreator(name, peerAddresses, datastoreContext, schemaContext));
202 public void postStop() {
205 if(txCommitTimeoutCheckSchedule != null) {
206 txCommitTimeoutCheckSchedule.cancel();
211 public void onReceiveRecover(Object message) {
212 if(LOG.isDebugEnabled()) {
213 LOG.debug("onReceiveRecover: Received message {} from {}",
214 message.getClass().toString(),
218 if (message instanceof RecoveryFailure){
219 LOG.error(((RecoveryFailure) message).cause(), "Recovery failed because of this cause");
221 super.onReceiveRecover(message);
226 public void onReceiveCommand(Object message) {
227 if(LOG.isDebugEnabled()) {
228 LOG.debug("onReceiveCommand: Received message {} from {}", message, getSender());
231 if(message.getClass().equals(ReadDataReply.SERIALIZABLE_CLASS)) {
232 handleReadDataReply(message);
233 } else if (message.getClass().equals(CreateTransaction.SERIALIZABLE_CLASS)) {
234 handleCreateTransaction(message);
235 } else if(message instanceof ForwardedReadyTransaction) {
236 handleForwardedReadyTransaction((ForwardedReadyTransaction)message);
237 } else if(message.getClass().equals(CanCommitTransaction.SERIALIZABLE_CLASS)) {
238 handleCanCommitTransaction(CanCommitTransaction.fromSerializable(message));
239 } else if(message.getClass().equals(CommitTransaction.SERIALIZABLE_CLASS)) {
240 handleCommitTransaction(CommitTransaction.fromSerializable(message));
241 } else if(message.getClass().equals(AbortTransaction.SERIALIZABLE_CLASS)) {
242 handleAbortTransaction(AbortTransaction.fromSerializable(message));
243 } else if (message.getClass().equals(CloseTransactionChain.SERIALIZABLE_CLASS)){
244 closeTransactionChain(CloseTransactionChain.fromSerializable(message));
245 } else if (message instanceof RegisterChangeListener) {
246 registerChangeListener((RegisterChangeListener) message);
247 } else if (message instanceof UpdateSchemaContext) {
248 updateSchemaContext((UpdateSchemaContext) message);
249 } else if (message instanceof PeerAddressResolved) {
250 PeerAddressResolved resolved = (PeerAddressResolved) message;
251 setPeerAddress(resolved.getPeerId().toString(),
252 resolved.getPeerAddress());
253 } else if(message.equals(TX_COMMIT_TIMEOUT_CHECK_MESSAGE)) {
254 handleTransactionCommitTimeoutCheck();
256 super.onReceiveCommand(message);
260 private void handleTransactionCommitTimeoutCheck() {
261 CohortEntry cohortEntry = commitCoordinator.getCurrentCohortEntry();
262 if(cohortEntry != null) {
263 long elapsed = System.currentTimeMillis() - cohortEntry.getLastAccessTime();
264 if(elapsed > transactionCommitTimeout) {
265 LOG.warning("Current transaction {} has timed out after {} ms - aborting",
266 cohortEntry.getTransactionID(), transactionCommitTimeout);
268 doAbortTransaction(cohortEntry.getTransactionID(), null);
273 private void handleCommitTransaction(CommitTransaction commit) {
274 final String transactionID = commit.getTransactionID();
276 LOG.debug("Committing transaction {}", transactionID);
278 // Get the current in-progress cohort entry in the commitCoordinator if it corresponds to
280 final CohortEntry cohortEntry = commitCoordinator.getCohortEntryIfCurrent(transactionID);
281 if(cohortEntry == null) {
282 // We're not the current Tx - the Tx was likely expired b/c it took too long in
283 // between the canCommit and commit messages.
284 IllegalStateException ex = new IllegalStateException(
285 String.format("Cannot commit transaction %s - it is not the current transaction",
287 LOG.error(ex.getMessage());
288 shardMBean.incrementFailedTransactionsCount();
289 getSender().tell(new akka.actor.Status.Failure(ex), getSelf());
293 // We perform the preCommit phase here atomically with the commit phase. This is an
294 // optimization to eliminate the overhead of an extra preCommit message. We lose front-end
295 // coordination of preCommit across shards in case of failure but preCommit should not
296 // normally fail since we ensure only one concurrent 3-phase commit.
299 // We block on the future here so we don't have to worry about possibly accessing our
300 // state on a different thread outside of our dispatcher. Also, the data store
301 // currently uses a same thread executor anyway.
302 cohortEntry.getCohort().preCommit().get();
305 Shard.this.persistData(getSender(), transactionID,
306 new CompositeModificationPayload(cohortEntry.getModification().toSerializable()));
308 Shard.this.finishCommit(getSender(), transactionID);
310 } catch (InterruptedException | ExecutionException e) {
311 LOG.error(e, "An exception occurred while preCommitting transaction {}",
312 cohortEntry.getTransactionID());
313 shardMBean.incrementFailedTransactionsCount();
314 getSender().tell(new akka.actor.Status.Failure(e), getSelf());
317 cohortEntry.updateLastAccessTime();
320 private void finishCommit(@Nonnull final ActorRef sender, final @Nonnull String transactionID) {
321 // With persistence enabled, this method is called via applyState by the leader strategy
322 // after the commit has been replicated to a majority of the followers.
324 CohortEntry cohortEntry = commitCoordinator.getCohortEntryIfCurrent(transactionID);
325 if(cohortEntry == null) {
326 // The transaction is no longer the current commit. This can happen if the transaction
327 // was aborted prior, most likely due to timeout in the front-end. We need to finish
328 // committing the transaction though since it was successfully persisted and replicated
329 // however we can't use the original cohort b/c it was already preCommitted and may
330 // conflict with the current commit or may have been aborted so we commit with a new
332 cohortEntry = commitCoordinator.getAndRemoveCohortEntry(transactionID);
333 if(cohortEntry != null) {
334 commitWithNewTransaction(cohortEntry.getModification());
335 sender.tell(COMMIT_TRANSACTION_REPLY, getSelf());
337 // This really shouldn't happen - it likely means that persistence or replication
338 // took so long to complete such that the cohort entry was expired from the cache.
339 IllegalStateException ex = new IllegalStateException(
340 String.format("Could not finish committing transaction %s - no CohortEntry found",
342 LOG.error(ex.getMessage());
343 sender.tell(new akka.actor.Status.Failure(ex), getSelf());
349 LOG.debug("Finishing commit for transaction {}", cohortEntry.getTransactionID());
352 // We block on the future here so we don't have to worry about possibly accessing our
353 // state on a different thread outside of our dispatcher. Also, the data store
354 // currently uses a same thread executor anyway.
355 cohortEntry.getCohort().commit().get();
357 sender.tell(COMMIT_TRANSACTION_REPLY, getSelf());
359 shardMBean.incrementCommittedTransactionCount();
360 shardMBean.setLastCommittedTransactionTime(System.currentTimeMillis());
362 } catch (InterruptedException | ExecutionException e) {
363 sender.tell(new akka.actor.Status.Failure(e), getSelf());
365 LOG.error(e, "An exception occurred while committing transaction {}", transactionID);
366 shardMBean.incrementFailedTransactionsCount();
369 commitCoordinator.currentTransactionComplete(transactionID, true);
372 private void handleCanCommitTransaction(CanCommitTransaction canCommit) {
373 LOG.debug("Can committing transaction {}", canCommit.getTransactionID());
374 commitCoordinator.handleCanCommit(canCommit, getSender(), self());
377 private void handleForwardedReadyTransaction(ForwardedReadyTransaction ready) {
378 LOG.debug("Readying transaction {}", ready.getTransactionID());
380 // This message is forwarded by the ShardTransaction on ready. We cache the cohort in the
381 // commitCoordinator in preparation for the subsequent three phase commit initiated by
383 commitCoordinator.transactionReady(ready.getTransactionID(), ready.getCohort(),
384 ready.getModification());
386 // Return our actor path as we'll handle the three phase commit.
387 ReadyTransactionReply readyTransactionReply =
388 new ReadyTransactionReply(Serialization.serializedActorPath(self()));
390 ready.isReturnSerialized() ? readyTransactionReply.toSerializable() : readyTransactionReply,
394 private void handleAbortTransaction(AbortTransaction abort) {
395 doAbortTransaction(abort.getTransactionID(), getSender());
398 private void doAbortTransaction(String transactionID, final ActorRef sender) {
399 final CohortEntry cohortEntry = commitCoordinator.getCohortEntryIfCurrent(transactionID);
400 if(cohortEntry != null) {
401 LOG.debug("Aborting transaction {}", transactionID);
403 // We don't remove the cached cohort entry here (ie pass false) in case the Tx was
404 // aborted during replication in which case we may still commit locally if replication
406 commitCoordinator.currentTransactionComplete(transactionID, false);
408 final ListenableFuture<Void> future = cohortEntry.getCohort().abort();
409 final ActorRef self = getSelf();
411 Futures.addCallback(future, new FutureCallback<Void>() {
413 public void onSuccess(Void v) {
414 shardMBean.incrementAbortTransactionsCount();
417 sender.tell(new AbortTransactionReply().toSerializable(), self);
422 public void onFailure(Throwable t) {
423 LOG.error(t, "An exception happened during abort");
426 sender.tell(new akka.actor.Status.Failure(t), self);
433 private void handleCreateTransaction(Object message) {
435 createTransaction(CreateTransaction.fromSerializable(message));
436 } else if (getLeader() != null) {
437 getLeader().forward(message, getContext());
439 getSender().tell(new akka.actor.Status.Failure(new IllegalStateException(
440 "Could not find shard leader so transaction cannot be created. This typically happens" +
441 " when system is coming up or recovering and a leader is being elected. Try again" +
442 " later.")), getSelf());
446 private void handleReadDataReply(Object message) {
447 // This must be for install snapshot. Don't want to open this up and trigger
450 self().tell(new CaptureSnapshotReply(ReadDataReply.getNormalizedNodeByteString(message)),
453 createSnapshotTransaction = null;
455 // Send a PoisonPill instead of sending close transaction because we do not really need
457 getSender().tell(PoisonPill.getInstance(), self());
460 private void closeTransactionChain(CloseTransactionChain closeTransactionChain) {
461 DOMStoreTransactionChain chain =
462 transactionChains.remove(closeTransactionChain.getTransactionChainId());
469 private ActorRef createTypedTransactionActor(
471 ShardTransactionIdentifier transactionId,
472 String transactionChainId ) {
474 DOMStoreTransactionFactory factory = store;
476 if(!transactionChainId.isEmpty()) {
477 factory = transactionChains.get(transactionChainId);
479 DOMStoreTransactionChain transactionChain = store.createTransactionChain();
480 transactionChains.put(transactionChainId, transactionChain);
481 factory = transactionChain;
485 if(this.schemaContext == null){
486 throw new NullPointerException("schemaContext should not be null");
489 if (transactionType == TransactionProxy.TransactionType.READ_ONLY.ordinal()) {
491 shardMBean.incrementReadOnlyTransactionCount();
493 return getContext().actorOf(
494 ShardTransaction.props(factory.newReadOnlyTransaction(), getSelf(),
495 schemaContext,datastoreContext, shardMBean,
496 transactionId.getRemoteTransactionId()), transactionId.toString());
498 } else if (transactionType == TransactionProxy.TransactionType.READ_WRITE.ordinal()) {
500 shardMBean.incrementReadWriteTransactionCount();
502 return getContext().actorOf(
503 ShardTransaction.props(factory.newReadWriteTransaction(), getSelf(),
504 schemaContext, datastoreContext, shardMBean,
505 transactionId.getRemoteTransactionId()), transactionId.toString());
508 } else if (transactionType == TransactionProxy.TransactionType.WRITE_ONLY.ordinal()) {
510 shardMBean.incrementWriteOnlyTransactionCount();
512 return getContext().actorOf(
513 ShardTransaction.props(factory.newWriteOnlyTransaction(), getSelf(),
514 schemaContext, datastoreContext, shardMBean,
515 transactionId.getRemoteTransactionId()), transactionId.toString());
517 throw new IllegalArgumentException(
518 "Shard="+name + ":CreateTransaction message has unidentified transaction type="
523 private void createTransaction(CreateTransaction createTransaction) {
524 createTransaction(createTransaction.getTransactionType(),
525 createTransaction.getTransactionId(), createTransaction.getTransactionChainId());
528 private ActorRef createTransaction(int transactionType, String remoteTransactionId, String transactionChainId) {
530 ShardTransactionIdentifier transactionId =
531 ShardTransactionIdentifier.builder()
532 .remoteTransactionId(remoteTransactionId)
534 if(LOG.isDebugEnabled()) {
535 LOG.debug("Creating transaction : {} ", transactionId);
537 ActorRef transactionActor =
538 createTypedTransactionActor(transactionType, transactionId, transactionChainId);
541 .tell(new CreateTransactionReply(
542 Serialization.serializedActorPath(transactionActor),
543 remoteTransactionId).toSerializable(),
546 return transactionActor;
549 private void syncCommitTransaction(DOMStoreWriteTransaction transaction)
550 throws ExecutionException, InterruptedException {
551 DOMStoreThreePhaseCommitCohort commitCohort = transaction.ready();
552 commitCohort.preCommit().get();
553 commitCohort.commit().get();
556 private void commitWithNewTransaction(Modification modification) {
557 DOMStoreWriteTransaction tx = store.newWriteOnlyTransaction();
558 modification.apply(tx);
560 syncCommitTransaction(tx);
561 shardMBean.incrementCommittedTransactionCount();
562 shardMBean.setLastCommittedTransactionTime(System.currentTimeMillis());
563 } catch (InterruptedException | ExecutionException e) {
564 shardMBean.incrementFailedTransactionsCount();
565 LOG.error(e, "Failed to commit");
569 private void updateSchemaContext(UpdateSchemaContext message) {
570 this.schemaContext = message.getSchemaContext();
571 updateSchemaContext(message.getSchemaContext());
572 store.onGlobalContextUpdated(message.getSchemaContext());
575 @VisibleForTesting void updateSchemaContext(SchemaContext schemaContext) {
576 store.onGlobalContextUpdated(schemaContext);
579 private void registerChangeListener(
580 RegisterChangeListener registerChangeListener) {
582 if(LOG.isDebugEnabled()) {
583 LOG.debug("registerDataChangeListener for {}", registerChangeListener
588 ActorSelection dataChangeListenerPath = getContext()
589 .system().actorSelection(
590 registerChangeListener.getDataChangeListenerPath());
593 // Notify the listener if notifications should be enabled or not
594 // If this shard is the leader then it will enable notifications else
596 dataChangeListenerPath
597 .tell(new EnableNotification(isLeader()), getSelf());
599 // Now store a reference to the data change listener so it can be notified
600 // at a later point if notifications should be enabled or disabled
601 dataChangeListeners.add(dataChangeListenerPath);
603 AsyncDataChangeListener<YangInstanceIdentifier, NormalizedNode<?, ?>>
604 listener = new DataChangeListenerProxy(schemaContext, dataChangeListenerPath);
606 ListenerRegistration<AsyncDataChangeListener<YangInstanceIdentifier, NormalizedNode<?, ?>>>
607 registration = store.registerChangeListener(registerChangeListener.getPath(),
608 listener, registerChangeListener.getScope());
609 ActorRef listenerRegistration =
610 getContext().actorOf(
611 DataChangeListenerRegistration.props(registration));
613 if(LOG.isDebugEnabled()) {
615 "registerDataChangeListener sending reply, listenerRegistrationPath = {} "
616 , listenerRegistration.path().toString());
620 .tell(new RegisterChangeListenerReply(listenerRegistration.path()),
624 private boolean isMetricsCaptureEnabled(){
625 CommonConfig config = new CommonConfig(getContext().system().settings().config());
626 return config.isMetricCaptureEnabled();
631 void startLogRecoveryBatch(int maxBatchSize) {
632 currentLogRecoveryBatch = Lists.newArrayListWithCapacity(maxBatchSize);
634 if(LOG.isDebugEnabled()) {
635 LOG.debug("{} : starting log recovery batch with max size {}", persistenceId(), maxBatchSize);
640 protected void appendRecoveredLogEntry(Payload data) {
641 if (data instanceof CompositeModificationPayload) {
642 currentLogRecoveryBatch.add(((CompositeModificationPayload) data).getModification());
644 LOG.error("Unknown state received {} during recovery", data);
649 protected void applyRecoverySnapshot(ByteString snapshot) {
650 if(recoveryCoordinator == null) {
651 recoveryCoordinator = new ShardRecoveryCoordinator(persistenceId(), schemaContext);
654 recoveryCoordinator.submit(snapshot, store.newWriteOnlyTransaction());
656 if(LOG.isDebugEnabled()) {
657 LOG.debug("{} : submitted recovery sbapshot", persistenceId());
662 protected void applyCurrentLogRecoveryBatch() {
663 if(recoveryCoordinator == null) {
664 recoveryCoordinator = new ShardRecoveryCoordinator(persistenceId(), schemaContext);
667 recoveryCoordinator.submit(currentLogRecoveryBatch, store.newWriteOnlyTransaction());
669 if(LOG.isDebugEnabled()) {
670 LOG.debug("{} : submitted log recovery batch with size {}", persistenceId(),
671 currentLogRecoveryBatch.size());
676 protected void onRecoveryComplete() {
677 if(recoveryCoordinator != null) {
678 Collection<DOMStoreWriteTransaction> txList = recoveryCoordinator.getTransactions();
680 if(LOG.isDebugEnabled()) {
681 LOG.debug("{} : recovery complete - committing {} Tx's", persistenceId(), txList.size());
684 for(DOMStoreWriteTransaction tx: txList) {
686 syncCommitTransaction(tx);
687 shardMBean.incrementCommittedTransactionCount();
688 } catch (InterruptedException | ExecutionException e) {
689 shardMBean.incrementFailedTransactionsCount();
690 LOG.error(e, "Failed to commit");
695 recoveryCoordinator = null;
696 currentLogRecoveryBatch = null;
697 updateJournalStats();
699 //notify shard manager
700 getContext().parent().tell(new ActorInitialized(), getSelf());
702 // Schedule a message to be periodically sent to check if the current in-progress
703 // transaction should be expired and aborted.
704 FiniteDuration period = Duration.create(transactionCommitTimeout / 3, TimeUnit.MILLISECONDS);
705 txCommitTimeoutCheckSchedule = getContext().system().scheduler().schedule(
706 period, period, getSelf(),
707 TX_COMMIT_TIMEOUT_CHECK_MESSAGE, getContext().dispatcher(), ActorRef.noSender());
711 protected void applyState(ActorRef clientActor, String identifier, Object data) {
713 if (data instanceof CompositeModificationPayload) {
714 Object modification = ((CompositeModificationPayload) data).getModification();
716 if(modification == null) {
718 "modification is null - this is very unexpected, clientActor = {}, identifier = {}",
719 identifier, clientActor != null ? clientActor.path().toString() : null);
720 } else if(clientActor == null) {
721 // There's no clientActor to which to send a commit reply so we must be applying
722 // replicated state from the leader.
723 commitWithNewTransaction(MutableCompositeModification.fromSerializable(
724 modification, schemaContext));
726 // This must be the OK to commit after replication consensus.
727 finishCommit(clientActor, identifier);
730 LOG.error("Unknown state received {} Class loader = {} CompositeNodeMod.ClassLoader = {}",
731 data, data.getClass().getClassLoader(),
732 CompositeModificationPayload.class.getClassLoader());
735 updateJournalStats();
739 private void updateJournalStats() {
740 ReplicatedLogEntry lastLogEntry = getLastLogEntry();
742 if (lastLogEntry != null) {
743 shardMBean.setLastLogIndex(lastLogEntry.getIndex());
744 shardMBean.setLastLogTerm(lastLogEntry.getTerm());
747 shardMBean.setCommitIndex(getCommitIndex());
748 shardMBean.setLastApplied(getLastApplied());
752 protected void createSnapshot() {
753 if (createSnapshotTransaction == null) {
755 // Create a transaction. We are really going to treat the transaction as a worker
756 // so that this actor does not get block building the snapshot
757 createSnapshotTransaction = createTransaction(
758 TransactionProxy.TransactionType.READ_ONLY.ordinal(),
759 "createSnapshot" + ++createSnapshotTransactionCounter, "");
761 createSnapshotTransaction.tell(
762 new ReadData(YangInstanceIdentifier.builder().build()).toSerializable(), self());
769 protected void applySnapshot(ByteString snapshot) {
770 // Since this will be done only on Recovery or when this actor is a Follower
771 // we can safely commit everything in here. We not need to worry about event notifications
772 // as they would have already been disabled on the follower
774 LOG.info("Applying snapshot");
776 DOMStoreWriteTransaction transaction = store.newWriteOnlyTransaction();
777 NormalizedNodeMessages.Node serializedNode = NormalizedNodeMessages.Node.parseFrom(snapshot);
778 NormalizedNode<?, ?> node = new NormalizedNodeToNodeCodec(schemaContext)
779 .decode(serializedNode);
781 // delete everything first
782 transaction.delete(YangInstanceIdentifier.builder().build());
784 // Add everything from the remote node back
785 transaction.write(YangInstanceIdentifier.builder().build(), node);
786 syncCommitTransaction(transaction);
787 } catch (InvalidProtocolBufferException | InterruptedException | ExecutionException e) {
788 LOG.error(e, "An exception occurred when applying snapshot");
790 LOG.info("Done applying snapshot");
794 @Override protected void onStateChanged() {
795 for (ActorSelection dataChangeListener : dataChangeListeners) {
797 .tell(new EnableNotification(isLeader()), getSelf());
800 shardMBean.setRaftState(getRaftState().name());
801 shardMBean.setCurrentTerm(getCurrentTerm());
803 // If this actor is no longer the leader close all the transaction chains
805 for(Map.Entry<String, DOMStoreTransactionChain> entry : transactionChains.entrySet()){
806 if(LOG.isDebugEnabled()) {
808 "onStateChanged: Closing transaction chain {} because shard {} is no longer the leader",
809 entry.getKey(), getId());
811 entry.getValue().close();
814 transactionChains.clear();
818 @Override protected void onLeaderChanged(String oldLeader, String newLeader) {
819 shardMBean.setLeader(newLeader);
822 @Override public String persistenceId() {
823 return this.name.toString();
826 private static class ShardCreator implements Creator<Shard> {
828 private static final long serialVersionUID = 1L;
830 final ShardIdentifier name;
831 final Map<ShardIdentifier, String> peerAddresses;
832 final DatastoreContext datastoreContext;
833 final SchemaContext schemaContext;
835 ShardCreator(ShardIdentifier name, Map<ShardIdentifier, String> peerAddresses,
836 DatastoreContext datastoreContext, SchemaContext schemaContext) {
838 this.peerAddresses = peerAddresses;
839 this.datastoreContext = datastoreContext;
840 this.schemaContext = schemaContext;
844 public Shard create() throws Exception {
845 return new Shard(name, peerAddresses, datastoreContext, schemaContext);
850 InMemoryDOMDataStore getDataStore() {
855 ShardStats getShardMBean() {