Search in sources :

Example 1 with Kind

use of zipkin2.Span.Kind in project brave by openzipkin.

the class TracingFilter method invoke.

@Override
public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
    if (tracer == null)
        return invoker.invoke(invocation);
    RpcContext rpcContext = RpcContext.getContext();
    Kind kind = rpcContext.isProviderSide() ? Kind.SERVER : Kind.CLIENT;
    final Span span;
    if (kind.equals(Kind.CLIENT)) {
        span = tracer.nextSpan();
        injector.inject(span.context(), invocation.getAttachments());
    } else {
        TraceContextOrSamplingFlags extracted = extractor.extract(invocation.getAttachments());
        span = extracted.context() != null ? tracer.joinSpan(extracted.context()) : tracer.nextSpan(extracted);
    }
    if (!span.isNoop()) {
        span.kind(kind).start();
        String service = invoker.getInterface().getSimpleName();
        String method = RpcUtils.getMethodName(invocation);
        span.kind(kind);
        span.name(service + "/" + method);
        InetSocketAddress remoteAddress = rpcContext.getRemoteAddress();
        Endpoint.Builder remoteEndpoint = Endpoint.newBuilder().port(remoteAddress.getPort());
        if (!remoteEndpoint.parseIp(remoteAddress.getAddress())) {
            remoteEndpoint.parseIp(remoteAddress.getHostName());
        }
        span.remoteEndpoint(remoteEndpoint.build());
    }
    boolean isOneway = false, deferFinish = false;
    try (Tracer.SpanInScope scope = tracer.withSpanInScope(span)) {
        Result result = invoker.invoke(invocation);
        if (result.hasException()) {
            onError(result.getException(), span.customizer());
        }
        isOneway = RpcUtils.isOneway(invoker.getUrl(), invocation);
        // the case on async client invocation
        Future<Object> future = rpcContext.getFuture();
        if (future instanceof FutureAdapter) {
            deferFinish = true;
            ((FutureAdapter) future).getFuture().setCallback(new FinishSpanCallback(span));
        }
        return result;
    } catch (Error | RuntimeException e) {
        onError(e, span.customizer());
        throw e;
    } finally {
        if (isOneway) {
            span.flush();
        } else if (!deferFinish) {
            span.finish();
        }
    }
}
Also used : InetSocketAddress(java.net.InetSocketAddress) Tracer(brave.Tracer) FutureAdapter(com.alibaba.dubbo.rpc.protocol.dubbo.FutureAdapter) Span(brave.Span) Result(com.alibaba.dubbo.rpc.Result) RpcContext(com.alibaba.dubbo.rpc.RpcContext) Endpoint(zipkin2.Endpoint) Kind(brave.Span.Kind) TraceContextOrSamplingFlags(brave.propagation.TraceContextOrSamplingFlags)

Example 2 with Kind

use of zipkin2.Span.Kind in project brave by openzipkin.

the class ITHttpClient method redirect.

@Test
public void redirect() throws Exception {
    Tracer tracer = httpTracing.tracing().tracer();
    server.enqueue(new MockResponse().setResponseCode(302).addHeader("Location: " + url("/bar")));
    // hehe to a bad location!
    server.enqueue(new MockResponse().setResponseCode(404));
    brave.Span parent = tracer.newTrace().name("test").start();
    try (SpanInScope ws = tracer.withSpanInScope(parent)) {
        get(client, "/foo");
    } catch (RuntimeException e) {
    // some think 404 is an exception
    } finally {
        parent.finish();
    }
    Span client1 = takeSpan();
    Span client2 = takeSpan();
    assertThat(Arrays.asList(client1.tags().get("http.path"), client2.tags().get("http.path"))).contains("/foo", "/bar");
    // local
    assertThat(takeSpan().kind()).isNull();
}
Also used : MockResponse(okhttp3.mockwebserver.MockResponse) Tracer(brave.Tracer) SpanInScope(brave.Tracer.SpanInScope) Span(zipkin2.Span) Test(org.junit.Test)

Example 3 with Kind

use of zipkin2.Span.Kind in project brave by openzipkin.

the class TracingConsumer method poll.

/**
 * This
 */
@Override
public ConsumerRecords<K, V> poll(long timeout) {
    ConsumerRecords<K, V> records = delegate.poll(timeout);
    if (records.isEmpty() || tracing.isNoop())
        return records;
    Map<String, Span> consumerSpansForTopic = new LinkedHashMap<>();
    for (TopicPartition partition : records.partitions()) {
        String topic = partition.topic();
        List<ConsumerRecord<K, V>> recordsInPartition = records.records(partition);
        for (int i = 0, length = recordsInPartition.size(); i < length; i++) {
            ConsumerRecord<K, V> record = recordsInPartition.get(i);
            TraceContextOrSamplingFlags extracted = extractor.extract(record.headers());
            // make or reuse a span for this topic
            if (extracted.samplingFlags() != null && extracted.extra().isEmpty()) {
                Span consumerSpanForTopic = consumerSpansForTopic.get(topic);
                if (consumerSpanForTopic == null) {
                    consumerSpansForTopic.put(topic, consumerSpanForTopic = tracing.tracer().nextSpan(extracted).name("poll").kind(Span.Kind.CONSUMER).tag(KafkaTags.KAFKA_TOPIC_TAG, topic).start());
                }
                // no need to remove propagation headers as we failed to extract anything
                injector.inject(consumerSpanForTopic.context(), record.headers());
            } else {
                // we extracted request-scoped data, so cannot share a consumer span.
                Span span = tracing.tracer().nextSpan(extracted);
                if (!span.isNoop()) {
                    span.name("poll").kind(Span.Kind.CONSUMER).tag(KafkaTags.KAFKA_TOPIC_TAG, topic);
                    if (remoteServiceName != null) {
                        span.remoteEndpoint(Endpoint.newBuilder().serviceName(remoteServiceName).build());
                    }
                    // span won't be shared by other records
                    span.start().finish();
                }
                // remove prior propagation headers from the record
                tracing.propagation().keys().forEach(key -> record.headers().remove(key));
                injector.inject(span.context(), record.headers());
            }
        }
    }
    consumerSpansForTopic.values().forEach(span -> {
        if (remoteServiceName != null) {
            span.remoteEndpoint(Endpoint.newBuilder().serviceName(remoteServiceName).build());
        }
        span.finish();
    });
    return records;
}
Also used : Span(brave.Span) ConsumerRecord(org.apache.kafka.clients.consumer.ConsumerRecord) Endpoint(zipkin2.Endpoint) LinkedHashMap(java.util.LinkedHashMap) TopicPartition(org.apache.kafka.common.TopicPartition) TraceContextOrSamplingFlags(brave.propagation.TraceContextOrSamplingFlags)

Example 4 with Kind

use of zipkin2.Span.Kind in project brave by openzipkin.

the class ITTracingCallFactory method currentSpanVisibleToUserInterceptors.

@Test
public void currentSpanVisibleToUserInterceptors() throws Exception {
    Tracer tracer = httpTracing.tracing().tracer();
    server.enqueue(new MockResponse());
    closeClient(client);
    client = TracingCallFactory.create(httpTracing, new OkHttpClient.Builder().addInterceptor(chain -> chain.proceed(chain.request().newBuilder().addHeader("my-id", currentTraceContext.get().traceIdString()).build())).build());
    brave.Span parent = tracer.newTrace().name("test").start();
    try (Tracer.SpanInScope ws = tracer.withSpanInScope(parent)) {
        get(client, "/foo");
    } finally {
        parent.finish();
    }
    RecordedRequest request = server.takeRequest();
    assertThat(request.getHeader("x-b3-traceId")).isEqualTo(request.getHeader("my-id"));
    // we report one local and one client span
    assertThat(Arrays.asList(takeSpan(), takeSpan())).extracting(Span::kind).containsOnly(null, Span.Kind.CLIENT);
}
Also used : Arrays(java.util.Arrays) Request(okhttp3.Request) Tracer(brave.Tracer) ITHttpAsyncClient(brave.test.http.ITHttpAsyncClient) RecordedRequest(okhttp3.mockwebserver.RecordedRequest) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) Span(zipkin2.Span) IOException(java.io.IOException) Test(org.junit.Test) RequestBody(okhttp3.RequestBody) TimeUnit(java.util.concurrent.TimeUnit) OkHttpClient(okhttp3.OkHttpClient) Response(okhttp3.Response) Call(okhttp3.Call) Callback(okhttp3.Callback) MockResponse(okhttp3.mockwebserver.MockResponse) MediaType(okhttp3.MediaType) RecordedRequest(okhttp3.mockwebserver.RecordedRequest) MockResponse(okhttp3.mockwebserver.MockResponse) Tracer(brave.Tracer) Test(org.junit.Test)

Example 5 with Kind

use of zipkin2.Span.Kind in project brave by openzipkin.

the class TracingRabbitListenerAdviceTest method reports_span_if_consume_fails.

@Test
public void reports_span_if_consume_fails() throws Throwable {
    Message message = MessageBuilder.withBody(new byte[] {}).build();
    onMessageConsumeFailed(message, new RuntimeException("expected exception"));
    assertThat(reportedSpans).extracting(Span::kind).containsExactly(CONSUMER, null);
    assertThat(reportedSpans).filteredOn(span -> span.kind() == null).extracting(Span::tags).extracting(tags -> tags.get("error")).contains("expected exception");
}
Also used : Tracing(brave.Tracing) MessageBuilder(org.springframework.amqp.core.MessageBuilder) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) Span(zipkin2.Span) Test(org.junit.Test) MessageProperties(org.springframework.amqp.core.MessageProperties) Mockito.when(org.mockito.Mockito.when) ArrayList(java.util.ArrayList) List(java.util.List) Sampler(brave.sampler.Sampler) MethodInvocation(org.aopalliance.intercept.MethodInvocation) Message(org.springframework.amqp.core.Message) Assert.fail(org.junit.Assert.fail) CONSUMER(zipkin2.Span.Kind.CONSUMER) Before(org.junit.Before) Mockito.mock(org.mockito.Mockito.mock) Message(org.springframework.amqp.core.Message) Span(zipkin2.Span) Test(org.junit.Test)

Aggregations

Span (zipkin2.Span)82 Test (org.junit.Test)54 Endpoint (zipkin2.Endpoint)25 Test (org.junit.jupiter.api.Test)17 V1Span (zipkin2.v1.V1Span)10 TraceSpan (com.google.devtools.cloudtrace.v1.TraceSpan)8 IOException (java.io.IOException)6 Map (java.util.Map)5 TestObjects.newClientSpan (zipkin2.TestObjects.newClientSpan)5 Tracer (brave.Tracer)4 Tracing (brave.Tracing)4 Trace (com.google.devtools.cloudtrace.v1.Trace)4 ArrayList (java.util.ArrayList)4 List (java.util.List)4 Assertions.assertThat (org.assertj.core.api.Assertions.assertThat)4 Before (org.junit.Before)4 SpringBootTest (org.springframework.boot.test.context.SpringBootTest)4 Span (brave.Span)3 Sampler (brave.sampler.Sampler)3 Annotation (zipkin2.Annotation)3