Search in sources :

Example 96 with TraceContext

use of brave.propagation.TraceContext in project brave by openzipkin.

the class ITTracingFilter_Consumer method usesParentFromInvocationTime.

/**
 * This tests that the parent is determined at the time the request was made, not when the request
 * was executed.
 */
@Test
public void usesParentFromInvocationTime() {
    TraceContext parent = newTraceContext(SamplingFlags.SAMPLED);
    try (Scope scope = currentTraceContext.newScope(parent)) {
        RpcContext.getContext().asyncCall(() -> client.get().sayHello("jorge"));
        RpcContext.getContext().asyncCall(() -> client.get().sayHello("romeo"));
    }
    try (Scope scope = currentTraceContext.newScope(null)) {
        // complete within a different scope
        for (int i = 0; i < 2; i++) {
            TraceContext extracted = server.takeRequest().context();
            assertChildOf(extracted, parent);
        }
    }
    // The spans may report in a different order than the requests
    for (int i = 0; i < 2; i++) {
        assertChildOf(testSpanHandler.takeRemoteSpan(CLIENT), parent);
    }
}
Also used : Scope(brave.propagation.CurrentTraceContext.Scope) TraceContext(brave.propagation.TraceContext) Test(org.junit.Test)

Example 97 with TraceContext

use of brave.propagation.TraceContext in project brave by openzipkin.

the class ITTracingFilter_Consumer method propagatesBaggage_unsampled.

@Test
public void propagatesBaggage_unsampled() {
    TraceContext parent = newTraceContext(SamplingFlags.NOT_SAMPLED);
    try (Scope scope = currentTraceContext.newScope(parent)) {
        BAGGAGE_FIELD.updateValue(parent, "joey");
        client.get().sayHello("jorge");
    }
    TraceContext extracted = server.takeRequest().context();
    assertThat(BAGGAGE_FIELD.getValue(extracted)).isEqualTo("joey");
}
Also used : Scope(brave.propagation.CurrentTraceContext.Scope) TraceContext(brave.propagation.TraceContext) Test(org.junit.Test)

Example 98 with TraceContext

use of brave.propagation.TraceContext in project brave by openzipkin.

the class ITTracingFilter_Consumer method customParser.

@Test
public void customParser() {
    Tag<DubboResponse> javaValue = new Tag<DubboResponse>("dubbo.result_value") {

        @Override
        protected String parseValue(DubboResponse input, TraceContext context) {
            Result result = input.result();
            if (result == null)
                return null;
            Object value = result.getValue();
            if (value instanceof JavaBeanDescriptor) {
                return String.valueOf(((JavaBeanDescriptor) value).getProperty("value"));
            }
            return null;
        }
    };
    RpcTracing rpcTracing = RpcTracing.newBuilder(tracing).clientResponseParser((res, context, span) -> {
        RpcResponseParser.DEFAULT.parse(res, context, span);
        if (res instanceof DubboResponse) {
            javaValue.tag((DubboResponse) res, span);
        }
    }).build();
    init().setRpcTracing(rpcTracing);
    String javaResult = client.get().sayHello("jorge");
    assertThat(testSpanHandler.takeRemoteSpan(CLIENT).tags()).containsEntry("dubbo.result_value", javaResult);
}
Also used : ReferenceConfig(com.alibaba.dubbo.config.ReferenceConfig) Result(com.alibaba.dubbo.rpc.Result) RpcResponseParser(brave.rpc.RpcResponseParser) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) ALWAYS_SAMPLE(brave.sampler.Sampler.ALWAYS_SAMPLE) ApplicationConfig(com.alibaba.dubbo.config.ApplicationConfig) Assertions.assertThatThrownBy(org.assertj.core.api.Assertions.assertThatThrownBy) RpcRuleSampler(brave.rpc.RpcRuleSampler) RpcContext(com.alibaba.dubbo.rpc.RpcContext) RpcRequestMatchers.methodEquals(brave.rpc.RpcRequestMatchers.methodEquals) RpcRequestMatchers.serviceEquals(brave.rpc.RpcRequestMatchers.serviceEquals) Before(org.junit.Before) CLIENT(brave.Span.Kind.CLIENT) JavaBeanDescriptor(com.alibaba.dubbo.common.beanutil.JavaBeanDescriptor) Test(org.junit.Test) RpcException(com.alibaba.dubbo.rpc.RpcException) TraceContext(brave.propagation.TraceContext) Clock(brave.Clock) RpcTracing(brave.rpc.RpcTracing) MutableSpan(brave.handler.MutableSpan) ExtensionLoader(com.alibaba.dubbo.common.extension.ExtensionLoader) NEVER_SAMPLE(brave.sampler.Sampler.NEVER_SAMPLE) Scope(brave.propagation.CurrentTraceContext.Scope) Tag(brave.Tag) SamplingFlags(brave.propagation.SamplingFlags) Filter(com.alibaba.dubbo.rpc.Filter) JavaBeanDescriptor(com.alibaba.dubbo.common.beanutil.JavaBeanDescriptor) TraceContext(brave.propagation.TraceContext) RpcTracing(brave.rpc.RpcTracing) Tag(brave.Tag) Result(com.alibaba.dubbo.rpc.Result) Test(org.junit.Test)

Example 99 with TraceContext

use of brave.propagation.TraceContext in project curiostack by curioswitch.

the class ServerModule method decorateService.

private static HttpService decorateService(HttpService service, Tracing tracing, Lazy<FirebaseAuthorizer> firebaseAuthorizer, Lazy<JwtAuthorizer.Factory> jwtAuthorizer, Optional<SslCommonNamesProvider> sslCommonNamesProvider, ServerConfig serverConfig, FirebaseAuthConfig authConfig) {
    if (sslCommonNamesProvider.isPresent() && !serverConfig.isDisableSslAuthorization()) {
        AuthServiceBuilder authServiceBuilder = AuthService.builder();
        authServiceBuilder.add(new SslAuthorizer(sslCommonNamesProvider.get()));
        service = service.decorate(authServiceBuilder.newDecorator());
    }
    if (serverConfig.isEnableIapAuthorization()) {
        service = service.decorate((delegate, ctx, req) -> {
            DecodedJWT jwt = ctx.attr(JwtAuthorizer.DECODED_JWT);
            String loggedInUserEmail = jwt != null ? jwt.getClaim("email").asString() : "unknown";
            RequestLoggingContext.put(ctx, "logged_in_user", loggedInUserEmail);
            return delegate.serve(ctx, req);
        }).decorate(AuthService.builder().addTokenAuthorizer(headers -> OAuth2Token.of(headers.get(HttpHeaderNames.of("x-goog-iap-jwt-assertion"))), jwtAuthorizer.get().create(Algorithm.ES256, "https://www.gstatic.com/iap/verify/public_key")).newDecorator());
    }
    if (!authConfig.getServiceAccountBase64().isEmpty()) {
        FirebaseAuthorizer authorizer = firebaseAuthorizer.get();
        service = service.decorate(AuthService.builder().addOAuth2(authorizer).onFailure(authorizer).newDecorator());
    }
    service = service.decorate(MetricCollectingService.newDecorator(RpcMetricLabels.grpcRequestLabeler("grpc_services"))).decorate(BraveService.newDecorator(tracing)).decorate((delegate, ctx, req) -> {
        TraceContext traceCtx = tracing.currentTraceContext().get();
        if (traceCtx != null) {
            RequestLoggingContext.put(ctx, "traceId", traceCtx.traceIdString());
            RequestLoggingContext.put(ctx, "spanId", traceCtx.spanIdString());
        }
        return delegate.serve(ctx, req);
    });
    return service;
}
Also used : ResourceUtil(org.curioswitch.common.server.framework.util.ResourceUtil) StaticSiteService(org.curioswitch.common.server.framework.staticsite.StaticSiteService) SslCommonNamesProvider(org.curioswitch.common.server.framework.auth.ssl.SslCommonNamesProvider) KeyStoreException(java.security.KeyStoreException) GrpcService(com.linecorp.armeria.server.grpc.GrpcService) ClientAuth(io.netty.handler.ssl.ClientAuth) Module(dagger.Module) OAuth2Token(com.linecorp.armeria.common.auth.OAuth2Token) Multibinds(dagger.multibindings.Multibinds) Duration(java.time.Duration) RpcAclsCommonNamesProvider(org.curioswitch.common.server.framework.auth.ssl.RpcAclsCommonNamesProvider) Path(java.nio.file.Path) ApplicationProtocolConfig(io.netty.handler.ssl.ApplicationProtocolConfig) LoggingService(com.linecorp.armeria.server.logging.LoggingService) Production(dagger.producers.Production) SelectedListenerFailureBehavior(io.netty.handler.ssl.ApplicationProtocolConfig.SelectedListenerFailureBehavior) CollectorRegistry(io.prometheus.client.CollectorRegistry) ServiceRequestContext(com.linecorp.armeria.server.ServiceRequestContext) ImmutableList.toImmutableList(com.google.common.collect.ImmutableList.toImmutableList) Set(java.util.Set) JavascriptStaticService(org.curioswitch.common.server.framework.staticsite.JavascriptStaticService) StaticSiteServiceDefinition(org.curioswitch.common.server.framework.staticsite.StaticSiteServiceDefinition) TraceContext(brave.propagation.TraceContext) Lazy(dagger.Lazy) UncheckedIOException(java.io.UncheckedIOException) SecurityModule(org.curioswitch.common.server.framework.security.SecurityModule) Logger(org.apache.logging.log4j.Logger) FirebaseAuthorizer(org.curioswitch.common.server.framework.auth.firebase.FirebaseAuthorizer) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) StackdriverReporter(org.curioswitch.common.server.framework.monitoring.StackdriverReporter) ModifiableServerConfig(org.curioswitch.common.server.framework.config.ModifiableServerConfig) ConfigBeanFactory(com.typesafe.config.ConfigBeanFactory) DecodedJWT(com.auth0.jwt.interfaces.DecodedJWT) ModifiableJavascriptStaticConfig(org.curioswitch.common.server.framework.config.ModifiableJavascriptStaticConfig) ProtoReflectionService(io.grpc.protobuf.services.ProtoReflectionService) GrpcSerializationFormats(com.linecorp.armeria.common.grpc.GrpcSerializationFormats) InsecureTrustManagerFactory(io.netty.handler.ssl.util.InsecureTrustManagerFactory) SslContextKeyConverter(org.curioswitch.common.server.framework.armeria.SslContextKeyConverter) HttpService(com.linecorp.armeria.server.HttpService) SettableHealthChecker(com.linecorp.armeria.server.healthcheck.SettableHealthChecker) Config(com.typesafe.config.Config) Executor(java.util.concurrent.Executor) IOException(java.io.IOException) Futures(com.google.common.util.concurrent.Futures) HttpsOnlyService(org.curioswitch.common.server.framework.security.HttpsOnlyService) Paths(java.nio.file.Paths) JavascriptStaticConfig(org.curioswitch.common.server.framework.config.JavascriptStaticConfig) X509Certificate(java.security.cert.X509Certificate) CertificateFactory(java.security.cert.CertificateFactory) Algorithm(org.curioswitch.common.server.framework.auth.jwt.JwtVerifier.Algorithm) IpFilteringService(org.curioswitch.common.server.framework.filter.IpFilteringService) FileWatcher(org.curioswitch.common.server.framework.files.FileWatcher) HttpHeaderNames(com.linecorp.armeria.common.HttpHeaderNames) FirebaseAuthModule(org.curioswitch.common.server.framework.auth.firebase.FirebaseAuthModule) SecurityConfig(org.curioswitch.common.server.framework.config.SecurityConfig) BraveService(com.linecorp.armeria.server.brave.BraveService) Server(com.linecorp.armeria.server.Server) DSLContext(org.jooq.DSLContext) DocService(com.linecorp.armeria.server.docs.DocService) FirebaseAuthConfig(org.curioswitch.common.server.framework.auth.firebase.FirebaseAuthConfig) HttpServiceWithRoutes(com.linecorp.armeria.server.HttpServiceWithRoutes) HttpResponse(com.linecorp.armeria.common.HttpResponse) ImmutableSet(com.google.common.collect.ImmutableSet) TrustManagerFactory(javax.net.ssl.TrustManagerFactory) GcloudAuthModule(org.curioswitch.curiostack.gcloud.core.auth.GcloudAuthModule) AuthServiceBuilder(com.linecorp.armeria.server.auth.AuthServiceBuilder) GrpcServiceDefinition(org.curioswitch.common.server.framework.grpc.GrpcServiceDefinition) KeyStore(java.security.KeyStore) RequestContext(com.linecorp.armeria.common.RequestContext) List(java.util.List) WatchedPath(org.curioswitch.common.server.framework.files.WatchedPath) HealthCheckService(com.linecorp.armeria.server.healthcheck.HealthCheckService) PostServerCustomizer(org.curioswitch.common.server.framework.server.PostServerCustomizer) Optional(java.util.Optional) BindsOptionalOf(dagger.BindsOptionalOf) ServerBuilder(com.linecorp.armeria.server.ServerBuilder) BindableService(io.grpc.BindableService) MetricsHttpService(org.curioswitch.common.server.framework.monitoring.MetricsHttpService) MonitoringModule(org.curioswitch.common.server.framework.monitoring.MonitoringModule) Singleton(javax.inject.Singleton) PrometheusExpositionService(com.linecorp.armeria.server.metric.PrometheusExpositionService) Function(java.util.function.Function) MediaType(com.linecorp.armeria.common.MediaType) ServerListener(com.linecorp.armeria.server.ServerListener) RequestLoggingContext(org.curioswitch.common.server.framework.logging.RequestLoggingContext) ImmutableList(com.google.common.collect.ImmutableList) RpcMetricLabels(org.curioswitch.common.server.framework.monitoring.RpcMetricLabels) HttpStatus(com.linecorp.armeria.common.HttpStatus) HttpServiceDefinition(org.curioswitch.common.server.framework.server.HttpServiceDefinition) JwtModule(org.curioswitch.common.server.framework.auth.jwt.JwtModule) Protocol(io.netty.handler.ssl.ApplicationProtocolConfig.Protocol) JwtAuthorizer(org.curioswitch.common.server.framework.auth.jwt.JwtAuthorizer) MetricCollectingService(com.linecorp.armeria.server.metric.MetricCollectingService) Provides(dagger.Provides) Tracing(brave.Tracing) EagerInit(org.curioswitch.common.server.framework.inject.EagerInit) SelfSignedCertificate(io.netty.handler.ssl.util.SelfSignedCertificate) ApplicationProtocolNames(io.netty.handler.ssl.ApplicationProtocolNames) SslAuthorizer(org.curioswitch.common.server.framework.auth.ssl.SslAuthorizer) DocServiceBuilder(com.linecorp.armeria.server.docs.DocServiceBuilder) CertificateException(java.security.cert.CertificateException) HealthChecker(com.linecorp.armeria.server.healthcheck.HealthChecker) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) AuthService(com.linecorp.armeria.server.auth.AuthService) SelectorFailureBehavior(io.netty.handler.ssl.ApplicationProtocolConfig.SelectorFailureBehavior) ServerConfig(org.curioswitch.common.server.framework.config.ServerConfig) ServerShutDownDelayer(org.curioswitch.common.server.framework.server.ServerShutDownDelayer) MeterRegistry(io.micrometer.core.instrument.MeterRegistry) LoggingModule(org.curioswitch.common.server.framework.logging.LoggingModule) Closeable(java.io.Closeable) GcloudIamModule(org.curioswitch.curiostack.gcloud.iam.GcloudIamModule) MonitoringConfig(org.curioswitch.common.server.framework.config.MonitoringConfig) CloseOnStop(org.curioswitch.common.server.framework.inject.CloseOnStop) GrpcServiceBuilder(com.linecorp.armeria.server.grpc.GrpcServiceBuilder) LogManager(org.apache.logging.log4j.LogManager) InputStream(java.io.InputStream) SslAuthorizer(org.curioswitch.common.server.framework.auth.ssl.SslAuthorizer) FirebaseAuthorizer(org.curioswitch.common.server.framework.auth.firebase.FirebaseAuthorizer) TraceContext(brave.propagation.TraceContext) AuthServiceBuilder(com.linecorp.armeria.server.auth.AuthServiceBuilder) DecodedJWT(com.auth0.jwt.interfaces.DecodedJWT)

Example 100 with TraceContext

use of brave.propagation.TraceContext in project reactor-netty by reactor.

the class TracingChannelOutboundHandler method flush.

@Override
@SuppressWarnings("try")
public void flush(ChannelHandlerContext ctx) {
    Span span = ctx.channel().attr(SPAN_ATTR_KEY).get();
    if (span != null) {
        try (Scope scope = currentTraceContext.maybeScope(span.context())) {
            ctx.flush();
        }
        return;
    } else {
        ChannelOperations<?, ?> ops = ChannelOperations.get(ctx.channel());
        if (ops instanceof HttpClientRequest) {
            TraceContext parent = ((HttpClientRequest) ops).currentContextView().getOrDefault(TraceContext.class, null);
            if (parent != null) {
                try (Scope scope = currentTraceContext.maybeScope(parent)) {
                    ctx.flush();
                }
                return;
            }
        }
    }
    ctx.flush();
}
Also used : HttpClientRequest(reactor.netty.http.client.HttpClientRequest) Scope(brave.propagation.CurrentTraceContext.Scope) CurrentTraceContext(brave.propagation.CurrentTraceContext) TraceContext(brave.propagation.TraceContext) Span(brave.Span)

Aggregations

TraceContext (brave.propagation.TraceContext)200 Test (org.junit.Test)163 CurrentTraceContext (brave.propagation.CurrentTraceContext)77 Scope (brave.propagation.CurrentTraceContext.Scope)52 StrictCurrentTraceContext (brave.propagation.StrictCurrentTraceContext)52 MutableSpan (brave.handler.MutableSpan)38 Span (brave.Span)17 Assertions.assertThat (org.assertj.core.api.Assertions.assertThat)13 MockResponse (okhttp3.mockwebserver.MockResponse)12 SpanHandler (brave.handler.SpanHandler)9 Clock (brave.Clock)7 SamplingFlags (brave.propagation.SamplingFlags)7 TraceContextOrSamplingFlags (brave.propagation.TraceContextOrSamplingFlags)7 ArrayList (java.util.ArrayList)7 List (java.util.List)7 AtomicReference (java.util.concurrent.atomic.AtomicReference)7 TestSpanHandler (brave.test.TestSpanHandler)6 AssertableCallback (brave.test.util.AssertableCallback)6 Message (javax.jms.Message)6 After (org.junit.After)6