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.SerializationUtils;
64 import org.opendaylight.controller.cluster.notifications.RoleChangeNotifier;
65 import org.opendaylight.controller.cluster.raft.RaftActor;
66 import org.opendaylight.controller.cluster.raft.ReplicatedLogEntry;
67 import org.opendaylight.controller.cluster.raft.protobuff.client.messages.CompositeModificationByteStringPayload;
68 import org.opendaylight.controller.cluster.raft.protobuff.client.messages.CompositeModificationPayload;
69 import org.opendaylight.controller.cluster.raft.protobuff.client.messages.Payload;
70 import org.opendaylight.controller.md.sal.common.api.data.AsyncDataChangeListener;
71 import org.opendaylight.controller.md.sal.dom.store.impl.InMemoryDOMDataStore;
72 import org.opendaylight.controller.md.sal.dom.store.impl.InMemoryDOMDataStoreFactory;
73 import org.opendaylight.controller.sal.core.spi.data.DOMStoreThreePhaseCommitCohort;
74 import org.opendaylight.controller.sal.core.spi.data.DOMStoreTransactionChain;
75 import org.opendaylight.controller.sal.core.spi.data.DOMStoreTransactionFactory;
76 import org.opendaylight.controller.sal.core.spi.data.DOMStoreWriteTransaction;
77 import org.opendaylight.yangtools.concepts.ListenerRegistration;
78 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
79 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
80 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
81 import scala.concurrent.duration.Duration;
82 import scala.concurrent.duration.FiniteDuration;
85 * A Shard represents a portion of the logical data tree <br/>
87 * Our Shard uses InMemoryDataStore as it's internal representation and delegates all requests it
90 public class Shard extends RaftActor {
92 private static final YangInstanceIdentifier DATASTORE_ROOT = YangInstanceIdentifier.builder().build();
94 private static final Object TX_COMMIT_TIMEOUT_CHECK_MESSAGE = "txCommitTimeoutCheck";
97 static final String DEFAULT_NAME = "default";
99 // The state of this Shard
100 private final InMemoryDOMDataStore store;
102 /// The name of this shard
103 private final ShardIdentifier name;
105 private final ShardStats shardMBean;
107 private final List<ActorSelection> dataChangeListeners = Lists.newArrayList();
109 private final List<DelayedListenerRegistration> delayedListenerRegistrations =
110 Lists.newArrayList();
112 private final DatastoreContext datastoreContext;
114 private final DataPersistenceProvider dataPersistenceProvider;
116 private SchemaContext schemaContext;
118 private int createSnapshotTransactionCounter;
120 private final ShardCommitCoordinator commitCoordinator;
122 private final long transactionCommitTimeout;
124 private Cancellable txCommitTimeoutCheckSchedule;
126 private final Optional<ActorRef> roleChangeNotifier;
129 * Coordinates persistence recovery on startup.
131 private ShardRecoveryCoordinator recoveryCoordinator;
132 private List<Object> currentLogRecoveryBatch;
134 private final Map<String, DOMStoreTransactionChain> transactionChains = new HashMap<>();
136 protected Shard(final ShardIdentifier name, final Map<ShardIdentifier, String> peerAddresses,
137 final DatastoreContext datastoreContext, final SchemaContext schemaContext) {
138 super(name.toString(), mapPeerAddresses(peerAddresses),
139 Optional.of(datastoreContext.getShardRaftConfig()));
142 this.datastoreContext = datastoreContext;
143 this.schemaContext = schemaContext;
144 this.dataPersistenceProvider = (datastoreContext.isPersistent()) ? new PersistentDataProvider() : new NonPersistentRaftDataProvider();
146 LOG.info("Shard created : {}, persistent : {}", name, datastoreContext.isPersistent());
148 store = InMemoryDOMDataStoreFactory.create(name.toString(), null,
149 datastoreContext.getDataStoreProperties());
151 if(schemaContext != null) {
152 store.onGlobalContextUpdated(schemaContext);
155 shardMBean = ShardMBeanFactory.getShardStatsMBean(name.toString(),
156 datastoreContext.getDataStoreMXBeanType());
157 shardMBean.setNotificationManager(store.getDataChangeListenerNotificationManager());
159 if (isMetricsCaptureEnabled()) {
160 getContext().become(new MeteringBehavior(this));
163 commitCoordinator = new ShardCommitCoordinator(TimeUnit.SECONDS.convert(1, TimeUnit.MINUTES),
164 datastoreContext.getShardTransactionCommitQueueCapacity(), LOG, name.toString());
166 transactionCommitTimeout = TimeUnit.MILLISECONDS.convert(
167 datastoreContext.getShardTransactionCommitTimeoutInSeconds(), TimeUnit.SECONDS);
169 // create a notifier actor for each cluster member
170 roleChangeNotifier = createRoleChangeNotifier(name.toString());
173 private static Map<String, String> mapPeerAddresses(
174 final Map<ShardIdentifier, String> peerAddresses) {
175 Map<String, String> map = new HashMap<>();
177 for (Map.Entry<ShardIdentifier, String> entry : peerAddresses
179 map.put(entry.getKey().toString(), entry.getValue());
185 public static Props props(final ShardIdentifier name,
186 final Map<ShardIdentifier, String> peerAddresses,
187 final DatastoreContext datastoreContext, final SchemaContext schemaContext) {
188 Preconditions.checkNotNull(name, "name should not be null");
189 Preconditions.checkNotNull(peerAddresses, "peerAddresses should not be null");
190 Preconditions.checkNotNull(datastoreContext, "dataStoreContext should not be null");
191 Preconditions.checkNotNull(schemaContext, "schemaContext should not be null");
193 return Props.create(new ShardCreator(name, peerAddresses, datastoreContext, schemaContext));
196 private Optional<ActorRef> createRoleChangeNotifier(String shardId) {
197 ActorRef shardRoleChangeNotifier = this.getContext().actorOf(
198 RoleChangeNotifier.getProps(shardId), shardId + "-notifier");
199 return Optional.<ActorRef>of(shardRoleChangeNotifier);
203 public void postStop() {
206 if(txCommitTimeoutCheckSchedule != null) {
207 txCommitTimeoutCheckSchedule.cancel();
212 public void onReceiveRecover(final Object message) throws Exception {
213 if(LOG.isDebugEnabled()) {
214 LOG.debug("{}: onReceiveRecover: Received message {} from {}", persistenceId(),
215 message.getClass().toString(), getSender());
218 if (message instanceof RecoveryFailure){
219 LOG.error("{}: Recovery failed because of this cause",
220 persistenceId(), ((RecoveryFailure) message).cause());
222 // Even though recovery failed, we still need to finish our recovery, eg send the
223 // ActorInitialized message and start the txCommitTimeoutCheckSchedule.
224 onRecoveryComplete();
226 super.onReceiveRecover(message);
231 public void onReceiveCommand(final Object message) throws Exception {
232 if (message.getClass().equals(CreateTransaction.SERIALIZABLE_CLASS)) {
233 handleCreateTransaction(message);
234 } else if(message instanceof ForwardedReadyTransaction) {
235 handleForwardedReadyTransaction((ForwardedReadyTransaction)message);
236 } else if(message.getClass().equals(CanCommitTransaction.SERIALIZABLE_CLASS)) {
237 handleCanCommitTransaction(CanCommitTransaction.fromSerializable(message));
238 } else if(message.getClass().equals(CommitTransaction.SERIALIZABLE_CLASS)) {
239 handleCommitTransaction(CommitTransaction.fromSerializable(message));
240 } else if(message.getClass().equals(AbortTransaction.SERIALIZABLE_CLASS)) {
241 handleAbortTransaction(AbortTransaction.fromSerializable(message));
242 } else if (message.getClass().equals(CloseTransactionChain.SERIALIZABLE_CLASS)){
243 closeTransactionChain(CloseTransactionChain.fromSerializable(message));
244 } else if (message instanceof RegisterChangeListener) {
245 registerChangeListener((RegisterChangeListener) message);
246 } else if (message instanceof UpdateSchemaContext) {
247 updateSchemaContext((UpdateSchemaContext) message);
248 } else if (message instanceof PeerAddressResolved) {
249 PeerAddressResolved resolved = (PeerAddressResolved) message;
250 setPeerAddress(resolved.getPeerId().toString(),
251 resolved.getPeerAddress());
252 } else if(message.equals(TX_COMMIT_TIMEOUT_CHECK_MESSAGE)) {
253 handleTransactionCommitTimeoutCheck();
255 super.onReceiveCommand(message);
260 protected Optional<ActorRef> getRoleChangeNotifier() {
261 return roleChangeNotifier;
264 private void handleTransactionCommitTimeoutCheck() {
265 CohortEntry cohortEntry = commitCoordinator.getCurrentCohortEntry();
266 if(cohortEntry != null) {
267 long elapsed = System.currentTimeMillis() - cohortEntry.getLastAccessTime();
268 if(elapsed > transactionCommitTimeout) {
269 LOG.warn("{}: Current transaction {} has timed out after {} ms - aborting",
270 persistenceId(), cohortEntry.getTransactionID(), transactionCommitTimeout);
272 doAbortTransaction(cohortEntry.getTransactionID(), null);
277 private void handleCommitTransaction(final CommitTransaction commit) {
278 final String transactionID = commit.getTransactionID();
280 LOG.debug("{}: Committing transaction {}", persistenceId(), transactionID);
282 // Get the current in-progress cohort entry in the commitCoordinator if it corresponds to
284 final CohortEntry cohortEntry = commitCoordinator.getCohortEntryIfCurrent(transactionID);
285 if(cohortEntry == null) {
286 // We're not the current Tx - the Tx was likely expired b/c it took too long in
287 // between the canCommit and commit messages.
288 IllegalStateException ex = new IllegalStateException(
289 String.format("%s: Cannot commit transaction %s - it is not the current transaction",
290 persistenceId(), transactionID));
291 LOG.error(ex.getMessage());
292 shardMBean.incrementFailedTransactionsCount();
293 getSender().tell(new akka.actor.Status.Failure(ex), getSelf());
297 // We perform the preCommit phase here atomically with the commit phase. This is an
298 // optimization to eliminate the overhead of an extra preCommit message. We lose front-end
299 // coordination of preCommit across shards in case of failure but preCommit should not
300 // normally fail since we ensure only one concurrent 3-phase commit.
303 // We block on the future here so we don't have to worry about possibly accessing our
304 // state on a different thread outside of our dispatcher. Also, the data store
305 // currently uses a same thread executor anyway.
306 cohortEntry.getCohort().preCommit().get();
308 // If we do not have any followers and we are not using persistence we can
309 // apply modification to the state immediately
310 if(!hasFollowers() && !persistence().isRecoveryApplicable()){
311 applyModificationToState(getSender(), transactionID, cohortEntry.getModification());
313 Shard.this.persistData(getSender(), transactionID,
314 new ModificationPayload(cohortEntry.getModification()));
316 } catch (Exception e) {
317 LOG.error("{} An exception occurred while preCommitting transaction {}",
318 persistenceId(), cohortEntry.getTransactionID(), e);
319 shardMBean.incrementFailedTransactionsCount();
320 getSender().tell(new akka.actor.Status.Failure(e), getSelf());
323 cohortEntry.updateLastAccessTime();
326 private void finishCommit(@Nonnull final ActorRef sender, final @Nonnull String transactionID) {
327 // With persistence enabled, this method is called via applyState by the leader strategy
328 // after the commit has been replicated to a majority of the followers.
330 CohortEntry cohortEntry = commitCoordinator.getCohortEntryIfCurrent(transactionID);
331 if(cohortEntry == null) {
332 // The transaction is no longer the current commit. This can happen if the transaction
333 // was aborted prior, most likely due to timeout in the front-end. We need to finish
334 // committing the transaction though since it was successfully persisted and replicated
335 // however we can't use the original cohort b/c it was already preCommitted and may
336 // conflict with the current commit or may have been aborted so we commit with a new
338 cohortEntry = commitCoordinator.getAndRemoveCohortEntry(transactionID);
339 if(cohortEntry != null) {
340 commitWithNewTransaction(cohortEntry.getModification());
341 sender.tell(CommitTransactionReply.INSTANCE.toSerializable(), getSelf());
343 // This really shouldn't happen - it likely means that persistence or replication
344 // took so long to complete such that the cohort entry was expired from the cache.
345 IllegalStateException ex = new IllegalStateException(
346 String.format("%s: Could not finish committing transaction %s - no CohortEntry found",
347 persistenceId(), transactionID));
348 LOG.error(ex.getMessage());
349 sender.tell(new akka.actor.Status.Failure(ex), getSelf());
355 LOG.debug("{}: Finishing commit for transaction {}", persistenceId(), cohortEntry.getTransactionID());
358 // We block on the future here so we don't have to worry about possibly accessing our
359 // state on a different thread outside of our dispatcher. Also, the data store
360 // currently uses a same thread executor anyway.
361 cohortEntry.getCohort().commit().get();
363 sender.tell(CommitTransactionReply.INSTANCE.toSerializable(), getSelf());
365 shardMBean.incrementCommittedTransactionCount();
366 shardMBean.setLastCommittedTransactionTime(System.currentTimeMillis());
368 } catch (Exception e) {
369 sender.tell(new akka.actor.Status.Failure(e), getSelf());
371 LOG.error("{}, An exception occurred while committing transaction {}", persistenceId(),
373 shardMBean.incrementFailedTransactionsCount();
375 commitCoordinator.currentTransactionComplete(transactionID, true);
379 private void handleCanCommitTransaction(final CanCommitTransaction canCommit) {
380 LOG.debug("{}: Can committing transaction {}", persistenceId(), canCommit.getTransactionID());
381 commitCoordinator.handleCanCommit(canCommit, getSender(), self());
384 private void handleForwardedReadyTransaction(ForwardedReadyTransaction ready) {
385 LOG.debug("{}: Readying transaction {}, client version {}", persistenceId(),
386 ready.getTransactionID(), ready.getTxnClientVersion());
388 // This message is forwarded by the ShardTransaction on ready. We cache the cohort in the
389 // commitCoordinator in preparation for the subsequent three phase commit initiated by
391 commitCoordinator.transactionReady(ready.getTransactionID(), ready.getCohort(),
392 ready.getModification());
394 // Return our actor path as we'll handle the three phase commit, except if the Tx client
395 // version < 1 (Helium-1 version). This means the Tx was initiated by a base Helium version
396 // node. In that case, the subsequent 3-phase commit messages won't contain the
397 // transactionId so to maintain backwards compatibility, we create a separate cohort actor
398 // to provide the compatible behavior.
399 ActorRef replyActorPath = self();
400 if(ready.getTxnClientVersion() < DataStoreVersions.HELIUM_1_VERSION) {
401 LOG.debug("{}: Creating BackwardsCompatibleThreePhaseCommitCohort", persistenceId());
402 replyActorPath = getContext().actorOf(BackwardsCompatibleThreePhaseCommitCohort.props(
403 ready.getTransactionID()));
406 ReadyTransactionReply readyTransactionReply = new ReadyTransactionReply(
407 Serialization.serializedActorPath(replyActorPath));
408 getSender().tell(ready.isReturnSerialized() ? readyTransactionReply.toSerializable() :
409 readyTransactionReply, getSelf());
412 private void handleAbortTransaction(final AbortTransaction abort) {
413 doAbortTransaction(abort.getTransactionID(), getSender());
416 void doAbortTransaction(final String transactionID, final ActorRef sender) {
417 final CohortEntry cohortEntry = commitCoordinator.getCohortEntryIfCurrent(transactionID);
418 if(cohortEntry != null) {
419 LOG.debug("{}: Aborting transaction {}", persistenceId(), transactionID);
421 // We don't remove the cached cohort entry here (ie pass false) in case the Tx was
422 // aborted during replication in which case we may still commit locally if replication
424 commitCoordinator.currentTransactionComplete(transactionID, false);
426 final ListenableFuture<Void> future = cohortEntry.getCohort().abort();
427 final ActorRef self = getSelf();
429 Futures.addCallback(future, new FutureCallback<Void>() {
431 public void onSuccess(final Void v) {
432 shardMBean.incrementAbortTransactionsCount();
435 sender.tell(AbortTransactionReply.INSTANCE.toSerializable(), self);
440 public void onFailure(final Throwable t) {
441 LOG.error("{}: An exception happened during abort", persistenceId(), t);
444 sender.tell(new akka.actor.Status.Failure(t), self);
451 private void handleCreateTransaction(final Object message) {
453 createTransaction(CreateTransaction.fromSerializable(message));
454 } else if (getLeader() != null) {
455 getLeader().forward(message, getContext());
457 getSender().tell(new akka.actor.Status.Failure(new NoShardLeaderException(String.format(
458 "Could not find leader for shard %s so transaction cannot be created. This typically happens" +
459 " when the system is coming up or recovering and a leader is being elected. Try again" +
460 " later.", persistenceId()))), getSelf());
464 private void closeTransactionChain(final CloseTransactionChain closeTransactionChain) {
465 DOMStoreTransactionChain chain =
466 transactionChains.remove(closeTransactionChain.getTransactionChainId());
473 private ActorRef createTypedTransactionActor(int transactionType,
474 ShardTransactionIdentifier transactionId, String transactionChainId,
475 short clientVersion ) {
477 DOMStoreTransactionFactory factory = store;
479 if(!transactionChainId.isEmpty()) {
480 factory = transactionChains.get(transactionChainId);
482 DOMStoreTransactionChain transactionChain = store.createTransactionChain();
483 transactionChains.put(transactionChainId, transactionChain);
484 factory = transactionChain;
488 if(this.schemaContext == null) {
489 throw new IllegalStateException("SchemaContext is not set");
492 if (transactionType == TransactionProxy.TransactionType.READ_ONLY.ordinal()) {
494 shardMBean.incrementReadOnlyTransactionCount();
496 return getContext().actorOf(
497 ShardTransaction.props(factory.newReadOnlyTransaction(), getSelf(),
498 schemaContext,datastoreContext, shardMBean,
499 transactionId.getRemoteTransactionId(), clientVersion),
500 transactionId.toString());
502 } else if (transactionType == TransactionProxy.TransactionType.READ_WRITE.ordinal()) {
504 shardMBean.incrementReadWriteTransactionCount();
506 return getContext().actorOf(
507 ShardTransaction.props(factory.newReadWriteTransaction(), getSelf(),
508 schemaContext, datastoreContext, shardMBean,
509 transactionId.getRemoteTransactionId(), clientVersion),
510 transactionId.toString());
513 } else if (transactionType == TransactionProxy.TransactionType.WRITE_ONLY.ordinal()) {
515 shardMBean.incrementWriteOnlyTransactionCount();
517 return getContext().actorOf(
518 ShardTransaction.props(factory.newWriteOnlyTransaction(), getSelf(),
519 schemaContext, datastoreContext, shardMBean,
520 transactionId.getRemoteTransactionId(), clientVersion),
521 transactionId.toString());
523 throw new IllegalArgumentException(
524 "Shard="+name + ":CreateTransaction message has unidentified transaction type="
529 private void createTransaction(CreateTransaction createTransaction) {
531 ActorRef transactionActor = createTransaction(createTransaction.getTransactionType(),
532 createTransaction.getTransactionId(), createTransaction.getTransactionChainId(),
533 createTransaction.getVersion());
535 getSender().tell(new CreateTransactionReply(Serialization.serializedActorPath(transactionActor),
536 createTransaction.getTransactionId()).toSerializable(), getSelf());
537 } catch (Exception e) {
538 getSender().tell(new akka.actor.Status.Failure(e), getSelf());
542 private ActorRef createTransaction(int transactionType, String remoteTransactionId,
543 String transactionChainId, short clientVersion) {
545 ShardTransactionIdentifier transactionId =
546 ShardTransactionIdentifier.builder()
547 .remoteTransactionId(remoteTransactionId)
550 if(LOG.isDebugEnabled()) {
551 LOG.debug("{}: Creating transaction : {} ", persistenceId(), transactionId);
554 ActorRef transactionActor = createTypedTransactionActor(transactionType, transactionId,
555 transactionChainId, clientVersion);
557 return transactionActor;
560 private void syncCommitTransaction(final DOMStoreWriteTransaction transaction)
561 throws ExecutionException, InterruptedException {
562 DOMStoreThreePhaseCommitCohort commitCohort = transaction.ready();
563 commitCohort.preCommit().get();
564 commitCohort.commit().get();
567 private void commitWithNewTransaction(final Modification modification) {
568 DOMStoreWriteTransaction tx = store.newWriteOnlyTransaction();
569 modification.apply(tx);
571 syncCommitTransaction(tx);
572 shardMBean.incrementCommittedTransactionCount();
573 shardMBean.setLastCommittedTransactionTime(System.currentTimeMillis());
574 } catch (InterruptedException | ExecutionException e) {
575 shardMBean.incrementFailedTransactionsCount();
576 LOG.error("{}: Failed to commit", persistenceId(), e);
580 private void updateSchemaContext(final UpdateSchemaContext message) {
581 this.schemaContext = message.getSchemaContext();
582 updateSchemaContext(message.getSchemaContext());
583 store.onGlobalContextUpdated(message.getSchemaContext());
587 void updateSchemaContext(final SchemaContext schemaContext) {
588 store.onGlobalContextUpdated(schemaContext);
591 private void registerChangeListener(final RegisterChangeListener registerChangeListener) {
593 LOG.debug("{}: registerDataChangeListener for {}", persistenceId(), registerChangeListener.getPath());
595 ListenerRegistration<AsyncDataChangeListener<YangInstanceIdentifier,
596 NormalizedNode<?, ?>>> registration;
598 registration = doChangeListenerRegistration(registerChangeListener);
600 LOG.debug("{}: Shard is not the leader - delaying registration", persistenceId());
602 DelayedListenerRegistration delayedReg =
603 new DelayedListenerRegistration(registerChangeListener);
604 delayedListenerRegistrations.add(delayedReg);
605 registration = delayedReg;
608 ActorRef listenerRegistration = getContext().actorOf(
609 DataChangeListenerRegistration.props(registration));
611 LOG.debug("{}: registerDataChangeListener sending reply, listenerRegistrationPath = {} ",
612 persistenceId(), listenerRegistration.path());
614 getSender().tell(new RegisterChangeListenerReply(listenerRegistration.path()), getSelf());
617 private ListenerRegistration<AsyncDataChangeListener<YangInstanceIdentifier,
618 NormalizedNode<?, ?>>> doChangeListenerRegistration(
619 final RegisterChangeListener registerChangeListener) {
621 ActorSelection dataChangeListenerPath = getContext().system().actorSelection(
622 registerChangeListener.getDataChangeListenerPath());
624 // Notify the listener if notifications should be enabled or not
625 // If this shard is the leader then it will enable notifications else
627 dataChangeListenerPath.tell(new EnableNotification(true), getSelf());
629 // Now store a reference to the data change listener so it can be notified
630 // at a later point if notifications should be enabled or disabled
631 dataChangeListeners.add(dataChangeListenerPath);
633 AsyncDataChangeListener<YangInstanceIdentifier, NormalizedNode<?, ?>> listener =
634 new DataChangeListenerProxy(dataChangeListenerPath);
636 LOG.debug("{}: Registering for path {}", persistenceId(), registerChangeListener.getPath());
638 return store.registerChangeListener(registerChangeListener.getPath(), listener,
639 registerChangeListener.getScope());
642 private boolean isMetricsCaptureEnabled(){
643 CommonConfig config = new CommonConfig(getContext().system().settings().config());
644 return config.isMetricCaptureEnabled();
649 void startLogRecoveryBatch(final int maxBatchSize) {
650 currentLogRecoveryBatch = Lists.newArrayListWithCapacity(maxBatchSize);
652 if(LOG.isDebugEnabled()) {
653 LOG.debug("{}: starting log recovery batch with max size {}", persistenceId(), maxBatchSize);
658 protected void appendRecoveredLogEntry(final Payload data) {
659 if(data instanceof ModificationPayload) {
661 currentLogRecoveryBatch.add(((ModificationPayload) data).getModification());
662 } catch (ClassNotFoundException | IOException e) {
663 LOG.error("{}: Error extracting ModificationPayload", persistenceId(), e);
665 } else if (data instanceof CompositeModificationPayload) {
666 currentLogRecoveryBatch.add(((CompositeModificationPayload) data).getModification());
667 } else if (data instanceof CompositeModificationByteStringPayload) {
668 currentLogRecoveryBatch.add(((CompositeModificationByteStringPayload) data).getModification());
670 LOG.error("{}: Unknown state received {} during recovery", persistenceId(), data);
675 protected void applyRecoverySnapshot(final byte[] snapshotBytes) {
676 if(recoveryCoordinator == null) {
677 recoveryCoordinator = new ShardRecoveryCoordinator(persistenceId(), schemaContext,
678 LOG, name.toString());
681 recoveryCoordinator.submit(snapshotBytes, store.newWriteOnlyTransaction());
683 if(LOG.isDebugEnabled()) {
684 LOG.debug("{}: submitted recovery sbapshot", persistenceId());
689 protected void applyCurrentLogRecoveryBatch() {
690 if(recoveryCoordinator == null) {
691 recoveryCoordinator = new ShardRecoveryCoordinator(persistenceId(), schemaContext,
692 LOG, name.toString());
695 recoveryCoordinator.submit(currentLogRecoveryBatch, store.newWriteOnlyTransaction());
697 if(LOG.isDebugEnabled()) {
698 LOG.debug("{}: submitted log recovery batch with size {}", persistenceId(),
699 currentLogRecoveryBatch.size());
704 protected void onRecoveryComplete() {
705 if(recoveryCoordinator != null) {
706 Collection<DOMStoreWriteTransaction> txList = recoveryCoordinator.getTransactions();
708 if(LOG.isDebugEnabled()) {
709 LOG.debug("{}: recovery complete - committing {} Tx's", persistenceId(), txList.size());
712 for(DOMStoreWriteTransaction tx: txList) {
714 syncCommitTransaction(tx);
715 shardMBean.incrementCommittedTransactionCount();
716 } catch (InterruptedException | ExecutionException e) {
717 shardMBean.incrementFailedTransactionsCount();
718 LOG.error("{}: Failed to commit", persistenceId(), e);
723 recoveryCoordinator = null;
724 currentLogRecoveryBatch = null;
725 updateJournalStats();
727 //notify shard manager
728 getContext().parent().tell(new ActorInitialized(), getSelf());
730 // Being paranoid here - this method should only be called once but just in case...
731 if(txCommitTimeoutCheckSchedule == null) {
732 // Schedule a message to be periodically sent to check if the current in-progress
733 // transaction should be expired and aborted.
734 FiniteDuration period = Duration.create(transactionCommitTimeout / 3, TimeUnit.MILLISECONDS);
735 txCommitTimeoutCheckSchedule = getContext().system().scheduler().schedule(
736 period, period, getSelf(),
737 TX_COMMIT_TIMEOUT_CHECK_MESSAGE, getContext().dispatcher(), ActorRef.noSender());
742 protected void applyState(final ActorRef clientActor, final String identifier, final Object data) {
744 if(data instanceof ModificationPayload) {
746 applyModificationToState(clientActor, identifier, ((ModificationPayload) data).getModification());
747 } catch (ClassNotFoundException | IOException e) {
748 LOG.error("{}: Error extracting ModificationPayload", persistenceId(), e);
751 else if (data instanceof CompositeModificationPayload) {
752 Object modification = ((CompositeModificationPayload) data).getModification();
754 applyModificationToState(clientActor, identifier, modification);
755 } else if(data instanceof CompositeModificationByteStringPayload ){
756 Object modification = ((CompositeModificationByteStringPayload) data).getModification();
758 applyModificationToState(clientActor, identifier, modification);
760 LOG.error("{}: Unknown state received {} Class loader = {} CompositeNodeMod.ClassLoader = {}",
761 persistenceId(), data, data.getClass().getClassLoader(),
762 CompositeModificationPayload.class.getClassLoader());
765 updateJournalStats();
769 private void applyModificationToState(ActorRef clientActor, String identifier, Object modification) {
770 if(modification == null) {
772 "{}: modification is null - this is very unexpected, clientActor = {}, identifier = {}",
773 persistenceId(), identifier, clientActor != null ? clientActor.path().toString() : null);
774 } else if(clientActor == null) {
775 // There's no clientActor to which to send a commit reply so we must be applying
776 // replicated state from the leader.
777 commitWithNewTransaction(MutableCompositeModification.fromSerializable(modification));
779 // This must be the OK to commit after replication consensus.
780 finishCommit(clientActor, identifier);
784 private void updateJournalStats() {
785 ReplicatedLogEntry lastLogEntry = getLastLogEntry();
787 if (lastLogEntry != null) {
788 shardMBean.setLastLogIndex(lastLogEntry.getIndex());
789 shardMBean.setLastLogTerm(lastLogEntry.getTerm());
792 shardMBean.setCommitIndex(getCommitIndex());
793 shardMBean.setLastApplied(getLastApplied());
794 shardMBean.setInMemoryJournalDataSize(getRaftActorContext().getReplicatedLog().dataSize());
798 protected void createSnapshot() {
799 // Create a transaction actor. We are really going to treat the transaction as a worker
800 // so that this actor does not get block building the snapshot. THe transaction actor will
801 // after processing the CreateSnapshot message.
803 ActorRef createSnapshotTransaction = createTransaction(
804 TransactionProxy.TransactionType.READ_ONLY.ordinal(),
805 "createSnapshot" + ++createSnapshotTransactionCounter, "",
806 DataStoreVersions.CURRENT_VERSION);
808 createSnapshotTransaction.tell(CreateSnapshot.INSTANCE, self());
813 protected void applySnapshot(final byte[] snapshotBytes) {
814 // Since this will be done only on Recovery or when this actor is a Follower
815 // we can safely commit everything in here. We not need to worry about event notifications
816 // as they would have already been disabled on the follower
818 LOG.info("{}: Applying snapshot", persistenceId());
820 DOMStoreWriteTransaction transaction = store.newWriteOnlyTransaction();
822 NormalizedNode<?, ?> node = SerializationUtils.deserializeNormalizedNode(snapshotBytes);
824 // delete everything first
825 transaction.delete(DATASTORE_ROOT);
827 // Add everything from the remote node back
828 transaction.write(DATASTORE_ROOT, node);
829 syncCommitTransaction(transaction);
830 } catch (InterruptedException | ExecutionException e) {
831 LOG.error("{}: An exception occurred when applying snapshot", persistenceId(), e);
833 LOG.info("{}: Done applying snapshot", persistenceId());
838 protected void onStateChanged() {
839 boolean isLeader = isLeader();
840 for (ActorSelection dataChangeListener : dataChangeListeners) {
841 dataChangeListener.tell(new EnableNotification(isLeader), getSelf());
845 for(DelayedListenerRegistration reg: delayedListenerRegistrations) {
846 if(!reg.isClosed()) {
847 reg.setDelegate(doChangeListenerRegistration(reg.getRegisterChangeListener()));
851 delayedListenerRegistrations.clear();
854 shardMBean.setRaftState(getRaftState().name());
855 shardMBean.setCurrentTerm(getCurrentTerm());
857 // If this actor is no longer the leader close all the transaction chains
859 for(Map.Entry<String, DOMStoreTransactionChain> entry : transactionChains.entrySet()){
860 if(LOG.isDebugEnabled()) {
862 "{}: onStateChanged: Closing transaction chain {} because shard {} is no longer the leader",
863 persistenceId(), entry.getKey(), getId());
865 entry.getValue().close();
868 transactionChains.clear();
873 protected DataPersistenceProvider persistence() {
874 return dataPersistenceProvider;
877 @Override protected void onLeaderChanged(final String oldLeader, final String newLeader) {
878 shardMBean.setLeader(newLeader);
881 @Override public String persistenceId() {
882 return this.name.toString();
886 DataPersistenceProvider getDataPersistenceProvider() {
887 return dataPersistenceProvider;
890 private static class ShardCreator implements Creator<Shard> {
892 private static final long serialVersionUID = 1L;
894 final ShardIdentifier name;
895 final Map<ShardIdentifier, String> peerAddresses;
896 final DatastoreContext datastoreContext;
897 final SchemaContext schemaContext;
899 ShardCreator(final ShardIdentifier name, final Map<ShardIdentifier, String> peerAddresses,
900 final DatastoreContext datastoreContext, final SchemaContext schemaContext) {
902 this.peerAddresses = peerAddresses;
903 this.datastoreContext = datastoreContext;
904 this.schemaContext = schemaContext;
908 public Shard create() throws Exception {
909 return new Shard(name, peerAddresses, datastoreContext, schemaContext);
914 InMemoryDOMDataStore getDataStore() {
919 ShardStats getShardMBean() {
923 private static class DelayedListenerRegistration implements
924 ListenerRegistration<AsyncDataChangeListener<YangInstanceIdentifier, NormalizedNode<?, ?>>> {
926 private volatile boolean closed;
928 private final RegisterChangeListener registerChangeListener;
930 private volatile ListenerRegistration<AsyncDataChangeListener<YangInstanceIdentifier,
931 NormalizedNode<?, ?>>> delegate;
933 DelayedListenerRegistration(final RegisterChangeListener registerChangeListener) {
934 this.registerChangeListener = registerChangeListener;
937 void setDelegate( final ListenerRegistration<AsyncDataChangeListener<YangInstanceIdentifier,
938 NormalizedNode<?, ?>>> registration) {
939 this.delegate = registration;
946 RegisterChangeListener getRegisterChangeListener() {
947 return registerChangeListener;
951 public AsyncDataChangeListener<YangInstanceIdentifier, NormalizedNode<?, ?>> getInstance() {
952 return delegate != null ? delegate.getInstance() : null;
956 public void close() {
958 if(delegate != null) {