diff --git a/README.md b/README.md index ff47b2e..3eb66d9 100644 --- a/README.md +++ b/README.md @@ -63,6 +63,7 @@ files. | [`startup-runners/`](startup-runners) | [CommandLineRunner vs ApplicationRunner vs ApplicationReadyEvent in Spring Boot 4](https://ankurm.com/commandlinerunner-vs-applicationrunner-vs-applicationreadyevent-spring-boot-4/) | the real order of every startup hook printed from a running app, one shared sort for both runner types with arbitrary ties, runner failure vs `ApplicationReadyEvent` listener failure (exit codes, `ApplicationFailedEvent`), a blocking runner holding readiness at 503, `SmartLifecycle` phases, and which hooks `@SpringBootTest` and `@WebMvcTest` run | | [`mapstruct/`](mapstruct) | [MapStruct with Spring Boot 4 and Java Records: DTO Mapping Done Right](https://ankurm.com/mapstruct-spring-boot-4-java-records-dto-mapping/) | records as source and target, nested and collection mapping, null strategies, `@AfterMapping` and `@DecoratedWith`, real compile-time error text for broken mappers, three ways to test a mapper, and an indicative comparison with hand-written code and Dozer | | [`secrets/`](secrets) | [Secrets in Spring Boot: Vault vs AWS Secrets Manager vs Kubernetes Secrets vs Jasypt](https://ankurm.com/spring-boot-secrets-management-vault-aws-kubernetes-jasypt/) | `spring.config.import` against a real Vault 2.2.1 (Spring Cloud Vault 5.0.3 on Boot 4.1.2): a missing path, a wrong token and an unreachable Vault all start the app with `db.password` unset unless `spring.cloud.vault.fail-fast=true` (and a missing path even then); a rotation in Vault invisible until `ContextRefresher.refresh()`, which updates the Environment and a `@RefreshScope` bean but not a record-bound `@ConfigurationProperties`; a least-privilege token; AWS Secrets Manager (Spring Cloud AWS 4.2.1, run against the moto emulator, not AWS) where a missing secret fails startup but `optional:` hides it and the 1 s polling reload never fired; Kubernetes Secrets as a kubelet-layout config tree that keeps its old value after the volume swap until a refresh; Jasypt 4.0.4 `ENC(...)` decrypted by anyone holding the ciphertext and the key; actuator `show-values=ALWAYS`; secrets in the jar, in `ps` and in `/proc//environ`; and `@DynamicPropertySource` arriving after the Vault import | +| [`otel-agent-vs-micrometer/`](otel-agent-vs-micrometer) | [OpenTelemetry Java Agent vs Micrometer Tracing in Spring Boot 4: Zero-Code vs In-Code](https://ankurm.com/opentelemetry-java-agent-vs-micrometer-tracing-spring-boot-4/) | one orders app built twice (no tracing dependency + `-javaagent` 2.34.0, and `spring-boot-starter-opentelemetry`) exporting OTLP to a decoding receiver: span trees, attribute keys and metric names side by side, `management.observations.conventions=opentelemetry` on 4.2.0, spans lost across a plain thread pool, JDBC spans via the agent vs a third-party library, both at once, startup/CPU cost | `core-di`, `core-beans`, `custom-starter`, `core-events`, `multi-datasource`, `i18n`, `aot-cache`, `kotlin`, `testing-no-containers`, `rest-test-client` and `hexagonal` are the exception: they have **no `docs/NN-topic.md` chapter folder**. Their deeper material lives in collapsible sections inside the articles themselves. Where their captured output sits is not diff --git a/otel-agent-vs-micrometer/.gitignore b/otel-agent-vs-micrometer/.gitignore new file mode 100644 index 0000000..f9d8e29 --- /dev/null +++ b/otel-agent-vs-micrometer/.gitignore @@ -0,0 +1,3 @@ +dist/ +target/ +.tmp-norest/ diff --git a/otel-agent-vs-micrometer/README.md b/otel-agent-vs-micrometer/README.md new file mode 100644 index 0000000..929bcdb --- /dev/null +++ b/otel-agent-vs-micrometer/README.md @@ -0,0 +1,63 @@ +# otel-agent-vs-micrometer + +One Spring Boot 4.2.0 application ("orders": a controller, a JDBC repository, an outgoing `RestClient` +call, a business method and a hand-off to another thread), instrumented two ways and compared with +real exports to a local OTLP receiver: + +* **Agent** - the unmodified `orders-plain.jar` (no tracing dependency) started with + `-javaagent:opentelemetry-javaagent.jar` (2.34.0). +* **Micrometer** - the same source built with `-Pmicrometer`, which adds + `spring-boot-starter-opentelemetry` (Micrometer Tracing + the OpenTelemetry SDK + OTLP export). + +Companion to the post +[OpenTelemetry Java Agent vs Micrometer Tracing in Spring Boot 4: Zero-Code vs In-Code](https://ankurm.com/opentelemetry-java-agent-vs-micrometer-tracing-spring-boot-4/). + +## Versions + +| Component | Version | +|---|---| +| Spring Boot | 4.2.0 (GA 19 Nov 2026) | +| Micrometer / Micrometer Tracing / OpenTelemetry SDK (Boot BOM) | 1.18.0 / 1.8.0 / 1.68.0 | +| OpenTelemetry Java agent | 2.34.0 | +| `datasource-micrometer-spring-boot` (third party, one scenario) | 2.3.1 | +| `opentelemetry-proto` (sink only) | 1.11.1-alpha | +| JDK | Temurin 25.0.5.1 | + +## Layout + +| Path | What it is | +|---|---| +| [`app/`](app) | the Spring Boot application; profile `micrometer` and `jdbc` switch the variant | +| [`sink/`](sink) | `OtlpSink`: a small OTLP/HTTP protobuf receiver that decodes spans and metrics and serves them as text | +| [`driver/LoadDriver.java`](driver/LoadDriver.java) | closed-loop load generator used for the overhead run | +| [`scripts/lib.sh`](scripts/lib.sh) | build, start and stop helpers, and the exact JVM flags for each variant | +| [`scripts/run-all.sh`](scripts/run-all.sh) | regenerates every file in `output/` | +| [`scripts/overhead.sh`](scripts/overhead.sh) | the startup/CPU/throughput measurement (file 08) | +| [`scripts/restclient-missing.sh`](scripts/restclient-missing.sh) | reproduces the missing `RestClient.Builder` failure (file 10) | + +## Run it + +```bash +export JAVA_HOME= # Maven 3.9, curl and network access to Maven Central are needed +scripts/run-all.sh # builds three jars, runs every scenario, writes output/ +``` + +Ports 18480 (app) and 14418 (sink) are used so that it does not collide with anything on 8080/4318. + +## Captured output + +| File | Scenario | +|---|---| +| [`01-agent-spans.txt`](output/01-agent-spans.txt) | agent: span tree and attribute keys | +| [`02-micrometer-spans.txt`](output/02-micrometer-spans.txt) | Micrometer, default conventions | +| [`03-micrometer-otel-conventions.txt`](output/03-micrometer-otel-conventions.txt) | Micrometer with `management.observations.conventions=opentelemetry` | +| [`04-metrics.txt`](output/04-metrics.txt) | every metric each approach exported, by instrumentation scope | +| [`05-thread-handoff.txt`](output/05-thread-handoff.txt) | context across a thread pool: agent, raw pool, Spring task decorator | +| [`06-micrometer-jdbc.txt`](output/06-micrometer-jdbc.txt) | adding third-party JDBC observation to the Micrometer build | +| [`07-both-at-once.txt`](output/07-both-at-once.txt) | agent and Micrometer starter in one JVM | +| [`08-overhead.txt`](output/08-overhead.txt) | startup CPU, per-request CPU, throughput, RSS (timing-sensitive) | +| [`09-resource.txt`](output/09-resource.txt) | resource attributes each approach sends | +| [`10-restclient-starter-missing.txt`](output/10-restclient-starter-missing.txt) | the Boot 4 startup failure without `spring-boot-starter-restclient` | + +Files 01-07, 09 and 10 are deterministic apart from ordering; file 08 drifts between runs and was +measured on a CPU-contended 2-vCPU sandbox. diff --git a/otel-agent-vs-micrometer/app/pom.xml b/otel-agent-vs-micrometer/app/pom.xml new file mode 100644 index 0000000..999752d --- /dev/null +++ b/otel-agent-vs-micrometer/app/pom.xml @@ -0,0 +1,81 @@ + + + 4.0.0 + + com.ankurm + otel-agent-vs-micrometer + 1.0.0 + + orders-app + + + + plain + + + + + org.springframework.boot + spring-boot-starter-webmvc + + + org.springframework.boot + spring-boot-starter-restclient + + + org.springframework.boot + spring-boot-starter-actuator + + + org.springframework.boot + spring-boot-starter-jdbc + + + com.h2database + h2 + runtime + + + + + + micrometer + + micrometer + + + + org.springframework.boot + spring-boot-starter-opentelemetry + + + + + + jdbc + + micrometer-jdbc + + + + net.ttddyy.observation + datasource-micrometer-spring-boot + 2.3.1 + + + + + + + orders-${variant} + + + org.springframework.boot + spring-boot-maven-plugin + + + + diff --git a/otel-agent-vs-micrometer/app/src/main/java/com/ankurm/otelcmp/AuditService.java b/otel-agent-vs-micrometer/app/src/main/java/com/ankurm/otelcmp/AuditService.java new file mode 100644 index 0000000..7ad0d89 --- /dev/null +++ b/otel-agent-vs-micrometer/app/src/main/java/com/ankurm/otelcmp/AuditService.java @@ -0,0 +1,55 @@ +package com.ankurm.otelcmp; + +import io.micrometer.observation.Observation; +import io.micrometer.observation.ObservationRegistry; +import java.util.concurrent.Executor; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.core.task.support.ContextPropagatingTaskDecorator; +import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; +import org.springframework.stereotype.Service; + +/** + * Hands work to another thread, which is where tracing context goes missing. + * audit.executor=raw a plain java.util.concurrent pool + * audit.executor=spring a ThreadPoolTaskExecutor with Spring's ContextPropagatingTaskDecorator + */ +@Service +public class AuditService { + + private final OrderRepository orders; + private final ObservationRegistry registry; + private final Executor executor; + + public AuditService(OrderRepository orders, ObservationRegistry registry, + @Value("${audit.executor:raw}") String mode) { + this.orders = orders; + this.registry = registry; + if (mode.equals("spring")) { + ThreadPoolTaskExecutor t = new ThreadPoolTaskExecutor(); + t.setCorePoolSize(2); + t.setThreadNamePrefix("audit-"); + t.setTaskDecorator(new ContextPropagatingTaskDecorator()); + t.initialize(); + this.executor = t; + } else { + ExecutorService e = Executors.newFixedThreadPool(2, r -> { + Thread th = new Thread(r, "audit-raw"); + th.setDaemon(true); + return th; + }); + this.executor = e; + } + } + + public void auditAndWait(long orderId) throws Exception { + java.util.concurrent.CompletableFuture.runAsync(() -> write(orderId), executor).get(10, TimeUnit.SECONDS); + } + + // Public so the agent's methods.include setting can name it, and so a CGLIB-free direct call works. + public void write(long orderId) { + Observation.createNotStarted("audit.write", registry).observe(() -> orders.audit(orderId, "viewed")); + } +} diff --git a/otel-agent-vs-micrometer/app/src/main/java/com/ankurm/otelcmp/InventoryClient.java b/otel-agent-vs-micrometer/app/src/main/java/com/ankurm/otelcmp/InventoryClient.java new file mode 100644 index 0000000..e3bdc93 --- /dev/null +++ b/otel-agent-vs-micrometer/app/src/main/java/com/ankurm/otelcmp/InventoryClient.java @@ -0,0 +1,22 @@ +package com.ankurm.otelcmp; + +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; +import org.springframework.web.client.RestClient; + +/** Calls this same application's /inventory endpoint, so one request produces a client span and a second server span. */ +@Component +public class InventoryClient { + + private final RestClient client; + + // The auto-configured RestClient.Builder is the one Spring Boot attaches observation (and so + // trace propagation headers) to. RestClient.create() would not be instrumented. + public InventoryClient(RestClient.Builder builder, @Value("${server.port:8080}") int port) { + this.client = builder.baseUrl("http://localhost:" + port).build(); + } + + public int stock(String sku) { + return client.get().uri("/inventory/{sku}", sku).retrieve().body(Integer.class); + } +} diff --git a/otel-agent-vs-micrometer/app/src/main/java/com/ankurm/otelcmp/OrderRepository.java b/otel-agent-vs-micrometer/app/src/main/java/com/ankurm/otelcmp/OrderRepository.java new file mode 100644 index 0000000..722f3a5 --- /dev/null +++ b/otel-agent-vs-micrometer/app/src/main/java/com/ankurm/otelcmp/OrderRepository.java @@ -0,0 +1,29 @@ +package com.ankurm.otelcmp; + +import org.springframework.jdbc.core.simple.JdbcClient; +import org.springframework.stereotype.Repository; + +@Repository +public class OrderRepository { + + public record Order(long id, String sku, int quantity, long unitPriceCents) {} + + private final JdbcClient jdbc; + + public OrderRepository(JdbcClient jdbc) { + this.jdbc = jdbc; + } + + public Order find(long id) { + return jdbc.sql("select id, sku, quantity, unit_price_cents from orders where id = :id") + .param("id", id) + .query((rs, n) -> new Order(rs.getLong("id"), rs.getString("sku"), + rs.getInt("quantity"), rs.getLong("unit_price_cents"))) + .single(); + } + + public void audit(long id, String note) { + jdbc.sql("insert into audit_log(order_id, note) values (:id, :note)") + .param("id", id).param("note", note).update(); + } +} diff --git a/otel-agent-vs-micrometer/app/src/main/java/com/ankurm/otelcmp/OrdersApplication.java b/otel-agent-vs-micrometer/app/src/main/java/com/ankurm/otelcmp/OrdersApplication.java new file mode 100644 index 0000000..ca32a11 --- /dev/null +++ b/otel-agent-vs-micrometer/app/src/main/java/com/ankurm/otelcmp/OrdersApplication.java @@ -0,0 +1,17 @@ +package com.ankurm.otelcmp; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +/** + * One application, built twice. The "plain" build has no tracing dependency at all; the + * "micrometer" build adds spring-boot-starter-opentelemetry. Nothing in this source tree knows + * which one it is running as, apart from {@link PricingService} and {@link AuditService}, which + * use the Micrometer Observation API (a no-op without a handler registered). + */ +@SpringBootApplication +public class OrdersApplication { + public static void main(String[] args) { + SpringApplication.run(OrdersApplication.class, args); + } +} diff --git a/otel-agent-vs-micrometer/app/src/main/java/com/ankurm/otelcmp/OrdersController.java b/otel-agent-vs-micrometer/app/src/main/java/com/ankurm/otelcmp/OrdersController.java new file mode 100644 index 0000000..c63c4a9 --- /dev/null +++ b/otel-agent-vs-micrometer/app/src/main/java/com/ankurm/otelcmp/OrdersController.java @@ -0,0 +1,51 @@ +package com.ankurm.otelcmp; + +import java.util.Map; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class OrdersController { + + private final OrderRepository orders; + private final InventoryClient inventory; + private final PricingService pricing; + private final AuditService audit; + + public OrdersController(OrderRepository orders, InventoryClient inventory, + PricingService pricing, AuditService audit) { + this.orders = orders; + this.inventory = inventory; + this.pricing = pricing; + this.audit = audit; + } + + /** One SQL query, one outgoing HTTP call, one business computation. */ + @GetMapping("/orders/{id}") + public Map order(@PathVariable long id) { + var order = orders.find(id); + int stock = inventory.stock(order.sku()); + return Map.of("id", order.id(), "sku", order.sku(), "totalCents", pricing.price(order), "stock", stock); + } + + /** Same, plus a hand-off to another thread that also writes to the database. */ + @GetMapping("/orders/{id}/audited") + public Map audited(@PathVariable long id) throws Exception { + var body = order(id); + audit.auditAndWait(id); + return body; + } + + /** The downstream service (served by this same JVM). */ + @GetMapping("/inventory/{sku}") + public int stock(@PathVariable String sku) { + return sku.length() * 10; + } + + /** No database, no outgoing call: used to measure instrumentation cost per request. */ + @GetMapping("/ping") + public String ping() { + return "pong"; + } +} diff --git a/otel-agent-vs-micrometer/app/src/main/java/com/ankurm/otelcmp/PricingService.java b/otel-agent-vs-micrometer/app/src/main/java/com/ankurm/otelcmp/PricingService.java new file mode 100644 index 0000000..b6e37aa --- /dev/null +++ b/otel-agent-vs-micrometer/app/src/main/java/com/ankurm/otelcmp/PricingService.java @@ -0,0 +1,29 @@ +package com.ankurm.otelcmp; + +import io.micrometer.observation.Observation; +import io.micrometer.observation.ObservationRegistry; +import org.springframework.stereotype.Service; + +/** + * A business operation we want a span for. + * + * In-code: the Observation below becomes a span when Micrometer Tracing is on the classpath. + * Zero-code: the agent is told about this method with + * -Dotel.instrumentation.methods.include=com.ankurm.otelcmp.PricingService[price] + * and this class needs no change. Under the agent the Observation is a harmless no-op. + */ +@Service +public class PricingService { + + private final ObservationRegistry registry; + + public PricingService(ObservationRegistry registry) { + this.registry = registry; + } + + public long price(OrderRepository.Order order) { + return Observation.createNotStarted("pricing.compute", registry) + .lowCardinalityKeyValue("pricing.sku", order.sku()) + .observe(() -> order.quantity() * order.unitPriceCents()); + } +} diff --git a/otel-agent-vs-micrometer/app/src/main/resources/application.properties b/otel-agent-vs-micrometer/app/src/main/resources/application.properties new file mode 100644 index 0000000..8fdeaa0 --- /dev/null +++ b/otel-agent-vs-micrometer/app/src/main/resources/application.properties @@ -0,0 +1,7 @@ +spring.application.name=orders +server.port=${PORT:8080} +spring.sql.init.mode=always +spring.sql.init.schema-locations=classpath:schema.sql +spring.sql.init.data-locations=classpath:data.sql +spring.datasource.url=jdbc:h2:mem:orders;DB_CLOSE_DELAY=-1 +management.endpoints.web.exposure.include=health,metrics,info diff --git a/otel-agent-vs-micrometer/app/src/main/resources/data.sql b/otel-agent-vs-micrometer/app/src/main/resources/data.sql new file mode 100644 index 0000000..252ac67 --- /dev/null +++ b/otel-agent-vs-micrometer/app/src/main/resources/data.sql @@ -0,0 +1 @@ +merge into orders (id, sku, quantity, unit_price_cents) key (id) values (1, 'KEYBOARD', 2, 4999); diff --git a/otel-agent-vs-micrometer/app/src/main/resources/schema.sql b/otel-agent-vs-micrometer/app/src/main/resources/schema.sql new file mode 100644 index 0000000..ed68f73 --- /dev/null +++ b/otel-agent-vs-micrometer/app/src/main/resources/schema.sql @@ -0,0 +1,2 @@ +create table if not exists orders (id bigint primary key, sku varchar(20), quantity int, unit_price_cents bigint); +create table if not exists audit_log (id bigint auto_increment primary key, order_id bigint, note varchar(50)); diff --git a/otel-agent-vs-micrometer/driver/LoadDriver.java b/otel-agent-vs-micrometer/driver/LoadDriver.java new file mode 100644 index 0000000..ec14444 --- /dev/null +++ b/otel-agent-vs-micrometer/driver/LoadDriver.java @@ -0,0 +1,58 @@ +import java.net.URI; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.concurrent.Callable; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; + +/** + * Closed-loop load generator. usage: java LoadDriver.java URL warmup measured threads rounds + * Prints one line per measured round: requests per second, p50 and p99 latency in microseconds. + * It shares the two vCPUs of the sandbox with the app under test and the OTLP sink, so the + * numbers are relative to each other, not absolute. + */ +public class LoadDriver { + public static void main(String[] a) throws Exception { + String url = a[0]; + int warmup = Integer.parseInt(a[1]), measured = Integer.parseInt(a[2]); + int threads = Integer.parseInt(a[3]), rounds = Integer.parseInt(a[4]); + HttpClient client = HttpClient.newBuilder().version(HttpClient.Version.HTTP_1_1).build(); + HttpRequest req = HttpRequest.newBuilder(URI.create(url)).GET().build(); + run(client, req, warmup, threads); + for (int r = 1; r <= rounds; r++) { + long t0 = System.nanoTime(); + long[] lat = run(client, req, measured, threads); + double secs = (System.nanoTime() - t0) / 1e9; + Arrays.sort(lat); + System.out.printf("round %d: %6.0f req/s p50 %5d us p99 %6d us%n", r, lat.length / secs, + lat[lat.length / 2] / 1000, lat[(int) (lat.length * 0.99)] / 1000); + } + } + + static long[] run(HttpClient c, HttpRequest req, int total, int threads) throws Exception { + ExecutorService ex = Executors.newFixedThreadPool(threads); + List> jobs = new ArrayList<>(); + int per = total / threads; + for (int t = 0; t < threads; t++) { + jobs.add(() -> { + long[] l = new long[per]; + for (int i = 0; i < per; i++) { + long s = System.nanoTime(); + HttpResponse r = c.send(req, HttpResponse.BodyHandlers.discarding()); + if (r.statusCode() != 200) throw new IllegalStateException("status " + r.statusCode()); + l[i] = System.nanoTime() - s; + } + return l; + }); + } + long[] all = new long[per * threads]; + int k = 0; + for (var f : ex.invokeAll(jobs)) for (long v : f.get()) all[k++] = v; + ex.shutdown(); + return all; + } +} diff --git a/otel-agent-vs-micrometer/output/01-agent-spans.txt b/otel-agent-vs-micrometer/output/01-agent-spans.txt new file mode 100644 index 0000000..e146e0a --- /dev/null +++ b/otel-agent-vs-micrometer/output/01-agent-spans.txt @@ -0,0 +1,37 @@ +# 01 OpenTelemetry Java agent 2.34.0 on the unmodified 'plain' jar (Spring Boot 4.2.0, JDK 25.0.5.1) +# Requests sent after warm-up: GET /orders/1, then GET /orders/1/audited +== spans + +-- span tree (one line per span: name [kind, instrumentation scope]) +trace 1 (5 spans) + GET /orders/{id} [SERVER, scope=io.opentelemetry.tomcat-10.0] + SELECT orders.orders [CLIENT, scope=io.opentelemetry.jdbc] + GET [CLIENT, scope=io.opentelemetry.java-http-client] + GET /inventory/{sku} [SERVER, scope=io.opentelemetry.tomcat-10.0] + PricingService.price [INTERNAL, scope=io.opentelemetry.methods] +trace 2 (7 spans) + GET /orders/{id}/audited [SERVER, scope=io.opentelemetry.tomcat-10.0] + SELECT orders.orders [CLIENT, scope=io.opentelemetry.jdbc] + GET [CLIENT, scope=io.opentelemetry.java-http-client] + GET /inventory/{sku} [SERVER, scope=io.opentelemetry.tomcat-10.0] + PricingService.price [INTERNAL, scope=io.opentelemetry.methods] + AuditService.write [INTERNAL, scope=io.opentelemetry.methods] + INSERT orders.audit_log [CLIENT, scope=io.opentelemetry.jdbc] + +-- attribute keys per span name +AuditService.write [INTERNAL] + code.function, code.namespace, thread.id, thread.name +GET /inventory/{sku} [SERVER] + client.address, http.request.method, http.response.status_code, http.route, network.peer.address, network.peer.port, network.protocol.version, server.address, server.port, thread.id, thread.name, url.path, url.scheme, user_agent.original +GET /orders/{id} [SERVER] + client.address, http.request.method, http.response.status_code, http.route, network.peer.address, network.peer.port, network.protocol.version, server.address, server.port, thread.id, thread.name, url.path, url.scheme, user_agent.original +GET /orders/{id}/audited [SERVER] + client.address, http.request.method, http.response.status_code, http.route, network.peer.address, network.peer.port, network.protocol.version, server.address, server.port, thread.id, thread.name, url.path, url.scheme, user_agent.original +GET [CLIENT] + http.request.method, http.response.status_code, network.protocol.version, server.address, server.port, thread.id, thread.name, url.full +INSERT orders.audit_log [CLIENT] + db.connection_string, db.name, db.operation, db.sql.table, db.statement, db.system, db.user, thread.id, thread.name +PricingService.price [INTERNAL] + code.function, code.namespace, thread.id, thread.name +SELECT orders.orders [CLIENT] + db.connection_string, db.name, db.operation, db.sql.table, db.statement, db.system, db.user, thread.id, thread.name diff --git a/otel-agent-vs-micrometer/output/02-micrometer-spans.txt b/otel-agent-vs-micrometer/output/02-micrometer-spans.txt new file mode 100644 index 0000000..0c8b227 --- /dev/null +++ b/otel-agent-vs-micrometer/output/02-micrometer-spans.txt @@ -0,0 +1,31 @@ +# 02 Micrometer Tracing via spring-boot-starter-opentelemetry, Spring Boot 4.2.0, default conventions +# Requests sent after warm-up: GET /orders/1, then GET /orders/1/audited (audit.executor=raw) +== spans + +-- span tree (one line per span: name [kind, instrumentation scope]) +trace 1 (4 spans) + http get /orders/{id} [SERVER, scope=org.springframework.boot] + http get [CLIENT, scope=org.springframework.boot] + http get /inventory/{sku} [SERVER, scope=org.springframework.boot] + pricing.compute [INTERNAL, scope=org.springframework.boot] +trace 2 (4 spans) + http get /orders/{id}/audited [SERVER, scope=org.springframework.boot] + http get [CLIENT, scope=org.springframework.boot] + http get /inventory/{sku} [SERVER, scope=org.springframework.boot] + pricing.compute [INTERNAL, scope=org.springframework.boot] +trace 3 (1 spans) + audit.write [INTERNAL, scope=org.springframework.boot] + +-- attribute keys per span name +audit.write [INTERNAL] + +http get /inventory/{sku} [SERVER] + exception, http.url, method, outcome, status, uri +http get /orders/{id} [SERVER] + exception, http.url, method, outcome, status, uri +http get /orders/{id}/audited [SERVER] + exception, http.url, method, outcome, status, uri +http get [CLIENT] + client.name, exception, http.url, method, outcome, status, uri +pricing.compute [INTERNAL] + pricing.sku diff --git a/otel-agent-vs-micrometer/output/03-micrometer-otel-conventions.txt b/otel-agent-vs-micrometer/output/03-micrometer-otel-conventions.txt new file mode 100644 index 0000000..bf22352 --- /dev/null +++ b/otel-agent-vs-micrometer/output/03-micrometer-otel-conventions.txt @@ -0,0 +1,37 @@ +# 03 Same Micrometer build with management.observations.conventions=opentelemetry (new in Spring Boot 4.2) +== spans + +-- span tree (one line per span: name [kind, instrumentation scope]) +trace 1 (4 spans) + GET /orders/{id} [SERVER, scope=org.springframework.boot] + http get [CLIENT, scope=org.springframework.boot] + GET /inventory/{sku} [SERVER, scope=org.springframework.boot] + pricing.compute [INTERNAL, scope=org.springframework.boot] +trace 2 (4 spans) + GET /orders/{id}/audited [SERVER, scope=org.springframework.boot] + http get [CLIENT, scope=org.springframework.boot] + GET /inventory/{sku} [SERVER, scope=org.springframework.boot] + pricing.compute [INTERNAL, scope=org.springframework.boot] +trace 3 (1 spans) + audit.write [INTERNAL, scope=org.springframework.boot] + +-- attribute keys per span name +GET /inventory/{sku} [SERVER] + error.type, http.request.method, http.request.method_original, http.response.status_code, http.route, outcome, url.path, url.scheme +GET /orders/{id} [SERVER] + error.type, http.request.method, http.request.method_original, http.response.status_code, http.route, outcome, url.path, url.scheme +GET /orders/{id}/audited [SERVER] + error.type, http.request.method, http.request.method_original, http.response.status_code, http.route, outcome, url.path, url.scheme +audit.write [INTERNAL] + +http get [CLIENT] + client.name, exception, http.url, method, outcome, status, uri +pricing.compute [INTERNAL] + pricing.sku + +-- HTTP metrics exported +scope (no scope name) (77 metrics) + http.client.requests histogram unit=milliseconds + http.client.requests.max gauge unit=milliseconds + http.server.request.duration histogram unit=milliseconds + http.server.request.duration.max gauge unit=milliseconds diff --git a/otel-agent-vs-micrometer/output/04-metrics.txt b/otel-agent-vs-micrometer/output/04-metrics.txt new file mode 100644 index 0000000..ef5b94f --- /dev/null +++ b/otel-agent-vs-micrometer/output/04-metrics.txt @@ -0,0 +1,114 @@ +# 04 Metrics received over OTLP, grouped by the instrumentation scope that produced them + +######## agent +scope io.opentelemetry.exporters.otlp-http (2 metrics) + otlp.exporter.exported sum + otlp.exporter.seen sum +scope io.opentelemetry.hikaricp-3.0 (7 metrics) + db.client.connections.create_time histogram unit=ms + db.client.connections.idle.min sum unit={connections} + db.client.connections.max sum unit={connections} + db.client.connections.pending_requests sum unit={requests} + db.client.connections.usage sum unit={connections} + db.client.connections.use_time histogram unit=ms + db.client.connections.wait_time histogram unit=ms +scope io.opentelemetry.java-http-client (1 metrics) + http.client.request.duration histogram unit=s +scope io.opentelemetry.runtime-telemetry-java8 (12 metrics) + jvm.class.count sum unit={class} + jvm.class.loaded sum unit={class} + jvm.class.unloaded sum unit={class} + jvm.cpu.count sum unit={cpu} + jvm.cpu.recent_utilization gauge unit=1 + jvm.cpu.time sum unit=s + jvm.gc.duration histogram unit=s + jvm.memory.committed sum unit=By + jvm.memory.limit sum unit=By + jvm.memory.used sum unit=By + jvm.memory.used_after_last_gc sum unit=By + jvm.thread.count sum unit={thread} +scope io.opentelemetry.sdk.trace (2 metrics) + processedSpans sum unit=1 + queueSize gauge unit=1 +scope io.opentelemetry.tomcat-10.0 (1 metrics) + http.server.request.duration histogram unit=s + +######## micrometer (default conventions) +scope (no scope name) (77 metrics) + application.ready.time gauge unit=milliseconds + application.started.time gauge unit=milliseconds + audit.write histogram unit=milliseconds + audit.write.max gauge unit=milliseconds + disk.free gauge unit=bytes + disk.total gauge unit=bytes + executor.active gauge unit=threads + executor.completed sum unit=tasks + executor.pool.core gauge unit=threads + executor.pool.max gauge unit=threads + executor.pool.size gauge unit=threads + executor.queue.remaining gauge unit=tasks + executor.queued gauge unit=tasks + hikaricp.connections gauge + hikaricp.connections.acquire histogram unit=milliseconds + hikaricp.connections.acquire.max gauge unit=milliseconds + hikaricp.connections.active gauge + hikaricp.connections.creation histogram unit=milliseconds + hikaricp.connections.creation.max gauge unit=milliseconds + hikaricp.connections.idle gauge + hikaricp.connections.max gauge + hikaricp.connections.min gauge + hikaricp.connections.pending gauge + hikaricp.connections.timeout sum + hikaricp.connections.usage histogram unit=milliseconds + hikaricp.connections.usage.max gauge unit=milliseconds + http.client.requests histogram unit=milliseconds + http.client.requests.max gauge unit=milliseconds + http.server.requests histogram unit=milliseconds + http.server.requests.max gauge unit=milliseconds + jdbc.connections.active gauge + jdbc.connections.idle gauge + jdbc.connections.max gauge + jdbc.connections.min gauge + jvm.buffer.count gauge unit=buffers + jvm.buffer.memory.used gauge unit=bytes + jvm.buffer.total.capacity gauge unit=bytes + jvm.classes.loaded gauge unit=classes + jvm.classes.loaded.count sum unit=classes + jvm.classes.unloaded sum unit=classes + jvm.compilation.time sum unit=ms + jvm.gc.live.data.size gauge unit=bytes + jvm.gc.max.data.size gauge unit=bytes + jvm.gc.memory.allocated sum unit=bytes + jvm.gc.memory.promoted sum unit=bytes + jvm.gc.overhead gauge + jvm.gc.pause histogram unit=milliseconds + jvm.gc.pause.max gauge unit=milliseconds + jvm.info gauge + jvm.memory.committed gauge unit=bytes + jvm.memory.max gauge unit=bytes + jvm.memory.usage.after.gc gauge + jvm.memory.used gauge unit=bytes + jvm.memory.used_after_last_gc gauge unit=bytes + jvm.threads.daemon gauge unit=threads + jvm.threads.live gauge unit=threads + jvm.threads.peak gauge unit=threads + jvm.threads.started sum unit=threads + jvm.threads.states gauge unit=threads + logback.events sum unit=events + pricing.compute histogram unit=milliseconds + pricing.compute.max gauge unit=milliseconds + process.cpu.time sum unit=ns + process.cpu.usage gauge + process.files.max gauge unit=files + process.files.open gauge unit=files + process.start.time gauge unit=milliseconds + process.uptime gauge unit=milliseconds + system.cpu.count gauge + system.cpu.usage gauge + system.load.average.1m gauge + tomcat.sessions.active.current gauge unit=sessions + tomcat.sessions.active.max gauge unit=sessions + tomcat.sessions.alive.max gauge unit=milliseconds + tomcat.sessions.created sum unit=sessions + tomcat.sessions.expired sum unit=sessions + tomcat.sessions.rejected sum unit=sessions diff --git a/otel-agent-vs-micrometer/output/05-thread-handoff.txt b/otel-agent-vs-micrometer/output/05-thread-handoff.txt new file mode 100644 index 0000000..bc7b227 --- /dev/null +++ b/otel-agent-vs-micrometer/output/05-thread-handoff.txt @@ -0,0 +1,29 @@ +# 05 Work handed to another thread (GET /orders/1/audited submits AuditService.write to a pool) +# One trace is expected: SERVER span with audit.write below it. Count the traces. + +== agent, audit.executor=raw +trace 1 (7 spans) + GET /orders/{id}/audited [SERVER, scope=io.opentelemetry.tomcat-10.0] + SELECT orders.orders [CLIENT, scope=io.opentelemetry.jdbc] + GET [CLIENT, scope=io.opentelemetry.java-http-client] + GET /inventory/{sku} [SERVER, scope=io.opentelemetry.tomcat-10.0] + PricingService.price [INTERNAL, scope=io.opentelemetry.methods] + AuditService.write [INTERNAL, scope=io.opentelemetry.methods] + INSERT orders.audit_log [CLIENT, scope=io.opentelemetry.jdbc] + +== micrometer, audit.executor=raw +trace 1 (4 spans) + http get /orders/{id}/audited [SERVER, scope=org.springframework.boot] + http get [CLIENT, scope=org.springframework.boot] + http get /inventory/{sku} [SERVER, scope=org.springframework.boot] + pricing.compute [INTERNAL, scope=org.springframework.boot] +trace 2 (1 spans) + audit.write [INTERNAL, scope=org.springframework.boot] + +== micrometer, audit.executor=spring +trace 1 (5 spans) + http get /orders/{id}/audited [SERVER, scope=org.springframework.boot] + http get [CLIENT, scope=org.springframework.boot] + http get /inventory/{sku} [SERVER, scope=org.springframework.boot] + pricing.compute [INTERNAL, scope=org.springframework.boot] + audit.write [INTERNAL, scope=org.springframework.boot] diff --git a/otel-agent-vs-micrometer/output/06-micrometer-jdbc.txt b/otel-agent-vs-micrometer/output/06-micrometer-jdbc.txt new file mode 100644 index 0000000..acc8673 --- /dev/null +++ b/otel-agent-vs-micrometer/output/06-micrometer-jdbc.txt @@ -0,0 +1,33 @@ +# 06 Micrometer build plus net.ttddyy.observation:datasource-micrometer-spring-boot 2.3.1 (third-party) +== spans + +-- span tree (one line per span: name [kind, instrumentation scope]) +trace 1 (7 spans) + http get /orders/{id} [SERVER, scope=org.springframework.boot] + connection [CLIENT, scope=org.springframework.boot] + query [CLIENT, scope=org.springframework.boot] + result-set [CLIENT, scope=org.springframework.boot] + http get [CLIENT, scope=org.springframework.boot] + http get /inventory/{sku} [SERVER, scope=org.springframework.boot] + pricing.compute [INTERNAL, scope=org.springframework.boot] +trace 2 (7 spans) + http get /orders/{id}/audited [SERVER, scope=org.springframework.boot] + connection [CLIENT, scope=org.springframework.boot] + query [CLIENT, scope=org.springframework.boot] + result-set [CLIENT, scope=org.springframework.boot] + http get [CLIENT, scope=org.springframework.boot] + http get /inventory/{sku} [SERVER, scope=org.springframework.boot] + pricing.compute [INTERNAL, scope=org.springframework.boot] +trace 3 (3 spans) + audit.write [INTERNAL, scope=org.springframework.boot] + connection [CLIENT, scope=org.springframework.boot] + query [CLIENT, scope=org.springframework.boot] + +-- attribute keys per span name +connection [CLIENT] + jdbc.datasource.driver, jdbc.datasource.name, jdbc.datasource.pool +-- +query [CLIENT] + jdbc.datasource.driver, jdbc.datasource.name, jdbc.datasource.pool, jdbc.query[0], jdbc.row-affected, peer.service +result-set [CLIENT] + jdbc.datasource.driver, jdbc.datasource.name, jdbc.datasource.pool, jdbc.row-count, peer.service diff --git a/otel-agent-vs-micrometer/output/07-both-at-once.txt b/otel-agent-vs-micrometer/output/07-both-at-once.txt new file mode 100644 index 0000000..020d77c --- /dev/null +++ b/otel-agent-vs-micrometer/output/07-both-at-once.txt @@ -0,0 +1,66 @@ +# 07 Micrometer build AND the agent in the same JVM, both exporting to the same sink +== spans + +-- span tree (one line per span: name [kind, instrumentation scope]) +trace 1 (8 spans) + GET /orders/{id} [SERVER, scope=io.opentelemetry.tomcat-10.0] + http get /orders/{id} [SERVER, scope=org.springframework.boot] + SELECT orders.orders [CLIENT, scope=io.opentelemetry.jdbc] + http get [CLIENT, scope=org.springframework.boot] + GET [CLIENT, scope=io.opentelemetry.java-http-client] + GET /inventory/{sku} [SERVER, scope=io.opentelemetry.tomcat-10.0] + http get /inventory/{sku} [SERVER, scope=org.springframework.boot] + pricing.compute [INTERNAL, scope=org.springframework.boot] +trace 2 (10 spans) + GET /orders/{id}/audited [SERVER, scope=io.opentelemetry.tomcat-10.0] + http get /orders/{id}/audited [SERVER, scope=org.springframework.boot] + SELECT orders.orders [CLIENT, scope=io.opentelemetry.jdbc] + http get [CLIENT, scope=org.springframework.boot] + GET [CLIENT, scope=io.opentelemetry.java-http-client] + GET /inventory/{sku} [SERVER, scope=io.opentelemetry.tomcat-10.0] + http get /inventory/{sku} [SERVER, scope=org.springframework.boot] + pricing.compute [INTERNAL, scope=org.springframework.boot] + audit.write [INTERNAL, scope=org.springframework.boot] + INSERT orders.audit_log [CLIENT, scope=io.opentelemetry.jdbc] +trace 3 (1 spans) + POST [CLIENT, scope=io.opentelemetry.java-http-client] +trace 4 (1 spans) + POST [CLIENT, scope=io.opentelemetry.java-http-client] + +-- attribute keys per span name +GET /inventory/{sku} [SERVER] + client.address, http.request.method, http.response.status_code, http.route, network.peer.address, network.peer.port, network.protocol.version, server.address, server.port, thread.id, thread.name, url.path, url.scheme, user_agent.original +GET /orders/{id} [SERVER] + client.address, http.request.method, http.response.status_code, http.route, network.peer.address, network.peer.port, network.protocol.version, server.address, server.port, thread.id, thread.name, url.path, url.scheme, user_agent.original +GET /orders/{id}/audited [SERVER] + client.address, http.request.method, http.response.status_code, http.route, network.peer.address, network.peer.port, network.protocol.version, server.address, server.port, thread.id, thread.name, url.path, url.scheme, user_agent.original +GET [CLIENT] + http.request.method, http.response.status_code, network.protocol.version, server.address, server.port, thread.id, thread.name, url.full +INSERT orders.audit_log [CLIENT] + db.connection_string, db.name, db.operation, db.sql.table, db.statement, db.system, db.user, thread.id, thread.name +POST [CLIENT] + http.request.method, http.response.status_code, network.protocol.version, server.address, server.port, thread.id, thread.name, url.full +SELECT orders.orders [CLIENT] + db.connection_string, db.name, db.operation, db.sql.table, db.statement, db.system, db.user, thread.id, thread.name +audit.write [INTERNAL] + +http get /inventory/{sku} [SERVER] + exception, http.url, method, outcome, status, uri +http get /orders/{id} [SERVER] + exception, http.url, method, outcome, status, uri +http get /orders/{id}/audited [SERVER] + exception, http.url, method, outcome, status, uri +http get [CLIENT] + client.name, exception, http.url, method, outcome, status, uri +pricing.compute [INTERNAL] + pricing.sku + +-- url.full of the lone POST client spans +http://localhost:14418/v1/metrics + +-- HTTP server metrics received (scope, name) +scope (no scope name) (79 metrics) + http.server.requests histogram unit=milliseconds + http.server.requests.max gauge unit=milliseconds +scope io.opentelemetry.tomcat-10.0 (1 metrics) + http.server.request.duration histogram unit=s diff --git a/otel-agent-vs-micrometer/output/08-overhead.txt b/otel-agent-vs-micrometer/output/08-overhead.txt new file mode 100644 index 0000000..ae9aac6 --- /dev/null +++ b/otel-agent-vs-micrometer/output/08-overhead.txt @@ -0,0 +1,92 @@ +# 08 Overhead: same jar family, same endpoints, 4 client threads, 5000 warm-up + 8000 measured requests x 3 rounds +# JDK 25.0.5.1, 2 vCPU shared by app, OTLP sink and load driver. Indicative only. + +== baseline: plain jar, no instrumentation +CPU consumed by the JVM from process start to ready (+4 s idle): 6090 ms +Started OrdersApplication in 2.639 seconds (process running for 2.971) +-- GET /ping +round 1: 2240 req/s p50 872 us p99 9240 us +round 2: 4647 req/s p50 467 us p99 6024 us +round 3: 7602 req/s p50 313 us p99 4336 us +app CPU per request: 206 us (utime+stime of the app JVM only, 24000 requests) +-- GET /orders/1 +round 1: 1025 req/s p50 3117 us p99 12533 us +round 2: 1627 req/s p50 1824 us p99 9003 us +round 3: 2864 req/s p50 1220 us p99 5087 us +app CPU per request: 791 us (utime+stime of the app JVM only, 24000 requests) +-- RSS after the run: 310 MiB + +== agent, all spans sampled +CPU consumed by the JVM from process start to ready (+4 s idle): 13920 ms +Started OrdersApplication in 3.393 seconds (process running for 7.212) +-- GET /ping +round 1: 1539 req/s p50 1589 us p99 11298 us +round 2: 2502 req/s p50 861 us p99 8897 us +round 3: 5087 req/s p50 393 us p99 5911 us +app CPU per request: 365 us (utime+stime of the app JVM only, 24000 requests) +-- GET /orders/1 +round 1: 710 req/s p50 4562 us p99 18314 us +round 2: 953 req/s p50 3059 us p99 14901 us +round 3: 1217 req/s p50 2038 us p99 15006 us +app CPU per request: 1253 us (utime+stime of the app JVM only, 24000 requests) +-- RSS after the run: 422 MiB + +== micrometer starter, all spans sampled +CPU consumed by the JVM from process start to ready (+4 s idle): 8760 ms +Started OrdersApplication in 3.765 seconds (process running for 4.238) +-- GET /ping +round 1: 1800 req/s p50 1300 us p99 10657 us +round 2: 2775 req/s p50 766 us p99 9238 us +round 3: 4193 req/s p50 426 us p99 7682 us +app CPU per request: 368 us (utime+stime of the app JVM only, 24000 requests) +-- GET /orders/1 +round 1: 898 req/s p50 2886 us p99 18366 us +round 2: 1075 req/s p50 2155 us p99 17843 us +round 3: 1660 req/s p50 1369 us p99 13317 us +app CPU per request: 937 us (utime+stime of the app JVM only, 24000 requests) +-- RSS after the run: 467 MiB + +== agent, 10% sampling +CPU consumed by the JVM from process start to ready (+4 s idle): 13900 ms +Started OrdersApplication in 3.557 seconds (process running for 6.947) +-- GET /ping +round 1: 1903 req/s p50 1261 us p99 8751 us +round 2: 3080 req/s p50 815 us p99 6476 us +round 3: 4395 req/s p50 506 us p99 5679 us +app CPU per request: 345 us (utime+stime of the app JVM only, 24000 requests) +-- GET /orders/1 +round 1: 730 req/s p50 4706 us p99 15682 us +round 2: 1337 req/s p50 2297 us p99 10480 us +round 3: 1978 req/s p50 1539 us p99 8297 us +app CPU per request: 1267 us (utime+stime of the app JVM only, 24000 requests) +-- RSS after the run: 415 MiB + +== micrometer starter, 10% sampling +CPU consumed by the JVM from process start to ready (+4 s idle): 7850 ms +Started OrdersApplication in 3.336 seconds (process running for 3.694) +-- GET /ping +round 1: 1607 req/s p50 1635 us p99 10174 us +round 2: 3176 req/s p50 736 us p99 7275 us +round 3: 4997 req/s p50 413 us p99 5595 us +app CPU per request: 326 us (utime+stime of the app JVM only, 24000 requests) +-- GET /orders/1 +round 1: 856 req/s p50 3859 us p99 16063 us +round 2: 1451 req/s p50 2154 us p99 9741 us +round 3: 1770 req/s p50 1809 us p99 8160 us +app CPU per request: 1076 us (utime+stime of the app JVM only, 24000 requests) +-- RSS after the run: 334 MiB + +== micrometer starter + JDBC observation, all spans sampled +CPU consumed by the JVM from process start to ready (+4 s idle): 9380 ms +Started OrdersApplication in 3.959 seconds (process running for 4.405) +-- GET /ping +round 1: 2018 req/s p50 1117 us p99 9328 us +round 2: 3270 req/s p50 586 us p99 9113 us +round 3: 5052 req/s p50 323 us p99 7483 us +app CPU per request: 317 us (utime+stime of the app JVM only, 24000 requests) +-- GET /orders/1 +round 1: 646 req/s p50 5076 us p99 20246 us +round 2: 1054 req/s p50 2731 us p99 15085 us +round 3: 1467 req/s p50 1636 us p99 14121 us +app CPU per request: 1190 us (utime+stime of the app JVM only, 24000 requests) +-- RSS after the run: 462 MiB diff --git a/otel-agent-vs-micrometer/output/09-resource.txt b/otel-agent-vs-micrometer/output/09-resource.txt new file mode 100644 index 0000000..1afa690 --- /dev/null +++ b/otel-agent-vs-micrometer/output/09-resource.txt @@ -0,0 +1,21 @@ +# 09 What each approach puts in the Resource (who is this service?) +# Machine-specific attributes are left out: host.name, os.*, process.pid, process.executable.path, +# process.command_args and service.instance.id. +== agent +host.arch = amd64 +process.runtime.description = Eclipse Adoptium OpenJDK 64-Bit Server VM 25.0.5.1+2-LTS +process.runtime.name = OpenJDK Runtime Environment +process.runtime.version = 25.0.5.1+2-LTS +service.name = orders +service.version = 1.0.0 +telemetry.distro.name = opentelemetry-java-instrumentation +telemetry.distro.version = 2.34.0 +telemetry.sdk.language = java +telemetry.sdk.name = opentelemetry +telemetry.sdk.version = 1.68.0 + +== micrometer +service.name = orders +telemetry.sdk.language = java +telemetry.sdk.name = opentelemetry +telemetry.sdk.version = 1.68.0 diff --git a/otel-agent-vs-micrometer/output/10-restclient-starter-missing.txt b/otel-agent-vs-micrometer/output/10-restclient-starter-missing.txt new file mode 100644 index 0000000..e370ae0 --- /dev/null +++ b/otel-agent-vs-micrometer/output/10-restclient-starter-missing.txt @@ -0,0 +1,14 @@ +# 10 The same app built WITHOUT spring-boot-starter-restclient (Spring Boot 4.2.0) +# dependencies kept: spring-boot-starter-webmvc, -actuator, -jdbc, h2 + +APPLICATION FAILED TO START +*************************** + +Description: + +Parameter 0 of constructor in com.ankurm.otelcmp.InventoryClient required a bean of type 'org.springframework.web.client.RestClient$Builder' that could not be found. + + +Action: + +Consider defining a bean of type 'org.springframework.web.client.RestClient$Builder' in your configuration. diff --git a/otel-agent-vs-micrometer/pom.xml b/otel-agent-vs-micrometer/pom.xml new file mode 100644 index 0000000..cb54a9a --- /dev/null +++ b/otel-agent-vs-micrometer/pom.xml @@ -0,0 +1,28 @@ + + + 4.0.0 + + + org.springframework.boot + spring-boot-starter-parent + 4.2.0 + + + + com.ankurm + otel-agent-vs-micrometer + 1.0.0 + pom + The same Spring Boot 4.2 app instrumented with the OpenTelemetry Java agent and with Micrometer Tracing + + + app + sink + + + + 25 + + diff --git a/otel-agent-vs-micrometer/scripts/lib.sh b/otel-agent-vs-micrometer/scripts/lib.sh new file mode 100755 index 0000000..628345c --- /dev/null +++ b/otel-agent-vs-micrometer/scripts/lib.sh @@ -0,0 +1,63 @@ +#!/usr/bin/env bash +# Shared helpers. Source this; do not run it. +# Kills by recorded PID, never by pattern (a pattern that matches the calling shell's own +# command line kills the shell). +ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +DIST="${DIST:-$ROOT/dist}" +OUT="$ROOT/output" +APP_PORT=18480 +SINK_PORT=14418 +TMPD="${TMPDIR_OTELCMP:-/tmp/otelcmp-run}"; mkdir -p "$TMPD" + +build() { + mkdir -p "$DIST" + ( cd "$ROOT" && mvn -B -q -DskipTests package ) >/dev/null + cp "$ROOT/app/target/orders-plain.jar" "$DIST/" + cp "$ROOT/sink/target/otlp-sink.jar" "$DIST/" + ( cd "$ROOT" && mvn -B -q -DskipTests -Pmicrometer -pl app package ) >/dev/null + cp "$ROOT/app/target/orders-micrometer.jar" "$DIST/" + if [ ! -f "$DIST/agent.jar" ]; then + curl -sfL -o "$DIST/agent.jar" \ + https://repo1.maven.org/maven2/io/opentelemetry/javaagent/opentelemetry-javaagent/2.34.0/opentelemetry-javaagent-2.34.0.jar + fi +} + +start_sink() { + java -jar "$DIST/otlp-sink.jar" $SINK_PORT >$TMPD/sink.log 2>&1 & + SINK_PID=$! + for i in $(seq 1 30); do curl -s -o /dev/null -X POST localhost:$SINK_PORT/reset && return; sleep 0.5; done + echo "sink did not start" >&2; return 1 +} + +# start_app +start_app() { + local variant="$1"; shift + java -DPORT=$APP_PORT "$@" -jar "$DIST/orders-$variant.jar" >$TMPD/app.log 2>&1 & + APP_PID=$! + for i in $(seq 1 120); do + curl -s -o /dev/null localhost:$APP_PORT/ping && return + sleep 0.5 + done + echo "app did not start" >&2; tail -20 $TMPD/app.log >&2; return 1 +} + +stop_app() { if [ -n "${APP_PID:-}" ]; then kill "$APP_PID" 2>/dev/null || true; wait "$APP_PID" 2>/dev/null || true; fi; APP_PID=""; } +stop_sink() { if [ -n "${SINK_PID:-}" ]; then kill "$SINK_PID" 2>/dev/null || true; wait "$SINK_PID" 2>/dev/null || true; fi; SINK_PID=""; } +cleanup() { stop_app; stop_sink; } + +# JVM flags for the ways of running the app. The export intervals (metrics 2 s, agent span batch 200 ms) +# are shortened so a transcript finishes in seconds; they are not the defaults. +MICROMETER_PROPS=( + -Dmanagement.opentelemetry.otlp.endpoint=http://localhost:$SINK_PORT + -Dmanagement.tracing.sampling.probability=1.0 + -Dmanagement.otlp.metrics.export.step=2s +) +AGENT_PROPS=( + -javaagent:"$DIST/agent.jar" + -Dotel.service.name=orders + -Dotel.exporter.otlp.endpoint=http://localhost:$SINK_PORT + -Dotel.exporter.otlp.protocol=http/protobuf + -Dotel.logs.exporter=none + -Dotel.metric.export.interval=2000 + -Dotel.bsp.schedule.delay=200 +) diff --git a/otel-agent-vs-micrometer/scripts/overhead.sh b/otel-agent-vs-micrometer/scripts/overhead.sh new file mode 100755 index 0000000..daa556d --- /dev/null +++ b/otel-agent-vs-micrometer/scripts/overhead.sh @@ -0,0 +1,52 @@ +#!/usr/bin/env bash +# Sourced by run-all.sh (or run directly). Measures startup, throughput, latency and RSS for +# the same endpoints under six configurations. Everything shares two vCPUs, so read the result +# as "relative cost on this box", not as production numbers. +set -euo pipefail +source "$(dirname "${BASH_SOURCE[0]}")/lib.sh" +trap cleanup EXIT +mkdir -p "$OUT" +F="$OUT/08-overhead.txt" +THREADS=4 WARM=5000 N=8000 ROUNDS=3 +AGENT_METHODS='com.ankurm.otelcmp.PricingService[price];com.ankurm.otelcmp.AuditService[write]' + +{ + echo "# 08 Overhead: same jar family, same endpoints, $THREADS client threads, $WARM warm-up + $N measured requests x $ROUNDS rounds" + echo "# JDK $(java -version 2>&1 | awk -F'"' '/version/{print $2}'), $(nproc) vCPU shared by app, OTLP sink and load driver. Indicative only." +} > "$F" + +# utime+stime of a process, in clock ticks (100 per second) +cpu_ticks() { awk '{print $14 + $15}' "/proc/$1/stat"; } + +run_cfg() { + local label="$1" jar="$2"; shift 2 + curl -s -X POST localhost:$SINK_PORT/reset >/dev/null + start_app "$jar" "$@" + sleep 4 + { + echo; echo "== $label" + echo "CPU consumed by the JVM from process start to ready (+4 s idle): $(( $(cpu_ticks "$APP_PID") * 10 )) ms" + grep -o 'Started OrdersApplication in .*' $TMPD/app.log | sed 's/)$//; s/$/)/' | head -1 + for ep in ping orders/1; do + echo "-- GET /$ep" + java "$ROOT/driver/LoadDriver.java" "http://localhost:$APP_PORT/$ep" $WARM 0 $THREADS 0 >/dev/null 2>&1 + local c0 c1 + c0=$(cpu_ticks "$APP_PID") + java "$ROOT/driver/LoadDriver.java" "http://localhost:$APP_PORT/$ep" 0 $N $THREADS $ROUNDS 2>&1 | grep -v 'Picked up' + c1=$(cpu_ticks "$APP_PID") + echo "app CPU per request: $(( (c1 - c0) * 10000 / (N * ROUNDS) )) us (utime+stime of the app JVM only, $(( N * ROUNDS )) requests)" + done + echo "-- RSS after the run: $(( $(ps -o rss= -p "$APP_PID") / 1024 )) MiB" + } >> "$F" + stop_app +} + +start_sink +run_cfg "baseline: plain jar, no instrumentation" plain +run_cfg "agent, all spans sampled" plain "${AGENT_PROPS[@]}" -Dotel.instrumentation.methods.include="$AGENT_METHODS" +run_cfg "micrometer starter, all spans sampled" micrometer "${MICROMETER_PROPS[@]}" +run_cfg "agent, 10% sampling" plain "${AGENT_PROPS[@]}" -Dotel.instrumentation.methods.include="$AGENT_METHODS" -Dotel.traces.sampler=parentbased_traceidratio -Dotel.traces.sampler.arg=0.1 +run_cfg "micrometer starter, 10% sampling" micrometer "${MICROMETER_PROPS[@]}" -Dmanagement.tracing.sampling.probability=0.1 +run_cfg "micrometer starter + JDBC observation, all spans sampled" micrometer-jdbc "${MICROMETER_PROPS[@]}" +stop_sink +echo "overhead written to $F" diff --git a/otel-agent-vs-micrometer/scripts/restclient-missing.sh b/otel-agent-vs-micrometer/scripts/restclient-missing.sh new file mode 100755 index 0000000..d84dbdc --- /dev/null +++ b/otel-agent-vs-micrometer/scripts/restclient-missing.sh @@ -0,0 +1,28 @@ +#!/usr/bin/env bash +# Boot 4 split RestClient auto-configuration out of spring-boot-starter-webmvc: without +# spring-boot-starter-restclient there is no RestClient.Builder bean. This builds a throwaway copy +# of the app without that starter and captures the startup failure. +set -euo pipefail +source "$(dirname "$0")/lib.sh" +trap cleanup EXIT +mkdir -p "$OUT" +W="$ROOT/.tmp-norest" +rm -rf "$W" || true; mkdir -p "$W" +cp -r "$ROOT/app/src" "$W/src" +python3 - "$ROOT/app/pom.xml" "$W/pom.xml" <<'PY' +import re, sys +s = open(sys.argv[1]).read() +s = re.sub(r"\s*\s*org.springframework.boot\s*spring-boot-starter-restclient\s*", "", s, count=1) +open(sys.argv[2], "w").write(s) +PY +( cd "$W" && mvn -B -q -DskipTests package ) >/dev/null +{ + echo "# 10 The same app built WITHOUT spring-boot-starter-restclient (Spring Boot 4.2.0)" + echo "# dependencies kept: spring-boot-starter-webmvc, -actuator, -jdbc, h2" + echo + # the JVM exits with status 1 on purpose here, so the pipeline's status is ignored + { java -DPORT=$APP_PORT -jar "$W/target/orders-plain.jar" 2>&1 | grep -v 'Picked up' \ + | sed -n '/APPLICATION FAILED TO START/,/Consider defining/p' | sed 's/^\*\*\*\*.*$/***************************/'; } || true +} > "$OUT/10-restclient-starter-missing.txt" +rm -rf "$W" || true +cat "$OUT/10-restclient-starter-missing.txt" diff --git a/otel-agent-vs-micrometer/scripts/run-all.sh b/otel-agent-vs-micrometer/scripts/run-all.sh new file mode 100755 index 0000000..4ad1942 --- /dev/null +++ b/otel-agent-vs-micrometer/scripts/run-all.sh @@ -0,0 +1,144 @@ +#!/usr/bin/env bash +# Regenerates every file in output/. Needs JDK 25, Maven 3.9, curl and network access to Maven Central. +# Timing-sensitive files (07, 08) will differ run to run; the span and metric files should not +# (apart from ordering of attributes and the exact lists noted in the post). +set -euo pipefail +source "$(dirname "$0")/lib.sh" +trap cleanup EXIT +mkdir -p "$OUT" +cd "$ROOT" + +[ "${SKIP_BUILD:-0}" = 1 ] || build +# build() already made plain, micrometer and sink; the third variant adds the JDBC observation library +( cd "$ROOT" && mvn -B -q -DskipTests -Pmicrometer,jdbc -pl app package ) >/dev/null +cp "$ROOT/app/target/orders-micrometer-jdbc.jar" "$DIST/" +bash "$ROOT/scripts/restclient-missing.sh" >/dev/null + +AGENT_METHODS='com.ankurm.otelcmp.PricingService[price];com.ankurm.otelcmp.AuditService[write]' + +# snapshot : print what the sink has received so far +snap() { + sleep 5 + echo "== $1"; echo + echo "-- span tree (one line per span: name [kind, instrumentation scope])" + curl -s localhost:$SINK_PORT/spans +} +# traffic: warm the app, reset the sink, then send exactly the requests the transcript describes +traffic() { + curl -s -o /dev/null localhost:$APP_PORT/orders/1 + sleep 8 # the Micrometer span exporter batches for 5 s; let the warm-up spans arrive, then discard them + curl -s -X POST localhost:$SINK_PORT/reset >/dev/null + curl -s -o /dev/null localhost:$APP_PORT/orders/1 + curl -s -o /dev/null localhost:$APP_PORT/orders/1/audited +} + +# ---- 01 agent -------------------------------------------------------------------------- +start_sink +start_app plain "${AGENT_PROPS[@]}" -Dotel.instrumentation.methods.include="$AGENT_METHODS" +traffic +{ + echo "# 01 OpenTelemetry Java agent 2.34.0 on the unmodified 'plain' jar (Spring Boot 4.2.0, JDK $(java -version 2>&1 | awk -F'"' '/version/{print $2}'))" + echo "# Requests sent after warm-up: GET /orders/1, then GET /orders/1/audited" + snap "spans" + echo; echo "-- attribute keys per span name" + curl -s localhost:$SINK_PORT/span-attrs +} > "$OUT/01-agent-spans.txt" +{ + echo "# 09 What each approach puts in the Resource (who is this service?)" + echo "# Machine-specific attributes are left out: host.name, os.*, process.pid, process.executable.path," + echo "# process.command_args and service.instance.id." + echo "== agent"; curl -s localhost:$SINK_PORT/resource | grep -v '^process.pid\|^service.instance.id\|^host.name\|^os\.\|^process.executable\|^process.command' +} > "$OUT/09-resource.txt" +curl -s localhost:$SINK_PORT/metrics > $TMPD/metrics-agent.txt +stop_app + +# ---- 02 micrometer, default conventions ----------------------------------------------------- +curl -s -X POST localhost:$SINK_PORT/reset >/dev/null +start_app micrometer "${MICROMETER_PROPS[@]}" +traffic +{ + echo "# 02 Micrometer Tracing via spring-boot-starter-opentelemetry, Spring Boot 4.2.0, default conventions" + echo "# Requests sent after warm-up: GET /orders/1, then GET /orders/1/audited (audit.executor=raw)" + snap "spans" + echo; echo "-- attribute keys per span name" + curl -s localhost:$SINK_PORT/span-attrs +} > "$OUT/02-micrometer-spans.txt" +{ echo; echo "== micrometer"; curl -s localhost:$SINK_PORT/resource | grep -v '^service.instance.id'; } >> "$OUT/09-resource.txt" +curl -s localhost:$SINK_PORT/metrics > $TMPD/metrics-micrometer.txt +stop_app + +# ---- 03 micrometer, OpenTelemetry conventions ------------------------------------------------------ +curl -s -X POST localhost:$SINK_PORT/reset >/dev/null +start_app micrometer "${MICROMETER_PROPS[@]}" -Dmanagement.observations.conventions=opentelemetry +traffic +{ + echo "# 03 Same Micrometer build with management.observations.conventions=opentelemetry (new in Spring Boot 4.2)" + snap "spans" + echo; echo "-- attribute keys per span name" + curl -s localhost:$SINK_PORT/span-attrs + sleep 1 + echo; echo "-- HTTP metrics exported" + curl -s localhost:$SINK_PORT/metrics | grep -E '^scope|http\.' | grep -E 'http\.|^scope' | grep -B1 'http\.' | grep -v '^--' +} > "$OUT/03-micrometer-otel-conventions.txt" +curl -s localhost:$SINK_PORT/metrics > $TMPD/metrics-micrometer-otelconv.txt +stop_app + +# ---- 04 metrics side by side ----------------------------------------------------------------- +{ + echo "# 04 Metrics received over OTLP, grouped by the instrumentation scope that produced them" + echo; echo "######## agent"; cat $TMPD/metrics-agent.txt + echo; echo "######## micrometer (default conventions)"; cat $TMPD/metrics-micrometer.txt +} > "$OUT/04-metrics.txt" + +# ---- 05 thread hand-off ------------------------------------------------------------------------- +{ + echo "# 05 Work handed to another thread (GET /orders/1/audited submits AuditService.write to a pool)" + echo "# One trace is expected: SERVER span with audit.write below it. Count the traces." + for cfg in "agent|plain|raw" "micrometer|micrometer|raw" "micrometer|micrometer|spring"; do + IFS='|' read -r kind jar ex <<<"$cfg" + curl -s -X POST localhost:$SINK_PORT/reset >/dev/null + if [ "$kind" = agent ]; then + start_app plain "${AGENT_PROPS[@]}" -Dotel.instrumentation.methods.include="$AGENT_METHODS" -Daudit.executor=$ex + else + start_app micrometer "${MICROMETER_PROPS[@]}" -Daudit.executor=$ex + fi + curl -s -o /dev/null localhost:$APP_PORT/orders/1/audited + sleep 8; curl -s -X POST localhost:$SINK_PORT/reset >/dev/null + curl -s -o /dev/null localhost:$APP_PORT/orders/1/audited + sleep 5 + echo; echo "== $kind, audit.executor=$ex" + curl -s localhost:$SINK_PORT/spans + stop_app + done +} > "$OUT/05-thread-handoff.txt" + +# ---- 06 JDBC gap --------------------------------------------------------------------------- +curl -s -X POST localhost:$SINK_PORT/reset >/dev/null +start_app micrometer-jdbc "${MICROMETER_PROPS[@]}" +traffic +{ + echo "# 06 Micrometer build plus net.ttddyy.observation:datasource-micrometer-spring-boot 2.3.1 (third-party)" + snap "spans" + echo; echo "-- attribute keys per span name" + curl -s localhost:$SINK_PORT/span-attrs | grep -A1 'connection\|query\|result-set' +} > "$OUT/06-micrometer-jdbc.txt" +stop_app + +# ---- 07 both at once ------------------------------------------------------------------------ +curl -s -X POST localhost:$SINK_PORT/reset >/dev/null +start_app micrometer "${MICROMETER_PROPS[@]}" -Dotel.service.name=orders "${AGENT_PROPS[@]}" +traffic +{ + echo "# 07 Micrometer build AND the agent in the same JVM, both exporting to the same sink" + snap "spans" + echo; echo "-- attribute keys per span name" + curl -s localhost:$SINK_PORT/span-attrs + echo; echo "-- url.full of the lone POST client spans" + curl -s "localhost:$SINK_PORT/span-values?name=POST&key=url.full" + echo; echo "-- HTTP server metrics received (scope, name)" + curl -s localhost:$SINK_PORT/metrics | grep -E '^scope|http\.server' | grep -B1 'http\.server' | grep -v '^--' +} > "$OUT/07-both-at-once.txt" +stop_app +stop_sink +[ "${SKIP_OVERHEAD:-0}" = 1 ] || source "$(dirname "$0")/overhead.sh" +echo "functional outputs written to $OUT" diff --git a/otel-agent-vs-micrometer/sink/pom.xml b/otel-agent-vs-micrometer/sink/pom.xml new file mode 100644 index 0000000..5eebe64 --- /dev/null +++ b/otel-agent-vs-micrometer/sink/pom.xml @@ -0,0 +1,47 @@ +<?xml version="1.0" encoding="UTF-8"?> +<project xmlns="http://maven.apache.org/POM/4.0.0" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> + <modelVersion>4.0.0</modelVersion> + <parent> + <groupId>com.ankurm</groupId> + <artifactId>otel-agent-vs-micrometer</artifactId> + <version>1.0.0</version> + </parent> + <artifactId>otlp-sink</artifactId> + + <dependencies> + <dependency> + <groupId>io.opentelemetry.proto</groupId> + <artifactId>opentelemetry-proto</artifactId> + <version>1.11.1-alpha</version> + </dependency> + <dependency> + <groupId>com.google.protobuf</groupId> + <artifactId>protobuf-java</artifactId> + </dependency> + </dependencies> + + <build> + <finalName>otlp-sink</finalName> + <plugins> + <plugin> + <artifactId>maven-shade-plugin</artifactId> + <executions> + <execution> + <phase>package</phase> + <goals><goal>shade</goal></goals> + <configuration> + <transformers combine.self="override"> + <transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer"> + <mainClass>com.ankurm.otelcmp.sink.OtlpSink</mainClass> + </transformer> + </transformers> + <createDependencyReducedPom>false</createDependencyReducedPom> + </configuration> + </execution> + </executions> + </plugin> + </plugins> + </build> +</project> diff --git a/otel-agent-vs-micrometer/sink/src/main/java/com/ankurm/otelcmp/sink/OtlpSink.java b/otel-agent-vs-micrometer/sink/src/main/java/com/ankurm/otelcmp/sink/OtlpSink.java new file mode 100644 index 0000000..7205763 --- /dev/null +++ b/otel-agent-vs-micrometer/sink/src/main/java/com/ankurm/otelcmp/sink/OtlpSink.java @@ -0,0 +1,180 @@ +package com.ankurm.otelcmp.sink; + +import com.sun.net.httpserver.HttpExchange; +import com.sun.net.httpserver.HttpServer; +import io.opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceRequest; +import io.opentelemetry.proto.collector.trace.v1.ExportTraceServiceRequest; +import io.opentelemetry.proto.common.v1.AnyValue; +import io.opentelemetry.proto.common.v1.KeyValue; +import io.opentelemetry.proto.metrics.v1.Metric; +import io.opentelemetry.proto.trace.v1.Span; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.net.InetSocketAddress; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.TreeMap; +import java.util.TreeSet; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.zip.GZIPInputStream; + +/** + * A minimal OTLP/HTTP (protobuf) receiver that decodes what it is sent, so a transcript can show + * real span names, kinds, parent links and attribute keys instead of grepping raw bytes. + * + * POST /v1/traces, /v1/metrics receive OTLP; /v1/logs is accepted and ignored + * POST /reset forget everything + * GET /spans span tree, one line per span + * GET /span-attrs attribute KEYS per span name (values are not printed) + * GET /span-values?name=POST&key=url.full the values of one attribute on spans with that name + * GET /metrics metric names with type and unit, per instrumentation scope + * GET /resource resource attribute keys and values of what was received + */ +public class OtlpSink { + + record SpanRec(String scope, String traceId, String spanId, String parentId, String name, + String kind, Map<String, String> attrs, long startNs, long endNs, String status) {} + + record MetricRec(String scope, String name, String type, String unit) {} + + static final List<SpanRec> SPANS = new CopyOnWriteArrayList<>(); + static final List<MetricRec> METRICS = new CopyOnWriteArrayList<>(); + static final Map<String, String> RESOURCE = new java.util.concurrent.ConcurrentHashMap<>(); + + public static void main(String[] args) throws Exception { + int port = args.length > 0 ? Integer.parseInt(args[0]) : 4318; + HttpServer server = HttpServer.create(new InetSocketAddress(port), 0); + server.createContext("/v1/traces", ex -> receive(ex, true)); + server.createContext("/v1/metrics", ex -> receive(ex, false)); + server.createContext("/v1/logs", ex -> { ex.getRequestBody().readAllBytes(); reply(ex, 200, ""); }); + server.createContext("/reset", ex -> { SPANS.clear(); METRICS.clear(); RESOURCE.clear(); reply(ex, 200, "reset\n"); }); + server.createContext("/spans", ex -> reply(ex, 200, spanTree())); + server.createContext("/span-attrs", ex -> reply(ex, 200, spanAttrs())); + server.createContext("/metrics", ex -> reply(ex, 200, metricList())); + server.createContext("/span-values", ex -> reply(ex, 200, spanValues(ex.getRequestURI().getQuery()))); + server.createContext("/resource", ex -> reply(ex, 200, resource())); + server.start(); + System.out.println("otlp-sink listening on " + port); + } + + static void receive(HttpExchange ex, boolean traces) throws IOException { + try (InputStream in = ex.getRequestBody()) { + byte[] body = in.readAllBytes(); + if ("gzip".equalsIgnoreCase(ex.getRequestHeaders().getFirst("Content-Encoding"))) { + body = new GZIPInputStream(new java.io.ByteArrayInputStream(body)).readAllBytes(); + } + if (traces) { + for (var rs : ExportTraceServiceRequest.parseFrom(body).getResourceSpansList()) { + for (KeyValue kv : rs.getResource().getAttributesList()) RESOURCE.put(kv.getKey(), str(kv.getValue())); + for (var ss : rs.getScopeSpansList()) { + for (Span s : ss.getSpansList()) { + Map<String, String> attrs = new TreeMap<>(); + for (KeyValue kv : s.getAttributesList()) attrs.put(kv.getKey(), str(kv.getValue())); + SPANS.add(new SpanRec(ss.getScope().getName(), hex(s.getTraceId().toByteArray()), + hex(s.getSpanId().toByteArray()), hex(s.getParentSpanId().toByteArray()), + s.getName(), s.getKind().name().replace("SPAN_KIND_", ""), attrs, + s.getStartTimeUnixNano(), s.getEndTimeUnixNano(), s.getStatus().getCode().name().replace("STATUS_CODE_", ""))); + } + } + } + } else { + for (var rm : ExportMetricsServiceRequest.parseFrom(body).getResourceMetricsList()) { + for (var sm : rm.getScopeMetricsList()) { + for (Metric m : sm.getMetricsList()) { + METRICS.add(new MetricRec(sm.getScope().getName(), m.getName(), m.getDataCase().name(), m.getUnit())); + } + } + } + } + } catch (Exception e) { + System.err.println("decode failed: " + e); + } + reply(ex, 200, ""); + } + + static String spanTree() { + List<SpanRec> spans = new ArrayList<>(SPANS); + Map<String, List<SpanRec>> byTrace = new LinkedHashMap<>(); + spans.stream().sorted(Comparator.comparingLong(SpanRec::startNs)) + .forEach(s -> byTrace.computeIfAbsent(s.traceId(), k -> new ArrayList<>()).add(s)); + StringBuilder sb = new StringBuilder(); + int n = 1; + for (var e : byTrace.entrySet()) { + sb.append("trace ").append(n++).append(" (").append(e.getValue().size()).append(" spans)\n"); + Map<String, SpanRec> ids = new LinkedHashMap<>(); + e.getValue().forEach(s -> ids.put(s.spanId(), s)); + for (SpanRec s : e.getValue()) { + if (s.parentId().isEmpty() || !ids.containsKey(s.parentId())) { + print(sb, s, e.getValue(), 1, s.parentId().isEmpty() ? "" : " [parent not in this trace]"); + } + } + } + return sb.toString(); + } + + static void print(StringBuilder sb, SpanRec s, List<SpanRec> all, int depth, String note) { + sb.append(" ".repeat(depth)).append(s.name()).append(" [").append(s.kind()).append(", scope=") + .append(s.scope()).append(s.status().equals("UNSET") ? "" : ", status=" + s.status()).append("]").append(note).append('\n'); + all.stream().filter(c -> c.parentId().equals(s.spanId())).sorted(Comparator.comparingLong(SpanRec::startNs)) + .forEach(c -> print(sb, c, all, depth + 1, "")); + } + + static String spanAttrs() { + Map<String, TreeSet<String>> byName = new TreeMap<>(); + for (SpanRec s : SPANS) byName.computeIfAbsent(s.name() + " [" + s.kind() + "]", k -> new TreeSet<>()).addAll(s.attrs().keySet()); + StringBuilder sb = new StringBuilder(); + byName.forEach((k, v) -> sb.append(k).append("\n ").append(String.join(", ", v)).append('\n')); + return sb.toString(); + } + + static String spanValues(String query) { + Map<String, String> q = new LinkedHashMap<>(); + for (String kv : query.split("&")) { String[] p = kv.split("=", 2); q.put(p[0], java.net.URLDecoder.decode(p[1], StandardCharsets.UTF_8)); } + StringBuilder sb = new StringBuilder(); + new TreeSet<>(SPANS.stream().filter(s -> s.name().equals(q.get("name"))) + .map(s -> s.attrs().getOrDefault(q.get("key"), "(absent)")).toList()).forEach(v -> sb.append(v).append('\n')); + return sb.toString(); + } + + static String metricList() { + Map<String, TreeSet<String>> byScope = new TreeMap<>(); + for (MetricRec m : METRICS) { + byScope.computeIfAbsent(m.scope().isEmpty() ? "(no scope name)" : m.scope(), k -> new TreeSet<>()) + .add(m.name() + " " + m.type().toLowerCase() + (m.unit().isEmpty() ? "" : " unit=" + m.unit())); + } + StringBuilder sb = new StringBuilder(); + byScope.forEach((k, v) -> { sb.append("scope ").append(k).append(" (").append(v.size()).append(" metrics)\n"); v.forEach(x -> sb.append(" ").append(x).append('\n')); }); + return sb.toString(); + } + + static String resource() { + StringBuilder sb = new StringBuilder(); + new TreeMap<>(RESOURCE).forEach((k, v) -> sb.append(k).append(" = ").append(v).append('\n')); + return sb.toString(); + } + + static String str(AnyValue v) { + return switch (v.getValueCase()) { + case STRING_VALUE -> v.getStringValue(); + case INT_VALUE -> Long.toString(v.getIntValue()); + case BOOL_VALUE -> Boolean.toString(v.getBoolValue()); + case DOUBLE_VALUE -> Double.toString(v.getDoubleValue()); + default -> v.getValueCase().name().toLowerCase(); + }; + } + + static String hex(byte[] b) { return HexFormat.of().formatHex(b); } + + static void reply(HttpExchange ex, int code, String body) throws IOException { + byte[] out = body.getBytes(StandardCharsets.UTF_8); + ex.sendResponseHeaders(code, out.length == 0 ? -1 : out.length); + if (out.length > 0) ex.getResponseBody().write(out); + ex.close(); + } +}