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.RoleChangeNotifier;
67 import org.opendaylight.controller.cluster.raft.RaftActor;
68 import org.opendaylight.controller.cluster.raft.ReplicatedLogEntry;
69 import org.opendaylight.controller.cluster.raft.messages.AppendEntriesReply;
70 import org.opendaylight.controller.cluster.raft.protobuff.client.messages.CompositeModificationByteStringPayload;
71 import org.opendaylight.controller.cluster.raft.protobuff.client.messages.CompositeModificationPayload;
72 import org.opendaylight.controller.cluster.raft.protobuff.client.messages.Payload;
73 import org.opendaylight.controller.md.sal.common.api.data.AsyncDataChangeListener;
74 import org.opendaylight.controller.md.sal.dom.store.impl.InMemoryDOMDataStore;
75 import org.opendaylight.controller.md.sal.dom.store.impl.InMemoryDOMDataStoreFactory;
76 import org.opendaylight.controller.sal.core.spi.data.DOMStoreThreePhaseCommitCohort;
77 import org.opendaylight.controller.sal.core.spi.data.DOMStoreTransaction;
78 import org.opendaylight.controller.sal.core.spi.data.DOMStoreTransactionChain;
79 import org.opendaylight.controller.sal.core.spi.data.DOMStoreTransactionFactory;
80 import org.opendaylight.controller.sal.core.spi.data.DOMStoreWriteTransaction;
81 import org.opendaylight.yangtools.concepts.ListenerRegistration;
82 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
83 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
84 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
85 import scala.concurrent.duration.Duration;
86 import scala.concurrent.duration.FiniteDuration;
89 * A Shard represents a portion of the logical data tree <br/>
91 * Our Shard uses InMemoryDataStore as it's internal representation and delegates all requests it
94 public class Shard extends RaftActor {
96 private static final YangInstanceIdentifier DATASTORE_ROOT = YangInstanceIdentifier.builder().build();
98 private static final Object TX_COMMIT_TIMEOUT_CHECK_MESSAGE = "txCommitTimeoutCheck";
101 static final String DEFAULT_NAME = "default";
103 // The state of this Shard
104 private final InMemoryDOMDataStore store;
106 /// The name of this shard
107 private final 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 DatastoreContext datastoreContext;
118 private DataPersistenceProvider dataPersistenceProvider;
120 private SchemaContext schemaContext;
122 private int createSnapshotTransactionCounter;
124 private final ShardCommitCoordinator commitCoordinator;
126 private long transactionCommitTimeout;
128 private Cancellable txCommitTimeoutCheckSchedule;
130 private final Optional<ActorRef> roleChangeNotifier;
132 private final MessageTracker appendEntriesReplyTracker;
135 * Coordinates persistence recovery on startup.
137 private ShardRecoveryCoordinator recoveryCoordinator;
138 private List<Object> currentLogRecoveryBatch;
140 private final Map<String, DOMStoreTransactionChain> transactionChains = new HashMap<>();
142 private final String txnDispatcherPath;
144 protected Shard(final ShardIdentifier name, final Map<ShardIdentifier, String> peerAddresses,
145 final DatastoreContext datastoreContext, final SchemaContext schemaContext) {
146 super(name.toString(), mapPeerAddresses(peerAddresses),
147 Optional.of(datastoreContext.getShardRaftConfig()));
150 this.datastoreContext = datastoreContext;
151 this.schemaContext = schemaContext;
152 this.dataPersistenceProvider = (datastoreContext.isPersistent())
153 ? new PersistentDataProvider() : new NonPersistentRaftDataProvider();
154 this.txnDispatcherPath = new Dispatchers(context().system().dispatchers())
155 .getDispatcherPath(Dispatchers.DispatcherType.Transaction);
158 LOG.info("Shard created : {}, persistent : {}", name, datastoreContext.isPersistent());
160 store = InMemoryDOMDataStoreFactory.create(name.toString(), null,
161 datastoreContext.getDataStoreProperties());
163 if(schemaContext != null) {
164 store.onGlobalContextUpdated(schemaContext);
167 shardMBean = ShardMBeanFactory.getShardStatsMBean(name.toString(),
168 datastoreContext.getDataStoreMXBeanType());
169 shardMBean.setNotificationManager(store.getDataChangeListenerNotificationManager());
171 if (isMetricsCaptureEnabled()) {
172 getContext().become(new MeteringBehavior(this));
175 commitCoordinator = new ShardCommitCoordinator(TimeUnit.SECONDS.convert(1, TimeUnit.MINUTES),
176 datastoreContext.getShardTransactionCommitQueueCapacity(), LOG, name.toString());
178 setTransactionCommitTimeout();
180 // create a notifier actor for each cluster member
181 roleChangeNotifier = createRoleChangeNotifier(name.toString());
183 appendEntriesReplyTracker = new MessageTracker(AppendEntriesReply.class,
184 getRaftActorContext().getConfigParams().getIsolatedCheckIntervalInMillis());
187 private void setTransactionCommitTimeout() {
188 transactionCommitTimeout = TimeUnit.MILLISECONDS.convert(
189 datastoreContext.getShardTransactionCommitTimeoutInSeconds(), TimeUnit.SECONDS);
192 private static Map<String, String> mapPeerAddresses(
193 final Map<ShardIdentifier, String> peerAddresses) {
194 Map<String, String> map = new HashMap<>();
196 for (Map.Entry<ShardIdentifier, String> entry : peerAddresses
198 map.put(entry.getKey().toString(), entry.getValue());
204 public static Props props(final ShardIdentifier name,
205 final Map<ShardIdentifier, String> peerAddresses,
206 final DatastoreContext datastoreContext, final SchemaContext schemaContext) {
207 Preconditions.checkNotNull(name, "name should not be null");
208 Preconditions.checkNotNull(peerAddresses, "peerAddresses should not be null");
209 Preconditions.checkNotNull(datastoreContext, "dataStoreContext should not be null");
210 Preconditions.checkNotNull(schemaContext, "schemaContext should not be null");
212 return Props.create(new ShardCreator(name, peerAddresses, datastoreContext, schemaContext));
215 private Optional<ActorRef> createRoleChangeNotifier(String shardId) {
216 ActorRef shardRoleChangeNotifier = this.getContext().actorOf(
217 RoleChangeNotifier.getProps(shardId), shardId + "-notifier");
218 return Optional.<ActorRef>of(shardRoleChangeNotifier);
222 public void postStop() {
223 LOG.info("Stopping Shard {}", persistenceId());
227 if(txCommitTimeoutCheckSchedule != null) {
228 txCommitTimeoutCheckSchedule.cancel();
231 shardMBean.unregisterMBean();
235 public void onReceiveRecover(final Object message) throws Exception {
236 if(LOG.isDebugEnabled()) {
237 LOG.debug("{}: onReceiveRecover: Received message {} from {}", persistenceId(),
238 message.getClass().toString(), getSender());
241 if (message instanceof RecoveryFailure){
242 LOG.error("{}: Recovery failed because of this cause",
243 persistenceId(), ((RecoveryFailure) message).cause());
245 // Even though recovery failed, we still need to finish our recovery, eg send the
246 // ActorInitialized message and start the txCommitTimeoutCheckSchedule.
247 onRecoveryComplete();
249 super.onReceiveRecover(message);
250 if(LOG.isTraceEnabled()) {
251 appendEntriesReplyTracker.begin();
257 public void onReceiveCommand(final Object message) throws Exception {
259 MessageTracker.Context context = appendEntriesReplyTracker.received(message);
261 if(context.error().isPresent()){
262 LOG.trace("{} : AppendEntriesReply failed to arrive at the expected interval {}", persistenceId(),
267 if (message.getClass().equals(CreateTransaction.SERIALIZABLE_CLASS)) {
268 handleCreateTransaction(message);
269 } else if (message instanceof ForwardedReadyTransaction) {
270 handleForwardedReadyTransaction((ForwardedReadyTransaction) message);
271 } else if (message.getClass().equals(CanCommitTransaction.SERIALIZABLE_CLASS)) {
272 handleCanCommitTransaction(CanCommitTransaction.fromSerializable(message));
273 } else if (message.getClass().equals(CommitTransaction.SERIALIZABLE_CLASS)) {
274 handleCommitTransaction(CommitTransaction.fromSerializable(message));
275 } else if (message.getClass().equals(AbortTransaction.SERIALIZABLE_CLASS)) {
276 handleAbortTransaction(AbortTransaction.fromSerializable(message));
277 } else if (message.getClass().equals(CloseTransactionChain.SERIALIZABLE_CLASS)) {
278 closeTransactionChain(CloseTransactionChain.fromSerializable(message));
279 } else if (message instanceof RegisterChangeListener) {
280 registerChangeListener((RegisterChangeListener) message);
281 } else if (message instanceof UpdateSchemaContext) {
282 updateSchemaContext((UpdateSchemaContext) message);
283 } else if (message instanceof PeerAddressResolved) {
284 PeerAddressResolved resolved = (PeerAddressResolved) message;
285 setPeerAddress(resolved.getPeerId().toString(),
286 resolved.getPeerAddress());
287 } else if (message.equals(TX_COMMIT_TIMEOUT_CHECK_MESSAGE)) {
288 handleTransactionCommitTimeoutCheck();
289 } else if(message instanceof DatastoreContext) {
290 onDatastoreContext((DatastoreContext)message);
292 super.onReceiveCommand(message);
300 protected Optional<ActorRef> getRoleChangeNotifier() {
301 return roleChangeNotifier;
304 private void onDatastoreContext(DatastoreContext context) {
305 datastoreContext = context;
307 commitCoordinator.setQueueCapacity(datastoreContext.getShardTransactionCommitQueueCapacity());
309 setTransactionCommitTimeout();
311 if(datastoreContext.isPersistent() &&
312 dataPersistenceProvider instanceof NonPersistentRaftDataProvider) {
313 dataPersistenceProvider = new PersistentDataProvider();
314 } else if(!datastoreContext.isPersistent() &&
315 dataPersistenceProvider instanceof PersistentDataProvider) {
316 dataPersistenceProvider = new NonPersistentRaftDataProvider();
319 updateConfigParams(datastoreContext.getShardRaftConfig());
322 private void handleTransactionCommitTimeoutCheck() {
323 CohortEntry cohortEntry = commitCoordinator.getCurrentCohortEntry();
324 if(cohortEntry != null) {
325 long elapsed = System.currentTimeMillis() - cohortEntry.getLastAccessTime();
326 if(elapsed > transactionCommitTimeout) {
327 LOG.warn("{}: Current transaction {} has timed out after {} ms - aborting",
328 persistenceId(), cohortEntry.getTransactionID(), transactionCommitTimeout);
330 doAbortTransaction(cohortEntry.getTransactionID(), null);
335 private void handleCommitTransaction(final CommitTransaction commit) {
336 final String transactionID = commit.getTransactionID();
338 LOG.debug("{}: Committing transaction {}", persistenceId(), transactionID);
340 // Get the current in-progress cohort entry in the commitCoordinator if it corresponds to
342 final CohortEntry cohortEntry = commitCoordinator.getCohortEntryIfCurrent(transactionID);
343 if(cohortEntry == null) {
344 // We're not the current Tx - the Tx was likely expired b/c it took too long in
345 // between the canCommit and commit messages.
346 IllegalStateException ex = new IllegalStateException(
347 String.format("%s: Cannot commit transaction %s - it is not the current transaction",
348 persistenceId(), transactionID));
349 LOG.error(ex.getMessage());
350 shardMBean.incrementFailedTransactionsCount();
351 getSender().tell(new akka.actor.Status.Failure(ex), getSelf());
355 // We perform the preCommit phase here atomically with the commit phase. This is an
356 // optimization to eliminate the overhead of an extra preCommit message. We lose front-end
357 // coordination of preCommit across shards in case of failure but preCommit should not
358 // normally fail since we ensure only one concurrent 3-phase commit.
361 // We block on the future here so we don't have to worry about possibly accessing our
362 // state on a different thread outside of our dispatcher. Also, the data store
363 // currently uses a same thread executor anyway.
364 cohortEntry.getCohort().preCommit().get();
366 // If we do not have any followers and we are not using persistence we can
367 // apply modification to the state immediately
368 if(!hasFollowers() && !persistence().isRecoveryApplicable()){
369 applyModificationToState(getSender(), transactionID, cohortEntry.getModification());
371 Shard.this.persistData(getSender(), transactionID,
372 new ModificationPayload(cohortEntry.getModification()));
374 } catch (Exception e) {
375 LOG.error("{} An exception occurred while preCommitting transaction {}",
376 persistenceId(), cohortEntry.getTransactionID(), e);
377 shardMBean.incrementFailedTransactionsCount();
378 getSender().tell(new akka.actor.Status.Failure(e), getSelf());
381 cohortEntry.updateLastAccessTime();
384 private void finishCommit(@Nonnull final ActorRef sender, final @Nonnull String transactionID) {
385 // With persistence enabled, this method is called via applyState by the leader strategy
386 // after the commit has been replicated to a majority of the followers.
388 CohortEntry cohortEntry = commitCoordinator.getCohortEntryIfCurrent(transactionID);
389 if(cohortEntry == null) {
390 // The transaction is no longer the current commit. This can happen if the transaction
391 // was aborted prior, most likely due to timeout in the front-end. We need to finish
392 // committing the transaction though since it was successfully persisted and replicated
393 // however we can't use the original cohort b/c it was already preCommitted and may
394 // conflict with the current commit or may have been aborted so we commit with a new
396 cohortEntry = commitCoordinator.getAndRemoveCohortEntry(transactionID);
397 if(cohortEntry != null) {
398 commitWithNewTransaction(cohortEntry.getModification());
399 sender.tell(CommitTransactionReply.INSTANCE.toSerializable(), getSelf());
401 // This really shouldn't happen - it likely means that persistence or replication
402 // took so long to complete such that the cohort entry was expired from the cache.
403 IllegalStateException ex = new IllegalStateException(
404 String.format("%s: Could not finish committing transaction %s - no CohortEntry found",
405 persistenceId(), transactionID));
406 LOG.error(ex.getMessage());
407 sender.tell(new akka.actor.Status.Failure(ex), getSelf());
413 LOG.debug("{}: Finishing commit for transaction {}", persistenceId(), cohortEntry.getTransactionID());
416 // We block on the future here so we don't have to worry about possibly accessing our
417 // state on a different thread outside of our dispatcher. Also, the data store
418 // currently uses a same thread executor anyway.
419 cohortEntry.getCohort().commit().get();
421 sender.tell(CommitTransactionReply.INSTANCE.toSerializable(), getSelf());
423 shardMBean.incrementCommittedTransactionCount();
424 shardMBean.setLastCommittedTransactionTime(System.currentTimeMillis());
426 } catch (Exception e) {
427 sender.tell(new akka.actor.Status.Failure(e), getSelf());
429 LOG.error("{}, An exception occurred while committing transaction {}", persistenceId(),
431 shardMBean.incrementFailedTransactionsCount();
433 commitCoordinator.currentTransactionComplete(transactionID, true);
437 private void handleCanCommitTransaction(final CanCommitTransaction canCommit) {
438 LOG.debug("{}: Can committing transaction {}", persistenceId(), canCommit.getTransactionID());
439 commitCoordinator.handleCanCommit(canCommit, getSender(), self());
442 private void handleForwardedReadyTransaction(ForwardedReadyTransaction ready) {
443 LOG.debug("{}: Readying transaction {}, client version {}", persistenceId(),
444 ready.getTransactionID(), ready.getTxnClientVersion());
446 // This message is forwarded by the ShardTransaction on ready. We cache the cohort in the
447 // commitCoordinator in preparation for the subsequent three phase commit initiated by
449 commitCoordinator.transactionReady(ready.getTransactionID(), ready.getCohort(),
450 ready.getModification());
452 // Return our actor path as we'll handle the three phase commit, except if the Tx client
453 // version < 1 (Helium-1 version). This means the Tx was initiated by a base Helium version
454 // node. In that case, the subsequent 3-phase commit messages won't contain the
455 // transactionId so to maintain backwards compatibility, we create a separate cohort actor
456 // to provide the compatible behavior.
457 ActorRef replyActorPath = self();
458 if(ready.getTxnClientVersion() < DataStoreVersions.HELIUM_1_VERSION) {
459 LOG.debug("{}: Creating BackwardsCompatibleThreePhaseCommitCohort", persistenceId());
460 replyActorPath = getContext().actorOf(BackwardsCompatibleThreePhaseCommitCohort.props(
461 ready.getTransactionID()));
464 ReadyTransactionReply readyTransactionReply = new ReadyTransactionReply(
465 Serialization.serializedActorPath(replyActorPath));
466 getSender().tell(ready.isReturnSerialized() ? readyTransactionReply.toSerializable() :
467 readyTransactionReply, getSelf());
470 private void handleAbortTransaction(final AbortTransaction abort) {
471 doAbortTransaction(abort.getTransactionID(), getSender());
474 void doAbortTransaction(final String transactionID, final ActorRef sender) {
475 final CohortEntry cohortEntry = commitCoordinator.getCohortEntryIfCurrent(transactionID);
476 if(cohortEntry != null) {
477 LOG.debug("{}: Aborting transaction {}", persistenceId(), transactionID);
479 // We don't remove the cached cohort entry here (ie pass false) in case the Tx was
480 // aborted during replication in which case we may still commit locally if replication
482 commitCoordinator.currentTransactionComplete(transactionID, false);
484 final ListenableFuture<Void> future = cohortEntry.getCohort().abort();
485 final ActorRef self = getSelf();
487 Futures.addCallback(future, new FutureCallback<Void>() {
489 public void onSuccess(final Void v) {
490 shardMBean.incrementAbortTransactionsCount();
493 sender.tell(AbortTransactionReply.INSTANCE.toSerializable(), self);
498 public void onFailure(final Throwable t) {
499 LOG.error("{}: An exception happened during abort", persistenceId(), t);
502 sender.tell(new akka.actor.Status.Failure(t), self);
509 private void handleCreateTransaction(final Object message) {
511 createTransaction(CreateTransaction.fromSerializable(message));
512 } else if (getLeader() != null) {
513 getLeader().forward(message, getContext());
515 getSender().tell(new akka.actor.Status.Failure(new NoShardLeaderException(String.format(
516 "Could not find leader for shard %s so transaction cannot be created. This typically happens" +
517 " when the system is coming up or recovering and a leader is being elected. Try again" +
518 " later.", persistenceId()))), getSelf());
522 private void closeTransactionChain(final CloseTransactionChain closeTransactionChain) {
523 DOMStoreTransactionChain chain =
524 transactionChains.remove(closeTransactionChain.getTransactionChainId());
531 private ActorRef createTypedTransactionActor(int transactionType,
532 ShardTransactionIdentifier transactionId, String transactionChainId,
533 short clientVersion ) {
535 DOMStoreTransactionFactory factory = store;
537 if(!transactionChainId.isEmpty()) {
538 factory = transactionChains.get(transactionChainId);
540 DOMStoreTransactionChain transactionChain = store.createTransactionChain();
541 transactionChains.put(transactionChainId, transactionChain);
542 factory = transactionChain;
546 if(this.schemaContext == null) {
547 throw new IllegalStateException("SchemaContext is not set");
550 if (transactionType == TransactionProxy.TransactionType.READ_ONLY.ordinal()) {
552 shardMBean.incrementReadOnlyTransactionCount();
554 return createShardTransaction(factory.newReadOnlyTransaction(), transactionId, clientVersion);
556 } else if (transactionType == TransactionProxy.TransactionType.READ_WRITE.ordinal()) {
558 shardMBean.incrementReadWriteTransactionCount();
560 return createShardTransaction(factory.newReadWriteTransaction(), transactionId, clientVersion);
562 } else if (transactionType == TransactionProxy.TransactionType.WRITE_ONLY.ordinal()) {
564 shardMBean.incrementWriteOnlyTransactionCount();
566 return createShardTransaction(factory.newWriteOnlyTransaction(), transactionId, clientVersion);
568 throw new IllegalArgumentException(
569 "Shard="+name + ":CreateTransaction message has unidentified transaction type="
574 private ActorRef createShardTransaction(DOMStoreTransaction transaction, ShardTransactionIdentifier transactionId,
575 short clientVersion){
576 return getContext().actorOf(
577 ShardTransaction.props(transaction, getSelf(),
578 schemaContext, datastoreContext, shardMBean,
579 transactionId.getRemoteTransactionId(), clientVersion)
580 .withDispatcher(txnDispatcherPath),
581 transactionId.toString());
585 private void createTransaction(CreateTransaction createTransaction) {
587 ActorRef transactionActor = createTransaction(createTransaction.getTransactionType(),
588 createTransaction.getTransactionId(), createTransaction.getTransactionChainId(),
589 createTransaction.getVersion());
591 getSender().tell(new CreateTransactionReply(Serialization.serializedActorPath(transactionActor),
592 createTransaction.getTransactionId()).toSerializable(), getSelf());
593 } catch (Exception e) {
594 getSender().tell(new akka.actor.Status.Failure(e), getSelf());
598 private ActorRef createTransaction(int transactionType, String remoteTransactionId,
599 String transactionChainId, short clientVersion) {
601 ShardTransactionIdentifier transactionId =
602 ShardTransactionIdentifier.builder()
603 .remoteTransactionId(remoteTransactionId)
606 if(LOG.isDebugEnabled()) {
607 LOG.debug("{}: Creating transaction : {} ", persistenceId(), transactionId);
610 ActorRef transactionActor = createTypedTransactionActor(transactionType, transactionId,
611 transactionChainId, clientVersion);
613 return transactionActor;
616 private void syncCommitTransaction(final DOMStoreWriteTransaction transaction)
617 throws ExecutionException, InterruptedException {
618 DOMStoreThreePhaseCommitCohort commitCohort = transaction.ready();
619 commitCohort.preCommit().get();
620 commitCohort.commit().get();
623 private void commitWithNewTransaction(final Modification modification) {
624 DOMStoreWriteTransaction tx = store.newWriteOnlyTransaction();
625 modification.apply(tx);
627 syncCommitTransaction(tx);
628 shardMBean.incrementCommittedTransactionCount();
629 shardMBean.setLastCommittedTransactionTime(System.currentTimeMillis());
630 } catch (InterruptedException | ExecutionException e) {
631 shardMBean.incrementFailedTransactionsCount();
632 LOG.error("{}: Failed to commit", persistenceId(), e);
636 private void updateSchemaContext(final UpdateSchemaContext message) {
637 this.schemaContext = message.getSchemaContext();
638 updateSchemaContext(message.getSchemaContext());
639 store.onGlobalContextUpdated(message.getSchemaContext());
643 void updateSchemaContext(final SchemaContext schemaContext) {
644 store.onGlobalContextUpdated(schemaContext);
647 private void registerChangeListener(final RegisterChangeListener registerChangeListener) {
649 LOG.debug("{}: registerDataChangeListener for {}", persistenceId(), registerChangeListener.getPath());
651 ListenerRegistration<AsyncDataChangeListener<YangInstanceIdentifier,
652 NormalizedNode<?, ?>>> registration;
654 registration = doChangeListenerRegistration(registerChangeListener);
656 LOG.debug("{}: Shard is not the leader - delaying registration", persistenceId());
658 DelayedListenerRegistration delayedReg =
659 new DelayedListenerRegistration(registerChangeListener);
660 delayedListenerRegistrations.add(delayedReg);
661 registration = delayedReg;
664 ActorRef listenerRegistration = getContext().actorOf(
665 DataChangeListenerRegistration.props(registration));
667 LOG.debug("{}: registerDataChangeListener sending reply, listenerRegistrationPath = {} ",
668 persistenceId(), listenerRegistration.path());
670 getSender().tell(new RegisterChangeListenerReply(listenerRegistration.path()), getSelf());
673 private ListenerRegistration<AsyncDataChangeListener<YangInstanceIdentifier,
674 NormalizedNode<?, ?>>> doChangeListenerRegistration(
675 final RegisterChangeListener registerChangeListener) {
677 ActorSelection dataChangeListenerPath = getContext().system().actorSelection(
678 registerChangeListener.getDataChangeListenerPath());
680 // Notify the listener if notifications should be enabled or not
681 // If this shard is the leader then it will enable notifications else
683 dataChangeListenerPath.tell(new EnableNotification(true), getSelf());
685 // Now store a reference to the data change listener so it can be notified
686 // at a later point if notifications should be enabled or disabled
687 dataChangeListeners.add(dataChangeListenerPath);
689 AsyncDataChangeListener<YangInstanceIdentifier, NormalizedNode<?, ?>> listener =
690 new DataChangeListenerProxy(dataChangeListenerPath);
692 LOG.debug("{}: Registering for path {}", persistenceId(), registerChangeListener.getPath());
694 return store.registerChangeListener(registerChangeListener.getPath(), listener,
695 registerChangeListener.getScope());
698 private boolean isMetricsCaptureEnabled(){
699 CommonConfig config = new CommonConfig(getContext().system().settings().config());
700 return config.isMetricCaptureEnabled();
705 void startLogRecoveryBatch(final int maxBatchSize) {
706 currentLogRecoveryBatch = Lists.newArrayListWithCapacity(maxBatchSize);
708 if(LOG.isDebugEnabled()) {
709 LOG.debug("{}: starting log recovery batch with max size {}", persistenceId(), maxBatchSize);
714 protected void appendRecoveredLogEntry(final Payload data) {
715 if(data instanceof ModificationPayload) {
717 currentLogRecoveryBatch.add(((ModificationPayload) data).getModification());
718 } catch (ClassNotFoundException | IOException e) {
719 LOG.error("{}: Error extracting ModificationPayload", persistenceId(), e);
721 } else if (data instanceof CompositeModificationPayload) {
722 currentLogRecoveryBatch.add(((CompositeModificationPayload) data).getModification());
723 } else if (data instanceof CompositeModificationByteStringPayload) {
724 currentLogRecoveryBatch.add(((CompositeModificationByteStringPayload) data).getModification());
726 LOG.error("{}: Unknown state received {} during recovery", persistenceId(), data);
731 protected void applyRecoverySnapshot(final byte[] snapshotBytes) {
732 if(recoveryCoordinator == null) {
733 recoveryCoordinator = new ShardRecoveryCoordinator(persistenceId(), schemaContext,
734 LOG, name.toString());
737 recoveryCoordinator.submit(snapshotBytes, store.newWriteOnlyTransaction());
739 if(LOG.isDebugEnabled()) {
740 LOG.debug("{}: submitted recovery sbapshot", persistenceId());
745 protected void applyCurrentLogRecoveryBatch() {
746 if(recoveryCoordinator == null) {
747 recoveryCoordinator = new ShardRecoveryCoordinator(persistenceId(), schemaContext,
748 LOG, name.toString());
751 recoveryCoordinator.submit(currentLogRecoveryBatch, store.newWriteOnlyTransaction());
753 if(LOG.isDebugEnabled()) {
754 LOG.debug("{}: submitted log recovery batch with size {}", persistenceId(),
755 currentLogRecoveryBatch.size());
760 protected void onRecoveryComplete() {
761 if(recoveryCoordinator != null) {
762 Collection<DOMStoreWriteTransaction> txList = recoveryCoordinator.getTransactions();
764 if(LOG.isDebugEnabled()) {
765 LOG.debug("{}: recovery complete - committing {} Tx's", persistenceId(), txList.size());
768 for(DOMStoreWriteTransaction tx: txList) {
770 syncCommitTransaction(tx);
771 shardMBean.incrementCommittedTransactionCount();
772 } catch (InterruptedException | ExecutionException e) {
773 shardMBean.incrementFailedTransactionsCount();
774 LOG.error("{}: Failed to commit", persistenceId(), e);
779 recoveryCoordinator = null;
780 currentLogRecoveryBatch = null;
781 updateJournalStats();
783 //notify shard manager
784 getContext().parent().tell(new ActorInitialized(), getSelf());
786 // Being paranoid here - this method should only be called once but just in case...
787 if(txCommitTimeoutCheckSchedule == null) {
788 // Schedule a message to be periodically sent to check if the current in-progress
789 // transaction should be expired and aborted.
790 FiniteDuration period = Duration.create(transactionCommitTimeout / 3, TimeUnit.MILLISECONDS);
791 txCommitTimeoutCheckSchedule = getContext().system().scheduler().schedule(
792 period, period, getSelf(),
793 TX_COMMIT_TIMEOUT_CHECK_MESSAGE, getContext().dispatcher(), ActorRef.noSender());
798 protected void applyState(final ActorRef clientActor, final String identifier, final Object data) {
800 if(data instanceof ModificationPayload) {
802 applyModificationToState(clientActor, identifier, ((ModificationPayload) data).getModification());
803 } catch (ClassNotFoundException | IOException e) {
804 LOG.error("{}: Error extracting ModificationPayload", persistenceId(), e);
807 else if (data instanceof CompositeModificationPayload) {
808 Object modification = ((CompositeModificationPayload) data).getModification();
810 applyModificationToState(clientActor, identifier, modification);
811 } else if(data instanceof CompositeModificationByteStringPayload ){
812 Object modification = ((CompositeModificationByteStringPayload) data).getModification();
814 applyModificationToState(clientActor, identifier, modification);
816 LOG.error("{}: Unknown state received {} Class loader = {} CompositeNodeMod.ClassLoader = {}",
817 persistenceId(), data, data.getClass().getClassLoader(),
818 CompositeModificationPayload.class.getClassLoader());
821 updateJournalStats();
825 private void applyModificationToState(ActorRef clientActor, String identifier, Object modification) {
826 if(modification == null) {
828 "{}: modification is null - this is very unexpected, clientActor = {}, identifier = {}",
829 persistenceId(), identifier, clientActor != null ? clientActor.path().toString() : null);
830 } else if(clientActor == null) {
831 // There's no clientActor to which to send a commit reply so we must be applying
832 // replicated state from the leader.
833 commitWithNewTransaction(MutableCompositeModification.fromSerializable(modification));
835 // This must be the OK to commit after replication consensus.
836 finishCommit(clientActor, identifier);
840 private void updateJournalStats() {
841 ReplicatedLogEntry lastLogEntry = getLastLogEntry();
843 if (lastLogEntry != null) {
844 shardMBean.setLastLogIndex(lastLogEntry.getIndex());
845 shardMBean.setLastLogTerm(lastLogEntry.getTerm());
848 shardMBean.setCommitIndex(getCommitIndex());
849 shardMBean.setLastApplied(getLastApplied());
850 shardMBean.setInMemoryJournalDataSize(getRaftActorContext().getReplicatedLog().dataSize());
854 protected void createSnapshot() {
855 // Create a transaction actor. We are really going to treat the transaction as a worker
856 // so that this actor does not get block building the snapshot. THe transaction actor will
857 // after processing the CreateSnapshot message.
859 ActorRef createSnapshotTransaction = createTransaction(
860 TransactionProxy.TransactionType.READ_ONLY.ordinal(),
861 "createSnapshot" + ++createSnapshotTransactionCounter, "",
862 DataStoreVersions.CURRENT_VERSION);
864 createSnapshotTransaction.tell(CreateSnapshot.INSTANCE, self());
869 protected void applySnapshot(final byte[] snapshotBytes) {
870 // Since this will be done only on Recovery or when this actor is a Follower
871 // we can safely commit everything in here. We not need to worry about event notifications
872 // as they would have already been disabled on the follower
874 LOG.info("{}: Applying snapshot", persistenceId());
876 DOMStoreWriteTransaction transaction = store.newWriteOnlyTransaction();
878 NormalizedNode<?, ?> node = SerializationUtils.deserializeNormalizedNode(snapshotBytes);
880 // delete everything first
881 transaction.delete(DATASTORE_ROOT);
883 // Add everything from the remote node back
884 transaction.write(DATASTORE_ROOT, node);
885 syncCommitTransaction(transaction);
886 } catch (InterruptedException | ExecutionException e) {
887 LOG.error("{}: An exception occurred when applying snapshot", persistenceId(), e);
889 LOG.info("{}: Done applying snapshot", persistenceId());
894 protected void onStateChanged() {
895 boolean isLeader = isLeader();
896 for (ActorSelection dataChangeListener : dataChangeListeners) {
897 dataChangeListener.tell(new EnableNotification(isLeader), getSelf());
901 for(DelayedListenerRegistration reg: delayedListenerRegistrations) {
902 if(!reg.isClosed()) {
903 reg.setDelegate(doChangeListenerRegistration(reg.getRegisterChangeListener()));
907 delayedListenerRegistrations.clear();
910 shardMBean.setRaftState(getRaftState().name());
911 shardMBean.setCurrentTerm(getCurrentTerm());
913 // If this actor is no longer the leader close all the transaction chains
915 for(Map.Entry<String, DOMStoreTransactionChain> entry : transactionChains.entrySet()){
916 if(LOG.isDebugEnabled()) {
918 "{}: onStateChanged: Closing transaction chain {} because shard {} is no longer the leader",
919 persistenceId(), entry.getKey(), getId());
921 entry.getValue().close();
924 transactionChains.clear();
929 protected DataPersistenceProvider persistence() {
930 return dataPersistenceProvider;
933 @Override protected void onLeaderChanged(final String oldLeader, final String newLeader) {
934 shardMBean.setLeader(newLeader);
937 @Override public String persistenceId() {
938 return this.name.toString();
942 DataPersistenceProvider getDataPersistenceProvider() {
943 return dataPersistenceProvider;
946 private static class ShardCreator implements Creator<Shard> {
948 private static final long serialVersionUID = 1L;
950 final ShardIdentifier name;
951 final Map<ShardIdentifier, String> peerAddresses;
952 final DatastoreContext datastoreContext;
953 final SchemaContext schemaContext;
955 ShardCreator(final ShardIdentifier name, final Map<ShardIdentifier, String> peerAddresses,
956 final DatastoreContext datastoreContext, final SchemaContext schemaContext) {
958 this.peerAddresses = peerAddresses;
959 this.datastoreContext = datastoreContext;
960 this.schemaContext = schemaContext;
964 public Shard create() throws Exception {
965 return new Shard(name, peerAddresses, datastoreContext, schemaContext);
970 InMemoryDOMDataStore getDataStore() {
975 ShardStats getShardMBean() {
979 private static class DelayedListenerRegistration implements
980 ListenerRegistration<AsyncDataChangeListener<YangInstanceIdentifier, NormalizedNode<?, ?>>> {
982 private volatile boolean closed;
984 private final RegisterChangeListener registerChangeListener;
986 private volatile ListenerRegistration<AsyncDataChangeListener<YangInstanceIdentifier,
987 NormalizedNode<?, ?>>> delegate;
989 DelayedListenerRegistration(final RegisterChangeListener registerChangeListener) {
990 this.registerChangeListener = registerChangeListener;
993 void setDelegate( final ListenerRegistration<AsyncDataChangeListener<YangInstanceIdentifier,
994 NormalizedNode<?, ?>>> registration) {
995 this.delegate = registration;
1002 RegisterChangeListener getRegisterChangeListener() {
1003 return registerChangeListener;
1007 public AsyncDataChangeListener<YangInstanceIdentifier, NormalizedNode<?, ?>> getInstance() {
1008 return delegate != null ? delegate.getInstance() : null;
1012 public void close() {
1014 if(delegate != null) {