HONEYCOMB-10: jVpp - the new java API. C code and jar file generation

Added comments generation for C and Java files.

Change-Id: Ifb670a5592eb871bfe68804f0a8d8f9b5b14f00a
Signed-off-by: Marek Gradzki <mgradzki@cisco.com>
Signed-off-by: Ed Warnicke <eaw@cisco.com>
This commit is contained in:
Marek Gradzki
2016-04-26 12:09:05 +02:00
committed by Ed Warnicke
parent c5e8681b32
commit d85036fd6b
15 changed files with 997 additions and 34 deletions

View File

@ -90,4 +90,51 @@ demo = japi/test/demo.class
$(demo): $(jarfile)
$(JAVAC) -cp $(jarfile) -d $(JAVAROOT) @srcdir@/japi/test/demo.java
all-local: $(jarfile) $(demo)
#
# jVpp binding
#
nobase_include_HEADERS += \
jvpp/org_openvpp_jvpp_VppJNIConnection.h
lib_LTLIBRARIES += libjvpp.la
libjvpp_la_SOURCES = jvpp/jvpp.c
libjvpp_la_LIBADD = -lvlibmemoryclient -lvlibapi -lsvm -lvppinfra \
-lpthread -lm -lrt
libjvpp_la_LDFLAGS = -module
libjvpp_la_CPPFLAGS = -I$(JAVA_HOME)/include -I$(JAVA_HOME)/include/linux
# todo make two jars api jar and impl jar
jarfile_jvpp = jvpp-$(PACKAGE_VERSION).jar
packagedir_jvpp = org/openvpp/jvpp
JAVAROOT = .
BUILT_SOURCES += jvpp/org_openvpp_jvpp_VppJNIConnection.h jvpp/jvpp.c
jvpp/org_openvpp_jvpp_VppJNIConnection.h: $(prefix)/../vpp/api/vpe.api
@echo " jVpp API"; \
mkdir -p dto future callfacade callback @srcdir@/jvpp/gen/target/org/openvpp/jvpp; \
$(CC) $(CPPFLAGS) -E -P -C -x c $< \
| vppapigen --input - --python defs_vpp_papi.py; \
@srcdir@/jvpp/gen/jvpp_gen.py -i defs_vpp_papi.py; \
cp -rf dto future callfacade callback *.java -t @srcdir@/jvpp/gen/target/org/openvpp/jvpp/; \
cp -rf jvpp_gen.h -t @srcdir@/jvpp/gen/target; \
rm -rf dto future callfacade callback *.java jvpp_gen.h; \
$(JAVAC) -classpath . -d . @srcdir@/jvpp/org/openvpp/jvpp/*.java \
@srcdir@/jvpp/org/openvpp/jvpp/dto/*.java \
@srcdir@/jvpp/org/openvpp/jvpp/callback/*.java \
@srcdir@/jvpp/org/openvpp/jvpp/future/*.java \
@srcdir@/jvpp/org/openvpp/jvpp/test/*.java \
@srcdir@/jvpp/gen/target/org/openvpp/jvpp/*.java \
@srcdir@/jvpp/gen/target/org/openvpp/jvpp/dto/*.java \
@srcdir@/jvpp/gen/target/org/openvpp/jvpp/callback/*.java \
@srcdir@/jvpp/gen/target/org/openvpp/jvpp/callfacade/*.java \
@srcdir@/jvpp/gen/target/org/openvpp/jvpp/future/*.java ; \
$(JAVAH) -classpath . -d jvpp org.openvpp.jvpp.VppJNIConnection ; \
$(JAVAH) -classpath . -d jvpp org.openvpp.jvpp.JVppImpl ;
$(jarfile_jvpp): libjvpp.la
cd .libs ; $(JAR) cf $(JARFLAGS) ../$@ libjvpp.so.0.0.0 ../$(packagedir_jvpp)/* ; cd ..
all-local: $(jarfile) $(jarfile_jvpp) $(demo)

View File

@ -8,12 +8,19 @@ AM_PROG_AS
AC_PROG_CC
AM_PROG_CC_C_O
if test -f /usr/bin/lsb_release && test `lsb_release -si` == "Ubuntu" && test `lsb_release -sr` == "14.04" && test -d /usr/lib/jvm/java-8-openjdk-amd64/ ; then
JAVA_HOME=/usr/lib/jvm/java-8-openjdk-amd64/
JAVAC=${JAVA_HOME}/bin/javac
PATH=${JAVA_HOME}/bin/:${PATH}
break
fi
AX_CHECK_JAVA_HOME
AX_PROG_JAVAC
AX_PROG_JAVAH
AX_PROG_JAR
AX_PROG_JAVADOC
AX_PROG_JAVA
AX_CHECK_JAVA_HOME
AC_OUTPUT([Makefile])

View File

@ -25,7 +25,11 @@ callback_template = Template("""
package $base_package.$callback_package;
/**
* $docs
* <p>Represents callback for vpe.api message.
* <br>It was generated by callback_gen.py based on $inputfile preparsed data:
* <pre>
$docs
* </pre>
*/
public interface $cls_name extends $base_package.$callback_package.JVppCallback {
@ -38,16 +42,16 @@ global_callback_template = Template("""
package $base_package.$callback_package;
/**
*
*
* Global aggregated callback interface
* <p>Global aggregated callback interface.
* <br>It was generated by callback_gen.py based on $inputfile
* <br>(python representation of vpe.api generated by vppapigen).
*/
public interface JVppGlobalCallback extends $callbacks {
}
""")
def generate_callbacks(func_list, base_package, callback_package, dto_package):
def generate_callbacks(func_list, base_package, callback_package, dto_package, inputfile):
""" Generates callback interfaces """
print "Generating Callback interfaces"
@ -73,7 +77,8 @@ def generate_callbacks(func_list, base_package, callback_package, dto_package):
reply_type = "%s.%s.%s" % (base_package, dto_package, camel_case_name_with_suffix)
method = "void on{0}({1} reply);".format(camel_case_name_with_suffix, reply_type)
callback_file.write(
callback_template.substitute(docs='Generated from ' + str(func),
callback_template.substitute(inputfile=inputfile,
docs=util.api_message_to_javadoc(func),
cls_name=camel_case_name + callback_suffix,
callback_method=method,
base_package=base_package,
@ -82,7 +87,8 @@ def generate_callbacks(func_list, base_package, callback_package, dto_package):
callback_file.close()
callback_file = open(os.path.join(callback_package, "JVppGlobalCallback.java"), 'w')
callback_file.write(global_callback_template.substitute(callbacks=", ".join(callbacks),
callback_file.write(global_callback_template.substitute(inputfile=inputfile,
callbacks=", ".join(callbacks),
base_package=base_package,
callback_package=callback_package))
callback_file.flush()

View File

@ -20,7 +20,11 @@ dto_template = Template("""
package $base_package.$dto_package;
/**
* $docs
* <p>This class represents $description.
* <br>It was generated by dto_gen.py based on $inputfile preparsed data:
* <pre>
$docs
* </pre>
*/
public final class $cls_name implements $base_package.$dto_package.$base_type {
@ -36,8 +40,7 @@ send_template = Template(""" @Override
return jvpp.$method_name($args);
}\n""")
def generate_dtos(func_list, base_package, dto_package):
def generate_dtos(func_list, base_package, dto_package, inputfile):
""" Generates dto objects in a dedicated package """
print "Generating DTOs"
@ -60,6 +63,7 @@ def generate_dtos(func_list, base_package, dto_package):
methods = ""
base_type = ""
if util.is_reply(camel_case_dto_name):
description = "vpe.api reply DTO"
request_dto_name = get_request_name(camel_case_dto_name, func['name'])
if util.is_details(camel_case_dto_name):
# FIXME assumption that dump calls end with "Dump" suffix. Not enforced in vpe.api
@ -75,11 +79,15 @@ def generate_dtos(func_list, base_package, dto_package):
args=args)
if util.is_dump(camel_case_dto_name):
base_type += "JVppDump"
description = "vpe.api dump request DTO"
else:
base_type += "JVppRequest"
description = "vpe.api request DTO"
dto_file = open(dto_path, 'w')
dto_file.write(dto_template.substitute(docs='Generated from ' + str(func),
dto_file.write(dto_template.substitute(inputfile=inputfile,
description=description,
docs=util.api_message_to_javadoc(func),
cls_name=camel_case_dto_name,
fields=fields,
methods=methods,
@ -89,13 +97,12 @@ def generate_dtos(func_list, base_package, dto_package):
dto_file.flush()
dto_file.close()
flush_dump_reply_dtos()
flush_dump_reply_dtos(inputfile)
dump_dto_suffix = "ReplyDump"
dump_reply_artificial_dtos = {}
# Returns request name or special one from unconventional_naming_rep_req map
def get_request_name(camel_case_dto_name, func_name):
return util.underscore_to_camelcase_upper(
@ -103,12 +110,14 @@ def get_request_name(camel_case_dto_name, func_name):
else util.remove_reply_suffix(camel_case_dto_name)
def flush_dump_reply_dtos():
def flush_dump_reply_dtos(inputfile):
for dump_reply_artificial_dto in dump_reply_artificial_dtos.values():
dto_path = os.path.join(dump_reply_artificial_dto['dto_package'],
dump_reply_artificial_dto['cls_name'] + ".java")
dto_file = open(dto_path, 'w')
dto_file.write(dto_template.substitute(docs=dump_reply_artificial_dto['docs'],
dto_file.write(dto_template.substitute(inputfile=inputfile,
description="vpe.api dump reply wrapper",
docs=dump_reply_artificial_dto['docs'],
cls_name=dump_reply_artificial_dto['cls_name'],
fields=dump_reply_artificial_dto['fields'],
methods=dump_reply_artificial_dto['methods'],
@ -133,7 +142,7 @@ def generate_dump_reply_dto(request_dto_name, base_package, dto_package, camel_c
dump_reply_artificial_dtos[request_dto_name]['fields'] = \
dump_reply_artificial_dtos[request_dto_name]['fields'] + '\n' + fields
else:
dump_reply_artificial_dtos[request_dto_name] = ({'docs': 'Dump reply wrapper generated from ' + str(func),
dump_reply_artificial_dtos[request_dto_name] = ({'docs': util.api_message_to_javadoc(func),
'cls_name': cls_name,
'fields': fields,
'methods': "",

File diff suppressed because it is too large Load Diff

View File

@ -22,6 +22,11 @@ import dto_gen
jvpp_ifc_template = Template("""
package $base_package.$callback_facade_package;
/**
* <p>Callback Java API representation of vpe.api.
* <br>It was generated by jvpp_callback_facade_gen.py based on $inputfile
* <br>(python representation of vpe.api generated by vppapigen).
*/
public interface CallbackJVpp extends java.lang.AutoCloseable {
@Override
@ -36,6 +41,11 @@ $methods
jvpp_impl_template = Template("""
package $base_package.$callback_facade_package;
/**
* <p>Default implementation of CallbackJVpp interface.
* <br>It was generated by jvpp_callback_facade_gen.py based on $inputfile
* <br>(python representation of vpe.api generated by vppapigen).
*/
public final class CallbackJVppFacade implements $base_package.$callback_facade_package.CallbackJVpp {
private final $base_package.JVpp jvpp;
@ -78,7 +88,7 @@ no_arg_method_impl_template = Template(""" public final void $name($base_pack
""")
def generate_jvpp(func_list, base_package, dto_package, callback_package, callback_facade_package):
def generate_jvpp(func_list, base_package, dto_package, callback_package, callback_facade_package, inputfile):
""" Generates callback facade """
print "Generating JVpp callback facade"
@ -131,7 +141,8 @@ def generate_jvpp(func_list, base_package, dto_package, callback_package, callba
join = os.path.join(callback_facade_package, "CallbackJVpp.java")
jvpp_file = open(join, 'w')
jvpp_file.write(
jvpp_ifc_template.substitute(methods="\n".join(methods),
jvpp_ifc_template.substitute(inputfile=inputfile,
methods="\n".join(methods),
base_package=base_package,
dto_package=dto_package,
callback_facade_package=callback_facade_package))
@ -139,7 +150,8 @@ def generate_jvpp(func_list, base_package, dto_package, callback_package, callba
jvpp_file.close()
jvpp_file = open(os.path.join(callback_facade_package, "CallbackJVppFacade.java"), 'w')
jvpp_file.write(jvpp_impl_template.substitute(methods="\n".join(methods_impl),
jvpp_file.write(jvpp_impl_template.substitute(inputfile=inputfile,
methods="\n".join(methods_impl),
base_package=base_package,
dto_package=dto_package,
callback_package=callback_package,
@ -147,14 +159,16 @@ def generate_jvpp(func_list, base_package, dto_package, callback_package, callba
jvpp_file.flush()
jvpp_file.close()
generate_callback(func_list, base_package, dto_package, callback_package, callback_facade_package)
generate_callback(func_list, base_package, dto_package, callback_package, callback_facade_package, inputfile)
jvpp_facade_callback_template = Template("""
package $base_package.$callback_facade_package;
/**
* Async facade callback setting values to future objects
* <p>JVppGlobalCallback implementation for Java Callback API.
* <br>It was generated by jvpp_callback_facade_gen.py based on $inputfile
* <br>(python representation of vpe.api generated by vppapigen).
*/
public final class CallbackJVppFacadeCallback implements $base_package.$callback_package.JVppGlobalCallback {
@ -185,7 +199,7 @@ jvpp_facade_callback_method_template = Template("""
""")
def generate_callback(func_list, base_package, dto_package, callback_package, callback_facade_package):
def generate_callback(func_list, base_package, dto_package, callback_package, callback_facade_package, inputfile):
callbacks = []
for func in func_list:
@ -204,7 +218,8 @@ def generate_callback(func_list, base_package, dto_package, callback_package, ca
callback_dto=camel_case_name_with_suffix))
jvpp_file = open(os.path.join(callback_facade_package, "CallbackJVppFacadeCallback.java"), 'w')
jvpp_file.write(jvpp_facade_callback_template.substitute(base_package=base_package,
jvpp_file.write(jvpp_facade_callback_template.substitute(inputfile=inputfile,
base_package=base_package,
dto_package=dto_package,
callback_package=callback_package,
methods="".join(callbacks),

View File

@ -22,7 +22,9 @@ jvpp_facade_callback_template = Template("""
package $base_package.$future_package;
/**
* Async facade callback setting values to future objects
* <p>Async facade callback setting values to future objects
* <br>It was generated by jvpp_future_facade_gen.py based on $inputfile
* <br>(python representation of vpe.api generated by vppapigen).
*/
public final class FutureJVppFacadeCallback implements $base_package.$callback_package.JVppGlobalCallback {
@ -119,7 +121,7 @@ jvpp_facade_details_callback_method_template = Template("""
""")
def generate_jvpp(func_list, base_package, dto_package, callback_package, future_facade_package):
def generate_jvpp(func_list, base_package, dto_package, callback_package, future_facade_package, inputfile):
""" Generates JVpp interface and JNI implementation """
print "Generating JVpp future facade"
@ -159,7 +161,8 @@ def generate_jvpp(func_list, base_package, dto_package, callback_package, future
callback_dto=camel_case_name_with_suffix))
jvpp_file = open(os.path.join(future_facade_package, "FutureJVppFacadeCallback.java"), 'w')
jvpp_file.write(jvpp_facade_callback_template.substitute(base_package=base_package,
jvpp_file.write(jvpp_facade_callback_template.substitute(inputfile=inputfile,
base_package=base_package,
dto_package=dto_package,
callback_package=callback_package,
methods="".join(callbacks),

131
vpp-api/java/jvpp/gen/jvpp_gen.py Executable file
View File

@ -0,0 +1,131 @@
#!/usr/bin/env python
#
# Copyright (c) 2016 Cisco and/or its affiliates.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at:
#
# http://www.apache.org/licenses/LICENSE-2.0
# l
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import argparse
import importlib
import sys
import callback_gen
import dto_gen
import jvpp_callback_facade_gen
import jvpp_future_facade_gen
import jvpp_impl_gen
import jvpp_c_gen
import util
# Invocation:
# ~/Projects/vpp/vpp-api/jvpp/gen$ mkdir -p java/org/openvpp/jvpp && cd java/org/openvpp/jvpp
# ~/Projects/vpp/vpp-api/jvpp/gen/java/org/openvpp/jvpp$ ../../../../jvpp_gen.py -idefs_api_vpp_papi.py
#
# Compilation:
# ~/Projects/vpp/vpp-api/jvpp/gen/java/org/openvpp/jvpp$ javac *.java dto/*.java callback/*.java
#
# where
# defs_api_vpp_papi.py - vpe.api in python format (generated by vppapigen)
from util import vpp_2_jni_type_mapping
parser = argparse.ArgumentParser(description='VPP Java API generator')
parser.add_argument('-i', action="store", dest="inputfile")
args = parser.parse_args()
sys.path.append(".")
inputfile = args.inputfile.replace('.py', '')
cfg = importlib.import_module(inputfile, package=None)
# FIXME: functions unsupported due to problems with vpe.api
def is_supported(f_name):
return f_name not in {'vnet_ip4_fib_counters', 'vnet_ip6_fib_counters'}
def is_request_field(field_name):
return field_name not in {'_vl_msg_id', 'client_index', 'context'}
def is_response_field(field_name):
return field_name not in {'_vl_msg_id'}
def get_args(t, filter):
arg_list = []
for i in t:
if not filter(i[1]):
continue
arg_list.append(i[1])
return arg_list
def get_types(t, filter):
types_list = []
c_types_list = []
for i in t:
if not filter(i[1]):
continue
if len(i) is 3: # array type
types_list.append(vpp_2_jni_type_mapping[i[0]] + 'Array')
c_types_list.append(i[0] + '[]')
else: # primitive type
types_list.append(vpp_2_jni_type_mapping[i[0]])
c_types_list.append(i[0])
return types_list, c_types_list
def get_definitions():
# Pass 1
func_list = []
func_name = {}
for a in cfg.vppapidef:
if not is_supported(a[0]):
continue
java_name = util.underscore_to_camelcase(a[0])
# For replies include all the arguments except message_id
if util.is_reply(java_name):
types, c_types = get_types(a[1:], is_response_field)
func_name[a[0]] = dict(
[('name', a[0]), ('java_name', java_name),
('args', get_args(a[1:], is_response_field)), ('full_args', get_args(a[1:], lambda x: True)),
('types', types), ('c_types', c_types)])
# For requests skip message_id, client_id and context
else:
types, c_types = get_types(a[1:], is_request_field)
func_name[a[0]] = dict(
[('name', a[0]), ('java_name', java_name),
('args', get_args(a[1:], is_request_field)), ('full_args', get_args(a[1:], lambda x: True)),
('types', types), ('c_types', c_types)])
# Indexed by name
func_list.append(func_name[a[0]])
return func_list, func_name
func_list, func_name = get_definitions()
base_package = 'org.openvpp.jvpp'
dto_package = 'dto'
callback_package = 'callback'
future_package = 'future'
# TODO find better package name
callback_facade_package = 'callfacade'
dto_gen.generate_dtos(func_list, base_package, dto_package, args.inputfile)
jvpp_impl_gen.generate_jvpp(func_list, base_package, dto_package, args.inputfile)
callback_gen.generate_callbacks(func_list, base_package, callback_package, dto_package, args.inputfile)
jvpp_c_gen.generate_jvpp(func_list, args.inputfile)
jvpp_future_facade_gen.generate_jvpp(func_list, base_package, dto_package, callback_package, future_package, args.inputfile)
jvpp_callback_facade_gen.generate_jvpp(func_list, base_package, dto_package, callback_package, callback_facade_package, args.inputfile)

View File

@ -19,6 +19,12 @@ from string import Template
jvpp_ifc_template = Template("""
package $base_package;
/**
* <p>Java representation of vpe.api.
* <br>It was generated by jvpp_impl_gen.py based on $inputfile
* <br>(python representation of vpe.api generated by vppapigen).
*/
public interface JVpp extends java.lang.AutoCloseable {
/**
@ -36,6 +42,11 @@ $methods
jvpp_impl_template = Template("""
package $base_package;
/**
* <p>Default implementation of JVpp interface.
* <br>It was generated by jvpp_impl_gen.py based on $inputfile
* <br>(python representation of vpe.api generated by vppapigen).
*/
public final class JVppImpl implements $base_package.JVpp {
private final $base_package.VppConnection connection;
@ -82,7 +93,7 @@ no_arg_method_impl_template = Template(""" public final int $name() {
""")
def generate_jvpp(func_list, base_package, dto_package):
def generate_jvpp(func_list, base_package, dto_package, inputfile):
""" Generates JVpp interface and JNI implementation """
print "Generating JVpp"
@ -126,14 +137,16 @@ def generate_jvpp(func_list, base_package, dto_package):
jvpp_file = open("JVpp.java", 'w')
jvpp_file.write(
jvpp_ifc_template.substitute(methods="\n".join(methods),
jvpp_ifc_template.substitute(inputfile=inputfile,
methods="\n".join(methods),
base_package=base_package,
dto_package=dto_package))
jvpp_file.flush()
jvpp_file.close()
jvpp_file = open("JVppImpl.java", 'w')
jvpp_file.write(jvpp_impl_template.substitute(methods="\n".join(methods_impl),
jvpp_file.write(jvpp_impl_template.substitute(inputfile=inputfile,
methods="\n".join(methods_impl),
base_package=base_package,
dto_package=dto_package))
jvpp_file.flush()

View File

@ -13,7 +13,7 @@
# See the License for the specific language governing permissions and
# limitations under the License.
import os
import os, pprint
from os import removedirs
@ -171,3 +171,8 @@ def remove_suffix(camel_case_name_with_suffix, suffix):
def is_control_ping(camel_case_name_with_suffix):
return "controlping" in camel_case_name_with_suffix.lower()
def api_message_to_javadoc(api_message):
""" Converts vpe.api message description to javadoc """
str = pprint.pformat(api_message, indent=4, width=120, depth=None)
return " * " + str.replace("\n", "\n * ")

275
vpp-api/java/jvpp/jvpp.c Normal file
View File

@ -0,0 +1,275 @@
/*
* Copyright (c) 2016 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#define _GNU_SOURCE /* for strcasestr(3) */
#include <vnet/vnet.h>
#define vl_api_version(n,v) static u32 vpe_api_version = (v);
#include <api/vpe.api.h>
#undef vl_api_version
#include <jni.h>
#include <jvpp/jvpp.h>
#include <jvpp/org_openvpp_jvpp_VppJNIConnection.h>
#include <jvpp/org_openvpp_jvpp_JVppImpl.h>
#include <api/vpe_msg_enum.h>
#define vl_typedefs /* define message structures */
#include <api/vpe_all_api_h.h>
#undef vl_typedefs
#define vl_endianfun
#include <api/vpe_all_api_h.h>
#undef vl_endianfun
/* instantiate all the print functions we know about */
#define vl_print(handle, ...)
#define vl_printfun
#include <api/vpe_all_api_h.h>
#undef vl_printfun
#define VPPJNI_DEBUG 0
#if VPPJNI_DEBUG == 1
#define DEBUG_LOG(...) clib_warning(__VA_ARGS__)
#else
#define DEBUG_LOG(...)
#endif
#include "gen/target/jvpp_gen.h"
static int connect_to_vpe(char *name);
/*
* The Java runtime isn't compile w/ -fstack-protector,
* so we have to supply missing external references for the
* regular vpp libraries. Weak reference in case folks get religion
* at a later date...
*/
void __stack_chk_guard (void) __attribute__((weak));
void __stack_chk_guard (void) { }
void vl_client_add_api_signatures (vl_api_memclnt_create_t *mp)
{
/*
* Send the main API signature in slot 0. This bit of code must
* match the checks in ../vpe/api/api.c: vl_msg_api_version_check().
*/
mp->api_versions[0] = clib_host_to_net_u32 (vpe_api_version);
}
/* cleanup handler for RX thread */
static void cleanup_rx_thread(void *arg)
{
vppjni_main_t * jm = &vppjni_main;
vppjni_lock (jm, 99);
int getEnvStat = (*jm->jvm)->GetEnv(jm->jvm, (void **)&(jm->jenv), JNI_VERSION_1_6);
if (getEnvStat == JNI_EVERSION) {
clib_warning ("Unsupported JNI version\n");
jm->retval = VNET_API_ERROR_UNSUPPORTED_JNI_VERSION;
goto out;
} else if (getEnvStat != JNI_EDETACHED) {
(*jm->jvm)->DetachCurrentThread(jm->jvm);
}
out:
vppjni_unlock (jm);
}
JNIEXPORT jint JNICALL Java_org_openvpp_jvpp_VppJNIConnection_clientConnect
(JNIEnv *env, jclass obj, jstring clientName, jobject callback)
{
int rv;
const char *client_name;
void vl_msg_reply_handler_hookup(void);
vppjni_main_t * jm = &vppjni_main;
/*
* Bail out now if we're not running as root
*/
if (geteuid() != 0)
return VNET_API_ERROR_NOT_RUNNING_AS_ROOT;
if (jm->is_connected)
return VNET_API_ERROR_ALREADY_CONNECTED;
client_name = (*env)->GetStringUTFChars(env, clientName, 0);
if (!client_name)
return VNET_API_ERROR_INVALID_VALUE;
rv = connect_to_vpe ((char *) client_name);
if (rv < 0)
clib_warning ("connection failed, rv %d", rv);
(*env)->ReleaseStringUTFChars (env, clientName, client_name);
if (rv == 0) {
f64 timeout;
clib_time_t clib_time;
clib_time_init (&clib_time);
/* vl_msg_reply_handler_hookup (); */
jm->is_connected = 1;
jm->callback = (*env)->NewGlobalRef(env, callback);
jm->callbackClass = (jclass)(*env)->NewGlobalRef(env, (*env)->GetObjectClass(env, callback));
{
// call control ping first to attach rx thread to java thread
vl_api_control_ping_t * mp;
M(CONTROL_PING, control_ping);
S;
// wait for results:
timeout = clib_time_now (&clib_time) + 1.0;
rv = VNET_API_ERROR_RESPONSE_NOT_READY;
while (clib_time_now (&clib_time) < timeout) {
if (jm->result_ready == 1) {
rv = (jm->retval);
break;
}
}
if (rv != 0) {
clib_warning ("first control ping failed: %d", rv);
}
}
}
DEBUG_LOG ("clientConnect result: %d", rv);
return rv;
}
JNIEXPORT void JNICALL Java_org_openvpp_jvpp_VppJNIConnection_clientDisconnect
(JNIEnv *env, jclass clazz)
{
vppjni_main_t * jm = &vppjni_main;
jm->is_connected = 0; // TODO make thread safe
vl_client_disconnect_from_vlib();
}
// control ping needs to be very first thing called
// to attach rx thread to java thread
static void vl_api_control_ping_reply_t_handler
(vl_api_control_ping_reply_t * mp)
{
vppjni_main_t * jm = &vppjni_main;
char was_thread_connected = 0;
// attach to java thread if not attached
int getEnvStat = (*jm->jvm)->GetEnv(jm->jvm, (void **)&(jm->jenv), JNI_VERSION_1_6);
if (getEnvStat == JNI_EDETACHED) {
if ((*jm->jvm)->AttachCurrentThread(jm->jvm, (void **)&(jm->jenv), NULL) != 0) {
clib_warning("Failed to attach thread\n");
jm->retval = VNET_API_ERROR_FAILED_TO_ATTACH_TO_JAVA_THREAD;
goto out;
}
// workaround as we can't use pthread_cleanup_push
pthread_key_create(&jm->cleanup_rx_thread_key, cleanup_rx_thread);
// destructor is only called if the value of key is non null
pthread_setspecific(jm->cleanup_rx_thread_key, (void *)1);
was_thread_connected = 1;
} else if (getEnvStat == JNI_EVERSION) {
clib_warning ("Unsupported JNI version\n");
jm->retval = VNET_API_ERROR_UNSUPPORTED_JNI_VERSION;
goto out;
}
if (was_thread_connected == 0) {
JNIEnv *env = jm->jenv;
jclass dtoClass = (*env)->FindClass(env, "org/openvpp/jvpp/dto/ControlPingReply");
jmethodID constructor = (*env)->GetMethodID(env, dtoClass, "<init>", "()V");
jmethodID callbackMethod = (*env)->GetMethodID(env, jm->callbackClass, "onControlPingReply", "(Lorg/openvpp/jvpp/dto/ControlPingReply;)V");
jobject dto = (*env)->NewObject(env, dtoClass, constructor);
printf("vl_api_control_ping_reply_t_handler ctx=%d\n", clib_net_to_host_u32(mp->context));
jfieldID contextFieldId = (*env)->GetFieldID(env, dtoClass, "context", "I");
(*env)->SetIntField(env, dto, contextFieldId, clib_net_to_host_u32(mp->context));
jfieldID retvalFieldId = (*env)->GetFieldID(env, dtoClass, "retval", "I");
(*env)->SetIntField(env, dto, retvalFieldId, clib_net_to_host_u32(mp->retval));
jfieldID clientIndexFieldId = (*env)->GetFieldID(env, dtoClass, "clientIndex", "I");
(*env)->SetIntField(env, dto, clientIndexFieldId, clib_net_to_host_u32(mp->client_index));
jfieldID vpePidFieldId = (*env)->GetFieldID(env, dtoClass, "vpePid", "I");
(*env)->SetIntField(env, dto, vpePidFieldId, clib_net_to_host_u32(mp->vpe_pid));
(*env)->CallVoidMethod(env, jm->callback, callbackMethod, dto);
}
out:
jm->result_ready = 1;
}
jint JNI_OnLoad(JavaVM *vm, void *reserved) {
vppjni_main_t * jm = &vppjni_main;
JNIEnv* env;
if ((*vm)->GetEnv(vm, (void**) &env, JNI_VERSION_1_6) != JNI_OK) {
return JNI_ERR;
}
jm->jvm = vm;
return JNI_VERSION_1_6;
}
void JNI_OnUnload(JavaVM *vm, void *reserved) {
vppjni_main_t * jm = &vppjni_main;
JNIEnv* env;
if ((*vm)->GetEnv(vm, (void**) &env, JNI_VERSION_1_6) != JNI_OK) {
return;
}
// cleanup:
(*env)->DeleteGlobalRef(env, jm->callbackClass);
(*env)->DeleteGlobalRef(env, jm->callback);
jm->callbackClass = NULL;
jm->callback = NULL;
jm->jenv = NULL;
jm->jvm = NULL;
}
static int connect_to_vpe(char *name)
{
vppjni_main_t * jm = &vppjni_main;
api_main_t * am = &api_main;
if (vl_client_connect_to_vlib("/vpe-api", name, 32) < 0)
return -1;
jm->my_client_index = am->my_client_index;
jm->vl_input_queue = am->shmem_hdr->vl_input_queue;
#define _(N,n) \
vl_msg_api_set_handlers(VL_API_##N, #n, \
vl_api_##n##_t_handler, \
vl_noop_handler, \
vl_api_##n##_t_endian, \
vl_api_##n##_t_print, \
sizeof(vl_api_##n##_t), 1);
foreach_vpe_api_msg;
#undef _
return 0;
}

112
vpp-api/java/jvpp/jvpp.h Normal file
View File

@ -0,0 +1,112 @@
/*
* Copyright (c) 2016 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef __included_vppjni_h__
#define __included_vppjni_h__
#include <vnet/vnet.h>
#include <vnet/ip/ip.h>
#include <vnet/api_errno.h>
#include <vlibapi/api.h>
#include <vlibmemory/api.h>
#include <jni.h>
typedef struct {
/* Unique identifier used for matching replays with requests */
volatile u32 context_id;
/* Spinlock */
volatile u32 lock;
u32 tag;
/* Used for first control ping */
// TODO better names?
volatile u32 result_ready;
volatile i32 retval;
/* JNI Native Method Interface pointer for message handlers */
JNIEnv *jenv;
/* thread cleanup */
pthread_key_t cleanup_rx_thread_key;
/* JNI Invoke Interface pointer for attachment of rx thread to java thread */
JavaVM *jvm;
/* Callback object and class references enabling asynchronous Java calls */
jobject callback;
jclass callbackClass;
/* Connected indication */
volatile u8 is_connected;
/* Convenience */
unix_shared_memory_queue_t * vl_input_queue;
u32 my_client_index;
} vppjni_main_t;
vppjni_main_t vppjni_main __attribute__((aligned (64)));
static inline u32 vppjni_get_context_id (vppjni_main_t * jm)
{
return __sync_add_and_fetch (&jm->context_id, 1);
}
static inline void vppjni_lock (vppjni_main_t * jm, u32 tag)
{
while (__sync_lock_test_and_set (&jm->lock, 1))
;
jm->tag = tag;
}
static inline void vppjni_unlock (vppjni_main_t * jm)
{
jm->tag = 0;
CLIB_MEMORY_BARRIER();
jm->lock = 0;
}
static inline int vppjni_sanity_check (vppjni_main_t * jm)
{
if (!jm->is_connected)
return VNET_API_ERROR_NOT_CONNECTED;
return 0;
}
// TODO remove macros (code is now fully autogenerated)
/* M: construct, but don't yet send a message */
#define M(T,t) \
do { \
jm->result_ready = 0; \
mp = vl_msg_api_alloc(sizeof(*mp)); \
memset (mp, 0, sizeof (*mp)); \
mp->_vl_msg_id = ntohs (VL_API_##T); \
mp->client_index = jm->my_client_index; \
} while(0);
#define M2(T,t,n) \
do { \
jm->result_ready = 0; \
mp = vl_msg_api_alloc(sizeof(*mp)+(n)); \
memset (mp, 0, sizeof (*mp)); \
mp->_vl_msg_id = ntohs (VL_API_##T); \
mp->client_index = jm->my_client_index; \
} while(0);
/* S: send a message */
#define S (vl_msg_api_send_shmem (jm->vl_input_queue, (u8 *)&mp))
#endif /* __included_vppjni_h__ */