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.event.Logging;
16 import akka.event.LoggingAdapter;
17 import akka.japi.Creator;
18 import akka.persistence.RecoveryFailure;
19 import akka.serialization.Serialization;
20 import com.google.common.annotations.VisibleForTesting;
21 import com.google.common.base.Optional;
22 import com.google.common.base.Preconditions;
23 import com.google.common.collect.Lists;
24 import com.google.common.util.concurrent.FutureCallback;
25 import com.google.common.util.concurrent.Futures;
26 import com.google.common.util.concurrent.ListenableFuture;
27 import java.io.IOException;
28 import java.util.Collection;
29 import java.util.HashMap;
30 import java.util.List;
32 import java.util.concurrent.ExecutionException;
33 import java.util.concurrent.TimeUnit;
34 import javax.annotation.Nonnull;
35 import org.opendaylight.controller.cluster.DataPersistenceProvider;
36 import org.opendaylight.controller.cluster.common.actor.CommonConfig;
37 import org.opendaylight.controller.cluster.common.actor.MeteringBehavior;
38 import org.opendaylight.controller.cluster.datastore.ShardCommitCoordinator.CohortEntry;
39 import org.opendaylight.controller.cluster.datastore.compat.BackwardsCompatibleThreePhaseCommitCohort;
40 import org.opendaylight.controller.cluster.datastore.exceptions.NoShardLeaderException;
41 import org.opendaylight.controller.cluster.datastore.identifiers.ShardIdentifier;
42 import org.opendaylight.controller.cluster.datastore.identifiers.ShardTransactionIdentifier;
43 import org.opendaylight.controller.cluster.datastore.jmx.mbeans.shard.ShardMBeanFactory;
44 import org.opendaylight.controller.cluster.datastore.jmx.mbeans.shard.ShardStats;
45 import org.opendaylight.controller.cluster.datastore.messages.AbortTransaction;
46 import org.opendaylight.controller.cluster.datastore.messages.AbortTransactionReply;
47 import org.opendaylight.controller.cluster.datastore.messages.ActorInitialized;
48 import org.opendaylight.controller.cluster.datastore.messages.CanCommitTransaction;
49 import org.opendaylight.controller.cluster.datastore.messages.CloseTransactionChain;
50 import org.opendaylight.controller.cluster.datastore.messages.CommitTransaction;
51 import org.opendaylight.controller.cluster.datastore.messages.CommitTransactionReply;
52 import org.opendaylight.controller.cluster.datastore.messages.CreateSnapshot;
53 import org.opendaylight.controller.cluster.datastore.messages.CreateTransaction;
54 import org.opendaylight.controller.cluster.datastore.messages.CreateTransactionReply;
55 import org.opendaylight.controller.cluster.datastore.messages.EnableNotification;
56 import org.opendaylight.controller.cluster.datastore.messages.ForwardedReadyTransaction;
57 import org.opendaylight.controller.cluster.datastore.messages.PeerAddressResolved;
58 import org.opendaylight.controller.cluster.datastore.messages.ReadyTransactionReply;
59 import org.opendaylight.controller.cluster.datastore.messages.RegisterChangeListener;
60 import org.opendaylight.controller.cluster.datastore.messages.RegisterChangeListenerReply;
61 import org.opendaylight.controller.cluster.datastore.messages.UpdateSchemaContext;
62 import org.opendaylight.controller.cluster.datastore.modification.Modification;
63 import org.opendaylight.controller.cluster.datastore.modification.ModificationPayload;
64 import org.opendaylight.controller.cluster.datastore.modification.MutableCompositeModification;
65 import org.opendaylight.controller.cluster.datastore.utils.SerializationUtils;
66 import org.opendaylight.controller.cluster.notifications.RoleChangeNotifier;
67 import org.opendaylight.controller.cluster.raft.RaftActor;
68 import org.opendaylight.controller.cluster.raft.ReplicatedLogEntry;
69 import org.opendaylight.controller.cluster.raft.protobuff.client.messages.CompositeModificationByteStringPayload;
70 import org.opendaylight.controller.cluster.raft.protobuff.client.messages.CompositeModificationPayload;
71 import org.opendaylight.controller.cluster.raft.protobuff.client.messages.Payload;
72 import org.opendaylight.controller.md.sal.common.api.data.AsyncDataChangeListener;
73 import org.opendaylight.controller.md.sal.dom.store.impl.InMemoryDOMDataStore;
74 import org.opendaylight.controller.md.sal.dom.store.impl.InMemoryDOMDataStoreFactory;
75 import org.opendaylight.controller.sal.core.spi.data.DOMStoreThreePhaseCommitCohort;
76 import org.opendaylight.controller.sal.core.spi.data.DOMStoreTransactionChain;
77 import org.opendaylight.controller.sal.core.spi.data.DOMStoreTransactionFactory;
78 import org.opendaylight.controller.sal.core.spi.data.DOMStoreWriteTransaction;
79 import org.opendaylight.yangtools.concepts.ListenerRegistration;
80 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
81 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
82 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
83 import scala.concurrent.duration.Duration;
84 import scala.concurrent.duration.FiniteDuration;
87 * A Shard represents a portion of the logical data tree <br/>
89 * Our Shard uses InMemoryDataStore as it's internal representation and delegates all requests it
92 public class Shard extends RaftActor {
94 private static final YangInstanceIdentifier DATASTORE_ROOT = YangInstanceIdentifier.builder().build();
96 private static final Object TX_COMMIT_TIMEOUT_CHECK_MESSAGE = "txCommitTimeoutCheck";
99 static final String DEFAULT_NAME = "default";
101 // The state of this Shard
102 private final InMemoryDOMDataStore store;
104 private final LoggingAdapter LOG = Logging.getLogger(getContext().system(), this);
106 /// The name of this shard
107 private final ShardIdentifier 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 final DatastoreContext datastoreContext;
118 private final DataPersistenceProvider dataPersistenceProvider;
120 private SchemaContext schemaContext;
122 private int createSnapshotTransactionCounter;
124 private final ShardCommitCoordinator commitCoordinator;
126 private final long transactionCommitTimeout;
128 private Cancellable txCommitTimeoutCheckSchedule;
130 private final Optional<ActorRef> roleChangeNotifier;
133 * Coordinates persistence recovery on startup.
135 private ShardRecoveryCoordinator recoveryCoordinator;
136 private List<Object> currentLogRecoveryBatch;
138 private final Map<String, DOMStoreTransactionChain> transactionChains = new HashMap<>();
140 protected Shard(final ShardIdentifier name, final Map<ShardIdentifier, String> peerAddresses,
141 final DatastoreContext datastoreContext, final SchemaContext schemaContext) {
142 super(name.toString(), mapPeerAddresses(peerAddresses),
143 Optional.of(datastoreContext.getShardRaftConfig()));
146 this.datastoreContext = datastoreContext;
147 this.schemaContext = schemaContext;
148 this.dataPersistenceProvider = (datastoreContext.isPersistent()) ? new PersistentDataProvider() : new NonPersistentRaftDataProvider();
150 LOG.info("Shard created : {}, persistent : {}", name, datastoreContext.isPersistent());
152 store = InMemoryDOMDataStoreFactory.create(name.toString(), null,
153 datastoreContext.getDataStoreProperties());
155 if(schemaContext != null) {
156 store.onGlobalContextUpdated(schemaContext);
159 shardMBean = ShardMBeanFactory.getShardStatsMBean(name.toString(),
160 datastoreContext.getDataStoreMXBeanType());
161 shardMBean.setNotificationManager(store.getDataChangeListenerNotificationManager());
163 if (isMetricsCaptureEnabled()) {
164 getContext().become(new MeteringBehavior(this));
167 commitCoordinator = new ShardCommitCoordinator(TimeUnit.SECONDS.convert(1, TimeUnit.MINUTES),
168 datastoreContext.getShardTransactionCommitQueueCapacity(), LOG, name.toString());
170 transactionCommitTimeout = TimeUnit.MILLISECONDS.convert(
171 datastoreContext.getShardTransactionCommitTimeoutInSeconds(), TimeUnit.SECONDS);
173 // create a notifier actor for each cluster member
174 roleChangeNotifier = createRoleChangeNotifier(name.toString());
177 private static Map<String, String> mapPeerAddresses(
178 final Map<ShardIdentifier, String> peerAddresses) {
179 Map<String, String> map = new HashMap<>();
181 for (Map.Entry<ShardIdentifier, String> entry : peerAddresses
183 map.put(entry.getKey().toString(), entry.getValue());
189 public static Props props(final ShardIdentifier name,
190 final Map<ShardIdentifier, String> peerAddresses,
191 final DatastoreContext datastoreContext, final SchemaContext schemaContext) {
192 Preconditions.checkNotNull(name, "name should not be null");
193 Preconditions.checkNotNull(peerAddresses, "peerAddresses should not be null");
194 Preconditions.checkNotNull(datastoreContext, "dataStoreContext should not be null");
195 Preconditions.checkNotNull(schemaContext, "schemaContext should not be null");
197 return Props.create(new ShardCreator(name, peerAddresses, datastoreContext, schemaContext));
200 private Optional<ActorRef> createRoleChangeNotifier(String shardId) {
201 ActorRef shardRoleChangeNotifier = this.getContext().actorOf(
202 RoleChangeNotifier.getProps(shardId), shardId + "-notifier");
203 return Optional.<ActorRef>of(shardRoleChangeNotifier);
207 public void postStop() {
210 if(txCommitTimeoutCheckSchedule != null) {
211 txCommitTimeoutCheckSchedule.cancel();
216 public void onReceiveRecover(final Object message) throws Exception {
217 if(LOG.isDebugEnabled()) {
218 LOG.debug("{}: onReceiveRecover: Received message {} from {}", persistenceId(),
219 message.getClass().toString(), getSender());
222 if (message instanceof RecoveryFailure){
223 LOG.error(((RecoveryFailure) message).cause(), "{}: Recovery failed because of this cause",
226 // Even though recovery failed, we still need to finish our recovery, eg send the
227 // ActorInitialized message and start the txCommitTimeoutCheckSchedule.
228 onRecoveryComplete();
230 super.onReceiveRecover(message);
235 public void onReceiveCommand(final Object message) throws Exception {
236 if(LOG.isDebugEnabled()) {
237 LOG.debug("{}: onReceiveCommand: Received message {} from {}", persistenceId(), message, getSender());
240 if (message.getClass().equals(CreateTransaction.SERIALIZABLE_CLASS)) {
241 handleCreateTransaction(message);
242 } else if(message instanceof ForwardedReadyTransaction) {
243 handleForwardedReadyTransaction((ForwardedReadyTransaction)message);
244 } else if(message.getClass().equals(CanCommitTransaction.SERIALIZABLE_CLASS)) {
245 handleCanCommitTransaction(CanCommitTransaction.fromSerializable(message));
246 } else if(message.getClass().equals(CommitTransaction.SERIALIZABLE_CLASS)) {
247 handleCommitTransaction(CommitTransaction.fromSerializable(message));
248 } else if(message.getClass().equals(AbortTransaction.SERIALIZABLE_CLASS)) {
249 handleAbortTransaction(AbortTransaction.fromSerializable(message));
250 } else if (message.getClass().equals(CloseTransactionChain.SERIALIZABLE_CLASS)){
251 closeTransactionChain(CloseTransactionChain.fromSerializable(message));
252 } else if (message instanceof RegisterChangeListener) {
253 registerChangeListener((RegisterChangeListener) message);
254 } else if (message instanceof UpdateSchemaContext) {
255 updateSchemaContext((UpdateSchemaContext) message);
256 } else if (message instanceof PeerAddressResolved) {
257 PeerAddressResolved resolved = (PeerAddressResolved) message;
258 setPeerAddress(resolved.getPeerId().toString(),
259 resolved.getPeerAddress());
260 } else if(message.equals(TX_COMMIT_TIMEOUT_CHECK_MESSAGE)) {
261 handleTransactionCommitTimeoutCheck();
263 super.onReceiveCommand(message);
268 protected Optional<ActorRef> getRoleChangeNotifier() {
269 return roleChangeNotifier;
272 private void handleTransactionCommitTimeoutCheck() {
273 CohortEntry cohortEntry = commitCoordinator.getCurrentCohortEntry();
274 if(cohortEntry != null) {
275 long elapsed = System.currentTimeMillis() - cohortEntry.getLastAccessTime();
276 if(elapsed > transactionCommitTimeout) {
277 LOG.warning("{}: Current transaction {} has timed out after {} ms - aborting",
278 persistenceId(), cohortEntry.getTransactionID(), transactionCommitTimeout);
280 doAbortTransaction(cohortEntry.getTransactionID(), null);
285 private void handleCommitTransaction(final CommitTransaction commit) {
286 final String transactionID = commit.getTransactionID();
288 LOG.debug("{}: Committing transaction {}", persistenceId(), transactionID);
290 // Get the current in-progress cohort entry in the commitCoordinator if it corresponds to
292 final CohortEntry cohortEntry = commitCoordinator.getCohortEntryIfCurrent(transactionID);
293 if(cohortEntry == null) {
294 // We're not the current Tx - the Tx was likely expired b/c it took too long in
295 // between the canCommit and commit messages.
296 IllegalStateException ex = new IllegalStateException(
297 String.format("%s: Cannot commit transaction %s - it is not the current transaction",
298 persistenceId(), transactionID));
299 LOG.error(ex.getMessage());
300 shardMBean.incrementFailedTransactionsCount();
301 getSender().tell(new akka.actor.Status.Failure(ex), getSelf());
305 // We perform the preCommit phase here atomically with the commit phase. This is an
306 // optimization to eliminate the overhead of an extra preCommit message. We lose front-end
307 // coordination of preCommit across shards in case of failure but preCommit should not
308 // normally fail since we ensure only one concurrent 3-phase commit.
311 // We block on the future here so we don't have to worry about possibly accessing our
312 // state on a different thread outside of our dispatcher. Also, the data store
313 // currently uses a same thread executor anyway.
314 cohortEntry.getCohort().preCommit().get();
316 // If we do not have any followers and we are not using persistence we can
317 // apply modification to the state immediately
318 if(!hasFollowers() && !persistence().isRecoveryApplicable()){
319 applyModificationToState(getSender(), transactionID, cohortEntry.getModification());
321 Shard.this.persistData(getSender(), transactionID,
322 new ModificationPayload(cohortEntry.getModification()));
324 } catch (Exception e) {
325 LOG.error(e, "{} An exception occurred while preCommitting transaction {}",
326 persistenceId(), cohortEntry.getTransactionID());
327 shardMBean.incrementFailedTransactionsCount();
328 getSender().tell(new akka.actor.Status.Failure(e), getSelf());
331 cohortEntry.updateLastAccessTime();
334 private void finishCommit(@Nonnull final ActorRef sender, final @Nonnull String transactionID) {
335 // With persistence enabled, this method is called via applyState by the leader strategy
336 // after the commit has been replicated to a majority of the followers.
338 CohortEntry cohortEntry = commitCoordinator.getCohortEntryIfCurrent(transactionID);
339 if(cohortEntry == null) {
340 // The transaction is no longer the current commit. This can happen if the transaction
341 // was aborted prior, most likely due to timeout in the front-end. We need to finish
342 // committing the transaction though since it was successfully persisted and replicated
343 // however we can't use the original cohort b/c it was already preCommitted and may
344 // conflict with the current commit or may have been aborted so we commit with a new
346 cohortEntry = commitCoordinator.getAndRemoveCohortEntry(transactionID);
347 if(cohortEntry != null) {
348 commitWithNewTransaction(cohortEntry.getModification());
349 sender.tell(CommitTransactionReply.INSTANCE.toSerializable(), getSelf());
351 // This really shouldn't happen - it likely means that persistence or replication
352 // took so long to complete such that the cohort entry was expired from the cache.
353 IllegalStateException ex = new IllegalStateException(
354 String.format("%s: Could not finish committing transaction %s - no CohortEntry found",
355 persistenceId(), transactionID));
356 LOG.error(ex.getMessage());
357 sender.tell(new akka.actor.Status.Failure(ex), getSelf());
363 LOG.debug("{}: Finishing commit for transaction {}", persistenceId(), cohortEntry.getTransactionID());
366 // We block on the future here so we don't have to worry about possibly accessing our
367 // state on a different thread outside of our dispatcher. Also, the data store
368 // currently uses a same thread executor anyway.
369 cohortEntry.getCohort().commit().get();
371 sender.tell(CommitTransactionReply.INSTANCE.toSerializable(), getSelf());
373 shardMBean.incrementCommittedTransactionCount();
374 shardMBean.setLastCommittedTransactionTime(System.currentTimeMillis());
376 } catch (Exception e) {
377 sender.tell(new akka.actor.Status.Failure(e), getSelf());
379 LOG.error(e, "{}, An exception occurred while committing transaction {}", persistenceId(), transactionID);
380 shardMBean.incrementFailedTransactionsCount();
382 commitCoordinator.currentTransactionComplete(transactionID, true);
386 private void handleCanCommitTransaction(final CanCommitTransaction canCommit) {
387 LOG.debug("{}: Can committing transaction {}", persistenceId(), canCommit.getTransactionID());
388 commitCoordinator.handleCanCommit(canCommit, getSender(), self());
391 private void handleForwardedReadyTransaction(ForwardedReadyTransaction ready) {
392 LOG.debug("{}: Readying transaction {}, client version {}", persistenceId(),
393 ready.getTransactionID(), ready.getTxnClientVersion());
395 // This message is forwarded by the ShardTransaction on ready. We cache the cohort in the
396 // commitCoordinator in preparation for the subsequent three phase commit initiated by
398 commitCoordinator.transactionReady(ready.getTransactionID(), ready.getCohort(),
399 ready.getModification());
401 // Return our actor path as we'll handle the three phase commit, except if the Tx client
402 // version < 1 (Helium-1 version). This means the Tx was initiated by a base Helium version
403 // node. In that case, the subsequent 3-phase commit messages won't contain the
404 // transactionId so to maintain backwards compatibility, we create a separate cohort actor
405 // to provide the compatible behavior.
406 ActorRef replyActorPath = self();
407 if(ready.getTxnClientVersion() < DataStoreVersions.HELIUM_1_VERSION) {
408 LOG.debug("{}: Creating BackwardsCompatibleThreePhaseCommitCohort", persistenceId());
409 replyActorPath = getContext().actorOf(BackwardsCompatibleThreePhaseCommitCohort.props(
410 ready.getTransactionID()));
413 ReadyTransactionReply readyTransactionReply = new ReadyTransactionReply(
414 Serialization.serializedActorPath(replyActorPath));
415 getSender().tell(ready.isReturnSerialized() ? readyTransactionReply.toSerializable() :
416 readyTransactionReply, getSelf());
419 private void handleAbortTransaction(final AbortTransaction abort) {
420 doAbortTransaction(abort.getTransactionID(), getSender());
423 void doAbortTransaction(final String transactionID, final ActorRef sender) {
424 final CohortEntry cohortEntry = commitCoordinator.getCohortEntryIfCurrent(transactionID);
425 if(cohortEntry != null) {
426 LOG.debug("{}: Aborting transaction {}", persistenceId(), transactionID);
428 // We don't remove the cached cohort entry here (ie pass false) in case the Tx was
429 // aborted during replication in which case we may still commit locally if replication
431 commitCoordinator.currentTransactionComplete(transactionID, false);
433 final ListenableFuture<Void> future = cohortEntry.getCohort().abort();
434 final ActorRef self = getSelf();
436 Futures.addCallback(future, new FutureCallback<Void>() {
438 public void onSuccess(final Void v) {
439 shardMBean.incrementAbortTransactionsCount();
442 sender.tell(AbortTransactionReply.INSTANCE.toSerializable(), self);
447 public void onFailure(final Throwable t) {
448 LOG.error(t, "{}: An exception happened during abort", persistenceId());
451 sender.tell(new akka.actor.Status.Failure(t), self);
458 private void handleCreateTransaction(final Object message) {
460 createTransaction(CreateTransaction.fromSerializable(message));
461 } else if (getLeader() != null) {
462 getLeader().forward(message, getContext());
464 getSender().tell(new akka.actor.Status.Failure(new NoShardLeaderException(String.format(
465 "Could not find leader for shard %s so transaction cannot be created. This typically happens" +
466 " when the system is coming up or recovering and a leader is being elected. Try again" +
467 " later.", persistenceId()))), getSelf());
471 private void closeTransactionChain(final CloseTransactionChain closeTransactionChain) {
472 DOMStoreTransactionChain chain =
473 transactionChains.remove(closeTransactionChain.getTransactionChainId());
480 private ActorRef createTypedTransactionActor(int transactionType,
481 ShardTransactionIdentifier transactionId, String transactionChainId,
482 short clientVersion ) {
484 DOMStoreTransactionFactory factory = store;
486 if(!transactionChainId.isEmpty()) {
487 factory = transactionChains.get(transactionChainId);
489 DOMStoreTransactionChain transactionChain = store.createTransactionChain();
490 transactionChains.put(transactionChainId, transactionChain);
491 factory = transactionChain;
495 if(this.schemaContext == null) {
496 throw new IllegalStateException("SchemaContext is not set");
499 if (transactionType == TransactionProxy.TransactionType.READ_ONLY.ordinal()) {
501 shardMBean.incrementReadOnlyTransactionCount();
503 return getContext().actorOf(
504 ShardTransaction.props(factory.newReadOnlyTransaction(), getSelf(),
505 schemaContext,datastoreContext, shardMBean,
506 transactionId.getRemoteTransactionId(), clientVersion),
507 transactionId.toString());
509 } else if (transactionType == TransactionProxy.TransactionType.READ_WRITE.ordinal()) {
511 shardMBean.incrementReadWriteTransactionCount();
513 return getContext().actorOf(
514 ShardTransaction.props(factory.newReadWriteTransaction(), getSelf(),
515 schemaContext, datastoreContext, shardMBean,
516 transactionId.getRemoteTransactionId(), clientVersion),
517 transactionId.toString());
520 } else if (transactionType == TransactionProxy.TransactionType.WRITE_ONLY.ordinal()) {
522 shardMBean.incrementWriteOnlyTransactionCount();
524 return getContext().actorOf(
525 ShardTransaction.props(factory.newWriteOnlyTransaction(), getSelf(),
526 schemaContext, datastoreContext, shardMBean,
527 transactionId.getRemoteTransactionId(), clientVersion),
528 transactionId.toString());
530 throw new IllegalArgumentException(
531 "Shard="+name + ":CreateTransaction message has unidentified transaction type="
536 private void createTransaction(CreateTransaction createTransaction) {
538 ActorRef transactionActor = createTransaction(createTransaction.getTransactionType(),
539 createTransaction.getTransactionId(), createTransaction.getTransactionChainId(),
540 createTransaction.getVersion());
542 getSender().tell(new CreateTransactionReply(Serialization.serializedActorPath(transactionActor),
543 createTransaction.getTransactionId()).toSerializable(), getSelf());
544 } catch (Exception e) {
545 getSender().tell(new akka.actor.Status.Failure(e), getSelf());
549 private ActorRef createTransaction(int transactionType, String remoteTransactionId,
550 String transactionChainId, short clientVersion) {
552 ShardTransactionIdentifier transactionId =
553 ShardTransactionIdentifier.builder()
554 .remoteTransactionId(remoteTransactionId)
557 if(LOG.isDebugEnabled()) {
558 LOG.debug("{}: Creating transaction : {} ", persistenceId(), transactionId);
561 ActorRef transactionActor = createTypedTransactionActor(transactionType, transactionId,
562 transactionChainId, clientVersion);
564 return transactionActor;
567 private void syncCommitTransaction(final DOMStoreWriteTransaction transaction)
568 throws ExecutionException, InterruptedException {
569 DOMStoreThreePhaseCommitCohort commitCohort = transaction.ready();
570 commitCohort.preCommit().get();
571 commitCohort.commit().get();
574 private void commitWithNewTransaction(final Modification modification) {
575 DOMStoreWriteTransaction tx = store.newWriteOnlyTransaction();
576 modification.apply(tx);
578 syncCommitTransaction(tx);
579 shardMBean.incrementCommittedTransactionCount();
580 shardMBean.setLastCommittedTransactionTime(System.currentTimeMillis());
581 } catch (InterruptedException | ExecutionException e) {
582 shardMBean.incrementFailedTransactionsCount();
583 LOG.error(e, "{}: Failed to commit", persistenceId());
587 private void updateSchemaContext(final UpdateSchemaContext message) {
588 this.schemaContext = message.getSchemaContext();
589 updateSchemaContext(message.getSchemaContext());
590 store.onGlobalContextUpdated(message.getSchemaContext());
594 void updateSchemaContext(final SchemaContext schemaContext) {
595 store.onGlobalContextUpdated(schemaContext);
598 private void registerChangeListener(final RegisterChangeListener registerChangeListener) {
600 LOG.debug("{}: registerDataChangeListener for {}", persistenceId(), registerChangeListener.getPath());
602 ListenerRegistration<AsyncDataChangeListener<YangInstanceIdentifier,
603 NormalizedNode<?, ?>>> registration;
605 registration = doChangeListenerRegistration(registerChangeListener);
607 LOG.debug("{}: Shard is not the leader - delaying registration", persistenceId());
609 DelayedListenerRegistration delayedReg =
610 new DelayedListenerRegistration(registerChangeListener);
611 delayedListenerRegistrations.add(delayedReg);
612 registration = delayedReg;
615 ActorRef listenerRegistration = getContext().actorOf(
616 DataChangeListenerRegistration.props(registration));
618 LOG.debug("{}: registerDataChangeListener sending reply, listenerRegistrationPath = {} ",
619 persistenceId(), listenerRegistration.path());
621 getSender().tell(new RegisterChangeListenerReply(listenerRegistration.path()), getSelf());
624 private ListenerRegistration<AsyncDataChangeListener<YangInstanceIdentifier,
625 NormalizedNode<?, ?>>> doChangeListenerRegistration(
626 final RegisterChangeListener registerChangeListener) {
628 ActorSelection dataChangeListenerPath = getContext().system().actorSelection(
629 registerChangeListener.getDataChangeListenerPath());
631 // Notify the listener if notifications should be enabled or not
632 // If this shard is the leader then it will enable notifications else
634 dataChangeListenerPath.tell(new EnableNotification(true), getSelf());
636 // Now store a reference to the data change listener so it can be notified
637 // at a later point if notifications should be enabled or disabled
638 dataChangeListeners.add(dataChangeListenerPath);
640 AsyncDataChangeListener<YangInstanceIdentifier, NormalizedNode<?, ?>> listener =
641 new DataChangeListenerProxy(dataChangeListenerPath);
643 LOG.debug("{}: Registering for path {}", persistenceId(), registerChangeListener.getPath());
645 return store.registerChangeListener(registerChangeListener.getPath(), listener,
646 registerChangeListener.getScope());
649 private boolean isMetricsCaptureEnabled(){
650 CommonConfig config = new CommonConfig(getContext().system().settings().config());
651 return config.isMetricCaptureEnabled();
656 void startLogRecoveryBatch(final int maxBatchSize) {
657 currentLogRecoveryBatch = Lists.newArrayListWithCapacity(maxBatchSize);
659 if(LOG.isDebugEnabled()) {
660 LOG.debug("{}: starting log recovery batch with max size {}", persistenceId(), maxBatchSize);
665 protected void appendRecoveredLogEntry(final Payload data) {
666 if(data instanceof ModificationPayload) {
668 currentLogRecoveryBatch.add(((ModificationPayload) data).getModification());
669 } catch (ClassNotFoundException | IOException e) {
670 LOG.error(e, "{}: Error extracting ModificationPayload", persistenceId());
672 } else if (data instanceof CompositeModificationPayload) {
673 currentLogRecoveryBatch.add(((CompositeModificationPayload) data).getModification());
674 } else if (data instanceof CompositeModificationByteStringPayload) {
675 currentLogRecoveryBatch.add(((CompositeModificationByteStringPayload) data).getModification());
677 LOG.error("{}: Unknown state received {} during recovery", persistenceId(), data);
682 protected void applyRecoverySnapshot(final byte[] snapshotBytes) {
683 if(recoveryCoordinator == null) {
684 recoveryCoordinator = new ShardRecoveryCoordinator(persistenceId(), schemaContext,
685 LOG, name.toString());
688 recoveryCoordinator.submit(snapshotBytes, store.newWriteOnlyTransaction());
690 if(LOG.isDebugEnabled()) {
691 LOG.debug("{}: submitted recovery sbapshot", persistenceId());
696 protected void applyCurrentLogRecoveryBatch() {
697 if(recoveryCoordinator == null) {
698 recoveryCoordinator = new ShardRecoveryCoordinator(persistenceId(), schemaContext,
699 LOG, name.toString());
702 recoveryCoordinator.submit(currentLogRecoveryBatch, store.newWriteOnlyTransaction());
704 if(LOG.isDebugEnabled()) {
705 LOG.debug("{}: submitted log recovery batch with size {}", persistenceId(),
706 currentLogRecoveryBatch.size());
711 protected void onRecoveryComplete() {
712 if(recoveryCoordinator != null) {
713 Collection<DOMStoreWriteTransaction> txList = recoveryCoordinator.getTransactions();
715 if(LOG.isDebugEnabled()) {
716 LOG.debug("{}: recovery complete - committing {} Tx's", persistenceId(), txList.size());
719 for(DOMStoreWriteTransaction tx: txList) {
721 syncCommitTransaction(tx);
722 shardMBean.incrementCommittedTransactionCount();
723 } catch (InterruptedException | ExecutionException e) {
724 shardMBean.incrementFailedTransactionsCount();
725 LOG.error(e, "{}: Failed to commit", persistenceId());
730 recoveryCoordinator = null;
731 currentLogRecoveryBatch = null;
732 updateJournalStats();
734 //notify shard manager
735 getContext().parent().tell(new ActorInitialized(), getSelf());
737 // Being paranoid here - this method should only be called once but just in case...
738 if(txCommitTimeoutCheckSchedule == null) {
739 // Schedule a message to be periodically sent to check if the current in-progress
740 // transaction should be expired and aborted.
741 FiniteDuration period = Duration.create(transactionCommitTimeout / 3, TimeUnit.MILLISECONDS);
742 txCommitTimeoutCheckSchedule = getContext().system().scheduler().schedule(
743 period, period, getSelf(),
744 TX_COMMIT_TIMEOUT_CHECK_MESSAGE, getContext().dispatcher(), ActorRef.noSender());
749 protected void applyState(final ActorRef clientActor, final String identifier, final Object data) {
751 if(data instanceof ModificationPayload) {
753 applyModificationToState(clientActor, identifier, ((ModificationPayload) data).getModification());
754 } catch (ClassNotFoundException | IOException e) {
755 LOG.error(e, "{}: Error extracting ModificationPayload", persistenceId());
758 else if (data instanceof CompositeModificationPayload) {
759 Object modification = ((CompositeModificationPayload) data).getModification();
761 applyModificationToState(clientActor, identifier, modification);
762 } else if(data instanceof CompositeModificationByteStringPayload ){
763 Object modification = ((CompositeModificationByteStringPayload) data).getModification();
765 applyModificationToState(clientActor, identifier, modification);
767 LOG.error("{}: Unknown state received {} Class loader = {} CompositeNodeMod.ClassLoader = {}",
768 persistenceId(), data, data.getClass().getClassLoader(),
769 CompositeModificationPayload.class.getClassLoader());
772 updateJournalStats();
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);
791 private void updateJournalStats() {
792 ReplicatedLogEntry lastLogEntry = getLastLogEntry();
794 if (lastLogEntry != null) {
795 shardMBean.setLastLogIndex(lastLogEntry.getIndex());
796 shardMBean.setLastLogTerm(lastLogEntry.getTerm());
799 shardMBean.setCommitIndex(getCommitIndex());
800 shardMBean.setLastApplied(getLastApplied());
801 shardMBean.setInMemoryJournalDataSize(getRaftActorContext().getReplicatedLog().dataSize());
805 protected void createSnapshot() {
806 // Create a transaction actor. We are really going to treat the transaction as a worker
807 // so that this actor does not get block building the snapshot. THe transaction actor will
808 // after processing the CreateSnapshot message.
810 ActorRef createSnapshotTransaction = createTransaction(
811 TransactionProxy.TransactionType.READ_ONLY.ordinal(),
812 "createSnapshot" + ++createSnapshotTransactionCounter, "",
813 DataStoreVersions.CURRENT_VERSION);
815 createSnapshotTransaction.tell(CreateSnapshot.INSTANCE, self());
820 protected void applySnapshot(final byte[] snapshotBytes) {
821 // Since this will be done only on Recovery or when this actor is a Follower
822 // we can safely commit everything in here. We not need to worry about event notifications
823 // as they would have already been disabled on the follower
825 LOG.info("{}: Applying snapshot", persistenceId());
827 DOMStoreWriteTransaction transaction = store.newWriteOnlyTransaction();
829 NormalizedNode<?, ?> node = SerializationUtils.deserializeNormalizedNode(snapshotBytes);
831 // delete everything first
832 transaction.delete(DATASTORE_ROOT);
834 // Add everything from the remote node back
835 transaction.write(DATASTORE_ROOT, node);
836 syncCommitTransaction(transaction);
837 } catch (InterruptedException | ExecutionException e) {
838 LOG.error(e, "{}: An exception occurred when applying snapshot", persistenceId());
840 LOG.info("{}: Done applying snapshot", persistenceId());
845 protected void onStateChanged() {
846 boolean isLeader = isLeader();
847 for (ActorSelection dataChangeListener : dataChangeListeners) {
848 dataChangeListener.tell(new EnableNotification(isLeader), getSelf());
852 for(DelayedListenerRegistration reg: delayedListenerRegistrations) {
853 if(!reg.isClosed()) {
854 reg.setDelegate(doChangeListenerRegistration(reg.getRegisterChangeListener()));
858 delayedListenerRegistrations.clear();
861 shardMBean.setRaftState(getRaftState().name());
862 shardMBean.setCurrentTerm(getCurrentTerm());
864 // If this actor is no longer the leader close all the transaction chains
866 for(Map.Entry<String, DOMStoreTransactionChain> entry : transactionChains.entrySet()){
867 if(LOG.isDebugEnabled()) {
869 "{}: onStateChanged: Closing transaction chain {} because shard {} is no longer the leader",
870 persistenceId(), entry.getKey(), getId());
872 entry.getValue().close();
875 transactionChains.clear();
880 protected DataPersistenceProvider persistence() {
881 return dataPersistenceProvider;
884 @Override protected void onLeaderChanged(final String oldLeader, final String newLeader) {
885 shardMBean.setLeader(newLeader);
888 @Override public String persistenceId() {
889 return this.name.toString();
893 DataPersistenceProvider getDataPersistenceProvider() {
894 return dataPersistenceProvider;
897 private static class ShardCreator implements Creator<Shard> {
899 private static final long serialVersionUID = 1L;
901 final ShardIdentifier name;
902 final Map<ShardIdentifier, String> peerAddresses;
903 final DatastoreContext datastoreContext;
904 final SchemaContext schemaContext;
906 ShardCreator(final ShardIdentifier name, final Map<ShardIdentifier, String> peerAddresses,
907 final DatastoreContext datastoreContext, final SchemaContext schemaContext) {
909 this.peerAddresses = peerAddresses;
910 this.datastoreContext = datastoreContext;
911 this.schemaContext = schemaContext;
915 public Shard create() throws Exception {
916 return new Shard(name, peerAddresses, datastoreContext, schemaContext);
921 InMemoryDOMDataStore getDataStore() {
926 ShardStats getShardMBean() {
930 private static class DelayedListenerRegistration implements
931 ListenerRegistration<AsyncDataChangeListener<YangInstanceIdentifier, NormalizedNode<?, ?>>> {
933 private volatile boolean closed;
935 private final RegisterChangeListener registerChangeListener;
937 private volatile ListenerRegistration<AsyncDataChangeListener<YangInstanceIdentifier,
938 NormalizedNode<?, ?>>> delegate;
940 DelayedListenerRegistration(final RegisterChangeListener registerChangeListener) {
941 this.registerChangeListener = registerChangeListener;
944 void setDelegate( final ListenerRegistration<AsyncDataChangeListener<YangInstanceIdentifier,
945 NormalizedNode<?, ?>>> registration) {
946 this.delegate = registration;
953 RegisterChangeListener getRegisterChangeListener() {
954 return registerChangeListener;
958 public AsyncDataChangeListener<YangInstanceIdentifier, NormalizedNode<?, ?>> getInstance() {
959 return delegate != null ? delegate.getInstance() : null;
963 public void close() {
965 if(delegate != null) {