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.DataPersistenceProvider;
33 import org.opendaylight.controller.cluster.common.actor.CommonConfig;
34 import org.opendaylight.controller.cluster.common.actor.MeteringBehavior;
35 import org.opendaylight.controller.cluster.datastore.ShardCommitCoordinator.CohortEntry;
36 import org.opendaylight.controller.cluster.datastore.compat.BackwardsCompatibleThreePhaseCommitCohort;
37 import org.opendaylight.controller.cluster.datastore.exceptions.NoShardLeaderException;
38 import org.opendaylight.controller.cluster.datastore.identifiers.ShardIdentifier;
39 import org.opendaylight.controller.cluster.datastore.identifiers.ShardTransactionIdentifier;
40 import org.opendaylight.controller.cluster.datastore.jmx.mbeans.shard.ShardMBeanFactory;
41 import org.opendaylight.controller.cluster.datastore.jmx.mbeans.shard.ShardStats;
42 import org.opendaylight.controller.cluster.datastore.messages.AbortTransaction;
43 import org.opendaylight.controller.cluster.datastore.messages.AbortTransactionReply;
44 import org.opendaylight.controller.cluster.datastore.messages.ActorInitialized;
45 import org.opendaylight.controller.cluster.datastore.messages.BatchedModifications;
46 import org.opendaylight.controller.cluster.datastore.messages.BatchedModificationsReply;
47 import org.opendaylight.controller.cluster.datastore.messages.CanCommitTransaction;
48 import org.opendaylight.controller.cluster.datastore.messages.CloseTransactionChain;
49 import org.opendaylight.controller.cluster.datastore.messages.CommitTransaction;
50 import org.opendaylight.controller.cluster.datastore.messages.CommitTransactionReply;
51 import org.opendaylight.controller.cluster.datastore.messages.CreateSnapshot;
52 import org.opendaylight.controller.cluster.datastore.messages.CreateTransaction;
53 import org.opendaylight.controller.cluster.datastore.messages.CreateTransactionReply;
54 import org.opendaylight.controller.cluster.datastore.messages.EnableNotification;
55 import org.opendaylight.controller.cluster.datastore.messages.ForwardedReadyTransaction;
56 import org.opendaylight.controller.cluster.datastore.messages.PeerAddressResolved;
57 import org.opendaylight.controller.cluster.datastore.messages.ReadyTransactionReply;
58 import org.opendaylight.controller.cluster.datastore.messages.RegisterChangeListener;
59 import org.opendaylight.controller.cluster.datastore.messages.RegisterChangeListenerReply;
60 import org.opendaylight.controller.cluster.datastore.messages.UpdateSchemaContext;
61 import org.opendaylight.controller.cluster.datastore.modification.Modification;
62 import org.opendaylight.controller.cluster.datastore.modification.ModificationPayload;
63 import org.opendaylight.controller.cluster.datastore.modification.MutableCompositeModification;
64 import org.opendaylight.controller.cluster.datastore.utils.Dispatchers;
65 import org.opendaylight.controller.cluster.datastore.utils.MessageTracker;
66 import org.opendaylight.controller.cluster.datastore.utils.SerializationUtils;
67 import org.opendaylight.controller.cluster.notifications.RegisterRoleChangeListener;
68 import org.opendaylight.controller.cluster.notifications.RoleChangeNotifier;
69 import org.opendaylight.controller.cluster.raft.RaftActor;
70 import org.opendaylight.controller.cluster.raft.base.messages.FollowerInitialSyncUpStatus;
71 import org.opendaylight.controller.cluster.raft.messages.AppendEntriesReply;
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.sal.core.spi.data.DOMStoreThreePhaseCommitCohort;
79 import org.opendaylight.controller.sal.core.spi.data.DOMStoreTransaction;
80 import org.opendaylight.controller.sal.core.spi.data.DOMStoreWriteTransaction;
81 import org.opendaylight.yangtools.concepts.ListenerRegistration;
82 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
83 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
84 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
85 import scala.concurrent.duration.Duration;
86 import scala.concurrent.duration.FiniteDuration;
89 * A Shard represents a portion of the logical data tree <br/>
91 * Our Shard uses InMemoryDataStore as it's internal representation and delegates all requests it
94 public class Shard extends RaftActor {
96 private static final YangInstanceIdentifier DATASTORE_ROOT = YangInstanceIdentifier.builder().build();
98 private static final Object TX_COMMIT_TIMEOUT_CHECK_MESSAGE = "txCommitTimeoutCheck";
101 static final String DEFAULT_NAME = "default";
103 // The state of this Shard
104 private final InMemoryDOMDataStore store;
106 /// The name of this shard
107 private final String name;
109 private final ShardStats shardMBean;
111 private final List<ActorSelection> dataChangeListeners = Lists.newArrayList();
113 private final List<DelayedListenerRegistration> delayedListenerRegistrations =
114 Lists.newArrayList();
116 private DatastoreContext datastoreContext;
118 private DataPersistenceProvider dataPersistenceProvider;
120 private SchemaContext schemaContext;
122 private int createSnapshotTransactionCounter;
124 private final ShardCommitCoordinator commitCoordinator;
126 private long transactionCommitTimeout;
128 private Cancellable txCommitTimeoutCheckSchedule;
130 private final Optional<ActorRef> roleChangeNotifier;
132 private final MessageTracker appendEntriesReplyTracker;
134 private final ReadyTransactionReply READY_TRANSACTION_REPLY = new ReadyTransactionReply(
135 Serialization.serializedActorPath(getSelf()));
139 * Coordinates persistence recovery on startup.
141 private ShardRecoveryCoordinator recoveryCoordinator;
143 private final DOMTransactionFactory transactionFactory;
145 private final String txnDispatcherPath;
147 protected Shard(final ShardIdentifier name, final Map<String, String> peerAddresses,
148 final DatastoreContext datastoreContext, final SchemaContext schemaContext) {
149 super(name.toString(), new HashMap<>(peerAddresses), Optional.of(datastoreContext.getShardRaftConfig()));
151 this.name = name.toString();
152 this.datastoreContext = datastoreContext;
153 this.schemaContext = schemaContext;
154 this.dataPersistenceProvider = (datastoreContext.isPersistent())
155 ? new PersistentDataProvider() : new NonPersistentRaftDataProvider();
156 this.txnDispatcherPath = new Dispatchers(context().system().dispatchers())
157 .getDispatcherPath(Dispatchers.DispatcherType.Transaction);
160 LOG.info("Shard created : {}, persistent : {}", name, datastoreContext.isPersistent());
162 store = InMemoryDOMDataStoreFactory.create(name.toString(), null,
163 datastoreContext.getDataStoreProperties());
165 if(schemaContext != null) {
166 store.onGlobalContextUpdated(schemaContext);
169 shardMBean = ShardMBeanFactory.getShardStatsMBean(name.toString(),
170 datastoreContext.getDataStoreMXBeanType());
171 shardMBean.setNotificationManager(store.getDataChangeListenerNotificationManager());
172 shardMBean.setShardActor(getSelf());
174 if (isMetricsCaptureEnabled()) {
175 getContext().become(new MeteringBehavior(this));
178 transactionFactory = new DOMTransactionFactory(store, shardMBean, LOG, this.name);
180 commitCoordinator = new ShardCommitCoordinator(transactionFactory,
181 TimeUnit.SECONDS.convert(5, TimeUnit.MINUTES),
182 datastoreContext.getShardTransactionCommitQueueCapacity(), self(), LOG, this.name);
184 setTransactionCommitTimeout();
186 // create a notifier actor for each cluster member
187 roleChangeNotifier = createRoleChangeNotifier(name.toString());
189 appendEntriesReplyTracker = new MessageTracker(AppendEntriesReply.class,
190 getRaftActorContext().getConfigParams().getIsolatedCheckIntervalInMillis());
192 recoveryCoordinator = new ShardRecoveryCoordinator(store, persistenceId(), LOG);
195 private void setTransactionCommitTimeout() {
196 transactionCommitTimeout = TimeUnit.MILLISECONDS.convert(
197 datastoreContext.getShardTransactionCommitTimeoutInSeconds(), TimeUnit.SECONDS);
200 public static Props props(final ShardIdentifier name,
201 final Map<String, String> peerAddresses,
202 final DatastoreContext datastoreContext, final SchemaContext schemaContext) {
203 Preconditions.checkNotNull(name, "name should not be null");
204 Preconditions.checkNotNull(peerAddresses, "peerAddresses should not be null");
205 Preconditions.checkNotNull(datastoreContext, "dataStoreContext should not be null");
206 Preconditions.checkNotNull(schemaContext, "schemaContext should not be null");
208 return Props.create(new ShardCreator(name, peerAddresses, datastoreContext, schemaContext));
211 private Optional<ActorRef> createRoleChangeNotifier(String shardId) {
212 ActorRef shardRoleChangeNotifier = this.getContext().actorOf(
213 RoleChangeNotifier.getProps(shardId), shardId + "-notifier");
214 return Optional.of(shardRoleChangeNotifier);
218 public void postStop() {
219 LOG.info("Stopping Shard {}", persistenceId());
223 if(txCommitTimeoutCheckSchedule != null) {
224 txCommitTimeoutCheckSchedule.cancel();
227 shardMBean.unregisterMBean();
231 public void onReceiveRecover(final Object message) throws Exception {
232 if(LOG.isDebugEnabled()) {
233 LOG.debug("{}: onReceiveRecover: Received message {} from {}", persistenceId(),
234 message.getClass().toString(), getSender());
237 if (message instanceof RecoveryFailure){
238 LOG.error("{}: Recovery failed because of this cause",
239 persistenceId(), ((RecoveryFailure) message).cause());
241 // Even though recovery failed, we still need to finish our recovery, eg send the
242 // ActorInitialized message and start the txCommitTimeoutCheckSchedule.
243 onRecoveryComplete();
245 super.onReceiveRecover(message);
246 if(LOG.isTraceEnabled()) {
247 appendEntriesReplyTracker.begin();
253 public void onReceiveCommand(final Object message) throws Exception {
255 MessageTracker.Context context = appendEntriesReplyTracker.received(message);
257 if(context.error().isPresent()){
258 LOG.trace("{} : AppendEntriesReply failed to arrive at the expected interval {}", persistenceId(),
263 if (CreateTransaction.SERIALIZABLE_CLASS.isInstance(message)) {
264 handleCreateTransaction(message);
265 } else if (BatchedModifications.class.isInstance(message)) {
266 handleBatchedModifications((BatchedModifications)message);
267 } else if (message instanceof ForwardedReadyTransaction) {
268 handleForwardedReadyTransaction((ForwardedReadyTransaction) message);
269 } else if (CanCommitTransaction.SERIALIZABLE_CLASS.isInstance(message)) {
270 handleCanCommitTransaction(CanCommitTransaction.fromSerializable(message));
271 } else if (CommitTransaction.SERIALIZABLE_CLASS.isInstance(message)) {
272 handleCommitTransaction(CommitTransaction.fromSerializable(message));
273 } else if (AbortTransaction.SERIALIZABLE_CLASS.isInstance(message)) {
274 handleAbortTransaction(AbortTransaction.fromSerializable(message));
275 } else if (CloseTransactionChain.SERIALIZABLE_CLASS.isInstance(message)) {
276 closeTransactionChain(CloseTransactionChain.fromSerializable(message));
277 } else if (message instanceof RegisterChangeListener) {
278 registerChangeListener((RegisterChangeListener) message);
279 } else if (message instanceof UpdateSchemaContext) {
280 updateSchemaContext((UpdateSchemaContext) message);
281 } else if (message instanceof PeerAddressResolved) {
282 PeerAddressResolved resolved = (PeerAddressResolved) message;
283 setPeerAddress(resolved.getPeerId().toString(),
284 resolved.getPeerAddress());
285 } else if (message.equals(TX_COMMIT_TIMEOUT_CHECK_MESSAGE)) {
286 handleTransactionCommitTimeoutCheck();
287 } else if(message instanceof DatastoreContext) {
288 onDatastoreContext((DatastoreContext)message);
289 } else if(message instanceof RegisterRoleChangeListener){
290 roleChangeNotifier.get().forward(message, context());
291 } else if (message instanceof FollowerInitialSyncUpStatus){
292 shardMBean.setFollowerInitialSyncStatus(((FollowerInitialSyncUpStatus) message).isInitialSyncDone());
293 context().parent().tell(message, self());
295 super.onReceiveCommand(message);
303 protected Optional<ActorRef> getRoleChangeNotifier() {
304 return roleChangeNotifier;
307 private void onDatastoreContext(DatastoreContext context) {
308 datastoreContext = context;
310 commitCoordinator.setQueueCapacity(datastoreContext.getShardTransactionCommitQueueCapacity());
312 setTransactionCommitTimeout();
314 if(datastoreContext.isPersistent() &&
315 dataPersistenceProvider instanceof NonPersistentRaftDataProvider) {
316 dataPersistenceProvider = new PersistentDataProvider();
317 } else if(!datastoreContext.isPersistent() &&
318 dataPersistenceProvider instanceof PersistentDataProvider) {
319 dataPersistenceProvider = new NonPersistentRaftDataProvider();
322 updateConfigParams(datastoreContext.getShardRaftConfig());
325 private void handleTransactionCommitTimeoutCheck() {
326 CohortEntry cohortEntry = commitCoordinator.getCurrentCohortEntry();
327 if(cohortEntry != null) {
328 long elapsed = System.currentTimeMillis() - cohortEntry.getLastAccessTime();
329 if(elapsed > transactionCommitTimeout) {
330 LOG.warn("{}: Current transaction {} has timed out after {} ms - aborting",
331 persistenceId(), cohortEntry.getTransactionID(), transactionCommitTimeout);
333 doAbortTransaction(cohortEntry.getTransactionID(), null);
338 private void handleCommitTransaction(final CommitTransaction commit) {
339 final String transactionID = commit.getTransactionID();
341 LOG.debug("{}: Committing transaction {}", persistenceId(), transactionID);
343 // Get the current in-progress cohort entry in the commitCoordinator if it corresponds to
345 final CohortEntry cohortEntry = commitCoordinator.getCohortEntryIfCurrent(transactionID);
346 if(cohortEntry == null) {
347 // We're not the current Tx - the Tx was likely expired b/c it took too long in
348 // between the canCommit and commit messages.
349 IllegalStateException ex = new IllegalStateException(
350 String.format("%s: Cannot commit transaction %s - it is not the current transaction",
351 persistenceId(), transactionID));
352 LOG.error(ex.getMessage());
353 shardMBean.incrementFailedTransactionsCount();
354 getSender().tell(new akka.actor.Status.Failure(ex), getSelf());
358 // We perform the preCommit phase here atomically with the commit phase. This is an
359 // optimization to eliminate the overhead of an extra preCommit message. We lose front-end
360 // coordination of preCommit across shards in case of failure but preCommit should not
361 // normally fail since we ensure only one concurrent 3-phase commit.
364 // We block on the future here so we don't have to worry about possibly accessing our
365 // state on a different thread outside of our dispatcher. Also, the data store
366 // currently uses a same thread executor anyway.
367 cohortEntry.getCohort().preCommit().get();
369 // If we do not have any followers and we are not using persistence
370 // or if cohortEntry has no modifications
371 // we can apply modification to the state immediately
372 if((!hasFollowers() && !persistence().isRecoveryApplicable()) || (!cohortEntry.hasModifications())){
373 applyModificationToState(getSender(), transactionID, cohortEntry.getModification());
375 Shard.this.persistData(getSender(), transactionID,
376 new ModificationPayload(cohortEntry.getModification()));
378 } catch (Exception e) {
379 LOG.error("{} An exception occurred while preCommitting transaction {}",
380 persistenceId(), cohortEntry.getTransactionID(), e);
381 shardMBean.incrementFailedTransactionsCount();
382 getSender().tell(new akka.actor.Status.Failure(e), getSelf());
385 cohortEntry.updateLastAccessTime();
388 private void finishCommit(@Nonnull final ActorRef sender, final @Nonnull String transactionID) {
389 // With persistence enabled, this method is called via applyState by the leader strategy
390 // after the commit has been replicated to a majority of the followers.
392 CohortEntry cohortEntry = commitCoordinator.getCohortEntryIfCurrent(transactionID);
393 if(cohortEntry == null) {
394 // The transaction is no longer the current commit. This can happen if the transaction
395 // was aborted prior, most likely due to timeout in the front-end. We need to finish
396 // committing the transaction though since it was successfully persisted and replicated
397 // however we can't use the original cohort b/c it was already preCommitted and may
398 // conflict with the current commit or may have been aborted so we commit with a new
400 cohortEntry = commitCoordinator.getAndRemoveCohortEntry(transactionID);
401 if(cohortEntry != null) {
402 commitWithNewTransaction(cohortEntry.getModification());
403 sender.tell(CommitTransactionReply.INSTANCE.toSerializable(), getSelf());
405 // This really shouldn't happen - it likely means that persistence or replication
406 // took so long to complete such that the cohort entry was expired from the cache.
407 IllegalStateException ex = new IllegalStateException(
408 String.format("%s: Could not finish committing transaction %s - no CohortEntry found",
409 persistenceId(), transactionID));
410 LOG.error(ex.getMessage());
411 sender.tell(new akka.actor.Status.Failure(ex), getSelf());
417 LOG.debug("{}: Finishing commit for transaction {}", persistenceId(), cohortEntry.getTransactionID());
420 // We block on the future here so we don't have to worry about possibly accessing our
421 // state on a different thread outside of our dispatcher. Also, the data store
422 // currently uses a same thread executor anyway.
423 cohortEntry.getCohort().commit().get();
425 sender.tell(CommitTransactionReply.INSTANCE.toSerializable(), getSelf());
427 shardMBean.incrementCommittedTransactionCount();
428 shardMBean.setLastCommittedTransactionTime(System.currentTimeMillis());
430 } catch (Exception e) {
431 sender.tell(new akka.actor.Status.Failure(e), getSelf());
433 LOG.error("{}, An exception occurred while committing transaction {}", persistenceId(),
435 shardMBean.incrementFailedTransactionsCount();
437 commitCoordinator.currentTransactionComplete(transactionID, true);
441 private void handleCanCommitTransaction(final CanCommitTransaction canCommit) {
442 LOG.debug("{}: Can committing transaction {}", persistenceId(), canCommit.getTransactionID());
443 commitCoordinator.handleCanCommit(canCommit, getSender(), self());
446 private void handleBatchedModifications(BatchedModifications batched) {
447 // This message is sent to prepare the modificationsa transaction directly on the Shard as an
448 // optimization to avoid the extra overhead of a separate ShardTransaction actor. On the last
449 // BatchedModifications message, the caller sets the ready flag in the message indicating
450 // modifications are complete. The reply contains the cohort actor path (this actor) for the caller
451 // to initiate the 3-phase commit. This also avoids the overhead of sending an additional
452 // ReadyTransaction message.
454 // If we're not the leader then forward to the leader. This is a safety measure - we shouldn't
455 // normally get here if we're not the leader as the front-end (TransactionProxy) should determine
456 // the primary/leader shard. However with timing and caching on the front-end, there's a small
457 // window where it could have a stale leader during leadership transitions.
461 BatchedModificationsReply reply = commitCoordinator.handleTransactionModifications(batched);
462 sender().tell(reply, self());
463 } catch (Exception e) {
464 LOG.error("{}: Error handling BatchedModifications for Tx {}", persistenceId(),
465 batched.getTransactionID(), e);
466 getSender().tell(new akka.actor.Status.Failure(e), getSelf());
469 ActorSelection leader = getLeader();
471 // TODO: what if this is not the first batch and leadership changed in between batched messages?
472 // We could check if the commitCoordinator already has a cached entry and forward all the previous
473 // batched modifications.
474 LOG.debug("{}: Forwarding BatchedModifications to leader {}", persistenceId(), leader);
475 leader.forward(batched, getContext());
477 // TODO: rather than throwing an immediate exception, we could schedule a timer to try again to make
478 // it more resilient in case we're in the process of electing a new leader.
479 getSender().tell(new akka.actor.Status.Failure(new NoShardLeaderException(String.format(
480 "Could not find the leader for shard %s. This typically happens" +
481 " when the system is coming up or recovering and a leader is being elected. Try again" +
482 " later.", persistenceId()))), getSelf());
487 private void handleForwardedReadyTransaction(ForwardedReadyTransaction ready) {
488 LOG.debug("{}: Readying transaction {}, client version {}", persistenceId(),
489 ready.getTransactionID(), ready.getTxnClientVersion());
491 // This message is forwarded by the ShardTransaction on ready. We cache the cohort in the
492 // commitCoordinator in preparation for the subsequent three phase commit initiated by
494 commitCoordinator.transactionReady(ready.getTransactionID(), ready.getCohort(),
495 (MutableCompositeModification) ready.getModification());
497 // Return our actor path as we'll handle the three phase commit, except if the Tx client
498 // version < 1 (Helium-1 version). This means the Tx was initiated by a base Helium version
499 // node. In that case, the subsequent 3-phase commit messages won't contain the
500 // transactionId so to maintain backwards compatibility, we create a separate cohort actor
501 // to provide the compatible behavior.
502 if(ready.getTxnClientVersion() < DataStoreVersions.HELIUM_1_VERSION) {
503 LOG.debug("{}: Creating BackwardsCompatibleThreePhaseCommitCohort", persistenceId());
504 ActorRef replyActorPath = getContext().actorOf(BackwardsCompatibleThreePhaseCommitCohort.props(
505 ready.getTransactionID()));
507 ReadyTransactionReply readyTransactionReply =
508 new ReadyTransactionReply(Serialization.serializedActorPath(replyActorPath));
509 getSender().tell(ready.isReturnSerialized() ? readyTransactionReply.toSerializable() :
510 readyTransactionReply, getSelf());
514 getSender().tell(ready.isReturnSerialized() ? READY_TRANSACTION_REPLY.toSerializable() :
515 READY_TRANSACTION_REPLY, getSelf());
519 private void handleAbortTransaction(final AbortTransaction abort) {
520 doAbortTransaction(abort.getTransactionID(), getSender());
523 void doAbortTransaction(final String transactionID, final ActorRef sender) {
524 final CohortEntry cohortEntry = commitCoordinator.getCohortEntryIfCurrent(transactionID);
525 if(cohortEntry != null) {
526 LOG.debug("{}: Aborting transaction {}", persistenceId(), transactionID);
528 // We don't remove the cached cohort entry here (ie pass false) in case the Tx was
529 // aborted during replication in which case we may still commit locally if replication
531 commitCoordinator.currentTransactionComplete(transactionID, false);
533 final ListenableFuture<Void> future = cohortEntry.getCohort().abort();
534 final ActorRef self = getSelf();
536 Futures.addCallback(future, new FutureCallback<Void>() {
538 public void onSuccess(final Void v) {
539 shardMBean.incrementAbortTransactionsCount();
542 sender.tell(AbortTransactionReply.INSTANCE.toSerializable(), self);
547 public void onFailure(final Throwable t) {
548 LOG.error("{}: An exception happened during abort", persistenceId(), t);
551 sender.tell(new akka.actor.Status.Failure(t), self);
558 private void handleCreateTransaction(final Object message) {
560 createTransaction(CreateTransaction.fromSerializable(message));
561 } else if (getLeader() != null) {
562 getLeader().forward(message, getContext());
564 getSender().tell(new akka.actor.Status.Failure(new NoShardLeaderException(String.format(
565 "Could not find leader for shard %s so transaction cannot be created. This typically happens" +
566 " when the system is coming up or recovering and a leader is being elected. Try again" +
567 " later.", persistenceId()))), getSelf());
571 private void closeTransactionChain(final CloseTransactionChain closeTransactionChain) {
572 transactionFactory.closeTransactionChain(closeTransactionChain.getTransactionChainId());
575 private ActorRef createTypedTransactionActor(int transactionType,
576 ShardTransactionIdentifier transactionId, String transactionChainId,
577 short clientVersion ) {
579 DOMStoreTransaction transaction = transactionFactory.newTransaction(
580 TransactionProxy.TransactionType.fromInt(transactionType), transactionId.toString(),
583 return createShardTransaction(transaction, transactionId, clientVersion);
586 private ActorRef createShardTransaction(DOMStoreTransaction transaction, ShardTransactionIdentifier transactionId,
587 short clientVersion){
588 return getContext().actorOf(
589 ShardTransaction.props(transaction, getSelf(),
590 schemaContext, datastoreContext, shardMBean,
591 transactionId.getRemoteTransactionId(), clientVersion)
592 .withDispatcher(txnDispatcherPath),
593 transactionId.toString());
597 private void createTransaction(CreateTransaction createTransaction) {
599 ActorRef transactionActor = createTransaction(createTransaction.getTransactionType(),
600 createTransaction.getTransactionId(), createTransaction.getTransactionChainId(),
601 createTransaction.getVersion());
603 getSender().tell(new CreateTransactionReply(Serialization.serializedActorPath(transactionActor),
604 createTransaction.getTransactionId()).toSerializable(), getSelf());
605 } catch (Exception e) {
606 getSender().tell(new akka.actor.Status.Failure(e), getSelf());
610 private ActorRef createTransaction(int transactionType, String remoteTransactionId,
611 String transactionChainId, short clientVersion) {
614 ShardTransactionIdentifier transactionId = new ShardTransactionIdentifier(remoteTransactionId);
616 if(LOG.isDebugEnabled()) {
617 LOG.debug("{}: Creating transaction : {} ", persistenceId(), transactionId);
620 ActorRef transactionActor = createTypedTransactionActor(transactionType, transactionId,
621 transactionChainId, clientVersion);
623 return transactionActor;
626 private void syncCommitTransaction(final DOMStoreWriteTransaction transaction)
627 throws ExecutionException, InterruptedException {
628 DOMStoreThreePhaseCommitCohort commitCohort = transaction.ready();
629 commitCohort.preCommit().get();
630 commitCohort.commit().get();
633 private void commitWithNewTransaction(final Modification modification) {
634 DOMStoreWriteTransaction tx = store.newWriteOnlyTransaction();
635 modification.apply(tx);
637 syncCommitTransaction(tx);
638 shardMBean.incrementCommittedTransactionCount();
639 shardMBean.setLastCommittedTransactionTime(System.currentTimeMillis());
640 } catch (InterruptedException | ExecutionException e) {
641 shardMBean.incrementFailedTransactionsCount();
642 LOG.error("{}: Failed to commit", persistenceId(), e);
646 private void updateSchemaContext(final UpdateSchemaContext message) {
647 this.schemaContext = message.getSchemaContext();
648 updateSchemaContext(message.getSchemaContext());
649 store.onGlobalContextUpdated(message.getSchemaContext());
653 void updateSchemaContext(final SchemaContext schemaContext) {
654 store.onGlobalContextUpdated(schemaContext);
657 private void registerChangeListener(final RegisterChangeListener registerChangeListener) {
659 LOG.debug("{}: registerDataChangeListener for {}", persistenceId(), registerChangeListener.getPath());
661 ListenerRegistration<AsyncDataChangeListener<YangInstanceIdentifier,
662 NormalizedNode<?, ?>>> registration;
664 registration = doChangeListenerRegistration(registerChangeListener);
666 LOG.debug("{}: Shard is not the leader - delaying registration", persistenceId());
668 DelayedListenerRegistration delayedReg =
669 new DelayedListenerRegistration(registerChangeListener);
670 delayedListenerRegistrations.add(delayedReg);
671 registration = delayedReg;
674 ActorRef listenerRegistration = getContext().actorOf(
675 DataChangeListenerRegistration.props(registration));
677 LOG.debug("{}: registerDataChangeListener sending reply, listenerRegistrationPath = {} ",
678 persistenceId(), listenerRegistration.path());
680 getSender().tell(new RegisterChangeListenerReply(listenerRegistration), getSelf());
683 private ListenerRegistration<AsyncDataChangeListener<YangInstanceIdentifier,
684 NormalizedNode<?, ?>>> doChangeListenerRegistration(
685 final RegisterChangeListener registerChangeListener) {
687 ActorSelection dataChangeListenerPath = getContext().system().actorSelection(
688 registerChangeListener.getDataChangeListenerPath());
690 // Notify the listener if notifications should be enabled or not
691 // If this shard is the leader then it will enable notifications else
693 dataChangeListenerPath.tell(new EnableNotification(true), getSelf());
695 // Now store a reference to the data change listener so it can be notified
696 // at a later point if notifications should be enabled or disabled
697 dataChangeListeners.add(dataChangeListenerPath);
699 AsyncDataChangeListener<YangInstanceIdentifier, NormalizedNode<?, ?>> listener =
700 new DataChangeListenerProxy(dataChangeListenerPath);
702 LOG.debug("{}: Registering for path {}", persistenceId(), registerChangeListener.getPath());
704 return store.registerChangeListener(registerChangeListener.getPath(), listener,
705 registerChangeListener.getScope());
708 private boolean isMetricsCaptureEnabled(){
709 CommonConfig config = new CommonConfig(getContext().system().settings().config());
710 return config.isMetricCaptureEnabled();
715 void startLogRecoveryBatch(final int maxBatchSize) {
716 recoveryCoordinator.startLogRecoveryBatch(maxBatchSize);
720 protected void appendRecoveredLogEntry(final Payload data) {
721 recoveryCoordinator.appendRecoveredLogPayload(data);
725 protected void applyRecoverySnapshot(final byte[] snapshotBytes) {
726 recoveryCoordinator.applyRecoveredSnapshot(snapshotBytes);
730 protected void applyCurrentLogRecoveryBatch() {
731 recoveryCoordinator.applyCurrentLogRecoveryBatch();
735 protected void onRecoveryComplete() {
736 recoveryCoordinator = null;
738 //notify shard manager
739 getContext().parent().tell(new ActorInitialized(), getSelf());
741 // Being paranoid here - this method should only be called once but just in case...
742 if(txCommitTimeoutCheckSchedule == null) {
743 // Schedule a message to be periodically sent to check if the current in-progress
744 // transaction should be expired and aborted.
745 FiniteDuration period = Duration.create(transactionCommitTimeout / 3, TimeUnit.MILLISECONDS);
746 txCommitTimeoutCheckSchedule = getContext().system().scheduler().schedule(
747 period, period, getSelf(),
748 TX_COMMIT_TIMEOUT_CHECK_MESSAGE, getContext().dispatcher(), ActorRef.noSender());
753 protected void applyState(final ActorRef clientActor, final String identifier, final Object data) {
755 if(data instanceof ModificationPayload) {
757 applyModificationToState(clientActor, identifier, ((ModificationPayload) data).getModification());
758 } catch (ClassNotFoundException | IOException e) {
759 LOG.error("{}: Error extracting ModificationPayload", persistenceId(), e);
762 else if (data instanceof CompositeModificationPayload) {
763 Object modification = ((CompositeModificationPayload) data).getModification();
765 applyModificationToState(clientActor, identifier, modification);
766 } else if(data instanceof CompositeModificationByteStringPayload ){
767 Object modification = ((CompositeModificationByteStringPayload) data).getModification();
769 applyModificationToState(clientActor, identifier, modification);
771 LOG.error("{}: Unknown state received {} Class loader = {} CompositeNodeMod.ClassLoader = {}",
772 persistenceId(), data, data.getClass().getClassLoader(),
773 CompositeModificationPayload.class.getClassLoader());
777 private void applyModificationToState(ActorRef clientActor, String identifier, Object modification) {
778 if(modification == null) {
780 "{}: modification is null - this is very unexpected, clientActor = {}, identifier = {}",
781 persistenceId(), identifier, clientActor != null ? clientActor.path().toString() : null);
782 } else if(clientActor == null) {
783 // There's no clientActor to which to send a commit reply so we must be applying
784 // replicated state from the leader.
785 commitWithNewTransaction(MutableCompositeModification.fromSerializable(modification));
787 // This must be the OK to commit after replication consensus.
788 finishCommit(clientActor, identifier);
793 protected void createSnapshot() {
794 // Create a transaction actor. We are really going to treat the transaction as a worker
795 // so that this actor does not get block building the snapshot. THe transaction actor will
796 // after processing the CreateSnapshot message.
798 ActorRef createSnapshotTransaction = createTransaction(
799 TransactionProxy.TransactionType.READ_ONLY.ordinal(),
800 "createSnapshot" + ++createSnapshotTransactionCounter, "",
801 DataStoreVersions.CURRENT_VERSION);
803 createSnapshotTransaction.tell(CreateSnapshot.INSTANCE, self());
808 protected void applySnapshot(final byte[] snapshotBytes) {
809 // Since this will be done only on Recovery or when this actor is a Follower
810 // we can safely commit everything in here. We not need to worry about event notifications
811 // as they would have already been disabled on the follower
813 LOG.info("{}: Applying snapshot", persistenceId());
815 DOMStoreWriteTransaction transaction = store.newWriteOnlyTransaction();
817 NormalizedNode<?, ?> node = SerializationUtils.deserializeNormalizedNode(snapshotBytes);
819 // delete everything first
820 transaction.delete(DATASTORE_ROOT);
822 // Add everything from the remote node back
823 transaction.write(DATASTORE_ROOT, node);
824 syncCommitTransaction(transaction);
825 } catch (InterruptedException | ExecutionException e) {
826 LOG.error("{}: An exception occurred when applying snapshot", persistenceId(), e);
828 LOG.info("{}: Done applying snapshot", persistenceId());
833 protected void onStateChanged() {
834 boolean isLeader = isLeader();
835 for (ActorSelection dataChangeListener : dataChangeListeners) {
836 dataChangeListener.tell(new EnableNotification(isLeader), getSelf());
840 for(DelayedListenerRegistration reg: delayedListenerRegistrations) {
841 if(!reg.isClosed()) {
842 reg.setDelegate(doChangeListenerRegistration(reg.getRegisterChangeListener()));
846 delayedListenerRegistrations.clear();
849 // If this actor is no longer the leader close all the transaction chains
851 if(LOG.isDebugEnabled()) {
853 "{}: onStateChanged: Closing all transaction chains because shard {} is no longer the leader",
854 persistenceId(), getId());
857 transactionFactory.closeAllTransactionChains();
862 protected DataPersistenceProvider persistence() {
863 return dataPersistenceProvider;
866 @Override public String persistenceId() {
871 DataPersistenceProvider getDataPersistenceProvider() {
872 return dataPersistenceProvider;
876 ShardCommitCoordinator getCommitCoordinator() {
877 return commitCoordinator;
881 private static class ShardCreator implements Creator<Shard> {
883 private static final long serialVersionUID = 1L;
885 final ShardIdentifier name;
886 final Map<String, String> peerAddresses;
887 final DatastoreContext datastoreContext;
888 final SchemaContext schemaContext;
890 ShardCreator(final ShardIdentifier name, final Map<String, String> peerAddresses,
891 final DatastoreContext datastoreContext, final SchemaContext schemaContext) {
893 this.peerAddresses = peerAddresses;
894 this.datastoreContext = datastoreContext;
895 this.schemaContext = schemaContext;
899 public Shard create() throws Exception {
900 return new Shard(name, peerAddresses, datastoreContext, schemaContext);
905 public InMemoryDOMDataStore getDataStore() {
910 ShardStats getShardMBean() {
914 private static class DelayedListenerRegistration implements
915 ListenerRegistration<AsyncDataChangeListener<YangInstanceIdentifier, NormalizedNode<?, ?>>> {
917 private volatile boolean closed;
919 private final RegisterChangeListener registerChangeListener;
921 private volatile ListenerRegistration<AsyncDataChangeListener<YangInstanceIdentifier,
922 NormalizedNode<?, ?>>> delegate;
924 DelayedListenerRegistration(final RegisterChangeListener registerChangeListener) {
925 this.registerChangeListener = registerChangeListener;
928 void setDelegate( final ListenerRegistration<AsyncDataChangeListener<YangInstanceIdentifier,
929 NormalizedNode<?, ?>>> registration) {
930 this.delegate = registration;
937 RegisterChangeListener getRegisterChangeListener() {
938 return registerChangeListener;
942 public AsyncDataChangeListener<YangInstanceIdentifier, NormalizedNode<?, ?>> getInstance() {
943 return delegate != null ? delegate.getInstance() : null;
947 public void close() {
949 if(delegate != null) {