2 * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
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
8 package org.opendaylight.mdsal.binding.dom.adapter;
10 import static com.google.common.base.Preconditions.checkArgument;
11 import static com.google.common.base.Preconditions.checkState;
12 import static java.util.Objects.requireNonNull;
14 import com.google.common.annotations.Beta;
15 import com.google.common.cache.CacheBuilder;
16 import com.google.common.cache.CacheLoader;
17 import com.google.common.cache.LoadingCache;
18 import com.google.common.collect.ImmutableBiMap;
19 import com.google.common.collect.ImmutableSet;
20 import com.google.common.collect.Iterators;
21 import java.lang.reflect.Method;
22 import java.time.Instant;
23 import java.util.AbstractMap.SimpleEntry;
24 import java.util.Collection;
25 import java.util.HashSet;
26 import java.util.Map.Entry;
27 import java.util.Optional;
29 import java.util.concurrent.TimeUnit;
30 import java.util.function.Function;
31 import java.util.stream.Collectors;
32 import javax.annotation.PreDestroy;
33 import javax.inject.Inject;
34 import javax.inject.Singleton;
35 import org.eclipse.jdt.annotation.NonNull;
36 import org.opendaylight.binding.runtime.api.BindingRuntimeContext;
37 import org.opendaylight.binding.runtime.api.BindingRuntimeGenerator;
38 import org.opendaylight.binding.runtime.api.ClassLoadingStrategy;
39 import org.opendaylight.binding.runtime.api.DefaultBindingRuntimeContext;
40 import org.opendaylight.mdsal.binding.api.DataTreeIdentifier;
41 import org.opendaylight.mdsal.binding.dom.codec.api.BindingCodecTree;
42 import org.opendaylight.mdsal.binding.dom.codec.api.BindingCodecTreeFactory;
43 import org.opendaylight.mdsal.binding.dom.codec.api.BindingDataObjectCodecTreeNode;
44 import org.opendaylight.mdsal.binding.dom.codec.api.BindingLazyContainerNode;
45 import org.opendaylight.mdsal.binding.dom.codec.api.BindingNormalizedNodeSerializer;
46 import org.opendaylight.mdsal.binding.dom.codec.api.MissingSchemaException;
47 import org.opendaylight.mdsal.binding.dom.codec.impl.BindingNormalizedNodeCodecRegistry;
48 import org.opendaylight.mdsal.binding.spec.naming.BindingMapping;
49 import org.opendaylight.mdsal.binding.spec.reflect.BindingReflections;
50 import org.opendaylight.mdsal.dom.api.DOMDataTreeIdentifier;
51 import org.opendaylight.mdsal.dom.api.DOMSchemaService;
52 import org.opendaylight.yangtools.concepts.ListenerRegistration;
53 import org.opendaylight.yangtools.yang.binding.Action;
54 import org.opendaylight.yangtools.yang.binding.DataContainer;
55 import org.opendaylight.yangtools.yang.binding.DataObject;
56 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
57 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier.PathArgument;
58 import org.opendaylight.yangtools.yang.binding.Notification;
59 import org.opendaylight.yangtools.yang.binding.RpcInput;
60 import org.opendaylight.yangtools.yang.binding.RpcOutput;
61 import org.opendaylight.yangtools.yang.binding.RpcService;
62 import org.opendaylight.yangtools.yang.common.QNameModule;
63 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
64 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
65 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
66 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
67 import org.opendaylight.yangtools.yang.data.impl.codec.DeserializationException;
68 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
69 import org.opendaylight.yangtools.yang.model.api.ActionDefinition;
70 import org.opendaylight.yangtools.yang.model.api.Module;
71 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
72 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
73 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
74 import org.opendaylight.yangtools.yang.model.api.SchemaContextListener;
75 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
76 import org.slf4j.Logger;
77 import org.slf4j.LoggerFactory;
80 * A combinations of {@link BindingCodecTreeFactory} and {@link BindingNormalizedNodeSerializer}, with internal
81 * caching of instance identifiers.
84 * NOTE: this class is non-final to allow controller adapter migration without duplicated code.
87 public class BindingToNormalizedNodeCodec implements BindingNormalizedNodeSerializer, SchemaContextListener,
90 private static final long WAIT_DURATION_SEC = 5;
91 private static final Logger LOG = LoggerFactory.getLogger(BindingToNormalizedNodeCodec.class);
93 private final LoadingCache<InstanceIdentifier<?>, YangInstanceIdentifier> iiCache = CacheBuilder.newBuilder()
94 .softValues().build(new CacheLoader<InstanceIdentifier<?>, YangInstanceIdentifier>() {
96 public YangInstanceIdentifier load(final InstanceIdentifier<?> key) {
97 return toYangInstanceIdentifierBlocking(key);
100 private final BindingNormalizedNodeCodecRegistry codecRegistry;
101 private final ClassLoadingStrategy classLoadingStrategy;
102 private final BindingRuntimeGenerator generator;
103 private final FutureSchema futureSchema;
105 private ListenerRegistration<?> listenerRegistration;
108 public BindingToNormalizedNodeCodec(final BindingRuntimeGenerator generator,
109 final ClassLoadingStrategy classLoadingStrategy, final BindingNormalizedNodeCodecRegistry codecRegistry) {
110 this(generator, classLoadingStrategy, codecRegistry, false);
114 public BindingToNormalizedNodeCodec(final BindingRuntimeContext runtimeContext) {
115 generator = (final SchemaContext context) -> {
116 throw new UnsupportedOperationException("Static context assigned");
118 classLoadingStrategy = runtimeContext.getStrategy();
119 codecRegistry = new BindingNormalizedNodeCodecRegistry(runtimeContext);
120 // TODO: this should have a specialized constructor or not be needed
121 futureSchema = FutureSchema.create(0, TimeUnit.SECONDS, false);
122 futureSchema.onRuntimeContextUpdated(runtimeContext);
125 public BindingToNormalizedNodeCodec(final BindingRuntimeGenerator generator,
126 final ClassLoadingStrategy classLoadingStrategy, final BindingNormalizedNodeCodecRegistry codecRegistry,
127 final boolean waitForSchema) {
128 this.generator = requireNonNull(generator, "generator");
129 this.classLoadingStrategy = requireNonNull(classLoadingStrategy, "classLoadingStrategy");
130 this.codecRegistry = requireNonNull(codecRegistry, "codecRegistry");
131 this.futureSchema = FutureSchema.create(WAIT_DURATION_SEC, TimeUnit.SECONDS, waitForSchema);
134 public static BindingToNormalizedNodeCodec newInstance(final BindingRuntimeGenerator generator,
135 final ClassLoadingStrategy classLoadingStrategy, final DOMSchemaService schemaService) {
136 final BindingNormalizedNodeCodecRegistry codecRegistry = new BindingNormalizedNodeCodecRegistry();
137 BindingToNormalizedNodeCodec instance = new BindingToNormalizedNodeCodec(generator, classLoadingStrategy,
138 codecRegistry, true);
139 instance.listenerRegistration = schemaService.registerSchemaContextListener(instance);
143 protected YangInstanceIdentifier toYangInstanceIdentifierBlocking(
144 final InstanceIdentifier<? extends DataObject> binding) {
146 return codecRegistry.toYangInstanceIdentifier(binding);
147 } catch (final MissingSchemaException e) {
148 waitForSchema(decompose(binding), e);
149 return codecRegistry.toYangInstanceIdentifier(binding);
154 * Translates supplied Binding Instance Identifier into NormalizedNode
155 * instance identifier.
158 * Binding Instance Identifier
159 * @return DOM Instance Identifier
160 * @throws IllegalArgumentException
161 * If supplied Instance Identifier is not valid.
163 public final YangInstanceIdentifier toNormalized(final InstanceIdentifier<? extends DataObject> binding) {
164 return codecRegistry.toYangInstanceIdentifier(binding);
168 public final YangInstanceIdentifier toYangInstanceIdentifier(final InstanceIdentifier<?> binding) {
169 return codecRegistry.toYangInstanceIdentifier(binding);
172 protected YangInstanceIdentifier toYangInstanceIdentifierCached(final InstanceIdentifier<?> binding) {
173 return iiCache.getUnchecked(binding);
177 public final <T extends DataObject> Entry<YangInstanceIdentifier, NormalizedNode<?, ?>> toNormalizedNode(
178 final InstanceIdentifier<T> path, final T data) {
180 return codecRegistry.toNormalizedNode(path, data);
181 } catch (final MissingSchemaException e) {
182 waitForSchema(decompose(path), e);
183 return codecRegistry.toNormalizedNode(path, data);
188 * Converts Binding Map.Entry to DOM Map.Entry.
191 * Same as {@link #toNormalizedNode(InstanceIdentifier, DataObject)}.
193 * @param binding Map Entry with InstanceIdentifier as key and DataObject as value.
194 * @return DOM Map Entry with {@link YangInstanceIdentifier} as key and {@link NormalizedNode}
197 @SuppressWarnings({"unchecked", "rawtypes"})
198 public final Entry<YangInstanceIdentifier, NormalizedNode<?, ?>> toNormalizedNode(
199 final Entry<InstanceIdentifier<? extends DataObject>, DataObject> binding) {
200 return toNormalizedNode((InstanceIdentifier) binding.getKey(), binding.getValue());
204 public final Entry<InstanceIdentifier<?>, DataObject> fromNormalizedNode(final YangInstanceIdentifier path,
205 final NormalizedNode<?, ?> data) {
206 return codecRegistry.fromNormalizedNode(path, data);
210 public final Notification fromNormalizedNodeNotification(final SchemaPath path, final ContainerNode data) {
211 return codecRegistry.fromNormalizedNodeNotification(path, data);
215 public final Notification fromNormalizedNodeNotification(final SchemaPath path, final ContainerNode data,
216 final Instant eventInstant) {
217 return codecRegistry.fromNormalizedNodeNotification(path, data, eventInstant);
221 public final DataObject fromNormalizedNodeRpcData(final SchemaPath path, final ContainerNode data) {
222 return codecRegistry.fromNormalizedNodeRpcData(path, data);
226 public <T extends RpcInput> T fromNormalizedNodeActionInput(final Class<? extends Action<?, ?, ?>> action,
227 final ContainerNode input) {
228 return codecRegistry.fromNormalizedNodeActionInput(action, input);
232 public <T extends RpcOutput> T fromNormalizedNodeActionOutput(final Class<? extends Action<?, ?, ?>> action,
233 final ContainerNode output) {
234 return codecRegistry.fromNormalizedNodeActionOutput(action, output);
238 public final InstanceIdentifier<?> fromYangInstanceIdentifier(final YangInstanceIdentifier dom) {
239 return codecRegistry.fromYangInstanceIdentifier(dom);
243 public final ContainerNode toNormalizedNodeNotification(final Notification data) {
244 return codecRegistry.toNormalizedNodeNotification(data);
248 public final ContainerNode toNormalizedNodeRpcData(final DataContainer data) {
249 return codecRegistry.toNormalizedNodeRpcData(data);
253 public ContainerNode toNormalizedNodeActionInput(final Class<? extends Action<?, ?, ?>> action,
254 final RpcInput input) {
255 return codecRegistry.toNormalizedNodeActionInput(action, input);
259 public ContainerNode toNormalizedNodeActionOutput(final Class<? extends Action<?, ?, ?>> action,
260 final RpcOutput output) {
261 return codecRegistry.toNormalizedNodeActionOutput(action, output);
265 public BindingLazyContainerNode<RpcInput> toLazyNormalizedNodeActionInput(
266 final Class<? extends Action<?, ?, ?>> action, final NodeIdentifier identifier, final RpcInput input) {
267 return codecRegistry.toLazyNormalizedNodeActionInput(action, identifier, input);
271 public BindingLazyContainerNode<RpcOutput> toLazyNormalizedNodeActionOutput(
272 final Class<? extends Action<?, ?, ?>> action, final NodeIdentifier identifier, final RpcOutput output) {
273 return codecRegistry.toLazyNormalizedNodeActionOutput(action, identifier, output);
277 * Returns a Binding-Aware instance identifier from normalized
278 * instance-identifier if it is possible to create representation.
281 * Returns Optional.empty for cases where target is mixin node except
284 public final Optional<InstanceIdentifier<? extends DataObject>> toBinding(final YangInstanceIdentifier normalized)
285 throws DeserializationException {
287 return Optional.ofNullable(codecRegistry.fromYangInstanceIdentifier(normalized));
288 } catch (final IllegalArgumentException e) {
289 return Optional.empty();
293 public final Optional<Entry<InstanceIdentifier<? extends DataObject>, DataObject>> toBinding(
294 final @NonNull Entry<YangInstanceIdentifier, ? extends NormalizedNode<?, ?>> normalized)
295 throws DeserializationException {
298 * This cast is required, due to generics behaviour in openjdk / oracle javac.
301 * InstanceIdentifier has definition InstanceIdentifier<T extends DataObject>,
302 * this means '?' is always  <? extends DataObject>. Eclipse compiler
303 * is able to determine this relationship and treats
304 * Entry<InstanceIdentifier<?>, DataObject> and Entry<InstanceIdentifier<? extends DataObject, DataObject>
305 * as assignable. However openjdk / oracle javac treats this two types
306 * as incompatible and issues a compile error.
309 * It is safe to lose generic information and cast it to other generic signature.
311 @SuppressWarnings("unchecked")
312 final Entry<InstanceIdentifier<? extends DataObject>, DataObject> binding = Entry.class.cast(
313 codecRegistry.fromNormalizedNode(normalized.getKey(), normalized.getValue()));
314 return Optional.ofNullable(binding);
315 } catch (final IllegalArgumentException e) {
316 return Optional.empty();
321 public void onGlobalContextUpdated(final SchemaContext context) {
322 final BindingRuntimeContext runtimeContext = DefaultBindingRuntimeContext.create(
323 generator.generateTypeMapping(context), classLoadingStrategy);
324 codecRegistry.onBindingRuntimeContextUpdated(runtimeContext);
325 futureSchema.onRuntimeContextUpdated(runtimeContext);
331 * @deprecated Use {@link BindingNormalizedNodeCodecRegistry#deserializeFunction} instead.
334 public final <T extends DataObject> Function<Optional<NormalizedNode<?, ?>>, Optional<T>> deserializeFunction(
335 final InstanceIdentifier<T> path) {
336 return codecRegistry.deserializeFunction(path)::apply;
339 public final BindingNormalizedNodeCodecRegistry getCodecRegistry() {
340 return codecRegistry;
345 public void close() {
346 if (listenerRegistration != null) {
347 listenerRegistration.close();
351 public final BindingNormalizedNodeCodecRegistry getCodecFactory() {
352 return codecRegistry;
355 // FIXME: This should be probably part of Binding Runtime context
356 public final ImmutableBiMap<Method, SchemaPath> getRpcMethodToSchemaPath(final Class<? extends RpcService> key) {
357 final Module module = getModuleBlocking(key);
358 final ImmutableBiMap.Builder<Method, SchemaPath> ret = ImmutableBiMap.builder();
360 for (final RpcDefinition rpcDef : module.getRpcs()) {
361 final Method method = findRpcMethod(key, rpcDef);
362 ret.put(method, rpcDef.getPath());
364 } catch (final NoSuchMethodException e) {
365 throw new IllegalStateException("Rpc defined in model does not have representation in generated class.", e);
370 protected ImmutableBiMap<Method, RpcDefinition> getRpcMethodToSchema(final Class<? extends RpcService> key) {
371 final Module module = getModuleBlocking(key);
372 final ImmutableBiMap.Builder<Method, RpcDefinition> ret = ImmutableBiMap.builder();
374 for (final RpcDefinition rpcDef : module.getRpcs()) {
375 final Method method = findRpcMethod(key, rpcDef);
376 ret.put(method, rpcDef);
378 } catch (final NoSuchMethodException e) {
379 throw new IllegalStateException("Rpc defined in model does not have representation in generated class.", e);
384 private Module getModuleBlocking(final Class<?> modeledClass) {
385 final QNameModule moduleName = BindingReflections.getQNameModule(modeledClass);
386 BindingRuntimeContext localRuntimeContext = runtimeContext();
387 Module module = localRuntimeContext == null ? null :
388 localRuntimeContext.getSchemaContext().findModule(moduleName).orElse(null);
389 if (module == null && futureSchema.waitForSchema(moduleName)) {
390 localRuntimeContext = runtimeContext();
391 checkState(localRuntimeContext != null, "BindingRuntimeContext is not available.");
392 module = localRuntimeContext.getSchemaContext().findModule(moduleName).orElse(null);
394 if (module != null) {
398 LOG.debug("Schema for {} is not available; expected module name: {}; BindingRuntimeContext: {}",
399 modeledClass, moduleName, localRuntimeContext);
400 throw new IllegalStateException(String.format("Schema for %s is not available; expected module name: %s; "
401 + "full BindingRuntimeContext available in debug log", modeledClass, moduleName));
404 private void waitForSchema(final Collection<Class<?>> binding, final MissingSchemaException exception) {
405 LOG.warn("Blocking thread to wait for schema convergence updates for {} {}", futureSchema.getDuration(),
406 futureSchema.getUnit());
407 if (!futureSchema.waitForSchema(binding)) {
412 private Method findRpcMethod(final Class<? extends RpcService> key, final RpcDefinition rpcDef)
413 throws NoSuchMethodException {
414 final String methodName = BindingMapping.getRpcMethodName(rpcDef.getQName());
415 final Class<?> inputClz = runtimeContext().getClassForSchema(rpcDef.getInput());
416 return key.getMethod(methodName, inputClz);
419 protected @NonNull Entry<InstanceIdentifier<?>, BindingDataObjectCodecTreeNode<?>> getSubtreeCodec(
420 final YangInstanceIdentifier domIdentifier) {
422 final BindingCodecTree currentCodecTree = codecRegistry.getCodecContext();
423 final InstanceIdentifier<?> bindingPath = codecRegistry.fromYangInstanceIdentifier(domIdentifier);
424 checkArgument(bindingPath != null);
426 * If we are able to deserialize YANG instance identifier, getSubtreeCodec must
427 * return non-null value.
429 final BindingDataObjectCodecTreeNode<?> codecContext = currentCodecTree.getSubtreeCodec(bindingPath);
430 return new SimpleEntry<>(bindingPath, codecContext);
433 @SuppressWarnings("unchecked")
434 public final Set<Class<? extends Notification>> getNotificationClasses(final Set<SchemaPath> interested) {
435 final Set<Class<? extends Notification>> result = new HashSet<>();
436 final BindingRuntimeContext runtimeContext = runtimeContext();
437 for (final NotificationDefinition notification : runtimeContext.getSchemaContext().getNotifications()) {
438 if (interested.contains(notification.getPath())) {
440 result.add((Class<? extends Notification>) runtimeContext.getClassForSchema(notification));
441 } catch (final IllegalStateException e) {
443 LOG.warn("Class for {} is currently not known.", notification.getPath(), e);
450 SchemaPath getActionPath(final Class<? extends Action<?, ?, ?>> type) {
451 final ActionDefinition schema = runtimeContext().getActionDefinition(type);
452 checkArgument(schema != null, "Failed to find schema for %s", type);
453 return schema.getPath();
456 private BindingRuntimeContext runtimeContext() {
457 return futureSchema.runtimeContext();
460 private static Collection<Class<?>> decompose(final InstanceIdentifier<?> path) {
461 return ImmutableSet.copyOf(Iterators.transform(path.getPathArguments().iterator(), PathArgument::getType));
464 protected NormalizedNode<?, ?> instanceIdentifierToNode(final YangInstanceIdentifier parentPath) {
465 return ImmutableNodes.fromInstanceId(runtimeContext().getSchemaContext(), parentPath);
468 protected Collection<DOMDataTreeIdentifier> toDOMDataTreeIdentifiers(
469 final Collection<DataTreeIdentifier<?>> subtrees) {
470 return subtrees.stream().map(this::toDOMDataTreeIdentifier).collect(Collectors.toSet());
473 protected DOMDataTreeIdentifier toDOMDataTreeIdentifier(final DataTreeIdentifier<?> path) {
474 final YangInstanceIdentifier domPath = toYangInstanceIdentifierBlocking(path.getRootIdentifier());
475 return new DOMDataTreeIdentifier(path.getDatastoreType(), domPath);