2 * Copyright (c) 2013, 2015 EBay Software Foundation 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
9 package org.opendaylight.ovsdb.lib.jsonrpc;
11 import com.fasterxml.jackson.core.JsonProcessingException;
12 import com.fasterxml.jackson.databind.JavaType;
13 import com.fasterxml.jackson.databind.JsonNode;
14 import com.fasterxml.jackson.databind.ObjectMapper;
15 import com.fasterxml.jackson.databind.type.TypeFactory;
16 import com.google.common.collect.Maps;
17 import com.google.common.reflect.Invokable;
18 import com.google.common.reflect.Reflection;
19 import com.google.common.reflect.TypeToken;
20 import com.google.common.util.concurrent.ListenableFuture;
21 import com.google.common.util.concurrent.SettableFuture;
22 import com.google.common.util.concurrent.ThreadFactoryBuilder;
23 import io.netty.channel.Channel;
24 import java.lang.reflect.InvocationHandler;
25 import java.lang.reflect.InvocationTargetException;
26 import java.lang.reflect.Method;
27 import java.util.List;
29 import java.util.UUID;
30 import java.util.concurrent.Executors;
31 import java.util.concurrent.ScheduledExecutorService;
32 import java.util.concurrent.ThreadFactory;
33 import java.util.concurrent.TimeUnit;
35 import org.opendaylight.ovsdb.lib.error.UnexpectedResultException;
36 import org.opendaylight.ovsdb.lib.error.UnsupportedArgumentException;
37 import org.opendaylight.ovsdb.lib.message.OvsdbRPC;
38 import org.slf4j.Logger;
39 import org.slf4j.LoggerFactory;
41 public class JsonRpcEndpoint {
43 private static final Logger LOG = LoggerFactory.getLogger(JsonRpcEndpoint.class);
44 private static final int REAPER_THREADS = 3;
45 private static final ThreadFactory FUTURE_REAPER_THREAD_FACTORY = new ThreadFactoryBuilder()
46 .setNameFormat("OVSDB-Lib-Future-Reaper-%d").build();
47 private static final ScheduledExecutorService FUTURE_REAPER_SERVICE
48 = Executors.newScheduledThreadPool(REAPER_THREADS, FUTURE_REAPER_THREAD_FACTORY);
50 private static int reaperInterval = 1000;
52 public class CallContext {
54 JsonRpc10Request request;
55 SettableFuture<Object> future;
57 public CallContext(JsonRpc10Request request, Method method, SettableFuture<Object> future) {
59 this.request = request;
63 public Method getMethod() {
67 public JsonRpc10Request getRequest() {
71 public SettableFuture<Object> getFuture() {
76 ObjectMapper objectMapper;
78 Map<String, CallContext> methodContext = Maps.newHashMap();
79 Map<Object, OvsdbRPC.Callback> requestCallbacks = Maps.newHashMap();
81 public JsonRpcEndpoint(ObjectMapper objectMapper, Channel channel) {
82 this.objectMapper = objectMapper;
83 this.nettyChannel = channel;
86 public <T> T getClient(final Object context, Class<T> klazz) {
88 return Reflection.newProxy(klazz, new InvocationHandler() {
90 public Object invoke(Object proxy, Method method, Object[] args) throws Exception {
91 if (method.getName().equals(OvsdbRPC.REGISTER_CALLBACK_METHOD)) {
92 if ((args == null) || args.length != 1 || !(args[0] instanceof OvsdbRPC.Callback)) {
95 requestCallbacks.put(context, (OvsdbRPC.Callback)args[0]);
99 JsonRpc10Request request = new JsonRpc10Request(UUID.randomUUID().toString());
100 request.setMethod(method.getName());
102 if (args != null && args.length != 0) {
103 List<Object> params = null;
105 if (args.length == 1) {
106 if (args[0] instanceof Params) {
107 params = ((Params) args[0]).params();
108 } else if (args[0] instanceof List) {
109 params = (List<Object>) args[0];
112 if (params == null) {
113 throw new UnsupportedArgumentException("do not understand this argument yet");
115 request.setParams(params);
119 String requestString = objectMapper.writeValueAsString(request);
120 LOG.trace("getClient Request : {}", requestString);
122 SettableFuture<Object> sf = SettableFuture.create();
123 methodContext.put(request.getId(), new CallContext(request, method, sf));
124 FUTURE_REAPER_SERVICE.schedule(new Runnable() {
127 CallContext cc = methodContext.remove(request.getId());
129 if ( cc.getFuture().isDone() || cc.getFuture().isCancelled()) {
132 cc.getFuture().cancel(false);
135 }, reaperInterval, TimeUnit.MILLISECONDS);
137 nettyChannel.writeAndFlush(requestString);
145 public void processResult(JsonNode response) throws NoSuchMethodException {
147 LOG.trace("Response : {}", response.toString());
148 CallContext returnCtxt = methodContext.remove(response.get("id").asText());
149 if (returnCtxt == null) {
153 if (ListenableFuture.class == returnCtxt.getMethod().getReturnType()) {
154 TypeToken<?> retType = TypeToken.of(
155 returnCtxt.getMethod().getGenericReturnType())
156 .resolveType(ListenableFuture.class.getMethod("get").getGenericReturnType());
157 JavaType javaType = TypeFactory.defaultInstance().constructType(retType.getType());
159 JsonNode result = response.get("result");
160 Object result1 = objectMapper.convertValue(result, javaType);
161 JsonNode error = response.get("error");
162 if (error != null && !error.isNull()) {
163 LOG.error("Error : {}", error.toString());
166 returnCtxt.getFuture().set(result1);
169 throw new UnexpectedResultException("Don't know how to handle this");
173 public void processRequest(Object context, JsonNode requestJson) {
174 JsonRpc10Request request = new JsonRpc10Request(requestJson.get("id").asText());
175 request.setMethod(requestJson.get("method").asText());
176 LOG.trace("Request : {} {} {}", requestJson.get("id"), requestJson.get("method"),
177 requestJson.get("params"));
178 OvsdbRPC.Callback callback = requestCallbacks.get(context);
179 if (callback != null) {
180 Method[] methods = callback.getClass().getDeclaredMethods();
181 for (Method method : methods) {
182 if (method.getName().equals(request.getMethod())) {
183 Class<?>[] parameters = method.getParameterTypes();
184 JsonNode params = requestJson.get("params");
185 Object param = objectMapper.convertValue(params, parameters[1]);
187 Invokable from = Invokable.from(method);
188 from.setAccessible(true);
189 from.invoke(callback, context, param);
190 } catch (IllegalAccessException | InvocationTargetException e) {
191 LOG.error("Unable to invoke callback {}", method.getName(), e);
198 // Echo dont need any special processing. hence handling it internally.
200 if (request.getMethod().equals("echo")) {
201 JsonRpc10Response response = new JsonRpc10Response(request.getId());
202 response.setError(null);
203 String jsonString = null;
205 jsonString = objectMapper.writeValueAsString(response);
206 nettyChannel.writeAndFlush(jsonString);
207 } catch (JsonProcessingException e) {
208 LOG.error("Exception while processing JSON string {}", jsonString, e);
213 // send a null response for list_dbs
214 if (request.getMethod().equals("list_dbs")) {
215 JsonRpc10Response response = new JsonRpc10Response(request.getId());
216 response.setError(null);
217 String jsonString = null;
219 jsonString = objectMapper.writeValueAsString(response);
220 nettyChannel.writeAndFlush(jsonString);
221 } catch (JsonProcessingException e) {
222 LOG.error("Exception while processing JSON string {}", jsonString, e);
227 LOG.error("No handler for Request : {} on {}", requestJson.toString(), context);
230 public Map<String, CallContext> getMethodContext() {
231 return methodContext;
234 public static void setReaperInterval(int interval) {
235 reaperInterval = interval;
236 LOG.info("Ovsdb Rpc Task interval is set to {} millisecond", reaperInterval);