Skip to content

Commit

Permalink
ref: add otel intrumentation methods for proxy logic
Browse files Browse the repository at this point in the history
  • Loading branch information
kenriortega committed Nov 14, 2021
1 parent 4025194 commit fd08b3d
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 33 deletions.
11 changes: 6 additions & 5 deletions internal/proxy/handlers/proxy.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,10 @@ import (

"github.com/kenriortega/ngonx/pkg/errors"
"github.com/kenriortega/ngonx/pkg/logger"
"github.com/kenriortega/ngonx/pkg/otelify"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/codes"
"go.opentelemetry.io/otel/trace"

"github.com/gbrlsnchs/jwt/v3"
domain "github.com/kenriortega/ngonx/internal/proxy/domain"
Expand Down Expand Up @@ -56,6 +58,7 @@ func (ph *ProxyHandler) ProxyGateway(
) {
ctx, span := otel.Tracer("proxy.gateway").Start(context.Background(), "ProxyGateway")
defer span.End()
traceID := trace.SpanContextFromContext(ctx).TraceID().String()
for _, endpoint := range endpoints.Endpoints {
start := time.Now()

Expand All @@ -81,8 +84,7 @@ func (ph *ProxyHandler) ProxyGateway(
case "apikey":
err = checkAPIKEY(ctx, req, ph, engine, key)
}
otelRegister(ctx, start, req, err)

otelRegisterByRequest(ctx, start, req, err)
}
proxy.ModifyResponse = func(resp *http.Response) error {
resp.Header.Set("X-Proxy", "Ngonx")
Expand Down Expand Up @@ -118,9 +120,8 @@ func (ph *ProxyHandler) ProxyGateway(

originalDirector := proxy.Director
proxy.Director = func(req *http.Request) {
// log the trace id with other fields so we can discover traces through logs
originalDirector(req)
otelRegister(ctx, start, req, nil)
otelRegisterByRequest(ctx, start, req, nil)
}
proxy.ModifyResponse = func(resp *http.Response) error {
resp.Header.Set("X-Proxy", "Ngonx")
Expand All @@ -136,5 +137,5 @@ func (ph *ProxyHandler) ProxyGateway(
)
}
}
span.AddEvent("ProxyGateway done!")
otelify.InstrumentedInfo(span, "proxy.Gateway", traceID)
}
44 changes: 17 additions & 27 deletions internal/proxy/handlers/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,11 @@ import (
"github.com/kenriortega/ngonx/pkg/otelify"
"github.com/prometheus/client_golang/prometheus"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/codes"
"go.opentelemetry.io/otel/trace"
"go.uber.org/zap"
)

func otelRegister(ctx context.Context, start time.Time, req *http.Request, err error) {
func otelRegisterByRequest(ctx context.Context, start time.Time, req *http.Request, err error) {

traceID := trace.SpanContextFromContext(ctx).TraceID().String()

Expand All @@ -32,6 +31,7 @@ func otelRegister(ctx context.Context, start time.Time, req *http.Request, err e
zap.String("path", req.URL.Path),
zap.Duration("latency", time.Since(start)),
)

return
}
logger.LogInfo(
Expand All @@ -44,16 +44,15 @@ func otelRegister(ctx context.Context, start time.Time, req *http.Request, err e

// checkJWT check jwt for request
func checkJWT(ctx context.Context, req *http.Request, key string) error {
_, span := otel.Tracer("proxy.gateway.checkJWT").Start(ctx, "checkJWT")
ctx, span := otel.Tracer("proxy.gateway.checkJWT").Start(ctx, "checkJWT")
defer span.End()
traceID := trace.SpanContextFromContext(ctx).TraceID().String()

header := req.Header.Get("Authorization") // pass to constanst
hs := jwt.NewHS256([]byte(key))
now := time.Now()
if !strings.HasPrefix(header, "Bearer ") {
span.RecordError(errors.ErrBearerTokenFormat)
span.SetStatus(codes.Error, errors.ErrBearerTokenFormat.Error())
logger.LogError(errors.Errorf("proxy: %v", errors.ErrBearerTokenFormat).Error())

otelify.InstrumentedError(span, "checkJWT.bearer", traceID, errors.ErrBearerTokenFormat)
return errors.ErrBearerTokenFormat
}

Expand All @@ -65,20 +64,14 @@ func checkJWT(ctx context.Context, req *http.Request, key string) error {
_, err := jwt.Verify([]byte(token), hs, &pl, validatePayload)

if errors.ErrorIs(err, jwt.ErrExpValidation) {
span.RecordError(errors.ErrTokenExpValidation)
span.SetStatus(codes.Error, errors.ErrTokenExpValidation.Error())
logger.LogError(errors.Errorf("proxy: %v", errors.ErrTokenExpValidation).Error())

otelify.InstrumentedError(span, "checkJWT.expValidation", traceID, errors.ErrTokenExpValidation)
return errors.ErrTokenExpValidation
}
if errors.ErrorIs(err, jwt.ErrHMACVerification) {
span.RecordError(errors.ErrTokenHMACValidation)
span.SetStatus(codes.Error, errors.ErrTokenHMACValidation.Error())
logger.LogError(errors.Errorf("proxy: %v", errors.ErrTokenHMACValidation).Error())

otelify.InstrumentedError(span, "checkJWT.HMACValidation", traceID, errors.ErrTokenHMACValidation)
return errors.ErrTokenHMACValidation
}
span.AddEvent("checkJWT done!")
otelify.InstrumentedInfo(span, "checkJWT", traceID)
return nil
}

Expand All @@ -89,25 +82,22 @@ func checkAPIKEY(
ph *ProxyHandler,
engine, key string,
) error {
_, span := otel.Tracer("proxy.gateway.checkAPIKey").Start(ctx, "checkAPIKEY")
ctx, span := otel.Tracer("proxy.gateway.checkAPIKey").Start(ctx, "checkAPIKEY")
defer span.End()
apikey, err := ph.Service.GetKEY(engine, key)
traceID := trace.SpanContextFromContext(ctx).TraceID().String()

header := req.Header.Get("X-API-KEY")
apikey, err := ph.Service.GetKEY(engine, key)
if err != nil {
span.RecordError(errors.ErrGetkeyView)
span.SetStatus(codes.Error, errors.ErrGetkeyView.Error())
logger.LogError(errors.Errorf("proxy: %v", errors.ErrGetkeyView).Error())

otelify.InstrumentedError(span, "checkAPIKEY.GetKEY", traceID, errors.ErrGetkeyView)
return errors.ErrGetkeyView
}
if apikey == header {
logger.LogInfo("proxy: check secret from request OK")
otelify.InstrumentedInfo(span, "checkAPIKEY", traceID)
return nil
} else {
invalidKeyErr := errors.NewError("Invalid API KEY")
span.RecordError(invalidKeyErr)
span.SetStatus(codes.Error, invalidKeyErr.Error())
logger.LogError(invalidKeyErr.Error())
otelify.InstrumentedError(span, "chackAPIKEY.invalidHeader", traceID, invalidKeyErr)
return invalidKeyErr
}

}
16 changes: 15 additions & 1 deletion internal/proxy/services/proxy.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,12 @@
package proxy

import (
"context"

domain "github.com/kenriortega/ngonx/internal/proxy/domain"
"github.com/kenriortega/ngonx/pkg/otelify"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/trace"
)

// ProxyService interface service for proxy repository funcionalities
Expand All @@ -22,19 +27,28 @@ func NewProxyService(repository domain.ProxyRepository) DefaultProxyService {

// SaveSecretKEY save secret key
func (s DefaultProxyService) SaveSecretKEY(engine, key, apikey string) (string, error) {

ctx, span := otel.Tracer("proxy.service.SaveSecretKEY").Start(context.Background(), "ProxyGateway")
defer span.End()
traceID := trace.SpanContextFromContext(ctx).TraceID().String()
err := s.repo.SaveKEY(engine, key, apikey)
if err != nil {
otelify.InstrumentedError(span, "SaveKey", traceID, err)
return "failed", err
}
otelify.InstrumentedInfo(span, "service.SaveSecretKEY", traceID)
return "ok", nil
}

// GetKEY get key
func (s DefaultProxyService) GetKEY(engine, key string) (string, error) {
ctx, span := otel.Tracer("proxy.service.GetKEY").Start(context.Background(), "ProxyGateway")
defer span.End()
traceID := trace.SpanContextFromContext(ctx).TraceID().String()
result, err := s.repo.GetKEY(engine, key)
if err != nil {
otelify.InstrumentedError(span, "GetKey", traceID, err)
return "failed", err
}
otelify.InstrumentedInfo(span, "service.GetKey", traceID)
return result, nil
}

0 comments on commit fd08b3d

Please sign in to comment.