VPP-330 Track pending map-requests with a fifo
[vpp.git] / vpp-api / java / jvpp / jvpp.c
1 /*
2  * Copyright (c) 2016 Cisco and/or its affiliates.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at:
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 #define _GNU_SOURCE /* for strcasestr(3) */
16 #include <vnet/vnet.h>
17
18 #define vl_api_version(n,v) static u32 vpe_api_version = (v);
19 #include <vpp-api/vpe.api.h>
20 #undef vl_api_version
21
22 #include <jni.h>
23 #include <jvpp/jvpp.h>
24 #include <jvpp/org_openvpp_jvpp_VppJNIConnection.h>
25 #include <jvpp/org_openvpp_jvpp_JVppImpl.h>
26
27 #include <vpp-api/vpe_msg_enum.h>
28 #define vl_typedefs             /* define message structures */
29 #include <vpp-api/vpe_all_api_h.h>
30 #undef vl_typedefs
31
32 #define vl_endianfun
33 #include <vpp-api/vpe_all_api_h.h>
34 #undef vl_endianfun
35
36 /* instantiate all the print functions we know about */
37 #define vl_print(handle, ...)
38 #define vl_printfun
39 #include <vpp-api/vpe_all_api_h.h>
40 #undef vl_printfun
41
42 #ifndef VPPJNI_DEBUG
43 #define VPPJNI_DEBUG 0
44 #endif
45
46 #if VPPJNI_DEBUG == 1
47   #define DEBUG_LOG(...) clib_warning(__VA_ARGS__)
48 #else
49   #define DEBUG_LOG(...)
50 #endif
51
52 #include "gen/target/jvpp_gen.h"
53
54 static int connect_to_vpe(char *name);
55
56 /*
57  * The Java runtime isn't compile w/ -fstack-protector,
58  * so we have to supply missing external references for the
59  * regular vpp libraries. Weak reference in case folks get religion
60  * at a later date...
61  */
62 void __stack_chk_guard (void) __attribute__((weak));
63 void __stack_chk_guard (void) {  }
64
65 void vl_client_add_api_signatures (vl_api_memclnt_create_t *mp)
66 {
67     /*
68      * Send the main API signature in slot 0. This bit of code must
69      * match the checks in ../vpe/api/api.c: vl_msg_api_version_check().
70      */
71     mp->api_versions[0] = clib_host_to_net_u32 (vpe_api_version);
72 }
73
74 /* cleanup handler for RX thread */
75 static void cleanup_rx_thread(void *arg)
76 {
77     vppjni_main_t * jm = &vppjni_main;
78
79     vppjni_lock (jm, 99);
80
81     int getEnvStat = (*jm->jvm)->GetEnv(jm->jvm, (void **)&(jm->jenv), JNI_VERSION_1_8);
82     if (getEnvStat == JNI_EVERSION) {
83         clib_warning ("Unsupported JNI version\n");
84         jm->retval = VNET_API_ERROR_UNSUPPORTED_JNI_VERSION;
85         goto out;
86     } else if (getEnvStat != JNI_EDETACHED) {
87         (*jm->jvm)->DetachCurrentThread(jm->jvm);
88     }
89 out:
90     vppjni_unlock (jm);
91 }
92
93 JNIEXPORT jint JNICALL Java_org_openvpp_jvpp_VppJNIConnection_clientConnect
94   (JNIEnv *env, jclass obj, jstring clientName, jobject callback)
95 {
96     int rv;
97     const char *client_name;
98     void vl_msg_reply_handler_hookup(void);
99     vppjni_main_t * jm = &vppjni_main;
100
101     /*
102      * Bail out now if we're not running as root
103      */
104     if (geteuid() != 0)
105         return VNET_API_ERROR_NOT_RUNNING_AS_ROOT;
106
107     if (jm->is_connected)
108         return VNET_API_ERROR_ALREADY_CONNECTED;
109
110     client_name = (*env)->GetStringUTFChars(env, clientName, 0);
111     if (!client_name)
112         return VNET_API_ERROR_INVALID_VALUE;
113
114     rv = connect_to_vpe ((char *) client_name);
115
116     if (rv < 0)
117         clib_warning ("connection failed, rv %d", rv);
118
119     (*env)->ReleaseStringUTFChars (env, clientName, client_name);
120
121     if (rv == 0) {
122         f64 timeout;
123         clib_time_t clib_time;
124         clib_time_init (&clib_time);
125
126         /* vl_msg_reply_handler_hookup (); */
127         jm->is_connected = 1;
128
129         jm->callback = (*env)->NewGlobalRef(env, callback);
130         jm->callbackClass = (jclass)(*env)->NewGlobalRef(env, (*env)->GetObjectClass(env, callback));
131
132         {
133             // call control ping first to attach rx thread to java thread
134             vl_api_control_ping_t * mp;
135             M(CONTROL_PING, control_ping);
136             S;
137
138             // wait for results: Current time + 10 seconds is the timeout
139             timeout = clib_time_now (&clib_time) + 10.0;
140             rv = VNET_API_ERROR_RESPONSE_NOT_READY;
141             while (clib_time_now (&clib_time) < timeout) {
142               if (jm->result_ready == 1) {
143                 rv = (jm->retval);
144                 break;
145               }
146             }
147
148             if (rv != 0) {
149                 clib_warning ("first control ping failed: %d", rv);
150             }
151         }
152     }
153     DEBUG_LOG ("clientConnect result: %d", rv);
154     return rv;
155 }
156
157 JNIEXPORT void JNICALL Java_org_openvpp_jvpp_VppJNIConnection_clientDisconnect
158   (JNIEnv *env, jclass clazz)
159 {
160     vppjni_main_t * jm = &vppjni_main;
161     jm->is_connected = 0; // TODO make thread safe
162     vl_client_disconnect_from_vlib();
163 }
164
165 /**
166 * Send error reply to the requestor
167 * const char* call  pointer to the request name
168 * int context       call context identifier
169 * int retval        result of the operation
170 */
171 void CallOnError(const char* call, int context, int retval)
172 {
173     DEBUG_LOG("\nCallOnError : callback=%s,retval=%d,context=%d\n",call,clib_net_to_host_u32(retval), clib_net_to_host_u32(context));
174     vppjni_main_t * jm = &vppjni_main;
175     JNIEnv *env = jm->jenv;
176     if (!env) printf( "CallOnError : env is null!\n");
177     if (!jm->callbackClass) {
178         DEBUG_LOG( "CallOnError : jm->callbackClass is null!\n");
179         return;
180     }
181
182     jmethodID excConstructor = (*env)->GetMethodID(env, callbackExceptionClass, "<init>", "(Ljava/lang/String;II)V");
183     if (!excConstructor) {
184         DEBUG_LOG( "CallOnError : excConstructor is null!\n");
185         return;
186     }
187     jmethodID callbackExcMethod = (*env)->GetMethodID(env, jm->callbackClass, "onError", "(Lorg/openvpp/jvpp/VppCallbackException;)V");
188     if (!callbackExcMethod) {
189         DEBUG_LOG( "CallOnError : callbackExcMethod is null!\n");
190         return;
191     }
192
193     jobject excObject = (*env)->NewObject(env, callbackExceptionClass, excConstructor,(*env)->NewStringUTF(env, call), clib_net_to_host_u32(context), clib_net_to_host_u32(retval));
194     if (!excObject) {
195         DEBUG_LOG( "CallOnError : excObject is null!\n");
196         return;
197     }
198
199     (*env)->CallVoidMethod(env, jm->callback, callbackExcMethod, excObject);
200     DEBUG_LOG( "CallOnError : Response sent\n");
201 }
202
203 // control ping needs to be very first thing called
204 // to attach rx thread to java thread
205 static void vl_api_control_ping_reply_t_handler
206 (vl_api_control_ping_reply_t * mp)
207 {
208     vppjni_main_t * jm = &vppjni_main;
209
210     char was_thread_connected = 0;
211
212     // attach to java thread if not attached
213     int getEnvStat = (*jm->jvm)->GetEnv(jm->jvm, (void **)&(jm->jenv), JNI_VERSION_1_8);
214     if (getEnvStat == JNI_EDETACHED) {
215         if ((*jm->jvm)->AttachCurrentThread(jm->jvm, (void **)&(jm->jenv), NULL) != 0) {
216             clib_warning("Failed to attach thread\n");
217             jm->retval = VNET_API_ERROR_FAILED_TO_ATTACH_TO_JAVA_THREAD;
218             goto out;
219         }
220
221         // workaround as we can't use pthread_cleanup_push
222         pthread_key_create(&jm->cleanup_rx_thread_key, cleanup_rx_thread);
223         // destructor is only called if the value of key is non null
224         pthread_setspecific(jm->cleanup_rx_thread_key, (void *)1);
225         was_thread_connected = 1;
226     } else if (getEnvStat == JNI_EVERSION) {
227         clib_warning ("Unsupported JNI version\n");
228         jm->retval = VNET_API_ERROR_UNSUPPORTED_JNI_VERSION;
229         goto out;
230     }
231
232     if (was_thread_connected == 0) {
233         JNIEnv *env = jm->jenv;
234
235         if (mp->retval<0){
236             CallOnError("controlPing", mp->context, mp->retval);
237         } else {
238             jmethodID constructor = (*env)->GetMethodID(env, controlPingReplyClass, "<init>", "()V");
239             jmethodID callbackMethod = (*env)->GetMethodID(env, jm->callbackClass, "onControlPingReply", "(Lorg/openvpp/jvpp/dto/ControlPingReply;)V");
240
241             jobject dto = (*env)->NewObject(env, controlPingReplyClass, constructor);
242
243             jfieldID contextFieldId = (*env)->GetFieldID(env, controlPingReplyClass, "context", "I");
244             (*env)->SetIntField(env, dto, contextFieldId, clib_net_to_host_u32(mp->context));
245
246             jfieldID clientIndexFieldId = (*env)->GetFieldID(env, controlPingReplyClass, "clientIndex", "I");
247             (*env)->SetIntField(env, dto, clientIndexFieldId, clib_net_to_host_u32(mp->client_index));
248
249             jfieldID vpePidFieldId = (*env)->GetFieldID(env, controlPingReplyClass, "vpePid", "I");
250             (*env)->SetIntField(env, dto, vpePidFieldId, clib_net_to_host_u32(mp->vpe_pid));
251
252             (*env)->CallVoidMethod(env, jm->callback, callbackMethod, dto);
253         }
254     }
255
256     out:
257         jm->result_ready = 1;
258 }
259
260 jint JNI_OnLoad(JavaVM *vm, void *reserved) {
261     vppjni_main_t * jm = &vppjni_main;
262     JNIEnv* env;
263     if ((*vm)->GetEnv(vm, (void**) &env, JNI_VERSION_1_8) != JNI_OK) {
264         return JNI_EVERSION;
265     }
266
267     if (cache_class_references(env) != 0) {
268         return JNI_ERR;
269     }
270
271     jm->jvm = vm;
272     return JNI_VERSION_1_8;
273 }
274
275 void JNI_OnUnload(JavaVM *vm, void *reserved) {
276     vppjni_main_t * jm = &vppjni_main;
277     JNIEnv* env;
278     if ((*vm)->GetEnv(vm, (void**) &env, JNI_VERSION_1_8) != JNI_OK) {
279         return;
280     }
281
282     // cleanup:
283     (*env)->DeleteGlobalRef(env, jm->callbackClass);
284     (*env)->DeleteGlobalRef(env, jm->callback);
285
286     jm->callbackClass = NULL;
287     jm->callback = NULL;
288     jm->jenv = NULL;
289     jm->jvm = NULL;
290 }
291
292 static int connect_to_vpe(char *name)
293 {
294     vppjni_main_t * jm = &vppjni_main;
295     api_main_t * am = &api_main;
296
297     if (vl_client_connect_to_vlib("/vpe-api", name, 32) < 0)
298         return -1;
299
300     jm->my_client_index = am->my_client_index;
301     jm->vl_input_queue = am->shmem_hdr->vl_input_queue;
302
303 #define _(N,n)                                  \
304     vl_msg_api_set_handlers(VL_API_##N, #n,     \
305             vl_api_##n##_t_handler,                 \
306             vl_noop_handler,                    \
307             vl_api_##n##_t_endian,              \
308             vl_api_##n##_t_print,               \
309             sizeof(vl_api_##n##_t), 1);
310     foreach_vpe_api_msg;
311 #undef _
312
313     return 0;
314 }