diff --git a/dd-java-agent/benchmark-integration/kafka/AnalyzeLateAttach.java b/dd-java-agent/benchmark-integration/kafka/AnalyzeLateAttach.java new file mode 100644 index 00000000000..21ad9d755bf --- /dev/null +++ b/dd-java-agent/benchmark-integration/kafka/AnalyzeLateAttach.java @@ -0,0 +1,270 @@ +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.TreeMap; +import java.util.TreeSet; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +/** + * Summarizes a run-late-attach.sh results directory: {@code java AnalyzeLateAttach.java }. + * + *

For each run it looks at two events, both in JVM uptime: + * + *

+ * + *

Around each event it reports the JIT's invalidations ({@code made not entrant}) of Kafka, + * tracer and benchmark methods, and the throughput cost against a reference rate: the lowest second + * after, the records lost in the 30 s after (in seconds of throughput), and how long until three + * seconds in a row are back within 3% of the reference. For the late event the reference is the 30 + * s before it. For the attach it is the settled rate with the agent, since the tracer's steady + * overhead isn't a warm-up cost. + */ +public class AnalyzeLateAttach { + private static final long WINDOW_BEFORE_MS = 30_000; + private static final long INVALIDATION_WINDOW_MS = 10_000; + private static final long RECOVERY_LIMIT_MS = 60_000; + private static final double RECOVERED = 0.97; + private static final Pattern RELEVANT = + Pattern.compile("org\\.apache\\.kafka|datadog|LateAttachConsumer"); + private static final Pattern JIT_LINE = Pattern.compile("^\\s*(\\d+)\\s+\\d+\\s+(.*)$"); + + public static void main(String[] args) throws IOException { + Path dir = Paths.get(args[0]); + long attachAfterMs = attachAfterMs(dir.resolve("config.txt")); + Map> byVariant = new TreeMap<>(); + try (Stream files = Files.list(dir.resolve("runs"))) { + for (Path csv : files.filter(p -> p.toString().endsWith(".csv")).sorted().collect( + Collectors.toList())) { + String tag = csv.getFileName().toString().replace(".csv", ""); + Run run = Run.load(dir.resolve("runs"), tag, attachAfterMs); + byVariant.computeIfAbsent(tag.substring(tag.indexOf('-') + 1), k -> new ArrayList<>()) + .add(run); + } + } + + System.out.println(); + System.out.printf( + "%-14s %-6s %-7s %9s %9s %9s %8s %8s %6s %s%n", + "run", "event", "at(s)", "before/s", "min/s", "lost(s)", "recover", "invalid", "app?", + "late cause"); + for (List runs : byVariant.values()) { + for (Run run : runs) { + run.print(); + } + } + + System.out.println(); + System.out.println("Invalidated Kafka/tracer/benchmark methods in the 10 s after each event" + + " (runs that saw each one):"); + for (Map.Entry> variant : byVariant.entrySet()) { + for (String event : new String[] {"attach", "late"}) { + Map counts = new TreeMap<>(); + for (Run run : variant.getValue()) { + for (String method : run.invalidated(event)) { + counts.merge(method, 1, Integer::sum); + } + } + if (counts.isEmpty()) { + continue; + } + System.out.println(" " + variant.getKey() + " / " + event + ":"); + counts.forEach((m, c) -> System.out.println(" " + c + "x " + m)); + } + } + } + + private static long attachAfterMs(Path config) throws IOException { + Matcher m = Pattern.compile("attach_after=(\\d+)").matcher(new String(Files.readAllBytes(config))); + return m.find() ? Long.parseLong(m.group(1)) * 1000 : 60_000; + } + + static final class Run { + final String tag; + final TreeMap perSecond = new TreeMap<>(); + final List invalidations = new ArrayList<>(); // {uptime ms, index into methods} + final List invalidatedMethods = new ArrayList<>(); + Long attach; + Long late; + String lateCause = "-"; + + private Run(String tag) { + this.tag = tag; + } + + static Run load(Path runs, String tag, long attachAfterMs) throws IOException { + Run run = new Run(tag); + for (String line : lines(runs.resolve(tag + ".csv"))) { + if (line.isEmpty() || line.startsWith("uptime")) { + continue; + } + String[] f = line.split(","); + run.perSecond.put(Long.parseLong(f[0]), Long.parseLong(f[1])); + } + Long headerAccess = null; + for (String line : lines(runs.resolve(tag + ".events"))) { + String[] f = line.split(" "); + if (f[0].equals("agent")) { + run.attach = Long.parseLong(f[1]); + } else if (f[0].equals("header-access") && f[1].equals("AVAILABLE")) { + headerAccess = Long.parseLong(f[2]); + } + } + long from = run.attach != null ? run.attach : attachAfterMs; + Long refresh = firstRefreshAfter(runs.resolve(tag + ".metadata"), from); + if (headerAccess != null) { + run.late = headerAccess; + run.lateCause = "RecordHeaderAccess AVAILABLE" + + (refresh != null ? String.format(" (refresh at %.1f s)", refresh / 1000.0) : ""); + } else if (refresh != null) { + run.late = refresh; + run.lateCause = "metadata refresh"; + } + for (String line : lines(runs.resolve(tag + ".jit"))) { + if (!line.contains("made not entrant")) { + continue; + } + Matcher m = JIT_LINE.matcher(line); + if (!m.matches()) { + continue; + } + String method = m.group(2).replace("made not entrant", "").replaceAll("\\s+", " ").trim(); + run.invalidations.add(new long[] {Long.parseLong(m.group(1)), run.invalidatedMethods.size()}); + run.invalidatedMethods.add(method); + } + return run; + } + + /** The first metadata update at or after {@code from}, shifted from log4j's clock to uptime. */ + private static Long firstRefreshAfter(Path metadata, long from) throws IOException { + Long offset = null; + List updates = new ArrayList<>(); + for (String line : lines(metadata)) { + String[] f = line.split(" ", 2); + if (f.length < 2 || !f[0].matches("\\d+")) { + continue; + } + long logged = Long.parseLong(f[0]); + if (f[1].startsWith("uptime-sync ")) { + offset = Long.parseLong(f[1].substring("uptime-sync ".length()).trim()) - logged; + } else if (f[1].contains("Updated cluster metadata")) { + updates.add(logged); + } + } + if (offset == null) { + return null; + } + for (long logged : updates) { + if (logged + offset >= from) { + return logged + offset; + } + } + return null; + } + + private static List lines(Path file) throws IOException { + return Files.exists(file) ? Files.readAllLines(file) : new ArrayList<>(); + } + + TreeSet invalidated(String event) { + Long at = event.equals("attach") ? attach : late; + TreeSet methods = new TreeSet<>(); + if (at == null) { + return methods; + } + for (long[] inv : invalidations) { + String method = invalidatedMethods.get((int) inv[1]); + if (inv[0] >= at - 1000 && inv[0] <= at + INVALIDATION_WINDOW_MS + && RELEVANT.matcher(method).find()) { + methods.add(stripCompileId(method)); + } + } + return methods; + } + + /** Drops PrintCompilation's attribute flags and tier, leaving the method and its size. */ + private static String stripCompileId(String method) { + return method.replaceFirst("^[%sbn! ]*\\d\\s+", ""); + } + + void print() { + // The attach is measured against the settled rate with the agent (the 30 s before the late + // event, or 60-90 s after the attach), not the rate before it: the tracer's steady overhead + // isn't a warm-up cost. The late event is measured against the 30 s before it. + double settled = Double.NaN; + if (late != null) { + settled = median(rates(late - WINDOW_BEFORE_MS, late)); + } else if (attach != null) { + settled = median(rates(attach + 60_000, attach + 90_000)); + } + printEvent("attach", attach, settled, "-"); + printEvent( + "late", late, late == null ? Double.NaN : median(rates(late - WINDOW_BEFORE_MS, late)), + lateCause); + } + + private void printEvent(String event, Long at, double base, String cause) { + if (at == null || Double.isNaN(base)) { + System.out.printf("%-14s %-6s %7s%n", tag, event, "-"); + return; + } + long min = Long.MAX_VALUE; + double lost = 0; + for (Map.Entry s : perSecond.subMap(at, true, at + 30_000, true).entrySet()) { + min = Math.min(min, s.getValue()); + lost += Math.max(0, base - s.getValue()) / base; + } + String recover = recovery(at, base); + TreeSet methods = invalidated(event); + boolean app = methods.stream().anyMatch(m -> m.contains("LateAttachConsumer")); + System.out.printf( + "%-14s %-6s %7.1f %9.0f %9s %9.2f %8s %8d %6s %s%n", + tag, event, at / 1000.0, base, min == Long.MAX_VALUE ? "-" : Long.toString(min), lost, + recover, methods.size(), app ? "yes" : "no", cause); + } + + /** Seconds until three seconds in a row are within 3% of {@code base}, or "> 60s". */ + private String recovery(long at, double base) { + List> after = + new ArrayList<>(perSecond.subMap(at, true, at + RECOVERY_LIMIT_MS, true).entrySet()); + for (int i = 0; i + 2 < after.size(); i++) { + if (after.get(i).getValue() >= RECOVERED * base + && after.get(i + 1).getValue() >= RECOVERED * base + && after.get(i + 2).getValue() >= RECOVERED * base) { + return String.format("%.0fs", (after.get(i).getKey() - at) / 1000.0); + } + } + return "> 60s"; + } + + private long[] rates(long from, long to) { + return perSecond.subMap(from, true, to, false).values().stream().mapToLong(Long::longValue) + .toArray(); + } + + private static double median(long[] values) { + if (values.length == 0) { + return Double.NaN; + } + long[] sorted = values.clone(); + Arrays.sort(sorted); + int mid = sorted.length / 2; + return sorted.length % 2 == 1 ? sorted[mid] : (sorted[mid - 1] + sorted[mid]) / 2.0; + } + } + + private AnalyzeLateAttach() {} +} diff --git a/dd-java-agent/benchmark-integration/kafka/Attach.java b/dd-java-agent/benchmark-integration/kafka/Attach.java new file mode 100644 index 00000000000..be893440a6e --- /dev/null +++ b/dd-java-agent/benchmark-integration/kafka/Attach.java @@ -0,0 +1,19 @@ +import com.sun.tools.attach.VirtualMachine; + +/** + * Loads a Java agent into a running JVM: {@code java Attach.java }. + * + *

The late-attach benchmark uses it to attach the tracer to an already-warm consumer. + */ +public class Attach { + public static void main(String[] args) throws Exception { + VirtualMachine vm = VirtualMachine.attach(args[0]); + try { + vm.loadAgent(args[1]); + } finally { + vm.detach(); + } + } + + private Attach() {} +} diff --git a/dd-java-agent/benchmark-integration/kafka/LateAttachConsumer.java b/dd-java-agent/benchmark-integration/kafka/LateAttachConsumer.java new file mode 100644 index 00000000000..b6647dd0b67 --- /dev/null +++ b/dd-java-agent/benchmark-integration/kafka/LateAttachConsumer.java @@ -0,0 +1,174 @@ +import java.io.FileWriter; +import java.io.PrintWriter; +import java.lang.management.ManagementFactory; +import java.lang.reflect.Field; +import java.time.Duration; +import java.util.Collections; +import java.util.List; +import java.util.Properties; +import org.apache.kafka.clients.consumer.ConsumerConfig; +import org.apache.kafka.clients.consumer.ConsumerRecord; +import org.apache.kafka.clients.consumer.ConsumerRecords; +import org.apache.kafka.clients.consumer.KafkaConsumer; +import org.apache.kafka.common.TopicPartition; +import org.apache.kafka.common.serialization.ByteArrayDeserializer; +import org.slf4j.LoggerFactory; + +/** + * Consumer for the late-attach benchmark: reads the pre-filled topic in a loop (seeking back to the + * start at its end) for a fixed time, so an agent attached mid-run meets an already-warm consumer. + * + *

Writes one CSV row per second of JVM uptime ({@code uptime_ms,records}) to the series file, and + * one line per event to the events file, both in JVM uptime milliseconds, which is close to the clock + * {@code -XX:+PrintCompilation} timestamps use: + * + *

+ * + *

Per-record work is in {@link #process}, a method of its own, as in an application: under the + * agent, the tracing iterator and header extraction inline into it, so it is the compiled unit that + * a later invalidation of that code throws away. + * + *

Usage: {@code java -cp "kafka/libs/*" LateAttachConsumer.java bootstrap topic seconds + * metadataMaxAgeMs seriesFile eventsFile} + */ +public class LateAttachConsumer { + private static final String HEADER_ACCESS_CLASS = + "datadog.trace.instrumentation.kafka_clients38.RecordHeaderAccess"; + private static final String TRACER_BOOTSTRAP_CLASS = + "datadog.trace.bootstrap.instrumentation.api.AgentTracer"; + + private static long checksum; + + public static void main(String[] args) throws Exception { + String bootstrap = args[0]; + String topic = args[1]; + long runMillis = Long.parseLong(args[2]) * 1000; + String metadataMaxAgeMs = args[3]; + + Properties props = new Properties(); + props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrap); + props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, ByteArrayDeserializer.class.getName()); + props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, ByteArrayDeserializer.class.getName()); + props.put(ConsumerConfig.METADATA_MAX_AGE_CONFIG, metadataMaxAgeMs); + props.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, "false"); + props.put(ConsumerConfig.MAX_POLL_RECORDS_CONFIG, "500"); + + try (PrintWriter series = new PrintWriter(new FileWriter(args[4])); + PrintWriter events = new PrintWriter(new FileWriter(args[5])); + KafkaConsumer consumer = new KafkaConsumer<>(props)) { + // assign, not subscribe: no group, so no rebalances, and the only metadata refreshes are the + // periodic ones metadata.max.age.ms sets. + List partitions = Collections.singletonList(new TopicPartition(topic, 0)); + consumer.assign(partitions); + consumer.seekToBeginning(partitions); + series.println("uptime_ms,records"); + // Through the metadata logger, so its file carries one line that maps log4j's clock (%r) + // onto JVM uptime. + LoggerFactory.getLogger("org.apache.kafka.clients.Metadata").debug("uptime-sync " + uptime()); + + long start = uptime(); + long nextReport = (start / 1000 + 1) * 1000; + long interval = 0; + boolean agentSeen = false; + Object headerAccess = null; + while (true) { + ConsumerRecords records = consumer.poll(Duration.ofMillis(100)); + if (records.isEmpty()) { + consumer.seekToBeginning(partitions); + continue; + } + interval += process(records); + long now = uptime(); + if (now >= nextReport) { + series.println(nextReport + "," + interval); + series.flush(); + interval = 0; + nextReport += 1000; + if (!agentSeen && loaded(TRACER_BOOTSTRAP_CLASS, null) != null) { + agentSeen = true; + event(events, "agent " + now); + } + if (agentSeen) { + Object state = headerAccessState(consumer.getClass().getClassLoader()); + if (state != headerAccess) { + headerAccess = state; + event(events, "header-access " + describe(state) + " " + now); + } + } + if (now - start >= runMillis) { + break; + } + } + } + } + System.out.println("checksum " + checksum); + } + + /** Per-batch work: iterate the records, as an application does, and touch each value. */ + private static long process(ConsumerRecords records) { + long count = 0; + for (ConsumerRecord record : records) { + byte[] value = record.value(); + checksum += value == null ? 0 : value.length; + count++; + } + return count; + } + + private static long uptime() { + return ManagementFactory.getRuntimeMXBean().getUptime(); + } + + private static void event(PrintWriter events, String line) { + events.println(line); + events.flush(); + } + + private static Class loaded(String name, ClassLoader loader) { + try { + return Class.forName(name, false, loader); + } catch (ClassNotFoundException | LinkageError e) { + return null; + } + } + + /** {@code RecordHeaderAccess.access}, or null while that class or its setup is absent. */ + private static Object headerAccessState(ClassLoader loader) { + Class type = loaded(HEADER_ACCESS_CLASS, loader); + if (type == null) { + return null; + } + try { + Field access = type.getDeclaredField("access"); + access.setAccessible(true); + return access.get(null); + } catch (ReflectiveOperationException | RuntimeException e) { + return null; + } + } + + /** AVAILABLE or UNAVAILABLE, by identity against the class's own constants. */ + private static String describe(Object state) { + if (state == null) { + return "none"; + } + for (String name : new String[] {"AVAILABLE", "UNAVAILABLE"}) { + try { + Field constant = state.getClass().getDeclaredField(name); + constant.setAccessible(true); + if (constant.get(null) == state) { + return name; + } + } catch (ReflectiveOperationException | RuntimeException e) { + // not a constant of that name + } + } + return "set"; + } + + private LateAttachConsumer() {} +} diff --git a/dd-java-agent/benchmark-integration/kafka/run-late-attach.sh b/dd-java-agent/benchmark-integration/kafka/run-late-attach.sh new file mode 100755 index 00000000000..5c1f5d4d74a --- /dev/null +++ b/dd-java-agent/benchmark-integration/kafka/run-late-attach.sh @@ -0,0 +1,131 @@ +#!/usr/bin/env bash +# Late-attach benchmark: starts a consumer with no agent, lets it warm up, attaches each variant's +# agent to the running JVM, and keeps consuming past the consumer's next periodic metadata refresh. +# It records throughput per second and the JIT's invalidations, to show what attaching costs a +# warm application and whether anything throws compiled code away again later, after warm-up. +# +# ./run-late-attach.sh NoAgent master=path/a.jar candidate=path/b.jar ... +# +# Needs the broker and the prefilled topic from broker.sh / prefill.sh. NoAgent runs the same +# consumer without attaching, as the drift baseline. +# +# Each run writes, under RESULTS_DIR/runs: +# .csv throughput per second of JVM uptime +# .events when the attach landed, and RecordHeaderAccess state changes (#13737 only) +# .jit -XX:+PrintCompilation output (made-not-entrant lines are the invalidations) +# .metadata the consumer's metadata updates (Kafka's DEBUG log), in JVM uptime ms +# +# Env: ATTACH_AFTER (60, seconds of warm-up before attaching), DURATION (480, seconds per run; it +# must reach past ATTACH_AFTER + METADATA_MAX_AGE_MS to see the refresh), METADATA_MAX_AGE_MS +# (300000, Kafka's default), HEAP (256m), REPS (3), RESULTS_DIR. The consumer's JDK is the one +# common.sh picks; the kafka-clients-3.8 instrumentation needs 17+. +set -euo pipefail +source "$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/common.sh" +require_kafka +[ "$#" -gt 0 ] || { echo "usage: $0 NoAgent label=agent.jar ..." >&2; exit 1; } + +attach_after="${ATTACH_AFTER:-60}" +duration="${DURATION:-480}" +max_age="${METADATA_MAX_AGE_MS:-300000}" +heap="${HEAP:-256m}" +if [ $((attach_after * 1000 + max_age)) -ge $((duration * 1000)) ]; then + log "ERROR: DURATION ($duration s) must exceed ATTACH_AFTER + METADATA_MAX_AGE_MS" \ + "($attach_after s + $max_age ms) to reach the first refresh after the attach" + exit 1 +fi + +results="${RESULTS_DIR:-$WORK_DIR/results/late-attach-$(date +%Y%m%d-%H%M%S)}" +mkdir -p "$results/runs" + +# Kafka's metadata updates, at DEBUG, timed in ms since log4j started (%r). The consumer logs its +# JVM uptime through the same logger at startup, so the analysis can shift %r onto uptime. +log4j_config="$results/late-attach-log4j.properties" +cat > "$log4j_config" <<'EOF' +log4j.rootLogger=WARN, stderr +log4j.appender.stderr=org.apache.log4j.ConsoleAppender +log4j.appender.stderr.layout=org.apache.log4j.PatternLayout +log4j.appender.stderr.layout.ConversionPattern=[%d] %p %m (%c)%n +log4j.appender.stderr.Target=System.err +log4j.logger.org.apache.kafka.clients.Metadata=DEBUG, metadata +log4j.additivity.org.apache.kafka.clients.Metadata=false +log4j.appender.metadata=org.apache.log4j.FileAppender +log4j.appender.metadata.File=${late.attach.metadata.file} +log4j.appender.metadata.layout=org.apache.log4j.PatternLayout +log4j.appender.metadata.layout.ConversionPattern=%r %m%n +EOF + +{ + echo "attach_after=$attach_after duration=$duration metadata_max_age_ms=$max_age heap=$heap" + java -version 2>&1 | head -1 + for v in "$@"; do echo "variant $v"; done +} > "$results/config.txt" + +# Without an Agent on TRACE_AGENT_PORT, every trace send would fail. Unless something already +# listens there, start the shared Agent stub (../agent-stub), which serves a real Agent's /info so the +# tracer computes client-side stats and drops unsampled traces as it would in production. +stub_pid="" +if ! (exec 3<>"/dev/tcp/127.0.0.1/$TRACE_AGENT_PORT") 2>/dev/null; then + stub_dir="$script_dir/../agent-stub" + java "$stub_dir/AgentStub.java" "$TRACE_AGENT_PORT" "$stub_dir/agent-info.json" \ + > "$results/agent-stub.log" 2>&1 & + stub_pid=$! + trap '[ -n "$stub_pid" ] && kill "$stub_pid" 2>/dev/null || true' EXIT + for _ in $(seq 1 30); do + (exec 3<>"/dev/tcp/127.0.0.1/$TRACE_AGENT_PORT") 2>/dev/null && break + sleep 1 + done + log "no Agent on port $TRACE_AGENT_PORT; started a stub (pid $stub_pid)" +fi + +# JDK 21+ warns on a dynamically loaded agent unless it's allowed up front; earlier JDKs reject the +# flag. +java_major="$(java -XshowSettings:properties -version 2>&1 \ + | awk -F' = ' '/java.specification.version/ {print $2}')" +dynamic_agent_opt="" +if [ "${java_major%%.*}" -ge 21 ] 2>/dev/null; then + dynamic_agent_opt="-XX:+EnableDynamicAgentLoading" +fi + +variants=("$@") +n=${#variants[@]} +for rep in $(seq 1 "${REPS:-3}"); do + rot=$(((rep - 1) % n)) + order=("${variants[@]:$rot}" "${variants[@]:0:$rot}") + for v in "${order[@]}"; do + parse_variant "$v" + tag="r$rep-$VARIANT_LABEL" + run="$results/runs/$tag" + # The agent's settings go in as system properties at JVM start: the tracer reads them when it + # initializes after the attach. -javaagent is dropped, since the agent arrives later. + agent_props="" + if [ "$VARIANT_JAR" != NoAgent ]; then + agent_props="$(variant_opts "$VARIANT_JAR" | sed 's/-javaagent:[^ ]*//')" + fi + log "$tag: warm-up ${attach_after}s, then attach; run ${duration}s" + # shellcheck disable=SC2086 # agent_props is a list of JVM options + java "-Xms$heap" "-Xmx$heap" -XX:+PrintCompilation $dynamic_agent_opt \ + "-Xlog:gc:file=$run.gc" "-Dlog4j.configuration=file:$log4j_config" \ + "-Dlate.attach.metadata.file=$run.metadata" $agent_props \ + -cp "$KAFKA_HOME/libs/*" "$script_dir/LateAttachConsumer.java" \ + "$BOOTSTRAP" "$CONSUME_TOPIC" "$duration" "$max_age" "$run.csv" "$run.events" \ + > "$run.jit" 2> "$run.err" & + pid=$! + if [ "$VARIANT_JAR" != NoAgent ]; then + sleep "$attach_after" + if ! java "$script_dir/Attach.java" "$pid" "$VARIANT_JAR" >> "$run.err" 2>&1; then + log "FAIL $tag: attach failed (see $run.err)" + fi + fi + status=0 + wait "$pid" || status=$? + if [ "$status" -ne 0 ]; then + log "FAIL $tag: consumer exit $status (see $run.err)" + fi + done +done +if [ -n "$stub_pid" ]; then + # What the stub received, per endpoint: a variant whose traces never arrived would show up here. + curl -fsS "http://127.0.0.1:$TRACE_AGENT_PORT/_stats" > "$results/agent-stub-stats.txt" 2>/dev/null || true +fi +log "results: $results" +java "$script_dir/AnalyzeLateAttach.java" "$results"