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
161 changes: 127 additions & 34 deletions helm-java/src/test/java/com/marcnuri/helm/HelmSignalHandlerTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,18 @@

package com.marcnuri.helm;

import com.marcnuri.helm.jni.RepoServerOptions;
import com.marcnuri.helm.jni.Result;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.Timeout;
import org.junit.jupiter.api.condition.DisabledOnOs;
import org.junit.jupiter.api.condition.OS;
import org.junit.jupiter.api.io.TempDir;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
Expand All @@ -32,70 +38,157 @@

/**
* Verifies that the host JVM keeps its OS-level termination signal handlers after native helm
* calls that used to register Go signal handlers (install path).
* calls that used to register Go signal handlers.
*
* <p>The Go runtime of the c-shared native library permanently replaced the JVM's SIGINT/SIGTERM
* handlers on the first {@code signal.Notify}, leaving the JVM unable to react to SIGTERM
* (shutdown hooks never ran, Kubernetes pods hung until SIGKILL).
*
* @author Wellington Mafra
* @author Marc Nuri
* @see <a href="https://github.com/manusa/helm-java/issues/409">manusa/helm-java#409</a>
*/
@DisabledOnOs(OS.WINDOWS) // relies on POSIX SIGTERM delivery and 128+n exit codes
// SEPARATE_THREAD is defensive: no blocking read is left, but it still bounds a call that ignores interrupts
@Timeout(value = 2, unit = TimeUnit.MINUTES, threadMode = Timeout.ThreadMode.SEPARATE_THREAD)
class HelmSignalHandlerTest {

private static final int SIGTERM_EXIT_CODE = 128 + 15;

private volatile Process probe;

@AfterEach
void destroyProbe() throws InterruptedException {
// Runs even if the test failed or timed out, so no probe process is left behind
if (probe != null) {
probe.destroyForcibly().waitFor(30, TimeUnit.SECONDS);
}
}

@Test
void jvmRunsShutdownHooksOnSigTermAfterInstall(@TempDir Path tempDir) throws Exception {
assertProbeExitsGracefullyOnSigTerm(SignalProbe.INSTALL, tempDir);
}

@Test
void jvmExitsOnSigTermAfterInstall() throws Exception {
void jvmRunsShutdownHooksOnSigTermAfterTemplate(@TempDir Path tempDir) throws Exception {
assertProbeExitsGracefullyOnSigTerm(SignalProbe.TEMPLATE, tempDir);
}

@Test
void jvmRunsShutdownHooksOnSigTermAfterTestOciServerStart(@TempDir Path tempDir) throws Exception {
assertProbeExitsGracefullyOnSigTerm(SignalProbe.TEST_OCI_SERVER, tempDir);
}

private void assertProbeExitsGracefullyOnSigTerm(String scenario, Path tempDir) throws Exception {
final String javaBin = Paths.get(System.getProperty("java.home"), "bin", "java").toString();
final ProcessBuilder processBuilder = new ProcessBuilder(
javaBin, "-cp", System.getProperty("java.class.path"), SignalProbe.class.getName());
javaBin,
// Extract the native library into the test's temporary directory
"-Dcom.marcnuri.jkube-helm.tempDir=" + tempDir,
"-cp", System.getProperty("java.class.path"),
SignalProbe.class.getName(), scenario, tempDir.toString());
processBuilder.environment().put("KUBECONFIG", "/dev/null");
processBuilder.redirectErrorStream(true);
final Process probe = processBuilder.start();
try {
final BufferedReader reader =
new BufferedReader(new InputStreamReader(probe.getInputStream(), StandardCharsets.UTF_8));
boolean ready = false;
String line;
while ((line = reader.readLine()) != null) {
if (SignalProbe.READY_MARKER.equals(line)) {
ready = true;
break;
}
}
assertThat(ready)
.as("probe process should complete the native helm install")
.isTrue();
// Process.destroy() delivers SIGTERM on POSIX systems
probe.destroy();
assertThat(probe.waitFor(15, TimeUnit.SECONDS))
.as("JVM should exit on SIGTERM after a native helm install (issue #409)")
.isTrue();
assertThat(probe.exitValue()).isEqualTo(SIGTERM_EXIT_CODE);
} finally {
probe.destroyForcibly();
// Go's os.TempDir() (e.g. the test OCI server's storage), so nothing is left behind
processBuilder.environment().put("TMPDIR", tempDir.toString());
// A file, not a pipe: Process.destroy() closes the pipes, which would lose the output after SIGTERM
final Path outputFile = tempDir.resolve("probe-output.log");
processBuilder.redirectErrorStream(true).redirectOutput(outputFile.toFile());
probe = processBuilder.start();
final long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(90);
while (!read(outputFile).contains(SignalProbe.READY_MARKER) && probe.isAlive() && System.nanoTime() < deadline) {
Thread.sleep(100);
}
assertThat(read(outputFile))
.as("probe process should complete the native helm %s call", scenario)
.contains(SignalProbe.READY_MARKER);
// Process.destroy() delivers SIGTERM on POSIX systems
probe.destroy();
assertThat(probe.waitFor(15, TimeUnit.SECONDS))
.as("JVM should exit on SIGTERM after a native helm %s call (issue #409), output:%n%s",
scenario, read(outputFile))
.isTrue();
assertThat(read(outputFile))
.as("JVM should run its shutdown hooks on SIGTERM after a native helm %s call (issue #409)", scenario)
.contains(SignalProbe.SHUTDOWN_HOOK_MARKER);
assertThat(probe.exitValue())
.as("JVM exit code on SIGTERM after a native helm %s call, output:%n%s", scenario, read(outputFile))
.isEqualTo(SIGTERM_EXIT_CODE);
}

private static String read(Path file) throws IOException {
return new String(Files.readAllBytes(file), StandardCharsets.UTF_8);
}

/**
* Runs in a separate JVM: performs a client-only install (reaching the native code path that
* used to call Go's {@code signal.Notify}), signals readiness, then waits to be terminated.
* Runs in a separate JVM: performs a native helm call that used to register Go signal handlers,
* registers a shutdown hook, signals readiness, then waits to be terminated.
*
* <p>Arguments: the scenario and a temporary directory to work in.
*/
static final class SignalProbe {

static final String READY_MARKER = "SIGNAL_PROBE_READY";
static final String SHUTDOWN_HOOK_MARKER = "SIGNAL_PROBE_SHUTDOWN_HOOK_RAN";
static final String INSTALL = "install";
static final String TEMPLATE = "template";
static final String TEST_OCI_SERVER = "test-oci-server";

public static void main(String[] args) throws Exception {
final Path tempDir = Files.createTempDirectory("helm-signal-probe");
final Helm helm = Helm.create().withName("test").withDir(tempDir).call();
helm.install().clientOnly().withName("test").call();
final String scenario = args[0];
final Path tempDir = Paths.get(args[1]);
switch (scenario) {
case INSTALL:
Helm.create().withName("test").withDir(tempDir).call().install().clientOnly().withName("test").call();
break;
case TEMPLATE:
Helm.create().withName("test").withDir(tempDir).call().template().call();
break;
case TEST_OCI_SERVER:
startTestOciServer();
break;
default:
throw new IllegalArgumentException("Unknown scenario: " + scenario);
}
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
System.out.println(SHUTDOWN_HOOK_MARKER);
System.out.flush();
}));
System.out.println(READY_MARKER);
System.out.flush();
Thread.sleep(TimeUnit.SECONDS.toMillis(60));
// Only reached if SIGTERM was ignored (the bug) or never delivered (test infrastructure issue)
System.exit(1);
}

/**
* Starts the test OCI registry and waits until it serves requests. The registry starts serving
* in a goroutine, after registering any signal handlers, so a response proves they are in place.
*/
private static void startTestOciServer() throws Exception {
final Result result = Helm.HelmLibHolder.INSTANCE.RepoOciServerStart(new RepoServerOptions());
if (result.err != null && !result.err.isEmpty()) {
throw new IllegalStateException("Test OCI server failed to start: " + result.err);
}
final String registry = result.out;
final URL url = new URL("http://" + registry + "/v2/");
final long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(30);
while (true) {
final HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setConnectTimeout(5_000);
connection.setReadTimeout(5_000);
try {
System.out.println("Test OCI server responded with " + connection.getResponseCode());
return;
} catch (IOException exception) {
if (System.nanoTime() > deadline) {
throw exception;
}
Thread.sleep(50);
} finally {
connection.disconnect();
}
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ void getSnapshotInstanceFromRemoteJar() {
} finally {
Thread.currentThread().setContextClassLoader(currentClassLoader);
System.clearProperty("com.marcnuri.jkube-helm.version");
System.clearProperty("com.marcnuri.jkube-helm.forceUpdate");
}
}

Expand All @@ -71,6 +72,7 @@ void getReleaseInstanceFromRemoteJar() {
} finally {
Thread.currentThread().setContextClassLoader(currentClassLoader);
System.clearProperty("com.marcnuri.jkube-helm.version");
System.clearProperty("com.marcnuri.jkube-helm.forceUpdate");
}
}

Expand Down
17 changes: 10 additions & 7 deletions native/internal/helm/install.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@ package helm

import (
"bytes"
"context"
"fmt"
"github.com/pkg/errors"
"helm.sh/helm/v3/pkg/action"
Expand Down Expand Up @@ -175,12 +174,16 @@ func install(options *InstallOptions) (*release.Release, *installOutputs, error)
}

// Run
// Don't use signal.Notify here: in a c-shared library the first call makes the Go
// runtime permanently replace the host process' (e.g. an embedding JVM's) OS-level
// SIGINT/SIGTERM handlers, and the cancellation it enabled was never reachable by
// embedders anyway. Interrupt handling is the host application's responsibility.
// See https://github.com/manusa/helm-java/issues/409
rel, err := client.RunWithContext(context.Background(), chartRequested, vals)
// signal.Notify is deliberately not used: in a c-shared library it makes the Go runtime
// take over the host process' (e.g. the JVM's) SIGINT/SIGTERM/SIGQUIT handlers for good,
// so shutdown hooks never run and kill -3 thread dumps stop working.
// The trade-off: a signal no longer cancels an in-flight install (which used to mark the
// release failed, or uninstall it with Atomic); the host decides how to terminate, and a
// release interrupted that way can be left pending-install. upgrade never had signal-based
// cancellation either.
// See manusa/helm-java#409, fixed by #411, which removed the signal handling added in #113 (for #112):
// https://github.com/manusa/helm-java/issues/409
rel, err := client.Run(chartRequested, vals)
return rel, outputs, err
}

Expand Down
6 changes: 4 additions & 2 deletions native/internal/helm/repotest.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,6 @@ import (
"os"
"path/filepath"
"testing"
"time"
)

var servers = cmap.New[*ActiveServer]()
Expand Down Expand Up @@ -102,7 +101,10 @@ func RepoOciServerStart(options *RepoServerOptions) (*repotest.OCIServer, error)
}
config := &configuration.Configuration{}
config.HTTP.Addr = fmt.Sprintf(":%d", port)
config.HTTP.DrainTimeout = time.Duration(1) * time.Second
// config.HTTP.DrainTimeout is deliberately left at 0: with a non-zero value, distribution's
// Registry.ListenAndServe calls signal.Notify for SIGINT/SIGTERM, which in a c-shared library
// takes over the host process' (e.g. the JVM's) handlers for good. With 0 it serves directly.
// See https://github.com/manusa/helm-java/issues/409
config.Storage = map[string]configuration.Parameters{"inmemory": map[string]interface{}{}}
config.Auth = configuration.Auth{
"htpasswd": configuration.Parameters{
Expand Down
10 changes: 7 additions & 3 deletions native/main_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import (
"net/http"
"os"
"path"
"path/filepath"
"strings"
"testing"
"time"
Expand Down Expand Up @@ -584,16 +585,19 @@ func TestRepoServerStopAll(t *testing.T) {
}

func TestSearchRepo(t *testing.T) {
repositoryConfigFile, _ := os.CreateTemp("", "repositories.yaml")
repositoryConfig := filepath.Join(t.TempDir(), "repositories.yaml")
err := helm.RepoAdd(&helm.RepoOptions{
Name: "helm",
Url: "https://charts.helm.sh/stable",
InsecureSkipTlsVerify: true,
RepositoryConfig: repositoryConfigFile.Name(),
RepositoryConfig: repositoryConfig,
})
if err != nil {
t.Fatalf("Expected repo add to succeed, got %s", err)
}
out, err := helm.SearchRepo(&helm.SearchOptions{
Keyword: "nginx",
RepositoryConfig: repositoryConfigFile.Name(),
RepositoryConfig: repositoryConfig,
})
if err != nil {
t.Errorf("Expected search to succeed, got %s", err)
Expand Down
Loading