Skip to content
Draft
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
270 changes: 270 additions & 0 deletions dd-java-agent/benchmark-integration/kafka/AnalyzeLateAttach.java
Original file line number Diff line number Diff line change
@@ -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 <dir>}.
*
* <p>For each run it looks at two events, both in JVM uptime:
*
* <ul>
* <li><b>attach</b>: when the agent's classes became visible. Every agent pays this one: it
* retransforms the Kafka classes the warm consumer already uses.
* <li><b>late</b>: the first thing after the attach that can throw compiled code away again:
* {@code RecordHeaderAccess} becoming available (#13737), or else the first metadata refresh
* after the attach, the moment #13737 would flip, so other agents get the same window.
* </ul>
*
* <p>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<String, List<Run>> byVariant = new TreeMap<>();
try (Stream<Path> 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<Run> 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<String, List<Run>> variant : byVariant.entrySet()) {
for (String event : new String[] {"attach", "late"}) {
Map<String, Integer> 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<Long, Long> perSecond = new TreeMap<>();
final List<long[]> invalidations = new ArrayList<>(); // {uptime ms, index into methods}
final List<String> 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<Long> 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<String> lines(Path file) throws IOException {
return Files.exists(file) ? Files.readAllLines(file) : new ArrayList<>();
}

TreeSet<String> invalidated(String event) {
Long at = event.equals("attach") ? attach : late;
TreeSet<String> 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<Long, Long> 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<String> 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<Map.Entry<Long, Long>> 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() {}
}
19 changes: 19 additions & 0 deletions dd-java-agent/benchmark-integration/kafka/Attach.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import com.sun.tools.attach.VirtualMachine;

/**
* Loads a Java agent into a running JVM: {@code java Attach.java <pid> <agent.jar>}.
*
* <p>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() {}
}
Loading
Loading