Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions sdk-tests/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -290,6 +290,10 @@
<include name="io/dapr/it/tracing/http/OpenTelemetryInterceptor$*.class"/>
<include name="io/dapr/it/tracing/http/OpenTelemetryInterceptorConfig.class"/>
<include name="io/dapr/it/tracing/http/OpenTelemetryInterceptorConfig$*.class"/>
<include name="io/dapr/it/tracing/grpc/TracingIT.class"/>
<include name="io/dapr/it/tracing/grpc/TracingIT$*.class"/>
<include name="io/dapr/it/tracing/grpc/Service.class"/>
<include name="io/dapr/it/tracing/grpc/Service$*.class"/>
</fileset>
</delete>
</target>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
/*
* Copyright 2026 The Dapr Authors
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.dapr.it.testcontainers.tracing;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;

import static org.junit.jupiter.api.Assertions.fail;

/** Assertions for traces exported by the containerized tracing applications. */
public final class TraceAssertions {
private TraceAssertions() {
}

/**
* Waits for the named client span and its exact child in the same trace, with child duration over one second.
* @param zipkin Zipkin endpoint reachable from the test JVM.
* @param traceId Expected trace ID.
* @param parentId Expected client span ID and child parent ID.
* @param spanName Unique client span name.
* @param childName Exact expected child span name.
* @throws Exception If querying fails or the wait is interrupted.
*/
public static void awaitTrace(URI zipkin, String traceId, String parentId, String spanName, String childName)
throws Exception {
HttpClient http = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(3)).build();
ObjectMapper mapper = new ObjectMapper();
URI traceUri = zipkin.resolve("/api/v2/trace/" + traceId);
long deadline = System.nanoTime() + Duration.ofSeconds(45).toNanos();
String lastObservation = "no response";
String lastError = "none";
while (System.nanoTime() < deadline) {
HttpRequest request = HttpRequest.newBuilder(traceUri).timeout(Duration.ofSeconds(3)).GET().build();
try {
HttpResponse<String> response = http.send(request, HttpResponse.BodyHandlers.ofString());
lastObservation = "HTTP " + response.statusCode() + ": " + response.body();
if (response.statusCode() == 200) {
JsonNode spans = mapper.readTree(response.body());
if (!spans.isArray()) {
throw new IllegalStateException("Unexpected Zipkin trace response: " + lastObservation);
}
boolean parentFound = false;
boolean childFound = false;
for (JsonNode candidate : spans) {
if (!traceId.equals(candidate.path("traceId").asText())) {
continue;
}
parentFound |= parentId.equals(candidate.path("id").asText())
&& spanName.equals(candidate.path("name").asText());
childFound |= parentId.equals(candidate.path("parentId").asText())
&& childName.equals(candidate.path("name").asText())
&& candidate.path("duration").asLong() > 1_000_000;
}
if (parentFound && childFound) {
System.out.printf("Trace validated: %s%n", response.body());
return;
}
}
} catch (JsonProcessingException e) {
throw new IllegalStateException("Invalid Zipkin trace response: " + lastObservation, e);
} catch (IOException e) {
lastError = e.toString();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw e;
}
try {
Thread.sleep(250);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw e;
}
}
fail("Timed out waiting for traceId=" + traceId + " client=" + spanName + " parentId=" + parentId
+ " child=" + childName + " duration > 1000000us; last observation: " + lastObservation
+ "; last request error: " + lastError);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
/*
* Copyright 2026 The Dapr Authors
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.dapr.it.testcontainers.tracing.grpc;

import io.dapr.client.DaprClient;
import io.dapr.client.domain.HttpExtension;
import io.dapr.it.testcontainers.support.DaprTestEnvironment;
import io.dapr.it.testcontainers.support.Endpoints;
import io.dapr.it.testcontainers.tracing.grpc.app.Service;
import io.dapr.testcontainers.Configuration;
import io.dapr.testcontainers.DaprProtocol;
import io.dapr.testcontainers.TracingConfigurationSettings;
import io.dapr.testcontainers.ZipkinTracingConfigurationSettings;
import io.opentelemetry.api.trace.Span;
import io.opentelemetry.api.trace.SpanKind;
import io.opentelemetry.api.trace.propagation.W3CTraceContextPropagator;
import io.opentelemetry.context.Scope;
import io.opentelemetry.context.propagation.ContextPropagators;
import io.opentelemetry.exporter.zipkin.ZipkinSpanExporter;
import io.opentelemetry.sdk.OpenTelemetrySdk;
import io.opentelemetry.sdk.common.CompletableResultCode;
import io.opentelemetry.sdk.trace.SdkTracerProvider;
import io.opentelemetry.sdk.trace.export.SimpleSpanProcessor;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import org.testcontainers.containers.GenericContainer;
import org.testcontainers.containers.wait.strategy.Wait;
import org.testcontainers.junit.jupiter.Container;
import org.testcontainers.junit.jupiter.Testcontainers;

import java.net.URI;
import java.time.Duration;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

import static io.dapr.it.MethodInvokeServiceProtos.SleepRequest;
import static io.dapr.it.testcontainers.tracing.TraceAssertions.awaitTrace;
import static io.dapr.it.tracing.OpenTelemetry.getReactorContext;
import static org.junit.jupiter.api.Assertions.assertTrue;

/** Exercises trace propagation through a real Dapr gRPC application callback. */
@Testcontainers
@Tag("testcontainers")
public class TracingIT {
private static final String APP_NAME = "tracing-grpc-it";
private static final int ZIPKIN_PORT = 9411;
private static final String CHILD_NAME = "calllocal/" + APP_NAME + "/sleepovergrpc";
private static final GenericContainer<?> ZIPKIN = new GenericContainer<>("openzipkin/zipkin:3.4")
.withExposedPorts(ZIPKIN_PORT)
.waitingFor(Wait.forHttp("/health").forPort(ZIPKIN_PORT).forStatusCode(200)
.withStartupTimeout(Duration.ofMinutes(2)));

@Container
private static final DaprTestEnvironment ENVIRONMENT = new DaprTestEnvironment(APP_NAME, Service.class,
DaprProtocol.GRPC)
.withPrerequisite(ZIPKIN, "zipkin", List.of())
.withConfiguration(new Configuration("tracing", new TracingConfigurationSettings("1", true, null,
new ZipkinTracingConfigurationSettings("http://zipkin:9411/api/v2/spans")), null));

@Test
public void testInvoke() throws Exception {
URI zipkin = Endpoints.http(ZIPKIN.getHost(), ZIPKIN.getMappedPort(ZIPKIN_PORT));
String spanName = UUID.randomUUID().toString();
try (SdkTracerProvider provider = SdkTracerProvider.builder().addSpanProcessor(SimpleSpanProcessor.create(
ZipkinSpanExporter.builder().setEndpoint(zipkin.resolve("/api/v2/spans").toString()).build())).build()) {
OpenTelemetrySdk telemetry = OpenTelemetrySdk.builder().setTracerProvider(provider)
.setPropagators(ContextPropagators.create(W3CTraceContextPropagator.getInstance())).build();
Span span = telemetry.getTracer("grpc integration test tracer").spanBuilder(spanName)
.setSpanKind(SpanKind.CLIENT).startSpan();
try {
try (DaprClient client = ENVIRONMENT.clientBuilder().build(); Scope scope = span.makeCurrent()) {
SleepRequest request = SleepRequest.newBuilder().setSeconds(1).build();
client.invokeMethod(APP_NAME, "sleepOverGRPC", request.toByteArray(), HttpExtension.POST)
.contextWrite(getReactorContext(telemetry)).block(Duration.ofSeconds(30));
}
} finally {
span.end();
}

CompletableResultCode flushed = provider.forceFlush().join(10, TimeUnit.SECONDS);
assertTrue(flushed.isSuccess(), "Client span export did not flush within 10 seconds");
awaitTrace(zipkin, span.getSpanContext().getTraceId(), span.getSpanContext().getSpanId(), spanName, CHILD_NAME);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,10 @@
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
limitations under the License.
*/
* limitations under the License.
*/

package io.dapr.it.tracing.grpc;
package io.dapr.it.testcontainers.tracing.grpc.app;

import com.google.protobuf.Any;
import io.dapr.grpc.GrpcHealthCheckService;
Expand All @@ -22,10 +22,12 @@
import io.grpc.stub.StreamObserver;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import static io.dapr.it.MethodInvokeServiceProtos.SleepRequest;
import static io.dapr.it.MethodInvokeServiceProtos.SleepResponse;

/** Dapr application callback fixture for the gRPC tracing integration test. */
public class Service {

public static final String SUCCESS_MESSAGE = "application discovered on port ";
Expand All @@ -51,18 +53,36 @@ private void start(int port) throws IOException {
.forPort(port)
.addService(this)
.addService(new GrpcHealthCheckService())
.build()
.start();
.build();
this.server.start();
System.out.printf("Server: started listening on port %d\n", port);

// Now we handle ctrl+c (or any other JVM shutdown)
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
System.out.println("Server: shutting down gracefully ...");
MyDaprService.this.server.shutdown();
MyDaprService.this.stop();
System.out.println("Server: Bye.");
}));
}

private void stop() {
if (server == null) {
return;
}
server.shutdown();
try {
if (!server.awaitTermination(5, TimeUnit.SECONDS)) {
server.shutdownNow();
if (!server.awaitTermination(5, TimeUnit.SECONDS)) {
throw new IllegalStateException("gRPC callback server did not terminate");
}
}
} catch (InterruptedException e) {
server.shutdownNow();
Thread.currentThread().interrupt();
}
}

/**
* Server mode: waits for shutdown trigger.
*
Expand Down Expand Up @@ -93,10 +113,9 @@ public void onInvoke(CommonProtos.InvokeRequest request,
responseBuilder.setData(Any.pack(res));
responseObserver.onNext(responseBuilder.build());
}
responseObserver.onCompleted();
} catch (Exception e) {
responseObserver.onError(e);
} finally {
responseObserver.onCompleted();
}
}

Expand All @@ -109,7 +128,7 @@ public SleepResponse sleep(SleepRequest request) {
Thread.sleep(request.getSeconds() * 1000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
new RuntimeException(e);
throw new IllegalStateException("gRPC callback sleep interrupted", e);
}

// Now respond with current timestamp.
Expand All @@ -128,7 +147,11 @@ public static void main(String[] args) throws Exception {
System.out.printf("Service starting on port %d ...\n", port);

final MyDaprService service = new MyDaprService();
service.start(port);
service.awaitTermination();
try {
service.start(port);
service.awaitTermination();
} finally {
service.stop();
}
}
}
Loading
Loading