2 * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
4 * This program and the accompanying materials are made available under the
5 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6 * and is available at http://www.eclipse.org/legal/epl-v10.html
9 package org.opendaylight.controller.cluster.datastore;
11 import akka.actor.ActorRef;
12 import akka.actor.ActorSelection;
13 import akka.actor.Cancellable;
14 import akka.actor.Props;
15 import akka.japi.Creator;
16 import akka.persistence.RecoveryFailure;
17 import akka.serialization.Serialization;
18 import com.google.common.annotations.VisibleForTesting;
19 import com.google.common.base.Optional;
20 import com.google.common.base.Preconditions;
21 import com.google.common.collect.Lists;
22 import com.google.common.util.concurrent.FutureCallback;
23 import com.google.common.util.concurrent.Futures;
24 import com.google.common.util.concurrent.ListenableFuture;
25 import java.io.IOException;
26 import java.util.Collection;
27 import java.util.HashMap;
28 import java.util.List;
30 import java.util.concurrent.ExecutionException;
31 import java.util.concurrent.TimeUnit;
32 import javax.annotation.Nonnull;
33 import org.opendaylight.controller.cluster.DataPersistenceProvider;
34 import org.opendaylight.controller.cluster.common.actor.CommonConfig;
35 import org.opendaylight.controller.cluster.common.actor.MeteringBehavior;
36 import org.opendaylight.controller.cluster.datastore.ShardCommitCoordinator.CohortEntry;
37 import org.opendaylight.controller.cluster.datastore.compat.BackwardsCompatibleThreePhaseCommitCohort;
38 import org.opendaylight.controller.cluster.datastore.exceptions.NoShardLeaderException;
39 import org.opendaylight.controller.cluster.datastore.identifiers.ShardIdentifier;
40 import org.opendaylight.controller.cluster.datastore.identifiers.ShardTransactionIdentifier;
41 import org.opendaylight.controller.cluster.datastore.jmx.mbeans.shard.ShardMBeanFactory;
42 import org.opendaylight.controller.cluster.datastore.jmx.mbeans.shard.ShardStats;
43 import org.opendaylight.controller.cluster.datastore.messages.AbortTransaction;
44 import org.opendaylight.controller.cluster.datastore.messages.AbortTransactionReply;
45 import org.opendaylight.controller.cluster.datastore.messages.ActorInitialized;
46 import org.opendaylight.controller.cluster.datastore.messages.CanCommitTransaction;
47 import org.opendaylight.controller.cluster.datastore.messages.CloseTransactionChain;
48 import org.opendaylight.controller.cluster.datastore.messages.CommitTransaction;
49 import org.opendaylight.controller.cluster.datastore.messages.CommitTransactionReply;
50 import org.opendaylight.controller.cluster.datastore.messages.CreateSnapshot;
51 import org.opendaylight.controller.cluster.datastore.messages.CreateTransaction;
52 import org.opendaylight.controller.cluster.datastore.messages.CreateTransactionReply;
53 import org.opendaylight.controller.cluster.datastore.messages.EnableNotification;
54 import org.opendaylight.controller.cluster.datastore.messages.ForwardedReadyTransaction;
55 import org.opendaylight.controller.cluster.datastore.messages.PeerAddressResolved;
56 import org.opendaylight.controller.cluster.datastore.messages.ReadyTransactionReply;
57 import org.opendaylight.controller.cluster.datastore.messages.RegisterChangeListener;
58 import org.opendaylight.controller.cluster.datastore.messages.RegisterChangeListenerReply;
59 import org.opendaylight.controller.cluster.datastore.messages.UpdateSchemaContext;
60 import org.opendaylight.controller.cluster.datastore.modification.Modification;
61 import org.opendaylight.controller.cluster.datastore.modification.ModificationPayload;
62 import org.opendaylight.controller.cluster.datastore.modification.MutableCompositeModification;
63 import org.opendaylight.controller.cluster.datastore.utils.Dispatchers;
64 import org.opendaylight.controller.cluster.datastore.utils.MessageTracker;
65 import org.opendaylight.controller.cluster.datastore.utils.SerializationUtils;
66 import org.opendaylight.controller.cluster.notifications.RegisterRoleChangeListener;
67 import org.opendaylight.controller.cluster.notifications.RoleChangeNotifier;
68 import org.opendaylight.controller.cluster.raft.RaftActor;
69 import org.opendaylight.controller.cluster.raft.ReplicatedLogEntry;
70 import org.opendaylight.controller.cluster.raft.messages.AppendEntriesReply;
71 import org.opendaylight.controller.cluster.raft.protobuff.client.messages.CompositeModificationByteStringPayload;
72 import org.opendaylight.controller.cluster.raft.protobuff.client.messages.CompositeModificationPayload;
73 import org.opendaylight.controller.cluster.raft.protobuff.client.messages.Payload;
74 import org.opendaylight.controller.md.sal.common.api.data.AsyncDataChangeListener;
75 import org.opendaylight.controller.md.sal.dom.store.impl.InMemoryDOMDataStore;
76 import org.opendaylight.controller.md.sal.dom.store.impl.InMemoryDOMDataStoreFactory;
77 import org.opendaylight.controller.sal.core.spi.data.DOMStoreThreePhaseCommitCohort;
78 import org.opendaylight.controller.sal.core.spi.data.DOMStoreTransaction;
79 import org.opendaylight.controller.sal.core.spi.data.DOMStoreTransactionChain;
80 import org.opendaylight.controller.sal.core.spi.data.DOMStoreTransactionFactory;
81 import org.opendaylight.controller.sal.core.spi.data.DOMStoreWriteTransaction;
82 import org.opendaylight.yangtools.concepts.ListenerRegistration;
83 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
84 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
85 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
86 import scala.concurrent.duration.Duration;
87 import scala.concurrent.duration.FiniteDuration;
90 * A Shard represents a portion of the logical data tree <br/>
92 * Our Shard uses InMemoryDataStore as it's internal representation and delegates all requests it
95 public class Shard extends RaftActor {
97 private static final YangInstanceIdentifier DATASTORE_ROOT = YangInstanceIdentifier.builder().build();
99 private static final Object TX_COMMIT_TIMEOUT_CHECK_MESSAGE = "txCommitTimeoutCheck";
102 static final String DEFAULT_NAME = "default";
104 // The state of this Shard
105 private final InMemoryDOMDataStore store;
107 /// The name of this shard
108 private final ShardIdentifier name;
110 private final ShardStats shardMBean;
112 private final List<ActorSelection> dataChangeListeners = Lists.newArrayList();
114 private final List<DelayedListenerRegistration> delayedListenerRegistrations =
115 Lists.newArrayList();
117 private DatastoreContext datastoreContext;
119 private DataPersistenceProvider dataPersistenceProvider;
121 private SchemaContext schemaContext;
123 private int createSnapshotTransactionCounter;
125 private final ShardCommitCoordinator commitCoordinator;
127 private long transactionCommitTimeout;
129 private Cancellable txCommitTimeoutCheckSchedule;
131 private final Optional<ActorRef> roleChangeNotifier;
133 private final MessageTracker appendEntriesReplyTracker;
136 * Coordinates persistence recovery on startup.
138 private ShardRecoveryCoordinator recoveryCoordinator;
139 private List<Object> currentLogRecoveryBatch;
141 private final Map<String, DOMStoreTransactionChain> transactionChains = new HashMap<>();
143 private final String txnDispatcherPath;
145 protected Shard(final ShardIdentifier name, final Map<ShardIdentifier, String> peerAddresses,
146 final DatastoreContext datastoreContext, final SchemaContext schemaContext) {
147 super(name.toString(), mapPeerAddresses(peerAddresses),
148 Optional.of(datastoreContext.getShardRaftConfig()));
151 this.datastoreContext = datastoreContext;
152 this.schemaContext = schemaContext;
153 this.dataPersistenceProvider = (datastoreContext.isPersistent())
154 ? new PersistentDataProvider() : new NonPersistentRaftDataProvider();
155 this.txnDispatcherPath = new Dispatchers(context().system().dispatchers())
156 .getDispatcherPath(Dispatchers.DispatcherType.Transaction);
159 LOG.info("Shard created : {}, persistent : {}", name, datastoreContext.isPersistent());
161 store = InMemoryDOMDataStoreFactory.create(name.toString(), null,
162 datastoreContext.getDataStoreProperties());
164 if(schemaContext != null) {
165 store.onGlobalContextUpdated(schemaContext);
168 shardMBean = ShardMBeanFactory.getShardStatsMBean(name.toString(),
169 datastoreContext.getDataStoreMXBeanType());
170 shardMBean.setNotificationManager(store.getDataChangeListenerNotificationManager());
172 if (isMetricsCaptureEnabled()) {
173 getContext().become(new MeteringBehavior(this));
176 commitCoordinator = new ShardCommitCoordinator(TimeUnit.SECONDS.convert(1, TimeUnit.MINUTES),
177 datastoreContext.getShardTransactionCommitQueueCapacity(), LOG, name.toString());
179 setTransactionCommitTimeout();
181 // create a notifier actor for each cluster member
182 roleChangeNotifier = createRoleChangeNotifier(name.toString());
184 appendEntriesReplyTracker = new MessageTracker(AppendEntriesReply.class,
185 getRaftActorContext().getConfigParams().getIsolatedCheckIntervalInMillis());
188 private void setTransactionCommitTimeout() {
189 transactionCommitTimeout = TimeUnit.MILLISECONDS.convert(
190 datastoreContext.getShardTransactionCommitTimeoutInSeconds(), TimeUnit.SECONDS);
193 private static Map<String, String> mapPeerAddresses(
194 final Map<ShardIdentifier, String> peerAddresses) {
195 Map<String, String> map = new HashMap<>();
197 for (Map.Entry<ShardIdentifier, String> entry : peerAddresses
199 map.put(entry.getKey().toString(), entry.getValue());
205 public static Props props(final ShardIdentifier name,
206 final Map<ShardIdentifier, String> peerAddresses,
207 final DatastoreContext datastoreContext, final SchemaContext schemaContext) {
208 Preconditions.checkNotNull(name, "name should not be null");
209 Preconditions.checkNotNull(peerAddresses, "peerAddresses should not be null");
210 Preconditions.checkNotNull(datastoreContext, "dataStoreContext should not be null");
211 Preconditions.checkNotNull(schemaContext, "schemaContext should not be null");
213 return Props.create(new ShardCreator(name, peerAddresses, datastoreContext, schemaContext));
216 private Optional<ActorRef> createRoleChangeNotifier(String shardId) {
217 ActorRef shardRoleChangeNotifier = this.getContext().actorOf(
218 RoleChangeNotifier.getProps(shardId), shardId + "-notifier");
219 return Optional.of(shardRoleChangeNotifier);
223 public void postStop() {
224 LOG.info("Stopping Shard {}", persistenceId());
228 if(txCommitTimeoutCheckSchedule != null) {
229 txCommitTimeoutCheckSchedule.cancel();
232 shardMBean.unregisterMBean();
236 public void onReceiveRecover(final Object message) throws Exception {
237 if(LOG.isDebugEnabled()) {
238 LOG.debug("{}: onReceiveRecover: Received message {} from {}", persistenceId(),
239 message.getClass().toString(), getSender());
242 if (message instanceof RecoveryFailure){
243 LOG.error("{}: Recovery failed because of this cause",
244 persistenceId(), ((RecoveryFailure) message).cause());
246 // Even though recovery failed, we still need to finish our recovery, eg send the
247 // ActorInitialized message and start the txCommitTimeoutCheckSchedule.
248 onRecoveryComplete();
250 super.onReceiveRecover(message);
251 if(LOG.isTraceEnabled()) {
252 appendEntriesReplyTracker.begin();
258 public void onReceiveCommand(final Object message) throws Exception {
260 MessageTracker.Context context = appendEntriesReplyTracker.received(message);
262 if(context.error().isPresent()){
263 LOG.trace("{} : AppendEntriesReply failed to arrive at the expected interval {}", persistenceId(),
268 if (message.getClass().equals(CreateTransaction.SERIALIZABLE_CLASS)) {
269 handleCreateTransaction(message);
270 } else if (message instanceof ForwardedReadyTransaction) {
271 handleForwardedReadyTransaction((ForwardedReadyTransaction) message);
272 } else if (message.getClass().equals(CanCommitTransaction.SERIALIZABLE_CLASS)) {
273 handleCanCommitTransaction(CanCommitTransaction.fromSerializable(message));
274 } else if (message.getClass().equals(CommitTransaction.SERIALIZABLE_CLASS)) {
275 handleCommitTransaction(CommitTransaction.fromSerializable(message));
276 } else if (message.getClass().equals(AbortTransaction.SERIALIZABLE_CLASS)) {
277 handleAbortTransaction(AbortTransaction.fromSerializable(message));
278 } else if (message.getClass().equals(CloseTransactionChain.SERIALIZABLE_CLASS)) {
279 closeTransactionChain(CloseTransactionChain.fromSerializable(message));
280 } else if (message instanceof RegisterChangeListener) {
281 registerChangeListener((RegisterChangeListener) message);
282 } else if (message instanceof UpdateSchemaContext) {
283 updateSchemaContext((UpdateSchemaContext) message);
284 } else if (message instanceof PeerAddressResolved) {
285 PeerAddressResolved resolved = (PeerAddressResolved) message;
286 setPeerAddress(resolved.getPeerId().toString(),
287 resolved.getPeerAddress());
288 } else if (message.equals(TX_COMMIT_TIMEOUT_CHECK_MESSAGE)) {
289 handleTransactionCommitTimeoutCheck();
290 } else if(message instanceof DatastoreContext) {
291 onDatastoreContext((DatastoreContext)message);
292 } else if(message instanceof RegisterRoleChangeListener){
293 roleChangeNotifier.get().forward(message, context());
295 super.onReceiveCommand(message);
303 protected Optional<ActorRef> getRoleChangeNotifier() {
304 return roleChangeNotifier;
307 private void onDatastoreContext(DatastoreContext context) {
308 datastoreContext = context;
310 commitCoordinator.setQueueCapacity(datastoreContext.getShardTransactionCommitQueueCapacity());
312 setTransactionCommitTimeout();
314 if(datastoreContext.isPersistent() &&
315 dataPersistenceProvider instanceof NonPersistentRaftDataProvider) {
316 dataPersistenceProvider = new PersistentDataProvider();
317 } else if(!datastoreContext.isPersistent() &&
318 dataPersistenceProvider instanceof PersistentDataProvider) {
319 dataPersistenceProvider = new NonPersistentRaftDataProvider();
322 updateConfigParams(datastoreContext.getShardRaftConfig());
325 private void handleTransactionCommitTimeoutCheck() {
326 CohortEntry cohortEntry = commitCoordinator.getCurrentCohortEntry();
327 if(cohortEntry != null) {
328 long elapsed = System.currentTimeMillis() - cohortEntry.getLastAccessTime();
329 if(elapsed > transactionCommitTimeout) {
330 LOG.warn("{}: Current transaction {} has timed out after {} ms - aborting",
331 persistenceId(), cohortEntry.getTransactionID(), transactionCommitTimeout);
333 doAbortTransaction(cohortEntry.getTransactionID(), null);
338 private void handleCommitTransaction(final CommitTransaction commit) {
339 final String transactionID = commit.getTransactionID();
341 LOG.debug("{}: Committing transaction {}", persistenceId(), transactionID);
343 // Get the current in-progress cohort entry in the commitCoordinator if it corresponds to
345 final CohortEntry cohortEntry = commitCoordinator.getCohortEntryIfCurrent(transactionID);
346 if(cohortEntry == null) {
347 // We're not the current Tx - the Tx was likely expired b/c it took too long in
348 // between the canCommit and commit messages.
349 IllegalStateException ex = new IllegalStateException(
350 String.format("%s: Cannot commit transaction %s - it is not the current transaction",
351 persistenceId(), transactionID));
352 LOG.error(ex.getMessage());
353 shardMBean.incrementFailedTransactionsCount();
354 getSender().tell(new akka.actor.Status.Failure(ex), getSelf());
358 // We perform the preCommit phase here atomically with the commit phase. This is an
359 // optimization to eliminate the overhead of an extra preCommit message. We lose front-end
360 // coordination of preCommit across shards in case of failure but preCommit should not
361 // normally fail since we ensure only one concurrent 3-phase commit.
364 // We block on the future here so we don't have to worry about possibly accessing our
365 // state on a different thread outside of our dispatcher. Also, the data store
366 // currently uses a same thread executor anyway.
367 cohortEntry.getCohort().preCommit().get();
369 // If we do not have any followers and we are not using persistence we can
370 // apply modification to the state immediately
371 if(!hasFollowers() && !persistence().isRecoveryApplicable()){
372 applyModificationToState(getSender(), transactionID, cohortEntry.getModification());
374 Shard.this.persistData(getSender(), transactionID,
375 new ModificationPayload(cohortEntry.getModification()));
377 } catch (Exception e) {
378 LOG.error("{} An exception occurred while preCommitting transaction {}",
379 persistenceId(), cohortEntry.getTransactionID(), e);
380 shardMBean.incrementFailedTransactionsCount();
381 getSender().tell(new akka.actor.Status.Failure(e), getSelf());
384 cohortEntry.updateLastAccessTime();
387 private void finishCommit(@Nonnull final ActorRef sender, final @Nonnull String transactionID) {
388 // With persistence enabled, this method is called via applyState by the leader strategy
389 // after the commit has been replicated to a majority of the followers.
391 CohortEntry cohortEntry = commitCoordinator.getCohortEntryIfCurrent(transactionID);
392 if(cohortEntry == null) {
393 // The transaction is no longer the current commit. This can happen if the transaction
394 // was aborted prior, most likely due to timeout in the front-end. We need to finish
395 // committing the transaction though since it was successfully persisted and replicated
396 // however we can't use the original cohort b/c it was already preCommitted and may
397 // conflict with the current commit or may have been aborted so we commit with a new
399 cohortEntry = commitCoordinator.getAndRemoveCohortEntry(transactionID);
400 if(cohortEntry != null) {
401 commitWithNewTransaction(cohortEntry.getModification());
402 sender.tell(CommitTransactionReply.INSTANCE.toSerializable(), getSelf());
404 // This really shouldn't happen - it likely means that persistence or replication
405 // took so long to complete such that the cohort entry was expired from the cache.
406 IllegalStateException ex = new IllegalStateException(
407 String.format("%s: Could not finish committing transaction %s - no CohortEntry found",
408 persistenceId(), transactionID));
409 LOG.error(ex.getMessage());
410 sender.tell(new akka.actor.Status.Failure(ex), getSelf());
416 LOG.debug("{}: Finishing commit for transaction {}", persistenceId(), cohortEntry.getTransactionID());
419 // We block on the future here so we don't have to worry about possibly accessing our
420 // state on a different thread outside of our dispatcher. Also, the data store
421 // currently uses a same thread executor anyway.
422 cohortEntry.getCohort().commit().get();
424 sender.tell(CommitTransactionReply.INSTANCE.toSerializable(), getSelf());
426 shardMBean.incrementCommittedTransactionCount();
427 shardMBean.setLastCommittedTransactionTime(System.currentTimeMillis());
429 } catch (Exception e) {
430 sender.tell(new akka.actor.Status.Failure(e), getSelf());
432 LOG.error("{}, An exception occurred while committing transaction {}", persistenceId(),
434 shardMBean.incrementFailedTransactionsCount();
436 commitCoordinator.currentTransactionComplete(transactionID, true);
440 private void handleCanCommitTransaction(final CanCommitTransaction canCommit) {
441 LOG.debug("{}: Can committing transaction {}", persistenceId(), canCommit.getTransactionID());
442 commitCoordinator.handleCanCommit(canCommit, getSender(), self());
445 private void handleForwardedReadyTransaction(ForwardedReadyTransaction ready) {
446 LOG.debug("{}: Readying transaction {}, client version {}", persistenceId(),
447 ready.getTransactionID(), ready.getTxnClientVersion());
449 // This message is forwarded by the ShardTransaction on ready. We cache the cohort in the
450 // commitCoordinator in preparation for the subsequent three phase commit initiated by
452 commitCoordinator.transactionReady(ready.getTransactionID(), ready.getCohort(),
453 ready.getModification());
455 // Return our actor path as we'll handle the three phase commit, except if the Tx client
456 // version < 1 (Helium-1 version). This means the Tx was initiated by a base Helium version
457 // node. In that case, the subsequent 3-phase commit messages won't contain the
458 // transactionId so to maintain backwards compatibility, we create a separate cohort actor
459 // to provide the compatible behavior.
460 ActorRef replyActorPath = self();
461 if(ready.getTxnClientVersion() < DataStoreVersions.HELIUM_1_VERSION) {
462 LOG.debug("{}: Creating BackwardsCompatibleThreePhaseCommitCohort", persistenceId());
463 replyActorPath = getContext().actorOf(BackwardsCompatibleThreePhaseCommitCohort.props(
464 ready.getTransactionID()));
467 ReadyTransactionReply readyTransactionReply = new ReadyTransactionReply(
468 Serialization.serializedActorPath(replyActorPath));
469 getSender().tell(ready.isReturnSerialized() ? readyTransactionReply.toSerializable() :
470 readyTransactionReply, getSelf());
473 private void handleAbortTransaction(final AbortTransaction abort) {
474 doAbortTransaction(abort.getTransactionID(), getSender());
477 void doAbortTransaction(final String transactionID, final ActorRef sender) {
478 final CohortEntry cohortEntry = commitCoordinator.getCohortEntryIfCurrent(transactionID);
479 if(cohortEntry != null) {
480 LOG.debug("{}: Aborting transaction {}", persistenceId(), transactionID);
482 // We don't remove the cached cohort entry here (ie pass false) in case the Tx was
483 // aborted during replication in which case we may still commit locally if replication
485 commitCoordinator.currentTransactionComplete(transactionID, false);
487 final ListenableFuture<Void> future = cohortEntry.getCohort().abort();
488 final ActorRef self = getSelf();
490 Futures.addCallback(future, new FutureCallback<Void>() {
492 public void onSuccess(final Void v) {
493 shardMBean.incrementAbortTransactionsCount();
496 sender.tell(AbortTransactionReply.INSTANCE.toSerializable(), self);
501 public void onFailure(final Throwable t) {
502 LOG.error("{}: An exception happened during abort", persistenceId(), t);
505 sender.tell(new akka.actor.Status.Failure(t), self);
512 private void handleCreateTransaction(final Object message) {
514 createTransaction(CreateTransaction.fromSerializable(message));
515 } else if (getLeader() != null) {
516 getLeader().forward(message, getContext());
518 getSender().tell(new akka.actor.Status.Failure(new NoShardLeaderException(String.format(
519 "Could not find leader for shard %s so transaction cannot be created. This typically happens" +
520 " when the system is coming up or recovering and a leader is being elected. Try again" +
521 " later.", persistenceId()))), getSelf());
525 private void closeTransactionChain(final CloseTransactionChain closeTransactionChain) {
526 DOMStoreTransactionChain chain =
527 transactionChains.remove(closeTransactionChain.getTransactionChainId());
534 private ActorRef createTypedTransactionActor(int transactionType,
535 ShardTransactionIdentifier transactionId, String transactionChainId,
536 short clientVersion ) {
538 DOMStoreTransactionFactory factory = store;
540 if(!transactionChainId.isEmpty()) {
541 factory = transactionChains.get(transactionChainId);
543 DOMStoreTransactionChain transactionChain = store.createTransactionChain();
544 transactionChains.put(transactionChainId, transactionChain);
545 factory = transactionChain;
549 if(this.schemaContext == null) {
550 throw new IllegalStateException("SchemaContext is not set");
553 if (transactionType == TransactionProxy.TransactionType.READ_ONLY.ordinal()) {
555 shardMBean.incrementReadOnlyTransactionCount();
557 return createShardTransaction(factory.newReadOnlyTransaction(), transactionId, clientVersion);
559 } else if (transactionType == TransactionProxy.TransactionType.READ_WRITE.ordinal()) {
561 shardMBean.incrementReadWriteTransactionCount();
563 return createShardTransaction(factory.newReadWriteTransaction(), transactionId, clientVersion);
565 } else if (transactionType == TransactionProxy.TransactionType.WRITE_ONLY.ordinal()) {
567 shardMBean.incrementWriteOnlyTransactionCount();
569 return createShardTransaction(factory.newWriteOnlyTransaction(), transactionId, clientVersion);
571 throw new IllegalArgumentException(
572 "Shard="+name + ":CreateTransaction message has unidentified transaction type="
577 private ActorRef createShardTransaction(DOMStoreTransaction transaction, ShardTransactionIdentifier transactionId,
578 short clientVersion){
579 return getContext().actorOf(
580 ShardTransaction.props(transaction, getSelf(),
581 schemaContext, datastoreContext, shardMBean,
582 transactionId.getRemoteTransactionId(), clientVersion)
583 .withDispatcher(txnDispatcherPath),
584 transactionId.toString());
588 private void createTransaction(CreateTransaction createTransaction) {
590 ActorRef transactionActor = createTransaction(createTransaction.getTransactionType(),
591 createTransaction.getTransactionId(), createTransaction.getTransactionChainId(),
592 createTransaction.getVersion());
594 getSender().tell(new CreateTransactionReply(Serialization.serializedActorPath(transactionActor),
595 createTransaction.getTransactionId()).toSerializable(), getSelf());
596 } catch (Exception e) {
597 getSender().tell(new akka.actor.Status.Failure(e), getSelf());
601 private ActorRef createTransaction(int transactionType, String remoteTransactionId,
602 String transactionChainId, short clientVersion) {
604 ShardTransactionIdentifier transactionId =
605 ShardTransactionIdentifier.builder()
606 .remoteTransactionId(remoteTransactionId)
609 if(LOG.isDebugEnabled()) {
610 LOG.debug("{}: Creating transaction : {} ", persistenceId(), transactionId);
613 ActorRef transactionActor = createTypedTransactionActor(transactionType, transactionId,
614 transactionChainId, clientVersion);
616 return transactionActor;
619 private void syncCommitTransaction(final DOMStoreWriteTransaction transaction)
620 throws ExecutionException, InterruptedException {
621 DOMStoreThreePhaseCommitCohort commitCohort = transaction.ready();
622 commitCohort.preCommit().get();
623 commitCohort.commit().get();
626 private void commitWithNewTransaction(final Modification modification) {
627 DOMStoreWriteTransaction tx = store.newWriteOnlyTransaction();
628 modification.apply(tx);
630 syncCommitTransaction(tx);
631 shardMBean.incrementCommittedTransactionCount();
632 shardMBean.setLastCommittedTransactionTime(System.currentTimeMillis());
633 } catch (InterruptedException | ExecutionException e) {
634 shardMBean.incrementFailedTransactionsCount();
635 LOG.error("{}: Failed to commit", persistenceId(), e);
639 private void updateSchemaContext(final UpdateSchemaContext message) {
640 this.schemaContext = message.getSchemaContext();
641 updateSchemaContext(message.getSchemaContext());
642 store.onGlobalContextUpdated(message.getSchemaContext());
646 void updateSchemaContext(final SchemaContext schemaContext) {
647 store.onGlobalContextUpdated(schemaContext);
650 private void registerChangeListener(final RegisterChangeListener registerChangeListener) {
652 LOG.debug("{}: registerDataChangeListener for {}", persistenceId(), registerChangeListener.getPath());
654 ListenerRegistration<AsyncDataChangeListener<YangInstanceIdentifier,
655 NormalizedNode<?, ?>>> registration;
657 registration = doChangeListenerRegistration(registerChangeListener);
659 LOG.debug("{}: Shard is not the leader - delaying registration", persistenceId());
661 DelayedListenerRegistration delayedReg =
662 new DelayedListenerRegistration(registerChangeListener);
663 delayedListenerRegistrations.add(delayedReg);
664 registration = delayedReg;
667 ActorRef listenerRegistration = getContext().actorOf(
668 DataChangeListenerRegistration.props(registration));
670 LOG.debug("{}: registerDataChangeListener sending reply, listenerRegistrationPath = {} ",
671 persistenceId(), listenerRegistration.path());
673 getSender().tell(new RegisterChangeListenerReply(listenerRegistration.path()), getSelf());
676 private ListenerRegistration<AsyncDataChangeListener<YangInstanceIdentifier,
677 NormalizedNode<?, ?>>> doChangeListenerRegistration(
678 final RegisterChangeListener registerChangeListener) {
680 ActorSelection dataChangeListenerPath = getContext().system().actorSelection(
681 registerChangeListener.getDataChangeListenerPath());
683 // Notify the listener if notifications should be enabled or not
684 // If this shard is the leader then it will enable notifications else
686 dataChangeListenerPath.tell(new EnableNotification(true), getSelf());
688 // Now store a reference to the data change listener so it can be notified
689 // at a later point if notifications should be enabled or disabled
690 dataChangeListeners.add(dataChangeListenerPath);
692 AsyncDataChangeListener<YangInstanceIdentifier, NormalizedNode<?, ?>> listener =
693 new DataChangeListenerProxy(dataChangeListenerPath);
695 LOG.debug("{}: Registering for path {}", persistenceId(), registerChangeListener.getPath());
697 return store.registerChangeListener(registerChangeListener.getPath(), listener,
698 registerChangeListener.getScope());
701 private boolean isMetricsCaptureEnabled(){
702 CommonConfig config = new CommonConfig(getContext().system().settings().config());
703 return config.isMetricCaptureEnabled();
708 void startLogRecoveryBatch(final int maxBatchSize) {
709 currentLogRecoveryBatch = Lists.newArrayListWithCapacity(maxBatchSize);
711 if(LOG.isDebugEnabled()) {
712 LOG.debug("{}: starting log recovery batch with max size {}", persistenceId(), maxBatchSize);
717 protected void appendRecoveredLogEntry(final Payload data) {
718 if(data instanceof ModificationPayload) {
720 currentLogRecoveryBatch.add(((ModificationPayload) data).getModification());
721 } catch (ClassNotFoundException | IOException e) {
722 LOG.error("{}: Error extracting ModificationPayload", persistenceId(), e);
724 } else if (data instanceof CompositeModificationPayload) {
725 currentLogRecoveryBatch.add(((CompositeModificationPayload) data).getModification());
726 } else if (data instanceof CompositeModificationByteStringPayload) {
727 currentLogRecoveryBatch.add(((CompositeModificationByteStringPayload) data).getModification());
729 LOG.error("{}: Unknown state received {} during recovery", persistenceId(), data);
734 protected void applyRecoverySnapshot(final byte[] snapshotBytes) {
735 if(recoveryCoordinator == null) {
736 recoveryCoordinator = new ShardRecoveryCoordinator(persistenceId(), schemaContext,
737 LOG, name.toString());
740 recoveryCoordinator.submit(snapshotBytes, store.newWriteOnlyTransaction());
742 if(LOG.isDebugEnabled()) {
743 LOG.debug("{}: submitted recovery sbapshot", persistenceId());
748 protected void applyCurrentLogRecoveryBatch() {
749 if(recoveryCoordinator == null) {
750 recoveryCoordinator = new ShardRecoveryCoordinator(persistenceId(), schemaContext,
751 LOG, name.toString());
754 recoveryCoordinator.submit(currentLogRecoveryBatch, store.newWriteOnlyTransaction());
756 if(LOG.isDebugEnabled()) {
757 LOG.debug("{}: submitted log recovery batch with size {}", persistenceId(),
758 currentLogRecoveryBatch.size());
763 protected void onRecoveryComplete() {
764 if(recoveryCoordinator != null) {
765 Collection<DOMStoreWriteTransaction> txList = recoveryCoordinator.getTransactions();
767 if(LOG.isDebugEnabled()) {
768 LOG.debug("{}: recovery complete - committing {} Tx's", persistenceId(), txList.size());
771 for(DOMStoreWriteTransaction tx: txList) {
773 syncCommitTransaction(tx);
774 shardMBean.incrementCommittedTransactionCount();
775 } catch (InterruptedException | ExecutionException e) {
776 shardMBean.incrementFailedTransactionsCount();
777 LOG.error("{}: Failed to commit", persistenceId(), e);
782 recoveryCoordinator = null;
783 currentLogRecoveryBatch = null;
784 updateJournalStats();
786 //notify shard manager
787 getContext().parent().tell(new ActorInitialized(), getSelf());
789 // Being paranoid here - this method should only be called once but just in case...
790 if(txCommitTimeoutCheckSchedule == null) {
791 // Schedule a message to be periodically sent to check if the current in-progress
792 // transaction should be expired and aborted.
793 FiniteDuration period = Duration.create(transactionCommitTimeout / 3, TimeUnit.MILLISECONDS);
794 txCommitTimeoutCheckSchedule = getContext().system().scheduler().schedule(
795 period, period, getSelf(),
796 TX_COMMIT_TIMEOUT_CHECK_MESSAGE, getContext().dispatcher(), ActorRef.noSender());
801 protected void applyState(final ActorRef clientActor, final String identifier, final Object data) {
803 if(data instanceof ModificationPayload) {
805 applyModificationToState(clientActor, identifier, ((ModificationPayload) data).getModification());
806 } catch (ClassNotFoundException | IOException e) {
807 LOG.error("{}: Error extracting ModificationPayload", persistenceId(), e);
810 else if (data instanceof CompositeModificationPayload) {
811 Object modification = ((CompositeModificationPayload) data).getModification();
813 applyModificationToState(clientActor, identifier, modification);
814 } else if(data instanceof CompositeModificationByteStringPayload ){
815 Object modification = ((CompositeModificationByteStringPayload) data).getModification();
817 applyModificationToState(clientActor, identifier, modification);
819 LOG.error("{}: Unknown state received {} Class loader = {} CompositeNodeMod.ClassLoader = {}",
820 persistenceId(), data, data.getClass().getClassLoader(),
821 CompositeModificationPayload.class.getClassLoader());
824 updateJournalStats();
828 private void applyModificationToState(ActorRef clientActor, String identifier, Object modification) {
829 if(modification == null) {
831 "{}: modification is null - this is very unexpected, clientActor = {}, identifier = {}",
832 persistenceId(), identifier, clientActor != null ? clientActor.path().toString() : null);
833 } else if(clientActor == null) {
834 // There's no clientActor to which to send a commit reply so we must be applying
835 // replicated state from the leader.
836 commitWithNewTransaction(MutableCompositeModification.fromSerializable(modification));
838 // This must be the OK to commit after replication consensus.
839 finishCommit(clientActor, identifier);
843 private void updateJournalStats() {
844 ReplicatedLogEntry lastLogEntry = getLastLogEntry();
846 if (lastLogEntry != null) {
847 shardMBean.setLastLogIndex(lastLogEntry.getIndex());
848 shardMBean.setLastLogTerm(lastLogEntry.getTerm());
851 shardMBean.setCommitIndex(getCommitIndex());
852 shardMBean.setLastApplied(getLastApplied());
853 shardMBean.setInMemoryJournalDataSize(getRaftActorContext().getReplicatedLog().dataSize());
857 protected void createSnapshot() {
858 // Create a transaction actor. We are really going to treat the transaction as a worker
859 // so that this actor does not get block building the snapshot. THe transaction actor will
860 // after processing the CreateSnapshot message.
862 ActorRef createSnapshotTransaction = createTransaction(
863 TransactionProxy.TransactionType.READ_ONLY.ordinal(),
864 "createSnapshot" + ++createSnapshotTransactionCounter, "",
865 DataStoreVersions.CURRENT_VERSION);
867 createSnapshotTransaction.tell(CreateSnapshot.INSTANCE, self());
872 protected void applySnapshot(final byte[] snapshotBytes) {
873 // Since this will be done only on Recovery or when this actor is a Follower
874 // we can safely commit everything in here. We not need to worry about event notifications
875 // as they would have already been disabled on the follower
877 LOG.info("{}: Applying snapshot", persistenceId());
879 DOMStoreWriteTransaction transaction = store.newWriteOnlyTransaction();
881 NormalizedNode<?, ?> node = SerializationUtils.deserializeNormalizedNode(snapshotBytes);
883 // delete everything first
884 transaction.delete(DATASTORE_ROOT);
886 // Add everything from the remote node back
887 transaction.write(DATASTORE_ROOT, node);
888 syncCommitTransaction(transaction);
889 } catch (InterruptedException | ExecutionException e) {
890 LOG.error("{}: An exception occurred when applying snapshot", persistenceId(), e);
892 LOG.info("{}: Done applying snapshot", persistenceId());
897 protected void onStateChanged() {
898 boolean isLeader = isLeader();
899 for (ActorSelection dataChangeListener : dataChangeListeners) {
900 dataChangeListener.tell(new EnableNotification(isLeader), getSelf());
904 for(DelayedListenerRegistration reg: delayedListenerRegistrations) {
905 if(!reg.isClosed()) {
906 reg.setDelegate(doChangeListenerRegistration(reg.getRegisterChangeListener()));
910 delayedListenerRegistrations.clear();
913 shardMBean.setRaftState(getRaftState().name());
914 shardMBean.setCurrentTerm(getCurrentTerm());
916 // If this actor is no longer the leader close all the transaction chains
918 for(Map.Entry<String, DOMStoreTransactionChain> entry : transactionChains.entrySet()){
919 if(LOG.isDebugEnabled()) {
921 "{}: onStateChanged: Closing transaction chain {} because shard {} is no longer the leader",
922 persistenceId(), entry.getKey(), getId());
924 entry.getValue().close();
927 transactionChains.clear();
932 protected DataPersistenceProvider persistence() {
933 return dataPersistenceProvider;
936 @Override protected void onLeaderChanged(final String oldLeader, final String newLeader) {
937 shardMBean.setLeader(newLeader);
940 @Override public String persistenceId() {
941 return this.name.toString();
945 DataPersistenceProvider getDataPersistenceProvider() {
946 return dataPersistenceProvider;
949 private static class ShardCreator implements Creator<Shard> {
951 private static final long serialVersionUID = 1L;
953 final ShardIdentifier name;
954 final Map<ShardIdentifier, String> peerAddresses;
955 final DatastoreContext datastoreContext;
956 final SchemaContext schemaContext;
958 ShardCreator(final ShardIdentifier name, final Map<ShardIdentifier, String> peerAddresses,
959 final DatastoreContext datastoreContext, final SchemaContext schemaContext) {
961 this.peerAddresses = peerAddresses;
962 this.datastoreContext = datastoreContext;
963 this.schemaContext = schemaContext;
967 public Shard create() throws Exception {
968 return new Shard(name, peerAddresses, datastoreContext, schemaContext);
973 InMemoryDOMDataStore getDataStore() {
978 ShardStats getShardMBean() {
982 private static class DelayedListenerRegistration implements
983 ListenerRegistration<AsyncDataChangeListener<YangInstanceIdentifier, NormalizedNode<?, ?>>> {
985 private volatile boolean closed;
987 private final RegisterChangeListener registerChangeListener;
989 private volatile ListenerRegistration<AsyncDataChangeListener<YangInstanceIdentifier,
990 NormalizedNode<?, ?>>> delegate;
992 DelayedListenerRegistration(final RegisterChangeListener registerChangeListener) {
993 this.registerChangeListener = registerChangeListener;
996 void setDelegate( final ListenerRegistration<AsyncDataChangeListener<YangInstanceIdentifier,
997 NormalizedNode<?, ?>>> registration) {
998 this.delegate = registration;
1001 boolean isClosed() {
1005 RegisterChangeListener getRegisterChangeListener() {
1006 return registerChangeListener;
1010 public AsyncDataChangeListener<YangInstanceIdentifier, NormalizedNode<?, ?>> getInstance() {
1011 return delegate != null ? delegate.getInstance() : null;
1015 public void close() {
1017 if(delegate != null) {