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 java.util.Collection;
31 import java.util.HashMap;
32 import java.util.List;
34 import java.util.concurrent.ExecutionException;
35 import java.util.concurrent.TimeUnit;
36 import javax.annotation.Nonnull;
37 import org.opendaylight.controller.cluster.DataPersistenceProvider;
38 import org.opendaylight.controller.cluster.common.actor.CommonConfig;
39 import org.opendaylight.controller.cluster.common.actor.MeteringBehavior;
40 import org.opendaylight.controller.cluster.datastore.ShardCommitCoordinator.CohortEntry;
41 import org.opendaylight.controller.cluster.datastore.compat.BackwardsCompatibleThreePhaseCommitCohort;
42 import org.opendaylight.controller.cluster.datastore.exceptions.NoShardLeaderException;
43 import org.opendaylight.controller.cluster.datastore.identifiers.ShardIdentifier;
44 import org.opendaylight.controller.cluster.datastore.identifiers.ShardTransactionIdentifier;
45 import org.opendaylight.controller.cluster.datastore.jmx.mbeans.shard.ShardMBeanFactory;
46 import org.opendaylight.controller.cluster.datastore.jmx.mbeans.shard.ShardStats;
47 import org.opendaylight.controller.cluster.datastore.messages.AbortTransaction;
48 import org.opendaylight.controller.cluster.datastore.messages.AbortTransactionReply;
49 import org.opendaylight.controller.cluster.datastore.messages.ActorInitialized;
50 import org.opendaylight.controller.cluster.datastore.messages.CanCommitTransaction;
51 import org.opendaylight.controller.cluster.datastore.messages.CloseTransactionChain;
52 import org.opendaylight.controller.cluster.datastore.messages.CommitTransaction;
53 import org.opendaylight.controller.cluster.datastore.messages.CommitTransactionReply;
54 import org.opendaylight.controller.cluster.datastore.messages.CreateTransaction;
55 import org.opendaylight.controller.cluster.datastore.messages.CreateTransactionReply;
56 import org.opendaylight.controller.cluster.datastore.messages.EnableNotification;
57 import org.opendaylight.controller.cluster.datastore.messages.ForwardedReadyTransaction;
58 import org.opendaylight.controller.cluster.datastore.messages.PeerAddressResolved;
59 import org.opendaylight.controller.cluster.datastore.messages.ReadData;
60 import org.opendaylight.controller.cluster.datastore.messages.ReadDataReply;
61 import org.opendaylight.controller.cluster.datastore.messages.ReadyTransactionReply;
62 import org.opendaylight.controller.cluster.datastore.messages.RegisterChangeListener;
63 import org.opendaylight.controller.cluster.datastore.messages.RegisterChangeListenerReply;
64 import org.opendaylight.controller.cluster.datastore.messages.UpdateSchemaContext;
65 import org.opendaylight.controller.cluster.datastore.modification.Modification;
66 import org.opendaylight.controller.cluster.datastore.modification.MutableCompositeModification;
67 import org.opendaylight.controller.cluster.datastore.node.NormalizedNodeToNodeCodec;
68 import org.opendaylight.controller.cluster.notifications.RoleChangeNotifier;
69 import org.opendaylight.controller.cluster.raft.RaftActor;
70 import org.opendaylight.controller.cluster.raft.ReplicatedLogEntry;
71 import org.opendaylight.controller.cluster.raft.base.messages.CaptureSnapshotReply;
72 import org.opendaylight.controller.cluster.raft.protobuff.client.messages.CompositeModificationByteStringPayload;
73 import org.opendaylight.controller.cluster.raft.protobuff.client.messages.CompositeModificationPayload;
74 import org.opendaylight.controller.cluster.raft.protobuff.client.messages.Payload;
75 import org.opendaylight.controller.md.sal.common.api.data.AsyncDataChangeListener;
76 import org.opendaylight.controller.md.sal.dom.store.impl.InMemoryDOMDataStore;
77 import org.opendaylight.controller.md.sal.dom.store.impl.InMemoryDOMDataStoreFactory;
78 import org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages;
79 import org.opendaylight.controller.sal.core.spi.data.DOMStoreThreePhaseCommitCohort;
80 import org.opendaylight.controller.sal.core.spi.data.DOMStoreTransactionChain;
81 import org.opendaylight.controller.sal.core.spi.data.DOMStoreTransactionFactory;
82 import org.opendaylight.controller.sal.core.spi.data.DOMStoreWriteTransaction;
83 import org.opendaylight.yangtools.concepts.ListenerRegistration;
84 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
85 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
86 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
87 import scala.concurrent.duration.Duration;
88 import scala.concurrent.duration.FiniteDuration;
91 * A Shard represents a portion of the logical data tree <br/>
93 * Our Shard uses InMemoryDataStore as it's internal representation and delegates all requests it
96 public class Shard extends RaftActor {
98 private static final Object COMMIT_TRANSACTION_REPLY = new CommitTransactionReply().toSerializable();
100 private static final Object TX_COMMIT_TIMEOUT_CHECK_MESSAGE = "txCommitTimeoutCheck";
103 static final String DEFAULT_NAME = "default";
105 // The state of this Shard
106 private final InMemoryDOMDataStore store;
108 private final LoggingAdapter LOG =
109 Logging.getLogger(getContext().system(), this);
111 /// The name of this shard
112 private final ShardIdentifier name;
114 private final ShardStats shardMBean;
116 private final List<ActorSelection> dataChangeListeners = Lists.newArrayList();
118 private final List<DelayedListenerRegistration> delayedListenerRegistrations =
119 Lists.newArrayList();
121 private final DatastoreContext datastoreContext;
123 private final DataPersistenceProvider dataPersistenceProvider;
125 private SchemaContext schemaContext;
127 private ActorRef createSnapshotTransaction;
129 private int createSnapshotTransactionCounter;
131 private final ShardCommitCoordinator commitCoordinator;
133 private final long transactionCommitTimeout;
135 private Cancellable txCommitTimeoutCheckSchedule;
137 private final Optional<ActorRef> roleChangeNotifier;
140 * Coordinates persistence recovery on startup.
142 private ShardRecoveryCoordinator recoveryCoordinator;
143 private List<Object> currentLogRecoveryBatch;
145 private final Map<String, DOMStoreTransactionChain> transactionChains = new HashMap<>();
147 protected Shard(final ShardIdentifier name, final Map<ShardIdentifier, String> peerAddresses,
148 final DatastoreContext datastoreContext, final SchemaContext schemaContext) {
149 super(name.toString(), mapPeerAddresses(peerAddresses),
150 Optional.of(datastoreContext.getShardRaftConfig()));
153 this.datastoreContext = datastoreContext;
154 this.schemaContext = schemaContext;
155 this.dataPersistenceProvider = (datastoreContext.isPersistent()) ? new PersistentDataProvider() : new NonPersistentRaftDataProvider();
157 LOG.info("Shard created : {} persistent : {}", name, datastoreContext.isPersistent());
159 store = InMemoryDOMDataStoreFactory.create(name.toString(), null,
160 datastoreContext.getDataStoreProperties());
162 if(schemaContext != null) {
163 store.onGlobalContextUpdated(schemaContext);
166 shardMBean = ShardMBeanFactory.getShardStatsMBean(name.toString(),
167 datastoreContext.getDataStoreMXBeanType());
168 shardMBean.setNotificationManager(store.getDataChangeListenerNotificationManager());
170 if (isMetricsCaptureEnabled()) {
171 getContext().become(new MeteringBehavior(this));
174 commitCoordinator = new ShardCommitCoordinator(TimeUnit.SECONDS.convert(1, TimeUnit.MINUTES),
175 datastoreContext.getShardTransactionCommitQueueCapacity());
177 transactionCommitTimeout = TimeUnit.MILLISECONDS.convert(
178 datastoreContext.getShardTransactionCommitTimeoutInSeconds(), TimeUnit.SECONDS);
180 // create a notifier actor for each cluster member
181 roleChangeNotifier = createRoleChangeNotifier(name.toString());
184 private static Map<String, String> mapPeerAddresses(
185 final Map<ShardIdentifier, String> peerAddresses) {
186 Map<String, String> map = new HashMap<>();
188 for (Map.Entry<ShardIdentifier, String> entry : peerAddresses
190 map.put(entry.getKey().toString(), entry.getValue());
196 public static Props props(final ShardIdentifier name,
197 final Map<ShardIdentifier, String> peerAddresses,
198 final DatastoreContext datastoreContext, final SchemaContext schemaContext) {
199 Preconditions.checkNotNull(name, "name should not be null");
200 Preconditions.checkNotNull(peerAddresses, "peerAddresses should not be null");
201 Preconditions.checkNotNull(datastoreContext, "dataStoreContext should not be null");
202 Preconditions.checkNotNull(schemaContext, "schemaContext should not be null");
204 return Props.create(new ShardCreator(name, peerAddresses, datastoreContext, schemaContext));
207 private Optional<ActorRef> createRoleChangeNotifier(String shardId) {
208 ActorRef shardRoleChangeNotifier = this.getContext().actorOf(
209 RoleChangeNotifier.getProps(shardId), shardId + "-notifier");
210 return Optional.<ActorRef>of(shardRoleChangeNotifier);
214 public void postStop() {
217 if(txCommitTimeoutCheckSchedule != null) {
218 txCommitTimeoutCheckSchedule.cancel();
223 public void onReceiveRecover(final Object message) throws Exception {
224 if(LOG.isDebugEnabled()) {
225 LOG.debug("onReceiveRecover: Received message {} from {}",
226 message.getClass().toString(),
230 if (message instanceof RecoveryFailure){
231 LOG.error(((RecoveryFailure) message).cause(), "Recovery failed because of this cause");
233 // Even though recovery failed, we still need to finish our recovery, eg send the
234 // ActorInitialized message and start the txCommitTimeoutCheckSchedule.
235 onRecoveryComplete();
237 super.onReceiveRecover(message);
242 public void onReceiveCommand(final Object message) throws Exception {
243 if(LOG.isDebugEnabled()) {
244 LOG.debug("onReceiveCommand: Received message {} from {}", message, getSender());
247 if(message.getClass().equals(ReadDataReply.SERIALIZABLE_CLASS)) {
248 handleReadDataReply(message);
249 } else if (message.getClass().equals(CreateTransaction.SERIALIZABLE_CLASS)) {
250 handleCreateTransaction(message);
251 } else if(message instanceof ForwardedReadyTransaction) {
252 handleForwardedReadyTransaction((ForwardedReadyTransaction)message);
253 } else if(message.getClass().equals(CanCommitTransaction.SERIALIZABLE_CLASS)) {
254 handleCanCommitTransaction(CanCommitTransaction.fromSerializable(message));
255 } else if(message.getClass().equals(CommitTransaction.SERIALIZABLE_CLASS)) {
256 handleCommitTransaction(CommitTransaction.fromSerializable(message));
257 } else if(message.getClass().equals(AbortTransaction.SERIALIZABLE_CLASS)) {
258 handleAbortTransaction(AbortTransaction.fromSerializable(message));
259 } else if (message.getClass().equals(CloseTransactionChain.SERIALIZABLE_CLASS)){
260 closeTransactionChain(CloseTransactionChain.fromSerializable(message));
261 } else if (message instanceof RegisterChangeListener) {
262 registerChangeListener((RegisterChangeListener) message);
263 } else if (message instanceof UpdateSchemaContext) {
264 updateSchemaContext((UpdateSchemaContext) message);
265 } else if (message instanceof PeerAddressResolved) {
266 PeerAddressResolved resolved = (PeerAddressResolved) message;
267 setPeerAddress(resolved.getPeerId().toString(),
268 resolved.getPeerAddress());
269 } else if(message.equals(TX_COMMIT_TIMEOUT_CHECK_MESSAGE)) {
270 handleTransactionCommitTimeoutCheck();
272 super.onReceiveCommand(message);
277 protected Optional<ActorRef> getRoleChangeNotifier() {
278 return roleChangeNotifier;
281 private void handleTransactionCommitTimeoutCheck() {
282 CohortEntry cohortEntry = commitCoordinator.getCurrentCohortEntry();
283 if(cohortEntry != null) {
284 long elapsed = System.currentTimeMillis() - cohortEntry.getLastAccessTime();
285 if(elapsed > transactionCommitTimeout) {
286 LOG.warning("Current transaction {} has timed out after {} ms - aborting",
287 cohortEntry.getTransactionID(), transactionCommitTimeout);
289 doAbortTransaction(cohortEntry.getTransactionID(), null);
294 private void handleCommitTransaction(final CommitTransaction commit) {
295 final String transactionID = commit.getTransactionID();
297 LOG.debug("Committing transaction {}", transactionID);
299 // Get the current in-progress cohort entry in the commitCoordinator if it corresponds to
301 final CohortEntry cohortEntry = commitCoordinator.getCohortEntryIfCurrent(transactionID);
302 if(cohortEntry == null) {
303 // We're not the current Tx - the Tx was likely expired b/c it took too long in
304 // between the canCommit and commit messages.
305 IllegalStateException ex = new IllegalStateException(
306 String.format("Cannot commit transaction %s - it is not the current transaction",
308 LOG.error(ex.getMessage());
309 shardMBean.incrementFailedTransactionsCount();
310 getSender().tell(new akka.actor.Status.Failure(ex), getSelf());
314 // We perform the preCommit phase here atomically with the commit phase. This is an
315 // optimization to eliminate the overhead of an extra preCommit message. We lose front-end
316 // coordination of preCommit across shards in case of failure but preCommit should not
317 // normally fail since we ensure only one concurrent 3-phase commit.
320 // We block on the future here so we don't have to worry about possibly accessing our
321 // state on a different thread outside of our dispatcher. Also, the data store
322 // currently uses a same thread executor anyway.
323 cohortEntry.getCohort().preCommit().get();
325 // If we do not have any followers and we are not using persistence we can
326 // apply modification to the state immediately
327 if(!hasFollowers() && !persistence().isRecoveryApplicable()){
328 applyModificationToState(getSender(), transactionID, cohortEntry.getModification());
330 Shard.this.persistData(getSender(), transactionID,
331 new CompositeModificationByteStringPayload(cohortEntry.getModification().toSerializable()));
333 } catch (InterruptedException | ExecutionException e) {
334 LOG.error(e, "An exception occurred while preCommitting transaction {}",
335 cohortEntry.getTransactionID());
336 shardMBean.incrementFailedTransactionsCount();
337 getSender().tell(new akka.actor.Status.Failure(e), getSelf());
340 cohortEntry.updateLastAccessTime();
343 private void finishCommit(@Nonnull final ActorRef sender, final @Nonnull String transactionID) {
344 // With persistence enabled, this method is called via applyState by the leader strategy
345 // after the commit has been replicated to a majority of the followers.
347 CohortEntry cohortEntry = commitCoordinator.getCohortEntryIfCurrent(transactionID);
348 if(cohortEntry == null) {
349 // The transaction is no longer the current commit. This can happen if the transaction
350 // was aborted prior, most likely due to timeout in the front-end. We need to finish
351 // committing the transaction though since it was successfully persisted and replicated
352 // however we can't use the original cohort b/c it was already preCommitted and may
353 // conflict with the current commit or may have been aborted so we commit with a new
355 cohortEntry = commitCoordinator.getAndRemoveCohortEntry(transactionID);
356 if(cohortEntry != null) {
357 commitWithNewTransaction(cohortEntry.getModification());
358 sender.tell(COMMIT_TRANSACTION_REPLY, getSelf());
360 // This really shouldn't happen - it likely means that persistence or replication
361 // took so long to complete such that the cohort entry was expired from the cache.
362 IllegalStateException ex = new IllegalStateException(
363 String.format("Could not finish committing transaction %s - no CohortEntry found",
365 LOG.error(ex.getMessage());
366 sender.tell(new akka.actor.Status.Failure(ex), getSelf());
372 LOG.debug("Finishing commit for transaction {}", cohortEntry.getTransactionID());
375 // We block on the future here so we don't have to worry about possibly accessing our
376 // state on a different thread outside of our dispatcher. Also, the data store
377 // currently uses a same thread executor anyway.
378 cohortEntry.getCohort().commit().get();
380 sender.tell(COMMIT_TRANSACTION_REPLY, getSelf());
382 shardMBean.incrementCommittedTransactionCount();
383 shardMBean.setLastCommittedTransactionTime(System.currentTimeMillis());
385 } catch (InterruptedException | ExecutionException e) {
386 sender.tell(new akka.actor.Status.Failure(e), getSelf());
388 LOG.error(e, "An exception occurred while committing transaction {}", transactionID);
389 shardMBean.incrementFailedTransactionsCount();
392 commitCoordinator.currentTransactionComplete(transactionID, true);
395 private void handleCanCommitTransaction(final CanCommitTransaction canCommit) {
396 LOG.debug("Can committing transaction {}", canCommit.getTransactionID());
397 commitCoordinator.handleCanCommit(canCommit, getSender(), self());
400 private void handleForwardedReadyTransaction(ForwardedReadyTransaction ready) {
401 LOG.debug("Readying transaction {}, client version {}", ready.getTransactionID(),
402 ready.getTxnClientVersion());
404 // This message is forwarded by the ShardTransaction on ready. We cache the cohort in the
405 // commitCoordinator in preparation for the subsequent three phase commit initiated by
407 commitCoordinator.transactionReady(ready.getTransactionID(), ready.getCohort(),
408 ready.getModification());
410 // Return our actor path as we'll handle the three phase commit, except if the Tx client
411 // version < 1 (Helium-1 version). This means the Tx was initiated by a base Helium version
412 // node. In that case, the subsequent 3-phase commit messages won't contain the
413 // transactionId so to maintain backwards compatibility, we create a separate cohort actor
414 // to provide the compatible behavior.
415 ActorRef replyActorPath = self();
416 if(ready.getTxnClientVersion() < CreateTransaction.HELIUM_1_VERSION) {
417 LOG.debug("Creating BackwardsCompatibleThreePhaseCommitCohort");
418 replyActorPath = getContext().actorOf(BackwardsCompatibleThreePhaseCommitCohort.props(
419 ready.getTransactionID()));
422 ReadyTransactionReply readyTransactionReply = new ReadyTransactionReply(
423 Serialization.serializedActorPath(replyActorPath));
424 getSender().tell(ready.isReturnSerialized() ? readyTransactionReply.toSerializable() :
425 readyTransactionReply, getSelf());
428 private void handleAbortTransaction(final AbortTransaction abort) {
429 doAbortTransaction(abort.getTransactionID(), getSender());
432 void doAbortTransaction(final String transactionID, final ActorRef sender) {
433 final CohortEntry cohortEntry = commitCoordinator.getCohortEntryIfCurrent(transactionID);
434 if(cohortEntry != null) {
435 LOG.debug("Aborting transaction {}", transactionID);
437 // We don't remove the cached cohort entry here (ie pass false) in case the Tx was
438 // aborted during replication in which case we may still commit locally if replication
440 commitCoordinator.currentTransactionComplete(transactionID, false);
442 final ListenableFuture<Void> future = cohortEntry.getCohort().abort();
443 final ActorRef self = getSelf();
445 Futures.addCallback(future, new FutureCallback<Void>() {
447 public void onSuccess(final Void v) {
448 shardMBean.incrementAbortTransactionsCount();
451 sender.tell(new AbortTransactionReply().toSerializable(), self);
456 public void onFailure(final Throwable t) {
457 LOG.error(t, "An exception happened during abort");
460 sender.tell(new akka.actor.Status.Failure(t), self);
467 private void handleCreateTransaction(final Object message) {
469 createTransaction(CreateTransaction.fromSerializable(message));
470 } else if (getLeader() != null) {
471 getLeader().forward(message, getContext());
473 getSender().tell(new akka.actor.Status.Failure(new NoShardLeaderException(
474 "Could not find shard leader so transaction cannot be created. This typically happens" +
475 " when the system is coming up or recovering and a leader is being elected. Try again" +
476 " later.")), getSelf());
480 private void handleReadDataReply(final Object message) {
481 // This must be for install snapshot. Don't want to open this up and trigger
484 self().tell(new CaptureSnapshotReply(ReadDataReply.getNormalizedNodeByteString(message)),
487 createSnapshotTransaction = null;
489 // Send a PoisonPill instead of sending close transaction because we do not really need
491 getSender().tell(PoisonPill.getInstance(), self());
494 private void closeTransactionChain(final CloseTransactionChain closeTransactionChain) {
495 DOMStoreTransactionChain chain =
496 transactionChains.remove(closeTransactionChain.getTransactionChainId());
503 private ActorRef createTypedTransactionActor(int transactionType,
504 ShardTransactionIdentifier transactionId, String transactionChainId, int clientVersion ) {
506 DOMStoreTransactionFactory factory = store;
508 if(!transactionChainId.isEmpty()) {
509 factory = transactionChains.get(transactionChainId);
511 DOMStoreTransactionChain transactionChain = store.createTransactionChain();
512 transactionChains.put(transactionChainId, transactionChain);
513 factory = transactionChain;
517 if(this.schemaContext == null) {
518 throw new IllegalStateException("SchemaContext is not set");
521 if (transactionType == TransactionProxy.TransactionType.READ_ONLY.ordinal()) {
523 shardMBean.incrementReadOnlyTransactionCount();
525 return getContext().actorOf(
526 ShardTransaction.props(factory.newReadOnlyTransaction(), getSelf(),
527 schemaContext,datastoreContext, shardMBean,
528 transactionId.getRemoteTransactionId(), clientVersion),
529 transactionId.toString());
531 } else if (transactionType == TransactionProxy.TransactionType.READ_WRITE.ordinal()) {
533 shardMBean.incrementReadWriteTransactionCount();
535 return getContext().actorOf(
536 ShardTransaction.props(factory.newReadWriteTransaction(), getSelf(),
537 schemaContext, datastoreContext, shardMBean,
538 transactionId.getRemoteTransactionId(), clientVersion),
539 transactionId.toString());
542 } else if (transactionType == TransactionProxy.TransactionType.WRITE_ONLY.ordinal()) {
544 shardMBean.incrementWriteOnlyTransactionCount();
546 return getContext().actorOf(
547 ShardTransaction.props(factory.newWriteOnlyTransaction(), getSelf(),
548 schemaContext, datastoreContext, shardMBean,
549 transactionId.getRemoteTransactionId(), clientVersion),
550 transactionId.toString());
552 throw new IllegalArgumentException(
553 "Shard="+name + ":CreateTransaction message has unidentified transaction type="
558 private void createTransaction(CreateTransaction createTransaction) {
560 ActorRef transactionActor = createTransaction(createTransaction.getTransactionType(),
561 createTransaction.getTransactionId(), createTransaction.getTransactionChainId(),
562 createTransaction.getVersion());
564 getSender().tell(new CreateTransactionReply(Serialization.serializedActorPath(transactionActor),
565 createTransaction.getTransactionId()).toSerializable(), getSelf());
566 } catch (Exception e) {
567 getSender().tell(new akka.actor.Status.Failure(e), getSelf());
571 private ActorRef createTransaction(int transactionType, String remoteTransactionId,
572 String transactionChainId, int clientVersion) {
574 ShardTransactionIdentifier transactionId =
575 ShardTransactionIdentifier.builder()
576 .remoteTransactionId(remoteTransactionId)
579 if(LOG.isDebugEnabled()) {
580 LOG.debug("Creating transaction : {} ", transactionId);
583 ActorRef transactionActor = createTypedTransactionActor(transactionType, transactionId,
584 transactionChainId, clientVersion);
586 return transactionActor;
589 private void syncCommitTransaction(final DOMStoreWriteTransaction transaction)
590 throws ExecutionException, InterruptedException {
591 DOMStoreThreePhaseCommitCohort commitCohort = transaction.ready();
592 commitCohort.preCommit().get();
593 commitCohort.commit().get();
596 private void commitWithNewTransaction(final Modification modification) {
597 DOMStoreWriteTransaction tx = store.newWriteOnlyTransaction();
598 modification.apply(tx);
600 syncCommitTransaction(tx);
601 shardMBean.incrementCommittedTransactionCount();
602 shardMBean.setLastCommittedTransactionTime(System.currentTimeMillis());
603 } catch (InterruptedException | ExecutionException e) {
604 shardMBean.incrementFailedTransactionsCount();
605 LOG.error(e, "Failed to commit");
609 private void updateSchemaContext(final UpdateSchemaContext message) {
610 this.schemaContext = message.getSchemaContext();
611 updateSchemaContext(message.getSchemaContext());
612 store.onGlobalContextUpdated(message.getSchemaContext());
616 void updateSchemaContext(final SchemaContext schemaContext) {
617 store.onGlobalContextUpdated(schemaContext);
620 private void registerChangeListener(final RegisterChangeListener registerChangeListener) {
622 LOG.debug("registerDataChangeListener for {}", registerChangeListener.getPath());
624 ListenerRegistration<AsyncDataChangeListener<YangInstanceIdentifier,
625 NormalizedNode<?, ?>>> registration;
627 registration = doChangeListenerRegistration(registerChangeListener);
629 LOG.debug("Shard is not the leader - delaying registration");
631 DelayedListenerRegistration delayedReg =
632 new DelayedListenerRegistration(registerChangeListener);
633 delayedListenerRegistrations.add(delayedReg);
634 registration = delayedReg;
637 ActorRef listenerRegistration = getContext().actorOf(
638 DataChangeListenerRegistration.props(registration));
640 LOG.debug("registerDataChangeListener sending reply, listenerRegistrationPath = {} ",
641 listenerRegistration.path());
643 getSender().tell(new RegisterChangeListenerReply(listenerRegistration.path()), getSelf());
646 private ListenerRegistration<AsyncDataChangeListener<YangInstanceIdentifier,
647 NormalizedNode<?, ?>>> doChangeListenerRegistration(
648 final RegisterChangeListener registerChangeListener) {
650 ActorSelection dataChangeListenerPath = getContext().system().actorSelection(
651 registerChangeListener.getDataChangeListenerPath());
653 // Notify the listener if notifications should be enabled or not
654 // If this shard is the leader then it will enable notifications else
656 dataChangeListenerPath.tell(new EnableNotification(true), getSelf());
658 // Now store a reference to the data change listener so it can be notified
659 // at a later point if notifications should be enabled or disabled
660 dataChangeListeners.add(dataChangeListenerPath);
662 AsyncDataChangeListener<YangInstanceIdentifier, NormalizedNode<?, ?>> listener =
663 new DataChangeListenerProxy(schemaContext, dataChangeListenerPath);
665 LOG.debug("Registering for path {}", registerChangeListener.getPath());
667 return store.registerChangeListener(registerChangeListener.getPath(), listener,
668 registerChangeListener.getScope());
671 private boolean isMetricsCaptureEnabled(){
672 CommonConfig config = new CommonConfig(getContext().system().settings().config());
673 return config.isMetricCaptureEnabled();
678 void startLogRecoveryBatch(final int maxBatchSize) {
679 currentLogRecoveryBatch = Lists.newArrayListWithCapacity(maxBatchSize);
681 if(LOG.isDebugEnabled()) {
682 LOG.debug("{} : starting log recovery batch with max size {}", persistenceId(), maxBatchSize);
687 protected void appendRecoveredLogEntry(final Payload data) {
688 if (data instanceof CompositeModificationPayload) {
689 currentLogRecoveryBatch.add(((CompositeModificationPayload) data).getModification());
690 } else if (data instanceof CompositeModificationByteStringPayload) {
691 currentLogRecoveryBatch.add(((CompositeModificationByteStringPayload) data).getModification());
693 LOG.error("Unknown state received {} during recovery", data);
698 protected void applyRecoverySnapshot(final ByteString snapshot) {
699 if(recoveryCoordinator == null) {
700 recoveryCoordinator = new ShardRecoveryCoordinator(persistenceId(), schemaContext);
703 recoveryCoordinator.submit(snapshot, store.newWriteOnlyTransaction());
705 if(LOG.isDebugEnabled()) {
706 LOG.debug("{} : submitted recovery sbapshot", persistenceId());
711 protected void applyCurrentLogRecoveryBatch() {
712 if(recoveryCoordinator == null) {
713 recoveryCoordinator = new ShardRecoveryCoordinator(persistenceId(), schemaContext);
716 recoveryCoordinator.submit(currentLogRecoveryBatch, store.newWriteOnlyTransaction());
718 if(LOG.isDebugEnabled()) {
719 LOG.debug("{} : submitted log recovery batch with size {}", persistenceId(),
720 currentLogRecoveryBatch.size());
725 protected void onRecoveryComplete() {
726 if(recoveryCoordinator != null) {
727 Collection<DOMStoreWriteTransaction> txList = recoveryCoordinator.getTransactions();
729 if(LOG.isDebugEnabled()) {
730 LOG.debug("{} : recovery complete - committing {} Tx's", persistenceId(), txList.size());
733 for(DOMStoreWriteTransaction tx: txList) {
735 syncCommitTransaction(tx);
736 shardMBean.incrementCommittedTransactionCount();
737 } catch (InterruptedException | ExecutionException e) {
738 shardMBean.incrementFailedTransactionsCount();
739 LOG.error(e, "Failed to commit");
744 recoveryCoordinator = null;
745 currentLogRecoveryBatch = null;
746 updateJournalStats();
748 //notify shard manager
749 getContext().parent().tell(new ActorInitialized(), getSelf());
751 // Being paranoid here - this method should only be called once but just in case...
752 if(txCommitTimeoutCheckSchedule == null) {
753 // Schedule a message to be periodically sent to check if the current in-progress
754 // transaction should be expired and aborted.
755 FiniteDuration period = Duration.create(transactionCommitTimeout / 3, TimeUnit.MILLISECONDS);
756 txCommitTimeoutCheckSchedule = getContext().system().scheduler().schedule(
757 period, period, getSelf(),
758 TX_COMMIT_TIMEOUT_CHECK_MESSAGE, getContext().dispatcher(), ActorRef.noSender());
763 protected void applyState(final ActorRef clientActor, final String identifier, final Object data) {
765 if (data instanceof CompositeModificationPayload) {
766 Object modification = ((CompositeModificationPayload) data).getModification();
768 applyModificationToState(clientActor, identifier, modification);
769 } else if(data instanceof CompositeModificationByteStringPayload ){
770 Object modification = ((CompositeModificationByteStringPayload) data).getModification();
772 applyModificationToState(clientActor, identifier, modification);
775 LOG.error("Unknown state received {} Class loader = {} CompositeNodeMod.ClassLoader = {}",
776 data, data.getClass().getClassLoader(),
777 CompositeModificationPayload.class.getClassLoader());
780 updateJournalStats();
784 private void applyModificationToState(ActorRef clientActor, String identifier, Object modification) {
785 if(modification == null) {
787 "modification is null - this is very unexpected, clientActor = {}, identifier = {}",
788 identifier, clientActor != null ? clientActor.path().toString() : null);
789 } else if(clientActor == null) {
790 // There's no clientActor to which to send a commit reply so we must be applying
791 // replicated state from the leader.
792 commitWithNewTransaction(MutableCompositeModification.fromSerializable(
793 modification, schemaContext));
795 // This must be the OK to commit after replication consensus.
796 finishCommit(clientActor, identifier);
800 private void updateJournalStats() {
801 ReplicatedLogEntry lastLogEntry = getLastLogEntry();
803 if (lastLogEntry != null) {
804 shardMBean.setLastLogIndex(lastLogEntry.getIndex());
805 shardMBean.setLastLogTerm(lastLogEntry.getTerm());
808 shardMBean.setCommitIndex(getCommitIndex());
809 shardMBean.setLastApplied(getLastApplied());
810 shardMBean.setInMemoryJournalDataSize(getRaftActorContext().getReplicatedLog().dataSize());
814 protected void createSnapshot() {
815 if (createSnapshotTransaction == null) {
817 // Create a transaction. We are really going to treat the transaction as a worker
818 // so that this actor does not get block building the snapshot
819 createSnapshotTransaction = createTransaction(
820 TransactionProxy.TransactionType.READ_ONLY.ordinal(),
821 "createSnapshot" + ++createSnapshotTransactionCounter, "",
822 CreateTransaction.CURRENT_VERSION);
824 createSnapshotTransaction.tell(
825 new ReadData(YangInstanceIdentifier.builder().build()).toSerializable(), self());
832 protected void applySnapshot(final ByteString snapshot) {
833 // Since this will be done only on Recovery or when this actor is a Follower
834 // we can safely commit everything in here. We not need to worry about event notifications
835 // as they would have already been disabled on the follower
837 LOG.info("Applying snapshot");
839 DOMStoreWriteTransaction transaction = store.newWriteOnlyTransaction();
840 NormalizedNodeMessages.Node serializedNode = NormalizedNodeMessages.Node.parseFrom(snapshot);
841 NormalizedNode<?, ?> node = new NormalizedNodeToNodeCodec(schemaContext)
842 .decode(serializedNode);
844 // delete everything first
845 transaction.delete(YangInstanceIdentifier.builder().build());
847 // Add everything from the remote node back
848 transaction.write(YangInstanceIdentifier.builder().build(), node);
849 syncCommitTransaction(transaction);
850 } catch (InvalidProtocolBufferException | InterruptedException | ExecutionException e) {
851 LOG.error(e, "An exception occurred when applying snapshot");
853 LOG.info("Done applying snapshot");
858 protected void onStateChanged() {
859 boolean isLeader = isLeader();
860 for (ActorSelection dataChangeListener : dataChangeListeners) {
861 dataChangeListener.tell(new EnableNotification(isLeader), getSelf());
865 for(DelayedListenerRegistration reg: delayedListenerRegistrations) {
866 if(!reg.isClosed()) {
867 reg.setDelegate(doChangeListenerRegistration(reg.getRegisterChangeListener()));
871 delayedListenerRegistrations.clear();
874 shardMBean.setRaftState(getRaftState().name());
875 shardMBean.setCurrentTerm(getCurrentTerm());
877 // If this actor is no longer the leader close all the transaction chains
879 for(Map.Entry<String, DOMStoreTransactionChain> entry : transactionChains.entrySet()){
880 if(LOG.isDebugEnabled()) {
882 "onStateChanged: Closing transaction chain {} because shard {} is no longer the leader",
883 entry.getKey(), getId());
885 entry.getValue().close();
888 transactionChains.clear();
893 protected DataPersistenceProvider persistence() {
894 return dataPersistenceProvider;
897 @Override protected void onLeaderChanged(final String oldLeader, final String newLeader) {
898 shardMBean.setLeader(newLeader);
901 @Override public String persistenceId() {
902 return this.name.toString();
906 DataPersistenceProvider getDataPersistenceProvider() {
907 return dataPersistenceProvider;
910 private static class ShardCreator implements Creator<Shard> {
912 private static final long serialVersionUID = 1L;
914 final ShardIdentifier name;
915 final Map<ShardIdentifier, String> peerAddresses;
916 final DatastoreContext datastoreContext;
917 final SchemaContext schemaContext;
919 ShardCreator(final ShardIdentifier name, final Map<ShardIdentifier, String> peerAddresses,
920 final DatastoreContext datastoreContext, final SchemaContext schemaContext) {
922 this.peerAddresses = peerAddresses;
923 this.datastoreContext = datastoreContext;
924 this.schemaContext = schemaContext;
928 public Shard create() throws Exception {
929 return new Shard(name, peerAddresses, datastoreContext, schemaContext);
934 InMemoryDOMDataStore getDataStore() {
939 ShardStats getShardMBean() {
943 private static class DelayedListenerRegistration implements
944 ListenerRegistration<AsyncDataChangeListener<YangInstanceIdentifier, NormalizedNode<?, ?>>> {
946 private volatile boolean closed;
948 private final RegisterChangeListener registerChangeListener;
950 private volatile ListenerRegistration<AsyncDataChangeListener<YangInstanceIdentifier,
951 NormalizedNode<?, ?>>> delegate;
953 DelayedListenerRegistration(final RegisterChangeListener registerChangeListener) {
954 this.registerChangeListener = registerChangeListener;
957 void setDelegate( final ListenerRegistration<AsyncDataChangeListener<YangInstanceIdentifier,
958 NormalizedNode<?, ?>>> registration) {
959 this.delegate = registration;
966 RegisterChangeListener getRegisterChangeListener() {
967 return registerChangeListener;
971 public AsyncDataChangeListener<YangInstanceIdentifier, NormalizedNode<?, ?>> getInstance() {
972 return delegate != null ? delegate.getInstance() : null;
976 public void close() {
978 if(delegate != null) {