Skip to content

Commit

Permalink
add otel bridge
Browse files Browse the repository at this point in the history
Signed-off-by: afzal442 <afzal442@gmail.com>
  • Loading branch information
afzalbin64 authored and afzal442 committed Jun 16, 2023
1 parent bfed6e7 commit f044b60
Show file tree
Hide file tree
Showing 3 changed files with 135 additions and 11 deletions.
69 changes: 68 additions & 1 deletion cmd/all-in-one/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,18 +16,29 @@
package main

import (
"context"
"fmt"
"io"
"log"
"os"
"time"

"github.com/opentracing/opentracing-go"
"github.com/spf13/cobra"
"github.com/spf13/viper"
jaegerClientConfig "github.com/uber/jaeger-client-go/config"
jaegerClientZapLog "github.com/uber/jaeger-client-go/log/zap"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/attribute"
otelBridge "go.opentelemetry.io/otel/bridge/opentracing"
"go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc"
"go.opentelemetry.io/otel/sdk/resource"
sdktrace "go.opentelemetry.io/otel/sdk/trace"
semconv "go.opentelemetry.io/otel/semconv/v1.17.0"
_ "go.uber.org/automaxprocs"
"go.uber.org/zap"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"

agentApp "github.com/jaegertracing/jaeger/cmd/agent/app"
agentRep "github.com/jaegertracing/jaeger/cmd/agent/app/reporter"
Expand Down Expand Up @@ -274,7 +285,28 @@ func startQuery(
) *queryApp.Server {
spanReader = storageMetrics.NewReadMetricsDecorator(spanReader, baseFactory.Namespace(metrics.NSOptions{Name: "query"}))
qs := querysvc.NewQueryService(spanReader, depReader, *queryOpts)
jtracer := jtracer.OT(opentracing.GlobalTracer())
// jtracer := jtracer.OT(opentracing.GlobalTracer())

ctx := context.Background()
exp, err := newExporter(ctx)
if err != nil {
log.Fatal(err)
}

tp := sdktrace.NewTracerProvider(
sdktrace.WithBatcher(exp),
sdktrace.WithResource(newResource()),
)

otelTracer := tp.Tracer("mytracer_name")
// Use the bridgeTracer as your OpenTracing tracer.
bridgeTracer, wrapperTracerProvider := otelBridge.NewTracerPair(otelTracer)
// Set the wrapperTracerProvider as the global OpenTelemetry
// TracerProvider so instrumentation will use it by default.
otel.SetTracerProvider(wrapperTracerProvider)

jtracer := jtracer.OT(bridgeTracer)

server, err := queryApp.NewServer(svc.Logger, qs, metricsQueryService, qOpts, tm, jtracer)
if err != nil {
svc.Logger.Fatal("Could not start jaeger-query service", zap.Error(err))
Expand All @@ -290,6 +322,41 @@ func startQuery(
return server
}

// newExporter returns a console exporter.
func newExporter(ctx context.Context) (sdktrace.SpanExporter, error) {
ctx, cancel := context.WithTimeout(ctx, time.Second)
defer cancel()
conn, err := grpc.DialContext(ctx, "otel_collector:4317",
// Note the use of insecure transport here. TLS is recommended in production.
grpc.WithTransportCredentials(insecure.NewCredentials()),
grpc.WithBlock(),
)
if err != nil {
return nil, fmt.Errorf("failed to create gRPC connection to collector: %w", err)
}

// Set up a trace exporter
traceExporter, err := otlptracegrpc.New(ctx, otlptracegrpc.WithGRPCConn(conn))
if err != nil {
return nil, fmt.Errorf("failed to create trace exporter: %w", err)
}
return traceExporter, nil
}

// newResource returns a resource describing this application.
func newResource() *resource.Resource {
r, _ := resource.Merge(
resource.Default(),
resource.NewWithAttributes(
semconv.SchemaURL,
semconv.ServiceName("query"),
semconv.ServiceVersion("v0.1.0"),
attribute.String("environment", "demo"),
),
)
return r
}

func initTracer(svc *flags.Service) io.Closer {
logger := svc.Logger
traceCfg := &jaegerClientConfig.Configuration{
Expand Down
35 changes: 35 additions & 0 deletions examples/hotrod/pkg/tracing/init.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ import (
"go.opentelemetry.io/otel/sdk/resource"
sdktrace "go.opentelemetry.io/otel/sdk/trace"
semconv "go.opentelemetry.io/otel/semconv/v1.7.0"
"go.opentelemetry.io/otel/trace"
"go.uber.org/zap"

"github.com/jaegertracing/jaeger/examples/hotrod/pkg/log"
Expand All @@ -43,6 +44,40 @@ import (

var once sync.Once

// InitOTEL initializes OpenTelemetry SDK and uses OTel-OpenTracing Bridge
// to return an OpenTracing-compatible tracer.
func InitOTEL(serviceName string, exporterType string, metricsFactory metrics.Factory, logger log.Factory) trace.Tracer {
once.Do(func() {
otel.SetTextMapPropagator(
propagation.NewCompositeTextMapPropagator(
propagation.TraceContext{},
propagation.Baggage{},
))
})

exp, err := createOtelExporter(exporterType)
if err != nil {
logger.Bg().Fatal("cannot create exporter", zap.String("exporterType", exporterType), zap.Error(err))
}
logger.Bg().Debug("using " + exporterType + " trace exporter")

rpcmetricsObserver := rpcmetrics.NewObserver(metricsFactory, rpcmetrics.DefaultNameNormalizer)

tp := sdktrace.NewTracerProvider(
sdktrace.WithBatcher(exp),
sdktrace.WithSpanProcessor(rpcmetricsObserver),
sdktrace.WithResource(resource.NewWithAttributes(
semconv.SchemaURL,
semconv.ServiceNameKey.String(serviceName),
)),
)
otel.SetTracerProvider(tp)
// _, otelTracerProvider := otbridge.NewTracerPair(tp.Tracer(""))
tracer := otel.Tracer("my otel tracer")
// logger.Bg().Debug("created OTEL->OT bridge", zap.String("service-name", serviceName))
return tracer
}

// Init initializes OpenTelemetry SDK and uses OTel-OpenTracing Bridge
// to return an OpenTracing-compatible tracer.
func Init(serviceName string, exporterType string, metricsFactory metrics.Factory, logger log.Factory) opentracing.Tracer {
Expand Down
42 changes: 32 additions & 10 deletions examples/hotrod/services/driver/redis.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,8 @@ import (
"math/rand"
"sync"

"github.com/opentracing/opentracing-go"
"github.com/opentracing/opentracing-go/ext"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/trace"
"go.uber.org/zap"

"github.com/jaegertracing/jaeger/examples/hotrod/pkg/delay"
Expand All @@ -35,27 +35,38 @@ import (

// Redis is a simulator of remote Redis cache
type Redis struct {
tracer opentracing.Tracer // simulate redis as a separate process
tracer trace.Tracer // simulate redis as a separate process
logger log.Factory
errorSimulator
}

func newRedis(otelExporter string, metricsFactory metrics.Factory, logger log.Factory) *Redis {
return &Redis{
tracer: tracing.Init("redis", otelExporter, metricsFactory, logger),
tracer: tracing.InitOTEL("redis", otelExporter, metricsFactory, logger),
logger: logger,
}
}

// FindDriverIDs finds IDs of drivers who are near the location.
func (r *Redis) FindDriverIDs(ctx context.Context, location string) []string {
if span := opentracing.SpanFromContext(ctx); span != nil {

// tracer := otel.Tracer(serviceName)
ctx, span := r.tracer.Start(ctx, "FindDriverIDs")
if span != nil {
_, span := r.tracer.Start(ctx, "FindDriverIDs", trace.WithSpanKind(trace.SpanKindServer) /*...set child of option*/)

span.SetAttributes(attribute.Key("param.location").String(location))

span.SetName("FindDriverIDs")
defer span.End()
}
/* if span := opentracing.SpanFromContext(ctx); span != nil {
span := r.tracer.StartSpan("FindDriverIDs", opentracing.ChildOf(span.Context()))
span.SetTag("param.location", location)
ext.SpanKindRPCClient.Set(span)
defer span.Finish()
ctx = opentracing.ContextWithSpan(ctx, span)
}
} */
// simulate RPC delay
delay.Sleep(config.RedisFindDelay, config.RedisFindDelayStdDev)

Expand All @@ -70,18 +81,29 @@ func (r *Redis) FindDriverIDs(ctx context.Context, location string) []string {

// GetDriver returns driver and the current car location
func (r *Redis) GetDriver(ctx context.Context, driverID string) (Driver, error) {
if span := opentracing.SpanFromContext(ctx); span != nil {
ctx, span := r.tracer.Start(ctx, "GetDriver")
if span != nil {
_, span := r.tracer.Start(ctx, "GetDriver", trace.WithSpanKind(trace.SpanKindServer) /*...set child of option*/)

span.SetAttributes(attribute.Key("param.driverID").String(driverID))

// TODO: Set span kind
// ext.SpanKindRPCClient.Set(span)
span.SetName("GetDriver")
defer span.End()
}
/* if span := opentracing.SpanFromContext(ctx); span != nil {
span := r.tracer.StartSpan("GetDriver", opentracing.ChildOf(span.Context()))
span.SetTag("param.driverID", driverID)
ext.SpanKindRPCClient.Set(span)
defer span.Finish()
ctx = opentracing.ContextWithSpan(ctx, span)
}
} */
// simulate RPC delay
delay.Sleep(config.RedisGetDelay, config.RedisGetDelayStdDev)
if err := r.checkError(); err != nil {
if span := opentracing.SpanFromContext(ctx); span != nil {
ext.Error.Set(span, true)
if _, span := r.tracer.Start(ctx, "GetDriver"); span != nil {
trace.Span.RecordError(span, err)
}
r.logger.For(ctx).Error("redis timeout", zap.String("driver_id", driverID), zap.Error(err))
return Driver{}, err
Expand Down

0 comments on commit f044b60

Please sign in to comment.