From 44657ec18bad5e6385d3b038d2dc14dd07a59821 Mon Sep 17 00:00:00 2001 From: Afzal Ansari Date: Fri, 30 Jun 2023 17:31:02 +0000 Subject: [PATCH] reformats HTTPClient Signed-off-by: Afzal Ansari reformats init otel func Signed-off-by: Afzal Ansari --- examples/hotrod/pkg/tracing/http.go | 7 ++ examples/hotrod/pkg/tracing/init.go | 4 +- examples/hotrod/pkg/tracing/mux.go | 4 +- examples/hotrod/services/customer/client.go | 11 +-- examples/hotrod/services/customer/database.go | 21 +++-- examples/hotrod/services/customer/server.go | 5 +- examples/hotrod/services/driver/redis.go | 3 +- .../hotrod/services/driver/server_test.go | 90 ------------------- examples/hotrod/services/frontend/server.go | 7 +- examples/hotrod/services/route/client.go | 11 +-- 10 files changed, 37 insertions(+), 126 deletions(-) delete mode 100644 examples/hotrod/services/driver/server_test.go diff --git a/examples/hotrod/pkg/tracing/http.go b/examples/hotrod/pkg/tracing/http.go index 02327e1e351..1ceca45197a 100644 --- a/examples/hotrod/pkg/tracing/http.go +++ b/examples/hotrod/pkg/tracing/http.go @@ -30,6 +30,13 @@ type HTTPClient struct { Client *http.Client } +func NewHTTPClient(tp trace.TracerProvider) HTTPClient { + return HTTPClient{ + TracerProvider: tp, + Client: &http.Client{Transport: &otelhttp.Transport{}}, + } +} + // GetJSON executes HTTP GET against specified url and tried to parse // the response into out object. func (c *HTTPClient) GetJSON(ctx context.Context, url string, out interface{}) error { diff --git a/examples/hotrod/pkg/tracing/init.go b/examples/hotrod/pkg/tracing/init.go index 367d328b30d..82333540273 100644 --- a/examples/hotrod/pkg/tracing/init.go +++ b/examples/hotrod/pkg/tracing/init.go @@ -45,11 +45,11 @@ import ( var once sync.Once // InitOTEL initializes OpenTelemetry SDK. -func InitOTEL(serviceName string, exporterType string, metricsFactory metrics.Factory, logger log.Factory) trace.Tracer { +func InitOTEL(serviceName string, exporterType string, metricsFactory metrics.Factory, logger log.Factory) trace.TracerProvider { _, oteltp := initBOTH(serviceName, exporterType, metricsFactory, logger) logger.Bg().Debug("Created OTEL tracer", zap.String("service-name", serviceName)) - return oteltp.Tracer(serviceName) + return oteltp } // Init returns OTel-OpenTracing Bridge. diff --git a/examples/hotrod/pkg/tracing/mux.go b/examples/hotrod/pkg/tracing/mux.go index ac35e86c0ce..f090811d83a 100644 --- a/examples/hotrod/pkg/tracing/mux.go +++ b/examples/hotrod/pkg/tracing/mux.go @@ -48,7 +48,7 @@ type TracedServeMux struct { func (tm *TracedServeMux) Handle(pattern string, handler http.Handler) { tm.logger.Bg().Debug("registering traced handler", zap.String("endpoint", pattern)) - middleware := otelhttp.NewHandler(tm.mux, pattern, + middleware := otelhttp.NewHandler(handler, pattern, otelhttp.WithTracerProvider(tm.tracer)) tm.mux.Handle(pattern, otelBaggageExtractor(middleware)) } @@ -58,7 +58,7 @@ func (tm *TracedServeMux) ServeHTTP(w http.ResponseWriter, r *http.Request) { tm.mux.ServeHTTP(w, r) } -// Used with nethttp.MWSpanObserver above. +// Used with otelhttp.NewHandler above. func otelBaggageExtractor(next http.Handler) http.Handler { propagator := propagation.Baggage{} return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { diff --git a/examples/hotrod/services/customer/client.go b/examples/hotrod/services/customer/client.go index da8369b120f..291fc208c6b 100644 --- a/examples/hotrod/services/customer/client.go +++ b/examples/hotrod/services/customer/client.go @@ -18,9 +18,7 @@ package customer import ( "context" "fmt" - "net/http" - "go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp" "go.opentelemetry.io/otel/trace" "go.uber.org/zap" @@ -31,18 +29,15 @@ import ( // Client is a remote client that implements customer.Interface type Client struct { logger log.Factory - client *tracing.HTTPClient + client tracing.HTTPClient hostPort string } // NewClient creates a new customer.Client func NewClient(tracer trace.TracerProvider, logger log.Factory, hostPort string) *Client { return &Client{ - logger: logger, - client: &tracing.HTTPClient{ - Client: &http.Client{Transport: &otelhttp.Transport{}}, - TracerProvider: tracer, - }, + logger: logger, + client: tracing.NewHTTPClient(tracer), hostPort: hostPort, } } diff --git a/examples/hotrod/services/customer/database.go b/examples/hotrod/services/customer/database.go index 739285b570d..a89b01f1989 100644 --- a/examples/hotrod/services/customer/database.go +++ b/examples/hotrod/services/customer/database.go @@ -19,8 +19,8 @@ import ( "context" "errors" - "go.opentelemetry.io/otel/attribute" - "go.opentelemetry.io/otel/trace" + "github.com/opentracing/opentracing-go" + tags "github.com/opentracing/opentracing-go/ext" "go.uber.org/zap" "github.com/jaegertracing/jaeger/examples/hotrod/pkg/delay" @@ -31,13 +31,13 @@ import ( // database simulates Customer repository implemented on top of an SQL database type database struct { - tracer trace.Tracer + tracer opentracing.Tracer logger log.Factory customers map[string]*Customer lock *tracing.Mutex } -func newDatabase(tracer trace.Tracer, logger log.Factory) *database { +func newDatabase(tracer opentracing.Tracer, logger log.Factory) *database { return &database{ tracer: tracer, logger: logger, @@ -73,10 +73,15 @@ func (d *database) Get(ctx context.Context, customerID string) (*Customer, error d.logger.For(ctx).Info("Loading customer", zap.String("customer_id", customerID)) // simulate opentracing instrumentation of an SQL query - ctx, span := d.tracer.Start(ctx, "SQL SELECT", trace.WithSpanKind(trace.SpanKindClient)) - // #nosec - span.SetAttributes(attribute.Key("sql.query").String("SELECT * FROM customer WHERE customer_id=" + customerID)) - defer span.End() + if span := opentracing.SpanFromContext(ctx); span != nil { + span := d.tracer.StartSpan("SQL SELECT", opentracing.ChildOf(span.Context())) + tags.SpanKindRPCClient.Set(span) + tags.PeerService.Set(span, "mysql") + // #nosec + span.SetTag("sql.query", "SELECT * FROM customer WHERE customer_id="+customerID) + defer span.Finish() + ctx = opentracing.ContextWithSpan(ctx, span) + } if !config.MySQLMutexDisabled { // simulate misconfigured connection pool that only gives one connection at a time diff --git a/examples/hotrod/services/customer/server.go b/examples/hotrod/services/customer/server.go index 91383b4a6bf..475d21c4ad5 100644 --- a/examples/hotrod/services/customer/server.go +++ b/examples/hotrod/services/customer/server.go @@ -19,7 +19,6 @@ import ( "encoding/json" "net/http" - "go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp" "go.opentelemetry.io/otel/trace" "go.uber.org/zap" @@ -44,7 +43,7 @@ func NewServer(hostPort string, otelExporter string, metricsFactory metrics.Fact tracer: tracing.InitOTEL("customer", otelExporter, metricsFactory, logger), logger: logger, database: newDatabase( - tracing.InitOTEL("mysql", otelExporter, metricsFactory, logger).Tracer("mysql"), + tracing.Init("mysql", otelExporter, metricsFactory, logger), logger.With(zap.String("component", "mysql")), ), } @@ -59,7 +58,7 @@ func (s *Server) Run() error { func (s *Server) createServeMux() http.Handler { mux := tracing.NewServeMux(false, s.tracer, s.logger) - mux.Handle("/customer", otelhttp.WithRouteTag("/customer", http.HandlerFunc(s.customer))) + mux.Handle("/customer", http.HandlerFunc(s.customer)) return mux } diff --git a/examples/hotrod/services/driver/redis.go b/examples/hotrod/services/driver/redis.go index 1199017dfb0..004d4c18996 100644 --- a/examples/hotrod/services/driver/redis.go +++ b/examples/hotrod/services/driver/redis.go @@ -42,8 +42,9 @@ type Redis struct { } func newRedis(otelExporter string, metricsFactory metrics.Factory, logger log.Factory) *Redis { + tp := tracing.InitOTEL("redis-manual", otelExporter, metricsFactory, logger) return &Redis{ - tracer: tracing.InitOTEL("redis-manual", otelExporter, metricsFactory, logger), + tracer: tp.Tracer("redis-manual"), logger: logger, } } diff --git a/examples/hotrod/services/driver/server_test.go b/examples/hotrod/services/driver/server_test.go deleted file mode 100644 index 686e60c5fa4..00000000000 --- a/examples/hotrod/services/driver/server_test.go +++ /dev/null @@ -1,90 +0,0 @@ -// Copyright (c) 2023 The Jaeger Authors. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package driver - -import ( - "context" - "testing" - - "github.com/stretchr/testify/assert" - "go.opentelemetry.io/otel/trace" - "go.uber.org/zap" - - "github.com/jaegertracing/jaeger/examples/hotrod/pkg/log" -) - -func TestFindNearest(t *testing.T) { - logger := zap.NewNop() - zapLogger := logger.With(zap.String("service", "test-driver")) - - hostPort := "localhost:8080" - - /* lis, err := net.Listen("tcp", hostPort) - server := grpc.NewServer(grpc.UnaryInterceptor(otelgrpc.UnaryServerInterceptor()), - grpc.StreamInterceptor(otelgrpc.StreamServerInterceptor()), - ).Serve(lis) */ - - locationRequest := &DriverLocationRequest{ - Location: "222,953", - } - - // Create a test server - server := NewServer(hostPort, "otlp", nil, log.NewFactory(zapLogger)) - ctx := context.Background() - - // Define a mock Redis implementation for testing - mockRedis := &Redis{ - // Implement the necessary methods for testing - tracer: trace.NewNoopTracerProvider().Tracer("test-tracer"), - logger: server.logger, - } - - // Assign the mock Redis to the server - server.redis = mockRedis - - // Call the FindNearest method - response, err := server.FindNearest(ctx, locationRequest) - - driverIDs := server.redis.FindDriverIDs(ctx, locationRequest.Location) - - retMe := make([]*DriverLocation, len(driverIDs)) - for i, driverID := range driverIDs { - var drv Driver - var err error - for i := 0; i < 3; i++ { - drv, err = server.redis.GetDriver(ctx, driverID) - if err == nil { - break - } - server.logger.For(ctx).Error("Retrying GetDriver after error", zap.Int("retry_no", i+1), zap.Error(err)) - } - if err != nil { - server.logger.For(ctx).Error("Failed to get driver after 3 attempts", zap.Error(err)) - return - } - retMe[i] = &DriverLocation{ - DriverID: drv.DriverID, - Location: drv.Location, - } - } - - // Assert the expected results - assert.NoError(t, err) - assert.NotNil(t, response) - assert.Equal(t, len(retMe), len(response.Locations)) - // assert.Equal(t, retMe[0].DriverID, response.Locations[0].DriverID) - // assert.Equal(t, retMe[0].Location, response.Locations[0].Location) - // Add more assertions as needed -} diff --git a/examples/hotrod/services/frontend/server.go b/examples/hotrod/services/frontend/server.go index 926ce5623c9..45527569f85 100644 --- a/examples/hotrod/services/frontend/server.go +++ b/examples/hotrod/services/frontend/server.go @@ -21,7 +21,6 @@ import ( "net/http" "path" - "go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp" "go.opentelemetry.io/otel/trace" "go.uber.org/zap" @@ -79,9 +78,9 @@ func (s *Server) Run() error { func (s *Server) createServeMux() http.Handler { mux := tracing.NewServeMux(true, s.tracer, s.logger) p := path.Join("/", s.basepath) - mux.Handle(p, otelhttp.WithRouteTag(p, http.StripPrefix(p, http.FileServer(s.assetFS)))) - mux.Handle(path.Join(p, "/dispatch"), otelhttp.WithRouteTag(path.Join(p, "/dispatch"), http.HandlerFunc(s.dispatch))) - mux.Handle(path.Join(p, "/config"), otelhttp.WithRouteTag(path.Join(p, "/config"), http.HandlerFunc(s.config))) + mux.Handle(p, http.StripPrefix(p, http.FileServer(s.assetFS))) + mux.Handle(path.Join(p, "/dispatch"), http.HandlerFunc(s.dispatch)) + mux.Handle(path.Join(p, "/config"), http.HandlerFunc(s.config)) return mux } diff --git a/examples/hotrod/services/route/client.go b/examples/hotrod/services/route/client.go index 5cb99446902..4832f27a136 100644 --- a/examples/hotrod/services/route/client.go +++ b/examples/hotrod/services/route/client.go @@ -17,10 +17,8 @@ package route import ( "context" - "net/http" "net/url" - "go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp" "go.opentelemetry.io/otel/trace" "go.uber.org/zap" @@ -31,18 +29,15 @@ import ( // Client is a remote client that implements route.Interface type Client struct { logger log.Factory - client *tracing.HTTPClient + client tracing.HTTPClient hostPort string } // NewClient creates a new route.Client func NewClient(tracer trace.TracerProvider, logger log.Factory, hostPort string) *Client { return &Client{ - logger: logger, - client: &tracing.HTTPClient{ - Client: &http.Client{Transport: &otelhttp.Transport{}}, - TracerProvider: tracer, - }, + logger: logger, + client: tracing.NewHTTPClient(tracer), hostPort: hostPort, } }