diff --git a/AGENTS.md b/AGENTS.md index 2bbd8f89..6bfcaf28 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -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) diff --git a/README.md b/README.md index 24c83467..478e8b82 100644 --- a/README.md +++ b/README.md @@ -14,7 +14,7 @@ Add the dependency to your project: com.marcnuri.helm-java helm-java - 0.0.15 + 0.0.22 ``` @@ -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 + + com.marcnuri.helm-java + helm-java + 0.0.22 + + + com.marcnuri.helm-java + * + + + + + com.marcnuri.helm-java + lib-api + 0.0.22 + + + com.marcnuri.helm-java + linux-arm64 + 0.0.22 + +``` + +**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 diff --git a/helm-java/pom.xml b/helm-java/pom.xml index 197ac734..17129c3a 100644 --- a/helm-java/pom.xml +++ b/helm-java/pom.xml @@ -165,6 +165,23 @@ + + linux-aarch64 + + + + unix + linux + aarch64 + + + + + ${project.groupId} + linux-arm64 + + + windows-amd64 diff --git a/lib/api/pom.xml b/lib/api/pom.xml index 135cddee..ccc5514f 100644 --- a/lib/api/pom.xml +++ b/lib/api/pom.xml @@ -28,6 +28,16 @@ net.java.dev.jna jna-platform-jpms + + org.junit.jupiter + junit-jupiter-api + test + + + org.assertj + assertj-core + test + diff --git a/lib/api/src/main/java/com/marcnuri/helm/jni/NativeLibrary.java b/lib/api/src/main/java/com/marcnuri/helm/jni/NativeLibrary.java index 4e684d2b..18fa4ddf 100644 --- a/lib/api/src/main/java/com/marcnuri/helm/jni/NativeLibrary.java +++ b/lib/api/src/main/java/com/marcnuri/helm/jni/NativeLibrary.java @@ -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; @@ -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. + * + *

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()); @@ -73,13 +106,38 @@ default HelmLib load() { } } + /** + * Creates the directory where the native binary is extracted. + * + *

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); } } diff --git a/lib/api/src/main/java/com/marcnuri/helm/jni/NativeLibrarySelector.java b/lib/api/src/main/java/com/marcnuri/helm/jni/NativeLibrarySelector.java new file mode 100644 index 00000000..a2aaa42a --- /dev/null +++ b/lib/api/src/main/java/com/marcnuri/helm/jni/NativeLibrarySelector.java @@ -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. + * + *

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: + *

    + *
  1. The first implementation that declares an OS and/or architecture, all of them matching the provided + * {@code os.name} and {@code os.arch}.
  2. + *
  3. 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.
  4. + *
+ * + * @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 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 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 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(); + } +} diff --git a/lib/api/src/main/java/com/marcnuri/helm/jni/Platform.java b/lib/api/src/main/java/com/marcnuri/helm/jni/Platform.java new file mode 100644 index 00000000..0f931c82 --- /dev/null +++ b/lib/api/src/main/java/com/marcnuri/helm/jni/Platform.java @@ -0,0 +1,72 @@ +/* + * 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.Locale; + +/** + * Detects the operating system and architecture of the running JVM using the names of the + * platform-specific native library modules (e.g. {@code linux}, {@code arm64}). + * + * @author Marc Nuri + */ +final class Platform { + + private Platform() { + } + + /** + * @return the OS name of the running JVM ({@code darwin}, {@code linux}, {@code windows}), or {@code null} if unsupported. + */ + static String osName() { + return osName(System.getProperty("os.name")); + } + + /** + * @return the architecture of the running JVM ({@code amd64}, {@code arm64}), or {@code null} if unsupported. + */ + static String archName() { + return archName(System.getProperty("os.arch")); + } + + static String osName(String osNameProperty) { + if (osNameProperty == null) { + return null; + } + final String osName = osNameProperty.toLowerCase(Locale.ROOT); + if (osName.contains("win")) { + return "windows"; + } else if (osName.contains("mac")) { + return "darwin"; + } else if (osName.contains("nux") || osName.contains("nix") || osName.contains("aix")) { + return "linux"; + } + return null; + } + + static String archName(String osArchProperty) { + if (osArchProperty == null) { + return null; + } + if (osArchProperty.equals("amd64") || osArchProperty.equals("x86_64")) { + return "amd64"; + } else if (osArchProperty.equals("arm64") || osArchProperty.equals("aarch64")) { + return "arm64"; + } + return null; + } +} diff --git a/lib/api/src/main/java/com/marcnuri/helm/jni/RemoteJarLoader.java b/lib/api/src/main/java/com/marcnuri/helm/jni/RemoteJarLoader.java index 532727be..513ecaf0 100644 --- a/lib/api/src/main/java/com/marcnuri/helm/jni/RemoteJarLoader.java +++ b/lib/api/src/main/java/com/marcnuri/helm/jni/RemoteJarLoader.java @@ -74,8 +74,8 @@ static ClassLoader remoteJar() { final String repository = isSnapshot ? nativeLibraries.getProperty(SNAPSHOTS) : nativeLibraries.getProperty(RELEASES); - final String osName = osName(); - final String archName = archName(); + final String osName = Platform.osName(); + final String archName = Platform.archName(); if (osName != null && archName != null) { final String groupUrl = repository + "/" + groupId.replace('.', '/') + "/" + osName + "-" + archName + "/" + version; final String jarName; @@ -121,26 +121,4 @@ private static URL cache(URL jarUrl, Path jarFile) throws IOException { } return jarFile.toUri().toURL(); } - - private static String osName() { - final String osName = System.getProperty("os.name").toLowerCase(); - if (osName.contains("win")) { - return "windows"; - } else if (osName.contains("mac")) { - return "darwin"; - } else if (osName.contains("nux") || osName.contains("nix") || osName.contains("aix")) { - return "linux"; - } - return null; - } - - private static String archName() { - final String arch = System.getProperty("os.arch"); - if (arch.equals("amd64") || arch.equals("x86_64")) { - return "amd64"; - } else if (arch.equals("arm64") || arch.equals("aarch64")) { - return "arm64"; - } - return null; - } } diff --git a/lib/api/src/test/java/com/marcnuri/helm/jni/NativeLibrarySelectorTest.java b/lib/api/src/test/java/com/marcnuri/helm/jni/NativeLibrarySelectorTest.java new file mode 100644 index 00000000..fba2bc97 --- /dev/null +++ b/lib/api/src/test/java/com/marcnuri/helm/jni/NativeLibrarySelectorTest.java @@ -0,0 +1,160 @@ +/* + * 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 org.junit.jupiter.api.Nested; +import org.junit.jupiter.api.Test; + +import java.util.Arrays; +import java.util.Collections; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +/** + * @author Marc Nuri + */ +class NativeLibrarySelectorTest { + + private final NativeLibrary linuxArm64 = new FakeNativeLibrary("linux", "arm64"); + private final NativeLibrary linuxAmd64 = new FakeNativeLibrary("linux", "amd64"); + private final NativeLibrary darwinArm64 = new FakeNativeLibrary("darwin", "arm64"); + private final NativeLibrary undeclared = new UndeclaredNativeLibrary(); + + @Nested + class ByPlatform { + + @Test + void selectsLinuxAmd64OnLinuxX8664() { + assertThat(NativeLibrarySelector.select(Arrays.asList(linuxArm64, linuxAmd64), null, "Linux", "amd64")) + .isSameAs(linuxAmd64); + } + + @Test + void selectsLinuxArm64OnLinuxAarch64() { + assertThat(NativeLibrarySelector.select(Arrays.asList(linuxAmd64, linuxArm64), null, "Linux", "aarch64")) + .isSameAs(linuxArm64); + } + + @Test + void selectsDarwinArm64OnMacOsAarch64() { + assertThat(NativeLibrarySelector.select(Arrays.asList(linuxArm64, darwinArm64), null, "Mac OS X", "aarch64")) + .isSameAs(darwinArm64); + } + + @Test + void prefersMatchingImplementationOverPreviousUndeclaredImplementation() { + // e.g. an older platform JAR (no OS/arch declared) listed before the right, newer one + assertThat(NativeLibrarySelector.select(Arrays.asList(linuxArm64, undeclared, linuxAmd64), null, "Linux", "amd64")) + .isSameAs(linuxAmd64); + } + + @Test + void selectsUndeclaredImplementationWhenNoneMatches() { + assertThat(NativeLibrarySelector.select(Arrays.asList(linuxArm64, undeclared, darwinArm64), null, "Linux", "amd64")) + .isSameAs(undeclared); + } + + @Test + void selectsUndeclaredImplementationOnUnsupportedPlatform() { + assertThat(NativeLibrarySelector.select(Arrays.asList(linuxAmd64, undeclared), null, "SunOS", "sparcv9")) + .isSameAs(undeclared); + } + + @Test + void returnsNullWithNoImplementations() { + assertThat(NativeLibrarySelector.select(Collections.emptyList(), null, "Linux", "amd64")) + .isNull(); + } + + @Test + void throwsWithNoCompatibleImplementation() { + assertThatThrownBy(() -> NativeLibrarySelector.select(Arrays.asList(linuxArm64, darwinArm64), null, "Linux", "amd64")) + .isInstanceOf(IllegalStateException.class) + .hasMessage("No NativeLibrary implementation found for the current platform (os.name=Linux, os.arch=amd64), " + + "available implementations: [" + FakeNativeLibrary.class.getName() + " (linux/arm64), " + + FakeNativeLibrary.class.getName() + " (darwin/arm64)]. Please add the dependency for your platform to your project"); + } + } + + @Nested + class Forced { + + @Test + void selectsForcedImplementationRegardlessOfPlatform() { + final NativeLibrary result = NativeLibrarySelector.select( + Arrays.asList(linuxAmd64, undeclared), UndeclaredNativeLibrary.class.getName(), "Linux", "amd64"); + assertThat(result).isSameAs(undeclared); + } + + @Test + void ignoresBlankForcedImplementation() { + final NativeLibrary result = NativeLibrarySelector.select( + Arrays.asList(linuxArm64, linuxAmd64), " ", "Linux", "amd64"); + assertThat(result).isSameAs(linuxAmd64); + } + + @Test + void selectsForcedImplementationForAnotherPlatform() { + final NativeLibrary result = NativeLibrarySelector.select( + Arrays.asList(undeclared, linuxArm64), FakeNativeLibrary.class.getName(), "Linux", "amd64"); + assertThat(result).isSameAs(linuxArm64); + } + + @Test + void throwsWhenForcedImplementationNotFound() { + assertThatThrownBy(() -> NativeLibrarySelector.select( + Collections.singletonList(linuxAmd64), "com.example.Missing", "Linux", "amd64")) + .isInstanceOf(IllegalStateException.class) + .hasMessage("NativeLibrary implementation com.example.Missing " + + "(set with the com.marcnuri.jkube-helm.nativeLibrary system property) not found, " + + "available implementations: [" + FakeNativeLibrary.class.getName() + " (linux/amd64)]"); + } + } + + static final class FakeNativeLibrary implements NativeLibrary { + private final String os; + private final String arch; + + FakeNativeLibrary(String os, String arch) { + this.os = os; + this.arch = arch; + } + + @Override + public String getBinaryName() { + return "helm-" + os + "-" + arch; + } + + @Override + public String getOs() { + return os; + } + + @Override + public String getArch() { + return arch; + } + } + + static final class UndeclaredNativeLibrary implements NativeLibrary { + @Override + public String getBinaryName() { + return "helm-custom"; + } + } +} diff --git a/lib/api/src/test/java/com/marcnuri/helm/jni/NativeLibraryServiceProviderTest.java b/lib/api/src/test/java/com/marcnuri/helm/jni/NativeLibraryServiceProviderTest.java new file mode 100644 index 00000000..9381c1ce --- /dev/null +++ b/lib/api/src/test/java/com/marcnuri/helm/jni/NativeLibraryServiceProviderTest.java @@ -0,0 +1,265 @@ +/* + * 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 org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Nested; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +import java.io.IOException; +import java.net.URL; +import java.net.URLClassLoader; +import java.nio.charset.StandardCharsets; +import java.nio.file.FileSystemException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.junit.jupiter.api.Assumptions.assumeFalse; +import static org.junit.jupiter.api.Assumptions.assumeTrue; + +/** + * @author Marc Nuri + */ +class NativeLibraryServiceProviderTest { + + private static final String NATIVE_LIBRARY = "com.marcnuri.jkube-helm.nativeLibrary"; + private static final String TEMP_DIR = "com.marcnuri.jkube-helm.tempDir"; + + @TempDir + private Path tempDir; + + private String previousNativeLibrary; + private String previousTempDir; + + @BeforeEach + void saveSystemProperties() { + previousNativeLibrary = System.clearProperty(NATIVE_LIBRARY); + previousTempDir = System.clearProperty(TEMP_DIR); + } + + @AfterEach + void restoreSystemProperties() { + restore(NATIVE_LIBRARY, previousNativeLibrary); + restore(TEMP_DIR, previousTempDir); + } + + @Nested + class ServiceLoaderOrder { + + private URLClassLoader classLoader; + + @BeforeEach + void setUp() throws IOException { + // The provider for another platform is registered (and iterated by the ServiceLoader) first + classLoader = servicesClassLoader(OtherPlatformNativeLibrary.class, CurrentPlatformNativeLibrary.class); + } + + @AfterEach + void tearDown() throws IOException { + classLoader.close(); + } + + @Test + void selectsProviderForCurrentPlatform() { + assertThat(NativeLibrary.serviceProviderLibrary(classLoader)) + .isInstanceOf(CurrentPlatformNativeLibrary.class); + } + + @Test + void selectsProviderSetWithSystemProperty() { + System.setProperty(NATIVE_LIBRARY, OtherPlatformNativeLibrary.class.getName()); + assertThat(NativeLibrary.serviceProviderLibrary(classLoader)) + .isInstanceOf(OtherPlatformNativeLibrary.class); + } + + @Test + void ignoresBlankSystemProperty() { + System.setProperty(NATIVE_LIBRARY, ""); + assertThat(NativeLibrary.serviceProviderLibrary(classLoader)) + .isInstanceOf(CurrentPlatformNativeLibrary.class); + } + + @Test + void throwsWhenProviderSetWithSystemPropertyIsNotRegistered() { + System.setProperty(NATIVE_LIBRARY, "com.example.Missing"); + assertThatThrownBy(() -> NativeLibrary.serviceProviderLibrary(classLoader)) + .isInstanceOf(IllegalStateException.class) + .hasMessageStartingWith("NativeLibrary implementation com.example.Missing (set with the com.marcnuri.jkube-helm.nativeLibrary system property) not found"); + } + } + + @Nested + class MixedVersions { + + @Test + void prefersProviderForCurrentPlatformOverPreviousUndeclaredProvider() throws IOException { + // An undeclared provider (e.g. a platform JAR prior to OS/arch declarations) is registered first + try (URLClassLoader classLoader = servicesClassLoader( + UndeclaredNativeLibrary.class, OtherPlatformNativeLibrary.class, CurrentPlatformNativeLibrary.class)) { + assertThat(NativeLibrary.serviceProviderLibrary(classLoader)) + .isInstanceOf(CurrentPlatformNativeLibrary.class); + } + } + + @Test + void fallsBackToUndeclaredProvider() throws IOException { + try (URLClassLoader classLoader = servicesClassLoader( + OtherPlatformNativeLibrary.class, UndeclaredNativeLibrary.class)) { + assertThat(NativeLibrary.serviceProviderLibrary(classLoader)) + .isInstanceOf(UndeclaredNativeLibrary.class); + } + } + } + + @Nested + class NoCompatibleProvider { + + @Test + void throwsWithPlatformAndAvailableProviders() throws IOException { + try (URLClassLoader classLoader = servicesClassLoader(OtherPlatformNativeLibrary.class)) { + assertThatThrownBy(() -> NativeLibrary.serviceProviderLibrary(classLoader)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("No NativeLibrary implementation found for the current platform (os.name=" + + System.getProperty("os.name") + ", os.arch=" + System.getProperty("os.arch") + ")") + .hasMessageContaining(OtherPlatformNativeLibrary.class.getName()); + } + } + } + + @Nested + class TempDirectory { + + @Test + void defaultsToJavaIoTmpdir() throws IOException { + final Path result = new CurrentPlatformNativeLibrary().createTempDirectory(); + try { + assertThat(result.getParent().toRealPath()) + .isEqualTo(Paths.get(System.getProperty("java.io.tmpdir")).toRealPath()); + } finally { + Files.deleteIfExists(result); + } + } + + @Test + void usesDirectorySetWithSystemProperty() { + final Path baseDir = tempDir.resolve("extract").resolve("here"); + System.setProperty(TEMP_DIR, baseDir.toString()); + final Path result = new CurrentPlatformNativeLibrary().createTempDirectory(); + assertThat(result) + .isDirectory() + .hasParent(baseDir); + assertThat(result.getFileName().toString()).startsWith("helm-java"); + } + + @Test + void usesSymbolicLinkToDirectorySetWithSystemProperty() throws IOException { + final Path target = Files.createDirectory(tempDir.resolve("target")); + final Path link; + try { + link = Files.createSymbolicLink(tempDir.resolve("link"), target); + } catch (UnsupportedOperationException exception) { + assumeTrue(false, "Symbolic links not supported: " + exception); + return; + } catch (FileSystemException exception) { + // Windows without the privilege to create symbolic links; a failure anywhere else fails the test + assumeFalse(System.getProperty("os.name").startsWith("Windows"), "Symbolic links not allowed: " + exception); + throw exception; + } + System.setProperty(TEMP_DIR, link.toString()); + final Path result = new CurrentPlatformNativeLibrary().createTempDirectory(); + assertThat(result) + .isDirectory() + .hasParent(link); + } + + @Test + void throwsWhenDirectorySetWithSystemPropertyIsAFile() throws IOException { + final Path file = Files.createFile(tempDir.resolve("a-file")); + System.setProperty(TEMP_DIR, file.toString()); + final NativeLibrary nativeLibrary = new CurrentPlatformNativeLibrary(); + assertThatThrownBy(nativeLibrary::createTempDirectory) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Unable to create temporary directory in " + file + + " (set with the com.marcnuri.jkube-helm.tempDir system property)"); + } + } + + private static void restore(String key, String value) { + if (value == null) { + System.clearProperty(key); + } else { + System.setProperty(key, value); + } + } + + private URLClassLoader servicesClassLoader(Class... providers) throws IOException { + final Path root = Files.createTempDirectory(tempDir, "services"); + final Path services = Files.createDirectories(root.resolve("META-INF").resolve("services")); + final StringBuilder content = new StringBuilder(); + for (Class provider : providers) { + content.append(provider.getName()).append('\n'); + } + Files.write(services.resolve(NativeLibrary.class.getName()), content.toString().getBytes(StandardCharsets.UTF_8)); + return new URLClassLoader(new URL[]{root.toUri().toURL()}, NativeLibraryServiceProviderTest.class.getClassLoader()); + } + + public static final class CurrentPlatformNativeLibrary implements NativeLibrary { + @Override + public String getBinaryName() { + return "helm-current"; + } + + @Override + public String getOs() { + return Platform.osName(); + } + + @Override + public String getArch() { + return Platform.archName(); + } + } + + public static final class UndeclaredNativeLibrary implements NativeLibrary { + @Override + public String getBinaryName() { + return "helm-undeclared"; + } + } + + public static final class OtherPlatformNativeLibrary implements NativeLibrary { + @Override + public String getBinaryName() { + return "helm-other"; + } + + @Override + public String getOs() { + return "linux".equals(Platform.osName()) ? "windows" : "linux"; + } + + @Override + public String getArch() { + return Platform.archName(); + } + } +} diff --git a/lib/api/src/test/java/com/marcnuri/helm/jni/PlatformTest.java b/lib/api/src/test/java/com/marcnuri/helm/jni/PlatformTest.java new file mode 100644 index 00000000..9b272b97 --- /dev/null +++ b/lib/api/src/test/java/com/marcnuri/helm/jni/PlatformTest.java @@ -0,0 +1,91 @@ +/* + * 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 org.junit.jupiter.api.Nested; +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +/** + * @author Marc Nuri + */ +class PlatformTest { + + @Nested + class OsName { + + @Test + void windows() { + assertThat(Platform.osName("Windows 10")).isEqualTo("windows"); + } + + @Test + void macOs() { + assertThat(Platform.osName("Mac OS X")).isEqualTo("darwin"); + } + + @Test + void linux() { + assertThat(Platform.osName("Linux")).isEqualTo("linux"); + } + + @Test + void unsupported() { + assertThat(Platform.osName("SunOS")).isNull(); + } + + @Test + void missing() { + assertThat(Platform.osName(null)).isNull(); + } + } + + @Nested + class ArchName { + + @Test + void amd64() { + assertThat(Platform.archName("amd64")).isEqualTo("amd64"); + } + + @Test + void x8664() { + assertThat(Platform.archName("x86_64")).isEqualTo("amd64"); + } + + @Test + void aarch64() { + assertThat(Platform.archName("aarch64")).isEqualTo("arm64"); + } + + @Test + void arm64() { + assertThat(Platform.archName("arm64")).isEqualTo("arm64"); + } + + @Test + void unsupported() { + assertThat(Platform.archName("sparcv9")).isNull(); + } + + @Test + void missing() { + assertThat(Platform.archName(null)).isNull(); + } + } +} diff --git a/lib/darwin-amd64/src/main/java/com/marcnuri/helm/jni/darwin/amd64/DarwinAmd64NativeLibrary.java b/lib/darwin-amd64/src/main/java/com/marcnuri/helm/jni/darwin/amd64/DarwinAmd64NativeLibrary.java index c15f6d18..247b5bb2 100644 --- a/lib/darwin-amd64/src/main/java/com/marcnuri/helm/jni/darwin/amd64/DarwinAmd64NativeLibrary.java +++ b/lib/darwin-amd64/src/main/java/com/marcnuri/helm/jni/darwin/amd64/DarwinAmd64NativeLibrary.java @@ -26,4 +26,14 @@ public class DarwinAmd64NativeLibrary implements NativeLibrary { public String getBinaryName() { return "helm-darwin-10.12-amd64.dylib"; } + + @Override + public String getOs() { + return "darwin"; + } + + @Override + public String getArch() { + return "amd64"; + } } diff --git a/lib/darwin-arm64/src/main/java/com/marcnuri/helm/jni/darwin/arm64/DarwinArm64NativeLibrary.java b/lib/darwin-arm64/src/main/java/com/marcnuri/helm/jni/darwin/arm64/DarwinArm64NativeLibrary.java index 947f05c5..1c855a79 100644 --- a/lib/darwin-arm64/src/main/java/com/marcnuri/helm/jni/darwin/arm64/DarwinArm64NativeLibrary.java +++ b/lib/darwin-arm64/src/main/java/com/marcnuri/helm/jni/darwin/arm64/DarwinArm64NativeLibrary.java @@ -26,4 +26,14 @@ public class DarwinArm64NativeLibrary implements NativeLibrary { public String getBinaryName() { return "helm-darwin-10.12-arm64.dylib"; } + + @Override + public String getOs() { + return "darwin"; + } + + @Override + public String getArch() { + return "arm64"; + } } diff --git a/lib/linux-amd64/src/main/java/com/marcnuri/helm/jni/linux/amd64/LinuxAmd64NativeLibrary.java b/lib/linux-amd64/src/main/java/com/marcnuri/helm/jni/linux/amd64/LinuxAmd64NativeLibrary.java index 2aeaa55b..c0921b80 100644 --- a/lib/linux-amd64/src/main/java/com/marcnuri/helm/jni/linux/amd64/LinuxAmd64NativeLibrary.java +++ b/lib/linux-amd64/src/main/java/com/marcnuri/helm/jni/linux/amd64/LinuxAmd64NativeLibrary.java @@ -26,4 +26,14 @@ public class LinuxAmd64NativeLibrary implements NativeLibrary { public String getBinaryName() { return "helm-linux-amd64.so"; } + + @Override + public String getOs() { + return "linux"; + } + + @Override + public String getArch() { + return "amd64"; + } } diff --git a/lib/linux-arm64/src/main/java/com/marcnuri/helm/jni/linux/arm64/LinuxArm64NativeLibrary.java b/lib/linux-arm64/src/main/java/com/marcnuri/helm/jni/linux/arm64/LinuxArm64NativeLibrary.java index b54110e7..28368a03 100644 --- a/lib/linux-arm64/src/main/java/com/marcnuri/helm/jni/linux/arm64/LinuxArm64NativeLibrary.java +++ b/lib/linux-arm64/src/main/java/com/marcnuri/helm/jni/linux/arm64/LinuxArm64NativeLibrary.java @@ -26,4 +26,14 @@ public class LinuxArm64NativeLibrary implements NativeLibrary { public String getBinaryName() { return "helm-linux-arm64.so"; } + + @Override + public String getOs() { + return "linux"; + } + + @Override + public String getArch() { + return "arm64"; + } } diff --git a/lib/windows-amd64/src/main/java/com/marcnuri/helm/jni/windows/amd64/WindowsAmd64NativeLibrary.java b/lib/windows-amd64/src/main/java/com/marcnuri/helm/jni/windows/amd64/WindowsAmd64NativeLibrary.java index 4bc539bf..7dc49502 100644 --- a/lib/windows-amd64/src/main/java/com/marcnuri/helm/jni/windows/amd64/WindowsAmd64NativeLibrary.java +++ b/lib/windows-amd64/src/main/java/com/marcnuri/helm/jni/windows/amd64/WindowsAmd64NativeLibrary.java @@ -26,4 +26,14 @@ public class WindowsAmd64NativeLibrary implements NativeLibrary { public String getBinaryName() { return "helm-windows-4.0-amd64.dll"; } + + @Override + public String getOs() { + return "windows"; + } + + @Override + public String getArch() { + return "amd64"; + } }