blob: 0b7c095df704c5ac1c8170385c157046e75c2f69 [file] [log] [blame]
Thomas Vachuska96d55b12015-05-11 08:52:03 -07001/*
2 * Copyright 2015 Open Networking Laboratory
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16package org.onosproject.incubator.store.config.impl;
17
18import com.fasterxml.jackson.databind.ObjectMapper;
Jonathan Hart111b42b2015-07-14 13:28:05 -070019import com.fasterxml.jackson.databind.node.ArrayNode;
Thomas Vachuska96d55b12015-05-11 08:52:03 -070020import com.fasterxml.jackson.databind.node.BooleanNode;
21import com.fasterxml.jackson.databind.node.DoubleNode;
22import com.fasterxml.jackson.databind.node.JsonNodeFactory;
23import com.fasterxml.jackson.databind.node.LongNode;
24import com.fasterxml.jackson.databind.node.ObjectNode;
25import com.fasterxml.jackson.databind.node.ShortNode;
26import com.fasterxml.jackson.databind.node.TextNode;
27import com.google.common.collect.ImmutableSet;
28import com.google.common.collect.Maps;
29import org.apache.felix.scr.annotations.Activate;
30import org.apache.felix.scr.annotations.Component;
31import org.apache.felix.scr.annotations.Deactivate;
32import org.apache.felix.scr.annotations.Reference;
33import org.apache.felix.scr.annotations.ReferenceCardinality;
34import org.apache.felix.scr.annotations.Service;
35import org.onlab.util.KryoNamespace;
Thomas Vachuska5f2cbe62015-07-30 15:10:34 -070036import org.onlab.util.Tools;
Thomas Vachuska96d55b12015-05-11 08:52:03 -070037import org.onosproject.incubator.net.config.Config;
38import org.onosproject.incubator.net.config.ConfigApplyDelegate;
39import org.onosproject.incubator.net.config.ConfigFactory;
40import org.onosproject.incubator.net.config.NetworkConfigEvent;
41import org.onosproject.incubator.net.config.NetworkConfigStore;
42import org.onosproject.incubator.net.config.NetworkConfigStoreDelegate;
43import org.onosproject.store.AbstractStore;
44import org.onosproject.store.serializers.KryoNamespaces;
45import org.onosproject.store.service.ConsistentMap;
Thomas Vachuska5f2cbe62015-07-30 15:10:34 -070046import org.onosproject.store.service.ConsistentMapException;
Thomas Vachuska96d55b12015-05-11 08:52:03 -070047import org.onosproject.store.service.MapEvent;
48import org.onosproject.store.service.MapEventListener;
49import org.onosproject.store.service.Serializer;
50import org.onosproject.store.service.StorageService;
51import org.onosproject.store.service.Versioned;
52import org.slf4j.Logger;
53import org.slf4j.LoggerFactory;
54
55import java.util.LinkedHashMap;
56import java.util.Map;
57import java.util.Objects;
58import java.util.Set;
59
60import static org.onosproject.incubator.net.config.NetworkConfigEvent.Type.*;
61
62/**
63 * Implementation of a distributed network configuration store.
64 */
65@Component(immediate = true)
66@Service
67public class DistributedNetworkConfigStore
68 extends AbstractStore<NetworkConfigEvent, NetworkConfigStoreDelegate>
69 implements NetworkConfigStore {
70
Thomas Vachuska5f2cbe62015-07-30 15:10:34 -070071 private static final int MAX_BACKOFF = 10;
72
Thomas Vachuska96d55b12015-05-11 08:52:03 -070073 private final Logger log = LoggerFactory.getLogger(getClass());
74
75 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
76 protected StorageService storageService;
77
78 private ConsistentMap<ConfigKey, ObjectNode> configs;
79
80 private final Map<String, ConfigFactory> factoriesByConfig = Maps.newConcurrentMap();
81 private final ObjectMapper mapper = new ObjectMapper();
82 private final ConfigApplyDelegate applyDelegate = new InternalApplyDelegate();
83 private final MapEventListener<ConfigKey, ObjectNode> listener = new InternalMapListener();
84
85 @Activate
86 public void activate() {
87 KryoNamespace.Builder kryoBuilder = new KryoNamespace.Builder()
88 .register(KryoNamespaces.API)
Jonathan Hart111b42b2015-07-14 13:28:05 -070089 .register(ConfigKey.class, ObjectNode.class, ArrayNode.class,
Thomas Vachuska96d55b12015-05-11 08:52:03 -070090 JsonNodeFactory.class, LinkedHashMap.class,
91 TextNode.class, BooleanNode.class,
92 LongNode.class, DoubleNode.class, ShortNode.class);
93
94 configs = storageService.<ConfigKey, ObjectNode>consistentMapBuilder()
95 .withSerializer(Serializer.using(kryoBuilder.build()))
96 .withName("onos-network-configs")
97 .build();
98 configs.addListener(listener);
99 log.info("Started");
100 }
101
102 @Deactivate
103 public void deactivate() {
104 configs.removeListener(listener);
105 log.info("Stopped");
106 }
107
108 @Override
109 public void addConfigFactory(ConfigFactory configFactory) {
110 factoriesByConfig.put(configFactory.configClass().getName(), configFactory);
Thomas Vachuskae6360222015-07-21 10:10:36 -0700111 notifyDelegate(new NetworkConfigEvent(CONFIG_REGISTERED, configFactory.configKey(),
112 configFactory.configClass()));
Thomas Vachuska96d55b12015-05-11 08:52:03 -0700113 }
114
115 @Override
116 public void removeConfigFactory(ConfigFactory configFactory) {
117 factoriesByConfig.remove(configFactory.configClass().getName());
Thomas Vachuskae6360222015-07-21 10:10:36 -0700118 notifyDelegate(new NetworkConfigEvent(CONFIG_UNREGISTERED, configFactory.configKey(),
119 configFactory.configClass()));
Thomas Vachuska96d55b12015-05-11 08:52:03 -0700120 }
121
122 @Override
123 @SuppressWarnings("unchecked")
124 public <S, C extends Config<S>> ConfigFactory<S, C> getConfigFactory(Class<C> configClass) {
125 return (ConfigFactory<S, C>) factoriesByConfig.get(configClass.getName());
126 }
127
128 @Override
129 @SuppressWarnings("unchecked")
130 public <S> Set<S> getSubjects(Class<S> subjectClass) {
131 ImmutableSet.Builder<S> builder = ImmutableSet.builder();
132 configs.keySet().forEach(k -> {
133 if (subjectClass.isInstance(k.subject)) {
134 builder.add((S) k.subject);
135 }
136 });
137 return builder.build();
138 }
139
140 @Override
141 @SuppressWarnings("unchecked")
142 public <S, C extends Config<S>> Set<S> getSubjects(Class<S> subjectClass, Class<C> configClass) {
143 ImmutableSet.Builder<S> builder = ImmutableSet.builder();
144 String cName = configClass.getName();
145 configs.keySet().forEach(k -> {
146 if (subjectClass.isInstance(k.subject) && cName.equals(k.configClass)) {
147 builder.add((S) k.subject);
148 }
149 });
150 return builder.build();
151 }
152
153 @Override
154 @SuppressWarnings("unchecked")
155 public <S> Set<Class<? extends Config<S>>> getConfigClasses(S subject) {
156 ImmutableSet.Builder<Class<? extends Config<S>>> builder = ImmutableSet.builder();
157 configs.keySet().forEach(k -> {
158 if (Objects.equals(subject, k.subject) && delegate != null) {
159 builder.add(factoriesByConfig.get(k.configClass).configClass());
160 }
161 });
162 return builder.build();
163 }
164
165 @Override
166 public <S, T extends Config<S>> T getConfig(S subject, Class<T> configClass) {
Thomas Vachuska6224a192015-07-30 16:11:40 -0700167 // FIXME: There has to be a better way to absorb the timeout exceptions!
Thomas Vachuska5f2cbe62015-07-30 15:10:34 -0700168 Versioned<ObjectNode> json = null;
169 try {
170 json = configs.get(key(subject, configClass));
Thomas Vachuska6224a192015-07-30 16:11:40 -0700171 } catch (ConsistentMapException e) {
Thomas Vachuska5f2cbe62015-07-30 15:10:34 -0700172 Tools.randomDelay(MAX_BACKOFF);
173 json = configs.get(key(subject, configClass));
174 }
Thomas Vachuska96d55b12015-05-11 08:52:03 -0700175 return json != null ? createConfig(subject, configClass, json.value()) : null;
176 }
177
178
179 @Override
180 public <S, C extends Config<S>> C createConfig(S subject, Class<C> configClass) {
181 Versioned<ObjectNode> json = configs.computeIfAbsent(key(subject, configClass),
182 k -> mapper.createObjectNode());
183 return createConfig(subject, configClass, json.value());
184 }
185
186 @Override
187 public <S, C extends Config<S>> C applyConfig(S subject, Class<C> configClass, ObjectNode json) {
188 return createConfig(subject, configClass,
189 configs.putAndGet(key(subject, configClass), json).value());
190 }
191
192 @Override
193 public <S, C extends Config<S>> void clearConfig(S subject, Class<C> configClass) {
194 configs.remove(key(subject, configClass));
195 }
196
197 /**
198 * Produces a config from the specified subject, config class and raw JSON.
199 *
200 * @param subject config subject
201 * @param configClass config class
202 * @param json raw JSON data
203 * @return config object or null of no factory found or if the specified
204 * JSON is null
205 */
206 @SuppressWarnings("unchecked")
207 private <S, C extends Config<S>> C createConfig(S subject, Class<C> configClass,
208 ObjectNode json) {
209 if (json != null) {
210 ConfigFactory<S, C> factory = factoriesByConfig.get(configClass.getName());
211 if (factory != null) {
212 C config = factory.createConfig();
213 config.init(subject, factory.configKey(), json, mapper, applyDelegate);
214 return config;
215 }
216 }
217 return null;
218 }
219
220
221 // Auxiliary delegate to receive notifications about changes applied to
222 // the network configuration - by the apps.
223 private class InternalApplyDelegate implements ConfigApplyDelegate {
224 @Override
225 public void onApply(Config config) {
226 configs.put(key(config.subject(), config.getClass()), config.node());
227 }
228 }
229
230 // Produces a key for uniquely tracking a subject config.
231 private static ConfigKey key(Object subject, Class<?> configClass) {
232 return new ConfigKey(subject, configClass);
233 }
234
235 // Auxiliary key to track subject configurations.
236 private static final class ConfigKey {
237 final Object subject;
238 final String configClass;
239
240 private ConfigKey(Object subject, Class<?> configClass) {
241 this.subject = subject;
242 this.configClass = configClass.getName();
243 }
244
245 @Override
246 public int hashCode() {
247 return Objects.hash(subject, configClass);
248 }
249
250 @Override
251 public boolean equals(Object obj) {
252 if (this == obj) {
253 return true;
254 }
255 if (obj instanceof ConfigKey) {
256 final ConfigKey other = (ConfigKey) obj;
257 return Objects.equals(this.subject, other.subject)
258 && Objects.equals(this.configClass, other.configClass);
259 }
260 return false;
261 }
262 }
263
264 private class InternalMapListener implements MapEventListener<ConfigKey, ObjectNode> {
265 @Override
266 public void event(MapEvent<ConfigKey, ObjectNode> event) {
267 NetworkConfigEvent.Type type;
268 switch (event.type()) {
269 case INSERT:
270 type = CONFIG_ADDED;
271 break;
272 case UPDATE:
273 type = CONFIG_UPDATED;
274 break;
275 case REMOVE:
276 default:
277 type = CONFIG_REMOVED;
278 break;
279 }
280 ConfigFactory factory = factoriesByConfig.get(event.key().configClass);
281 if (factory != null) {
282 notifyDelegate(new NetworkConfigEvent(type, event.key().subject,
283 factory.configClass()));
284 }
285 }
286 }
287}