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.Props;
14 import akka.event.Logging;
15 import akka.event.LoggingAdapter;
16 import akka.japi.Creator;
17 import akka.serialization.Serialization;
18 import com.google.common.base.Optional;
19 import com.google.common.util.concurrent.ListenableFuture;
20 import org.opendaylight.controller.cluster.datastore.jmx.mbeans.shard.ShardMBeanFactory;
21 import org.opendaylight.controller.cluster.datastore.jmx.mbeans.shard.ShardStats;
22 import org.opendaylight.controller.cluster.datastore.messages.CommitTransactionReply;
23 import org.opendaylight.controller.cluster.datastore.messages.CreateTransaction;
24 import org.opendaylight.controller.cluster.datastore.messages.CreateTransactionChain;
25 import org.opendaylight.controller.cluster.datastore.messages.CreateTransactionChainReply;
26 import org.opendaylight.controller.cluster.datastore.messages.CreateTransactionReply;
27 import org.opendaylight.controller.cluster.datastore.messages.EnableNotification;
28 import org.opendaylight.controller.cluster.datastore.messages.ForwardedCommitTransaction;
29 import org.opendaylight.controller.cluster.datastore.messages.PeerAddressResolved;
30 import org.opendaylight.controller.cluster.datastore.messages.RegisterChangeListener;
31 import org.opendaylight.controller.cluster.datastore.messages.RegisterChangeListenerReply;
32 import org.opendaylight.controller.cluster.datastore.messages.UpdateSchemaContext;
33 import org.opendaylight.controller.cluster.datastore.modification.Modification;
34 import org.opendaylight.controller.cluster.datastore.modification.MutableCompositeModification;
35 import org.opendaylight.controller.cluster.raft.ConfigParams;
36 import org.opendaylight.controller.cluster.raft.DefaultConfigParamsImpl;
37 import org.opendaylight.controller.cluster.raft.RaftActor;
38 import org.opendaylight.controller.cluster.raft.ReplicatedLogEntry;
39 import org.opendaylight.controller.md.sal.common.api.data.AsyncDataChangeListener;
40 import org.opendaylight.controller.md.sal.dom.store.impl.InMemoryDOMDataStore;
41 import org.opendaylight.controller.md.sal.dom.store.impl.InMemoryDOMDataStoreFactory;
42 import org.opendaylight.controller.sal.core.spi.data.DOMStoreReadWriteTransaction;
43 import org.opendaylight.controller.sal.core.spi.data.DOMStoreThreePhaseCommitCohort;
44 import org.opendaylight.controller.sal.core.spi.data.DOMStoreTransactionChain;
45 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
46 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
47 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
48 import scala.concurrent.duration.FiniteDuration;
50 import java.util.ArrayList;
51 import java.util.HashMap;
52 import java.util.List;
54 import java.util.concurrent.ExecutionException;
55 import java.util.concurrent.TimeUnit;
58 * A Shard represents a portion of the logical data tree <br/>
60 * Our Shard uses InMemoryDataStore as it's internal representation and delegates all requests it
63 public class Shard extends RaftActor {
65 private static final ConfigParams configParams = new ShardConfigParams();
67 public static final String DEFAULT_NAME = "default";
69 private final InMemoryDOMDataStore store;
71 private final Map<Object, DOMStoreThreePhaseCommitCohort>
72 modificationToCohort = new HashMap<>();
74 private final LoggingAdapter LOG =
75 Logging.getLogger(getContext().system(), this);
77 // By default persistent will be true and can be turned off using the system
78 // property persistent
79 private final boolean persistent;
81 private final String name;
83 private volatile SchemaContext schemaContext;
85 private final ShardStats shardMBean;
87 private final List<ActorSelection> dataChangeListeners = new ArrayList<>();
89 private Shard(String name, Map<String, String> peerAddresses) {
90 super(name, peerAddresses, Optional.of(configParams));
94 String setting = System.getProperty("shard.persistent");
96 this.persistent = !"false".equals(setting);
98 LOG.info("Creating shard : {} persistent : {}", name, persistent);
100 store = InMemoryDOMDataStoreFactory.create(name, null);
102 shardMBean = ShardMBeanFactory.getShardStatsMBean(name);
106 public static Props props(final String name,
107 final Map<String, String> peerAddresses) {
108 return Props.create(new Creator<Shard>() {
111 public Shard create() throws Exception {
112 return new Shard(name, peerAddresses);
119 @Override public void onReceiveCommand(Object message) {
120 LOG.debug("Received message {} from {}", message.getClass().toString(),
123 if (message.getClass()
124 .equals(CreateTransactionChain.SERIALIZABLE_CLASS)) {
126 createTransactionChain();
127 } else if (getLeader() != null) {
128 getLeader().forward(message, getContext());
130 } else if (message instanceof RegisterChangeListener) {
131 registerChangeListener((RegisterChangeListener) message);
132 } else if (message instanceof UpdateSchemaContext) {
133 updateSchemaContext((UpdateSchemaContext) message);
134 } else if (message instanceof ForwardedCommitTransaction) {
135 handleForwardedCommit((ForwardedCommitTransaction) message);
136 } else if (message.getClass()
137 .equals(CreateTransaction.SERIALIZABLE_CLASS)) {
139 createTransaction(CreateTransaction.fromSerializable(message));
140 } else if (getLeader() != null) {
141 getLeader().forward(message, getContext());
143 } else if (message instanceof PeerAddressResolved) {
144 PeerAddressResolved resolved = (PeerAddressResolved) message;
145 setPeerAddress(resolved.getPeerId(), resolved.getPeerAddress());
147 super.onReceiveCommand(message);
151 private ActorRef createTypedTransactionActor(
152 CreateTransaction createTransaction, String transactionId) {
153 if (createTransaction.getTransactionType()
154 == TransactionProxy.TransactionType.READ_ONLY.ordinal()) {
155 shardMBean.incrementReadOnlyTransactionCount();
156 return getContext().actorOf(
158 .props(store.newReadOnlyTransaction(), getSelf(),
159 schemaContext), transactionId);
161 } else if (createTransaction.getTransactionType()
162 == TransactionProxy.TransactionType.READ_WRITE.ordinal()) {
163 shardMBean.incrementReadWriteTransactionCount();
164 return getContext().actorOf(
166 .props(store.newReadWriteTransaction(), getSelf(),
167 schemaContext), transactionId);
170 } else if (createTransaction.getTransactionType()
171 == TransactionProxy.TransactionType.WRITE_ONLY.ordinal()) {
172 shardMBean.incrementWriteOnlyTransactionCount();
173 return getContext().actorOf(
175 .props(store.newWriteOnlyTransaction(), getSelf(),
176 schemaContext), transactionId);
178 throw new IllegalArgumentException(
179 "CreateTransaction message has unidentified transaction type="
180 + createTransaction.getTransactionType());
184 private void createTransaction(CreateTransaction createTransaction) {
186 String transactionId = "shard-" + createTransaction.getTransactionId();
187 LOG.info("Creating transaction : {} ", transactionId);
188 ActorRef transactionActor =
189 createTypedTransactionActor(createTransaction, transactionId);
192 .tell(new CreateTransactionReply(
193 Serialization.serializedActorPath(transactionActor),
194 createTransaction.getTransactionId()).toSerializable(),
199 private void commit(final ActorRef sender, Object serialized) {
200 Modification modification =
201 MutableCompositeModification.fromSerializable(
202 serialized, schemaContext);
203 DOMStoreThreePhaseCommitCohort cohort =
204 modificationToCohort.remove(serialized);
205 if (cohort == null) {
207 "Could not find cohort for modification : {}", modification);
208 LOG.info("Writing modification using a new transaction");
209 DOMStoreReadWriteTransaction transaction =
210 store.newReadWriteTransaction();
211 modification.apply(transaction);
212 DOMStoreThreePhaseCommitCohort commitCohort = transaction.ready();
213 ListenableFuture<Void> future =
214 commitCohort.preCommit();
217 future = commitCohort.commit();
219 } catch (InterruptedException e) {
220 LOG.error("Failed to commit", e);
221 } catch (ExecutionException e) {
222 LOG.error("Failed to commit", e);
226 final ListenableFuture<Void> future = cohort.commit();
227 shardMBean.incrementCommittedTransactionCount();
228 final ActorRef self = getSelf();
229 future.addListener(new Runnable() {
235 if (sender != null) {
237 .tell(new CommitTransactionReply().toSerializable(),
240 LOG.error("sender is null ???");
242 } catch (InterruptedException | ExecutionException e) {
243 // FIXME : Handle this properly
244 LOG.error(e, "An exception happened when committing");
247 }, getContext().dispatcher());
250 private void handleForwardedCommit(ForwardedCommitTransaction message) {
251 Object serializedModification =
252 message.getModification().toSerializable();
255 .put(serializedModification, message.getCohort());
258 this.persistData(getSender(), "identifier",
259 new CompositeModificationPayload(serializedModification));
261 this.commit(getSender(), serializedModification);
265 private void updateSchemaContext(UpdateSchemaContext message) {
266 this.schemaContext = message.getSchemaContext();
267 store.onGlobalContextUpdated(message.getSchemaContext());
270 private void registerChangeListener(
271 RegisterChangeListener registerChangeListener) {
273 LOG.debug("registerDataChangeListener for " + registerChangeListener
277 ActorSelection dataChangeListenerPath = getContext()
278 .system().actorSelection(
279 registerChangeListener.getDataChangeListenerPath());
282 // Notify the listener if notifications should be enabled or not
283 // If this shard is the leader then it will enable notifications else
285 dataChangeListenerPath
286 .tell(new EnableNotification(isLeader()), getSelf());
288 // Now store a reference to the data change listener so it can be notified
289 // at a later point if notifications should be enabled or disabled
290 dataChangeListeners.add(dataChangeListenerPath);
292 AsyncDataChangeListener<YangInstanceIdentifier, NormalizedNode<?, ?>>
294 new DataChangeListenerProxy(schemaContext, dataChangeListenerPath);
296 org.opendaylight.yangtools.concepts.ListenerRegistration<AsyncDataChangeListener<YangInstanceIdentifier, NormalizedNode<?, ?>>>
298 store.registerChangeListener(registerChangeListener.getPath(),
299 listener, registerChangeListener.getScope());
300 ActorRef listenerRegistration =
301 getContext().actorOf(
302 DataChangeListenerRegistration.props(registration));
305 "registerDataChangeListener sending reply, listenerRegistrationPath = "
306 + listenerRegistration.path().toString());
309 .tell(new RegisterChangeListenerReply(listenerRegistration.path()),
313 private void createTransactionChain() {
314 DOMStoreTransactionChain chain = store.createTransactionChain();
315 ActorRef transactionChain =
316 getContext().actorOf(
317 ShardTransactionChain.props(chain, schemaContext));
319 .tell(new CreateTransactionChainReply(transactionChain.path())
325 @Override protected void applyState(ActorRef clientActor, String identifier,
328 if (data instanceof CompositeModificationPayload) {
329 Object modification =
330 ((CompositeModificationPayload) data).getModification();
332 if (modification != null) {
333 commit(clientActor, modification);
335 LOG.error("modification is null - this is very unexpected");
340 LOG.error("Unknown state received {}", data);
343 ReplicatedLogEntry lastLogEntry = getLastLogEntry();
345 if(lastLogEntry != null){
346 shardMBean.setLastLogIndex(lastLogEntry.getIndex());
347 shardMBean.setLastLogTerm(lastLogEntry.getTerm());
350 shardMBean.setCommitIndex(getCommitIndex());
351 shardMBean.setLastApplied(getLastApplied());
355 @Override protected Object createSnapshot() {
356 throw new UnsupportedOperationException("createSnapshot");
359 @Override protected void applySnapshot(Object snapshot) {
360 throw new UnsupportedOperationException("applySnapshot");
363 @Override protected void onStateChanged() {
364 for (ActorSelection dataChangeListener : dataChangeListeners) {
366 .tell(new EnableNotification(isLeader()), getSelf());
369 if (getLeaderId() != null) {
370 shardMBean.setLeader(getLeaderId());
373 shardMBean.setRaftState(getRaftState().name());
374 shardMBean.setCurrentTerm(getCurrentTerm());
377 @Override public String persistenceId() {
382 private static class ShardConfigParams extends DefaultConfigParamsImpl {
383 public static final FiniteDuration HEART_BEAT_INTERVAL =
384 new FiniteDuration(500, TimeUnit.MILLISECONDS);
386 @Override public FiniteDuration getHeartBeatInterval() {
387 return HEART_BEAT_INTERVAL;