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 final DatastoreContext datastoreContext;
118 private final DataPersistenceProvider dataPersistenceProvider;
120 private SchemaContext schemaContext;
122 private int createSnapshotTransactionCounter;
124 private final ShardCommitCoordinator commitCoordinator;
126 private final long transactionCommitTimeout;
128 private Cancellable txCommitTimeoutCheckSchedule;
130 private final Optional<ActorRef> roleChangeNotifier;
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 transactionCommitTimeout = TimeUnit.MILLISECONDS.convert(
179 datastoreContext.getShardTransactionCommitTimeoutInSeconds(), TimeUnit.SECONDS);
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 static Map<String, String> mapPeerAddresses(
189 final Map<ShardIdentifier, String> peerAddresses) {
190 Map<String, String> map = new HashMap<>();
192 for (Map.Entry<ShardIdentifier, String> entry : peerAddresses
194 map.put(entry.getKey().toString(), entry.getValue());
200 public static Props props(final ShardIdentifier name,
201 final Map<ShardIdentifier, String> peerAddresses,
202 final DatastoreContext datastoreContext, final SchemaContext schemaContext) {
203 Preconditions.checkNotNull(name, "name should not be null");
204 Preconditions.checkNotNull(peerAddresses, "peerAddresses should not be null");
205 Preconditions.checkNotNull(datastoreContext, "dataStoreContext should not be null");
206 Preconditions.checkNotNull(schemaContext, "schemaContext should not be null");
208 return Props.create(new ShardCreator(name, peerAddresses, datastoreContext, schemaContext));
211 private Optional<ActorRef> createRoleChangeNotifier(String shardId) {
212 ActorRef shardRoleChangeNotifier = this.getContext().actorOf(
213 RoleChangeNotifier.getProps(shardId), shardId + "-notifier");
214 return Optional.<ActorRef>of(shardRoleChangeNotifier);
218 public void postStop() {
221 if(txCommitTimeoutCheckSchedule != null) {
222 txCommitTimeoutCheckSchedule.cancel();
227 public void onReceiveRecover(final Object message) throws Exception {
228 if(LOG.isDebugEnabled()) {
229 LOG.debug("{}: onReceiveRecover: Received message {} from {}", persistenceId(),
230 message.getClass().toString(), getSender());
233 if (message instanceof RecoveryFailure){
234 LOG.error("{}: Recovery failed because of this cause",
235 persistenceId(), ((RecoveryFailure) message).cause());
237 // Even though recovery failed, we still need to finish our recovery, eg send the
238 // ActorInitialized message and start the txCommitTimeoutCheckSchedule.
239 onRecoveryComplete();
241 super.onReceiveRecover(message);
242 if(LOG.isTraceEnabled()) {
243 appendEntriesReplyTracker.begin();
249 public void onReceiveCommand(final Object message) throws Exception {
251 MessageTracker.Context context = appendEntriesReplyTracker.received(message);
253 if(context.error().isPresent()){
254 LOG.trace("{} : AppendEntriesReply failed to arrive at the expected interval {}", persistenceId(),
259 if (message.getClass().equals(CreateTransaction.SERIALIZABLE_CLASS)) {
260 handleCreateTransaction(message);
261 } else if (message instanceof ForwardedReadyTransaction) {
262 handleForwardedReadyTransaction((ForwardedReadyTransaction) message);
263 } else if (message.getClass().equals(CanCommitTransaction.SERIALIZABLE_CLASS)) {
264 handleCanCommitTransaction(CanCommitTransaction.fromSerializable(message));
265 } else if (message.getClass().equals(CommitTransaction.SERIALIZABLE_CLASS)) {
266 handleCommitTransaction(CommitTransaction.fromSerializable(message));
267 } else if (message.getClass().equals(AbortTransaction.SERIALIZABLE_CLASS)) {
268 handleAbortTransaction(AbortTransaction.fromSerializable(message));
269 } else if (message.getClass().equals(CloseTransactionChain.SERIALIZABLE_CLASS)) {
270 closeTransactionChain(CloseTransactionChain.fromSerializable(message));
271 } else if (message instanceof RegisterChangeListener) {
272 registerChangeListener((RegisterChangeListener) message);
273 } else if (message instanceof UpdateSchemaContext) {
274 updateSchemaContext((UpdateSchemaContext) message);
275 } else if (message instanceof PeerAddressResolved) {
276 PeerAddressResolved resolved = (PeerAddressResolved) message;
277 setPeerAddress(resolved.getPeerId().toString(),
278 resolved.getPeerAddress());
279 } else if (message.equals(TX_COMMIT_TIMEOUT_CHECK_MESSAGE)) {
280 handleTransactionCommitTimeoutCheck();
282 super.onReceiveCommand(message);
290 protected Optional<ActorRef> getRoleChangeNotifier() {
291 return roleChangeNotifier;
294 private void handleTransactionCommitTimeoutCheck() {
295 CohortEntry cohortEntry = commitCoordinator.getCurrentCohortEntry();
296 if(cohortEntry != null) {
297 long elapsed = System.currentTimeMillis() - cohortEntry.getLastAccessTime();
298 if(elapsed > transactionCommitTimeout) {
299 LOG.warn("{}: Current transaction {} has timed out after {} ms - aborting",
300 persistenceId(), cohortEntry.getTransactionID(), transactionCommitTimeout);
302 doAbortTransaction(cohortEntry.getTransactionID(), null);
307 private void handleCommitTransaction(final CommitTransaction commit) {
308 final String transactionID = commit.getTransactionID();
310 LOG.debug("{}: Committing transaction {}", persistenceId(), transactionID);
312 // Get the current in-progress cohort entry in the commitCoordinator if it corresponds to
314 final CohortEntry cohortEntry = commitCoordinator.getCohortEntryIfCurrent(transactionID);
315 if(cohortEntry == null) {
316 // We're not the current Tx - the Tx was likely expired b/c it took too long in
317 // between the canCommit and commit messages.
318 IllegalStateException ex = new IllegalStateException(
319 String.format("%s: Cannot commit transaction %s - it is not the current transaction",
320 persistenceId(), transactionID));
321 LOG.error(ex.getMessage());
322 shardMBean.incrementFailedTransactionsCount();
323 getSender().tell(new akka.actor.Status.Failure(ex), getSelf());
327 // We perform the preCommit phase here atomically with the commit phase. This is an
328 // optimization to eliminate the overhead of an extra preCommit message. We lose front-end
329 // coordination of preCommit across shards in case of failure but preCommit should not
330 // normally fail since we ensure only one concurrent 3-phase commit.
333 // We block on the future here so we don't have to worry about possibly accessing our
334 // state on a different thread outside of our dispatcher. Also, the data store
335 // currently uses a same thread executor anyway.
336 cohortEntry.getCohort().preCommit().get();
338 // If we do not have any followers and we are not using persistence we can
339 // apply modification to the state immediately
340 if(!hasFollowers() && !persistence().isRecoveryApplicable()){
341 applyModificationToState(getSender(), transactionID, cohortEntry.getModification());
343 Shard.this.persistData(getSender(), transactionID,
344 new ModificationPayload(cohortEntry.getModification()));
346 } catch (Exception e) {
347 LOG.error("{} An exception occurred while preCommitting transaction {}",
348 persistenceId(), cohortEntry.getTransactionID(), e);
349 shardMBean.incrementFailedTransactionsCount();
350 getSender().tell(new akka.actor.Status.Failure(e), getSelf());
353 cohortEntry.updateLastAccessTime();
356 private void finishCommit(@Nonnull final ActorRef sender, final @Nonnull String transactionID) {
357 // With persistence enabled, this method is called via applyState by the leader strategy
358 // after the commit has been replicated to a majority of the followers.
360 CohortEntry cohortEntry = commitCoordinator.getCohortEntryIfCurrent(transactionID);
361 if(cohortEntry == null) {
362 // The transaction is no longer the current commit. This can happen if the transaction
363 // was aborted prior, most likely due to timeout in the front-end. We need to finish
364 // committing the transaction though since it was successfully persisted and replicated
365 // however we can't use the original cohort b/c it was already preCommitted and may
366 // conflict with the current commit or may have been aborted so we commit with a new
368 cohortEntry = commitCoordinator.getAndRemoveCohortEntry(transactionID);
369 if(cohortEntry != null) {
370 commitWithNewTransaction(cohortEntry.getModification());
371 sender.tell(CommitTransactionReply.INSTANCE.toSerializable(), getSelf());
373 // This really shouldn't happen - it likely means that persistence or replication
374 // took so long to complete such that the cohort entry was expired from the cache.
375 IllegalStateException ex = new IllegalStateException(
376 String.format("%s: Could not finish committing transaction %s - no CohortEntry found",
377 persistenceId(), transactionID));
378 LOG.error(ex.getMessage());
379 sender.tell(new akka.actor.Status.Failure(ex), getSelf());
385 LOG.debug("{}: Finishing commit for transaction {}", persistenceId(), cohortEntry.getTransactionID());
388 // We block on the future here so we don't have to worry about possibly accessing our
389 // state on a different thread outside of our dispatcher. Also, the data store
390 // currently uses a same thread executor anyway.
391 cohortEntry.getCohort().commit().get();
393 sender.tell(CommitTransactionReply.INSTANCE.toSerializable(), getSelf());
395 shardMBean.incrementCommittedTransactionCount();
396 shardMBean.setLastCommittedTransactionTime(System.currentTimeMillis());
398 } catch (Exception e) {
399 sender.tell(new akka.actor.Status.Failure(e), getSelf());
401 LOG.error("{}, An exception occurred while committing transaction {}", persistenceId(),
403 shardMBean.incrementFailedTransactionsCount();
405 commitCoordinator.currentTransactionComplete(transactionID, true);
409 private void handleCanCommitTransaction(final CanCommitTransaction canCommit) {
410 LOG.debug("{}: Can committing transaction {}", persistenceId(), canCommit.getTransactionID());
411 commitCoordinator.handleCanCommit(canCommit, getSender(), self());
414 private void handleForwardedReadyTransaction(ForwardedReadyTransaction ready) {
415 LOG.debug("{}: Readying transaction {}, client version {}", persistenceId(),
416 ready.getTransactionID(), ready.getTxnClientVersion());
418 // This message is forwarded by the ShardTransaction on ready. We cache the cohort in the
419 // commitCoordinator in preparation for the subsequent three phase commit initiated by
421 commitCoordinator.transactionReady(ready.getTransactionID(), ready.getCohort(),
422 ready.getModification());
424 // Return our actor path as we'll handle the three phase commit, except if the Tx client
425 // version < 1 (Helium-1 version). This means the Tx was initiated by a base Helium version
426 // node. In that case, the subsequent 3-phase commit messages won't contain the
427 // transactionId so to maintain backwards compatibility, we create a separate cohort actor
428 // to provide the compatible behavior.
429 ActorRef replyActorPath = self();
430 if(ready.getTxnClientVersion() < DataStoreVersions.HELIUM_1_VERSION) {
431 LOG.debug("{}: Creating BackwardsCompatibleThreePhaseCommitCohort", persistenceId());
432 replyActorPath = getContext().actorOf(BackwardsCompatibleThreePhaseCommitCohort.props(
433 ready.getTransactionID()));
436 ReadyTransactionReply readyTransactionReply = new ReadyTransactionReply(
437 Serialization.serializedActorPath(replyActorPath));
438 getSender().tell(ready.isReturnSerialized() ? readyTransactionReply.toSerializable() :
439 readyTransactionReply, getSelf());
442 private void handleAbortTransaction(final AbortTransaction abort) {
443 doAbortTransaction(abort.getTransactionID(), getSender());
446 void doAbortTransaction(final String transactionID, final ActorRef sender) {
447 final CohortEntry cohortEntry = commitCoordinator.getCohortEntryIfCurrent(transactionID);
448 if(cohortEntry != null) {
449 LOG.debug("{}: Aborting transaction {}", persistenceId(), transactionID);
451 // We don't remove the cached cohort entry here (ie pass false) in case the Tx was
452 // aborted during replication in which case we may still commit locally if replication
454 commitCoordinator.currentTransactionComplete(transactionID, false);
456 final ListenableFuture<Void> future = cohortEntry.getCohort().abort();
457 final ActorRef self = getSelf();
459 Futures.addCallback(future, new FutureCallback<Void>() {
461 public void onSuccess(final Void v) {
462 shardMBean.incrementAbortTransactionsCount();
465 sender.tell(AbortTransactionReply.INSTANCE.toSerializable(), self);
470 public void onFailure(final Throwable t) {
471 LOG.error("{}: An exception happened during abort", persistenceId(), t);
474 sender.tell(new akka.actor.Status.Failure(t), self);
481 private void handleCreateTransaction(final Object message) {
483 createTransaction(CreateTransaction.fromSerializable(message));
484 } else if (getLeader() != null) {
485 getLeader().forward(message, getContext());
487 getSender().tell(new akka.actor.Status.Failure(new NoShardLeaderException(String.format(
488 "Could not find leader for shard %s so transaction cannot be created. This typically happens" +
489 " when the system is coming up or recovering and a leader is being elected. Try again" +
490 " later.", persistenceId()))), getSelf());
494 private void closeTransactionChain(final CloseTransactionChain closeTransactionChain) {
495 DOMStoreTransactionChain chain =
496 transactionChains.remove(closeTransactionChain.getTransactionChainId());
503 private ActorRef createTypedTransactionActor(int transactionType,
504 ShardTransactionIdentifier transactionId, String transactionChainId,
505 short clientVersion ) {
507 DOMStoreTransactionFactory factory = store;
509 if(!transactionChainId.isEmpty()) {
510 factory = transactionChains.get(transactionChainId);
512 DOMStoreTransactionChain transactionChain = store.createTransactionChain();
513 transactionChains.put(transactionChainId, transactionChain);
514 factory = transactionChain;
518 if(this.schemaContext == null) {
519 throw new IllegalStateException("SchemaContext is not set");
522 if (transactionType == TransactionProxy.TransactionType.READ_ONLY.ordinal()) {
524 shardMBean.incrementReadOnlyTransactionCount();
526 return createShardTransaction(factory.newReadOnlyTransaction(), transactionId, clientVersion);
528 } else if (transactionType == TransactionProxy.TransactionType.READ_WRITE.ordinal()) {
530 shardMBean.incrementReadWriteTransactionCount();
532 return createShardTransaction(factory.newReadWriteTransaction(), transactionId, clientVersion);
534 } else if (transactionType == TransactionProxy.TransactionType.WRITE_ONLY.ordinal()) {
536 shardMBean.incrementWriteOnlyTransactionCount();
538 return createShardTransaction(factory.newWriteOnlyTransaction(), transactionId, clientVersion);
540 throw new IllegalArgumentException(
541 "Shard="+name + ":CreateTransaction message has unidentified transaction type="
546 private ActorRef createShardTransaction(DOMStoreTransaction transaction, ShardTransactionIdentifier transactionId,
547 short clientVersion){
548 return getContext().actorOf(
549 ShardTransaction.props(transaction, getSelf(),
550 schemaContext, datastoreContext, shardMBean,
551 transactionId.getRemoteTransactionId(), clientVersion)
552 .withDispatcher(txnDispatcherPath),
553 transactionId.toString());
557 private void createTransaction(CreateTransaction createTransaction) {
559 ActorRef transactionActor = createTransaction(createTransaction.getTransactionType(),
560 createTransaction.getTransactionId(), createTransaction.getTransactionChainId(),
561 createTransaction.getVersion());
563 getSender().tell(new CreateTransactionReply(Serialization.serializedActorPath(transactionActor),
564 createTransaction.getTransactionId()).toSerializable(), getSelf());
565 } catch (Exception e) {
566 getSender().tell(new akka.actor.Status.Failure(e), getSelf());
570 private ActorRef createTransaction(int transactionType, String remoteTransactionId,
571 String transactionChainId, short clientVersion) {
573 ShardTransactionIdentifier transactionId =
574 ShardTransactionIdentifier.builder()
575 .remoteTransactionId(remoteTransactionId)
578 if(LOG.isDebugEnabled()) {
579 LOG.debug("{}: Creating transaction : {} ", persistenceId(), transactionId);
582 ActorRef transactionActor = createTypedTransactionActor(transactionType, transactionId,
583 transactionChainId, clientVersion);
585 return transactionActor;
588 private void syncCommitTransaction(final DOMStoreWriteTransaction transaction)
589 throws ExecutionException, InterruptedException {
590 DOMStoreThreePhaseCommitCohort commitCohort = transaction.ready();
591 commitCohort.preCommit().get();
592 commitCohort.commit().get();
595 private void commitWithNewTransaction(final Modification modification) {
596 DOMStoreWriteTransaction tx = store.newWriteOnlyTransaction();
597 modification.apply(tx);
599 syncCommitTransaction(tx);
600 shardMBean.incrementCommittedTransactionCount();
601 shardMBean.setLastCommittedTransactionTime(System.currentTimeMillis());
602 } catch (InterruptedException | ExecutionException e) {
603 shardMBean.incrementFailedTransactionsCount();
604 LOG.error("{}: Failed to commit", persistenceId(), e);
608 private void updateSchemaContext(final UpdateSchemaContext message) {
609 this.schemaContext = message.getSchemaContext();
610 updateSchemaContext(message.getSchemaContext());
611 store.onGlobalContextUpdated(message.getSchemaContext());
615 void updateSchemaContext(final SchemaContext schemaContext) {
616 store.onGlobalContextUpdated(schemaContext);
619 private void registerChangeListener(final RegisterChangeListener registerChangeListener) {
621 LOG.debug("{}: registerDataChangeListener for {}", persistenceId(), registerChangeListener.getPath());
623 ListenerRegistration<AsyncDataChangeListener<YangInstanceIdentifier,
624 NormalizedNode<?, ?>>> registration;
626 registration = doChangeListenerRegistration(registerChangeListener);
628 LOG.debug("{}: Shard is not the leader - delaying registration", persistenceId());
630 DelayedListenerRegistration delayedReg =
631 new DelayedListenerRegistration(registerChangeListener);
632 delayedListenerRegistrations.add(delayedReg);
633 registration = delayedReg;
636 ActorRef listenerRegistration = getContext().actorOf(
637 DataChangeListenerRegistration.props(registration));
639 LOG.debug("{}: registerDataChangeListener sending reply, listenerRegistrationPath = {} ",
640 persistenceId(), listenerRegistration.path());
642 getSender().tell(new RegisterChangeListenerReply(listenerRegistration.path()), getSelf());
645 private ListenerRegistration<AsyncDataChangeListener<YangInstanceIdentifier,
646 NormalizedNode<?, ?>>> doChangeListenerRegistration(
647 final RegisterChangeListener registerChangeListener) {
649 ActorSelection dataChangeListenerPath = getContext().system().actorSelection(
650 registerChangeListener.getDataChangeListenerPath());
652 // Notify the listener if notifications should be enabled or not
653 // If this shard is the leader then it will enable notifications else
655 dataChangeListenerPath.tell(new EnableNotification(true), getSelf());
657 // Now store a reference to the data change listener so it can be notified
658 // at a later point if notifications should be enabled or disabled
659 dataChangeListeners.add(dataChangeListenerPath);
661 AsyncDataChangeListener<YangInstanceIdentifier, NormalizedNode<?, ?>> listener =
662 new DataChangeListenerProxy(dataChangeListenerPath);
664 LOG.debug("{}: Registering for path {}", persistenceId(), registerChangeListener.getPath());
666 return store.registerChangeListener(registerChangeListener.getPath(), listener,
667 registerChangeListener.getScope());
670 private boolean isMetricsCaptureEnabled(){
671 CommonConfig config = new CommonConfig(getContext().system().settings().config());
672 return config.isMetricCaptureEnabled();
677 void startLogRecoveryBatch(final int maxBatchSize) {
678 currentLogRecoveryBatch = Lists.newArrayListWithCapacity(maxBatchSize);
680 if(LOG.isDebugEnabled()) {
681 LOG.debug("{}: starting log recovery batch with max size {}", persistenceId(), maxBatchSize);
686 protected void appendRecoveredLogEntry(final Payload data) {
687 if(data instanceof ModificationPayload) {
689 currentLogRecoveryBatch.add(((ModificationPayload) data).getModification());
690 } catch (ClassNotFoundException | IOException e) {
691 LOG.error("{}: Error extracting ModificationPayload", persistenceId(), e);
693 } else if (data instanceof CompositeModificationPayload) {
694 currentLogRecoveryBatch.add(((CompositeModificationPayload) data).getModification());
695 } else if (data instanceof CompositeModificationByteStringPayload) {
696 currentLogRecoveryBatch.add(((CompositeModificationByteStringPayload) data).getModification());
698 LOG.error("{}: Unknown state received {} during recovery", persistenceId(), data);
703 protected void applyRecoverySnapshot(final byte[] snapshotBytes) {
704 if(recoveryCoordinator == null) {
705 recoveryCoordinator = new ShardRecoveryCoordinator(persistenceId(), schemaContext,
706 LOG, name.toString());
709 recoveryCoordinator.submit(snapshotBytes, store.newWriteOnlyTransaction());
711 if(LOG.isDebugEnabled()) {
712 LOG.debug("{}: submitted recovery sbapshot", persistenceId());
717 protected void applyCurrentLogRecoveryBatch() {
718 if(recoveryCoordinator == null) {
719 recoveryCoordinator = new ShardRecoveryCoordinator(persistenceId(), schemaContext,
720 LOG, name.toString());
723 recoveryCoordinator.submit(currentLogRecoveryBatch, store.newWriteOnlyTransaction());
725 if(LOG.isDebugEnabled()) {
726 LOG.debug("{}: submitted log recovery batch with size {}", persistenceId(),
727 currentLogRecoveryBatch.size());
732 protected void onRecoveryComplete() {
733 if(recoveryCoordinator != null) {
734 Collection<DOMStoreWriteTransaction> txList = recoveryCoordinator.getTransactions();
736 if(LOG.isDebugEnabled()) {
737 LOG.debug("{}: recovery complete - committing {} Tx's", persistenceId(), txList.size());
740 for(DOMStoreWriteTransaction tx: txList) {
742 syncCommitTransaction(tx);
743 shardMBean.incrementCommittedTransactionCount();
744 } catch (InterruptedException | ExecutionException e) {
745 shardMBean.incrementFailedTransactionsCount();
746 LOG.error("{}: Failed to commit", persistenceId(), e);
751 recoveryCoordinator = null;
752 currentLogRecoveryBatch = null;
753 updateJournalStats();
755 //notify shard manager
756 getContext().parent().tell(new ActorInitialized(), getSelf());
758 // Being paranoid here - this method should only be called once but just in case...
759 if(txCommitTimeoutCheckSchedule == null) {
760 // Schedule a message to be periodically sent to check if the current in-progress
761 // transaction should be expired and aborted.
762 FiniteDuration period = Duration.create(transactionCommitTimeout / 3, TimeUnit.MILLISECONDS);
763 txCommitTimeoutCheckSchedule = getContext().system().scheduler().schedule(
764 period, period, getSelf(),
765 TX_COMMIT_TIMEOUT_CHECK_MESSAGE, getContext().dispatcher(), ActorRef.noSender());
770 protected void applyState(final ActorRef clientActor, final String identifier, final Object data) {
772 if(data instanceof ModificationPayload) {
774 applyModificationToState(clientActor, identifier, ((ModificationPayload) data).getModification());
775 } catch (ClassNotFoundException | IOException e) {
776 LOG.error("{}: Error extracting ModificationPayload", persistenceId(), e);
779 else if (data instanceof CompositeModificationPayload) {
780 Object modification = ((CompositeModificationPayload) data).getModification();
782 applyModificationToState(clientActor, identifier, modification);
783 } else if(data instanceof CompositeModificationByteStringPayload ){
784 Object modification = ((CompositeModificationByteStringPayload) data).getModification();
786 applyModificationToState(clientActor, identifier, modification);
788 LOG.error("{}: Unknown state received {} Class loader = {} CompositeNodeMod.ClassLoader = {}",
789 persistenceId(), data, data.getClass().getClassLoader(),
790 CompositeModificationPayload.class.getClassLoader());
793 updateJournalStats();
797 private void applyModificationToState(ActorRef clientActor, String identifier, Object modification) {
798 if(modification == null) {
800 "{}: modification is null - this is very unexpected, clientActor = {}, identifier = {}",
801 persistenceId(), identifier, clientActor != null ? clientActor.path().toString() : null);
802 } else if(clientActor == null) {
803 // There's no clientActor to which to send a commit reply so we must be applying
804 // replicated state from the leader.
805 commitWithNewTransaction(MutableCompositeModification.fromSerializable(modification));
807 // This must be the OK to commit after replication consensus.
808 finishCommit(clientActor, identifier);
812 private void updateJournalStats() {
813 ReplicatedLogEntry lastLogEntry = getLastLogEntry();
815 if (lastLogEntry != null) {
816 shardMBean.setLastLogIndex(lastLogEntry.getIndex());
817 shardMBean.setLastLogTerm(lastLogEntry.getTerm());
820 shardMBean.setCommitIndex(getCommitIndex());
821 shardMBean.setLastApplied(getLastApplied());
822 shardMBean.setInMemoryJournalDataSize(getRaftActorContext().getReplicatedLog().dataSize());
826 protected void createSnapshot() {
827 // Create a transaction actor. We are really going to treat the transaction as a worker
828 // so that this actor does not get block building the snapshot. THe transaction actor will
829 // after processing the CreateSnapshot message.
831 ActorRef createSnapshotTransaction = createTransaction(
832 TransactionProxy.TransactionType.READ_ONLY.ordinal(),
833 "createSnapshot" + ++createSnapshotTransactionCounter, "",
834 DataStoreVersions.CURRENT_VERSION);
836 createSnapshotTransaction.tell(CreateSnapshot.INSTANCE, self());
841 protected void applySnapshot(final byte[] snapshotBytes) {
842 // Since this will be done only on Recovery or when this actor is a Follower
843 // we can safely commit everything in here. We not need to worry about event notifications
844 // as they would have already been disabled on the follower
846 LOG.info("{}: Applying snapshot", persistenceId());
848 DOMStoreWriteTransaction transaction = store.newWriteOnlyTransaction();
850 NormalizedNode<?, ?> node = SerializationUtils.deserializeNormalizedNode(snapshotBytes);
852 // delete everything first
853 transaction.delete(DATASTORE_ROOT);
855 // Add everything from the remote node back
856 transaction.write(DATASTORE_ROOT, node);
857 syncCommitTransaction(transaction);
858 } catch (InterruptedException | ExecutionException e) {
859 LOG.error("{}: An exception occurred when applying snapshot", persistenceId(), e);
861 LOG.info("{}: Done applying snapshot", persistenceId());
866 protected void onStateChanged() {
867 boolean isLeader = isLeader();
868 for (ActorSelection dataChangeListener : dataChangeListeners) {
869 dataChangeListener.tell(new EnableNotification(isLeader), getSelf());
873 for(DelayedListenerRegistration reg: delayedListenerRegistrations) {
874 if(!reg.isClosed()) {
875 reg.setDelegate(doChangeListenerRegistration(reg.getRegisterChangeListener()));
879 delayedListenerRegistrations.clear();
882 shardMBean.setRaftState(getRaftState().name());
883 shardMBean.setCurrentTerm(getCurrentTerm());
885 // If this actor is no longer the leader close all the transaction chains
887 for(Map.Entry<String, DOMStoreTransactionChain> entry : transactionChains.entrySet()){
888 if(LOG.isDebugEnabled()) {
890 "{}: onStateChanged: Closing transaction chain {} because shard {} is no longer the leader",
891 persistenceId(), entry.getKey(), getId());
893 entry.getValue().close();
896 transactionChains.clear();
901 protected DataPersistenceProvider persistence() {
902 return dataPersistenceProvider;
905 @Override protected void onLeaderChanged(final String oldLeader, final String newLeader) {
906 shardMBean.setLeader(newLeader);
909 @Override public String persistenceId() {
910 return this.name.toString();
914 DataPersistenceProvider getDataPersistenceProvider() {
915 return dataPersistenceProvider;
918 private static class ShardCreator implements Creator<Shard> {
920 private static final long serialVersionUID = 1L;
922 final ShardIdentifier name;
923 final Map<ShardIdentifier, String> peerAddresses;
924 final DatastoreContext datastoreContext;
925 final SchemaContext schemaContext;
927 ShardCreator(final ShardIdentifier name, final Map<ShardIdentifier, String> peerAddresses,
928 final DatastoreContext datastoreContext, final SchemaContext schemaContext) {
930 this.peerAddresses = peerAddresses;
931 this.datastoreContext = datastoreContext;
932 this.schemaContext = schemaContext;
936 public Shard create() throws Exception {
937 return new Shard(name, peerAddresses, datastoreContext, schemaContext);
942 InMemoryDOMDataStore getDataStore() {
947 ShardStats getShardMBean() {
951 private static class DelayedListenerRegistration implements
952 ListenerRegistration<AsyncDataChangeListener<YangInstanceIdentifier, NormalizedNode<?, ?>>> {
954 private volatile boolean closed;
956 private final RegisterChangeListener registerChangeListener;
958 private volatile ListenerRegistration<AsyncDataChangeListener<YangInstanceIdentifier,
959 NormalizedNode<?, ?>>> delegate;
961 DelayedListenerRegistration(final RegisterChangeListener registerChangeListener) {
962 this.registerChangeListener = registerChangeListener;
965 void setDelegate( final ListenerRegistration<AsyncDataChangeListener<YangInstanceIdentifier,
966 NormalizedNode<?, ?>>> registration) {
967 this.delegate = registration;
974 RegisterChangeListener getRegisterChangeListener() {
975 return registerChangeListener;
979 public AsyncDataChangeListener<YangInstanceIdentifier, NormalizedNode<?, ?>> getInstance() {
980 return delegate != null ? delegate.getInstance() : null;
984 public void close() {
986 if(delegate != null) {