8fa88ead0797a69df10c65f63078bac05476b479
[controller.git] / opendaylight / md-sal / sal-binding-broker / src / main / java / org / opendaylight / controller / sal / binding / codegen / impl / AbstractRuntimeCodeGenerator.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.sal.binding.codegen.impl;
9
10 import java.util.Map;
11 import java.util.WeakHashMap;
12
13 import javassist.ClassPool;
14 import javassist.CtClass;
15 import javassist.CtMethod;
16 import javassist.NotFoundException;
17
18 import javax.annotation.concurrent.GuardedBy;
19
20 import org.eclipse.xtext.xbase.lib.Extension;
21 import org.opendaylight.controller.sal.binding.api.rpc.RpcRouter;
22 import org.opendaylight.controller.sal.binding.codegen.RpcIsNotRoutedException;
23 import org.opendaylight.controller.sal.binding.spi.NotificationInvokerFactory;
24 import org.opendaylight.yangtools.sal.binding.generator.util.JavassistUtils;
25 import org.opendaylight.yangtools.yang.binding.BindingMapping;
26 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
27 import org.opendaylight.yangtools.yang.binding.NotificationListener;
28 import org.opendaylight.yangtools.yang.binding.RpcService;
29 import org.opendaylight.yangtools.yang.binding.annotations.RoutingContext;
30 import org.opendaylight.yangtools.yang.binding.util.ClassLoaderUtils;
31
32 import com.google.common.base.Supplier;
33
34 abstract class AbstractRuntimeCodeGenerator implements org.opendaylight.controller.sal.binding.codegen.RuntimeCodeGenerator, NotificationInvokerFactory {
35     @GuardedBy("this")
36     private final Map<Class<? extends NotificationListener>, RuntimeGeneratedInvokerPrototype> invokerClasses = new WeakHashMap<>();
37     private final CtClass brokerNotificationListener;
38
39     @Extension
40     protected final JavassistUtils utils;
41
42     protected AbstractRuntimeCodeGenerator(final ClassPool pool) {
43         utils = JavassistUtils.forClassPool(pool);
44
45         /*
46          * Make sure Javassist ClassPool sees the classloader of RpcService
47          */
48         utils.ensureClassLoader(RpcService.class);
49
50         brokerNotificationListener = utils.asCtClass(org.opendaylight.controller.sal.binding.api.NotificationListener.class);
51     }
52
53     protected final CtClass getBrokerNotificationListener() {
54         return brokerNotificationListener;
55     }
56
57     protected abstract RuntimeGeneratedInvokerPrototype generateListenerInvoker(Class<? extends NotificationListener> cls);
58     protected abstract <T extends RpcService> Supplier<T> directProxySupplier(final Class<T> serviceType);
59     protected abstract <T extends RpcService> Supplier<T> routerSupplier(final Class<T> serviceType, RpcServiceMetadata metadata);
60
61     private RpcServiceMetadata getRpcMetadata(final CtClass iface) throws ClassNotFoundException, NotFoundException, RpcIsNotRoutedException {
62         final RpcServiceMetadata metadata = new RpcServiceMetadata();
63
64         for (CtMethod method : iface.getMethods()) {
65             if (isRpcMethodWithInput(iface, method)) {
66                 final RpcMetadata routingPair = getRpcMetadata(method);
67                 if (routingPair != null) {
68                     metadata.addContext(routingPair.getContext());
69                     metadata.addRpcMethod(method.getName(), routingPair);
70
71                     /*
72                      * Force-load the RPC class representing the "input" of this RPC.
73                      *
74                      * FIXME: this is pre-existing side-effect of the original code, which
75                      *        kept a reference to the loaded class, but it did not use it.
76                      *
77                      *        There was no explanation as to why forcing this load was
78                      *        necessary. As far as I can tell now is that it forces the
79                      *        resolution of method arguments, which would (according to
80                      *        my reading of JLS) occur only when the method is invoked via
81                      *        binding-aware class action, not when coming from
82                      *        binding-independent world. Whether that makes sense or not,
83                      *        remains to be investigated.
84                      */
85                     Thread.currentThread().getContextClassLoader().loadClass(routingPair.getInputType().getName());
86                 } else {
87                     throw new RpcIsNotRoutedException("RPC " + method.getName() + " from "+ iface.getName() +" is not routed");
88                 }
89             }
90         }
91
92         return metadata;
93     }
94
95
96     private boolean isRpcMethodWithInput(final CtClass iface, final CtMethod method) throws NotFoundException {
97         if(iface.equals(method.getDeclaringClass())
98                 && method.getParameterTypes().length == 1) {
99             final CtClass onlyArg = method.getParameterTypes()[0];
100             if(onlyArg.isInterface() && onlyArg.getName().endsWith(BindingMapping.RPC_INPUT_SUFFIX)) {
101                 return true;
102             }
103         }
104         return false;
105     }
106
107     private RpcMetadata getRpcMetadata(final CtMethod method) throws NotFoundException {
108         final CtClass inputClass = method.getParameterTypes()[0];
109         return rpcMethodMetadata(inputClass, inputClass, method.getName());
110     }
111
112     private RpcMetadata rpcMethodMetadata(final CtClass dataClass, final CtClass inputClass, final String rpcMethod) throws NotFoundException {
113         for (CtMethod method : dataClass.getMethods()) {
114             if (method.getName().startsWith("get") && method.getParameterTypes().length == 0) {
115                 for (Object annotation : method.getAvailableAnnotations()) {
116                     if (annotation instanceof RoutingContext) {
117                         boolean encapsulated = !method.getReturnType().equals(utils.asCtClass(InstanceIdentifier.class));
118                         return new RpcMetadata(rpcMethod, ((RoutingContext)annotation).value(), method, encapsulated, inputClass);
119                     }
120                 }
121             }
122         }
123
124         for (CtClass iface : dataClass.getInterfaces()) {
125             final RpcMetadata ret = rpcMethodMetadata(iface, inputClass, rpcMethod);
126             if(ret != null) {
127                 return ret;
128             }
129         }
130         return null;
131     }
132
133     private synchronized RuntimeGeneratedInvokerPrototype resolveInvokerClass(final Class<? extends NotificationListener> cls) {
134         RuntimeGeneratedInvokerPrototype invoker = invokerClasses.get(cls);
135         if (invoker != null) {
136             return invoker;
137         }
138
139         utils.getLock().lock();
140         try {
141             invoker = ClassLoaderUtils.withClassLoader(cls.getClassLoader(), new Supplier<RuntimeGeneratedInvokerPrototype>() {
142                 @Override
143                 public RuntimeGeneratedInvokerPrototype get() {
144                     return generateListenerInvoker(cls);
145                 }
146             });
147
148             invokerClasses.put(cls, invoker);
149             return invoker;
150         } finally {
151             utils.getLock().unlock();
152         }
153     }
154
155     @Override
156     public final NotificationInvokerFactory getInvokerFactory() {
157         return this;
158     }
159
160     @Override
161     public final <T extends RpcService> T getDirectProxyFor(final Class<T> serviceType) {
162         utils.getLock().lock();
163         try {
164             return ClassLoaderUtils.withClassLoader(serviceType.getClassLoader(), directProxySupplier(serviceType));
165         } finally {
166             utils.getLock().unlock();
167         }
168     }
169
170     @Override
171     public final <T extends RpcService> RpcRouter<T> getRouterFor(final Class<T> serviceType, final String name) throws RpcIsNotRoutedException {
172         final RpcServiceMetadata metadata = ClassLoaderUtils.withClassLoader(serviceType.getClassLoader(), new Supplier<RpcServiceMetadata>() {
173             @Override
174             public RpcServiceMetadata get() {
175                 try {
176                     return getRpcMetadata(utils.asCtClass(serviceType));
177                 } catch (ClassNotFoundException | NotFoundException e) {
178                     throw new IllegalStateException(String.format("Failed to load metadata for class {}", serviceType), e);
179                 }
180             }
181         });
182
183         utils.getLock().lock();
184         try {
185             final T instance = ClassLoaderUtils.withClassLoader(serviceType.getClassLoader(), routerSupplier(serviceType, metadata));
186             return new RpcRouterCodegenInstance<T>(name, serviceType, instance, metadata.getContexts());
187         } finally {
188             utils.getLock().unlock();
189         }
190     }
191
192     @Override
193     public NotificationInvoker invokerFor(final NotificationListener instance) {
194         final Class<? extends NotificationListener> cls = instance.getClass();
195         final RuntimeGeneratedInvokerPrototype prototype = resolveInvokerClass(cls);
196
197         try {
198             return RuntimeGeneratedInvoker.create(instance, prototype);
199         } catch (InstantiationException | IllegalAccessException e) {
200             throw new IllegalStateException(String.format("Failed to create invoker for %s", instance), e);
201         }
202     }
203 }