Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ Java caller
→ returns C.Result (out/err/stdOut/stdErr) → JNA → Result → parsed into Release
```

Native library loading: `Helm` class holds `HelmLibHolder.INSTANCE`, initialized lazily by `NativeLibrary.getInstance().load()`. `getInstance()` uses Java `ServiceLoader` to discover the platform module on the classpath (each platform JAR has `META-INF/services/com.marcnuri.helm.jni.NativeLibrary`); if none found, falls back to `RemoteJarLoader` (downloads the correct platform JAR at runtime — works for Gradle, fails when air-gapped). `helm-java/pom.xml` has OS-activated profiles that pull in the right platform module automatically; both `amd64`/`x86_64` and `arm64`/`aarch64` aliases are handled.
Native library loading: `Helm` class holds `HelmLibHolder.INSTANCE`, initialized lazily by `NativeLibrary.getInstance().load()`. `getInstance()` uses Java `ServiceLoader` to discover the platform module on the classpath (each platform JAR has `META-INF/services/com.marcnuri.helm.jni.NativeLibrary`) and `NativeLibrarySelector` picks the first one whose `getOs()`/`getArch()` match the running JVM, else the first that declares neither (detection in `Platform`; providers declaring another platform are never picked; the `com.marcnuri.jkube-helm.nativeLibrary` system property forces one by class name, `com.marcnuri.jkube-helm.tempDir` sets the extraction dir); if none are registered, falls back to `RemoteJarLoader` (downloads the correct platform JAR at runtime — works for Gradle, fails when air-gapped). `helm-java/pom.xml` has OS-activated profiles that pull in the right platform module automatically; both `amd64`/`x86_64` and `arm64`/`aarch64` aliases are handled.

## Public API shape (Helm.java)

Expand Down
54 changes: 53 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ Add the dependency to your project:
<dependency>
<groupId>com.marcnuri.helm-java</groupId>
<artifactId>helm-java</artifactId>
<version>0.0.15</version>
<version>0.0.22</version>
</dependency>
```

Expand All @@ -28,6 +28,58 @@ public static void main(String... args) {

Check the features section for more examples and documentation.

### Native libraries

Helm runs in-process from a native library built for each platform, shipped in its own artifact:
`darwin-amd64`, `darwin-arm64`, `linux-amd64`, `linux-arm64`, and `windows-amd64`.

**How the platform artifact is chosen.**

- **Maven:** the `helm-java` artifact adds the native library artifact through profiles activated by the OS and architecture of the machine **running the build**.
An application built on Linux x86_64 gets `linux-amd64`, whatever host it runs on later.
- **Without a platform artifact** (e.g. Gradle, which doesn't activate Maven profiles): the matching artifact is downloaded from Maven Central the first time it's needed.
This doesn't work in air-gapped environments.

**Building for another platform.** When the build host and the target host differ (e.g. a container image for `linux/arm64` built on an x86_64 machine), exclude the platform artifacts and add the one for the target explicitly:

```xml
<dependency>
<groupId>com.marcnuri.helm-java</groupId>
<artifactId>helm-java</artifactId>
<version>0.0.22</version>
<exclusions>
<exclusion>
<groupId>com.marcnuri.helm-java</groupId>
<artifactId>*</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.marcnuri.helm-java</groupId>
<artifactId>lib-api</artifactId>
<version>0.0.22</version>
</dependency>
<dependency>
<groupId>com.marcnuri.helm-java</groupId>
<artifactId>linux-arm64</artifactId>
<version>0.0.22</version>
</dependency>
```

**Several platforms in one application (since 0.0.23).** You can ship more than one platform artifact. At runtime, the library is chosen in this order:

1. The first one whose declared OS and/or architecture match the current platform.
2. If there is none, the first one that declares no platform at all (custom implementations, or platform artifacts older than 0.0.23).

Libraries declaring another platform are never used. If libraries are on the classpath but none of them can be used, loading fails with an error listing them. In that case, no download from Maven Central is attempted.

**System properties (since 0.0.23).** These customize how the native library is loaded:

| Property | Description |
|-----------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| `com.marcnuri.jkube-helm.tempDir` | Base directory where the native library is extracted before loading it (defaults to `java.io.tmpdir`). It's created if missing, and each JVM extracts into its own `helm-java*` subdirectory inside it. Set it to an executable location if `/tmp` is mounted with `noexec`. |
| `com.marcnuri.jkube-helm.nativeLibrary` | Fully qualified class name of the `com.marcnuri.helm.jni.NativeLibrary` implementation to use, regardless of the detected platform. The class must be registered in a `META-INF/services/com.marcnuri.helm.jni.NativeLibrary` file on the classpath, like the ones in the platform artifacts. |

## Features

### Create
Expand Down
17 changes: 17 additions & 0 deletions helm-java/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -165,6 +165,23 @@
</dependency>
</dependencies>
</profile>
<profile>
<id>linux-aarch64</id>
<activation>
<!-- Linux JVMs report aarch64; the name keeps Apple Silicon macOS (also family unix) out of this profile -->
<os>
<family>unix</family>
<name>linux</name>
<arch>aarch64</arch>
</os>
</activation>
<dependencies>
<dependency>
<groupId>${project.groupId}</groupId>
<artifactId>linux-arm64</artifactId>
</dependency>
</dependencies>
</profile>
<profile>
<id>windows-amd64</id>
<activation>
Expand Down
10 changes: 10 additions & 0 deletions lib/api/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,16 @@
<groupId>net.java.dev.jna</groupId>
<artifactId>jna-platform-jpms</artifactId>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<scope>test</scope>
</dependency>
</dependencies>

<build>
Expand Down
76 changes: 67 additions & 9 deletions lib/api/src/main/java/com/marcnuri/helm/jni/NativeLibrary.java
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,9 @@
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.InvalidPathException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.Objects;
import java.util.ServiceLoader;
Expand All @@ -47,17 +49,48 @@ static NativeLibrary getInstance() {
throw new IllegalStateException("No NativeLibrary implementation found, please add one of the supported dependencies to your project");
}

/**
* Returns the registered {@link NativeLibrary} implementation for the current platform.
*
* <p>The first implementation whose declared {@link #getOs()} and {@link #getArch()} match the running JVM is
* preferred. If there is none, the first implementation that declares neither is used. Implementations declaring
* another platform are never selected.
* The {@code com.marcnuri.jkube-helm.nativeLibrary} system property can be set to the fully qualified class name
* of a registered implementation to use that one instead.
*
* @param classLoader the class loader to look up the implementations with, or {@code null} for the context class loader.
* @return the selected implementation, or {@code null} if no implementations are registered.
* @throws IllegalStateException if implementations are registered, but none can be selected.
*/
static NativeLibrary serviceProviderLibrary(ClassLoader classLoader) {
for (NativeLibrary nativeLibrary : ServiceLoader.load(
NativeLibrary.class, classLoader == null ? Thread.currentThread().getContextClassLoader() : classLoader)
) {
return nativeLibrary;
}
return null;
return NativeLibrarySelector.select(
ServiceLoader.load(NativeLibrary.class, classLoader == null ? Thread.currentThread().getContextClassLoader() : classLoader),
System.getProperty(NativeLibrarySelector.NATIVE_LIBRARY),
System.getProperty("os.name"),
System.getProperty("os.arch")
);
}

String getBinaryName();

/**
* The operating system the native binary is built for ({@code darwin}, {@code linux}, {@code windows}).
*
* @return the operating system, or {@code null} if the binary can be loaded on any operating system.
*/
default String getOs() {
return null;
}

/**
* The architecture the native binary is built for ({@code amd64}, {@code arm64}).
*
* @return the architecture, or {@code null} if the binary can be loaded on any architecture.
*/
default String getArch() {
return null;
}

default HelmLib load() {
final Path temp = createTempDirectory();
final Path tempBinary = temp.resolve(getBinaryName());
Expand All @@ -73,13 +106,38 @@ default HelmLib load() {
}
}

/**
* Creates the directory where the native binary is extracted.
*
* <p>The directory is created under the {@code com.marcnuri.jkube-helm.tempDir} system property if set
* (creating it if missing), or under {@code java.io.tmpdir} otherwise.
*
* @return the created directory.
*/
default Path createTempDirectory() {
final String baseDir = System.getProperty(NativeLibrarySelector.TEMP_DIR);
if (baseDir == null || baseDir.trim().isEmpty()) {
try {
final Path temp = Files.createTempDirectory("helm-java");
temp.toFile().deleteOnExit();
return temp;
} catch (IOException exception) {
throw new IllegalStateException("Unable to create temporary directory", exception);
}
}
try {
final Path temp = Files.createTempDirectory("helm-java");
final Path base = Paths.get(baseDir);
// On Java 8, Files.createDirectories throws FileAlreadyExistsException for an existing symbolic link to a
// directory (e.g. /tmp on macOS); newer JDKs accept it, so keep this check while Java 8 is supported
if (!Files.isDirectory(base)) {
Files.createDirectories(base);
}
final Path temp = Files.createTempDirectory(base, "helm-java");
temp.toFile().deleteOnExit();
return temp;
} catch (IOException exception) {
throw new IllegalStateException("Unable to create temporary directory", exception);
} catch (IOException | InvalidPathException exception) {
throw new IllegalStateException("Unable to create temporary directory in " + baseDir +
" (set with the " + NativeLibrarySelector.TEMP_DIR + " system property)", exception);
}
}

Expand Down
115 changes: 115 additions & 0 deletions lib/api/src/main/java/com/marcnuri/helm/jni/NativeLibrarySelector.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
/*
* Copyright 2024 Marc Nuri
*
* 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.
*/

package com.marcnuri.helm.jni;

import java.util.ArrayList;
import java.util.List;

/**
* Chooses which of the available {@link NativeLibrary} implementations to load.
*
* @author Marc Nuri
*/
final class NativeLibrarySelector {

/**
* System property to force a specific {@link NativeLibrary} implementation (fully qualified class name).
*/
static final String NATIVE_LIBRARY = "com.marcnuri.jkube-helm.nativeLibrary";
/**
* System property to set the base directory where the native library is extracted (defaults to {@code java.io.tmpdir}).
*/
static final String TEMP_DIR = "com.marcnuri.jkube-helm.tempDir";

private NativeLibrarySelector() {
}

/**
* Selects the {@link NativeLibrary} to use from the provided implementations.
*
* <p>If {@code forcedNativeLibrary} is set (not blank), the implementation with that class name is returned,
* regardless of its platform. Otherwise, implementations are chosen in this order of preference:
* <ol>
* <li>The first implementation that declares an OS and/or architecture, all of them matching the provided
* {@code os.name} and {@code os.arch}.</li>
* <li>The first implementation that declares neither an OS nor an architecture (e.g. third-party
* implementations or platform modules prior to this change), which is assumed compatible with any platform.</li>
* </ol>
*
* @return the selected implementation, or {@code null} if there are no implementations at all.
* @throws IllegalStateException if there are implementations, but none of them can be selected.
*/
static NativeLibrary select(
Iterable<NativeLibrary> nativeLibraries, String forcedNativeLibrary, String osNameProperty, String osArchProperty) {
final String forced = forcedNativeLibrary == null || forcedNativeLibrary.trim().isEmpty() ?
null : forcedNativeLibrary.trim();
final String os = Platform.osName(osNameProperty);
final String arch = Platform.archName(osArchProperty);
final List<NativeLibrary> available = new ArrayList<>();
NativeLibrary firstUndeclared = null;
for (NativeLibrary nativeLibrary : nativeLibraries) {
if (forced != null) {
if (nativeLibrary.getClass().getName().equals(forced)) {
return nativeLibrary;
}
} else if (isUndeclared(nativeLibrary)) {
if (firstUndeclared == null) {
firstUndeclared = nativeLibrary;
}
} else if (matches(nativeLibrary, os, arch)) {
return nativeLibrary;
}
available.add(nativeLibrary);
}
if (firstUndeclared != null) {
return firstUndeclared;
}
if (available.isEmpty()) {
return null;
}
if (forced != null) {
throw new IllegalStateException("NativeLibrary implementation " + forced +
" (set with the " + NATIVE_LIBRARY + " system property) not found, available implementations: " +
describe(available));
}
throw new IllegalStateException("No NativeLibrary implementation found for the current platform (os.name=" +
osNameProperty + ", os.arch=" + osArchProperty + "), available implementations: " + describe(available) +
". Please add the dependency for your platform to your project");
}

private static boolean isUndeclared(NativeLibrary nativeLibrary) {
return nativeLibrary.getOs() == null && nativeLibrary.getArch() == null;
}

private static boolean matches(NativeLibrary nativeLibrary, String os, String arch) {
return (nativeLibrary.getOs() == null || nativeLibrary.getOs().equals(os)) &&
(nativeLibrary.getArch() == null || nativeLibrary.getArch().equals(arch));
}

private static String describe(List<NativeLibrary> nativeLibraries) {
final StringBuilder sb = new StringBuilder("[");
for (int i = 0; i < nativeLibraries.size(); i++) {
final NativeLibrary nativeLibrary = nativeLibraries.get(i);
if (i > 0) {
sb.append(", ");
}
sb.append(nativeLibrary.getClass().getName())
.append(" (").append(nativeLibrary.getOs()).append('/').append(nativeLibrary.getArch()).append(')');
}
return sb.append(']').toString();
}
}
Loading
Loading