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.io.IOException;
31 import java.util.Collection;
32 import java.util.HashMap;
33 import java.util.List;
35 import java.util.concurrent.ExecutionException;
36 import java.util.concurrent.TimeUnit;
37 import javax.annotation.Nonnull;
38 import org.opendaylight.controller.cluster.DataPersistenceProvider;
39 import org.opendaylight.controller.cluster.common.actor.CommonConfig;
40 import org.opendaylight.controller.cluster.common.actor.MeteringBehavior;
41 import org.opendaylight.controller.cluster.datastore.ShardCommitCoordinator.CohortEntry;
42 import org.opendaylight.controller.cluster.datastore.compat.BackwardsCompatibleThreePhaseCommitCohort;
43 import org.opendaylight.controller.cluster.datastore.exceptions.NoShardLeaderException;
44 import org.opendaylight.controller.cluster.datastore.identifiers.ShardIdentifier;
45 import org.opendaylight.controller.cluster.datastore.identifiers.ShardTransactionIdentifier;
46 import org.opendaylight.controller.cluster.datastore.jmx.mbeans.shard.ShardMBeanFactory;
47 import org.opendaylight.controller.cluster.datastore.jmx.mbeans.shard.ShardStats;
48 import org.opendaylight.controller.cluster.datastore.messages.AbortTransaction;
49 import org.opendaylight.controller.cluster.datastore.messages.AbortTransactionReply;
50 import org.opendaylight.controller.cluster.datastore.messages.ActorInitialized;
51 import org.opendaylight.controller.cluster.datastore.messages.CanCommitTransaction;
52 import org.opendaylight.controller.cluster.datastore.messages.CloseTransactionChain;
53 import org.opendaylight.controller.cluster.datastore.messages.CommitTransaction;
54 import org.opendaylight.controller.cluster.datastore.messages.CommitTransactionReply;
55 import org.opendaylight.controller.cluster.datastore.messages.CreateTransaction;
56 import org.opendaylight.controller.cluster.datastore.messages.CreateTransactionReply;
57 import org.opendaylight.controller.cluster.datastore.messages.EnableNotification;
58 import org.opendaylight.controller.cluster.datastore.messages.ForwardedReadyTransaction;
59 import org.opendaylight.controller.cluster.datastore.messages.PeerAddressResolved;
60 import org.opendaylight.controller.cluster.datastore.messages.ReadData;
61 import org.opendaylight.controller.cluster.datastore.messages.ReadDataReply;
62 import org.opendaylight.controller.cluster.datastore.messages.ReadyTransactionReply;
63 import org.opendaylight.controller.cluster.datastore.messages.RegisterChangeListener;
64 import org.opendaylight.controller.cluster.datastore.messages.RegisterChangeListenerReply;
65 import org.opendaylight.controller.cluster.datastore.messages.UpdateSchemaContext;
66 import org.opendaylight.controller.cluster.datastore.modification.Modification;
67 import org.opendaylight.controller.cluster.datastore.modification.ModificationPayload;
68 import org.opendaylight.controller.cluster.datastore.modification.MutableCompositeModification;
69 import org.opendaylight.controller.cluster.datastore.node.NormalizedNodeToNodeCodec;
70 import org.opendaylight.controller.cluster.notifications.RoleChangeNotifier;
71 import org.opendaylight.controller.cluster.raft.RaftActor;
72 import org.opendaylight.controller.cluster.raft.ReplicatedLogEntry;
73 import org.opendaylight.controller.cluster.raft.base.messages.CaptureSnapshotReply;
74 import org.opendaylight.controller.cluster.raft.protobuff.client.messages.CompositeModificationByteStringPayload;
75 import org.opendaylight.controller.cluster.raft.protobuff.client.messages.CompositeModificationPayload;
76 import org.opendaylight.controller.cluster.raft.protobuff.client.messages.Payload;
77 import org.opendaylight.controller.md.sal.common.api.data.AsyncDataChangeListener;
78 import org.opendaylight.controller.md.sal.dom.store.impl.InMemoryDOMDataStore;
79 import org.opendaylight.controller.md.sal.dom.store.impl.InMemoryDOMDataStoreFactory;
80 import org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages;
81 import org.opendaylight.controller.sal.core.spi.data.DOMStoreThreePhaseCommitCohort;
82 import org.opendaylight.controller.sal.core.spi.data.DOMStoreTransactionChain;
83 import org.opendaylight.controller.sal.core.spi.data.DOMStoreTransactionFactory;
84 import org.opendaylight.controller.sal.core.spi.data.DOMStoreWriteTransaction;
85 import org.opendaylight.yangtools.concepts.ListenerRegistration;
86 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
87 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
88 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
89 import scala.concurrent.duration.Duration;
90 import scala.concurrent.duration.FiniteDuration;
93 * A Shard represents a portion of the logical data tree <br/>
95 * Our Shard uses InMemoryDataStore as it's internal representation and delegates all requests it
98 public class Shard extends RaftActor {
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 ModificationPayload(cohortEntry.getModification()));
333 } catch (InterruptedException | ExecutionException | IOException 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(CommitTransactionReply.INSTANCE.toSerializable(), 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(CommitTransactionReply.INSTANCE.toSerializable(), 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() < DataStoreVersions.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(AbortTransactionReply.INSTANCE.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.fromSerializableAsByteString(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,
505 short clientVersion ) {
507 DOMStoreTransactionFactory factory = store;
509 if(!transactionChainId.isEmpty()) {
510 factory = transactionChains.get(transactionChainId);
512 DOMStoreTransactionChain transactionChain = store.createTransactionChain();
513 transactionChains.put(transactionChainId, transactionChain);
514 factory = transactionChain;
518 if(this.schemaContext == null) {
519 throw new IllegalStateException("SchemaContext is not set");
522 if (transactionType == TransactionProxy.TransactionType.READ_ONLY.ordinal()) {
524 shardMBean.incrementReadOnlyTransactionCount();
526 return getContext().actorOf(
527 ShardTransaction.props(factory.newReadOnlyTransaction(), getSelf(),
528 schemaContext,datastoreContext, shardMBean,
529 transactionId.getRemoteTransactionId(), clientVersion),
530 transactionId.toString());
532 } else if (transactionType == TransactionProxy.TransactionType.READ_WRITE.ordinal()) {
534 shardMBean.incrementReadWriteTransactionCount();
536 return getContext().actorOf(
537 ShardTransaction.props(factory.newReadWriteTransaction(), getSelf(),
538 schemaContext, datastoreContext, shardMBean,
539 transactionId.getRemoteTransactionId(), clientVersion),
540 transactionId.toString());
543 } else if (transactionType == TransactionProxy.TransactionType.WRITE_ONLY.ordinal()) {
545 shardMBean.incrementWriteOnlyTransactionCount();
547 return getContext().actorOf(
548 ShardTransaction.props(factory.newWriteOnlyTransaction(), getSelf(),
549 schemaContext, datastoreContext, shardMBean,
550 transactionId.getRemoteTransactionId(), clientVersion),
551 transactionId.toString());
553 throw new IllegalArgumentException(
554 "Shard="+name + ":CreateTransaction message has unidentified transaction type="
559 private void createTransaction(CreateTransaction createTransaction) {
561 ActorRef transactionActor = createTransaction(createTransaction.getTransactionType(),
562 createTransaction.getTransactionId(), createTransaction.getTransactionChainId(),
563 createTransaction.getVersion());
565 getSender().tell(new CreateTransactionReply(Serialization.serializedActorPath(transactionActor),
566 createTransaction.getTransactionId()).toSerializable(), getSelf());
567 } catch (Exception e) {
568 getSender().tell(new akka.actor.Status.Failure(e), getSelf());
572 private ActorRef createTransaction(int transactionType, String remoteTransactionId,
573 String transactionChainId, short clientVersion) {
575 ShardTransactionIdentifier transactionId =
576 ShardTransactionIdentifier.builder()
577 .remoteTransactionId(remoteTransactionId)
580 if(LOG.isDebugEnabled()) {
581 LOG.debug("Creating transaction : {} ", transactionId);
584 ActorRef transactionActor = createTypedTransactionActor(transactionType, transactionId,
585 transactionChainId, clientVersion);
587 return transactionActor;
590 private void syncCommitTransaction(final DOMStoreWriteTransaction transaction)
591 throws ExecutionException, InterruptedException {
592 DOMStoreThreePhaseCommitCohort commitCohort = transaction.ready();
593 commitCohort.preCommit().get();
594 commitCohort.commit().get();
597 private void commitWithNewTransaction(final Modification modification) {
598 DOMStoreWriteTransaction tx = store.newWriteOnlyTransaction();
599 modification.apply(tx);
601 syncCommitTransaction(tx);
602 shardMBean.incrementCommittedTransactionCount();
603 shardMBean.setLastCommittedTransactionTime(System.currentTimeMillis());
604 } catch (InterruptedException | ExecutionException e) {
605 shardMBean.incrementFailedTransactionsCount();
606 LOG.error(e, "Failed to commit");
610 private void updateSchemaContext(final UpdateSchemaContext message) {
611 this.schemaContext = message.getSchemaContext();
612 updateSchemaContext(message.getSchemaContext());
613 store.onGlobalContextUpdated(message.getSchemaContext());
617 void updateSchemaContext(final SchemaContext schemaContext) {
618 store.onGlobalContextUpdated(schemaContext);
621 private void registerChangeListener(final RegisterChangeListener registerChangeListener) {
623 LOG.debug("registerDataChangeListener for {}", registerChangeListener.getPath());
625 ListenerRegistration<AsyncDataChangeListener<YangInstanceIdentifier,
626 NormalizedNode<?, ?>>> registration;
628 registration = doChangeListenerRegistration(registerChangeListener);
630 LOG.debug("Shard is not the leader - delaying registration");
632 DelayedListenerRegistration delayedReg =
633 new DelayedListenerRegistration(registerChangeListener);
634 delayedListenerRegistrations.add(delayedReg);
635 registration = delayedReg;
638 ActorRef listenerRegistration = getContext().actorOf(
639 DataChangeListenerRegistration.props(registration));
641 LOG.debug("registerDataChangeListener sending reply, listenerRegistrationPath = {} ",
642 listenerRegistration.path());
644 getSender().tell(new RegisterChangeListenerReply(listenerRegistration.path()), getSelf());
647 private ListenerRegistration<AsyncDataChangeListener<YangInstanceIdentifier,
648 NormalizedNode<?, ?>>> doChangeListenerRegistration(
649 final RegisterChangeListener registerChangeListener) {
651 ActorSelection dataChangeListenerPath = getContext().system().actorSelection(
652 registerChangeListener.getDataChangeListenerPath());
654 // Notify the listener if notifications should be enabled or not
655 // If this shard is the leader then it will enable notifications else
657 dataChangeListenerPath.tell(new EnableNotification(true), getSelf());
659 // Now store a reference to the data change listener so it can be notified
660 // at a later point if notifications should be enabled or disabled
661 dataChangeListeners.add(dataChangeListenerPath);
663 AsyncDataChangeListener<YangInstanceIdentifier, NormalizedNode<?, ?>> listener =
664 new DataChangeListenerProxy(dataChangeListenerPath);
666 LOG.debug("Registering for path {}", registerChangeListener.getPath());
668 return store.registerChangeListener(registerChangeListener.getPath(), listener,
669 registerChangeListener.getScope());
672 private boolean isMetricsCaptureEnabled(){
673 CommonConfig config = new CommonConfig(getContext().system().settings().config());
674 return config.isMetricCaptureEnabled();
679 void startLogRecoveryBatch(final int maxBatchSize) {
680 currentLogRecoveryBatch = Lists.newArrayListWithCapacity(maxBatchSize);
682 if(LOG.isDebugEnabled()) {
683 LOG.debug("{} : starting log recovery batch with max size {}", persistenceId(), maxBatchSize);
688 protected void appendRecoveredLogEntry(final Payload data) {
689 if(data instanceof ModificationPayload) {
691 currentLogRecoveryBatch.add(((ModificationPayload) data).getModification());
692 } catch (ClassNotFoundException | IOException e) {
693 LOG.error(e, "Error extracting ModificationPayload");
695 } else if (data instanceof CompositeModificationPayload) {
696 currentLogRecoveryBatch.add(((CompositeModificationPayload) data).getModification());
697 } else if (data instanceof CompositeModificationByteStringPayload) {
698 currentLogRecoveryBatch.add(((CompositeModificationByteStringPayload) data).getModification());
700 LOG.error("Unknown state received {} during recovery", data);
705 protected void applyRecoverySnapshot(final ByteString snapshot) {
706 if(recoveryCoordinator == null) {
707 recoveryCoordinator = new ShardRecoveryCoordinator(persistenceId(), schemaContext);
710 recoveryCoordinator.submit(snapshot, store.newWriteOnlyTransaction());
712 if(LOG.isDebugEnabled()) {
713 LOG.debug("{} : submitted recovery sbapshot", persistenceId());
718 protected void applyCurrentLogRecoveryBatch() {
719 if(recoveryCoordinator == null) {
720 recoveryCoordinator = new ShardRecoveryCoordinator(persistenceId(), schemaContext);
723 recoveryCoordinator.submit(currentLogRecoveryBatch, store.newWriteOnlyTransaction());
725 if(LOG.isDebugEnabled()) {
726 LOG.debug("{} : submitted log recovery batch with size {}", persistenceId(),
727 currentLogRecoveryBatch.size());
732 protected void onRecoveryComplete() {
733 if(recoveryCoordinator != null) {
734 Collection<DOMStoreWriteTransaction> txList = recoveryCoordinator.getTransactions();
736 if(LOG.isDebugEnabled()) {
737 LOG.debug("{} : recovery complete - committing {} Tx's", persistenceId(), txList.size());
740 for(DOMStoreWriteTransaction tx: txList) {
742 syncCommitTransaction(tx);
743 shardMBean.incrementCommittedTransactionCount();
744 } catch (InterruptedException | ExecutionException e) {
745 shardMBean.incrementFailedTransactionsCount();
746 LOG.error(e, "Failed to commit");
751 recoveryCoordinator = null;
752 currentLogRecoveryBatch = null;
753 updateJournalStats();
755 //notify shard manager
756 getContext().parent().tell(new ActorInitialized(), getSelf());
758 // Being paranoid here - this method should only be called once but just in case...
759 if(txCommitTimeoutCheckSchedule == null) {
760 // Schedule a message to be periodically sent to check if the current in-progress
761 // transaction should be expired and aborted.
762 FiniteDuration period = Duration.create(transactionCommitTimeout / 3, TimeUnit.MILLISECONDS);
763 txCommitTimeoutCheckSchedule = getContext().system().scheduler().schedule(
764 period, period, getSelf(),
765 TX_COMMIT_TIMEOUT_CHECK_MESSAGE, getContext().dispatcher(), ActorRef.noSender());
770 protected void applyState(final ActorRef clientActor, final String identifier, final Object data) {
772 if(data instanceof ModificationPayload) {
774 applyModificationToState(clientActor, identifier, ((ModificationPayload) data).getModification());
775 } catch (ClassNotFoundException | IOException e) {
776 LOG.error(e, "Error extracting ModificationPayload");
779 else if (data instanceof CompositeModificationPayload) {
780 Object modification = ((CompositeModificationPayload) data).getModification();
782 applyModificationToState(clientActor, identifier, modification);
783 } else if(data instanceof CompositeModificationByteStringPayload ){
784 Object modification = ((CompositeModificationByteStringPayload) data).getModification();
786 applyModificationToState(clientActor, identifier, modification);
788 LOG.error("Unknown state received {} Class loader = {} CompositeNodeMod.ClassLoader = {}",
789 data, data.getClass().getClassLoader(),
790 CompositeModificationPayload.class.getClassLoader());
793 updateJournalStats();
797 private void applyModificationToState(ActorRef clientActor, String identifier, Object modification) {
798 if(modification == null) {
800 "modification is null - this is very unexpected, clientActor = {}, identifier = {}",
801 identifier, clientActor != null ? clientActor.path().toString() : null);
802 } else if(clientActor == null) {
803 // There's no clientActor to which to send a commit reply so we must be applying
804 // replicated state from the leader.
805 commitWithNewTransaction(MutableCompositeModification.fromSerializable(modification));
807 // This must be the OK to commit after replication consensus.
808 finishCommit(clientActor, identifier);
812 private void updateJournalStats() {
813 ReplicatedLogEntry lastLogEntry = getLastLogEntry();
815 if (lastLogEntry != null) {
816 shardMBean.setLastLogIndex(lastLogEntry.getIndex());
817 shardMBean.setLastLogTerm(lastLogEntry.getTerm());
820 shardMBean.setCommitIndex(getCommitIndex());
821 shardMBean.setLastApplied(getLastApplied());
822 shardMBean.setInMemoryJournalDataSize(getRaftActorContext().getReplicatedLog().dataSize());
826 protected void createSnapshot() {
827 if (createSnapshotTransaction == null) {
829 // Create a transaction. We are really going to treat the transaction as a worker
830 // so that this actor does not get block building the snapshot
831 createSnapshotTransaction = createTransaction(
832 TransactionProxy.TransactionType.READ_ONLY.ordinal(),
833 "createSnapshot" + ++createSnapshotTransactionCounter, "",
834 DataStoreVersions.CURRENT_VERSION);
836 createSnapshotTransaction.tell(
837 new ReadData(YangInstanceIdentifier.builder().build()).toSerializable(), self());
844 protected void applySnapshot(final ByteString snapshot) {
845 // Since this will be done only on Recovery or when this actor is a Follower
846 // we can safely commit everything in here. We not need to worry about event notifications
847 // as they would have already been disabled on the follower
849 LOG.info("Applying snapshot");
851 DOMStoreWriteTransaction transaction = store.newWriteOnlyTransaction();
852 NormalizedNodeMessages.Node serializedNode = NormalizedNodeMessages.Node.parseFrom(snapshot);
853 NormalizedNode<?, ?> node = new NormalizedNodeToNodeCodec(schemaContext)
854 .decode(serializedNode);
856 // delete everything first
857 transaction.delete(YangInstanceIdentifier.builder().build());
859 // Add everything from the remote node back
860 transaction.write(YangInstanceIdentifier.builder().build(), node);
861 syncCommitTransaction(transaction);
862 } catch (InvalidProtocolBufferException | InterruptedException | ExecutionException e) {
863 LOG.error(e, "An exception occurred when applying snapshot");
865 LOG.info("Done applying snapshot");
870 protected void onStateChanged() {
871 boolean isLeader = isLeader();
872 for (ActorSelection dataChangeListener : dataChangeListeners) {
873 dataChangeListener.tell(new EnableNotification(isLeader), getSelf());
877 for(DelayedListenerRegistration reg: delayedListenerRegistrations) {
878 if(!reg.isClosed()) {
879 reg.setDelegate(doChangeListenerRegistration(reg.getRegisterChangeListener()));
883 delayedListenerRegistrations.clear();
886 shardMBean.setRaftState(getRaftState().name());
887 shardMBean.setCurrentTerm(getCurrentTerm());
889 // If this actor is no longer the leader close all the transaction chains
891 for(Map.Entry<String, DOMStoreTransactionChain> entry : transactionChains.entrySet()){
892 if(LOG.isDebugEnabled()) {
894 "onStateChanged: Closing transaction chain {} because shard {} is no longer the leader",
895 entry.getKey(), getId());
897 entry.getValue().close();
900 transactionChains.clear();
905 protected DataPersistenceProvider persistence() {
906 return dataPersistenceProvider;
909 @Override protected void onLeaderChanged(final String oldLeader, final String newLeader) {
910 shardMBean.setLeader(newLeader);
913 @Override public String persistenceId() {
914 return this.name.toString();
918 DataPersistenceProvider getDataPersistenceProvider() {
919 return dataPersistenceProvider;
922 private static class ShardCreator implements Creator<Shard> {
924 private static final long serialVersionUID = 1L;
926 final ShardIdentifier name;
927 final Map<ShardIdentifier, String> peerAddresses;
928 final DatastoreContext datastoreContext;
929 final SchemaContext schemaContext;
931 ShardCreator(final ShardIdentifier name, final Map<ShardIdentifier, String> peerAddresses,
932 final DatastoreContext datastoreContext, final SchemaContext schemaContext) {
934 this.peerAddresses = peerAddresses;
935 this.datastoreContext = datastoreContext;
936 this.schemaContext = schemaContext;
940 public Shard create() throws Exception {
941 return new Shard(name, peerAddresses, datastoreContext, schemaContext);
946 InMemoryDOMDataStore getDataStore() {
951 ShardStats getShardMBean() {
955 private static class DelayedListenerRegistration implements
956 ListenerRegistration<AsyncDataChangeListener<YangInstanceIdentifier, NormalizedNode<?, ?>>> {
958 private volatile boolean closed;
960 private final RegisterChangeListener registerChangeListener;
962 private volatile ListenerRegistration<AsyncDataChangeListener<YangInstanceIdentifier,
963 NormalizedNode<?, ?>>> delegate;
965 DelayedListenerRegistration(final RegisterChangeListener registerChangeListener) {
966 this.registerChangeListener = registerChangeListener;
969 void setDelegate( final ListenerRegistration<AsyncDataChangeListener<YangInstanceIdentifier,
970 NormalizedNode<?, ?>>> registration) {
971 this.delegate = registration;
978 RegisterChangeListener getRegisterChangeListener() {
979 return registerChangeListener;
983 public AsyncDataChangeListener<YangInstanceIdentifier, NormalizedNode<?, ?>> getInstance() {
984 return delegate != null ? delegate.getInstance() : null;
988 public void close() {
990 if(delegate != null) {