Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat!(opentelemetry): migrate from opencensus to opentelemetry #266

Draft
wants to merge 18 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
18 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 13 additions & 6 deletions app.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,17 +12,18 @@ import (
"strings"
"time"

"flamingo.me/opentelemetry"
"go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp"

"flamingo.me/dingo"
"github.com/spf13/cobra"
"go.opencensus.io/plugin/ochttp"

"flamingo.me/flamingo/v3/core/runtime"
"flamingo.me/flamingo/v3/core/zap"
"flamingo.me/flamingo/v3/framework"
"flamingo.me/flamingo/v3/framework/cmd"
"flamingo.me/flamingo/v3/framework/config"
"flamingo.me/flamingo/v3/framework/flamingo"
"flamingo.me/flamingo/v3/framework/opencensus"
"flamingo.me/flamingo/v3/framework/web"
)

Expand Down Expand Up @@ -331,7 +332,7 @@ type servemodule struct {
server *http.Server
eventRouter flamingo.EventRouter
logger flamingo.Logger
configuredSampler *opencensus.ConfiguredURLPrefixSampler
configuredSampler *opentelemetry.ConfiguredURLPrefixSampler
certFile, keyFile string
publicEndpoint bool
}
Expand All @@ -341,10 +342,10 @@ func (a *servemodule) Inject(
router *web.Router,
eventRouter flamingo.EventRouter,
logger flamingo.Logger,
configuredSampler *opencensus.ConfiguredURLPrefixSampler,
configuredSampler *opentelemetry.ConfiguredURLPrefixSampler,
cfg *struct {
Port int `inject:"config:core.serve.port"`
PublicEndpoint bool `inject:"config:flamingo.opencensus.publicEndpoint,optional"`
PublicEndpoint bool `inject:"config:flamingo.opentelemetry.publicEndpoint,optional"`
},
) {
a.router = router
Expand Down Expand Up @@ -376,7 +377,13 @@ func serveProvider(a *servemodule, logger flamingo.Logger) *cobra.Command {
Use: "serve",
Short: "Default serve command - starts on Port 3322",
Run: func(cmd *cobra.Command, args []string) {
a.server.Handler = &ochttp.Handler{IsPublicEndpoint: a.publicEndpoint, Handler: a.router.Handler(), GetStartOptions: a.configuredSampler.GetStartOptions()}
options := []otelhttp.Option{
otelhttp.WithFilter(a.configuredSampler.GetFilterOption()),
}
if a.publicEndpoint {
options = append(options, otelhttp.WithPublicEndpoint())
}
a.server.Handler = otelhttp.NewHandler(a.router.Handler(), "server", options...)

err := a.listenAndServe()
if err != nil {
Expand Down
2 changes: 1 addition & 1 deletion core/cache/cache.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ package cache
import (
"time"

"go.opencensus.io/trace"
"go.opentelemetry.io/otel/trace"
)

type (
Expand Down
28 changes: 14 additions & 14 deletions core/cache/httpFrontend.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,10 @@ import (
"net/http"
"time"

"go.opencensus.io/trace"
"golang.org/x/sync/singleflight"

"flamingo.me/flamingo/v3/framework/flamingo"
"github.com/golang/groupcache/singleflight"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/trace"
)

type (
Expand Down Expand Up @@ -79,8 +79,8 @@ func (hf *HTTPFrontend) Get(ctx context.Context, key string, loader HTTPLoader)
return nil, errors.New("NO backend in Cache")
}

ctx, span := trace.StartSpan(ctx, "flamingo/cache/httpFrontend/Get")
span.Annotate(nil, key)
ctx, span := otel.Tracer("flamingo.me/opentelemetry").Start(ctx, "flamingo/cache/httpFrontend/Get")
span.AddEvent(key)
defer span.End()

if entry, ok := hf.backend.Get(key); ok {
Expand Down Expand Up @@ -111,16 +111,16 @@ func (hf *HTTPFrontend) Get(ctx context.Context, key string, loader HTTPLoader)
}

func (hf *HTTPFrontend) load(ctx context.Context, key string, loader HTTPLoader, keepExistingEntry bool) (cachedResponse, error) {
oldSpan := trace.FromContext(ctx)
newContext := trace.NewContext(context.Background(), oldSpan)
oldSpan := trace.SpanFromContext(ctx)
newContext := trace.ContextWithSpan(context.Background(), oldSpan)

newContextWithSpan, span := trace.StartSpan(newContext, "flamingo/cache/httpFrontend/load")
span.Annotate(nil, key)
newContextWithSpan, span := otel.Tracer("flamingo.me/opentelemetry").Start(newContext, "flamingo/cache/httpFrontend/load")
span.AddEvent(key)
defer span.End()

data, err, _ := hf.Do(key, func() (res interface{}, resultErr error) {
ctx, fetchRoutineSpan := trace.StartSpan(newContextWithSpan, "flamingo/cache/httpFrontend/fetchRoutine")
fetchRoutineSpan.Annotate(nil, key)
data, err := hf.Do(key, func() (res interface{}, resultErr error) {
ctx, fetchRoutineSpan := otel.Tracer("flamingo.me/opentelemetry").Start(newContextWithSpan, "flamingo/cache/httpFrontend/fetchRoutine")
fetchRoutineSpan.AddEvent(key)
defer fetchRoutineSpan.End()

defer func() {
Expand Down Expand Up @@ -198,8 +198,8 @@ func (hf *HTTPFrontend) load(ctx context.Context, key string, loader HTTPLoader,
})
}

span.AddAttributes(trace.StringAttribute("parenttrace", response.span.TraceID.String()))
span.AddAttributes(trace.StringAttribute("parentspan", response.span.SpanID.String()))
span.SetAttributes(attribute.String("parenttrace", response.span.TraceID().String()))
span.SetAttributes(attribute.String("parentspan", response.span.SpanID().String()))

return cached, err
}
2 changes: 1 addition & 1 deletion core/cache/stringFrontend.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ package cache
import (
"time"

"go.opencensus.io/trace"
"go.opentelemetry.io/otel/trace"
"golang.org/x/sync/singleflight"
)

Expand Down
7 changes: 3 additions & 4 deletions core/gotemplate/engine.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@ import (
"time"

"flamingo.me/flamingo/v3/framework/flamingo"
"go.opencensus.io/trace"
)

const pathSeparatorString = string(os.PathSeparator)
Expand Down Expand Up @@ -60,7 +59,7 @@ func (e *engine) Inject(
}

func (e *engine) Render(ctx context.Context, name string, data interface{}) (io.Reader, error) {
ctx, span := trace.StartSpan(ctx, "gotemplate/Render")
ctx, span := otel.Tracer("flamingo.me/opentelemetry").Start(ctx, "gotemplate/Render")
defer span.End()

lock.Lock()
Expand All @@ -73,7 +72,7 @@ func (e *engine) Render(ctx context.Context, name string, data interface{}) (io.
}
lock.Unlock()

_, span = trace.StartSpan(ctx, "gotemplate/Execute")
_, span = otel.Tracer("flamingo.me/opentelemetry").Start(ctx, "gotemplate/Execute")
buf := &bytes.Buffer{}

if _, ok := e.templates[name+".html"]; !ok {
Expand All @@ -98,7 +97,7 @@ func (e *engine) Render(ctx context.Context, name string, data interface{}) (io.
}

func (e *engine) loadTemplates(ctx context.Context) error {
ctx, span := trace.StartSpan(ctx, "gotemplate/loadTemplates")
ctx, span := otel.Tracer("flamingo.me/opentelemetry").Start(ctx, "gotemplate/loadTemplates")
defer span.End()

e.templates = make(map[string]*template.Template, 0)
Expand Down
29 changes: 16 additions & 13 deletions core/oauth/interfaces/callback_controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,8 @@ import (
"flamingo.me/flamingo/v3/core/oauth/application"
"flamingo.me/flamingo/v3/core/oauth/domain"
"flamingo.me/flamingo/v3/framework/flamingo"
"flamingo.me/flamingo/v3/framework/opencensus"
"flamingo.me/flamingo/v3/framework/web"
"go.opencensus.io/stats"
"go.opencensus.io/stats/view"
"go.opentelemetry.io/otel/metric"
)

type (
Expand All @@ -33,16 +31,21 @@ type (

var (
// loginFailedCount counts the failed login attempts
loginFailedCount = stats.Int64("flamingo/oauth/login_failed", "Count of failed login attempts", stats.UnitDimensionless)
loginFailedCount metric.Int64Counter
// loginSucceededCount counts the successful login attempts
loginSucceededCount = stats.Int64("flamingo/oauth/login_succeeded", "Count of succeeded login attempts", stats.UnitDimensionless)
loginSucceededCount metric.Int64Counter
)

func init() {
if err := opencensus.View("flamingo/oauth/login_failed", loginFailedCount, view.Count()); err != nil {
var err error
loginFailedCount, err = otel.Meter("flamingo.me/opentelemetry").Int64Counter("flamingo/oauth/login_failed",
metric.WithDescription("Count of failed login attempts"))
if err != nil {
panic(err)
}
if err := opencensus.View("flamingo/oauth/login_succeeded", loginSucceededCount, view.Count()); err != nil {
loginSucceededCount, err = otel.Meter("flamingo.me/opentelemetry").Int64Counter("flamingo/oauth/login_succeeded",
metric.WithDescription("Count of succeeded login attempts"))
if err != nil {
panic(err)
}
}
Expand Down Expand Up @@ -73,7 +76,7 @@ func (cc *CallbackController) Get(ctx context.Context, request *web.Request) web
cc.logger.Error(fmt.Sprintf("Invalid State - expected: %v got: %v", state, request.Request().URL.Query().Get("state")))
}

stats.Record(ctx, loginFailedCount.M(1))
loginFailedCount.Add(ctx, 1)
return cc.responder.ServerError(errors.New("invalid state"))
}

Expand All @@ -86,30 +89,30 @@ func (cc *CallbackController) Get(ctx context.Context, request *web.Request) web
if code == "" && errCode == "" {
err := errors.New("missing both code and error get parameter")
cc.logger.Error("core.auth.callback Missing parameter", err)
stats.Record(ctx, loginFailedCount.M(1))
loginFailedCount.Add(ctx, 1)
return cc.responder.ServerError(err)
} else if code != "" {
oauth2Token, err := cc.authManager.OAuth2Config(ctx, request).Exchange(cc.authManager.OAuthCtx(ctx), code)
if err != nil {
cc.logger.Error("core.auth.callback Error OAuth2Config Exchange", err)
stats.Record(ctx, loginFailedCount.M(1))
loginFailedCount.Add(ctx, 1)
return cc.responder.ServerError(fmt.Errorf("core.auth.callback error in OAuth2Config Exchange: %w", err))
}

err = cc.authManager.StoreTokenDetails(ctx, request.Session(), oauth2Token)
if err != nil {
cc.logger.Error("core.auth.callback Error", err)
stats.Record(ctx, loginFailedCount.M(1))
loginFailedCount.Add(ctx, 1)
return cc.responder.ServerError(fmt.Errorf("core.auth.StoreTokenDetails error %w", err))
}
cc.eventPublisher.PublishLoginEvent(ctx, &domain.LoginEvent{Session: request.Session()})
cc.logger.Debug("successful logged in and saved tokens", oauth2Token)
cc.logger.Debugf("Token expiry %v", oauth2Token.Expiry)
request.Session().AddFlash("successful logged in")
stats.Record(ctx, loginSucceededCount.M(1))
loginSucceededCount.Add(ctx, 1)
} else if errCode != "" {
cc.logger.Error("core.auth.callback Error parameter", errCode)
stats.Record(ctx, loginFailedCount.M(1))
loginFailedCount.Add(ctx, 1)
}

if redirect, ok := request.Session().Load("auth.redirect"); ok {
Expand Down
3 changes: 1 addition & 2 deletions core/requesttask/filter.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ import (
"sync"

"flamingo.me/flamingo/v3/framework/web"
"go.opencensus.io/trace"
)

type (
Expand All @@ -31,7 +30,7 @@ func TryDo(ctx context.Context, r *web.Request, task func(ctx context.Context, r
wg.Add(1)

go func() {
ctx, span := trace.StartSpan(ctx, "requestTask")
ctx, span := otel.Tracer("flamingo.me/opentelemetry").Start(ctx, "requestTask")
task(ctx, r)
span.End()
wg.Done()
Expand Down
31 changes: 16 additions & 15 deletions core/zap/logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,27 +4,29 @@ import (
"context"
"fmt"

"go.opencensus.io/stats"
"go.opencensus.io/stats/view"
"go.opencensus.io/tag"
"go.opencensus.io/trace"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/attribute"

"flamingo.me/flamingo/v3/framework/flamingo"
"flamingo.me/flamingo/v3/framework/opencensus"
"flamingo.me/flamingo/v3/framework/web"
"go.opentelemetry.io/otel/metric"
"go.opentelemetry.io/otel/trace"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
)

type Option func(*Logger)

var (
logCount = stats.Int64("flamingo/zap/logs", "Count of logs", stats.UnitDimensionless)
keyLevel, _ = tag.NewKey("level")
logCount metric.Int64Counter
keyLevel attribute.Key = "level"
)

func init() {
if err := opencensus.View("flamingo/zap/logs", logCount, view.Count(), keyLevel); err != nil {
var err error
logCount, err = otel.Meter("flamingo.me/opentelemetry").Int64Counter("flamingo/zap/logs",
metric.WithDescription("Count of logs"))
if err != nil {
panic(err)
}
}
Expand Down Expand Up @@ -61,10 +63,10 @@ func NewLogger(logger *zap.Logger, options ...Option) *Logger {
// referer: referer from request
// request: received payload from request
func (l *Logger) WithContext(ctx context.Context) flamingo.Logger {
span := trace.FromContext(ctx)
span := trace.SpanFromContext(ctx)
fields := map[flamingo.LogKey]interface{}{
flamingo.LogKeyTraceID: span.SpanContext().TraceID.String(),
flamingo.LogKeySpanID: span.SpanContext().SpanID.String(),
flamingo.LogKeyTraceID: span.SpanContext().TraceID().String(),
flamingo.LogKeySpanID: span.SpanContext().SpanID().String(),
}

req := web.RequestFromContext(ctx)
Expand All @@ -90,8 +92,7 @@ func (l *Logger) record(level string) {
return
}

ctx, _ := tag.New(context.Background(), tag.Upsert(opencensus.KeyArea, l.configArea), tag.Upsert(keyLevel, level))
stats.Record(ctx, logCount.M(1))
logCount.Add(context.Background(), 1, metric.WithAttributes(attribute.String(web.AreaKey.Key(), l.configArea), keyLevel.String(level)))
}

// Debug logs a message at debug level
Expand Down
Loading