Distributed Torres even asynchronously! Link Cloud Tasks and Cloud Trace

Introduction

Google's distributed trace monitoring CloudTrace is based on or based on OpenCensus, so you can trace properly even with asynchronous processing as well.

So, I implemented asynchronous processing this time using CloudTasks, but I didn't write how to do it in the manual, so I made a note.

manner

First, the code to execute CloudTasks in Java. This is basically the tutorial.

try ( var client = CloudTasksClient.create()) {
    var queuePath = QueueName.of(projectId, locationId, queueId).toString();

    var traceparent = getTraceparent();
    var taskBuilder = Task.newBuilder()
            .setHttpRequest(HttpRequest.newBuilder()
                    .putHeaders("traceparent", traceparent)
                    .setUrl("http://locahost:9000")
                    .setHttpMethod(HttpMethod.GET)
                    .build());

    // Send create task request.
    var task = client.createTask(queuePath, taskBuilder.build());
    logger.debug("task-create", $("taskid", task.getName()));
}

The point is that we use traceparent in the HTTP headers. [Previous article](https://qiita.com/koduki/items/200da6983ccc0d7cf3ca As I wrote in), if you do not propagate the context with this, the request itself will be reflected, but it will not be recognized by CloudTrace as a series of requests.

So generate a traceparent from the current Span with code like this:

private static final Setter<Map<String, String>> setter = new Setter<Map<String, String>>() {
    @Override
    public void put(Map<String, String> carrier, String key, String value) {
        carrier.put(key, value);
    }
};

public String getTraceparent() {
    var traceContextFormat = new TraceContextFormat();

    var current = Tracing.getTracer().getCurrentSpan().getContext();
    var carrier = new LinkedHashMap<String, String>();
    traceContextFormat.inject(
            SpanContext.create(current.getTraceId(), current.getSpanId(), current.getTraceOptions(), current.getTracestate()),
            carrier,
            setter);
    var traceparent = carrier.get("traceparent");

    return traceparent;
}

As a prerequisite, you need to put ʻopencensus-api` as a dependency.

The main traceparents are TraceContextFormat and Setter <Map <String, String >>. By passing the Span ID and Span ID to this guy, it will be converted in the following format.

image.png

You can create it yourself, but the format is subtly cumbersome, so there's no reason not to use the existing code.

Now, the asynchronous processing is traced properly as below. image.png

reference:

Recommended Posts

Distributed Torres even asynchronously! Link Cloud Tasks and Cloud Trace