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