blob: 4a31aff27269ae606dd5fa54938d2043f675dfaa [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 */
Thomas Vachuska4998caa2015-08-26 13:28:38 -070016package org.onosproject.store.config.impl;
Thomas Vachuska96d55b12015-05-11 08:52:03 -070017
Thomas Vachuska0a400ea2015-09-04 11:25:03 -070018import com.fasterxml.jackson.databind.JsonNode;
Thomas Vachuska96d55b12015-05-11 08:52:03 -070019import com.fasterxml.jackson.databind.ObjectMapper;
Jonathan Hart111b42b2015-07-14 13:28:05 -070020import com.fasterxml.jackson.databind.node.ArrayNode;
Thomas Vachuska96d55b12015-05-11 08:52:03 -070021import com.fasterxml.jackson.databind.node.BooleanNode;
22import com.fasterxml.jackson.databind.node.DoubleNode;
Ayaka Koshibe1a002512015-09-03 13:09:23 -070023import com.fasterxml.jackson.databind.node.IntNode;
Thomas Vachuska96d55b12015-05-11 08:52:03 -070024import com.fasterxml.jackson.databind.node.JsonNodeFactory;
25import com.fasterxml.jackson.databind.node.LongNode;
HIGUCHI Yutad9fe3a32015-11-24 18:52:25 -080026import com.fasterxml.jackson.databind.node.NullNode;
Thomas Vachuska96d55b12015-05-11 08:52:03 -070027import com.fasterxml.jackson.databind.node.ObjectNode;
28import com.fasterxml.jackson.databind.node.ShortNode;
29import com.fasterxml.jackson.databind.node.TextNode;
30import com.google.common.collect.ImmutableSet;
31import com.google.common.collect.Maps;
Thomas Vachuska6f350ed2016-01-08 09:53:03 -080032import com.google.common.collect.Sets;
Thomas Vachuska96d55b12015-05-11 08:52:03 -070033import org.apache.felix.scr.annotations.Activate;
34import org.apache.felix.scr.annotations.Component;
35import org.apache.felix.scr.annotations.Deactivate;
36import org.apache.felix.scr.annotations.Reference;
37import org.apache.felix.scr.annotations.ReferenceCardinality;
38import org.apache.felix.scr.annotations.Service;
39import org.onlab.util.KryoNamespace;
Thomas Vachuska5f2cbe62015-07-30 15:10:34 -070040import org.onlab.util.Tools;
Ray Milkeya4122362015-08-18 15:19:08 -070041import org.onosproject.net.config.Config;
42import org.onosproject.net.config.ConfigApplyDelegate;
43import org.onosproject.net.config.ConfigFactory;
44import org.onosproject.net.config.NetworkConfigEvent;
45import org.onosproject.net.config.NetworkConfigStore;
46import org.onosproject.net.config.NetworkConfigStoreDelegate;
Thomas Vachuska96d55b12015-05-11 08:52:03 -070047import org.onosproject.store.AbstractStore;
48import org.onosproject.store.serializers.KryoNamespaces;
49import org.onosproject.store.service.ConsistentMap;
Thomas Vachuska5f2cbe62015-07-30 15:10:34 -070050import org.onosproject.store.service.ConsistentMapException;
Thomas Vachuska96d55b12015-05-11 08:52:03 -070051import org.onosproject.store.service.MapEvent;
52import org.onosproject.store.service.MapEventListener;
53import org.onosproject.store.service.Serializer;
54import org.onosproject.store.service.StorageService;
55import org.onosproject.store.service.Versioned;
56import org.slf4j.Logger;
57import org.slf4j.LoggerFactory;
58
59import java.util.LinkedHashMap;
60import java.util.Map;
61import java.util.Objects;
62import java.util.Set;
63
Thomas Vachuskace0bbb32015-11-18 16:56:10 -080064import static com.google.common.base.Preconditions.checkArgument;
Ray Milkeya4122362015-08-18 15:19:08 -070065import static org.onosproject.net.config.NetworkConfigEvent.Type.*;
Thomas Vachuska96d55b12015-05-11 08:52:03 -070066
67/**
68 * Implementation of a distributed network configuration store.
69 */
70@Component(immediate = true)
71@Service
72public class DistributedNetworkConfigStore
73 extends AbstractStore<NetworkConfigEvent, NetworkConfigStoreDelegate>
74 implements NetworkConfigStore {
75
76 private final Logger log = LoggerFactory.getLogger(getClass());
77
Thomas Vachuskace0bbb32015-11-18 16:56:10 -080078 private static final int MAX_BACKOFF = 10;
79 private static final String INVALID_CONFIG_JSON =
80 "JSON node does not contain valid configuration";
81
Thomas Vachuska96d55b12015-05-11 08:52:03 -070082 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
83 protected StorageService storageService;
84
Thomas Vachuska0a400ea2015-09-04 11:25:03 -070085 private ConsistentMap<ConfigKey, JsonNode> configs;
Thomas Vachuska96d55b12015-05-11 08:52:03 -070086
87 private final Map<String, ConfigFactory> factoriesByConfig = Maps.newConcurrentMap();
88 private final ObjectMapper mapper = new ObjectMapper();
89 private final ConfigApplyDelegate applyDelegate = new InternalApplyDelegate();
Thomas Vachuska0a400ea2015-09-04 11:25:03 -070090 private final MapEventListener<ConfigKey, JsonNode> listener = new InternalMapListener();
Thomas Vachuska96d55b12015-05-11 08:52:03 -070091
92 @Activate
93 public void activate() {
94 KryoNamespace.Builder kryoBuilder = new KryoNamespace.Builder()
95 .register(KryoNamespaces.API)
Jonathan Hart111b42b2015-07-14 13:28:05 -070096 .register(ConfigKey.class, ObjectNode.class, ArrayNode.class,
Thomas Vachuska96d55b12015-05-11 08:52:03 -070097 JsonNodeFactory.class, LinkedHashMap.class,
98 TextNode.class, BooleanNode.class,
HIGUCHI Yutad9fe3a32015-11-24 18:52:25 -080099 LongNode.class, DoubleNode.class, ShortNode.class, IntNode.class,
100 NullNode.class);
Thomas Vachuska96d55b12015-05-11 08:52:03 -0700101
Thomas Vachuska0a400ea2015-09-04 11:25:03 -0700102 configs = storageService.<ConfigKey, JsonNode>consistentMapBuilder()
Thomas Vachuska96d55b12015-05-11 08:52:03 -0700103 .withSerializer(Serializer.using(kryoBuilder.build()))
104 .withName("onos-network-configs")
Madan Jampani3d6a2f62015-08-12 07:19:07 -0700105 .withRelaxedReadConsistency()
Thomas Vachuska96d55b12015-05-11 08:52:03 -0700106 .build();
107 configs.addListener(listener);
108 log.info("Started");
109 }
110
111 @Deactivate
112 public void deactivate() {
113 configs.removeListener(listener);
114 log.info("Stopped");
115 }
116
117 @Override
118 public void addConfigFactory(ConfigFactory configFactory) {
119 factoriesByConfig.put(configFactory.configClass().getName(), configFactory);
Thomas Vachuska6f350ed2016-01-08 09:53:03 -0800120 processPendingConfigs(configFactory);
Thomas Vachuskae6360222015-07-21 10:10:36 -0700121 notifyDelegate(new NetworkConfigEvent(CONFIG_REGISTERED, configFactory.configKey(),
122 configFactory.configClass()));
Thomas Vachuska96d55b12015-05-11 08:52:03 -0700123 }
124
Thomas Vachuska6f350ed2016-01-08 09:53:03 -0800125 // Sweep through any pending configurations, validate them and then prune them.
126 private void processPendingConfigs(ConfigFactory configFactory) {
127 Set<ConfigKey> toBePruned = Sets.newHashSet();
128 configs.keySet().forEach(k -> {
129 if (Objects.equals(k.configKey, configFactory.configKey())) {
130 validateConfig(k, configFactory, configs.get(k).value());
131 toBePruned.add(k); // Prune whether valid or not
132 }
133 });
134 toBePruned.forEach(configs::remove);
135 }
136
137 @SuppressWarnings("unchecked")
138 private void validateConfig(ConfigKey key, ConfigFactory configFactory, JsonNode json) {
139 Config config = createConfig(key.subject, configFactory.configClass(), json);
140 try {
141 checkArgument(config.isValid(), INVALID_CONFIG_JSON);
142 configs.putAndGet(key(key.subject, configFactory.configClass()), json);
143 } catch (Exception e) {
144 log.warn("Failed to validate pending {} configuration for {}: {}",
145 key.configKey, configFactory.subjectFactory().subjectKey(key.subject), json);
146 }
147 }
148
Thomas Vachuska96d55b12015-05-11 08:52:03 -0700149 @Override
150 public void removeConfigFactory(ConfigFactory configFactory) {
151 factoriesByConfig.remove(configFactory.configClass().getName());
Thomas Vachuskae6360222015-07-21 10:10:36 -0700152 notifyDelegate(new NetworkConfigEvent(CONFIG_UNREGISTERED, configFactory.configKey(),
153 configFactory.configClass()));
Thomas Vachuska96d55b12015-05-11 08:52:03 -0700154 }
155
156 @Override
157 @SuppressWarnings("unchecked")
158 public <S, C extends Config<S>> ConfigFactory<S, C> getConfigFactory(Class<C> configClass) {
159 return (ConfigFactory<S, C>) factoriesByConfig.get(configClass.getName());
160 }
161
162 @Override
163 @SuppressWarnings("unchecked")
164 public <S> Set<S> getSubjects(Class<S> subjectClass) {
165 ImmutableSet.Builder<S> builder = ImmutableSet.builder();
166 configs.keySet().forEach(k -> {
167 if (subjectClass.isInstance(k.subject)) {
168 builder.add((S) k.subject);
169 }
170 });
171 return builder.build();
172 }
173
174 @Override
175 @SuppressWarnings("unchecked")
176 public <S, C extends Config<S>> Set<S> getSubjects(Class<S> subjectClass, Class<C> configClass) {
177 ImmutableSet.Builder<S> builder = ImmutableSet.builder();
178 String cName = configClass.getName();
179 configs.keySet().forEach(k -> {
Thomas Vachuska6f350ed2016-01-08 09:53:03 -0800180 if (subjectClass.isInstance(k.subject) && Objects.equals(cName, k.configClass)) {
Thomas Vachuska96d55b12015-05-11 08:52:03 -0700181 builder.add((S) k.subject);
182 }
183 });
184 return builder.build();
185 }
186
187 @Override
188 @SuppressWarnings("unchecked")
189 public <S> Set<Class<? extends Config<S>>> getConfigClasses(S subject) {
190 ImmutableSet.Builder<Class<? extends Config<S>>> builder = ImmutableSet.builder();
191 configs.keySet().forEach(k -> {
Thomas Vachuska6f350ed2016-01-08 09:53:03 -0800192 if (Objects.equals(subject, k.subject) && k.configClass != null && delegate != null) {
Thomas Vachuska96d55b12015-05-11 08:52:03 -0700193 builder.add(factoriesByConfig.get(k.configClass).configClass());
194 }
195 });
196 return builder.build();
197 }
198
199 @Override
200 public <S, T extends Config<S>> T getConfig(S subject, Class<T> configClass) {
Madan Jampania29c6772015-08-17 13:17:07 -0700201 // TODO: need to identify and address the root cause for timeouts.
Thomas Vachuska0a400ea2015-09-04 11:25:03 -0700202 Versioned<JsonNode> json = Tools.retryable(configs::get, ConsistentMapException.class, 1, MAX_BACKOFF)
203 .apply(key(subject, configClass));
Thomas Vachuska96d55b12015-05-11 08:52:03 -0700204 return json != null ? createConfig(subject, configClass, json.value()) : null;
205 }
206
207
208 @Override
209 public <S, C extends Config<S>> C createConfig(S subject, Class<C> configClass) {
Thomas Vachuska0a400ea2015-09-04 11:25:03 -0700210 ConfigFactory<S, C> factory = getConfigFactory(configClass);
211 Versioned<JsonNode> json = configs.computeIfAbsent(key(subject, configClass),
212 k -> factory.isList() ?
213 mapper.createArrayNode() :
214 mapper.createObjectNode());
Thomas Vachuska96d55b12015-05-11 08:52:03 -0700215 return createConfig(subject, configClass, json.value());
216 }
217
218 @Override
Thomas Vachuska0a400ea2015-09-04 11:25:03 -0700219 public <S, C extends Config<S>> C applyConfig(S subject, Class<C> configClass, JsonNode json) {
Thomas Vachuskace0bbb32015-11-18 16:56:10 -0800220 // Create the configuration and validate it.
221 C config = createConfig(subject, configClass, json);
222 checkArgument(config.isValid(), INVALID_CONFIG_JSON);
223
224 // Insert the validated configuration and get it back.
225 Versioned<JsonNode> versioned = configs.putAndGet(key(subject, configClass), json);
226
227 // Re-create the config if for some reason what we attempted to put
228 // was supplanted by someone else already.
Thomas Vachuska6f350ed2016-01-08 09:53:03 -0800229 return versioned.value() == json ? config : createConfig(subject, configClass, versioned.value());
230 }
231
232 @Override
233 public <S> void queueConfig(S subject, String configKey, JsonNode json) {
234 configs.put(key(subject, configKey), json);
Thomas Vachuska96d55b12015-05-11 08:52:03 -0700235 }
236
237 @Override
238 public <S, C extends Config<S>> void clearConfig(S subject, Class<C> configClass) {
239 configs.remove(key(subject, configClass));
240 }
241
Thomas Vachuska6f350ed2016-01-08 09:53:03 -0800242 @Override
243 public <S> void clearQueuedConfig(S subject, String configKey) {
244 configs.remove(key(subject, configKey));
245 }
246
Thomas Vachuska96d55b12015-05-11 08:52:03 -0700247 /**
248 * Produces a config from the specified subject, config class and raw JSON.
249 *
250 * @param subject config subject
251 * @param configClass config class
252 * @param json raw JSON data
253 * @return config object or null of no factory found or if the specified
254 * JSON is null
255 */
256 @SuppressWarnings("unchecked")
257 private <S, C extends Config<S>> C createConfig(S subject, Class<C> configClass,
Thomas Vachuska0a400ea2015-09-04 11:25:03 -0700258 JsonNode json) {
Thomas Vachuska96d55b12015-05-11 08:52:03 -0700259 if (json != null) {
260 ConfigFactory<S, C> factory = factoriesByConfig.get(configClass.getName());
261 if (factory != null) {
262 C config = factory.createConfig();
263 config.init(subject, factory.configKey(), json, mapper, applyDelegate);
264 return config;
265 }
266 }
267 return null;
268 }
269
Charles Chan023a8982016-02-04 11:00:41 -0800270 /**
271 * Produces a detached config from the specified subject, config class and
272 * raw JSON.
273 *
274 * A detached config can no longer be applied. This should be used only for
275 * passing the config object in the NetworkConfigEvent.
276 *
277 * @param subject config subject
278 * @param configClass config class
279 * @param json raw JSON data
280 * @return config object or null of no factory found or if the specified
281 * JSON is null
282 */
283 @SuppressWarnings("unchecked")
284 private Config createDetachedConfig(Object subject,
285 Class configClass, JsonNode json) {
286 if (json != null) {
287 ConfigFactory factory = factoriesByConfig.get(configClass.getName());
288 if (factory != null) {
289 Config config = factory.createConfig();
290 config.init(subject, factory.configKey(), json, mapper, null);
291 return config;
292 }
293 }
294 return null;
295 }
296
Thomas Vachuska96d55b12015-05-11 08:52:03 -0700297
298 // Auxiliary delegate to receive notifications about changes applied to
299 // the network configuration - by the apps.
300 private class InternalApplyDelegate implements ConfigApplyDelegate {
301 @Override
302 public void onApply(Config config) {
303 configs.put(key(config.subject(), config.getClass()), config.node());
304 }
305 }
306
307 // Produces a key for uniquely tracking a subject config.
308 private static ConfigKey key(Object subject, Class<?> configClass) {
309 return new ConfigKey(subject, configClass);
310 }
311
Thomas Vachuska6f350ed2016-01-08 09:53:03 -0800312 // Produces a key for uniquely tracking a subject config.
313 private static ConfigKey key(Object subject, String configKey) {
314 return new ConfigKey(subject, configKey);
315 }
316
Thomas Vachuska96d55b12015-05-11 08:52:03 -0700317 // Auxiliary key to track subject configurations.
Thomas Vachuska6f350ed2016-01-08 09:53:03 -0800318 // Keys with non-null configKey are pending configurations.
Thomas Vachuska96d55b12015-05-11 08:52:03 -0700319 private static final class ConfigKey {
320 final Object subject;
Thomas Vachuska6f350ed2016-01-08 09:53:03 -0800321 final String configKey;
Thomas Vachuska96d55b12015-05-11 08:52:03 -0700322 final String configClass;
323
Thomas Vachuska6f350ed2016-01-08 09:53:03 -0800324 // Create a key for pending configuration class
325 private ConfigKey(Object subject, String configKey) {
326 this.subject = subject;
327 this.configKey = configKey;
328 this.configClass = null;
329 }
330
331 // Create a key for registered class configuration
Thomas Vachuska96d55b12015-05-11 08:52:03 -0700332 private ConfigKey(Object subject, Class<?> configClass) {
333 this.subject = subject;
Thomas Vachuska6f350ed2016-01-08 09:53:03 -0800334 this.configKey = null;
Thomas Vachuska96d55b12015-05-11 08:52:03 -0700335 this.configClass = configClass.getName();
336 }
337
338 @Override
339 public int hashCode() {
Thomas Vachuska6f350ed2016-01-08 09:53:03 -0800340 return Objects.hash(subject, configKey, configClass);
Thomas Vachuska96d55b12015-05-11 08:52:03 -0700341 }
342
343 @Override
344 public boolean equals(Object obj) {
345 if (this == obj) {
346 return true;
347 }
348 if (obj instanceof ConfigKey) {
349 final ConfigKey other = (ConfigKey) obj;
350 return Objects.equals(this.subject, other.subject)
Thomas Vachuska6f350ed2016-01-08 09:53:03 -0800351 && Objects.equals(this.configKey, other.configKey)
Thomas Vachuska96d55b12015-05-11 08:52:03 -0700352 && Objects.equals(this.configClass, other.configClass);
353 }
354 return false;
355 }
356 }
357
Thomas Vachuska0a400ea2015-09-04 11:25:03 -0700358 private class InternalMapListener implements MapEventListener<ConfigKey, JsonNode> {
Thomas Vachuska96d55b12015-05-11 08:52:03 -0700359 @Override
Thomas Vachuska0a400ea2015-09-04 11:25:03 -0700360 public void event(MapEvent<ConfigKey, JsonNode> event) {
Thomas Vachuska6f350ed2016-01-08 09:53:03 -0800361 // Do not delegate pending configs.
362 if (event.key().configClass == null) {
363 return;
364 }
365
Thomas Vachuska96d55b12015-05-11 08:52:03 -0700366 ConfigFactory factory = factoriesByConfig.get(event.key().configClass);
367 if (factory != null) {
Charles Chan023a8982016-02-04 11:00:41 -0800368 Object subject = event.key().subject;
369 Class configClass = factory.configClass();
370 Versioned<JsonNode> newValue = event.newValue();
371 Versioned<JsonNode> oldValue = event.oldValue();
372
373 Config config = (newValue != null) ?
374 createDetachedConfig(subject, configClass, newValue.value()) :
375 null;
376 Config prevConfig = (oldValue != null) ?
377 createDetachedConfig(subject, configClass, oldValue.value()) :
378 null;
379
380 NetworkConfigEvent.Type type;
381 switch (event.type()) {
382 case INSERT:
383 type = CONFIG_ADDED;
384 break;
385 case UPDATE:
386 type = CONFIG_UPDATED;
387 break;
388 case REMOVE:
389 default:
390 type = CONFIG_REMOVED;
391 break;
392 }
Thomas Vachuska96d55b12015-05-11 08:52:03 -0700393 notifyDelegate(new NetworkConfigEvent(type, event.key().subject,
Charles Chan023a8982016-02-04 11:00:41 -0800394 config, prevConfig, factory.configClass()));
Thomas Vachuska96d55b12015-05-11 08:52:03 -0700395 }
396 }
397 }
398}