221e874fd507b6ce1e52016ae09f33d9a0c5d514
[controller.git] / opendaylight / md-sal / sal-distributed-datastore / src / main / java / org / opendaylight / controller / cluster / datastore / Shard.java
1 /*
2  * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
3  *
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
7  */
8
9 package org.opendaylight.controller.cluster.datastore;
10
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.persistence.Persistent;
18 import akka.persistence.UntypedProcessor;
19 import com.google.common.util.concurrent.ListenableFuture;
20 import com.google.common.util.concurrent.ListeningExecutorService;
21 import com.google.common.util.concurrent.MoreExecutors;
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.ForwardedCommitTransaction;
28 import org.opendaylight.controller.cluster.datastore.messages.NonPersistent;
29 import org.opendaylight.controller.cluster.datastore.messages.RegisterChangeListener;
30 import org.opendaylight.controller.cluster.datastore.messages.RegisterChangeListenerReply;
31 import org.opendaylight.controller.cluster.datastore.messages.UpdateSchemaContext;
32 import org.opendaylight.controller.cluster.datastore.modification.Modification;
33 import org.opendaylight.controller.md.sal.common.api.data.AsyncDataChangeListener;
34 import org.opendaylight.controller.md.sal.dom.store.impl.InMemoryDOMDataStore;
35 import org.opendaylight.controller.sal.core.spi.data.DOMStoreReadWriteTransaction;
36 import org.opendaylight.controller.sal.core.spi.data.DOMStoreThreePhaseCommitCohort;
37 import org.opendaylight.controller.sal.core.spi.data.DOMStoreTransactionChain;
38 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier;
39 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
40
41 import java.util.HashMap;
42 import java.util.Map;
43 import java.util.concurrent.ExecutionException;
44 import java.util.concurrent.Executors;
45
46 /**
47  * A Shard represents a portion of the logical data tree <br/>
48  * <p>
49  * Our Shard uses InMemoryDataStore as it's internal representation and delegates all requests it
50  * </p>
51  */
52 public class Shard extends UntypedProcessor {
53
54     public static final String DEFAULT_NAME = "default";
55
56     private final ListeningExecutorService storeExecutor =
57         MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(2));
58
59     private final InMemoryDOMDataStore store;
60
61     private final Map<Modification, DOMStoreThreePhaseCommitCohort>
62         modificationToCohort = new HashMap<>();
63
64     private final LoggingAdapter log =
65         Logging.getLogger(getContext().system(), this);
66
67     // By default persistent will be true and can be turned off using the system
68     // property persistent
69     private final boolean persistent;
70
71     private Shard(String name) {
72
73         String setting = System.getProperty("shard.persistent");
74         this.persistent = !"false".equals(setting);
75
76         log.info("Creating shard : {} persistent : {}", name , persistent);
77
78         store = new InMemoryDOMDataStore(name, storeExecutor);
79     }
80
81     public static Props props(final String name) {
82         return Props.create(new Creator<Shard>() {
83
84             @Override
85             public Shard create() throws Exception {
86                 return new Shard(name);
87             }
88
89         });
90     }
91
92
93     @Override
94     public void onReceive(Object message) throws Exception {
95         log.debug("Received message {}", message);
96
97         if (message instanceof CreateTransactionChain) {
98             createTransactionChain();
99         } else if (message instanceof RegisterChangeListener) {
100             registerChangeListener((RegisterChangeListener) message);
101         } else if (message instanceof UpdateSchemaContext) {
102             updateSchemaContext((UpdateSchemaContext) message);
103         } else if (message instanceof ForwardedCommitTransaction) {
104             handleForwardedCommit((ForwardedCommitTransaction) message);
105         } else if (message instanceof Persistent) {
106             commit((Modification) ((Persistent) message).payload());
107         } else if (message instanceof CreateTransaction) {
108             createTransaction();
109         } else if(message instanceof NonPersistent){
110             commit((Modification) ((NonPersistent) message).payload());
111         }
112     }
113
114     private void createTransaction() {
115         DOMStoreReadWriteTransaction transaction =
116             store.newReadWriteTransaction();
117         ActorRef transactionActor = getContext().actorOf(
118             ShardTransaction.props(transaction, getSelf()));
119         getSender()
120             .tell(new CreateTransactionReply(transactionActor.path()),
121                 getSelf());
122     }
123
124     private void commit(Modification modification) {
125         DOMStoreThreePhaseCommitCohort cohort =
126             modificationToCohort.remove(modification);
127         if (cohort == null) {
128             log.error(
129                 "Could not find cohort for modification : " + modification);
130             return;
131         }
132         final ListenableFuture<Void> future = cohort.commit();
133         final ActorRef sender = getSender();
134         final ActorRef self = getSelf();
135         future.addListener(new Runnable() {
136             @Override
137             public void run() {
138                 try {
139                     future.get();
140                     sender.tell(new CommitTransactionReply(), self);
141                 } catch (InterruptedException | ExecutionException e) {
142                     log.error(e, "An exception happened when committing");
143                 }
144             }
145         }, getContext().dispatcher());
146     }
147
148     private void handleForwardedCommit(ForwardedCommitTransaction message) {
149         log.info("received forwarded transaction");
150         modificationToCohort
151             .put(message.getModification(), message.getCohort());
152         if(persistent) {
153             getSelf().forward(Persistent.create(message.getModification()),
154                 getContext());
155         } else {
156             getSelf().forward(NonPersistent.create(message.getModification()),
157                 getContext());
158         }
159     }
160
161     private void updateSchemaContext(UpdateSchemaContext message) {
162         store.onGlobalContextUpdated(message.getSchemaContext());
163     }
164
165     private void registerChangeListener(
166         RegisterChangeListener registerChangeListener) {
167
168         ActorSelection dataChangeListenerPath = getContext()
169             .system().actorSelection(registerChangeListener.getDataChangeListenerPath());
170
171         AsyncDataChangeListener<InstanceIdentifier, NormalizedNode<?, ?>>
172             listener = new DataChangeListenerProxy(dataChangeListenerPath);
173
174         org.opendaylight.yangtools.concepts.ListenerRegistration<AsyncDataChangeListener<InstanceIdentifier, NormalizedNode<?, ?>>>
175             registration =
176             store.registerChangeListener(registerChangeListener.getPath(),
177                 listener, registerChangeListener.getScope());
178         ActorRef listenerRegistration =
179             getContext().actorOf(
180                 DataChangeListenerRegistration.props(registration));
181         getSender()
182             .tell(new RegisterChangeListenerReply(listenerRegistration.path()),
183                 getSelf());
184     }
185
186     private void createTransactionChain() {
187         DOMStoreTransactionChain chain = store.createTransactionChain();
188         ActorRef transactionChain =
189             getContext().actorOf(ShardTransactionChain.props(chain));
190         getSender()
191             .tell(new CreateTransactionChainReply(transactionChain.path()),
192                 getSelf());
193     }
194 }

©2013 OpenDaylight, A Linux Foundation Collaborative Project. All Rights Reserved.
OpenDaylight is a registered trademark of The OpenDaylight Project, Inc.
Linux Foundation and OpenDaylight are registered trademarks of the Linux Foundation.
Linux is a registered trademark of Linus Torvalds.