Bump yangtools to 4.0.1
[controller.git] / opendaylight / md-sal / sal-distributed-datastore / src / main / java / org / opendaylight / controller / cluster / datastore / DatastoreContextIntrospector.java
1 /*
2  * Copyright (c) 2015 Brocade Communications 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 package org.opendaylight.controller.cluster.datastore;
9
10 import static com.google.common.base.Preconditions.checkArgument;
11
12 import com.google.common.collect.ImmutableMap;
13 import com.google.common.collect.ImmutableSet;
14 import com.google.common.primitives.Primitives;
15 import java.beans.BeanInfo;
16 import java.beans.ConstructorProperties;
17 import java.beans.IntrospectionException;
18 import java.beans.Introspector;
19 import java.beans.MethodDescriptor;
20 import java.beans.PropertyDescriptor;
21 import java.lang.reflect.Constructor;
22 import java.lang.reflect.InvocationTargetException;
23 import java.lang.reflect.Method;
24 import java.util.AbstractMap.SimpleImmutableEntry;
25 import java.util.ArrayList;
26 import java.util.Collection;
27 import java.util.HashMap;
28 import java.util.List;
29 import java.util.Map;
30 import java.util.Map.Entry;
31 import java.util.Set;
32 import java.util.function.Function;
33 import org.apache.commons.lang3.StringUtils;
34 import org.apache.commons.text.WordUtils;
35 import org.checkerframework.checker.lock.qual.GuardedBy;
36 import org.opendaylight.controller.cluster.datastore.DatastoreContext.Builder;
37 import org.opendaylight.mdsal.binding.dom.codec.api.BindingNormalizedNodeSerializer;
38 import org.opendaylight.mdsal.binding.spec.reflect.BindingReflections;
39 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.distributed.datastore.provider.rev140612.DataStoreProperties;
40 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.distributed.datastore.provider.rev140612.DataStorePropertiesContainer;
41 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
42 import org.opendaylight.yangtools.yang.common.QName;
43 import org.opendaylight.yangtools.yang.common.Uint16;
44 import org.opendaylight.yangtools.yang.common.Uint32;
45 import org.opendaylight.yangtools.yang.common.Uint64;
46 import org.opendaylight.yangtools.yang.common.Uint8;
47 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
48 import org.slf4j.Logger;
49 import org.slf4j.LoggerFactory;
50
51 /**
52  * Introspects on a DatastoreContext instance to set its properties via reflection.
53  * i
54  * @author Thomas Pantelis
55  */
56 public class DatastoreContextIntrospector {
57     private static final Logger LOG = LoggerFactory.getLogger(DatastoreContextIntrospector.class);
58
59     private static final Map<String, Entry<Class<?>, Method>> DATA_STORE_PROP_INFO = new HashMap<>();
60
61     private static final Map<Class<?>, Constructor<?>> CONSTRUCTORS = new HashMap<>();
62
63     private static final Map<Class<?>, Method> YANG_TYPE_GETTERS = new HashMap<>();
64
65     private static final Map<String, Method> BUILDER_SETTERS = new HashMap<>();
66
67     private static final ImmutableMap<Class<?>, Function<String, Object>> UINT_FACTORIES =
68             ImmutableMap.<Class<?>, Function<String, Object>>builder()
69             .put(Uint8.class, Uint8::valueOf)
70             .put(Uint16.class, Uint16::valueOf)
71             .put(Uint32.class, Uint32::valueOf)
72             .put(Uint64.class, Uint64::valueOf)
73             .build();
74
75     static {
76         try {
77             introspectDatastoreContextBuilder();
78             introspectDataStoreProperties();
79             introspectPrimitiveTypes();
80         } catch (final IntrospectionException e) {
81             LOG.error("Error initializing DatastoreContextIntrospector", e);
82         }
83     }
84
85     /**
86      * Introspects each primitive wrapper (ie Integer, Long etc) and String type to find the
87      * constructor that takes a single String argument. For primitive wrappers, this constructor
88      * converts from a String representation.
89      */
90     // Disables "Either log or rethrow this exception" sonar warning
91     @SuppressWarnings("squid:S1166")
92     private static void introspectPrimitiveTypes() {
93         final Set<Class<?>> primitives = ImmutableSet.<Class<?>>builder().addAll(
94                 Primitives.allWrapperTypes()).add(String.class).build();
95         for (final Class<?> primitive: primitives) {
96             try {
97                 processPropertyType(primitive);
98             } catch (final NoSuchMethodException e) {
99                 // Ignore primitives that can't be constructed from a String, eg Character and Void.
100             } catch (SecurityException | IntrospectionException e) {
101                 LOG.error("Error introspect primitive type {}", primitive, e);
102             }
103         }
104     }
105
106     /**
107      * Introspects the DatastoreContext.Builder class to find all its setter methods that we will
108      * invoke via reflection. We can't use the bean Introspector here as the Builder setters don't
109      * follow the bean property naming convention, ie setter prefixed with "set", so look for all
110      * the methods that return Builder.
111      */
112     private static void introspectDatastoreContextBuilder() {
113         for (final Method method: Builder.class.getMethods()) {
114             if (Builder.class.equals(method.getReturnType())) {
115                 BUILDER_SETTERS.put(method.getName(), method);
116             }
117         }
118     }
119
120     /**
121      * Introspects the DataStoreProperties interface that is generated from the DataStoreProperties
122      * yang grouping. We use the bean Introspector to find the types of all the properties defined
123      * in the interface (this is the type returned from the getter method). For each type, we find
124      * the appropriate constructor that we will use.
125      */
126     private static void introspectDataStoreProperties() throws IntrospectionException {
127         final BeanInfo beanInfo = Introspector.getBeanInfo(DataStoreProperties.class);
128         for (final PropertyDescriptor desc: beanInfo.getPropertyDescriptors()) {
129             processDataStoreProperty(desc.getName(), desc.getPropertyType(), desc.getReadMethod());
130         }
131
132         // Getter methods that return Boolean and start with "is" instead of "get" aren't recognized as
133         // properties and thus aren't returned from getPropertyDescriptors. A getter starting with
134         // "is" is only supported if it returns primitive boolean. So we'll check for these via
135         // getMethodDescriptors.
136         for (final MethodDescriptor desc: beanInfo.getMethodDescriptors()) {
137             final String methodName = desc.getName();
138             if (Boolean.class.equals(desc.getMethod().getReturnType()) && methodName.startsWith("is")) {
139                 final String propertyName = WordUtils.uncapitalize(methodName.substring(2));
140                 processDataStoreProperty(propertyName, Boolean.class, desc.getMethod());
141             }
142         }
143     }
144
145     /**
146      * Processes a property defined on the DataStoreProperties interface.
147      */
148     @SuppressWarnings("checkstyle:IllegalCatch")
149     private static void processDataStoreProperty(final String name, final Class<?> propertyType,
150             final Method readMethod) {
151         checkArgument(BUILDER_SETTERS.containsKey(name),
152                 "DataStoreProperties property \"%s\" does not have corresponding setter in DatastoreContext.Builder",
153                 name);
154         try {
155             processPropertyType(propertyType);
156             DATA_STORE_PROP_INFO.put(name, new SimpleImmutableEntry<>(propertyType, readMethod));
157         } catch (final Exception e) {
158             LOG.error("Error finding constructor for type {}", propertyType, e);
159         }
160     }
161
162     /**
163      * Finds the appropriate constructor for the specified type that we will use to construct
164      * instances.
165      */
166     private static void processPropertyType(final Class<?> propertyType)
167             throws NoSuchMethodException, SecurityException, IntrospectionException {
168         final Class<?> wrappedType = Primitives.wrap(propertyType);
169         if (CONSTRUCTORS.containsKey(wrappedType)) {
170             return;
171         }
172
173         // If the type is a primitive (or String type), we look for the constructor that takes a
174         // single String argument, which, for primitives, validates and converts from a String
175         // representation which is the form we get on ingress.
176         if (propertyType.isPrimitive() || Primitives.isWrapperType(propertyType) || propertyType.equals(String.class)) {
177             CONSTRUCTORS.put(wrappedType, propertyType.getConstructor(String.class));
178         } else {
179             // This must be a yang-defined type. We need to find the constructor that takes a
180             // primitive as the only argument. This will be used to construct instances to perform
181             // validation (eg range checking). The yang-generated types have a couple single-argument
182             // constructors but the one we want has the bean ConstructorProperties annotation.
183             for (final Constructor<?> ctor: propertyType.getConstructors()) {
184                 final ConstructorProperties ctorPropsAnnotation = ctor.getAnnotation(ConstructorProperties.class);
185                 if (ctor.getParameterCount() == 1 && ctorPropsAnnotation != null) {
186                     findYangTypeGetter(propertyType, ctorPropsAnnotation.value()[0]);
187                     CONSTRUCTORS.put(propertyType, ctor);
188                     break;
189                 }
190             }
191         }
192     }
193
194     /**
195      * Finds the getter method on a yang-generated type for the specified property name.
196      */
197     private static void findYangTypeGetter(final Class<?> type, final String propertyName)
198             throws IntrospectionException {
199         for (final PropertyDescriptor desc: Introspector.getBeanInfo(type).getPropertyDescriptors()) {
200             if (desc.getName().equals(propertyName)) {
201                 YANG_TYPE_GETTERS.put(type, desc.getReadMethod());
202                 return;
203             }
204         }
205
206         throw new IntrospectionException(String.format(
207                 "Getter method for constructor property %s not found for YANG type %s",
208                 propertyName, type));
209     }
210
211     @GuardedBy(value = "this")
212     private DatastoreContext context;
213     @GuardedBy(value = "this")
214     private Map<String, Object> currentProperties;
215
216     public DatastoreContextIntrospector(final DatastoreContext context,
217             final BindingNormalizedNodeSerializer bindingSerializer) {
218         final QName qname = BindingReflections.findQName(DataStorePropertiesContainer.class);
219         final DataStorePropertiesContainer defaultPropsContainer = (DataStorePropertiesContainer)
220                 bindingSerializer.fromNormalizedNode(bindingSerializer.toYangInstanceIdentifier(
221                         InstanceIdentifier.builder(DataStorePropertiesContainer.class).build()),
222                 ImmutableNodes.containerNode(qname)).getValue();
223
224         final Builder builder = DatastoreContext.newBuilderFrom(context);
225         for (Entry<String, Entry<Class<?>, Method>> entry: DATA_STORE_PROP_INFO.entrySet()) {
226             Object value;
227             try {
228                 value = entry.getValue().getValue().invoke(defaultPropsContainer);
229             } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
230                 LOG.error("Error obtaining default value for property {}", entry.getKey(), e);
231                 value = null;
232             }
233
234             if (value != null) {
235                 convertValueAndInvokeSetter(entry.getKey(), value, builder);
236             }
237         }
238
239         this.context = builder.build();
240     }
241
242     public synchronized DatastoreContext getContext() {
243         return context;
244     }
245
246     public DatastoreContextFactory newContextFactory() {
247         return new DatastoreContextFactory(this);
248     }
249
250     public synchronized DatastoreContext getShardDatastoreContext(final String forShardName) {
251         if (currentProperties == null) {
252             return context;
253         }
254
255         final Builder builder = DatastoreContext.newBuilderFrom(context);
256         final String dataStoreTypePrefix = context.getDataStoreName() + '.';
257         final String shardNamePrefix = forShardName + '.';
258
259         final List<String> keys = getSortedKeysByDatastoreType(currentProperties.keySet(), dataStoreTypePrefix);
260
261         for (String key: keys) {
262             final Object value = currentProperties.get(key);
263             if (key.startsWith(dataStoreTypePrefix)) {
264                 key = key.replaceFirst(dataStoreTypePrefix, "");
265             }
266
267             if (key.startsWith(shardNamePrefix)) {
268                 key = key.replaceFirst(shardNamePrefix, "");
269                 convertValueAndInvokeSetter(key, value.toString(), builder);
270             }
271         }
272
273         return builder.build();
274     }
275
276     /**
277      * Applies the given properties to the cached DatastoreContext and yields a new DatastoreContext
278      * instance which can be obtained via {@link #getContext()}.
279      *
280      * @param properties the properties to apply
281      * @return true if the cached DatastoreContext was updated, false otherwise.
282      */
283     public synchronized boolean update(final Map<String, Object> properties) {
284         currentProperties = null;
285         if (properties == null || properties.isEmpty()) {
286             return false;
287         }
288
289         LOG.debug("In update: properties: {}", properties);
290
291         final ImmutableMap.Builder<String, Object> mapBuilder = ImmutableMap.<String, Object>builder();
292
293         final Builder builder = DatastoreContext.newBuilderFrom(context);
294
295         final String dataStoreTypePrefix = context.getDataStoreName() + '.';
296
297         final List<String> keys = getSortedKeysByDatastoreType(properties.keySet(), dataStoreTypePrefix);
298
299         boolean updated = false;
300         for (String key: keys) {
301             final Object value = properties.get(key);
302             mapBuilder.put(key, value);
303
304             // If the key is prefixed with the data store type, strip it off.
305             if (key.startsWith(dataStoreTypePrefix)) {
306                 key = key.replaceFirst(dataStoreTypePrefix, "");
307             }
308
309             if (convertValueAndInvokeSetter(key, value.toString(), builder)) {
310                 updated = true;
311             }
312         }
313
314         currentProperties = mapBuilder.build();
315
316         if (updated) {
317             context = builder.build();
318         }
319
320         return updated;
321     }
322
323     private static ArrayList<String> getSortedKeysByDatastoreType(final Collection<String> inKeys,
324             final String dataStoreTypePrefix) {
325         // Sort the property keys by putting the names prefixed with the data store type last. This
326         // is done so data store specific settings are applied after global settings.
327         final ArrayList<String> keys = new ArrayList<>(inKeys);
328         keys.sort((key1, key2) -> key1.startsWith(dataStoreTypePrefix) ? 1 :
329             key2.startsWith(dataStoreTypePrefix) ? -1 : key1.compareTo(key2));
330         return keys;
331     }
332
333     @SuppressWarnings("checkstyle:IllegalCatch")
334     private boolean convertValueAndInvokeSetter(final String inKey, final Object inValue, final Builder builder) {
335         final String key = convertToCamelCase(inKey);
336
337         try {
338             // Convert the value to the right type.
339             final Object value = convertValue(key, inValue);
340             if (value == null) {
341                 return false;
342             }
343
344             LOG.debug("Converted value for property {}: {} ({})",
345                     key, value, value.getClass().getSimpleName());
346
347             // Call the setter method on the Builder instance.
348             final Method setter = BUILDER_SETTERS.get(key);
349             setter.invoke(builder, constructorValueRecursively(
350                     Primitives.wrap(setter.getParameterTypes()[0]), value.toString()));
351
352             return true;
353         } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException
354                 | InstantiationException e) {
355             LOG.error("Error converting value ({}) for property {}", inValue, key, e);
356         }
357
358         return false;
359     }
360
361     private static String convertToCamelCase(final String inString) {
362         String str = inString.trim();
363         if (StringUtils.contains(str, '-') || StringUtils.contains(str, ' ')) {
364             str = inString.replace('-', ' ');
365             str = WordUtils.capitalizeFully(str);
366             str = StringUtils.deleteWhitespace(str);
367         }
368
369         return StringUtils.uncapitalize(str);
370     }
371
372     private Object convertValue(final String name, final Object from)
373             throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
374         final Entry<Class<?>, Method> propertyInfo = DATA_STORE_PROP_INFO.get(name);
375         if (propertyInfo == null) {
376             LOG.debug("Property not found for {}", name);
377             return null;
378         }
379
380         final Class<?> propertyType = propertyInfo.getKey();
381
382         LOG.debug("Type for property {}: {}, converting value {} ({})",
383                 name, propertyType.getSimpleName(), from, from.getClass().getSimpleName());
384
385         // Recurse the chain of constructors depth-first to get the resulting value. Eg, if the
386         // property type is the yang-generated NonZeroUint32Type, it's constructor takes a Long so
387         // we have to first construct a Long instance from the input value.
388         Object converted = constructorValueRecursively(propertyType, from);
389
390         // If the converted type is a yang-generated type, call the getter to obtain the actual value.
391         final Method getter = YANG_TYPE_GETTERS.get(converted.getClass());
392         if (getter != null) {
393             converted = getter.invoke(converted);
394         }
395
396         return converted;
397     }
398
399     private Object constructorValueRecursively(final Class<?> toType, final Object fromValue)
400             throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
401         LOG.trace("convertValueRecursively - toType: {}, fromValue {} ({})",
402                 toType.getSimpleName(), fromValue, fromValue.getClass().getSimpleName());
403
404         if (toType.equals(fromValue.getClass())) {
405             return fromValue;
406         }
407
408         final Constructor<?> ctor = CONSTRUCTORS.get(toType);
409         if (ctor == null) {
410             if (fromValue instanceof String) {
411                 final Function<String, Object> factory = UINT_FACTORIES.get(toType);
412                 if (factory != null) {
413                     return factory.apply((String) fromValue);
414                 }
415             }
416
417             throw new IllegalArgumentException(String.format("Constructor not found for type %s", toType));
418         }
419
420         LOG.trace("Found {}", ctor);
421         Object value = fromValue;
422
423         // Once we find a constructor that takes the original type as an argument, we're done recursing.
424         if (!ctor.getParameterTypes()[0].equals(fromValue.getClass())) {
425             value = constructorValueRecursively(ctor.getParameterTypes()[0], fromValue);
426         }
427
428         return ctor.newInstance(value);
429     }
430 }