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.PoisonPill;
14 import akka.actor.Props;
15 import akka.event.Logging;
16 import akka.event.LoggingAdapter;
17 import akka.japi.Creator;
18 import akka.persistence.RecoveryFailure;
19 import akka.serialization.Serialization;
20 import com.google.common.annotations.VisibleForTesting;
21 import com.google.common.base.Optional;
22 import com.google.common.base.Preconditions;
23 import com.google.common.collect.Lists;
24 import com.google.common.util.concurrent.CheckedFuture;
25 import com.google.common.util.concurrent.FutureCallback;
26 import com.google.common.util.concurrent.Futures;
27 import com.google.common.util.concurrent.ListenableFuture;
28 import com.google.protobuf.ByteString;
29 import com.google.protobuf.InvalidProtocolBufferException;
30 import org.opendaylight.controller.cluster.common.actor.CommonConfig;
31 import org.opendaylight.controller.cluster.common.actor.MeteringBehavior;
32 import org.opendaylight.controller.cluster.datastore.identifiers.ShardIdentifier;
33 import org.opendaylight.controller.cluster.datastore.identifiers.ShardTransactionIdentifier;
34 import org.opendaylight.controller.cluster.datastore.jmx.mbeans.shard.ShardMBeanFactory;
35 import org.opendaylight.controller.cluster.datastore.jmx.mbeans.shard.ShardStats;
36 import org.opendaylight.controller.cluster.datastore.messages.ActorInitialized;
37 import org.opendaylight.controller.cluster.datastore.messages.CloseTransactionChain;
38 import org.opendaylight.controller.cluster.datastore.messages.CommitTransactionReply;
39 import org.opendaylight.controller.cluster.datastore.messages.CreateTransaction;
40 import org.opendaylight.controller.cluster.datastore.messages.CreateTransactionReply;
41 import org.opendaylight.controller.cluster.datastore.messages.EnableNotification;
42 import org.opendaylight.controller.cluster.datastore.messages.ForwardedCommitTransaction;
43 import org.opendaylight.controller.cluster.datastore.messages.PeerAddressResolved;
44 import org.opendaylight.controller.cluster.datastore.messages.ReadData;
45 import org.opendaylight.controller.cluster.datastore.messages.ReadDataReply;
46 import org.opendaylight.controller.cluster.datastore.messages.RegisterChangeListener;
47 import org.opendaylight.controller.cluster.datastore.messages.RegisterChangeListenerReply;
48 import org.opendaylight.controller.cluster.datastore.messages.UpdateSchemaContext;
49 import org.opendaylight.controller.cluster.datastore.modification.Modification;
50 import org.opendaylight.controller.cluster.datastore.modification.MutableCompositeModification;
51 import org.opendaylight.controller.cluster.datastore.node.NormalizedNodeToNodeCodec;
52 import org.opendaylight.controller.cluster.raft.RaftActor;
53 import org.opendaylight.controller.cluster.raft.ReplicatedLogEntry;
54 import org.opendaylight.controller.cluster.raft.base.messages.CaptureSnapshotReply;
55 import org.opendaylight.controller.cluster.raft.protobuff.client.messages.CompositeModificationPayload;
56 import org.opendaylight.controller.cluster.raft.protobuff.client.messages.Payload;
57 import org.opendaylight.controller.md.sal.common.api.data.AsyncDataChangeListener;
58 import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
59 import org.opendaylight.controller.md.sal.dom.store.impl.InMemoryDOMDataStore;
60 import org.opendaylight.controller.md.sal.dom.store.impl.InMemoryDOMDataStoreFactory;
61 import org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages;
62 import org.opendaylight.controller.sal.core.spi.data.DOMStoreReadTransaction;
63 import org.opendaylight.controller.sal.core.spi.data.DOMStoreThreePhaseCommitCohort;
64 import org.opendaylight.controller.sal.core.spi.data.DOMStoreTransactionChain;
65 import org.opendaylight.controller.sal.core.spi.data.DOMStoreTransactionFactory;
66 import org.opendaylight.controller.sal.core.spi.data.DOMStoreWriteTransaction;
67 import org.opendaylight.yangtools.concepts.ListenerRegistration;
68 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
69 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
70 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
71 import java.util.ArrayList;
72 import java.util.Collection;
73 import java.util.HashMap;
74 import java.util.List;
76 import java.util.concurrent.ExecutionException;
79 * A Shard represents a portion of the logical data tree <br/>
81 * Our Shard uses InMemoryDataStore as it's internal representation and delegates all requests it
84 public class Shard extends RaftActor {
86 public static final String DEFAULT_NAME = "default";
88 // The state of this Shard
89 private final InMemoryDOMDataStore store;
91 private final Map<Object, DOMStoreThreePhaseCommitCohort>
92 modificationToCohort = new HashMap<>();
94 private final LoggingAdapter LOG =
95 Logging.getLogger(getContext().system(), this);
97 // By default persistent will be true and can be turned off using the system
98 // property shard.persistent
99 private final boolean persistent;
101 /// The name of this shard
102 private final ShardIdentifier name;
104 private final ShardStats shardMBean;
106 private final List<ActorSelection> dataChangeListeners = new ArrayList<>();
108 private final DatastoreContext datastoreContext;
110 private SchemaContext schemaContext;
112 private ActorRef createSnapshotTransaction;
115 * Coordinates persistence recovery on startup.
117 private ShardRecoveryCoordinator recoveryCoordinator;
118 private List<Object> currentLogRecoveryBatch;
120 private final Map<String, DOMStoreTransactionChain> transactionChains = new HashMap<>();
122 protected Shard(ShardIdentifier name, Map<ShardIdentifier, String> peerAddresses,
123 DatastoreContext datastoreContext, SchemaContext schemaContext) {
124 super(name.toString(), mapPeerAddresses(peerAddresses),
125 Optional.of(datastoreContext.getShardRaftConfig()));
128 this.datastoreContext = datastoreContext;
129 this.schemaContext = schemaContext;
131 String setting = System.getProperty("shard.persistent");
133 this.persistent = !"false".equals(setting);
135 LOG.info("Shard created : {} persistent : {}", name, persistent);
137 store = InMemoryDOMDataStoreFactory.create(name.toString(), null,
138 datastoreContext.getDataStoreProperties());
140 if(schemaContext != null) {
141 store.onGlobalContextUpdated(schemaContext);
144 shardMBean = ShardMBeanFactory.getShardStatsMBean(name.toString(),
145 datastoreContext.getDataStoreMXBeanType());
146 shardMBean.setDataStoreExecutor(store.getDomStoreExecutor());
147 shardMBean.setNotificationManager(store.getDataChangeListenerNotificationManager());
149 if (isMetricsCaptureEnabled()) {
150 getContext().become(new MeteringBehavior(this));
154 private static Map<String, String> mapPeerAddresses(
155 Map<ShardIdentifier, String> peerAddresses) {
156 Map<String, String> map = new HashMap<>();
158 for (Map.Entry<ShardIdentifier, String> entry : peerAddresses
160 map.put(entry.getKey().toString(), entry.getValue());
166 public static Props props(final ShardIdentifier name,
167 final Map<ShardIdentifier, String> peerAddresses,
168 DatastoreContext datastoreContext, SchemaContext schemaContext) {
169 Preconditions.checkNotNull(name, "name should not be null");
170 Preconditions.checkNotNull(peerAddresses, "peerAddresses should not be null");
171 Preconditions.checkNotNull(datastoreContext, "dataStoreContext should not be null");
172 Preconditions.checkNotNull(schemaContext, "schemaContext should not be null");
174 return Props.create(new ShardCreator(name, peerAddresses, datastoreContext, schemaContext));
177 @Override public void onReceiveRecover(Object message) {
178 if(LOG.isDebugEnabled()) {
179 LOG.debug("onReceiveRecover: Received message {} from {}",
180 message.getClass().toString(),
184 if (message instanceof RecoveryFailure){
185 LOG.error(((RecoveryFailure) message).cause(), "Recovery failed because of this cause");
187 super.onReceiveRecover(message);
191 @Override public void onReceiveCommand(Object message) {
192 if(LOG.isDebugEnabled()) {
193 LOG.debug("onReceiveCommand: Received message {} from {}",
194 message.getClass().toString(),
198 if(message.getClass().equals(ReadDataReply.SERIALIZABLE_CLASS)) {
199 // This must be for install snapshot. Don't want to open this up and trigger
202 .tell(new CaptureSnapshotReply(ReadDataReply.getNormalizedNodeByteString(message)),
205 createSnapshotTransaction = null;
206 // Send a PoisonPill instead of sending close transaction because we do not really need
208 getSender().tell(PoisonPill.getInstance(), self());
210 } else if (message.getClass().equals(CloseTransactionChain.SERIALIZABLE_CLASS)){
211 closeTransactionChain(CloseTransactionChain.fromSerializable(message));
212 } else if (message instanceof RegisterChangeListener) {
213 registerChangeListener((RegisterChangeListener) message);
214 } else if (message instanceof UpdateSchemaContext) {
215 updateSchemaContext((UpdateSchemaContext) message);
216 } else if (message instanceof ForwardedCommitTransaction) {
217 handleForwardedCommit((ForwardedCommitTransaction) message);
218 } else if (message.getClass()
219 .equals(CreateTransaction.SERIALIZABLE_CLASS)) {
221 createTransaction(CreateTransaction.fromSerializable(message));
222 } else if (getLeader() != null) {
223 getLeader().forward(message, getContext());
225 getSender().tell(new akka.actor.Status.Failure(new IllegalStateException(
226 "Could not find shard leader so transaction cannot be created. This typically happens" +
227 " when system is coming up or recovering and a leader is being elected. Try again" +
228 " later.")), getSelf());
230 } else if (message instanceof PeerAddressResolved) {
231 PeerAddressResolved resolved = (PeerAddressResolved) message;
232 setPeerAddress(resolved.getPeerId().toString(),
233 resolved.getPeerAddress());
235 super.onReceiveCommand(message);
239 private void closeTransactionChain(CloseTransactionChain closeTransactionChain) {
240 DOMStoreTransactionChain chain =
241 transactionChains.remove(closeTransactionChain.getTransactionChainId());
248 private ActorRef createTypedTransactionActor(
250 ShardTransactionIdentifier transactionId,
251 String transactionChainId ) {
253 DOMStoreTransactionFactory factory = store;
255 if(!transactionChainId.isEmpty()) {
256 factory = transactionChains.get(transactionChainId);
258 DOMStoreTransactionChain transactionChain = store.createTransactionChain();
259 transactionChains.put(transactionChainId, transactionChain);
260 factory = transactionChain;
264 if(this.schemaContext == null){
265 throw new NullPointerException("schemaContext should not be null");
269 == TransactionProxy.TransactionType.READ_ONLY.ordinal()) {
271 shardMBean.incrementReadOnlyTransactionCount();
273 return getContext().actorOf(
274 ShardTransaction.props(factory.newReadOnlyTransaction(), getSelf(),
275 schemaContext,datastoreContext, shardMBean), transactionId.toString());
277 } else if (transactionType
278 == TransactionProxy.TransactionType.READ_WRITE.ordinal()) {
280 shardMBean.incrementReadWriteTransactionCount();
282 return getContext().actorOf(
283 ShardTransaction.props(factory.newReadWriteTransaction(), getSelf(),
284 schemaContext, datastoreContext, shardMBean), transactionId.toString());
287 } else if (transactionType
288 == TransactionProxy.TransactionType.WRITE_ONLY.ordinal()) {
290 shardMBean.incrementWriteOnlyTransactionCount();
292 return getContext().actorOf(
293 ShardTransaction.props(factory.newWriteOnlyTransaction(), getSelf(),
294 schemaContext, datastoreContext, shardMBean), transactionId.toString());
296 throw new IllegalArgumentException(
297 "Shard="+name + ":CreateTransaction message has unidentified transaction type="
302 private void createTransaction(CreateTransaction createTransaction) {
303 createTransaction(createTransaction.getTransactionType(),
304 createTransaction.getTransactionId(), createTransaction.getTransactionChainId());
307 private ActorRef createTransaction(int transactionType, String remoteTransactionId, String transactionChainId) {
309 ShardTransactionIdentifier transactionId =
310 ShardTransactionIdentifier.builder()
311 .remoteTransactionId(remoteTransactionId)
313 if(LOG.isDebugEnabled()) {
314 LOG.debug("Creating transaction : {} ", transactionId);
316 ActorRef transactionActor =
317 createTypedTransactionActor(transactionType, transactionId, transactionChainId);
320 .tell(new CreateTransactionReply(
321 Serialization.serializedActorPath(transactionActor),
322 remoteTransactionId).toSerializable(),
325 return transactionActor;
328 private void syncCommitTransaction(DOMStoreWriteTransaction transaction)
329 throws ExecutionException, InterruptedException {
330 DOMStoreThreePhaseCommitCohort commitCohort = transaction.ready();
331 commitCohort.preCommit().get();
332 commitCohort.commit().get();
336 private void commit(final ActorRef sender, Object serialized) {
337 Modification modification = MutableCompositeModification
338 .fromSerializable(serialized, schemaContext);
339 DOMStoreThreePhaseCommitCohort cohort =
340 modificationToCohort.remove(serialized);
341 if (cohort == null) {
342 // If there's no cached cohort then we must be applying replicated state.
343 commitWithNewTransaction(serialized);
348 LOG.error("Commit failed. Sender cannot be null");
352 ListenableFuture<Void> future = cohort.commit();
354 Futures.addCallback(future, new FutureCallback<Void>() {
356 public void onSuccess(Void v) {
357 sender.tell(new CommitTransactionReply().toSerializable(), getSelf());
358 shardMBean.incrementCommittedTransactionCount();
359 shardMBean.setLastCommittedTransactionTime(System.currentTimeMillis());
363 public void onFailure(Throwable t) {
364 LOG.error(t, "An exception happened during commit");
365 shardMBean.incrementFailedTransactionsCount();
366 sender.tell(new akka.actor.Status.Failure(t), getSelf());
372 private void commitWithNewTransaction(Object modification) {
373 DOMStoreWriteTransaction tx = store.newWriteOnlyTransaction();
374 MutableCompositeModification.fromSerializable(modification, schemaContext).apply(tx);
376 syncCommitTransaction(tx);
377 shardMBean.incrementCommittedTransactionCount();
378 } catch (InterruptedException | ExecutionException e) {
379 shardMBean.incrementFailedTransactionsCount();
380 LOG.error(e, "Failed to commit");
384 private void handleForwardedCommit(ForwardedCommitTransaction message) {
385 Object serializedModification =
386 message.getModification().toSerializable();
389 .put(serializedModification, message.getCohort());
392 this.persistData(getSender(), "identifier",
393 new CompositeModificationPayload(serializedModification));
395 this.commit(getSender(), serializedModification);
399 private void updateSchemaContext(UpdateSchemaContext message) {
400 this.schemaContext = message.getSchemaContext();
401 updateSchemaContext(message.getSchemaContext());
402 store.onGlobalContextUpdated(message.getSchemaContext());
405 @VisibleForTesting void updateSchemaContext(SchemaContext schemaContext) {
406 store.onGlobalContextUpdated(schemaContext);
409 private void registerChangeListener(
410 RegisterChangeListener registerChangeListener) {
412 if(LOG.isDebugEnabled()) {
413 LOG.debug("registerDataChangeListener for {}", registerChangeListener
418 ActorSelection dataChangeListenerPath = getContext()
419 .system().actorSelection(
420 registerChangeListener.getDataChangeListenerPath());
423 // Notify the listener if notifications should be enabled or not
424 // If this shard is the leader then it will enable notifications else
426 dataChangeListenerPath
427 .tell(new EnableNotification(isLeader()), getSelf());
429 // Now store a reference to the data change listener so it can be notified
430 // at a later point if notifications should be enabled or disabled
431 dataChangeListeners.add(dataChangeListenerPath);
433 AsyncDataChangeListener<YangInstanceIdentifier, NormalizedNode<?, ?>>
434 listener = new DataChangeListenerProxy(schemaContext, dataChangeListenerPath);
436 ListenerRegistration<AsyncDataChangeListener<YangInstanceIdentifier, NormalizedNode<?, ?>>>
437 registration = store.registerChangeListener(registerChangeListener.getPath(),
438 listener, registerChangeListener.getScope());
439 ActorRef listenerRegistration =
440 getContext().actorOf(
441 DataChangeListenerRegistration.props(registration));
443 if(LOG.isDebugEnabled()) {
445 "registerDataChangeListener sending reply, listenerRegistrationPath = {} "
446 , listenerRegistration.path().toString());
450 .tell(new RegisterChangeListenerReply(listenerRegistration.path()),
454 private boolean isMetricsCaptureEnabled(){
455 CommonConfig config = new CommonConfig(getContext().system().settings().config());
456 return config.isMetricCaptureEnabled();
461 void startLogRecoveryBatch(int maxBatchSize) {
462 currentLogRecoveryBatch = Lists.newArrayListWithCapacity(maxBatchSize);
464 if(LOG.isDebugEnabled()) {
465 LOG.debug("{} : starting log recovery batch with max size {}", persistenceId(), maxBatchSize);
470 protected void appendRecoveredLogEntry(Payload data) {
471 if (data instanceof CompositeModificationPayload) {
472 currentLogRecoveryBatch.add(((CompositeModificationPayload) data).getModification());
474 LOG.error("Unknown state received {} during recovery", data);
479 protected void applyRecoverySnapshot(ByteString snapshot) {
480 if(recoveryCoordinator == null) {
481 recoveryCoordinator = new ShardRecoveryCoordinator(persistenceId(), schemaContext);
484 recoveryCoordinator.submit(snapshot, store.newWriteOnlyTransaction());
486 if(LOG.isDebugEnabled()) {
487 LOG.debug("{} : submitted recovery sbapshot", persistenceId());
492 protected void applyCurrentLogRecoveryBatch() {
493 if(recoveryCoordinator == null) {
494 recoveryCoordinator = new ShardRecoveryCoordinator(persistenceId(), schemaContext);
497 recoveryCoordinator.submit(currentLogRecoveryBatch, store.newWriteOnlyTransaction());
499 if(LOG.isDebugEnabled()) {
500 LOG.debug("{} : submitted log recovery batch with size {}", persistenceId(),
501 currentLogRecoveryBatch.size());
506 protected void onRecoveryComplete() {
507 if(recoveryCoordinator != null) {
508 Collection<DOMStoreWriteTransaction> txList = recoveryCoordinator.getTransactions();
510 if(LOG.isDebugEnabled()) {
511 LOG.debug("{} : recovery complete - committing {} Tx's", persistenceId(), txList.size());
514 for(DOMStoreWriteTransaction tx: txList) {
516 syncCommitTransaction(tx);
517 shardMBean.incrementCommittedTransactionCount();
518 } catch (InterruptedException | ExecutionException e) {
519 shardMBean.incrementFailedTransactionsCount();
520 LOG.error(e, "Failed to commit");
525 recoveryCoordinator = null;
526 currentLogRecoveryBatch = null;
527 updateJournalStats();
529 //notify shard manager
530 getContext().parent().tell(new ActorInitialized(), getSelf());
534 protected void applyState(ActorRef clientActor, String identifier, Object data) {
536 if (data instanceof CompositeModificationPayload) {
537 Object modification = ((CompositeModificationPayload) data).getModification();
539 if (modification != null) {
540 commit(clientActor, modification);
543 "modification is null - this is very unexpected, clientActor = {}, identifier = {}",
544 identifier, clientActor != null ? clientActor.path().toString() : null);
548 LOG.error("Unknown state received {} Class loader = {} CompositeNodeMod.ClassLoader = {}",
549 data, data.getClass().getClassLoader(),
550 CompositeModificationPayload.class.getClassLoader());
553 updateJournalStats();
557 private void updateJournalStats() {
558 ReplicatedLogEntry lastLogEntry = getLastLogEntry();
560 if (lastLogEntry != null) {
561 shardMBean.setLastLogIndex(lastLogEntry.getIndex());
562 shardMBean.setLastLogTerm(lastLogEntry.getTerm());
565 shardMBean.setCommitIndex(getCommitIndex());
566 shardMBean.setLastApplied(getLastApplied());
570 protected void createSnapshot() {
571 if (createSnapshotTransaction == null) {
573 // Create a transaction. We are really going to treat the transaction as a worker
574 // so that this actor does not get block building the snapshot
575 createSnapshotTransaction = createTransaction(
576 TransactionProxy.TransactionType.READ_ONLY.ordinal(),
577 "createSnapshot", "");
579 createSnapshotTransaction.tell(
580 new ReadData(YangInstanceIdentifier.builder().build()).toSerializable(), self());
587 protected void applySnapshot(ByteString snapshot) {
588 // Since this will be done only on Recovery or when this actor is a Follower
589 // we can safely commit everything in here. We not need to worry about event notifications
590 // as they would have already been disabled on the follower
592 LOG.info("Applying snapshot");
594 DOMStoreWriteTransaction transaction = store.newWriteOnlyTransaction();
595 NormalizedNodeMessages.Node serializedNode = NormalizedNodeMessages.Node.parseFrom(snapshot);
596 NormalizedNode<?, ?> node = new NormalizedNodeToNodeCodec(schemaContext)
597 .decode(serializedNode);
599 // delete everything first
600 transaction.delete(YangInstanceIdentifier.builder().build());
602 // Add everything from the remote node back
603 transaction.write(YangInstanceIdentifier.builder().build(), node);
604 syncCommitTransaction(transaction);
605 } catch (InvalidProtocolBufferException | InterruptedException | ExecutionException e) {
606 LOG.error(e, "An exception occurred when applying snapshot");
608 LOG.info("Done applying snapshot");
612 @Override protected void onStateChanged() {
613 for (ActorSelection dataChangeListener : dataChangeListeners) {
615 .tell(new EnableNotification(isLeader()), getSelf());
618 shardMBean.setRaftState(getRaftState().name());
619 shardMBean.setCurrentTerm(getCurrentTerm());
621 // If this actor is no longer the leader close all the transaction chains
623 for(Map.Entry<String, DOMStoreTransactionChain> entry : transactionChains.entrySet()){
624 if(LOG.isDebugEnabled()) {
626 "onStateChanged: Closing transaction chain {} because shard {} is no longer the leader",
627 entry.getKey(), getId());
629 entry.getValue().close();
632 transactionChains.clear();
636 @Override protected void onLeaderChanged(String oldLeader, String newLeader) {
637 shardMBean.setLeader(newLeader);
640 @Override public String persistenceId() {
641 return this.name.toString();
644 private static class ShardCreator implements Creator<Shard> {
646 private static final long serialVersionUID = 1L;
648 final ShardIdentifier name;
649 final Map<ShardIdentifier, String> peerAddresses;
650 final DatastoreContext datastoreContext;
651 final SchemaContext schemaContext;
653 ShardCreator(ShardIdentifier name, Map<ShardIdentifier, String> peerAddresses,
654 DatastoreContext datastoreContext, SchemaContext schemaContext) {
656 this.peerAddresses = peerAddresses;
657 this.datastoreContext = datastoreContext;
658 this.schemaContext = schemaContext;
662 public Shard create() throws Exception {
663 return new Shard(name, peerAddresses, datastoreContext, schemaContext);
668 NormalizedNode<?,?> readStore(YangInstanceIdentifier id)
669 throws ExecutionException, InterruptedException {
670 DOMStoreReadTransaction transaction = store.newReadOnlyTransaction();
672 CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> future =
673 transaction.read(id);
675 Optional<NormalizedNode<?, ?>> optional = future.get();
676 NormalizedNode<?, ?> node = optional.isPresent()? optional.get() : null;
684 void writeToStore(YangInstanceIdentifier id, NormalizedNode<?,?> node)
685 throws ExecutionException, InterruptedException {
686 DOMStoreWriteTransaction transaction = store.newWriteOnlyTransaction();
688 transaction.write(id, node);
690 syncCommitTransaction(transaction);
694 ShardStats getShardMBean() {