diff --git a/changelog/unreleased/trace-proxy-middlewares.md b/changelog/unreleased/trace-proxy-middlewares.md
new file mode 100644
index 0000000000..ba30e24ced
--- /dev/null
+++ b/changelog/unreleased/trace-proxy-middlewares.md
@@ -0,0 +1,5 @@
+Bugfix: trace proxy middlewares
+
+We moved trace initialization to an early middleware to also trace requests made by other proxy middlewares.
+
+https://github.com/owncloud/ocis/pull/6313
diff --git a/go.mod b/go.mod
index 715d6a600d..7576498539 100644
--- a/go.mod
+++ b/go.mod
@@ -37,7 +37,7 @@ require (
github.com/go-micro/plugins/v4/server/http v1.2.1
github.com/go-micro/plugins/v4/wrapper/breaker/gobreaker v1.2.0
github.com/go-micro/plugins/v4/wrapper/monitoring/prometheus v1.2.0
- github.com/go-micro/plugins/v4/wrapper/trace/opencensus v1.1.0
+ github.com/go-micro/plugins/v4/wrapper/trace/opentelemetry v1.2.0
github.com/go-ozzo/ozzo-validation/v4 v4.3.0
github.com/gofrs/uuid v4.4.0+incompatible
github.com/golang-jwt/jwt/v4 v4.5.0
@@ -80,12 +80,12 @@ require (
github.com/xhit/go-simple-mail/v2 v2.13.0
go-micro.dev/v4 v4.9.0
go.etcd.io/bbolt v1.3.7
- go.opencensus.io v0.24.0
- go.opentelemetry.io/otel v1.14.0
- go.opentelemetry.io/otel/exporters/jaeger v1.14.0
- go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.14.0
- go.opentelemetry.io/otel/sdk v1.14.0
- go.opentelemetry.io/otel/trace v1.14.0
+ go.opentelemetry.io/contrib/zpages v0.41.1
+ go.opentelemetry.io/otel v1.15.1
+ go.opentelemetry.io/otel/exporters/jaeger v1.15.1
+ go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.15.1
+ go.opentelemetry.io/otel/sdk v1.15.1
+ go.opentelemetry.io/otel/trace v1.15.1
golang.org/x/crypto v0.9.0
golang.org/x/exp v0.0.0-20221026004748-78e5e7837ae6
golang.org/x/image v0.6.0
@@ -146,7 +146,7 @@ require (
github.com/bmizerany/pat v0.0.0-20210406213842-e4b6760bdd6f // indirect
github.com/bombsimon/logrusr/v3 v3.1.0 // indirect
github.com/cenkalti/backoff v2.2.1+incompatible // indirect
- github.com/cenkalti/backoff/v4 v4.2.0 // indirect
+ github.com/cenkalti/backoff/v4 v4.2.1 // indirect
github.com/ceph/go-ceph v0.18.0 // indirect
github.com/cespare/xxhash/v2 v2.2.0 // indirect
github.com/cevaris/ordered_map v0.0.0-20190319150403-3adeae072e73 // indirect
@@ -306,9 +306,10 @@ require (
go.etcd.io/etcd/api/v3 v3.5.7 // indirect
go.etcd.io/etcd/client/pkg/v3 v3.5.7 // indirect
go.etcd.io/etcd/client/v3 v3.5.7 // indirect
+ go.opencensus.io v0.24.0 // indirect
go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.36.4 // indirect
- go.opentelemetry.io/otel/exporters/otlp/internal/retry v1.14.0 // indirect
- go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.14.0 // indirect
+ go.opentelemetry.io/otel/exporters/otlp/internal/retry v1.15.1 // indirect
+ go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.15.1 // indirect
go.opentelemetry.io/proto/otlp v0.19.0 // indirect
go.uber.org/atomic v1.10.0 // indirect
go.uber.org/multierr v1.8.0 // indirect
diff --git a/go.sum b/go.sum
index f424880de9..44b7205dac 100644
--- a/go.sum
+++ b/go.sum
@@ -568,8 +568,8 @@ github.com/cenkalti/backoff v2.2.1+incompatible h1:tNowT99t7UNflLxfYYSlKYsBpXdEe
github.com/cenkalti/backoff v2.2.1+incompatible/go.mod h1:90ReRw6GdpyfrHakVjL/QHaoyV4aDUVVkXQJJJ3NXXM=
github.com/cenkalti/backoff/v4 v4.1.0/go.mod h1:scbssz8iZGpm3xbr14ovlUdkxfGXNInqkPWOWmG2CLw=
github.com/cenkalti/backoff/v4 v4.1.2/go.mod h1:scbssz8iZGpm3xbr14ovlUdkxfGXNInqkPWOWmG2CLw=
-github.com/cenkalti/backoff/v4 v4.2.0 h1:HN5dHm3WBOgndBH6E8V0q2jIYIR3s9yglV8k/+MN3u4=
-github.com/cenkalti/backoff/v4 v4.2.0/go.mod h1:Y3VNntkOUPxTVeUxJ/G5vcM//AlwfmyYozVcomhLiZE=
+github.com/cenkalti/backoff/v4 v4.2.1 h1:y4OZtCnogmCPw98Zjyt5a6+QwPLGkiQsYW5oUqylYbM=
+github.com/cenkalti/backoff/v4 v4.2.1/go.mod h1:Y3VNntkOUPxTVeUxJ/G5vcM//AlwfmyYozVcomhLiZE=
github.com/census-instrumentation/opencensus-proto v0.2.0/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU=
github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU=
github.com/census-instrumentation/opencensus-proto v0.3.0/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU=
@@ -803,8 +803,8 @@ github.com/go-micro/plugins/v4/wrapper/breaker/gobreaker v1.2.0 h1:EQj4l7fuOSz8u
github.com/go-micro/plugins/v4/wrapper/breaker/gobreaker v1.2.0/go.mod h1:JR9Ox/iJIrcXm8nCWdAEBsyG7Q7lyMLzsTZPfXrqvwo=
github.com/go-micro/plugins/v4/wrapper/monitoring/prometheus v1.2.0 h1:UWBUYtMXCxQ9bIGOYcbLOjtPv8ovvCRjWWM6tHhB4S8=
github.com/go-micro/plugins/v4/wrapper/monitoring/prometheus v1.2.0/go.mod h1:8BYxs/wEE4ZJayHZQffw4A8s9rcPumyoNms0hYoNocM=
-github.com/go-micro/plugins/v4/wrapper/trace/opencensus v1.1.0 h1:ITm1vEP8BPEccWFAu6/tMFHrxHfwYzE4GdkCy6PlF6A=
-github.com/go-micro/plugins/v4/wrapper/trace/opencensus v1.1.0/go.mod h1:4izlDcwSo9tu8v2TcaBgpO3EmNqUkB4oMFSwxvSt438=
+github.com/go-micro/plugins/v4/wrapper/trace/opentelemetry v1.2.0 h1:e2hgtWMNqJ3DmbMt9ZxzmH/BkVAw9Xg23l6CHrXQfKw=
+github.com/go-micro/plugins/v4/wrapper/trace/opentelemetry v1.2.0/go.mod h1:BBqL7ckGNb7rFfk3vU2Yj/CILVsz/WF19CkAyveQl8A=
github.com/go-openapi/analysis v0.21.2/go.mod h1:HZwRk4RRisyG8vx2Oe6aqeSQcoxRp47Xkp3+K6q+LdY=
github.com/go-openapi/errors v0.19.8/go.mod h1:cM//ZKUKyO06HSwqAelJ5NsEMMcpa6VpXe8DOa1Mi1M=
github.com/go-openapi/errors v0.19.9/go.mod h1:cM//ZKUKyO06HSwqAelJ5NsEMMcpa6VpXe8DOa1Mi1M=
@@ -1675,20 +1675,22 @@ go.opencensus.io v0.24.0 h1:y73uSU6J157QMP2kn2r30vwW1A2W2WFwSCGnAVxeaD0=
go.opencensus.io v0.24.0/go.mod h1:vNK8G9p7aAivkbmorf4v+7Hgx+Zs0yY+0fOtgBfjQKo=
go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.36.4 h1:PRXhsszxTt5bbPriTjmaweWUsAnJYeWBhUMLRetUgBU=
go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.36.4/go.mod h1:05eWWy6ZWzmpeImD3UowLTB3VjDMU1yxQ+ENuVWDM3c=
-go.opentelemetry.io/otel v1.14.0 h1:/79Huy8wbf5DnIPhemGB+zEPVwnN6fuQybr/SRXa6hM=
-go.opentelemetry.io/otel v1.14.0/go.mod h1:o4buv+dJzx8rohcUeRmWUZhqupFvzWis188WlggnNeU=
-go.opentelemetry.io/otel/exporters/jaeger v1.14.0 h1:CjbUNd4iN2hHmWekmOqZ+zSCU+dzZppG8XsV+A3oc8Q=
-go.opentelemetry.io/otel/exporters/jaeger v1.14.0/go.mod h1:4Ay9kk5vELRrbg5z4cpP9EtmQRFap2Wb0woPG4lujZA=
-go.opentelemetry.io/otel/exporters/otlp/internal/retry v1.14.0 h1:/fXHZHGvro6MVqV34fJzDhi7sHGpX3Ej/Qjmfn003ho=
-go.opentelemetry.io/otel/exporters/otlp/internal/retry v1.14.0/go.mod h1:UFG7EBMRdXyFstOwH028U0sVf+AvukSGhF0g8+dmNG8=
-go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.14.0 h1:TKf2uAs2ueguzLaxOCBXNpHxfO/aC7PAdDsSH0IbeRQ=
-go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.14.0/go.mod h1:HrbCVv40OOLTABmOn1ZWty6CHXkU8DK/Urc43tHug70=
-go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.14.0 h1:ap+y8RXX3Mu9apKVtOkM6WSFESLM8K3wNQyOU8sWHcc=
-go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.14.0/go.mod h1:5w41DY6S9gZrbjuq6Y+753e96WfPha5IcsOSZTtullM=
-go.opentelemetry.io/otel/sdk v1.14.0 h1:PDCppFRDq8A1jL9v6KMI6dYesaq+DFcDZvjsoGvxGzY=
-go.opentelemetry.io/otel/sdk v1.14.0/go.mod h1:bwIC5TjrNG6QDCHNWvW4HLHtUQ4I+VQDsnjhvyZCALM=
-go.opentelemetry.io/otel/trace v1.14.0 h1:wp2Mmvj41tDsyAJXiWDWpfNsOiIyd38fy85pyKcFq/M=
-go.opentelemetry.io/otel/trace v1.14.0/go.mod h1:8avnQLK+CG77yNLUae4ea2JDQ6iT+gozhnZjy/rw9G8=
+go.opentelemetry.io/contrib/zpages v0.41.1 h1:FReY8OWFNtYm4mWleTRxTUyD3r02uGcwS6ZeElahs00=
+go.opentelemetry.io/contrib/zpages v0.41.1/go.mod h1:C3iy146ccMyv1+gEaxVDDHuoT7yXAKKmbg+twudDpeg=
+go.opentelemetry.io/otel v1.15.1 h1:3Iwq3lfRByPaws0f6bU3naAqOR1n5IeDWd9390kWHa8=
+go.opentelemetry.io/otel v1.15.1/go.mod h1:mHHGEHVDLal6YrKMmk9LqC4a3sF5g+fHfrttQIB1NTc=
+go.opentelemetry.io/otel/exporters/jaeger v1.15.1 h1:x3SLvwli0OyAJapNcOIzf1xXBRBA+HD3elrMQmFfmXo=
+go.opentelemetry.io/otel/exporters/jaeger v1.15.1/go.mod h1:0Ck9b5oLL/bFZvfAEEqtrb1U0jZXjm5fWXMCOCG3vvM=
+go.opentelemetry.io/otel/exporters/otlp/internal/retry v1.15.1 h1:XYDQtNzdb2T4uM1pku2m76eSMDJgqhJ+6KzkqgQBALc=
+go.opentelemetry.io/otel/exporters/otlp/internal/retry v1.15.1/go.mod h1:uOTV75+LOzV+ODmL8ahRLWkFA3eQcSC2aAsbxIu4duk=
+go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.15.1 h1:tyoeaUh8REKay72DVYsSEBYV18+fGONe+YYPaOxgLoE=
+go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.15.1/go.mod h1:HUSnrjQQ19KX9ECjpQxufsF+3ioD3zISPMlauTPZu2g=
+go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.15.1 h1:pIfoG5IAZFzp9EUlJzdSkpUwpaUAAnD+Ru1nBLTACIQ=
+go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.15.1/go.mod h1:poNKBqF5+nR/6ke2oGTDjHfksrsHDOHXAl2g4+9ONsY=
+go.opentelemetry.io/otel/sdk v1.15.1 h1:5FKR+skgpzvhPQHIEfcwMYjCBr14LWzs3uSqKiQzETI=
+go.opentelemetry.io/otel/sdk v1.15.1/go.mod h1:8rVtxQfrbmbHKfqzpQkT5EzZMcbMBwTzNAggbEAM0KA=
+go.opentelemetry.io/otel/trace v1.15.1 h1:uXLo6iHJEzDfrNC0L0mNjItIp06SyaBQxu5t3xMlngY=
+go.opentelemetry.io/otel/trace v1.15.1/go.mod h1:IWdQG/5N1x7f6YUlmdLeJvH9yxtuJAfc4VW5Agv9r/8=
go.opentelemetry.io/proto/otlp v0.7.0/go.mod h1:PqfVotwruBrMGOCsRd/89rSnXhoiJIqeYNgFYFoEGnI=
go.opentelemetry.io/proto/otlp v0.19.0 h1:IVN6GR+mhC4s5yfcTbmzHYODqvWAp3ZedA2SJPI1Nnw=
go.opentelemetry.io/proto/otlp v0.19.0/go.mod h1:H7XAot3MsfNsj7EXtrA2q5xSNQ10UqI405h3+duxN4U=
diff --git a/ocis-pkg/service/debug/service.go b/ocis-pkg/service/debug/service.go
index a0432b8652..0f806e5748 100644
--- a/ocis-pkg/service/debug/service.go
+++ b/ocis-pkg/service/debug/service.go
@@ -10,7 +10,7 @@ import (
"github.com/owncloud/ocis/v2/ocis-pkg/middleware"
graphMiddleware "github.com/owncloud/ocis/v2/services/graph/pkg/middleware"
"github.com/prometheus/client_golang/prometheus/promhttp"
- "go.opencensus.io/zpages"
+ "go.opentelemetry.io/contrib/zpages"
)
// NewService initializes a new debug service.
@@ -42,7 +42,8 @@ func NewService(opts ...Option) *http.Server {
}
if dopts.Zpages {
- zpages.Handle(mux, "/debug")
+ h := zpages.NewTracezHandler(zpages.NewSpanProcessor())
+ mux.Handle("/debug", h)
}
return &http.Server{
diff --git a/ocis-pkg/service/grpc/client.go b/ocis-pkg/service/grpc/client.go
index 528118237d..d3c4090089 100644
--- a/ocis-pkg/service/grpc/client.go
+++ b/ocis-pkg/service/grpc/client.go
@@ -9,9 +9,11 @@ import (
mgrpcc "github.com/go-micro/plugins/v4/client/grpc"
mbreaker "github.com/go-micro/plugins/v4/wrapper/breaker/gobreaker"
+ mtracer "github.com/go-micro/plugins/v4/wrapper/trace/opentelemetry"
"github.com/owncloud/ocis/v2/ocis-pkg/registry"
"github.com/owncloud/ocis/v2/ocis-pkg/shared"
"go-micro.dev/v4/client"
+ "go.opentelemetry.io/otel/trace"
)
var (
@@ -23,6 +25,7 @@ var (
type ClientOptions struct {
tlsMode string
caCert string
+ tp trace.TracerProvider
}
// Option is used to pass client options
@@ -42,13 +45,19 @@ func WithTLSCACert(v string) ClientOption {
}
}
+// WithTraceProvider allows to set the trace Provider for grpc clients
+func WithTraceProvider(tp trace.TracerProvider) ClientOption {
+ return func(o *ClientOptions) {
+ o.tp = tp
+ }
+}
+
// Configure configures the default oOCIS grpc client (e.g. TLS settings)
func Configure(opts ...ClientOption) error {
var options ClientOptions
for _, opt := range opts {
opt(&options)
}
-
var outerr error
once.Do(func() {
reg := registry.GetRegistry()
@@ -56,6 +65,9 @@ func Configure(opts ...ClientOption) error {
cOpts := []client.Option{
client.Registry(reg),
client.Wrap(mbreaker.NewClientWrapper()),
+ client.Wrap(mtracer.NewClientWrapper(
+ mtracer.WithTraceProvider(options.tp),
+ )),
}
switch options.tlsMode {
case "insecure":
@@ -74,12 +86,14 @@ func Configure(opts ...ClientOption) error {
return
}
if !certs.AppendCertsFromPEM(pemData) {
- outerr = errors.New("Error initializing LDAP Backend. Adding CA cert failed")
+ outerr = errors.New("could not initialize default client, adding CA cert failed")
return
}
tlsConfig.RootCAs = certs
}
cOpts = append(cOpts, mgrpcc.AuthTLS(tlsConfig))
+ //case "off":
+ //default:
}
defaultClient = mgrpcc.NewClient(cOpts...)
@@ -99,3 +113,46 @@ func GetClientOptions(t *shared.GRPCClientTLS) []ClientOption {
}
return opts
}
+
+func NewClient(opts ...ClientOption) (client.Client, error) {
+ var options ClientOptions
+ for _, opt := range opts {
+ opt(&options)
+ }
+
+ reg := registry.GetRegistry()
+ var tlsConfig *tls.Config
+ cOpts := []client.Option{
+ client.Registry(reg),
+ client.Wrap(mbreaker.NewClientWrapper()),
+ client.Wrap(mtracer.NewClientWrapper(
+ mtracer.WithTraceProvider(options.tp),
+ )),
+ }
+ switch options.tlsMode {
+ case "insecure":
+ tlsConfig = &tls.Config{
+ InsecureSkipVerify: true,
+ }
+ cOpts = append(cOpts, mgrpcc.AuthTLS(tlsConfig))
+ case "on":
+ tlsConfig = &tls.Config{}
+ // Note: If caCert is empty we use the system's default set of trusted CAs
+ if options.caCert != "" {
+ certs := x509.NewCertPool()
+ pemData, err := os.ReadFile(options.caCert)
+ if err != nil {
+ return nil, err
+ }
+ if !certs.AppendCertsFromPEM(pemData) {
+ return nil, errors.New("could not initialize client, adding CA cert failed")
+ }
+ tlsConfig.RootCAs = certs
+ }
+ cOpts = append(cOpts, mgrpcc.AuthTLS(tlsConfig))
+ //case "off":
+ //default:
+ }
+
+ return mgrpcc.NewClient(cOpts...), nil
+}
diff --git a/ocis-pkg/service/grpc/service.go b/ocis-pkg/service/grpc/service.go
index 823ad5430a..d507213ef2 100644
--- a/ocis-pkg/service/grpc/service.go
+++ b/ocis-pkg/service/grpc/service.go
@@ -8,7 +8,7 @@ import (
mgrpcs "github.com/go-micro/plugins/v4/server/grpc"
"github.com/go-micro/plugins/v4/wrapper/monitoring/prometheus"
- "github.com/go-micro/plugins/v4/wrapper/trace/opencensus"
+ mtracer "github.com/go-micro/plugins/v4/wrapper/trace/opentelemetry"
ociscrypto "github.com/owncloud/ocis/v2/ocis-pkg/crypto"
"github.com/owncloud/ocis/v2/ocis-pkg/registry"
"go-micro.dev/v4"
@@ -62,9 +62,9 @@ func NewService(opts ...Option) (Service, error) {
micro.RegisterTTL(time.Second * 30),
micro.RegisterInterval(time.Second * 10),
micro.WrapHandler(prometheus.NewHandlerWrapper()),
- micro.WrapClient(opencensus.NewClientWrapper()),
- micro.WrapHandler(opencensus.NewHandlerWrapper()),
- micro.WrapSubscriber(opencensus.NewSubscriberWrapper()),
+ micro.WrapClient(mtracer.NewClientWrapper()),
+ micro.WrapHandler(mtracer.NewHandlerWrapper()),
+ micro.WrapSubscriber(mtracer.NewSubscriberWrapper()),
}
return Service{micro.NewService(mopts...)}, nil
diff --git a/services/graph/pkg/server/http/server.go b/services/graph/pkg/server/http/server.go
index fe9e34d75f..213cc7577f 100644
--- a/services/graph/pkg/server/http/server.go
+++ b/services/graph/pkg/server/http/server.go
@@ -18,7 +18,6 @@ import (
"github.com/owncloud/ocis/v2/ocis-pkg/keycloak"
"github.com/owncloud/ocis/v2/ocis-pkg/middleware"
"github.com/owncloud/ocis/v2/ocis-pkg/service/grpc"
- ogrpc "github.com/owncloud/ocis/v2/ocis-pkg/service/grpc"
"github.com/owncloud/ocis/v2/ocis-pkg/service/http"
"github.com/owncloud/ocis/v2/ocis-pkg/version"
ehsvc "github.com/owncloud/ocis/v2/protogen/gen/ocis/services/eventhistory/v0"
@@ -26,6 +25,7 @@ import (
settingssvc "github.com/owncloud/ocis/v2/protogen/gen/ocis/services/settings/v0"
graphMiddleware "github.com/owncloud/ocis/v2/services/graph/pkg/middleware"
svc "github.com/owncloud/ocis/v2/services/graph/pkg/service/v0"
+ "github.com/owncloud/ocis/v2/services/graph/pkg/tracing"
"github.com/pkg/errors"
"go-micro.dev/v4"
"go-micro.dev/v4/events"
@@ -115,13 +115,17 @@ func Server(opts ...Option) (http.Service, error) {
var requireAdminMiddleware func(stdhttp.Handler) stdhttp.Handler
var roleService svc.RoleService
var gatewayClient gateway.GatewayAPIClient
+ grpcClient, err := grpc.NewClient(append(grpc.GetClientOptions(options.Config.GRPCClientTLS), grpc.WithTraceProvider(tracing.TraceProvider))...)
+ if err != nil {
+ return http.Service{}, err
+ }
if options.Config.HTTP.APIToken == "" {
middlewares = append(middlewares,
graphMiddleware.Auth(
account.Logger(options.Logger),
account.JWTSecret(options.Config.TokenManager.JWTSecret),
))
- roleService = settingssvc.NewRoleService("com.owncloud.api.settings", grpc.DefaultClient())
+ roleService = settingssvc.NewRoleService("com.owncloud.api.settings", grpcClient)
gatewayClient, err = pool.GetGatewayServiceClient(options.Config.Reva.Address, options.Config.Reva.GetRevaOptions()...)
if err != nil {
return http.Service{}, errors.Wrap(err, "could not initialize gateway client")
@@ -145,7 +149,7 @@ func Server(opts ...Option) (http.Service, error) {
keyCloakClient = keycloak.New(kcc.BasePath, kcc.ClientID, kcc.ClientSecret, kcc.ClientRealm, kcc.InsecureSkipVerify)
}
- hClient := ehsvc.NewEventHistoryService("com.owncloud.api.eventhistory", ogrpc.DefaultClient())
+ hClient := ehsvc.NewEventHistoryService("com.owncloud.api.eventhistory", grpcClient)
var handle svc.Service
handle, err = svc.NewService(
@@ -156,7 +160,7 @@ func Server(opts ...Option) (http.Service, error) {
svc.WithRoleService(roleService),
svc.WithRequireAdminMiddleware(requireAdminMiddleware),
svc.WithGatewayClient(gatewayClient),
- svc.WithSearchService(searchsvc.NewSearchProviderService("com.owncloud.api.search", grpc.DefaultClient())),
+ svc.WithSearchService(searchsvc.NewSearchProviderService("com.owncloud.api.search", grpcClient)),
svc.KeycloakClient(keyCloakClient),
svc.EventHistoryClient(hClient),
)
diff --git a/services/graph/pkg/service/v0/drives.go b/services/graph/pkg/service/v0/drives.go
index 75f53475a9..5cb2a46622 100644
--- a/services/graph/pkg/service/v0/drives.go
+++ b/services/graph/pkg/service/v0/drives.go
@@ -31,6 +31,7 @@ import (
v0 "github.com/owncloud/ocis/v2/protogen/gen/ocis/messages/settings/v0"
settingssvc "github.com/owncloud/ocis/v2/protogen/gen/ocis/services/settings/v0"
"github.com/owncloud/ocis/v2/services/graph/pkg/service/v0/errorcode"
+ gtracing "github.com/owncloud/ocis/v2/services/graph/pkg/tracing"
settingsServiceExt "github.com/owncloud/ocis/v2/services/settings/pkg/store/defaults"
"github.com/pkg/errors"
merrors "go-micro.dev/v4/errors"
@@ -582,13 +583,17 @@ func (g Graph) formatDrives(ctx context.Context, baseURL *url.URL, storageSpaces
func (g Graph) ListStorageSpacesWithFilters(ctx context.Context, filters []*storageprovider.ListStorageSpacesRequest_Filter, unrestricted bool) (*storageprovider.ListStorageSpacesResponse, error) {
client := g.GetGatewayClient()
- permissions := make(map[string]struct{}, 1)
- s := settingssvc.NewPermissionService("com.owncloud.api.settings", grpc.DefaultClient())
+ grpcClient, err := grpc.NewClient(append(grpc.GetClientOptions(g.config.GRPCClientTLS), grpc.WithTraceProvider(gtracing.TraceProvider))...)
+ if err != nil {
+ return nil, err
+ }
+ s := settingssvc.NewPermissionService("com.owncloud.api.settings", grpcClient)
- _, err := s.GetPermissionByID(ctx, &settingssvc.GetPermissionByIDRequest{
+ _, err = s.GetPermissionByID(ctx, &settingssvc.GetPermissionByIDRequest{
PermissionId: settingsServiceExt.ListAllSpacesPermissionID,
})
+ permissions := make(map[string]struct{}, 1)
// No error means the user has the permission
if err == nil {
permissions[settingsServiceExt.ListAllSpacesPermissionName] = struct{}{}
diff --git a/services/graph/pkg/service/v0/password_test.go b/services/graph/pkg/service/v0/password_test.go
index fea072f399..72bf4a07fc 100644
--- a/services/graph/pkg/service/v0/password_test.go
+++ b/services/graph/pkg/service/v0/password_test.go
@@ -18,6 +18,7 @@ import (
. "github.com/onsi/gomega"
libregraph "github.com/owncloud/libre-graph-api-go"
"github.com/owncloud/ocis/v2/ocis-pkg/log"
+ "github.com/owncloud/ocis/v2/ocis-pkg/shared"
"github.com/owncloud/ocis/v2/services/graph/mocks"
"github.com/owncloud/ocis/v2/services/graph/pkg/config"
"github.com/owncloud/ocis/v2/services/graph/pkg/config/defaults"
@@ -44,6 +45,7 @@ var _ = Describe("Users changing their own password", func() {
ctx = context.Background()
cfg = defaults.FullDefaultConfig()
cfg.TokenManager.JWTSecret = "loremipsum"
+ cfg.GRPCClientTLS = &shared.GRPCClientTLS{}
gatewayClient = &cs3mocks.GatewayAPIClient{}
ldapClient = mockedLDAPClient()
diff --git a/services/graph/pkg/service/v0/service.go b/services/graph/pkg/service/v0/service.go
index 5c46f716e1..86fe823dd9 100644
--- a/services/graph/pkg/service/v0/service.go
+++ b/services/graph/pkg/service/v0/service.go
@@ -23,6 +23,7 @@ import (
"github.com/owncloud/ocis/v2/services/graph/pkg/identity"
"github.com/owncloud/ocis/v2/services/graph/pkg/identity/ldap"
graphm "github.com/owncloud/ocis/v2/services/graph/pkg/middleware"
+ gtracing "github.com/owncloud/ocis/v2/services/graph/pkg/tracing"
microstore "go-micro.dev/v4/store"
)
@@ -155,7 +156,11 @@ func NewService(opts ...Option) (Graph, error) {
}
if options.PermissionService == nil {
- svc.permissionsService = settingssvc.NewPermissionService("com.owncloud.api.settings", grpc.DefaultClient())
+ grpcClient, err := grpc.NewClient(append(grpc.GetClientOptions(options.Config.GRPCClientTLS), grpc.WithTraceProvider(gtracing.TraceProvider))...)
+ if err != nil {
+ return svc, err
+ }
+ svc.permissionsService = settingssvc.NewPermissionService("com.owncloud.api.settings", grpcClient)
} else {
svc.permissionsService = options.PermissionService
}
diff --git a/services/proxy/pkg/command/server.go b/services/proxy/pkg/command/server.go
index 3476662b01..e49317c172 100644
--- a/services/proxy/pkg/command/server.go
+++ b/services/proxy/pkg/command/server.go
@@ -271,7 +271,11 @@ func (h *StaticRouteHandler) backchannelLogout(w http.ResponseWriter, r *http.Re
}
func loadMiddlewares(ctx context.Context, logger log.Logger, cfg *config.Config, userInfoCache microstore.Store) alice.Chain {
- rolesClient := settingssvc.NewRoleService("com.owncloud.api.settings", grpc.DefaultClient())
+ grpcClient, err := grpc.NewClient(append(grpc.GetClientOptions(cfg.GRPCClientTLS), grpc.WithTraceProvider(tracing.TraceProvider))...)
+ if err != nil {
+ logger.Fatal().Err(err).Msg("Failed to get gateway client")
+ }
+ rolesClient := settingssvc.NewRoleService("com.owncloud.api.settings", grpcClient)
revaClient, err := pool.GetGatewayServiceClient(cfg.Reva.Address, cfg.Reva.GetRevaOptions()...)
if err != nil {
logger.Fatal().Err(err).Msg("Failed to get gateway client")
@@ -318,7 +322,7 @@ func loadMiddlewares(ctx context.Context, logger log.Logger, cfg *config.Config,
logger.Fatal().Msgf("Invalid role assignment driver '%s'", cfg.RoleAssignment.Driver)
}
- storeClient := storesvc.NewStoreService("com.owncloud.api.store", grpc.DefaultClient())
+ storeClient := storesvc.NewStoreService("com.owncloud.api.store", grpcClient)
if err != nil {
logger.Error().Err(err).
Str("gateway", cfg.Reva.Address).
@@ -375,6 +379,7 @@ func loadMiddlewares(ctx context.Context, logger log.Logger, cfg *config.Config,
return alice.New(
// first make sure we log all requests and redirect to https if necessary
+ middleware.Tracer(),
pkgmiddleware.TraceContext,
chimiddleware.RealIP,
chimiddleware.RequestID,
diff --git a/services/proxy/pkg/middleware/tracing.go b/services/proxy/pkg/middleware/tracing.go
new file mode 100644
index 0000000000..84760cba27
--- /dev/null
+++ b/services/proxy/pkg/middleware/tracing.go
@@ -0,0 +1,50 @@
+package middleware
+
+import (
+ "fmt"
+ "net/http"
+
+ chimiddleware "github.com/go-chi/chi/v5/middleware"
+ pkgtrace "github.com/owncloud/ocis/v2/ocis-pkg/tracing"
+ proxytracing "github.com/owncloud/ocis/v2/services/proxy/pkg/tracing"
+ "go.opentelemetry.io/otel/attribute"
+ "go.opentelemetry.io/otel/propagation"
+ "go.opentelemetry.io/otel/trace"
+)
+
+// Tracer provides a middleware to start traces
+func Tracer() func(next http.Handler) http.Handler {
+ return func(next http.Handler) http.Handler {
+ return &tracer{
+ next: next,
+ }
+ }
+}
+
+type tracer struct {
+ next http.Handler
+}
+
+func (m tracer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
+ var (
+ ctx = r.Context()
+ span trace.Span
+ )
+
+ tracer := proxytracing.TraceProvider.Tracer("proxy")
+ spanOpts := []trace.SpanStartOption{
+ trace.WithSpanKind(trace.SpanKindServer),
+ }
+ ctx, span = tracer.Start(ctx, fmt.Sprintf("%s %v", r.Method, r.URL.Path), spanOpts...)
+ defer span.End()
+
+ span.SetAttributes(
+ attribute.KeyValue{
+ Key: "x-request-id",
+ Value: attribute.StringValue(chimiddleware.GetReqID(r.Context())),
+ })
+
+ pkgtrace.Propagator.Inject(ctx, propagation.HeaderCarrier(r.Header))
+
+ m.next.ServeHTTP(w, r.WithContext(ctx))
+}
diff --git a/services/proxy/pkg/proxy/proxy.go b/services/proxy/pkg/proxy/proxy.go
index ab33dcc53a..0694f66197 100644
--- a/services/proxy/pkg/proxy/proxy.go
+++ b/services/proxy/pkg/proxy/proxy.go
@@ -4,25 +4,16 @@ import (
"crypto/tls"
"crypto/x509"
"errors"
- "fmt"
"net"
"net/http"
"net/http/httputil"
"os"
"time"
- chimiddleware "github.com/go-chi/chi/v5/middleware"
-
- "go.opentelemetry.io/otel/attribute"
-
"github.com/owncloud/ocis/v2/ocis-pkg/log"
- pkgtrace "github.com/owncloud/ocis/v2/ocis-pkg/tracing"
"github.com/owncloud/ocis/v2/services/proxy/pkg/config"
"github.com/owncloud/ocis/v2/services/proxy/pkg/proxy/policy"
"github.com/owncloud/ocis/v2/services/proxy/pkg/router"
- proxytracing "github.com/owncloud/ocis/v2/services/proxy/pkg/tracing"
- "go.opentelemetry.io/otel/propagation"
- "go.opentelemetry.io/otel/trace"
)
// MultiHostReverseProxy extends "httputil" to support multiple hosts with different policies
@@ -84,25 +75,5 @@ func NewMultiHostReverseProxy(opts ...Option) (*MultiHostReverseProxy, error) {
}
func (p *MultiHostReverseProxy) ServeHTTP(w http.ResponseWriter, r *http.Request) {
- var (
- ctx = r.Context()
- span trace.Span
- )
-
- tracer := proxytracing.TraceProvider.Tracer("proxy")
- spanOpts := []trace.SpanStartOption{
- trace.WithSpanKind(trace.SpanKindServer),
- }
- ctx, span = tracer.Start(ctx, fmt.Sprintf("%s %v", r.Method, r.URL.Path), spanOpts...)
- defer span.End()
-
- span.SetAttributes(
- attribute.KeyValue{
- Key: "x-request-id",
- Value: attribute.StringValue(chimiddleware.GetReqID(r.Context())),
- })
-
- pkgtrace.Propagator.Inject(ctx, propagation.HeaderCarrier(r.Header))
-
- p.ReverseProxy.ServeHTTP(w, r.WithContext(ctx))
+ p.ReverseProxy.ServeHTTP(w, r)
}
diff --git a/vendor/github.com/go-micro/plugins/v4/wrapper/trace/opencensus/README.md b/vendor/github.com/go-micro/plugins/v4/wrapper/trace/opencensus/README.md
deleted file mode 100644
index d18ebcef08..0000000000
--- a/vendor/github.com/go-micro/plugins/v4/wrapper/trace/opencensus/README.md
+++ /dev/null
@@ -1,31 +0,0 @@
-# OpenCensus wrappers
-
-OpenCensus wrappers propagate traces (spans) accross services.
-
-## Usage
-
-```go
-service := micro.NewService(
- micro.Name("go.micro.srv.greeter"),
- micro.WrapClient(opencensus.NewClientWrapper()),
- micro.WrapHandler(opencensus.NewHandlerWrapper()),
- micro.WrapSubscriber(opencensus.NewSubscriberWrapper()),
-)
-```
-
-### Views
-
-The OpenCensus package exposes some convenience views.
-Don't forget to register these views:
-
-```go
-// Register to all RPC server views.
-if err := view.Register(opencensus.DefaultServerViews...); err != nil {
- log.Fatal(err)
-}
-
-// Register to all RPC client views.
-if err := view.Register(opencensus.DefaultClientViews...); err != nil {
- log.Fatal(err)
-}
-```
diff --git a/vendor/github.com/go-micro/plugins/v4/wrapper/trace/opencensus/opencensus.go b/vendor/github.com/go-micro/plugins/v4/wrapper/trace/opencensus/opencensus.go
deleted file mode 100644
index f427d030f3..0000000000
--- a/vendor/github.com/go-micro/plugins/v4/wrapper/trace/opencensus/opencensus.go
+++ /dev/null
@@ -1,150 +0,0 @@
-// Package opencensus provides wrappers for OpenCensus tracing.
-package opencensus
-
-import (
- "context"
- "encoding/base64"
- "fmt"
-
- "go-micro.dev/v4/client"
- log "go-micro.dev/v4/logger"
- "go-micro.dev/v4/metadata"
- "go-micro.dev/v4/server"
- "go.opencensus.io/trace"
- "go.opencensus.io/trace/propagation"
-)
-
-const (
- // TracePropagationField is the key for the tracing context
- // that will be injected in go-micro's metadata.
- TracePropagationField = "X-Trace-Context"
-)
-
-// clientWrapper wraps an RPC client and adds tracing.
-type clientWrapper struct {
- client.Client
-}
-
-func injectTraceIntoCtx(ctx context.Context, span *trace.Span) context.Context {
- spanCtx := propagation.Binary(span.SpanContext())
- return metadata.Set(ctx, TracePropagationField, base64.RawStdEncoding.EncodeToString(spanCtx))
-}
-
-// Call implements client.Client.Call.
-func (w *clientWrapper) Call(
- ctx context.Context,
- req client.Request,
- rsp interface{},
- opts ...client.CallOption) (err error) {
- t := newRequestTracker(req, ClientProfile)
- ctx = t.start(ctx, true)
-
- defer func() { t.end(ctx, err) }()
-
- ctx = injectTraceIntoCtx(ctx, t.span)
-
- err = w.Client.Call(ctx, req, rsp, opts...)
- return
-}
-
-// Publish implements client.Client.Publish.
-func (w *clientWrapper) Publish(ctx context.Context, p client.Message, opts ...client.PublishOption) (err error) {
- t := newEventTracker(p, ClientProfile)
- ctx = t.start(ctx, true)
-
- defer func() { t.end(ctx, err) }()
-
- ctx = injectTraceIntoCtx(ctx, t.span)
-
- err = w.Client.Publish(ctx, p, opts...)
- return
-}
-
-// NewClientWrapper returns a client.Wrapper
-// that adds monitoring to outgoing requests.
-func NewClientWrapper() client.Wrapper {
- return func(c client.Client) client.Client {
- return &clientWrapper{c}
- }
-}
-
-func getTraceFromCtx(ctx context.Context) *trace.SpanContext {
- encodedTraceCtx, ok := metadata.Get(ctx, TracePropagationField)
- if !ok {
- return nil
- }
-
- traceCtxBytes, err := base64.RawStdEncoding.DecodeString(encodedTraceCtx)
- if err != nil {
- log.Errorf("Could not decode trace context: %s", err.Error())
- return nil
- }
-
- spanCtx, ok := propagation.FromBinary(traceCtxBytes)
- if !ok {
- log.Errorf("Could not decode trace context from binary")
- return nil
- }
-
- return &spanCtx
-}
-
-// NewHandlerWrapper returns a server.HandlerWrapper
-// that adds tracing to incoming requests.
-func NewHandlerWrapper() server.HandlerWrapper {
- return func(fn server.HandlerFunc) server.HandlerFunc {
- return func(ctx context.Context, req server.Request, rsp interface{}) (err error) {
- t := newRequestTracker(req, ServerProfile)
- ctx = t.start(ctx, false)
-
- defer func() { t.end(ctx, err) }()
-
- spanCtx := getTraceFromCtx(ctx)
- if spanCtx != nil {
- ctx, t.span = trace.StartSpanWithRemoteParent(
- ctx,
- fmt.Sprintf("rpc/%s/%s/%s", ServerProfile.Role, req.Service(), req.Endpoint()),
- *spanCtx,
- )
- } else {
- ctx, t.span = trace.StartSpan(
- ctx,
- fmt.Sprintf("rpc/%s/%s/%s", ServerProfile.Role, req.Service(), req.Endpoint()),
- )
- }
-
- err = fn(ctx, req, rsp)
- return
- }
- }
-}
-
-// NewSubscriberWrapper returns a server.SubscriberWrapper
-// that adds tracing to subscription requests.
-func NewSubscriberWrapper() server.SubscriberWrapper {
- return func(fn server.SubscriberFunc) server.SubscriberFunc {
- return func(ctx context.Context, p server.Message) (err error) {
- t := newEventTracker(p, ServerProfile)
- ctx = t.start(ctx, false)
-
- defer func() { t.end(ctx, err) }()
-
- spanCtx := getTraceFromCtx(ctx)
- if spanCtx != nil {
- ctx, t.span = trace.StartSpanWithRemoteParent(
- ctx,
- fmt.Sprintf("rpc/%s/pubsub/%s", ServerProfile.Role, p.Topic()),
- *spanCtx,
- )
- } else {
- ctx, t.span = trace.StartSpan(
- ctx,
- fmt.Sprintf("rpc/%s/pubsub/%s", ServerProfile.Role, p.Topic()),
- )
- }
-
- err = fn(ctx, p)
- return
- }
- }
-}
diff --git a/vendor/github.com/go-micro/plugins/v4/wrapper/trace/opencensus/stats.go b/vendor/github.com/go-micro/plugins/v4/wrapper/trace/opencensus/stats.go
deleted file mode 100644
index 2fd7865f7d..0000000000
--- a/vendor/github.com/go-micro/plugins/v4/wrapper/trace/opencensus/stats.go
+++ /dev/null
@@ -1,142 +0,0 @@
-package opencensus
-
-import (
- "go.opencensus.io/stats"
- "go.opencensus.io/stats/view"
- "go.opencensus.io/tag"
-)
-
-// The following client RPC measures are supported for use in custom views.
-var (
- ClientRequestCount = stats.Int64("opencensus.io/rpc/client/request_count", "Number of RPC requests started", stats.UnitNone)
- ClientLatency = stats.Float64("opencensus.io/rpc/client/latency", "End-to-end latency", stats.UnitMilliseconds)
-)
-
-// The following server RPC measures are supported for use in custom views.
-var (
- ServerRequestCount = stats.Int64("opencensus.io/rpc/server/request_count", "Number of RPC requests received", stats.UnitNone)
- ServerLatency = stats.Float64("opencensus.io/rpc/server/latency", "End-to-end latency", stats.UnitMilliseconds)
-)
-
-// The following tags are applied to stats recorded by this package.
-// Service and Method are applied to all measures.
-// StatusCode is not applied to ClientRequestCount or ServerRequestCount,
-// since it is recorded before the status is known.
-var (
- // StatusCode is the RPC status code.
- StatusCode, _ = tag.NewKey("rpc.status")
-
- // Service is the name of the micro-service.
- Service, _ = tag.NewKey("rpc.service")
-
- // Method is the service method called.
- Endpoint, _ = tag.NewKey("rpc.endpoint")
-)
-
-// Default distributions used by views in this package.
-var (
- DefaultLatencyDistribution = view.Distribution(0, 1, 2, 3, 4, 5, 6, 8, 10, 13, 16, 20, 25, 30, 40, 50, 65, 80, 100, 130, 160, 200, 250, 300, 400, 500, 650, 800, 1000, 2000, 5000, 10000, 20000, 50000, 100000)
-)
-
-// This package provides some convenience views.
-// You need to subscribe to the views for data to actually be collected.
-var (
- ClientRequestCountView = &view.View{
- Name: "opencensus.io/rpc/client/request_count",
- Description: "Count of RPC requests started",
- Measure: ClientRequestCount,
- Aggregation: view.Count(),
- }
-
- ClientLatencyView = &view.View{
- Name: "opencensus.io/rpc/client/latency",
- Description: "Latency distribution of RPC requests",
- Measure: ClientLatency,
- Aggregation: DefaultLatencyDistribution,
- }
-
- ClientRequestCountByMethod = &view.View{
- Name: "opencensus.io/rpc/client/request_count_by_method",
- Description: "Client request count by RPC method",
- TagKeys: []tag.Key{Endpoint},
- Measure: ClientRequestCount,
- Aggregation: view.Count(),
- }
-
- ClientResponseCountByStatusCode = &view.View{
- Name: "opencensus.io/rpc/client/response_count_by_status_code",
- Description: "Client response count by RPC status code",
- TagKeys: []tag.Key{StatusCode},
- Measure: ClientLatency,
- Aggregation: view.Count(),
- }
-
- ServerRequestCountView = &view.View{
- Name: "opencensus.io/rpc/server/request_count",
- Description: "Count of RPC requests received",
- Measure: ServerRequestCount,
- Aggregation: view.Count(),
- }
-
- ServerLatencyView = &view.View{
- Name: "opencensus.io/rpc/server/latency",
- Description: "Latency distribution of RPC requests",
- Measure: ServerLatency,
- Aggregation: DefaultLatencyDistribution,
- }
-
- ServerRequestCountByMethod = &view.View{
- Name: "opencensus.io/rpc/server/request_count_by_method",
- Description: "Server request count by RPC method",
- TagKeys: []tag.Key{Endpoint},
- Measure: ServerRequestCount,
- Aggregation: view.Count(),
- }
-
- ServerResponseCountByStatusCode = &view.View{
- Name: "opencensus.io/rpc/server/response_count_by_status_code",
- Description: "Server response count by RPC status code",
- TagKeys: []tag.Key{StatusCode},
- Measure: ServerLatency,
- Aggregation: view.Count(),
- }
-)
-
-// DefaultClientViews are the default client views provided by this package.
-var DefaultClientViews = []*view.View{
- ClientRequestCountView,
- ClientLatencyView,
- ClientRequestCountByMethod,
- ClientResponseCountByStatusCode,
-}
-
-// DefaultServerViews are the default server views provided by this package.
-var DefaultServerViews = []*view.View{
- ServerRequestCountView,
- ServerLatencyView,
- ServerRequestCountByMethod,
- ServerResponseCountByStatusCode,
-}
-
-// StatsProfile groups metrics-related data.
-type StatsProfile struct {
- Role string
- CountMeasure *stats.Int64Measure
- LatencyMeasure *stats.Float64Measure
-}
-
-var (
- // ClientProfile is used for RPC clients.
- ClientProfile = &StatsProfile{
- Role: "client",
- CountMeasure: ClientRequestCount,
- LatencyMeasure: ClientLatency,
- }
-
- // ServerProfile is used for RPC servers.
- ServerProfile = &StatsProfile{
- Role: "server",
- CountMeasure: ServerRequestCount,
- LatencyMeasure: ServerLatency,
- }
-)
diff --git a/vendor/github.com/go-micro/plugins/v4/wrapper/trace/opencensus/status.go b/vendor/github.com/go-micro/plugins/v4/wrapper/trace/opencensus/status.go
deleted file mode 100644
index bb7bdceb4d..0000000000
--- a/vendor/github.com/go-micro/plugins/v4/wrapper/trace/opencensus/status.go
+++ /dev/null
@@ -1,45 +0,0 @@
-package opencensus
-
-import (
- "fmt"
-
- microerr "go-micro.dev/v4/errors"
-
- "go.opencensus.io/trace"
-
- "google.golang.org/genproto/googleapis/rpc/code"
-)
-
-var microCodeToStatusCode = map[int32]code.Code{
- 400: code.Code_INVALID_ARGUMENT,
- 401: code.Code_UNAUTHENTICATED,
- 403: code.Code_PERMISSION_DENIED,
- 404: code.Code_NOT_FOUND,
- 409: code.Code_ABORTED,
- 500: code.Code_INTERNAL,
-}
-
-func getResponseStatus(err error) trace.Status {
- if err != nil {
- microErr, ok := err.(*microerr.Error)
- if ok {
- statusCode := microErr.Code
- code, ok := microCodeToStatusCode[microErr.Code]
- if ok {
- statusCode = int32(code)
- }
-
- return trace.Status{
- Code: statusCode,
- Message: fmt.Sprintf("%s: %s", microErr.Id, microErr.Detail),
- }
- }
-
- return trace.Status{
- Code: int32(code.Code_UNKNOWN),
- Message: err.Error(),
- }
- }
-
- return trace.Status{}
-}
diff --git a/vendor/github.com/go-micro/plugins/v4/wrapper/trace/opencensus/tracker.go b/vendor/github.com/go-micro/plugins/v4/wrapper/trace/opencensus/tracker.go
deleted file mode 100644
index 9b1d4ee4db..0000000000
--- a/vendor/github.com/go-micro/plugins/v4/wrapper/trace/opencensus/tracker.go
+++ /dev/null
@@ -1,81 +0,0 @@
-package opencensus
-
-import (
- "context"
- "fmt"
- "strconv"
- "time"
-
- "go.opencensus.io/stats"
- "go.opencensus.io/tag"
- "go.opencensus.io/trace"
-)
-
-type tracker struct {
- startedAt time.Time
-
- profile *StatsProfile
- span *trace.Span
-
- method string
- service string
-}
-
-type requestDescriptor interface {
- Service() string
- Endpoint() string
-}
-
-type publicationDescriptor interface {
- Topic() string
-}
-
-// newRequestTracker creates a new tracker for an RPC request (client or server).
-func newRequestTracker(req requestDescriptor, profile *StatsProfile) *tracker {
- return &tracker{
- profile: profile,
- method: req.Endpoint(),
- service: req.Service(),
- }
-}
-
-// newEventTracker creates a new tracker for a publication (client or server).
-func newEventTracker(pub publicationDescriptor, profile *StatsProfile) *tracker {
- return &tracker{
- profile: profile,
- method: pub.Topic(),
- service: "pubsub",
- }
-}
-
-// start monitoring a request. You can choose to let this method
-// start a span for the request or attach one later.
-func (t *tracker) start(ctx context.Context, startSpan bool) context.Context {
- t.startedAt = time.Now()
-
- ctx, _ = tag.New(ctx, tag.Upsert(Service, t.service), tag.Upsert(Endpoint, t.method))
- stats.Record(ctx, t.profile.CountMeasure.M(1))
-
- if startSpan {
- ctx, t.span = trace.StartSpan(
- ctx,
- fmt.Sprintf("rpc/%s/%s/%s", t.profile.Role, t.service, t.method),
- )
- }
-
- return ctx
-}
-
-// end a request's monitoring session. If there is a span ongoing, it will
-// be ended and metrics will be recorded.
-func (t *tracker) end(ctx context.Context, err error) {
- status := getResponseStatus(err)
-
- ctx, _ = tag.New(ctx, tag.Upsert(StatusCode, strconv.Itoa(int(status.Code))))
- stats.Record(ctx, t.profile.LatencyMeasure.M(float64(time.Since(t.startedAt))/float64(time.Millisecond)))
-
- if t.span != nil {
- t.span.SetStatus(status)
- t.span.End()
- }
-}
diff --git a/vendor/github.com/go-micro/plugins/v4/wrapper/trace/opencensus/LICENSE b/vendor/github.com/go-micro/plugins/v4/wrapper/trace/opentelemetry/LICENSE
similarity index 100%
rename from vendor/github.com/go-micro/plugins/v4/wrapper/trace/opencensus/LICENSE
rename to vendor/github.com/go-micro/plugins/v4/wrapper/trace/opentelemetry/LICENSE
diff --git a/vendor/github.com/go-micro/plugins/v4/wrapper/trace/opentelemetry/README.md b/vendor/github.com/go-micro/plugins/v4/wrapper/trace/opentelemetry/README.md
new file mode 100644
index 0000000000..d1944d5bbb
--- /dev/null
+++ b/vendor/github.com/go-micro/plugins/v4/wrapper/trace/opentelemetry/README.md
@@ -0,0 +1,14 @@
+# OpenTelemetry wrappers
+
+OpenTelemetry wrappers propagate traces (spans) accross services.
+
+## Usage
+
+```go
+service := micro.NewService(
+ micro.Name("go.micro.srv.greeter"),
+ micro.WrapClient(opentelemetry.NewClientWrapper()),
+ micro.WrapHandler(open.NewHandlerWrapper()),
+ micro.WrapSubscriber(opentelemetry.NewSubscriberWrapper()),
+)
+```
\ No newline at end of file
diff --git a/vendor/github.com/go-micro/plugins/v4/wrapper/trace/opentelemetry/opentelemetry.go b/vendor/github.com/go-micro/plugins/v4/wrapper/trace/opentelemetry/opentelemetry.go
new file mode 100644
index 0000000000..8f9453921f
--- /dev/null
+++ b/vendor/github.com/go-micro/plugins/v4/wrapper/trace/opentelemetry/opentelemetry.go
@@ -0,0 +1,55 @@
+package opentelemetry
+
+import (
+ "context"
+ "strings"
+
+ "go-micro.dev/v4/metadata"
+ "go.opentelemetry.io/otel"
+ "go.opentelemetry.io/otel/baggage"
+ "go.opentelemetry.io/otel/propagation"
+ "go.opentelemetry.io/otel/trace"
+)
+
+const (
+ instrumentationName = "github.com/go-micro/plugins/v4/wrapper/trace/opentelemetry"
+)
+
+// StartSpanFromContext returns a new span with the given operation name and options. If a span
+// is found in the context, it will be used as the parent of the resulting span.
+func StartSpanFromContext(ctx context.Context, tp trace.TracerProvider, name string, opts ...trace.SpanStartOption) (context.Context, trace.Span) {
+ md, ok := metadata.FromContext(ctx)
+ if !ok {
+ md = make(metadata.Metadata)
+ }
+ propagator, carrier := otel.GetTextMapPropagator(), make(propagation.MapCarrier)
+ for k, v := range md {
+ for _, f := range propagator.Fields() {
+ if strings.EqualFold(k, f) {
+ carrier[f] = v
+ }
+ }
+ }
+ ctx = propagator.Extract(ctx, carrier)
+ spanCtx := trace.SpanContextFromContext(ctx)
+ ctx = baggage.ContextWithBaggage(ctx, baggage.FromContext(ctx))
+
+ var tracer trace.Tracer
+ var span trace.Span
+ if tp != nil {
+ tracer = tp.Tracer(instrumentationName)
+ } else {
+ tracer = otel.Tracer(instrumentationName)
+ }
+ ctx, span = tracer.Start(trace.ContextWithRemoteSpanContext(ctx, spanCtx), name, opts...)
+
+ carrier = make(propagation.MapCarrier)
+ propagator.Inject(ctx, carrier)
+ for k, v := range carrier {
+ //lint:ignore SA1019 no unicode punctution handle needed
+ md.Set(strings.Title(k), v)
+ }
+ ctx = metadata.NewContext(ctx, md)
+
+ return ctx, span
+}
diff --git a/vendor/github.com/go-micro/plugins/v4/wrapper/trace/opentelemetry/options.go b/vendor/github.com/go-micro/plugins/v4/wrapper/trace/opentelemetry/options.go
new file mode 100644
index 0000000000..fc36c7e208
--- /dev/null
+++ b/vendor/github.com/go-micro/plugins/v4/wrapper/trace/opentelemetry/options.go
@@ -0,0 +1,72 @@
+package opentelemetry
+
+import (
+ "context"
+
+ "go-micro.dev/v4/client"
+ "go-micro.dev/v4/server"
+ "go.opentelemetry.io/otel/trace"
+)
+
+type Options struct {
+ TraceProvider trace.TracerProvider
+
+ CallFilter CallFilter
+ StreamFilter StreamFilter
+ PublishFilter PublishFilter
+ SubscriberFilter SubscriberFilter
+ HandlerFilter HandlerFilter
+}
+
+// CallFilter used to filter client.Call, return true to skip call trace.
+type CallFilter func(context.Context, client.Request) bool
+
+// StreamFilter used to filter client.Stream, return true to skip stream trace.
+type StreamFilter func(context.Context, client.Request) bool
+
+// PublishFilter used to filter client.Publish, return true to skip publish trace.
+type PublishFilter func(context.Context, client.Message) bool
+
+// SubscriberFilter used to filter server.Subscribe, return true to skip subcribe trace.
+type SubscriberFilter func(context.Context, server.Message) bool
+
+// HandlerFilter used to filter server.Handle, return true to skip handle trace.
+type HandlerFilter func(context.Context, server.Request) bool
+
+type Option func(*Options)
+
+func WithTraceProvider(tp trace.TracerProvider) Option {
+ return func(o *Options) {
+ o.TraceProvider = tp
+ }
+}
+
+func WithCallFilter(filter CallFilter) Option {
+ return func(o *Options) {
+ o.CallFilter = filter
+ }
+}
+
+func WithStreamFilter(filter StreamFilter) Option {
+ return func(o *Options) {
+ o.StreamFilter = filter
+ }
+}
+
+func WithPublishFilter(filter PublishFilter) Option {
+ return func(o *Options) {
+ o.PublishFilter = filter
+ }
+}
+
+func WithSubscribeFilter(filter SubscriberFilter) Option {
+ return func(o *Options) {
+ o.SubscriberFilter = filter
+ }
+}
+
+func WithHandleFilter(filter HandlerFilter) Option {
+ return func(o *Options) {
+ o.HandlerFilter = filter
+ }
+}
diff --git a/vendor/github.com/go-micro/plugins/v4/wrapper/trace/opentelemetry/wrapper.go b/vendor/github.com/go-micro/plugins/v4/wrapper/trace/opentelemetry/wrapper.go
new file mode 100644
index 0000000000..da2649405a
--- /dev/null
+++ b/vendor/github.com/go-micro/plugins/v4/wrapper/trace/opentelemetry/wrapper.go
@@ -0,0 +1,175 @@
+package opentelemetry
+
+import (
+ "context"
+ "fmt"
+
+ "go-micro.dev/v4/client"
+ "go-micro.dev/v4/registry"
+ "go-micro.dev/v4/server"
+ "go.opentelemetry.io/otel/codes"
+ "go.opentelemetry.io/otel/trace"
+)
+
+// NewCallWrapper accepts an opentracing Tracer and returns a Call Wrapper.
+func NewCallWrapper(opts ...Option) client.CallWrapper {
+ options := Options{}
+ for _, o := range opts {
+ o(&options)
+ }
+ return func(cf client.CallFunc) client.CallFunc {
+ return func(ctx context.Context, node *registry.Node, req client.Request, rsp interface{}, opts client.CallOptions) error {
+ if options.CallFilter != nil && options.CallFilter(ctx, req) {
+ return cf(ctx, node, req, rsp, opts)
+ }
+ name := fmt.Sprintf("%s.%s", req.Service(), req.Endpoint())
+ spanOpts := []trace.SpanStartOption{
+ trace.WithSpanKind(trace.SpanKindClient),
+ }
+ ctx, span := StartSpanFromContext(ctx, options.TraceProvider, name, spanOpts...)
+ defer span.End()
+ if err := cf(ctx, node, req, rsp, opts); err != nil {
+ span.SetStatus(codes.Error, err.Error())
+ span.RecordError(err)
+ return err
+ }
+ return nil
+ }
+ }
+}
+
+// NewHandlerWrapper accepts an opentracing Tracer and returns a Handler Wrapper.
+func NewHandlerWrapper(opts ...Option) server.HandlerWrapper {
+ options := Options{}
+ for _, o := range opts {
+ o(&options)
+ }
+ return func(h server.HandlerFunc) server.HandlerFunc {
+ return func(ctx context.Context, req server.Request, rsp interface{}) error {
+ if options.HandlerFilter != nil && options.HandlerFilter(ctx, req) {
+ return h(ctx, req, rsp)
+ }
+ name := fmt.Sprintf("%s.%s", req.Service(), req.Endpoint())
+ spanOpts := []trace.SpanStartOption{
+ trace.WithSpanKind(trace.SpanKindServer),
+ }
+ ctx, span := StartSpanFromContext(ctx, options.TraceProvider, name, spanOpts...)
+ defer span.End()
+ if err := h(ctx, req, rsp); err != nil {
+ span.SetStatus(codes.Error, err.Error())
+ span.RecordError(err)
+ return err
+ }
+ return nil
+ }
+ }
+}
+
+// NewSubscriberWrapper accepts an opentracing Tracer and returns a Subscriber Wrapper.
+func NewSubscriberWrapper(opts ...Option) server.SubscriberWrapper {
+ options := Options{}
+ for _, o := range opts {
+ o(&options)
+ }
+ return func(next server.SubscriberFunc) server.SubscriberFunc {
+ return func(ctx context.Context, msg server.Message) error {
+ if options.SubscriberFilter != nil && options.SubscriberFilter(ctx, msg) {
+ return next(ctx, msg)
+ }
+ name := "Sub from " + msg.Topic()
+ spanOpts := []trace.SpanStartOption{
+ trace.WithSpanKind(trace.SpanKindServer),
+ }
+ ctx, span := StartSpanFromContext(ctx, options.TraceProvider, name, spanOpts...)
+ defer span.End()
+ if err := next(ctx, msg); err != nil {
+ span.SetStatus(codes.Error, err.Error())
+ span.RecordError(err)
+ return err
+ }
+ return nil
+ }
+ }
+}
+
+// NewClientWrapper returns a client.Wrapper
+// that adds monitoring to outgoing requests.
+func NewClientWrapper(opts ...Option) client.Wrapper {
+ options := Options{}
+ for _, o := range opts {
+ o(&options)
+ }
+ return func(c client.Client) client.Client {
+ w := &clientWrapper{
+ Client: c,
+ tp: options.TraceProvider,
+ callFilter: options.CallFilter,
+ streamFilter: options.StreamFilter,
+ publishFilter: options.PublishFilter,
+ }
+ return w
+ }
+}
+
+type clientWrapper struct {
+ client.Client
+
+ tp trace.TracerProvider
+ callFilter CallFilter
+ streamFilter StreamFilter
+ publishFilter PublishFilter
+}
+
+func (w *clientWrapper) Call(ctx context.Context, req client.Request, rsp interface{}, opts ...client.CallOption) error {
+ if w.callFilter != nil && w.callFilter(ctx, req) {
+ return w.Client.Call(ctx, req, rsp, opts...)
+ }
+ name := fmt.Sprintf("%s.%s", req.Service(), req.Endpoint())
+ spanOpts := []trace.SpanStartOption{
+ trace.WithSpanKind(trace.SpanKindClient),
+ }
+ ctx, span := StartSpanFromContext(ctx, w.tp, name, spanOpts...)
+ defer span.End()
+ if err := w.Client.Call(ctx, req, rsp, opts...); err != nil {
+ span.SetStatus(codes.Error, err.Error())
+ span.RecordError(err)
+ return err
+ }
+ return nil
+}
+
+func (w *clientWrapper) Stream(ctx context.Context, req client.Request, opts ...client.CallOption) (client.Stream, error) {
+ if w.streamFilter != nil && w.streamFilter(ctx, req) {
+ return w.Client.Stream(ctx, req, opts...)
+ }
+ name := fmt.Sprintf("%s.%s", req.Service(), req.Endpoint())
+ spanOpts := []trace.SpanStartOption{
+ trace.WithSpanKind(trace.SpanKindClient),
+ }
+ ctx, span := StartSpanFromContext(ctx, w.tp, name, spanOpts...)
+ defer span.End()
+ stream, err := w.Client.Stream(ctx, req, opts...)
+ if err != nil {
+ span.SetStatus(codes.Error, err.Error())
+ span.RecordError(err)
+ }
+ return stream, err
+}
+
+func (w *clientWrapper) Publish(ctx context.Context, p client.Message, opts ...client.PublishOption) error {
+ if w.publishFilter != nil && w.publishFilter(ctx, p) {
+ return w.Client.Publish(ctx, p, opts...)
+ }
+ name := fmt.Sprintf("Pub to %s", p.Topic())
+ spanOpts := []trace.SpanStartOption{
+ trace.WithSpanKind(trace.SpanKindClient),
+ }
+ ctx, span := StartSpanFromContext(ctx, w.tp, name, spanOpts...)
+ defer span.End()
+ if err := w.Client.Publish(ctx, p, opts...); err != nil {
+ span.SetStatus(codes.Error, err.Error())
+ span.RecordError(err)
+ return err
+ }
+ return nil
+}
diff --git a/vendor/go.opencensus.io/plugin/ocgrpc/client.go b/vendor/go.opencensus.io/plugin/ocgrpc/client.go
deleted file mode 100644
index 2063b6f76a..0000000000
--- a/vendor/go.opencensus.io/plugin/ocgrpc/client.go
+++ /dev/null
@@ -1,56 +0,0 @@
-// Copyright 2018, OpenCensus 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 ocgrpc
-
-import (
- "context"
-
- "go.opencensus.io/trace"
- "google.golang.org/grpc/stats"
-)
-
-// ClientHandler implements a gRPC stats.Handler for recording OpenCensus stats and
-// traces. Use with gRPC clients only.
-type ClientHandler struct {
- // StartOptions allows configuring the StartOptions used to create new spans.
- //
- // StartOptions.SpanKind will always be set to trace.SpanKindClient
- // for spans started by this handler.
- StartOptions trace.StartOptions
-}
-
-// HandleConn exists to satisfy gRPC stats.Handler.
-func (c *ClientHandler) HandleConn(ctx context.Context, cs stats.ConnStats) {
- // no-op
-}
-
-// TagConn exists to satisfy gRPC stats.Handler.
-func (c *ClientHandler) TagConn(ctx context.Context, cti *stats.ConnTagInfo) context.Context {
- // no-op
- return ctx
-}
-
-// HandleRPC implements per-RPC tracing and stats instrumentation.
-func (c *ClientHandler) HandleRPC(ctx context.Context, rs stats.RPCStats) {
- traceHandleRPC(ctx, rs)
- statsHandleRPC(ctx, rs)
-}
-
-// TagRPC implements per-RPC context management.
-func (c *ClientHandler) TagRPC(ctx context.Context, rti *stats.RPCTagInfo) context.Context {
- ctx = c.traceTagRPC(ctx, rti)
- ctx = c.statsTagRPC(ctx, rti)
- return ctx
-}
diff --git a/vendor/go.opencensus.io/plugin/ocgrpc/client_metrics.go b/vendor/go.opencensus.io/plugin/ocgrpc/client_metrics.go
deleted file mode 100644
index fb3c19d6b6..0000000000
--- a/vendor/go.opencensus.io/plugin/ocgrpc/client_metrics.go
+++ /dev/null
@@ -1,118 +0,0 @@
-// Copyright 2017, OpenCensus 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 ocgrpc
-
-import (
- "go.opencensus.io/stats"
- "go.opencensus.io/stats/view"
- "go.opencensus.io/tag"
-)
-
-// The following variables are measures are recorded by ClientHandler:
-var (
- ClientSentMessagesPerRPC = stats.Int64("grpc.io/client/sent_messages_per_rpc", "Number of messages sent in the RPC (always 1 for non-streaming RPCs).", stats.UnitDimensionless)
- ClientSentBytesPerRPC = stats.Int64("grpc.io/client/sent_bytes_per_rpc", "Total bytes sent across all request messages per RPC.", stats.UnitBytes)
- ClientReceivedMessagesPerRPC = stats.Int64("grpc.io/client/received_messages_per_rpc", "Number of response messages received per RPC (always 1 for non-streaming RPCs).", stats.UnitDimensionless)
- ClientReceivedBytesPerRPC = stats.Int64("grpc.io/client/received_bytes_per_rpc", "Total bytes received across all response messages per RPC.", stats.UnitBytes)
- ClientRoundtripLatency = stats.Float64("grpc.io/client/roundtrip_latency", "Time between first byte of request sent to last byte of response received, or terminal error.", stats.UnitMilliseconds)
- ClientStartedRPCs = stats.Int64("grpc.io/client/started_rpcs", "Number of started client RPCs.", stats.UnitDimensionless)
- ClientServerLatency = stats.Float64("grpc.io/client/server_latency", `Propagated from the server and should have the same value as "grpc.io/server/latency".`, stats.UnitMilliseconds)
-)
-
-// Predefined views may be registered to collect data for the above measures.
-// As always, you may also define your own custom views over measures collected by this
-// package. These are declared as a convenience only; none are registered by
-// default.
-var (
- ClientSentBytesPerRPCView = &view.View{
- Measure: ClientSentBytesPerRPC,
- Name: "grpc.io/client/sent_bytes_per_rpc",
- Description: "Distribution of bytes sent per RPC, by method.",
- TagKeys: []tag.Key{KeyClientMethod},
- Aggregation: DefaultBytesDistribution,
- }
-
- ClientReceivedBytesPerRPCView = &view.View{
- Measure: ClientReceivedBytesPerRPC,
- Name: "grpc.io/client/received_bytes_per_rpc",
- Description: "Distribution of bytes received per RPC, by method.",
- TagKeys: []tag.Key{KeyClientMethod},
- Aggregation: DefaultBytesDistribution,
- }
-
- ClientRoundtripLatencyView = &view.View{
- Measure: ClientRoundtripLatency,
- Name: "grpc.io/client/roundtrip_latency",
- Description: "Distribution of round-trip latency, by method.",
- TagKeys: []tag.Key{KeyClientMethod},
- Aggregation: DefaultMillisecondsDistribution,
- }
-
- // Purposely reuses the count from `ClientRoundtripLatency`, tagging
- // with method and status to result in ClientCompletedRpcs.
- ClientCompletedRPCsView = &view.View{
- Measure: ClientRoundtripLatency,
- Name: "grpc.io/client/completed_rpcs",
- Description: "Count of RPCs by method and status.",
- TagKeys: []tag.Key{KeyClientMethod, KeyClientStatus},
- Aggregation: view.Count(),
- }
-
- ClientStartedRPCsView = &view.View{
- Measure: ClientStartedRPCs,
- Name: "grpc.io/client/started_rpcs",
- Description: "Number of started client RPCs.",
- TagKeys: []tag.Key{KeyClientMethod},
- Aggregation: view.Count(),
- }
-
- ClientSentMessagesPerRPCView = &view.View{
- Measure: ClientSentMessagesPerRPC,
- Name: "grpc.io/client/sent_messages_per_rpc",
- Description: "Distribution of sent messages count per RPC, by method.",
- TagKeys: []tag.Key{KeyClientMethod},
- Aggregation: DefaultMessageCountDistribution,
- }
-
- ClientReceivedMessagesPerRPCView = &view.View{
- Measure: ClientReceivedMessagesPerRPC,
- Name: "grpc.io/client/received_messages_per_rpc",
- Description: "Distribution of received messages count per RPC, by method.",
- TagKeys: []tag.Key{KeyClientMethod},
- Aggregation: DefaultMessageCountDistribution,
- }
-
- ClientServerLatencyView = &view.View{
- Measure: ClientServerLatency,
- Name: "grpc.io/client/server_latency",
- Description: "Distribution of server latency as viewed by client, by method.",
- TagKeys: []tag.Key{KeyClientMethod},
- Aggregation: DefaultMillisecondsDistribution,
- }
-)
-
-// DefaultClientViews are the default client views provided by this package.
-var DefaultClientViews = []*view.View{
- ClientSentBytesPerRPCView,
- ClientReceivedBytesPerRPCView,
- ClientRoundtripLatencyView,
- ClientCompletedRPCsView,
-}
-
-// TODO(jbd): Add roundtrip_latency, uncompressed_request_bytes, uncompressed_response_bytes, request_count, response_count.
-// TODO(acetechnologist): This is temporary and will need to be replaced by a
-// mechanism to load these defaults from a common repository/config shared by
-// all supported languages. Likely a serialized protobuf of these defaults.
diff --git a/vendor/go.opencensus.io/plugin/ocgrpc/client_stats_handler.go b/vendor/go.opencensus.io/plugin/ocgrpc/client_stats_handler.go
deleted file mode 100644
index b36349820d..0000000000
--- a/vendor/go.opencensus.io/plugin/ocgrpc/client_stats_handler.go
+++ /dev/null
@@ -1,49 +0,0 @@
-// Copyright 2017, OpenCensus 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 ocgrpc
-
-import (
- "context"
- "time"
-
- "go.opencensus.io/tag"
- "google.golang.org/grpc/grpclog"
- "google.golang.org/grpc/stats"
-)
-
-// statsTagRPC gets the tag.Map populated by the application code, serializes
-// its tags into the GRPC metadata in order to be sent to the server.
-func (h *ClientHandler) statsTagRPC(ctx context.Context, info *stats.RPCTagInfo) context.Context {
- startTime := time.Now()
- if info == nil {
- if grpclog.V(2) {
- grpclog.Info("clientHandler.TagRPC called with nil info.")
- }
- return ctx
- }
-
- d := &rpcData{
- startTime: startTime,
- method: info.FullMethodName,
- }
- ts := tag.FromContext(ctx)
- if ts != nil {
- encoded := tag.Encode(ts)
- ctx = stats.SetTags(ctx, encoded)
- }
-
- return context.WithValue(ctx, rpcDataKey, d)
-}
diff --git a/vendor/go.opencensus.io/plugin/ocgrpc/server.go b/vendor/go.opencensus.io/plugin/ocgrpc/server.go
deleted file mode 100644
index 8a53e09727..0000000000
--- a/vendor/go.opencensus.io/plugin/ocgrpc/server.go
+++ /dev/null
@@ -1,81 +0,0 @@
-// Copyright 2018, OpenCensus 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 ocgrpc
-
-import (
- "context"
-
- "google.golang.org/grpc/stats"
-
- "go.opencensus.io/trace"
-)
-
-// ServerHandler implements gRPC stats.Handler recording OpenCensus stats and
-// traces. Use with gRPC servers.
-//
-// When installed (see Example), tracing metadata is read from inbound RPCs
-// by default. If no tracing metadata is present, or if the tracing metadata is
-// present but the SpanContext isn't sampled, then a new trace may be started
-// (as determined by Sampler).
-type ServerHandler struct {
- // IsPublicEndpoint may be set to true to always start a new trace around
- // each RPC. Any SpanContext in the RPC metadata will be added as a linked
- // span instead of making it the parent of the span created around the
- // server RPC.
- //
- // Be aware that if you leave this false (the default) on a public-facing
- // server, callers will be able to send tracing metadata in gRPC headers
- // and trigger traces in your backend.
- IsPublicEndpoint bool
-
- // StartOptions to use for to spans started around RPCs handled by this server.
- //
- // These will apply even if there is tracing metadata already
- // present on the inbound RPC but the SpanContext is not sampled. This
- // ensures that each service has some opportunity to be traced. If you would
- // like to not add any additional traces for this gRPC service, set:
- //
- // StartOptions.Sampler = trace.ProbabilitySampler(0.0)
- //
- // StartOptions.SpanKind will always be set to trace.SpanKindServer
- // for spans started by this handler.
- StartOptions trace.StartOptions
-}
-
-var _ stats.Handler = (*ServerHandler)(nil)
-
-// HandleConn exists to satisfy gRPC stats.Handler.
-func (s *ServerHandler) HandleConn(ctx context.Context, cs stats.ConnStats) {
- // no-op
-}
-
-// TagConn exists to satisfy gRPC stats.Handler.
-func (s *ServerHandler) TagConn(ctx context.Context, cti *stats.ConnTagInfo) context.Context {
- // no-op
- return ctx
-}
-
-// HandleRPC implements per-RPC tracing and stats instrumentation.
-func (s *ServerHandler) HandleRPC(ctx context.Context, rs stats.RPCStats) {
- traceHandleRPC(ctx, rs)
- statsHandleRPC(ctx, rs)
-}
-
-// TagRPC implements per-RPC context management.
-func (s *ServerHandler) TagRPC(ctx context.Context, rti *stats.RPCTagInfo) context.Context {
- ctx = s.traceTagRPC(ctx, rti)
- ctx = s.statsTagRPC(ctx, rti)
- return ctx
-}
diff --git a/vendor/go.opencensus.io/plugin/ocgrpc/server_metrics.go b/vendor/go.opencensus.io/plugin/ocgrpc/server_metrics.go
deleted file mode 100644
index fe0e971086..0000000000
--- a/vendor/go.opencensus.io/plugin/ocgrpc/server_metrics.go
+++ /dev/null
@@ -1,108 +0,0 @@
-// Copyright 2017, OpenCensus 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 ocgrpc
-
-import (
- "go.opencensus.io/stats"
- "go.opencensus.io/stats/view"
- "go.opencensus.io/tag"
-)
-
-// The following variables are measures are recorded by ServerHandler:
-var (
- ServerReceivedMessagesPerRPC = stats.Int64("grpc.io/server/received_messages_per_rpc", "Number of messages received in each RPC. Has value 1 for non-streaming RPCs.", stats.UnitDimensionless)
- ServerReceivedBytesPerRPC = stats.Int64("grpc.io/server/received_bytes_per_rpc", "Total bytes received across all messages per RPC.", stats.UnitBytes)
- ServerSentMessagesPerRPC = stats.Int64("grpc.io/server/sent_messages_per_rpc", "Number of messages sent in each RPC. Has value 1 for non-streaming RPCs.", stats.UnitDimensionless)
- ServerSentBytesPerRPC = stats.Int64("grpc.io/server/sent_bytes_per_rpc", "Total bytes sent in across all response messages per RPC.", stats.UnitBytes)
- ServerStartedRPCs = stats.Int64("grpc.io/server/started_rpcs", "Number of started server RPCs.", stats.UnitDimensionless)
- ServerLatency = stats.Float64("grpc.io/server/server_latency", "Time between first byte of request received to last byte of response sent, or terminal error.", stats.UnitMilliseconds)
-)
-
-// TODO(acetechnologist): This is temporary and will need to be replaced by a
-// mechanism to load these defaults from a common repository/config shared by
-// all supported languages. Likely a serialized protobuf of these defaults.
-
-// Predefined views may be registered to collect data for the above measures.
-// As always, you may also define your own custom views over measures collected by this
-// package. These are declared as a convenience only; none are registered by
-// default.
-var (
- ServerReceivedBytesPerRPCView = &view.View{
- Name: "grpc.io/server/received_bytes_per_rpc",
- Description: "Distribution of received bytes per RPC, by method.",
- Measure: ServerReceivedBytesPerRPC,
- TagKeys: []tag.Key{KeyServerMethod},
- Aggregation: DefaultBytesDistribution,
- }
-
- ServerSentBytesPerRPCView = &view.View{
- Name: "grpc.io/server/sent_bytes_per_rpc",
- Description: "Distribution of total sent bytes per RPC, by method.",
- Measure: ServerSentBytesPerRPC,
- TagKeys: []tag.Key{KeyServerMethod},
- Aggregation: DefaultBytesDistribution,
- }
-
- ServerLatencyView = &view.View{
- Name: "grpc.io/server/server_latency",
- Description: "Distribution of server latency in milliseconds, by method.",
- TagKeys: []tag.Key{KeyServerMethod},
- Measure: ServerLatency,
- Aggregation: DefaultMillisecondsDistribution,
- }
-
- // Purposely reuses the count from `ServerLatency`, tagging
- // with method and status to result in ServerCompletedRpcs.
- ServerCompletedRPCsView = &view.View{
- Name: "grpc.io/server/completed_rpcs",
- Description: "Count of RPCs by method and status.",
- TagKeys: []tag.Key{KeyServerMethod, KeyServerStatus},
- Measure: ServerLatency,
- Aggregation: view.Count(),
- }
-
- ServerStartedRPCsView = &view.View{
- Measure: ServerStartedRPCs,
- Name: "grpc.io/server/started_rpcs",
- Description: "Number of started server RPCs.",
- TagKeys: []tag.Key{KeyServerMethod},
- Aggregation: view.Count(),
- }
-
- ServerReceivedMessagesPerRPCView = &view.View{
- Name: "grpc.io/server/received_messages_per_rpc",
- Description: "Distribution of messages received count per RPC, by method.",
- TagKeys: []tag.Key{KeyServerMethod},
- Measure: ServerReceivedMessagesPerRPC,
- Aggregation: DefaultMessageCountDistribution,
- }
-
- ServerSentMessagesPerRPCView = &view.View{
- Name: "grpc.io/server/sent_messages_per_rpc",
- Description: "Distribution of messages sent count per RPC, by method.",
- TagKeys: []tag.Key{KeyServerMethod},
- Measure: ServerSentMessagesPerRPC,
- Aggregation: DefaultMessageCountDistribution,
- }
-)
-
-// DefaultServerViews are the default server views provided by this package.
-var DefaultServerViews = []*view.View{
- ServerReceivedBytesPerRPCView,
- ServerSentBytesPerRPCView,
- ServerLatencyView,
- ServerCompletedRPCsView,
-}
diff --git a/vendor/go.opencensus.io/plugin/ocgrpc/server_stats_handler.go b/vendor/go.opencensus.io/plugin/ocgrpc/server_stats_handler.go
deleted file mode 100644
index afcef023af..0000000000
--- a/vendor/go.opencensus.io/plugin/ocgrpc/server_stats_handler.go
+++ /dev/null
@@ -1,63 +0,0 @@
-// Copyright 2017, OpenCensus 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 ocgrpc
-
-import (
- "time"
-
- "context"
-
- "go.opencensus.io/tag"
- "google.golang.org/grpc/grpclog"
- "google.golang.org/grpc/stats"
-)
-
-// statsTagRPC gets the metadata from gRPC context, extracts the encoded tags from
-// it and creates a new tag.Map and puts them into the returned context.
-func (h *ServerHandler) statsTagRPC(ctx context.Context, info *stats.RPCTagInfo) context.Context {
- startTime := time.Now()
- if info == nil {
- if grpclog.V(2) {
- grpclog.Infof("opencensus: TagRPC called with nil info.")
- }
- return ctx
- }
- d := &rpcData{
- startTime: startTime,
- method: info.FullMethodName,
- }
- propagated := h.extractPropagatedTags(ctx)
- ctx = tag.NewContext(ctx, propagated)
- ctx, _ = tag.New(ctx, tag.Upsert(KeyServerMethod, methodName(info.FullMethodName)))
- return context.WithValue(ctx, rpcDataKey, d)
-}
-
-// extractPropagatedTags creates a new tag map containing the tags extracted from the
-// gRPC metadata.
-func (h *ServerHandler) extractPropagatedTags(ctx context.Context) *tag.Map {
- buf := stats.Tags(ctx)
- if buf == nil {
- return nil
- }
- propagated, err := tag.Decode(buf)
- if err != nil {
- if grpclog.V(2) {
- grpclog.Warningf("opencensus: Failed to decode tags from gRPC metadata failed to decode: %v", err)
- }
- return nil
- }
- return propagated
-}
diff --git a/vendor/go.opencensus.io/plugin/ocgrpc/stats_common.go b/vendor/go.opencensus.io/plugin/ocgrpc/stats_common.go
deleted file mode 100644
index 9cb27320ca..0000000000
--- a/vendor/go.opencensus.io/plugin/ocgrpc/stats_common.go
+++ /dev/null
@@ -1,248 +0,0 @@
-// Copyright 2017, OpenCensus 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 ocgrpc
-
-import (
- "context"
- "strconv"
- "strings"
- "sync/atomic"
- "time"
-
- "go.opencensus.io/metric/metricdata"
- ocstats "go.opencensus.io/stats"
- "go.opencensus.io/stats/view"
- "go.opencensus.io/tag"
- "go.opencensus.io/trace"
- "google.golang.org/grpc/codes"
- "google.golang.org/grpc/grpclog"
- "google.golang.org/grpc/stats"
- "google.golang.org/grpc/status"
-)
-
-type grpcInstrumentationKey string
-
-// rpcData holds the instrumentation RPC data that is needed between the start
-// and end of an call. It holds the info that this package needs to keep track
-// of between the various GRPC events.
-type rpcData struct {
- // reqCount and respCount has to be the first words
- // in order to be 64-aligned on 32-bit architectures.
- sentCount, sentBytes, recvCount, recvBytes int64 // access atomically
-
- // startTime represents the time at which TagRPC was invoked at the
- // beginning of an RPC. It is an appoximation of the time when the
- // application code invoked GRPC code.
- startTime time.Time
- method string
-}
-
-// The following variables define the default hard-coded auxiliary data used by
-// both the default GRPC client and GRPC server metrics.
-var (
- DefaultBytesDistribution = view.Distribution(1024, 2048, 4096, 16384, 65536, 262144, 1048576, 4194304, 16777216, 67108864, 268435456, 1073741824, 4294967296)
- DefaultMillisecondsDistribution = view.Distribution(0.01, 0.05, 0.1, 0.3, 0.6, 0.8, 1, 2, 3, 4, 5, 6, 8, 10, 13, 16, 20, 25, 30, 40, 50, 65, 80, 100, 130, 160, 200, 250, 300, 400, 500, 650, 800, 1000, 2000, 5000, 10000, 20000, 50000, 100000)
- DefaultMessageCountDistribution = view.Distribution(1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384, 32768, 65536)
-)
-
-// Server tags are applied to the context used to process each RPC, as well as
-// the measures at the end of each RPC.
-var (
- KeyServerMethod = tag.MustNewKey("grpc_server_method")
- KeyServerStatus = tag.MustNewKey("grpc_server_status")
-)
-
-// Client tags are applied to measures at the end of each RPC.
-var (
- KeyClientMethod = tag.MustNewKey("grpc_client_method")
- KeyClientStatus = tag.MustNewKey("grpc_client_status")
-)
-
-var (
- rpcDataKey = grpcInstrumentationKey("opencensus-rpcData")
-)
-
-func methodName(fullname string) string {
- return strings.TrimLeft(fullname, "/")
-}
-
-// statsHandleRPC processes the RPC events.
-func statsHandleRPC(ctx context.Context, s stats.RPCStats) {
- switch st := s.(type) {
- case *stats.OutHeader, *stats.InHeader, *stats.InTrailer, *stats.OutTrailer:
- // do nothing for client
- case *stats.Begin:
- handleRPCBegin(ctx, st)
- case *stats.OutPayload:
- handleRPCOutPayload(ctx, st)
- case *stats.InPayload:
- handleRPCInPayload(ctx, st)
- case *stats.End:
- handleRPCEnd(ctx, st)
- default:
- grpclog.Infof("unexpected stats: %T", st)
- }
-}
-
-func handleRPCBegin(ctx context.Context, s *stats.Begin) {
- d, ok := ctx.Value(rpcDataKey).(*rpcData)
- if !ok {
- if grpclog.V(2) {
- grpclog.Infoln("Failed to retrieve *rpcData from context.")
- }
- }
-
- if s.IsClient() {
- ocstats.RecordWithOptions(ctx,
- ocstats.WithTags(tag.Upsert(KeyClientMethod, methodName(d.method))),
- ocstats.WithMeasurements(ClientStartedRPCs.M(1)))
- } else {
- ocstats.RecordWithOptions(ctx,
- ocstats.WithTags(tag.Upsert(KeyClientMethod, methodName(d.method))),
- ocstats.WithMeasurements(ServerStartedRPCs.M(1)))
- }
-}
-
-func handleRPCOutPayload(ctx context.Context, s *stats.OutPayload) {
- d, ok := ctx.Value(rpcDataKey).(*rpcData)
- if !ok {
- if grpclog.V(2) {
- grpclog.Infoln("Failed to retrieve *rpcData from context.")
- }
- return
- }
-
- atomic.AddInt64(&d.sentBytes, int64(s.Length))
- atomic.AddInt64(&d.sentCount, 1)
-}
-
-func handleRPCInPayload(ctx context.Context, s *stats.InPayload) {
- d, ok := ctx.Value(rpcDataKey).(*rpcData)
- if !ok {
- if grpclog.V(2) {
- grpclog.Infoln("Failed to retrieve *rpcData from context.")
- }
- return
- }
-
- atomic.AddInt64(&d.recvBytes, int64(s.Length))
- atomic.AddInt64(&d.recvCount, 1)
-}
-
-func handleRPCEnd(ctx context.Context, s *stats.End) {
- d, ok := ctx.Value(rpcDataKey).(*rpcData)
- if !ok {
- if grpclog.V(2) {
- grpclog.Infoln("Failed to retrieve *rpcData from context.")
- }
- return
- }
-
- elapsedTime := time.Since(d.startTime)
-
- var st string
- if s.Error != nil {
- s, ok := status.FromError(s.Error)
- if ok {
- st = statusCodeToString(s)
- }
- } else {
- st = "OK"
- }
-
- latencyMillis := float64(elapsedTime) / float64(time.Millisecond)
- attachments := getSpanCtxAttachment(ctx)
- if s.Client {
- ocstats.RecordWithOptions(ctx,
- ocstats.WithTags(
- tag.Upsert(KeyClientMethod, methodName(d.method)),
- tag.Upsert(KeyClientStatus, st)),
- ocstats.WithAttachments(attachments),
- ocstats.WithMeasurements(
- ClientSentBytesPerRPC.M(atomic.LoadInt64(&d.sentBytes)),
- ClientSentMessagesPerRPC.M(atomic.LoadInt64(&d.sentCount)),
- ClientReceivedMessagesPerRPC.M(atomic.LoadInt64(&d.recvCount)),
- ClientReceivedBytesPerRPC.M(atomic.LoadInt64(&d.recvBytes)),
- ClientRoundtripLatency.M(latencyMillis)))
- } else {
- ocstats.RecordWithOptions(ctx,
- ocstats.WithTags(
- tag.Upsert(KeyServerStatus, st),
- ),
- ocstats.WithAttachments(attachments),
- ocstats.WithMeasurements(
- ServerSentBytesPerRPC.M(atomic.LoadInt64(&d.sentBytes)),
- ServerSentMessagesPerRPC.M(atomic.LoadInt64(&d.sentCount)),
- ServerReceivedMessagesPerRPC.M(atomic.LoadInt64(&d.recvCount)),
- ServerReceivedBytesPerRPC.M(atomic.LoadInt64(&d.recvBytes)),
- ServerLatency.M(latencyMillis)))
- }
-}
-
-func statusCodeToString(s *status.Status) string {
- // see https://github.com/grpc/grpc/blob/master/doc/statuscodes.md
- switch c := s.Code(); c {
- case codes.OK:
- return "OK"
- case codes.Canceled:
- return "CANCELLED"
- case codes.Unknown:
- return "UNKNOWN"
- case codes.InvalidArgument:
- return "INVALID_ARGUMENT"
- case codes.DeadlineExceeded:
- return "DEADLINE_EXCEEDED"
- case codes.NotFound:
- return "NOT_FOUND"
- case codes.AlreadyExists:
- return "ALREADY_EXISTS"
- case codes.PermissionDenied:
- return "PERMISSION_DENIED"
- case codes.ResourceExhausted:
- return "RESOURCE_EXHAUSTED"
- case codes.FailedPrecondition:
- return "FAILED_PRECONDITION"
- case codes.Aborted:
- return "ABORTED"
- case codes.OutOfRange:
- return "OUT_OF_RANGE"
- case codes.Unimplemented:
- return "UNIMPLEMENTED"
- case codes.Internal:
- return "INTERNAL"
- case codes.Unavailable:
- return "UNAVAILABLE"
- case codes.DataLoss:
- return "DATA_LOSS"
- case codes.Unauthenticated:
- return "UNAUTHENTICATED"
- default:
- return "CODE_" + strconv.FormatInt(int64(c), 10)
- }
-}
-
-func getSpanCtxAttachment(ctx context.Context) metricdata.Attachments {
- attachments := map[string]interface{}{}
- span := trace.FromContext(ctx)
- if span == nil {
- return attachments
- }
- spanCtx := span.SpanContext()
- if spanCtx.IsSampled() {
- attachments[metricdata.AttachmentKeySpanContext] = spanCtx
- }
- return attachments
-}
diff --git a/vendor/go.opencensus.io/plugin/ocgrpc/trace_common.go b/vendor/go.opencensus.io/plugin/ocgrpc/trace_common.go
deleted file mode 100644
index 61bc543d0a..0000000000
--- a/vendor/go.opencensus.io/plugin/ocgrpc/trace_common.go
+++ /dev/null
@@ -1,107 +0,0 @@
-// Copyright 2017, OpenCensus 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 ocgrpc
-
-import (
- "context"
- "strings"
-
- "google.golang.org/grpc/codes"
- "google.golang.org/grpc/metadata"
- "google.golang.org/grpc/stats"
- "google.golang.org/grpc/status"
-
- "go.opencensus.io/trace"
- "go.opencensus.io/trace/propagation"
-)
-
-const traceContextKey = "grpc-trace-bin"
-
-// TagRPC creates a new trace span for the client side of the RPC.
-//
-// It returns ctx with the new trace span added and a serialization of the
-// SpanContext added to the outgoing gRPC metadata.
-func (c *ClientHandler) traceTagRPC(ctx context.Context, rti *stats.RPCTagInfo) context.Context {
- name := strings.TrimPrefix(rti.FullMethodName, "/")
- name = strings.Replace(name, "/", ".", -1)
- ctx, span := trace.StartSpan(ctx, name,
- trace.WithSampler(c.StartOptions.Sampler),
- trace.WithSpanKind(trace.SpanKindClient)) // span is ended by traceHandleRPC
- traceContextBinary := propagation.Binary(span.SpanContext())
- return metadata.AppendToOutgoingContext(ctx, traceContextKey, string(traceContextBinary))
-}
-
-// TagRPC creates a new trace span for the server side of the RPC.
-//
-// It checks the incoming gRPC metadata in ctx for a SpanContext, and if
-// it finds one, uses that SpanContext as the parent context of the new span.
-//
-// It returns ctx, with the new trace span added.
-func (s *ServerHandler) traceTagRPC(ctx context.Context, rti *stats.RPCTagInfo) context.Context {
- md, _ := metadata.FromIncomingContext(ctx)
- name := strings.TrimPrefix(rti.FullMethodName, "/")
- name = strings.Replace(name, "/", ".", -1)
- traceContext := md[traceContextKey]
- var (
- parent trace.SpanContext
- haveParent bool
- )
- if len(traceContext) > 0 {
- // Metadata with keys ending in -bin are actually binary. They are base64
- // encoded before being put on the wire, see:
- // https://github.com/grpc/grpc-go/blob/08d6261/Documentation/grpc-metadata.md#storing-binary-data-in-metadata
- traceContextBinary := []byte(traceContext[0])
- parent, haveParent = propagation.FromBinary(traceContextBinary)
- if haveParent && !s.IsPublicEndpoint {
- ctx, _ := trace.StartSpanWithRemoteParent(ctx, name, parent,
- trace.WithSpanKind(trace.SpanKindServer),
- trace.WithSampler(s.StartOptions.Sampler),
- )
- return ctx
- }
- }
- ctx, span := trace.StartSpan(ctx, name,
- trace.WithSpanKind(trace.SpanKindServer),
- trace.WithSampler(s.StartOptions.Sampler))
- if haveParent {
- span.AddLink(trace.Link{TraceID: parent.TraceID, SpanID: parent.SpanID, Type: trace.LinkTypeChild})
- }
- return ctx
-}
-
-func traceHandleRPC(ctx context.Context, rs stats.RPCStats) {
- span := trace.FromContext(ctx)
- // TODO: compressed and uncompressed sizes are not populated in every message.
- switch rs := rs.(type) {
- case *stats.Begin:
- span.AddAttributes(
- trace.BoolAttribute("Client", rs.Client),
- trace.BoolAttribute("FailFast", rs.FailFast))
- case *stats.InPayload:
- span.AddMessageReceiveEvent(0 /* TODO: messageID */, int64(rs.Length), int64(rs.WireLength))
- case *stats.OutPayload:
- span.AddMessageSendEvent(0, int64(rs.Length), int64(rs.WireLength))
- case *stats.End:
- if rs.Error != nil {
- s, ok := status.FromError(rs.Error)
- if ok {
- span.SetStatus(trace.Status{Code: int32(s.Code()), Message: s.Message()})
- } else {
- span.SetStatus(trace.Status{Code: int32(codes.Internal), Message: rs.Error.Error()})
- }
- }
- span.End()
- }
-}
diff --git a/vendor/go.opencensus.io/zpages/internal/resources.go b/vendor/go.opencensus.io/zpages/internal/resources.go
deleted file mode 100644
index 5b7fc76b29..0000000000
--- a/vendor/go.opencensus.io/zpages/internal/resources.go
+++ /dev/null
@@ -1,284 +0,0 @@
-// Code generated by "esc -pkg resources -o resources.go public/ templates/"; DO NOT EDIT.
-
-package internal
-
-import (
- "bytes"
- "compress/gzip"
- "encoding/base64"
- "io/ioutil"
- "net/http"
- "os"
- "path"
- "sync"
- "time"
-)
-
-type _escLocalFS struct{}
-
-var _escLocal _escLocalFS
-
-type _escStaticFS struct{}
-
-var _escStatic _escStaticFS
-
-type _escDirectory struct {
- fs http.FileSystem
- name string
-}
-
-type _escFile struct {
- compressed string
- size int64
- modtime int64
- local string
- isDir bool
-
- once sync.Once
- data []byte
- name string
-}
-
-func (_escLocalFS) Open(name string) (http.File, error) {
- f, present := _escData[path.Clean(name)]
- if !present {
- return nil, os.ErrNotExist
- }
- return os.Open(f.local)
-}
-
-func (_escStaticFS) prepare(name string) (*_escFile, error) {
- f, present := _escData[path.Clean(name)]
- if !present {
- return nil, os.ErrNotExist
- }
- var err error
- f.once.Do(func() {
- f.name = path.Base(name)
- if f.size == 0 {
- return
- }
- var gr *gzip.Reader
- b64 := base64.NewDecoder(base64.StdEncoding, bytes.NewBufferString(f.compressed))
- gr, err = gzip.NewReader(b64)
- if err != nil {
- return
- }
- f.data, err = ioutil.ReadAll(gr)
- })
- if err != nil {
- return nil, err
- }
- return f, nil
-}
-
-func (fs _escStaticFS) Open(name string) (http.File, error) {
- f, err := fs.prepare(name)
- if err != nil {
- return nil, err
- }
- return f.File()
-}
-
-func (dir _escDirectory) Open(name string) (http.File, error) {
- return dir.fs.Open(dir.name + name)
-}
-
-func (f *_escFile) File() (http.File, error) {
- type httpFile struct {
- *bytes.Reader
- *_escFile
- }
- return &httpFile{
- Reader: bytes.NewReader(f.data),
- _escFile: f,
- }, nil
-}
-
-func (f *_escFile) Close() error {
- return nil
-}
-
-func (f *_escFile) Readdir(count int) ([]os.FileInfo, error) {
- return nil, nil
-}
-
-func (f *_escFile) Stat() (os.FileInfo, error) {
- return f, nil
-}
-
-func (f *_escFile) Name() string {
- return f.name
-}
-
-func (f *_escFile) Size() int64 {
- return f.size
-}
-
-func (f *_escFile) Mode() os.FileMode {
- return 0
-}
-
-func (f *_escFile) ModTime() time.Time {
- return time.Unix(f.modtime, 0)
-}
-
-func (f *_escFile) IsDir() bool {
- return f.isDir
-}
-
-func (f *_escFile) Sys() interface{} {
- return f
-}
-
-// FS returns a http.Filesystem for the embedded assets. If useLocal is true,
-// the filesystem's contents are instead used.
-func FS(useLocal bool) http.FileSystem {
- if useLocal {
- return _escLocal
- }
- return _escStatic
-}
-
-// Dir returns a http.Filesystem for the embedded assets on a given prefix dir.
-// If useLocal is true, the filesystem's contents are instead used.
-func Dir(useLocal bool, name string) http.FileSystem {
- if useLocal {
- return _escDirectory{fs: _escLocal, name: name}
- }
- return _escDirectory{fs: _escStatic, name: name}
-}
-
-// FSByte returns the named file from the embedded assets. If useLocal is
-// true, the filesystem's contents are instead used.
-func FSByte(useLocal bool, name string) ([]byte, error) {
- if useLocal {
- f, err := _escLocal.Open(name)
- if err != nil {
- return nil, err
- }
- b, err := ioutil.ReadAll(f)
- _ = f.Close()
- return b, err
- }
- f, err := _escStatic.prepare(name)
- if err != nil {
- return nil, err
- }
- return f.data, nil
-}
-
-// FSMustByte is the same as FSByte, but panics if name is not present.
-func FSMustByte(useLocal bool, name string) []byte {
- b, err := FSByte(useLocal, name)
- if err != nil {
- panic(err)
- }
- return b
-}
-
-// FSString is the string version of FSByte.
-func FSString(useLocal bool, name string) (string, error) {
- b, err := FSByte(useLocal, name)
- return string(b), err
-}
-
-// FSMustString is the string version of FSMustByte.
-func FSMustString(useLocal bool, name string) string {
- return string(FSMustByte(useLocal, name))
-}
-
-var _escData = map[string]*_escFile{
-
- "/public/opencensus.css": {
- local: "public/opencensus.css",
- size: 0,
- modtime: 1519153040,
- compressed: `
-H4sIAAAAAAAC/wEAAP//AAAAAAAAAAA=
-`,
- },
-
- "/templates/footer.html": {
- local: "templates/footer.html",
- size: 16,
- modtime: 1519153248,
- compressed: `
-H4sIAAAAAAAC/7LRT8pPqbTjstHPKMnNseMCBAAA//8ATCBFEAAAAA==
-`,
- },
-
- "/templates/header.html": {
- local: "templates/header.html",
- size: 523,
- modtime: 1519164535,
- compressed: `
-H4sIAAAAAAAC/5TRv07rMBQG8D1P4ev1qvat7oKQEwZgYEAwdGF0nZP4UP+JfE6oqqrvjkyKBGIpky0f
-+6fP+syfu6fbzcvzvfAcQ9eYuohg09hKSLIzHmzfNUIIYSKwFc7bQsCtnHlYXcnziJEDdMej2tTN6WT0
-crJMA6adKBBaST4XdjMLdDlJ4QsMrdR6v9+rPEFykGgmhVkP9q1eUeiy1D8ZPgQgD8CfxjRvAzr9BXFE
-F730zBNdaz3kxKTGnMcAdkJSLkddM9wMNmI4tI+WoaANfx9cTiR/QbvcgxqBYx/q39bqv/qn45lTmHoc
-82rCtFMR00fwM06u4MSihwGKoOIuJSvzSrIzehG6xuilSLPN/aHWvP7Wll93zXsAAAD//6iqQ1ULAgAA
-`,
- },
-
- "/templates/rpcz.html": {
- local: "templates/rpcz.html",
- size: 2626,
- modtime: 1519164559,
- compressed: `
-H4sIAAAAAAAC/+yW3WrbMBTH7/0UwmUjYyxJU3o1W1C6sQ4WNrq+gCwdfzBFMtJx9+Hl3cex3DhNCrOz
-XfbGxFZ+5/8D+Ry5bZ0wBbD5VxT4wdmm9tttlNQ8QZFpYFkhrbYuPQMAyHP2vVJYpufL5QueoGNCV4VJ
-JRgExxNUPMmtQearX5C+XvG2nb+rHEisrNlukwUt8mRB/1ugowuF8GRR8+ggMD7L8/wSIGa5ExtIM/uD
-SdDa10JWpkiX3V0tlKK7FY8ixhgjp6ECAFwqiHm3FJZLCi2DKnnsLzGphfdprM9jJi0lmfSCX9vG4FTo
-6r5gWiAY+ZPNNv7VVP5WILCZq+ViOvvR1A2y2bfsBPZzg6fD752zzndU2Aza47H70r9KGnLka8DSql38
-S5P5+u3x9Vgr1HBVUSJfV2bel3i8cOOefn5ncf6c+Zz5XzKfaADyGLrlYn9UvlnxB52DERlFw4Q2oval
-RRrQDyX3zBVPMhq4oXlo2mZHjXvcyqrXjzv/mAp0A29dmQbht6TfVGscdWMbN5W5syj0I2ik59V98SmM
-2F5240elDlynO5kKwjtspO3tl2sa6r2qEwijYnusM50KBdE9aqRqd4DsySqBYnT2Du6UT0OD+AE7Uj6c
-YKfaD/R0/YH9F/9wiE5uv4BN7L8A/a0BwxxqWzCKPg37b7bdgz8BAAD//6NjPmJCCgAA
-`,
- },
-
- "/templates/summary.html": {
- local: "templates/summary.html",
- size: 1619,
- modtime: 1519164559,
- compressed: `
-H4sIAAAAAAAC/6yVPW/bMBCG9/yKg2p4qu2kW12JRQtkCzok3YoOlHSWBdMngaSc2iz/e8EP+Stqi8Re
-DIo63t3zvjwr1TwXCEpvBWZJ3sgS5US1vKipmsNtwm4AAFItwyI8lFA0QrWcsjvgoq4oE7jQLM3ZU8sJ
-vvE1prOcpTNdnhxjY8pV+yn8/j5+8KFDiZMCSaNMXPLHjqim6i2pB5v/OFDjgWukYgtPfN0KVFerNcRz
-L2Ujhyuls17xv0t/pcbelsYYyalCmEbBvnbFCrVzXlmb6uU/wX8YM7X2Z0ReMmOQSmuviRIENGbEYZ7B
-9LvkBap7KtumJm2teyNqWin/9sGt/GaAGsnmuaYSf733Sx/z2DyHkAmMiK/RbzreuFkvADdIh7NOBrkf
-LF6sKtl0VM7hHSImjlko9EGBHyZRAUdvTMzdD8b/9IgtRKijVC/k57CUuMgSp421n3dOOgeUGePBrB3v
-9LbF7NY1Of1S6HrjG+HsUMr1ft7wIXIfdUb1aoa9Ib0bGy66IH28d07ACxjvxjvV5X5pzCj65rhDpSPs
-/o6e0J9Pge+G+dv98tClYlxs6IcDbPDW/wGpE8cGfB2Iiij9kHnIdOY/JezmTwAAAP//Dz6TJ1MGAAA=
-`,
- },
-
- "/templates/traces.html": {
- local: "templates/traces.html",
- size: 420,
- modtime: 1519164578,
- compressed: `
-H4sIAAAAAAAC/4yQsU70MBCEez/FKtIv3RW/w6WgOIw7kGgoDiRqO14gwnGM1xEgs++OnKMA5Qq2ssYz
-I82nolZW30UT4NaMuIdSZH0wg2qtVm3UQkVd1XlkhgO+zkiZvj8SavHwjAFO35U3kdDBhrDfiv9/PFFK
-MuEJQR6mN2IuJaYh5Edo/nXn1MBmCA7fQV4P6B3B2ZYZfnh23dqzO3p+i12tlp85mR4HxyxKweCYVbvs
-UjYt25UFyh8eL5t+8lPaWz/jRaPva+zGVUowogkEZMbo0UE6MpKiIlinTf9yMh6mvKpYMH8FAAD//yQs
-JUakAQAA
-`,
- },
-
- "/": {
- isDir: true,
- local: "",
- },
-
- "/public": {
- isDir: true,
- local: "public",
- },
-
- "/templates": {
- isDir: true,
- local: "templates",
- },
-}
diff --git a/vendor/go.opencensus.io/zpages/rpcz.go b/vendor/go.opencensus.io/zpages/rpcz.go
deleted file mode 100644
index ef4dd15b32..0000000000
--- a/vendor/go.opencensus.io/zpages/rpcz.go
+++ /dev/null
@@ -1,333 +0,0 @@
-// Copyright 2017, OpenCensus 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 zpages
-
-import (
- "fmt"
- "io"
- "log"
- "math"
- "net/http"
- "sort"
- "sync"
- "text/tabwriter"
- "time"
-
- "go.opencensus.io/plugin/ocgrpc"
- "go.opencensus.io/stats/view"
-)
-
-const bytesPerKb = 1024
-
-var (
- programStartTime = time.Now()
- mu sync.Mutex // protects snaps
- snaps = make(map[methodKey]*statSnapshot)
-
- // viewType lists the views we are interested in for RPC stats.
- // A view's map value indicates whether that view contains data for received
- // RPCs.
- viewType = map[*view.View]bool{
- ocgrpc.ClientCompletedRPCsView: false,
- ocgrpc.ClientSentBytesPerRPCView: false,
- ocgrpc.ClientSentMessagesPerRPCView: false,
- ocgrpc.ClientReceivedBytesPerRPCView: false,
- ocgrpc.ClientReceivedMessagesPerRPCView: false,
- ocgrpc.ClientRoundtripLatencyView: false,
- ocgrpc.ServerCompletedRPCsView: true,
- ocgrpc.ServerReceivedBytesPerRPCView: true,
- ocgrpc.ServerReceivedMessagesPerRPCView: true,
- ocgrpc.ServerSentBytesPerRPCView: true,
- ocgrpc.ServerSentMessagesPerRPCView: true,
- ocgrpc.ServerLatencyView: true,
- }
-)
-
-func registerRPCViews() {
- views := make([]*view.View, 0, len(viewType))
- for v := range viewType {
- views = append(views, v)
- }
- if err := view.Register(views...); err != nil {
- log.Printf("error subscribing to views: %v", err)
- }
- view.RegisterExporter(snapExporter{})
-}
-
-func rpczHandler(w http.ResponseWriter, r *http.Request) {
- w.Header().Set("Content-Type", "text/html; charset=utf-8")
- WriteHTMLRpczPage(w)
-}
-
-// WriteHTMLRpczPage writes an HTML document to w containing per-method RPC stats.
-func WriteHTMLRpczPage(w io.Writer) {
- if err := headerTemplate.Execute(w, headerData{Title: "RPC Stats"}); err != nil {
- log.Printf("zpages: executing template: %v", err)
- }
- WriteHTMLRpczSummary(w)
- if err := footerTemplate.Execute(w, nil); err != nil {
- log.Printf("zpages: executing template: %v", err)
- }
-}
-
-// WriteHTMLRpczSummary writes HTML to w containing per-method RPC stats.
-//
-// It includes neither a header nor footer, so you can embed this data in other pages.
-func WriteHTMLRpczSummary(w io.Writer) {
- mu.Lock()
- if err := statsTemplate.Execute(w, getStatsPage()); err != nil {
- log.Printf("zpages: executing template: %v", err)
- }
- mu.Unlock()
-}
-
-// WriteTextRpczPage writes formatted text to w containing per-method RPC stats.
-func WriteTextRpczPage(w io.Writer) {
- mu.Lock()
- defer mu.Unlock()
- page := getStatsPage()
-
- for i, sg := range page.StatGroups {
- switch i {
- case 0:
- fmt.Fprint(w, "Sent:\n")
- case 1:
- fmt.Fprint(w, "\nReceived:\n")
- }
- tw := tabwriter.NewWriter(w, 6, 8, 1, ' ', 0)
- fmt.Fprint(tw, "Method\tCount\t\t\tAvgLat\t\t\tMaxLat\t\t\tRate\t\t\tIn (MiB/s)\t\t\tOut (MiB/s)\t\t\tErrors\t\t\n")
- fmt.Fprint(tw, "\tMin\tHr\tTot\tMin\tHr\tTot\tMin\tHr\tTot\tMin\tHr\tTot\tMin\tHr\tTot\tMin\tHr\tTot\tMin\tHr\tTot\n")
- for _, s := range sg.Snapshots {
- fmt.Fprintf(tw, "%s\t%d\t%d\t%d\t%v\t%v\t%v\t%.2f\t%.2f\t%.2f\t%.2f\t%.2f\t%.2f\t%.2f\t%.2f\t%.2f\t%d\t%d\t%d\n",
- s.Method,
- s.CountMinute,
- s.CountHour,
- s.CountTotal,
- s.AvgLatencyMinute,
- s.AvgLatencyHour,
- s.AvgLatencyTotal,
- s.RPCRateMinute,
- s.RPCRateHour,
- s.RPCRateTotal,
- s.InputRateMinute/bytesPerKb,
- s.InputRateHour/bytesPerKb,
- s.InputRateTotal/bytesPerKb,
- s.OutputRateMinute/bytesPerKb,
- s.OutputRateHour/bytesPerKb,
- s.OutputRateTotal/bytesPerKb,
- s.ErrorsMinute,
- s.ErrorsHour,
- s.ErrorsTotal)
- }
- tw.Flush()
- }
-}
-
-// headerData contains data for the header template.
-type headerData struct {
- Title string
-}
-
-// statsPage aggregates stats on the page for 'sent' and 'received' categories
-type statsPage struct {
- StatGroups []*statGroup
-}
-
-// statGroup aggregates snapshots for a directional category
-type statGroup struct {
- Direction string
- Snapshots []*statSnapshot
-}
-
-func (s *statGroup) Len() int {
- return len(s.Snapshots)
-}
-
-func (s *statGroup) Swap(i, j int) {
- s.Snapshots[i], s.Snapshots[j] = s.Snapshots[j], s.Snapshots[i]
-}
-
-func (s *statGroup) Less(i, j int) bool {
- return s.Snapshots[i].Method < s.Snapshots[j].Method
-}
-
-// statSnapshot holds the data items that are presented in a single row of RPC
-// stat information.
-type statSnapshot struct {
- // TODO: compute hour/minute values from cumulative
- Method string
- Received bool
- CountMinute uint64
- CountHour uint64
- CountTotal uint64
- AvgLatencyMinute time.Duration
- AvgLatencyHour time.Duration
- AvgLatencyTotal time.Duration
- RPCRateMinute float64
- RPCRateHour float64
- RPCRateTotal float64
- InputRateMinute float64
- InputRateHour float64
- InputRateTotal float64
- OutputRateMinute float64
- OutputRateHour float64
- OutputRateTotal float64
- ErrorsMinute uint64
- ErrorsHour uint64
- ErrorsTotal uint64
-}
-
-type methodKey struct {
- method string
- received bool
-}
-
-type snapExporter struct{}
-
-func (s snapExporter) ExportView(vd *view.Data) {
- received, ok := viewType[vd.View]
- if !ok {
- return
- }
- if len(vd.Rows) == 0 {
- return
- }
- ageSec := float64(time.Since(programStartTime)) / float64(time.Second)
-
- computeRate := func(maxSec, x float64) float64 {
- dur := ageSec
- if maxSec > 0 && dur > maxSec {
- dur = maxSec
- }
- return x / dur
- }
-
- convertTime := func(ms float64) time.Duration {
- if math.IsInf(ms, 0) || math.IsNaN(ms) {
- return 0
- }
- return time.Duration(float64(time.Millisecond) * ms)
- }
-
- haveResetErrors := make(map[string]struct{})
-
- mu.Lock()
- defer mu.Unlock()
- for _, row := range vd.Rows {
- var method string
- for _, tag := range row.Tags {
- if tag.Key == ocgrpc.KeyClientMethod || tag.Key == ocgrpc.KeyServerMethod {
- method = tag.Value
- break
- }
- }
-
- key := methodKey{method: method, received: received}
- s := snaps[key]
- if s == nil {
- s = &statSnapshot{Method: method, Received: received}
- snaps[key] = s
- }
-
- var (
- sum float64
- count float64
- )
- switch v := row.Data.(type) {
- case *view.CountData:
- sum = float64(v.Value)
- count = float64(v.Value)
- case *view.DistributionData:
- sum = v.Sum()
- count = float64(v.Count)
- case *view.SumData:
- sum = v.Value
- count = v.Value
- }
-
- // Update field of s corresponding to the view.
- switch vd.View {
- case ocgrpc.ClientCompletedRPCsView:
- if _, ok := haveResetErrors[method]; !ok {
- haveResetErrors[method] = struct{}{}
- s.ErrorsTotal = 0
- }
- for _, tag := range row.Tags {
- if tag.Key == ocgrpc.KeyClientStatus && tag.Value != "OK" {
- s.ErrorsTotal += uint64(count)
- }
- }
-
- case ocgrpc.ClientRoundtripLatencyView:
- s.AvgLatencyTotal = convertTime(sum / count)
-
- case ocgrpc.ClientSentBytesPerRPCView:
- s.OutputRateTotal = computeRate(0, sum)
-
- case ocgrpc.ClientReceivedBytesPerRPCView:
- s.InputRateTotal = computeRate(0, sum)
-
- case ocgrpc.ClientSentMessagesPerRPCView:
- s.CountTotal = uint64(count)
- s.RPCRateTotal = computeRate(0, count)
-
- case ocgrpc.ClientReceivedMessagesPerRPCView:
- // currently unused
-
- case ocgrpc.ServerCompletedRPCsView:
- if _, ok := haveResetErrors[method]; !ok {
- haveResetErrors[method] = struct{}{}
- s.ErrorsTotal = 0
- }
- for _, tag := range row.Tags {
- if tag.Key == ocgrpc.KeyServerStatus && tag.Value != "OK" {
- s.ErrorsTotal += uint64(count)
- }
- }
-
- case ocgrpc.ServerLatencyView:
- s.AvgLatencyTotal = convertTime(sum / count)
-
- case ocgrpc.ServerSentBytesPerRPCView:
- s.OutputRateTotal = computeRate(0, sum)
-
- case ocgrpc.ServerReceivedMessagesPerRPCView:
- s.CountTotal = uint64(count)
- s.RPCRateTotal = computeRate(0, count)
-
- case ocgrpc.ServerSentMessagesPerRPCView:
- // currently unused
- }
- }
-}
-
-func getStatsPage() *statsPage {
- sentStats := statGroup{Direction: "Sent"}
- receivedStats := statGroup{Direction: "Received"}
- for key, sg := range snaps {
- if key.received {
- receivedStats.Snapshots = append(receivedStats.Snapshots, sg)
- } else {
- sentStats.Snapshots = append(sentStats.Snapshots, sg)
- }
- }
- sort.Sort(&sentStats)
- sort.Sort(&receivedStats)
-
- return &statsPage{
- StatGroups: []*statGroup{&sentStats, &receivedStats},
- }
-}
diff --git a/vendor/go.opencensus.io/zpages/templates.go b/vendor/go.opencensus.io/zpages/templates.go
deleted file mode 100644
index 6675b0ab08..0000000000
--- a/vendor/go.opencensus.io/zpages/templates.go
+++ /dev/null
@@ -1,125 +0,0 @@
-// Copyright 2017, OpenCensus 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 zpages
-
-import (
- "fmt"
- "html/template"
- "io/ioutil"
- "log"
- "strconv"
- "time"
-
- "go.opencensus.io/trace"
- "go.opencensus.io/zpages/internal"
-)
-
-var (
- fs = internal.FS(false)
- templateFunctions = template.FuncMap{
- "count": countFormatter,
- "ms": msFormatter,
- "rate": rateFormatter,
- "datarate": dataRateFormatter,
- "even": even,
- "traceid": traceIDFormatter,
- }
- headerTemplate = parseTemplate("header")
- summaryTableTemplate = parseTemplate("summary")
- statsTemplate = parseTemplate("rpcz")
- tracesTableTemplate = parseTemplate("traces")
- footerTemplate = parseTemplate("footer")
-)
-
-func parseTemplate(name string) *template.Template {
- f, err := fs.Open("/templates/" + name + ".html")
- if err != nil {
- log.Panicf("%v: %v", name, err)
- }
- defer f.Close()
- text, err := ioutil.ReadAll(f)
- if err != nil {
- log.Panicf("%v: %v", name, err)
- }
- return template.Must(template.New(name).Funcs(templateFunctions).Parse(string(text)))
-}
-
-func countFormatter(num uint64) string {
- if num <= 0 {
- return " "
- }
- var floatVal float64
- var suffix string
-
- if num >= 1e18 {
- floatVal = float64(num) / 1e18
- suffix = " E "
- } else if num >= 1e15 {
- floatVal = float64(num) / 1e15
- suffix = " P "
- } else if num >= 1e12 {
- floatVal = float64(num) / 1e12
- suffix = " T "
- } else if num >= 1e9 {
- floatVal = float64(num) / 1e9
- suffix = " G "
- } else if num >= 1e6 {
- floatVal = float64(num) / 1e6
- suffix = " M "
- }
-
- if floatVal != 0 {
- return fmt.Sprintf("%1.3f%s", floatVal, suffix)
- }
- return fmt.Sprint(num)
-}
-
-func msFormatter(d time.Duration) string {
- if d == 0 {
- return "0"
- }
- if d < 10*time.Millisecond {
- return fmt.Sprintf("%.3f", float64(d)*1e-6)
- }
- return strconv.Itoa(int(d / time.Millisecond))
-}
-
-func rateFormatter(r float64) string {
- return fmt.Sprintf("%.3f", r)
-}
-
-func dataRateFormatter(b float64) string {
- return fmt.Sprintf("%.3f", b/1e6)
-}
-
-func traceIDFormatter(r traceRow) template.HTML {
- sc := r.SpanContext
- if sc == (trace.SpanContext{}) {
- return ""
- }
- col := "black"
- if sc.TraceOptions.IsSampled() {
- col = "blue"
- }
- if r.ParentSpanID != (trace.SpanID{}) {
- return template.HTML(fmt.Sprintf(`trace_id: %s span_id: %s parent_span_id: %s`, col, sc.TraceID, sc.SpanID, r.ParentSpanID))
- }
- return template.HTML(fmt.Sprintf(`trace_id: %s span_id: %s`, col, sc.TraceID, sc.SpanID))
-}
-
-func even(x int) bool {
- return x%2 == 0
-}
diff --git a/vendor/go.opencensus.io/zpages/tracez.go b/vendor/go.opencensus.io/zpages/tracez.go
deleted file mode 100644
index 330022c23e..0000000000
--- a/vendor/go.opencensus.io/zpages/tracez.go
+++ /dev/null
@@ -1,442 +0,0 @@
-// Copyright 2017, OpenCensus 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 zpages
-
-import (
- "fmt"
- "io"
- "log"
- "net/http"
- "sort"
- "strconv"
- "strings"
- "text/tabwriter"
- "time"
-
- "go.opencensus.io/internal"
- "go.opencensus.io/trace"
-)
-
-const (
- // spanNameQueryField is the header for span name.
- spanNameQueryField = "zspanname"
- // spanTypeQueryField is the header for type (running = 0, latency = 1, error = 2) to display.
- spanTypeQueryField = "ztype"
- // spanSubtypeQueryField is the header for sub-type:
- // * for latency based samples [0, 8] representing the latency buckets, where 0 is the first one;
- // * for error based samples, 0 means all, otherwise the error code;
- spanSubtypeQueryField = "zsubtype"
- // maxTraceMessageLength is the maximum length of a message in tracez output.
- maxTraceMessageLength = 1024
-)
-
-var (
- defaultLatencies = [...]time.Duration{
- 10 * time.Microsecond,
- 100 * time.Microsecond,
- time.Millisecond,
- 10 * time.Millisecond,
- 100 * time.Millisecond,
- time.Second,
- 10 * time.Second,
- 100 * time.Second,
- }
- canonicalCodes = [...]string{
- "OK",
- "CANCELLED",
- "UNKNOWN",
- "INVALID_ARGUMENT",
- "DEADLINE_EXCEEDED",
- "NOT_FOUND",
- "ALREADY_EXISTS",
- "PERMISSION_DENIED",
- "RESOURCE_EXHAUSTED",
- "FAILED_PRECONDITION",
- "ABORTED",
- "OUT_OF_RANGE",
- "UNIMPLEMENTED",
- "INTERNAL",
- "UNAVAILABLE",
- "DATA_LOSS",
- "UNAUTHENTICATED",
- }
-)
-
-func canonicalCodeString(code int32) string {
- if code < 0 || int(code) >= len(canonicalCodes) {
- return "error code " + strconv.FormatInt(int64(code), 10)
- }
- return canonicalCodes[code]
-}
-
-func tracezHandler(w http.ResponseWriter, r *http.Request) {
- r.ParseForm()
- w.Header().Set("Content-Type", "text/html; charset=utf-8")
- name := r.Form.Get(spanNameQueryField)
- t, _ := strconv.Atoi(r.Form.Get(spanTypeQueryField))
- st, _ := strconv.Atoi(r.Form.Get(spanSubtypeQueryField))
- WriteHTMLTracezPage(w, name, t, st)
-}
-
-// WriteHTMLTracezPage writes an HTML document to w containing locally-sampled trace spans.
-func WriteHTMLTracezPage(w io.Writer, spanName string, spanType, spanSubtype int) {
- if err := headerTemplate.Execute(w, headerData{Title: "Trace Spans"}); err != nil {
- log.Printf("zpages: executing template: %v", err)
- }
- WriteHTMLTracezSummary(w)
- WriteHTMLTracezSpans(w, spanName, spanType, spanSubtype)
- if err := footerTemplate.Execute(w, nil); err != nil {
- log.Printf("zpages: executing template: %v", err)
- }
-}
-
-// WriteHTMLTracezSummary writes HTML to w containing a summary of locally-sampled trace spans.
-//
-// It includes neither a header nor footer, so you can embed this data in other pages.
-func WriteHTMLTracezSummary(w io.Writer) {
- if err := summaryTableTemplate.Execute(w, getSummaryPageData()); err != nil {
- log.Printf("zpages: executing template: %v", err)
- }
-}
-
-// WriteHTMLTracezSpans writes HTML to w containing locally-sampled trace spans.
-//
-// It includes neither a header nor footer, so you can embed this data in other pages.
-func WriteHTMLTracezSpans(w io.Writer, spanName string, spanType, spanSubtype int) {
- if spanName == "" {
- return
- }
- if err := tracesTableTemplate.Execute(w, traceDataFromSpans(spanName, traceSpans(spanName, spanType, spanSubtype))); err != nil {
- log.Printf("zpages: executing template: %v", err)
- }
-}
-
-// WriteTextTracezSpans writes formatted text to w containing locally-sampled trace spans.
-func WriteTextTracezSpans(w io.Writer, spanName string, spanType, spanSubtype int) {
- spans := traceSpans(spanName, spanType, spanSubtype)
- data := traceDataFromSpans(spanName, spans)
- writeTextTraces(w, data)
-}
-
-// WriteTextTracezSummary writes formatted text to w containing a summary of locally-sampled trace spans.
-func WriteTextTracezSummary(w io.Writer) {
- w.Write([]byte("Locally sampled spans summary\n\n"))
-
- data := getSummaryPageData()
- if len(data.Rows) == 0 {
- return
- }
-
- tw := tabwriter.NewWriter(w, 8, 8, 1, ' ', 0)
-
- for i, s := range data.Header {
- if i != 0 {
- tw.Write([]byte("\t"))
- }
- tw.Write([]byte(s))
- }
- tw.Write([]byte("\n"))
-
- put := func(x int) {
- if x == 0 {
- tw.Write([]byte(".\t"))
- return
- }
- fmt.Fprintf(tw, "%d\t", x)
- }
- for _, r := range data.Rows {
- tw.Write([]byte(r.Name))
- tw.Write([]byte("\t"))
- put(r.Active)
- for _, l := range r.Latency {
- put(l)
- }
- put(r.Errors)
- tw.Write([]byte("\n"))
- }
- tw.Flush()
-}
-
-// traceData contains data for the trace data template.
-type traceData struct {
- Name string
- Num int
- Rows []traceRow
-}
-
-type traceRow struct {
- Fields [3]string
- trace.SpanContext
- ParentSpanID trace.SpanID
-}
-
-type events []interface{}
-
-func (e events) Len() int { return len(e) }
-func (e events) Less(i, j int) bool {
- var ti time.Time
- switch x := e[i].(type) {
- case *trace.Annotation:
- ti = x.Time
- case *trace.MessageEvent:
- ti = x.Time
- }
- switch x := e[j].(type) {
- case *trace.Annotation:
- return ti.Before(x.Time)
- case *trace.MessageEvent:
- return ti.Before(x.Time)
- }
- return false
-}
-
-func (e events) Swap(i, j int) { e[i], e[j] = e[j], e[i] }
-
-func traceRows(s *trace.SpanData) []traceRow {
- start := s.StartTime
-
- lasty, lastm, lastd := start.Date()
- wholeTime := func(t time.Time) string {
- return t.Format("2006/01/02-15:04:05") + fmt.Sprintf(".%06d", t.Nanosecond()/1000)
- }
- formatTime := func(t time.Time) string {
- y, m, d := t.Date()
- if y == lasty && m == lastm && d == lastd {
- return t.Format(" 15:04:05") + fmt.Sprintf(".%06d", t.Nanosecond()/1000)
- }
- lasty, lastm, lastd = y, m, d
- return wholeTime(t)
- }
-
- lastTime := start
- formatElapsed := func(t time.Time) string {
- d := t.Sub(lastTime)
- lastTime = t
- u := int64(d / 1000)
- // There are five cases for duration printing:
- // -1234567890s
- // -1234.123456
- // .123456
- // 12345.123456
- // 12345678901s
- switch {
- case u < -9999999999:
- return fmt.Sprintf("%11ds", u/1e6)
- case u < 0:
- sec := u / 1e6
- u -= sec * 1e6
- return fmt.Sprintf("%5d.%06d", sec, -u)
- case u < 1e6:
- return fmt.Sprintf(" .%6d", u)
- case u <= 99999999999:
- sec := u / 1e6
- u -= sec * 1e6
- return fmt.Sprintf("%5d.%06d", sec, u)
- default:
- return fmt.Sprintf("%11ds", u/1e6)
- }
- }
-
- firstRow := traceRow{Fields: [3]string{wholeTime(start), "", ""}, SpanContext: s.SpanContext, ParentSpanID: s.ParentSpanID}
- if s.EndTime.IsZero() {
- firstRow.Fields[1] = " "
- } else {
- firstRow.Fields[1] = formatElapsed(s.EndTime)
- lastTime = start
- }
- out := []traceRow{firstRow}
-
- formatAttributes := func(a map[string]interface{}) string {
- if len(a) == 0 {
- return ""
- }
- var keys []string
- for key := range a {
- keys = append(keys, key)
- }
- sort.Strings(keys)
- var s []string
- for _, key := range keys {
- val := a[key]
- switch val.(type) {
- case string:
- s = append(s, fmt.Sprintf("%s=%q", key, val))
- default:
- s = append(s, fmt.Sprintf("%s=%v", key, val))
- }
- }
- return "Attributes:{" + strings.Join(s, ", ") + "}"
- }
-
- if s.Status != (trace.Status{}) {
- msg := fmt.Sprintf("Status{canonicalCode=%s, description=%q}",
- canonicalCodeString(s.Status.Code), s.Status.Message)
- out = append(out, traceRow{Fields: [3]string{"", "", msg}})
- }
-
- if len(s.Attributes) != 0 {
- out = append(out, traceRow{Fields: [3]string{"", "", formatAttributes(s.Attributes)}})
- }
-
- var es events
- for i := range s.Annotations {
- es = append(es, &s.Annotations[i])
- }
- for i := range s.MessageEvents {
- es = append(es, &s.MessageEvents[i])
- }
- sort.Sort(es)
- for _, e := range es {
- switch e := e.(type) {
- case *trace.Annotation:
- msg := e.Message
- if len(e.Attributes) != 0 {
- msg = msg + " " + formatAttributes(e.Attributes)
- }
- row := traceRow{Fields: [3]string{
- formatTime(e.Time),
- formatElapsed(e.Time),
- msg,
- }}
- out = append(out, row)
- case *trace.MessageEvent:
- row := traceRow{Fields: [3]string{formatTime(e.Time), formatElapsed(e.Time)}}
- switch e.EventType {
- case trace.MessageEventTypeSent:
- row.Fields[2] = fmt.Sprintf("sent message [%d bytes, %d compressed bytes]", e.UncompressedByteSize, e.CompressedByteSize)
- case trace.MessageEventTypeRecv:
- row.Fields[2] = fmt.Sprintf("received message [%d bytes, %d compressed bytes]", e.UncompressedByteSize, e.CompressedByteSize)
- }
- out = append(out, row)
- }
- }
- for i := range out {
- if len(out[i].Fields[2]) > maxTraceMessageLength {
- out[i].Fields[2] = out[i].Fields[2][:maxTraceMessageLength]
- }
- }
- return out
-}
-
-func traceSpans(spanName string, spanType, spanSubtype int) []*trace.SpanData {
- internalTrace := internal.Trace.(interface {
- ReportActiveSpans(name string) []*trace.SpanData
- ReportSpansByError(name string, code int32) []*trace.SpanData
- ReportSpansByLatency(name string, minLatency, maxLatency time.Duration) []*trace.SpanData
- })
- var spans []*trace.SpanData
- switch spanType {
- case 0: // active
- spans = internalTrace.ReportActiveSpans(spanName)
- case 1: // latency
- var min, max time.Duration
- n := len(defaultLatencies)
- if spanSubtype == 0 {
- max = defaultLatencies[0]
- } else if spanSubtype == n {
- min, max = defaultLatencies[spanSubtype-1], (1<<63)-1
- } else if 0 < spanSubtype && spanSubtype < n {
- min, max = defaultLatencies[spanSubtype-1], defaultLatencies[spanSubtype]
- }
- spans = internalTrace.ReportSpansByLatency(spanName, min, max)
- case 2: // error
- spans = internalTrace.ReportSpansByError(spanName, 0)
- }
- return spans
-}
-
-func traceDataFromSpans(name string, spans []*trace.SpanData) traceData {
- data := traceData{
- Name: name,
- Num: len(spans),
- }
- for _, s := range spans {
- data.Rows = append(data.Rows, traceRows(s)...)
- }
- return data
-}
-
-func writeTextTraces(w io.Writer, data traceData) {
- tw := tabwriter.NewWriter(w, 1, 8, 1, ' ', 0)
- fmt.Fprint(tw, "When\tElapsed(s)\tType\n")
- for _, r := range data.Rows {
- tw.Write([]byte(r.Fields[0]))
- tw.Write([]byte("\t"))
- tw.Write([]byte(r.Fields[1]))
- tw.Write([]byte("\t"))
- tw.Write([]byte(r.Fields[2]))
- if sc := r.SpanContext; sc != (trace.SpanContext{}) {
- fmt.Fprintf(tw, "trace_id: %s span_id: %s", sc.TraceID, sc.SpanID)
- if r.ParentSpanID != (trace.SpanID{}) {
- fmt.Fprintf(tw, " parent_span_id: %s", r.ParentSpanID)
- }
- }
- tw.Write([]byte("\n"))
- }
- tw.Flush()
-}
-
-type summaryPageData struct {
- Header []string
- LatencyBucketNames []string
- Links bool
- TracesEndpoint string
- Rows []summaryPageRow
-}
-
-type summaryPageRow struct {
- Name string
- Active int
- Latency []int
- Errors int
-}
-
-func getSummaryPageData() summaryPageData {
- data := summaryPageData{
- Links: true,
- TracesEndpoint: "tracez",
- }
- internalTrace := internal.Trace.(interface {
- ReportSpansPerMethod() map[string]internal.PerMethodSummary
- })
- for name, s := range internalTrace.ReportSpansPerMethod() {
- if len(data.Header) == 0 {
- data.Header = []string{"Name", "Active"}
- for _, b := range s.LatencyBuckets {
- l := b.MinLatency
- s := fmt.Sprintf(">%v", l)
- if l == 100*time.Second {
- s = ">100s"
- }
- data.Header = append(data.Header, s)
- data.LatencyBucketNames = append(data.LatencyBucketNames, s)
- }
- data.Header = append(data.Header, "Errors")
- }
- row := summaryPageRow{Name: name, Active: s.Active}
- for _, l := range s.LatencyBuckets {
- row.Latency = append(row.Latency, l.Size)
- }
- for _, e := range s.ErrorBuckets {
- row.Errors += e.Size
- }
- data.Rows = append(data.Rows, row)
- }
- sort.Slice(data.Rows, func(i, j int) bool {
- return data.Rows[i].Name < data.Rows[j].Name
- })
- return data
-}
diff --git a/vendor/go.opencensus.io/zpages/zpages.go b/vendor/go.opencensus.io/zpages/zpages.go
deleted file mode 100644
index 7ee2c2e58e..0000000000
--- a/vendor/go.opencensus.io/zpages/zpages.go
+++ /dev/null
@@ -1,70 +0,0 @@
-// Copyright 2017, OpenCensus 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 zpages implements a collection of HTML pages that display RPC stats
-// and trace data, and also functions to write that same data in plain text to
-// an io.Writer.
-//
-// Users can also embed the HTML for stats and traces in custom status pages.
-//
-// zpages are currrently work-in-process and cannot display minutely and
-// hourly stats correctly.
-//
-// # Performance
-//
-// Installing the zpages has a performance overhead because additional traces
-// and stats will be collected in-process. In most cases, we expect this
-// overhead will not be significant but it depends on many factors, including
-// how many spans your process creates and how richly annotated they are.
-package zpages // import "go.opencensus.io/zpages"
-
-import (
- "net/http"
- "path"
- "sync"
-
- "go.opencensus.io/internal"
-)
-
-// TODO(ramonza): Remove Handler to make initialization lazy.
-
-// Handler is deprecated: Use Handle.
-var Handler http.Handler
-
-func init() {
- mux := http.NewServeMux()
- Handle(mux, "/")
- Handler = mux
-}
-
-// Handle adds the z-pages to the given ServeMux rooted at pathPrefix.
-func Handle(mux *http.ServeMux, pathPrefix string) {
- enable()
- if mux == nil {
- mux = http.DefaultServeMux
- }
- mux.HandleFunc(path.Join(pathPrefix, "rpcz"), rpczHandler)
- mux.HandleFunc(path.Join(pathPrefix, "tracez"), tracezHandler)
- mux.Handle(path.Join(pathPrefix, "public/"), http.FileServer(fs))
-}
-
-var enableOnce sync.Once
-
-func enable() {
- enableOnce.Do(func() {
- internal.LocalSpanStoreEnabled = true
- registerRPCViews()
- })
-}
diff --git a/vendor/go.opentelemetry.io/contrib/zpages/LICENSE b/vendor/go.opentelemetry.io/contrib/zpages/LICENSE
new file mode 100644
index 0000000000..261eeb9e9f
--- /dev/null
+++ b/vendor/go.opentelemetry.io/contrib/zpages/LICENSE
@@ -0,0 +1,201 @@
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright [yyyy] [name of copyright owner]
+
+ 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.
diff --git a/vendor/go.opentelemetry.io/contrib/zpages/boundaries.go b/vendor/go.opentelemetry.io/contrib/zpages/boundaries.go
new file mode 100644
index 0000000000..3d437170a9
--- /dev/null
+++ b/vendor/go.opentelemetry.io/contrib/zpages/boundaries.go
@@ -0,0 +1,61 @@
+// Copyright The OpenTelemetry 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 zpages // import "go.opentelemetry.io/contrib/zpages"
+
+import (
+ "sort"
+ "time"
+)
+
+const zeroDuration = time.Duration(0)
+const maxDuration = time.Duration(1<<63 - 1)
+
+var defaultBoundaries = newBoundaries([]time.Duration{
+ 10 * time.Microsecond,
+ 100 * time.Microsecond,
+ time.Millisecond,
+ 10 * time.Millisecond,
+ 100 * time.Millisecond,
+ time.Second,
+ 10 * time.Second,
+ 100 * time.Second,
+})
+
+// boundaries represents the interval bounds for the latency based samples.
+type boundaries struct {
+ durations []time.Duration
+}
+
+// newBoundaries returns a new boundaries.
+func newBoundaries(durations []time.Duration) *boundaries {
+ sort.Slice(durations, func(i, j int) bool {
+ return durations[i] < durations[j]
+ })
+ return &boundaries{durations: durations}
+}
+
+// numBuckets returns the number of buckets needed for these boundaries.
+func (lb boundaries) numBuckets() int {
+ return len(lb.durations) + 1
+}
+
+// getBucketIndex returns the appropriate bucket index for a given latency.
+func (lb boundaries) getBucketIndex(latency time.Duration) int {
+ i := 0
+ for i < len(lb.durations) && latency >= lb.durations[i] {
+ i++
+ }
+ return i
+}
diff --git a/vendor/go.opentelemetry.io/contrib/zpages/bucket.go b/vendor/go.opentelemetry.io/contrib/zpages/bucket.go
new file mode 100644
index 0000000000..f88c73a341
--- /dev/null
+++ b/vendor/go.opentelemetry.io/contrib/zpages/bucket.go
@@ -0,0 +1,74 @@
+// Copyright The OpenTelemetry Authors
+// Copyright 2017, OpenCensus 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 zpages // import "go.opentelemetry.io/contrib/zpages"
+
+import (
+ "time"
+
+ sdktrace "go.opentelemetry.io/otel/sdk/trace"
+)
+
+const (
+ // defaultBucketCapacity is the default capacity for every bucket (latency or error based).
+ defaultBucketCapacity = 10
+ // samplePeriod is the minimum time between accepting spans in a single bucket.
+ samplePeriod = time.Second
+)
+
+// bucket is a container for a set of spans for latency buckets or errored spans.
+type bucket struct {
+ nextTime time.Time // next time we can accept a span
+ buffer []sdktrace.ReadOnlySpan // circular buffer of spans
+ nextIndex int // location next ReadOnlySpan should be placed in buffer
+ overflow bool // whether the circular buffer has wrapped around
+}
+
+// newBucket returns a new bucket with the given capacity.
+func newBucket(capacity uint) *bucket {
+ return &bucket{
+ buffer: make([]sdktrace.ReadOnlySpan, capacity),
+ }
+}
+
+// add adds a span to the bucket, if nextTime has been reached.
+func (b *bucket) add(s sdktrace.ReadOnlySpan) {
+ if s.EndTime().Before(b.nextTime) {
+ return
+ }
+ if len(b.buffer) == 0 {
+ return
+ }
+ b.nextTime = s.EndTime().Add(samplePeriod)
+ b.buffer[b.nextIndex] = s
+ b.nextIndex++
+ if b.nextIndex == len(b.buffer) {
+ b.nextIndex = 0
+ b.overflow = true
+ }
+}
+
+// len returns the number of spans in the bucket.
+func (b *bucket) len() int {
+ if b.overflow {
+ return len(b.buffer)
+ }
+ return b.nextIndex
+}
+
+// spans returns the spans in this bucket.
+func (b *bucket) spans() []sdktrace.ReadOnlySpan {
+ return append([]sdktrace.ReadOnlySpan(nil), b.buffer[0:b.len()]...)
+}
diff --git a/vendor/go.opencensus.io/zpages/internal/gen.go b/vendor/go.opentelemetry.io/contrib/zpages/internal/gen.go
similarity index 72%
rename from vendor/go.opencensus.io/zpages/internal/gen.go
rename to vendor/go.opentelemetry.io/contrib/zpages/internal/gen.go
index 453e217544..5972035f82 100644
--- a/vendor/go.opencensus.io/zpages/internal/gen.go
+++ b/vendor/go.opentelemetry.io/contrib/zpages/internal/gen.go
@@ -1,4 +1,4 @@
-// Copyright 2018, OpenCensus Authors
+// Copyright The OpenTelemetry Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
@@ -11,9 +11,10 @@
// 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 internal // import "go.opencensus.io/zpages/internal"
+package internal // import "go.opentelemetry.io/contrib/zpages/internal"
-// go get https://github.com/mjibson/esc.git
-//go:generate esc -pkg internal -o resources.go public/ templates/
+import "embed"
+
+//go:embed templates/*
+var Templates embed.FS
diff --git a/vendor/go.opentelemetry.io/contrib/zpages/internal/templates/footer.html b/vendor/go.opentelemetry.io/contrib/zpages/internal/templates/footer.html
new file mode 100644
index 0000000000..308b1d01b6
--- /dev/null
+++ b/vendor/go.opentelemetry.io/contrib/zpages/internal/templates/footer.html
@@ -0,0 +1,2 @@
+