aboutsummaryrefslogtreecommitdiffstats
path: root/vpp-api/python/vpp_papi/pneum_wrap.c
blob: d1795aa13a7e1bb551b6394e838cc7b08be45692 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
#include <Python.h>
#include "pneum.h"

static PyObject *pneum_callback = NULL;

int
wrap_pneum_callback (char *data, int len)
{
  PyGILState_STATE gstate;
  PyObject *result;//, *arglist;

  gstate = PyGILState_Ensure();

  /* Time to call the callback */
#if PY_VERSION_HEX >= 0x03000000
  result = PyObject_CallFunction(pneum_callback, "y#", data, len);
#else
  result = PyObject_CallFunction(pneum_callback, "s#", data, len);
#endif
  if (result)
    Py_DECREF(result);
  else
    PyErr_Print();

  PyGILState_Release(gstate);
  return (0);
}

static PyObject *
wrap_connect (PyObject *self, PyObject *args)
{
  char *name;
  int rv;
  PyObject *temp;

  if (!PyArg_ParseTuple(args, "sO:set_callback", &name, &temp))
    return (NULL);
  
  if (!PyCallable_Check(temp)) {
    PyErr_SetString(PyExc_TypeError, "parameter must be callable");
    return NULL;
  }

  Py_XINCREF(temp);         /* Add a reference to new callback */
  Py_XDECREF(pneum_callback);  /* Dispose of previous callback */
  pneum_callback = temp;       /* Remember new callback */

  Py_BEGIN_ALLOW_THREADS
  rv = pneum_connect(name);
  Py_END_ALLOW_THREADS
  return PyLong_FromLong(rv);
}

static PyObject *
wrap_disconnect (PyObject *self, PyObject *args)
{
  int rv;
  Py_BEGIN_ALLOW_THREADS
  rv = pneum_disconnect();
  Py_END_ALLOW_THREADS
  return PyLong_FromLong(rv);
}
static PyObject *
wrap_write (PyObject *self, PyObject *args)
{
  char *data;
  int len, rv;

  if (!PyArg_ParseTuple(args, "s#", &data, &len)) 
    return NULL;     
  Py_BEGIN_ALLOW_THREADS
  rv = pneum_write(data, len);
  Py_END_ALLOW_THREADS

  return PyLong_FromLong(rv);
}

void vl_msg_api_free(void *);

static PyObject *
wrap_read (PyObject *self, PyObject *args)
{
  char *data;
  int len, rv;

  Py_BEGIN_ALLOW_THREADS
  rv = pneum_read(&data, &len);
  Py_END_ALLOW_THREADS

  if (rv != 0) { Py_RETURN_NONE; }
#if PY_VERSION_HEX >= 0x03000000
  PyObject *ret = Py_BuildValue("y#", data, len);
#else
  PyObject *ret = Py_BuildValue("s#", data, len);
#endif
  if (!ret) { Py_RETURN_NONE; }

  vl_msg_api_free(data);
  return ret;
}

static PyMethodDef vpp_api_Methods[] = {
  {"connect", wrap_connect, METH_VARARGS, "Connect to the VPP API."},
  {"disconnect", wrap_disconnect, METH_VARARGS, "Disconnect from the VPP API."},
  {"write", wrap_write, METH_VARARGS, "Write data to the VPP API."},
  {"read", wrap_read, METH_VARARGS, "Read data from the VPP API."},
  {NULL, NULL, 0, NULL}        /* Sentinel */
};

#if PY_VERSION_HEX >= 0x03000000
PyMODINIT_FUNC
PyInit_vpp_api (void)
#else
void
initvpp_api (void)
#endif
{
#if PY_VERSION_HEX >= 0x03000000
  static struct PyModuleDef vpp_api_module = {
# if PY_VERSION_HEX >= 0x03020000
    PyModuleDef_HEAD_INIT,
# else
    {
      PyObject_HEAD_INIT(NULL)
      NULL, /* m_init */
      0,    /* m_index */
      NULL, /* m_copy */
    },
# endif
    (char *) "vpp_api",
    NULL,
    -1,
    vpp_api_Methods,
    NULL,
    NULL,
    NULL,
    NULL
  };
#endif

  /* Ensure threading is initialised */
  if (!PyEval_ThreadsInitialized()) {
    PyEval_InitThreads();
  }

#if PY_VERSION_HEX >= 0x03000000
  return PyModule_Create(&vpp_api_module);
#else
  Py_InitModule((char *) "vpp_api", vpp_api_Methods);
  return;
#endif
}
n class="p">(class_reference_template.substitute( ref_name=util.add_notification_suffix(ref_name))) find_class_invocations.append(find_class_invocation_template.substitute( plugin_name=plugin_name, ref_name=util.add_notification_suffix(ref_name), class_name=util.add_notification_suffix(class_name))) delete_class_invocations.append(delete_class_invocation_template.substitute( ref_name=util.add_notification_suffix(ref_name))) # add exception class to class cache ref_name = 'callbackException' class_name = 'io/fd/vpp/jvpp/VppCallbackException' class_references.append(class_reference_template.substitute( ref_name=ref_name)) find_class_invocations.append(find_class_template.substitute( ref_name=ref_name, class_name=class_name)) delete_class_invocations.append(delete_class_invocation_template.substitute(ref_name=ref_name)) return class_cache_template.substitute( class_references="".join(class_references), find_class_invocations="".join(find_class_invocations), delete_class_invocations="".join(delete_class_invocations)) # TODO: cache method and field identifiers to achieve better performance # https://jira.fd.io/browse/HONEYCOMB-42 request_class_template = Template(""" jclass requestClass = (*env)->FindClass(env, "io/fd/vpp/jvpp/${plugin_name}/dto/${java_name_upper}");""") request_field_identifier_template = Template(""" jfieldID ${field_reference_name}FieldId = (*env)->GetFieldID(env, ${object_name}Class, "${field_name}", "${jni_signature}"); ${jni_type} ${field_reference_name} = (*env)->Get${jni_getter}(env, ${object_name}, ${field_reference_name}FieldId); """) jni_msg_size_template = Template(""" + ${array_length}*sizeof(${element_type})""") jni_impl_template = Template(""" /** * JNI binding for sending ${c_name} message. * Generated based on $inputfile preparsed data: $api_data */ JNIEXPORT jint JNICALL Java_io_fd_vpp_jvpp_${plugin_name}_JVpp${java_plugin_name}Impl_${field_name}0 (JNIEnv * env, jclass clazz$args) { ${plugin_name}_main_t *plugin_main = &${plugin_name}_main; vl_api_${c_name}_t * mp; u32 my_context_id = vppjni_get_context_id (&jvpp_main); $request_class $jni_identifiers // create message: mp = vl_msg_api_alloc(${msg_size}); memset (mp, 0, ${msg_size}); mp->_vl_msg_id = ntohs (get_message_id(env, "${c_name}_${crc}")); mp->client_index = plugin_main->my_client_index; mp->context = clib_host_to_net_u32 (my_context_id); $msg_initialization // send message: vl_msg_api_send_shmem (plugin_main->vl_input_queue, (u8 *)&mp); if ((*env)->ExceptionCheck(env)) { return JNI_ERR; } return my_context_id; }""") def generate_jni_impl(func_list, plugin_name, inputfile): jni_impl = [] for f in func_list: f_name = f['name'] camel_case_function_name = util.underscore_to_camelcase(f_name) if is_manually_generated(f_name, plugin_name) or util.is_reply(camel_case_function_name) \ or util.is_ignored(f_name) or util.is_just_notification(f_name): continue arguments = '' request_class = '' jni_identifiers = '' msg_initialization = '' f_name_uppercase = f_name.upper() msg_size = 'sizeof(*mp)' if f['args']: arguments = ', jobject request' camel_case_function_name_upper = util.underscore_to_camelcase_upper(f_name) request_class = request_class_template.substitute( java_name_upper=camel_case_function_name_upper, plugin_name=plugin_name) for t in zip(f['types'], f['args'], f['lengths'], f['arg_types']): field_name = util.underscore_to_camelcase(t[1]) is_variable_len_array = t[2][1] if is_variable_len_array: msg_size += jni_msg_size_template.substitute(array_length=util.underscore_to_camelcase(t[2][0]), element_type=t[3]) jni_identifiers += jni_gen.jni_request_identifiers_for_type(field_type=t[0], field_reference_name=field_name, field_name=field_name) msg_initialization += jni_gen.jni_request_binding_for_type(field_type=t[0], c_name=t[1], field_reference_name=field_name, field_length=t[2][0], is_variable_len_array=is_variable_len_array) jni_impl.append(jni_impl_template.substitute( inputfile=inputfile, api_data=util.api_message_to_javadoc(f), field_reference_name=camel_case_function_name, field_name=camel_case_function_name, c_name_uppercase=f_name_uppercase, c_name=f_name, crc=f['crc'], plugin_name=plugin_name, java_plugin_name=plugin_name.title(), request_class=request_class, jni_identifiers=jni_identifiers, msg_size=msg_size, msg_initialization=msg_initialization, args=arguments)) return "\n".join(jni_impl) # code fragment for checking result of the operation before sending request reply callback_err_handler_template = Template(""" // for negative result don't send callback message but send error callback if (mp->retval<0) { call_on_error("${handler_name}", mp->context, mp->retval, plugin_main->callbackClass, plugin_main->callbackObject, callbackExceptionClass); return; } if (mp->retval == VNET_API_ERROR_IN_PROGRESS) { clib_warning("Result in progress"); return; } """) msg_handler_template = Template(""" /** * Handler for ${handler_name} message. * Generated based on $inputfile preparsed data: $api_data */ static void vl_api_${handler_name}_t_handler (vl_api_${handler_name}_t * mp) { ${plugin_name}_main_t *plugin_main = &${plugin_name}_main; JNIEnv *env = jvpp_main.jenv; $err_handler jmethodID constructor = (*env)->GetMethodID(env, ${class_ref_name}Class, "<init>", "()V"); jmethodID callbackMethod = (*env)->GetMethodID(env, plugin_main->callbackClass, "on${dto_name}", "(Lio/fd/vpp/jvpp/${plugin_name}/dto/${dto_name};)V"); jobject dto = (*env)->NewObject(env, ${class_ref_name}Class, constructor); $dto_setters (*env)->CallVoidMethod(env, plugin_main->callbackObject, callbackMethod, dto); // free DTO as per http://stackoverflow.com/questions/1340938/memory-leak-when-calling-java-code-from-c-using-jni (*env)->DeleteLocalRef(env, dto); }""") def generate_msg_handlers(func_list, plugin_name, inputfile): handlers = [] for f in func_list: handler_name = f['name'] dto_name = util.underscore_to_camelcase_upper(handler_name) ref_name = util.underscore_to_camelcase(handler_name) if is_manually_generated(handler_name, plugin_name) or util.is_ignored(handler_name): continue if not util.is_reply(dto_name) and not util.is_notification(handler_name): continue if util.is_notification(handler_name): dto_name = util.add_notification_suffix(dto_name) ref_name = util.add_notification_suffix(ref_name) dto_setters = '' err_handler = '' # dto setters for t in zip(f['types'], f['args'], f['lengths']): c_name = t[1] java_name = util.underscore_to_camelcase(c_name) field_length = t[2][0] is_variable_len_array = t[2][1] length_field_type = None if is_variable_len_array: length_field_type = f['types'][f['args'].index(field_length)] dto_setters += jni_gen.jni_reply_handler_for_type(handler_name=handler_name, ref_name=ref_name, field_type=t[0], c_name=t[1], field_reference_name=java_name, field_name=java_name, field_length=field_length, is_variable_len_array=is_variable_len_array, length_field_type=length_field_type) # for retval don't generate setters and generate retval check if util.is_retval_field(c_name): err_handler = callback_err_handler_template.substitute( handler_name=handler_name ) continue handlers.append(msg_handler_template.substitute( inputfile=inputfile, api_data=util.api_message_to_javadoc(f), handler_name=handler_name, plugin_name=plugin_name, dto_name=dto_name, class_ref_name=ref_name, dto_setters=dto_setters, err_handler=err_handler)) return "\n".join(handlers) handler_registration_template = Template("""_(${name}_${crc}, ${name}) \\ """) def generate_handler_registration(func_list): handler_registration = ["#define foreach_api_reply_handler \\\n"] for f in func_list: name = f['name'] camelcase_name = util.underscore_to_camelcase(f['name']) if (not util.is_reply(camelcase_name) and not util.is_notification(name)) or util.is_ignored(name) \ or util.is_control_ping(camelcase_name): continue handler_registration.append(handler_registration_template.substitute( name=name, crc=f['crc'])) return "".join(handler_registration) api_verification_template = Template("""_(${name}_${crc}) \\ """) def generate_api_verification(func_list): api_verification = ["#define foreach_supported_api_message \\\n"] for f in func_list: name = f['name'] if util.is_ignored(name): continue api_verification.append(api_verification_template.substitute( name=name, crc=f['crc'])) return "".join(api_verification) jvpp_c_template = Template("""/** * This file contains JNI bindings for jvpp Java API. * It was generated by jvpp_c_gen.py based on $inputfile * (python representation of api file generated by vppapigen). */ // JAVA class reference cache $class_cache // List of supported API messages used for verification $api_verification // JNI bindings $jni_implementations // Message handlers $msg_handlers // Registration of message handlers in vlib $handler_registration """) def generate_jvpp(func_list, plugin_name, inputfile, path): """ Generates jvpp C file """ print "Generating jvpp C" class_cache = generate_class_cache(func_list, plugin_name) jni_impl = generate_jni_impl(func_list, plugin_name, inputfile) msg_handlers = generate_msg_handlers(func_list, plugin_name, inputfile) handler_registration = generate_handler_registration(func_list) api_verification = generate_api_verification(func_list) jvpp_c_file = open("%s/jvpp_%s_gen.h" % (path, plugin_name), 'w') jvpp_c_file.write(jvpp_c_template.substitute( inputfile=inputfile, class_cache=class_cache, api_verification=api_verification, jni_implementations=jni_impl, msg_handlers=msg_handlers, handler_registration=handler_registration)) jvpp_c_file.flush() jvpp_c_file.close()