Merge "Add cli flag for virtual environment"
[ovsdb.git] / library / impl / src / main / java / org / opendaylight / ovsdb / lib / jsonrpc / JsonRpcEndpoint.java
1 /*
2  * Copyright (c) 2013, 2015 EBay Software Foundation 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
9 package org.opendaylight.ovsdb.lib.jsonrpc;
10
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;
28 import java.util.Map;
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;
34
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;
40
41 public class JsonRpcEndpoint {
42
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);
49
50     private static int reaperInterval = 1000;
51
52     public class CallContext {
53         Method method;
54         JsonRpc10Request request;
55         SettableFuture<Object> future;
56
57         public CallContext(JsonRpc10Request request, Method method, SettableFuture<Object> future) {
58             this.method = method;
59             this.request = request;
60             this.future = future;
61         }
62
63         public Method getMethod() {
64             return method;
65         }
66
67         public JsonRpc10Request getRequest() {
68             return request;
69         }
70
71         public SettableFuture<Object> getFuture() {
72             return future;
73         }
74     }
75
76     ObjectMapper objectMapper;
77     Channel nettyChannel;
78     Map<String, CallContext> methodContext = Maps.newHashMap();
79     Map<Object, OvsdbRPC.Callback> requestCallbacks = Maps.newHashMap();
80
81     public JsonRpcEndpoint(ObjectMapper objectMapper, Channel channel) {
82         this.objectMapper = objectMapper;
83         this.nettyChannel = channel;
84     }
85
86     public <T> T getClient(final Object context, Class<T> klazz) {
87
88         return Reflection.newProxy(klazz, new InvocationHandler() {
89             @Override
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)) {
93                         return false;
94                     }
95                     requestCallbacks.put(context, (OvsdbRPC.Callback)args[0]);
96                     return true;
97                 }
98
99                 JsonRpc10Request request = new JsonRpc10Request(UUID.randomUUID().toString());
100                 request.setMethod(method.getName());
101
102                 if (args != null && args.length != 0) {
103                     List<Object> params = null;
104
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];
110                         }
111
112                         if (params == null) {
113                             throw new UnsupportedArgumentException("do not understand this argument yet");
114                         }
115                         request.setParams(params);
116                     }
117                 }
118
119                 String requestString = objectMapper.writeValueAsString(request);
120                 LOG.trace("getClient Request : {}", requestString);
121
122                 SettableFuture<Object> sf = SettableFuture.create();
123                 methodContext.put(request.getId(), new CallContext(request, method, sf));
124                 FUTURE_REAPER_SERVICE.schedule(new Runnable() {
125                     @Override
126                     public void run() {
127                         CallContext cc = methodContext.remove(request.getId());
128                         if ( cc != null) {
129                             if ( cc.getFuture().isDone() || cc.getFuture().isCancelled()) {
130                                 return;
131                             }
132                             cc.getFuture().cancel(false);
133                         }
134                     }
135                 }, reaperInterval, TimeUnit.MILLISECONDS);
136
137                 nettyChannel.writeAndFlush(requestString);
138
139                 return sf;
140             }
141         }
142         );
143     }
144
145     public void processResult(JsonNode response) throws NoSuchMethodException {
146
147         LOG.trace("Response : {}", response.toString());
148         CallContext returnCtxt = methodContext.remove(response.get("id").asText());
149         if (returnCtxt == null) {
150             return;
151         }
152
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());
158
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());
164             }
165
166             returnCtxt.getFuture().set(result1);
167
168         } else {
169             throw new UnexpectedResultException("Don't know how to handle this");
170         }
171     }
172
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]);
186                     try {
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);
192                     }
193                     return;
194                 }
195             }
196         }
197
198         // Echo dont need any special processing. hence handling it internally.
199
200         if (request.getMethod().equals("echo")) {
201             JsonRpc10Response response = new JsonRpc10Response(request.getId());
202             response.setError(null);
203             String jsonString = null;
204             try {
205                 jsonString = objectMapper.writeValueAsString(response);
206                 nettyChannel.writeAndFlush(jsonString);
207             } catch (JsonProcessingException e) {
208                 LOG.error("Exception while processing JSON string {}", jsonString, e);
209             }
210             return;
211         }
212
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;
218             try {
219                 jsonString = objectMapper.writeValueAsString(response);
220                 nettyChannel.writeAndFlush(jsonString);
221             } catch (JsonProcessingException e) {
222                 LOG.error("Exception while processing JSON string {}", jsonString, e);
223             }
224             return;
225         }
226
227         LOG.error("No handler for Request : {} on {}", requestJson.toString(), context);
228     }
229
230     public Map<String, CallContext> getMethodContext() {
231         return methodContext;
232     }
233
234     public static void setReaperInterval(int interval) {
235         reaperInterval = interval;
236         LOG.info("Ovsdb Rpc Task interval is set to {} millisecond", reaperInterval);
237     }
238 }