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.Props;
15 import akka.japi.Creator;
16 import akka.persistence.RecoveryFailure;
17 import akka.serialization.Serialization;
18 import com.google.common.annotations.VisibleForTesting;
19 import com.google.common.base.Optional;
20 import com.google.common.base.Preconditions;
21 import com.google.common.collect.Lists;
22 import com.google.common.util.concurrent.FutureCallback;
23 import com.google.common.util.concurrent.Futures;
24 import com.google.common.util.concurrent.ListenableFuture;
25 import java.io.IOException;
26 import java.util.HashMap;
27 import java.util.List;
29 import java.util.concurrent.ExecutionException;
30 import java.util.concurrent.TimeUnit;
31 import javax.annotation.Nonnull;
32 import org.opendaylight.controller.cluster.common.actor.CommonConfig;
33 import org.opendaylight.controller.cluster.common.actor.MeteringBehavior;
34 import org.opendaylight.controller.cluster.datastore.ShardCommitCoordinator.CohortEntry;
35 import org.opendaylight.controller.cluster.datastore.compat.BackwardsCompatibleThreePhaseCommitCohort;
36 import org.opendaylight.controller.cluster.datastore.exceptions.NoShardLeaderException;
37 import org.opendaylight.controller.cluster.datastore.identifiers.ShardIdentifier;
38 import org.opendaylight.controller.cluster.datastore.identifiers.ShardTransactionIdentifier;
39 import org.opendaylight.controller.cluster.datastore.jmx.mbeans.shard.ShardMBeanFactory;
40 import org.opendaylight.controller.cluster.datastore.jmx.mbeans.shard.ShardStats;
41 import org.opendaylight.controller.cluster.datastore.messages.AbortTransaction;
42 import org.opendaylight.controller.cluster.datastore.messages.AbortTransactionReply;
43 import org.opendaylight.controller.cluster.datastore.messages.ActorInitialized;
44 import org.opendaylight.controller.cluster.datastore.messages.BatchedModifications;
45 import org.opendaylight.controller.cluster.datastore.messages.BatchedModificationsReply;
46 import org.opendaylight.controller.cluster.datastore.messages.CanCommitTransaction;
47 import org.opendaylight.controller.cluster.datastore.messages.CloseTransactionChain;
48 import org.opendaylight.controller.cluster.datastore.messages.CommitTransaction;
49 import org.opendaylight.controller.cluster.datastore.messages.CommitTransactionReply;
50 import org.opendaylight.controller.cluster.datastore.messages.CreateSnapshot;
51 import org.opendaylight.controller.cluster.datastore.messages.CreateTransaction;
52 import org.opendaylight.controller.cluster.datastore.messages.CreateTransactionReply;
53 import org.opendaylight.controller.cluster.datastore.messages.EnableNotification;
54 import org.opendaylight.controller.cluster.datastore.messages.ForwardedReadyTransaction;
55 import org.opendaylight.controller.cluster.datastore.messages.PeerAddressResolved;
56 import org.opendaylight.controller.cluster.datastore.messages.ReadyTransactionReply;
57 import org.opendaylight.controller.cluster.datastore.messages.RegisterChangeListener;
58 import org.opendaylight.controller.cluster.datastore.messages.RegisterChangeListenerReply;
59 import org.opendaylight.controller.cluster.datastore.messages.UpdateSchemaContext;
60 import org.opendaylight.controller.cluster.datastore.modification.Modification;
61 import org.opendaylight.controller.cluster.datastore.modification.ModificationPayload;
62 import org.opendaylight.controller.cluster.datastore.modification.MutableCompositeModification;
63 import org.opendaylight.controller.cluster.datastore.utils.Dispatchers;
64 import org.opendaylight.controller.cluster.datastore.utils.MessageTracker;
65 import org.opendaylight.controller.cluster.datastore.utils.SerializationUtils;
66 import org.opendaylight.controller.cluster.notifications.RegisterRoleChangeListener;
67 import org.opendaylight.controller.cluster.notifications.RoleChangeNotifier;
68 import org.opendaylight.controller.cluster.raft.RaftActor;
69 import org.opendaylight.controller.cluster.raft.base.messages.FollowerInitialSyncUpStatus;
70 import org.opendaylight.controller.cluster.raft.messages.AppendEntriesReply;
71 import org.opendaylight.controller.cluster.raft.protobuff.client.messages.CompositeModificationByteStringPayload;
72 import org.opendaylight.controller.cluster.raft.protobuff.client.messages.CompositeModificationPayload;
73 import org.opendaylight.controller.cluster.raft.protobuff.client.messages.Payload;
74 import org.opendaylight.controller.md.sal.common.api.data.AsyncDataChangeListener;
75 import org.opendaylight.controller.md.sal.dom.store.impl.InMemoryDOMDataStore;
76 import org.opendaylight.controller.md.sal.dom.store.impl.InMemoryDOMDataStoreFactory;
77 import org.opendaylight.controller.sal.core.spi.data.DOMStoreThreePhaseCommitCohort;
78 import org.opendaylight.controller.sal.core.spi.data.DOMStoreTransaction;
79 import org.opendaylight.controller.sal.core.spi.data.DOMStoreWriteTransaction;
80 import org.opendaylight.yangtools.concepts.ListenerRegistration;
81 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
82 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
83 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
84 import scala.concurrent.duration.Duration;
85 import scala.concurrent.duration.FiniteDuration;
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 YangInstanceIdentifier DATASTORE_ROOT = YangInstanceIdentifier.builder().build();
97 private static final Object TX_COMMIT_TIMEOUT_CHECK_MESSAGE = "txCommitTimeoutCheck";
100 static final String DEFAULT_NAME = "default";
102 // The state of this Shard
103 private final InMemoryDOMDataStore store;
105 /// The name of this shard
106 private final String name;
108 private final ShardStats shardMBean;
110 private final List<ActorSelection> dataChangeListeners = Lists.newArrayList();
112 private final List<DelayedListenerRegistration> delayedListenerRegistrations =
113 Lists.newArrayList();
115 private DatastoreContext datastoreContext;
117 private SchemaContext schemaContext;
119 private int createSnapshotTransactionCounter;
121 private final ShardCommitCoordinator commitCoordinator;
123 private long transactionCommitTimeout;
125 private Cancellable txCommitTimeoutCheckSchedule;
127 private final Optional<ActorRef> roleChangeNotifier;
129 private final MessageTracker appendEntriesReplyTracker;
131 private final ReadyTransactionReply READY_TRANSACTION_REPLY = new ReadyTransactionReply(
132 Serialization.serializedActorPath(getSelf()));
136 * Coordinates persistence recovery on startup.
138 private ShardRecoveryCoordinator recoveryCoordinator;
140 private final DOMTransactionFactory transactionFactory;
142 private final String txnDispatcherPath;
144 protected Shard(final ShardIdentifier name, final Map<String, String> peerAddresses,
145 final DatastoreContext datastoreContext, final SchemaContext schemaContext) {
146 super(name.toString(), new HashMap<>(peerAddresses), Optional.of(datastoreContext.getShardRaftConfig()));
148 this.name = name.toString();
149 this.datastoreContext = datastoreContext;
150 this.schemaContext = schemaContext;
151 this.txnDispatcherPath = new Dispatchers(context().system().dispatchers())
152 .getDispatcherPath(Dispatchers.DispatcherType.Transaction);
154 setPersistence(datastoreContext.isPersistent());
156 LOG.info("Shard created : {}, persistent : {}", name, datastoreContext.isPersistent());
158 store = InMemoryDOMDataStoreFactory.create(name.toString(), null,
159 datastoreContext.getDataStoreProperties());
161 if(schemaContext != null) {
162 store.onGlobalContextUpdated(schemaContext);
165 shardMBean = ShardMBeanFactory.getShardStatsMBean(name.toString(),
166 datastoreContext.getDataStoreMXBeanType());
167 shardMBean.setNotificationManager(store.getDataChangeListenerNotificationManager());
168 shardMBean.setShardActor(getSelf());
170 if (isMetricsCaptureEnabled()) {
171 getContext().become(new MeteringBehavior(this));
174 transactionFactory = new DOMTransactionFactory(store, shardMBean, LOG, this.name);
176 commitCoordinator = new ShardCommitCoordinator(transactionFactory,
177 TimeUnit.SECONDS.convert(5, TimeUnit.MINUTES),
178 datastoreContext.getShardTransactionCommitQueueCapacity(), self(), LOG, this.name);
180 setTransactionCommitTimeout();
182 // create a notifier actor for each cluster member
183 roleChangeNotifier = createRoleChangeNotifier(name.toString());
185 appendEntriesReplyTracker = new MessageTracker(AppendEntriesReply.class,
186 getRaftActorContext().getConfigParams().getIsolatedCheckIntervalInMillis());
188 recoveryCoordinator = new ShardRecoveryCoordinator(store, persistenceId(), LOG);
191 private void setTransactionCommitTimeout() {
192 transactionCommitTimeout = TimeUnit.MILLISECONDS.convert(
193 datastoreContext.getShardTransactionCommitTimeoutInSeconds(), TimeUnit.SECONDS);
196 public static Props props(final ShardIdentifier name,
197 final Map<String, 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.of(shardRoleChangeNotifier);
214 public void postStop() {
215 LOG.info("Stopping Shard {}", persistenceId());
219 if(txCommitTimeoutCheckSchedule != null) {
220 txCommitTimeoutCheckSchedule.cancel();
223 shardMBean.unregisterMBean();
227 public void onReceiveRecover(final Object message) throws Exception {
228 if(LOG.isDebugEnabled()) {
229 LOG.debug("{}: onReceiveRecover: Received message {} from {}", persistenceId(),
230 message.getClass().toString(), getSender());
233 if (message instanceof RecoveryFailure){
234 LOG.error("{}: Recovery failed because of this cause",
235 persistenceId(), ((RecoveryFailure) message).cause());
237 // Even though recovery failed, we still need to finish our recovery, eg send the
238 // ActorInitialized message and start the txCommitTimeoutCheckSchedule.
239 onRecoveryComplete();
241 super.onReceiveRecover(message);
242 if(LOG.isTraceEnabled()) {
243 appendEntriesReplyTracker.begin();
249 public void onReceiveCommand(final Object message) throws Exception {
251 MessageTracker.Context context = appendEntriesReplyTracker.received(message);
253 if(context.error().isPresent()){
254 LOG.trace("{} : AppendEntriesReply failed to arrive at the expected interval {}", persistenceId(),
259 if (CreateTransaction.SERIALIZABLE_CLASS.isInstance(message)) {
260 handleCreateTransaction(message);
261 } else if (BatchedModifications.class.isInstance(message)) {
262 handleBatchedModifications((BatchedModifications)message);
263 } else if (message instanceof ForwardedReadyTransaction) {
264 handleForwardedReadyTransaction((ForwardedReadyTransaction) message);
265 } else if (CanCommitTransaction.SERIALIZABLE_CLASS.isInstance(message)) {
266 handleCanCommitTransaction(CanCommitTransaction.fromSerializable(message));
267 } else if (CommitTransaction.SERIALIZABLE_CLASS.isInstance(message)) {
268 handleCommitTransaction(CommitTransaction.fromSerializable(message));
269 } else if (AbortTransaction.SERIALIZABLE_CLASS.isInstance(message)) {
270 handleAbortTransaction(AbortTransaction.fromSerializable(message));
271 } else if (CloseTransactionChain.SERIALIZABLE_CLASS.isInstance(message)) {
272 closeTransactionChain(CloseTransactionChain.fromSerializable(message));
273 } else if (message instanceof RegisterChangeListener) {
274 registerChangeListener((RegisterChangeListener) message);
275 } else if (message instanceof UpdateSchemaContext) {
276 updateSchemaContext((UpdateSchemaContext) message);
277 } else if (message instanceof PeerAddressResolved) {
278 PeerAddressResolved resolved = (PeerAddressResolved) message;
279 setPeerAddress(resolved.getPeerId().toString(),
280 resolved.getPeerAddress());
281 } else if (message.equals(TX_COMMIT_TIMEOUT_CHECK_MESSAGE)) {
282 handleTransactionCommitTimeoutCheck();
283 } else if(message instanceof DatastoreContext) {
284 onDatastoreContext((DatastoreContext)message);
285 } else if(message instanceof RegisterRoleChangeListener){
286 roleChangeNotifier.get().forward(message, context());
287 } else if (message instanceof FollowerInitialSyncUpStatus){
288 shardMBean.setFollowerInitialSyncStatus(((FollowerInitialSyncUpStatus) message).isInitialSyncDone());
289 context().parent().tell(message, self());
291 super.onReceiveCommand(message);
299 protected Optional<ActorRef> getRoleChangeNotifier() {
300 return roleChangeNotifier;
303 private void onDatastoreContext(DatastoreContext context) {
304 datastoreContext = context;
306 commitCoordinator.setQueueCapacity(datastoreContext.getShardTransactionCommitQueueCapacity());
308 setTransactionCommitTimeout();
310 if(datastoreContext.isPersistent() && !persistence().isRecoveryApplicable()) {
311 setPersistence(true);
312 } else if(!datastoreContext.isPersistent() && persistence().isRecoveryApplicable()) {
313 setPersistence(false);
316 updateConfigParams(datastoreContext.getShardRaftConfig());
319 private void handleTransactionCommitTimeoutCheck() {
320 CohortEntry cohortEntry = commitCoordinator.getCurrentCohortEntry();
321 if(cohortEntry != null) {
322 long elapsed = System.currentTimeMillis() - cohortEntry.getLastAccessTime();
323 if(elapsed > transactionCommitTimeout) {
324 LOG.warn("{}: Current transaction {} has timed out after {} ms - aborting",
325 persistenceId(), cohortEntry.getTransactionID(), transactionCommitTimeout);
327 doAbortTransaction(cohortEntry.getTransactionID(), null);
332 private void handleCommitTransaction(final CommitTransaction commit) {
333 final String transactionID = commit.getTransactionID();
335 LOG.debug("{}: Committing transaction {}", persistenceId(), transactionID);
337 // Get the current in-progress cohort entry in the commitCoordinator if it corresponds to
339 final CohortEntry cohortEntry = commitCoordinator.getCohortEntryIfCurrent(transactionID);
340 if(cohortEntry == null) {
341 // We're not the current Tx - the Tx was likely expired b/c it took too long in
342 // between the canCommit and commit messages.
343 IllegalStateException ex = new IllegalStateException(
344 String.format("%s: Cannot commit transaction %s - it is not the current transaction",
345 persistenceId(), transactionID));
346 LOG.error(ex.getMessage());
347 shardMBean.incrementFailedTransactionsCount();
348 getSender().tell(new akka.actor.Status.Failure(ex), getSelf());
352 // We perform the preCommit phase here atomically with the commit phase. This is an
353 // optimization to eliminate the overhead of an extra preCommit message. We lose front-end
354 // coordination of preCommit across shards in case of failure but preCommit should not
355 // normally fail since we ensure only one concurrent 3-phase commit.
358 // We block on the future here so we don't have to worry about possibly accessing our
359 // state on a different thread outside of our dispatcher. Also, the data store
360 // currently uses a same thread executor anyway.
361 cohortEntry.getCohort().preCommit().get();
363 // If we do not have any followers and we are not using persistence
364 // or if cohortEntry has no modifications
365 // we can apply modification to the state immediately
366 if((!hasFollowers() && !persistence().isRecoveryApplicable()) || (!cohortEntry.hasModifications())){
367 applyModificationToState(getSender(), transactionID, cohortEntry.getModification());
369 Shard.this.persistData(getSender(), transactionID,
370 new ModificationPayload(cohortEntry.getModification()));
372 } catch (Exception e) {
373 LOG.error("{} An exception occurred while preCommitting transaction {}",
374 persistenceId(), cohortEntry.getTransactionID(), e);
375 shardMBean.incrementFailedTransactionsCount();
376 getSender().tell(new akka.actor.Status.Failure(e), getSelf());
379 cohortEntry.updateLastAccessTime();
382 private void finishCommit(@Nonnull final ActorRef sender, final @Nonnull String transactionID) {
383 // With persistence enabled, this method is called via applyState by the leader strategy
384 // after the commit has been replicated to a majority of the followers.
386 CohortEntry cohortEntry = commitCoordinator.getCohortEntryIfCurrent(transactionID);
387 if(cohortEntry == null) {
388 // The transaction is no longer the current commit. This can happen if the transaction
389 // was aborted prior, most likely due to timeout in the front-end. We need to finish
390 // committing the transaction though since it was successfully persisted and replicated
391 // however we can't use the original cohort b/c it was already preCommitted and may
392 // conflict with the current commit or may have been aborted so we commit with a new
394 cohortEntry = commitCoordinator.getAndRemoveCohortEntry(transactionID);
395 if(cohortEntry != null) {
396 commitWithNewTransaction(cohortEntry.getModification());
397 sender.tell(CommitTransactionReply.INSTANCE.toSerializable(), getSelf());
399 // This really shouldn't happen - it likely means that persistence or replication
400 // took so long to complete such that the cohort entry was expired from the cache.
401 IllegalStateException ex = new IllegalStateException(
402 String.format("%s: Could not finish committing transaction %s - no CohortEntry found",
403 persistenceId(), transactionID));
404 LOG.error(ex.getMessage());
405 sender.tell(new akka.actor.Status.Failure(ex), getSelf());
411 LOG.debug("{}: Finishing commit for transaction {}", persistenceId(), cohortEntry.getTransactionID());
414 // We block on the future here so we don't have to worry about possibly accessing our
415 // state on a different thread outside of our dispatcher. Also, the data store
416 // currently uses a same thread executor anyway.
417 cohortEntry.getCohort().commit().get();
419 sender.tell(CommitTransactionReply.INSTANCE.toSerializable(), getSelf());
421 shardMBean.incrementCommittedTransactionCount();
422 shardMBean.setLastCommittedTransactionTime(System.currentTimeMillis());
424 } catch (Exception e) {
425 sender.tell(new akka.actor.Status.Failure(e), getSelf());
427 LOG.error("{}, An exception occurred while committing transaction {}", persistenceId(),
429 shardMBean.incrementFailedTransactionsCount();
431 commitCoordinator.currentTransactionComplete(transactionID, true);
435 private void handleCanCommitTransaction(final CanCommitTransaction canCommit) {
436 LOG.debug("{}: Can committing transaction {}", persistenceId(), canCommit.getTransactionID());
437 commitCoordinator.handleCanCommit(canCommit, getSender(), self());
440 private void handleBatchedModifications(BatchedModifications batched) {
441 // This message is sent to prepare the modificationsa transaction directly on the Shard as an
442 // optimization to avoid the extra overhead of a separate ShardTransaction actor. On the last
443 // BatchedModifications message, the caller sets the ready flag in the message indicating
444 // modifications are complete. The reply contains the cohort actor path (this actor) for the caller
445 // to initiate the 3-phase commit. This also avoids the overhead of sending an additional
446 // ReadyTransaction message.
448 // If we're not the leader then forward to the leader. This is a safety measure - we shouldn't
449 // normally get here if we're not the leader as the front-end (TransactionProxy) should determine
450 // the primary/leader shard. However with timing and caching on the front-end, there's a small
451 // window where it could have a stale leader during leadership transitions.
455 BatchedModificationsReply reply = commitCoordinator.handleTransactionModifications(batched);
456 sender().tell(reply, self());
457 } catch (Exception e) {
458 LOG.error("{}: Error handling BatchedModifications for Tx {}", persistenceId(),
459 batched.getTransactionID(), e);
460 getSender().tell(new akka.actor.Status.Failure(e), getSelf());
463 ActorSelection leader = getLeader();
465 // TODO: what if this is not the first batch and leadership changed in between batched messages?
466 // We could check if the commitCoordinator already has a cached entry and forward all the previous
467 // batched modifications.
468 LOG.debug("{}: Forwarding BatchedModifications to leader {}", persistenceId(), leader);
469 leader.forward(batched, getContext());
471 // TODO: rather than throwing an immediate exception, we could schedule a timer to try again to make
472 // it more resilient in case we're in the process of electing a new leader.
473 getSender().tell(new akka.actor.Status.Failure(new NoShardLeaderException(String.format(
474 "Could not find the leader for shard %s. This typically happens" +
475 " when the system is coming up or recovering and a leader is being elected. Try again" +
476 " later.", persistenceId()))), getSelf());
481 private void handleForwardedReadyTransaction(ForwardedReadyTransaction ready) {
482 LOG.debug("{}: Readying transaction {}, client version {}", persistenceId(),
483 ready.getTransactionID(), ready.getTxnClientVersion());
485 // This message is forwarded by the ShardTransaction on ready. We cache the cohort in the
486 // commitCoordinator in preparation for the subsequent three phase commit initiated by
488 commitCoordinator.transactionReady(ready.getTransactionID(), ready.getCohort(),
489 (MutableCompositeModification) ready.getModification());
491 // Return our actor path as we'll handle the three phase commit, except if the Tx client
492 // version < 1 (Helium-1 version). This means the Tx was initiated by a base Helium version
493 // node. In that case, the subsequent 3-phase commit messages won't contain the
494 // transactionId so to maintain backwards compatibility, we create a separate cohort actor
495 // to provide the compatible behavior.
496 if(ready.getTxnClientVersion() < DataStoreVersions.HELIUM_1_VERSION) {
497 LOG.debug("{}: Creating BackwardsCompatibleThreePhaseCommitCohort", persistenceId());
498 ActorRef replyActorPath = getContext().actorOf(BackwardsCompatibleThreePhaseCommitCohort.props(
499 ready.getTransactionID()));
501 ReadyTransactionReply readyTransactionReply =
502 new ReadyTransactionReply(Serialization.serializedActorPath(replyActorPath));
503 getSender().tell(ready.isReturnSerialized() ? readyTransactionReply.toSerializable() :
504 readyTransactionReply, getSelf());
508 getSender().tell(ready.isReturnSerialized() ? READY_TRANSACTION_REPLY.toSerializable() :
509 READY_TRANSACTION_REPLY, getSelf());
513 private void handleAbortTransaction(final AbortTransaction abort) {
514 doAbortTransaction(abort.getTransactionID(), getSender());
517 void doAbortTransaction(final String transactionID, final ActorRef sender) {
518 final CohortEntry cohortEntry = commitCoordinator.getCohortEntryIfCurrent(transactionID);
519 if(cohortEntry != null) {
520 LOG.debug("{}: Aborting transaction {}", persistenceId(), transactionID);
522 // We don't remove the cached cohort entry here (ie pass false) in case the Tx was
523 // aborted during replication in which case we may still commit locally if replication
525 commitCoordinator.currentTransactionComplete(transactionID, false);
527 final ListenableFuture<Void> future = cohortEntry.getCohort().abort();
528 final ActorRef self = getSelf();
530 Futures.addCallback(future, new FutureCallback<Void>() {
532 public void onSuccess(final Void v) {
533 shardMBean.incrementAbortTransactionsCount();
536 sender.tell(AbortTransactionReply.INSTANCE.toSerializable(), self);
541 public void onFailure(final Throwable t) {
542 LOG.error("{}: An exception happened during abort", persistenceId(), t);
545 sender.tell(new akka.actor.Status.Failure(t), self);
552 private void handleCreateTransaction(final Object message) {
554 createTransaction(CreateTransaction.fromSerializable(message));
555 } else if (getLeader() != null) {
556 getLeader().forward(message, getContext());
558 getSender().tell(new akka.actor.Status.Failure(new NoShardLeaderException(String.format(
559 "Could not find leader for shard %s so transaction cannot be created. This typically happens" +
560 " when the system is coming up or recovering and a leader is being elected. Try again" +
561 " later.", persistenceId()))), getSelf());
565 private void closeTransactionChain(final CloseTransactionChain closeTransactionChain) {
566 transactionFactory.closeTransactionChain(closeTransactionChain.getTransactionChainId());
569 private ActorRef createTypedTransactionActor(int transactionType,
570 ShardTransactionIdentifier transactionId, String transactionChainId,
571 short clientVersion ) {
573 DOMStoreTransaction transaction = transactionFactory.newTransaction(
574 TransactionProxy.TransactionType.fromInt(transactionType), transactionId.toString(),
577 return createShardTransaction(transaction, transactionId, clientVersion);
580 private ActorRef createShardTransaction(DOMStoreTransaction transaction, ShardTransactionIdentifier transactionId,
581 short clientVersion){
582 return getContext().actorOf(
583 ShardTransaction.props(transaction, getSelf(),
584 schemaContext, datastoreContext, shardMBean,
585 transactionId.getRemoteTransactionId(), clientVersion)
586 .withDispatcher(txnDispatcherPath),
587 transactionId.toString());
591 private void createTransaction(CreateTransaction createTransaction) {
593 ActorRef transactionActor = createTransaction(createTransaction.getTransactionType(),
594 createTransaction.getTransactionId(), createTransaction.getTransactionChainId(),
595 createTransaction.getVersion());
597 getSender().tell(new CreateTransactionReply(Serialization.serializedActorPath(transactionActor),
598 createTransaction.getTransactionId()).toSerializable(), getSelf());
599 } catch (Exception e) {
600 getSender().tell(new akka.actor.Status.Failure(e), getSelf());
604 private ActorRef createTransaction(int transactionType, String remoteTransactionId,
605 String transactionChainId, short clientVersion) {
608 ShardTransactionIdentifier transactionId = new ShardTransactionIdentifier(remoteTransactionId);
610 if(LOG.isDebugEnabled()) {
611 LOG.debug("{}: Creating transaction : {} ", persistenceId(), transactionId);
614 ActorRef transactionActor = createTypedTransactionActor(transactionType, transactionId,
615 transactionChainId, clientVersion);
617 return transactionActor;
620 private void syncCommitTransaction(final DOMStoreWriteTransaction transaction)
621 throws ExecutionException, InterruptedException {
622 DOMStoreThreePhaseCommitCohort commitCohort = transaction.ready();
623 commitCohort.preCommit().get();
624 commitCohort.commit().get();
627 private void commitWithNewTransaction(final Modification modification) {
628 DOMStoreWriteTransaction tx = store.newWriteOnlyTransaction();
629 modification.apply(tx);
631 syncCommitTransaction(tx);
632 shardMBean.incrementCommittedTransactionCount();
633 shardMBean.setLastCommittedTransactionTime(System.currentTimeMillis());
634 } catch (InterruptedException | ExecutionException e) {
635 shardMBean.incrementFailedTransactionsCount();
636 LOG.error("{}: Failed to commit", persistenceId(), e);
640 private void updateSchemaContext(final UpdateSchemaContext message) {
641 this.schemaContext = message.getSchemaContext();
642 updateSchemaContext(message.getSchemaContext());
643 store.onGlobalContextUpdated(message.getSchemaContext());
647 void updateSchemaContext(final SchemaContext schemaContext) {
648 store.onGlobalContextUpdated(schemaContext);
651 private void registerChangeListener(final RegisterChangeListener registerChangeListener) {
653 LOG.debug("{}: registerDataChangeListener for {}", persistenceId(), registerChangeListener.getPath());
655 ListenerRegistration<AsyncDataChangeListener<YangInstanceIdentifier,
656 NormalizedNode<?, ?>>> registration;
658 registration = doChangeListenerRegistration(registerChangeListener);
660 LOG.debug("{}: Shard is not the leader - delaying registration", persistenceId());
662 DelayedListenerRegistration delayedReg =
663 new DelayedListenerRegistration(registerChangeListener);
664 delayedListenerRegistrations.add(delayedReg);
665 registration = delayedReg;
668 ActorRef listenerRegistration = getContext().actorOf(
669 DataChangeListenerRegistration.props(registration));
671 LOG.debug("{}: registerDataChangeListener sending reply, listenerRegistrationPath = {} ",
672 persistenceId(), listenerRegistration.path());
674 getSender().tell(new RegisterChangeListenerReply(listenerRegistration), getSelf());
677 private ListenerRegistration<AsyncDataChangeListener<YangInstanceIdentifier,
678 NormalizedNode<?, ?>>> doChangeListenerRegistration(
679 final RegisterChangeListener registerChangeListener) {
681 ActorSelection dataChangeListenerPath = getContext().system().actorSelection(
682 registerChangeListener.getDataChangeListenerPath());
684 // Notify the listener if notifications should be enabled or not
685 // If this shard is the leader then it will enable notifications else
687 dataChangeListenerPath.tell(new EnableNotification(true), getSelf());
689 // Now store a reference to the data change listener so it can be notified
690 // at a later point if notifications should be enabled or disabled
691 dataChangeListeners.add(dataChangeListenerPath);
693 AsyncDataChangeListener<YangInstanceIdentifier, NormalizedNode<?, ?>> listener =
694 new DataChangeListenerProxy(dataChangeListenerPath);
696 LOG.debug("{}: Registering for path {}", persistenceId(), registerChangeListener.getPath());
698 return store.registerChangeListener(registerChangeListener.getPath(), listener,
699 registerChangeListener.getScope());
702 private boolean isMetricsCaptureEnabled(){
703 CommonConfig config = new CommonConfig(getContext().system().settings().config());
704 return config.isMetricCaptureEnabled();
709 void startLogRecoveryBatch(final int maxBatchSize) {
710 recoveryCoordinator.startLogRecoveryBatch(maxBatchSize);
714 protected void appendRecoveredLogEntry(final Payload data) {
715 recoveryCoordinator.appendRecoveredLogPayload(data);
719 protected void applyRecoverySnapshot(final byte[] snapshotBytes) {
720 recoveryCoordinator.applyRecoveredSnapshot(snapshotBytes);
724 protected void applyCurrentLogRecoveryBatch() {
725 recoveryCoordinator.applyCurrentLogRecoveryBatch();
729 protected void onRecoveryComplete() {
730 recoveryCoordinator = null;
732 //notify shard manager
733 getContext().parent().tell(new ActorInitialized(), getSelf());
735 // Being paranoid here - this method should only be called once but just in case...
736 if(txCommitTimeoutCheckSchedule == null) {
737 // Schedule a message to be periodically sent to check if the current in-progress
738 // transaction should be expired and aborted.
739 FiniteDuration period = Duration.create(transactionCommitTimeout / 3, TimeUnit.MILLISECONDS);
740 txCommitTimeoutCheckSchedule = getContext().system().scheduler().schedule(
741 period, period, getSelf(),
742 TX_COMMIT_TIMEOUT_CHECK_MESSAGE, getContext().dispatcher(), ActorRef.noSender());
747 protected void applyState(final ActorRef clientActor, final String identifier, final Object data) {
749 if(data instanceof ModificationPayload) {
751 applyModificationToState(clientActor, identifier, ((ModificationPayload) data).getModification());
752 } catch (ClassNotFoundException | IOException e) {
753 LOG.error("{}: Error extracting ModificationPayload", persistenceId(), e);
756 else if (data instanceof CompositeModificationPayload) {
757 Object modification = ((CompositeModificationPayload) data).getModification();
759 applyModificationToState(clientActor, identifier, modification);
760 } else if(data instanceof CompositeModificationByteStringPayload ){
761 Object modification = ((CompositeModificationByteStringPayload) data).getModification();
763 applyModificationToState(clientActor, identifier, modification);
765 LOG.error("{}: Unknown state received {} Class loader = {} CompositeNodeMod.ClassLoader = {}",
766 persistenceId(), data, data.getClass().getClassLoader(),
767 CompositeModificationPayload.class.getClassLoader());
771 private void applyModificationToState(ActorRef clientActor, String identifier, Object modification) {
772 if(modification == null) {
774 "{}: modification is null - this is very unexpected, clientActor = {}, identifier = {}",
775 persistenceId(), identifier, clientActor != null ? clientActor.path().toString() : null);
776 } else if(clientActor == null) {
777 // There's no clientActor to which to send a commit reply so we must be applying
778 // replicated state from the leader.
779 commitWithNewTransaction(MutableCompositeModification.fromSerializable(modification));
781 // This must be the OK to commit after replication consensus.
782 finishCommit(clientActor, identifier);
787 protected void createSnapshot() {
788 // Create a transaction actor. We are really going to treat the transaction as a worker
789 // so that this actor does not get block building the snapshot. THe transaction actor will
790 // after processing the CreateSnapshot message.
792 ActorRef createSnapshotTransaction = createTransaction(
793 TransactionProxy.TransactionType.READ_ONLY.ordinal(),
794 "createSnapshot" + ++createSnapshotTransactionCounter, "",
795 DataStoreVersions.CURRENT_VERSION);
797 createSnapshotTransaction.tell(CreateSnapshot.INSTANCE, self());
802 protected void applySnapshot(final byte[] snapshotBytes) {
803 // Since this will be done only on Recovery or when this actor is a Follower
804 // we can safely commit everything in here. We not need to worry about event notifications
805 // as they would have already been disabled on the follower
807 LOG.info("{}: Applying snapshot", persistenceId());
809 DOMStoreWriteTransaction transaction = store.newWriteOnlyTransaction();
811 NormalizedNode<?, ?> node = SerializationUtils.deserializeNormalizedNode(snapshotBytes);
813 // delete everything first
814 transaction.delete(DATASTORE_ROOT);
816 // Add everything from the remote node back
817 transaction.write(DATASTORE_ROOT, node);
818 syncCommitTransaction(transaction);
819 } catch (InterruptedException | ExecutionException e) {
820 LOG.error("{}: An exception occurred when applying snapshot", persistenceId(), e);
822 LOG.info("{}: Done applying snapshot", persistenceId());
827 protected void onStateChanged() {
828 boolean isLeader = isLeader();
829 for (ActorSelection dataChangeListener : dataChangeListeners) {
830 dataChangeListener.tell(new EnableNotification(isLeader), getSelf());
834 for(DelayedListenerRegistration reg: delayedListenerRegistrations) {
835 if(!reg.isClosed()) {
836 reg.setDelegate(doChangeListenerRegistration(reg.getRegisterChangeListener()));
840 delayedListenerRegistrations.clear();
843 // If this actor is no longer the leader close all the transaction chains
845 if(LOG.isDebugEnabled()) {
847 "{}: onStateChanged: Closing all transaction chains because shard {} is no longer the leader",
848 persistenceId(), getId());
851 transactionFactory.closeAllTransactionChains();
856 public String persistenceId() {
861 ShardCommitCoordinator getCommitCoordinator() {
862 return commitCoordinator;
866 private static class ShardCreator implements Creator<Shard> {
868 private static final long serialVersionUID = 1L;
870 final ShardIdentifier name;
871 final Map<String, String> peerAddresses;
872 final DatastoreContext datastoreContext;
873 final SchemaContext schemaContext;
875 ShardCreator(final ShardIdentifier name, final Map<String, String> peerAddresses,
876 final DatastoreContext datastoreContext, final SchemaContext schemaContext) {
878 this.peerAddresses = peerAddresses;
879 this.datastoreContext = datastoreContext;
880 this.schemaContext = schemaContext;
884 public Shard create() throws Exception {
885 return new Shard(name, peerAddresses, datastoreContext, schemaContext);
890 public InMemoryDOMDataStore getDataStore() {
895 ShardStats getShardMBean() {
899 private static class DelayedListenerRegistration implements
900 ListenerRegistration<AsyncDataChangeListener<YangInstanceIdentifier, NormalizedNode<?, ?>>> {
902 private volatile boolean closed;
904 private final RegisterChangeListener registerChangeListener;
906 private volatile ListenerRegistration<AsyncDataChangeListener<YangInstanceIdentifier,
907 NormalizedNode<?, ?>>> delegate;
909 DelayedListenerRegistration(final RegisterChangeListener registerChangeListener) {
910 this.registerChangeListener = registerChangeListener;
913 void setDelegate( final ListenerRegistration<AsyncDataChangeListener<YangInstanceIdentifier,
914 NormalizedNode<?, ?>>> registration) {
915 this.delegate = registration;
922 RegisterChangeListener getRegisterChangeListener() {
923 return registerChangeListener;
927 public AsyncDataChangeListener<YangInstanceIdentifier, NormalizedNode<?, ?>> getInstance() {
928 return delegate != null ? delegate.getInstance() : null;
932 public void close() {
934 if(delegate != null) {