6cc05530d379435cb0e2c4486ddcdd00f1b4cb06
[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 <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 <api/vpe_msg_enum.h>
28 #define vl_typedefs             /* define message structures */
29 #include <api/vpe_all_api_h.h>
30 #undef vl_typedefs
31
32 #define vl_endianfun
33 #include <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 <api/vpe_all_api_h.h>
40 #undef vl_printfun
41
42 #define VPPJNI_DEBUG 0
43
44 #if VPPJNI_DEBUG == 1
45   #define DEBUG_LOG(...) clib_warning(__VA_ARGS__)
46 #else
47   #define DEBUG_LOG(...)
48 #endif
49
50 #include "gen/target/jvpp_gen.h"
51
52 static int connect_to_vpe(char *name);
53
54 /*
55  * The Java runtime isn't compile w/ -fstack-protector,
56  * so we have to supply missing external references for the
57  * regular vpp libraries. Weak reference in case folks get religion
58  * at a later date...
59  */
60 void __stack_chk_guard (void) __attribute__((weak));
61 void __stack_chk_guard (void) {  }
62
63 void vl_client_add_api_signatures (vl_api_memclnt_create_t *mp)
64 {
65     /*
66      * Send the main API signature in slot 0. This bit of code must
67      * match the checks in ../vpe/api/api.c: vl_msg_api_version_check().
68      */
69     mp->api_versions[0] = clib_host_to_net_u32 (vpe_api_version);
70 }
71
72 /* cleanup handler for RX thread */
73 static void cleanup_rx_thread(void *arg)
74 {
75     vppjni_main_t * jm = &vppjni_main;
76
77     vppjni_lock (jm, 99);
78
79     int getEnvStat = (*jm->jvm)->GetEnv(jm->jvm, (void **)&(jm->jenv), JNI_VERSION_1_8);
80     if (getEnvStat == JNI_EVERSION) {
81         clib_warning ("Unsupported JNI version\n");
82         jm->retval = VNET_API_ERROR_UNSUPPORTED_JNI_VERSION;
83         goto out;
84     } else if (getEnvStat != JNI_EDETACHED) {
85         (*jm->jvm)->DetachCurrentThread(jm->jvm);
86     }
87 out:
88     vppjni_unlock (jm);
89 }
90
91 JNIEXPORT jint JNICALL Java_org_openvpp_jvpp_VppJNIConnection_clientConnect
92   (JNIEnv *env, jclass obj, jstring clientName, jobject callback)
93 {
94     int rv;
95     const char *client_name;
96     void vl_msg_reply_handler_hookup(void);
97     vppjni_main_t * jm = &vppjni_main;
98
99     /*
100      * Bail out now if we're not running as root
101      */
102     if (geteuid() != 0)
103         return VNET_API_ERROR_NOT_RUNNING_AS_ROOT;
104
105     if (jm->is_connected)
106         return VNET_API_ERROR_ALREADY_CONNECTED;
107
108     client_name = (*env)->GetStringUTFChars(env, clientName, 0);
109     if (!client_name)
110         return VNET_API_ERROR_INVALID_VALUE;
111
112     rv = connect_to_vpe ((char *) client_name);
113
114     if (rv < 0)
115         clib_warning ("connection failed, rv %d", rv);
116
117     (*env)->ReleaseStringUTFChars (env, clientName, client_name);
118
119     if (rv == 0) {
120         f64 timeout;
121         clib_time_t clib_time;
122         clib_time_init (&clib_time);
123
124         /* vl_msg_reply_handler_hookup (); */
125         jm->is_connected = 1;
126
127         jm->callback = (*env)->NewGlobalRef(env, callback);
128         jm->callbackClass = (jclass)(*env)->NewGlobalRef(env, (*env)->GetObjectClass(env, callback));
129
130         {
131             // call control ping first to attach rx thread to java thread
132             vl_api_control_ping_t * mp;
133             M(CONTROL_PING, control_ping);
134             S;
135
136             // wait for results:
137             timeout = clib_time_now (&clib_time) + 1.0;
138             rv = VNET_API_ERROR_RESPONSE_NOT_READY;
139             while (clib_time_now (&clib_time) < timeout) {
140               if (jm->result_ready == 1) {
141                 rv = (jm->retval);
142                 break;
143               }
144             }
145
146             if (rv != 0) {
147                 clib_warning ("first control ping failed: %d", rv);
148             }
149         }
150     }
151     DEBUG_LOG ("clientConnect result: %d", rv);
152     return rv;
153 }
154
155 JNIEXPORT void JNICALL Java_org_openvpp_jvpp_VppJNIConnection_clientDisconnect
156   (JNIEnv *env, jclass clazz)
157 {
158     vppjni_main_t * jm = &vppjni_main;
159     jm->is_connected = 0; // TODO make thread safe
160     vl_client_disconnect_from_vlib();
161 }
162
163 // control ping needs to be very first thing called
164 // to attach rx thread to java thread
165 static void vl_api_control_ping_reply_t_handler
166 (vl_api_control_ping_reply_t * mp)
167 {
168     vppjni_main_t * jm = &vppjni_main;
169
170     char was_thread_connected = 0;
171
172     // attach to java thread if not attached
173     int getEnvStat = (*jm->jvm)->GetEnv(jm->jvm, (void **)&(jm->jenv), JNI_VERSION_1_8);
174     if (getEnvStat == JNI_EDETACHED) {
175         if ((*jm->jvm)->AttachCurrentThread(jm->jvm, (void **)&(jm->jenv), NULL) != 0) {
176             clib_warning("Failed to attach thread\n");
177             jm->retval = VNET_API_ERROR_FAILED_TO_ATTACH_TO_JAVA_THREAD;
178             goto out;
179         }
180
181         // workaround as we can't use pthread_cleanup_push
182         pthread_key_create(&jm->cleanup_rx_thread_key, cleanup_rx_thread);
183         // destructor is only called if the value of key is non null
184         pthread_setspecific(jm->cleanup_rx_thread_key, (void *)1);
185         was_thread_connected = 1;
186     } else if (getEnvStat == JNI_EVERSION) {
187         clib_warning ("Unsupported JNI version\n");
188         jm->retval = VNET_API_ERROR_UNSUPPORTED_JNI_VERSION;
189         goto out;
190     }
191
192     if (was_thread_connected == 0) {
193         JNIEnv *env = jm->jenv;
194
195         jmethodID constructor = (*env)->GetMethodID(env, controlPingReplyClass, "<init>", "()V");
196         jmethodID callbackMethod = (*env)->GetMethodID(env, jm->callbackClass, "onControlPingReply", "(Lorg/openvpp/jvpp/dto/ControlPingReply;)V");
197
198         jobject dto = (*env)->NewObject(env, controlPingReplyClass, constructor);
199
200         jfieldID contextFieldId = (*env)->GetFieldID(env, controlPingReplyClass, "context", "I");
201         (*env)->SetIntField(env, dto, contextFieldId, clib_net_to_host_u32(mp->context));
202
203         jfieldID retvalFieldId = (*env)->GetFieldID(env, controlPingReplyClass, "retval", "I");
204         (*env)->SetIntField(env, dto, retvalFieldId, clib_net_to_host_u32(mp->retval));
205
206         jfieldID clientIndexFieldId = (*env)->GetFieldID(env, controlPingReplyClass, "clientIndex", "I");
207         (*env)->SetIntField(env, dto, clientIndexFieldId, clib_net_to_host_u32(mp->client_index));
208
209         jfieldID vpePidFieldId = (*env)->GetFieldID(env, controlPingReplyClass, "vpePid", "I");
210         (*env)->SetIntField(env, dto, vpePidFieldId, clib_net_to_host_u32(mp->vpe_pid));
211
212         (*env)->CallVoidMethod(env, jm->callback, callbackMethod, dto);
213     }
214
215     out:
216         jm->result_ready = 1;
217 }
218
219 jint JNI_OnLoad(JavaVM *vm, void *reserved) {
220     vppjni_main_t * jm = &vppjni_main;
221     JNIEnv* env;
222     if ((*vm)->GetEnv(vm, (void**) &env, JNI_VERSION_1_8) != JNI_OK) {
223         return JNI_EVERSION;
224     }
225
226     if (cache_class_references(env) != 0) {
227         return JNI_ERR;
228     }
229
230     jm->jvm = vm;
231     return JNI_VERSION_1_8;
232 }
233
234 void JNI_OnUnload(JavaVM *vm, void *reserved) {
235     vppjni_main_t * jm = &vppjni_main;
236     JNIEnv* env;
237     if ((*vm)->GetEnv(vm, (void**) &env, JNI_VERSION_1_8) != JNI_OK) {
238         return;
239     }
240
241     // cleanup:
242     (*env)->DeleteGlobalRef(env, jm->callbackClass);
243     (*env)->DeleteGlobalRef(env, jm->callback);
244
245     jm->callbackClass = NULL;
246     jm->callback = NULL;
247     jm->jenv = NULL;
248     jm->jvm = NULL;
249 }
250
251 static int connect_to_vpe(char *name)
252 {
253     vppjni_main_t * jm = &vppjni_main;
254     api_main_t * am = &api_main;
255
256     if (vl_client_connect_to_vlib("/vpe-api", name, 32) < 0)
257         return -1;
258
259     jm->my_client_index = am->my_client_index;
260     jm->vl_input_queue = am->shmem_hdr->vl_input_queue;
261
262 #define _(N,n)                                  \
263     vl_msg_api_set_handlers(VL_API_##N, #n,     \
264             vl_api_##n##_t_handler,                 \
265             vl_noop_handler,                    \
266             vl_api_##n##_t_endian,              \
267             vl_api_##n##_t_print,               \
268             sizeof(vl_api_##n##_t), 1);
269     foreach_vpe_api_msg;
270 #undef _
271
272     return 0;
273 }