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.Collection;
27 import java.util.HashMap;
28 import java.util.List;
30 import java.util.concurrent.ExecutionException;
31 import java.util.concurrent.TimeUnit;
32 import javax.annotation.Nonnull;
33 import org.opendaylight.controller.cluster.DataPersistenceProvider;
34 import org.opendaylight.controller.cluster.common.actor.CommonConfig;
35 import org.opendaylight.controller.cluster.common.actor.MeteringBehavior;
36 import org.opendaylight.controller.cluster.datastore.ShardCommitCoordinator.CohortEntry;
37 import org.opendaylight.controller.cluster.datastore.compat.BackwardsCompatibleThreePhaseCommitCohort;
38 import org.opendaylight.controller.cluster.datastore.exceptions.NoShardLeaderException;
39 import org.opendaylight.controller.cluster.datastore.identifiers.ShardIdentifier;
40 import org.opendaylight.controller.cluster.datastore.identifiers.ShardTransactionIdentifier;
41 import org.opendaylight.controller.cluster.datastore.jmx.mbeans.shard.ShardMBeanFactory;
42 import org.opendaylight.controller.cluster.datastore.jmx.mbeans.shard.ShardStats;
43 import org.opendaylight.controller.cluster.datastore.messages.AbortTransaction;
44 import org.opendaylight.controller.cluster.datastore.messages.AbortTransactionReply;
45 import org.opendaylight.controller.cluster.datastore.messages.ActorInitialized;
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.ReplicatedLogEntry;
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.DOMStoreTransactionChain;
81 import org.opendaylight.controller.sal.core.spi.data.DOMStoreTransactionFactory;
82 import org.opendaylight.controller.sal.core.spi.data.DOMStoreWriteTransaction;
83 import org.opendaylight.yangtools.concepts.ListenerRegistration;
84 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
85 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
86 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
87 import scala.concurrent.duration.Duration;
88 import scala.concurrent.duration.FiniteDuration;
91 * A Shard represents a portion of the logical data tree <br/>
93 * Our Shard uses InMemoryDataStore as it's internal representation and delegates all requests it
96 public class Shard extends RaftActor {
98 private static final YangInstanceIdentifier DATASTORE_ROOT = YangInstanceIdentifier.builder().build();
100 private static final Object TX_COMMIT_TIMEOUT_CHECK_MESSAGE = "txCommitTimeoutCheck";
103 static final String DEFAULT_NAME = "default";
105 // The state of this Shard
106 private final InMemoryDOMDataStore store;
108 /// The name of this shard
109 private final ShardIdentifier name;
111 private final ShardStats shardMBean;
113 private final List<ActorSelection> dataChangeListeners = Lists.newArrayList();
115 private final List<DelayedListenerRegistration> delayedListenerRegistrations =
116 Lists.newArrayList();
118 private DatastoreContext datastoreContext;
120 private DataPersistenceProvider dataPersistenceProvider;
122 private SchemaContext schemaContext;
124 private int createSnapshotTransactionCounter;
126 private final ShardCommitCoordinator commitCoordinator;
128 private long transactionCommitTimeout;
130 private Cancellable txCommitTimeoutCheckSchedule;
132 private final Optional<ActorRef> roleChangeNotifier;
134 private final MessageTracker appendEntriesReplyTracker;
136 private final ReadyTransactionReply READY_TRANSACTION_REPLY = new ReadyTransactionReply(
137 Serialization.serializedActorPath(getSelf()));
141 * Coordinates persistence recovery on startup.
143 private ShardRecoveryCoordinator recoveryCoordinator;
144 private List<Object> currentLogRecoveryBatch;
146 private final Map<String, DOMStoreTransactionChain> transactionChains = new HashMap<>();
148 private final String txnDispatcherPath;
150 protected Shard(final ShardIdentifier name, final Map<ShardIdentifier, String> peerAddresses,
151 final DatastoreContext datastoreContext, final SchemaContext schemaContext) {
152 super(name.toString(), mapPeerAddresses(peerAddresses),
153 Optional.of(datastoreContext.getShardRaftConfig()));
156 this.datastoreContext = datastoreContext;
157 this.schemaContext = schemaContext;
158 this.dataPersistenceProvider = (datastoreContext.isPersistent())
159 ? new PersistentDataProvider() : new NonPersistentRaftDataProvider();
160 this.txnDispatcherPath = new Dispatchers(context().system().dispatchers())
161 .getDispatcherPath(Dispatchers.DispatcherType.Transaction);
164 LOG.info("Shard created : {}, persistent : {}", name, datastoreContext.isPersistent());
166 store = InMemoryDOMDataStoreFactory.create(name.toString(), null,
167 datastoreContext.getDataStoreProperties());
169 if(schemaContext != null) {
170 store.onGlobalContextUpdated(schemaContext);
173 shardMBean = ShardMBeanFactory.getShardStatsMBean(name.toString(),
174 datastoreContext.getDataStoreMXBeanType());
175 shardMBean.setNotificationManager(store.getDataChangeListenerNotificationManager());
177 if (isMetricsCaptureEnabled()) {
178 getContext().become(new MeteringBehavior(this));
181 commitCoordinator = new ShardCommitCoordinator(TimeUnit.SECONDS.convert(1, TimeUnit.MINUTES),
182 datastoreContext.getShardTransactionCommitQueueCapacity(), LOG, name.toString());
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());
193 private void setTransactionCommitTimeout() {
194 transactionCommitTimeout = TimeUnit.MILLISECONDS.convert(
195 datastoreContext.getShardTransactionCommitTimeoutInSeconds(), TimeUnit.SECONDS);
198 private static Map<String, String> mapPeerAddresses(
199 final Map<ShardIdentifier, String> peerAddresses) {
200 Map<String, String> map = new HashMap<>();
202 for (Map.Entry<ShardIdentifier, String> entry : peerAddresses
204 map.put(entry.getKey().toString(), entry.getValue());
210 public static Props props(final ShardIdentifier name,
211 final Map<ShardIdentifier, String> peerAddresses,
212 final DatastoreContext datastoreContext, final SchemaContext schemaContext) {
213 Preconditions.checkNotNull(name, "name should not be null");
214 Preconditions.checkNotNull(peerAddresses, "peerAddresses should not be null");
215 Preconditions.checkNotNull(datastoreContext, "dataStoreContext should not be null");
216 Preconditions.checkNotNull(schemaContext, "schemaContext should not be null");
218 return Props.create(new ShardCreator(name, peerAddresses, datastoreContext, schemaContext));
221 private Optional<ActorRef> createRoleChangeNotifier(String shardId) {
222 ActorRef shardRoleChangeNotifier = this.getContext().actorOf(
223 RoleChangeNotifier.getProps(shardId), shardId + "-notifier");
224 return Optional.of(shardRoleChangeNotifier);
228 public void postStop() {
229 LOG.info("Stopping Shard {}", persistenceId());
233 if(txCommitTimeoutCheckSchedule != null) {
234 txCommitTimeoutCheckSchedule.cancel();
237 shardMBean.unregisterMBean();
241 public void onReceiveRecover(final Object message) throws Exception {
242 if(LOG.isDebugEnabled()) {
243 LOG.debug("{}: onReceiveRecover: Received message {} from {}", persistenceId(),
244 message.getClass().toString(), getSender());
247 if (message instanceof RecoveryFailure){
248 LOG.error("{}: Recovery failed because of this cause",
249 persistenceId(), ((RecoveryFailure) message).cause());
251 // Even though recovery failed, we still need to finish our recovery, eg send the
252 // ActorInitialized message and start the txCommitTimeoutCheckSchedule.
253 onRecoveryComplete();
255 super.onReceiveRecover(message);
256 if(LOG.isTraceEnabled()) {
257 appendEntriesReplyTracker.begin();
263 public void onReceiveCommand(final Object message) throws Exception {
265 MessageTracker.Context context = appendEntriesReplyTracker.received(message);
267 if(context.error().isPresent()){
268 LOG.trace("{} : AppendEntriesReply failed to arrive at the expected interval {}", persistenceId(),
273 if (CreateTransaction.SERIALIZABLE_CLASS.isInstance(message)) {
274 handleCreateTransaction(message);
275 } else if (message instanceof ForwardedReadyTransaction) {
276 handleForwardedReadyTransaction((ForwardedReadyTransaction) message);
277 } else if (CanCommitTransaction.SERIALIZABLE_CLASS.isInstance(message)) {
278 handleCanCommitTransaction(CanCommitTransaction.fromSerializable(message));
279 } else if (CommitTransaction.SERIALIZABLE_CLASS.isInstance(message)) {
280 handleCommitTransaction(CommitTransaction.fromSerializable(message));
281 } else if (AbortTransaction.SERIALIZABLE_CLASS.isInstance(message)) {
282 handleAbortTransaction(AbortTransaction.fromSerializable(message));
283 } else if (CloseTransactionChain.SERIALIZABLE_CLASS.isInstance(message)) {
284 closeTransactionChain(CloseTransactionChain.fromSerializable(message));
285 } else if (message instanceof RegisterChangeListener) {
286 registerChangeListener((RegisterChangeListener) message);
287 } else if (message instanceof UpdateSchemaContext) {
288 updateSchemaContext((UpdateSchemaContext) message);
289 } else if (message instanceof PeerAddressResolved) {
290 PeerAddressResolved resolved = (PeerAddressResolved) message;
291 setPeerAddress(resolved.getPeerId().toString(),
292 resolved.getPeerAddress());
293 } else if (message.equals(TX_COMMIT_TIMEOUT_CHECK_MESSAGE)) {
294 handleTransactionCommitTimeoutCheck();
295 } else if(message instanceof DatastoreContext) {
296 onDatastoreContext((DatastoreContext)message);
297 } else if(message instanceof RegisterRoleChangeListener){
298 roleChangeNotifier.get().forward(message, context());
299 } else if (message instanceof FollowerInitialSyncUpStatus){
300 shardMBean.setFollowerInitialSyncStatus(((FollowerInitialSyncUpStatus) message).isInitialSyncDone());
301 context().parent().tell(message, self());
303 super.onReceiveCommand(message);
311 protected Optional<ActorRef> getRoleChangeNotifier() {
312 return roleChangeNotifier;
315 private void onDatastoreContext(DatastoreContext context) {
316 datastoreContext = context;
318 commitCoordinator.setQueueCapacity(datastoreContext.getShardTransactionCommitQueueCapacity());
320 setTransactionCommitTimeout();
322 if(datastoreContext.isPersistent() &&
323 dataPersistenceProvider instanceof NonPersistentRaftDataProvider) {
324 dataPersistenceProvider = new PersistentDataProvider();
325 } else if(!datastoreContext.isPersistent() &&
326 dataPersistenceProvider instanceof PersistentDataProvider) {
327 dataPersistenceProvider = new NonPersistentRaftDataProvider();
330 updateConfigParams(datastoreContext.getShardRaftConfig());
333 private void handleTransactionCommitTimeoutCheck() {
334 CohortEntry cohortEntry = commitCoordinator.getCurrentCohortEntry();
335 if(cohortEntry != null) {
336 long elapsed = System.currentTimeMillis() - cohortEntry.getLastAccessTime();
337 if(elapsed > transactionCommitTimeout) {
338 LOG.warn("{}: Current transaction {} has timed out after {} ms - aborting",
339 persistenceId(), cohortEntry.getTransactionID(), transactionCommitTimeout);
341 doAbortTransaction(cohortEntry.getTransactionID(), null);
346 private void handleCommitTransaction(final CommitTransaction commit) {
347 final String transactionID = commit.getTransactionID();
349 LOG.debug("{}: Committing transaction {}", persistenceId(), transactionID);
351 // Get the current in-progress cohort entry in the commitCoordinator if it corresponds to
353 final CohortEntry cohortEntry = commitCoordinator.getCohortEntryIfCurrent(transactionID);
354 if(cohortEntry == null) {
355 // We're not the current Tx - the Tx was likely expired b/c it took too long in
356 // between the canCommit and commit messages.
357 IllegalStateException ex = new IllegalStateException(
358 String.format("%s: Cannot commit transaction %s - it is not the current transaction",
359 persistenceId(), transactionID));
360 LOG.error(ex.getMessage());
361 shardMBean.incrementFailedTransactionsCount();
362 getSender().tell(new akka.actor.Status.Failure(ex), getSelf());
366 // We perform the preCommit phase here atomically with the commit phase. This is an
367 // optimization to eliminate the overhead of an extra preCommit message. We lose front-end
368 // coordination of preCommit across shards in case of failure but preCommit should not
369 // normally fail since we ensure only one concurrent 3-phase commit.
372 // We block on the future here so we don't have to worry about possibly accessing our
373 // state on a different thread outside of our dispatcher. Also, the data store
374 // currently uses a same thread executor anyway.
375 cohortEntry.getCohort().preCommit().get();
377 // If we do not have any followers and we are not using persistence we can
378 // apply modification to the state immediately
379 if(!hasFollowers() && !persistence().isRecoveryApplicable()){
380 applyModificationToState(getSender(), transactionID, cohortEntry.getModification());
382 Shard.this.persistData(getSender(), transactionID,
383 new ModificationPayload(cohortEntry.getModification()));
385 } catch (Exception e) {
386 LOG.error("{} An exception occurred while preCommitting transaction {}",
387 persistenceId(), cohortEntry.getTransactionID(), e);
388 shardMBean.incrementFailedTransactionsCount();
389 getSender().tell(new akka.actor.Status.Failure(e), getSelf());
392 cohortEntry.updateLastAccessTime();
395 private void finishCommit(@Nonnull final ActorRef sender, final @Nonnull String transactionID) {
396 // With persistence enabled, this method is called via applyState by the leader strategy
397 // after the commit has been replicated to a majority of the followers.
399 CohortEntry cohortEntry = commitCoordinator.getCohortEntryIfCurrent(transactionID);
400 if(cohortEntry == null) {
401 // The transaction is no longer the current commit. This can happen if the transaction
402 // was aborted prior, most likely due to timeout in the front-end. We need to finish
403 // committing the transaction though since it was successfully persisted and replicated
404 // however we can't use the original cohort b/c it was already preCommitted and may
405 // conflict with the current commit or may have been aborted so we commit with a new
407 cohortEntry = commitCoordinator.getAndRemoveCohortEntry(transactionID);
408 if(cohortEntry != null) {
409 commitWithNewTransaction(cohortEntry.getModification());
410 sender.tell(CommitTransactionReply.INSTANCE.toSerializable(), getSelf());
412 // This really shouldn't happen - it likely means that persistence or replication
413 // took so long to complete such that the cohort entry was expired from the cache.
414 IllegalStateException ex = new IllegalStateException(
415 String.format("%s: Could not finish committing transaction %s - no CohortEntry found",
416 persistenceId(), transactionID));
417 LOG.error(ex.getMessage());
418 sender.tell(new akka.actor.Status.Failure(ex), getSelf());
424 LOG.debug("{}: Finishing commit for transaction {}", persistenceId(), cohortEntry.getTransactionID());
427 // We block on the future here so we don't have to worry about possibly accessing our
428 // state on a different thread outside of our dispatcher. Also, the data store
429 // currently uses a same thread executor anyway.
430 cohortEntry.getCohort().commit().get();
432 sender.tell(CommitTransactionReply.INSTANCE.toSerializable(), getSelf());
434 shardMBean.incrementCommittedTransactionCount();
435 shardMBean.setLastCommittedTransactionTime(System.currentTimeMillis());
437 } catch (Exception e) {
438 sender.tell(new akka.actor.Status.Failure(e), getSelf());
440 LOG.error("{}, An exception occurred while committing transaction {}", persistenceId(),
442 shardMBean.incrementFailedTransactionsCount();
444 commitCoordinator.currentTransactionComplete(transactionID, true);
448 private void handleCanCommitTransaction(final CanCommitTransaction canCommit) {
449 LOG.debug("{}: Can committing transaction {}", persistenceId(), canCommit.getTransactionID());
450 commitCoordinator.handleCanCommit(canCommit, getSender(), self());
453 private void handleForwardedReadyTransaction(ForwardedReadyTransaction ready) {
454 LOG.debug("{}: Readying transaction {}, client version {}", persistenceId(),
455 ready.getTransactionID(), ready.getTxnClientVersion());
457 // This message is forwarded by the ShardTransaction on ready. We cache the cohort in the
458 // commitCoordinator in preparation for the subsequent three phase commit initiated by
460 commitCoordinator.transactionReady(ready.getTransactionID(), ready.getCohort(),
461 ready.getModification());
463 // Return our actor path as we'll handle the three phase commit, except if the Tx client
464 // version < 1 (Helium-1 version). This means the Tx was initiated by a base Helium version
465 // node. In that case, the subsequent 3-phase commit messages won't contain the
466 // transactionId so to maintain backwards compatibility, we create a separate cohort actor
467 // to provide the compatible behavior.
468 if(ready.getTxnClientVersion() < DataStoreVersions.HELIUM_1_VERSION) {
469 LOG.debug("{}: Creating BackwardsCompatibleThreePhaseCommitCohort", persistenceId());
470 ActorRef replyActorPath = getContext().actorOf(BackwardsCompatibleThreePhaseCommitCohort.props(
471 ready.getTransactionID()));
473 ReadyTransactionReply readyTransactionReply =
474 new ReadyTransactionReply(Serialization.serializedActorPath(replyActorPath));
475 getSender().tell(ready.isReturnSerialized() ? readyTransactionReply.toSerializable() :
476 readyTransactionReply, getSelf());
480 getSender().tell(ready.isReturnSerialized() ? READY_TRANSACTION_REPLY.toSerializable() :
481 READY_TRANSACTION_REPLY, getSelf());
485 private void handleAbortTransaction(final AbortTransaction abort) {
486 doAbortTransaction(abort.getTransactionID(), getSender());
489 void doAbortTransaction(final String transactionID, final ActorRef sender) {
490 final CohortEntry cohortEntry = commitCoordinator.getCohortEntryIfCurrent(transactionID);
491 if(cohortEntry != null) {
492 LOG.debug("{}: Aborting transaction {}", persistenceId(), transactionID);
494 // We don't remove the cached cohort entry here (ie pass false) in case the Tx was
495 // aborted during replication in which case we may still commit locally if replication
497 commitCoordinator.currentTransactionComplete(transactionID, false);
499 final ListenableFuture<Void> future = cohortEntry.getCohort().abort();
500 final ActorRef self = getSelf();
502 Futures.addCallback(future, new FutureCallback<Void>() {
504 public void onSuccess(final Void v) {
505 shardMBean.incrementAbortTransactionsCount();
508 sender.tell(AbortTransactionReply.INSTANCE.toSerializable(), self);
513 public void onFailure(final Throwable t) {
514 LOG.error("{}: An exception happened during abort", persistenceId(), t);
517 sender.tell(new akka.actor.Status.Failure(t), self);
524 private void handleCreateTransaction(final Object message) {
526 createTransaction(CreateTransaction.fromSerializable(message));
527 } else if (getLeader() != null) {
528 getLeader().forward(message, getContext());
530 getSender().tell(new akka.actor.Status.Failure(new NoShardLeaderException(String.format(
531 "Could not find leader for shard %s so transaction cannot be created. This typically happens" +
532 " when the system is coming up or recovering and a leader is being elected. Try again" +
533 " later.", persistenceId()))), getSelf());
537 private void closeTransactionChain(final CloseTransactionChain closeTransactionChain) {
538 DOMStoreTransactionChain chain =
539 transactionChains.remove(closeTransactionChain.getTransactionChainId());
546 private ActorRef createTypedTransactionActor(int transactionType,
547 ShardTransactionIdentifier transactionId, String transactionChainId,
548 short clientVersion ) {
550 DOMStoreTransactionFactory factory = store;
552 if(!transactionChainId.isEmpty()) {
553 factory = transactionChains.get(transactionChainId);
555 DOMStoreTransactionChain transactionChain = store.createTransactionChain();
556 transactionChains.put(transactionChainId, transactionChain);
557 factory = transactionChain;
561 if(this.schemaContext == null) {
562 throw new IllegalStateException("SchemaContext is not set");
565 if (transactionType == TransactionProxy.TransactionType.WRITE_ONLY.ordinal()) {
567 shardMBean.incrementWriteOnlyTransactionCount();
569 return createShardTransaction(factory.newWriteOnlyTransaction(), transactionId, clientVersion);
571 } else if (transactionType == TransactionProxy.TransactionType.READ_WRITE.ordinal()) {
573 shardMBean.incrementReadWriteTransactionCount();
575 return createShardTransaction(factory.newReadWriteTransaction(), transactionId, clientVersion);
577 } else if (transactionType == TransactionProxy.TransactionType.READ_ONLY.ordinal()) {
579 shardMBean.incrementReadOnlyTransactionCount();
581 return createShardTransaction(factory.newReadOnlyTransaction(), transactionId, clientVersion);
584 throw new IllegalArgumentException(
585 "Shard="+name + ":CreateTransaction message has unidentified transaction type="
590 private ActorRef createShardTransaction(DOMStoreTransaction transaction, ShardTransactionIdentifier transactionId,
591 short clientVersion){
592 return getContext().actorOf(
593 ShardTransaction.props(transaction, getSelf(),
594 schemaContext, datastoreContext, shardMBean,
595 transactionId.getRemoteTransactionId(), clientVersion)
596 .withDispatcher(txnDispatcherPath),
597 transactionId.toString());
601 private void createTransaction(CreateTransaction createTransaction) {
603 ActorRef transactionActor = createTransaction(createTransaction.getTransactionType(),
604 createTransaction.getTransactionId(), createTransaction.getTransactionChainId(),
605 createTransaction.getVersion());
607 getSender().tell(new CreateTransactionReply(Serialization.serializedActorPath(transactionActor),
608 createTransaction.getTransactionId()).toSerializable(), getSelf());
609 } catch (Exception e) {
610 getSender().tell(new akka.actor.Status.Failure(e), getSelf());
614 private ActorRef createTransaction(int transactionType, String remoteTransactionId,
615 String transactionChainId, short clientVersion) {
618 ShardTransactionIdentifier transactionId = new ShardTransactionIdentifier(remoteTransactionId);
620 if(LOG.isDebugEnabled()) {
621 LOG.debug("{}: Creating transaction : {} ", persistenceId(), transactionId);
624 ActorRef transactionActor = createTypedTransactionActor(transactionType, transactionId,
625 transactionChainId, clientVersion);
627 return transactionActor;
630 private void syncCommitTransaction(final DOMStoreWriteTransaction transaction)
631 throws ExecutionException, InterruptedException {
632 DOMStoreThreePhaseCommitCohort commitCohort = transaction.ready();
633 commitCohort.preCommit().get();
634 commitCohort.commit().get();
637 private void commitWithNewTransaction(final Modification modification) {
638 DOMStoreWriteTransaction tx = store.newWriteOnlyTransaction();
639 modification.apply(tx);
641 syncCommitTransaction(tx);
642 shardMBean.incrementCommittedTransactionCount();
643 shardMBean.setLastCommittedTransactionTime(System.currentTimeMillis());
644 } catch (InterruptedException | ExecutionException e) {
645 shardMBean.incrementFailedTransactionsCount();
646 LOG.error("{}: Failed to commit", persistenceId(), e);
650 private void updateSchemaContext(final UpdateSchemaContext message) {
651 this.schemaContext = message.getSchemaContext();
652 updateSchemaContext(message.getSchemaContext());
653 store.onGlobalContextUpdated(message.getSchemaContext());
657 void updateSchemaContext(final SchemaContext schemaContext) {
658 store.onGlobalContextUpdated(schemaContext);
661 private void registerChangeListener(final RegisterChangeListener registerChangeListener) {
663 LOG.debug("{}: registerDataChangeListener for {}", persistenceId(), registerChangeListener.getPath());
665 ListenerRegistration<AsyncDataChangeListener<YangInstanceIdentifier,
666 NormalizedNode<?, ?>>> registration;
668 registration = doChangeListenerRegistration(registerChangeListener);
670 LOG.debug("{}: Shard is not the leader - delaying registration", persistenceId());
672 DelayedListenerRegistration delayedReg =
673 new DelayedListenerRegistration(registerChangeListener);
674 delayedListenerRegistrations.add(delayedReg);
675 registration = delayedReg;
678 ActorRef listenerRegistration = getContext().actorOf(
679 DataChangeListenerRegistration.props(registration));
681 LOG.debug("{}: registerDataChangeListener sending reply, listenerRegistrationPath = {} ",
682 persistenceId(), listenerRegistration.path());
684 getSender().tell(new RegisterChangeListenerReply(listenerRegistration.path()), getSelf());
687 private ListenerRegistration<AsyncDataChangeListener<YangInstanceIdentifier,
688 NormalizedNode<?, ?>>> doChangeListenerRegistration(
689 final RegisterChangeListener registerChangeListener) {
691 ActorSelection dataChangeListenerPath = getContext().system().actorSelection(
692 registerChangeListener.getDataChangeListenerPath());
694 // Notify the listener if notifications should be enabled or not
695 // If this shard is the leader then it will enable notifications else
697 dataChangeListenerPath.tell(new EnableNotification(true), getSelf());
699 // Now store a reference to the data change listener so it can be notified
700 // at a later point if notifications should be enabled or disabled
701 dataChangeListeners.add(dataChangeListenerPath);
703 AsyncDataChangeListener<YangInstanceIdentifier, NormalizedNode<?, ?>> listener =
704 new DataChangeListenerProxy(dataChangeListenerPath);
706 LOG.debug("{}: Registering for path {}", persistenceId(), registerChangeListener.getPath());
708 return store.registerChangeListener(registerChangeListener.getPath(), listener,
709 registerChangeListener.getScope());
712 private boolean isMetricsCaptureEnabled(){
713 CommonConfig config = new CommonConfig(getContext().system().settings().config());
714 return config.isMetricCaptureEnabled();
719 void startLogRecoveryBatch(final int maxBatchSize) {
720 currentLogRecoveryBatch = Lists.newArrayListWithCapacity(maxBatchSize);
722 if(LOG.isDebugEnabled()) {
723 LOG.debug("{}: starting log recovery batch with max size {}", persistenceId(), maxBatchSize);
728 protected void appendRecoveredLogEntry(final Payload data) {
729 if(data instanceof ModificationPayload) {
731 currentLogRecoveryBatch.add(((ModificationPayload) data).getModification());
732 } catch (ClassNotFoundException | IOException e) {
733 LOG.error("{}: Error extracting ModificationPayload", persistenceId(), e);
735 } else if (data instanceof CompositeModificationPayload) {
736 currentLogRecoveryBatch.add(((CompositeModificationPayload) data).getModification());
737 } else if (data instanceof CompositeModificationByteStringPayload) {
738 currentLogRecoveryBatch.add(((CompositeModificationByteStringPayload) data).getModification());
740 LOG.error("{}: Unknown state received {} during recovery", persistenceId(), data);
745 protected void applyRecoverySnapshot(final byte[] snapshotBytes) {
746 if(recoveryCoordinator == null) {
747 recoveryCoordinator = new ShardRecoveryCoordinator(persistenceId(), schemaContext,
748 LOG, name.toString());
751 recoveryCoordinator.submit(snapshotBytes, store.newWriteOnlyTransaction());
753 if(LOG.isDebugEnabled()) {
754 LOG.debug("{}: submitted recovery sbapshot", persistenceId());
759 protected void applyCurrentLogRecoveryBatch() {
760 if(recoveryCoordinator == null) {
761 recoveryCoordinator = new ShardRecoveryCoordinator(persistenceId(), schemaContext,
762 LOG, name.toString());
765 recoveryCoordinator.submit(currentLogRecoveryBatch, store.newWriteOnlyTransaction());
767 if(LOG.isDebugEnabled()) {
768 LOG.debug("{}: submitted log recovery batch with size {}", persistenceId(),
769 currentLogRecoveryBatch.size());
774 protected void onRecoveryComplete() {
775 if(recoveryCoordinator != null) {
776 Collection<DOMStoreWriteTransaction> txList = recoveryCoordinator.getTransactions();
778 if(LOG.isDebugEnabled()) {
779 LOG.debug("{}: recovery complete - committing {} Tx's", persistenceId(), txList.size());
782 for(DOMStoreWriteTransaction tx: txList) {
784 syncCommitTransaction(tx);
785 shardMBean.incrementCommittedTransactionCount();
786 } catch (InterruptedException | ExecutionException e) {
787 shardMBean.incrementFailedTransactionsCount();
788 LOG.error("{}: Failed to commit", persistenceId(), e);
793 recoveryCoordinator = null;
794 currentLogRecoveryBatch = null;
795 updateJournalStats();
797 //notify shard manager
798 getContext().parent().tell(new ActorInitialized(), getSelf());
800 // Being paranoid here - this method should only be called once but just in case...
801 if(txCommitTimeoutCheckSchedule == null) {
802 // Schedule a message to be periodically sent to check if the current in-progress
803 // transaction should be expired and aborted.
804 FiniteDuration period = Duration.create(transactionCommitTimeout / 3, TimeUnit.MILLISECONDS);
805 txCommitTimeoutCheckSchedule = getContext().system().scheduler().schedule(
806 period, period, getSelf(),
807 TX_COMMIT_TIMEOUT_CHECK_MESSAGE, getContext().dispatcher(), ActorRef.noSender());
812 protected void applyState(final ActorRef clientActor, final String identifier, final Object data) {
814 if(data instanceof ModificationPayload) {
816 applyModificationToState(clientActor, identifier, ((ModificationPayload) data).getModification());
817 } catch (ClassNotFoundException | IOException e) {
818 LOG.error("{}: Error extracting ModificationPayload", persistenceId(), e);
821 else if (data instanceof CompositeModificationPayload) {
822 Object modification = ((CompositeModificationPayload) data).getModification();
824 applyModificationToState(clientActor, identifier, modification);
825 } else if(data instanceof CompositeModificationByteStringPayload ){
826 Object modification = ((CompositeModificationByteStringPayload) data).getModification();
828 applyModificationToState(clientActor, identifier, modification);
830 LOG.error("{}: Unknown state received {} Class loader = {} CompositeNodeMod.ClassLoader = {}",
831 persistenceId(), data, data.getClass().getClassLoader(),
832 CompositeModificationPayload.class.getClassLoader());
835 updateJournalStats();
839 private void applyModificationToState(ActorRef clientActor, String identifier, Object modification) {
840 if(modification == null) {
842 "{}: modification is null - this is very unexpected, clientActor = {}, identifier = {}",
843 persistenceId(), identifier, clientActor != null ? clientActor.path().toString() : null);
844 } else if(clientActor == null) {
845 // There's no clientActor to which to send a commit reply so we must be applying
846 // replicated state from the leader.
847 commitWithNewTransaction(MutableCompositeModification.fromSerializable(modification));
849 // This must be the OK to commit after replication consensus.
850 finishCommit(clientActor, identifier);
854 private void updateJournalStats() {
855 ReplicatedLogEntry lastLogEntry = getLastLogEntry();
857 if (lastLogEntry != null) {
858 shardMBean.setLastLogIndex(lastLogEntry.getIndex());
859 shardMBean.setLastLogTerm(lastLogEntry.getTerm());
862 shardMBean.setCommitIndex(getCommitIndex());
863 shardMBean.setLastApplied(getLastApplied());
864 shardMBean.setInMemoryJournalDataSize(getRaftActorContext().getReplicatedLog().dataSize());
868 protected void createSnapshot() {
869 // Create a transaction actor. We are really going to treat the transaction as a worker
870 // so that this actor does not get block building the snapshot. THe transaction actor will
871 // after processing the CreateSnapshot message.
873 ActorRef createSnapshotTransaction = createTransaction(
874 TransactionProxy.TransactionType.READ_ONLY.ordinal(),
875 "createSnapshot" + ++createSnapshotTransactionCounter, "",
876 DataStoreVersions.CURRENT_VERSION);
878 createSnapshotTransaction.tell(CreateSnapshot.INSTANCE, self());
883 protected void applySnapshot(final byte[] snapshotBytes) {
884 // Since this will be done only on Recovery or when this actor is a Follower
885 // we can safely commit everything in here. We not need to worry about event notifications
886 // as they would have already been disabled on the follower
888 LOG.info("{}: Applying snapshot", persistenceId());
890 DOMStoreWriteTransaction transaction = store.newWriteOnlyTransaction();
892 NormalizedNode<?, ?> node = SerializationUtils.deserializeNormalizedNode(snapshotBytes);
894 // delete everything first
895 transaction.delete(DATASTORE_ROOT);
897 // Add everything from the remote node back
898 transaction.write(DATASTORE_ROOT, node);
899 syncCommitTransaction(transaction);
900 } catch (InterruptedException | ExecutionException e) {
901 LOG.error("{}: An exception occurred when applying snapshot", persistenceId(), e);
903 LOG.info("{}: Done applying snapshot", persistenceId());
908 protected void onStateChanged() {
909 boolean isLeader = isLeader();
910 for (ActorSelection dataChangeListener : dataChangeListeners) {
911 dataChangeListener.tell(new EnableNotification(isLeader), getSelf());
915 for(DelayedListenerRegistration reg: delayedListenerRegistrations) {
916 if(!reg.isClosed()) {
917 reg.setDelegate(doChangeListenerRegistration(reg.getRegisterChangeListener()));
921 delayedListenerRegistrations.clear();
924 shardMBean.setRaftState(getRaftState().name());
925 shardMBean.setCurrentTerm(getCurrentTerm());
927 // If this actor is no longer the leader close all the transaction chains
929 for(Map.Entry<String, DOMStoreTransactionChain> entry : transactionChains.entrySet()){
930 if(LOG.isDebugEnabled()) {
932 "{}: onStateChanged: Closing transaction chain {} because shard {} is no longer the leader",
933 persistenceId(), entry.getKey(), getId());
935 entry.getValue().close();
938 transactionChains.clear();
943 protected DataPersistenceProvider persistence() {
944 return dataPersistenceProvider;
947 @Override protected void onLeaderChanged(final String oldLeader, final String newLeader) {
948 shardMBean.setLeader(newLeader);
951 @Override public String persistenceId() {
952 return this.name.toString();
956 DataPersistenceProvider getDataPersistenceProvider() {
957 return dataPersistenceProvider;
960 private static class ShardCreator implements Creator<Shard> {
962 private static final long serialVersionUID = 1L;
964 final ShardIdentifier name;
965 final Map<ShardIdentifier, String> peerAddresses;
966 final DatastoreContext datastoreContext;
967 final SchemaContext schemaContext;
969 ShardCreator(final ShardIdentifier name, final Map<ShardIdentifier, String> peerAddresses,
970 final DatastoreContext datastoreContext, final SchemaContext schemaContext) {
972 this.peerAddresses = peerAddresses;
973 this.datastoreContext = datastoreContext;
974 this.schemaContext = schemaContext;
978 public Shard create() throws Exception {
979 return new Shard(name, peerAddresses, datastoreContext, schemaContext);
984 public InMemoryDOMDataStore getDataStore() {
989 ShardStats getShardMBean() {
993 private static class DelayedListenerRegistration implements
994 ListenerRegistration<AsyncDataChangeListener<YangInstanceIdentifier, NormalizedNode<?, ?>>> {
996 private volatile boolean closed;
998 private final RegisterChangeListener registerChangeListener;
1000 private volatile ListenerRegistration<AsyncDataChangeListener<YangInstanceIdentifier,
1001 NormalizedNode<?, ?>>> delegate;
1003 DelayedListenerRegistration(final RegisterChangeListener registerChangeListener) {
1004 this.registerChangeListener = registerChangeListener;
1007 void setDelegate( final ListenerRegistration<AsyncDataChangeListener<YangInstanceIdentifier,
1008 NormalizedNode<?, ?>>> registration) {
1009 this.delegate = registration;
1012 boolean isClosed() {
1016 RegisterChangeListener getRegisterChangeListener() {
1017 return registerChangeListener;
1021 public AsyncDataChangeListener<YangInstanceIdentifier, NormalizedNode<?, ?>> getInstance() {
1022 return delegate != null ? delegate.getInstance() : null;
1026 public void close() {
1028 if(delegate != null) {