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;
137 * Coordinates persistence recovery on startup.
139 private ShardRecoveryCoordinator recoveryCoordinator;
140 private List<Object> currentLogRecoveryBatch;
142 private final Map<String, DOMStoreTransactionChain> transactionChains = new HashMap<>();
144 private final String txnDispatcherPath;
146 protected Shard(final ShardIdentifier name, final Map<ShardIdentifier, String> peerAddresses,
147 final DatastoreContext datastoreContext, final SchemaContext schemaContext) {
148 super(name.toString(), mapPeerAddresses(peerAddresses),
149 Optional.of(datastoreContext.getShardRaftConfig()));
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());
173 if (isMetricsCaptureEnabled()) {
174 getContext().become(new MeteringBehavior(this));
177 commitCoordinator = new ShardCommitCoordinator(TimeUnit.SECONDS.convert(1, TimeUnit.MINUTES),
178 datastoreContext.getShardTransactionCommitQueueCapacity(), LOG, name.toString());
180 setTransactionCommitTimeout();
182 // create a notifier actor for each cluster member
183 roleChangeNotifier = createRoleChangeNotifier(name.toString());
185 appendEntriesReplyTracker = new MessageTracker(AppendEntriesReply.class,
186 getRaftActorContext().getConfigParams().getIsolatedCheckIntervalInMillis());
189 private void setTransactionCommitTimeout() {
190 transactionCommitTimeout = TimeUnit.MILLISECONDS.convert(
191 datastoreContext.getShardTransactionCommitTimeoutInSeconds(), TimeUnit.SECONDS);
194 private static Map<String, String> mapPeerAddresses(
195 final Map<ShardIdentifier, String> peerAddresses) {
196 Map<String, String> map = new HashMap<>();
198 for (Map.Entry<ShardIdentifier, String> entry : peerAddresses
200 map.put(entry.getKey().toString(), entry.getValue());
206 public static Props props(final ShardIdentifier name,
207 final Map<ShardIdentifier, String> peerAddresses,
208 final DatastoreContext datastoreContext, final SchemaContext schemaContext) {
209 Preconditions.checkNotNull(name, "name should not be null");
210 Preconditions.checkNotNull(peerAddresses, "peerAddresses should not be null");
211 Preconditions.checkNotNull(datastoreContext, "dataStoreContext should not be null");
212 Preconditions.checkNotNull(schemaContext, "schemaContext should not be null");
214 return Props.create(new ShardCreator(name, peerAddresses, datastoreContext, schemaContext));
217 private Optional<ActorRef> createRoleChangeNotifier(String shardId) {
218 ActorRef shardRoleChangeNotifier = this.getContext().actorOf(
219 RoleChangeNotifier.getProps(shardId), shardId + "-notifier");
220 return Optional.of(shardRoleChangeNotifier);
224 public void postStop() {
225 LOG.info("Stopping Shard {}", persistenceId());
229 if(txCommitTimeoutCheckSchedule != null) {
230 txCommitTimeoutCheckSchedule.cancel();
233 shardMBean.unregisterMBean();
237 public void onReceiveRecover(final Object message) throws Exception {
238 if(LOG.isDebugEnabled()) {
239 LOG.debug("{}: onReceiveRecover: Received message {} from {}", persistenceId(),
240 message.getClass().toString(), getSender());
243 if (message instanceof RecoveryFailure){
244 LOG.error("{}: Recovery failed because of this cause",
245 persistenceId(), ((RecoveryFailure) message).cause());
247 // Even though recovery failed, we still need to finish our recovery, eg send the
248 // ActorInitialized message and start the txCommitTimeoutCheckSchedule.
249 onRecoveryComplete();
251 super.onReceiveRecover(message);
252 if(LOG.isTraceEnabled()) {
253 appendEntriesReplyTracker.begin();
259 public void onReceiveCommand(final Object message) throws Exception {
261 MessageTracker.Context context = appendEntriesReplyTracker.received(message);
263 if(context.error().isPresent()){
264 LOG.trace("{} : AppendEntriesReply failed to arrive at the expected interval {}", persistenceId(),
269 if (message.getClass().equals(CreateTransaction.SERIALIZABLE_CLASS)) {
270 handleCreateTransaction(message);
271 } else if (message instanceof ForwardedReadyTransaction) {
272 handleForwardedReadyTransaction((ForwardedReadyTransaction) message);
273 } else if (message.getClass().equals(CanCommitTransaction.SERIALIZABLE_CLASS)) {
274 handleCanCommitTransaction(CanCommitTransaction.fromSerializable(message));
275 } else if (message.getClass().equals(CommitTransaction.SERIALIZABLE_CLASS)) {
276 handleCommitTransaction(CommitTransaction.fromSerializable(message));
277 } else if (message.getClass().equals(AbortTransaction.SERIALIZABLE_CLASS)) {
278 handleAbortTransaction(AbortTransaction.fromSerializable(message));
279 } else if (message.getClass().equals(CloseTransactionChain.SERIALIZABLE_CLASS)) {
280 closeTransactionChain(CloseTransactionChain.fromSerializable(message));
281 } else if (message instanceof RegisterChangeListener) {
282 registerChangeListener((RegisterChangeListener) message);
283 } else if (message instanceof UpdateSchemaContext) {
284 updateSchemaContext((UpdateSchemaContext) message);
285 } else if (message instanceof PeerAddressResolved) {
286 PeerAddressResolved resolved = (PeerAddressResolved) message;
287 setPeerAddress(resolved.getPeerId().toString(),
288 resolved.getPeerAddress());
289 } else if (message.equals(TX_COMMIT_TIMEOUT_CHECK_MESSAGE)) {
290 handleTransactionCommitTimeoutCheck();
291 } else if(message instanceof DatastoreContext) {
292 onDatastoreContext((DatastoreContext)message);
293 } else if(message instanceof RegisterRoleChangeListener){
294 roleChangeNotifier.get().forward(message, context());
295 } else if (message instanceof FollowerInitialSyncUpStatus){
296 shardMBean.setFollowerInitialSyncStatus(((FollowerInitialSyncUpStatus) message).isInitialSyncDone());
297 context().parent().tell(message, self());
299 super.onReceiveCommand(message);
307 protected Optional<ActorRef> getRoleChangeNotifier() {
308 return roleChangeNotifier;
311 private void onDatastoreContext(DatastoreContext context) {
312 datastoreContext = context;
314 commitCoordinator.setQueueCapacity(datastoreContext.getShardTransactionCommitQueueCapacity());
316 setTransactionCommitTimeout();
318 if(datastoreContext.isPersistent() &&
319 dataPersistenceProvider instanceof NonPersistentRaftDataProvider) {
320 dataPersistenceProvider = new PersistentDataProvider();
321 } else if(!datastoreContext.isPersistent() &&
322 dataPersistenceProvider instanceof PersistentDataProvider) {
323 dataPersistenceProvider = new NonPersistentRaftDataProvider();
326 updateConfigParams(datastoreContext.getShardRaftConfig());
329 private void handleTransactionCommitTimeoutCheck() {
330 CohortEntry cohortEntry = commitCoordinator.getCurrentCohortEntry();
331 if(cohortEntry != null) {
332 long elapsed = System.currentTimeMillis() - cohortEntry.getLastAccessTime();
333 if(elapsed > transactionCommitTimeout) {
334 LOG.warn("{}: Current transaction {} has timed out after {} ms - aborting",
335 persistenceId(), cohortEntry.getTransactionID(), transactionCommitTimeout);
337 doAbortTransaction(cohortEntry.getTransactionID(), null);
342 private void handleCommitTransaction(final CommitTransaction commit) {
343 final String transactionID = commit.getTransactionID();
345 LOG.debug("{}: Committing transaction {}", persistenceId(), transactionID);
347 // Get the current in-progress cohort entry in the commitCoordinator if it corresponds to
349 final CohortEntry cohortEntry = commitCoordinator.getCohortEntryIfCurrent(transactionID);
350 if(cohortEntry == null) {
351 // We're not the current Tx - the Tx was likely expired b/c it took too long in
352 // between the canCommit and commit messages.
353 IllegalStateException ex = new IllegalStateException(
354 String.format("%s: Cannot commit transaction %s - it is not the current transaction",
355 persistenceId(), transactionID));
356 LOG.error(ex.getMessage());
357 shardMBean.incrementFailedTransactionsCount();
358 getSender().tell(new akka.actor.Status.Failure(ex), getSelf());
362 // We perform the preCommit phase here atomically with the commit phase. This is an
363 // optimization to eliminate the overhead of an extra preCommit message. We lose front-end
364 // coordination of preCommit across shards in case of failure but preCommit should not
365 // normally fail since we ensure only one concurrent 3-phase commit.
368 // We block on the future here so we don't have to worry about possibly accessing our
369 // state on a different thread outside of our dispatcher. Also, the data store
370 // currently uses a same thread executor anyway.
371 cohortEntry.getCohort().preCommit().get();
373 // If we do not have any followers and we are not using persistence we can
374 // apply modification to the state immediately
375 if(!hasFollowers() && !persistence().isRecoveryApplicable()){
376 applyModificationToState(getSender(), transactionID, cohortEntry.getModification());
378 Shard.this.persistData(getSender(), transactionID,
379 new ModificationPayload(cohortEntry.getModification()));
381 } catch (Exception e) {
382 LOG.error("{} An exception occurred while preCommitting transaction {}",
383 persistenceId(), cohortEntry.getTransactionID(), e);
384 shardMBean.incrementFailedTransactionsCount();
385 getSender().tell(new akka.actor.Status.Failure(e), getSelf());
388 cohortEntry.updateLastAccessTime();
391 private void finishCommit(@Nonnull final ActorRef sender, final @Nonnull String transactionID) {
392 // With persistence enabled, this method is called via applyState by the leader strategy
393 // after the commit has been replicated to a majority of the followers.
395 CohortEntry cohortEntry = commitCoordinator.getCohortEntryIfCurrent(transactionID);
396 if(cohortEntry == null) {
397 // The transaction is no longer the current commit. This can happen if the transaction
398 // was aborted prior, most likely due to timeout in the front-end. We need to finish
399 // committing the transaction though since it was successfully persisted and replicated
400 // however we can't use the original cohort b/c it was already preCommitted and may
401 // conflict with the current commit or may have been aborted so we commit with a new
403 cohortEntry = commitCoordinator.getAndRemoveCohortEntry(transactionID);
404 if(cohortEntry != null) {
405 commitWithNewTransaction(cohortEntry.getModification());
406 sender.tell(CommitTransactionReply.INSTANCE.toSerializable(), getSelf());
408 // This really shouldn't happen - it likely means that persistence or replication
409 // took so long to complete such that the cohort entry was expired from the cache.
410 IllegalStateException ex = new IllegalStateException(
411 String.format("%s: Could not finish committing transaction %s - no CohortEntry found",
412 persistenceId(), transactionID));
413 LOG.error(ex.getMessage());
414 sender.tell(new akka.actor.Status.Failure(ex), getSelf());
420 LOG.debug("{}: Finishing commit for transaction {}", persistenceId(), cohortEntry.getTransactionID());
423 // We block on the future here so we don't have to worry about possibly accessing our
424 // state on a different thread outside of our dispatcher. Also, the data store
425 // currently uses a same thread executor anyway.
426 cohortEntry.getCohort().commit().get();
428 sender.tell(CommitTransactionReply.INSTANCE.toSerializable(), getSelf());
430 shardMBean.incrementCommittedTransactionCount();
431 shardMBean.setLastCommittedTransactionTime(System.currentTimeMillis());
433 } catch (Exception e) {
434 sender.tell(new akka.actor.Status.Failure(e), getSelf());
436 LOG.error("{}, An exception occurred while committing transaction {}", persistenceId(),
438 shardMBean.incrementFailedTransactionsCount();
440 commitCoordinator.currentTransactionComplete(transactionID, true);
444 private void handleCanCommitTransaction(final CanCommitTransaction canCommit) {
445 LOG.debug("{}: Can committing transaction {}", persistenceId(), canCommit.getTransactionID());
446 commitCoordinator.handleCanCommit(canCommit, getSender(), self());
449 private void handleForwardedReadyTransaction(ForwardedReadyTransaction ready) {
450 LOG.debug("{}: Readying transaction {}, client version {}", persistenceId(),
451 ready.getTransactionID(), ready.getTxnClientVersion());
453 // This message is forwarded by the ShardTransaction on ready. We cache the cohort in the
454 // commitCoordinator in preparation for the subsequent three phase commit initiated by
456 commitCoordinator.transactionReady(ready.getTransactionID(), ready.getCohort(),
457 ready.getModification());
459 // Return our actor path as we'll handle the three phase commit, except if the Tx client
460 // version < 1 (Helium-1 version). This means the Tx was initiated by a base Helium version
461 // node. In that case, the subsequent 3-phase commit messages won't contain the
462 // transactionId so to maintain backwards compatibility, we create a separate cohort actor
463 // to provide the compatible behavior.
464 ActorRef replyActorPath = self();
465 if(ready.getTxnClientVersion() < DataStoreVersions.HELIUM_1_VERSION) {
466 LOG.debug("{}: Creating BackwardsCompatibleThreePhaseCommitCohort", persistenceId());
467 replyActorPath = getContext().actorOf(BackwardsCompatibleThreePhaseCommitCohort.props(
468 ready.getTransactionID()));
471 ReadyTransactionReply readyTransactionReply = new ReadyTransactionReply(
472 Serialization.serializedActorPath(replyActorPath));
473 getSender().tell(ready.isReturnSerialized() ? readyTransactionReply.toSerializable() :
474 readyTransactionReply, getSelf());
477 private void handleAbortTransaction(final AbortTransaction abort) {
478 doAbortTransaction(abort.getTransactionID(), getSender());
481 void doAbortTransaction(final String transactionID, final ActorRef sender) {
482 final CohortEntry cohortEntry = commitCoordinator.getCohortEntryIfCurrent(transactionID);
483 if(cohortEntry != null) {
484 LOG.debug("{}: Aborting transaction {}", persistenceId(), transactionID);
486 // We don't remove the cached cohort entry here (ie pass false) in case the Tx was
487 // aborted during replication in which case we may still commit locally if replication
489 commitCoordinator.currentTransactionComplete(transactionID, false);
491 final ListenableFuture<Void> future = cohortEntry.getCohort().abort();
492 final ActorRef self = getSelf();
494 Futures.addCallback(future, new FutureCallback<Void>() {
496 public void onSuccess(final Void v) {
497 shardMBean.incrementAbortTransactionsCount();
500 sender.tell(AbortTransactionReply.INSTANCE.toSerializable(), self);
505 public void onFailure(final Throwable t) {
506 LOG.error("{}: An exception happened during abort", persistenceId(), t);
509 sender.tell(new akka.actor.Status.Failure(t), self);
516 private void handleCreateTransaction(final Object message) {
518 createTransaction(CreateTransaction.fromSerializable(message));
519 } else if (getLeader() != null) {
520 getLeader().forward(message, getContext());
522 getSender().tell(new akka.actor.Status.Failure(new NoShardLeaderException(String.format(
523 "Could not find leader for shard %s so transaction cannot be created. This typically happens" +
524 " when the system is coming up or recovering and a leader is being elected. Try again" +
525 " later.", persistenceId()))), getSelf());
529 private void closeTransactionChain(final CloseTransactionChain closeTransactionChain) {
530 DOMStoreTransactionChain chain =
531 transactionChains.remove(closeTransactionChain.getTransactionChainId());
538 private ActorRef createTypedTransactionActor(int transactionType,
539 ShardTransactionIdentifier transactionId, String transactionChainId,
540 short clientVersion ) {
542 DOMStoreTransactionFactory factory = store;
544 if(!transactionChainId.isEmpty()) {
545 factory = transactionChains.get(transactionChainId);
547 DOMStoreTransactionChain transactionChain = store.createTransactionChain();
548 transactionChains.put(transactionChainId, transactionChain);
549 factory = transactionChain;
553 if(this.schemaContext == null) {
554 throw new IllegalStateException("SchemaContext is not set");
557 if (transactionType == TransactionProxy.TransactionType.READ_ONLY.ordinal()) {
559 shardMBean.incrementReadOnlyTransactionCount();
561 return createShardTransaction(factory.newReadOnlyTransaction(), transactionId, clientVersion);
563 } else if (transactionType == TransactionProxy.TransactionType.READ_WRITE.ordinal()) {
565 shardMBean.incrementReadWriteTransactionCount();
567 return createShardTransaction(factory.newReadWriteTransaction(), transactionId, clientVersion);
569 } else if (transactionType == TransactionProxy.TransactionType.WRITE_ONLY.ordinal()) {
571 shardMBean.incrementWriteOnlyTransactionCount();
573 return createShardTransaction(factory.newWriteOnlyTransaction(), transactionId, clientVersion);
575 throw new IllegalArgumentException(
576 "Shard="+name + ":CreateTransaction message has unidentified transaction type="
581 private ActorRef createShardTransaction(DOMStoreTransaction transaction, ShardTransactionIdentifier transactionId,
582 short clientVersion){
583 return getContext().actorOf(
584 ShardTransaction.props(transaction, getSelf(),
585 schemaContext, datastoreContext, shardMBean,
586 transactionId.getRemoteTransactionId(), clientVersion)
587 .withDispatcher(txnDispatcherPath),
588 transactionId.toString());
592 private void createTransaction(CreateTransaction createTransaction) {
594 ActorRef transactionActor = createTransaction(createTransaction.getTransactionType(),
595 createTransaction.getTransactionId(), createTransaction.getTransactionChainId(),
596 createTransaction.getVersion());
598 getSender().tell(new CreateTransactionReply(Serialization.serializedActorPath(transactionActor),
599 createTransaction.getTransactionId()).toSerializable(), getSelf());
600 } catch (Exception e) {
601 getSender().tell(new akka.actor.Status.Failure(e), getSelf());
605 private ActorRef createTransaction(int transactionType, String remoteTransactionId,
606 String transactionChainId, short clientVersion) {
608 ShardTransactionIdentifier transactionId =
609 ShardTransactionIdentifier.builder()
610 .remoteTransactionId(remoteTransactionId)
613 if(LOG.isDebugEnabled()) {
614 LOG.debug("{}: Creating transaction : {} ", persistenceId(), transactionId);
617 ActorRef transactionActor = createTypedTransactionActor(transactionType, transactionId,
618 transactionChainId, clientVersion);
620 return transactionActor;
623 private void syncCommitTransaction(final DOMStoreWriteTransaction transaction)
624 throws ExecutionException, InterruptedException {
625 DOMStoreThreePhaseCommitCohort commitCohort = transaction.ready();
626 commitCohort.preCommit().get();
627 commitCohort.commit().get();
630 private void commitWithNewTransaction(final Modification modification) {
631 DOMStoreWriteTransaction tx = store.newWriteOnlyTransaction();
632 modification.apply(tx);
634 syncCommitTransaction(tx);
635 shardMBean.incrementCommittedTransactionCount();
636 shardMBean.setLastCommittedTransactionTime(System.currentTimeMillis());
637 } catch (InterruptedException | ExecutionException e) {
638 shardMBean.incrementFailedTransactionsCount();
639 LOG.error("{}: Failed to commit", persistenceId(), e);
643 private void updateSchemaContext(final UpdateSchemaContext message) {
644 this.schemaContext = message.getSchemaContext();
645 updateSchemaContext(message.getSchemaContext());
646 store.onGlobalContextUpdated(message.getSchemaContext());
650 void updateSchemaContext(final SchemaContext schemaContext) {
651 store.onGlobalContextUpdated(schemaContext);
654 private void registerChangeListener(final RegisterChangeListener registerChangeListener) {
656 LOG.debug("{}: registerDataChangeListener for {}", persistenceId(), registerChangeListener.getPath());
658 ListenerRegistration<AsyncDataChangeListener<YangInstanceIdentifier,
659 NormalizedNode<?, ?>>> registration;
661 registration = doChangeListenerRegistration(registerChangeListener);
663 LOG.debug("{}: Shard is not the leader - delaying registration", persistenceId());
665 DelayedListenerRegistration delayedReg =
666 new DelayedListenerRegistration(registerChangeListener);
667 delayedListenerRegistrations.add(delayedReg);
668 registration = delayedReg;
671 ActorRef listenerRegistration = getContext().actorOf(
672 DataChangeListenerRegistration.props(registration));
674 LOG.debug("{}: registerDataChangeListener sending reply, listenerRegistrationPath = {} ",
675 persistenceId(), listenerRegistration.path());
677 getSender().tell(new RegisterChangeListenerReply(listenerRegistration.path()), getSelf());
680 private ListenerRegistration<AsyncDataChangeListener<YangInstanceIdentifier,
681 NormalizedNode<?, ?>>> doChangeListenerRegistration(
682 final RegisterChangeListener registerChangeListener) {
684 ActorSelection dataChangeListenerPath = getContext().system().actorSelection(
685 registerChangeListener.getDataChangeListenerPath());
687 // Notify the listener if notifications should be enabled or not
688 // If this shard is the leader then it will enable notifications else
690 dataChangeListenerPath.tell(new EnableNotification(true), getSelf());
692 // Now store a reference to the data change listener so it can be notified
693 // at a later point if notifications should be enabled or disabled
694 dataChangeListeners.add(dataChangeListenerPath);
696 AsyncDataChangeListener<YangInstanceIdentifier, NormalizedNode<?, ?>> listener =
697 new DataChangeListenerProxy(dataChangeListenerPath);
699 LOG.debug("{}: Registering for path {}", persistenceId(), registerChangeListener.getPath());
701 return store.registerChangeListener(registerChangeListener.getPath(), listener,
702 registerChangeListener.getScope());
705 private boolean isMetricsCaptureEnabled(){
706 CommonConfig config = new CommonConfig(getContext().system().settings().config());
707 return config.isMetricCaptureEnabled();
712 void startLogRecoveryBatch(final int maxBatchSize) {
713 currentLogRecoveryBatch = Lists.newArrayListWithCapacity(maxBatchSize);
715 if(LOG.isDebugEnabled()) {
716 LOG.debug("{}: starting log recovery batch with max size {}", persistenceId(), maxBatchSize);
721 protected void appendRecoveredLogEntry(final Payload data) {
722 if(data instanceof ModificationPayload) {
724 currentLogRecoveryBatch.add(((ModificationPayload) data).getModification());
725 } catch (ClassNotFoundException | IOException e) {
726 LOG.error("{}: Error extracting ModificationPayload", persistenceId(), e);
728 } else if (data instanceof CompositeModificationPayload) {
729 currentLogRecoveryBatch.add(((CompositeModificationPayload) data).getModification());
730 } else if (data instanceof CompositeModificationByteStringPayload) {
731 currentLogRecoveryBatch.add(((CompositeModificationByteStringPayload) data).getModification());
733 LOG.error("{}: Unknown state received {} during recovery", persistenceId(), data);
738 protected void applyRecoverySnapshot(final byte[] snapshotBytes) {
739 if(recoveryCoordinator == null) {
740 recoveryCoordinator = new ShardRecoveryCoordinator(persistenceId(), schemaContext,
741 LOG, name.toString());
744 recoveryCoordinator.submit(snapshotBytes, store.newWriteOnlyTransaction());
746 if(LOG.isDebugEnabled()) {
747 LOG.debug("{}: submitted recovery sbapshot", persistenceId());
752 protected void applyCurrentLogRecoveryBatch() {
753 if(recoveryCoordinator == null) {
754 recoveryCoordinator = new ShardRecoveryCoordinator(persistenceId(), schemaContext,
755 LOG, name.toString());
758 recoveryCoordinator.submit(currentLogRecoveryBatch, store.newWriteOnlyTransaction());
760 if(LOG.isDebugEnabled()) {
761 LOG.debug("{}: submitted log recovery batch with size {}", persistenceId(),
762 currentLogRecoveryBatch.size());
767 protected void onRecoveryComplete() {
768 if(recoveryCoordinator != null) {
769 Collection<DOMStoreWriteTransaction> txList = recoveryCoordinator.getTransactions();
771 if(LOG.isDebugEnabled()) {
772 LOG.debug("{}: recovery complete - committing {} Tx's", persistenceId(), txList.size());
775 for(DOMStoreWriteTransaction tx: txList) {
777 syncCommitTransaction(tx);
778 shardMBean.incrementCommittedTransactionCount();
779 } catch (InterruptedException | ExecutionException e) {
780 shardMBean.incrementFailedTransactionsCount();
781 LOG.error("{}: Failed to commit", persistenceId(), e);
786 recoveryCoordinator = null;
787 currentLogRecoveryBatch = null;
788 updateJournalStats();
790 //notify shard manager
791 getContext().parent().tell(new ActorInitialized(), getSelf());
793 // Being paranoid here - this method should only be called once but just in case...
794 if(txCommitTimeoutCheckSchedule == null) {
795 // Schedule a message to be periodically sent to check if the current in-progress
796 // transaction should be expired and aborted.
797 FiniteDuration period = Duration.create(transactionCommitTimeout / 3, TimeUnit.MILLISECONDS);
798 txCommitTimeoutCheckSchedule = getContext().system().scheduler().schedule(
799 period, period, getSelf(),
800 TX_COMMIT_TIMEOUT_CHECK_MESSAGE, getContext().dispatcher(), ActorRef.noSender());
805 protected void applyState(final ActorRef clientActor, final String identifier, final Object data) {
807 if(data instanceof ModificationPayload) {
809 applyModificationToState(clientActor, identifier, ((ModificationPayload) data).getModification());
810 } catch (ClassNotFoundException | IOException e) {
811 LOG.error("{}: Error extracting ModificationPayload", persistenceId(), e);
814 else if (data instanceof CompositeModificationPayload) {
815 Object modification = ((CompositeModificationPayload) data).getModification();
817 applyModificationToState(clientActor, identifier, modification);
818 } else if(data instanceof CompositeModificationByteStringPayload ){
819 Object modification = ((CompositeModificationByteStringPayload) data).getModification();
821 applyModificationToState(clientActor, identifier, modification);
823 LOG.error("{}: Unknown state received {} Class loader = {} CompositeNodeMod.ClassLoader = {}",
824 persistenceId(), data, data.getClass().getClassLoader(),
825 CompositeModificationPayload.class.getClassLoader());
828 updateJournalStats();
832 private void applyModificationToState(ActorRef clientActor, String identifier, Object modification) {
833 if(modification == null) {
835 "{}: modification is null - this is very unexpected, clientActor = {}, identifier = {}",
836 persistenceId(), identifier, clientActor != null ? clientActor.path().toString() : null);
837 } else if(clientActor == null) {
838 // There's no clientActor to which to send a commit reply so we must be applying
839 // replicated state from the leader.
840 commitWithNewTransaction(MutableCompositeModification.fromSerializable(modification));
842 // This must be the OK to commit after replication consensus.
843 finishCommit(clientActor, identifier);
847 private void updateJournalStats() {
848 ReplicatedLogEntry lastLogEntry = getLastLogEntry();
850 if (lastLogEntry != null) {
851 shardMBean.setLastLogIndex(lastLogEntry.getIndex());
852 shardMBean.setLastLogTerm(lastLogEntry.getTerm());
855 shardMBean.setCommitIndex(getCommitIndex());
856 shardMBean.setLastApplied(getLastApplied());
857 shardMBean.setInMemoryJournalDataSize(getRaftActorContext().getReplicatedLog().dataSize());
861 protected void createSnapshot() {
862 // Create a transaction actor. We are really going to treat the transaction as a worker
863 // so that this actor does not get block building the snapshot. THe transaction actor will
864 // after processing the CreateSnapshot message.
866 ActorRef createSnapshotTransaction = createTransaction(
867 TransactionProxy.TransactionType.READ_ONLY.ordinal(),
868 "createSnapshot" + ++createSnapshotTransactionCounter, "",
869 DataStoreVersions.CURRENT_VERSION);
871 createSnapshotTransaction.tell(CreateSnapshot.INSTANCE, self());
876 protected void applySnapshot(final byte[] snapshotBytes) {
877 // Since this will be done only on Recovery or when this actor is a Follower
878 // we can safely commit everything in here. We not need to worry about event notifications
879 // as they would have already been disabled on the follower
881 LOG.info("{}: Applying snapshot", persistenceId());
883 DOMStoreWriteTransaction transaction = store.newWriteOnlyTransaction();
885 NormalizedNode<?, ?> node = SerializationUtils.deserializeNormalizedNode(snapshotBytes);
887 // delete everything first
888 transaction.delete(DATASTORE_ROOT);
890 // Add everything from the remote node back
891 transaction.write(DATASTORE_ROOT, node);
892 syncCommitTransaction(transaction);
893 } catch (InterruptedException | ExecutionException e) {
894 LOG.error("{}: An exception occurred when applying snapshot", persistenceId(), e);
896 LOG.info("{}: Done applying snapshot", persistenceId());
901 protected void onStateChanged() {
902 boolean isLeader = isLeader();
903 for (ActorSelection dataChangeListener : dataChangeListeners) {
904 dataChangeListener.tell(new EnableNotification(isLeader), getSelf());
908 for(DelayedListenerRegistration reg: delayedListenerRegistrations) {
909 if(!reg.isClosed()) {
910 reg.setDelegate(doChangeListenerRegistration(reg.getRegisterChangeListener()));
914 delayedListenerRegistrations.clear();
917 shardMBean.setRaftState(getRaftState().name());
918 shardMBean.setCurrentTerm(getCurrentTerm());
920 // If this actor is no longer the leader close all the transaction chains
922 for(Map.Entry<String, DOMStoreTransactionChain> entry : transactionChains.entrySet()){
923 if(LOG.isDebugEnabled()) {
925 "{}: onStateChanged: Closing transaction chain {} because shard {} is no longer the leader",
926 persistenceId(), entry.getKey(), getId());
928 entry.getValue().close();
931 transactionChains.clear();
936 protected DataPersistenceProvider persistence() {
937 return dataPersistenceProvider;
940 @Override protected void onLeaderChanged(final String oldLeader, final String newLeader) {
941 shardMBean.setLeader(newLeader);
944 @Override public String persistenceId() {
945 return this.name.toString();
949 DataPersistenceProvider getDataPersistenceProvider() {
950 return dataPersistenceProvider;
953 private static class ShardCreator implements Creator<Shard> {
955 private static final long serialVersionUID = 1L;
957 final ShardIdentifier name;
958 final Map<ShardIdentifier, String> peerAddresses;
959 final DatastoreContext datastoreContext;
960 final SchemaContext schemaContext;
962 ShardCreator(final ShardIdentifier name, final Map<ShardIdentifier, String> peerAddresses,
963 final DatastoreContext datastoreContext, final SchemaContext schemaContext) {
965 this.peerAddresses = peerAddresses;
966 this.datastoreContext = datastoreContext;
967 this.schemaContext = schemaContext;
971 public Shard create() throws Exception {
972 return new Shard(name, peerAddresses, datastoreContext, schemaContext);
977 InMemoryDOMDataStore getDataStore() {
982 ShardStats getShardMBean() {
986 private static class DelayedListenerRegistration implements
987 ListenerRegistration<AsyncDataChangeListener<YangInstanceIdentifier, NormalizedNode<?, ?>>> {
989 private volatile boolean closed;
991 private final RegisterChangeListener registerChangeListener;
993 private volatile ListenerRegistration<AsyncDataChangeListener<YangInstanceIdentifier,
994 NormalizedNode<?, ?>>> delegate;
996 DelayedListenerRegistration(final RegisterChangeListener registerChangeListener) {
997 this.registerChangeListener = registerChangeListener;
1000 void setDelegate( final ListenerRegistration<AsyncDataChangeListener<YangInstanceIdentifier,
1001 NormalizedNode<?, ?>>> registration) {
1002 this.delegate = registration;
1005 boolean isClosed() {
1009 RegisterChangeListener getRegisterChangeListener() {
1010 return registerChangeListener;
1014 public AsyncDataChangeListener<YangInstanceIdentifier, NormalizedNode<?, ?>> getInstance() {
1015 return delegate != null ? delegate.getInstance() : null;
1019 public void close() {
1021 if(delegate != null) {