Fix wait for schema in BindingToNormalizedNodeCodec
[controller.git] / opendaylight / md-sal / sal-binding-broker / src / main / java / org / opendaylight / controller / md / sal / binding / impl / BindingToNormalizedNodeCodec.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 package org.opendaylight.controller.md.sal.binding.impl;
9
10 import com.google.common.base.Function;
11 import com.google.common.base.Optional;
12 import com.google.common.base.Preconditions;
13 import com.google.common.cache.CacheBuilder;
14 import com.google.common.cache.CacheLoader;
15 import com.google.common.cache.LoadingCache;
16 import com.google.common.collect.ImmutableBiMap;
17 import java.lang.reflect.Method;
18 import java.net.URI;
19 import java.util.AbstractMap.SimpleEntry;
20 import java.util.Collection;
21 import java.util.Date;
22 import java.util.HashSet;
23 import java.util.Iterator;
24 import java.util.Map;
25 import java.util.Map.Entry;
26 import java.util.Set;
27 import java.util.concurrent.TimeUnit;
28 import javax.annotation.Nonnull;
29 import org.opendaylight.controller.md.sal.common.impl.util.compat.DataNormalizationException;
30 import org.opendaylight.controller.md.sal.common.impl.util.compat.DataNormalizationOperation;
31 import org.opendaylight.controller.md.sal.common.impl.util.compat.DataNormalizer;
32 import org.opendaylight.yangtools.binding.data.codec.api.BindingCodecTree;
33 import org.opendaylight.yangtools.binding.data.codec.api.BindingCodecTreeFactory;
34 import org.opendaylight.yangtools.binding.data.codec.api.BindingCodecTreeNode;
35 import org.opendaylight.yangtools.binding.data.codec.api.BindingNormalizedNodeSerializer;
36 import org.opendaylight.yangtools.binding.data.codec.impl.BindingNormalizedNodeCodecRegistry;
37 import org.opendaylight.yangtools.binding.data.codec.impl.MissingSchemaException;
38 import org.opendaylight.yangtools.sal.binding.generator.impl.GeneratedClassLoadingStrategy;
39 import org.opendaylight.yangtools.sal.binding.generator.util.BindingRuntimeContext;
40 import org.opendaylight.yangtools.yang.binding.BindingMapping;
41 import org.opendaylight.yangtools.yang.binding.DataContainer;
42 import org.opendaylight.yangtools.yang.binding.DataObject;
43 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
44 import org.opendaylight.yangtools.yang.binding.Notification;
45 import org.opendaylight.yangtools.yang.binding.RpcService;
46 import org.opendaylight.yangtools.yang.binding.util.BindingReflections;
47 import org.opendaylight.yangtools.yang.common.QNameModule;
48 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
49 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
50 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
51 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
52 import org.opendaylight.yangtools.yang.data.impl.codec.DeserializationException;
53 import org.opendaylight.yangtools.yang.model.api.Module;
54 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
55 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
56 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
57 import org.opendaylight.yangtools.yang.model.api.SchemaContextListener;
58 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
59 import org.slf4j.Logger;
60 import org.slf4j.LoggerFactory;
61
62 public final class BindingToNormalizedNodeCodec implements BindingCodecTreeFactory, BindingNormalizedNodeSerializer, SchemaContextListener, AutoCloseable {
63
64     private static final long WAIT_DURATION_SEC = 5;
65     private static final Logger LOG = LoggerFactory.getLogger(BindingToNormalizedNodeCodec.class);
66
67     private final BindingNormalizedNodeCodecRegistry codecRegistry;
68
69     private final GeneratedClassLoadingStrategy classLoadingStrategy;
70     private final FutureSchema futureSchema;
71     private final LoadingCache<InstanceIdentifier<?>, YangInstanceIdentifier> iiCache = CacheBuilder.newBuilder()
72             .softValues().build(new CacheLoader<InstanceIdentifier<?>, YangInstanceIdentifier>() {
73
74                 @Override
75                 public YangInstanceIdentifier load(final InstanceIdentifier<?> key) throws Exception {
76                     return toYangInstanceIdentifierBlocking(key);
77                 }
78
79             });
80
81     private DataNormalizer legacyToNormalized;
82
83     public BindingToNormalizedNodeCodec(final GeneratedClassLoadingStrategy classLoadingStrategy,
84             final BindingNormalizedNodeCodecRegistry codecRegistry) {
85         this(classLoadingStrategy,codecRegistry,false);
86
87     }
88
89     public BindingToNormalizedNodeCodec(final GeneratedClassLoadingStrategy classLoadingStrategy,
90             final BindingNormalizedNodeCodecRegistry codecRegistry,final boolean waitForSchema) {
91         this.classLoadingStrategy = Preconditions.checkNotNull(classLoadingStrategy,"classLoadingStrategy");
92         this.codecRegistry = Preconditions.checkNotNull(codecRegistry,"codecRegistry");
93         this.futureSchema = new FutureSchema(WAIT_DURATION_SEC, TimeUnit.SECONDS, waitForSchema);
94     }
95
96     YangInstanceIdentifier toYangInstanceIdentifierBlocking(final InstanceIdentifier<? extends DataObject> binding) {
97         try {
98             return codecRegistry.toYangInstanceIdentifier(binding);
99         } catch (final MissingSchemaException e) {
100             waitForSchema(decompose(binding),e);
101             return codecRegistry.toYangInstanceIdentifier(binding);
102         }
103     }
104
105     /**
106      * Translates supplied Binding Instance Identifier into NormalizedNode
107      * instance identifier.
108      *
109      * @param binding
110      *            Binding Instance Identifier
111      * @return DOM Instance Identifier
112      * @throws IllegalArgumentException
113      *             If supplied Instance Identifier is not valid.
114      */
115     public YangInstanceIdentifier toNormalized(final InstanceIdentifier<? extends DataObject> binding) {
116         return codecRegistry.toYangInstanceIdentifier(binding);
117     }
118
119     @Override
120     public YangInstanceIdentifier toYangInstanceIdentifier(final InstanceIdentifier<?> binding) {
121         return codecRegistry.toYangInstanceIdentifier(binding);
122     }
123
124
125     YangInstanceIdentifier toYangInstanceIdentifierCached(final InstanceIdentifier<?> binding) {
126         return iiCache .getUnchecked(binding);
127     }
128
129     @Override
130     public <T extends DataObject> Entry<YangInstanceIdentifier, NormalizedNode<?, ?>> toNormalizedNode(
131             final InstanceIdentifier<T> path, final T data) {
132         return codecRegistry.toNormalizedNode(path, data);
133     }
134
135     /**
136      * Converts Binding Map.Entry to DOM Map.Entry
137      *
138      * Same as {@link #toNormalizedNode(InstanceIdentifier, DataObject)}.
139      *
140      * @param binding Map Entry with InstanceIdentifier as key and DataObject as value.
141      * @return DOM Map Entry with {@link YangInstanceIdentifier} as key and {@link NormalizedNode}
142      *         as value.
143      */
144     @SuppressWarnings({"unchecked", "rawtypes"})
145     public Entry<YangInstanceIdentifier, NormalizedNode<?, ?>> toNormalizedNode(
146             final Entry<InstanceIdentifier<? extends DataObject>, DataObject> binding) {
147         return toNormalizedNode((InstanceIdentifier) binding.getKey(),binding.getValue());
148     }
149
150     @Override
151     public Entry<InstanceIdentifier<?>, DataObject> fromNormalizedNode(final YangInstanceIdentifier path,
152             final NormalizedNode<?, ?> data) {
153         return codecRegistry.fromNormalizedNode(path, data);
154     }
155
156     @Override
157     public Notification fromNormalizedNodeNotification(final SchemaPath path, final ContainerNode data) {
158         return codecRegistry.fromNormalizedNodeNotification(path, data);
159     }
160
161     @Override
162     public DataObject fromNormalizedNodeRpcData(final SchemaPath path, final ContainerNode data) {
163         return codecRegistry.fromNormalizedNodeRpcData(path, data);
164     }
165
166     @Override
167     public InstanceIdentifier<?> fromYangInstanceIdentifier(final YangInstanceIdentifier dom) {
168         return codecRegistry.fromYangInstanceIdentifier(dom);
169     }
170
171     @Override
172     public ContainerNode toNormalizedNodeNotification(final Notification data) {
173         return codecRegistry.toNormalizedNodeNotification(data);
174     }
175
176     @Override
177     public ContainerNode toNormalizedNodeRpcData(final DataContainer data) {
178         return codecRegistry.toNormalizedNodeRpcData(data);
179     }
180
181     /**
182      *
183      * Returns a Binding-Aware instance identifier from normalized
184      * instance-identifier if it is possible to create representation.
185      *
186      * Returns Optional.absent for cases where target is mixin node except
187      * augmentation.
188      *
189      */
190     public Optional<InstanceIdentifier<? extends DataObject>> toBinding(final YangInstanceIdentifier normalized)
191                     throws DeserializationException {
192         try {
193             return Optional.<InstanceIdentifier<? extends DataObject>>fromNullable(codecRegistry.fromYangInstanceIdentifier(normalized));
194         } catch (final IllegalArgumentException e) {
195             return Optional.absent();
196         }
197     }
198
199     public DataNormalizer getDataNormalizer() {
200         return legacyToNormalized;
201     }
202
203     public Optional<Entry<InstanceIdentifier<? extends DataObject>, DataObject>> toBinding(
204             @Nonnull final Entry<YangInstanceIdentifier, ? extends NormalizedNode<?, ?>> normalized)
205                     throws DeserializationException {
206         try {
207             /*
208              * This cast is required, due to generics behaviour in openjdk / oracle javac
209              *
210              * InstanceIdentifier has definition InstanceIdentifier<T extends DataObject>,
211              * this means '?' is always  <? extends DataObject>. Eclipse compiler
212              * is able to determine this relationship and treats
213              * Entry<InstanceIdentifier<?>,DataObject> and Entry<InstanceIdentifier<? extends DataObject,DataObject>
214              * as assignable. However openjdk / oracle javac treats this two types
215              * as incompatible and issues a compile error.
216              *
217              * It is safe to  loose generic information and cast it to other generic signature.
218              *
219              */
220             @SuppressWarnings("unchecked")
221             final Entry<InstanceIdentifier<? extends DataObject>, DataObject> binding = Entry.class.cast(codecRegistry.fromNormalizedNode(normalized.getKey(), normalized.getValue()));
222             return Optional.fromNullable(binding);
223         } catch (final IllegalArgumentException e) {
224             return Optional.absent();
225         }
226     }
227
228     @Override
229     public void onGlobalContextUpdated(final SchemaContext schemaContext) {
230         legacyToNormalized = new DataNormalizer(schemaContext);
231         BindingRuntimeContext runtimeContext = BindingRuntimeContext.create(classLoadingStrategy, schemaContext);
232         codecRegistry.onBindingRuntimeContextUpdated(runtimeContext);
233         futureSchema.onRuntimeContextUpdated(runtimeContext);
234     }
235
236     public <T extends DataObject> Function<Optional<NormalizedNode<?, ?>>, Optional<T>>  deserializeFunction(final InstanceIdentifier<T> path) {
237         return codecRegistry.deserializeFunction(path);
238     }
239
240     /**
241      * Returns an default object according to YANG schema for supplied path.
242      *
243      * @param path DOM Path
244      * @return Node with defaults set on.
245      */
246     public NormalizedNode<?, ?> getDefaultNodeFor(final YangInstanceIdentifier path) {
247         final Iterator<PathArgument> iterator = path.getPathArguments().iterator();
248         DataNormalizationOperation<?> currentOp = legacyToNormalized.getRootOperation();
249         while (iterator.hasNext()) {
250             final PathArgument currentArg = iterator.next();
251             try {
252                 currentOp = currentOp.getChild(currentArg);
253             } catch (final DataNormalizationException e) {
254                 throw new IllegalArgumentException(String.format("Invalid child encountered in path %s", path), e);
255             }
256         }
257         return currentOp.createDefault(path.getLastPathArgument());
258     }
259
260     public BindingNormalizedNodeCodecRegistry getCodecRegistry() {
261         return codecRegistry;
262     }
263
264     @Override
265     public void close() {
266         // NOOP Intentionally
267     }
268
269     public BindingNormalizedNodeCodecRegistry getCodecFactory() {
270         return codecRegistry;
271     }
272
273     // FIXME: This should be probably part of Binding Runtime context
274     public ImmutableBiMap<Method, SchemaPath> getRpcMethodToSchemaPath(final Class<? extends RpcService> key) {
275         final Module module = getModuleBlocking(key);
276         final ImmutableBiMap.Builder<Method, SchemaPath> ret = ImmutableBiMap.<Method, SchemaPath>builder();
277         try {
278             for (final RpcDefinition rpcDef : module.getRpcs()) {
279                 final Method method = findRpcMethod(key, rpcDef);
280                 ret.put(method, rpcDef.getPath());
281             }
282         } catch (final NoSuchMethodException e) {
283             throw new IllegalStateException("Rpc defined in model does not have representation in generated class.", e);
284         }
285         return ret.build();
286     }
287
288     protected ImmutableBiMap<Method, RpcDefinition> getRpcMethodToSchema(final Class<? extends RpcService> key) {
289         final Module module = getModuleBlocking(key);
290         final ImmutableBiMap.Builder<Method, RpcDefinition> ret = ImmutableBiMap.builder();
291         try {
292             for (final RpcDefinition rpcDef : module.getRpcs()) {
293                 final Method method = findRpcMethod(key, rpcDef);
294                 ret.put(method, rpcDef);
295             }
296         } catch (final NoSuchMethodException e) {
297             throw new IllegalStateException("Rpc defined in model does not have representation in generated class.", e);
298         }
299         return ret.build();
300     }
301
302     private Module getModuleBlocking(final Class<?> modeledClass) {
303         final QNameModule moduleName = BindingReflections.getQNameModule(modeledClass);
304         final URI namespace = moduleName.getNamespace();
305         final Date revision = moduleName.getRevision();
306         Module module = runtimeContext().getSchemaContext().findModuleByNamespaceAndRevision(namespace, revision);
307         if(module == null && futureSchema.waitForSchema(namespace,revision)) {
308             module = runtimeContext().getSchemaContext().findModuleByNamespaceAndRevision(namespace, revision);
309         }
310         Preconditions.checkState(module != null, "Schema for %s is not available.", modeledClass);
311         return module;
312     }
313
314     private void waitForSchema(final Collection<Class<?>> binding, final MissingSchemaException e) {
315         LOG.warn("Blocking thread to wait for schema convergence updates for {} {}", futureSchema.getDuration(),
316                 futureSchema.getUnit());
317         if(futureSchema.waitForSchema(binding)) {
318             return;
319         }
320
321         throw e;
322     }
323
324     private Method findRpcMethod(final Class<? extends RpcService> key, final RpcDefinition rpcDef) throws NoSuchMethodException {
325         final String methodName = BindingMapping.getMethodName(rpcDef.getQName());
326         if(rpcDef.getInput() != null) {
327             final Class<?> inputClz = runtimeContext().getClassForSchema(rpcDef.getInput());
328             return key.getMethod(methodName, inputClz);
329         }
330         return key.getMethod(methodName);
331     }
332
333     private BindingRuntimeContext runtimeContext() {
334         return futureSchema.runtimeContext();
335     }
336
337     @Override
338     public BindingCodecTree create(final BindingRuntimeContext context) {
339         return codecRegistry.create(context);
340     }
341
342     @Override
343     public BindingCodecTree create(final SchemaContext context, final Class<?>... bindingClasses) {
344         return codecRegistry.create(context, bindingClasses);
345     }
346
347     @Nonnull
348     protected Map.Entry<InstanceIdentifier<?>, BindingCodecTreeNode<?>> getSubtreeCodec(
349             final YangInstanceIdentifier domIdentifier) {
350
351         final BindingCodecTree currentCodecTree = codecRegistry.getCodecContext();
352         final InstanceIdentifier<?> bindingPath = codecRegistry.fromYangInstanceIdentifier(domIdentifier);
353         Preconditions.checkArgument(bindingPath != null);
354         /**
355          * If we are able to deserialize YANG instance identifier, getSubtreeCodec must
356          * return non-null value.
357          */
358         final BindingCodecTreeNode<?> codecContext = currentCodecTree.getSubtreeCodec(bindingPath);
359         return new SimpleEntry<InstanceIdentifier<?>, BindingCodecTreeNode<?>>(bindingPath, codecContext);
360     }
361
362     @SuppressWarnings("unchecked")
363     public Set<Class<? extends Notification>> getNotificationClasses(final Set<SchemaPath> interested) {
364         final Set<Class<? extends Notification>> result = new HashSet<>();
365         final Set<NotificationDefinition> knownNotifications = runtimeContext().getSchemaContext().getNotifications();
366         for (final NotificationDefinition notification : knownNotifications) {
367             if (interested.contains(notification.getPath())) {
368                 try {
369                     result.add((Class<? extends Notification>) runtimeContext().getClassForSchema(notification));
370                 } catch (final IllegalStateException e) {
371                     // Ignore
372                     LOG.warn("Class for {} is currently not known.",notification.getPath(),e);
373                 }
374             }
375         }
376         return result;
377     }
378
379     private static Collection<Class<?>> decompose(final InstanceIdentifier<?> path) {
380         final Set<Class<?>> clazzes = new HashSet<>();
381         for(final InstanceIdentifier.PathArgument arg : path.getPathArguments()) {
382             clazzes.add(arg.getType());
383         }
384         return clazzes;
385     }
386
387 }

©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.