diff --git a/README.md b/README.md index 0092e85..274fd3c 100644 --- a/README.md +++ b/README.md @@ -31,7 +31,7 @@ The work a request hands to a Spring executor (Spring 5.3 to 6.2) or to verified Executor wrapping is **fail-closed**: only positively verified safe executors (exact `ThreadPoolExecutor` / `ScheduledThreadPoolExecutor` with exact `AbortPolicy` and an exact in-order JDK queue — `LinkedBlockingQueue`, `SynchronousQueue`, `ArrayBlockingQueue`, `LinkedBlockingDeque`, or `LinkedTransferQueue` — exact `ForkJoinPool`, verified JDK `Delegated*` / `ThreadPerTaskExecutor`, and known Spring executor/adapter types whose subclasses do not override `execute`/`submit`/`doExecute` and whose inner pool is allow-listed) are wrapped. Known same-thread inline executors (`org.springframework.core.task.SyncTaskExecutor` and Guava `com.google.common.util.concurrent.DirectExecutor` / `MoreExecutors.directExecutor()` / `DirectExecutorService`) are allow-listed so they are neither wrapped nor flagged (the task runs inline on the request thread). Plain non-`Executor` synchronous helpers with an `execute(Runnable)` or `submit(...)` method are checked at runtime (`instanceof Executor` / `ExecutorService` / `CompletionService` / Spring `AsyncTaskExecutor`) and are never flagged. Any unknown or custom executor (such as Hazelcast `IExecutorService`, Ignite, Redisson, striped/keyed executors, coalescing executors, custom `ExecutorService` / `ThreadPoolExecutor` / Spring executor subclasses, priority queues, or non-`AbortPolicy` handlers) and any `Comparable` task receives the application's original task untouched so application serialization, ordering, and `instanceof` checks are preserved, while the active testcase window (and subsequent tail window) is marked contaminated (`"untracked-executor:"`). Similarly, untracked async submission sites inside a request or job (`ScheduledExecutorService.schedule*` and Spring `TaskScheduler.schedule*` with weak `ScheduledFuture` liveness tracking until done/cancelled — with verified JDK `ScheduledThreadPoolExecutor` also propagating request/job context across multi-hop retries and downstream fan-outs without blocking `END`, `java.util.Timer.schedule*` / `scheduleAtFixedRate*` with `TimerTask` liveness and cancellation tracking, `ExecutorService.invokeAny`, `Thread.start()` including subclasses via runtime `instanceof Thread` check and JDK 21 `Thread.startVirtualThread` / `Thread.Builder.start` with weak `Thread.isAlive()` liveness tracking, non-JDK/custom executor `execute`/`submit` decided by runtime receiver, `ForkJoinPool.execute`/`submit(ForkJoinTask)` and `ForkJoinTask.fork()`, Guava `ListenableFuture.addListener` / `Futures.addCallback` / `transform*` / `catching*`, Reactor `Mono`/`Flux`/`ParallelFlux` `.subscribe()`, custom `CompletionStage`, and async method references such as `executor::execute`) mark the originating window contaminated (`"untracked-async:"` / `"untracked-executor:"`). When a concrete handle (`ScheduledFuture`, `Thread`, `TimerTask`) is tracked, its liveness alone drives subsequent `tail:` contamination (so a 30 s timeout cancelled before returning, a `Thread.start()` + `join()` finished before the response, or a cancelled `TimerTask` leaves subsequent windows clean). Plain dependent stages on `CompletableFuture` subclasses that inherit dependent methods and `whenComplete` directly (including JDK `HttpClient.sendAsync`'s `MinimalFuture` and JDK `MinimalStage`) are tracked without throwing `UnsupportedOperationException`, and abandoned futures collected by GC release their window permits automatically via `ReferenceQueue` (with a 30 s cap on idle uncompleted permits while actively executing work remains tracked until exit and any late-starting task contaminates the currently open window). Limits: on JDK 16+ without `--add-opens java.base/java.util.concurrent=ALL-UNNAMED`, `Executors.unconfigurableExecutorService(...)`, `Executors.newSingleThreadScheduledExecutor()`, and any `Executors$DelegatedExecutorService` / `DelegatedScheduledExecutorService` wrapper (including `Executors.newSingleThreadExecutor()` when backed by `DelegatedExecutorService` rather than `FinalizableDelegatedExecutorService` / `AutoShutdownDelegatedExecutorService`) cannot be reflectively inspected and fall back to `untracked-executor:java.util.concurrent.Executors$Delegated*`; custom `ScheduledExecutorService` implementations, raw `Thread` / virtual threads, `Timer`, and Spring `TaskScheduler` run tasks unwrapped (app-safe), so nested async hops spawned inside them are not tracked beyond the parent handle's lifetime; RxJava schedulers/observables, Kotlin coroutines, OkHttp's `Dispatcher`, JDK NIO `Asynchronous*Channel` / `AsynchronousChannelGroup`, and Spring's `SimpleApplicationEventMulticaster` configured with a non-hooked executor (such as a plain JDK pool) are not intercepted; when any of them is detected (or when an untracked executor/async method reference is captured anywhere in the application), the agent permanently drops `asyncExecutors=false` in `HELLO` and Unix `ACK` caps so deduplication fails closed to soft-mark only. Set `KEPLOY_JAVA_ASYNC_CALLSITES=off` to disable JDK executor and `CompletableFuture` call-site rewriting completely (declaring `asyncExecutors=false`). In external-JaCoCo mode (when `-javaagent:jacocoagent.jar` is attached separately), call-site rewriting matches the derived application package prefix while skipping shaded/relocated packages (`/shaded/`, `/relocated/`, `/repackaged/`) and known library packages; in indexed mode, exact indexed app classes (including `org/springframework/samples/...` such as Spring PetClinic) are rewritten without shaded-package filtering while still keeping core third-party libraries (Netty, OkHttp, gRPC, AWS SDK, etc.) untouched even if misconfigured in `KEPLOY_JAVA_CLASS_DIRS`. -When Keploy is absent (no collector connected and no control command received), runtime request counting, executor wrapping, and job/listener tracking remain unarmed (zero-allocation static sentinel token, zero task wrapping); every armed window opened while any pre-arming request or job remains in flight (or within the tail window of an unarmed hand-off, plus the first armed window after unarmed traffic ran) is marked contaminated (`"armed-mid-flight"`). If a test records coverage probes while no Tomcat, Jetty, or Undertow request entry ran (for example on Netty/WebFlux, gRPC, Vert.x, Micronaut, JDK `HttpServer`, Armeria, Helidon, Play, or a server loaded before the agent), the record emits `"unverified":["no-server-entry"]` (omitted when empty, and kept separate from `"contaminated"` so older Enterprise collectors keep measuring uncounted servers while v3 collectors fail closed on any non-empty `"unverified"`). +When Keploy is absent (no collector connected, no `KEPLOY_DEDUP_ATTACH=via-proc` declaration, and no control command received), runtime request counting, executor wrapping, and job/listener tracking remain unarmed (zero-allocation static sentinel token, zero task wrapping); every armed window opened while any pre-arming request or job remains in flight (or within the tail window of an unarmed hand-off, plus the first armed window after unarmed traffic ran) is marked contaminated (`"armed-mid-flight"`). When Keploy launches a replay with a deferred via-proc collector (where the data receiver socket is bound on the first control command rather than before JVM startup), setting `KEPLOY_DEDUP_ATTACH=via-proc` (or system property `-Dkeploy.dedup.attach=via-proc`) arms the runtime gate immediately after binding `/tmp/coverage_control.sock` so pre-test readiness probes complete cleanly without marking the first testcase `"armed-mid-flight"`, while any pre-test request still in flight at `START` still contaminates that window. If a test records coverage probes while no Tomcat, Jetty, or Undertow request entry ran (for example on Netty/WebFlux, gRPC, Vert.x, Micronaut, JDK `HttpServer`, Armeria, Helidon, Play, or a server loaded before the agent), the record emits `"unverified":["no-server-entry"]` (omitted when empty, and kept separate from `"contaminated"` so older Enterprise collectors keep measuring uncounted servers while v3 collectors fail closed on any non-empty `"unverified"`). A scheduled job or message listener that runs while a testcase runs puts its lines in that testcase's coverage: JaCoCo's probes do not say which thread hit them. The agent sees each run of a Quartz job (1.x and 2.x, and Spring's Quartz support), a Spring `@Scheduled` method, and Spring Kafka (`KafkaMessageListenerContainer$ListenerConsumer`), RabbitMQ (`AbstractMessageListenerContainer.doInvokeListener`), and JMS (`AbstractMessageListenerContainer.doInvokeListener`) message listeners. Background HTTP session listeners invoked outside any tracked request or job (such as container session-expiry timers firing `HttpSessionListener`, `HttpSessionAttributeListener`, `HttpSessionBindingListener`, `HttpSessionActivationListener`, `HttpSessionIdListener`, or container-native session listeners across Tomcat 8.5–11, Jetty 9.4–12.1 including `ee8`/`ee9`/`ee10`/`ee11`, and Undertow 2.2–2.3) are hooked alike: overlapping windows are marked `"session-listener:#"` and `asyncExecutors=false` is latched so dedup fails closed, while synchronous in-request `HttpSession.invalidate()` and listener-free session expiries (including Tomcat's default `WsSessionListener` and Undertow's JSR-356 `JsrWebSocketFilter$LogoutListener`, which Spring Boot's Undertow starter registers by default) remain clean. A testcase whose window a run overlapped, from its `START` to the read of its probes at `END` (a job already running at the `START` counts), names the jobs and listeners in `"contaminated":["quartz:." | "scheduled:." | "kafka:@" | "listener:@" | "session-listener:#", ...]` after `windowCut`: at most 8 names, then `"+N"` for N more; left out when none ran. Listener attribution (topic/queue/destination and listener bean class) is inspected once per container instance and cached lock-free. The probes stay in the record; a Keploy that reads the key does not judge that testcase (an older one ignores the key). A job that ends before a `START` is not named: the `START` clears what it ran. The work a job's or listener's run hands to verified executors counts as a run of the same job, with the same name, from when the task starts until it returns or throws, whether or not `END` waits: so a testcase whose window the task runs in is named, even when the job itself returned before that testcase's `START`. Chained re-submissions inherit a 30 s budget from hop 1 so a self-resubmitting loop stops propagating attribution past its budget, while any expired handed-off task that is still executing continues marking overlapping windows `"job-tail:"` until it actually exits. `END` does not wait for it. Limits: work on custom unhooked messaging clients (plain `KafkaConsumer.poll`, `reactor-kafka`, Kafka Streams), a `java.util.Timer`, a Spring `SchedulingConfigurer` plain `Runnable`, a reactive/Kotlin `suspend` `@Scheduled` method, or external session-store adapters that dispatch Servlet session listeners outside the servlet container (such as Spring Session's `SessionEventHttpSessionListenerAdapter` / `HttpSessionAdapter`) is not seen. No job or listener run is seen when the agent was never started as a `-javaagent` in the JVM, nor when the target class loaded before the agent started. diff --git a/keploy-sdk/src/main/java/io/keploy/dedup/KeployDedupAgent.java b/keploy-sdk/src/main/java/io/keploy/dedup/KeployDedupAgent.java index 2a53153..655ccad 100644 --- a/keploy-sdk/src/main/java/io/keploy/dedup/KeployDedupAgent.java +++ b/keploy-sdk/src/main/java/io/keploy/dedup/KeployDedupAgent.java @@ -536,8 +536,9 @@ private static boolean start(CoverageIndex index, Instrumentation instrumentatio startedIndex = index; // Start unarmed (complete no-op when Keploy is absent); armed as soon - // as a collector connects (TCP connect, live unix data socket, or first - // control command/START). + // as a collector connects (TCP connect, live unix data socket, + // KEPLOY_DEDUP_ATTACH=via-proc at unix bind, or first control + // command/START). RequestGate.disarm(); CoverageCollector collector = new CoverageCollector( new JacocoClient(resolveHost(), resolvePort()), index, instrumentation); @@ -924,6 +925,17 @@ private static String resolveEndpoint() { return value.trim().isEmpty() ? null : value.trim(); } + /** + * Returns whether the launcher declared a deferred via-proc collector + * ({@code KEPLOY_DEDUP_ATTACH=via-proc} / {@code -Dkeploy.dedup.attach=via-proc}). + * In via-proc mode the collector binds the data socket only at the first + * command, so the SDK arms {@link RequestGate} immediately after binding + * its Unix control socket before the app serves any pre-test probe traffic. + */ + private static boolean isViaProcAttachDeclared() { + return "via-proc".equalsIgnoreCase(envOrProperty("KEPLOY_DEDUP_ATTACH", "keploy.dedup.attach", "")); + } + private static String envOrProperty(String envKey, String propertyKey, String defaultValue) { String value = System.getenv(envKey); if (value == null || value.trim().isEmpty()) { @@ -1123,8 +1135,10 @@ void bind() throws IOException { throw t; } serverSocket = socket; - // Arm immediately if Keploy's data receiver is already listening. - if (receiverKey(publisher.socketFile) != null) { + // Arm immediately if Keploy's data receiver is already listening, + // or if the launcher declared a via-proc collector will attach + // before tests run (KEPLOY_DEDUP_ATTACH=via-proc). + if (receiverKey(publisher.socketFile) != null || isViaProcAttachDeclared()) { RequestGate.arm(); } } diff --git a/keploy-sdk/src/test/java/io/keploy/dedup/HonestProtocolAndAsyncTest.java b/keploy-sdk/src/test/java/io/keploy/dedup/HonestProtocolAndAsyncTest.java index fbdf785..e23496a 100644 --- a/keploy-sdk/src/test/java/io/keploy/dedup/HonestProtocolAndAsyncTest.java +++ b/keploy-sdk/src/test/java/io/keploy/dedup/HonestProtocolAndAsyncTest.java @@ -99,6 +99,7 @@ public class HonestProtocolAndAsyncTest { private static final String POD_UID_PROPERTY = "keploy.dedup.pod.uid"; private static final String POD_NAME_PROPERTY = "keploy.dedup.pod.name"; private static final String SESSION_ID_PROPERTY = "keploy.dedup.session.id"; + private static final String ATTACH_PROPERTY = "keploy.dedup.attach"; @Rule public TemporaryFolder tmp = new TemporaryFolder(); @@ -172,6 +173,7 @@ public void tearDown() throws IOException { System.clearProperty(POD_UID_PROPERTY); System.clearProperty(POD_NAME_PROPERTY); System.clearProperty(SESSION_ID_PROPERTY); + System.clearProperty(ATTACH_PROPERTY); if (collector != null) { collector.close(); collector = null; @@ -7780,6 +7782,287 @@ protected Class loadClass(String name, boolean resolve) throws ClassNotFoundE }.loadClass(binaryName); } + @Test(timeout = 60000) + public void viaProcAttachArmsAtUnixBindSoCompletedPreTestProbeLeavesFirstWindowClean() throws Exception { + byte[] shopBytes = new byte[] {21, 22, 23}; + File classesDir = tmp.newFolder("viaproc-classes"); + File shop = new File(classesDir, "com/acme/Shop.class"); + shop.getParentFile().mkdirs(); + Files.write(shop.toPath(), shopBytes); + System.setProperty(CLASS_DIRS_PROPERTY, classesDir.getAbsolutePath()); + System.setProperty(JACOCO_PORT_PROPERTY, "1"); + System.setProperty(WARMUP_DISABLED_PROPERTY, "true"); + System.clearProperty(ENDPOINT_PROPERTY); + + KeployDedupAgent.transformerAdded = true; + KeployDedupAgent.executorCallSitesEnabled = true; + ServerEntries.restoreCounted(Collections.emptySet()); + ServerEntries.restoreUncounted(Collections.emptySet()); + ServerEntries.setHookStatusForTests(false, false, false); + + InProcessScanTest.Agent realAgent = new InProcessScanTest.Agent(); + boolean[] probes = realAgent.probes(IndexReport.classId(shopBytes), "com/acme/Shop", 4); + DeferredRtLoader.agent = realAgent; + savedContextLoader = Thread.currentThread().getContextClassLoader(); + Thread.currentThread().setContextClassLoader(new DeferredRtLoader(getClass().getClassLoader())); + + // Case 1: KEPLOY_DEDUP_ATTACH=via-proc with NO data socket bound yet at start() time + // (exact --dedup-via-proc startup sequence). RequestGate must arm at bind() so a + // completed pre-test readiness probe leaves the first testcase window completely clean. + File sockDir = tmp.newFolder("viaproc-clean"); + KeployDedupAgent.controlSocketPath = new File(sockDir, "ctrl.sock").getAbsolutePath(); + KeployDedupAgent.dataSocketPath = new File(sockDir, "data.sock").getAbsolutePath(); + System.setProperty(ATTACH_PROPERTY, "via-proc"); + + org.newsclub.net.unix.AFUNIXServerSocket dataServer = null; + try { + assertTrue(KeployDedupAgent.start()); + assertTrue("via-proc attach declaration must arm RequestGate immediately after Unix bind", + RequestGate.isArmed()); + + // Simulate OSS readiness probe arriving and finishing before the collector binds + // the data socket or sends the first START. + Object probeTok = RequestGate.enter(); + assertFalse("armed pre-test probe must not take the unarmed sentinel path", + RequestGate.isUnarmedToken(probeTok)); + probes[0] = true; + RequestGate.exit(probeTok); + + // Collector now attaches on the first command (via-proc attachApp binds data.sock). + java.util.concurrent.BlockingQueue records = new java.util.concurrent.LinkedBlockingQueue<>(); + dataServer = startUnixDataReceiver(new File(KeployDedupAgent.dataSocketPath), records); + + assertTrue(sendUnixControl("START ts/test-1").startsWith("ACK proto=3")); + Object req1 = RequestGate.enter(); + probes[1] = true; + RequestGate.exit(req1); + assertTrue(sendUnixControl("END ts/test-1").startsWith("ACK proto=3")); + + String rec1 = nextCoverageRecord(records); + assertEquals("{\"id\":\"ts/test-1\",\"executedLinesByFile\":{\"com/acme/Shop\":[1]}}", rec1); + } finally { + KeployDedupAgent.stop(); + if (dataServer != null) { + dataServer.close(); + } + } + + // Case 2: Fail-closed honesty is preserved when a pre-test request is STILL IN FLIGHT + // when START arrives — even with via-proc arming at bind, test-1 must be contaminated. + File sockDir2 = tmp.newFolder("viaproc-inflight"); + KeployDedupAgent.controlSocketPath = new File(sockDir2, "ctrl.sock").getAbsolutePath(); + KeployDedupAgent.dataSocketPath = new File(sockDir2, "data.sock").getAbsolutePath(); + System.setProperty(ATTACH_PROPERTY, "via-proc"); + + org.newsclub.net.unix.AFUNIXServerSocket dataServer2 = null; + Object lingeringTok = null; + try { + assertTrue(KeployDedupAgent.start()); + assertTrue(RequestGate.isArmed()); + + lingeringTok = RequestGate.enter(); + java.util.concurrent.BlockingQueue records2 = new java.util.concurrent.LinkedBlockingQueue<>(); + dataServer2 = startUnixDataReceiver(new File(KeployDedupAgent.dataSocketPath), records2); + + assertTrue(sendUnixControl("START ts/test-inflight").startsWith("ACK proto=3")); + Object req = RequestGate.enter(); + probes[2] = true; + RequestGate.exit(req); + assertTrue(sendUnixControl("END ts/test-inflight").startsWith("ACK proto=3")); + + String rec = nextCoverageRecord(records2); + assertEquals("pre-test request still in flight at START must still contaminate the first window", + "{\"id\":\"ts/test-inflight\",\"executedLinesByFile\":{\"com/acme/Shop\":[2]}," + + "\"contaminated\":[\"tail:prev\"]}", + rec); + } finally { + if (lingeringTok != null) { + RequestGate.exit(lingeringTok); + } + KeployDedupAgent.stop(); + if (dataServer2 != null) { + dataServer2.close(); + } + } + } + + @Test(timeout = 60000) + public void withoutViaProcAttachUnixBindRemainsUnarmedAndPreservesArmedMidFlight() throws Exception { + byte[] shopBytes = new byte[] {31, 32, 33}; + File classesDir = tmp.newFolder("unarmed-classes"); + File shop = new File(classesDir, "com/acme/Shop.class"); + shop.getParentFile().mkdirs(); + Files.write(shop.toPath(), shopBytes); + System.setProperty(CLASS_DIRS_PROPERTY, classesDir.getAbsolutePath()); + System.setProperty(JACOCO_PORT_PROPERTY, "1"); + System.setProperty(WARMUP_DISABLED_PROPERTY, "true"); + System.clearProperty(ENDPOINT_PROPERTY); + + KeployDedupAgent.transformerAdded = true; + KeployDedupAgent.executorCallSitesEnabled = true; + ServerEntries.restoreCounted(Collections.emptySet()); + ServerEntries.restoreUncounted(Collections.emptySet()); + ServerEntries.setHookStatusForTests(false, false, false); + + InProcessScanTest.Agent realAgent = new InProcessScanTest.Agent(); + boolean[] probes = realAgent.probes(IndexReport.classId(shopBytes), "com/acme/Shop", 4); + DeferredRtLoader.agent = realAgent; + savedContextLoader = Thread.currentThread().getContextClassLoader(); + Thread.currentThread().setContextClassLoader(new DeferredRtLoader(getClass().getClassLoader())); + + String[] nonViaProcValues = new String[] {null, "", "true", "tcp", "user", "via-proc-extra"}; + for (int i = 0; i < nonViaProcValues.length; i++) { + String value = nonViaProcValues[i]; + if (value == null) { + System.clearProperty(ATTACH_PROPERTY); + } else { + System.setProperty(ATTACH_PROPERTY, value); + } + File sockDir = tmp.newFolder("unarmed-mode-" + i); + KeployDedupAgent.controlSocketPath = new File(sockDir, "ctrl.sock").getAbsolutePath(); + KeployDedupAgent.dataSocketPath = new File(sockDir, "data.sock").getAbsolutePath(); + + org.newsclub.net.unix.AFUNIXServerSocket dataServer = null; + try { + assertTrue(KeployDedupAgent.start()); + assertFalse("attach value '" + value + "' must leave RequestGate unarmed at Unix bind", + RequestGate.isArmed()); + + // User traffic runs zero-allocation unarmed before any Keploy command arrives. + Object userTok = RequestGate.enter(); + assertTrue("unarmed user traffic must receive static sentinel token for attach=" + value, + RequestGate.isUnarmedToken(userTok)); + RequestGate.exit(userTok); + + // Only check full START/END contamination on the unset (default user-traffic) case + // to keep the loop fast while asserting unarmed semantics for every non-via-proc value. + if (value == null) { + java.util.concurrent.BlockingQueue records = + new java.util.concurrent.LinkedBlockingQueue<>(); + dataServer = startUnixDataReceiver(new File(KeployDedupAgent.dataSocketPath), records); + + assertTrue(sendUnixControl("START ts/test-1").startsWith("ACK proto=3")); + Object req1 = RequestGate.enter(); + probes[1] = true; + RequestGate.exit(req1); + assertTrue(sendUnixControl("END ts/test-1").startsWith("ACK proto=3")); + assertEquals("first window after unarmed user traffic must keep armed-mid-flight", + "{\"id\":\"ts/test-1\",\"executedLinesByFile\":{\"com/acme/Shop\":[1]}," + + "\"contaminated\":[\"armed-mid-flight\"]}", + nextCoverageRecord(records)); + + assertTrue(sendUnixControl("START ts/test-2").startsWith("ACK proto=3")); + Object req2 = RequestGate.enter(); + probes[2] = true; + RequestGate.exit(req2); + assertTrue(sendUnixControl("END ts/test-2").startsWith("ACK proto=3")); + assertEquals("second armed window must be clean after one-time armed-mid-flight", + "{\"id\":\"ts/test-2\",\"executedLinesByFile\":{\"com/acme/Shop\":[2]}}", + nextCoverageRecord(records)); + } + } finally { + KeployDedupAgent.stop(); + if (dataServer != null) { + dataServer.close(); + } + } + } + } + + @Test(timeout = 60000) + public void viaProcAttachReadsEnvironmentVariableInChildJvm() throws Exception { + String javaBin = new File(System.getProperty("java.home"), "bin/java").getAbsolutePath(); + String cp = System.getProperty("java.class.path"); + + for (boolean declareViaProc : new boolean[] {true, false}) { + File sockDir = tmp.newFolder("viaproc-env-" + declareViaProc); + ProcessBuilder pb = new ProcessBuilder( + javaBin, "-cp", cp, ViaProcEnvProbe.class.getName(), + new File(sockDir, "ctrl.sock").getAbsolutePath(), + new File(sockDir, "data.sock").getAbsolutePath()); + pb.redirectErrorStream(true); + pb.environment().remove("KEPLOY_COVERAGE_ENDPOINT"); + if (declareViaProc) { + pb.environment().put("KEPLOY_DEDUP_ATTACH", "via-proc"); + } else { + pb.environment().remove("KEPLOY_DEDUP_ATTACH"); + } + Process proc = pb.start(); + StringBuilder out = new StringBuilder(); + try (BufferedReader r = new BufferedReader( + new InputStreamReader(proc.getInputStream(), StandardCharsets.UTF_8))) { + String line; + while ((line = r.readLine()) != null) { + out.append(line).append('\n'); + } + } + assertTrue("child JVM exited promptly", proc.waitFor(30, TimeUnit.SECONDS)); + assertEquals("child JVM rc=0, output=" + out, 0, proc.exitValue()); + String want = "ARMED=" + declareViaProc; + assertTrue("expected '" + want + "' in child JVM output, got:\n" + out, + out.toString().contains(want)); + } + } + + private static org.newsclub.net.unix.AFUNIXServerSocket startUnixDataReceiver( + File socketFile, java.util.concurrent.BlockingQueue records) throws IOException { + org.newsclub.net.unix.AFUNIXServerSocket server = org.newsclub.net.unix.AFUNIXServerSocket.newInstance(); + server.bind(org.newsclub.net.unix.AFUNIXSocketAddress.of(socketFile)); + Thread reader = new Thread(() -> { + while (!server.isClosed()) { + try (Socket conn = server.accept(); + BufferedReader r = new BufferedReader( + new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8))) { + StringBuilder sb = new StringBuilder(); + String l; + while ((l = r.readLine()) != null) { + sb.append(l); + } + if (sb.length() > 0) { + records.add(sb.toString()); + } + } catch (IOException ignored) { + } + } + }, "unix-viaproc-data-reader"); + reader.setDaemon(true); + reader.start(); + return server; + } + + private static String nextCoverageRecord(java.util.concurrent.BlockingQueue records) + throws InterruptedException { + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(10); + while (System.nanoTime() < deadline) { + long remMs = Math.max(1L, TimeUnit.NANOSECONDS.toMillis(deadline - System.nanoTime())); + String rec = records.poll(remMs, TimeUnit.MILLISECONDS); + if (rec == null) { + break; + } + if (!rec.contains("\"kind\":\"index\"") && !rec.contains("\"kind\":\"background\"")) { + return rec; + } + } + return null; + } + + public static final class ViaProcEnvProbe { + public static void main(String[] args) { + KeployDedupAgent.controlSocketPath = args[0]; + KeployDedupAgent.dataSocketPath = args[1]; + System.setProperty(WARMUP_DISABLED_PROPERTY, "true"); + try { + if (!KeployDedupAgent.start()) { + System.err.println("KeployDedupAgent.start() returned false"); + System.exit(2); + } + System.out.println("ARMED=" + RequestGate.isArmed()); + } finally { + KeployDedupAgent.stop(); + } + } + } + // Simulates org.jacoco.agent.rt.RT being on the classpath before its // premain starts the agent: getAgent() throws IllegalStateException while // DeferredRtLoader.agent is null, then returns the live agent once set.