Skip to content

Commit

Permalink
Java build system enhancements (microsoft#2866)
Browse files Browse the repository at this point in the history
  • Loading branch information
yuzawa-san authored Feb 18, 2020
1 parent ecdcd68 commit 411b3aa
Show file tree
Hide file tree
Showing 14 changed files with 412 additions and 298 deletions.
4 changes: 3 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,8 @@ onnxprofile_profile_test_*.json
/csharp/src/Microsoft.ML.OnnxRuntime/Microsoft.ML.OnnxRuntime.props
cmake/external/FeaturizersLibrary/
# Java specific ignores
java/src/main/native/ai_onnxruntime_*.h
java/gradlew
java/gradlew.bat
java/gradle
java/.gradle

126 changes: 44 additions & 82 deletions cmake/onnxruntime_java.cmake
Original file line number Diff line number Diff line change
Expand Up @@ -12,99 +12,61 @@ include_directories(${JNI_INCLUDE_DIRS})
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -std=c11")

set(JAVA_ROOT ${REPO_ROOT}/java)
set(CMAKE_JAVA_COMPILE_FLAGS "-source" "1.8" "-target" "1.8" "-encoding" "UTF-8")
set(JAVA_OUTPUT_DIR ${CMAKE_CURRENT_BINARY_DIR}/java)
if (onnxruntime_RUN_ONNX_TESTS)
set(JAVA_DEPENDS onnxruntime ${test_data_target})
else()
set(JAVA_DEPENDS onnxruntime)
endif()

# Specify the Java source files
set(onnxruntime4j_src
${REPO_ROOT}/java/src/main/java/ai/onnxruntime/MapInfo.java
${REPO_ROOT}/java/src/main/java/ai/onnxruntime/NodeInfo.java
${REPO_ROOT}/java/src/main/java/ai/onnxruntime/OnnxRuntime.java
${REPO_ROOT}/java/src/main/java/ai/onnxruntime/OnnxJavaType.java
${REPO_ROOT}/java/src/main/java/ai/onnxruntime/OnnxMap.java
${REPO_ROOT}/java/src/main/java/ai/onnxruntime/OnnxSequence.java
${REPO_ROOT}/java/src/main/java/ai/onnxruntime/OnnxTensor.java
${REPO_ROOT}/java/src/main/java/ai/onnxruntime/OnnxValue.java
${REPO_ROOT}/java/src/main/java/ai/onnxruntime/OrtAllocator.java
${REPO_ROOT}/java/src/main/java/ai/onnxruntime/OrtEnvironment.java
${REPO_ROOT}/java/src/main/java/ai/onnxruntime/OrtException.java
${REPO_ROOT}/java/src/main/java/ai/onnxruntime/OrtSession.java
${REPO_ROOT}/java/src/main/java/ai/onnxruntime/OrtUtil.java
${REPO_ROOT}/java/src/main/java/ai/onnxruntime/package-info.java
${REPO_ROOT}/java/src/main/java/ai/onnxruntime/SequenceInfo.java
${REPO_ROOT}/java/src/main/java/ai/onnxruntime/TensorInfo.java
${REPO_ROOT}/java/src/main/java/ai/onnxruntime/ValueInfo.java
)
# use the gradle wrapper if it exists
if(EXISTS "${JAVA_ROOT}/gradlew")
set(GRADLE_EXECUTABLE "${JAVA_ROOT}/gradlew")
else()
# fall back to gradle on our PATH
find_program(GRADLE_EXECUTABLE gradle)
if(NOT GRADLE_EXECUTABLE)
message(SEND_ERROR "Gradle installation not found")
endif()
endif()
message(STATUS "Using gradle: ${GRADLE_EXECUTABLE}")

# Build the jar and generate the native headers
add_jar(onnxruntime4j SOURCES ${onnxruntime4j_src} VERSION ${ORT_VERSION} GENERATE_NATIVE_HEADERS onnxruntime4j_generated DESTINATION ${REPO_ROOT}/java/src/main/native/)
# Specify the Java source files
file(GLOB_RECURSE onnxruntime4j_gradle_files "${JAVA_ROOT}/*.gradle")
file(GLOB_RECURSE onnxruntime4j_src "${JAVA_ROOT}/src/main/java/ai/onnxruntime/*.java")
set(JAVA_OUTPUT_JAR ${JAVA_ROOT}/build/libs/onnxruntime.jar)
# this jar is solely used to signalling mechanism for dependency management in CMake
# if any of the Java sources change, the jar (and generated headers) will be regenerated and the onnxruntime4j_jni target will be rebuilt
add_custom_command(OUTPUT ${JAVA_OUTPUT_JAR} COMMAND ${GRADLE_EXECUTABLE} clean jar WORKING_DIRECTORY ${JAVA_ROOT} DEPENDS ${onnxruntime4j_gradle_files} ${onnxruntime4j_src})
add_custom_target(onnxruntime4j DEPENDS ${JAVA_OUTPUT_JAR})
set_source_files_properties(${JAVA_OUTPUT_JAR} PROPERTIES GENERATED TRUE)
set_property(TARGET onnxruntime4j APPEND PROPERTY ADDITIONAL_CLEAN_FILES "${JAVA_OUTPUT_DIR}")

# Specify the native sources (without the generated headers)
# Specify the native sources
file(GLOB onnxruntime4j_native_src
"${REPO_ROOT}/java/src/main/native/*.c"
"${REPO_ROOT}/java/src/main/native/OrtJniUtil.h"
"${JAVA_ROOT}/src/main/native/*.c"
"${JAVA_ROOT}/src/main/native/*.h"
"${REPO_ROOT}/include/onnxruntime/core/session/*.h"
)

# Build the JNI library
add_library(onnxruntime4j_jni SHARED ${onnxruntime4j_native_src} ${onnxruntime4j_generated})
add_library(onnxruntime4j_jni SHARED ${onnxruntime4j_native_src})
# depend on java sources. if they change, the JNI should recompile
add_dependencies(onnxruntime4j_jni onnxruntime4j)
onnxruntime_add_include_to_target(onnxruntime4j_jni onnxruntime_session)
target_include_directories(onnxruntime4j_jni PRIVATE ${REPO_ROOT}/include ${REPO_ROOT}/java/src/main/native)
target_link_libraries(onnxruntime4j_jni PUBLIC onnxruntime onnxruntime4j_generated)

# Now the jar, jni binary and shared lib binary have been built, now to build the jar with the binaries added.

# This blob creates the new jar name
get_property(onnxruntime_jar_name TARGET onnxruntime4j PROPERTY JAR_FILE)
get_filename_component(onnxruntime_jar_abs ${onnxruntime_jar_name} ABSOLUTE)
get_filename_component(jar_path ${onnxruntime_jar_abs} DIRECTORY)
set(onnxruntime_jar_binaries_name "${jar_path}/onnxruntime4j-${ORT_VERSION}-with-binaries.jar")
set(onnxruntime_jar_binaries_platform "$<SHELL_PATH:${onnxruntime_jar_binaries_name}>")

# Copy the current jar
add_custom_command(TARGET onnxruntime4j_jni PRE_BUILD
COMMAND ${CMAKE_COMMAND} -E copy
${onnxruntime_jar_name}
${onnxruntime_jar_binaries_platform})

# Make a temp directory to store the binaries
add_custom_command(TARGET onnxruntime4j_jni POST_BUILD
COMMAND ${CMAKE_COMMAND} -E make_directory "${CMAKE_CURRENT_BINARY_DIR}/java-libs/lib")

# Copy the binaries
add_custom_command(TARGET onnxruntime4j_jni POST_BUILD COMMAND ${CMAKE_COMMAND} -E copy "$<TARGET_FILE:onnxruntime4j_jni>" ${CMAKE_CURRENT_BINARY_DIR}/java-libs/lib/)

if (WIN32)
add_custom_command(TARGET onnxruntime4j_jni POST_BUILD COMMAND ${CMAKE_COMMAND} -E copy "$<TARGET_FILE:onnxruntime>" ${CMAKE_CURRENT_BINARY_DIR}/java-libs/lib/)
# Update the with-binaries jar so it includes the binaries
add_custom_command(
TARGET onnxruntime4j_jni POST_BUILD
COMMAND ${Java_JAR_EXECUTABLE} -uf ${onnxruntime_jar_binaries_platform} -C ${CMAKE_CURRENT_BINARY_DIR}/java-libs lib/$<TARGET_FILE_NAME:onnxruntime4j_jni> -C ${CMAKE_CURRENT_BINARY_DIR}/java-libs lib/$<TARGET_FILE_NAME:onnxruntime>
DEPENDS onnxruntime4j
COMMENT "Rebuilding Java archive ${_JAVA_TARGET_OUTPUT_NAME}"
VERBATIM
)
else ()
add_custom_command(TARGET onnxruntime4j_jni POST_BUILD COMMAND ${CMAKE_COMMAND} -E copy "$<TARGET_LINKER_FILE:onnxruntime>" ${CMAKE_CURRENT_BINARY_DIR}/java-libs/lib/)
# Update the with-binaries jar so it includes the binaries
add_custom_command(
TARGET onnxruntime4j_jni POST_BUILD
COMMAND ${Java_JAR_EXECUTABLE} -uf ${onnxruntime_jar_binaries_platform} -C ${CMAKE_CURRENT_BINARY_DIR}/java-libs lib/$<TARGET_FILE_NAME:onnxruntime4j_jni> -C ${CMAKE_CURRENT_BINARY_DIR}/java-libs lib/$<TARGET_LINKER_FILE_NAME:onnxruntime>
DEPENDS onnxruntime4j
COMMENT "Rebuilding Java archive ${_JAVA_TARGET_OUTPUT_NAME}"
VERBATIM
)
endif()
# the JNI headers are generated in the onnxruntime4j target
target_include_directories(onnxruntime4j_jni PRIVATE ${REPO_ROOT}/include ${JAVA_ROOT}/build/headers)
target_link_libraries(onnxruntime4j_jni PUBLIC onnxruntime)

create_javadoc(onnxruntime4j_javadoc
FILES ${onnxruntime4j_src}
DOCTITLE "Onnx Runtime Java API"
WINDOWTITLE "OnnxRuntime-Java-API"
AUTHOR FALSE
USE TRUE
VERSION FALSE
)
# expose native libraries to the gradle build process
file(MAKE_DIRECTORY ${JAVA_OUTPUT_DIR}/build)
set(JAVA_PACKAGE_DIR ai/onnxruntime/native/)
set(JAVA_NATIVE_LIB_DIR ${JAVA_OUTPUT_DIR}/native-lib)
set(JAVA_NATIVE_JNI_DIR ${JAVA_OUTPUT_DIR}/native-jni)
set(JAVA_PACKAGE_LIB_DIR ${JAVA_NATIVE_LIB_DIR}/${JAVA_PACKAGE_DIR})
set(JAVA_PACKAGE_JNI_DIR ${JAVA_NATIVE_JNI_DIR}/${JAVA_PACKAGE_DIR})
file(MAKE_DIRECTORY ${JAVA_PACKAGE_LIB_DIR})
file(MAKE_DIRECTORY ${JAVA_PACKAGE_JNI_DIR})
add_custom_command(TARGET onnxruntime4j_jni POST_BUILD COMMAND ${CMAKE_COMMAND} -E create_symlink $<TARGET_FILE:onnxruntime> ${JAVA_PACKAGE_LIB_DIR}/$<TARGET_LINKER_FILE_NAME:onnxruntime>)
add_custom_command(TARGET onnxruntime4j_jni POST_BUILD COMMAND ${CMAKE_COMMAND} -E create_symlink $<TARGET_FILE:onnxruntime4j_jni> ${JAVA_PACKAGE_JNI_DIR}/$<TARGET_LINKER_FILE_NAME:onnxruntime4j_jni>)
# run the build process (this copies the results back into CMAKE_CURRENT_BINARY_DIR)
add_custom_command(TARGET onnxruntime4j_jni POST_BUILD COMMAND ${GRADLE_EXECUTABLE} cmakeBuild -DcmakeBuildDir=${CMAKE_CURRENT_BINARY_DIR} WORKING_DIRECTORY ${JAVA_ROOT})
34 changes: 3 additions & 31 deletions cmake/onnxruntime_unittests.cmake
Original file line number Diff line number Diff line change
Expand Up @@ -691,35 +691,7 @@ set_property(TARGET custom_op_library APPEND_STRING PROPERTY LINK_FLAGS ${ONNXRU

if (onnxruntime_BUILD_JAVA)
message(STATUS "Running Java tests")
# Build and run tests
set(onnxruntime4j_test_src
${REPO_ROOT}/java/src/test/java/ai/onnxruntime/InferenceTest.java
${REPO_ROOT}/java/src/test/java/ai/onnxruntime/TestHelpers.java
${REPO_ROOT}/java/src/test/java/ai/onnxruntime/OnnxMl.java
${REPO_ROOT}/java/src/test/java/ai/onnxruntime/UtilTest.java
)

# Create test directories
file(MAKE_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/java-tests/")
file(MAKE_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/java-tests/results")

# Download test dependencies
if (NOT EXISTS ${CMAKE_CURRENT_BINARY_DIR}/java-tests/junit-platform-console-standalone-1.5.2.jar)
message("Downloading JUnit 5")
file(DOWNLOAD https://repo1.maven.org/maven2/org/junit/platform/junit-platform-console-standalone/1.5.2/junit-platform-console-standalone-1.5.2.jar ${CMAKE_CURRENT_BINARY_DIR}/java-tests/junit-platform-console-standalone-1.5.2.jar EXPECTED_HASH SHA1=8d937d2b461018a876836362b256629f4da5feb1)
endif()

if (NOT EXISTS ${CMAKE_CURRENT_BINARY_DIR}/java-tests/protobuf-java-3.10.0.jar)
message("Downloading protobuf-java 3.10.0")
file(DOWNLOAD https://repo1.maven.org/maven2/com/google/protobuf/protobuf-java/3.10.0/protobuf-java-3.10.0.jar ${CMAKE_CURRENT_BINARY_DIR}/java-tests/protobuf-java-3.10.0.jar EXPECTED_HASH SHA1=410b61dd0088aab4caa05739558d43df248958c9)
endif()

# Build the test jar
add_jar(onnxruntime4j_test SOURCES ${onnxruntime4j_test_src} VERSION ${ORT_VERSION} INCLUDE_JARS ${onnxruntime_jar_name} ${CMAKE_CURRENT_BINARY_DIR}/java-tests/junit-platform-console-standalone-1.5.2.jar ${CMAKE_CURRENT_BINARY_DIR}/java-tests/protobuf-java-3.10.0.jar)

add_dependencies(onnxruntime4j_test onnxruntime4j_jni onnxruntime4j)
get_property(onnxruntime_test_jar_name TARGET onnxruntime4j_test PROPERTY JAR_FILE)

# Run the tests with JUnit's console launcher
add_test(NAME java-api COMMAND ${Java_JAVA_EXECUTABLE} -jar ${CMAKE_CURRENT_BINARY_DIR}/java-tests/junit-platform-console-standalone-1.5.2.jar -cp ${CMAKE_CURRENT_BINARY_DIR}/java-tests/protobuf-java-3.10.0.jar -cp ${onnxruntime_test_jar_name} -cp ${onnxruntime_jar_binaries_platform} --scan-class-path --fail-if-no-tests --reports-dir=${CMAKE_CURRENT_BINARY_DIR}/java-tests/results --disable-banner WORKING_DIRECTORY ${REPO_ROOT})
# delegate to gradle's test runner
add_test(NAME onnxruntime4j_test COMMAND ${GRADLE_EXECUTABLE} cmakeCheck -DcmakeBuildDir=${CMAKE_CURRENT_BINARY_DIR} WORKING_DIRECTORY ${REPO_ROOT}/java)
set_property(TEST onnxruntime4j_test APPEND PROPERTY DEPENDS onnxruntime4j_jni)
endif()
80 changes: 80 additions & 0 deletions java/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
# ONNX Runtime Java API

This directory contains the Java language binding for the ONNX runtime.
Java Native Interface (JNI) is used to allow for seamless calls to ONNX runtime from Java.

## Usage

TBD: maven distribution

The minimum supported Java Runtime is version 8.

An example implementation is located in [src/test/java/sample/ScoreMNIST.java](src/test/java/sample/ScoreMNIST.java)

This project can be built manually using the instructions below.

### Building

Use the main project's [build instructions](../BUILD.md) with the `--build_java` option.

#### Requirements

JDK version 8 or later is required.
The [Gradle](https://gradle.org/) build system is required and used here to manage the Java project's dependency management, compilation, testing, and assembly.
You may use your system Gradle installation installed on your PATH.
Version 6 or newer is recommended.
Optionally, you may use your own Gradle [wrapper](https://docs.gradle.org/current/userguide/gradle_wrapper.html) which will be locked to a version specified in the `build.gradle` configuration.
This can be done once by using system Gradle installation to invoke the wrapper task in the java project's directory: `cd REPO_ROOT/java && gradle wrapper`
Any installed wrapper is gitignored.

#### Build Output

The build will generate output in `$REPO_ROOT/build/$OS/$CONFIGURATION/java/build`:

* `docs/javadoc/` - HTML javadoc
* `reports/` - detailed test results and other reports
* `libs/onnxruntime.jar` - JAR with classes, depends on `onnxruntime-jni.jar` and `onnxruntime-lib.jar `
* `libs/onnxruntime-jni.jar`- JAR with JNI shared library
* `libs/onnxruntime-lib.jar` - JAR with onnxruntime shared library
* `libs/onnxruntime-all.jar` - the 3 preceding jars all combined: JAR with classes, JNI shared library, and onnxruntime shared library

The reason the shared libraries are split out like that is that users can mix and match to suit their use case:

* To support a single OS/Architecture without any dependencies, use `libs/onnxruntime-all.jar`.
* To support cross-platform: bundle a single `libs/onnxruntime.jar` and with all of the respective `libs/onnxruntime-jni.jar` and `libs/onnxruntime-lib.jar` for all of the desired OS/Architectures.
* To support use case where an onnxruntime shared library will reside in the system's library search path: bundle a single `libs/onnxruntime.jar` and with all of the `libs/onnxruntime-jni.jar`. The onnxruntime shared library should be loaded using one of the other methods described in the "Advanced Loading" section below.

#### Build System Overview

The main CMake build system delegates building and testing to Gradle.
This allows the CMake system to ensure all of the C/C++ compilation is achieved prior to the Java build.
The Java build depends on C/C++ onnxruntime shared library and a C JNI shared library (source located in the `src/main/native` directory).
The JNI shared library is the glue that allows for Java to call functions in onnxruntime shared library.
Given the fact that CMake injects native dependencies during CMake builds, some gradle tasks (primarily, `build`, `test`, and `check`) may fail.

When running the build script, CMake will compile the `onnxruntime` target and the JNI glue `onnxruntime4j_jni` target and expose the resulting libraries in a place where Gradle can ingest them.
Upon successful compilation of those targets, a special Gradle task to build will be executed. The results will be placed in the output directory stated above.

### Advanced Loading

The default behavior is to load the shared libraries using classpath resources.
If your use case requires custom loading of the shared libraries, please consult the javadoc in the [package-info.java](src/main/java/ai/onnxruntime/package-info.java) or [OnnxRuntime.java](src/main/java/ai/onnxruntime/OnnxRuntime.java) files.

## Development

### Code Formatting

[Spotless](https://github.com/diffplug/spotless/tree/master/plugin-gradle) is used to keep the code properly formatted.
Gradle's `spotlessCheck` task will show any misformatted code.
Gradle's `spotlessApply` task will try to fix the formatting.
Misformatted code will raise failures when checks are ran during test run.

### JNI Headers

When adding or updating native methods in the Java files, it may be necessary to examine the relevant JNI headers in `build/headers/ai_onnxruntime*.h`.
These files can be manually generated using Gradle's `compileJava` task which will compile the Java and update the header files accordingly.
Then the corresponding C files in `./src/main/native/ai_onnxruntime*.c` may be updated and the build can be ran.

### Dependencies

The Java API does not have any runtime or compile dependencies currently.
117 changes: 117 additions & 0 deletions java/build.gradle
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
plugins {
id 'java'
id 'com.diffplug.gradle.spotless' version '3.26.0'
}

allprojects {
repositories {
mavenCentral()
}
}

java {
sourceCompatibility = JavaVersion.VERSION_1_8
targetCompatibility = JavaVersion.VERSION_1_8
withJavadocJar()
withSourcesJar()
}

wrapper {
gradleVersion = '6.1.1'
}

spotless {
//java {
// removeUnusedImports()
// googleJavaFormat()
//}
format 'gradle', {
target '**/*.gradle'
trimTrailingWhitespace()
indentWithTabs()
}
}

// cmake runs will inform us of the build directory of the current run
def cmakeBuildDir = System.properties['cmakeBuildDir']
def cmakeJavaDir = "${cmakeBuildDir}/java"
def cmakeNativeLibDir = "${cmakeJavaDir}/native-lib"
def cmakeNativeJniDir = "${cmakeJavaDir}/native-jni"
def cmakeBuildOutputDir = "${cmakeJavaDir}/build"

compileJava {
options.compilerArgs += ["-h", "${project.buildDir}/headers/"]
}

sourceSets.test {
// add test resource files
resources.srcDirs += [
"${rootProject.projectDir}/../csharp/testdata",
"${rootProject.projectDir}/../onnxruntime/test/testdata"
]
if (cmakeBuildDir != null) {
// add compiled native libs
resources.srcDirs += [
cmakeNativeLibDir,
cmakeNativeJniDir
]
}
}

if (cmakeBuildDir != null) {
// generate tasks to be called from cmake

task jniJar(type: Jar) {
classifier = 'jni'
from cmakeNativeJniDir
}

task libJar(type: Jar) {
classifier = 'lib'
from cmakeNativeLibDir
}

task allJar(type: Jar) {
classifier = 'all'
from sourceSets.main.output
from cmakeNativeJniDir
from cmakeNativeLibDir
}

task cmakeBuild(type: Copy) {
from project.buildDir
include 'libs/**'
include 'docs/**'
into cmakeBuildOutputDir
}
cmakeBuild.dependsOn jar
cmakeBuild.dependsOn jniJar
cmakeBuild.dependsOn libJar
cmakeBuild.dependsOn allJar
cmakeBuild.dependsOn sourcesJar
cmakeBuild.dependsOn javadocJar
cmakeBuild.dependsOn javadoc


task cmakeCheck(type: Copy) {
from project.buildDir
include 'reports/**'
into cmakeBuildOutputDir
}
cmakeCheck.dependsOn check

}


dependencies {
testImplementation 'org.junit.jupiter:junit-jupiter-api:5.1.1'
testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.1.1'
testImplementation 'com.google.protobuf:protobuf-java:3.10.0'
}

test {
useJUnitPlatform()
testLogging {
events "passed", "skipped", "failed"
}
}
1 change: 1 addition & 0 deletions java/settings.gradle
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
rootProject.name = 'onnxruntime'
Loading

0 comments on commit 411b3aa

Please sign in to comment.