Skip to content

Commit

Permalink
otel context
Browse files Browse the repository at this point in the history
  • Loading branch information
YifeiZhuang committed May 18, 2024
1 parent e490273 commit 9ca1736
Show file tree
Hide file tree
Showing 6 changed files with 49 additions and 1 deletion.
1 change: 1 addition & 0 deletions census/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ dependencies {
project(":grpc-context"), // Override opencensus dependency with our newer version
libraries.opencensus.api,
libraries.opencensus.contrib.grpc.metrics
implementation 'io.opentelemetry:opentelemetry-api:1.38.0'

testImplementation testFixtures(project(':grpc-api')),
testFixtures(project(':grpc-core')),
Expand Down
7 changes: 7 additions & 0 deletions census/src/main/java/io/grpc/census/CensusTracingModule.java
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@
import io.opencensus.trace.Status;
import io.opencensus.trace.Tracer;
import io.opencensus.trace.propagation.BinaryFormat;
import io.opencensus.trace.unsafe.ContextHandleUtils;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
Expand Down Expand Up @@ -416,6 +417,11 @@ public Context filterContext(Context context) {
// Access directly the unsafe trace API to create the new Context. This is a safe usage
// because gRPC always creates a new Context for each of the server calls and does not
// inherit from the parent Context.
logger.log(Level.INFO, "filtering context in server tracer: {0}", new Object[]{span.getContext()});
//ContextHandleUtils.withValue(ContextHandleUtils.currentContext(), span).attach();
//logger.log(Level.INFO, "filtering context getting from otel spancontext {0}",
// new Object[]{io.opentelemetry.api.trace.Span.fromContext(io.opentelemetry.context.Context.current()).getSpanContext()});
//ContextHandleUtils.tryExtractGrpcContext(ContextHandleUtils.withValue(ContextHandleUtils.currentContext(), span));
return io.opencensus.trace.unsafe.ContextUtils.withValue(context, span);
}

Expand Down Expand Up @@ -470,6 +476,7 @@ public <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall(
// as Tracer.getCurrentSpan() except when no value available when the return value is null
// for the direct access and BlankSpan when Tracer API is used.
Span parentSpan = io.opencensus.trace.unsafe.ContextUtils.getValue(Context.current());
logger.log(Level.INFO, "tracing client interceptor, getting parent span: {0}", new Object[]{parentSpan.getContext()});
Span clientSpan = censusTracer
.spanBuilderWithExplicitParent(
generateTraceSpanName(false, method.getFullMethodName()),
Expand Down
4 changes: 4 additions & 0 deletions interop-testing/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,9 @@ dependencies {
libraries.opencensus.contrib.grpc.metrics,
libraries.google.auth.oauth2Http,
libraries.guava.jre // Fix checkUpperBoundDeps using -android
implementation 'io.opentelemetry:opentelemetry-sdk-extension-autoconfigure:1.38.0'
implementation 'io.opentelemetry:opentelemetry-exporter-logging:1.38.0'
implementation 'io.opentelemetry:opentelemetry-api:1.38.0'
api project(':grpc-api'),
project(':grpc-stub'),
project(':grpc-protobuf'),
Expand All @@ -44,6 +47,7 @@ dependencies {
libraries.netty.tcnative.classes,
project(':grpc-grpclb'),
project(':grpc-rls')
runtimeOnly 'io.opentelemetry:opentelemetry-opencensus-shim:1.38.0-alpha'
testImplementation testFixtures(project(':grpc-api')),
testFixtures(project(':grpc-core')),
project(':grpc-inprocess'),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@
import io.grpc.StatusRuntimeException;
import io.grpc.auth.MoreCallCredentials;
import io.grpc.census.InternalCensusStatsAccessor;
import io.grpc.census.InternalCensusTracingAccessor;
import io.grpc.census.internal.DeprecatedCensusConstants;
import io.grpc.internal.GrpcUtil;
import io.grpc.internal.testing.StatsTestUtils;
Expand Down Expand Up @@ -93,6 +94,7 @@
import io.grpc.testing.integration.Messages.StreamingOutputCallRequest;
import io.grpc.testing.integration.Messages.StreamingOutputCallResponse;
import io.grpc.testing.integration.Messages.TestOrcaReport;
import io.opencensus.common.Scope;
import io.opencensus.contrib.grpc.metrics.RpcMeasureConstants;
import io.opencensus.stats.Measure;
import io.opencensus.stats.Measure.MeasureDouble;
Expand All @@ -101,6 +103,7 @@
import io.opencensus.tags.TagValue;
import io.opencensus.trace.Span;
import io.opencensus.trace.SpanContext;
import io.opencensus.trace.Tracer;
import io.opencensus.trace.Tracing;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
Expand Down Expand Up @@ -342,6 +345,7 @@ public <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall(
* Must be called by the subclass setup method if overridden.
*/
@Before
@SuppressWarnings("CheckReturnValue")
public void setUp() {
ServerBuilder<?> serverBuilder = getServerBuilder();
configBuilder(serverBuilder);
Expand All @@ -356,7 +360,12 @@ public void setUp() {
blockingStub = TestServiceGrpc.newBlockingStub(channel);
asyncStub = TestServiceGrpc.newStub(channel);
}

blockingStub.withInterceptors(InternalCensusTracingAccessor.getClientInterceptor());
Tracer tracer = Tracing.getTracer();
Span applicationSpan = tracer.spanBuilder("application span is parent span").startSpan();
try (Scope scope = tracer.withSpan(applicationSpan)) {
applicationSpan.addAnnotation("anstract interop test started");
}
ClientInterceptor[] additionalInterceptors = getAdditionalInterceptors();
if (additionalInterceptors != null) {
blockingStub = blockingStub.withInterceptors(additionalInterceptors);
Expand Down Expand Up @@ -440,8 +449,19 @@ protected boolean metricsExpected() {
}

@Test
@SuppressWarnings({"deprecation", "CheckReturnValue"})
public void emptyUnary() throws Exception {
Tracer tracer = Tracing.getTracer();
Span applicationSpan = tracer.spanBuilder("application span is parent span").startSpan();
io.opencensus.trace.unsafe.ContextUtils.withValue(Context.current(), applicationSpan).attach();
logger.log(Level.INFO, "parent span " + applicationSpan.getContext());
assertEquals(EMPTY, blockingStub.emptyCall(EMPTY));

// try (Scope scope = tracer.withSpan(applicationSpan)) {
// applicationSpan.addAnnotation("anstract interop test started");
// logger.log(Level.INFO, "parent span " + applicationSpan.getContext());
// assertEquals(EMPTY, blockingStub.emptyCall(EMPTY));
// }
}

@Test
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
import com.google.common.base.Preconditions;
import com.google.common.collect.Queues;
import com.google.protobuf.ByteString;
import io.grpc.Context;
import io.grpc.ForwardingServerCall.SimpleForwardingServerCall;
import io.grpc.Metadata;
import io.grpc.ServerCall;
Expand All @@ -41,6 +42,8 @@
import io.grpc.testing.integration.Messages.StreamingOutputCallResponse;
import io.grpc.testing.integration.Messages.TestOrcaReport;
import io.grpc.testing.integration.TestServiceGrpc.AsyncService;
import io.opencensus.trace.Tracing;
import io.opencensus.trace.unsafe.ContextHandleUtils;
import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.HashMap;
Expand All @@ -54,13 +57,17 @@
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.concurrent.GuardedBy;
import io.opentelemetry.api.OpenTelemetry;

/**
* Implementation of the business logic for the TestService. Uses an executor to schedule chunks
* sent in response streams.
*/
public class TestServiceImpl implements io.grpc.BindableService, AsyncService {
private static final Logger log = Logger.getLogger("TestServiceImpl");
private final Random random = new Random();

private final ScheduledExecutorService executor;
Expand All @@ -87,8 +94,15 @@ public final io.grpc.ServerServiceDefinition bindService() {
}

@Override
@SuppressWarnings("deprecation")
public void emptyCall(EmptyProtos.Empty request,
StreamObserver<EmptyProtos.Empty> responseObserver) {
log.log(Level.INFO, "SpanContext from OC: (hint:empty) {0} ",
new Object[]{Tracing.getTracer().getCurrentSpan().getContext()});
log.log(Level.INFO, "SpanContext from Otel: (hint:empty) {0} ",
new Object[]{io.opentelemetry.api.trace.Span.fromContext(io.opentelemetry.context.Context.current()).getSpanContext()});
log.log(Level.INFO, "SpanContext from gRPC: (hint:the same from context filter) {0}",
new Object[]{io.opencensus.trace.unsafe.ContextUtils.getValue(Context.current()).getContext()});
responseObserver.onNext(EmptyProtos.Empty.getDefaultInstance());
responseObserver.onCompleted();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
import io.grpc.ServerInterceptors;
import io.grpc.TlsServerCredentials;
import io.grpc.alts.AltsServerCredentials;
import io.grpc.census.InternalCensusTracingAccessor;
import io.grpc.services.MetricRecorder;
import io.grpc.testing.TlsTesting;
import io.grpc.xds.orca.OrcaMetricReportingServerInterceptor;
Expand Down Expand Up @@ -163,6 +164,7 @@ void start() throws Exception {
new TestServiceImpl(executor, metricRecorder), TestServiceImpl.interceptors()))
.addService(orcaOobService)
.intercept(OrcaMetricReportingServerInterceptor.create(metricRecorder))
.addStreamTracerFactory(InternalCensusTracingAccessor.getServerStreamTracerFactory())
.build()
.start();
}
Expand Down

0 comments on commit 9ca1736

Please sign in to comment.