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.RegisterDataTreeChangeListener;
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 SchemaContext schemaContext;
120 private int createSnapshotTransactionCounter;
122 private final ShardCommitCoordinator commitCoordinator;
124 private long transactionCommitTimeout;
126 private Cancellable txCommitTimeoutCheckSchedule;
128 private final Optional<ActorRef> roleChangeNotifier;
130 private final MessageTracker appendEntriesReplyTracker;
132 private final ReadyTransactionReply READY_TRANSACTION_REPLY = new ReadyTransactionReply(
133 Serialization.serializedActorPath(getSelf()));
137 * Coordinates persistence recovery on startup.
139 private ShardRecoveryCoordinator recoveryCoordinator;
141 private final DOMTransactionFactory transactionFactory;
143 private final String txnDispatcherPath;
145 private final DataTreeChangeListenerSupport treeChangeSupport = new DataTreeChangeListenerSupport(this);
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.txnDispatcherPath = new Dispatchers(context().system().dispatchers())
155 .getDispatcherPath(Dispatchers.DispatcherType.Transaction);
157 setPersistence(datastoreContext.isPersistent());
159 LOG.info("Shard created : {}, persistent : {}", name, datastoreContext.isPersistent());
161 store = InMemoryDOMDataStoreFactory.create(name.toString(), null,
162 datastoreContext.getDataStoreProperties());
164 if (schemaContext != null) {
165 store.onGlobalContextUpdated(schemaContext);
168 shardMBean = ShardMBeanFactory.getShardStatsMBean(name.toString(),
169 datastoreContext.getDataStoreMXBeanType());
170 shardMBean.setNotificationManager(store.getDataChangeListenerNotificationManager());
171 shardMBean.setShardActor(getSelf());
173 if (isMetricsCaptureEnabled()) {
174 getContext().become(new MeteringBehavior(this));
177 transactionFactory = new DOMTransactionFactory(store, shardMBean, LOG, this.name);
179 commitCoordinator = new ShardCommitCoordinator(transactionFactory,
180 TimeUnit.SECONDS.convert(5, TimeUnit.MINUTES),
181 datastoreContext.getShardTransactionCommitQueueCapacity(), self(), LOG, this.name);
183 setTransactionCommitTimeout();
185 // create a notifier actor for each cluster member
186 roleChangeNotifier = createRoleChangeNotifier(name.toString());
188 appendEntriesReplyTracker = new MessageTracker(AppendEntriesReply.class,
189 getRaftActorContext().getConfigParams().getIsolatedCheckIntervalInMillis());
191 recoveryCoordinator = new ShardRecoveryCoordinator(store, persistenceId(), LOG);
194 private void setTransactionCommitTimeout() {
195 transactionCommitTimeout = TimeUnit.MILLISECONDS.convert(
196 datastoreContext.getShardTransactionCommitTimeoutInSeconds(), TimeUnit.SECONDS);
199 public static Props props(final ShardIdentifier name,
200 final Map<String, String> peerAddresses,
201 final DatastoreContext datastoreContext, final SchemaContext schemaContext) {
202 Preconditions.checkNotNull(name, "name should not be null");
203 Preconditions.checkNotNull(peerAddresses, "peerAddresses should not be null");
204 Preconditions.checkNotNull(datastoreContext, "dataStoreContext should not be null");
205 Preconditions.checkNotNull(schemaContext, "schemaContext should not be null");
207 return Props.create(new ShardCreator(name, peerAddresses, datastoreContext, schemaContext));
210 private Optional<ActorRef> createRoleChangeNotifier(String shardId) {
211 ActorRef shardRoleChangeNotifier = this.getContext().actorOf(
212 RoleChangeNotifier.getProps(shardId), shardId + "-notifier");
213 return Optional.of(shardRoleChangeNotifier);
217 public void postStop() {
218 LOG.info("Stopping Shard {}", persistenceId());
222 if(txCommitTimeoutCheckSchedule != null) {
223 txCommitTimeoutCheckSchedule.cancel();
226 shardMBean.unregisterMBean();
230 public void onReceiveRecover(final Object message) throws Exception {
231 if(LOG.isDebugEnabled()) {
232 LOG.debug("{}: onReceiveRecover: Received message {} from {}", persistenceId(),
233 message.getClass().toString(), getSender());
236 if (message instanceof RecoveryFailure){
237 LOG.error("{}: Recovery failed because of this cause",
238 persistenceId(), ((RecoveryFailure) message).cause());
240 // Even though recovery failed, we still need to finish our recovery, eg send the
241 // ActorInitialized message and start the txCommitTimeoutCheckSchedule.
242 onRecoveryComplete();
244 super.onReceiveRecover(message);
245 if(LOG.isTraceEnabled()) {
246 appendEntriesReplyTracker.begin();
252 public void onReceiveCommand(final Object message) throws Exception {
254 MessageTracker.Context context = appendEntriesReplyTracker.received(message);
256 if(context.error().isPresent()){
257 LOG.trace("{} : AppendEntriesReply failed to arrive at the expected interval {}", persistenceId(),
262 if (CreateTransaction.SERIALIZABLE_CLASS.isInstance(message)) {
263 handleCreateTransaction(message);
264 } else if (BatchedModifications.class.isInstance(message)) {
265 handleBatchedModifications((BatchedModifications)message);
266 } else if (message instanceof ForwardedReadyTransaction) {
267 handleForwardedReadyTransaction((ForwardedReadyTransaction) message);
268 } else if (CanCommitTransaction.SERIALIZABLE_CLASS.isInstance(message)) {
269 handleCanCommitTransaction(CanCommitTransaction.fromSerializable(message));
270 } else if (CommitTransaction.SERIALIZABLE_CLASS.isInstance(message)) {
271 handleCommitTransaction(CommitTransaction.fromSerializable(message));
272 } else if (AbortTransaction.SERIALIZABLE_CLASS.isInstance(message)) {
273 handleAbortTransaction(AbortTransaction.fromSerializable(message));
274 } else if (CloseTransactionChain.SERIALIZABLE_CLASS.isInstance(message)) {
275 closeTransactionChain(CloseTransactionChain.fromSerializable(message));
276 } else if (message instanceof RegisterChangeListener) {
277 registerChangeListener((RegisterChangeListener) message);
278 } else if (message instanceof RegisterDataTreeChangeListener) {
279 treeChangeSupport.onMessage((RegisterDataTreeChangeListener) message, isLeader());
280 } else if (message instanceof UpdateSchemaContext) {
281 updateSchemaContext((UpdateSchemaContext) message);
282 } else if (message instanceof PeerAddressResolved) {
283 PeerAddressResolved resolved = (PeerAddressResolved) message;
284 setPeerAddress(resolved.getPeerId().toString(),
285 resolved.getPeerAddress());
286 } else if (message.equals(TX_COMMIT_TIMEOUT_CHECK_MESSAGE)) {
287 handleTransactionCommitTimeoutCheck();
288 } else if(message instanceof DatastoreContext) {
289 onDatastoreContext((DatastoreContext)message);
290 } else if(message instanceof RegisterRoleChangeListener){
291 roleChangeNotifier.get().forward(message, context());
292 } else if (message instanceof FollowerInitialSyncUpStatus){
293 shardMBean.setFollowerInitialSyncStatus(((FollowerInitialSyncUpStatus) message).isInitialSyncDone());
294 context().parent().tell(message, self());
296 super.onReceiveCommand(message);
304 protected Optional<ActorRef> getRoleChangeNotifier() {
305 return roleChangeNotifier;
308 private void onDatastoreContext(DatastoreContext context) {
309 datastoreContext = context;
311 commitCoordinator.setQueueCapacity(datastoreContext.getShardTransactionCommitQueueCapacity());
313 setTransactionCommitTimeout();
315 if(datastoreContext.isPersistent() && !persistence().isRecoveryApplicable()) {
316 setPersistence(true);
317 } else if(!datastoreContext.isPersistent() && persistence().isRecoveryApplicable()) {
318 setPersistence(false);
321 updateConfigParams(datastoreContext.getShardRaftConfig());
324 private void handleTransactionCommitTimeoutCheck() {
325 CohortEntry cohortEntry = commitCoordinator.getCurrentCohortEntry();
326 if(cohortEntry != null) {
327 long elapsed = System.currentTimeMillis() - cohortEntry.getLastAccessTime();
328 if(elapsed > transactionCommitTimeout) {
329 LOG.warn("{}: Current transaction {} has timed out after {} ms - aborting",
330 persistenceId(), cohortEntry.getTransactionID(), transactionCommitTimeout);
332 doAbortTransaction(cohortEntry.getTransactionID(), null);
337 private void handleCommitTransaction(final CommitTransaction commit) {
338 final String transactionID = commit.getTransactionID();
340 LOG.debug("{}: Committing transaction {}", persistenceId(), transactionID);
342 // Get the current in-progress cohort entry in the commitCoordinator if it corresponds to
344 final CohortEntry cohortEntry = commitCoordinator.getCohortEntryIfCurrent(transactionID);
345 if(cohortEntry == null) {
346 // We're not the current Tx - the Tx was likely expired b/c it took too long in
347 // between the canCommit and commit messages.
348 IllegalStateException ex = new IllegalStateException(
349 String.format("%s: Cannot commit transaction %s - it is not the current transaction",
350 persistenceId(), transactionID));
351 LOG.error(ex.getMessage());
352 shardMBean.incrementFailedTransactionsCount();
353 getSender().tell(new akka.actor.Status.Failure(ex), getSelf());
357 // We perform the preCommit phase here atomically with the commit phase. This is an
358 // optimization to eliminate the overhead of an extra preCommit message. We lose front-end
359 // coordination of preCommit across shards in case of failure but preCommit should not
360 // normally fail since we ensure only one concurrent 3-phase commit.
363 // We block on the future here so we don't have to worry about possibly accessing our
364 // state on a different thread outside of our dispatcher. Also, the data store
365 // currently uses a same thread executor anyway.
366 cohortEntry.getCohort().preCommit().get();
368 // If we do not have any followers and we are not using persistence
369 // or if cohortEntry has no modifications
370 // we can apply modification to the state immediately
371 if((!hasFollowers() && !persistence().isRecoveryApplicable()) || (!cohortEntry.hasModifications())){
372 applyModificationToState(getSender(), transactionID, cohortEntry.getModification());
374 Shard.this.persistData(getSender(), transactionID,
375 new ModificationPayload(cohortEntry.getModification()));
377 } catch (Exception e) {
378 LOG.error("{} An exception occurred while preCommitting transaction {}",
379 persistenceId(), cohortEntry.getTransactionID(), e);
380 shardMBean.incrementFailedTransactionsCount();
381 getSender().tell(new akka.actor.Status.Failure(e), getSelf());
384 cohortEntry.updateLastAccessTime();
387 private void finishCommit(@Nonnull final ActorRef sender, final @Nonnull String transactionID) {
388 // With persistence enabled, this method is called via applyState by the leader strategy
389 // after the commit has been replicated to a majority of the followers.
391 CohortEntry cohortEntry = commitCoordinator.getCohortEntryIfCurrent(transactionID);
392 if(cohortEntry == null) {
393 // The transaction is no longer the current commit. This can happen if the transaction
394 // was aborted prior, most likely due to timeout in the front-end. We need to finish
395 // committing the transaction though since it was successfully persisted and replicated
396 // however we can't use the original cohort b/c it was already preCommitted and may
397 // conflict with the current commit or may have been aborted so we commit with a new
399 cohortEntry = commitCoordinator.getAndRemoveCohortEntry(transactionID);
400 if(cohortEntry != null) {
401 commitWithNewTransaction(cohortEntry.getModification());
402 sender.tell(CommitTransactionReply.INSTANCE.toSerializable(), getSelf());
404 // This really shouldn't happen - it likely means that persistence or replication
405 // took so long to complete such that the cohort entry was expired from the cache.
406 IllegalStateException ex = new IllegalStateException(
407 String.format("%s: Could not finish committing transaction %s - no CohortEntry found",
408 persistenceId(), transactionID));
409 LOG.error(ex.getMessage());
410 sender.tell(new akka.actor.Status.Failure(ex), getSelf());
416 LOG.debug("{}: Finishing commit for transaction {}", persistenceId(), cohortEntry.getTransactionID());
419 // We block on the future here so we don't have to worry about possibly accessing our
420 // state on a different thread outside of our dispatcher. Also, the data store
421 // currently uses a same thread executor anyway.
422 cohortEntry.getCohort().commit().get();
424 sender.tell(CommitTransactionReply.INSTANCE.toSerializable(), getSelf());
426 shardMBean.incrementCommittedTransactionCount();
427 shardMBean.setLastCommittedTransactionTime(System.currentTimeMillis());
429 } catch (Exception e) {
430 sender.tell(new akka.actor.Status.Failure(e), getSelf());
432 LOG.error("{}, An exception occurred while committing transaction {}", persistenceId(),
434 shardMBean.incrementFailedTransactionsCount();
436 commitCoordinator.currentTransactionComplete(transactionID, true);
440 private void handleCanCommitTransaction(final CanCommitTransaction canCommit) {
441 LOG.debug("{}: Can committing transaction {}", persistenceId(), canCommit.getTransactionID());
442 commitCoordinator.handleCanCommit(canCommit, getSender(), self());
445 private void handleBatchedModifications(BatchedModifications batched) {
446 // This message is sent to prepare the modificationsa transaction directly on the Shard as an
447 // optimization to avoid the extra overhead of a separate ShardTransaction actor. On the last
448 // BatchedModifications message, the caller sets the ready flag in the message indicating
449 // modifications are complete. The reply contains the cohort actor path (this actor) for the caller
450 // to initiate the 3-phase commit. This also avoids the overhead of sending an additional
451 // ReadyTransaction message.
453 // If we're not the leader then forward to the leader. This is a safety measure - we shouldn't
454 // normally get here if we're not the leader as the front-end (TransactionProxy) should determine
455 // the primary/leader shard. However with timing and caching on the front-end, there's a small
456 // window where it could have a stale leader during leadership transitions.
460 BatchedModificationsReply reply = commitCoordinator.handleTransactionModifications(batched);
461 sender().tell(reply, self());
462 } catch (Exception e) {
463 LOG.error("{}: Error handling BatchedModifications for Tx {}", persistenceId(),
464 batched.getTransactionID(), e);
465 getSender().tell(new akka.actor.Status.Failure(e), getSelf());
468 ActorSelection leader = getLeader();
470 // TODO: what if this is not the first batch and leadership changed in between batched messages?
471 // We could check if the commitCoordinator already has a cached entry and forward all the previous
472 // batched modifications.
473 LOG.debug("{}: Forwarding BatchedModifications to leader {}", persistenceId(), leader);
474 leader.forward(batched, getContext());
476 // TODO: rather than throwing an immediate exception, we could schedule a timer to try again to make
477 // it more resilient in case we're in the process of electing a new leader.
478 getSender().tell(new akka.actor.Status.Failure(new NoShardLeaderException(String.format(
479 "Could not find the leader for shard %s. This typically happens" +
480 " when the system is coming up or recovering and a leader is being elected. Try again" +
481 " later.", persistenceId()))), getSelf());
486 private void handleForwardedReadyTransaction(ForwardedReadyTransaction ready) {
487 LOG.debug("{}: Readying transaction {}, client version {}", persistenceId(),
488 ready.getTransactionID(), ready.getTxnClientVersion());
490 // This message is forwarded by the ShardTransaction on ready. We cache the cohort in the
491 // commitCoordinator in preparation for the subsequent three phase commit initiated by
493 commitCoordinator.transactionReady(ready.getTransactionID(), ready.getCohort(),
494 (MutableCompositeModification) ready.getModification());
496 // Return our actor path as we'll handle the three phase commit, except if the Tx client
497 // version < 1 (Helium-1 version). This means the Tx was initiated by a base Helium version
498 // node. In that case, the subsequent 3-phase commit messages won't contain the
499 // transactionId so to maintain backwards compatibility, we create a separate cohort actor
500 // to provide the compatible behavior.
501 if(ready.getTxnClientVersion() < DataStoreVersions.HELIUM_1_VERSION) {
502 LOG.debug("{}: Creating BackwardsCompatibleThreePhaseCommitCohort", persistenceId());
503 ActorRef replyActorPath = getContext().actorOf(BackwardsCompatibleThreePhaseCommitCohort.props(
504 ready.getTransactionID()));
506 ReadyTransactionReply readyTransactionReply =
507 new ReadyTransactionReply(Serialization.serializedActorPath(replyActorPath));
508 getSender().tell(ready.isReturnSerialized() ? readyTransactionReply.toSerializable() :
509 readyTransactionReply, getSelf());
513 getSender().tell(ready.isReturnSerialized() ? READY_TRANSACTION_REPLY.toSerializable() :
514 READY_TRANSACTION_REPLY, getSelf());
518 private void handleAbortTransaction(final AbortTransaction abort) {
519 doAbortTransaction(abort.getTransactionID(), getSender());
522 void doAbortTransaction(final String transactionID, final ActorRef sender) {
523 final CohortEntry cohortEntry = commitCoordinator.getCohortEntryIfCurrent(transactionID);
524 if(cohortEntry != null) {
525 LOG.debug("{}: Aborting transaction {}", persistenceId(), transactionID);
527 // We don't remove the cached cohort entry here (ie pass false) in case the Tx was
528 // aborted during replication in which case we may still commit locally if replication
530 commitCoordinator.currentTransactionComplete(transactionID, false);
532 final ListenableFuture<Void> future = cohortEntry.getCohort().abort();
533 final ActorRef self = getSelf();
535 Futures.addCallback(future, new FutureCallback<Void>() {
537 public void onSuccess(final Void v) {
538 shardMBean.incrementAbortTransactionsCount();
541 sender.tell(AbortTransactionReply.INSTANCE.toSerializable(), self);
546 public void onFailure(final Throwable t) {
547 LOG.error("{}: An exception happened during abort", persistenceId(), t);
550 sender.tell(new akka.actor.Status.Failure(t), self);
557 private void handleCreateTransaction(final Object message) {
559 createTransaction(CreateTransaction.fromSerializable(message));
560 } else if (getLeader() != null) {
561 getLeader().forward(message, getContext());
563 getSender().tell(new akka.actor.Status.Failure(new NoShardLeaderException(String.format(
564 "Could not find leader for shard %s so transaction cannot be created. This typically happens" +
565 " when the system is coming up or recovering and a leader is being elected. Try again" +
566 " later.", persistenceId()))), getSelf());
570 private void closeTransactionChain(final CloseTransactionChain closeTransactionChain) {
571 transactionFactory.closeTransactionChain(closeTransactionChain.getTransactionChainId());
574 private ActorRef createTypedTransactionActor(int transactionType,
575 ShardTransactionIdentifier transactionId, String transactionChainId,
576 short clientVersion ) {
578 DOMStoreTransaction transaction = transactionFactory.newTransaction(
579 TransactionProxy.TransactionType.fromInt(transactionType), transactionId.toString(),
582 return createShardTransaction(transaction, transactionId, clientVersion);
585 private ActorRef createShardTransaction(DOMStoreTransaction transaction, ShardTransactionIdentifier transactionId,
586 short clientVersion){
587 return getContext().actorOf(
588 ShardTransaction.props(transaction, getSelf(),
589 schemaContext, datastoreContext, shardMBean,
590 transactionId.getRemoteTransactionId(), clientVersion)
591 .withDispatcher(txnDispatcherPath),
592 transactionId.toString());
596 private void createTransaction(CreateTransaction createTransaction) {
598 ActorRef transactionActor = createTransaction(createTransaction.getTransactionType(),
599 createTransaction.getTransactionId(), createTransaction.getTransactionChainId(),
600 createTransaction.getVersion());
602 getSender().tell(new CreateTransactionReply(Serialization.serializedActorPath(transactionActor),
603 createTransaction.getTransactionId()).toSerializable(), getSelf());
604 } catch (Exception e) {
605 getSender().tell(new akka.actor.Status.Failure(e), getSelf());
609 private ActorRef createTransaction(int transactionType, String remoteTransactionId,
610 String transactionChainId, short clientVersion) {
613 ShardTransactionIdentifier transactionId = new ShardTransactionIdentifier(remoteTransactionId);
615 if(LOG.isDebugEnabled()) {
616 LOG.debug("{}: Creating transaction : {} ", persistenceId(), transactionId);
619 ActorRef transactionActor = createTypedTransactionActor(transactionType, transactionId,
620 transactionChainId, clientVersion);
622 return transactionActor;
625 private void syncCommitTransaction(final DOMStoreWriteTransaction transaction)
626 throws ExecutionException, InterruptedException {
627 DOMStoreThreePhaseCommitCohort commitCohort = transaction.ready();
628 commitCohort.preCommit().get();
629 commitCohort.commit().get();
632 private void commitWithNewTransaction(final Modification modification) {
633 DOMStoreWriteTransaction tx = store.newWriteOnlyTransaction();
634 modification.apply(tx);
636 syncCommitTransaction(tx);
637 shardMBean.incrementCommittedTransactionCount();
638 shardMBean.setLastCommittedTransactionTime(System.currentTimeMillis());
639 } catch (InterruptedException | ExecutionException e) {
640 shardMBean.incrementFailedTransactionsCount();
641 LOG.error("{}: Failed to commit", persistenceId(), e);
645 private void updateSchemaContext(final UpdateSchemaContext message) {
646 this.schemaContext = message.getSchemaContext();
647 updateSchemaContext(message.getSchemaContext());
648 store.onGlobalContextUpdated(message.getSchemaContext());
652 void updateSchemaContext(final SchemaContext schemaContext) {
653 store.onGlobalContextUpdated(schemaContext);
656 private void registerChangeListener(final RegisterChangeListener registerChangeListener) {
658 LOG.debug("{}: registerDataChangeListener for {}", persistenceId(), registerChangeListener.getPath());
660 ListenerRegistration<AsyncDataChangeListener<YangInstanceIdentifier,
661 NormalizedNode<?, ?>>> registration;
663 registration = doChangeListenerRegistration(registerChangeListener);
665 LOG.debug("{}: Shard is not the leader - delaying registration", persistenceId());
667 DelayedListenerRegistration delayedReg =
668 new DelayedListenerRegistration(registerChangeListener);
669 delayedListenerRegistrations.add(delayedReg);
670 registration = delayedReg;
673 ActorRef listenerRegistration = getContext().actorOf(
674 DataChangeListenerRegistration.props(registration));
676 LOG.debug("{}: registerDataChangeListener sending reply, listenerRegistrationPath = {} ",
677 persistenceId(), listenerRegistration.path());
679 getSender().tell(new RegisterChangeListenerReply(listenerRegistration), getSelf());
682 private ListenerRegistration<AsyncDataChangeListener<YangInstanceIdentifier,
683 NormalizedNode<?, ?>>> doChangeListenerRegistration(
684 final RegisterChangeListener registerChangeListener) {
686 ActorSelection dataChangeListenerPath = getContext().system().actorSelection(
687 registerChangeListener.getDataChangeListenerPath());
689 // Notify the listener if notifications should be enabled or not
690 // If this shard is the leader then it will enable notifications else
692 dataChangeListenerPath.tell(new EnableNotification(true), getSelf());
694 // Now store a reference to the data change listener so it can be notified
695 // at a later point if notifications should be enabled or disabled
696 dataChangeListeners.add(dataChangeListenerPath);
698 AsyncDataChangeListener<YangInstanceIdentifier, NormalizedNode<?, ?>> listener =
699 new DataChangeListenerProxy(dataChangeListenerPath);
701 LOG.debug("{}: Registering for path {}", persistenceId(), registerChangeListener.getPath());
703 return store.registerChangeListener(registerChangeListener.getPath(), listener,
704 registerChangeListener.getScope());
707 private boolean isMetricsCaptureEnabled(){
708 CommonConfig config = new CommonConfig(getContext().system().settings().config());
709 return config.isMetricCaptureEnabled();
714 void startLogRecoveryBatch(final int maxBatchSize) {
715 recoveryCoordinator.startLogRecoveryBatch(maxBatchSize);
719 protected void appendRecoveredLogEntry(final Payload data) {
720 recoveryCoordinator.appendRecoveredLogPayload(data);
724 protected void applyRecoverySnapshot(final byte[] snapshotBytes) {
725 recoveryCoordinator.applyRecoveredSnapshot(snapshotBytes);
729 protected void applyCurrentLogRecoveryBatch() {
730 recoveryCoordinator.applyCurrentLogRecoveryBatch();
734 protected void onRecoveryComplete() {
735 recoveryCoordinator = null;
737 //notify shard manager
738 getContext().parent().tell(new ActorInitialized(), getSelf());
740 // Being paranoid here - this method should only be called once but just in case...
741 if(txCommitTimeoutCheckSchedule == null) {
742 // Schedule a message to be periodically sent to check if the current in-progress
743 // transaction should be expired and aborted.
744 FiniteDuration period = Duration.create(transactionCommitTimeout / 3, TimeUnit.MILLISECONDS);
745 txCommitTimeoutCheckSchedule = getContext().system().scheduler().schedule(
746 period, period, getSelf(),
747 TX_COMMIT_TIMEOUT_CHECK_MESSAGE, getContext().dispatcher(), ActorRef.noSender());
752 protected void applyState(final ActorRef clientActor, final String identifier, final Object data) {
754 if(data instanceof ModificationPayload) {
756 applyModificationToState(clientActor, identifier, ((ModificationPayload) data).getModification());
757 } catch (ClassNotFoundException | IOException e) {
758 LOG.error("{}: Error extracting ModificationPayload", persistenceId(), e);
761 else if (data instanceof CompositeModificationPayload) {
762 Object modification = ((CompositeModificationPayload) data).getModification();
764 applyModificationToState(clientActor, identifier, modification);
765 } else if(data instanceof CompositeModificationByteStringPayload ){
766 Object modification = ((CompositeModificationByteStringPayload) data).getModification();
768 applyModificationToState(clientActor, identifier, modification);
770 LOG.error("{}: Unknown state received {} Class loader = {} CompositeNodeMod.ClassLoader = {}",
771 persistenceId(), data, data.getClass().getClassLoader(),
772 CompositeModificationPayload.class.getClassLoader());
776 private void applyModificationToState(ActorRef clientActor, String identifier, Object modification) {
777 if(modification == null) {
779 "{}: modification is null - this is very unexpected, clientActor = {}, identifier = {}",
780 persistenceId(), identifier, clientActor != null ? clientActor.path().toString() : null);
781 } else if(clientActor == null) {
782 // There's no clientActor to which to send a commit reply so we must be applying
783 // replicated state from the leader.
784 commitWithNewTransaction(MutableCompositeModification.fromSerializable(modification));
786 // This must be the OK to commit after replication consensus.
787 finishCommit(clientActor, identifier);
792 protected void createSnapshot() {
793 // Create a transaction actor. We are really going to treat the transaction as a worker
794 // so that this actor does not get block building the snapshot. THe transaction actor will
795 // after processing the CreateSnapshot message.
797 ActorRef createSnapshotTransaction = createTransaction(
798 TransactionProxy.TransactionType.READ_ONLY.ordinal(),
799 "createSnapshot" + ++createSnapshotTransactionCounter, "",
800 DataStoreVersions.CURRENT_VERSION);
802 createSnapshotTransaction.tell(CreateSnapshot.INSTANCE, self());
807 protected void applySnapshot(final byte[] snapshotBytes) {
808 // Since this will be done only on Recovery or when this actor is a Follower
809 // we can safely commit everything in here. We not need to worry about event notifications
810 // as they would have already been disabled on the follower
812 LOG.info("{}: Applying snapshot", persistenceId());
814 DOMStoreWriteTransaction transaction = store.newWriteOnlyTransaction();
816 NormalizedNode<?, ?> node = SerializationUtils.deserializeNormalizedNode(snapshotBytes);
818 // delete everything first
819 transaction.delete(DATASTORE_ROOT);
821 // Add everything from the remote node back
822 transaction.write(DATASTORE_ROOT, node);
823 syncCommitTransaction(transaction);
824 } catch (InterruptedException | ExecutionException e) {
825 LOG.error("{}: An exception occurred when applying snapshot", persistenceId(), e);
827 LOG.info("{}: Done applying snapshot", persistenceId());
832 protected void onStateChanged() {
833 boolean isLeader = isLeader();
834 treeChangeSupport.onLeadershipChange(isLeader);
836 for (ActorSelection dataChangeListener : dataChangeListeners) {
837 dataChangeListener.tell(new EnableNotification(isLeader), getSelf());
841 for(DelayedListenerRegistration reg: delayedListenerRegistrations) {
842 if(!reg.isClosed()) {
843 reg.setDelegate(doChangeListenerRegistration(reg.getRegisterChangeListener()));
847 delayedListenerRegistrations.clear();
850 // If this actor is no longer the leader close all the transaction chains
852 if(LOG.isDebugEnabled()) {
854 "{}: onStateChanged: Closing all transaction chains because shard {} is no longer the leader",
855 persistenceId(), getId());
858 transactionFactory.closeAllTransactionChains();
863 public String persistenceId() {
868 ShardCommitCoordinator getCommitCoordinator() {
869 return commitCoordinator;
873 private static class ShardCreator implements Creator<Shard> {
875 private static final long serialVersionUID = 1L;
877 final ShardIdentifier name;
878 final Map<String, String> peerAddresses;
879 final DatastoreContext datastoreContext;
880 final SchemaContext schemaContext;
882 ShardCreator(final ShardIdentifier name, final Map<String, String> peerAddresses,
883 final DatastoreContext datastoreContext, final SchemaContext schemaContext) {
885 this.peerAddresses = peerAddresses;
886 this.datastoreContext = datastoreContext;
887 this.schemaContext = schemaContext;
891 public Shard create() throws Exception {
892 return new Shard(name, peerAddresses, datastoreContext, schemaContext);
897 public InMemoryDOMDataStore getDataStore() {
902 ShardStats getShardMBean() {
906 private static class DelayedListenerRegistration implements
907 ListenerRegistration<AsyncDataChangeListener<YangInstanceIdentifier, NormalizedNode<?, ?>>> {
909 private volatile boolean closed;
911 private final RegisterChangeListener registerChangeListener;
913 private volatile ListenerRegistration<AsyncDataChangeListener<YangInstanceIdentifier,
914 NormalizedNode<?, ?>>> delegate;
916 DelayedListenerRegistration(final RegisterChangeListener registerChangeListener) {
917 this.registerChangeListener = registerChangeListener;
920 void setDelegate( final ListenerRegistration<AsyncDataChangeListener<YangInstanceIdentifier,
921 NormalizedNode<?, ?>>> registration) {
922 this.delegate = registration;
929 RegisterChangeListener getRegisterChangeListener() {
930 return registerChangeListener;
934 public AsyncDataChangeListener<YangInstanceIdentifier, NormalizedNode<?, ?>> getInstance() {
935 return delegate != null ? delegate.getInstance() : null;
939 public void close() {
941 if(delegate != null) {