diff --git a/go.mod b/go.mod index 0f669573e..37a743be9 100644 --- a/go.mod +++ b/go.mod @@ -17,7 +17,7 @@ require ( github.com/go-playground/locales v0.13.0 github.com/go-playground/universal-translator v0.17.0 github.com/go-playground/validator/v10 v10.4.1 - github.com/go-redis/redis/v8 v8.2.1 + github.com/go-redis/redis/v8 v8.7.0 github.com/google/go-querystring v1.0.0 // indirect github.com/google/uuid v1.2.0 github.com/gorilla/mux v1.8.0 diff --git a/go.sum b/go.sum index eadb32b3e..ba378ab64 100644 --- a/go.sum +++ b/go.sum @@ -159,6 +159,8 @@ github.com/go-redis/redis/v8 v8.2.0 h1:h8HbcOIjMpEywOmAF5TXNZOdvUryqSAIQHsIxH7On github.com/go-redis/redis/v8 v8.2.0/go.mod h1:ysgGY09J/QeDYbu3HikWEIPCwaeOkuNoTgKayTEaEOw= github.com/go-redis/redis/v8 v8.2.1 h1:PCgs6b+iWVG3AseLbNcIneoDSRKv+BdYUl3TtXOiZCY= github.com/go-redis/redis/v8 v8.2.1/go.mod h1:ysgGY09J/QeDYbu3HikWEIPCwaeOkuNoTgKayTEaEOw= +github.com/go-redis/redis/v8 v8.7.0 h1:LJ8sFG5eNH1u3SxlptEZ3mEgm/5J9Qx6QhiTG3HhpCo= +github.com/go-redis/redis/v8 v8.7.0/go.mod h1:BRxHBWn3pO3CfjyX6vAoyeRmCquvxr6QG+2onGV2gYs= github.com/go-sql-driver/mysql v1.5.0 h1:ozyZYNQW3x3HtqT1jira07DN2PArx2v7/mN66gGcHOs= github.com/go-sql-driver/mysql v1.5.0/go.mod h1:DCzpHaOWr8IXmIStZouvnhqoel9Qv2LBy8hT2VhHyBg= github.com/gobuffalo/here v0.6.0 h1:hYrd0a6gDmWxBM4TnrGw8mQg24iSVoIkHEk7FodQcBI= @@ -210,6 +212,7 @@ github.com/google/go-cmp v0.5.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/ github.com/google/go-cmp v0.5.1 h1:JFrFEBb2xKufg6XkJsJr+WbKb4FQlURi5RUcBveYu9k= github.com/google/go-cmp v0.5.1/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.5.2/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.5.4/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-querystring v1.0.0 h1:Xkwi/a1rcvNg1PPYe5vI8GbeBY/jrVuDX5ASuANWTrk= github.com/google/go-querystring v1.0.0/go.mod h1:odCYkC5MyYFN7vkCjXpyrEuKhc/BUO6wN/zVPAxq5ck= github.com/google/gofuzz v1.0.0 h1:A8PeW59pxE9IoFRqBp37U+mSNaQoZ46F1f0f863XSXw= @@ -405,12 +408,14 @@ github.com/onsi/ginkgo v1.10.1/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+ github.com/onsi/ginkgo v1.12.1/go.mod h1:zj2OWP4+oCPe1qIXoGWkgMRwljMUYCdkwsT2108oapk= github.com/onsi/ginkgo v1.14.1 h1:jMU0WaQrP0a/YAEq8eJmJKjBoMs+pClEr1vDMlM/Do4= github.com/onsi/ginkgo v1.14.1/go.mod h1:iSB4RoI2tjJc9BBv4NKIKWKya62Rps+oPG/Lv9klQyY= +github.com/onsi/ginkgo v1.15.0/go.mod h1:hF8qUzuuC8DJGygJH3726JnCZX4MYbRB8yFfISqnKUg= github.com/onsi/gomega v1.7.0 h1:XPnZz8VVBHjVsy1vzJmRwIcSwiUO+JFfrv/xGiigmME= github.com/onsi/gomega v1.7.0/go.mod h1:ex+gbHU/CVuBBDIJjb2X0qEXbFg53c61hWP/1CpauHY= github.com/onsi/gomega v1.7.1/go.mod h1:XdKZgCCFLUoM/7CFJVPcG8C1xQ1AJ0vpAezJrB7JYyY= github.com/onsi/gomega v1.10.1/go.mod h1:iN09h71vgCQne3DLsj+A5owkum+a2tYe+TOCB1ybHNo= github.com/onsi/gomega v1.10.2 h1:aY/nuoWlKJud2J6U0E3NWsjlg+0GtwXxgEqthRdzlcs= github.com/onsi/gomega v1.10.2/go.mod h1:iN09h71vgCQne3DLsj+A5owkum+a2tYe+TOCB1ybHNo= +github.com/onsi/gomega v1.10.5/go.mod h1:gza4q3jKQJijlu05nKWRCW/GavJumGt8aNRxWg7mt48= github.com/patrickmn/go-cache v2.1.0+incompatible h1:HRMgzkcYKYpi3C8ajMPV8OFXaaRUnok+kx1WdO15EQc= github.com/patrickmn/go-cache v2.1.0+incompatible/go.mod h1:3Qf8kWWT7OJRJbdiICTKqZju1ZixQ/KpMGzzAfe6+WQ= github.com/pelletier/go-toml v1.2.0/go.mod h1:5z9KED0ma1S8pY6P1sdut58dfprrGBbd/94hg7ilaic= @@ -504,6 +509,13 @@ go.opencensus.io v0.22.3/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw= go.opencensus.io v0.22.4/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw= go.opentelemetry.io/otel v0.11.0 h1:IN2tzQa9Gc4ZVKnTaMbPVcHjvzOdg5n9QfnmlqiET7E= go.opentelemetry.io/otel v0.11.0/go.mod h1:G8UCk+KooF2HLkgo8RHX9epABH/aRGYET7gQOqBVdB0= +go.opentelemetry.io/otel v0.18.0 h1:d5Of7+Zw4ANFOJB+TIn2K3QWsgS2Ht7OU9DqZHI6qu8= +go.opentelemetry.io/otel v0.18.0/go.mod h1:PT5zQj4lTsR1YeARt8YNKcFb88/c2IKoSABK9mX0r78= +go.opentelemetry.io/otel/metric v0.18.0 h1:yuZCmY9e1ZTaMlZXLrrbAPmYW6tW1A5ozOZeOYGaTaY= +go.opentelemetry.io/otel/metric v0.18.0/go.mod h1:kEH2QtzAyBy3xDVQfGZKIcok4ZZFvd5xyKPfPcuK6pE= +go.opentelemetry.io/otel/oteltest v0.18.0/go.mod h1:NyierCU3/G8DLTva7KRzGii2fdxdR89zXKH1bNWY7Bo= +go.opentelemetry.io/otel/trace v0.18.0 h1:ilCfc/fptVKaDMK1vWk0elxpolurJbEgey9J6g6s+wk= +go.opentelemetry.io/otel/trace v0.18.0/go.mod h1:FzdUu3BPwZSZebfQ1vl5/tAa8LyMLXSJN57AXIt/iDk= golang.org/x/crypto v0.0.0-20181203042331-505ab145d0a9/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/crypto v0.0.0-20190325154230-a5d413f7728c h1:Vj5n4GlwjmQteupaxJ9+0FNOmBrHfq7vN4btdGoDZgI= @@ -606,6 +618,9 @@ golang.org/x/net v0.0.0-20200822124328-c89045814202/go.mod h1:/O7V0waA8r7cgGh81R golang.org/x/net v0.0.0-20200927032502-5d4f70055728/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA= golang.org/x/net v0.0.0-20200930145003-4acb6c075d10 h1:YfxMZzv3PjGonQYNUaeU2+DhAdqOxerQ30JFB6WgAXo= golang.org/x/net v0.0.0-20200930145003-4acb6c075d10/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA= +golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= +golang.org/x/net v0.0.0-20201202161906-c7110b5ffcbb h1:eBmm0M9fYhWpKZLjQUUKka/LtIxf46G4fxeEz5KJr9U= +golang.org/x/net v0.0.0-20201202161906-c7110b5ffcbb/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= golang.org/x/oauth2 v0.0.0-20180620175406-ef147856a6dd/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= @@ -623,6 +638,7 @@ golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJ golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20200317015054-43a5402ce75a/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20200625203802-6e8e738ad208/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20181205085412-a5c9d58dba9a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= @@ -669,6 +685,9 @@ golang.org/x/sys v0.0.0-20200615200032-f1bc736245b1/go.mod h1:h1NjWce9XRLGQEsW7w golang.org/x/sys v0.0.0-20200803210538-64077c9b5642/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200905004654-be1d3432aa8f h1:Fqb3ao1hUmOR3GkUOg/Y+BadLwykBIzs5q8Ez2SbHyc= golang.org/x/sys v0.0.0-20200905004654-be1d3432aa8f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210112080510-489259a85091 h1:DMyOG0U+gKfu8JZzg2UQe9MeaC1X+xQWlAKcRnjxjCw= +golang.org/x/sys v0.0.0-20210112080510-489259a85091/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/text v0.0.0-20170915032832-14c0d48ead0c/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.1-0.20180807135948-17ff2d5776d2/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= @@ -729,6 +748,7 @@ golang.org/x/tools v0.0.0-20200804011535-6c149bb5ef0d/go.mod h1:njjCfa9FT2d7l9Bc golang.org/x/tools v0.0.0-20200825202427-b303f430e36d/go.mod h1:njjCfa9FT2d7l9Bc6FUM5FLjQPp3cFF28FI3qnDFljA= golang.org/x/tools v0.0.0-20200904185747-39188db58858/go.mod h1:Cj7w3i3Rnn0Xh82ur9kSqwfTHTeVxaDqrfMjpcNT6bE= golang.org/x/tools v0.0.0-20200929161345-d7fc70abf50f/go.mod h1:z6u4i615ZeAfBE4XtMziQW1fSVJXACjjbWkB/mvPzlU= +golang.org/x/tools v0.0.0-20201224043029-2b0845dc783e/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543 h1:E7g+9GITq07hpfrRu66IVDexMakfv52eLZ2CXBWiKr4= diff --git a/vendor/github.com/go-redis/redis/v8/.golangci.yml b/vendor/github.com/go-redis/redis/v8/.golangci.yml index 2132eee96..b88b2b9b5 100644 --- a/vendor/github.com/go-redis/redis/v8/.golangci.yml +++ b/vendor/github.com/go-redis/redis/v8/.golangci.yml @@ -17,5 +17,8 @@ linters: - gomnd - goerr113 - exhaustive - - gofumpt - nestif + - nlreturn + - exhaustivestruct + - wrapcheck + - errorlint diff --git a/vendor/github.com/go-redis/redis/v8/.travis.yml b/vendor/github.com/go-redis/redis/v8/.travis.yml index adedd8df4..a221d84db 100644 --- a/vendor/github.com/go-redis/redis/v8/.travis.yml +++ b/vendor/github.com/go-redis/redis/v8/.travis.yml @@ -17,4 +17,4 @@ go_import_path: github.com/go-redis/redis before_install: - curl -sSfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | sh -s -- - -b $(go env GOPATH)/bin v1.28.3 + -b $(go env GOPATH)/bin v1.32.2 diff --git a/vendor/github.com/go-redis/redis/v8/CHANGELOG.md b/vendor/github.com/go-redis/redis/v8/CHANGELOG.md index d0c4c8c1c..8392d5485 100644 --- a/vendor/github.com/go-redis/redis/v8/CHANGELOG.md +++ b/vendor/github.com/go-redis/redis/v8/CHANGELOG.md @@ -2,96 +2,4 @@ > :heart: [**Uptrace.dev** - distributed traces, logs, and errors in one place](https://uptrace.dev) -## v8 - -- Documentation at https://redis.uptrace.dev/ - -- All commands require `context.Context` as a first argument, e.g. `rdb.Ping(ctx)`. If you are not - using `context.Context` yet, the simplest option is to define global package variable - `var ctx = context.TODO()` and use it when `ctx` is required. - -- Full support for `context.Context` canceling. - -- Added `redis.NewFailoverClusterClient` that supports routing read-only commands to a slave node. - -- Added `redisext.OpenTemetryHook` that adds - [Redis OpenTelemetry instrumentation](https://redis.uptrace.dev/tracing/). - -- Redis slow log support. - -- Ring uses Rendezvous Hashing by default which provides better distribution. You need to move - existing keys to a new location or keys will be inaccessible / lost. To use old hashing scheme: - -```go -import "github.com/golang/groupcache/consistenthash" - -ring := redis.NewRing(&redis.RingOptions{ - NewConsistentHash: func() { - return consistenthash.New(100, crc32.ChecksumIEEE) - }, -}) -``` - -- `ClusterOptions.MaxRedirects` default value is changed from 8 to 3. -- `Options.MaxRetries` default value is changed from 0 to 3. - -- `Cluster.ForEachNode` is renamed to `ForEachShard` for consistency with `Ring`. - -## v7.3 - -- New option `Options.Username` which causes client to use `AuthACL`. Be aware if your connection - URL contains username. - -## v7.2 - -- Existing `HMSet` is renamed to `HSet` and old deprecated `HMSet` is restored for Redis 3 users. - -## v7.1 - -- Existing `Cmd.String` is renamed to `Cmd.Text`. New `Cmd.String` implements `fmt.Stringer` - interface. - -## v7 - -- _Important_. Tx.Pipeline now returns a non-transactional pipeline. Use Tx.TxPipeline for a - transactional pipeline. -- WrapProcess is replaced with more convenient AddHook that has access to context.Context. -- WithContext now can not be used to create a shallow copy of the client. -- New methods ProcessContext, DoContext, and ExecContext. -- Client respects Context.Deadline when setting net.Conn deadline. -- Client listens on Context.Done while waiting for a connection from the pool and returns an error - when context context is cancelled. -- Add PubSub.ChannelWithSubscriptions that sends `*Subscription` in addition to `*Message` to allow - detecting reconnections. -- `time.Time` is now marshalled in RFC3339 format. `rdb.Get("foo").Time()` helper is added to parse - the time. -- `SetLimiter` is removed and added `Options.Limiter` instead. -- `HMSet` is deprecated as of Redis v4. - -## v6.15 - -- Cluster and Ring pipelines process commands for each node in its own goroutine. - -## 6.14 - -- Added Options.MinIdleConns. -- Added Options.MaxConnAge. -- PoolStats.FreeConns is renamed to PoolStats.IdleConns. -- Add Client.Do to simplify creating custom commands. -- Add Cmd.String, Cmd.Int, Cmd.Int64, Cmd.Uint64, Cmd.Float64, and Cmd.Bool helpers. -- Lower memory usage. - -## v6.13 - -- Ring got new options called `HashReplicas` and `Hash`. It is recommended to set - `HashReplicas = 1000` for better keys distribution between shards. -- Cluster client was optimized to use much less memory when reloading cluster state. -- PubSub.ReceiveMessage is re-worked to not use ReceiveTimeout so it does not lose data when timeout - occurres. In most cases it is recommended to use PubSub.Channel instead. -- Dialer.KeepAlive is set to 5 minutes by default. - -## v6.12 - -- ClusterClient got new option called `ClusterSlots` which allows to build cluster of normal Redis - Servers that don't have cluster mode enabled. See - https://godoc.org/github.com/go-redis/redis#example-NewClusterClient--ManualSetup +See https://redis.uptrace.dev/changelog/ diff --git a/vendor/github.com/go-redis/redis/v8/Makefile b/vendor/github.com/go-redis/redis/v8/Makefile index 49e4c96f0..348277c07 100644 --- a/vendor/github.com/go-redis/redis/v8/Makefile +++ b/vendor/github.com/go-redis/redis/v8/Makefile @@ -15,7 +15,13 @@ bench: testdeps testdata/redis: mkdir -p $@ - wget -qO- http://download.redis.io/redis-stable.tar.gz | tar xvz --strip-components=1 -C $@ + wget -qO- https://download.redis.io/releases/redis-6.2-rc3.tar.gz | tar xvz --strip-components=1 -C $@ testdata/redis/src/redis-server: testdata/redis cd $< && make all + +tag: + git tag $(VERSION) + git tag extra/rediscmd/$(VERSION) + git tag extra/redisotel/$(VERSION) + git tag extra/rediscensus/$(VERSION) diff --git a/vendor/github.com/go-redis/redis/v8/README.md b/vendor/github.com/go-redis/redis/v8/README.md index 52cc75670..130b7bb89 100644 --- a/vendor/github.com/go-redis/redis/v8/README.md +++ b/vendor/github.com/go-redis/redis/v8/README.md @@ -1,25 +1,28 @@ +

+ + + +

+ # Redis client for Golang [![Build Status](https://travis-ci.org/go-redis/redis.png?branch=master)](https://travis-ci.org/go-redis/redis) [![PkgGoDev](https://pkg.go.dev/badge/github.com/go-redis/redis/v8)](https://pkg.go.dev/github.com/go-redis/redis/v8?tab=doc) [![Documentation](https://img.shields.io/badge/redis-documentation-informational)](https://redis.uptrace.dev/) -[![Chat](https://discordapp.com/api/guilds/756530933771010068/widget.png)](https://discord.gg/ZQJDR3R) - -> :heart: [**Uptrace.dev** - distributed traces, logs, and errors in one place](https://uptrace.dev) +[![Chat](https://discordapp.com/api/guilds/752070105847955518/widget.png)](https://discord.gg/rWtp5Aj) -- [Docs](https://redis.uptrace.dev) +- Join [Discord](https://discord.gg/rWtp5Aj) to ask questions. +- [Documentation](https://redis.uptrace.dev) - [Reference](https://pkg.go.dev/github.com/go-redis/redis/v8?tab=doc) - [Examples](https://pkg.go.dev/github.com/go-redis/redis/v8?tab=doc#pkg-examples) -- [RealWorld example app](https://github.com/uptrace/go-realworld-example-app) -- Use [Discord](https://discord.gg/ZQJDR3R) or [stackoverflow](https://stackoverflow.com/) to ask - questions. +- [RealWorld example app](https://github.com/uptrace/go-treemux-realworld-example-app) ## Ecosystem -- [redisext](https://github.com/go-redis/redisext) - tracing using OpenTelemetryHook. +- [Redis Mock](https://github.com/go-redis/redismock). +- [Distributed Locks](https://github.com/bsm/redislock). - [Redis Cache](https://github.com/go-redis/cache). - [Rate limiting](https://github.com/go-redis/redis_rate). -- [Distributed Locks](https://github.com/bsm/redislock). ## Features @@ -39,23 +42,20 @@ - [Ring](https://pkg.go.dev/github.com/go-redis/redis/v8?tab=doc#NewRing). - [Instrumentation](https://pkg.go.dev/github.com/go-redis/redis/v8?tab=doc#ex-package--Instrumentation). -API docs: https://pkg.go.dev/github.com/go-redis/redis/v8?tab=doc. Examples: -https://pkg.go.dev/github.com/go-redis/redis/v8?tab=doc#pkg-examples. - ## Installation -go-redis requires a Go version with [Modules](https://github.com/golang/go/wiki/Modules) support and -uses import versioning. So please make sure to initialize a Go module before installing go-redis: +go-redis supports 2 last Go versions and requires a Go version with +[modules](https://github.com/golang/go/wiki/Modules) support. So make sure to initialize a Go +module: ```shell go mod init github.com/my/repo -go get github.com/go-redis/redis/v8 ``` -Import: +And then install go-redis/v8 (note _v8_ in the import; omitting it is a popular mistake): -```go -import "github.com/go-redis/redis/v8" +```shell +go get github.com/go-redis/redis/v8 ``` ## Quickstart @@ -68,24 +68,13 @@ import ( var ctx = context.Background() -func ExampleNewClient() { - rdb := redis.NewClient(&redis.Options{ - Addr: "localhost:6379", - Password: "", // no password set - DB: 0, // use default DB - }) - - pong, err := rdb.Ping(ctx).Result() - fmt.Println(pong, err) - // Output: PONG -} - func ExampleClient() { rdb := redis.NewClient(&redis.Options{ Addr: "localhost:6379", Password: "", // no password set DB: 0, // use default DB }) + err := rdb.Set(ctx, "key", "value", 0).Err() if err != nil { panic(err) @@ -110,11 +99,6 @@ func ExampleClient() { } ``` -## Howto - -Please go through [examples](https://pkg.go.dev/github.com/go-redis/redis/v8?tab=doc#pkg-examples) -to get an idea how to use this package. - ## Look and feel Some corner cases: @@ -150,8 +134,36 @@ vals, err := rdb.Eval(ctx, "return {KEYS[1],ARGV[1]}", []string{"key"}, "hello") res, err := rdb.Do(ctx, "set", "key", "value").Result() ``` +## Run the test + +go-redis will start a redis-server and run the test cases. + +The paths of redis-server bin file and redis config file are definded in `main_test.go`: + +``` +var ( + redisServerBin, _ = filepath.Abs(filepath.Join("testdata", "redis", "src", "redis-server")) + redisServerConf, _ = filepath.Abs(filepath.Join("testdata", "redis", "redis.conf")) +) +``` + +For local testing, you can change the variables to refer to your local files, or create a soft link +to the corresponding folder for redis-server and copy the config file to `testdata/redis/`: + +``` +ln -s /usr/bin/redis-server ./go-redis/testdata/redis/src +cp ./go-redis/testdata/redis.conf ./go-redis/testdata/redis/ +``` + +Lastly, run: + +``` +go test +``` + ## See also +- [Fast and flexible HTTP router](https://github.com/vmihailenco/treemux) - [Golang PostgreSQL ORM](https://github.com/go-pg/pg) - [Golang msgpack](https://github.com/vmihailenco/msgpack) - [Golang message task queue](https://github.com/vmihailenco/taskq) diff --git a/vendor/github.com/go-redis/redis/v8/cluster.go b/vendor/github.com/go-redis/redis/v8/cluster.go index a6ce5c584..2ce475c41 100644 --- a/vendor/github.com/go-redis/redis/v8/cluster.go +++ b/vendor/github.com/go-redis/redis/v8/cluster.go @@ -86,7 +86,7 @@ func (opt *ClusterOptions) init() { opt.MaxRedirects = 3 } - if (opt.RouteByLatency || opt.RouteRandomly) && opt.ClusterSlots == nil { + if opt.RouteByLatency || opt.RouteRandomly { opt.ReadOnly = true } @@ -153,9 +153,13 @@ func (opt *ClusterOptions) clientOptions() *Options { IdleTimeout: opt.IdleTimeout, IdleCheckFrequency: disableIdleCheck, - readOnly: opt.ReadOnly, - TLSConfig: opt.TLSConfig, + // If ClusterSlots is populated, then we probably have an artificial + // cluster whose nodes are not in clustering mode (otherwise there isn't + // much use for ClusterSlots config). This means we cannot execute the + // READONLY command against that node -- setting readOnly to false in such + // situations in the options below will prevent that from happening. + readOnly: opt.ReadOnly && opt.ClusterSlots == nil, } } @@ -1252,10 +1256,13 @@ func (c *ClusterClient) TxPipelined(ctx context.Context, fn func(Pipeliner) erro } func (c *ClusterClient) processTxPipeline(ctx context.Context, cmds []Cmder) error { - return c.hooks.processPipeline(ctx, cmds, c._processTxPipeline) + return c.hooks.processTxPipeline(ctx, cmds, c._processTxPipeline) } func (c *ClusterClient) _processTxPipeline(ctx context.Context, cmds []Cmder) error { + // Trim multi .. exec. + cmds = cmds[1 : len(cmds)-1] + state, err := c.state.Get(ctx) if err != nil { setCmdsErr(cmds, err) @@ -1291,6 +1298,7 @@ func (c *ClusterClient) _processTxPipeline(ctx context.Context, cmds []Cmder) er if err == nil { return } + if attempt < c.opt.MaxRedirects { if err := c.mapCmdsByNode(ctx, failedCmds, cmds); err != nil { setCmdsErr(cmds, err) @@ -1631,7 +1639,7 @@ func (c *ClusterClient) cmdNode( return nil, err } - if (c.opt.RouteByLatency || c.opt.RouteRandomly) && cmdInfo != nil && cmdInfo.ReadOnly { + if c.opt.ReadOnly && cmdInfo != nil && cmdInfo.ReadOnly { return c.slotReadOnlyNode(state, slot) } return state.slotMasterNode(slot) @@ -1655,6 +1663,35 @@ func (c *ClusterClient) slotMasterNode(ctx context.Context, slot int) (*clusterN return state.slotMasterNode(slot) } +// SlaveForKey gets a client for a replica node to run any command on it. +// This is especially useful if we want to run a particular lua script which has +// only read only commands on the replica. +// This is because other redis commands generally have a flag that points that +// they are read only and automatically run on the replica nodes +// if ClusterOptions.ReadOnly flag is set to true. +func (c *ClusterClient) SlaveForKey(ctx context.Context, key string) (*Client, error) { + state, err := c.state.Get(ctx) + if err != nil { + return nil, err + } + slot := hashtag.Slot(key) + node, err := c.slotReadOnlyNode(state, slot) + if err != nil { + return nil, err + } + return node.Client, err +} + +// MasterForKey return a client to the master node for a particular key. +func (c *ClusterClient) MasterForKey(ctx context.Context, key string) (*Client, error) { + slot := hashtag.Slot(key) + node, err := c.slotMasterNode(ctx, slot) + if err != nil { + return nil, err + } + return node.Client, err +} + func appendUniqueNode(nodes []*clusterNode, node *clusterNode) []*clusterNode { for _, n := range nodes { if n == node { diff --git a/vendor/github.com/go-redis/redis/v8/command.go b/vendor/github.com/go-redis/redis/v8/command.go index 5dd553325..6ca06344b 100644 --- a/vendor/github.com/go-redis/redis/v8/command.go +++ b/vendor/github.com/go-redis/redis/v8/command.go @@ -8,6 +8,7 @@ import ( "time" "github.com/go-redis/redis/v8/internal" + "github.com/go-redis/redis/v8/internal/hscan" "github.com/go-redis/redis/v8/internal/proto" "github.com/go-redis/redis/v8/internal/util" ) @@ -371,6 +372,26 @@ func (cmd *SliceCmd) String() string { return cmdString(cmd, cmd.val) } +// Scan scans the results from the map into a destination struct. The map keys +// are matched in the Redis struct fields by the `redis:"field"` tag. +func (cmd *SliceCmd) Scan(dst interface{}) error { + if cmd.err != nil { + return cmd.err + } + + // Pass the list of keys and values. + // Skip the first two args for: HMGET key + var args []interface{} + if cmd.args[0] == "hmget" { + args = cmd.args[2:] + } else { + // Otherwise, it's: MGET field field ... + args = cmd.args[1:] + } + + return hscan.Scan(dst, args, cmd.val) +} + func (cmd *SliceCmd) readReply(rd *proto.Reader) error { v, err := rd.ReadArrayReply(sliceParser) if err != nil { @@ -917,6 +938,27 @@ func (cmd *StringStringMapCmd) String() string { return cmdString(cmd, cmd.val) } +// Scan scans the results from the map into a destination struct. The map keys +// are matched in the Redis struct fields by the `redis:"field"` tag. +func (cmd *StringStringMapCmd) Scan(dst interface{}) error { + if cmd.err != nil { + return cmd.err + } + + strct, err := hscan.Struct(dst) + if err != nil { + return err + } + + for k, v := range cmd.val { + if err := strct.Scan(k, v); err != nil { + return err + } + } + + return nil +} + func (cmd *StringStringMapCmd) readReply(rd *proto.Reader) error { _, err := rd.ReadArrayReply(func(rd *proto.Reader, n int64) (interface{}, error) { cmd.val = make(map[string]string, n/2) @@ -1403,6 +1445,103 @@ func (cmd *XPendingExtCmd) readReply(rd *proto.Reader) error { //------------------------------------------------------------------------------ +type XInfoConsumersCmd struct { + baseCmd + val []XInfoConsumer +} + +type XInfoConsumer struct { + Name string + Pending int64 + Idle int64 +} + +var _ Cmder = (*XInfoGroupsCmd)(nil) + +func NewXInfoConsumersCmd(ctx context.Context, stream string, group string) *XInfoConsumersCmd { + return &XInfoConsumersCmd{ + baseCmd: baseCmd{ + ctx: ctx, + args: []interface{}{"xinfo", "consumers", stream, group}, + }, + } +} + +func (cmd *XInfoConsumersCmd) Val() []XInfoConsumer { + return cmd.val +} + +func (cmd *XInfoConsumersCmd) Result() ([]XInfoConsumer, error) { + return cmd.val, cmd.err +} + +func (cmd *XInfoConsumersCmd) String() string { + return cmdString(cmd, cmd.val) +} + +func (cmd *XInfoConsumersCmd) readReply(rd *proto.Reader) error { + n, err := rd.ReadArrayLen() + if err != nil { + return err + } + + cmd.val = make([]XInfoConsumer, n) + + for i := 0; i < n; i++ { + cmd.val[i], err = readXConsumerInfo(rd) + if err != nil { + return err + } + } + + return nil +} + +func readXConsumerInfo(rd *proto.Reader) (XInfoConsumer, error) { + var consumer XInfoConsumer + + n, err := rd.ReadArrayLen() + if err != nil { + return consumer, err + } + if n != 6 { + return consumer, fmt.Errorf("redis: got %d elements in XINFO CONSUMERS reply, wanted 6", n) + } + + for i := 0; i < 3; i++ { + key, err := rd.ReadString() + if err != nil { + return consumer, err + } + + val, err := rd.ReadString() + if err != nil { + return consumer, err + } + + switch key { + case "name": + consumer.Name = val + case "pending": + consumer.Pending, err = strconv.ParseInt(val, 0, 64) + if err != nil { + return consumer, err + } + case "idle": + consumer.Idle, err = strconv.ParseInt(val, 0, 64) + if err != nil { + return consumer, err + } + default: + return consumer, fmt.Errorf("redis: unexpected content %s in XINFO CONSUMERS reply", key) + } + } + + return consumer, nil +} + +//------------------------------------------------------------------------------ + type XInfoGroupsCmd struct { baseCmd val []XInfoGroup diff --git a/vendor/github.com/go-redis/redis/v8/commands.go b/vendor/github.com/go-redis/redis/v8/commands.go index f4e6afc14..2acbd837d 100644 --- a/vendor/github.com/go-redis/redis/v8/commands.go +++ b/vendor/github.com/go-redis/redis/v8/commands.go @@ -124,6 +124,8 @@ type Cmdable interface { MSet(ctx context.Context, values ...interface{}) *StatusCmd MSetNX(ctx context.Context, values ...interface{}) *BoolCmd Set(ctx context.Context, key string, value interface{}, expiration time.Duration) *StatusCmd + SetArgs(ctx context.Context, key string, value interface{}, a SetArgs) *StatusCmd + SetEX(ctx context.Context, key string, value interface{}, expiration time.Duration) *StatusCmd SetNX(ctx context.Context, key string, value interface{}, expiration time.Duration) *BoolCmd SetXX(ctx context.Context, key string, value interface{}, expiration time.Duration) *BoolCmd SetRange(ctx context.Context, key string, offset int64, value string) *IntCmd @@ -140,6 +142,7 @@ type Cmdable interface { BitField(ctx context.Context, key string, args ...interface{}) *IntSliceCmd Scan(ctx context.Context, cursor uint64, match string, count int64) *ScanCmd + ScanType(ctx context.Context, cursor uint64, match string, count int64, keyType string) *ScanCmd SScan(ctx context.Context, key string, cursor uint64, match string, count int64) *ScanCmd HScan(ctx context.Context, key string, cursor uint64, match string, count int64) *ScanCmd ZScan(ctx context.Context, key string, cursor uint64, match string, count int64) *ScanCmd @@ -167,6 +170,8 @@ type Cmdable interface { LInsertAfter(ctx context.Context, key string, pivot, value interface{}) *IntCmd LLen(ctx context.Context, key string) *IntCmd LPop(ctx context.Context, key string) *StringCmd + LPos(ctx context.Context, key string, value string, args LPosArgs) *IntCmd + LPosCount(ctx context.Context, key string, value string, count int64, args LPosArgs) *IntSliceCmd LPush(ctx context.Context, key string, values ...interface{}) *IntCmd LPushX(ctx context.Context, key string, values ...interface{}) *IntCmd LRange(ctx context.Context, key string, start, stop int64) *StringSliceCmd @@ -784,6 +789,63 @@ func (c cmdable) Set(ctx context.Context, key string, value interface{}, expirat return cmd } +// SetArgs provides arguments for the SetArgs function. +type SetArgs struct { + // Mode can be `NX` or `XX` or empty. + Mode string + + // Zero `TTL` or `Expiration` means that the key has no expiration time. + TTL time.Duration + ExpireAt time.Time + + // When Get is true, the command returns the old value stored at key, or nil when key did not exist. + Get bool + + // KeepTTL is a Redis KEEPTTL option to keep existing TTL. + KeepTTL bool +} + +// SetArgs supports all the options that the SET command supports. +// It is the alternative to the Set function when you want +// to have more control over the options. +func (c cmdable) SetArgs(ctx context.Context, key string, value interface{}, a SetArgs) *StatusCmd { + args := []interface{}{"set", key, value} + + if a.KeepTTL { + args = append(args, "keepttl") + } + + if !a.ExpireAt.IsZero() { + args = append(args, "exat", a.ExpireAt.Unix()) + } + if a.TTL > 0 { + if usePrecise(a.TTL) { + args = append(args, "px", formatMs(ctx, a.TTL)) + } else { + args = append(args, "ex", formatSec(ctx, a.TTL)) + } + } + + if a.Mode != "" { + args = append(args, a.Mode) + } + + if a.Get { + args = append(args, "get") + } + + cmd := NewStatusCmd(ctx, args...) + _ = c(ctx, cmd) + return cmd +} + +// Redis `SETEX key expiration value` command. +func (c cmdable) SetEX(ctx context.Context, key string, value interface{}, expiration time.Duration) *StatusCmd { + cmd := NewStatusCmd(ctx, "setex", key, formatSec(ctx, expiration), value) + _ = c(ctx, cmd) + return cmd +} + // Redis `SET key value [expiration] NX` command. // // Zero expiration means the key has no expiration time. @@ -955,6 +1017,22 @@ func (c cmdable) Scan(ctx context.Context, cursor uint64, match string, count in return cmd } +func (c cmdable) ScanType(ctx context.Context, cursor uint64, match string, count int64, keyType string) *ScanCmd { + args := []interface{}{"scan", cursor} + if match != "" { + args = append(args, "match", match) + } + if count > 0 { + args = append(args, "count", count) + } + if keyType != "" { + args = append(args, "type", keyType) + } + cmd := NewScanCmd(ctx, c, args...) + _ = c(ctx, cmd) + return cmd +} + func (c cmdable) SScan(ctx context.Context, key string, cursor uint64, match string, count int64) *ScanCmd { args := []interface{}{"sscan", key, cursor} if match != "" { @@ -1180,6 +1258,37 @@ func (c cmdable) LPop(ctx context.Context, key string) *StringCmd { return cmd } +type LPosArgs struct { + Rank, MaxLen int64 +} + +func (c cmdable) LPos(ctx context.Context, key string, value string, a LPosArgs) *IntCmd { + args := []interface{}{"lpos", key, value} + if a.Rank != 0 { + args = append(args, "rank", a.Rank) + } + if a.MaxLen != 0 { + args = append(args, "maxlen", a.MaxLen) + } + + cmd := NewIntCmd(ctx, args...) + _ = c(ctx, cmd) + return cmd +} + +func (c cmdable) LPosCount(ctx context.Context, key string, value string, count int64, a LPosArgs) *IntSliceCmd { + args := []interface{}{"lpos", key, value, "count", count} + if a.Rank != 0 { + args = append(args, "rank", a.Rank) + } + if a.MaxLen != 0 { + args = append(args, "maxlen", a.MaxLen) + } + cmd := NewIntSliceCmd(ctx, args...) + _ = c(ctx, cmd) + return cmd +} + func (c cmdable) LPush(ctx context.Context, key string, values ...interface{}) *IntCmd { args := make([]interface{}, 2, 2+len(values)) args[0] = "lpush" @@ -1694,6 +1803,12 @@ func (c cmdable) XTrimApprox(ctx context.Context, key string, maxLen int64) *Int return cmd } +func (c cmdable) XInfoConsumers(ctx context.Context, key string, group string) *XInfoConsumersCmd { + cmd := NewXInfoConsumersCmd(ctx, key, group) + _ = c(ctx, cmd) + return cmd +} + func (c cmdable) XInfoGroups(ctx context.Context, key string) *XInfoGroupsCmd { cmd := NewXInfoGroupsCmd(ctx, key) _ = c(ctx, cmd) diff --git a/vendor/github.com/go-redis/redis/v8/error.go b/vendor/github.com/go-redis/redis/v8/error.go index d29c0c99f..2ed5dc628 100644 --- a/vendor/github.com/go-redis/redis/v8/error.go +++ b/vendor/github.com/go-redis/redis/v8/error.go @@ -52,6 +52,9 @@ func shouldRetry(err error, retryTimeout bool) bool { if strings.HasPrefix(s, "CLUSTERDOWN ") { return true } + if strings.HasPrefix(s, "TRYAGAIN ") { + return true + } return false } @@ -62,8 +65,11 @@ func isRedisError(err error) bool { } func isBadConn(err error, allowTimeout bool) bool { - if err == nil { + switch err { + case nil: return false + case context.Canceled, context.DeadlineExceeded: + return true } if isRedisError(err) { diff --git a/vendor/github.com/go-redis/redis/v8/go.mod b/vendor/github.com/go-redis/redis/v8/go.mod index 21c0bb85b..ebb78e77f 100644 --- a/vendor/github.com/go-redis/redis/v8/go.mod +++ b/vendor/github.com/go-redis/redis/v8/go.mod @@ -1,11 +1,13 @@ module github.com/go-redis/redis/v8 -go 1.11 +go 1.13 require ( github.com/cespare/xxhash/v2 v2.1.1 github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f - github.com/onsi/ginkgo v1.14.1 - github.com/onsi/gomega v1.10.2 - go.opentelemetry.io/otel v0.11.0 + github.com/onsi/ginkgo v1.15.0 + github.com/onsi/gomega v1.10.5 + go.opentelemetry.io/otel v0.18.0 + go.opentelemetry.io/otel/metric v0.18.0 + go.opentelemetry.io/otel/trace v0.18.0 ) diff --git a/vendor/github.com/go-redis/redis/v8/go.sum b/vendor/github.com/go-redis/redis/v8/go.sum index 82fcc1683..cc26ed7b7 100644 --- a/vendor/github.com/go-redis/redis/v8/go.sum +++ b/vendor/github.com/go-redis/redis/v8/go.sum @@ -18,45 +18,68 @@ github.com/golang/protobuf v1.4.2/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= -github.com/google/go-cmp v0.5.1 h1:JFrFEBb2xKufg6XkJsJr+WbKb4FQlURi5RUcBveYu9k= -github.com/google/go-cmp v0.5.1/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.5.4 h1:L8R9j+yAqZuZjsqh/z+F1NCffTKKLShY6zXTItVIZ8M= +github.com/google/go-cmp v0.5.4/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU= github.com/nxadm/tail v1.4.4 h1:DQuhQpB1tVlglWS2hLQ5OV6B5r8aGxSrPc5Qo6uTN78= github.com/nxadm/tail v1.4.4/go.mod h1:kenIhsEOeOJmVchQTgglprH7qJGnHDVpk1VPCcaMI8A= github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= github.com/onsi/ginkgo v1.12.1/go.mod h1:zj2OWP4+oCPe1qIXoGWkgMRwljMUYCdkwsT2108oapk= -github.com/onsi/ginkgo v1.14.1 h1:jMU0WaQrP0a/YAEq8eJmJKjBoMs+pClEr1vDMlM/Do4= -github.com/onsi/ginkgo v1.14.1/go.mod h1:iSB4RoI2tjJc9BBv4NKIKWKya62Rps+oPG/Lv9klQyY= +github.com/onsi/ginkgo v1.15.0 h1:1V1NfVQR87RtWAgp1lv9JZJ5Jap+XFGKPi00andXGi4= +github.com/onsi/ginkgo v1.15.0/go.mod h1:hF8qUzuuC8DJGygJH3726JnCZX4MYbRB8yFfISqnKUg= github.com/onsi/gomega v1.7.1/go.mod h1:XdKZgCCFLUoM/7CFJVPcG8C1xQ1AJ0vpAezJrB7JYyY= github.com/onsi/gomega v1.10.1/go.mod h1:iN09h71vgCQne3DLsj+A5owkum+a2tYe+TOCB1ybHNo= -github.com/onsi/gomega v1.10.2 h1:aY/nuoWlKJud2J6U0E3NWsjlg+0GtwXxgEqthRdzlcs= -github.com/onsi/gomega v1.10.2/go.mod h1:iN09h71vgCQne3DLsj+A5owkum+a2tYe+TOCB1ybHNo= +github.com/onsi/gomega v1.10.5 h1:7n6FEkpFmfCoo2t+YYqXH0evK+a9ICQz0xcAy9dYcaQ= +github.com/onsi/gomega v1.10.5/go.mod h1:gza4q3jKQJijlu05nKWRCW/GavJumGt8aNRxWg7mt48= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= -github.com/stretchr/testify v1.6.1 h1:hDPOHmpOpP40lSULcqw7IrRb/u7w6RpDC9399XyoNd0= -github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= -go.opentelemetry.io/otel v0.11.0 h1:IN2tzQa9Gc4ZVKnTaMbPVcHjvzOdg5n9QfnmlqiET7E= -go.opentelemetry.io/otel v0.11.0/go.mod h1:G8UCk+KooF2HLkgo8RHX9epABH/aRGYET7gQOqBVdB0= +github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY= +github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= +go.opentelemetry.io/otel v0.18.0 h1:d5Of7+Zw4ANFOJB+TIn2K3QWsgS2Ht7OU9DqZHI6qu8= +go.opentelemetry.io/otel v0.18.0/go.mod h1:PT5zQj4lTsR1YeARt8YNKcFb88/c2IKoSABK9mX0r78= +go.opentelemetry.io/otel/metric v0.18.0 h1:yuZCmY9e1ZTaMlZXLrrbAPmYW6tW1A5ozOZeOYGaTaY= +go.opentelemetry.io/otel/metric v0.18.0/go.mod h1:kEH2QtzAyBy3xDVQfGZKIcok4ZZFvd5xyKPfPcuK6pE= +go.opentelemetry.io/otel/oteltest v0.18.0 h1:FbKDFm/LnQDOHuGjED+fy3s5YMVg0z019GJ9Er66hYo= +go.opentelemetry.io/otel/oteltest v0.18.0/go.mod h1:NyierCU3/G8DLTva7KRzGii2fdxdR89zXKH1bNWY7Bo= +go.opentelemetry.io/otel/trace v0.18.0 h1:ilCfc/fptVKaDMK1vWk0elxpolurJbEgey9J6g6s+wk= +go.opentelemetry.io/otel/trace v0.18.0/go.mod h1:FzdUu3BPwZSZebfQ1vl5/tAa8LyMLXSJN57AXIt/iDk= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= +golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= +golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= -golang.org/x/net v0.0.0-20200520004742-59133d7f0dd7 h1:AeiKBIuRw3UomYXSbLy0Mc2dDLfdtbT/IVn4keq83P0= +golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20200520004742-59133d7f0dd7/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= +golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= +golang.org/x/net v0.0.0-20201202161906-c7110b5ffcbb h1:eBmm0M9fYhWpKZLjQUUKka/LtIxf46G4fxeEz5KJr9U= +golang.org/x/net v0.0.0-20201202161906-c7110b5ffcbb/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190904154756-749cb33beabd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20191005200804-aed5e4c7ecf9/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20191120155948-bd437916bb0e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200519105757-fe76b779f299 h1:DYfZAGf2WMFjMxbgTjaC+2HC7NkNAQs+6Q8b9WEB/F4= -golang.org/x/sys v0.0.0-20200519105757-fe76b779f299/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210112080510-489259a85091 h1:DMyOG0U+gKfu8JZzg2UQe9MeaC1X+xQWlAKcRnjxjCw= +golang.org/x/sys v0.0.0-20210112080510-489259a85091/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= -golang.org/x/text v0.3.2 h1:tW2bmiBqwgJj/UpqtC8EpXEZVYOwU0yG4iWbprSVAcs= -golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= +golang.org/x/text v0.3.3 h1:cokOdA+Jmi5PJGXLlLllQSgYigAEfHXJAERHVMaCc2k= +golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= -golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543 h1:E7g+9GITq07hpfrRu66IVDexMakfv52eLZ2CXBWiKr4= +golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20201224043029-2b0845dc783e/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= +golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 h1:go1bK/D/BFZV2I8cIQd1NKEZ+0owSTG1fDTci4IqFcE= +golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8= google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0= google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM= diff --git a/vendor/github.com/go-redis/redis/v8/internal/arg.go b/vendor/github.com/go-redis/redis/v8/internal/arg.go index 4f683393d..b97fa0d68 100644 --- a/vendor/github.com/go-redis/redis/v8/internal/arg.go +++ b/vendor/github.com/go-redis/redis/v8/internal/arg.go @@ -1,7 +1,6 @@ package internal import ( - "encoding/hex" "fmt" "strconv" "time" @@ -52,96 +51,6 @@ func AppendArg(b []byte, v interface{}) []byte { } func appendUTF8String(dst []byte, src []byte) []byte { - if isSimple(src) { - dst = append(dst, src...) - return dst - } - - s := len(dst) - dst = append(dst, make([]byte, hex.EncodedLen(len(src)))...) - hex.Encode(dst[s:], src) + dst = append(dst, src...) return dst } - -func isSimple(b []byte) bool { - for _, c := range b { - if !isSimpleByte(c) { - return false - } - } - return true -} - -func isSimpleByte(c byte) bool { - return simple[c] -} - -var simple = [256]bool{ - '-': true, - '_': true, - - '0': true, - '1': true, - '2': true, - '3': true, - '4': true, - '5': true, - '6': true, - '7': true, - '8': true, - '9': true, - - 'a': true, - 'b': true, - 'c': true, - 'd': true, - 'e': true, - 'f': true, - 'g': true, - 'h': true, - 'i': true, - 'j': true, - 'k': true, - 'l': true, - 'm': true, - 'n': true, - 'o': true, - 'p': true, - 'q': true, - 'r': true, - 's': true, - 't': true, - 'u': true, - 'v': true, - 'w': true, - 'x': true, - 'y': true, - 'z': true, - - 'A': true, - 'B': true, - 'C': true, - 'D': true, - 'E': true, - 'F': true, - 'G': true, - 'H': true, - 'I': true, - 'J': true, - 'K': true, - 'L': true, - 'M': true, - 'N': true, - 'O': true, - 'P': true, - 'Q': true, - 'R': true, - 'S': true, - 'T': true, - 'U': true, - 'V': true, - 'W': true, - 'X': true, - 'Y': true, - 'Z': true, -} diff --git a/vendor/github.com/go-redis/redis/v8/internal/hscan/hscan.go b/vendor/github.com/go-redis/redis/v8/internal/hscan/hscan.go new file mode 100644 index 000000000..6f97f9287 --- /dev/null +++ b/vendor/github.com/go-redis/redis/v8/internal/hscan/hscan.go @@ -0,0 +1,201 @@ +package hscan + +import ( + "errors" + "fmt" + "reflect" + "strconv" +) + +// decoderFunc represents decoding functions for default built-in types. +type decoderFunc func(reflect.Value, string) error + +var ( + // List of built-in decoders indexed by their numeric constant values (eg: reflect.Bool = 1). + decoders = []decoderFunc{ + reflect.Bool: decodeBool, + reflect.Int: decodeInt, + reflect.Int8: decodeInt8, + reflect.Int16: decodeInt16, + reflect.Int32: decodeInt32, + reflect.Int64: decodeInt64, + reflect.Uint: decodeUint, + reflect.Uint8: decodeUint8, + reflect.Uint16: decodeUint16, + reflect.Uint32: decodeUint32, + reflect.Uint64: decodeUint64, + reflect.Float32: decodeFloat32, + reflect.Float64: decodeFloat64, + reflect.Complex64: decodeUnsupported, + reflect.Complex128: decodeUnsupported, + reflect.Array: decodeUnsupported, + reflect.Chan: decodeUnsupported, + reflect.Func: decodeUnsupported, + reflect.Interface: decodeUnsupported, + reflect.Map: decodeUnsupported, + reflect.Ptr: decodeUnsupported, + reflect.Slice: decodeSlice, + reflect.String: decodeString, + reflect.Struct: decodeUnsupported, + reflect.UnsafePointer: decodeUnsupported, + } + + // Global map of struct field specs that is populated once for every new + // struct type that is scanned. This caches the field types and the corresponding + // decoder functions to avoid iterating through struct fields on subsequent scans. + globalStructMap = newStructMap() +) + +func Struct(dst interface{}) (StructValue, error) { + v := reflect.ValueOf(dst) + + // The dstination to scan into should be a struct pointer. + if v.Kind() != reflect.Ptr || v.IsNil() { + return StructValue{}, fmt.Errorf("redis.Scan(non-pointer %T)", dst) + } + + v = v.Elem() + if v.Kind() != reflect.Struct { + return StructValue{}, fmt.Errorf("redis.Scan(non-struct %T)", dst) + } + + return StructValue{ + spec: globalStructMap.get(v.Type()), + value: v, + }, nil +} + +// Scan scans the results from a key-value Redis map result set to a destination struct. +// The Redis keys are matched to the struct's field with the `redis` tag. +func Scan(dst interface{}, keys []interface{}, vals []interface{}) error { + if len(keys) != len(vals) { + return errors.New("args should have the same number of keys and vals") + } + + strct, err := Struct(dst) + if err != nil { + return err + } + + // Iterate through the (key, value) sequence. + for i := 0; i < len(vals); i++ { + key, ok := keys[i].(string) + if !ok { + continue + } + + val, ok := vals[i].(string) + if !ok { + continue + } + + if err := strct.Scan(key, val); err != nil { + return err + } + } + + return nil +} + +func decodeBool(f reflect.Value, s string) error { + b, err := strconv.ParseBool(s) + if err != nil { + return err + } + f.SetBool(b) + return nil +} + +func decodeInt8(f reflect.Value, s string) error { + return decodeNumber(f, s, 8) +} + +func decodeInt16(f reflect.Value, s string) error { + return decodeNumber(f, s, 16) +} + +func decodeInt32(f reflect.Value, s string) error { + return decodeNumber(f, s, 32) +} + +func decodeInt64(f reflect.Value, s string) error { + return decodeNumber(f, s, 64) +} + +func decodeInt(f reflect.Value, s string) error { + return decodeNumber(f, s, 0) +} + +func decodeNumber(f reflect.Value, s string, bitSize int) error { + v, err := strconv.ParseInt(s, 10, bitSize) + if err != nil { + return err + } + f.SetInt(v) + return nil +} + +func decodeUint8(f reflect.Value, s string) error { + return decodeUnsignedNumber(f, s, 8) +} + +func decodeUint16(f reflect.Value, s string) error { + return decodeUnsignedNumber(f, s, 16) +} + +func decodeUint32(f reflect.Value, s string) error { + return decodeUnsignedNumber(f, s, 32) +} + +func decodeUint64(f reflect.Value, s string) error { + return decodeUnsignedNumber(f, s, 64) +} + +func decodeUint(f reflect.Value, s string) error { + return decodeUnsignedNumber(f, s, 0) +} + +func decodeUnsignedNumber(f reflect.Value, s string, bitSize int) error { + v, err := strconv.ParseUint(s, 10, bitSize) + if err != nil { + return err + } + f.SetUint(v) + return nil +} + +func decodeFloat32(f reflect.Value, s string) error { + v, err := strconv.ParseFloat(s, 32) + if err != nil { + return err + } + f.SetFloat(v) + return nil +} + +// although the default is float64, but we better define it. +func decodeFloat64(f reflect.Value, s string) error { + v, err := strconv.ParseFloat(s, 64) + if err != nil { + return err + } + f.SetFloat(v) + return nil +} + +func decodeString(f reflect.Value, s string) error { + f.SetString(s) + return nil +} + +func decodeSlice(f reflect.Value, s string) error { + // []byte slice ([]uint8). + if f.Type().Elem().Kind() == reflect.Uint8 { + f.SetBytes([]byte(s)) + } + return nil +} + +func decodeUnsupported(v reflect.Value, s string) error { + return fmt.Errorf("redis.Scan(unsupported %s)", v.Type()) +} diff --git a/vendor/github.com/go-redis/redis/v8/internal/hscan/structmap.go b/vendor/github.com/go-redis/redis/v8/internal/hscan/structmap.go new file mode 100644 index 000000000..1b233258d --- /dev/null +++ b/vendor/github.com/go-redis/redis/v8/internal/hscan/structmap.go @@ -0,0 +1,93 @@ +package hscan + +import ( + "fmt" + "reflect" + "strings" + "sync" +) + +// structMap contains the map of struct fields for target structs +// indexed by the struct type. +type structMap struct { + m sync.Map +} + +func newStructMap() *structMap { + return new(structMap) +} + +func (s *structMap) get(t reflect.Type) *structSpec { + if v, ok := s.m.Load(t); ok { + return v.(*structSpec) + } + + spec := newStructSpec(t, "redis") + s.m.Store(t, spec) + return spec +} + +//------------------------------------------------------------------------------ + +// structSpec contains the list of all fields in a target struct. +type structSpec struct { + m map[string]*structField +} + +func (s *structSpec) set(tag string, sf *structField) { + s.m[tag] = sf +} + +func newStructSpec(t reflect.Type, fieldTag string) *structSpec { + out := &structSpec{ + m: make(map[string]*structField), + } + + num := t.NumField() + for i := 0; i < num; i++ { + f := t.Field(i) + + tag := f.Tag.Get(fieldTag) + if tag == "" || tag == "-" { + continue + } + + tag = strings.Split(tag, ",")[0] + if tag == "" { + continue + } + + // Use the built-in decoder. + out.set(tag, &structField{index: i, fn: decoders[f.Type.Kind()]}) + } + + return out +} + +//------------------------------------------------------------------------------ + +// structField represents a single field in a target struct. +type structField struct { + index int + fn decoderFunc +} + +//------------------------------------------------------------------------------ + +type StructValue struct { + spec *structSpec + value reflect.Value +} + +func (s StructValue) Scan(key string, value string) error { + field, ok := s.spec.m[key] + if !ok { + return nil + } + if err := field.fn(s.value.Field(field.index), value); err != nil { + t := s.value.Type() + return fmt.Errorf("cannot scan redis.result %s into struct field %s.%s of type %s, error-%s", + value, t.Name(), t.Field(field.index).Name, t.Field(field.index).Type, err.Error()) + } + return nil +} diff --git a/vendor/github.com/go-redis/redis/v8/internal/instruments.go b/vendor/github.com/go-redis/redis/v8/internal/instruments.go index e837526d8..49d6111e1 100644 --- a/vendor/github.com/go-redis/redis/v8/internal/instruments.go +++ b/vendor/github.com/go-redis/redis/v8/internal/instruments.go @@ -3,8 +3,8 @@ package internal import ( "context" - "go.opentelemetry.io/otel/api/global" - "go.opentelemetry.io/otel/api/metric" + "go.opentelemetry.io/otel/metric" + "go.opentelemetry.io/otel/metric/global" ) var ( diff --git a/vendor/github.com/go-redis/redis/v8/internal/internal.go b/vendor/github.com/go-redis/redis/v8/internal/internal.go index 735d6affd..4a59c599b 100644 --- a/vendor/github.com/go-redis/redis/v8/internal/internal.go +++ b/vendor/github.com/go-redis/redis/v8/internal/internal.go @@ -15,6 +15,10 @@ func RetryBackoff(retry int, minBackoff, maxBackoff time.Duration) time.Duration } d := minBackoff << uint(retry) + if d < minBackoff { + return maxBackoff + } + d = minBackoff + time.Duration(rand.Int63n(int64(d))) if d > maxBackoff || d < minBackoff { diff --git a/vendor/github.com/go-redis/redis/v8/internal/pool/conn.go b/vendor/github.com/go-redis/redis/v8/internal/pool/conn.go index 9c243c64e..b78453043 100644 --- a/vendor/github.com/go-redis/redis/v8/internal/pool/conn.go +++ b/vendor/github.com/go-redis/redis/v8/internal/pool/conn.go @@ -9,6 +9,7 @@ import ( "github.com/go-redis/redis/v8/internal" "github.com/go-redis/redis/v8/internal/proto" + "go.opentelemetry.io/otel/trace" ) var noDeadline = time.Time{} @@ -58,16 +59,19 @@ func (cn *Conn) Write(b []byte) (int, error) { } func (cn *Conn) RemoteAddr() net.Addr { - return cn.netConn.RemoteAddr() + if cn.netConn != nil { + return cn.netConn.RemoteAddr() + } + return nil } func (cn *Conn) WithReader(ctx context.Context, timeout time.Duration, fn func(rd *proto.Reader) error) error { - return internal.WithSpan(ctx, "with_reader", func(ctx context.Context) error { + return internal.WithSpan(ctx, "redis.with_reader", func(ctx context.Context, span trace.Span) error { if err := cn.netConn.SetReadDeadline(cn.deadline(ctx, timeout)); err != nil { - return internal.RecordError(ctx, err) + return internal.RecordError(ctx, span, err) } if err := fn(cn.rd); err != nil { - return internal.RecordError(ctx, err) + return internal.RecordError(ctx, span, err) } return nil }) @@ -76,9 +80,9 @@ func (cn *Conn) WithReader(ctx context.Context, timeout time.Duration, fn func(r func (cn *Conn) WithWriter( ctx context.Context, timeout time.Duration, fn func(wr *proto.Writer) error, ) error { - return internal.WithSpan(ctx, "with_writer", func(ctx context.Context) error { + return internal.WithSpan(ctx, "redis.with_writer", func(ctx context.Context, span trace.Span) error { if err := cn.netConn.SetWriteDeadline(cn.deadline(ctx, timeout)); err != nil { - return internal.RecordError(ctx, err) + return internal.RecordError(ctx, span, err) } if cn.bw.Buffered() > 0 { @@ -86,11 +90,11 @@ func (cn *Conn) WithWriter( } if err := fn(cn.wr); err != nil { - return internal.RecordError(ctx, err) + return internal.RecordError(ctx, span, err) } if err := cn.bw.Flush(); err != nil { - return internal.RecordError(ctx, err) + return internal.RecordError(ctx, span, err) } internal.WritesCounter.Add(ctx, 1) diff --git a/vendor/github.com/go-redis/redis/v8/internal/pool/pool.go b/vendor/github.com/go-redis/redis/v8/internal/pool/pool.go index 355742bf3..254a18de5 100644 --- a/vendor/github.com/go-redis/redis/v8/internal/pool/pool.go +++ b/vendor/github.com/go-redis/redis/v8/internal/pool/pool.go @@ -477,6 +477,7 @@ func (p *ConnPool) ReapStaleConns() (int, error) { p.connsMu.Lock() cn := p.reapStaleConn() p.connsMu.Unlock() + p.freeTurn() if cn != nil { diff --git a/vendor/github.com/go-redis/redis/v8/internal/proto/reader.go b/vendor/github.com/go-redis/redis/v8/internal/proto/reader.go index d9e6c1202..0fbc51e9a 100644 --- a/vendor/github.com/go-redis/redis/v8/internal/proto/reader.go +++ b/vendor/github.com/go-redis/redis/v8/internal/proto/reader.go @@ -71,13 +71,25 @@ func (r *Reader) ReadLine() ([]byte, error) { func (r *Reader) readLine() ([]byte, error) { b, err := r.rd.ReadSlice('\n') if err != nil { - return nil, err + if err != bufio.ErrBufferFull { + return nil, err + } + + full := make([]byte, len(b)) + copy(full, b) + + b, err = r.rd.ReadBytes('\n') + if err != nil { + return nil, err + } + + full = append(full, b...) + b = full } if len(b) <= 2 || b[len(b)-1] != '\n' || b[len(b)-2] != '\r' { return nil, fmt.Errorf("redis: invalid reply: %q", b) } - b = b[:len(b)-2] - return b, nil + return b[:len(b)-2], nil } func (r *Reader) ReadReply(m MultiBulkParse) (interface{}, error) { diff --git a/vendor/github.com/go-redis/redis/v8/internal/proto/scan.go b/vendor/github.com/go-redis/redis/v8/internal/proto/scan.go index 8fa032317..c2c3ed17d 100644 --- a/vendor/github.com/go-redis/redis/v8/internal/proto/scan.go +++ b/vendor/github.com/go-redis/redis/v8/internal/proto/scan.go @@ -4,10 +4,13 @@ import ( "encoding" "fmt" "reflect" + "time" "github.com/go-redis/redis/v8/internal/util" ) +// Scan parses bytes `b` to `v` with appropriate type. +// nolint: gocyclo func Scan(b []byte, v interface{}) error { switch v := v.(type) { case nil: @@ -99,6 +102,10 @@ func Scan(b []byte, v interface{}) error { case *bool: *v = len(b) == 1 && b[0] == '1' return nil + case *time.Time: + var err error + *v, err = time.Parse(time.RFC3339Nano, util.BytesToString(b)) + return err case encoding.BinaryUnmarshaler: return v.UnmarshalBinary(b) default: @@ -124,7 +131,7 @@ func ScanSlice(data []string, slice interface{}) error { for i, s := range data { elem := next() if err := Scan([]byte(s), elem.Addr().Interface()); err != nil { - err = fmt.Errorf("redis: ScanSlice index=%d value=%q failed: %s", i, s, err) + err = fmt.Errorf("redis: ScanSlice index=%d value=%q failed: %w", i, s, err) return err } } diff --git a/vendor/github.com/go-redis/redis/v8/internal/rand/rand.go b/vendor/github.com/go-redis/redis/v8/internal/rand/rand.go index 40676f3cb..2edccba94 100644 --- a/vendor/github.com/go-redis/redis/v8/internal/rand/rand.go +++ b/vendor/github.com/go-redis/redis/v8/internal/rand/rand.go @@ -43,3 +43,8 @@ func (s *source) Seed(seed int64) { s.src.Seed(seed) s.mu.Unlock() } + +// Shuffle pseudo-randomizes the order of elements. +// n is the number of elements. +// swap swaps the elements with indexes i and j. +func Shuffle(n int, swap func(i, j int)) { pseudo.Shuffle(n, swap) } diff --git a/vendor/github.com/go-redis/redis/v8/internal/util.go b/vendor/github.com/go-redis/redis/v8/internal/util.go index 710bfe14c..4d7921bf3 100644 --- a/vendor/github.com/go-redis/redis/v8/internal/util.go +++ b/vendor/github.com/go-redis/redis/v8/internal/util.go @@ -6,12 +6,12 @@ import ( "github.com/go-redis/redis/v8/internal/proto" "github.com/go-redis/redis/v8/internal/util" - "go.opentelemetry.io/otel/api/global" - "go.opentelemetry.io/otel/api/trace" + "go.opentelemetry.io/otel" + "go.opentelemetry.io/otel/trace" ) func Sleep(ctx context.Context, dur time.Duration) error { - return WithSpan(ctx, "sleep", func(ctx context.Context) error { + return WithSpan(ctx, "time.Sleep", func(ctx context.Context, span trace.Span) error { t := time.NewTimer(dur) defer t.Stop() @@ -50,32 +50,24 @@ func isLower(s string) bool { return true } -func Unwrap(err error) error { - u, ok := err.(interface { - Unwrap() error - }) - if !ok { - return nil - } - return u.Unwrap() -} - //------------------------------------------------------------------------------ -func WithSpan(ctx context.Context, name string, fn func(context.Context) error) error { - if !trace.SpanFromContext(ctx).IsRecording() { - return fn(ctx) +var tracer = otel.Tracer("github.com/go-redis/redis") + +func WithSpan(ctx context.Context, name string, fn func(context.Context, trace.Span) error) error { + if span := trace.SpanFromContext(ctx); !span.IsRecording() { + return fn(ctx, span) } - ctx, span := global.Tracer("github.com/go-redis/redis").Start(ctx, name) + ctx, span := tracer.Start(ctx, name) defer span.End() - return fn(ctx) + return fn(ctx, span) } -func RecordError(ctx context.Context, err error) error { +func RecordError(ctx context.Context, span trace.Span, err error) error { if err != proto.Nil { - trace.SpanFromContext(ctx).RecordError(ctx, err) + span.RecordError(err) } return err } diff --git a/vendor/github.com/go-redis/redis/v8/options.go b/vendor/github.com/go-redis/redis/v8/options.go index 373037c50..5d24d5317 100644 --- a/vendor/github.com/go-redis/redis/v8/options.go +++ b/vendor/github.com/go-redis/redis/v8/options.go @@ -14,8 +14,8 @@ import ( "github.com/go-redis/redis/v8/internal" "github.com/go-redis/redis/v8/internal/pool" - "go.opentelemetry.io/otel/api/trace" - "go.opentelemetry.io/otel/label" + "go.opentelemetry.io/otel/attribute" + "go.opentelemetry.io/otel/trace" ) // Limiter is the interface of a rate limiter or a circuit breaker. @@ -29,6 +29,7 @@ type Limiter interface { ReportResult(result error) } +// Options keeps the settings to setup redis connection. type Options struct { // The network type, either tcp or unix. // Default is tcp. @@ -57,7 +58,7 @@ type Options struct { DB int // Maximum number of retries before giving up. - // Default is 3 retries. + // Default is 3 retries; -1 (not 0) disables retries. MaxRetries int // Minimum backoff between each retry. // Default is 8 milliseconds; -1 disables backoff. @@ -187,26 +188,35 @@ func (opt *Options) clone() *Options { } // ParseURL parses an URL into Options that can be used to connect to Redis. +// Scheme is required. +// There are two connection types: by tcp socket and by unix socket. +// Tcp connection: +// redis://:@:/ +// Unix connection: +// unix://:@?db= func ParseURL(redisURL string) (*Options, error) { - o := &Options{Network: "tcp"} u, err := url.Parse(redisURL) if err != nil { return nil, err } - if u.Scheme != "redis" && u.Scheme != "rediss" { - return nil, errors.New("invalid redis URL scheme: " + u.Scheme) + switch u.Scheme { + case "redis", "rediss": + return setupTCPConn(u) + case "unix": + return setupUnixConn(u) + default: + return nil, fmt.Errorf("redis: invalid URL scheme: %s", u.Scheme) } +} - if u.User != nil { - o.Username = u.User.Username() - if p, ok := u.User.Password(); ok { - o.Password = p - } - } +func setupTCPConn(u *url.URL) (*Options, error) { + o := &Options{Network: "tcp"} + + o.Username, o.Password = getUserPassword(u) if len(u.Query()) > 0 { - return nil, errors.New("no options supported") + return nil, errors.New("redis: no options supported") } h, p, err := net.SplitHostPort(u.Host) @@ -229,31 +239,69 @@ func ParseURL(redisURL string) (*Options, error) { o.DB = 0 case 1: if o.DB, err = strconv.Atoi(f[0]); err != nil { - return nil, fmt.Errorf("invalid redis database number: %q", f[0]) + return nil, fmt.Errorf("redis: invalid database number: %q", f[0]) } default: - return nil, errors.New("invalid redis URL path: " + u.Path) + return nil, fmt.Errorf("redis: invalid URL path: %s", u.Path) } if u.Scheme == "rediss" { o.TLSConfig = &tls.Config{ServerName: h} } + + return o, nil +} + +func setupUnixConn(u *url.URL) (*Options, error) { + o := &Options{ + Network: "unix", + } + + if strings.TrimSpace(u.Path) == "" { // path is required with unix connection + return nil, errors.New("redis: empty unix socket path") + } + o.Addr = u.Path + + o.Username, o.Password = getUserPassword(u) + + dbStr := u.Query().Get("db") + if dbStr == "" { + return o, nil // if database is not set, connect to 0 db. + } + + db, err := strconv.Atoi(dbStr) + if err != nil { + return nil, fmt.Errorf("redis: invalid database number: %w", err) + } + o.DB = db + return o, nil } +func getUserPassword(u *url.URL) (string, string) { + var user, password string + if u.User != nil { + user = u.User.Username() + if p, ok := u.User.Password(); ok { + password = p + } + } + return user, password +} + func newConnPool(opt *Options) *pool.ConnPool { return pool.NewConnPool(&pool.Options{ Dialer: func(ctx context.Context) (net.Conn, error) { var conn net.Conn - err := internal.WithSpan(ctx, "dialer", func(ctx context.Context) error { - var err error - trace.SpanFromContext(ctx).SetAttributes( - label.String("redis.network", opt.Network), - label.String("redis.addr", opt.Addr), + err := internal.WithSpan(ctx, "redis.dial", func(ctx context.Context, span trace.Span) error { + span.SetAttributes( + attribute.String("db.connection_string", opt.Addr), ) + + var err error conn, err = opt.Dialer(ctx, opt.Network, opt.Addr) if err != nil { - _ = internal.RecordError(ctx, err) + _ = internal.RecordError(ctx, span, err) } return err }) diff --git a/vendor/github.com/go-redis/redis/v8/redis.go b/vendor/github.com/go-redis/redis/v8/redis.go index 3cff1b5e3..3dfdb82aa 100644 --- a/vendor/github.com/go-redis/redis/v8/redis.go +++ b/vendor/github.com/go-redis/redis/v8/redis.go @@ -2,12 +2,16 @@ package redis import ( "context" + "errors" "fmt" + "sync/atomic" "time" "github.com/go-redis/redis/v8/internal" "github.com/go-redis/redis/v8/internal/pool" "github.com/go-redis/redis/v8/internal/proto" + "go.opentelemetry.io/otel/attribute" + "go.opentelemetry.io/otel/trace" ) // Nil reply returned by Redis when key does not exist. @@ -127,20 +131,7 @@ func (hs hooks) processTxPipeline( } func (hs hooks) withContext(ctx context.Context, fn func() error) error { - done := ctx.Done() - if done == nil { - return fn() - } - - errc := make(chan error, 1) - go func() { errc <- fn() }() - - select { - case <-done: - return ctx.Err() - case err := <-errc: - return err - } + return fn() } //------------------------------------------------------------------------------ @@ -223,12 +214,12 @@ func (c *baseClient) _getConn(ctx context.Context) (*pool.Conn, error) { return cn, nil } - err = internal.WithSpan(ctx, "init_conn", func(ctx context.Context) error { + err = internal.WithSpan(ctx, "redis.init_conn", func(ctx context.Context, span trace.Span) error { return c.initConn(ctx, cn) }) if err != nil { c.connPool.Remove(ctx, cn, err) - if err := internal.Unwrap(err); err != nil { + if err := errors.Unwrap(err); err != nil { return nil, err } return nil, err @@ -297,17 +288,42 @@ func (c *baseClient) releaseConn(ctx context.Context, cn *pool.Conn, err error) func (c *baseClient) withConn( ctx context.Context, fn func(context.Context, *pool.Conn) error, ) error { - return internal.WithSpan(ctx, "with_conn", func(ctx context.Context) error { + return internal.WithSpan(ctx, "redis.with_conn", func(ctx context.Context, span trace.Span) error { cn, err := c.getConn(ctx) if err != nil { return err } + + if span.IsRecording() { + if remoteAddr := cn.RemoteAddr(); remoteAddr != nil { + span.SetAttributes(attribute.String("net.peer.ip", remoteAddr.String())) + } + } + defer func() { c.releaseConn(ctx, cn, err) }() - err = fn(ctx, cn) - return err + done := ctx.Done() + if done == nil { + err = fn(ctx, cn) + return err + } + + errc := make(chan error, 1) + go func() { errc <- fn(ctx, cn) }() + + select { + case <-done: + _ = cn.Close() + // Wait for the goroutine to finish and send something. + <-errc + + err = ctx.Err() + return err + case err = <-errc: + return err + } }) } @@ -317,14 +333,14 @@ func (c *baseClient) process(ctx context.Context, cmd Cmder) error { attempt := attempt var retry bool - err := internal.WithSpan(ctx, "process", func(ctx context.Context) error { + err := internal.WithSpan(ctx, "redis.process", func(ctx context.Context, span trace.Span) error { if attempt > 0 { if err := internal.Sleep(ctx, c.retryBackoff(attempt)); err != nil { return err } } - retryTimeout := true + retryTimeout := uint32(1) err := c.withConn(ctx, func(ctx context.Context, cn *pool.Conn) error { err := cn.WithWriter(ctx, c.opt.WriteTimeout, func(wr *proto.Writer) error { return writeCmd(wr, cmd) @@ -335,7 +351,9 @@ func (c *baseClient) process(ctx context.Context, cmd Cmder) error { err = cn.WithReader(ctx, c.cmdTimeout(cmd), cmd.readReply) if err != nil { - retryTimeout = cmd.readTimeout() == nil + if cmd.readTimeout() == nil { + atomic.StoreUint32(&retryTimeout, 1) + } return err } @@ -344,7 +362,7 @@ func (c *baseClient) process(ctx context.Context, cmd Cmder) error { if err == nil { return nil } - retry = shouldRetry(err, retryTimeout) + retry = shouldRetry(err, atomic.LoadUint32(&retryTimeout) == 1) return err }) if err == nil || !retry { @@ -710,6 +728,7 @@ type conn struct { baseClient cmdable statefulCmdable + hooks // TODO: inherit hooks } // Conn is like Client, but its pool contains single connection. @@ -734,7 +753,15 @@ func newConn(ctx context.Context, opt *Options, connPool pool.Pooler) *Conn { } func (c *Conn) Process(ctx context.Context, cmd Cmder) error { - return c.baseClient.process(ctx, cmd) + return c.hooks.process(ctx, cmd, c.baseClient.process) +} + +func (c *Conn) processPipeline(ctx context.Context, cmds []Cmder) error { + return c.hooks.processPipeline(ctx, cmds, c.baseClient.processPipeline) +} + +func (c *Conn) processTxPipeline(ctx context.Context, cmds []Cmder) error { + return c.hooks.processTxPipeline(ctx, cmds, c.baseClient.processTxPipeline) } func (c *Conn) Pipelined(ctx context.Context, fn func(Pipeliner) error) ([]Cmder, error) { diff --git a/vendor/github.com/go-redis/redis/v8/renovate.json b/vendor/github.com/go-redis/redis/v8/renovate.json deleted file mode 100644 index f45d8f110..000000000 --- a/vendor/github.com/go-redis/redis/v8/renovate.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "extends": [ - "config:base" - ] -} diff --git a/vendor/github.com/go-redis/redis/v8/ring.go b/vendor/github.com/go-redis/redis/v8/ring.go index 205b0249d..34d05f35a 100644 --- a/vendor/github.com/go-redis/redis/v8/ring.go +++ b/vendor/github.com/go-redis/redis/v8/ring.go @@ -13,7 +13,6 @@ import ( "github.com/cespare/xxhash/v2" "github.com/dgryski/go-rendezvous" - "github.com/go-redis/redis/v8/internal" "github.com/go-redis/redis/v8/internal/hashtag" "github.com/go-redis/redis/v8/internal/pool" diff --git a/vendor/github.com/go-redis/redis/v8/script.go b/vendor/github.com/go-redis/redis/v8/script.go index 07ed482c5..5cab18d61 100644 --- a/vendor/github.com/go-redis/redis/v8/script.go +++ b/vendor/github.com/go-redis/redis/v8/script.go @@ -8,7 +8,7 @@ import ( "strings" ) -type scripter interface { +type Scripter interface { Eval(ctx context.Context, script string, keys []string, args ...interface{}) *Cmd EvalSha(ctx context.Context, sha1 string, keys []string, args ...interface{}) *Cmd ScriptExists(ctx context.Context, hashes ...string) *BoolSliceCmd @@ -16,9 +16,9 @@ type scripter interface { } var ( - _ scripter = (*Client)(nil) - _ scripter = (*Ring)(nil) - _ scripter = (*ClusterClient)(nil) + _ Scripter = (*Client)(nil) + _ Scripter = (*Ring)(nil) + _ Scripter = (*ClusterClient)(nil) ) type Script struct { @@ -38,25 +38,25 @@ func (s *Script) Hash() string { return s.hash } -func (s *Script) Load(ctx context.Context, c scripter) *StringCmd { +func (s *Script) Load(ctx context.Context, c Scripter) *StringCmd { return c.ScriptLoad(ctx, s.src) } -func (s *Script) Exists(ctx context.Context, c scripter) *BoolSliceCmd { +func (s *Script) Exists(ctx context.Context, c Scripter) *BoolSliceCmd { return c.ScriptExists(ctx, s.hash) } -func (s *Script) Eval(ctx context.Context, c scripter, keys []string, args ...interface{}) *Cmd { +func (s *Script) Eval(ctx context.Context, c Scripter, keys []string, args ...interface{}) *Cmd { return c.Eval(ctx, s.src, keys, args...) } -func (s *Script) EvalSha(ctx context.Context, c scripter, keys []string, args ...interface{}) *Cmd { +func (s *Script) EvalSha(ctx context.Context, c Scripter, keys []string, args ...interface{}) *Cmd { return c.EvalSha(ctx, s.hash, keys, args...) } // Run optimistically uses EVALSHA to run the script. If script does not exist // it is retried using EVAL. -func (s *Script) Run(ctx context.Context, c scripter, keys []string, args ...interface{}) *Cmd { +func (s *Script) Run(ctx context.Context, c Scripter, keys []string, args ...interface{}) *Cmd { r := s.EvalSha(ctx, c, keys, args...) if err := r.Err(); err != nil && strings.HasPrefix(err.Error(), "NOSCRIPT ") { return s.Eval(ctx, c, keys, args...) diff --git a/vendor/github.com/go-redis/redis/v8/sentinel.go b/vendor/github.com/go-redis/redis/v8/sentinel.go index 7db984373..3e8afb745 100644 --- a/vendor/github.com/go-redis/redis/v8/sentinel.go +++ b/vendor/github.com/go-redis/redis/v8/sentinel.go @@ -36,6 +36,12 @@ type FailoverOptions struct { // Route all commands to slave read-only nodes. SlaveOnly bool + // Use slaves disconnected with master when cannot get connected slaves + // Now, this option only works in RandomSlaveAddr function. + UseDisconnectedSlaves bool + + // Client queries sentinels in a random order + QuerySentinelRandomly bool // Following options are copied from Options struct. Dialer func(ctx context.Context, network, addr string) (net.Conn, error) @@ -167,6 +173,10 @@ func NewFailoverClient(failoverOpt *FailoverOptions) *Client { sentinelAddrs := make([]string, len(failoverOpt.SentinelAddrs)) copy(sentinelAddrs, failoverOpt.SentinelAddrs) + rand.Shuffle(len(sentinelAddrs), func(i, j int) { + sentinelAddrs[i], sentinelAddrs[j] = sentinelAddrs[j], sentinelAddrs[i] + }) + failover := &sentinelFailover{ opt: failoverOpt, sentinelAddrs: sentinelAddrs, @@ -177,11 +187,14 @@ func NewFailoverClient(failoverOpt *FailoverOptions) *Client { opt.init() connPool := newConnPool(opt) + + failover.mu.Lock() failover.onFailover = func(ctx context.Context, addr string) { _ = connPool.Filter(func(cn *pool.Conn) bool { return cn.RemoteAddr().String() != addr }) } + failover.mu.Unlock() c := Client{ baseClient: newBaseClient(opt, connPool), @@ -430,10 +443,22 @@ func (c *sentinelFailover) closeSentinel() error { } func (c *sentinelFailover) RandomSlaveAddr(ctx context.Context) (string, error) { - addresses, err := c.slaveAddrs(ctx) + if c.opt == nil { + return "", errors.New("opt is nil") + } + + addresses, err := c.slaveAddrs(ctx, false) if err != nil { return "", err } + + if len(addresses) == 0 && c.opt.UseDisconnectedSlaves { + addresses, err = c.slaveAddrs(ctx, true) + if err != nil { + return "", err + } + } + if len(addresses) == 0 { return c.MasterAddr(ctx) } @@ -482,10 +507,10 @@ func (c *sentinelFailover) MasterAddr(ctx context.Context) (string, error) { return addr, nil } - return "", errors.New("redis: all sentinels are unreachable") + return "", errors.New("redis: all sentinels specified in configuration are unreachable") } -func (c *sentinelFailover) slaveAddrs(ctx context.Context) ([]string, error) { +func (c *sentinelFailover) slaveAddrs(ctx context.Context, useDisconnected bool) ([]string, error) { c.mu.RLock() sentinel := c.sentinel c.mu.RUnlock() @@ -508,6 +533,8 @@ func (c *sentinelFailover) slaveAddrs(ctx context.Context) ([]string, error) { _ = c.closeSentinel() } + var sentinelReachable bool + for i, sentinelAddr := range c.sentinelAddrs { sentinel := NewSentinelClient(c.opt.sentinelOptions(sentinelAddr)) @@ -518,16 +545,22 @@ func (c *sentinelFailover) slaveAddrs(ctx context.Context) ([]string, error) { _ = sentinel.Close() continue } - + sentinelReachable = true + addrs := parseSlaveAddrs(slaves, useDisconnected) + if len(addrs) == 0 { + continue + } // Push working sentinel to the top. c.sentinelAddrs[0], c.sentinelAddrs[i] = c.sentinelAddrs[i], c.sentinelAddrs[0] c.setSentinel(ctx, sentinel) - addrs := parseSlaveAddrs(slaves) return addrs, nil } - return []string{}, errors.New("redis: all sentinels are unreachable") + if sentinelReachable { + return []string{}, nil + } + return []string{}, errors.New("redis: all sentinels specified in configuration are unreachable") } func (c *sentinelFailover) getMasterAddr(ctx context.Context, sentinel *SentinelClient) string { @@ -547,12 +580,11 @@ func (c *sentinelFailover) getSlaveAddrs(ctx context.Context, sentinel *Sentinel c.opt.MasterName, err) return []string{} } - return parseSlaveAddrs(addrs) + return parseSlaveAddrs(addrs, false) } -func parseSlaveAddrs(addrs []interface{}) []string { +func parseSlaveAddrs(addrs []interface{}, keepDisconnected bool) []string { nodes := make([]string, 0, len(addrs)) - for _, node := range addrs { ip := "" port := "" @@ -574,8 +606,12 @@ func parseSlaveAddrs(addrs []interface{}) []string { for _, flag := range flags { switch flag { - case "s_down", "o_down", "disconnected": + case "s_down", "o_down": isDown = true + case "disconnected": + if !keepDisconnected { + isDown = true + } } } @@ -646,6 +682,7 @@ func (c *sentinelFailover) discoverSentinels(ctx context.Context) { func (c *sentinelFailover) listen(pubsub *PubSub) { ctx := context.TODO() + if c.onUpdate != nil { c.onUpdate(ctx) } @@ -701,7 +738,7 @@ func NewFailoverClusterClient(failoverOpt *FailoverOptions) *ClusterClient { Addr: masterAddr, }} - slaveAddrs, err := failover.slaveAddrs(ctx) + slaveAddrs, err := failover.slaveAddrs(ctx, false) if err != nil { return nil, err } @@ -723,9 +760,12 @@ func NewFailoverClusterClient(failoverOpt *FailoverOptions) *ClusterClient { } c := NewClusterClient(opt) + + failover.mu.Lock() failover.onUpdate = func(ctx context.Context) { c.ReloadState(ctx) } + failover.mu.Unlock() return c } diff --git a/vendor/github.com/go-redis/redis/v8/tx.go b/vendor/github.com/go-redis/redis/v8/tx.go index ad825c610..08d381a9d 100644 --- a/vendor/github.com/go-redis/redis/v8/tx.go +++ b/vendor/github.com/go-redis/redis/v8/tx.go @@ -65,16 +65,13 @@ func (c *Tx) Process(ctx context.Context, cmd Cmder) error { // The transaction is automatically closed when fn exits. func (c *Client) Watch(ctx context.Context, fn func(*Tx) error, keys ...string) error { tx := c.newTx(ctx) + defer tx.Close(ctx) if len(keys) > 0 { if err := tx.Watch(ctx, keys...).Err(); err != nil { - _ = tx.Close(ctx) return err } } - - err := fn(tx) - _ = tx.Close(ctx) - return err + return fn(tx) } // Close closes the transaction, releasing any open resources. diff --git a/vendor/github.com/go-redis/redis/v8/universal.go b/vendor/github.com/go-redis/redis/v8/universal.go index 5a7d0d5bc..5f0e1e33a 100644 --- a/vendor/github.com/go-redis/redis/v8/universal.go +++ b/vendor/github.com/go-redis/redis/v8/universal.go @@ -181,6 +181,7 @@ type UniversalClient interface { Subscribe(ctx context.Context, channels ...string) *PubSub PSubscribe(ctx context.Context, channels ...string) *PubSub Close() error + PoolStats() *PoolStats } var ( diff --git a/vendor/go.opentelemetry.io/otel/.gitignore b/vendor/go.opentelemetry.io/otel/.gitignore index cbef19714..69f09e575 100644 --- a/vendor/go.opentelemetry.io/otel/.gitignore +++ b/vendor/go.opentelemetry.io/otel/.gitignore @@ -10,13 +10,10 @@ coverage.* gen/ -/example/basic/basic -/example/grpc/client/client -/example/grpc/server/server -/example/http/client/client -/example/http/server/server /example/jaeger/jaeger /example/namedtracer/namedtracer +/example/opencensus/opencensus /example/prometheus/prometheus +/example/prom-collector/prom-collector /example/zipkin/zipkin /example/otel-collector/otel-collector diff --git a/vendor/go.opentelemetry.io/otel/CHANGELOG.md b/vendor/go.opentelemetry.io/otel/CHANGELOG.md index e553b56ae..b2cccb871 100644 --- a/vendor/go.opentelemetry.io/otel/CHANGELOG.md +++ b/vendor/go.opentelemetry.io/otel/CHANGELOG.md @@ -8,15 +8,337 @@ This project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.htm ## [Unreleased] +## [0.18.0] - 2020-03-03 + +### Added + +- Added `resource.Default()` for use with meter and tracer providers. (#1507) +- `AttributePerEventCountLimit` and `AttributePerLinkCountLimit` for `SpanLimits`. (#1535) +- Added `Keys()` method to `propagation.TextMapCarrier` and `propagation.HeaderCarrier` to adapt `http.Header` to this interface. (#1544) +- Added `code` attributes to `go.opentelemetry.io/otel/semconv` package. (#1558) +- Compatibility testing suite in the CI system for the following systems. (#1567) + | OS | Go Version | Architecture | + | ------- | ---------- | ------------ | + | Ubuntu | 1.15 | amd64 | + | Ubuntu | 1.14 | amd64 | + | Ubuntu | 1.15 | 386 | + | Ubuntu | 1.14 | 386 | + | MacOS | 1.15 | amd64 | + | MacOS | 1.14 | amd64 | + | Windows | 1.15 | amd64 | + | Windows | 1.14 | amd64 | + | Windows | 1.15 | 386 | + | Windows | 1.14 | 386 | + +### Changed + +- Replaced interface `oteltest.SpanRecorder` with its existing implementation + `StandardSpanRecorder` (#1542). +- Default span limit values to 128. (#1535) +- Rename `MaxEventsPerSpan`, `MaxAttributesPerSpan` and `MaxLinksPerSpan` to `EventCountLimit`, `AttributeCountLimit` and `LinkCountLimit`, and move these fields into `SpanLimits`. (#1535) +- Renamed the `otel/label` package to `otel/attribute`. (#1541) +- Vendor the Jaeger exporter's dependency on Apache Thrift. (#1551) +- Parallelize the CI linting and testing. (#1567) +- Stagger timestamps in exact aggregator tests. (#1569) +- Changed all examples to use `WithBatchTimeout(5 * time.Second)` rather than `WithBatchTimeout(5)`. (#1621) +- Prevent end-users from implementing some interfaces (#1575) +``` + "otel/exporters/otlp/otlphttp".Option + "otel/exporters/stdout".Option + "otel/oteltest".Option + "otel/trace".TracerOption + "otel/trace".SpanOption + "otel/trace".EventOption + "otel/trace".LifeCycleOption + "otel/trace".InstrumentationOption + "otel/sdk/resource".Option + "otel/sdk/trace".ParentBasedSamplerOption + "otel/sdk/trace".ReadOnlySpan + "otel/sdk/trace".ReadWriteSpan +``` + +### Removed + +- Removed attempt to resample spans upon changing the span name with `span.SetName()`. (#1545) +- The `test-benchmark` is no longer a dependency of the `precommit` make target. (#1567) +- Removed the `test-386` make target. + This was replaced with a full compatibility testing suite (i.e. multi OS/arch) in the CI system. (#1567) + +### Fixed + +- The sequential timing check of timestamps in the stdout exporter are now setup explicitly to be sequential (#1571). (#1572) +- Windows build of Jaeger tests now compiles with OS specific functions (#1576). (#1577) +- The sequential timing check of timestamps of go.opentelemetry.io/otel/sdk/metric/aggregator/lastvalue are now setup explicitly to be sequential (#1578). (#1579) +- Validate tracestate header keys with vedors according to the W3C TraceContext specification (#1475). (#1581) +- The OTLP exporter includes related labels for translations of a GaugeArray (#1563). (#1570) + +## [0.17.0] - 2020-02-12 + +### Changed + +- Rename project default branch from `master` to `main`. (#1505) +- Reverse order in which `Resource` attributes are merged, per change in spec. (#1501) +- Add tooling to maintain "replace" directives in go.mod files automatically. (#1528) +- Create new modules: otel/metric, otel/trace, otel/oteltest, otel/sdk/export/metric, otel/sdk/metric (#1528) +- Move metric-related public global APIs from otel to otel/metric/global. (#1528) + +## Fixed + +- Fixed otlpgrpc reconnection issue. +- The example code in the README.md of `go.opentelemetry.io/otel/exporters/otlp` is moved to a compiled example test and used the new `WithAddress` instead of `WithEndpoint`. (#1513) +- The otel-collector example now uses the default OTLP receiver port of the collector. + +## [0.16.0] - 2020-01-13 + +### Added + +- Add the `ReadOnlySpan` and `ReadWriteSpan` interfaces to provide better control for accessing span data. (#1360) +- `NewGRPCDriver` function returns a `ProtocolDriver` that maintains a single gRPC connection to the collector. (#1369) +- Added documentation about the project's versioning policy. (#1388) +- Added `NewSplitDriver` for OTLP exporter that allows sending traces and metrics to different endpoints. (#1418) +- Added codeql worfklow to GitHub Actions (#1428) +- Added Gosec workflow to GitHub Actions (#1429) +- Add new HTTP driver for OTLP exporter in `exporters/otlp/otlphttp`. Currently it only supports the binary protobuf payloads. (#1420) + +### Changed + +- Rename `internal/testing` to `internal/internaltest`. (#1449) +- Rename `export.SpanData` to `export.SpanSnapshot` and use it only for exporting spans. (#1360) +- Store the parent's full `SpanContext` rather than just its span ID in the `span` struct. (#1360) +- Improve span duration accuracy. (#1360) +- Migrated CI/CD from CircleCI to GitHub Actions (#1382) +- Remove duplicate checkout from GitHub Actions workflow (#1407) +- Metric `array` aggregator renamed `exact` to match its `aggregation.Kind` (#1412) +- Metric `exact` aggregator includes per-point timestamps (#1412) +- Metric stdout exporter uses MinMaxSumCount aggregator for ValueRecorder instruments (#1412) +- `NewExporter` from `exporters/otlp` now takes a `ProtocolDriver` as a parameter. (#1369) +- Many OTLP Exporter options became gRPC ProtocolDriver options. (#1369) +- Unify endpoint API that related to OTel exporter. (#1401) +- Optimize metric histogram aggregator to re-use its slice of buckets. (#1435) +- Metric aggregator Count() and histogram Bucket.Counts are consistently `uint64`. (1430) +- Histogram aggregator accepts functional options, uses default boundaries if none given. (#1434) +- `SamplingResult` now passed a `Tracestate` from the parent `SpanContext` (#1432) +- Moved gRPC driver for OTLP exporter to `exporters/otlp/otlpgrpc`. (#1420) +- The `TraceContext` propagator now correctly propagates `TraceState` through the `SpanContext`. (#1447) +- Metric Push and Pull Controller components are combined into a single "basic" Controller: + - `WithExporter()` and `Start()` to configure Push behavior + - `Start()` is optional; use `Collect()` and `ForEach()` for Pull behavior + - `Start()` and `Stop()` accept Context. (#1378) +- The `Event` type is moved from the `otel/sdk/export/trace` package to the `otel/trace` API package. (#1452) + +### Removed + +- Remove `errUninitializedSpan` as its only usage is now obsolete. (#1360) +- Remove Metric export functionality related to quantiles and summary data points: this is not specified (#1412) +- Remove DDSketch metric aggregator; our intention is to re-introduce this as an option of the histogram aggregator after [new OTLP histogram data types](https://github.com/open-telemetry/opentelemetry-proto/pull/226) are released (#1412) + +### Fixed + +- `BatchSpanProcessor.Shutdown()` will now shutdown underlying `export.SpanExporter`. (#1443) + +## [0.15.0] - 2020-12-10 + +### Added + +- The `WithIDGenerator` `TracerProviderOption` is added to the `go.opentelemetry.io/otel/trace` package to configure an `IDGenerator` for the `TracerProvider`. (#1363) + +### Changed + +- The Zipkin exporter now uses the Span status code to determine. (#1328) +- `NewExporter` and `Start` functions in `go.opentelemetry.io/otel/exporters/otlp` now receive `context.Context` as a first parameter. (#1357) +- Move the OpenCensus example into `example` directory. (#1359) +- Moved the SDK's `internal.IDGenerator` interface in to the `sdk/trace` package to enable support for externally-defined ID generators. (#1363) +- Bump `github.com/google/go-cmp` from 0.5.3 to 0.5.4 (#1374) +- Bump `github.com/golangci/golangci-lint` in `/internal/tools` (#1375) + +### Fixed + +- Metric SDK `SumObserver` and `UpDownSumObserver` instruments correctness fixes. (#1381) + +## [0.14.0] - 2020-11-19 + +### Added + +- An `EventOption` and the related `NewEventConfig` function are added to the `go.opentelemetry.io/otel` package to configure Span events. (#1254) +- A `TextMapPropagator` and associated `TextMapCarrier` are added to the `go.opentelemetry.io/otel/oteltest` package to test `TextMap` type propagators and their use. (#1259) +- `SpanContextFromContext` returns `SpanContext` from context. (#1255) +- `TraceState` has been added to `SpanContext`. (#1340) +- `DeploymentEnvironmentKey` added to `go.opentelemetry.io/otel/semconv` package. (#1323) +- Add an OpenCensus to OpenTelemetry tracing bridge. (#1305) +- Add a parent context argument to `SpanProcessor.OnStart` to follow the specification. (#1333) +- Add missing tests for `sdk/trace/attributes_map.go`. (#1337) + +### Changed + +- Move the `go.opentelemetry.io/otel/api/trace` package into `go.opentelemetry.io/otel/trace` with the following changes. (#1229) (#1307) + - `ID` has been renamed to `TraceID`. + - `IDFromHex` has been renamed to `TraceIDFromHex`. + - `EmptySpanContext` is removed. +- Move the `go.opentelemetry.io/otel/api/trace/tracetest` package into `go.opentelemetry.io/otel/oteltest`. (#1229) +- OTLP Exporter updates: + - supports OTLP v0.6.0 (#1230, #1354) + - supports configurable aggregation temporality (default: Cumulative, optional: Stateless). (#1296) +- The Sampler is now called on local child spans. (#1233) +- The `Kind` type from the `go.opentelemetry.io/otel/api/metric` package was renamed to `InstrumentKind` to more specifically describe what it is and avoid semantic ambiguity. (#1240) +- The `MetricKind` method of the `Descriptor` type in the `go.opentelemetry.io/otel/api/metric` package was renamed to `Descriptor.InstrumentKind`. + This matches the returned type and fixes misuse of the term metric. (#1240) +- Move test harness from the `go.opentelemetry.io/otel/api/apitest` package into `go.opentelemetry.io/otel/oteltest`. (#1241) +- Move the `go.opentelemetry.io/otel/api/metric/metrictest` package into `go.opentelemetry.io/oteltest` as part of #964. (#1252) +- Move the `go.opentelemetry.io/otel/api/metric` package into `go.opentelemetry.io/otel/metric` as part of #1303. (#1321) +- Move the `go.opentelemetry.io/otel/api/metric/registry` package into `go.opentelemetry.io/otel/metric/registry` as a part of #1303. (#1316) +- Move the `Number` type (together with related functions) from `go.opentelemetry.io/otel/api/metric` package into `go.opentelemetry.io/otel/metric/number` as a part of #1303. (#1316) +- The function signature of the Span `AddEvent` method in `go.opentelemetry.io/otel` is updated to no longer take an unused context and instead take a required name and a variable number of `EventOption`s. (#1254) +- The function signature of the Span `RecordError` method in `go.opentelemetry.io/otel` is updated to no longer take an unused context and instead take a required error value and a variable number of `EventOption`s. (#1254) +- Move the `go.opentelemetry.io/otel/api/global` package to `go.opentelemetry.io/otel`. (#1262) (#1330) +- Move the `Version` function from `go.opentelemetry.io/otel/sdk` to `go.opentelemetry.io/otel`. (#1330) +- Rename correlation context header from `"otcorrelations"` to `"baggage"` to match the OpenTelemetry specification. (#1267) +- Fix `Code.UnmarshalJSON` to work with valid JSON only. (#1276) +- The `resource.New()` method changes signature to support builtin attributes and functional options, including `telemetry.sdk.*` and + `host.name` semantic conventions; the former method is renamed `resource.NewWithAttributes`. (#1235) +- The Prometheus exporter now exports non-monotonic counters (i.e. `UpDownCounter`s) as gauges. (#1210) +- Correct the `Span.End` method documentation in the `otel` API to state updates are not allowed on a span after it has ended. (#1310) +- Updated span collection limits for attribute, event and link counts to 1000 (#1318) +- Renamed `semconv.HTTPUrlKey` to `semconv.HTTPURLKey`. (#1338) + +### Removed + +- The `ErrInvalidHexID`, `ErrInvalidTraceIDLength`, `ErrInvalidSpanIDLength`, `ErrInvalidSpanIDLength`, or `ErrNilSpanID` from the `go.opentelemetry.io/otel` package are unexported now. (#1243) +- The `AddEventWithTimestamp` method on the `Span` interface in `go.opentelemetry.io/otel` is removed due to its redundancy. + It is replaced by using the `AddEvent` method with a `WithTimestamp` option. (#1254) +- The `MockSpan` and `MockTracer` types are removed from `go.opentelemetry.io/otel/oteltest`. + `Tracer` and `Span` from the same module should be used in their place instead. (#1306) +- `WorkerCount` option is removed from `go.opentelemetry.io/otel/exporters/otlp`. (#1350) +- Remove the following labels types: INT32, UINT32, UINT64 and FLOAT32. (#1314) + +### Fixed + +- Rename `MergeItererator` to `MergeIterator` in the `go.opentelemetry.io/otel/label` package. (#1244) +- The `go.opentelemetry.io/otel/api/global` packages global TextMapPropagator now delegates functionality to a globally set delegate for all previously returned propagators. (#1258) +- Fix condition in `label.Any`. (#1299) +- Fix global `TracerProvider` to pass options to its configured provider. (#1329) +- Fix missing handler for `ExactKind` aggregator in OTLP metrics transformer (#1309) + +## [0.13.0] - 2020-10-08 + +### Added + +- OTLP Metric exporter supports Histogram aggregation. (#1209) +- The `Code` struct from the `go.opentelemetry.io/otel/codes` package now supports JSON marshaling and unmarshaling as well as implements the `Stringer` interface. (#1214) +- A Baggage API to implement the OpenTelemetry specification. (#1217) +- Add Shutdown method to sdk/trace/provider, shutdown processors in the order they were registered. (#1227) + +### Changed + +- Set default propagator to no-op propagator. (#1184) +- The `HTTPSupplier`, `HTTPExtractor`, `HTTPInjector`, and `HTTPPropagator` from the `go.opentelemetry.io/otel/api/propagation` package were replaced with unified `TextMapCarrier` and `TextMapPropagator` in the `go.opentelemetry.io/otel/propagation` package. (#1212) (#1325) +- The `New` function from the `go.opentelemetry.io/otel/api/propagation` package was replaced with `NewCompositeTextMapPropagator` in the `go.opentelemetry.io/otel` package. (#1212) +- The status codes of the `go.opentelemetry.io/otel/codes` package have been updated to match the latest OpenTelemetry specification. + They now are `Unset`, `Error`, and `Ok`. + They no longer track the gRPC codes. (#1214) +- The `StatusCode` field of the `SpanData` struct in the `go.opentelemetry.io/otel/sdk/export/trace` package now uses the codes package from this package instead of the gRPC project. (#1214) +- Move the `go.opentelemetry.io/otel/api/baggage` package into `go.opentelemetry.io/otel/baggage`. (#1217) (#1325) +- A `Shutdown` method of `SpanProcessor` and all its implementations receives a context and returns an error. (#1264) + +### Fixed + +- Copies of data from arrays and slices passed to `go.opentelemetry.io/otel/label.ArrayValue()` are now used in the returned `Value` instead of using the mutable data itself. (#1226) + +### Removed + +- The `ExtractHTTP` and `InjectHTTP` functions from the `go.opentelemetry.io/otel/api/propagation` package were removed. (#1212) +- The `Propagators` interface from the `go.opentelemetry.io/otel/api/propagation` package was removed to conform to the OpenTelemetry specification. + The explicit `TextMapPropagator` type can be used in its place as this is the `Propagator` type the specification defines. (#1212) +- The `SetAttribute` method of the `Span` from the `go.opentelemetry.io/otel/api/trace` package was removed given its redundancy with the `SetAttributes` method. (#1216) +- The internal implementation of Baggage storage is removed in favor of using the new Baggage API functionality. (#1217) +- Remove duplicate hostname key `HostHostNameKey` in Resource semantic conventions. (#1219) +- Nested array/slice support has been removed. (#1226) + +## [0.12.0] - 2020-09-24 + +### Added + +- A `SpanConfigure` function in `go.opentelemetry.io/otel/api/trace` to create a new `SpanConfig` from `SpanOption`s. (#1108) +- In the `go.opentelemetry.io/otel/api/trace` package, `NewTracerConfig` was added to construct new `TracerConfig`s. + This addition was made to conform with our project option conventions. (#1155) +- Instrumentation library information was added to the Zipkin exporter. (#1119) +- The `SpanProcessor` interface now has a `ForceFlush()` method. (#1166) +- More semantic conventions for k8s as resource attributes. (#1167) + +### Changed + +- Add reconnecting udp connection type to Jaeger exporter. + This change adds a new optional implementation of the udp conn interface used to detect changes to an agent's host dns record. + It then adopts the new destination address to ensure the exporter doesn't get stuck. This change was ported from jaegertracing/jaeger-client-go#520. (#1063) +- Replace `StartOption` and `EndOption` in `go.opentelemetry.io/otel/api/trace` with `SpanOption`. + This change is matched by replacing the `StartConfig` and `EndConfig` with a unified `SpanConfig`. (#1108) +- Replace the `LinkedTo` span option in `go.opentelemetry.io/otel/api/trace` with `WithLinks`. + This is be more consistent with our other option patterns, i.e. passing the item to be configured directly instead of its component parts, and provides a cleaner function signature. (#1108) +- The `go.opentelemetry.io/otel/api/trace` `TracerOption` was changed to an interface to conform to project option conventions. (#1109) +- Move the `B3` and `TraceContext` from within the `go.opentelemetry.io/otel/api/trace` package to their own `go.opentelemetry.io/otel/propagators` package. + This removal of the propagators is reflective of the OpenTelemetry specification for these propagators as well as cleans up the `go.opentelemetry.io/otel/api/trace` API. (#1118) +- Rename Jaeger tags used for instrumentation library information to reflect changes in OpenTelemetry specification. (#1119) +- Rename `ProbabilitySampler` to `TraceIDRatioBased` and change semantics to ignore parent span sampling status. (#1115) +- Move `tools` package under `internal`. (#1141) +- Move `go.opentelemetry.io/otel/api/correlation` package to `go.opentelemetry.io/otel/api/baggage`. (#1142) + The `correlation.CorrelationContext` propagator has been renamed `baggage.Baggage`. Other exported functions and types are unchanged. +- Rename `ParentOrElse` sampler to `ParentBased` and allow setting samplers depending on parent span. (#1153) +- In the `go.opentelemetry.io/otel/api/trace` package, `SpanConfigure` was renamed to `NewSpanConfig`. (#1155) +- Change `dependabot.yml` to add a `Skip Changelog` label to dependabot-sourced PRs. (#1161) +- The [configuration style guide](https://github.com/open-telemetry/opentelemetry-go/blob/master/CONTRIBUTING.md#config) has been updated to + recommend the use of `newConfig()` instead of `configure()`. (#1163) +- The `otlp.Config` type has been unexported and changed to `otlp.config`, along with its initializer. (#1163) +- Ensure exported interface types include parameter names and update the + Style Guide to reflect this styling rule. (#1172) +- Don't consider unset environment variable for resource detection to be an error. (#1170) +- Rename `go.opentelemetry.io/otel/api/metric.ConfigureInstrument` to `NewInstrumentConfig` and + `go.opentelemetry.io/otel/api/metric.ConfigureMeter` to `NewMeterConfig`. +- ValueObserver instruments use LastValue aggregator by default. (#1165) +- OTLP Metric exporter supports LastValue aggregation. (#1165) +- Move the `go.opentelemetry.io/otel/api/unit` package to `go.opentelemetry.io/otel/unit`. (#1185) +- Rename `Provider` to `MeterProvider` in the `go.opentelemetry.io/otel/api/metric` package. (#1190) +- Rename `NoopProvider` to `NoopMeterProvider` in the `go.opentelemetry.io/otel/api/metric` package. (#1190) +- Rename `NewProvider` to `NewMeterProvider` in the `go.opentelemetry.io/otel/api/metric/metrictest` package. (#1190) +- Rename `Provider` to `MeterProvider` in the `go.opentelemetry.io/otel/api/metric/registry` package. (#1190) +- Rename `NewProvider` to `NewMeterProvider` in the `go.opentelemetry.io/otel/api/metri/registryc` package. (#1190) +- Rename `Provider` to `TracerProvider` in the `go.opentelemetry.io/otel/api/trace` package. (#1190) +- Rename `NoopProvider` to `NoopTracerProvider` in the `go.opentelemetry.io/otel/api/trace` package. (#1190) +- Rename `Provider` to `TracerProvider` in the `go.opentelemetry.io/otel/api/trace/tracetest` package. (#1190) +- Rename `NewProvider` to `NewTracerProvider` in the `go.opentelemetry.io/otel/api/trace/tracetest` package. (#1190) +- Rename `WrapperProvider` to `WrapperTracerProvider` in the `go.opentelemetry.io/otel/bridge/opentracing` package. (#1190) +- Rename `NewWrapperProvider` to `NewWrapperTracerProvider` in the `go.opentelemetry.io/otel/bridge/opentracing` package. (#1190) +- Rename `Provider` method of the pull controller to `MeterProvider` in the `go.opentelemetry.io/otel/sdk/metric/controller/pull` package. (#1190) +- Rename `Provider` method of the push controller to `MeterProvider` in the `go.opentelemetry.io/otel/sdk/metric/controller/push` package. (#1190) +- Rename `ProviderOptions` to `TracerProviderConfig` in the `go.opentelemetry.io/otel/sdk/trace` package. (#1190) +- Rename `ProviderOption` to `TracerProviderOption` in the `go.opentelemetry.io/otel/sdk/trace` package. (#1190) +- Rename `Provider` to `TracerProvider` in the `go.opentelemetry.io/otel/sdk/trace` package. (#1190) +- Rename `NewProvider` to `NewTracerProvider` in the `go.opentelemetry.io/otel/sdk/trace` package. (#1190) +- Renamed `SamplingDecision` values to comply with OpenTelemetry specification change. (#1192) +- Renamed Zipkin attribute names from `ot.status_code & ot.status_description` to `otel.status_code & otel.status_description`. (#1201) +- The default SDK now invokes registered `SpanProcessor`s in the order they were registered with the `TracerProvider`. (#1195) +- Add test of spans being processed by the `SpanProcessor`s in the order they were registered. (#1203) + +### Removed + +- Remove the B3 propagator from `go.opentelemetry.io/otel/propagators`. It is now located in the + `go.opentelemetry.io/contrib/propagators/` module. (#1191) +- Remove the semantic convention for HTTP status text, `HTTPStatusTextKey` from package `go.opentelemetry.io/otel/semconv`. (#1194) + +### Fixed + +- Zipkin example no longer mentions `ParentSampler`, corrected to `ParentBased`. (#1171) +- Fix missing shutdown processor in otel-collector example. (#1186) +- Fix missing shutdown processor in basic and namedtracer examples. (#1197) + ## [0.11.0] - 2020-08-24 ### Added +- Support for exporting array-valued attributes via OTLP. (#992) - `Noop` and `InMemory` `SpanBatcher` implementations to help with testing integrations. (#994) -- Integration tests for more OTel Collector Attribute types. (#1062) -- A dimensionality-reducing metric Processor. (#1057) - Support for filtering metric label sets. (#1047) -- Support for exporting array-valued attributes via OTLP. (#992) +- A dimensionality-reducing metric Processor. (#1057) +- Integration tests for more OTel Collector Attribute types. (#1062) +- A new `WithSpanProcessor` `ProviderOption` is added to the `go.opentelemetry.io/otel/sdk/trace` package to create a `Provider` and automatically register the `SpanProcessor`. (#1078) ### Changed @@ -35,6 +357,13 @@ This project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.htm - Unify Callback Function Naming. Rename `*Callback` with `*Func`. (#1061) - CI builds validate against last two versions of Go, dropping 1.13 and adding 1.15. (#1064) +- The `go.opentelemetry.io/otel/sdk/export/trace` interfaces `SpanSyncer` and `SpanBatcher` have been replaced with a specification compliant `Exporter` interface. + This interface still supports the export of `SpanData`, but only as a slice. + Implementation are also required now to return any error from `ExportSpans` if one occurs as well as implement a `Shutdown` method for exporter clean-up. (#1078) +- The `go.opentelemetry.io/otel/sdk/trace` `NewBatchSpanProcessor` function no longer returns an error. + If a `nil` exporter is passed as an argument to this function, instead of it returning an error, it now returns a `BatchSpanProcessor` that handles the export of `SpanData` by not taking any action. (#1078) +- The `go.opentelemetry.io/otel/sdk/trace` `NewProvider` function to create a `Provider` no longer returns an error, instead only a `*Provider`. + This change is related to `NewBatchSpanProcessor` not returning an error which was the only error this function would return. (#1078) ### Removed @@ -780,7 +1109,14 @@ It contains api and sdk for trace and meter. - CODEOWNERS file to track owners of this project. -[Unreleased]: https://github.com/open-telemetry/opentelemetry-go/compare/v0.11.0...HEAD +[Unreleased]: https://github.com/open-telemetry/opentelemetry-go/compare/v0.18.0...HEAD +[0.18.0]: https://github.com/open-telemetry/opentelemetry-go/releases/tag/v0.18.0 +[0.17.0]: https://github.com/open-telemetry/opentelemetry-go/releases/tag/v0.17.0 +[0.16.0]: https://github.com/open-telemetry/opentelemetry-go/releases/tag/v0.16.0 +[0.15.0]: https://github.com/open-telemetry/opentelemetry-go/releases/tag/v0.15.0 +[0.14.0]: https://github.com/open-telemetry/opentelemetry-go/releases/tag/v0.14.0 +[0.13.0]: https://github.com/open-telemetry/opentelemetry-go/releases/tag/v0.13.0 +[0.12.0]: https://github.com/open-telemetry/opentelemetry-go/releases/tag/v0.12.0 [0.11.0]: https://github.com/open-telemetry/opentelemetry-go/releases/tag/v0.11.0 [0.10.0]: https://github.com/open-telemetry/opentelemetry-go/releases/tag/v0.10.0 [0.9.0]: https://github.com/open-telemetry/opentelemetry-go/releases/tag/v0.9.0 diff --git a/vendor/go.opentelemetry.io/otel/CODEOWNERS b/vendor/go.opentelemetry.io/otel/CODEOWNERS index cbca5922a..6c50189a4 100644 --- a/vendor/go.opentelemetry.io/otel/CODEOWNERS +++ b/vendor/go.opentelemetry.io/otel/CODEOWNERS @@ -5,13 +5,13 @@ ##################################################### # # Learn about membership in OpenTelemetry community: -# https://github.com/open-telemetry/community/blob/master/community-membership.md -# +# https://github.com/open-telemetry/community/blob/main/community-membership.md # -# Learn about CODEOWNERS file format: +# +# Learn about CODEOWNERS file format: # https://help.github.com/en/articles/about-code-owners # -* @jmacd @lizthegrey @MrAlias @Aneurysm9 @evantorrie +* @jmacd @lizthegrey @MrAlias @Aneurysm9 @evantorrie @XSAM @dashpole CODEOWNERS @MrAlias @Aneurysm9 diff --git a/vendor/go.opentelemetry.io/otel/CONTRIBUTING.md b/vendor/go.opentelemetry.io/otel/CONTRIBUTING.md index 0059076af..2b31ccfec 100644 --- a/vendor/go.opentelemetry.io/otel/CONTRIBUTING.md +++ b/vendor/go.opentelemetry.io/otel/CONTRIBUTING.md @@ -9,7 +9,7 @@ See the [public meeting notes](https://docs.google.com/document/d/1A63zSWX0x2CyCK_LoNhmQC4rqhLpYXJzXbEPDUQ2n6w/edit#heading=h.9tngw7jdwd6b) for a summary description of past meetings. To request edit access, join the meeting or get in touch on -[Gitter](https://gitter.im/open-telemetry/opentelemetry-go). +[Slack](https://cloud-native.slack.com/archives/C01NPAXACKT). ## Development @@ -19,6 +19,8 @@ You can view and edit the source code by cloning this repository: git clone https://github.com/open-telemetry/opentelemetry-go.git ``` +Run `make test` to run the tests instead of `go test`. + There are some generated files checked into the repo. To make sure that the generated files are up-to-date, run `make` (or `make precommit` - the `precommit` target is the default). @@ -95,19 +97,20 @@ request ID to the entry you added to `CHANGELOG.md`. A PR is considered to be **ready to merge** when: * It has received two approvals from Collaborators/Maintainers (at - different companies). + different companies). This is not enforced through technical means + and a PR may be **ready to merge** with a single approval if the change + and its approach have been discussed and consensus reached. * Major feedbacks are resolved. * It has been open for review for at least one working day. This gives people reasonable time to review. -* Trivial change (typo, cosmetic, doc, etc.) doesn't have to wait for - one day. +* Trivial changes (typo, cosmetic, doc, etc.) do not have to wait for + one day and may be merged with a single Maintainer's approval. * `CHANGELOG.md` has been updated to reflect what has been added, changed, removed, or fixed. * Urgent fix can take exception as long as it has been actively communicated. -Any Collaborator/Maintainer can merge the PR once it is **ready to -merge**. +Any Maintainer can merge the PR once it is **ready to merge**. ## Design Choices @@ -115,7 +118,7 @@ As with other OpenTelemetry clients, opentelemetry-go follows the [opentelemetry-specification](https://github.com/open-telemetry/opentelemetry-specification). It's especially valuable to read through the [library -guidelines](https://github.com/open-telemetry/opentelemetry-specification/blob/master/specification/library-guidelines.md). +guidelines](https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/library-guidelines.md). ### Focus on Capabilities, Not Structure Compliance @@ -184,13 +187,13 @@ how the user can extend the configuration. It is important that `config` are not shared across package boundaries. Meaning a `config` from one package should not be directly used by another. -Optionally, it is common to include a `configure` function (with the same +Optionally, it is common to include a `newConfig` function (with the same naming scheme). This function wraps any defaults setting and looping over all options to create a configured `config`. ```go -// configure returns an appropriately configured config. -func configure([]Option) config { +// newConfig returns an appropriately configured config. +func newConfig([]Option) config { // Set default values for config. config := config{/* […] */} for _, option := range options { @@ -206,7 +209,7 @@ error as well that is expected to be handled by the instantiation function or propagated to the user. Given the design goal of not having the user need to work with the `config`, -the `configure` function should also be unexported. +the `newConfig` function should also be unexported. #### `Option` @@ -215,7 +218,7 @@ To set the value of the options a `config` contains, a corresponding ```go type Option interface { - Apply(*Config) + Apply(*config) } ``` @@ -241,7 +244,7 @@ func With*(…) Option { … } ```go type defaultFalseOption bool -func (o defaultFalseOption) Apply(c *Config) { +func (o defaultFalseOption) Apply(c *config) { c.Bool = bool(o) } @@ -254,7 +257,7 @@ func WithOption() Option { ```go type defaultTrueOption bool -func (o defaultTrueOption) Apply(c *Config) { +func (o defaultTrueOption) Apply(c *config) { c.Bool = bool(o) } @@ -271,7 +274,7 @@ type myTypeOption struct { MyType MyType } -func (o myTypeOption) Apply(c *Config) { +func (o myTypeOption) Apply(c *config) { c.MyType = o.MyType } @@ -342,6 +345,14 @@ func NewDog(name string, o ...DogOption) Dog {…} func NewBird(name string, o ...BirdOption) Bird {…} ``` +### Interface Type + +To allow other developers to better comprehend the code, it is important +to ensure it is sufficiently documented. One simple measure that contributes +to this aim is self-documenting by naming method parameters. Therefore, +where appropriate, methods of every exported interface type should have +their parameters appropriately named. + ## Approvers and Maintainers Approvers: @@ -349,6 +360,8 @@ Approvers: - [Liz Fong-Jones](https://github.com/lizthegrey), Honeycomb - [Evan Torrie](https://github.com/evantorrie), Verizon Media - [Josh MacDonald](https://github.com/jmacd), LightStep +- [Sam Xie](https://github.com/XSAM) +- [David Ashpole](https://github.com/dashpole), Google Maintainers: @@ -358,4 +371,4 @@ Maintainers: ### Become an Approver or a Maintainer See the [community membership document in OpenTelemetry community -repo](https://github.com/open-telemetry/community/blob/master/community-membership.md). +repo](https://github.com/open-telemetry/community/blob/main/community-membership.md). diff --git a/vendor/go.opentelemetry.io/otel/Makefile b/vendor/go.opentelemetry.io/otel/Makefile index 9156960ca..46a44b5f6 100644 --- a/vendor/go.opentelemetry.io/otel/Makefile +++ b/vendor/go.opentelemetry.io/otel/Makefile @@ -13,145 +13,167 @@ # limitations under the License. EXAMPLES := $(shell ./get_main_pkgs.sh ./example) -TOOLS_MOD_DIR := ./tools +TOOLS_MOD_DIR := ./internal/tools # All source code and documents. Used in spell check. ALL_DOCS := $(shell find . -name '*.md' -type f | sort) # All directories with go.mod files related to opentelemetry library. Used for building, testing and linting. -ALL_GO_MOD_DIRS := $(filter-out $(TOOLS_MOD_DIR), $(shell find . -type f -name 'go.mod' -exec dirname {} \; | sort)) +ALL_GO_MOD_DIRS := $(filter-out $(TOOLS_MOD_DIR), $(shell find . -type f -name 'go.mod' -exec dirname {} \; | egrep -v '^./example' | sort)) $(shell find ./example -type f -name 'go.mod' -exec dirname {} \; | sort) ALL_COVERAGE_MOD_DIRS := $(shell find . -type f -name 'go.mod' -exec dirname {} \; | egrep -v '^./example|^$(TOOLS_MOD_DIR)' | sort) -# Mac OS Catalina 10.5.x doesn't support 386. Hence skip 386 test -SKIP_386_TEST = false -UNAME_S := $(shell uname -s) -ifeq ($(UNAME_S),Darwin) - SW_VERS := $(shell sw_vers -productVersion) - ifeq ($(shell echo $(SW_VERS) | egrep '^(10.1[5-9]|1[1-9]|[2-9])'), $(SW_VERS)) - SKIP_386_TEST = true - endif -endif - -GOTEST_MIN = go test -timeout 30s -GOTEST = $(GOTEST_MIN) -race -GOTEST_WITH_COVERAGE = $(GOTEST) -coverprofile=coverage.out -covermode=atomic -coverpkg=./... +GO = go +TIMEOUT = 60 .DEFAULT_GOAL := precommit -.PHONY: precommit +.PHONY: precommit ci +precommit: dependabot-check license-check lint build examples test-default +ci: precommit check-clean-work-tree test-coverage -TOOLS_DIR := $(abspath ./.tools) +# Tools -$(TOOLS_DIR)/golangci-lint: $(TOOLS_MOD_DIR)/go.mod $(TOOLS_MOD_DIR)/go.sum $(TOOLS_MOD_DIR)/tools.go - cd $(TOOLS_MOD_DIR) && \ - go build -o $(TOOLS_DIR)/golangci-lint github.com/golangci/golangci-lint/cmd/golangci-lint +TOOLS = $(CURDIR)/.tools -$(TOOLS_DIR)/misspell: $(TOOLS_MOD_DIR)/go.mod $(TOOLS_MOD_DIR)/go.sum $(TOOLS_MOD_DIR)/tools.go +$(TOOLS): + @mkdir -p $@ +$(TOOLS)/%: | $(TOOLS) cd $(TOOLS_MOD_DIR) && \ - go build -o $(TOOLS_DIR)/misspell github.com/client9/misspell/cmd/misspell + $(GO) build -o $@ $(PACKAGE) -$(TOOLS_DIR)/stringer: $(TOOLS_MOD_DIR)/go.mod $(TOOLS_MOD_DIR)/go.sum $(TOOLS_MOD_DIR)/tools.go - cd $(TOOLS_MOD_DIR) && \ - go build -o $(TOOLS_DIR)/stringer golang.org/x/tools/cmd/stringer +CROSSLINK = $(TOOLS)/crosslink +$(TOOLS)/crosslink: PACKAGE=go.opentelemetry.io/otel/$(TOOLS_MOD_DIR)/crosslink -$(TOOLS_DIR)/gojq: $(TOOLS_MOD_DIR)/go.mod $(TOOLS_MOD_DIR)/go.sum $(TOOLS_MOD_DIR)/tools.go - cd $(TOOLS_MOD_DIR) && \ - go build -o $(TOOLS_DIR)/gojq github.com/itchyny/gojq/cmd/gojq +GOLANGCI_LINT = $(TOOLS)/golangci-lint +$(TOOLS)/golangci-lint: PACKAGE=github.com/golangci/golangci-lint/cmd/golangci-lint -precommit: generate build lint examples test +MISSPELL = $(TOOLS)/misspell +$(TOOLS)/misspell: PACKAGE= github.com/client9/misspell/cmd/misspell -.PHONY: test-with-coverage -test-with-coverage: - set -e; \ - printf "" > coverage.txt; \ - for dir in $(ALL_COVERAGE_MOD_DIRS); do \ - echo "go test ./... + coverage in $${dir}"; \ - (cd "$${dir}" && \ - $(GOTEST_WITH_COVERAGE) ./... && \ - go tool cover -html=coverage.out -o coverage.html); \ - [ -f "$${dir}/coverage.out" ] && cat "$${dir}/coverage.out" >> coverage.txt; \ - done; \ - sed -i.bak -e '2,$$ { /^mode: /d; }' coverage.txt +STRINGER = $(TOOLS)/stringer +$(TOOLS)/stringer: PACKAGE=golang.org/x/tools/cmd/stringer +$(TOOLS)/gojq: PACKAGE=github.com/itchyny/gojq/cmd/gojq -.PHONY: ci -ci: precommit check-clean-work-tree license-check test-with-coverage test-386 +.PHONY: tools +tools: $(CROSSLINK) $(GOLANGCI_LINT) $(MISSPELL) $(STRINGER) $(TOOLS)/gojq -.PHONY: check-clean-work-tree -check-clean-work-tree: - @if ! git diff --quiet; then \ - echo; \ - echo 'Working tree is not clean, did you forget to run "make precommit"?'; \ - echo; \ - git status; \ - exit 1; \ - fi -.PHONY: build -build: - # TODO: Fix this on windows. +# Build + +.PHONY: examples generate build +examples: + @set -e; for ex in $(EXAMPLES); do \ + echo "$(GO) build $${dir}/..."; \ + (cd "$${ex}" && \ + $(GO) build .); \ + done + +generate: $(STRINGER) set -e; for dir in $(ALL_GO_MOD_DIRS); do \ - echo "compiling all packages in $${dir}"; \ + echo "$(GO) generate $${dir}/..."; \ (cd "$${dir}" && \ - go build ./... && \ - go test -run xxxxxMatchNothingxxxxx ./... >/dev/null); \ + PATH="$(TOOLS):$${PATH}" $(GO) generate ./...); \ done -.PHONY: test -test: +build: generate + # Build all package code including testing code. set -e; for dir in $(ALL_GO_MOD_DIRS); do \ - echo "go test ./... + race in $${dir}"; \ + echo "$(GO) build $${dir}/..."; \ (cd "$${dir}" && \ - $(GOTEST) ./...); \ + $(GO) build ./... && \ + $(GO) list ./... \ + | grep -v third_party \ + | xargs $(GO) test -vet=off -run xxxxxMatchNothingxxxxx >/dev/null); \ done -.PHONY: test-386 -test-386: - if [ $(SKIP_386_TEST) = true ] ; then \ - echo "skipping the test for GOARCH 386 as it is not supported on the current OS"; \ - else \ - set -e; for dir in $(ALL_GO_MOD_DIRS); do \ - echo "go test ./... GOARCH 386 in $${dir}"; \ - (cd "$${dir}" && \ - GOARCH=386 $(GOTEST_MIN) ./...); \ - done; \ - fi +# Tests -.PHONY: examples -examples: - @set -e; for ex in $(EXAMPLES); do \ - echo "Building $${ex}"; \ - (cd "$${ex}" && \ - go build .); \ +TEST_TARGETS := test-default test-bench test-short test-verbose test-race +.PHONY: $(TEST_TARGETS) test +test-default: ARGS=-v -race +test-bench: ARGS=-run=xxxxxMatchNothingxxxxx -test.benchtime=1ms -bench=. +test-short: ARGS=-short +test-verbose: ARGS=-v +test-race: ARGS=-race +$(TEST_TARGETS): test +test: + @set -e; for dir in $(ALL_GO_MOD_DIRS); do \ + echo "$(GO) test -timeout $(TIMEOUT)s $(ARGS) $${dir}/..."; \ + (cd "$${dir}" && \ + $(GO) list ./... \ + | grep -v third_party \ + | xargs $(GO) test -timeout $(TIMEOUT)s $(ARGS)); \ done +COVERAGE_MODE = atomic +COVERAGE_PROFILE = coverage.out +.PHONY: test-coverage +test-coverage: + @set -e; \ + printf "" > coverage.txt; \ + for dir in $(ALL_COVERAGE_MOD_DIRS); do \ + echo "$(GO) test -coverpkg=./... -covermode=$(COVERAGE_MODE) -coverprofile="$(COVERAGE_PROFILE)" $${dir}/..."; \ + (cd "$${dir}" && \ + $(GO) list ./... \ + | grep -v third_party \ + | xargs $(GO) test -coverpkg=./... -covermode=$(COVERAGE_MODE) -coverprofile="$(COVERAGE_PROFILE)" && \ + $(GO) tool cover -html=coverage.out -o coverage.html); \ + [ -f "$${dir}/coverage.out" ] && cat "$${dir}/coverage.out" >> coverage.txt; \ + done; \ + sed -i.bak -e '2,$$ { /^mode: /d; }' coverage.txt + .PHONY: lint -lint: $(TOOLS_DIR)/golangci-lint $(TOOLS_DIR)/misspell +lint: misspell lint-modules | $(GOLANGCI_LINT) set -e; for dir in $(ALL_GO_MOD_DIRS); do \ echo "golangci-lint in $${dir}"; \ (cd "$${dir}" && \ - $(TOOLS_DIR)/golangci-lint run --fix && \ - $(TOOLS_DIR)/golangci-lint run); \ - done - $(TOOLS_DIR)/misspell -w $(ALL_DOCS) - set -e; for dir in $(ALL_GO_MOD_DIRS) $(TOOLS_MOD_DIR); do \ - echo "go mod tidy in $${dir}"; \ - (cd "$${dir}" && \ - go mod tidy); \ + $(GOLANGCI_LINT) run --fix && \ + $(GOLANGCI_LINT) run); \ done -generate: $(TOOLS_DIR)/stringer - set -e; for dir in $(ALL_GO_MOD_DIRS); do \ - echo "running generators in $${dir}"; \ +.PHONY: misspell +misspell: | $(MISSPELL) + $(MISSPELL) -w $(ALL_DOCS) + +.PHONY: lint-modules +lint-modules: | $(CROSSLINK) + set -e; for dir in $(ALL_GO_MOD_DIRS) $(TOOLS_MOD_DIR); do \ + echo "$(GO) mod tidy in $${dir}"; \ (cd "$${dir}" && \ - PATH="$(TOOLS_DIR):$${PATH}" go generate ./...); \ + $(GO) mod tidy); \ done + echo "cross-linking all go modules" + $(CROSSLINK) .PHONY: license-check license-check: - @licRes=$$(for f in $$(find . -type f \( -iname '*.go' -o -iname '*.sh' \) ! -path './vendor/*' ! -path './exporters/otlp/internal/opentelemetry-proto/*') ; do \ + @licRes=$$(for f in $$(find . -type f \( -iname '*.go' -o -iname '*.sh' \) ! -path '**/third_party/*' ! -path './exporters/otlp/internal/opentelemetry-proto/*') ; do \ awk '/Copyright The OpenTelemetry Authors|generated|GENERATED/ && NR<=3 { found=1; next } END { if (!found) print FILENAME }' $$f; \ done); \ if [ -n "$${licRes}" ]; then \ echo "license header checking failed:"; echo "$${licRes}"; \ exit 1; \ fi + +.PHONY: dependabot-check +dependabot-check: + @result=$$( \ + for f in $$( find . -type f -name go.mod -exec dirname {} \; | sed 's/^.\/\?/\//' ); \ + do grep -q "$$f" .github/dependabot.yml \ + || echo "$$f"; \ + done; \ + ); \ + if [ -n "$$result" ]; then \ + echo "missing go.mod dependabot check:"; echo "$$result"; \ + exit 1; \ + fi + +.PHONY: check-clean-work-tree +check-clean-work-tree: + @if ! git diff --quiet; then \ + echo; \ + echo 'Working tree is not clean, did you forget to run "make precommit"?'; \ + echo; \ + git status; \ + exit 1; \ + fi diff --git a/vendor/go.opentelemetry.io/otel/Makefile.proto b/vendor/go.opentelemetry.io/otel/Makefile.proto deleted file mode 100644 index 417c3b31c..000000000 --- a/vendor/go.opentelemetry.io/otel/Makefile.proto +++ /dev/null @@ -1,72 +0,0 @@ -# -*- mode: makefile; -*- -# 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. -# -# This Makefile.proto has rules to generate *.pb.go files in -# `exporters/otlp/internal/opentelemetry-proto-gen` from the .proto files in -# `exporters/otlp/internal/opentelemetry-proto` using protoc with a go plugin. -# -# The protoc binary and other tools are sourced from a docker image -# `PROTOC_IMAGE`. -# -# Prereqs: The archiving utility `pax` is installed. - -PROTOC_IMAGE := namely/protoc-all:1.29_2 -PROTOBUF_VERSION := v1 -OTEL_PROTO_SUBMODULE := exporters/otlp/internal/opentelemetry-proto -PROTOBUF_GEN_DIR := exporters/otlp/internal/opentelemetry-proto-gen -PROTOBUF_TEMP_DIR := gen/pb-go -PROTO_SOURCE_DIR := gen/proto -SUBMODULE_PROTO_FILES := $(wildcard $(OTEL_PROTO_SUBMODULE)/opentelemetry/proto/*/$(PROTOBUF_VERSION)/*.proto \ - $(OTEL_PROTO_SUBMODULE)/opentelemetry/proto/collector/*/$(PROTOBUF_VERSION)/*.proto) -SOURCE_PROTO_FILES := $(subst $(OTEL_PROTO_SUBMODULE),$(PROTO_SOURCE_DIR),$(SUBMODULE_PROTO_FILES)) - -default: protobuf - -.PHONY: protobuf protobuf-source gen-protobuf copy-protobufs -protobuf: protobuf-source gen-protobuf copy-protobufs - -protobuf-source: $(SOURCE_PROTO_FILES) | $(PROTO_SOURCE_DIR)/ - -# Changes go_package in .proto file to point to repo-local location -define exec-replace-pkgname -sed 's,go_package = "github.com/open-telemetry/opentelemetry-proto/gen/go,go_package = "go.opentelemetry.io/otel/exporters/otlp/internal/opentelemetry-proto-gen,' < $(1) > $(2) - -endef - -# replace opentelemetry-proto package name by go.opentelemetry.io/otel specific version -$(SOURCE_PROTO_FILES): $(PROTO_SOURCE_DIR)/%.proto: $(OTEL_PROTO_SUBMODULE)/%.proto - @mkdir -p $(@D) - $(call exec-replace-pkgname,$<,$@) - -# Command to run protoc using docker image -define exec-protoc-all -docker run -v `pwd`:/defs $(PROTOC_IMAGE) $(1) - -endef - -gen-protobuf: $(SOURCE_PROTO_FILES) | $(PROTOBUF_GEN_DIR)/ - $(foreach file,$(subst ${PROTO_SOURCE_DIR}/,,$(SOURCE_PROTO_FILES)),$(call exec-protoc-all, -i $(PROTO_SOURCE_DIR) -f ${file} -l gogo -o ${PROTOBUF_TEMP_DIR})) - -# requires `pax` to be installed, as it has consistent options for both BSD (Darwin) and Linux -copy-protobufs: | $(PROTOBUF_GEN_DIR)/ - find ./$(PROTOBUF_TEMP_DIR)/go.opentelemetry.io/otel/$(PROTOBUF_GEN_DIR) -type f -print0 | \ - pax -0 -s ',^./$(PROTOBUF_TEMP_DIR)/go.opentelemetry.io/otel/$(PROTOBUF_GEN_DIR),,' -rw ./$(PROTOBUF_GEN_DIR) - -$(PROTO_SOURCE_DIR)/ $(PROTOBUF_GEN_DIR)/: - mkdir -p $@ - -.PHONY: clean -clean: - rm -rf ./gen diff --git a/vendor/go.opentelemetry.io/otel/Makefile.protos b/vendor/go.opentelemetry.io/otel/Makefile.protos new file mode 100644 index 000000000..16edc57ee --- /dev/null +++ b/vendor/go.opentelemetry.io/otel/Makefile.protos @@ -0,0 +1,129 @@ +# -*- mode: makefile; -*- +# 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. +# +# This Makefile.protos has rules to generate go code for otlp +# exporter. It does it by copying the proto files from +# `exporters/otlp/internal/opentelemetry-proto` (which is a +# submodule that needs to be checked out) into `gen/proto`, changing +# the go_package option to a valid string, generating the go files and +# finally copying the files into the module. The files are not +# generated in place, because protoc generates a too-deep directory +# structure. +# +# Currently, all the generated code is in +# `exporters/otlp/internal/opentelemetry-proto-gen`. +# +# Prereqs: wget (for downloading the zip file with protoc binary), +# unzip (for unpacking the archive), rsync (for copying back the +# generated files). + +PROTOC_VERSION := 3.14.0 + +TOOLS_DIR := $(abspath ./.tools) +TOOLS_MOD_DIR := ./internal/tools +PROTOBUF_VERSION := v1 +OTEL_PROTO_SUBMODULE := exporters/otlp/internal/opentelemetry-proto +GEN_TEMP_DIR := gen +SUBMODULE_PROTO_FILES := $(wildcard $(OTEL_PROTO_SUBMODULE)/opentelemetry/proto/*/$(PROTOBUF_VERSION)/*.proto) $(wildcard $(OTEL_PROTO_SUBMODULE)/opentelemetry/proto/collector/*/$(PROTOBUF_VERSION)/*.proto) + +ifeq ($(strip $(SUBMODULE_PROTO_FILES)),) +$(error Submodule at $(OTEL_PROTO_SUBMODULE) is not checked out, use "git submodule update --init") +endif + +PROTOBUF_GEN_DIR := exporters/otlp/internal/opentelemetry-proto-gen +PROTOBUF_TEMP_DIR := $(GEN_TEMP_DIR)/pb-go +PROTO_SOURCE_DIR := $(GEN_TEMP_DIR)/proto +SOURCE_PROTO_FILES := $(subst $(OTEL_PROTO_SUBMODULE),$(PROTO_SOURCE_DIR),$(SUBMODULE_PROTO_FILES)) + +.DEFAULT_GOAL := protobuf + +UNAME_S := $(shell uname -s) +UNAME_M := $(shell uname -m) + +ifeq ($(UNAME_S),Linux) + +PROTOC_OS := linux +PROTOC_ARCH := $(UNAME_M) + +else ifeq ($(UNAME_S),Darwin) + +PROTOC_OS := osx +PROTOC_ARCH := x86_64 + +endif + +PROTOC_ZIP_URL := https://github.com/protocolbuffers/protobuf/releases/download/v$(PROTOC_VERSION)/protoc-$(PROTOC_VERSION)-$(PROTOC_OS)-$(PROTOC_ARCH).zip + +$(TOOLS_DIR)/PROTOC_$(PROTOC_VERSION): + @rm -f "$(TOOLS_DIR)"/PROTOC_* && \ + touch "$@" + +# Depend on a versioned file (like PROTOC_3.14.0), so when version +# gets bumped, we will depend on a nonexistent file and thus download +# a newer version. +$(TOOLS_DIR)/protoc/bin/protoc: $(TOOLS_DIR)/PROTOC_$(PROTOC_VERSION) + echo "Fetching protoc $(PROTOC_VERSION)" && \ + rm -rf $(TOOLS_DIR)/protoc && \ + wget -O $(TOOLS_DIR)/protoc.zip $(PROTOC_ZIP_URL) && \ + unzip $(TOOLS_DIR)/protoc.zip -d $(TOOLS_DIR)/protoc-tmp && \ + rm $(TOOLS_DIR)/protoc.zip && \ + touch $(TOOLS_DIR)/protoc-tmp/bin/protoc && \ + mv $(TOOLS_DIR)/protoc-tmp $(TOOLS_DIR)/protoc + +$(TOOLS_DIR)/protoc-gen-gogofast: $(TOOLS_MOD_DIR)/go.mod $(TOOLS_MOD_DIR)/go.sum $(TOOLS_MOD_DIR)/tools.go + cd $(TOOLS_MOD_DIR) && \ + go build -o $(TOOLS_DIR)/protoc-gen-gogofast github.com/gogo/protobuf/protoc-gen-gogofast && \ + go mod tidy + +# Return a sed expression for replacing the go_package option in proto +# file with a one that's valid for us. +# +# Example: $(call get-sed-expr,$(PROTOBUF_GEN_DIR)) +define get-sed-expr +'s,go_package = "github.com/open-telemetry/opentelemetry-proto/gen/go,go_package = "go.opentelemetry.io/otel/$(1),' +endef + +.PHONY: protobuf +protobuf: protobuf-source gen-protobuf copy-protobufs + +.PHONY: protobuf-source +protobuf-source: $(SOURCE_PROTO_FILES) + +# This copies proto files from submodule into $(PROTO_SOURCE_DIR), +# thus satisfying the $(SOURCE_PROTO_FILES) prerequisite. The copies +# have their package name replaced by go.opentelemetry.io/otel. +$(PROTO_SOURCE_DIR)/%.proto: $(OTEL_PROTO_SUBMODULE)/%.proto + @ \ + mkdir -p $(@D); \ + sed -e $(call get-sed-expr,$(PROTOBUF_GEN_DIR)) "$<" >"$@.tmp"; \ + mv "$@.tmp" "$@" + +.PHONY: gen-protobuf +gen-protobuf: $(SOURCE_PROTO_FILES) $(TOOLS_DIR)/protoc-gen-gogofast $(TOOLS_DIR)/protoc/bin/protoc + @ \ + mkdir -p "$(PROTOBUF_TEMP_DIR)"; \ + set -e; for f in $^; do \ + if [[ "$${f}" == $(TOOLS_DIR)/* ]]; then continue; fi; \ + echo "protoc $${f#"$(PROTO_SOURCE_DIR)/"}"; \ + PATH="$(TOOLS_DIR):$${PATH}" $(TOOLS_DIR)/protoc/bin/protoc --proto_path="$(PROTO_SOURCE_DIR)" --gogofast_out="plugins=grpc:$(PROTOBUF_TEMP_DIR)" "$${f}"; \ + done + +.PHONY: copy-protobufs +copy-protobufs: + @rsync -a $(PROTOBUF_TEMP_DIR)/go.opentelemetry.io/otel/exporters . + +.PHONY: clean +clean: + rm -rf $(GEN_TEMP_DIR) diff --git a/vendor/go.opentelemetry.io/otel/README.md b/vendor/go.opentelemetry.io/otel/README.md index 55dbe2133..c841ba896 100644 --- a/vendor/go.opentelemetry.io/otel/README.md +++ b/vendor/go.opentelemetry.io/otel/README.md @@ -1,80 +1,92 @@ # OpenTelemetry-Go -[![Circle CI](https://circleci.com/gh/open-telemetry/opentelemetry-go.svg?style=svg)](https://circleci.com/gh/open-telemetry/opentelemetry-go) -[![Docs](https://godoc.org/go.opentelemetry.io/otel?status.svg)](https://pkg.go.dev/go.opentelemetry.io/otel) +[![CI](https://github.com/open-telemetry/opentelemetry-go/workflows/ci/badge.svg)](https://github.com/open-telemetry/opentelemetry-go/actions?query=workflow%3Aci+branch%3Amain) +[![PkgGoDev](https://pkg.go.dev/badge/go.opentelemetry.io/otel)](https://pkg.go.dev/go.opentelemetry.io/otel) [![Go Report Card](https://goreportcard.com/badge/go.opentelemetry.io/otel)](https://goreportcard.com/report/go.opentelemetry.io/otel) -[![Gitter](https://badges.gitter.im/open-telemetry/opentelemetry-go.svg)](https://gitter.im/open-telemetry/opentelemetry-go?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge) +[![Slack](https://img.shields.io/badge/slack-@cncf/otel--go-brightgreen.svg?logo=slack)](https://cloud-native.slack.com/archives/C01NPAXACKT) -The Go [OpenTelemetry](https://opentelemetry.io/) client. -## Installation +The Go [OpenTelemetry](https://opentelemetry.io/) implementation. -This repository includes multiple packages. The `api` -package contains core data types, interfaces and no-op implementations that comprise the OpenTelemetry API following -[the -specification](https://github.com/open-telemetry/opentelemetry-specification). -The `sdk` package is the reference implementation of the API. +## Project Status -Libraries that produce telemetry data should only depend on `api` -and defer the choice of the SDK to the application developer. Applications may -depend on `sdk` or another package that implements the API. +**Warning**: this project is currently in a pre-GA phase. Backwards +incompatible changes may be introduced in subsequent minor version releases as +we work to track the evolving OpenTelemetry specification and user feedback. -All packages are published to [go.opentelemetry.io/otel](https://pkg.go.dev/go.opentelemetry.io/otel) and is the preferred location to import from. +Our progress towards a GA release candidate is tracked in [this project +board](https://github.com/orgs/open-telemetry/projects/5). This release +candidate will follow semantic versioning and will be released with a major +version greater than zero. -Additional resources: +Progress and status specific to this repository is tracked in our local +[project boards](https://github.com/open-telemetry/opentelemetry-go/projects) +and +[milestones](https://github.com/open-telemetry/opentelemetry-go/milestones). -- [Developing using Go Modules](https://blog.golang.org/using-go-modules) -- [Adding dependencies and installing them](https://golang.org/cmd/go/#hdr-Add_dependencies_to_current_module_and_install_them) +Project versioning information and stability guarantees can be found in the +[versioning documentation](./VERSIONING.md). -## Quick Start +### Compatibility -Below is a brief example of importing OpenTelemetry, initializing a tracer and creating some simple spans. +This project is tested on the following systems. -```go -package main +| OS | Go Version | Architecture | +| ------- | ---------- | ------------ | +| Ubuntu | 1.15 | amd64 | +| Ubuntu | 1.14 | amd64 | +| Ubuntu | 1.15 | 386 | +| Ubuntu | 1.14 | 386 | +| MacOS | 1.15 | amd64 | +| MacOS | 1.14 | amd64 | +| Windows | 1.15 | amd64 | +| Windows | 1.14 | amd64 | +| Windows | 1.15 | 386 | +| Windows | 1.14 | 386 | -import ( - "context" - "log" +While this project should work for other systems, no compatibility guarantees +are made for those systems currently. - "go.opentelemetry.io/otel/api/global" - "go.opentelemetry.io/otel/exporters/stdout" - sdktrace "go.opentelemetry.io/otel/sdk/trace" -) +## Getting Started -func main() { - pusher, err := stdout.InstallNewPipeline(nil, nil) - if err != nil { - log.Fatal(err) - } - defer pusher.Stop() +You can find a getting started guide on [opentelemetry.io](https://opentelemetry.io/docs/go/getting-started/). - tracer := global.Tracer("ex.com/basic") - ctx, span := tracer.Start(context.Background(), "main") - defer span.End() - /* … */ -} -``` +OpenTelemetry's goal is to provide a single set of APIs to capture distributed +traces and metrics from your application and send them to an observability +platform. This project allows you to do just that for applications written in +Go. There are two steps to this process: instrument your application, and +configure an exporter. -See the [API -documentation](https://pkg.go.dev/go.opentelemetry.io/otel) for more -detail, and the -[opentelemetry examples](./example/). +### Instrumentation -## Compatible Exporters +To start capturing distributed traces and metric events from your application +it first needs to be instrumented. The easiest way to do this is by using an +instrumentation library for your code. Be sure to check out [the officially +supported instrumentation +libraries](https://github.com/open-telemetry/opentelemetry-go-contrib/tree/main/instrumentation). -See the Go packages depending upon -[sdk/export/trace](https://pkg.go.dev/go.opentelemetry.io/otel/sdk/export/trace?tab=importedby) -and [sdk/export/metric](https://pkg.go.dev/go.opentelemetry.io/otel/sdk/export/metric?tab=importedby) -for a list of all exporters compatible with OpenTelemetry's Go SDK. +If you need to extend the telemetry an instrumentation library provides or want +to build your own instrumentation for your application directly you will need +to use the +[go.opentelemetry.io/otel/api](https://pkg.go.dev/go.opentelemetry.io/otel/api) +package. The included [examples](./example/) are a good way to see some +practical uses of this process. -## Compatible Libraries +### Export -See the -[opentelemetry-go-contrib](https://github.com/open-telemetry/opentelemetry-go-contrib) -repo for packages that facilitates instrumenting other useful Go libraries -with opentelemetry-go for distributed tracing and monitoring. +Now that your application is instrumented to collect telemetry, it needs an +export pipeline to send that telemetry to an observability platform. + +You can find officially supported exporters [here](./exporters/) and in the +companion [contrib +repository](https://github.com/open-telemetry/opentelemetry-go-contrib/tree/main/exporters/metric). +Additionally, there are many vendor specific or 3rd party exporters for +OpenTelemetry. These exporters are broken down by +[trace](https://pkg.go.dev/go.opentelemetry.io/otel/sdk/export/trace?tab=importedby) +and +[metric](https://pkg.go.dev/go.opentelemetry.io/otel/sdk/export/metric?tab=importedby) +support. ## Contributing -See the [contributing file](CONTRIBUTING.md). +See the [contributing documentation](CONTRIBUTING.md). diff --git a/vendor/go.opentelemetry.io/otel/RELEASING.md b/vendor/go.opentelemetry.io/otel/RELEASING.md index 0fba7f175..71d23b47a 100644 --- a/vendor/go.opentelemetry.io/otel/RELEASING.md +++ b/vendor/go.opentelemetry.io/otel/RELEASING.md @@ -13,7 +13,7 @@ Update go.mod for submodules to depend on the new release which will happen in t 2. Verify the changes. ``` - git diff master + git diff main ``` This should have changed the version for all modules to be ``. @@ -44,7 +44,7 @@ Failure to do so will leave things in a broken state. It is critical you make sure the version you push upstream is correct. [Failure to do so will lead to minor emergencies and tough to work around](https://github.com/open-telemetry/opentelemetry-go/issues/331). -1. Run the tag.sh script using the `` of the commit on the master branch for the merged Pull Request. +1. Run the tag.sh script using the `` of the commit on the main branch for the merged Pull Request. ``` ./tag.sh @@ -78,4 +78,4 @@ This ensures they build with the published release, not the local copy. ## Contrib Repository -Once verified be sure to [make a release for the `contrib` repository](https://github.com/open-telemetry/opentelemetry-go-contrib/blob/master/RELEASING.md) that uses this release. +Once verified be sure to [make a release for the `contrib` repository](https://github.com/open-telemetry/opentelemetry-go-contrib/blob/main/RELEASING.md) that uses this release. diff --git a/vendor/go.opentelemetry.io/otel/VERSIONING.md b/vendor/go.opentelemetry.io/otel/VERSIONING.md new file mode 100644 index 000000000..3579b794e --- /dev/null +++ b/vendor/go.opentelemetry.io/otel/VERSIONING.md @@ -0,0 +1,217 @@ +# Versioning + +This document describes the versioning policy for this repository. This policy +is designed so the following goals can be achieved. + +**Users are provided a codebase of value that is stable and secure.** + +## Policy + +* Versioning of this project will be idiomatic of a Go project using [Go + modules](https://github.com/golang/go/wiki/Modules). + * [Semantic import + versioning](https://github.com/golang/go/wiki/Modules#semantic-import-versioning) + will be used. + * Versions will comply with [semver 2.0](https://semver.org/spec/v2.0.0.html). + * If a module is version `v2` or higher, the major version of the module + must be included as a `/vN` at the end of the module paths used in + `go.mod` files (e.g., `module go.opentelemetry.io/otel/v2`, `require + go.opentelemetry.io/otel/v2 v2.0.1`) and in the package import path + (e.g., `import "go.opentelemetry.io/otel/v2/trace"`). This includes the + paths used in `go get` commands (e.g., `go get + go.opentelemetry.io/otel/v2@v2.0.1`. Note there is both a `/v2` and a + `@v2.0.1` in that example. One way to think about it is that the module + name now includes the `/v2`, so include `/v2` whenever you are using the + module name). + * If a module is version `v0` or `v1`, do not include the major version in + either the module path or the import path. + * Modules will be used to encapsulate signals and components. + * Experimental modules still under active development will be versioned at + `v0` to imply the stability guarantee defined by + [semver](https://semver.org/spec/v2.0.0.html#spec-item-4). + + > Major version zero (0.y.z) is for initial development. Anything MAY + > change at any time. The public API SHOULD NOT be considered stable. + + * Mature modules for which we guarantee a stable public API will be versioned + with a major version greater than `v0`. + * The decision to make a module stable will be made on a case-by-case + basis by the maintainers of this project. + * Experimental modules will start their versioning at `v0.0.0` and will + increment their minor version when backwards incompatible changes are + released and increment their patch version when backwards compatible + changes are released. + * All stable modules that use the same major version number will use the + same entire version number. + * Stable modules may be released with an incremented minor or patch + version even though that module has not been changed, but rather so + that it will remain at the same version as other stable modules that + did undergo change. + * When an experimental module becomes stable a new stable module version + will be released and will include this now stable module. The new + stable module version will be an increment of the minor version number + and will be applied to all existing stable modules as well as the newly + stable module being released. +* Versioning of the associated [contrib + repository](https://github.com/open-telemetry/opentelemetry-go-contrib) of + this project will be idiomatic of a Go project using [Go + modules](https://github.com/golang/go/wiki/Modules). + * [Semantic import + versioning](https://github.com/golang/go/wiki/Modules#semantic-import-versioning) + will be used. + * Versions will comply with [semver 2.0](https://semver.org/spec/v2.0.0.html). + * If a module is version `v2` or higher, the + major version of the module must be included as a `/vN` at the end of the + module paths used in `go.mod` files (e.g., `module + go.opentelemetry.io/contrib/instrumentation/host/v2`, `require + go.opentelemetry.io/contrib/instrumentation/host/v2 v2.0.1`) and in the + package import path (e.g., `import + "go.opentelemetry.io/contrib/instrumentation/host/v2"`). This includes + the paths used in `go get` commands (e.g., `go get + go.opentelemetry.io/contrib/instrumentation/host/v2@v2.0.1`. Note there + is both a `/v2` and a `@v2.0.1` in that example. One way to think about + it is that the module name now includes the `/v2`, so include `/v2` + whenever you are using the module name). + * If a module is version `v0` or `v1`, do not include the major version + in either the module path or the import path. + * In addition to public APIs, telemetry produced by stable instrumentation + will remain stable and backwards compatible. This is to avoid breaking + alerts and dashboard. + * Modules will be used to encapsulate instrumentation, detectors, exporters, + propagators, and any other independent sets of related components. + * Experimental modules still under active development will be versioned at + `v0` to imply the stability guarantee defined by + [semver](https://semver.org/spec/v2.0.0.html#spec-item-4). + + > Major version zero (0.y.z) is for initial development. Anything MAY + > change at any time. The public API SHOULD NOT be considered stable. + + * Mature modules for which we guarantee a stable public API and telemetry will + be versioned with a major version greater than `v0`. + * Experimental modules will start their versioning at `v0.0.0` and will + increment their minor version when backwards incompatible changes are + released and increment their patch version when backwards compatible + changes are released. + * Stable contrib modules cannot depend on experimental modules from this + project. + * All stable contrib modules of the same major version with this project + will use the same entire version as this project. + * Stable modules may be released with an incremented minor or patch + version even though that module's code has not been changed. Instead + the only change that will have been included is to have updated that + modules dependency on this project's stable APIs. + * When an experimental module in contrib becomes stable a new stable + module version will be released and will include this now stable + module. The new stable module version will be an increment of the minor + version number and will be applied to all existing stable contrib + modules, this project's modules, and the newly stable module being + released. + * Contrib modules will be kept up to date with this project's releases. + * Due to the dependency contrib modules will implicitly have on this + project's modules the release of stable contrib modules to match the + released version number will be staggered after this project's release. + There is no explicit time guarantee for how long after this projects + release the contrib release will be. Effort should be made to keep them + as close in time as possible. + * No additional stable release in this project can be made until the + contrib repository has a matching stable release. + * No release can be made in the contrib repository after this project's + stable release except for a stable release of the contrib repository. +* GitHub releases will be made for all releases. +* Go modules will be made available at Go package mirrors. + +## Example Versioning Lifecycle + +To better understand the implementation of the above policy the following +example is provided. This project is simplified to include only the following +modules and their versions: + +* `otel`: `v0.14.0` +* `otel/trace`: `v0.14.0` +* `otel/metric`: `v0.14.0` +* `otel/baggage`: `v0.14.0` +* `otel/sdk/trace`: `v0.14.0` +* `otel/sdk/metric`: `v0.14.0` + +These modules have been developed to a point where the `otel/trace`, +`otel/baggage`, and `otel/sdk/trace` modules have reached a point that they +should be considered for a stable release. The `otel/metric` and +`otel/sdk/metric` are still under active development and the `otel` module +depends on both `otel/trace` and `otel/metric`. + +The `otel` package is refactored to remove its dependencies on `otel/metric` so +it can be released as stable as well. With that done the following release +candidates are made: + +* `otel`: `v1.0.0-rc.1` +* `otel/trace`: `v1.0.0-rc.1` +* `otel/baggage`: `v1.0.0-rc.1` +* `otel/sdk/trace`: `v1.0.0-rc.1` + +The `otel/metric` and `otel/sdk/metric` modules remain at `v0.14.0`. + +A few minor issues are discovered in the `otel/trace` package. These issues are +resolved with some minor, but backwards incompatible, changes and are released +as a second release candidate: + +* `otel`: `v1.0.0-rc.2` +* `otel/trace`: `v1.0.0-rc.2` +* `otel/baggage`: `v1.0.0-rc.2` +* `otel/sdk/trace`: `v1.0.0-rc.2` + +Notice that all module version numbers are incremented to adhere to our +versioning policy. + +After these release candidates have been evaluated to satisfaction, they are +released as version `v1.0.0`. + +* `otel`: `v1.0.0` +* `otel/trace`: `v1.0.0` +* `otel/baggage`: `v1.0.0` +* `otel/sdk/trace`: `v1.0.0` + +Since both the `go` utility and the Go module system support [the semantic +versioning definition of +precedence](https://semver.org/spec/v2.0.0.html#spec-item-11), this release +will correctly be interpreted as the successor to the previous release +candidates. + +Active development of this project continues. The `otel/metric` module now has +backwards incompatible changes to its API that need to be released and the +`otel/baggage` module has a minor bug fix that needs to be released. The +following release is made: + +* `otel`: `v1.0.1` +* `otel/trace`: `v1.0.1` +* `otel/metric`: `v0.15.0` +* `otel/baggage`: `v1.0.1` +* `otel/sdk/trace`: `v1.0.1` +* `otel/sdk/metric`: `v0.15.0` + +Notice that, again, all stable module versions are incremented in unison and +the `otel/sdk/metric` package, which depends on the `otel/metric` package, also +bumped its version. This bump of the `otel/sdk/metric` package makes sense +given their coupling, though it is not explicitly required by our versioning +policy. + +As we progress, the `otel/metric` and `otel/sdk/metric` packages have reached a +point where they should be evaluated for stability. The `otel` module is +reintegrated with the `otel/metric` package and the following release is made: + +* `otel`: `v1.1.0-rc.1` +* `otel/trace`: `v1.1.0-rc.1` +* `otel/metric`: `v1.1.0-rc.1` +* `otel/baggage`: `v1.1.0-rc.1` +* `otel/sdk/trace`: `v1.1.0-rc.1` +* `otel/sdk/metric`: `v1.1.0-rc.1` + +All the modules are evaluated and determined to a viable stable release. They +are then released as version `v1.1.0` (the minor version is incremented to +indicate the addition of new signal). + +* `otel`: `v1.1.0` +* `otel/trace`: `v1.1.0` +* `otel/metric`: `v1.1.0` +* `otel/baggage`: `v1.1.0` +* `otel/sdk/trace`: `v1.1.0` +* `otel/sdk/metric`: `v1.1.0` diff --git a/vendor/go.opentelemetry.io/otel/api/correlation/doc.go b/vendor/go.opentelemetry.io/otel/api/correlation/doc.go deleted file mode 100644 index 1147a4f39..000000000 --- a/vendor/go.opentelemetry.io/otel/api/correlation/doc.go +++ /dev/null @@ -1,19 +0,0 @@ -// 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. - -// This package implements the correlation functionality as specified -// in the OpenTelemetry specification. Currently it provides a data -// structure for storing correlations (Map) and a way of putting Map -// object into the context and retrieving it from context. -package correlation // import "go.opentelemetry.io/otel/api/correlation" diff --git a/vendor/go.opentelemetry.io/otel/api/correlation/map.go b/vendor/go.opentelemetry.io/otel/api/correlation/map.go deleted file mode 100644 index df517da49..000000000 --- a/vendor/go.opentelemetry.io/otel/api/correlation/map.go +++ /dev/null @@ -1,176 +0,0 @@ -// 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 correlation - -import "go.opentelemetry.io/otel/label" - -type rawMap map[label.Key]label.Value -type keySet map[label.Key]struct{} - -// Map is an immutable storage for correlations. -type Map struct { - m rawMap -} - -// MapUpdate contains information about correlation changes to be -// made. -type MapUpdate struct { - // DropSingleK contains a single key to be dropped from - // correlations. Use this to avoid an overhead of a slice - // allocation if there is only one key to drop. - DropSingleK label.Key - // DropMultiK contains all the keys to be dropped from - // correlations. - DropMultiK []label.Key - - // SingleKV contains a single key-value pair to be added to - // correlations. Use this to avoid an overhead of a slice - // allocation if there is only one key-value pair to add. - SingleKV label.KeyValue - // MultiKV contains all the key-value pairs to be added to - // correlations. - MultiKV []label.KeyValue -} - -func newMap(raw rawMap) Map { - return Map{ - m: raw, - } -} - -// NewEmptyMap creates an empty correlations map. -func NewEmptyMap() Map { - return newMap(nil) -} - -// NewMap creates a map with the contents of the update applied. In -// this function, having an update with DropSingleK or DropMultiK -// makes no sense - those fields are effectively ignored. -func NewMap(update MapUpdate) Map { - return NewEmptyMap().Apply(update) -} - -// Apply creates a copy of the map with the contents of the update -// applied. Apply will first drop the keys from DropSingleK and -// DropMultiK, then add key-value pairs from SingleKV and MultiKV. -func (m Map) Apply(update MapUpdate) Map { - delSet, addSet := getModificationSets(update) - mapSize := getNewMapSize(m.m, delSet, addSet) - - r := make(rawMap, mapSize) - for k, v := range m.m { - // do not copy items we want to drop - if _, ok := delSet[k]; ok { - continue - } - // do not copy items we would overwrite - if _, ok := addSet[k]; ok { - continue - } - r[k] = v - } - if update.SingleKV.Key.Defined() { - r[update.SingleKV.Key] = update.SingleKV.Value - } - for _, kv := range update.MultiKV { - r[kv.Key] = kv.Value - } - if len(r) == 0 { - r = nil - } - return newMap(r) -} - -func getModificationSets(update MapUpdate) (delSet, addSet keySet) { - deletionsCount := len(update.DropMultiK) - if update.DropSingleK.Defined() { - deletionsCount++ - } - if deletionsCount > 0 { - delSet = make(map[label.Key]struct{}, deletionsCount) - for _, k := range update.DropMultiK { - delSet[k] = struct{}{} - } - if update.DropSingleK.Defined() { - delSet[update.DropSingleK] = struct{}{} - } - } - - additionsCount := len(update.MultiKV) - if update.SingleKV.Key.Defined() { - additionsCount++ - } - if additionsCount > 0 { - addSet = make(map[label.Key]struct{}, additionsCount) - for _, k := range update.MultiKV { - addSet[k.Key] = struct{}{} - } - if update.SingleKV.Key.Defined() { - addSet[update.SingleKV.Key] = struct{}{} - } - } - - return -} - -func getNewMapSize(m rawMap, delSet, addSet keySet) int { - mapSizeDiff := 0 - for k := range addSet { - if _, ok := m[k]; !ok { - mapSizeDiff++ - } - } - for k := range delSet { - if _, ok := m[k]; ok { - if _, inAddSet := addSet[k]; !inAddSet { - mapSizeDiff-- - } - } - } - return len(m) + mapSizeDiff -} - -// Value gets a value from correlations map and returns a boolean -// value indicating whether the key exist in the map. -func (m Map) Value(k label.Key) (label.Value, bool) { - value, ok := m.m[k] - return value, ok -} - -// HasValue returns a boolean value indicating whether the key exist -// in the map. -func (m Map) HasValue(k label.Key) bool { - _, has := m.Value(k) - return has -} - -// Len returns a length of the map. -func (m Map) Len() int { - return len(m.m) -} - -// Foreach calls a passed callback once on each key-value pair until -// all the key-value pairs of the map were iterated or the callback -// returns false, whichever happens first. -func (m Map) Foreach(f func(label.KeyValue) bool) { - for k, v := range m.m { - if !f(label.KeyValue{ - Key: k, - Value: v, - }) { - return - } - } -} diff --git a/vendor/go.opentelemetry.io/otel/api/metric/async.go b/vendor/go.opentelemetry.io/otel/api/metric/async.go deleted file mode 100644 index d0d488df1..000000000 --- a/vendor/go.opentelemetry.io/otel/api/metric/async.go +++ /dev/null @@ -1,217 +0,0 @@ -// 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 metric - -import ( - "context" - - "go.opentelemetry.io/otel/label" -) - -// The file is organized as follows: -// -// - Observation type -// - Three kinds of Observer callback (int64, float64, batch) -// - Three kinds of Observer result (int64, float64, batch) -// - Three kinds of Observe() function (int64, float64, batch) -// - Three kinds of AsyncRunner interface (abstract, single, batch) -// - Two kinds of Observer constructor (int64, float64) -// - Two kinds of Observation() function (int64, float64) -// - Various internals - -// Observation is used for reporting an asynchronous batch of metric -// values. Instances of this type should be created by asynchronous -// instruments (e.g., Int64ValueObserver.Observation()). -type Observation struct { - // number needs to be aligned for 64-bit atomic operations. - number Number - instrument AsyncImpl -} - -// Int64ObserverFunc is a type of callback that integral -// observers run. -type Int64ObserverFunc func(context.Context, Int64ObserverResult) - -// Float64ObserverFunc is a type of callback that floating point -// observers run. -type Float64ObserverFunc func(context.Context, Float64ObserverResult) - -// BatchObserverFunc is a callback argument for use with any -// Observer instrument that will be reported as a batch of -// observations. -type BatchObserverFunc func(context.Context, BatchObserverResult) - -// Int64ObserverResult is passed to an observer callback to capture -// observations for one asynchronous integer metric instrument. -type Int64ObserverResult struct { - instrument AsyncImpl - function func([]label.KeyValue, ...Observation) -} - -// Float64ObserverResult is passed to an observer callback to capture -// observations for one asynchronous floating point metric instrument. -type Float64ObserverResult struct { - instrument AsyncImpl - function func([]label.KeyValue, ...Observation) -} - -// BatchObserverResult is passed to a batch observer callback to -// capture observations for multiple asynchronous instruments. -type BatchObserverResult struct { - function func([]label.KeyValue, ...Observation) -} - -// Observe captures a single integer value from the associated -// instrument callback, with the given labels. -func (ir Int64ObserverResult) Observe(value int64, labels ...label.KeyValue) { - ir.function(labels, Observation{ - instrument: ir.instrument, - number: NewInt64Number(value), - }) -} - -// Observe captures a single floating point value from the associated -// instrument callback, with the given labels. -func (fr Float64ObserverResult) Observe(value float64, labels ...label.KeyValue) { - fr.function(labels, Observation{ - instrument: fr.instrument, - number: NewFloat64Number(value), - }) -} - -// Observe captures a multiple observations from the associated batch -// instrument callback, with the given labels. -func (br BatchObserverResult) Observe(labels []label.KeyValue, obs ...Observation) { - br.function(labels, obs...) -} - -// AsyncRunner is expected to convert into an AsyncSingleRunner or an -// AsyncBatchRunner. SDKs will encounter an error if the AsyncRunner -// does not satisfy one of these interfaces. -type AsyncRunner interface { - // AnyRunner() is a non-exported method with no functional use - // other than to make this a non-empty interface. - AnyRunner() -} - -// AsyncSingleRunner is an interface implemented by single-observer -// callbacks. -type AsyncSingleRunner interface { - // Run accepts a single instrument and function for capturing - // observations of that instrument. Each call to the function - // receives one captured observation. (The function accepts - // multiple observations so the same implementation can be - // used for batch runners.) - Run(ctx context.Context, single AsyncImpl, capture func([]label.KeyValue, ...Observation)) - - AsyncRunner -} - -// AsyncBatchRunner is an interface implemented by batch-observer -// callbacks. -type AsyncBatchRunner interface { - // Run accepts a function for capturing observations of - // multiple instruments. - Run(ctx context.Context, capture func([]label.KeyValue, ...Observation)) - - AsyncRunner -} - -var _ AsyncSingleRunner = (*Int64ObserverFunc)(nil) -var _ AsyncSingleRunner = (*Float64ObserverFunc)(nil) -var _ AsyncBatchRunner = (*BatchObserverFunc)(nil) - -// newInt64AsyncRunner returns a single-observer callback for integer Observer instruments. -func newInt64AsyncRunner(c Int64ObserverFunc) AsyncSingleRunner { - return &c -} - -// newFloat64AsyncRunner returns a single-observer callback for floating point Observer instruments. -func newFloat64AsyncRunner(c Float64ObserverFunc) AsyncSingleRunner { - return &c -} - -// newBatchAsyncRunner returns a batch-observer callback use with multiple Observer instruments. -func newBatchAsyncRunner(c BatchObserverFunc) AsyncBatchRunner { - return &c -} - -// AnyRunner implements AsyncRunner. -func (*Int64ObserverFunc) AnyRunner() {} - -// AnyRunner implements AsyncRunner. -func (*Float64ObserverFunc) AnyRunner() {} - -// AnyRunner implements AsyncRunner. -func (*BatchObserverFunc) AnyRunner() {} - -// Run implements AsyncSingleRunner. -func (i *Int64ObserverFunc) Run(ctx context.Context, impl AsyncImpl, function func([]label.KeyValue, ...Observation)) { - (*i)(ctx, Int64ObserverResult{ - instrument: impl, - function: function, - }) -} - -// Run implements AsyncSingleRunner. -func (f *Float64ObserverFunc) Run(ctx context.Context, impl AsyncImpl, function func([]label.KeyValue, ...Observation)) { - (*f)(ctx, Float64ObserverResult{ - instrument: impl, - function: function, - }) -} - -// Run implements AsyncBatchRunner. -func (b *BatchObserverFunc) Run(ctx context.Context, function func([]label.KeyValue, ...Observation)) { - (*b)(ctx, BatchObserverResult{ - function: function, - }) -} - -// wrapInt64ValueObserverInstrument converts an AsyncImpl into Int64ValueObserver. -func wrapInt64ValueObserverInstrument(asyncInst AsyncImpl, err error) (Int64ValueObserver, error) { - common, err := checkNewAsync(asyncInst, err) - return Int64ValueObserver{asyncInstrument: common}, err -} - -// wrapFloat64ValueObserverInstrument converts an AsyncImpl into Float64ValueObserver. -func wrapFloat64ValueObserverInstrument(asyncInst AsyncImpl, err error) (Float64ValueObserver, error) { - common, err := checkNewAsync(asyncInst, err) - return Float64ValueObserver{asyncInstrument: common}, err -} - -// wrapInt64SumObserverInstrument converts an AsyncImpl into Int64SumObserver. -func wrapInt64SumObserverInstrument(asyncInst AsyncImpl, err error) (Int64SumObserver, error) { - common, err := checkNewAsync(asyncInst, err) - return Int64SumObserver{asyncInstrument: common}, err -} - -// wrapFloat64SumObserverInstrument converts an AsyncImpl into Float64SumObserver. -func wrapFloat64SumObserverInstrument(asyncInst AsyncImpl, err error) (Float64SumObserver, error) { - common, err := checkNewAsync(asyncInst, err) - return Float64SumObserver{asyncInstrument: common}, err -} - -// wrapInt64UpDownSumObserverInstrument converts an AsyncImpl into Int64UpDownSumObserver. -func wrapInt64UpDownSumObserverInstrument(asyncInst AsyncImpl, err error) (Int64UpDownSumObserver, error) { - common, err := checkNewAsync(asyncInst, err) - return Int64UpDownSumObserver{asyncInstrument: common}, err -} - -// wrapFloat64UpDownSumObserverInstrument converts an AsyncImpl into Float64UpDownSumObserver. -func wrapFloat64UpDownSumObserverInstrument(asyncInst AsyncImpl, err error) (Float64UpDownSumObserver, error) { - common, err := checkNewAsync(asyncInst, err) - return Float64UpDownSumObserver{asyncInstrument: common}, err -} diff --git a/vendor/go.opentelemetry.io/otel/api/metric/counter.go b/vendor/go.opentelemetry.io/otel/api/metric/counter.go deleted file mode 100644 index c03421d2a..000000000 --- a/vendor/go.opentelemetry.io/otel/api/metric/counter.go +++ /dev/null @@ -1,95 +0,0 @@ -// 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 metric - -import ( - "context" - - "go.opentelemetry.io/otel/label" -) - -// Float64Counter is a metric that accumulates float64 values. -type Float64Counter struct { - syncInstrument -} - -// Int64Counter is a metric that accumulates int64 values. -type Int64Counter struct { - syncInstrument -} - -// BoundFloat64Counter is a bound instrument for Float64Counter. -// -// It inherits the Unbind function from syncBoundInstrument. -type BoundFloat64Counter struct { - syncBoundInstrument -} - -// BoundInt64Counter is a boundInstrument for Int64Counter. -// -// It inherits the Unbind function from syncBoundInstrument. -type BoundInt64Counter struct { - syncBoundInstrument -} - -// Bind creates a bound instrument for this counter. The labels are -// associated with values recorded via subsequent calls to Record. -func (c Float64Counter) Bind(labels ...label.KeyValue) (h BoundFloat64Counter) { - h.syncBoundInstrument = c.bind(labels) - return -} - -// Bind creates a bound instrument for this counter. The labels are -// associated with values recorded via subsequent calls to Record. -func (c Int64Counter) Bind(labels ...label.KeyValue) (h BoundInt64Counter) { - h.syncBoundInstrument = c.bind(labels) - return -} - -// Measurement creates a Measurement object to use with batch -// recording. -func (c Float64Counter) Measurement(value float64) Measurement { - return c.float64Measurement(value) -} - -// Measurement creates a Measurement object to use with batch -// recording. -func (c Int64Counter) Measurement(value int64) Measurement { - return c.int64Measurement(value) -} - -// Add adds the value to the counter's sum. The labels should contain -// the keys and values to be associated with this value. -func (c Float64Counter) Add(ctx context.Context, value float64, labels ...label.KeyValue) { - c.directRecord(ctx, NewFloat64Number(value), labels) -} - -// Add adds the value to the counter's sum. The labels should contain -// the keys and values to be associated with this value. -func (c Int64Counter) Add(ctx context.Context, value int64, labels ...label.KeyValue) { - c.directRecord(ctx, NewInt64Number(value), labels) -} - -// Add adds the value to the counter's sum using the labels -// previously bound to this counter via Bind() -func (b BoundFloat64Counter) Add(ctx context.Context, value float64) { - b.directRecord(ctx, NewFloat64Number(value)) -} - -// Add adds the value to the counter's sum using the labels -// previously bound to this counter via Bind() -func (b BoundInt64Counter) Add(ctx context.Context, value int64) { - b.directRecord(ctx, NewInt64Number(value)) -} diff --git a/vendor/go.opentelemetry.io/otel/api/metric/descriptor.go b/vendor/go.opentelemetry.io/otel/api/metric/descriptor.go deleted file mode 100644 index ccc2e94b5..000000000 --- a/vendor/go.opentelemetry.io/otel/api/metric/descriptor.go +++ /dev/null @@ -1,77 +0,0 @@ -// 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 metric - -import "go.opentelemetry.io/otel/api/unit" - -// Descriptor contains all the settings that describe an instrument, -// including its name, metric kind, number kind, and the configurable -// options. -type Descriptor struct { - name string - kind Kind - numberKind NumberKind - config InstrumentConfig -} - -// NewDescriptor returns a Descriptor with the given contents. -func NewDescriptor(name string, mkind Kind, nkind NumberKind, opts ...InstrumentOption) Descriptor { - return Descriptor{ - name: name, - kind: mkind, - numberKind: nkind, - config: ConfigureInstrument(opts), - } -} - -// Name returns the metric instrument's name. -func (d Descriptor) Name() string { - return d.name -} - -// MetricKind returns the specific kind of instrument. -func (d Descriptor) MetricKind() Kind { - return d.kind -} - -// Description provides a human-readable description of the metric -// instrument. -func (d Descriptor) Description() string { - return d.config.Description -} - -// Unit describes the units of the metric instrument. Unitless -// metrics return the empty string. -func (d Descriptor) Unit() unit.Unit { - return d.config.Unit -} - -// NumberKind returns whether this instrument is declared over int64, -// float64, or uint64 values. -func (d Descriptor) NumberKind() NumberKind { - return d.numberKind -} - -// InstrumentationName returns the name of the library that provided -// instrumentation for this instrument. -func (d Descriptor) InstrumentationName() string { - return d.config.InstrumentationName -} - -// InstrumentationVersion returns the version of the library that provided -// instrumentation for this instrument. -func (d Descriptor) InstrumentationVersion() string { - return d.config.InstrumentationVersion -} diff --git a/vendor/go.opentelemetry.io/otel/api/metric/doc.go b/vendor/go.opentelemetry.io/otel/api/metric/doc.go deleted file mode 100644 index cda2159d0..000000000 --- a/vendor/go.opentelemetry.io/otel/api/metric/doc.go +++ /dev/null @@ -1,49 +0,0 @@ -// 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. - -// metric package provides an API for reporting diagnostic -// measurements using instruments categorized as follows: -// -// Synchronous instruments are called by the user with a Context. -// Asynchronous instruments are called by the SDK during collection. -// -// Additive instruments are semantically intended for capturing a sum. -// Non-additive instruments are intended for capturing a distribution. -// -// Additive instruments may be monotonic, in which case they are -// non-descreasing and naturally define a rate. -// -// The synchronous instrument names are: -// -// Counter: additive, monotonic -// UpDownCounter: additive -// ValueRecorder: non-additive -// -// and the asynchronous instruments are: -// -// SumObserver: additive, monotonic -// UpDownSumObserver: additive -// ValueObserver: non-additive -// -// All instruments are provided with support for either float64 or -// int64 input values. -// -// The Meter interface supports allocating new instruments as well as -// interfaces for recording batches of synchronous measurements or -// asynchronous observations. To obtain a Meter, use a Provider. -// -// The Provider interface supports obtaining a named Meter interface. -// To obtain a Provider implementation, initialize and configure any -// compatible SDK. -package metric // import "go.opentelemetry.io/otel/api/metric" diff --git a/vendor/go.opentelemetry.io/otel/api/metric/kind.go b/vendor/go.opentelemetry.io/otel/api/metric/kind.go deleted file mode 100644 index 9d4b453f3..000000000 --- a/vendor/go.opentelemetry.io/otel/api/metric/kind.go +++ /dev/null @@ -1,79 +0,0 @@ -// 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. - -//go:generate stringer -type=Kind - -package metric - -// Kind describes the kind of instrument. -type Kind int8 - -const ( - // ValueRecorderKind indicates a ValueRecorder instrument. - ValueRecorderKind Kind = iota - // ValueObserverKind indicates an ValueObserver instrument. - ValueObserverKind - - // CounterKind indicates a Counter instrument. - CounterKind - // UpDownCounterKind indicates a UpDownCounter instrument. - UpDownCounterKind - - // SumObserverKind indicates a SumObserver instrument. - SumObserverKind - // UpDownSumObserverKind indicates a UpDownSumObserver instrument. - UpDownSumObserverKind -) - -// Synchronous returns whether this is a synchronous kind of instrument. -func (k Kind) Synchronous() bool { - switch k { - case CounterKind, UpDownCounterKind, ValueRecorderKind: - return true - } - return false -} - -// Asynchronous returns whether this is an asynchronous kind of instrument. -func (k Kind) Asynchronous() bool { - return !k.Synchronous() -} - -// Adding returns whether this kind of instrument adds its inputs (as opposed to Grouping). -func (k Kind) Adding() bool { - switch k { - case CounterKind, UpDownCounterKind, SumObserverKind, UpDownSumObserverKind: - return true - } - return false -} - -// Adding returns whether this kind of instrument groups its inputs (as opposed to Adding). -func (k Kind) Grouping() bool { - return !k.Adding() -} - -// Monotonic returns whether this kind of instrument exposes a non-decreasing sum. -func (k Kind) Monotonic() bool { - switch k { - case CounterKind, SumObserverKind: - return true - } - return false -} - -// Cumulative returns whether this kind of instrument receives precomputed sums. -func (k Kind) PrecomputedSum() bool { - return k.Adding() && k.Asynchronous() -} diff --git a/vendor/go.opentelemetry.io/otel/api/metric/must.go b/vendor/go.opentelemetry.io/otel/api/metric/must.go deleted file mode 100644 index c88e050a3..000000000 --- a/vendor/go.opentelemetry.io/otel/api/metric/must.go +++ /dev/null @@ -1,222 +0,0 @@ -// 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 metric - -// MeterMust is a wrapper for Meter interfaces that panics when any -// instrument constructor encounters an error. -type MeterMust struct { - meter Meter -} - -// BatchObserverMust is a wrapper for BatchObserver that panics when -// any instrument constructor encounters an error. -type BatchObserverMust struct { - batch BatchObserver -} - -// Must constructs a MeterMust implementation from a Meter, allowing -// the application to panic when any instrument constructor yields an -// error. -func Must(meter Meter) MeterMust { - return MeterMust{meter: meter} -} - -// NewInt64Counter calls `Meter.NewInt64Counter` and returns the -// instrument, panicking if it encounters an error. -func (mm MeterMust) NewInt64Counter(name string, cos ...InstrumentOption) Int64Counter { - if inst, err := mm.meter.NewInt64Counter(name, cos...); err != nil { - panic(err) - } else { - return inst - } -} - -// NewFloat64Counter calls `Meter.NewFloat64Counter` and returns the -// instrument, panicking if it encounters an error. -func (mm MeterMust) NewFloat64Counter(name string, cos ...InstrumentOption) Float64Counter { - if inst, err := mm.meter.NewFloat64Counter(name, cos...); err != nil { - panic(err) - } else { - return inst - } -} - -// NewInt64UpDownCounter calls `Meter.NewInt64UpDownCounter` and returns the -// instrument, panicking if it encounters an error. -func (mm MeterMust) NewInt64UpDownCounter(name string, cos ...InstrumentOption) Int64UpDownCounter { - if inst, err := mm.meter.NewInt64UpDownCounter(name, cos...); err != nil { - panic(err) - } else { - return inst - } -} - -// NewFloat64UpDownCounter calls `Meter.NewFloat64UpDownCounter` and returns the -// instrument, panicking if it encounters an error. -func (mm MeterMust) NewFloat64UpDownCounter(name string, cos ...InstrumentOption) Float64UpDownCounter { - if inst, err := mm.meter.NewFloat64UpDownCounter(name, cos...); err != nil { - panic(err) - } else { - return inst - } -} - -// NewInt64ValueRecorder calls `Meter.NewInt64ValueRecorder` and returns the -// instrument, panicking if it encounters an error. -func (mm MeterMust) NewInt64ValueRecorder(name string, mos ...InstrumentOption) Int64ValueRecorder { - if inst, err := mm.meter.NewInt64ValueRecorder(name, mos...); err != nil { - panic(err) - } else { - return inst - } -} - -// NewFloat64ValueRecorder calls `Meter.NewFloat64ValueRecorder` and returns the -// instrument, panicking if it encounters an error. -func (mm MeterMust) NewFloat64ValueRecorder(name string, mos ...InstrumentOption) Float64ValueRecorder { - if inst, err := mm.meter.NewFloat64ValueRecorder(name, mos...); err != nil { - panic(err) - } else { - return inst - } -} - -// NewInt64ValueObserver calls `Meter.NewInt64ValueObserver` and -// returns the instrument, panicking if it encounters an error. -func (mm MeterMust) NewInt64ValueObserver(name string, callback Int64ObserverFunc, oos ...InstrumentOption) Int64ValueObserver { - if inst, err := mm.meter.NewInt64ValueObserver(name, callback, oos...); err != nil { - panic(err) - } else { - return inst - } -} - -// NewFloat64ValueObserver calls `Meter.NewFloat64ValueObserver` and -// returns the instrument, panicking if it encounters an error. -func (mm MeterMust) NewFloat64ValueObserver(name string, callback Float64ObserverFunc, oos ...InstrumentOption) Float64ValueObserver { - if inst, err := mm.meter.NewFloat64ValueObserver(name, callback, oos...); err != nil { - panic(err) - } else { - return inst - } -} - -// NewInt64SumObserver calls `Meter.NewInt64SumObserver` and -// returns the instrument, panicking if it encounters an error. -func (mm MeterMust) NewInt64SumObserver(name string, callback Int64ObserverFunc, oos ...InstrumentOption) Int64SumObserver { - if inst, err := mm.meter.NewInt64SumObserver(name, callback, oos...); err != nil { - panic(err) - } else { - return inst - } -} - -// NewFloat64SumObserver calls `Meter.NewFloat64SumObserver` and -// returns the instrument, panicking if it encounters an error. -func (mm MeterMust) NewFloat64SumObserver(name string, callback Float64ObserverFunc, oos ...InstrumentOption) Float64SumObserver { - if inst, err := mm.meter.NewFloat64SumObserver(name, callback, oos...); err != nil { - panic(err) - } else { - return inst - } -} - -// NewInt64UpDownSumObserver calls `Meter.NewInt64UpDownSumObserver` and -// returns the instrument, panicking if it encounters an error. -func (mm MeterMust) NewInt64UpDownSumObserver(name string, callback Int64ObserverFunc, oos ...InstrumentOption) Int64UpDownSumObserver { - if inst, err := mm.meter.NewInt64UpDownSumObserver(name, callback, oos...); err != nil { - panic(err) - } else { - return inst - } -} - -// NewFloat64UpDownSumObserver calls `Meter.NewFloat64UpDownSumObserver` and -// returns the instrument, panicking if it encounters an error. -func (mm MeterMust) NewFloat64UpDownSumObserver(name string, callback Float64ObserverFunc, oos ...InstrumentOption) Float64UpDownSumObserver { - if inst, err := mm.meter.NewFloat64UpDownSumObserver(name, callback, oos...); err != nil { - panic(err) - } else { - return inst - } -} - -// NewBatchObserver returns a wrapper around BatchObserver that panics -// when any instrument constructor returns an error. -func (mm MeterMust) NewBatchObserver(callback BatchObserverFunc) BatchObserverMust { - return BatchObserverMust{ - batch: mm.meter.NewBatchObserver(callback), - } -} - -// NewInt64ValueObserver calls `BatchObserver.NewInt64ValueObserver` and -// returns the instrument, panicking if it encounters an error. -func (bm BatchObserverMust) NewInt64ValueObserver(name string, oos ...InstrumentOption) Int64ValueObserver { - if inst, err := bm.batch.NewInt64ValueObserver(name, oos...); err != nil { - panic(err) - } else { - return inst - } -} - -// NewFloat64ValueObserver calls `BatchObserver.NewFloat64ValueObserver` and -// returns the instrument, panicking if it encounters an error. -func (bm BatchObserverMust) NewFloat64ValueObserver(name string, oos ...InstrumentOption) Float64ValueObserver { - if inst, err := bm.batch.NewFloat64ValueObserver(name, oos...); err != nil { - panic(err) - } else { - return inst - } -} - -// NewInt64SumObserver calls `BatchObserver.NewInt64SumObserver` and -// returns the instrument, panicking if it encounters an error. -func (bm BatchObserverMust) NewInt64SumObserver(name string, oos ...InstrumentOption) Int64SumObserver { - if inst, err := bm.batch.NewInt64SumObserver(name, oos...); err != nil { - panic(err) - } else { - return inst - } -} - -// NewFloat64SumObserver calls `BatchObserver.NewFloat64SumObserver` and -// returns the instrument, panicking if it encounters an error. -func (bm BatchObserverMust) NewFloat64SumObserver(name string, oos ...InstrumentOption) Float64SumObserver { - if inst, err := bm.batch.NewFloat64SumObserver(name, oos...); err != nil { - panic(err) - } else { - return inst - } -} - -// NewInt64UpDownSumObserver calls `BatchObserver.NewInt64UpDownSumObserver` and -// returns the instrument, panicking if it encounters an error. -func (bm BatchObserverMust) NewInt64UpDownSumObserver(name string, oos ...InstrumentOption) Int64UpDownSumObserver { - if inst, err := bm.batch.NewInt64UpDownSumObserver(name, oos...); err != nil { - panic(err) - } else { - return inst - } -} - -// NewFloat64UpDownSumObserver calls `BatchObserver.NewFloat64UpDownSumObserver` and -// returns the instrument, panicking if it encounters an error. -func (bm BatchObserverMust) NewFloat64UpDownSumObserver(name string, oos ...InstrumentOption) Float64UpDownSumObserver { - if inst, err := bm.batch.NewFloat64UpDownSumObserver(name, oos...); err != nil { - panic(err) - } else { - return inst - } -} diff --git a/vendor/go.opentelemetry.io/otel/api/metric/numberkind_string.go b/vendor/go.opentelemetry.io/otel/api/metric/numberkind_string.go deleted file mode 100644 index e99a8745e..000000000 --- a/vendor/go.opentelemetry.io/otel/api/metric/numberkind_string.go +++ /dev/null @@ -1,24 +0,0 @@ -// Code generated by "stringer -type=NumberKind"; DO NOT EDIT. - -package metric - -import "strconv" - -func _() { - // An "invalid array index" compiler error signifies that the constant values have changed. - // Re-run the stringer command to generate them again. - var x [1]struct{} - _ = x[Int64NumberKind-0] - _ = x[Float64NumberKind-1] -} - -const _NumberKind_name = "Int64NumberKindFloat64NumberKind" - -var _NumberKind_index = [...]uint8{0, 15, 32} - -func (i NumberKind) String() string { - if i < 0 || i >= NumberKind(len(_NumberKind_index)-1) { - return "NumberKind(" + strconv.FormatInt(int64(i), 10) + ")" - } - return _NumberKind_name[_NumberKind_index[i]:_NumberKind_index[i+1]] -} diff --git a/vendor/go.opentelemetry.io/otel/api/metric/observer.go b/vendor/go.opentelemetry.io/otel/api/metric/observer.go deleted file mode 100644 index c347da78f..000000000 --- a/vendor/go.opentelemetry.io/otel/api/metric/observer.go +++ /dev/null @@ -1,124 +0,0 @@ -// 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 metric - -// BatchObserver represents an Observer callback that can report -// observations for multiple instruments. -type BatchObserver struct { - meter Meter - runner AsyncBatchRunner -} - -// Int64ValueObserver is a metric that captures a set of int64 values at a -// point in time. -type Int64ValueObserver struct { - asyncInstrument -} - -// Float64ValueObserver is a metric that captures a set of float64 values -// at a point in time. -type Float64ValueObserver struct { - asyncInstrument -} - -// Int64SumObserver is a metric that captures a precomputed sum of -// int64 values at a point in time. -type Int64SumObserver struct { - asyncInstrument -} - -// Float64SumObserver is a metric that captures a precomputed sum of -// float64 values at a point in time. -type Float64SumObserver struct { - asyncInstrument -} - -// Int64UpDownSumObserver is a metric that captures a precomputed sum of -// int64 values at a point in time. -type Int64UpDownSumObserver struct { - asyncInstrument -} - -// Float64UpDownSumObserver is a metric that captures a precomputed sum of -// float64 values at a point in time. -type Float64UpDownSumObserver struct { - asyncInstrument -} - -// Observation returns an Observation, a BatchObserverFunc -// argument, for an asynchronous integer instrument. -// This returns an implementation-level object for use by the SDK, -// users should not refer to this. -func (i Int64ValueObserver) Observation(v int64) Observation { - return Observation{ - number: NewInt64Number(v), - instrument: i.instrument, - } -} - -// Observation returns an Observation, a BatchObserverFunc -// argument, for an asynchronous integer instrument. -// This returns an implementation-level object for use by the SDK, -// users should not refer to this. -func (f Float64ValueObserver) Observation(v float64) Observation { - return Observation{ - number: NewFloat64Number(v), - instrument: f.instrument, - } -} - -// Observation returns an Observation, a BatchObserverFunc -// argument, for an asynchronous integer instrument. -// This returns an implementation-level object for use by the SDK, -// users should not refer to this. -func (i Int64SumObserver) Observation(v int64) Observation { - return Observation{ - number: NewInt64Number(v), - instrument: i.instrument, - } -} - -// Observation returns an Observation, a BatchObserverFunc -// argument, for an asynchronous integer instrument. -// This returns an implementation-level object for use by the SDK, -// users should not refer to this. -func (f Float64SumObserver) Observation(v float64) Observation { - return Observation{ - number: NewFloat64Number(v), - instrument: f.instrument, - } -} - -// Observation returns an Observation, a BatchObserverFunc -// argument, for an asynchronous integer instrument. -// This returns an implementation-level object for use by the SDK, -// users should not refer to this. -func (i Int64UpDownSumObserver) Observation(v int64) Observation { - return Observation{ - number: NewInt64Number(v), - instrument: i.instrument, - } -} - -// Observation returns an Observation, a BatchObserverFunc -// argument, for an asynchronous integer instrument. -// This returns an implementation-level object for use by the SDK, -// users should not refer to this. -func (f Float64UpDownSumObserver) Observation(v float64) Observation { - return Observation{ - number: NewFloat64Number(v), - instrument: f.instrument, - } -} diff --git a/vendor/go.opentelemetry.io/otel/api/metric/sync.go b/vendor/go.opentelemetry.io/otel/api/metric/sync.go deleted file mode 100644 index a08a65ba1..000000000 --- a/vendor/go.opentelemetry.io/otel/api/metric/sync.go +++ /dev/null @@ -1,192 +0,0 @@ -// 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 metric - -import ( - "context" - "errors" - - "go.opentelemetry.io/otel/label" -) - -// ErrSDKReturnedNilImpl is returned when a new `MeterImpl` returns nil. -var ErrSDKReturnedNilImpl = errors.New("SDK returned a nil implementation") - -// Measurement is used for reporting a synchronous batch of metric -// values. Instances of this type should be created by synchronous -// instruments (e.g., Int64Counter.Measurement()). -type Measurement struct { - // number needs to be aligned for 64-bit atomic operations. - number Number - instrument SyncImpl -} - -// syncInstrument contains a SyncImpl. -type syncInstrument struct { - instrument SyncImpl -} - -// syncBoundInstrument contains a BoundSyncImpl. -type syncBoundInstrument struct { - boundInstrument BoundSyncImpl -} - -// asyncInstrument contains a AsyncImpl. -type asyncInstrument struct { - instrument AsyncImpl -} - -// SyncImpl returns the instrument that created this measurement. -// This returns an implementation-level object for use by the SDK, -// users should not refer to this. -func (m Measurement) SyncImpl() SyncImpl { - return m.instrument -} - -// Number returns a number recorded in this measurement. -func (m Measurement) Number() Number { - return m.number -} - -// AsyncImpl returns the instrument that created this observation. -// This returns an implementation-level object for use by the SDK, -// users should not refer to this. -func (m Observation) AsyncImpl() AsyncImpl { - return m.instrument -} - -// Number returns a number recorded in this observation. -func (m Observation) Number() Number { - return m.number -} - -// AsyncImpl implements AsyncImpl. -func (a asyncInstrument) AsyncImpl() AsyncImpl { - return a.instrument -} - -// SyncImpl returns the implementation object for synchronous instruments. -func (s syncInstrument) SyncImpl() SyncImpl { - return s.instrument -} - -func (s syncInstrument) bind(labels []label.KeyValue) syncBoundInstrument { - return newSyncBoundInstrument(s.instrument.Bind(labels)) -} - -func (s syncInstrument) float64Measurement(value float64) Measurement { - return newMeasurement(s.instrument, NewFloat64Number(value)) -} - -func (s syncInstrument) int64Measurement(value int64) Measurement { - return newMeasurement(s.instrument, NewInt64Number(value)) -} - -func (s syncInstrument) directRecord(ctx context.Context, number Number, labels []label.KeyValue) { - s.instrument.RecordOne(ctx, number, labels) -} - -func (h syncBoundInstrument) directRecord(ctx context.Context, number Number) { - h.boundInstrument.RecordOne(ctx, number) -} - -// Unbind calls SyncImpl.Unbind. -func (h syncBoundInstrument) Unbind() { - h.boundInstrument.Unbind() -} - -// checkNewAsync receives an AsyncImpl and potential -// error, and returns the same types, checking for and ensuring that -// the returned interface is not nil. -func checkNewAsync(instrument AsyncImpl, err error) (asyncInstrument, error) { - if instrument == nil { - if err == nil { - err = ErrSDKReturnedNilImpl - } - instrument = NoopAsync{} - } - return asyncInstrument{ - instrument: instrument, - }, err -} - -// checkNewSync receives an SyncImpl and potential -// error, and returns the same types, checking for and ensuring that -// the returned interface is not nil. -func checkNewSync(instrument SyncImpl, err error) (syncInstrument, error) { - if instrument == nil { - if err == nil { - err = ErrSDKReturnedNilImpl - } - // Note: an alternate behavior would be to synthesize a new name - // or group all duplicately-named instruments of a certain type - // together and use a tag for the original name, e.g., - // name = 'invalid.counter.int64' - // label = 'original-name=duplicate-counter-name' - instrument = NoopSync{} - } - return syncInstrument{ - instrument: instrument, - }, err -} - -func newSyncBoundInstrument(boundInstrument BoundSyncImpl) syncBoundInstrument { - return syncBoundInstrument{ - boundInstrument: boundInstrument, - } -} - -func newMeasurement(instrument SyncImpl, number Number) Measurement { - return Measurement{ - instrument: instrument, - number: number, - } -} - -// wrapInt64CounterInstrument converts a SyncImpl into Int64Counter. -func wrapInt64CounterInstrument(syncInst SyncImpl, err error) (Int64Counter, error) { - common, err := checkNewSync(syncInst, err) - return Int64Counter{syncInstrument: common}, err -} - -// wrapFloat64CounterInstrument converts a SyncImpl into Float64Counter. -func wrapFloat64CounterInstrument(syncInst SyncImpl, err error) (Float64Counter, error) { - common, err := checkNewSync(syncInst, err) - return Float64Counter{syncInstrument: common}, err -} - -// wrapInt64UpDownCounterInstrument converts a SyncImpl into Int64UpDownCounter. -func wrapInt64UpDownCounterInstrument(syncInst SyncImpl, err error) (Int64UpDownCounter, error) { - common, err := checkNewSync(syncInst, err) - return Int64UpDownCounter{syncInstrument: common}, err -} - -// wrapFloat64UpDownCounterInstrument converts a SyncImpl into Float64UpDownCounter. -func wrapFloat64UpDownCounterInstrument(syncInst SyncImpl, err error) (Float64UpDownCounter, error) { - common, err := checkNewSync(syncInst, err) - return Float64UpDownCounter{syncInstrument: common}, err -} - -// wrapInt64ValueRecorderInstrument converts a SyncImpl into Int64ValueRecorder. -func wrapInt64ValueRecorderInstrument(syncInst SyncImpl, err error) (Int64ValueRecorder, error) { - common, err := checkNewSync(syncInst, err) - return Int64ValueRecorder{syncInstrument: common}, err -} - -// wrapFloat64ValueRecorderInstrument converts a SyncImpl into Float64ValueRecorder. -func wrapFloat64ValueRecorderInstrument(syncInst SyncImpl, err error) (Float64ValueRecorder, error) { - common, err := checkNewSync(syncInst, err) - return Float64ValueRecorder{syncInstrument: common}, err -} diff --git a/vendor/go.opentelemetry.io/otel/api/metric/updowncounter.go b/vendor/go.opentelemetry.io/otel/api/metric/updowncounter.go deleted file mode 100644 index 10182460a..000000000 --- a/vendor/go.opentelemetry.io/otel/api/metric/updowncounter.go +++ /dev/null @@ -1,96 +0,0 @@ -// 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 metric - -import ( - "context" - - "go.opentelemetry.io/otel/label" -) - -// Float64UpDownCounter is a metric instrument that sums floating -// point values. -type Float64UpDownCounter struct { - syncInstrument -} - -// Int64UpDownCounter is a metric instrument that sums integer values. -type Int64UpDownCounter struct { - syncInstrument -} - -// BoundFloat64UpDownCounter is a bound instrument for Float64UpDownCounter. -// -// It inherits the Unbind function from syncBoundInstrument. -type BoundFloat64UpDownCounter struct { - syncBoundInstrument -} - -// BoundInt64UpDownCounter is a boundInstrument for Int64UpDownCounter. -// -// It inherits the Unbind function from syncBoundInstrument. -type BoundInt64UpDownCounter struct { - syncBoundInstrument -} - -// Bind creates a bound instrument for this counter. The labels are -// associated with values recorded via subsequent calls to Record. -func (c Float64UpDownCounter) Bind(labels ...label.KeyValue) (h BoundFloat64UpDownCounter) { - h.syncBoundInstrument = c.bind(labels) - return -} - -// Bind creates a bound instrument for this counter. The labels are -// associated with values recorded via subsequent calls to Record. -func (c Int64UpDownCounter) Bind(labels ...label.KeyValue) (h BoundInt64UpDownCounter) { - h.syncBoundInstrument = c.bind(labels) - return -} - -// Measurement creates a Measurement object to use with batch -// recording. -func (c Float64UpDownCounter) Measurement(value float64) Measurement { - return c.float64Measurement(value) -} - -// Measurement creates a Measurement object to use with batch -// recording. -func (c Int64UpDownCounter) Measurement(value int64) Measurement { - return c.int64Measurement(value) -} - -// Add adds the value to the counter's sum. The labels should contain -// the keys and values to be associated with this value. -func (c Float64UpDownCounter) Add(ctx context.Context, value float64, labels ...label.KeyValue) { - c.directRecord(ctx, NewFloat64Number(value), labels) -} - -// Add adds the value to the counter's sum. The labels should contain -// the keys and values to be associated with this value. -func (c Int64UpDownCounter) Add(ctx context.Context, value int64, labels ...label.KeyValue) { - c.directRecord(ctx, NewInt64Number(value), labels) -} - -// Add adds the value to the counter's sum using the labels -// previously bound to this counter via Bind() -func (b BoundFloat64UpDownCounter) Add(ctx context.Context, value float64) { - b.directRecord(ctx, NewFloat64Number(value)) -} - -// Add adds the value to the counter's sum using the labels -// previously bound to this counter via Bind() -func (b BoundInt64UpDownCounter) Add(ctx context.Context, value int64) { - b.directRecord(ctx, NewInt64Number(value)) -} diff --git a/vendor/go.opentelemetry.io/otel/api/metric/valuerecorder.go b/vendor/go.opentelemetry.io/otel/api/metric/valuerecorder.go deleted file mode 100644 index fa7e2d4f8..000000000 --- a/vendor/go.opentelemetry.io/otel/api/metric/valuerecorder.go +++ /dev/null @@ -1,97 +0,0 @@ -// 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 metric - -import ( - "context" - - "go.opentelemetry.io/otel/label" -) - -// Float64ValueRecorder is a metric that records float64 values. -type Float64ValueRecorder struct { - syncInstrument -} - -// Int64ValueRecorder is a metric that records int64 values. -type Int64ValueRecorder struct { - syncInstrument -} - -// BoundFloat64ValueRecorder is a bound instrument for Float64ValueRecorder. -// -// It inherits the Unbind function from syncBoundInstrument. -type BoundFloat64ValueRecorder struct { - syncBoundInstrument -} - -// BoundInt64ValueRecorder is a bound instrument for Int64ValueRecorder. -// -// It inherits the Unbind function from syncBoundInstrument. -type BoundInt64ValueRecorder struct { - syncBoundInstrument -} - -// Bind creates a bound instrument for this ValueRecorder. The labels are -// associated with values recorded via subsequent calls to Record. -func (c Float64ValueRecorder) Bind(labels ...label.KeyValue) (h BoundFloat64ValueRecorder) { - h.syncBoundInstrument = c.bind(labels) - return -} - -// Bind creates a bound instrument for this ValueRecorder. The labels are -// associated with values recorded via subsequent calls to Record. -func (c Int64ValueRecorder) Bind(labels ...label.KeyValue) (h BoundInt64ValueRecorder) { - h.syncBoundInstrument = c.bind(labels) - return -} - -// Measurement creates a Measurement object to use with batch -// recording. -func (c Float64ValueRecorder) Measurement(value float64) Measurement { - return c.float64Measurement(value) -} - -// Measurement creates a Measurement object to use with batch -// recording. -func (c Int64ValueRecorder) Measurement(value int64) Measurement { - return c.int64Measurement(value) -} - -// Record adds a new value to the list of ValueRecorder's records. The -// labels should contain the keys and values to be associated with -// this value. -func (c Float64ValueRecorder) Record(ctx context.Context, value float64, labels ...label.KeyValue) { - c.directRecord(ctx, NewFloat64Number(value), labels) -} - -// Record adds a new value to the ValueRecorder's distribution. The -// labels should contain the keys and values to be associated with -// this value. -func (c Int64ValueRecorder) Record(ctx context.Context, value int64, labels ...label.KeyValue) { - c.directRecord(ctx, NewInt64Number(value), labels) -} - -// Record adds a new value to the ValueRecorder's distribution using the labels -// previously bound to the ValueRecorder via Bind(). -func (b BoundFloat64ValueRecorder) Record(ctx context.Context, value float64) { - b.directRecord(ctx, NewFloat64Number(value)) -} - -// Record adds a new value to the ValueRecorder's distribution using the labels -// previously bound to the ValueRecorder via Bind(). -func (b BoundInt64ValueRecorder) Record(ctx context.Context, value int64) { - b.directRecord(ctx, NewInt64Number(value)) -} diff --git a/vendor/go.opentelemetry.io/otel/api/propagation/propagation.go b/vendor/go.opentelemetry.io/otel/api/propagation/propagation.go deleted file mode 100644 index 8e2d38338..000000000 --- a/vendor/go.opentelemetry.io/otel/api/propagation/propagation.go +++ /dev/null @@ -1,143 +0,0 @@ -// 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 propagation - -import ( - "context" -) - -// HTTPSupplier is an interface that specifies methods to retrieve and -// store a single value for a key to an associated carrier. It is -// implemented by http.Headers. -type HTTPSupplier interface { - // Get method retrieves a single value for a given key. - Get(key string) string - // Set method stores a single value for a given key. Note that - // this should not be appending a value to some array, but - // rather overwrite the old value. - Set(key string, value string) -} - -// HTTPExtractor extracts information from a HTTPSupplier into a -// context. -type HTTPExtractor interface { - // Extract method retrieves encoded information using supplier - // from the associated carrier, decodes it and creates a new - // context containing the decoded information. - // - // Information can be a correlation context or a remote span - // context. In case of span context, the propagator should - // store it in the context using - // trace.ContextWithRemoteSpanContext. In case of correlation - // context, the propagator should use correlation.WithMap to - // store it in the context. - Extract(context.Context, HTTPSupplier) context.Context -} - -// HTTPInjector injects information into a HTTPSupplier. -type HTTPInjector interface { - // Inject method retrieves information from the context, - // encodes it into propagator specific format and then injects - // the encoded information using supplier into an associated - // carrier. - Inject(context.Context, HTTPSupplier) -} - -// Config contains the current set of extractors and injectors. -type Config struct { - httpEx []HTTPExtractor - httpIn []HTTPInjector -} - -// Propagators is the interface to a set of injectors and extractors -// for all supported carrier formats. It can be used to chain multiple -// propagators into a single entity. -type Propagators interface { - // HTTPExtractors returns the configured extractors. - HTTPExtractors() []HTTPExtractor - - // HTTPInjectors returns the configured injectors. - HTTPInjectors() []HTTPInjector -} - -// HTTPPropagator is the interface to inject to and extract from -// HTTPSupplier. -type HTTPPropagator interface { - HTTPInjector - HTTPExtractor - - // GetAllKeys returns the HTTP header names used. - GetAllKeys() []string -} - -// Option support passing configuration parameters to New(). -type Option func(*Config) - -// propagators is the default Propagators implementation. -type propagators struct { - config Config -} - -// New returns a standard Propagators implementation. -func New(options ...Option) Propagators { - config := Config{} - for _, opt := range options { - opt(&config) - } - return &propagators{ - config: config, - } -} - -// WithInjectors appends to the optional injector set. -func WithInjectors(inj ...HTTPInjector) Option { - return func(config *Config) { - config.httpIn = append(config.httpIn, inj...) - } -} - -// WithExtractors appends to the optional extractor set. -func WithExtractors(ext ...HTTPExtractor) Option { - return func(config *Config) { - config.httpEx = append(config.httpEx, ext...) - } -} - -// HTTPExtractors implements Propagators. -func (p *propagators) HTTPExtractors() []HTTPExtractor { - return p.config.httpEx -} - -// HTTPInjectors implements Propagators. -func (p *propagators) HTTPInjectors() []HTTPInjector { - return p.config.httpIn -} - -// ExtractHTTP applies props.HTTPExtractors() to the passed context -// and the supplier and returns the combined result context. -func ExtractHTTP(ctx context.Context, props Propagators, supplier HTTPSupplier) context.Context { - for _, ex := range props.HTTPExtractors() { - ctx = ex.Extract(ctx, supplier) - } - return ctx -} - -// InjectHTTP applies props.HTTPInjectors() to the passed context and -// the supplier. -func InjectHTTP(ctx context.Context, props Propagators, supplier HTTPSupplier) { - for _, in := range props.HTTPInjectors() { - in.Inject(ctx, supplier) - } -} diff --git a/vendor/go.opentelemetry.io/otel/api/trace/api.go b/vendor/go.opentelemetry.io/otel/api/trace/api.go deleted file mode 100644 index 19528d43b..000000000 --- a/vendor/go.opentelemetry.io/otel/api/trace/api.go +++ /dev/null @@ -1,273 +0,0 @@ -// 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 trace - -import ( - "context" - "time" - - "go.opentelemetry.io/otel/codes" - "go.opentelemetry.io/otel/label" -) - -type Provider interface { - // Tracer creates an implementation of the Tracer interface. - // The instrumentationName must be the name of the library providing - // instrumentation. This name may be the same as the instrumented code - // only if that code provides built-in instrumentation. If the - // instrumentationName is empty, then a implementation defined default - // name will be used instead. - Tracer(instrumentationName string, opts ...TracerOption) Tracer -} - -// TODO (MrAlias): unify this API option design: -// https://github.com/open-telemetry/opentelemetry-go/issues/536 - -// TracerConfig contains options for a Tracer. -type TracerConfig struct { - InstrumentationVersion string -} - -// TracerOption configures a TracerConfig option. -type TracerOption func(*TracerConfig) - -// WithInstrumentationVersion sets the instrumentation version for a Tracer. -func WithInstrumentationVersion(version string) TracerOption { - return func(c *TracerConfig) { - c.InstrumentationVersion = version - } -} - -type Tracer interface { - // Start a span. - Start(ctx context.Context, spanName string, opts ...StartOption) (context.Context, Span) -} - -// EndConfig provides options to set properties of span at the time of ending -// the span. -type EndConfig struct { - EndTime time.Time -} - -// EndOption applies changes to EndConfig that sets options when the span is ended. -type EndOption func(*EndConfig) - -// WithEndTime sets the end time of the span to provided time t, when it is ended. -func WithEndTime(t time.Time) EndOption { - return func(c *EndConfig) { - c.EndTime = t - } -} - -// ErrorConfig provides options to set properties of an error event at the time it is recorded. -type ErrorConfig struct { - Timestamp time.Time - StatusCode codes.Code -} - -// ErrorOption applies changes to ErrorConfig that sets options when an error event is recorded. -type ErrorOption func(*ErrorConfig) - -// WithErrorTime sets the time at which the error event should be recorded. -func WithErrorTime(t time.Time) ErrorOption { - return func(c *ErrorConfig) { - c.Timestamp = t - } -} - -// WithErrorStatus indicates the span status that should be set when recording an error event. -func WithErrorStatus(s codes.Code) ErrorOption { - return func(c *ErrorConfig) { - c.StatusCode = s - } -} - -type Span interface { - // Tracer returns tracer used to create this span. Tracer cannot be nil. - Tracer() Tracer - - // End completes the span. No updates are allowed to span after it - // ends. The only exception is setting status of the span. - End(options ...EndOption) - - // AddEvent adds an event to the span. - AddEvent(ctx context.Context, name string, attrs ...label.KeyValue) - // AddEventWithTimestamp adds an event with a custom timestamp - // to the span. - AddEventWithTimestamp(ctx context.Context, timestamp time.Time, name string, attrs ...label.KeyValue) - - // IsRecording returns true if the span is active and recording events is enabled. - IsRecording() bool - - // RecordError records an error as a span event. - RecordError(ctx context.Context, err error, opts ...ErrorOption) - - // SpanContext returns span context of the span. Returned SpanContext is usable - // even after the span ends. - SpanContext() SpanContext - - // SetStatus sets the status of the span in the form of a code - // and a message. SetStatus overrides the value of previous - // calls to SetStatus on the Span. - // - // The default span status is OK, so it is not necessary to - // explicitly set an OK status on successful Spans unless it - // is to add an OK message or to override a previous status on the Span. - SetStatus(codes.Code, string) - - // SetName sets the name of the span. - SetName(name string) - - // Set span attributes - SetAttributes(...label.KeyValue) - - // Set singular span attribute, with type inference. - SetAttribute(string, interface{}) -} - -// StartOption applies changes to StartConfig that sets options at span start time. -type StartOption func(*StartConfig) - -// StartConfig provides options to set properties of span at the time of starting -// a new span. -type StartConfig struct { - Attributes []label.KeyValue - StartTime time.Time - Links []Link - Record bool - NewRoot bool - SpanKind SpanKind -} - -// Link is used to establish relationship between two spans within the same Trace or -// across different Traces. Few examples of Link usage. -// 1. Batch Processing: A batch of elements may contain elements associated with one -// or more traces/spans. Since there can only be one parent SpanContext, Link is -// used to keep reference to SpanContext of all elements in the batch. -// 2. Public Endpoint: A SpanContext in incoming client request on a public endpoint -// is untrusted from service provider perspective. In such case it is advisable to -// start a new trace with appropriate sampling decision. -// However, it is desirable to associate incoming SpanContext to new trace initiated -// on service provider side so two traces (from Client and from Service Provider) can -// be correlated. -type Link struct { - SpanContext - Attributes []label.KeyValue -} - -// SpanKind represents the role of a Span inside a Trace. Often, this defines how a Span -// will be processed and visualized by various backends. -type SpanKind int - -const ( - // As a convenience, these match the proto definition, see - // opentelemetry/proto/trace/v1/trace.proto - // - // The unspecified value is not a valid `SpanKind`. Use - // `ValidateSpanKind()` to coerce a span kind to a valid - // value. - SpanKindUnspecified SpanKind = 0 - SpanKindInternal SpanKind = 1 - SpanKindServer SpanKind = 2 - SpanKindClient SpanKind = 3 - SpanKindProducer SpanKind = 4 - SpanKindConsumer SpanKind = 5 -) - -// ValidateSpanKind returns a valid span kind value. This will coerce -// invalid values into the default value, SpanKindInternal. -func ValidateSpanKind(spanKind SpanKind) SpanKind { - switch spanKind { - case SpanKindInternal, - SpanKindServer, - SpanKindClient, - SpanKindProducer, - SpanKindConsumer: - // valid - return spanKind - default: - return SpanKindInternal - } -} - -// String returns the specified name of the SpanKind in lower-case. -func (sk SpanKind) String() string { - switch sk { - case SpanKindInternal: - return "internal" - case SpanKindServer: - return "server" - case SpanKindClient: - return "client" - case SpanKindProducer: - return "producer" - case SpanKindConsumer: - return "consumer" - default: - return "unspecified" - } -} - -// WithStartTime sets the start time of the span to provided time t, when it is started. -// In absence of this option, wall clock time is used as start time. -// This option is typically used when starting of the span is delayed. -func WithStartTime(t time.Time) StartOption { - return func(c *StartConfig) { - c.StartTime = t - } -} - -// WithAttributes sets attributes to span. These attributes provides additional -// data about the span. -// Multiple `WithAttributes` options appends the attributes preserving the order. -func WithAttributes(attrs ...label.KeyValue) StartOption { - return func(c *StartConfig) { - c.Attributes = append(c.Attributes, attrs...) - } -} - -// WithRecord specifies that the span should be recorded. -// Note that the implementation may still override this preference, -// e.g., if the span is a child in an unsampled trace. -func WithRecord() StartOption { - return func(c *StartConfig) { - c.Record = true - } -} - -// WithNewRoot specifies that the current span or remote span context -// in context passed to `Start` should be ignored when deciding about -// a parent, which effectively means creating a span with new trace -// ID. The current span and the remote span context may be added as -// links to the span by the implementation. -func WithNewRoot() StartOption { - return func(c *StartConfig) { - c.NewRoot = true - } -} - -// LinkedTo allows instantiating a Span with initial Links. -func LinkedTo(sc SpanContext, attrs ...label.KeyValue) StartOption { - return func(c *StartConfig) { - c.Links = append(c.Links, Link{sc, attrs}) - } -} - -// WithSpanKind specifies the role a Span on a Trace. -func WithSpanKind(sk SpanKind) StartOption { - return func(c *StartConfig) { - c.SpanKind = sk - } -} diff --git a/vendor/go.opentelemetry.io/otel/api/trace/b3_propagator.go b/vendor/go.opentelemetry.io/otel/api/trace/b3_propagator.go deleted file mode 100644 index 4627618f7..000000000 --- a/vendor/go.opentelemetry.io/otel/api/trace/b3_propagator.go +++ /dev/null @@ -1,343 +0,0 @@ -// 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 trace - -import ( - "context" - "errors" - "strings" - - "go.opentelemetry.io/otel/api/propagation" -) - -const ( - // Default B3 Header names. - b3ContextHeader = "b3" - b3DebugFlagHeader = "x-b3-flags" - b3TraceIDHeader = "x-b3-traceid" - b3SpanIDHeader = "x-b3-spanid" - b3SampledHeader = "x-b3-sampled" - b3ParentSpanIDHeader = "x-b3-parentspanid" - - b3TraceIDPadding = "0000000000000000" - - // B3 Single Header encoding widths. - separatorWidth = 1 // Single "-" character. - samplingWidth = 1 // Single hex character. - traceID64BitsWidth = 64 / 4 // 16 hex character Trace ID. - traceID128BitsWidth = 128 / 4 // 32 hex character Trace ID. - spanIDWidth = 16 // 16 hex character ID. - parentSpanIDWidth = 16 // 16 hex character ID. -) - -var ( - empty = EmptySpanContext() - - errInvalidSampledByte = errors.New("invalid B3 Sampled found") - errInvalidSampledHeader = errors.New("invalid B3 Sampled header found") - errInvalidTraceIDHeader = errors.New("invalid B3 TraceID header found") - errInvalidSpanIDHeader = errors.New("invalid B3 SpanID header found") - errInvalidParentSpanIDHeader = errors.New("invalid B3 ParentSpanID header found") - errInvalidScope = errors.New("require either both TraceID and SpanID or none") - errInvalidScopeParent = errors.New("ParentSpanID requires both TraceID and SpanID to be available") - errInvalidScopeParentSingle = errors.New("ParentSpanID requires TraceID, SpanID and Sampled to be available") - errEmptyContext = errors.New("empty request context") - errInvalidTraceIDValue = errors.New("invalid B3 TraceID value found") - errInvalidSpanIDValue = errors.New("invalid B3 SpanID value found") - errInvalidParentSpanIDValue = errors.New("invalid B3 ParentSpanID value found") -) - -// B3Encoding is a bitmask representation of the B3 encoding type. -type B3Encoding uint8 - -// supports returns if e has o bit(s) set. -func (e B3Encoding) supports(o B3Encoding) bool { - return e&o == o -} - -const ( - // B3MultipleHeader is a B3 encoding that uses multiple headers to - // transmit tracing information all prefixed with `x-b3-`. - B3MultipleHeader B3Encoding = 1 << iota - // B3SingleHeader is a B3 encoding that uses a single header named `b3` - // to transmit tracing information. - B3SingleHeader - // B3Unspecified is an unspecified B3 encoding. - B3Unspecified B3Encoding = 0 -) - -// B3 propagator serializes SpanContext to/from B3 Headers. -// This propagator supports both versions of B3 headers, -// 1. Single Header: -// b3: {TraceId}-{SpanId}-{SamplingState}-{ParentSpanId} -// 2. Multiple Headers: -// x-b3-traceid: {TraceId} -// x-b3-parentspanid: {ParentSpanId} -// x-b3-spanid: {SpanId} -// x-b3-sampled: {SamplingState} -// x-b3-flags: {DebugFlag} -type B3 struct { - // InjectEncoding are the B3 encodings used when injecting trace - // information. If no encoding is specified (i.e. `B3Unspecified`) - // `B3MultipleHeader` will be used as the default. - InjectEncoding B3Encoding -} - -var _ propagation.HTTPPropagator = B3{} - -// Inject injects a context into the supplier as B3 headers. -// The parent span ID is omitted because it is not tracked in the -// SpanContext. -func (b3 B3) Inject(ctx context.Context, supplier propagation.HTTPSupplier) { - sc := SpanFromContext(ctx).SpanContext() - - if b3.InjectEncoding.supports(B3SingleHeader) { - header := []string{} - if sc.TraceID.IsValid() && sc.SpanID.IsValid() { - header = append(header, sc.TraceID.String(), sc.SpanID.String()) - } - - if sc.isDebug() { - header = append(header, "d") - } else if !sc.isDeferred() { - if sc.IsSampled() { - header = append(header, "1") - } else { - header = append(header, "0") - } - } - - supplier.Set(b3ContextHeader, strings.Join(header, "-")) - } - - if b3.InjectEncoding.supports(B3MultipleHeader) || b3.InjectEncoding == B3Unspecified { - if sc.TraceID.IsValid() && sc.SpanID.IsValid() { - supplier.Set(b3TraceIDHeader, sc.TraceID.String()) - supplier.Set(b3SpanIDHeader, sc.SpanID.String()) - } - - if sc.isDebug() { - // Since Debug implies deferred, don't also send "X-B3-Sampled". - supplier.Set(b3DebugFlagHeader, "1") - } else if !sc.isDeferred() { - if sc.IsSampled() { - supplier.Set(b3SampledHeader, "1") - } else { - supplier.Set(b3SampledHeader, "0") - } - } - } -} - -// Extract extracts a context from the supplier if it contains B3 headers. -func (b3 B3) Extract(ctx context.Context, supplier propagation.HTTPSupplier) context.Context { - var ( - sc SpanContext - err error - ) - - // Default to Single Header if a valid value exists. - if h := supplier.Get(b3ContextHeader); h != "" { - sc, err = extractSingle(h) - if err == nil && sc.IsValid() { - return ContextWithRemoteSpanContext(ctx, sc) - } - // The Single Header value was invalid, fallback to Multiple Header. - } - - var ( - traceID = supplier.Get(b3TraceIDHeader) - spanID = supplier.Get(b3SpanIDHeader) - parentSpanID = supplier.Get(b3ParentSpanIDHeader) - sampled = supplier.Get(b3SampledHeader) - debugFlag = supplier.Get(b3DebugFlagHeader) - ) - sc, err = extractMultiple(traceID, spanID, parentSpanID, sampled, debugFlag) - if err != nil || !sc.IsValid() { - return ctx - } - return ContextWithRemoteSpanContext(ctx, sc) -} - -func (b3 B3) GetAllKeys() []string { - header := []string{} - if b3.InjectEncoding.supports(B3SingleHeader) { - header = append(header, b3ContextHeader) - } - if b3.InjectEncoding.supports(B3MultipleHeader) || b3.InjectEncoding == B3Unspecified { - header = append(header, b3TraceIDHeader, b3SpanIDHeader, b3SampledHeader, b3DebugFlagHeader) - } - return header -} - -// extractMultiple reconstructs a SpanContext from header values based on B3 -// Multiple header. It is based on the implementation found here: -// https://github.com/openzipkin/zipkin-go/blob/v0.2.2/propagation/b3/spancontext.go -// and adapted to support a SpanContext. -func extractMultiple(traceID, spanID, parentSpanID, sampled, flags string) (SpanContext, error) { - var ( - err error - requiredCount int - sc = SpanContext{} - ) - - // correct values for an existing sampled header are "0" and "1". - // For legacy support and being lenient to other tracing implementations we - // allow "true" and "false" as inputs for interop purposes. - switch strings.ToLower(sampled) { - case "0", "false": - // Zero value for TraceFlags sample bit is unset. - case "1", "true": - sc.TraceFlags = FlagsSampled - case "": - sc.TraceFlags = FlagsDeferred - default: - return empty, errInvalidSampledHeader - } - - // The only accepted value for Flags is "1". This will set Debug to - // true. All other values and omission of header will be ignored. - if flags == "1" { - sc.TraceFlags |= FlagsDebug - } - - if traceID != "" { - requiredCount++ - id := traceID - if len(traceID) == 16 { - // Pad 64-bit trace IDs. - id = b3TraceIDPadding + traceID - } - if sc.TraceID, err = IDFromHex(id); err != nil { - return empty, errInvalidTraceIDHeader - } - } - - if spanID != "" { - requiredCount++ - if sc.SpanID, err = SpanIDFromHex(spanID); err != nil { - return empty, errInvalidSpanIDHeader - } - } - - if requiredCount != 0 && requiredCount != 2 { - return empty, errInvalidScope - } - - if parentSpanID != "" { - if requiredCount == 0 { - return empty, errInvalidScopeParent - } - // Validate parent span ID but we do not use it so do not save it. - if _, err = SpanIDFromHex(parentSpanID); err != nil { - return empty, errInvalidParentSpanIDHeader - } - } - - return sc, nil -} - -// extractSingle reconstructs a SpanContext from contextHeader based on a B3 -// Single header. It is based on the implementation found here: -// https://github.com/openzipkin/zipkin-go/blob/v0.2.2/propagation/b3/spancontext.go -// and adapted to support a SpanContext. -func extractSingle(contextHeader string) (SpanContext, error) { - if contextHeader == "" { - return empty, errEmptyContext - } - - var ( - sc = SpanContext{} - sampling string - ) - - headerLen := len(contextHeader) - - if headerLen == samplingWidth { - sampling = contextHeader - } else if headerLen == traceID64BitsWidth || headerLen == traceID128BitsWidth { - // Trace ID by itself is invalid. - return empty, errInvalidScope - } else if headerLen >= traceID64BitsWidth+spanIDWidth+separatorWidth { - pos := 0 - var traceID string - if string(contextHeader[traceID64BitsWidth]) == "-" { - // traceID must be 64 bits - pos += traceID64BitsWidth // {traceID} - traceID = b3TraceIDPadding + string(contextHeader[0:pos]) - } else if string(contextHeader[32]) == "-" { - // traceID must be 128 bits - pos += traceID128BitsWidth // {traceID} - traceID = string(contextHeader[0:pos]) - } else { - return empty, errInvalidTraceIDValue - } - var err error - sc.TraceID, err = IDFromHex(traceID) - if err != nil { - return empty, errInvalidTraceIDValue - } - pos += separatorWidth // {traceID}- - - sc.SpanID, err = SpanIDFromHex(contextHeader[pos : pos+spanIDWidth]) - if err != nil { - return empty, errInvalidSpanIDValue - } - pos += spanIDWidth // {traceID}-{spanID} - - if headerLen > pos { - if headerLen == pos+separatorWidth { - // {traceID}-{spanID}- is invalid. - return empty, errInvalidSampledByte - } - pos += separatorWidth // {traceID}-{spanID}- - - if headerLen == pos+samplingWidth { - sampling = string(contextHeader[pos]) - } else if headerLen == pos+parentSpanIDWidth { - // {traceID}-{spanID}-{parentSpanID} is invalid. - return empty, errInvalidScopeParentSingle - } else if headerLen == pos+samplingWidth+separatorWidth+parentSpanIDWidth { - sampling = string(contextHeader[pos]) - pos += samplingWidth + separatorWidth // {traceID}-{spanID}-{sampling}- - - // Validate parent span ID but we do not use it so do not - // save it. - _, err = SpanIDFromHex(contextHeader[pos:]) - if err != nil { - return empty, errInvalidParentSpanIDValue - } - } else { - return empty, errInvalidParentSpanIDValue - } - } - } else { - return empty, errInvalidTraceIDValue - } - switch sampling { - case "": - sc.TraceFlags = FlagsDeferred - case "d": - sc.TraceFlags = FlagsDebug - case "1": - sc.TraceFlags = FlagsSampled - case "0": - // Zero value for TraceFlags sample bit is unset. - default: - return empty, errInvalidSampledByte - } - - return sc, nil -} diff --git a/vendor/go.opentelemetry.io/otel/api/trace/context.go b/vendor/go.opentelemetry.io/otel/api/trace/context.go deleted file mode 100644 index 489e3c120..000000000 --- a/vendor/go.opentelemetry.io/otel/api/trace/context.go +++ /dev/null @@ -1,55 +0,0 @@ -// 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 trace - -import ( - "context" -) - -type traceContextKeyType int - -const ( - currentSpanKey traceContextKeyType = iota - remoteContextKey -) - -// ContextWithSpan creates a new context with a current span set to -// the passed span. -func ContextWithSpan(ctx context.Context, span Span) context.Context { - return context.WithValue(ctx, currentSpanKey, span) -} - -// SpanFromContext returns the current span stored in the context. -func SpanFromContext(ctx context.Context) Span { - if span, has := ctx.Value(currentSpanKey).(Span); has { - return span - } - return NoopSpan{} -} - -// ContextWithRemoteSpanContext creates a new context with a remote -// span context set to the passed span context. -func ContextWithRemoteSpanContext(ctx context.Context, sc SpanContext) context.Context { - return context.WithValue(ctx, remoteContextKey, sc) -} - -// RemoteSpanContextFromContext returns the remote span context stored -// in the context. -func RemoteSpanContextFromContext(ctx context.Context) SpanContext { - if sc, ok := ctx.Value(remoteContextKey).(SpanContext); ok { - return sc - } - return EmptySpanContext() -} diff --git a/vendor/go.opentelemetry.io/otel/api/trace/doc.go b/vendor/go.opentelemetry.io/otel/api/trace/doc.go deleted file mode 100644 index 56c13f049..000000000 --- a/vendor/go.opentelemetry.io/otel/api/trace/doc.go +++ /dev/null @@ -1,15 +0,0 @@ -// 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 trace // import "go.opentelemetry.io/otel/api/trace" diff --git a/vendor/go.opentelemetry.io/otel/api/trace/noop_span.go b/vendor/go.opentelemetry.io/otel/api/trace/noop_span.go deleted file mode 100644 index 27f0d319f..000000000 --- a/vendor/go.opentelemetry.io/otel/api/trace/noop_span.go +++ /dev/null @@ -1,79 +0,0 @@ -// 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 trace - -import ( - "context" - "time" - - "go.opentelemetry.io/otel/codes" - "go.opentelemetry.io/otel/label" -) - -type NoopSpan struct { -} - -var _ Span = (*NoopSpan)(nil) - -// SpanContext returns an invalid span context. -func (NoopSpan) SpanContext() SpanContext { - return EmptySpanContext() -} - -// IsRecording always returns false for NoopSpan. -func (NoopSpan) IsRecording() bool { - return false -} - -// SetStatus does nothing. -func (NoopSpan) SetStatus(status codes.Code, msg string) { -} - -// SetError does nothing. -func (NoopSpan) SetError(v bool) { -} - -// SetAttributes does nothing. -func (NoopSpan) SetAttributes(attributes ...label.KeyValue) { -} - -// SetAttribute does nothing. -func (NoopSpan) SetAttribute(k string, v interface{}) { -} - -// End does nothing. -func (NoopSpan) End(options ...EndOption) { -} - -// RecordError does nothing. -func (NoopSpan) RecordError(ctx context.Context, err error, opts ...ErrorOption) { -} - -// Tracer returns noop implementation of Tracer. -func (NoopSpan) Tracer() Tracer { - return NoopTracer{} -} - -// AddEvent does nothing. -func (NoopSpan) AddEvent(ctx context.Context, name string, attrs ...label.KeyValue) { -} - -// AddEventWithTimestamp does nothing. -func (NoopSpan) AddEventWithTimestamp(ctx context.Context, timestamp time.Time, name string, attrs ...label.KeyValue) { -} - -// SetName does nothing. -func (NoopSpan) SetName(name string) { -} diff --git a/vendor/go.opentelemetry.io/otel/api/trace/span_context.go b/vendor/go.opentelemetry.io/otel/api/trace/span_context.go deleted file mode 100644 index abce3f76a..000000000 --- a/vendor/go.opentelemetry.io/otel/api/trace/span_context.go +++ /dev/null @@ -1,197 +0,0 @@ -// 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 trace - -import ( - "bytes" - "encoding/hex" - "encoding/json" -) - -const ( - // FlagsSampled is a bitmask with the sampled bit set. A SpanContext - // with the sampling bit set means the span is sampled. - FlagsSampled = byte(0x01) - // FlagsDeferred is a bitmask with the deferred bit set. A SpanContext - // with the deferred bit set means the sampling decision has been - // defered to the receiver. - FlagsDeferred = byte(0x02) - // FlagsDebug is a bitmask with the debug bit set. - FlagsDebug = byte(0x04) - - ErrInvalidHexID errorConst = "trace-id and span-id can only contain [0-9a-f] characters, all lowercase" - - ErrInvalidTraceIDLength errorConst = "hex encoded trace-id must have length equals to 32" - ErrNilTraceID errorConst = "trace-id can't be all zero" - - ErrInvalidSpanIDLength errorConst = "hex encoded span-id must have length equals to 16" - ErrNilSpanID errorConst = "span-id can't be all zero" -) - -type errorConst string - -func (e errorConst) Error() string { - return string(e) -} - -// ID is a unique identity of a trace. -type ID [16]byte - -var nilTraceID ID -var _ json.Marshaler = nilTraceID - -// IsValid checks whether the trace ID is valid. A valid trace ID does -// not consist of zeros only. -func (t ID) IsValid() bool { - return !bytes.Equal(t[:], nilTraceID[:]) -} - -// MarshalJSON implements a custom marshal function to encode TraceID -// as a hex string. -func (t ID) MarshalJSON() ([]byte, error) { - return json.Marshal(t.String()) -} - -// String returns the hex string representation form of a TraceID -func (t ID) String() string { - return hex.EncodeToString(t[:]) -} - -// SpanID is a unique identify of a span in a trace. -type SpanID [8]byte - -var nilSpanID SpanID -var _ json.Marshaler = nilSpanID - -// IsValid checks whether the span ID is valid. A valid span ID does -// not consist of zeros only. -func (s SpanID) IsValid() bool { - return !bytes.Equal(s[:], nilSpanID[:]) -} - -// MarshalJSON implements a custom marshal function to encode SpanID -// as a hex string. -func (s SpanID) MarshalJSON() ([]byte, error) { - return json.Marshal(s.String()) -} - -// String returns the hex string representation form of a SpanID -func (s SpanID) String() string { - return hex.EncodeToString(s[:]) -} - -// IDFromHex returns a TraceID from a hex string if it is compliant -// with the w3c trace-context specification. -// See more at https://www.w3.org/TR/trace-context/#trace-id -func IDFromHex(h string) (ID, error) { - t := ID{} - if len(h) != 32 { - return t, ErrInvalidTraceIDLength - } - - if err := decodeHex(h, t[:]); err != nil { - return t, err - } - - if !t.IsValid() { - return t, ErrNilTraceID - } - return t, nil -} - -// SpanIDFromHex returns a SpanID from a hex string if it is compliant -// with the w3c trace-context specification. -// See more at https://www.w3.org/TR/trace-context/#parent-id -func SpanIDFromHex(h string) (SpanID, error) { - s := SpanID{} - if len(h) != 16 { - return s, ErrInvalidSpanIDLength - } - - if err := decodeHex(h, s[:]); err != nil { - return s, err - } - - if !s.IsValid() { - return s, ErrNilSpanID - } - return s, nil -} - -func decodeHex(h string, b []byte) error { - for _, r := range h { - switch { - case 'a' <= r && r <= 'f': - continue - case '0' <= r && r <= '9': - continue - default: - return ErrInvalidHexID - } - } - - decoded, err := hex.DecodeString(h) - if err != nil { - return err - } - - copy(b, decoded) - return nil -} - -// SpanContext contains basic information about the span - its trace -// ID, span ID and trace flags. -type SpanContext struct { - TraceID ID - SpanID SpanID - TraceFlags byte -} - -// EmptySpanContext is meant for internal use to return invalid span -// context during error conditions. -func EmptySpanContext() SpanContext { - return SpanContext{} -} - -// IsValid checks if the span context is valid. A valid span context -// has a valid trace ID and a valid span ID. -func (sc SpanContext) IsValid() bool { - return sc.HasTraceID() && sc.HasSpanID() -} - -// HasTraceID checks if the span context has a valid trace ID. -func (sc SpanContext) HasTraceID() bool { - return sc.TraceID.IsValid() -} - -// HasSpanID checks if the span context has a valid span ID. -func (sc SpanContext) HasSpanID() bool { - return sc.SpanID.IsValid() -} - -// isDeferred returns if the deferred bit is set in the trace flags. -func (sc SpanContext) isDeferred() bool { - return sc.TraceFlags&FlagsDeferred == FlagsDeferred -} - -// isDebug returns if the debug bit is set in the trace flags. -func (sc SpanContext) isDebug() bool { - return sc.TraceFlags&FlagsDebug == FlagsDebug -} - -// IsSampled returns if the sampling bit is set in the trace flags. -func (sc SpanContext) IsSampled() bool { - return sc.TraceFlags&FlagsSampled == FlagsSampled -} diff --git a/vendor/go.opentelemetry.io/otel/api/trace/trace_context_propagator.go b/vendor/go.opentelemetry.io/otel/api/trace/trace_context_propagator.go deleted file mode 100644 index 5413106f4..000000000 --- a/vendor/go.opentelemetry.io/otel/api/trace/trace_context_propagator.go +++ /dev/null @@ -1,152 +0,0 @@ -// 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 trace - -import ( - "context" - "encoding/hex" - "fmt" - "regexp" - - "go.opentelemetry.io/otel/api/propagation" -) - -const ( - supportedVersion = 0 - maxVersion = 254 - traceparentHeader = "traceparent" - tracestateHeader = "tracestate" -) - -type traceContextPropagatorKeyType uint - -const ( - tracestateKey traceContextPropagatorKeyType = 0 -) - -// TraceContext propagates SpanContext in W3C TraceContext format. -//nolint:golint -type TraceContext struct{} - -var _ propagation.HTTPPropagator = TraceContext{} -var traceCtxRegExp = regexp.MustCompile("^(?P[0-9a-f]{2})-(?P[a-f0-9]{32})-(?P[a-f0-9]{16})-(?P[a-f0-9]{2})(?:-.*)?$") - -// DefaultHTTPPropagator returns the default trace HTTP propagator. -func DefaultHTTPPropagator() propagation.HTTPPropagator { - return TraceContext{} -} - -func (TraceContext) Inject(ctx context.Context, supplier propagation.HTTPSupplier) { - tracestate := ctx.Value(tracestateKey) - if state, ok := tracestate.(string); tracestate != nil && ok { - supplier.Set(tracestateHeader, state) - } - - sc := SpanFromContext(ctx).SpanContext() - if !sc.IsValid() { - return - } - h := fmt.Sprintf("%.2x-%s-%s-%.2x", - supportedVersion, - sc.TraceID, - sc.SpanID, - sc.TraceFlags&FlagsSampled) - supplier.Set(traceparentHeader, h) -} - -func (tc TraceContext) Extract(ctx context.Context, supplier propagation.HTTPSupplier) context.Context { - state := supplier.Get(tracestateHeader) - if state != "" { - ctx = context.WithValue(ctx, tracestateKey, state) - } - - sc := tc.extract(supplier) - if !sc.IsValid() { - return ctx - } - return ContextWithRemoteSpanContext(ctx, sc) -} - -func (TraceContext) extract(supplier propagation.HTTPSupplier) SpanContext { - h := supplier.Get(traceparentHeader) - if h == "" { - return EmptySpanContext() - } - - matches := traceCtxRegExp.FindStringSubmatch(h) - - if len(matches) == 0 { - return EmptySpanContext() - } - - if len(matches) < 5 { // four subgroups plus the overall match - return EmptySpanContext() - } - - if len(matches[1]) != 2 { - return EmptySpanContext() - } - ver, err := hex.DecodeString(matches[1]) - if err != nil { - return EmptySpanContext() - } - version := int(ver[0]) - if version > maxVersion { - return EmptySpanContext() - } - - if version == 0 && len(matches) != 5 { // four subgroups plus the overall match - return EmptySpanContext() - } - - if len(matches[2]) != 32 { - return EmptySpanContext() - } - - var sc SpanContext - - sc.TraceID, err = IDFromHex(matches[2][:32]) - if err != nil { - return EmptySpanContext() - } - - if len(matches[3]) != 16 { - return EmptySpanContext() - } - sc.SpanID, err = SpanIDFromHex(matches[3]) - if err != nil { - return EmptySpanContext() - } - - if len(matches[4]) != 2 { - return EmptySpanContext() - } - opts, err := hex.DecodeString(matches[4]) - if err != nil || len(opts) < 1 || (version == 0 && opts[0] > 2) { - return EmptySpanContext() - } - // Clear all flags other than the trace-context supported sampling bit. - sc.TraceFlags = opts[0] & FlagsSampled - - if !sc.IsValid() { - return EmptySpanContext() - } - - return sc -} - -func (TraceContext) GetAllKeys() []string { - return []string{traceparentHeader, tracestateHeader} -} diff --git a/vendor/go.opentelemetry.io/otel/api/trace/noop_trace_provider.go b/vendor/go.opentelemetry.io/otel/attribute/doc.go similarity index 63% rename from vendor/go.opentelemetry.io/otel/api/trace/noop_trace_provider.go rename to vendor/go.opentelemetry.io/otel/attribute/doc.go index 6a5f1a285..44bc32c9e 100644 --- a/vendor/go.opentelemetry.io/otel/api/trace/noop_trace_provider.go +++ b/vendor/go.opentelemetry.io/otel/attribute/doc.go @@ -12,13 +12,9 @@ // See the License for the specific language governing permissions and // limitations under the License. -package trace - -type NoopProvider struct{} - -var _ Provider = NoopProvider{} - -// Tracer returns noop implementation of Tracer. -func (p NoopProvider) Tracer(_ string, _ ...TracerOption) Tracer { - return NoopTracer{} -} +// package attribute provides key and value attributes. +// +// This package is currently in a pre-GA phase. Backwards incompatible changes +// may be introduced in subsequent minor version releases as we work to track +// the evolving OpenTelemetry specification and user feedback. +package attribute // import "go.opentelemetry.io/otel/attribute" diff --git a/vendor/go.opentelemetry.io/otel/label/encoder.go b/vendor/go.opentelemetry.io/otel/attribute/encoder.go similarity index 97% rename from vendor/go.opentelemetry.io/otel/label/encoder.go rename to vendor/go.opentelemetry.io/otel/attribute/encoder.go index 17e6d2dfb..8b940f78d 100644 --- a/vendor/go.opentelemetry.io/otel/label/encoder.go +++ b/vendor/go.opentelemetry.io/otel/attribute/encoder.go @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -package label +package attribute // import "go.opentelemetry.io/otel/attribute" import ( "bytes" @@ -28,8 +28,8 @@ type ( Encoder interface { // Encode returns the serialized encoding of the label // set using its Iterator. This result may be cached - // by a label.Set. - Encode(Iterator) string + // by a attribute.Set. + Encode(iterator Iterator) string // ID returns a value that is unique for each class of // label encoder. Label encoders allocate these using diff --git a/vendor/go.opentelemetry.io/otel/label/iterator.go b/vendor/go.opentelemetry.io/otel/attribute/iterator.go similarity index 90% rename from vendor/go.opentelemetry.io/otel/label/iterator.go rename to vendor/go.opentelemetry.io/otel/attribute/iterator.go index 9e7223998..e03aabb62 100644 --- a/vendor/go.opentelemetry.io/otel/label/iterator.go +++ b/vendor/go.opentelemetry.io/otel/attribute/iterator.go @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -package label +package attribute // import "go.opentelemetry.io/otel/attribute" // Iterator allows iterating over the set of labels in order, // sorted by key. @@ -24,7 +24,7 @@ type Iterator struct { // MergeIterator supports iterating over two sets of labels while // eliminating duplicate values from the combined set. The first // iterator value takes precedence. -type MergeItererator struct { +type MergeIterator struct { one oneIterator two oneIterator current KeyValue @@ -55,7 +55,7 @@ func (i *Iterator) Attribute() KeyValue { return i.Label() } -// IndexedLabel returns current index and label. Must be called only +// IndexedLabel returns current index and attribute. Must be called only // after Next returns true. func (i *Iterator) IndexedLabel() (int, KeyValue) { return i.idx, i.Label() @@ -84,8 +84,8 @@ func (i *Iterator) ToSlice() []KeyValue { // NewMergeIterator returns a MergeIterator for merging two label sets // Duplicates are resolved by taking the value from the first set. -func NewMergeIterator(s1, s2 *Set) MergeItererator { - mi := MergeItererator{ +func NewMergeIterator(s1, s2 *Set) MergeIterator { + mi := MergeIterator{ one: makeOne(s1.Iter()), two: makeOne(s2.Iter()), } @@ -107,7 +107,7 @@ func (oi *oneIterator) advance() { } // Next returns true if there is another label available. -func (m *MergeItererator) Next() bool { +func (m *MergeIterator) Next() bool { if m.one.done && m.two.done { return false } @@ -138,6 +138,6 @@ func (m *MergeItererator) Next() bool { } // Label returns the current value after Next() returns true. -func (m *MergeItererator) Label() KeyValue { +func (m *MergeIterator) Label() KeyValue { return m.current } diff --git a/vendor/go.opentelemetry.io/otel/label/key.go b/vendor/go.opentelemetry.io/otel/attribute/key.go similarity index 58% rename from vendor/go.opentelemetry.io/otel/label/key.go rename to vendor/go.opentelemetry.io/otel/attribute/key.go index 7d7237809..492c438a9 100644 --- a/vendor/go.opentelemetry.io/otel/label/key.go +++ b/vendor/go.opentelemetry.io/otel/attribute/key.go @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -package label +package attribute // import "go.opentelemetry.io/otel/attribute" // Key represents the key part in key-value pairs. It's a string. The // allowed character set in the key depends on the use of the key. @@ -44,19 +44,6 @@ func (k Key) Int64(v int64) KeyValue { } } -// Uint64 creates a KeyValue instance with a UINT64 Value. -// -// If creating both key and a uint64 value at the same time, then -// instead of calling Key(name).Uint64(value) consider using a -// convenience function provided by the api/key package - -// key.Uint64(name, value). -func (k Key) Uint64(v uint64) KeyValue { - return KeyValue{ - Key: k, - Value: Uint64Value(v), - } -} - // Float64 creates a KeyValue instance with a FLOAT64 Value. // // If creating both key and a float64 value at the same time, then @@ -70,45 +57,6 @@ func (k Key) Float64(v float64) KeyValue { } } -// Int32 creates a KeyValue instance with an INT32 Value. -// -// If creating both key and an int32 value at the same time, then -// instead of calling Key(name).Int32(value) consider using a -// convenience function provided by the api/key package - -// key.Int32(name, value). -func (k Key) Int32(v int32) KeyValue { - return KeyValue{ - Key: k, - Value: Int32Value(v), - } -} - -// Uint32 creates a KeyValue instance with a UINT32 Value. -// -// If creating both key and a uint32 value at the same time, then -// instead of calling Key(name).Uint32(value) consider using a -// convenience function provided by the api/key package - -// key.Uint32(name, value). -func (k Key) Uint32(v uint32) KeyValue { - return KeyValue{ - Key: k, - Value: Uint32Value(v), - } -} - -// Float32 creates a KeyValue instance with a FLOAT32 Value. -// -// If creating both key and a float32 value at the same time, then -// instead of calling Key(name).Float32(value) consider using a -// convenience function provided by the api/key package - -// key.Float32(name, value). -func (k Key) Float32(v float32) KeyValue { - return KeyValue{ - Key: k, - Value: Float32Value(v), - } -} - // String creates a KeyValue instance with a STRING Value. // // If creating both key and a string value at the same time, then @@ -122,8 +70,7 @@ func (k Key) String(v string) KeyValue { } } -// Int creates a KeyValue instance with either an INT32 or an INT64 -// Value, depending on whether the int type is 32 or 64 bits wide. +// Int creates a KeyValue instance with an INT64 Value. // // If creating both key and an int value at the same time, then // instead of calling Key(name).Int(value) consider using a @@ -136,20 +83,6 @@ func (k Key) Int(v int) KeyValue { } } -// Uint creates a KeyValue instance with either a UINT32 or a UINT64 -// Value, depending on whether the uint type is 32 or 64 bits wide. -// -// If creating both key and a uint value at the same time, then -// instead of calling Key(name).Uint(value) consider using a -// convenience function provided by the api/key package - -// key.Uint(name, value). -func (k Key) Uint(v uint) KeyValue { - return KeyValue{ - Key: k, - Value: UintValue(v), - } -} - // Defined returns true for non-empty keys. func (k Key) Defined() bool { return len(k) != 0 diff --git a/vendor/go.opentelemetry.io/otel/label/kv.go b/vendor/go.opentelemetry.io/otel/attribute/kv.go similarity index 67% rename from vendor/go.opentelemetry.io/otel/label/kv.go rename to vendor/go.opentelemetry.io/otel/attribute/kv.go index 3e2764f47..0e5b06d82 100644 --- a/vendor/go.opentelemetry.io/otel/label/kv.go +++ b/vendor/go.opentelemetry.io/otel/attribute/kv.go @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -package label +package attribute // import "go.opentelemetry.io/otel/attribute" import ( "encoding/json" @@ -38,36 +38,12 @@ func Int64(k string, v int64) KeyValue { return Key(k).Int64(v) } -// Uint64 creates a new key-value pair with a passed name and a uint64 -// value. -func Uint64(k string, v uint64) KeyValue { - return Key(k).Uint64(v) -} - // Float64 creates a new key-value pair with a passed name and a float64 // value. func Float64(k string, v float64) KeyValue { return Key(k).Float64(v) } -// Int32 creates a new key-value pair with a passed name and an int32 -// value. -func Int32(k string, v int32) KeyValue { - return Key(k).Int32(v) -} - -// Uint32 creates a new key-value pair with a passed name and a uint32 -// value. -func Uint32(k string, v uint32) KeyValue { - return Key(k).Uint32(v) -} - -// Float32 creates a new key-value pair with a passed name and a float32 -// value. -func Float32(k string, v float32) KeyValue { - return Key(k).Float32(v) -} - // String creates a new key-value pair with a passed name and a string // value. func String(k, v string) KeyValue { @@ -87,13 +63,6 @@ func Int(k string, v int) KeyValue { return Key(k).Int(v) } -// Uint creates a new key-value pair instance with a passed name and -// either an uint32 or an uint64 value, depending on whether the uint -// type is 32 or 64 bits wide. -func Uint(k string, v uint) KeyValue { - return Key(k).Uint(v) -} - // Array creates a new key-value pair with a passed name and a array. // Only arrays of primitive type are supported. func Array(k string, v interface{}) KeyValue { @@ -120,24 +89,14 @@ func Any(k string, value interface{}) KeyValue { return Bool(k, rv.Bool()) case reflect.Int, reflect.Int8, reflect.Int16: return Int(k, int(rv.Int())) - case reflect.Int32: - return Int32(k, int32(rv.Int())) case reflect.Int64: - return Int64(k, int64(rv.Int())) - case reflect.Uint, reflect.Uint8, reflect.Uint16: - return Uint(k, uint(rv.Uint())) - case reflect.Uint32: - return Uint32(k, uint32(rv.Uint())) - case reflect.Uint64, reflect.Uintptr: - return Uint64(k, rv.Uint()) - case reflect.Float32: - return Float32(k, float32(rv.Float())) + return Int64(k, rv.Int()) case reflect.Float64: return Float64(k, rv.Float()) case reflect.String: return String(k, rv.String()) } - if b, err := json.Marshal(value); value != nil && err == nil { + if b, err := json.Marshal(value); b != nil && err == nil { return String(k, string(b)) } return String(k, fmt.Sprint(value)) diff --git a/vendor/go.opentelemetry.io/otel/label/set.go b/vendor/go.opentelemetry.io/otel/attribute/set.go similarity index 97% rename from vendor/go.opentelemetry.io/otel/label/set.go rename to vendor/go.opentelemetry.io/otel/attribute/set.go index 3bd5263cb..882dc112f 100644 --- a/vendor/go.opentelemetry.io/otel/label/set.go +++ b/vendor/go.opentelemetry.io/otel/attribute/set.go @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -package label +package attribute // import "go.opentelemetry.io/otel/attribute" import ( "encoding/json" @@ -78,6 +78,9 @@ var ( const maxConcurrentEncoders = 3 +// EmptySet returns a reference to a Set with no elements. +// +// This is a convenience provided for optimized calling utility. func EmptySet() *Set { return emptySet } @@ -292,7 +295,7 @@ func NewSetWithFiltered(kvs []KeyValue, filter Filter) (Set, []KeyValue) { // - allocating a `Set` for storing the return value of this // constructor. // -// The result maintains a cache of encoded labels, by label.EncoderID. +// The result maintains a cache of encoded labels, by attribute.EncoderID. // This value should not be copied after its first use. // // The second `[]KeyValue` return value is a list of labels that were diff --git a/vendor/go.opentelemetry.io/otel/label/type_string.go b/vendor/go.opentelemetry.io/otel/attribute/type_string.go similarity index 61% rename from vendor/go.opentelemetry.io/otel/label/type_string.go rename to vendor/go.opentelemetry.io/otel/attribute/type_string.go index 62afeb60a..1f2c7dccf 100644 --- a/vendor/go.opentelemetry.io/otel/label/type_string.go +++ b/vendor/go.opentelemetry.io/otel/attribute/type_string.go @@ -1,6 +1,6 @@ // Code generated by "stringer -type=Type"; DO NOT EDIT. -package label +package attribute import "strconv" @@ -10,19 +10,15 @@ func _() { var x [1]struct{} _ = x[INVALID-0] _ = x[BOOL-1] - _ = x[INT32-2] - _ = x[INT64-3] - _ = x[UINT32-4] - _ = x[UINT64-5] - _ = x[FLOAT32-6] - _ = x[FLOAT64-7] - _ = x[STRING-8] - _ = x[ARRAY-9] + _ = x[INT64-2] + _ = x[FLOAT64-3] + _ = x[STRING-4] + _ = x[ARRAY-5] } -const _Type_name = "INVALIDBOOLINT32INT64UINT32UINT64FLOAT32FLOAT64STRINGARRAY" +const _Type_name = "INVALIDBOOLINT64FLOAT64STRINGARRAY" -var _Type_index = [...]uint8{0, 7, 11, 16, 21, 27, 33, 40, 47, 53, 58} +var _Type_index = [...]uint8{0, 7, 11, 16, 23, 29, 34} func (i Type) String() string { if i < 0 || i >= Type(len(_Type_index)-1) { diff --git a/vendor/go.opentelemetry.io/otel/label/value.go b/vendor/go.opentelemetry.io/otel/attribute/value.go similarity index 51% rename from vendor/go.opentelemetry.io/otel/label/value.go rename to vendor/go.opentelemetry.io/otel/attribute/value.go index 633979f1b..44ef795cb 100644 --- a/vendor/go.opentelemetry.io/otel/label/value.go +++ b/vendor/go.opentelemetry.io/otel/attribute/value.go @@ -12,15 +12,13 @@ // See the License for the specific language governing permissions and // limitations under the License. -package label +package attribute // import "go.opentelemetry.io/otel/attribute" import ( "encoding/json" "fmt" "reflect" "strconv" - "strings" - "unsafe" "go.opentelemetry.io/otel/internal" ) @@ -41,16 +39,20 @@ type Value struct { } const ( - INVALID Type = iota // No value. - BOOL // Boolean value, use AsBool() to get it. - INT32 // 32 bit signed integral value, use AsInt32() to get it. - INT64 // 64 bit signed integral value, use AsInt64() to get it. - UINT32 // 32 bit unsigned integral value, use AsUint32() to get it. - UINT64 // 64 bit unsigned integral value, use AsUint64() to get it. - FLOAT32 // 32 bit floating point value, use AsFloat32() to get it. - FLOAT64 // 64 bit floating point value, use AsFloat64() to get it. - STRING // String value, use AsString() to get it. - ARRAY // Array value of arbitrary type, use AsArray() to get it. + // INVALID is used for a Value with no value set. + INVALID Type = iota + // BOOL is a boolean Type Value. + BOOL + // INT64 is a 64-bit signed integral Type Value. + INT64 + // UINT32 is a 32-bit unsigned integral Type Value. + FLOAT64 + // STRING is a string Type Value. + STRING + // ARRAY is an array Type Value used to store 1-dimensional slices or + // arrays of bool, int, int32, int64, uint, uint32, uint64, float, + // float32, float64, or string types. + ARRAY ) // BoolValue creates a BOOL Value. @@ -69,14 +71,6 @@ func Int64Value(v int64) Value { } } -// Uint64Value creates a UINT64 Value. -func Uint64Value(v uint64) Value { - return Value{ - vtype: UINT64, - numeric: internal.Uint64ToRaw(v), - } -} - // Float64Value creates a FLOAT64 Value. func Float64Value(v float64) Value { return Value{ @@ -85,31 +79,7 @@ func Float64Value(v float64) Value { } } -// Int32Value creates an INT32 Value. -func Int32Value(v int32) Value { - return Value{ - vtype: INT32, - numeric: internal.Int32ToRaw(v), - } -} - -// Uint32 creates a UINT32 Value. -func Uint32Value(v uint32) Value { - return Value{ - vtype: UINT32, - numeric: internal.Uint32ToRaw(v), - } -} - -// Float32 creates a FLOAT32 Value. -func Float32Value(v float32) Value { - return Value{ - vtype: FLOAT32, - numeric: internal.Float32ToRaw(v), - } -} - -// String creates a STRING Value. +// StringValue creates a STRING Value. func StringValue(v string) Value { return Value{ vtype: STRING, @@ -117,45 +87,35 @@ func StringValue(v string) Value { } } -// Int creates either an INT32 or an INT64 Value, depending on whether -// the int type is 32 or 64 bits wide. +// IntValue creates an INT64 Value. func IntValue(v int) Value { - if unsafe.Sizeof(v) == 4 { - return Int32Value(int32(v)) - } return Int64Value(int64(v)) } -// Uint creates either a UINT32 or a UINT64 Value, depending on -// whether the uint type is 32 or 64 bits wide. -func UintValue(v uint) Value { - if unsafe.Sizeof(v) == 4 { - return Uint32Value(uint32(v)) - } - return Uint64Value(uint64(v)) -} - -// Array creates an ARRAY value. -func ArrayValue(array interface{}) Value { - switch reflect.TypeOf(array).Kind() { +// ArrayValue creates an ARRAY value from an array or slice. +// Only arrays or slices of bool, int, int64, float, float64, or string types are allowed. +// Specifically, arrays and slices can not contain other arrays, slices, structs, or non-standard +// types. If the passed value is not an array or slice of these types an +// INVALID value is returned. +func ArrayValue(v interface{}) Value { + switch reflect.TypeOf(v).Kind() { case reflect.Array, reflect.Slice: - isValidType := func() bool { - // get array type regardless of dimensions - typeName := reflect.TypeOf(array).String() - typeName = typeName[strings.LastIndex(typeName, "]")+1:] - switch typeName { - case "bool", "int", "int32", "int64", - "float32", "float64", "string", - "uint", "uint32", "uint64": - return true - } - return false - }() - if isValidType { + // get array type regardless of dimensions + typ := reflect.TypeOf(v).Elem() + kind := typ.Kind() + switch kind { + case reflect.Bool, reflect.Int, reflect.Int64, + reflect.Float64, reflect.String: + val := reflect.ValueOf(v) + length := val.Len() + frozen := reflect.Indirect(reflect.New(reflect.ArrayOf(length, typ))) + reflect.Copy(frozen, val) return Value{ vtype: ARRAY, - array: array, + array: frozen.Interface(), } + default: + return Value{vtype: INVALID} } } return Value{vtype: INVALID} @@ -172,36 +132,12 @@ func (v Value) AsBool() bool { return internal.RawToBool(v.numeric) } -// AsInt32 returns the int32 value. Make sure that the Value's type is -// INT32. -func (v Value) AsInt32() int32 { - return internal.RawToInt32(v.numeric) -} - // AsInt64 returns the int64 value. Make sure that the Value's type is // INT64. func (v Value) AsInt64() int64 { return internal.RawToInt64(v.numeric) } -// AsUint32 returns the uint32 value. Make sure that the Value's type -// is UINT32. -func (v Value) AsUint32() uint32 { - return internal.RawToUint32(v.numeric) -} - -// AsUint64 returns the uint64 value. Make sure that the Value's type is -// UINT64. -func (v Value) AsUint64() uint64 { - return internal.RawToUint64(v.numeric) -} - -// AsFloat32 returns the float32 value. Make sure that the Value's -// type is FLOAT32. -func (v Value) AsFloat32() float32 { - return internal.RawToFloat32(v.numeric) -} - // AsFloat64 returns the float64 value. Make sure that the Value's // type is FLOAT64. func (v Value) AsFloat64() float64 { @@ -228,16 +164,8 @@ func (v Value) AsInterface() interface{} { return v.AsArray() case BOOL: return v.AsBool() - case INT32: - return v.AsInt32() case INT64: return v.AsInt64() - case UINT32: - return v.AsUint32() - case UINT64: - return v.AsUint64() - case FLOAT32: - return v.AsFloat32() case FLOAT64: return v.AsFloat64() case STRING: @@ -253,16 +181,8 @@ func (v Value) Emit() string { return fmt.Sprint(v.array) case BOOL: return strconv.FormatBool(v.AsBool()) - case INT32: - return strconv.FormatInt(int64(v.AsInt32()), 10) case INT64: return strconv.FormatInt(v.AsInt64(), 10) - case UINT32: - return strconv.FormatUint(uint64(v.AsUint32()), 10) - case UINT64: - return strconv.FormatUint(v.AsUint64(), 10) - case FLOAT32: - return fmt.Sprint(v.AsFloat32()) case FLOAT64: return fmt.Sprint(v.AsFloat64()) case STRING: diff --git a/vendor/go.opentelemetry.io/otel/codes/codes.go b/vendor/go.opentelemetry.io/otel/codes/codes.go index 7d4aaee22..064a9279f 100644 --- a/vendor/go.opentelemetry.io/otel/codes/codes.go +++ b/vendor/go.opentelemetry.io/otel/codes/codes.go @@ -12,78 +12,95 @@ // See the License for the specific language governing permissions and // limitations under the License. -// Package codes defines the canonical error codes used by OpenTelemetry. -// -// It conforms to [the OpenTelemetry -// specification](https://github.com/open-telemetry/opentelemetry-specification/blob/master/specification/trace/api.md#statuscanonicalcode). -// This also means that it follows gRPC codes and is based on -// [google.golang.org/grpc/codes](https://godoc.org/google.golang.org/grpc/codes). -// -// This package was added to this project, instead of using that existing -// package, to avoid the large package size it includes and not impose that -// burden on projects using this package. -package codes +package codes // import "go.opentelemetry.io/otel/codes" -// Code is an 32-bit representation of a status state. -type Code uint32 +import ( + "encoding/json" + "fmt" + "strconv" +) -// WARNING: any changes here must be propagated to the -// otel/sdk/internal/codes.go file. const ( - // OK means success. - OK Code = 0 - // Canceled indicates the operation was canceled (typically by the - // caller). - Canceled Code = 1 - // Unknown error. An example of where this error may be returned is if an - // error is raised by a dependant API that does not contain enough - // information to convert it into a more appropriate error. - Unknown Code = 2 - // InvalidArgument indicates a client specified an invalid argument. Note - // that this differs from FailedPrecondition. InvalidArgument indicates - // arguments that are problematic regardless of the state of the system. - InvalidArgument Code = 3 - // DeadlineExceeded means a deadline expired before the operation could - // complete. For operations that change the state of the system, this error - // may be returned even if the operation has completed successfully. - DeadlineExceeded Code = 4 - // NotFound means some requested entity (e.g., file or directory) was not - // found. - NotFound Code = 5 - // AlreadyExists means some entity that we attempted to create (e.g., file - // or directory) already exists. - AlreadyExists Code = 6 - // PermissionDenied means the caller does not have permission to execute - // the specified operation. PermissionDenied must not be used if the caller - // cannot be identified (use Unauthenticated instead for those errors). - PermissionDenied Code = 7 - // ResourceExhausted means some resource has been exhausted, perhaps a - // per-user quota, or perhaps the entire file system is out of space. - ResourceExhausted Code = 8 - // FailedPrecondition means the operation was rejected because the system - // is not in a state required for the operation's execution. - FailedPrecondition Code = 9 - // Aborted means the operation was aborted, typically due to a concurrency - // issue like sequencer check failures, transaction aborts, etc. - Aborted Code = 10 - // OutOfRange means the operation was attempted past the valid range. - // E.g., seeking or reading past end of file. Unlike InvalidArgument, this - // error indicates a problem that may be fixed if the system state - // changes. - OutOfRange Code = 11 - // Unimplemented means the operation is not implemented or not - // supported/enabled in this service. - Unimplemented Code = 12 - // Internal means an internal errors. It means some invariants expected by - // underlying system has been broken. - Internal Code = 13 - // Unavailable means the service is currently unavailable. This is most - // likely a transient condition and may be corrected by retrying with a - // backoff. - Unavailable Code = 14 - // DataLoss means unrecoverable data loss or corruption has occurred. - DataLoss Code = 15 - // Unauthenticated means the request does not have valid authentication - // credentials for the operation. - Unauthenticated Code = 16 + // Unset is the default status code. + Unset Code = 0 + // Error indicates the operation contains an error. + Error Code = 1 + // Ok indicates operation has been validated by an Application developers + // or Operator to have completed successfully, or contain no error. + Ok Code = 2 + + maxCode = 3 ) + +// Code is an 32-bit representation of a status state. +type Code uint32 + +var codeToStr = map[Code]string{ + Unset: "Unset", + Error: "Error", + Ok: "Ok", +} + +var strToCode = map[string]Code{ + `"Unset"`: Unset, + `"Error"`: Error, + `"Ok"`: Ok, +} + +// String returns the Code as a string. +func (c Code) String() string { + return codeToStr[c] +} + +// UnmarshalJSON unmarshals b into the Code. +// +// This is based on the functionality in the gRPC codes package: +// https://github.com/grpc/grpc-go/blob/bb64fee312b46ebee26be43364a7a966033521b1/codes/codes.go#L218-L244 +func (c *Code) UnmarshalJSON(b []byte) error { + // From json.Unmarshaler: By convention, to approximate the behavior of + // Unmarshal itself, Unmarshalers implement UnmarshalJSON([]byte("null")) as + // a no-op. + if string(b) == "null" { + return nil + } + if c == nil { + return fmt.Errorf("nil receiver passed to UnmarshalJSON") + } + + var x interface{} + if err := json.Unmarshal(b, &x); err != nil { + return err + } + switch x.(type) { + case string: + if jc, ok := strToCode[string(b)]; ok { + *c = jc + return nil + } + return fmt.Errorf("invalid code: %q", string(b)) + case float64: + if ci, err := strconv.ParseUint(string(b), 10, 32); err == nil { + if ci >= maxCode { + return fmt.Errorf("invalid code: %q", ci) + } + + *c = Code(ci) + return nil + } + return fmt.Errorf("invalid code: %q", string(b)) + default: + return fmt.Errorf("invalid code: %q", string(b)) + } +} + +// MarshalJSON returns c as the JSON encoding of c. +func (c *Code) MarshalJSON() ([]byte, error) { + if c == nil { + return []byte("null"), nil + } + str, ok := codeToStr[*c] + if !ok { + return nil, fmt.Errorf("invalid code: %d", *c) + } + return []byte(fmt.Sprintf("%q", str)), nil +} diff --git a/vendor/go.opentelemetry.io/otel/api/global/propagation.go b/vendor/go.opentelemetry.io/otel/codes/doc.go similarity index 53% rename from vendor/go.opentelemetry.io/otel/api/global/propagation.go rename to vendor/go.opentelemetry.io/otel/codes/doc.go index e3090293d..fcf89ba1a 100644 --- a/vendor/go.opentelemetry.io/otel/api/global/propagation.go +++ b/vendor/go.opentelemetry.io/otel/codes/doc.go @@ -12,21 +12,14 @@ // See the License for the specific language governing permissions and // limitations under the License. -package global +/* +Package codes defines the canonical error codes used by OpenTelemetry. -import ( - "go.opentelemetry.io/otel/api/global/internal" - "go.opentelemetry.io/otel/api/propagation" -) +This package is currently in a pre-GA phase. Backwards incompatible changes +may be introduced in subsequent minor version releases as we work to track +the evolving OpenTelemetry specification and user feedback. -// Propagators returns the registered global propagators instance. If -// none is registered then an instance of propagators.NoopPropagators -// is returned. -func Propagators() propagation.Propagators { - return internal.Propagators() -} - -// SetPropagators registers `p` as the global propagators instance. -func SetPropagators(p propagation.Propagators) { - internal.SetPropagators(p) -} +It conforms to [the OpenTelemetry +specification](https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/trace/api.md#statuscanonicalcode). +*/ +package codes // import "go.opentelemetry.io/otel/codes" diff --git a/vendor/go.opentelemetry.io/otel/doc.go b/vendor/go.opentelemetry.io/otel/doc.go index af2e5e4d3..771ce81cc 100644 --- a/vendor/go.opentelemetry.io/otel/doc.go +++ b/vendor/go.opentelemetry.io/otel/doc.go @@ -12,4 +12,27 @@ // See the License for the specific language governing permissions and // limitations under the License. +/* +Package otel provides global access to the OpenTelemetry API. The subpackages of +the otel package provide an implementation of the OpenTelemetry API. + +This package is currently in a pre-GA phase. Backwards incompatible changes +may be introduced in subsequent minor version releases as we work to track the +evolving OpenTelemetry specification and user feedback. + +The provided API is used to instrument code and measure data about that code's +performance and operation. The measured data, by default, is not processed or +transmitted anywhere. An implementation of the OpenTelemetry SDK, like the +default SDK implementation (go.opentelemetry.io/otel/sdk), and associated +exporters are used to process and transport this data. + +To read the getting started guide, see https://opentelemetry.io/docs/go/getting-started/. + +To read more about tracing, see go.opentelemetry.io/otel/trace. + +To read more about metrics, see go.opentelemetry.io/otel/metric. + +To read more about propagation, see go.opentelemetry.io/otel/propagation and +go.opentelemetry.io/otel/baggage. +*/ package otel // import "go.opentelemetry.io/otel" diff --git a/vendor/go.opentelemetry.io/otel/error_handler.go b/vendor/go.opentelemetry.io/otel/error_handler.go index 3c5604917..ac42f8be0 100644 --- a/vendor/go.opentelemetry.io/otel/error_handler.go +++ b/vendor/go.opentelemetry.io/otel/error_handler.go @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -package otel +package otel // import "go.opentelemetry.io/otel" // ErrorHandler handles irremediable events. type ErrorHandler interface { diff --git a/vendor/go.opentelemetry.io/otel/get_main_pkgs.sh b/vendor/go.opentelemetry.io/otel/get_main_pkgs.sh index d1c892f0e..9a58fb1d3 100644 --- a/vendor/go.opentelemetry.io/otel/get_main_pkgs.sh +++ b/vendor/go.opentelemetry.io/otel/get_main_pkgs.sh @@ -23,14 +23,19 @@ fi p=$(pwd) mod_dirs=() -mapfile -t mod_dirs < <(find "${top_dir}" -type f -name 'go.mod' -exec dirname {} \; | sort) + +# Note `mapfile` does not exist in older bash versions: +# https://stackoverflow.com/questions/41475261/need-alternative-to-readarray-mapfile-for-script-on-older-version-of-bash + +while IFS= read -r line; do + mod_dirs+=("$line") +done < <(find "${top_dir}" -type f -name 'go.mod' -exec dirname {} \; | sort) for mod_dir in "${mod_dirs[@]}"; do cd "${mod_dir}" - main_dirs=() - mapfile -t main_dirs < <(go list --find -f '{{.Name}}|{{.Dir}}' ./... | grep '^main|' | cut -f 2- -d '|') - for main_dir in "${main_dirs[@]}"; do - echo ".${main_dir#${p}}" - done + + while IFS= read -r line; do + echo ".${line#${p}}" + done < <(go list --find -f '{{.Name}}|{{.Dir}}' ./... | grep '^main|' | cut -f 2- -d '|') cd "${p}" done diff --git a/vendor/go.opentelemetry.io/otel/go.mod b/vendor/go.opentelemetry.io/otel/go.mod index dc10203c6..7c657d091 100644 --- a/vendor/go.opentelemetry.io/otel/go.mod +++ b/vendor/go.opentelemetry.io/otel/go.mod @@ -3,6 +3,53 @@ module go.opentelemetry.io/otel go 1.14 require ( - github.com/google/go-cmp v0.5.1 - github.com/stretchr/testify v1.6.1 + github.com/google/go-cmp v0.5.4 + github.com/stretchr/testify v1.7.0 + go.opentelemetry.io/otel/metric v0.18.0 + go.opentelemetry.io/otel/oteltest v0.18.0 + go.opentelemetry.io/otel/trace v0.18.0 ) + +replace go.opentelemetry.io/otel => ./ + +replace go.opentelemetry.io/otel/bridge/opencensus => ./bridge/opencensus + +replace go.opentelemetry.io/otel/bridge/opentracing => ./bridge/opentracing + +replace go.opentelemetry.io/otel/example/jaeger => ./example/jaeger + +replace go.opentelemetry.io/otel/example/namedtracer => ./example/namedtracer + +replace go.opentelemetry.io/otel/example/opencensus => ./example/opencensus + +replace go.opentelemetry.io/otel/example/otel-collector => ./example/otel-collector + +replace go.opentelemetry.io/otel/example/prom-collector => ./example/prom-collector + +replace go.opentelemetry.io/otel/example/prometheus => ./example/prometheus + +replace go.opentelemetry.io/otel/example/zipkin => ./example/zipkin + +replace go.opentelemetry.io/otel/exporters/metric/prometheus => ./exporters/metric/prometheus + +replace go.opentelemetry.io/otel/exporters/otlp => ./exporters/otlp + +replace go.opentelemetry.io/otel/exporters/stdout => ./exporters/stdout + +replace go.opentelemetry.io/otel/exporters/trace/jaeger => ./exporters/trace/jaeger + +replace go.opentelemetry.io/otel/exporters/trace/zipkin => ./exporters/trace/zipkin + +replace go.opentelemetry.io/otel/internal/tools => ./internal/tools + +replace go.opentelemetry.io/otel/sdk => ./sdk + +replace go.opentelemetry.io/otel/metric => ./metric + +replace go.opentelemetry.io/otel/oteltest => ./oteltest + +replace go.opentelemetry.io/otel/sdk/export/metric => ./sdk/export/metric + +replace go.opentelemetry.io/otel/sdk/metric => ./sdk/metric + +replace go.opentelemetry.io/otel/trace => ./trace diff --git a/vendor/go.opentelemetry.io/otel/go.sum b/vendor/go.opentelemetry.io/otel/go.sum index 741ca4ea2..99debc273 100644 --- a/vendor/go.opentelemetry.io/otel/go.sum +++ b/vendor/go.opentelemetry.io/otel/go.sum @@ -1,12 +1,12 @@ github.com/davecgh/go-spew v1.1.0 h1:ZDRjVQ15GmhC3fiQ8ni8+OwkZQO4DARzQgrnXU1Liz8= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/google/go-cmp v0.5.1 h1:JFrFEBb2xKufg6XkJsJr+WbKb4FQlURi5RUcBveYu9k= -github.com/google/go-cmp v0.5.1/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.5.4 h1:L8R9j+yAqZuZjsqh/z+F1NCffTKKLShY6zXTItVIZ8M= +github.com/google/go-cmp v0.5.4/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= -github.com/stretchr/testify v1.6.1 h1:hDPOHmpOpP40lSULcqw7IrRb/u7w6RpDC9399XyoNd0= -github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY= +github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543 h1:E7g+9GITq07hpfrRu66IVDexMakfv52eLZ2CXBWiKr4= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= diff --git a/vendor/go.opentelemetry.io/otel/api/global/handler.go b/vendor/go.opentelemetry.io/otel/handler.go similarity index 82% rename from vendor/go.opentelemetry.io/otel/api/global/handler.go rename to vendor/go.opentelemetry.io/otel/handler.go index 83f3e523a..27e1caa30 100644 --- a/vendor/go.opentelemetry.io/otel/api/global/handler.go +++ b/vendor/go.opentelemetry.io/otel/handler.go @@ -12,15 +12,13 @@ // See the License for the specific language governing permissions and // limitations under the License. -package global +package otel // import "go.opentelemetry.io/otel" import ( "log" "os" "sync" "sync/atomic" - - "go.opentelemetry.io/otel" ) var ( @@ -37,7 +35,7 @@ var ( delegateErrorHandlerOnce sync.Once // Comiple time check that loggingErrorHandler implements ErrorHandler. - _ otel.ErrorHandler = (*loggingErrorHandler)(nil) + _ ErrorHandler = (*loggingErrorHandler)(nil) ) // loggingErrorHandler logs all errors to STDERR. @@ -48,7 +46,7 @@ type loggingErrorHandler struct { } // setDelegate sets the ErrorHandler delegate if one is not already set. -func (h *loggingErrorHandler) setDelegate(d otel.ErrorHandler) { +func (h *loggingErrorHandler) setDelegate(d ErrorHandler) { if h.delegate.Load() != nil { // Delegate already registered return @@ -56,26 +54,26 @@ func (h *loggingErrorHandler) setDelegate(d otel.ErrorHandler) { h.delegate.Store(d) } -// Handle implements otel.ErrorHandler. +// Handle implements ErrorHandler. func (h *loggingErrorHandler) Handle(err error) { if d := h.delegate.Load(); d != nil { - d.(otel.ErrorHandler).Handle(err) + d.(ErrorHandler).Handle(err) return } h.l.Print(err) } -// ErrorHandler returns the global ErrorHandler instance. If no ErrorHandler +// GetErrorHandler returns the global ErrorHandler instance. If no ErrorHandler // instance has been set (`SetErrorHandler`), the default ErrorHandler which // logs errors to STDERR is returned. -func ErrorHandler() otel.ErrorHandler { +func GetErrorHandler() ErrorHandler { return globalErrorHandler } // SetErrorHandler sets the global ErrorHandler to be h. -func SetErrorHandler(h otel.ErrorHandler) { +func SetErrorHandler(h ErrorHandler) { delegateErrorHandlerOnce.Do(func() { - current := ErrorHandler() + current := GetErrorHandler() if current == h { return } @@ -87,5 +85,5 @@ func SetErrorHandler(h otel.ErrorHandler) { // Handle is a convience function for ErrorHandler().Handle(err) func Handle(err error) { - ErrorHandler().Handle(err) + GetErrorHandler().Handle(err) } diff --git a/vendor/go.opentelemetry.io/otel/api/correlation/context.go b/vendor/go.opentelemetry.io/otel/internal/baggage/baggage.go similarity index 55% rename from vendor/go.opentelemetry.io/otel/api/correlation/context.go rename to vendor/go.opentelemetry.io/otel/internal/baggage/baggage.go index ee3841984..b1f7daf8d 100644 --- a/vendor/go.opentelemetry.io/otel/api/correlation/context.go +++ b/vendor/go.opentelemetry.io/otel/internal/baggage/baggage.go @@ -12,14 +12,174 @@ // See the License for the specific language governing permissions and // limitations under the License. -package correlation +// Package baggage provides types and functions to manage W3C Baggage. +package baggage import ( "context" - "go.opentelemetry.io/otel/label" + "go.opentelemetry.io/otel/attribute" ) +type rawMap map[attribute.Key]attribute.Value +type keySet map[attribute.Key]struct{} + +// Map is an immutable storage for correlations. +type Map struct { + m rawMap +} + +// MapUpdate contains information about correlation changes to be +// made. +type MapUpdate struct { + // DropSingleK contains a single key to be dropped from + // correlations. Use this to avoid an overhead of a slice + // allocation if there is only one key to drop. + DropSingleK attribute.Key + // DropMultiK contains all the keys to be dropped from + // correlations. + DropMultiK []attribute.Key + + // SingleKV contains a single key-value pair to be added to + // correlations. Use this to avoid an overhead of a slice + // allocation if there is only one key-value pair to add. + SingleKV attribute.KeyValue + // MultiKV contains all the key-value pairs to be added to + // correlations. + MultiKV []attribute.KeyValue +} + +func newMap(raw rawMap) Map { + return Map{ + m: raw, + } +} + +// NewEmptyMap creates an empty correlations map. +func NewEmptyMap() Map { + return newMap(nil) +} + +// NewMap creates a map with the contents of the update applied. In +// this function, having an update with DropSingleK or DropMultiK +// makes no sense - those fields are effectively ignored. +func NewMap(update MapUpdate) Map { + return NewEmptyMap().Apply(update) +} + +// Apply creates a copy of the map with the contents of the update +// applied. Apply will first drop the keys from DropSingleK and +// DropMultiK, then add key-value pairs from SingleKV and MultiKV. +func (m Map) Apply(update MapUpdate) Map { + delSet, addSet := getModificationSets(update) + mapSize := getNewMapSize(m.m, delSet, addSet) + + r := make(rawMap, mapSize) + for k, v := range m.m { + // do not copy items we want to drop + if _, ok := delSet[k]; ok { + continue + } + // do not copy items we would overwrite + if _, ok := addSet[k]; ok { + continue + } + r[k] = v + } + if update.SingleKV.Key.Defined() { + r[update.SingleKV.Key] = update.SingleKV.Value + } + for _, kv := range update.MultiKV { + r[kv.Key] = kv.Value + } + if len(r) == 0 { + r = nil + } + return newMap(r) +} + +func getModificationSets(update MapUpdate) (delSet, addSet keySet) { + deletionsCount := len(update.DropMultiK) + if update.DropSingleK.Defined() { + deletionsCount++ + } + if deletionsCount > 0 { + delSet = make(map[attribute.Key]struct{}, deletionsCount) + for _, k := range update.DropMultiK { + delSet[k] = struct{}{} + } + if update.DropSingleK.Defined() { + delSet[update.DropSingleK] = struct{}{} + } + } + + additionsCount := len(update.MultiKV) + if update.SingleKV.Key.Defined() { + additionsCount++ + } + if additionsCount > 0 { + addSet = make(map[attribute.Key]struct{}, additionsCount) + for _, k := range update.MultiKV { + addSet[k.Key] = struct{}{} + } + if update.SingleKV.Key.Defined() { + addSet[update.SingleKV.Key] = struct{}{} + } + } + + return +} + +func getNewMapSize(m rawMap, delSet, addSet keySet) int { + mapSizeDiff := 0 + for k := range addSet { + if _, ok := m[k]; !ok { + mapSizeDiff++ + } + } + for k := range delSet { + if _, ok := m[k]; ok { + if _, inAddSet := addSet[k]; !inAddSet { + mapSizeDiff-- + } + } + } + return len(m) + mapSizeDiff +} + +// Value gets a value from correlations map and returns a boolean +// value indicating whether the key exist in the map. +func (m Map) Value(k attribute.Key) (attribute.Value, bool) { + value, ok := m.m[k] + return value, ok +} + +// HasValue returns a boolean value indicating whether the key exist +// in the map. +func (m Map) HasValue(k attribute.Key) bool { + _, has := m.Value(k) + return has +} + +// Len returns a length of the map. +func (m Map) Len() int { + return len(m.m) +} + +// Foreach calls a passed callback once on each key-value pair until +// all the key-value pairs of the map were iterated or the callback +// returns false, whichever happens first. +func (m Map) Foreach(f func(attribute.KeyValue) bool) { + for k, v := range m.m { + if !f(attribute.KeyValue{ + Key: k, + Value: v, + }) { + return + } + } +} + type correlationsType struct{} // SetHookFunc describes a type of a callback that is called when @@ -148,9 +308,15 @@ func ContextWithMap(ctx context.Context, m Map) context.Context { } } +// ContextWithNoCorrelationData returns a context stripped of correlation +// data. +func ContextWithNoCorrelationData(ctx context.Context) context.Context { + return context.WithValue(ctx, correlationsKey, nil) +} + // NewContext returns a context with the map from passed context // updated with the passed key-value pairs. -func NewContext(ctx context.Context, keyvalues ...label.KeyValue) context.Context { +func NewContext(ctx context.Context, keyvalues ...attribute.KeyValue) context.Context { return ContextWithMap(ctx, MapFromContext(ctx).Apply(MapUpdate{ MultiKV: keyvalues, })) diff --git a/vendor/go.opentelemetry.io/otel/api/global/internal/meter.go b/vendor/go.opentelemetry.io/otel/internal/global/meter.go similarity index 83% rename from vendor/go.opentelemetry.io/otel/api/global/internal/meter.go rename to vendor/go.opentelemetry.io/otel/internal/global/meter.go index ce3ed2099..36f9edeb8 100644 --- a/vendor/go.opentelemetry.io/otel/api/global/internal/meter.go +++ b/vendor/go.opentelemetry.io/otel/internal/global/meter.go @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -package internal +package global import ( "context" @@ -20,24 +20,25 @@ import ( "sync/atomic" "unsafe" - "go.opentelemetry.io/otel/api/metric" - "go.opentelemetry.io/otel/api/metric/registry" - "go.opentelemetry.io/otel/label" + "go.opentelemetry.io/otel/attribute" + "go.opentelemetry.io/otel/metric" + "go.opentelemetry.io/otel/metric/number" + "go.opentelemetry.io/otel/metric/registry" ) -// This file contains the forwarding implementation of metric.Provider -// used as the default global instance. Metric events using instruments -// provided by this implementation are no-ops until the first Meter -// implementation is set as the global provider. +// This file contains the forwarding implementation of MeterProvider used as +// the default global instance. Metric events using instruments provided by +// this implementation are no-ops until the first Meter implementation is set +// as the global provider. // -// The implementation here uses Mutexes to maintain a list of active -// Meters in the Provider and Instruments in each Meter, under the -// assumption that these interfaces are not performance-critical. +// The implementation here uses Mutexes to maintain a list of active Meters in +// the MeterProvider and Instruments in each Meter, under the assumption that +// these interfaces are not performance-critical. // -// We have the invariant that setDelegate() will be called before a -// new metric.Provider implementation is registered as the global -// provider. Mutexes in the Provider and Meters ensure that each -// instrument has a delegate before the global provider is set. +// We have the invariant that setDelegate() will be called before a new +// MeterProvider implementation is registered as the global provider. Mutexes +// in the MeterProvider and Meters ensure that each instrument has a delegate +// before the global provider is set. // // Bound instrument operations are implemented by delegating to the // instrument after it is registered, with a sync.Once initializer to @@ -51,7 +52,7 @@ type meterKey struct { } type meterProvider struct { - delegate metric.Provider + delegate metric.MeterProvider // lock protects `delegate` and `meters`. lock sync.Mutex @@ -105,15 +106,15 @@ type AsyncImpler interface { } type syncHandle struct { - delegate unsafe.Pointer // (*metric.HandleImpl) + delegate unsafe.Pointer // (*metric.BoundInstrumentImpl) inst *syncImpl - labels []label.KeyValue + labels []attribute.KeyValue initialize sync.Once } -var _ metric.Provider = &meterProvider{} +var _ metric.MeterProvider = &meterProvider{} var _ metric.MeterImpl = &meterImpl{} var _ metric.InstrumentImpl = &syncImpl{} var _ metric.BoundSyncImpl = &syncHandle{} @@ -123,7 +124,7 @@ func (inst *instrument) Descriptor() metric.Descriptor { return inst.descriptor } -// Provider interface and delegation +// MeterProvider interface and delegation func newMeterProvider() *meterProvider { return &meterProvider{ @@ -131,7 +132,7 @@ func newMeterProvider() *meterProvider { } } -func (p *meterProvider) setDelegate(provider metric.Provider) { +func (p *meterProvider) setDelegate(provider metric.MeterProvider) { p.lock.Lock() defer p.lock.Unlock() @@ -152,7 +153,7 @@ func (p *meterProvider) Meter(instrumentationName string, opts ...metric.MeterOp key := meterKey{ Name: instrumentationName, - Version: metric.ConfigureMeter(opts).InstrumentationVersion, + Version: metric.NewMeterConfig(opts...).InstrumentationVersion, } entry, ok := p.meters[key] if !ok { @@ -166,7 +167,7 @@ func (p *meterProvider) Meter(instrumentationName string, opts ...metric.MeterOp // Meter interface and delegation -func (m *meterImpl) setDelegate(name, version string, provider metric.Provider) { +func (m *meterImpl) setDelegate(name, version string, provider metric.MeterProvider) { m.lock.Lock() defer m.lock.Unlock() @@ -227,7 +228,7 @@ func (inst *syncImpl) Implementation() interface{} { return inst } -func (inst *syncImpl) Bind(labels []label.KeyValue) metric.BoundSyncImpl { +func (inst *syncImpl) Bind(labels []attribute.KeyValue) metric.BoundSyncImpl { if implPtr := (*metric.SyncImpl)(atomic.LoadPointer(&inst.delegate)); implPtr != nil { return (*implPtr).Bind(labels) } @@ -299,13 +300,13 @@ func (obs *asyncImpl) setDelegate(d metric.MeterImpl) { // Metric updates -func (m *meterImpl) RecordBatch(ctx context.Context, labels []label.KeyValue, measurements ...metric.Measurement) { +func (m *meterImpl) RecordBatch(ctx context.Context, labels []attribute.KeyValue, measurements ...metric.Measurement) { if delegatePtr := (*metric.MeterImpl)(atomic.LoadPointer(&m.delegate)); delegatePtr != nil { (*delegatePtr).RecordBatch(ctx, labels, measurements...) } } -func (inst *syncImpl) RecordOne(ctx context.Context, number metric.Number, labels []label.KeyValue) { +func (inst *syncImpl) RecordOne(ctx context.Context, number number.Number, labels []attribute.KeyValue) { if instPtr := (*metric.SyncImpl)(atomic.LoadPointer(&inst.delegate)); instPtr != nil { (*instPtr).RecordOne(ctx, number, labels) } @@ -313,7 +314,7 @@ func (inst *syncImpl) RecordOne(ctx context.Context, number metric.Number, label // Bound instrument initialization -func (bound *syncHandle) RecordOne(ctx context.Context, number metric.Number) { +func (bound *syncHandle) RecordOne(ctx context.Context, number number.Number) { instPtr := (*metric.SyncImpl)(atomic.LoadPointer(&bound.inst.delegate)) if instPtr == nil { return diff --git a/vendor/go.opentelemetry.io/otel/internal/global/propagator.go b/vendor/go.opentelemetry.io/otel/internal/global/propagator.go new file mode 100644 index 000000000..1c8b8589b --- /dev/null +++ b/vendor/go.opentelemetry.io/otel/internal/global/propagator.go @@ -0,0 +1,82 @@ +// 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 global + +import ( + "context" + "sync" + + "go.opentelemetry.io/otel/propagation" +) + +// textMapPropagator is a default TextMapPropagator that delegates calls to a +// registered delegate if one is set, otherwise it defaults to delegating the +// calls to a the default no-op propagation.TextMapPropagator. +type textMapPropagator struct { + mtx sync.Mutex + once sync.Once + delegate propagation.TextMapPropagator + noop propagation.TextMapPropagator +} + +// Compile-time guarantee that textMapPropagator implements the +// propagation.TextMapPropagator interface. +var _ propagation.TextMapPropagator = (*textMapPropagator)(nil) + +func newTextMapPropagator() *textMapPropagator { + return &textMapPropagator{ + noop: propagation.NewCompositeTextMapPropagator(), + } +} + +// SetDelegate sets a delegate propagation.TextMapPropagator that all calls are +// forwarded to. Delegation can only be performed once, all subsequent calls +// perform no delegation. +func (p *textMapPropagator) SetDelegate(delegate propagation.TextMapPropagator) { + if delegate == nil { + return + } + + p.mtx.Lock() + p.once.Do(func() { p.delegate = delegate }) + p.mtx.Unlock() +} + +// effectiveDelegate returns the current delegate of p if one is set, +// otherwise the default noop TextMapPropagator is returned. This method +// can be called concurrently. +func (p *textMapPropagator) effectiveDelegate() propagation.TextMapPropagator { + p.mtx.Lock() + defer p.mtx.Unlock() + if p.delegate != nil { + return p.delegate + } + return p.noop +} + +// Inject set cross-cutting concerns from the Context into the carrier. +func (p *textMapPropagator) Inject(ctx context.Context, carrier propagation.TextMapCarrier) { + p.effectiveDelegate().Inject(ctx, carrier) +} + +// Extract reads cross-cutting concerns from the carrier into a Context. +func (p *textMapPropagator) Extract(ctx context.Context, carrier propagation.TextMapCarrier) context.Context { + return p.effectiveDelegate().Extract(ctx, carrier) +} + +// Fields returns the keys whose values are set with Inject. +func (p *textMapPropagator) Fields() []string { + return p.effectiveDelegate().Fields() +} diff --git a/vendor/go.opentelemetry.io/otel/api/global/internal/state.go b/vendor/go.opentelemetry.io/otel/internal/global/state.go similarity index 50% rename from vendor/go.opentelemetry.io/otel/api/global/internal/state.go rename to vendor/go.opentelemetry.io/otel/internal/global/state.go index f965aa9cc..f3bf00351 100644 --- a/vendor/go.opentelemetry.io/otel/api/global/internal/state.go +++ b/vendor/go.opentelemetry.io/otel/internal/global/state.go @@ -12,29 +12,28 @@ // See the License for the specific language governing permissions and // limitations under the License. -package internal +package global import ( "sync" "sync/atomic" - "go.opentelemetry.io/otel/api/correlation" - "go.opentelemetry.io/otel/api/metric" - "go.opentelemetry.io/otel/api/propagation" - "go.opentelemetry.io/otel/api/trace" + "go.opentelemetry.io/otel/metric" + "go.opentelemetry.io/otel/propagation" + "go.opentelemetry.io/otel/trace" ) type ( - traceProviderHolder struct { - tp trace.Provider + tracerProviderHolder struct { + tp trace.TracerProvider } meterProviderHolder struct { - mp metric.Provider + mp metric.MeterProvider } propagatorsHolder struct { - pr propagation.Propagators + tm propagation.TextMapPropagator } ) @@ -43,39 +42,40 @@ var ( globalMeter = defaultMeterValue() globalPropagators = defaultPropagatorsValue() - delegateMeterOnce sync.Once - delegateTraceOnce sync.Once + delegateMeterOnce sync.Once + delegateTraceOnce sync.Once + delegateTextMapPropagatorOnce sync.Once ) -// TraceProvider is the internal implementation for global.TraceProvider. -func TraceProvider() trace.Provider { - return globalTracer.Load().(traceProviderHolder).tp +// TracerProvider is the internal implementation for global.TracerProvider. +func TracerProvider() trace.TracerProvider { + return globalTracer.Load().(tracerProviderHolder).tp } -// SetTraceProvider is the internal implementation for global.SetTraceProvider. -func SetTraceProvider(tp trace.Provider) { +// SetTracerProvider is the internal implementation for global.SetTracerProvider. +func SetTracerProvider(tp trace.TracerProvider) { delegateTraceOnce.Do(func() { - current := TraceProvider() + current := TracerProvider() if current == tp { // Setting the provider to the prior default is nonsense, panic. // Panic is acceptable because we are likely still early in the // process lifetime. - panic("invalid Provider, the global instance cannot be reinstalled") - } else if def, ok := current.(*traceProvider); ok { + panic("invalid TracerProvider, the global instance cannot be reinstalled") + } else if def, ok := current.(*tracerProvider); ok { def.setDelegate(tp) } }) - globalTracer.Store(traceProviderHolder{tp: tp}) + globalTracer.Store(tracerProviderHolder{tp: tp}) } // MeterProvider is the internal implementation for global.MeterProvider. -func MeterProvider() metric.Provider { +func MeterProvider() metric.MeterProvider { return globalMeter.Load().(meterProviderHolder).mp } // SetMeterProvider is the internal implementation for global.SetMeterProvider. -func SetMeterProvider(mp metric.Provider) { +func SetMeterProvider(mp metric.MeterProvider) { delegateMeterOnce.Do(func() { current := MeterProvider() @@ -83,7 +83,7 @@ func SetMeterProvider(mp metric.Provider) { // Setting the provider to the prior default is nonsense, panic. // Panic is acceptable because we are likely still early in the // process lifetime. - panic("invalid Provider, the global instance cannot be reinstalled") + panic("invalid MeterProvider, the global instance cannot be reinstalled") } else if def, ok := current.(*meterProvider); ok { def.setDelegate(mp) } @@ -91,19 +91,32 @@ func SetMeterProvider(mp metric.Provider) { globalMeter.Store(meterProviderHolder{mp: mp}) } -// Propagators is the internal implementation for global.Propagators. -func Propagators() propagation.Propagators { - return globalPropagators.Load().(propagatorsHolder).pr +// TextMapPropagator is the internal implementation for global.TextMapPropagator. +func TextMapPropagator() propagation.TextMapPropagator { + return globalPropagators.Load().(propagatorsHolder).tm } -// SetPropagators is the internal implementation for global.SetPropagators. -func SetPropagators(pr propagation.Propagators) { - globalPropagators.Store(propagatorsHolder{pr: pr}) +// SetTextMapPropagator is the internal implementation for global.SetTextMapPropagator. +func SetTextMapPropagator(p propagation.TextMapPropagator) { + // For the textMapPropagator already returned by TextMapPropagator + // delegate to p. + delegateTextMapPropagatorOnce.Do(func() { + if current := TextMapPropagator(); current == p { + // Setting the provider to the prior default is nonsense, panic. + // Panic is acceptable because we are likely still early in the + // process lifetime. + panic("invalid TextMapPropagator, the global instance cannot be reinstalled") + } else if def, ok := current.(*textMapPropagator); ok { + def.SetDelegate(p) + } + }) + // Return p when subsequent calls to TextMapPropagator are made. + globalPropagators.Store(propagatorsHolder{tm: p}) } func defaultTracerValue() *atomic.Value { v := &atomic.Value{} - v.Store(traceProviderHolder{tp: &traceProvider{}}) + v.Store(tracerProviderHolder{tp: &tracerProvider{}}) return v } @@ -115,21 +128,10 @@ func defaultMeterValue() *atomic.Value { func defaultPropagatorsValue() *atomic.Value { v := &atomic.Value{} - v.Store(propagatorsHolder{pr: getDefaultPropagators()}) + v.Store(propagatorsHolder{tm: newTextMapPropagator()}) return v } -// getDefaultPropagators returns a default Propagators, configured -// with W3C trace and correlation context propagation. -func getDefaultPropagators() propagation.Propagators { - tcPropagator := trace.TraceContext{} - ccPropagator := correlation.CorrelationContext{} - return propagation.New( - propagation.WithExtractors(tcPropagator, ccPropagator), - propagation.WithInjectors(tcPropagator, ccPropagator), - ) -} - // ResetForTest restores the initial global state, for testing purposes. func ResetForTest() { globalTracer = defaultTracerValue() @@ -137,4 +139,5 @@ func ResetForTest() { globalPropagators = defaultPropagatorsValue() delegateMeterOnce = sync.Once{} delegateTraceOnce = sync.Once{} + delegateTextMapPropagatorOnce = sync.Once{} } diff --git a/vendor/go.opentelemetry.io/otel/api/global/internal/trace.go b/vendor/go.opentelemetry.io/otel/internal/global/trace.go similarity index 67% rename from vendor/go.opentelemetry.io/otel/api/global/internal/trace.go rename to vendor/go.opentelemetry.io/otel/internal/global/trace.go index 69024b667..7b6993153 100644 --- a/vendor/go.opentelemetry.io/otel/api/global/internal/trace.go +++ b/vendor/go.opentelemetry.io/otel/internal/global/trace.go @@ -12,18 +12,18 @@ // See the License for the specific language governing permissions and // limitations under the License. -package internal +package global /* -This file contains the forwarding implementation of the trace.Provider used as +This file contains the forwarding implementation of the TracerProvider used as the default global instance. Prior to initialization of an SDK, Tracers -returned by the global Provider will provide no-op functionality. This means -that all Span created prior to initialization are no-op Spans. +returned by the global TracerProvider will provide no-op functionality. This +means that all Span created prior to initialization are no-op Spans. Once an SDK has been initialized, all provided no-op Tracers are swapped for -Tracers provided by the SDK defined Provider. However, any Span started prior -to this initialization does not change its behavior. Meaning, the Span remains -a no-op Span. +Tracers provided by the SDK defined TracerProvider. However, any Span started +prior to this initialization does not change its behavior. Meaning, the Span +remains a no-op Span. The implementation to track and swap Tracers locks all new Tracer creation until the swap is complete. This assumes that this operation is not @@ -35,30 +35,34 @@ import ( "context" "sync" - "go.opentelemetry.io/otel/api/trace" + "go.opentelemetry.io/otel/internal/trace/noop" + "go.opentelemetry.io/otel/trace" ) -// traceProvider is a placeholder for a configured SDK Provider. +// tracerProvider is a placeholder for a configured SDK TracerProvider. // -// All Provider functionality is forwarded to a delegate once configured. -type traceProvider struct { +// All TracerProvider functionality is forwarded to a delegate once +// configured. +type tracerProvider struct { mtx sync.Mutex tracers []*tracer - delegate trace.Provider + delegate trace.TracerProvider } -// Compile-time guarantee that traceProvider implements the trace.Provider interface. -var _ trace.Provider = &traceProvider{} +// Compile-time guarantee that tracerProvider implements the TracerProvider +// interface. +var _ trace.TracerProvider = &tracerProvider{} -// setDelegate configures p to delegate all Provider functionality to provider. +// setDelegate configures p to delegate all TracerProvider functionality to +// provider. // // All Tracers provided prior to this function call are switched out to be // Tracers provided by provider. // // Delegation only happens on the first call to this method. All subsequent // calls result in no delegation changes. -func (p *traceProvider) setDelegate(provider trace.Provider) { +func (p *tracerProvider) setDelegate(provider trace.TracerProvider) { if p.delegate != nil { return } @@ -74,13 +78,13 @@ func (p *traceProvider) setDelegate(provider trace.Provider) { p.tracers = nil } -// Tracer implements trace.Provider. -func (p *traceProvider) Tracer(name string, opts ...trace.TracerOption) trace.Tracer { +// Tracer implements TracerProvider. +func (p *tracerProvider) Tracer(name string, opts ...trace.TracerOption) trace.Tracer { p.mtx.Lock() defer p.mtx.Unlock() if p.delegate != nil { - return p.delegate.Tracer(name) + return p.delegate.Tracer(name, opts...) } t := &tracer{name: name, opts: opts} @@ -110,15 +114,15 @@ var _ trace.Tracer = &tracer{} // // Delegation only happens on the first call to this method. All subsequent // calls result in no delegation changes. -func (t *tracer) setDelegate(provider trace.Provider) { +func (t *tracer) setDelegate(provider trace.TracerProvider) { t.once.Do(func() { t.delegate = provider.Tracer(t.name, t.opts...) }) } // Start implements trace.Tracer by forwarding the call to t.delegate if // set, otherwise it forwards the call to a NoopTracer. -func (t *tracer) Start(ctx context.Context, name string, opts ...trace.StartOption) (context.Context, trace.Span) { +func (t *tracer) Start(ctx context.Context, name string, opts ...trace.SpanOption) (context.Context, trace.Span) { if t.delegate != nil { return t.delegate.Start(ctx, name, opts...) } - return trace.NoopTracer{}.Start(ctx, name, opts...) + return noop.Tracer.Start(ctx, name, opts...) } diff --git a/vendor/go.opentelemetry.io/otel/internal/rawhelpers.go b/vendor/go.opentelemetry.io/otel/internal/rawhelpers.go index dae825ed8..0d806b1c8 100644 --- a/vendor/go.opentelemetry.io/otel/internal/rawhelpers.go +++ b/vendor/go.opentelemetry.io/otel/internal/rawhelpers.go @@ -38,14 +38,6 @@ func RawToInt64(r uint64) int64 { return int64(r) } -func Uint64ToRaw(u uint64) uint64 { - return u -} - -func RawToUint64(r uint64) uint64 { - return r -} - func Float64ToRaw(f float64) uint64 { return math.Float64bits(f) } @@ -54,30 +46,6 @@ func RawToFloat64(r uint64) float64 { return math.Float64frombits(r) } -func Int32ToRaw(i int32) uint64 { - return uint64(i) -} - -func RawToInt32(r uint64) int32 { - return int32(r) -} - -func Uint32ToRaw(u uint32) uint64 { - return uint64(u) -} - -func RawToUint32(r uint64) uint32 { - return uint32(r) -} - -func Float32ToRaw(f float32) uint64 { - return Uint32ToRaw(math.Float32bits(f)) -} - -func RawToFloat32(r uint64) float32 { - return math.Float32frombits(RawToUint32(r)) -} - func RawPtrToFloat64Ptr(r *uint64) *float64 { return (*float64)(unsafe.Pointer(r)) } @@ -85,7 +53,3 @@ func RawPtrToFloat64Ptr(r *uint64) *float64 { func RawPtrToInt64Ptr(r *uint64) *int64 { return (*int64)(unsafe.Pointer(r)) } - -func RawPtrToUint64Ptr(r *uint64) *uint64 { - return r -} diff --git a/vendor/go.opentelemetry.io/otel/api/trace/noop_trace.go b/vendor/go.opentelemetry.io/otel/internal/trace/noop/noop.go similarity index 63% rename from vendor/go.opentelemetry.io/otel/api/trace/noop_trace.go rename to vendor/go.opentelemetry.io/otel/internal/trace/noop/noop.go index ffdb91318..765c21a28 100644 --- a/vendor/go.opentelemetry.io/otel/api/trace/noop_trace.go +++ b/vendor/go.opentelemetry.io/otel/internal/trace/noop/noop.go @@ -12,18 +12,24 @@ // See the License for the specific language governing permissions and // limitations under the License. -package trace +// Package noop provides noop tracing implementations for tracer and span. +package noop import ( "context" + + "go.opentelemetry.io/otel/trace" ) -type NoopTracer struct{} +var ( + // Tracer is a noop tracer that starts noop spans. + Tracer trace.Tracer -var _ Tracer = NoopTracer{} + // Span is a noop Span. + Span trace.Span +) -// Start starts a noop span. -func (NoopTracer) Start(ctx context.Context, name string, opts ...StartOption) (context.Context, Span) { - span := NoopSpan{} - return ContextWithSpan(ctx, span), span +func init() { + Tracer = trace.NewNoopTracerProvider().Tracer("") + _, Span = Tracer.Start(context.Background(), "") } diff --git a/vendor/go.opentelemetry.io/otel/metric/LICENSE b/vendor/go.opentelemetry.io/otel/metric/LICENSE new file mode 100644 index 000000000..261eeb9e9 --- /dev/null +++ b/vendor/go.opentelemetry.io/otel/metric/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/otel/api/metric/config.go b/vendor/go.opentelemetry.io/otel/metric/config.go similarity index 80% rename from vendor/go.opentelemetry.io/otel/api/metric/config.go rename to vendor/go.opentelemetry.io/otel/metric/config.go index b5d45f9ae..02f0ff8e0 100644 --- a/vendor/go.opentelemetry.io/otel/api/metric/config.go +++ b/vendor/go.opentelemetry.io/otel/metric/config.go @@ -12,11 +12,13 @@ // See the License for the specific language governing permissions and // limitations under the License. -package metric +package metric // import "go.opentelemetry.io/otel/metric" -import "go.opentelemetry.io/otel/api/unit" +import ( + "go.opentelemetry.io/otel/unit" +) -// InstrumentConfig contains options for instrument descriptors. +// InstrumentConfig contains options for metric instrument descriptors. type InstrumentConfig struct { // Description describes the instrument in human-readable terms. Description string @@ -30,16 +32,16 @@ type InstrumentConfig struct { InstrumentationVersion string } -// InstrumentOption is an interface for applying instrument options. +// InstrumentOption is an interface for applying metric instrument options. type InstrumentOption interface { // ApplyMeter is used to set a InstrumentOption value of a // InstrumentConfig. ApplyInstrument(*InstrumentConfig) } -// ConfigureInstrument is a helper that applies all the InstrumentOptions -// to an InstrumentConfig. -func ConfigureInstrument(opts []InstrumentOption) InstrumentConfig { +// NewInstrumentConfig creates a new InstrumentConfig +// and applies all the given options. +func NewInstrumentConfig(opts ...InstrumentOption) InstrumentConfig { var config InstrumentConfig for _, o := range opts { o.ApplyInstrument(&config) @@ -93,9 +95,9 @@ type MeterOption interface { ApplyMeter(*MeterConfig) } -// ConfigureMeter is a helper that applies all the MeterOptions to a -// MeterConfig. -func ConfigureMeter(opts []MeterOption) MeterConfig { +// NewMeterConfig creates a new MeterConfig and applies +// all the given options. +func NewMeterConfig(opts ...MeterOption) MeterConfig { var config MeterConfig for _, o := range opts { o.ApplyMeter(&config) @@ -103,14 +105,15 @@ func ConfigureMeter(opts []MeterOption) MeterConfig { return config } -// Option is an interface for applying Instrument or Meter options. -type Option interface { +// InstrumentationOption is an interface for applying instrumentation specific +// options. +type InstrumentationOption interface { InstrumentOption MeterOption } // WithInstrumentationVersion sets the instrumentation version. -func WithInstrumentationVersion(version string) Option { +func WithInstrumentationVersion(version string) InstrumentationOption { return instrumentationVersionOption(version) } diff --git a/vendor/go.opentelemetry.io/otel/metric/doc.go b/vendor/go.opentelemetry.io/otel/metric/doc.go new file mode 100644 index 000000000..7889ff000 --- /dev/null +++ b/vendor/go.opentelemetry.io/otel/metric/doc.go @@ -0,0 +1,67 @@ +// 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 metric provides an implementation of the metrics part of the +OpenTelemetry API. + +This package is currently in a pre-GA phase. Backwards incompatible changes +may be introduced in subsequent minor version releases as we work to track the +evolving OpenTelemetry specification and user feedback. + +Measurements can be made about an operation being performed or the state of a +system in general. These measurements can be crucial to the reliable operation +of code and provide valuable insights about the inner workings of a system. + +Measurements are made using instruments provided by this package. The type of +instrument used will depend on the type of measurement being made and of what +part of a system is being measured. + +Instruments are categorized as Synchronous or Asynchronous and independently +as Adding or Grouping. Synchronous instruments are called by the user with a +Context. Asynchronous instruments are called by the SDK during collection. +Additive instruments are semantically intended for capturing a sum. Grouping +instruments are intended for capturing a distribution. + +Additive instruments may be monotonic, in which case they are non-decreasing +and naturally define a rate. + +The synchronous instrument names are: + + Counter: additive, monotonic + UpDownCounter: additive + ValueRecorder: grouping + +and the asynchronous instruments are: + + SumObserver: additive, monotonic + UpDownSumObserver: additive + ValueObserver: grouping + +All instruments are provided with support for either float64 or int64 input +values. + +An instrument is created using a Meter. Additionally, a Meter is used to +record batches of synchronous measurements or asynchronous observations. A +Meter is obtained using a MeterProvider. A Meter, like a Tracer, is unique to +the instrumentation it instruments and must be named and versioned when +created with a MeterProvider with the name and version of the instrumentation +library. + +Instrumentation should be designed to accept a MeterProvider from which it can +create its own unique Meter. Alternatively, the registered global +MeterProvider from the go.opentelemetry.io/otel package can be used as a +default. +*/ +package metric // import "go.opentelemetry.io/otel/metric" diff --git a/vendor/go.opentelemetry.io/otel/api/global/metric.go b/vendor/go.opentelemetry.io/otel/metric/global/metric.go similarity index 74% rename from vendor/go.opentelemetry.io/otel/api/global/metric.go rename to vendor/go.opentelemetry.io/otel/metric/global/metric.go index 04409c46e..8d16d34d4 100644 --- a/vendor/go.opentelemetry.io/otel/api/global/metric.go +++ b/vendor/go.opentelemetry.io/otel/metric/global/metric.go @@ -12,15 +12,15 @@ // See the License for the specific language governing permissions and // limitations under the License. -package global +package global // import "go.opentelemetry.io/otel/metric/global" import ( - "go.opentelemetry.io/otel/api/global/internal" - "go.opentelemetry.io/otel/api/metric" + "go.opentelemetry.io/otel/internal/global" + "go.opentelemetry.io/otel/metric" ) // Meter creates an implementation of the Meter interface from the global -// Provider. The instrumentationName must be the name of the library +// MeterProvider. The instrumentationName must be the name of the library // providing instrumentation. This name may be the same as the instrumented // code only if that code provides built-in instrumentation. If the // instrumentationName is empty, then a implementation defined default name @@ -28,10 +28,10 @@ import ( // // This is short for MeterProvider().Meter(name) func Meter(instrumentationName string, opts ...metric.MeterOption) metric.Meter { - return MeterProvider().Meter(instrumentationName, opts...) + return GetMeterProvider().Meter(instrumentationName, opts...) } -// MeterProvider returns the registered global meter provider. If +// GetMeterProvider returns the registered global meter provider. If // none is registered then a default meter provider is returned that // forwards the Meter interface to the first registered Meter. // @@ -39,11 +39,11 @@ func Meter(instrumentationName string, opts ...metric.MeterOption) metric.Meter // meter := global.MeterProvider().Meter("example.com/foo") // or // meter := global.Meter("example.com/foo") -func MeterProvider() metric.Provider { - return internal.MeterProvider() +func GetMeterProvider() metric.MeterProvider { + return global.MeterProvider() } // SetMeterProvider registers `mp` as the global meter provider. -func SetMeterProvider(mp metric.Provider) { - internal.SetMeterProvider(mp) +func SetMeterProvider(mp metric.MeterProvider) { + global.SetMeterProvider(mp) } diff --git a/vendor/go.opentelemetry.io/otel/metric/go.mod b/vendor/go.opentelemetry.io/otel/metric/go.mod new file mode 100644 index 000000000..c91e82fc8 --- /dev/null +++ b/vendor/go.opentelemetry.io/otel/metric/go.mod @@ -0,0 +1,54 @@ +module go.opentelemetry.io/otel/metric + +go 1.14 + +replace go.opentelemetry.io/otel => ../ + +replace go.opentelemetry.io/otel/bridge/opencensus => ../bridge/opencensus + +replace go.opentelemetry.io/otel/bridge/opentracing => ../bridge/opentracing + +replace go.opentelemetry.io/otel/example/jaeger => ../example/jaeger + +replace go.opentelemetry.io/otel/example/namedtracer => ../example/namedtracer + +replace go.opentelemetry.io/otel/example/opencensus => ../example/opencensus + +replace go.opentelemetry.io/otel/example/otel-collector => ../example/otel-collector + +replace go.opentelemetry.io/otel/example/prom-collector => ../example/prom-collector + +replace go.opentelemetry.io/otel/example/prometheus => ../example/prometheus + +replace go.opentelemetry.io/otel/example/zipkin => ../example/zipkin + +replace go.opentelemetry.io/otel/exporters/metric/prometheus => ../exporters/metric/prometheus + +replace go.opentelemetry.io/otel/exporters/otlp => ../exporters/otlp + +replace go.opentelemetry.io/otel/exporters/stdout => ../exporters/stdout + +replace go.opentelemetry.io/otel/exporters/trace/jaeger => ../exporters/trace/jaeger + +replace go.opentelemetry.io/otel/exporters/trace/zipkin => ../exporters/trace/zipkin + +replace go.opentelemetry.io/otel/internal/tools => ../internal/tools + +replace go.opentelemetry.io/otel/metric => ./ + +replace go.opentelemetry.io/otel/oteltest => ../oteltest + +replace go.opentelemetry.io/otel/sdk => ../sdk + +replace go.opentelemetry.io/otel/sdk/export/metric => ../sdk/export/metric + +replace go.opentelemetry.io/otel/sdk/metric => ../sdk/metric + +replace go.opentelemetry.io/otel/trace => ../trace + +require ( + github.com/google/go-cmp v0.5.4 + github.com/stretchr/testify v1.7.0 + go.opentelemetry.io/otel v0.18.0 + go.opentelemetry.io/otel/oteltest v0.18.0 +) diff --git a/vendor/go.opentelemetry.io/otel/metric/go.sum b/vendor/go.opentelemetry.io/otel/metric/go.sum new file mode 100644 index 000000000..99debc273 --- /dev/null +++ b/vendor/go.opentelemetry.io/otel/metric/go.sum @@ -0,0 +1,15 @@ +github.com/davecgh/go-spew v1.1.0 h1:ZDRjVQ15GmhC3fiQ8ni8+OwkZQO4DARzQgrnXU1Liz8= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/google/go-cmp v0.5.4 h1:L8R9j+yAqZuZjsqh/z+F1NCffTKKLShY6zXTItVIZ8M= +github.com/google/go-cmp v0.5.4/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY= +github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543 h1:E7g+9GITq07hpfrRu66IVDexMakfv52eLZ2CXBWiKr4= +golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c h1:dUUwHk2QECo/6vqA44rthZ8ie2QXMNeKRTHCNY2nXvo= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/vendor/go.opentelemetry.io/otel/metric/instrumentkind_string.go b/vendor/go.opentelemetry.io/otel/metric/instrumentkind_string.go new file mode 100644 index 000000000..2805e2250 --- /dev/null +++ b/vendor/go.opentelemetry.io/otel/metric/instrumentkind_string.go @@ -0,0 +1,28 @@ +// Code generated by "stringer -type=InstrumentKind"; DO NOT EDIT. + +package metric + +import "strconv" + +func _() { + // An "invalid array index" compiler error signifies that the constant values have changed. + // Re-run the stringer command to generate them again. + var x [1]struct{} + _ = x[ValueRecorderInstrumentKind-0] + _ = x[ValueObserverInstrumentKind-1] + _ = x[CounterInstrumentKind-2] + _ = x[UpDownCounterInstrumentKind-3] + _ = x[SumObserverInstrumentKind-4] + _ = x[UpDownSumObserverInstrumentKind-5] +} + +const _InstrumentKind_name = "ValueRecorderInstrumentKindValueObserverInstrumentKindCounterInstrumentKindUpDownCounterInstrumentKindSumObserverInstrumentKindUpDownSumObserverInstrumentKind" + +var _InstrumentKind_index = [...]uint8{0, 27, 54, 75, 102, 127, 158} + +func (i InstrumentKind) String() string { + if i < 0 || i >= InstrumentKind(len(_InstrumentKind_index)-1) { + return "InstrumentKind(" + strconv.FormatInt(int64(i), 10) + ")" + } + return _InstrumentKind_name[_InstrumentKind_index[i]:_InstrumentKind_index[i+1]] +} diff --git a/vendor/go.opentelemetry.io/otel/api/metric/meter.go b/vendor/go.opentelemetry.io/otel/metric/metric.go similarity index 50% rename from vendor/go.opentelemetry.io/otel/api/metric/meter.go rename to vendor/go.opentelemetry.io/otel/metric/metric.go index 079c29477..b591985df 100644 --- a/vendor/go.opentelemetry.io/otel/api/metric/meter.go +++ b/vendor/go.opentelemetry.io/otel/metric/metric.go @@ -12,27 +12,18 @@ // See the License for the specific language governing permissions and // limitations under the License. -package metric +package metric // import "go.opentelemetry.io/otel/metric" import ( "context" - "go.opentelemetry.io/otel/label" + "go.opentelemetry.io/otel/attribute" + "go.opentelemetry.io/otel/metric/number" + "go.opentelemetry.io/otel/unit" ) -// The file is organized as follows: -// -// - Provider interface -// - Meter struct -// - RecordBatch -// - BatchObserver -// - Synchronous instrument constructors (2 x int64,float64) -// - Asynchronous instrument constructors (1 x int64,float64) -// - Batch asynchronous constructors (1 x int64,float64) -// - Internals - -// Provider supports named Meter instances. -type Provider interface { +// MeterProvider supports named Meter instances. +type MeterProvider interface { // Meter creates an implementation of the Meter interface. // The instrumentationName must be the name of the library providing // instrumentation. This name may be the same as the instrumented code @@ -42,8 +33,7 @@ type Provider interface { Meter(instrumentationName string, opts ...MeterOption) Meter } -// Meter is the OpenTelemetry metric API, based on a `MeterImpl` -// implementation and the `Meter` library name. +// Meter is the creator of metric instruments. // // An uninitialized Meter is a no-op implementation. type Meter struct { @@ -52,7 +42,7 @@ type Meter struct { } // RecordBatch atomically records a batch of measurements. -func (m Meter) RecordBatch(ctx context.Context, ls []label.KeyValue, ms ...Measurement) { +func (m Meter) RecordBatch(ctx context.Context, ls []attribute.KeyValue, ms ...Measurement) { if m.impl == nil { return } @@ -74,7 +64,7 @@ func (m Meter) NewBatchObserver(callback BatchObserverFunc) BatchObserver { // duplicate registration). func (m Meter) NewInt64Counter(name string, options ...InstrumentOption) (Int64Counter, error) { return wrapInt64CounterInstrument( - m.newSync(name, CounterKind, Int64NumberKind, options)) + m.newSync(name, CounterInstrumentKind, number.Int64Kind, options)) } // NewFloat64Counter creates a new floating point Counter with the @@ -83,7 +73,7 @@ func (m Meter) NewInt64Counter(name string, options ...InstrumentOption) (Int64C // duplicate registration). func (m Meter) NewFloat64Counter(name string, options ...InstrumentOption) (Float64Counter, error) { return wrapFloat64CounterInstrument( - m.newSync(name, CounterKind, Float64NumberKind, options)) + m.newSync(name, CounterInstrumentKind, number.Float64Kind, options)) } // NewInt64UpDownCounter creates a new integer UpDownCounter instrument with the @@ -92,7 +82,7 @@ func (m Meter) NewFloat64Counter(name string, options ...InstrumentOption) (Floa // duplicate registration). func (m Meter) NewInt64UpDownCounter(name string, options ...InstrumentOption) (Int64UpDownCounter, error) { return wrapInt64UpDownCounterInstrument( - m.newSync(name, UpDownCounterKind, Int64NumberKind, options)) + m.newSync(name, UpDownCounterInstrumentKind, number.Int64Kind, options)) } // NewFloat64UpDownCounter creates a new floating point UpDownCounter with the @@ -101,7 +91,7 @@ func (m Meter) NewInt64UpDownCounter(name string, options ...InstrumentOption) ( // duplicate registration). func (m Meter) NewFloat64UpDownCounter(name string, options ...InstrumentOption) (Float64UpDownCounter, error) { return wrapFloat64UpDownCounterInstrument( - m.newSync(name, UpDownCounterKind, Float64NumberKind, options)) + m.newSync(name, UpDownCounterInstrumentKind, number.Float64Kind, options)) } // NewInt64ValueRecorder creates a new integer ValueRecorder instrument with the @@ -110,7 +100,7 @@ func (m Meter) NewFloat64UpDownCounter(name string, options ...InstrumentOption) // duplicate registration). func (m Meter) NewInt64ValueRecorder(name string, opts ...InstrumentOption) (Int64ValueRecorder, error) { return wrapInt64ValueRecorderInstrument( - m.newSync(name, ValueRecorderKind, Int64NumberKind, opts)) + m.newSync(name, ValueRecorderInstrumentKind, number.Int64Kind, opts)) } // NewFloat64ValueRecorder creates a new floating point ValueRecorder with the @@ -119,7 +109,7 @@ func (m Meter) NewInt64ValueRecorder(name string, opts ...InstrumentOption) (Int // duplicate registration). func (m Meter) NewFloat64ValueRecorder(name string, opts ...InstrumentOption) (Float64ValueRecorder, error) { return wrapFloat64ValueRecorderInstrument( - m.newSync(name, ValueRecorderKind, Float64NumberKind, opts)) + m.newSync(name, ValueRecorderInstrumentKind, number.Float64Kind, opts)) } // NewInt64ValueObserver creates a new integer ValueObserver instrument @@ -131,7 +121,7 @@ func (m Meter) NewInt64ValueObserver(name string, callback Int64ObserverFunc, op return wrapInt64ValueObserverInstrument(NoopAsync{}, nil) } return wrapInt64ValueObserverInstrument( - m.newAsync(name, ValueObserverKind, Int64NumberKind, opts, + m.newAsync(name, ValueObserverInstrumentKind, number.Int64Kind, opts, newInt64AsyncRunner(callback))) } @@ -144,7 +134,7 @@ func (m Meter) NewFloat64ValueObserver(name string, callback Float64ObserverFunc return wrapFloat64ValueObserverInstrument(NoopAsync{}, nil) } return wrapFloat64ValueObserverInstrument( - m.newAsync(name, ValueObserverKind, Float64NumberKind, opts, + m.newAsync(name, ValueObserverInstrumentKind, number.Float64Kind, opts, newFloat64AsyncRunner(callback))) } @@ -157,7 +147,7 @@ func (m Meter) NewInt64SumObserver(name string, callback Int64ObserverFunc, opts return wrapInt64SumObserverInstrument(NoopAsync{}, nil) } return wrapInt64SumObserverInstrument( - m.newAsync(name, SumObserverKind, Int64NumberKind, opts, + m.newAsync(name, SumObserverInstrumentKind, number.Int64Kind, opts, newInt64AsyncRunner(callback))) } @@ -170,7 +160,7 @@ func (m Meter) NewFloat64SumObserver(name string, callback Float64ObserverFunc, return wrapFloat64SumObserverInstrument(NoopAsync{}, nil) } return wrapFloat64SumObserverInstrument( - m.newAsync(name, SumObserverKind, Float64NumberKind, opts, + m.newAsync(name, SumObserverInstrumentKind, number.Float64Kind, opts, newFloat64AsyncRunner(callback))) } @@ -183,7 +173,7 @@ func (m Meter) NewInt64UpDownSumObserver(name string, callback Int64ObserverFunc return wrapInt64UpDownSumObserverInstrument(NoopAsync{}, nil) } return wrapInt64UpDownSumObserverInstrument( - m.newAsync(name, UpDownSumObserverKind, Int64NumberKind, opts, + m.newAsync(name, UpDownSumObserverInstrumentKind, number.Int64Kind, opts, newInt64AsyncRunner(callback))) } @@ -196,7 +186,7 @@ func (m Meter) NewFloat64UpDownSumObserver(name string, callback Float64Observer return wrapFloat64UpDownSumObserverInstrument(NoopAsync{}, nil) } return wrapFloat64UpDownSumObserverInstrument( - m.newAsync(name, UpDownSumObserverKind, Float64NumberKind, opts, + m.newAsync(name, UpDownSumObserverInstrumentKind, number.Float64Kind, opts, newFloat64AsyncRunner(callback))) } @@ -209,7 +199,7 @@ func (b BatchObserver) NewInt64ValueObserver(name string, opts ...InstrumentOpti return wrapInt64ValueObserverInstrument(NoopAsync{}, nil) } return wrapInt64ValueObserverInstrument( - b.meter.newAsync(name, ValueObserverKind, Int64NumberKind, opts, b.runner)) + b.meter.newAsync(name, ValueObserverInstrumentKind, number.Int64Kind, opts, b.runner)) } // NewFloat64ValueObserver creates a new floating point ValueObserver with @@ -221,7 +211,7 @@ func (b BatchObserver) NewFloat64ValueObserver(name string, opts ...InstrumentOp return wrapFloat64ValueObserverInstrument(NoopAsync{}, nil) } return wrapFloat64ValueObserverInstrument( - b.meter.newAsync(name, ValueObserverKind, Float64NumberKind, opts, + b.meter.newAsync(name, ValueObserverInstrumentKind, number.Float64Kind, opts, b.runner)) } @@ -234,7 +224,7 @@ func (b BatchObserver) NewInt64SumObserver(name string, opts ...InstrumentOption return wrapInt64SumObserverInstrument(NoopAsync{}, nil) } return wrapInt64SumObserverInstrument( - b.meter.newAsync(name, SumObserverKind, Int64NumberKind, opts, b.runner)) + b.meter.newAsync(name, SumObserverInstrumentKind, number.Int64Kind, opts, b.runner)) } // NewFloat64SumObserver creates a new floating point SumObserver with @@ -246,7 +236,7 @@ func (b BatchObserver) NewFloat64SumObserver(name string, opts ...InstrumentOpti return wrapFloat64SumObserverInstrument(NoopAsync{}, nil) } return wrapFloat64SumObserverInstrument( - b.meter.newAsync(name, SumObserverKind, Float64NumberKind, opts, + b.meter.newAsync(name, SumObserverInstrumentKind, number.Float64Kind, opts, b.runner)) } @@ -259,7 +249,7 @@ func (b BatchObserver) NewInt64UpDownSumObserver(name string, opts ...Instrument return wrapInt64UpDownSumObserverInstrument(NoopAsync{}, nil) } return wrapInt64UpDownSumObserverInstrument( - b.meter.newAsync(name, UpDownSumObserverKind, Int64NumberKind, opts, b.runner)) + b.meter.newAsync(name, UpDownSumObserverInstrumentKind, number.Int64Kind, opts, b.runner)) } // NewFloat64UpDownSumObserver creates a new floating point UpDownSumObserver with @@ -271,7 +261,7 @@ func (b BatchObserver) NewFloat64UpDownSumObserver(name string, opts ...Instrume return wrapFloat64UpDownSumObserverInstrument(NoopAsync{}, nil) } return wrapFloat64UpDownSumObserverInstrument( - b.meter.newAsync(name, UpDownSumObserverKind, Float64NumberKind, opts, + b.meter.newAsync(name, UpDownSumObserverInstrumentKind, number.Float64Kind, opts, b.runner)) } @@ -283,8 +273,8 @@ func (m Meter) MeterImpl() MeterImpl { // newAsync constructs one new asynchronous instrument. func (m Meter) newAsync( name string, - mkind Kind, - nkind NumberKind, + mkind InstrumentKind, + nkind number.Kind, opts []InstrumentOption, runner AsyncRunner, ) ( @@ -303,8 +293,8 @@ func (m Meter) newAsync( // newSync constructs one new synchronous instrument. func (m Meter) newSync( name string, - metricKind Kind, - numberKind NumberKind, + metricKind InstrumentKind, + numberKind number.Kind, opts []InstrumentOption, ) ( SyncImpl, @@ -318,3 +308,270 @@ func (m Meter) newSync( desc.config.InstrumentationVersion = m.version return m.impl.NewSyncInstrument(desc) } + +// MeterMust is a wrapper for Meter interfaces that panics when any +// instrument constructor encounters an error. +type MeterMust struct { + meter Meter +} + +// BatchObserverMust is a wrapper for BatchObserver that panics when +// any instrument constructor encounters an error. +type BatchObserverMust struct { + batch BatchObserver +} + +// Must constructs a MeterMust implementation from a Meter, allowing +// the application to panic when any instrument constructor yields an +// error. +func Must(meter Meter) MeterMust { + return MeterMust{meter: meter} +} + +// NewInt64Counter calls `Meter.NewInt64Counter` and returns the +// instrument, panicking if it encounters an error. +func (mm MeterMust) NewInt64Counter(name string, cos ...InstrumentOption) Int64Counter { + if inst, err := mm.meter.NewInt64Counter(name, cos...); err != nil { + panic(err) + } else { + return inst + } +} + +// NewFloat64Counter calls `Meter.NewFloat64Counter` and returns the +// instrument, panicking if it encounters an error. +func (mm MeterMust) NewFloat64Counter(name string, cos ...InstrumentOption) Float64Counter { + if inst, err := mm.meter.NewFloat64Counter(name, cos...); err != nil { + panic(err) + } else { + return inst + } +} + +// NewInt64UpDownCounter calls `Meter.NewInt64UpDownCounter` and returns the +// instrument, panicking if it encounters an error. +func (mm MeterMust) NewInt64UpDownCounter(name string, cos ...InstrumentOption) Int64UpDownCounter { + if inst, err := mm.meter.NewInt64UpDownCounter(name, cos...); err != nil { + panic(err) + } else { + return inst + } +} + +// NewFloat64UpDownCounter calls `Meter.NewFloat64UpDownCounter` and returns the +// instrument, panicking if it encounters an error. +func (mm MeterMust) NewFloat64UpDownCounter(name string, cos ...InstrumentOption) Float64UpDownCounter { + if inst, err := mm.meter.NewFloat64UpDownCounter(name, cos...); err != nil { + panic(err) + } else { + return inst + } +} + +// NewInt64ValueRecorder calls `Meter.NewInt64ValueRecorder` and returns the +// instrument, panicking if it encounters an error. +func (mm MeterMust) NewInt64ValueRecorder(name string, mos ...InstrumentOption) Int64ValueRecorder { + if inst, err := mm.meter.NewInt64ValueRecorder(name, mos...); err != nil { + panic(err) + } else { + return inst + } +} + +// NewFloat64ValueRecorder calls `Meter.NewFloat64ValueRecorder` and returns the +// instrument, panicking if it encounters an error. +func (mm MeterMust) NewFloat64ValueRecorder(name string, mos ...InstrumentOption) Float64ValueRecorder { + if inst, err := mm.meter.NewFloat64ValueRecorder(name, mos...); err != nil { + panic(err) + } else { + return inst + } +} + +// NewInt64ValueObserver calls `Meter.NewInt64ValueObserver` and +// returns the instrument, panicking if it encounters an error. +func (mm MeterMust) NewInt64ValueObserver(name string, callback Int64ObserverFunc, oos ...InstrumentOption) Int64ValueObserver { + if inst, err := mm.meter.NewInt64ValueObserver(name, callback, oos...); err != nil { + panic(err) + } else { + return inst + } +} + +// NewFloat64ValueObserver calls `Meter.NewFloat64ValueObserver` and +// returns the instrument, panicking if it encounters an error. +func (mm MeterMust) NewFloat64ValueObserver(name string, callback Float64ObserverFunc, oos ...InstrumentOption) Float64ValueObserver { + if inst, err := mm.meter.NewFloat64ValueObserver(name, callback, oos...); err != nil { + panic(err) + } else { + return inst + } +} + +// NewInt64SumObserver calls `Meter.NewInt64SumObserver` and +// returns the instrument, panicking if it encounters an error. +func (mm MeterMust) NewInt64SumObserver(name string, callback Int64ObserverFunc, oos ...InstrumentOption) Int64SumObserver { + if inst, err := mm.meter.NewInt64SumObserver(name, callback, oos...); err != nil { + panic(err) + } else { + return inst + } +} + +// NewFloat64SumObserver calls `Meter.NewFloat64SumObserver` and +// returns the instrument, panicking if it encounters an error. +func (mm MeterMust) NewFloat64SumObserver(name string, callback Float64ObserverFunc, oos ...InstrumentOption) Float64SumObserver { + if inst, err := mm.meter.NewFloat64SumObserver(name, callback, oos...); err != nil { + panic(err) + } else { + return inst + } +} + +// NewInt64UpDownSumObserver calls `Meter.NewInt64UpDownSumObserver` and +// returns the instrument, panicking if it encounters an error. +func (mm MeterMust) NewInt64UpDownSumObserver(name string, callback Int64ObserverFunc, oos ...InstrumentOption) Int64UpDownSumObserver { + if inst, err := mm.meter.NewInt64UpDownSumObserver(name, callback, oos...); err != nil { + panic(err) + } else { + return inst + } +} + +// NewFloat64UpDownSumObserver calls `Meter.NewFloat64UpDownSumObserver` and +// returns the instrument, panicking if it encounters an error. +func (mm MeterMust) NewFloat64UpDownSumObserver(name string, callback Float64ObserverFunc, oos ...InstrumentOption) Float64UpDownSumObserver { + if inst, err := mm.meter.NewFloat64UpDownSumObserver(name, callback, oos...); err != nil { + panic(err) + } else { + return inst + } +} + +// NewBatchObserver returns a wrapper around BatchObserver that panics +// when any instrument constructor returns an error. +func (mm MeterMust) NewBatchObserver(callback BatchObserverFunc) BatchObserverMust { + return BatchObserverMust{ + batch: mm.meter.NewBatchObserver(callback), + } +} + +// NewInt64ValueObserver calls `BatchObserver.NewInt64ValueObserver` and +// returns the instrument, panicking if it encounters an error. +func (bm BatchObserverMust) NewInt64ValueObserver(name string, oos ...InstrumentOption) Int64ValueObserver { + if inst, err := bm.batch.NewInt64ValueObserver(name, oos...); err != nil { + panic(err) + } else { + return inst + } +} + +// NewFloat64ValueObserver calls `BatchObserver.NewFloat64ValueObserver` and +// returns the instrument, panicking if it encounters an error. +func (bm BatchObserverMust) NewFloat64ValueObserver(name string, oos ...InstrumentOption) Float64ValueObserver { + if inst, err := bm.batch.NewFloat64ValueObserver(name, oos...); err != nil { + panic(err) + } else { + return inst + } +} + +// NewInt64SumObserver calls `BatchObserver.NewInt64SumObserver` and +// returns the instrument, panicking if it encounters an error. +func (bm BatchObserverMust) NewInt64SumObserver(name string, oos ...InstrumentOption) Int64SumObserver { + if inst, err := bm.batch.NewInt64SumObserver(name, oos...); err != nil { + panic(err) + } else { + return inst + } +} + +// NewFloat64SumObserver calls `BatchObserver.NewFloat64SumObserver` and +// returns the instrument, panicking if it encounters an error. +func (bm BatchObserverMust) NewFloat64SumObserver(name string, oos ...InstrumentOption) Float64SumObserver { + if inst, err := bm.batch.NewFloat64SumObserver(name, oos...); err != nil { + panic(err) + } else { + return inst + } +} + +// NewInt64UpDownSumObserver calls `BatchObserver.NewInt64UpDownSumObserver` and +// returns the instrument, panicking if it encounters an error. +func (bm BatchObserverMust) NewInt64UpDownSumObserver(name string, oos ...InstrumentOption) Int64UpDownSumObserver { + if inst, err := bm.batch.NewInt64UpDownSumObserver(name, oos...); err != nil { + panic(err) + } else { + return inst + } +} + +// NewFloat64UpDownSumObserver calls `BatchObserver.NewFloat64UpDownSumObserver` and +// returns the instrument, panicking if it encounters an error. +func (bm BatchObserverMust) NewFloat64UpDownSumObserver(name string, oos ...InstrumentOption) Float64UpDownSumObserver { + if inst, err := bm.batch.NewFloat64UpDownSumObserver(name, oos...); err != nil { + panic(err) + } else { + return inst + } +} + +// Descriptor contains all the settings that describe an instrument, +// including its name, metric kind, number kind, and the configurable +// options. +type Descriptor struct { + name string + instrumentKind InstrumentKind + numberKind number.Kind + config InstrumentConfig +} + +// NewDescriptor returns a Descriptor with the given contents. +func NewDescriptor(name string, ikind InstrumentKind, nkind number.Kind, opts ...InstrumentOption) Descriptor { + return Descriptor{ + name: name, + instrumentKind: ikind, + numberKind: nkind, + config: NewInstrumentConfig(opts...), + } +} + +// Name returns the metric instrument's name. +func (d Descriptor) Name() string { + return d.name +} + +// InstrumentKind returns the specific kind of instrument. +func (d Descriptor) InstrumentKind() InstrumentKind { + return d.instrumentKind +} + +// Description provides a human-readable description of the metric +// instrument. +func (d Descriptor) Description() string { + return d.config.Description +} + +// Unit describes the units of the metric instrument. Unitless +// metrics return the empty string. +func (d Descriptor) Unit() unit.Unit { + return d.config.Unit +} + +// NumberKind returns whether this instrument is declared over int64, +// float64, or uint64 values. +func (d Descriptor) NumberKind() number.Kind { + return d.numberKind +} + +// InstrumentationName returns the name of the library that provided +// instrumentation for this instrument. +func (d Descriptor) InstrumentationName() string { + return d.config.InstrumentationName +} + +// InstrumentationVersion returns the version of the library that provided +// instrumentation for this instrument. +func (d Descriptor) InstrumentationVersion() string { + return d.config.InstrumentationVersion +} diff --git a/vendor/go.opentelemetry.io/otel/metric/metric_instrument.go b/vendor/go.opentelemetry.io/otel/metric/metric_instrument.go new file mode 100644 index 000000000..6f3fc997c --- /dev/null +++ b/vendor/go.opentelemetry.io/otel/metric/metric_instrument.go @@ -0,0 +1,777 @@ +// 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. + +//go:generate stringer -type=InstrumentKind + +package metric // import "go.opentelemetry.io/otel/metric" + +import ( + "context" + "errors" + + "go.opentelemetry.io/otel/attribute" + "go.opentelemetry.io/otel/metric/number" +) + +// ErrSDKReturnedNilImpl is returned when a new `MeterImpl` returns nil. +var ErrSDKReturnedNilImpl = errors.New("SDK returned a nil implementation") + +// InstrumentKind describes the kind of instrument. +type InstrumentKind int8 + +const ( + // ValueRecorderInstrumentKind indicates a ValueRecorder instrument. + ValueRecorderInstrumentKind InstrumentKind = iota + // ValueObserverInstrumentKind indicates an ValueObserver instrument. + ValueObserverInstrumentKind + + // CounterInstrumentKind indicates a Counter instrument. + CounterInstrumentKind + // UpDownCounterInstrumentKind indicates a UpDownCounter instrument. + UpDownCounterInstrumentKind + + // SumObserverInstrumentKind indicates a SumObserver instrument. + SumObserverInstrumentKind + // UpDownSumObserverInstrumentKind indicates a UpDownSumObserver + // instrument. + UpDownSumObserverInstrumentKind +) + +// Synchronous returns whether this is a synchronous kind of instrument. +func (k InstrumentKind) Synchronous() bool { + switch k { + case CounterInstrumentKind, UpDownCounterInstrumentKind, ValueRecorderInstrumentKind: + return true + } + return false +} + +// Asynchronous returns whether this is an asynchronous kind of instrument. +func (k InstrumentKind) Asynchronous() bool { + return !k.Synchronous() +} + +// Adding returns whether this kind of instrument adds its inputs (as opposed to Grouping). +func (k InstrumentKind) Adding() bool { + switch k { + case CounterInstrumentKind, UpDownCounterInstrumentKind, SumObserverInstrumentKind, UpDownSumObserverInstrumentKind: + return true + } + return false +} + +// Grouping returns whether this kind of instrument groups its inputs (as opposed to Adding). +func (k InstrumentKind) Grouping() bool { + return !k.Adding() +} + +// Monotonic returns whether this kind of instrument exposes a non-decreasing sum. +func (k InstrumentKind) Monotonic() bool { + switch k { + case CounterInstrumentKind, SumObserverInstrumentKind: + return true + } + return false +} + +// PrecomputedSum returns whether this kind of instrument receives precomputed sums. +func (k InstrumentKind) PrecomputedSum() bool { + return k.Adding() && k.Asynchronous() +} + +// Observation is used for reporting an asynchronous batch of metric +// values. Instances of this type should be created by asynchronous +// instruments (e.g., Int64ValueObserver.Observation()). +type Observation struct { + // number needs to be aligned for 64-bit atomic operations. + number number.Number + instrument AsyncImpl +} + +// Int64ObserverFunc is a type of callback that integral +// observers run. +type Int64ObserverFunc func(context.Context, Int64ObserverResult) + +// Float64ObserverFunc is a type of callback that floating point +// observers run. +type Float64ObserverFunc func(context.Context, Float64ObserverResult) + +// BatchObserverFunc is a callback argument for use with any +// Observer instrument that will be reported as a batch of +// observations. +type BatchObserverFunc func(context.Context, BatchObserverResult) + +// Int64ObserverResult is passed to an observer callback to capture +// observations for one asynchronous integer metric instrument. +type Int64ObserverResult struct { + instrument AsyncImpl + function func([]attribute.KeyValue, ...Observation) +} + +// Float64ObserverResult is passed to an observer callback to capture +// observations for one asynchronous floating point metric instrument. +type Float64ObserverResult struct { + instrument AsyncImpl + function func([]attribute.KeyValue, ...Observation) +} + +// BatchObserverResult is passed to a batch observer callback to +// capture observations for multiple asynchronous instruments. +type BatchObserverResult struct { + function func([]attribute.KeyValue, ...Observation) +} + +// Observe captures a single integer value from the associated +// instrument callback, with the given labels. +func (ir Int64ObserverResult) Observe(value int64, labels ...attribute.KeyValue) { + ir.function(labels, Observation{ + instrument: ir.instrument, + number: number.NewInt64Number(value), + }) +} + +// Observe captures a single floating point value from the associated +// instrument callback, with the given labels. +func (fr Float64ObserverResult) Observe(value float64, labels ...attribute.KeyValue) { + fr.function(labels, Observation{ + instrument: fr.instrument, + number: number.NewFloat64Number(value), + }) +} + +// Observe captures a multiple observations from the associated batch +// instrument callback, with the given labels. +func (br BatchObserverResult) Observe(labels []attribute.KeyValue, obs ...Observation) { + br.function(labels, obs...) +} + +// AsyncRunner is expected to convert into an AsyncSingleRunner or an +// AsyncBatchRunner. SDKs will encounter an error if the AsyncRunner +// does not satisfy one of these interfaces. +type AsyncRunner interface { + // AnyRunner() is a non-exported method with no functional use + // other than to make this a non-empty interface. + AnyRunner() +} + +// AsyncSingleRunner is an interface implemented by single-observer +// callbacks. +type AsyncSingleRunner interface { + // Run accepts a single instrument and function for capturing + // observations of that instrument. Each call to the function + // receives one captured observation. (The function accepts + // multiple observations so the same implementation can be + // used for batch runners.) + Run(ctx context.Context, single AsyncImpl, capture func([]attribute.KeyValue, ...Observation)) + + AsyncRunner +} + +// AsyncBatchRunner is an interface implemented by batch-observer +// callbacks. +type AsyncBatchRunner interface { + // Run accepts a function for capturing observations of + // multiple instruments. + Run(ctx context.Context, capture func([]attribute.KeyValue, ...Observation)) + + AsyncRunner +} + +var _ AsyncSingleRunner = (*Int64ObserverFunc)(nil) +var _ AsyncSingleRunner = (*Float64ObserverFunc)(nil) +var _ AsyncBatchRunner = (*BatchObserverFunc)(nil) + +// newInt64AsyncRunner returns a single-observer callback for integer Observer instruments. +func newInt64AsyncRunner(c Int64ObserverFunc) AsyncSingleRunner { + return &c +} + +// newFloat64AsyncRunner returns a single-observer callback for floating point Observer instruments. +func newFloat64AsyncRunner(c Float64ObserverFunc) AsyncSingleRunner { + return &c +} + +// newBatchAsyncRunner returns a batch-observer callback use with multiple Observer instruments. +func newBatchAsyncRunner(c BatchObserverFunc) AsyncBatchRunner { + return &c +} + +// AnyRunner implements AsyncRunner. +func (*Int64ObserverFunc) AnyRunner() {} + +// AnyRunner implements AsyncRunner. +func (*Float64ObserverFunc) AnyRunner() {} + +// AnyRunner implements AsyncRunner. +func (*BatchObserverFunc) AnyRunner() {} + +// Run implements AsyncSingleRunner. +func (i *Int64ObserverFunc) Run(ctx context.Context, impl AsyncImpl, function func([]attribute.KeyValue, ...Observation)) { + (*i)(ctx, Int64ObserverResult{ + instrument: impl, + function: function, + }) +} + +// Run implements AsyncSingleRunner. +func (f *Float64ObserverFunc) Run(ctx context.Context, impl AsyncImpl, function func([]attribute.KeyValue, ...Observation)) { + (*f)(ctx, Float64ObserverResult{ + instrument: impl, + function: function, + }) +} + +// Run implements AsyncBatchRunner. +func (b *BatchObserverFunc) Run(ctx context.Context, function func([]attribute.KeyValue, ...Observation)) { + (*b)(ctx, BatchObserverResult{ + function: function, + }) +} + +// wrapInt64ValueObserverInstrument converts an AsyncImpl into Int64ValueObserver. +func wrapInt64ValueObserverInstrument(asyncInst AsyncImpl, err error) (Int64ValueObserver, error) { + common, err := checkNewAsync(asyncInst, err) + return Int64ValueObserver{asyncInstrument: common}, err +} + +// wrapFloat64ValueObserverInstrument converts an AsyncImpl into Float64ValueObserver. +func wrapFloat64ValueObserverInstrument(asyncInst AsyncImpl, err error) (Float64ValueObserver, error) { + common, err := checkNewAsync(asyncInst, err) + return Float64ValueObserver{asyncInstrument: common}, err +} + +// wrapInt64SumObserverInstrument converts an AsyncImpl into Int64SumObserver. +func wrapInt64SumObserverInstrument(asyncInst AsyncImpl, err error) (Int64SumObserver, error) { + common, err := checkNewAsync(asyncInst, err) + return Int64SumObserver{asyncInstrument: common}, err +} + +// wrapFloat64SumObserverInstrument converts an AsyncImpl into Float64SumObserver. +func wrapFloat64SumObserverInstrument(asyncInst AsyncImpl, err error) (Float64SumObserver, error) { + common, err := checkNewAsync(asyncInst, err) + return Float64SumObserver{asyncInstrument: common}, err +} + +// wrapInt64UpDownSumObserverInstrument converts an AsyncImpl into Int64UpDownSumObserver. +func wrapInt64UpDownSumObserverInstrument(asyncInst AsyncImpl, err error) (Int64UpDownSumObserver, error) { + common, err := checkNewAsync(asyncInst, err) + return Int64UpDownSumObserver{asyncInstrument: common}, err +} + +// wrapFloat64UpDownSumObserverInstrument converts an AsyncImpl into Float64UpDownSumObserver. +func wrapFloat64UpDownSumObserverInstrument(asyncInst AsyncImpl, err error) (Float64UpDownSumObserver, error) { + common, err := checkNewAsync(asyncInst, err) + return Float64UpDownSumObserver{asyncInstrument: common}, err +} + +// BatchObserver represents an Observer callback that can report +// observations for multiple instruments. +type BatchObserver struct { + meter Meter + runner AsyncBatchRunner +} + +// Int64ValueObserver is a metric that captures a set of int64 values at a +// point in time. +type Int64ValueObserver struct { + asyncInstrument +} + +// Float64ValueObserver is a metric that captures a set of float64 values +// at a point in time. +type Float64ValueObserver struct { + asyncInstrument +} + +// Int64SumObserver is a metric that captures a precomputed sum of +// int64 values at a point in time. +type Int64SumObserver struct { + asyncInstrument +} + +// Float64SumObserver is a metric that captures a precomputed sum of +// float64 values at a point in time. +type Float64SumObserver struct { + asyncInstrument +} + +// Int64UpDownSumObserver is a metric that captures a precomputed sum of +// int64 values at a point in time. +type Int64UpDownSumObserver struct { + asyncInstrument +} + +// Float64UpDownSumObserver is a metric that captures a precomputed sum of +// float64 values at a point in time. +type Float64UpDownSumObserver struct { + asyncInstrument +} + +// Observation returns an Observation, a BatchObserverFunc +// argument, for an asynchronous integer instrument. +// This returns an implementation-level object for use by the SDK, +// users should not refer to this. +func (i Int64ValueObserver) Observation(v int64) Observation { + return Observation{ + number: number.NewInt64Number(v), + instrument: i.instrument, + } +} + +// Observation returns an Observation, a BatchObserverFunc +// argument, for an asynchronous integer instrument. +// This returns an implementation-level object for use by the SDK, +// users should not refer to this. +func (f Float64ValueObserver) Observation(v float64) Observation { + return Observation{ + number: number.NewFloat64Number(v), + instrument: f.instrument, + } +} + +// Observation returns an Observation, a BatchObserverFunc +// argument, for an asynchronous integer instrument. +// This returns an implementation-level object for use by the SDK, +// users should not refer to this. +func (i Int64SumObserver) Observation(v int64) Observation { + return Observation{ + number: number.NewInt64Number(v), + instrument: i.instrument, + } +} + +// Observation returns an Observation, a BatchObserverFunc +// argument, for an asynchronous integer instrument. +// This returns an implementation-level object for use by the SDK, +// users should not refer to this. +func (f Float64SumObserver) Observation(v float64) Observation { + return Observation{ + number: number.NewFloat64Number(v), + instrument: f.instrument, + } +} + +// Observation returns an Observation, a BatchObserverFunc +// argument, for an asynchronous integer instrument. +// This returns an implementation-level object for use by the SDK, +// users should not refer to this. +func (i Int64UpDownSumObserver) Observation(v int64) Observation { + return Observation{ + number: number.NewInt64Number(v), + instrument: i.instrument, + } +} + +// Observation returns an Observation, a BatchObserverFunc +// argument, for an asynchronous integer instrument. +// This returns an implementation-level object for use by the SDK, +// users should not refer to this. +func (f Float64UpDownSumObserver) Observation(v float64) Observation { + return Observation{ + number: number.NewFloat64Number(v), + instrument: f.instrument, + } +} + +// Measurement is used for reporting a synchronous batch of metric +// values. Instances of this type should be created by synchronous +// instruments (e.g., Int64Counter.Measurement()). +type Measurement struct { + // number needs to be aligned for 64-bit atomic operations. + number number.Number + instrument SyncImpl +} + +// syncInstrument contains a SyncImpl. +type syncInstrument struct { + instrument SyncImpl +} + +// syncBoundInstrument contains a BoundSyncImpl. +type syncBoundInstrument struct { + boundInstrument BoundSyncImpl +} + +// asyncInstrument contains a AsyncImpl. +type asyncInstrument struct { + instrument AsyncImpl +} + +// SyncImpl returns the instrument that created this measurement. +// This returns an implementation-level object for use by the SDK, +// users should not refer to this. +func (m Measurement) SyncImpl() SyncImpl { + return m.instrument +} + +// Number returns a number recorded in this measurement. +func (m Measurement) Number() number.Number { + return m.number +} + +// AsyncImpl returns the instrument that created this observation. +// This returns an implementation-level object for use by the SDK, +// users should not refer to this. +func (m Observation) AsyncImpl() AsyncImpl { + return m.instrument +} + +// Number returns a number recorded in this observation. +func (m Observation) Number() number.Number { + return m.number +} + +// AsyncImpl implements AsyncImpl. +func (a asyncInstrument) AsyncImpl() AsyncImpl { + return a.instrument +} + +// SyncImpl returns the implementation object for synchronous instruments. +func (s syncInstrument) SyncImpl() SyncImpl { + return s.instrument +} + +func (s syncInstrument) bind(labels []attribute.KeyValue) syncBoundInstrument { + return newSyncBoundInstrument(s.instrument.Bind(labels)) +} + +func (s syncInstrument) float64Measurement(value float64) Measurement { + return newMeasurement(s.instrument, number.NewFloat64Number(value)) +} + +func (s syncInstrument) int64Measurement(value int64) Measurement { + return newMeasurement(s.instrument, number.NewInt64Number(value)) +} + +func (s syncInstrument) directRecord(ctx context.Context, number number.Number, labels []attribute.KeyValue) { + s.instrument.RecordOne(ctx, number, labels) +} + +func (h syncBoundInstrument) directRecord(ctx context.Context, number number.Number) { + h.boundInstrument.RecordOne(ctx, number) +} + +// Unbind calls SyncImpl.Unbind. +func (h syncBoundInstrument) Unbind() { + h.boundInstrument.Unbind() +} + +// checkNewAsync receives an AsyncImpl and potential +// error, and returns the same types, checking for and ensuring that +// the returned interface is not nil. +func checkNewAsync(instrument AsyncImpl, err error) (asyncInstrument, error) { + if instrument == nil { + if err == nil { + err = ErrSDKReturnedNilImpl + } + instrument = NoopAsync{} + } + return asyncInstrument{ + instrument: instrument, + }, err +} + +// checkNewSync receives an SyncImpl and potential +// error, and returns the same types, checking for and ensuring that +// the returned interface is not nil. +func checkNewSync(instrument SyncImpl, err error) (syncInstrument, error) { + if instrument == nil { + if err == nil { + err = ErrSDKReturnedNilImpl + } + // Note: an alternate behavior would be to synthesize a new name + // or group all duplicately-named instruments of a certain type + // together and use a tag for the original name, e.g., + // name = 'invalid.counter.int64' + // label = 'original-name=duplicate-counter-name' + instrument = NoopSync{} + } + return syncInstrument{ + instrument: instrument, + }, err +} + +func newSyncBoundInstrument(boundInstrument BoundSyncImpl) syncBoundInstrument { + return syncBoundInstrument{ + boundInstrument: boundInstrument, + } +} + +func newMeasurement(instrument SyncImpl, number number.Number) Measurement { + return Measurement{ + instrument: instrument, + number: number, + } +} + +// wrapInt64CounterInstrument converts a SyncImpl into Int64Counter. +func wrapInt64CounterInstrument(syncInst SyncImpl, err error) (Int64Counter, error) { + common, err := checkNewSync(syncInst, err) + return Int64Counter{syncInstrument: common}, err +} + +// wrapFloat64CounterInstrument converts a SyncImpl into Float64Counter. +func wrapFloat64CounterInstrument(syncInst SyncImpl, err error) (Float64Counter, error) { + common, err := checkNewSync(syncInst, err) + return Float64Counter{syncInstrument: common}, err +} + +// wrapInt64UpDownCounterInstrument converts a SyncImpl into Int64UpDownCounter. +func wrapInt64UpDownCounterInstrument(syncInst SyncImpl, err error) (Int64UpDownCounter, error) { + common, err := checkNewSync(syncInst, err) + return Int64UpDownCounter{syncInstrument: common}, err +} + +// wrapFloat64UpDownCounterInstrument converts a SyncImpl into Float64UpDownCounter. +func wrapFloat64UpDownCounterInstrument(syncInst SyncImpl, err error) (Float64UpDownCounter, error) { + common, err := checkNewSync(syncInst, err) + return Float64UpDownCounter{syncInstrument: common}, err +} + +// wrapInt64ValueRecorderInstrument converts a SyncImpl into Int64ValueRecorder. +func wrapInt64ValueRecorderInstrument(syncInst SyncImpl, err error) (Int64ValueRecorder, error) { + common, err := checkNewSync(syncInst, err) + return Int64ValueRecorder{syncInstrument: common}, err +} + +// wrapFloat64ValueRecorderInstrument converts a SyncImpl into Float64ValueRecorder. +func wrapFloat64ValueRecorderInstrument(syncInst SyncImpl, err error) (Float64ValueRecorder, error) { + common, err := checkNewSync(syncInst, err) + return Float64ValueRecorder{syncInstrument: common}, err +} + +// Float64Counter is a metric that accumulates float64 values. +type Float64Counter struct { + syncInstrument +} + +// Int64Counter is a metric that accumulates int64 values. +type Int64Counter struct { + syncInstrument +} + +// BoundFloat64Counter is a bound instrument for Float64Counter. +// +// It inherits the Unbind function from syncBoundInstrument. +type BoundFloat64Counter struct { + syncBoundInstrument +} + +// BoundInt64Counter is a boundInstrument for Int64Counter. +// +// It inherits the Unbind function from syncBoundInstrument. +type BoundInt64Counter struct { + syncBoundInstrument +} + +// Bind creates a bound instrument for this counter. The labels are +// associated with values recorded via subsequent calls to Record. +func (c Float64Counter) Bind(labels ...attribute.KeyValue) (h BoundFloat64Counter) { + h.syncBoundInstrument = c.bind(labels) + return +} + +// Bind creates a bound instrument for this counter. The labels are +// associated with values recorded via subsequent calls to Record. +func (c Int64Counter) Bind(labels ...attribute.KeyValue) (h BoundInt64Counter) { + h.syncBoundInstrument = c.bind(labels) + return +} + +// Measurement creates a Measurement object to use with batch +// recording. +func (c Float64Counter) Measurement(value float64) Measurement { + return c.float64Measurement(value) +} + +// Measurement creates a Measurement object to use with batch +// recording. +func (c Int64Counter) Measurement(value int64) Measurement { + return c.int64Measurement(value) +} + +// Add adds the value to the counter's sum. The labels should contain +// the keys and values to be associated with this value. +func (c Float64Counter) Add(ctx context.Context, value float64, labels ...attribute.KeyValue) { + c.directRecord(ctx, number.NewFloat64Number(value), labels) +} + +// Add adds the value to the counter's sum. The labels should contain +// the keys and values to be associated with this value. +func (c Int64Counter) Add(ctx context.Context, value int64, labels ...attribute.KeyValue) { + c.directRecord(ctx, number.NewInt64Number(value), labels) +} + +// Add adds the value to the counter's sum using the labels +// previously bound to this counter via Bind() +func (b BoundFloat64Counter) Add(ctx context.Context, value float64) { + b.directRecord(ctx, number.NewFloat64Number(value)) +} + +// Add adds the value to the counter's sum using the labels +// previously bound to this counter via Bind() +func (b BoundInt64Counter) Add(ctx context.Context, value int64) { + b.directRecord(ctx, number.NewInt64Number(value)) +} + +// Float64UpDownCounter is a metric instrument that sums floating +// point values. +type Float64UpDownCounter struct { + syncInstrument +} + +// Int64UpDownCounter is a metric instrument that sums integer values. +type Int64UpDownCounter struct { + syncInstrument +} + +// BoundFloat64UpDownCounter is a bound instrument for Float64UpDownCounter. +// +// It inherits the Unbind function from syncBoundInstrument. +type BoundFloat64UpDownCounter struct { + syncBoundInstrument +} + +// BoundInt64UpDownCounter is a boundInstrument for Int64UpDownCounter. +// +// It inherits the Unbind function from syncBoundInstrument. +type BoundInt64UpDownCounter struct { + syncBoundInstrument +} + +// Bind creates a bound instrument for this counter. The labels are +// associated with values recorded via subsequent calls to Record. +func (c Float64UpDownCounter) Bind(labels ...attribute.KeyValue) (h BoundFloat64UpDownCounter) { + h.syncBoundInstrument = c.bind(labels) + return +} + +// Bind creates a bound instrument for this counter. The labels are +// associated with values recorded via subsequent calls to Record. +func (c Int64UpDownCounter) Bind(labels ...attribute.KeyValue) (h BoundInt64UpDownCounter) { + h.syncBoundInstrument = c.bind(labels) + return +} + +// Measurement creates a Measurement object to use with batch +// recording. +func (c Float64UpDownCounter) Measurement(value float64) Measurement { + return c.float64Measurement(value) +} + +// Measurement creates a Measurement object to use with batch +// recording. +func (c Int64UpDownCounter) Measurement(value int64) Measurement { + return c.int64Measurement(value) +} + +// Add adds the value to the counter's sum. The labels should contain +// the keys and values to be associated with this value. +func (c Float64UpDownCounter) Add(ctx context.Context, value float64, labels ...attribute.KeyValue) { + c.directRecord(ctx, number.NewFloat64Number(value), labels) +} + +// Add adds the value to the counter's sum. The labels should contain +// the keys and values to be associated with this value. +func (c Int64UpDownCounter) Add(ctx context.Context, value int64, labels ...attribute.KeyValue) { + c.directRecord(ctx, number.NewInt64Number(value), labels) +} + +// Add adds the value to the counter's sum using the labels +// previously bound to this counter via Bind() +func (b BoundFloat64UpDownCounter) Add(ctx context.Context, value float64) { + b.directRecord(ctx, number.NewFloat64Number(value)) +} + +// Add adds the value to the counter's sum using the labels +// previously bound to this counter via Bind() +func (b BoundInt64UpDownCounter) Add(ctx context.Context, value int64) { + b.directRecord(ctx, number.NewInt64Number(value)) +} + +// Float64ValueRecorder is a metric that records float64 values. +type Float64ValueRecorder struct { + syncInstrument +} + +// Int64ValueRecorder is a metric that records int64 values. +type Int64ValueRecorder struct { + syncInstrument +} + +// BoundFloat64ValueRecorder is a bound instrument for Float64ValueRecorder. +// +// It inherits the Unbind function from syncBoundInstrument. +type BoundFloat64ValueRecorder struct { + syncBoundInstrument +} + +// BoundInt64ValueRecorder is a bound instrument for Int64ValueRecorder. +// +// It inherits the Unbind function from syncBoundInstrument. +type BoundInt64ValueRecorder struct { + syncBoundInstrument +} + +// Bind creates a bound instrument for this ValueRecorder. The labels are +// associated with values recorded via subsequent calls to Record. +func (c Float64ValueRecorder) Bind(labels ...attribute.KeyValue) (h BoundFloat64ValueRecorder) { + h.syncBoundInstrument = c.bind(labels) + return +} + +// Bind creates a bound instrument for this ValueRecorder. The labels are +// associated with values recorded via subsequent calls to Record. +func (c Int64ValueRecorder) Bind(labels ...attribute.KeyValue) (h BoundInt64ValueRecorder) { + h.syncBoundInstrument = c.bind(labels) + return +} + +// Measurement creates a Measurement object to use with batch +// recording. +func (c Float64ValueRecorder) Measurement(value float64) Measurement { + return c.float64Measurement(value) +} + +// Measurement creates a Measurement object to use with batch +// recording. +func (c Int64ValueRecorder) Measurement(value int64) Measurement { + return c.int64Measurement(value) +} + +// Record adds a new value to the list of ValueRecorder's records. The +// labels should contain the keys and values to be associated with +// this value. +func (c Float64ValueRecorder) Record(ctx context.Context, value float64, labels ...attribute.KeyValue) { + c.directRecord(ctx, number.NewFloat64Number(value), labels) +} + +// Record adds a new value to the ValueRecorder's distribution. The +// labels should contain the keys and values to be associated with +// this value. +func (c Int64ValueRecorder) Record(ctx context.Context, value int64, labels ...attribute.KeyValue) { + c.directRecord(ctx, number.NewInt64Number(value), labels) +} + +// Record adds a new value to the ValueRecorder's distribution using the labels +// previously bound to the ValueRecorder via Bind(). +func (b BoundFloat64ValueRecorder) Record(ctx context.Context, value float64) { + b.directRecord(ctx, number.NewFloat64Number(value)) +} + +// Record adds a new value to the ValueRecorder's distribution using the labels +// previously bound to the ValueRecorder via Bind(). +func (b BoundInt64ValueRecorder) Record(ctx context.Context, value int64) { + b.directRecord(ctx, number.NewInt64Number(value)) +} diff --git a/vendor/go.opentelemetry.io/otel/api/metric/noop.go b/vendor/go.opentelemetry.io/otel/metric/metric_noop.go similarity index 69% rename from vendor/go.opentelemetry.io/otel/api/metric/noop.go rename to vendor/go.opentelemetry.io/otel/metric/metric_noop.go index de2c5681a..30e57b694 100644 --- a/vendor/go.opentelemetry.io/otel/api/metric/noop.go +++ b/vendor/go.opentelemetry.io/otel/metric/metric_noop.go @@ -12,27 +12,28 @@ // See the License for the specific language governing permissions and // limitations under the License. -package metric +package metric // import "go.opentelemetry.io/otel/metric" import ( "context" - "go.opentelemetry.io/otel/label" + "go.opentelemetry.io/otel/attribute" + "go.opentelemetry.io/otel/metric/number" ) -type NoopProvider struct{} +type NoopMeterProvider struct{} type noopInstrument struct{} type noopBoundInstrument struct{} type NoopSync struct{ noopInstrument } type NoopAsync struct{ noopInstrument } -var _ Provider = NoopProvider{} +var _ MeterProvider = NoopMeterProvider{} var _ SyncImpl = NoopSync{} var _ BoundSyncImpl = noopBoundInstrument{} var _ AsyncImpl = NoopAsync{} -func (NoopProvider) Meter(_ string, _ ...MeterOption) Meter { +func (NoopMeterProvider) Meter(_ string, _ ...MeterOption) Meter { return Meter{} } @@ -44,15 +45,15 @@ func (noopInstrument) Descriptor() Descriptor { return Descriptor{} } -func (noopBoundInstrument) RecordOne(context.Context, Number) { +func (noopBoundInstrument) RecordOne(context.Context, number.Number) { } func (noopBoundInstrument) Unbind() { } -func (NoopSync) Bind([]label.KeyValue) BoundSyncImpl { +func (NoopSync) Bind([]attribute.KeyValue) BoundSyncImpl { return noopBoundInstrument{} } -func (NoopSync) RecordOne(context.Context, Number, []label.KeyValue) { +func (NoopSync) RecordOne(context.Context, number.Number, []attribute.KeyValue) { } diff --git a/vendor/go.opentelemetry.io/otel/api/metric/sdkapi.go b/vendor/go.opentelemetry.io/otel/metric/metric_sdkapi.go similarity index 81% rename from vendor/go.opentelemetry.io/otel/api/metric/sdkapi.go rename to vendor/go.opentelemetry.io/otel/metric/metric_sdkapi.go index 3c4e11ee4..94164f7b4 100644 --- a/vendor/go.opentelemetry.io/otel/api/metric/sdkapi.go +++ b/vendor/go.opentelemetry.io/otel/metric/metric_sdkapi.go @@ -12,19 +12,20 @@ // See the License for the specific language governing permissions and // limitations under the License. -package metric +package metric // import "go.opentelemetry.io/otel/metric" import ( "context" - "go.opentelemetry.io/otel/label" + "go.opentelemetry.io/otel/attribute" + "go.opentelemetry.io/otel/metric/number" ) // MeterImpl is the interface an SDK must implement to supply a Meter // implementation. type MeterImpl interface { // RecordBatch atomically records a batch of measurements. - RecordBatch(context.Context, []label.KeyValue, ...Measurement) + RecordBatch(ctx context.Context, labels []attribute.KeyValue, measurement ...Measurement) // NewSyncInstrument returns a newly constructed // synchronous instrument implementation or an error, should @@ -59,10 +60,10 @@ type SyncImpl interface { // Bind creates an implementation-level bound instrument, // binding a label set with this instrument implementation. - Bind(labels []label.KeyValue) BoundSyncImpl + Bind(labels []attribute.KeyValue) BoundSyncImpl // RecordOne captures a single synchronous metric event. - RecordOne(ctx context.Context, number Number, labels []label.KeyValue) + RecordOne(ctx context.Context, number number.Number, labels []attribute.KeyValue) } // BoundSyncImpl is the implementation-level interface to a @@ -70,7 +71,7 @@ type SyncImpl interface { type BoundSyncImpl interface { // RecordOne captures a single synchronous metric event. - RecordOne(ctx context.Context, number Number) + RecordOne(ctx context.Context, number number.Number) // Unbind frees the resources associated with this bound instrument. It // does not affect the metric this bound instrument was created through. @@ -85,10 +86,10 @@ type AsyncImpl interface { // WrapMeterImpl constructs a `Meter` implementation from a // `MeterImpl` implementation. -func WrapMeterImpl(impl MeterImpl, instrumentatioName string, opts ...MeterOption) Meter { +func WrapMeterImpl(impl MeterImpl, instrumentationName string, opts ...MeterOption) Meter { return Meter{ impl: impl, - name: instrumentatioName, - version: ConfigureMeter(opts).InstrumentationVersion, + name: instrumentationName, + version: NewMeterConfig(opts...).InstrumentationVersion, } } diff --git a/vendor/go.opentelemetry.io/otel/otel.go b/vendor/go.opentelemetry.io/otel/metric/number/doc.go similarity index 60% rename from vendor/go.opentelemetry.io/otel/otel.go rename to vendor/go.opentelemetry.io/otel/metric/number/doc.go index 7d1c424bf..0649ff875 100644 --- a/vendor/go.opentelemetry.io/otel/otel.go +++ b/vendor/go.opentelemetry.io/otel/metric/number/doc.go @@ -12,16 +12,12 @@ // See the License for the specific language governing permissions and // limitations under the License. -package otel +/* +Package number provides a number abstraction for instruments that +either support int64 or float64 input values. -import ( - "go.opentelemetry.io/otel/api/metric" - "go.opentelemetry.io/otel/api/propagation" - "go.opentelemetry.io/otel/api/trace" -) - -type Tracer = trace.Tracer - -type Meter = metric.Meter - -type Propagators = propagation.Propagators +This package is currently in a pre-GA phase. Backwards incompatible changes +may be introduced in subsequent minor version releases as we work to track the +evolving OpenTelemetry specification and user feedback. +*/ +package number // import "go.opentelemetry.io/otel/metric/number" diff --git a/vendor/go.opentelemetry.io/otel/api/metric/kind_string.go b/vendor/go.opentelemetry.io/otel/metric/number/kind_string.go similarity index 56% rename from vendor/go.opentelemetry.io/otel/api/metric/kind_string.go rename to vendor/go.opentelemetry.io/otel/metric/number/kind_string.go index eb1a0d503..6288c7ea2 100644 --- a/vendor/go.opentelemetry.io/otel/api/metric/kind_string.go +++ b/vendor/go.opentelemetry.io/otel/metric/number/kind_string.go @@ -1,6 +1,6 @@ // Code generated by "stringer -type=Kind"; DO NOT EDIT. -package metric +package number import "strconv" @@ -8,17 +8,13 @@ func _() { // An "invalid array index" compiler error signifies that the constant values have changed. // Re-run the stringer command to generate them again. var x [1]struct{} - _ = x[ValueRecorderKind-0] - _ = x[ValueObserverKind-1] - _ = x[CounterKind-2] - _ = x[UpDownCounterKind-3] - _ = x[SumObserverKind-4] - _ = x[UpDownSumObserverKind-5] + _ = x[Int64Kind-0] + _ = x[Float64Kind-1] } -const _Kind_name = "ValueRecorderKindValueObserverKindCounterKindUpDownCounterKindSumObserverKindUpDownSumObserverKind" +const _Kind_name = "Int64KindFloat64Kind" -var _Kind_index = [...]uint8{0, 17, 34, 45, 62, 77, 98} +var _Kind_index = [...]uint8{0, 9, 20} func (i Kind) String() string { if i < 0 || i >= Kind(len(_Kind_index)-1) { diff --git a/vendor/go.opentelemetry.io/otel/api/metric/number.go b/vendor/go.opentelemetry.io/otel/metric/number/number.go similarity index 86% rename from vendor/go.opentelemetry.io/otel/api/metric/number.go rename to vendor/go.opentelemetry.io/otel/metric/number/number.go index c3ca0ed79..3ec95e201 100644 --- a/vendor/go.opentelemetry.io/otel/api/metric/number.go +++ b/vendor/go.opentelemetry.io/otel/metric/number/number.go @@ -12,9 +12,9 @@ // See the License for the specific language governing permissions and // limitations under the License. -package metric +package number // import "go.opentelemetry.io/otel/metric/number" -//go:generate stringer -type=NumberKind +//go:generate stringer -type=Kind import ( "fmt" @@ -24,22 +24,22 @@ import ( "go.opentelemetry.io/otel/internal" ) -// NumberKind describes the data type of the Number. -type NumberKind int8 +// Kind describes the data type of the Number. +type Kind int8 const ( - // Int64NumberKind means that the Number stores int64. - Int64NumberKind NumberKind = iota - // Float64NumberKind means that the Number stores float64. - Float64NumberKind + // Int64Kind means that the Number stores int64. + Int64Kind Kind = iota + // Float64Kind means that the Number stores float64. + Float64Kind ) -// Zero returns a zero value for a given NumberKind -func (k NumberKind) Zero() Number { +// Zero returns a zero value for a given Kind +func (k Kind) Zero() Number { switch k { - case Int64NumberKind: + case Int64Kind: return NewInt64Number(0) - case Float64NumberKind: + case Float64Kind: return NewFloat64Number(0.) default: return Number(0) @@ -47,12 +47,12 @@ func (k NumberKind) Zero() Number { } // Minimum returns the minimum representable value -// for a given NumberKind -func (k NumberKind) Minimum() Number { +// for a given Kind +func (k Kind) Minimum() Number { switch k { - case Int64NumberKind: + case Int64Kind: return NewInt64Number(math.MinInt64) - case Float64NumberKind: + case Float64Kind: return NewFloat64Number(-1. * math.MaxFloat64) default: return Number(0) @@ -60,12 +60,12 @@ func (k NumberKind) Minimum() Number { } // Maximum returns the maximum representable value -// for a given NumberKind -func (k NumberKind) Maximum() Number { +// for a given Kind +func (k Kind) Maximum() Number { switch k { - case Int64NumberKind: + case Int64Kind: return NewInt64Number(math.MaxInt64) - case Float64NumberKind: + case Float64Kind: return NewFloat64Number(math.MaxFloat64) default: return Number(0) @@ -73,7 +73,7 @@ func (k NumberKind) Maximum() Number { } // Number represents either an integral or a floating point value. It -// needs to be accompanied with a source of NumberKind that describes +// needs to be accompanied with a source of Kind that describes // the actual type of the value stored within Number. type Number uint64 @@ -96,13 +96,11 @@ func NewFloat64Number(f float64) Number { // NewNumberSignChange returns a number with the same magnitude and // the opposite sign. `kind` must describe the kind of number in `nn`. -// -// Does not change Uint64NumberKind values. -func NewNumberSignChange(kind NumberKind, nn Number) Number { +func NewNumberSignChange(kind Kind, nn Number) Number { switch kind { - case Int64NumberKind: + case Int64Kind: return NewInt64Number(-nn.AsInt64()) - case Float64NumberKind: + case Float64Kind: return NewFloat64Number(-nn.AsFloat64()) } return nn @@ -182,11 +180,11 @@ func (n *Number) AsFloat64Ptr() *float64 { // CoerceToInt64 casts the number to int64. May result in // data/precision loss. -func (n *Number) CoerceToInt64(kind NumberKind) int64 { +func (n *Number) CoerceToInt64(kind Kind) int64 { switch kind { - case Int64NumberKind: + case Int64Kind: return n.AsInt64() - case Float64NumberKind: + case Float64Kind: return int64(n.AsFloat64()) default: // you get what you deserve @@ -196,11 +194,11 @@ func (n *Number) CoerceToInt64(kind NumberKind) int64 { // CoerceToFloat64 casts the number to float64. May result in // data/precision loss. -func (n *Number) CoerceToFloat64(kind NumberKind) float64 { +func (n *Number) CoerceToFloat64(kind Kind) float64 { switch kind { - case Int64NumberKind: + case Int64Kind: return float64(n.AsInt64()) - case Float64NumberKind: + case Float64Kind: return n.AsFloat64() default: // you get what you deserve @@ -330,18 +328,18 @@ func (n *Number) SwapFloat64Atomic(f float64) float64 { // AddNumber assumes that this and the passed number are of the passed // kind and adds the passed number to this number. -func (n *Number) AddNumber(kind NumberKind, nn Number) { +func (n *Number) AddNumber(kind Kind, nn Number) { switch kind { - case Int64NumberKind: + case Int64Kind: n.AddInt64(nn.AsInt64()) - case Float64NumberKind: + case Float64Kind: n.AddFloat64(nn.AsFloat64()) } } // AddRaw assumes that this number and the passed raw value are of the // passed kind and adds the passed raw value to this number. -func (n *Number) AddRaw(kind NumberKind, r uint64) { +func (n *Number) AddRaw(kind Kind, r uint64) { n.AddNumber(kind, NewNumberFromRaw(r)) } @@ -361,11 +359,11 @@ func (n *Number) AddFloat64(f float64) { // AddNumberAtomic assumes that this and the passed number are of the // passed kind and adds the passed number to this number atomically. -func (n *Number) AddNumberAtomic(kind NumberKind, nn Number) { +func (n *Number) AddNumberAtomic(kind Kind, nn Number) { switch kind { - case Int64NumberKind: + case Int64Kind: n.AddInt64Atomic(nn.AsInt64()) - case Float64NumberKind: + case Float64Kind: n.AddFloat64Atomic(nn.AsFloat64()) } } @@ -373,7 +371,7 @@ func (n *Number) AddNumberAtomic(kind NumberKind, nn Number) { // AddRawAtomic assumes that this number and the passed raw value are // of the passed kind and adds the passed raw value to this number // atomically. -func (n *Number) AddRawAtomic(kind NumberKind, r uint64) { +func (n *Number) AddRawAtomic(kind Kind, r uint64) { n.AddNumberAtomic(kind, NewNumberFromRaw(r)) } @@ -429,11 +427,11 @@ func (n *Number) CompareAndSwapFloat64(of, nf float64) bool { // 0 if the numbers are equal // -1 if the subject `n` is less than the argument `nn` // +1 if the subject `n` is greater than the argument `nn` -func (n *Number) CompareNumber(kind NumberKind, nn Number) int { +func (n *Number) CompareNumber(kind Kind, nn Number) int { switch kind { - case Int64NumberKind: + case Int64Kind: return n.CompareInt64(nn.AsInt64()) - case Float64NumberKind: + case Float64Kind: return n.CompareFloat64(nn.AsFloat64()) default: // you get what you deserve @@ -443,7 +441,7 @@ func (n *Number) CompareNumber(kind NumberKind, nn Number) int { // CompareRaw compares two numbers, where one is input as a raw // uint64, interpreting both values as a `kind` of number. -func (n *Number) CompareRaw(kind NumberKind, r uint64) int { +func (n *Number) CompareRaw(kind Kind, r uint64) int { return n.CompareNumber(kind, NewNumberFromRaw(r)) } @@ -482,17 +480,17 @@ func (n *Number) CompareFloat64(f float64) int { // - relations to zero // IsPositive returns true if the actual value is greater than zero. -func (n *Number) IsPositive(kind NumberKind) bool { +func (n *Number) IsPositive(kind Kind) bool { return n.compareWithZero(kind) > 0 } // IsNegative returns true if the actual value is less than zero. -func (n *Number) IsNegative(kind NumberKind) bool { +func (n *Number) IsNegative(kind Kind) bool { return n.compareWithZero(kind) < 0 } // IsZero returns true if the actual value is equal to zero. -func (n *Number) IsZero(kind NumberKind) bool { +func (n *Number) IsZero(kind Kind) bool { return n.compareWithZero(kind) == 0 } @@ -501,11 +499,11 @@ func (n *Number) IsZero(kind NumberKind) bool { // Emit returns a string representation of the raw value of the // Number. A %d is used for integral values, %f for floating point // values. -func (n *Number) Emit(kind NumberKind) string { +func (n *Number) Emit(kind Kind) string { switch kind { - case Int64NumberKind: + case Int64Kind: return fmt.Sprintf("%d", n.AsInt64()) - case Float64NumberKind: + case Float64Kind: return fmt.Sprintf("%f", n.AsFloat64()) default: return "" @@ -513,12 +511,12 @@ func (n *Number) Emit(kind NumberKind) string { } // AsInterface returns the number as an interface{}, typically used -// for NumberKind-correct JSON conversion. -func (n *Number) AsInterface(kind NumberKind) interface{} { +// for Kind-correct JSON conversion. +func (n *Number) AsInterface(kind Kind) interface{} { switch kind { - case Int64NumberKind: + case Int64Kind: return n.AsInt64() - case Float64NumberKind: + case Float64Kind: return n.AsFloat64() default: return math.NaN() @@ -527,11 +525,11 @@ func (n *Number) AsInterface(kind NumberKind) interface{} { // - private stuff -func (n *Number) compareWithZero(kind NumberKind) int { +func (n *Number) compareWithZero(kind Kind) int { switch kind { - case Int64NumberKind: + case Int64Kind: return n.CompareInt64(0) - case Float64NumberKind: + case Float64Kind: return n.CompareFloat64(0.) default: // you get what you deserve diff --git a/vendor/go.opentelemetry.io/otel/api/propagation/doc.go b/vendor/go.opentelemetry.io/otel/metric/registry/doc.go similarity index 56% rename from vendor/go.opentelemetry.io/otel/api/propagation/doc.go rename to vendor/go.opentelemetry.io/otel/metric/registry/doc.go index d2839f5be..a53ba4554 100644 --- a/vendor/go.opentelemetry.io/otel/api/propagation/doc.go +++ b/vendor/go.opentelemetry.io/otel/metric/registry/doc.go @@ -12,5 +12,13 @@ // See the License for the specific language governing permissions and // limitations under the License. -// Package propagation contains interface definition for HTTP propagators. -package propagation // import "go.opentelemetry.io/otel/api/propagation" +/* +Package registry provides a non-standalone implementation of +MeterProvider that adds uniqueness checking for instrument descriptors +on top of other MeterProvider it wraps. + +This package is currently in a pre-GA phase. Backwards incompatible changes +may be introduced in subsequent minor version releases as we work to track the +evolving OpenTelemetry specification and user feedback. +*/ +package registry // import "go.opentelemetry.io/otel/metric/registry" diff --git a/vendor/go.opentelemetry.io/otel/api/metric/registry/registry.go b/vendor/go.opentelemetry.io/otel/metric/registry/registry.go similarity index 83% rename from vendor/go.opentelemetry.io/otel/api/metric/registry/registry.go rename to vendor/go.opentelemetry.io/otel/metric/registry/registry.go index 16b6883a9..0a42a0fdf 100644 --- a/vendor/go.opentelemetry.io/otel/api/metric/registry/registry.go +++ b/vendor/go.opentelemetry.io/otel/metric/registry/registry.go @@ -12,23 +12,23 @@ // See the License for the specific language governing permissions and // limitations under the License. -package registry // import "go.opentelemetry.io/otel/api/metric/registry" +package registry // import "go.opentelemetry.io/otel/metric/registry" import ( "context" "fmt" "sync" - "go.opentelemetry.io/otel/api/metric" - "go.opentelemetry.io/otel/label" + "go.opentelemetry.io/otel/attribute" + "go.opentelemetry.io/otel/metric" ) -// Provider is a standard metric.Provider for wrapping `MeterImpl` -type Provider struct { +// MeterProvider is a standard MeterProvider for wrapping `MeterImpl` +type MeterProvider struct { impl metric.MeterImpl } -var _ metric.Provider = (*Provider)(nil) +var _ metric.MeterProvider = (*MeterProvider)(nil) // uniqueInstrumentMeterImpl implements the metric.MeterImpl interface, adding // uniqueness checking for instrument descriptors. Use NewUniqueInstrumentMeter @@ -47,23 +47,23 @@ type key struct { InstrumentationVersion string } -// NewProvider returns a new provider that implements instrument +// NewMeterProvider returns a new provider that implements instrument // name-uniqueness checking. -func NewProvider(impl metric.MeterImpl) *Provider { - return &Provider{ +func NewMeterProvider(impl metric.MeterImpl) *MeterProvider { + return &MeterProvider{ impl: NewUniqueInstrumentMeterImpl(impl), } } -// Meter implements metric.Provider. -func (p *Provider) Meter(instrumentationName string, opts ...metric.MeterOption) metric.Meter { +// Meter implements MeterProvider. +func (p *MeterProvider) Meter(instrumentationName string, opts ...metric.MeterOption) metric.Meter { return metric.WrapMeterImpl(p.impl, instrumentationName, opts...) } // ErrMetricKindMismatch is the standard error for mismatched metric // instrument definitions. var ErrMetricKindMismatch = fmt.Errorf( - "A metric was already registered by this name with another kind or number type") + "a metric was already registered by this name with another kind or number type") // NewUniqueInstrumentMeterImpl returns a wrapped metric.MeterImpl with // the addition of uniqueness checking. @@ -75,7 +75,7 @@ func NewUniqueInstrumentMeterImpl(impl metric.MeterImpl) metric.MeterImpl { } // RecordBatch implements metric.MeterImpl. -func (u *uniqueInstrumentMeterImpl) RecordBatch(ctx context.Context, labels []label.KeyValue, ms ...metric.Measurement) { +func (u *uniqueInstrumentMeterImpl) RecordBatch(ctx context.Context, labels []attribute.KeyValue, ms ...metric.Measurement) { u.impl.RecordBatch(ctx, labels, ms...) } @@ -90,19 +90,19 @@ func keyOf(descriptor metric.Descriptor) key { // NewMetricKindMismatchError formats an error that describes a // mismatched metric instrument definition. func NewMetricKindMismatchError(desc metric.Descriptor) error { - return fmt.Errorf("Metric was %s (%s %s)registered as a %s %s: %w", + return fmt.Errorf("metric was %s (%s %s)registered as a %s %s: %w", desc.Name(), desc.InstrumentationName(), desc.InstrumentationVersion(), desc.NumberKind(), - desc.MetricKind(), + desc.InstrumentKind(), ErrMetricKindMismatch) } // Compatible determines whether two metric.Descriptors are considered // the same for the purpose of uniqueness checking. func Compatible(candidate, existing metric.Descriptor) bool { - return candidate.MetricKind() == existing.MetricKind() && + return candidate.InstrumentKind() == existing.InstrumentKind() && candidate.NumberKind() == existing.NumberKind() } diff --git a/vendor/go.opentelemetry.io/otel/pre_release.sh b/vendor/go.opentelemetry.io/otel/pre_release.sh index e09924b77..0de22169c 100644 --- a/vendor/go.opentelemetry.io/otel/pre_release.sh +++ b/vendor/go.opentelemetry.io/otel/pre_release.sh @@ -54,7 +54,7 @@ if [[ ${TAG_FOUND} = ${TAG} ]] ; then exit -1 fi -# Get version for sdk/opentelemetry.go +# Get version for version.go OTEL_VERSION=$(echo "${TAG}" | grep -o '^v[0-9]\+\.[0-9]\+\.[0-9]\+') # Strip leading v OTEL_VERSION="${OTEL_VERSION#v}" @@ -68,13 +68,13 @@ if ! git diff --quiet; then \ exit 1 fi -# Update sdk/opentelemetry.go -cp ./sdk/opentelemetry.go ./sdk/opentelemetry.go.bak -sed "s/\(return \"\)[0-9]*\.[0-9]*\.[0-9]*\"/\1${OTEL_VERSION}\"/" ./sdk/opentelemetry.go.bak >./sdk/opentelemetry.go -rm -f ./sdk/opentelemetry.go.bak +# Update version.go +cp ./version.go ./version.go.bak +sed "s/\(return \"\)[0-9]*\.[0-9]*\.[0-9]*\"/\1${OTEL_VERSION}\"/" ./version.go.bak >./version.go +rm -f ./version.go.bak # Update go.mod -git checkout -b pre_release_${TAG} master +git checkout -b pre_release_${TAG} main PACKAGE_DIRS=$(find . -mindepth 2 -type f -name 'go.mod' -exec dirname {} \; | egrep -v 'tools' | sed 's/^\.\///' | sort) for dir in $PACKAGE_DIRS; do @@ -91,5 +91,5 @@ git add . make ci git commit -m "Prepare for releasing $TAG" -printf "Now run following to verify the changes.\ngit diff master\n" +printf "Now run following to verify the changes.\ngit diff main\n" printf "\nThen push the changes to upstream\n" diff --git a/vendor/go.opentelemetry.io/otel/propagation.go b/vendor/go.opentelemetry.io/otel/propagation.go new file mode 100644 index 000000000..d29aaa32c --- /dev/null +++ b/vendor/go.opentelemetry.io/otel/propagation.go @@ -0,0 +1,31 @@ +// 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 otel // import "go.opentelemetry.io/otel" + +import ( + "go.opentelemetry.io/otel/internal/global" + "go.opentelemetry.io/otel/propagation" +) + +// GetTextMapPropagator returns the global TextMapPropagator. If none has been +// set, a No-Op TextMapPropagator is returned. +func GetTextMapPropagator() propagation.TextMapPropagator { + return global.TextMapPropagator() +} + +// SetTextMapPropagator sets propagator as the global TextMapPropagator. +func SetTextMapPropagator(propagator propagation.TextMapPropagator) { + global.SetTextMapPropagator(propagator) +} diff --git a/vendor/go.opentelemetry.io/otel/api/correlation/correlation_context_propagator.go b/vendor/go.opentelemetry.io/otel/propagation/baggage.go similarity index 53% rename from vendor/go.opentelemetry.io/otel/api/correlation/correlation_context_propagator.go rename to vendor/go.opentelemetry.io/otel/propagation/baggage.go index bf93e701f..bc7619189 100644 --- a/vendor/go.opentelemetry.io/otel/api/correlation/correlation_context_propagator.go +++ b/vendor/go.opentelemetry.io/otel/propagation/baggage.go @@ -12,40 +12,33 @@ // See the License for the specific language governing permissions and // limitations under the License. -package correlation +package propagation // import "go.opentelemetry.io/otel/propagation" import ( "context" "net/url" "strings" - "go.opentelemetry.io/otel/api/propagation" - "go.opentelemetry.io/otel/label" + "go.opentelemetry.io/otel/attribute" + "go.opentelemetry.io/otel/internal/baggage" ) -// Temporary header name until W3C finalizes format. -// https://github.com/open-telemetry/opentelemetry-specification/blob/18b2752ebe6c7f0cdd8c7b2bcbdceb0ae3f5ad95/specification/correlationcontext/api.md#header-name -const correlationContextHeader = "otcorrelations" +const baggageHeader = "baggage" -// CorrelationContext propagates Key:Values in W3C CorrelationContext -// format. -// nolint:golint -type CorrelationContext struct{} - -var _ propagation.HTTPPropagator = CorrelationContext{} +// Baggage is a propagator that supports the W3C Baggage format. +// +// This propagates user-defined baggage associated with a trace. The complete +// specification is defined at https://w3c.github.io/baggage/. +type Baggage struct{} -// DefaultHTTPPropagator returns the default context correlation HTTP -// propagator. -func DefaultHTTPPropagator() propagation.HTTPPropagator { - return CorrelationContext{} -} +var _ TextMapPropagator = Baggage{} -// Inject implements HTTPInjector. -func (CorrelationContext) Inject(ctx context.Context, supplier propagation.HTTPSupplier) { - correlationCtx := MapFromContext(ctx) +// Inject sets baggage key-values from ctx into the carrier. +func (b Baggage) Inject(ctx context.Context, carrier TextMapCarrier) { + baggageMap := baggage.MapFromContext(ctx) firstIter := true var headerValueBuilder strings.Builder - correlationCtx.Foreach(func(kv label.KeyValue) bool { + baggageMap.Foreach(func(kv attribute.KeyValue) bool { if !firstIter { headerValueBuilder.WriteRune(',') } @@ -57,21 +50,21 @@ func (CorrelationContext) Inject(ctx context.Context, supplier propagation.HTTPS }) if headerValueBuilder.Len() > 0 { headerString := headerValueBuilder.String() - supplier.Set(correlationContextHeader, headerString) + carrier.Set(baggageHeader, headerString) } } -// Extract implements HTTPExtractor. -func (CorrelationContext) Extract(ctx context.Context, supplier propagation.HTTPSupplier) context.Context { - correlationContext := supplier.Get(correlationContextHeader) - if correlationContext == "" { - return ctx +// Extract returns a copy of parent with the baggage from the carrier added. +func (b Baggage) Extract(parent context.Context, carrier TextMapCarrier) context.Context { + bVal := carrier.Get(baggageHeader) + if bVal == "" { + return parent } - contextValues := strings.Split(correlationContext, ",") - keyValues := make([]label.KeyValue, 0, len(contextValues)) - for _, contextValue := range contextValues { - valueAndProps := strings.Split(contextValue, ";") + baggageValues := strings.Split(bVal, ",") + keyValues := make([]attribute.KeyValue, 0, len(baggageValues)) + for _, baggageValue := range baggageValues { + valueAndProps := strings.Split(baggageValue, ";") if len(valueAndProps) < 1 { continue } @@ -99,20 +92,20 @@ func (CorrelationContext) Extract(ctx context.Context, supplier propagation.HTTP trimmedValueWithProps.WriteString(prop) } - keyValues = append(keyValues, label.String(trimmedName, trimmedValueWithProps.String())) + keyValues = append(keyValues, attribute.String(trimmedName, trimmedValueWithProps.String())) } if len(keyValues) > 0 { // Only update the context if valid values were found - return ContextWithMap(ctx, NewMap(MapUpdate{ + return baggage.ContextWithMap(parent, baggage.NewMap(baggage.MapUpdate{ MultiKV: keyValues, })) } - return ctx + return parent } -// GetAllKeys implements HTTPPropagator. -func (CorrelationContext) GetAllKeys() []string { - return []string{correlationContextHeader} +// Fields returns the keys who's values are set with Inject. +func (b Baggage) Fields() []string { + return []string{baggageHeader} } diff --git a/vendor/go.opentelemetry.io/otel/propagation/doc.go b/vendor/go.opentelemetry.io/otel/propagation/doc.go new file mode 100644 index 000000000..89573f1ba --- /dev/null +++ b/vendor/go.opentelemetry.io/otel/propagation/doc.go @@ -0,0 +1,28 @@ +// 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 propagation contains OpenTelemetry context propagators. + +This package is currently in a pre-GA phase. Backwards incompatible changes +may be introduced in subsequent minor version releases as we work to track the +evolving OpenTelemetry specification and user feedback. + +OpenTelemetry propagators are used to extract and inject context data from and +into messages exchanged by applications. The propagator supported by this +package is the W3C Trace Context encoding +(https://www.w3.org/TR/trace-context/), and W3C Baggage +(https://w3c.github.io/baggage/). +*/ +package propagation // import "go.opentelemetry.io/otel/propagation" diff --git a/vendor/go.opentelemetry.io/otel/propagation/propagation.go b/vendor/go.opentelemetry.io/otel/propagation/propagation.go new file mode 100644 index 000000000..9cfeb347a --- /dev/null +++ b/vendor/go.opentelemetry.io/otel/propagation/propagation.go @@ -0,0 +1,105 @@ +// 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 propagation // import "go.opentelemetry.io/otel/propagation" + +import ( + "context" + "net/http" +) + +// TextMapCarrier is the storage medium used by a TextMapPropagator. +type TextMapCarrier interface { + // Get returns the value associated with the passed key. + Get(key string) string + // Set stores the key-value pair. + Set(key string, value string) + // Keys lists the keys stored in this carrier. + Keys() []string +} + +// HeaderCarrier adapts http.Header to satisfy the TextMapCarrier interface. +type HeaderCarrier http.Header + +// Get returns the value associated with the passed key. +func (hc HeaderCarrier) Get(key string) string { + return http.Header(hc).Get(key) +} + +// Set stores the key-value pair. +func (hc HeaderCarrier) Set(key string, value string) { + http.Header(hc).Set(key, value) +} + +// Keys lists the keys stored in this carrier. +func (hc HeaderCarrier) Keys() []string { + keys := make([]string, 0, len(hc)) + for k := range hc { + keys = append(keys, k) + } + return keys +} + +// TextMapPropagator propagates cross-cutting concerns as key-value text +// pairs within a carrier that travels in-band across process boundaries. +type TextMapPropagator interface { + // Inject set cross-cutting concerns from the Context into the carrier. + Inject(ctx context.Context, carrier TextMapCarrier) + // Extract reads cross-cutting concerns from the carrier into a Context. + Extract(ctx context.Context, carrier TextMapCarrier) context.Context + // Fields returns the keys who's values are set with Inject. + Fields() []string +} + +type compositeTextMapPropagator []TextMapPropagator + +func (p compositeTextMapPropagator) Inject(ctx context.Context, carrier TextMapCarrier) { + for _, i := range p { + i.Inject(ctx, carrier) + } +} + +func (p compositeTextMapPropagator) Extract(ctx context.Context, carrier TextMapCarrier) context.Context { + for _, i := range p { + ctx = i.Extract(ctx, carrier) + } + return ctx +} + +func (p compositeTextMapPropagator) Fields() []string { + unique := make(map[string]struct{}) + for _, i := range p { + for _, k := range i.Fields() { + unique[k] = struct{}{} + } + } + + fields := make([]string, 0, len(unique)) + for k := range unique { + fields = append(fields, k) + } + return fields +} + +// NewCompositeTextMapPropagator returns a unified TextMapPropagator from the +// group of passed TextMapPropagator. This allows different cross-cutting +// concerns to be propagates in a unified manner. +// +// The returned TextMapPropagator will inject and extract cross-cutting +// concerns in the order the TextMapPropagators were provided. Additionally, +// the Fields method will return a de-duplicated slice of the keys that are +// set with the Inject method. +func NewCompositeTextMapPropagator(p ...TextMapPropagator) TextMapPropagator { + return compositeTextMapPropagator(p) +} diff --git a/vendor/go.opentelemetry.io/otel/propagation/trace_context.go b/vendor/go.opentelemetry.io/otel/propagation/trace_context.go new file mode 100644 index 000000000..fc52975cf --- /dev/null +++ b/vendor/go.opentelemetry.io/otel/propagation/trace_context.go @@ -0,0 +1,169 @@ +// 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 propagation // import "go.opentelemetry.io/otel/propagation" + +import ( + "context" + "encoding/hex" + "fmt" + "regexp" + "strings" + + "go.opentelemetry.io/otel/attribute" + "go.opentelemetry.io/otel/trace" +) + +const ( + supportedVersion = 0 + maxVersion = 254 + traceparentHeader = "traceparent" + tracestateHeader = "tracestate" +) + +// TraceContext is a propagator that supports the W3C Trace Context format +// (https://www.w3.org/TR/trace-context/) +// +// This propagator will propagate the traceparent and tracestate headers to +// guarantee traces are not broken. It is up to the users of this propagator +// to choose if they want to participate in a trace by modifying the +// traceparent header and relevant parts of the tracestate header containing +// their proprietary information. +type TraceContext struct{} + +var _ TextMapPropagator = TraceContext{} +var traceCtxRegExp = regexp.MustCompile("^(?P[0-9a-f]{2})-(?P[a-f0-9]{32})-(?P[a-f0-9]{16})-(?P[a-f0-9]{2})(?:-.*)?$") + +// Inject set tracecontext from the Context into the carrier. +func (tc TraceContext) Inject(ctx context.Context, carrier TextMapCarrier) { + sc := trace.SpanContextFromContext(ctx) + if !sc.IsValid() { + return + } + + carrier.Set(tracestateHeader, sc.TraceState.String()) + + h := fmt.Sprintf("%.2x-%s-%s-%.2x", + supportedVersion, + sc.TraceID, + sc.SpanID, + sc.TraceFlags&trace.FlagsSampled) + carrier.Set(traceparentHeader, h) +} + +// Extract reads tracecontext from the carrier into a returned Context. +func (tc TraceContext) Extract(ctx context.Context, carrier TextMapCarrier) context.Context { + sc := tc.extract(carrier) + if !sc.IsValid() { + return ctx + } + return trace.ContextWithRemoteSpanContext(ctx, sc) +} + +func (tc TraceContext) extract(carrier TextMapCarrier) trace.SpanContext { + h := carrier.Get(traceparentHeader) + if h == "" { + return trace.SpanContext{} + } + + matches := traceCtxRegExp.FindStringSubmatch(h) + + if len(matches) == 0 { + return trace.SpanContext{} + } + + if len(matches) < 5 { // four subgroups plus the overall match + return trace.SpanContext{} + } + + if len(matches[1]) != 2 { + return trace.SpanContext{} + } + ver, err := hex.DecodeString(matches[1]) + if err != nil { + return trace.SpanContext{} + } + version := int(ver[0]) + if version > maxVersion { + return trace.SpanContext{} + } + + if version == 0 && len(matches) != 5 { // four subgroups plus the overall match + return trace.SpanContext{} + } + + if len(matches[2]) != 32 { + return trace.SpanContext{} + } + + var sc trace.SpanContext + + sc.TraceID, err = trace.TraceIDFromHex(matches[2][:32]) + if err != nil { + return trace.SpanContext{} + } + + if len(matches[3]) != 16 { + return trace.SpanContext{} + } + sc.SpanID, err = trace.SpanIDFromHex(matches[3]) + if err != nil { + return trace.SpanContext{} + } + + if len(matches[4]) != 2 { + return trace.SpanContext{} + } + opts, err := hex.DecodeString(matches[4]) + if err != nil || len(opts) < 1 || (version == 0 && opts[0] > 2) { + return trace.SpanContext{} + } + // Clear all flags other than the trace-context supported sampling bit. + sc.TraceFlags = opts[0] & trace.FlagsSampled + + sc.TraceState = parseTraceState(carrier.Get(tracestateHeader)) + + if !sc.IsValid() { + return trace.SpanContext{} + } + + return sc +} + +// Fields returns the keys who's values are set with Inject. +func (tc TraceContext) Fields() []string { + return []string{traceparentHeader, tracestateHeader} +} + +func parseTraceState(in string) trace.TraceState { + if in == "" { + return trace.TraceState{} + } + + kvs := []attribute.KeyValue{} + for _, entry := range strings.Split(in, ",") { + parts := strings.SplitN(entry, "=", 2) + if len(parts) != 2 { + // Parse failure, abort! + return trace.TraceState{} + } + kvs = append(kvs, attribute.String(parts[0], parts[1])) + } + + // Ignoring error here as "failure to parse tracestate MUST NOT + // affect the parsing of traceparent." + // https://www.w3.org/TR/trace-context/#tracestate-header + ts, _ := trace.TraceStateFromKeyValues(kvs...) + return ts +} diff --git a/vendor/go.opentelemetry.io/otel/tag.sh b/vendor/go.opentelemetry.io/otel/tag.sh index 2a0ef1d26..70767c703 100644 --- a/vendor/go.opentelemetry.io/otel/tag.sh +++ b/vendor/go.opentelemetry.io/otel/tag.sh @@ -17,7 +17,7 @@ readonly PROGNAME=$(basename "$0") readonly PROGDIR=$(readlink -m "$(dirname "$0")") -readonly EXCLUDE_PACKAGES="tools" +readonly EXCLUDE_PACKAGES="internal/tools" readonly SEMVER_REGEX="v(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)(\\-[0-9A-Za-z-]+(\\.[0-9A-Za-z-]+)*)?(\\+[0-9A-Za-z-]+(\\.[0-9A-Za-z-]+)*)?" usage() { diff --git a/vendor/go.opentelemetry.io/otel/api/global/trace.go b/vendor/go.opentelemetry.io/otel/trace.go similarity index 58% rename from vendor/go.opentelemetry.io/otel/api/global/trace.go rename to vendor/go.opentelemetry.io/otel/trace.go index 5c23325b7..1d5ffb8ea 100644 --- a/vendor/go.opentelemetry.io/otel/api/global/trace.go +++ b/vendor/go.opentelemetry.io/otel/trace.go @@ -12,33 +12,33 @@ // See the License for the specific language governing permissions and // limitations under the License. -package global +package otel // import "go.opentelemetry.io/otel" import ( - "go.opentelemetry.io/otel/api/global/internal" - "go.opentelemetry.io/otel/api/trace" + "go.opentelemetry.io/otel/internal/global" + "go.opentelemetry.io/otel/trace" ) // Tracer creates a named tracer that implements Tracer interface. // If the name is an empty string then provider uses default name. // -// This is short for TraceProvider().Tracer(name) +// This is short for GetTracerProvider().Tracer(name) func Tracer(name string) trace.Tracer { - return TraceProvider().Tracer(name) + return GetTracerProvider().Tracer(name) } -// TraceProvider returns the registered global trace provider. -// If none is registered then an instance of trace.NoopProvider is returned. +// GetTracerProvider returns the registered global trace provider. +// If none is registered then an instance of NoopTracerProvider is returned. // // Use the trace provider to create a named tracer. E.g. -// tracer := global.TraceProvider().Tracer("example.com/foo") +// tracer := global.GetTracerProvider().Tracer("example.com/foo") // or // tracer := global.Tracer("example.com/foo") -func TraceProvider() trace.Provider { - return internal.TraceProvider() +func GetTracerProvider() trace.TracerProvider { + return global.TracerProvider() } -// SetTraceProvider registers `tp` as the global trace provider. -func SetTraceProvider(tp trace.Provider) { - internal.SetTraceProvider(tp) +// SetTracerProvider registers `tp` as the global trace provider. +func SetTracerProvider(tp trace.TracerProvider) { + global.SetTracerProvider(tp) } diff --git a/vendor/go.opentelemetry.io/otel/trace/LICENSE b/vendor/go.opentelemetry.io/otel/trace/LICENSE new file mode 100644 index 000000000..261eeb9e9 --- /dev/null +++ b/vendor/go.opentelemetry.io/otel/trace/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/otel/trace/config.go b/vendor/go.opentelemetry.io/otel/trace/config.go new file mode 100644 index 000000000..33335e7ac --- /dev/null +++ b/vendor/go.opentelemetry.io/otel/trace/config.go @@ -0,0 +1,219 @@ +// 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 trace + +import ( + "time" + + "go.opentelemetry.io/otel/attribute" +) + +// TracerConfig is a group of options for a Tracer. +type TracerConfig struct { + // InstrumentationVersion is the version of the library providing + // instrumentation. + InstrumentationVersion string +} + +// NewTracerConfig applies all the options to a returned TracerConfig. +func NewTracerConfig(options ...TracerOption) *TracerConfig { + config := new(TracerConfig) + for _, option := range options { + option.ApplyTracer(config) + } + return config +} + +// TracerOption applies an option to a TracerConfig. +type TracerOption interface { + ApplyTracer(*TracerConfig) + + // A private method to prevent users implementing the + // interface and so future additions to it will not + // violate compatibility. + private() +} + +// SpanConfig is a group of options for a Span. +type SpanConfig struct { + // Attributes describe the associated qualities of a Span. + Attributes []attribute.KeyValue + // Timestamp is a time in a Span life-cycle. + Timestamp time.Time + // Links are the associations a Span has with other Spans. + Links []Link + // Record is the recording state of a Span. + Record bool + // NewRoot identifies a Span as the root Span for a new trace. This is + // commonly used when an existing trace crosses trust boundaries and the + // remote parent span context should be ignored for security. + NewRoot bool + // SpanKind is the role a Span has in a trace. + SpanKind SpanKind +} + +// NewSpanConfig applies all the options to a returned SpanConfig. +// No validation is performed on the returned SpanConfig (e.g. no uniqueness +// checking or bounding of data), it is left to the SDK to perform this +// action. +func NewSpanConfig(options ...SpanOption) *SpanConfig { + c := new(SpanConfig) + for _, option := range options { + option.ApplySpan(c) + } + return c +} + +// SpanOption applies an option to a SpanConfig. +type SpanOption interface { + ApplySpan(*SpanConfig) + + // A private method to prevent users implementing the + // interface and so future additions to it will not + // violate compatibility. + private() +} + +// NewEventConfig applies all the EventOptions to a returned SpanConfig. If no +// timestamp option is passed, the returned SpanConfig will have a Timestamp +// set to the call time, otherwise no validation is performed on the returned +// SpanConfig. +func NewEventConfig(options ...EventOption) *SpanConfig { + c := new(SpanConfig) + for _, option := range options { + option.ApplyEvent(c) + } + if c.Timestamp.IsZero() { + c.Timestamp = time.Now() + } + return c +} + +// EventOption applies span event options to a SpanConfig. +type EventOption interface { + ApplyEvent(*SpanConfig) + + // A private method to prevent users implementing the + // interface and so future additions to it will not + // violate compatibility. + private() +} + +// LifeCycleOption applies span life-cycle options to a SpanConfig. These +// options set values releated to events in a spans life-cycle like starting, +// ending, experiencing an error and other user defined notable events. +type LifeCycleOption interface { + SpanOption + EventOption +} + +type attributeSpanOption []attribute.KeyValue + +func (o attributeSpanOption) ApplySpan(c *SpanConfig) { o.apply(c) } +func (o attributeSpanOption) ApplyEvent(c *SpanConfig) { o.apply(c) } +func (attributeSpanOption) private() {} +func (o attributeSpanOption) apply(c *SpanConfig) { + c.Attributes = append(c.Attributes, []attribute.KeyValue(o)...) +} + +// WithAttributes adds the attributes related to a span life-cycle event. +// These attributes are used to describe the work a Span represents when this +// option is provided to a Span's start or end events. Otherwise, these +// attributes provide additional information about the event being recorded +// (e.g. error, state change, processing progress, system event). +// +// If multiple of these options are passed the attributes of each successive +// option will extend the attributes instead of overwriting. There is no +// guarantee of uniqueness in the resulting attributes. +func WithAttributes(attributes ...attribute.KeyValue) LifeCycleOption { + return attributeSpanOption(attributes) +} + +type timestampSpanOption time.Time + +func (o timestampSpanOption) ApplySpan(c *SpanConfig) { o.apply(c) } +func (o timestampSpanOption) ApplyEvent(c *SpanConfig) { o.apply(c) } +func (timestampSpanOption) private() {} +func (o timestampSpanOption) apply(c *SpanConfig) { c.Timestamp = time.Time(o) } + +// WithTimestamp sets the time of a Span life-cycle moment (e.g. started, +// stopped, errored). +func WithTimestamp(t time.Time) LifeCycleOption { + return timestampSpanOption(t) +} + +type linksSpanOption []Link + +func (o linksSpanOption) ApplySpan(c *SpanConfig) { c.Links = append(c.Links, []Link(o)...) } +func (linksSpanOption) private() {} + +// WithLinks adds links to a Span. The links are added to the existing Span +// links, i.e. this does not overwrite. +func WithLinks(links ...Link) SpanOption { + return linksSpanOption(links) +} + +type recordSpanOption bool + +func (o recordSpanOption) ApplySpan(c *SpanConfig) { c.Record = bool(o) } +func (recordSpanOption) private() {} + +// WithRecord specifies that the span should be recorded. It is important to +// note that implementations may override this option, i.e. if the span is a +// child of an un-sampled trace. +func WithRecord() SpanOption { + return recordSpanOption(true) +} + +type newRootSpanOption bool + +func (o newRootSpanOption) ApplySpan(c *SpanConfig) { c.NewRoot = bool(o) } +func (newRootSpanOption) private() {} + +// WithNewRoot specifies that the Span should be treated as a root Span. Any +// existing parent span context will be ignored when defining the Span's trace +// identifiers. +func WithNewRoot() SpanOption { + return newRootSpanOption(true) +} + +type spanKindSpanOption SpanKind + +func (o spanKindSpanOption) ApplySpan(c *SpanConfig) { c.SpanKind = SpanKind(o) } +func (o spanKindSpanOption) private() {} + +// WithSpanKind sets the SpanKind of a Span. +func WithSpanKind(kind SpanKind) SpanOption { + return spanKindSpanOption(kind) +} + +// InstrumentationOption is an interface for applying instrumentation specific +// options. +type InstrumentationOption interface { + TracerOption +} + +// WithInstrumentationVersion sets the instrumentation version. +func WithInstrumentationVersion(version string) InstrumentationOption { + return instrumentationVersionOption(version) +} + +type instrumentationVersionOption string + +func (i instrumentationVersionOption) ApplyTracer(config *TracerConfig) { + config.InstrumentationVersion = string(i) +} + +func (instrumentationVersionOption) private() {} diff --git a/vendor/go.opentelemetry.io/otel/trace/doc.go b/vendor/go.opentelemetry.io/otel/trace/doc.go new file mode 100644 index 000000000..c962f3bc6 --- /dev/null +++ b/vendor/go.opentelemetry.io/otel/trace/doc.go @@ -0,0 +1,70 @@ +// 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 trace provides an implementation of the tracing part of the +OpenTelemetry API. + +This package is currently in a pre-GA phase. Backwards incompatible changes +may be introduced in subsequent minor version releases as we work to track the +evolving OpenTelemetry specification and user feedback. + +To participate in distributed traces a Span needs to be created for the +operation being performed as part of a traced workflow. It its simplest form: + + var tracer trace.Tracer + + func init() { + tracer = otel.Tracer("instrumentation/package/name") + } + + func operation(ctx context.Context) { + var span trace.Span + ctx, span = tracer.Start(ctx, "operation") + defer span.End() + // ... + } + +A Tracer is unique to the instrumentation and is used to create Spans. +Instrumentation should be designed to accept a TracerProvider from which it +can create its own unique Tracer. Alternatively, the registered global +TracerProvider from the go.opentelemetry.io/otel package can be used as +a default. + + const ( + name = "instrumentation/package/name" + version = "0.1.0" + ) + + type Instrumentation struct { + tracer trace.Tracer + } + + func NewInstrumentation(tp trace.TracerProvider) *Instrumentation { + if tp == nil { + tp = otel.TracerProvider() + } + return &Instrumentation{ + tracer: tp.Tracer(name, trace.WithInstrumentationVersion(version)), + } + } + + func operation(ctx context.Context, inst *Instrumentation) { + var span trace.Span + ctx, span = inst.tracer.Start(ctx, "operation") + defer span.End() + // ... + } +*/ +package trace // import "go.opentelemetry.io/otel/trace" diff --git a/vendor/go.opentelemetry.io/otel/trace/go.mod b/vendor/go.opentelemetry.io/otel/trace/go.mod new file mode 100644 index 000000000..f59852720 --- /dev/null +++ b/vendor/go.opentelemetry.io/otel/trace/go.mod @@ -0,0 +1,52 @@ +module go.opentelemetry.io/otel/trace + +go 1.14 + +replace go.opentelemetry.io/otel => ../ + +replace go.opentelemetry.io/otel/bridge/opencensus => ../bridge/opencensus + +replace go.opentelemetry.io/otel/bridge/opentracing => ../bridge/opentracing + +replace go.opentelemetry.io/otel/example/jaeger => ../example/jaeger + +replace go.opentelemetry.io/otel/example/namedtracer => ../example/namedtracer + +replace go.opentelemetry.io/otel/example/opencensus => ../example/opencensus + +replace go.opentelemetry.io/otel/example/otel-collector => ../example/otel-collector + +replace go.opentelemetry.io/otel/example/prom-collector => ../example/prom-collector + +replace go.opentelemetry.io/otel/example/prometheus => ../example/prometheus + +replace go.opentelemetry.io/otel/example/zipkin => ../example/zipkin + +replace go.opentelemetry.io/otel/exporters/metric/prometheus => ../exporters/metric/prometheus + +replace go.opentelemetry.io/otel/exporters/otlp => ../exporters/otlp + +replace go.opentelemetry.io/otel/exporters/stdout => ../exporters/stdout + +replace go.opentelemetry.io/otel/exporters/trace/jaeger => ../exporters/trace/jaeger + +replace go.opentelemetry.io/otel/exporters/trace/zipkin => ../exporters/trace/zipkin + +replace go.opentelemetry.io/otel/internal/tools => ../internal/tools + +replace go.opentelemetry.io/otel/metric => ../metric + +replace go.opentelemetry.io/otel/oteltest => ../oteltest + +replace go.opentelemetry.io/otel/sdk => ../sdk + +replace go.opentelemetry.io/otel/sdk/export/metric => ../sdk/export/metric + +replace go.opentelemetry.io/otel/sdk/metric => ../sdk/metric + +replace go.opentelemetry.io/otel/trace => ./ + +require ( + github.com/stretchr/testify v1.7.0 + go.opentelemetry.io/otel v0.18.0 +) diff --git a/vendor/go.opentelemetry.io/otel/trace/go.sum b/vendor/go.opentelemetry.io/otel/trace/go.sum new file mode 100644 index 000000000..99debc273 --- /dev/null +++ b/vendor/go.opentelemetry.io/otel/trace/go.sum @@ -0,0 +1,15 @@ +github.com/davecgh/go-spew v1.1.0 h1:ZDRjVQ15GmhC3fiQ8ni8+OwkZQO4DARzQgrnXU1Liz8= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/google/go-cmp v0.5.4 h1:L8R9j+yAqZuZjsqh/z+F1NCffTKKLShY6zXTItVIZ8M= +github.com/google/go-cmp v0.5.4/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY= +github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543 h1:E7g+9GITq07hpfrRu66IVDexMakfv52eLZ2CXBWiKr4= +golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c h1:dUUwHk2QECo/6vqA44rthZ8ie2QXMNeKRTHCNY2nXvo= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/vendor/go.opentelemetry.io/otel/trace/trace.go b/vendor/go.opentelemetry.io/otel/trace/trace.go new file mode 100644 index 000000000..57ba19432 --- /dev/null +++ b/vendor/go.opentelemetry.io/otel/trace/trace.go @@ -0,0 +1,562 @@ +// 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 trace // import "go.opentelemetry.io/otel/trace" + +import ( + "bytes" + "context" + "encoding/hex" + "encoding/json" + "regexp" + "strings" + "time" + + "go.opentelemetry.io/otel/attribute" + "go.opentelemetry.io/otel/codes" +) + +const ( + // FlagsSampled is a bitmask with the sampled bit set. A SpanContext + // with the sampling bit set means the span is sampled. + FlagsSampled = byte(0x01) + // FlagsDeferred is a bitmask with the deferred bit set. A SpanContext + // with the deferred bit set means the sampling decision has been + // defered to the receiver. + FlagsDeferred = byte(0x02) + // FlagsDebug is a bitmask with the debug bit set. + FlagsDebug = byte(0x04) + + errInvalidHexID errorConst = "trace-id and span-id can only contain [0-9a-f] characters, all lowercase" + + errInvalidTraceIDLength errorConst = "hex encoded trace-id must have length equals to 32" + errNilTraceID errorConst = "trace-id can't be all zero" + + errInvalidSpanIDLength errorConst = "hex encoded span-id must have length equals to 16" + errNilSpanID errorConst = "span-id can't be all zero" + + // based on the W3C Trace Context specification, see https://www.w3.org/TR/trace-context-1/#tracestate-header + traceStateKeyFormat = `[a-z][_0-9a-z\-\*\/]{0,255}` + traceStateKeyFormatWithMultiTenantVendor = `[a-z0-9][_0-9a-z\-\*\/]{0,240}@[a-z][_0-9a-z\-\*\/]{0,13}` + traceStateValueFormat = `[\x20-\x2b\x2d-\x3c\x3e-\x7e]{0,255}[\x21-\x2b\x2d-\x3c\x3e-\x7e]` + + traceStateMaxListMembers = 32 + + errInvalidTraceStateKeyValue errorConst = "provided key or value is not valid according to the" + + " W3C Trace Context specification" + errInvalidTraceStateMembersNumber errorConst = "trace state would exceed the maximum limit of members (32)" + errInvalidTraceStateDuplicate errorConst = "trace state key/value pairs with duplicate keys provided" +) + +type errorConst string + +func (e errorConst) Error() string { + return string(e) +} + +// TraceID is a unique identity of a trace. +// nolint:golint +type TraceID [16]byte + +var nilTraceID TraceID +var _ json.Marshaler = nilTraceID + +// IsValid checks whether the trace TraceID is valid. A valid trace ID does +// not consist of zeros only. +func (t TraceID) IsValid() bool { + return !bytes.Equal(t[:], nilTraceID[:]) +} + +// MarshalJSON implements a custom marshal function to encode TraceID +// as a hex string. +func (t TraceID) MarshalJSON() ([]byte, error) { + return json.Marshal(t.String()) +} + +// String returns the hex string representation form of a TraceID +func (t TraceID) String() string { + return hex.EncodeToString(t[:]) +} + +// SpanID is a unique identity of a span in a trace. +type SpanID [8]byte + +var nilSpanID SpanID +var _ json.Marshaler = nilSpanID + +// IsValid checks whether the SpanID is valid. A valid SpanID does not consist +// of zeros only. +func (s SpanID) IsValid() bool { + return !bytes.Equal(s[:], nilSpanID[:]) +} + +// MarshalJSON implements a custom marshal function to encode SpanID +// as a hex string. +func (s SpanID) MarshalJSON() ([]byte, error) { + return json.Marshal(s.String()) +} + +// String returns the hex string representation form of a SpanID +func (s SpanID) String() string { + return hex.EncodeToString(s[:]) +} + +// TraceIDFromHex returns a TraceID from a hex string if it is compliant with +// the W3C trace-context specification. See more at +// https://www.w3.org/TR/trace-context/#trace-id +// nolint:golint +func TraceIDFromHex(h string) (TraceID, error) { + t := TraceID{} + if len(h) != 32 { + return t, errInvalidTraceIDLength + } + + if err := decodeHex(h, t[:]); err != nil { + return t, err + } + + if !t.IsValid() { + return t, errNilTraceID + } + return t, nil +} + +// SpanIDFromHex returns a SpanID from a hex string if it is compliant +// with the w3c trace-context specification. +// See more at https://www.w3.org/TR/trace-context/#parent-id +func SpanIDFromHex(h string) (SpanID, error) { + s := SpanID{} + if len(h) != 16 { + return s, errInvalidSpanIDLength + } + + if err := decodeHex(h, s[:]); err != nil { + return s, err + } + + if !s.IsValid() { + return s, errNilSpanID + } + return s, nil +} + +func decodeHex(h string, b []byte) error { + for _, r := range h { + switch { + case 'a' <= r && r <= 'f': + continue + case '0' <= r && r <= '9': + continue + default: + return errInvalidHexID + } + } + + decoded, err := hex.DecodeString(h) + if err != nil { + return err + } + + copy(b, decoded) + return nil +} + +// TraceState provides additional vendor-specific trace identification information +// across different distributed tracing systems. It represents an immutable list consisting +// of key/value pairs. There can be a maximum of 32 entries in the list. +// +// Key and value of each list member must be valid according to the W3C Trace Context specification +// (see https://www.w3.org/TR/trace-context-1/#key and https://www.w3.org/TR/trace-context-1/#value +// respectively). +// +// Trace state must be valid according to the W3C Trace Context specification at all times. All +// mutating operations validate their input and, in case of valid parameters, return a new TraceState. +type TraceState struct { //nolint:golint + // TODO @matej-g: Consider implementing this as attribute.Set, see + // comment https://github.com/open-telemetry/opentelemetry-go/pull/1340#discussion_r540599226 + kvs []attribute.KeyValue +} + +var _ json.Marshaler = TraceState{} +var keyFormatRegExp = regexp.MustCompile( + `^((` + traceStateKeyFormat + `)|(` + traceStateKeyFormatWithMultiTenantVendor + `))$`, +) +var valueFormatRegExp = regexp.MustCompile(`^(` + traceStateValueFormat + `)$`) + +// MarshalJSON implements a custom marshal function to encode trace state. +func (ts TraceState) MarshalJSON() ([]byte, error) { + return json.Marshal(ts.kvs) +} + +// String returns trace state as a string valid according to the +// W3C Trace Context specification. +func (ts TraceState) String() string { + var sb strings.Builder + + for i, kv := range ts.kvs { + sb.WriteString((string)(kv.Key)) + sb.WriteByte('=') + sb.WriteString(kv.Value.Emit()) + + if i != len(ts.kvs)-1 { + sb.WriteByte(',') + } + } + + return sb.String() +} + +// Get returns a value for given key from the trace state. +// If no key is found or provided key is invalid, returns an empty value. +func (ts TraceState) Get(key attribute.Key) attribute.Value { + if !isTraceStateKeyValid(key) { + return attribute.Value{} + } + + for _, kv := range ts.kvs { + if kv.Key == key { + return kv.Value + } + } + + return attribute.Value{} +} + +// Insert adds a new key/value, if one doesn't exists; otherwise updates the existing entry. +// The new or updated entry is always inserted at the beginning of the TraceState, i.e. +// on the left side, as per the W3C Trace Context specification requirement. +func (ts TraceState) Insert(entry attribute.KeyValue) (TraceState, error) { + if !isTraceStateKeyValueValid(entry) { + return ts, errInvalidTraceStateKeyValue + } + + ckvs := ts.copyKVsAndDeleteEntry(entry.Key) + if len(ckvs)+1 > traceStateMaxListMembers { + return ts, errInvalidTraceStateMembersNumber + } + + ckvs = append(ckvs, attribute.KeyValue{}) + copy(ckvs[1:], ckvs) + ckvs[0] = entry + + return TraceState{ckvs}, nil +} + +// Delete removes specified entry from the trace state. +func (ts TraceState) Delete(key attribute.Key) (TraceState, error) { + if !isTraceStateKeyValid(key) { + return ts, errInvalidTraceStateKeyValue + } + + return TraceState{ts.copyKVsAndDeleteEntry(key)}, nil +} + +// IsEmpty returns true if the TraceState does not contain any entries +func (ts TraceState) IsEmpty() bool { + return len(ts.kvs) == 0 +} + +func (ts TraceState) copyKVsAndDeleteEntry(key attribute.Key) []attribute.KeyValue { + ckvs := make([]attribute.KeyValue, len(ts.kvs)) + copy(ckvs, ts.kvs) + for i, kv := range ts.kvs { + if kv.Key == key { + ckvs = append(ckvs[:i], ckvs[i+1:]...) + break + } + } + + return ckvs +} + +// TraceStateFromKeyValues is a convenience method to create a new TraceState from +// provided key/value pairs. +func TraceStateFromKeyValues(kvs ...attribute.KeyValue) (TraceState, error) { //nolint:golint + if len(kvs) == 0 { + return TraceState{}, nil + } + + if len(kvs) > traceStateMaxListMembers { + return TraceState{}, errInvalidTraceStateMembersNumber + } + + km := make(map[attribute.Key]bool) + for _, kv := range kvs { + if !isTraceStateKeyValueValid(kv) { + return TraceState{}, errInvalidTraceStateKeyValue + } + _, ok := km[kv.Key] + if ok { + return TraceState{}, errInvalidTraceStateDuplicate + } + km[kv.Key] = true + } + + ckvs := make([]attribute.KeyValue, len(kvs)) + copy(ckvs, kvs) + return TraceState{ckvs}, nil +} + +func isTraceStateKeyValid(key attribute.Key) bool { + return keyFormatRegExp.MatchString(string(key)) +} + +func isTraceStateKeyValueValid(kv attribute.KeyValue) bool { + return isTraceStateKeyValid(kv.Key) && + valueFormatRegExp.MatchString(kv.Value.Emit()) +} + +// SpanContext contains identifying trace information about a Span. +type SpanContext struct { + TraceID TraceID + SpanID SpanID + TraceFlags byte + TraceState TraceState +} + +// IsValid returns if the SpanContext is valid. A valid span context has a +// valid TraceID and SpanID. +func (sc SpanContext) IsValid() bool { + return sc.HasTraceID() && sc.HasSpanID() +} + +// HasTraceID checks if the SpanContext has a valid TraceID. +func (sc SpanContext) HasTraceID() bool { + return sc.TraceID.IsValid() +} + +// HasSpanID checks if the SpanContext has a valid SpanID. +func (sc SpanContext) HasSpanID() bool { + return sc.SpanID.IsValid() +} + +// IsDeferred returns if the deferred bit is set in the trace flags. +func (sc SpanContext) IsDeferred() bool { + return sc.TraceFlags&FlagsDeferred == FlagsDeferred +} + +// IsDebug returns if the debug bit is set in the trace flags. +func (sc SpanContext) IsDebug() bool { + return sc.TraceFlags&FlagsDebug == FlagsDebug +} + +// IsSampled returns if the sampling bit is set in the trace flags. +func (sc SpanContext) IsSampled() bool { + return sc.TraceFlags&FlagsSampled == FlagsSampled +} + +type traceContextKeyType int + +const ( + currentSpanKey traceContextKeyType = iota + remoteContextKey +) + +// ContextWithSpan returns a copy of parent with span set to current. +func ContextWithSpan(parent context.Context, span Span) context.Context { + return context.WithValue(parent, currentSpanKey, span) +} + +// SpanFromContext returns the current span from ctx, or noop span if none set. +func SpanFromContext(ctx context.Context) Span { + if span, ok := ctx.Value(currentSpanKey).(Span); ok { + return span + } + return noopSpan{} +} + +// SpanContextFromContext returns the current SpanContext from ctx, or an empty SpanContext if none set. +func SpanContextFromContext(ctx context.Context) SpanContext { + if span := SpanFromContext(ctx); span != nil { + return span.SpanContext() + } + return SpanContext{} +} + +// ContextWithRemoteSpanContext returns a copy of parent with a remote set as +// the remote span context. +func ContextWithRemoteSpanContext(parent context.Context, remote SpanContext) context.Context { + return context.WithValue(parent, remoteContextKey, remote) +} + +// RemoteSpanContextFromContext returns the remote span context from ctx. +func RemoteSpanContextFromContext(ctx context.Context) SpanContext { + if sc, ok := ctx.Value(remoteContextKey).(SpanContext); ok { + return sc + } + return SpanContext{} +} + +// Span is the individual component of a trace. It represents a single named +// and timed operation of a workflow that is traced. A Tracer is used to +// create a Span and it is then up to the operation the Span represents to +// properly end the Span when the operation itself ends. +type Span interface { + // Tracer returns the Tracer that created the Span. Tracer MUST NOT be + // nil. + Tracer() Tracer + + // End completes the Span. The Span is considered complete and ready to be + // delivered through the rest of the telemetry pipeline after this method + // is called. Therefore, updates to the Span are not allowed after this + // method has been called. + End(options ...SpanOption) + + // AddEvent adds an event with the provided name and options. + AddEvent(name string, options ...EventOption) + + // IsRecording returns the recording state of the Span. It will return + // true if the Span is active and events can be recorded. + IsRecording() bool + + // RecordError records an error as a Span event. + RecordError(err error, options ...EventOption) + + // SpanContext returns the SpanContext of the Span. The returned + // SpanContext is usable even after the End has been called for the Span. + SpanContext() SpanContext + + // SetStatus sets the status of the Span in the form of a code and a + // message. SetStatus overrides the value of previous calls to SetStatus + // on the Span. + SetStatus(code codes.Code, msg string) + + // SetName sets the Span name. + SetName(name string) + + // SetAttributes sets kv as attributes of the Span. If a key from kv + // already exists for an attribute of the Span it will be overwritten with + // the value contained in kv. + SetAttributes(kv ...attribute.KeyValue) +} + +// Event is a thing that happened during a Span's lifetime. +type Event struct { + // Name is the name of this event + Name string + + // Attributes describe the aspects of the event. + Attributes []attribute.KeyValue + + // Time at which this event was recorded. + Time time.Time +} + +// Link is the relationship between two Spans. The relationship can be within +// the same Trace or across different Traces. +// +// For example, a Link is used in the following situations: +// +// 1. Batch Processing: A batch of operations may contain operations +// associated with one or more traces/spans. Since there can only be one +// parent SpanContext, a Link is used to keep reference to the +// SpanContext of all operations in the batch. +// 2. Public Endpoint: A SpanContext for an in incoming client request on a +// public endpoint should be considered untrusted. In such a case, a new +// trace with its own identity and sampling decision needs to be created, +// but this new trace needs to be related to the original trace in some +// form. A Link is used to keep reference to the original SpanContext and +// track the relationship. +type Link struct { + SpanContext + Attributes []attribute.KeyValue +} + +// SpanKind is the role a Span plays in a Trace. +type SpanKind int + +// As a convenience, these match the proto definition, see +// https://github.com/open-telemetry/opentelemetry-proto/blob/30d237e1ff3ab7aa50e0922b5bebdd93505090af/opentelemetry/proto/trace/v1/trace.proto#L101-L129 +// +// The unspecified value is not a valid `SpanKind`. Use `ValidateSpanKind()` +// to coerce a span kind to a valid value. +const ( + // SpanKindUnspecified is an unspecified SpanKind and is not a valid + // SpanKind. SpanKindUnspecified should be replaced with SpanKindInternal + // if it is received. + SpanKindUnspecified SpanKind = 0 + // SpanKindInternal is a SpanKind for a Span that represents an internal + // operation within an application. + SpanKindInternal SpanKind = 1 + // SpanKindServer is a SpanKind for a Span that represents the operation + // of handling a request from a client. + SpanKindServer SpanKind = 2 + // SpanKindClient is a SpanKind for a Span that represents the operation + // of client making a request to a server. + SpanKindClient SpanKind = 3 + // SpanKindProducer is a SpanKind for a Span that represents the operation + // of a producer sending a message to a message broker. Unlike + // SpanKindClient and SpanKindServer, there is often no direct + // relationship between this kind of Span and a SpanKindConsumer kind. A + // SpanKindProducer Span will end once the message is accepted by the + // message broker which might not overlap with the processing of that + // message. + SpanKindProducer SpanKind = 4 + // SpanKindConsumer is a SpanKind for a Span that represents the operation + // of a consumer receiving a message from a message broker. Like + // SpanKindProducer Spans, there is often no direct relationship between + // this Span and the Span that produced the message. + SpanKindConsumer SpanKind = 5 +) + +// ValidateSpanKind returns a valid span kind value. This will coerce +// invalid values into the default value, SpanKindInternal. +func ValidateSpanKind(spanKind SpanKind) SpanKind { + switch spanKind { + case SpanKindInternal, + SpanKindServer, + SpanKindClient, + SpanKindProducer, + SpanKindConsumer: + // valid + return spanKind + default: + return SpanKindInternal + } +} + +// String returns the specified name of the SpanKind in lower-case. +func (sk SpanKind) String() string { + switch sk { + case SpanKindInternal: + return "internal" + case SpanKindServer: + return "server" + case SpanKindClient: + return "client" + case SpanKindProducer: + return "producer" + case SpanKindConsumer: + return "consumer" + default: + return "unspecified" + } +} + +// Tracer is the creator of Spans. +type Tracer interface { + // Start creates a span. + Start(ctx context.Context, spanName string, opts ...SpanOption) (context.Context, Span) +} + +// TracerProvider provides access to instrumentation Tracers. +type TracerProvider interface { + // Tracer creates an implementation of the Tracer interface. + // The instrumentationName must be the name of the library providing + // instrumentation. This name may be the same as the instrumented code + // only if that code provides built-in instrumentation. If the + // instrumentationName is empty, then a implementation defined default + // name will be used instead. + Tracer(instrumentationName string, opts ...TracerOption) Tracer +} diff --git a/vendor/go.opentelemetry.io/otel/trace/trace_noop.go b/vendor/go.opentelemetry.io/otel/trace/trace_noop.go new file mode 100644 index 000000000..e47d50697 --- /dev/null +++ b/vendor/go.opentelemetry.io/otel/trace/trace_noop.go @@ -0,0 +1,84 @@ +// 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 trace // import "go.opentelemetry.io/otel/trace" + +import ( + "context" + + "go.opentelemetry.io/otel/attribute" + "go.opentelemetry.io/otel/codes" +) + +// NewNoopTracerProvider returns an implementation of TracerProvider that +// performs no operations. The Tracer and Spans created from the returned +// TracerProvider also perform no operations. +func NewNoopTracerProvider() TracerProvider { + return noopTracerProvider{} +} + +type noopTracerProvider struct{} + +var _ TracerProvider = noopTracerProvider{} + +// Tracer returns noop implementation of Tracer. +func (p noopTracerProvider) Tracer(string, ...TracerOption) Tracer { + return noopTracer{} +} + +// noopTracer is an implementation of Tracer that preforms no operations. +type noopTracer struct{} + +var _ Tracer = noopTracer{} + +// Start starts a noop span. +func (t noopTracer) Start(ctx context.Context, name string, _ ...SpanOption) (context.Context, Span) { + span := noopSpan{} + return ContextWithSpan(ctx, span), span +} + +// noopSpan is an implementation of Span that preforms no operations. +type noopSpan struct{} + +var _ noopSpan = noopSpan{} + +// SpanContext returns an empty span context. +func (noopSpan) SpanContext() SpanContext { return SpanContext{} } + +// IsRecording always returns false. +func (noopSpan) IsRecording() bool { return false } + +// SetStatus does nothing. +func (noopSpan) SetStatus(codes.Code, string) {} + +// SetError does nothing. +func (noopSpan) SetError(bool) {} + +// SetAttributes does nothing. +func (noopSpan) SetAttributes(...attribute.KeyValue) {} + +// End does nothing. +func (noopSpan) End(...SpanOption) {} + +// RecordError does nothing. +func (noopSpan) RecordError(error, ...EventOption) {} + +// Tracer returns the Tracer that created this Span. +func (noopSpan) Tracer() Tracer { return noopTracer{} } + +// AddEvent does nothing. +func (noopSpan) AddEvent(string, ...EventOption) {} + +// SetName does nothing. +func (noopSpan) SetName(string) {} diff --git a/vendor/go.opentelemetry.io/otel/api/unit/doc.go b/vendor/go.opentelemetry.io/otel/unit/doc.go similarity index 65% rename from vendor/go.opentelemetry.io/otel/api/unit/doc.go rename to vendor/go.opentelemetry.io/otel/unit/doc.go index f03ed5595..0d77a750c 100644 --- a/vendor/go.opentelemetry.io/otel/api/unit/doc.go +++ b/vendor/go.opentelemetry.io/otel/unit/doc.go @@ -12,4 +12,9 @@ // See the License for the specific language governing permissions and // limitations under the License. -package unit // import "go.opentelemetry.io/otel/api/unit" +// Package unit provides units. +// +// This package is currently in a pre-GA phase. Backwards incompatible changes +// may be introduced in subsequent minor version releases as we work to track +// the evolving OpenTelemetry specification and user feedback. +package unit // import "go.opentelemetry.io/otel/unit" diff --git a/vendor/go.opentelemetry.io/otel/api/unit/unit.go b/vendor/go.opentelemetry.io/otel/unit/unit.go similarity index 92% rename from vendor/go.opentelemetry.io/otel/api/unit/unit.go rename to vendor/go.opentelemetry.io/otel/unit/unit.go index dcd39af02..523bfe1d0 100644 --- a/vendor/go.opentelemetry.io/otel/api/unit/unit.go +++ b/vendor/go.opentelemetry.io/otel/unit/unit.go @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -package unit +package unit // import "go.opentelemetry.io/otel/unit" type Unit string diff --git a/vendor/go.opentelemetry.io/otel/label/doc.go b/vendor/go.opentelemetry.io/otel/version.go similarity index 78% rename from vendor/go.opentelemetry.io/otel/label/doc.go rename to vendor/go.opentelemetry.io/otel/version.go index d631d2387..46e6ca653 100644 --- a/vendor/go.opentelemetry.io/otel/label/doc.go +++ b/vendor/go.opentelemetry.io/otel/version.go @@ -12,5 +12,9 @@ // See the License for the specific language governing permissions and // limitations under the License. -// Package label provides key and value labels. -package label // import "go.opentelemetry.io/otel/label" +package otel // import "go.opentelemetry.io/otel" + +// Version is the current release version of OpenTelemetry in use. +func Version() string { + return "0.18.0" +} diff --git a/vendor/golang.org/x/net/html/const.go b/vendor/golang.org/x/net/html/const.go index 73804d347..ff7acf2d5 100644 --- a/vendor/golang.org/x/net/html/const.go +++ b/vendor/golang.org/x/net/html/const.go @@ -52,7 +52,7 @@ var isSpecialElementMap = map[string]bool{ "iframe": true, "img": true, "input": true, - "keygen": true, + "keygen": true, // "keygen" has been removed from the spec, but are kept here for backwards compatibility. "li": true, "link": true, "listing": true, diff --git a/vendor/golang.org/x/net/html/foreign.go b/vendor/golang.org/x/net/html/foreign.go index 74774c458..9da9e9dc4 100644 --- a/vendor/golang.org/x/net/html/foreign.go +++ b/vendor/golang.org/x/net/html/foreign.go @@ -161,65 +161,62 @@ var mathMLAttributeAdjustments = map[string]string{ } var svgAttributeAdjustments = map[string]string{ - "attributename": "attributeName", - "attributetype": "attributeType", - "basefrequency": "baseFrequency", - "baseprofile": "baseProfile", - "calcmode": "calcMode", - "clippathunits": "clipPathUnits", - "contentscripttype": "contentScriptType", - "contentstyletype": "contentStyleType", - "diffuseconstant": "diffuseConstant", - "edgemode": "edgeMode", - "externalresourcesrequired": "externalResourcesRequired", - "filterunits": "filterUnits", - "glyphref": "glyphRef", - "gradienttransform": "gradientTransform", - "gradientunits": "gradientUnits", - "kernelmatrix": "kernelMatrix", - "kernelunitlength": "kernelUnitLength", - "keypoints": "keyPoints", - "keysplines": "keySplines", - "keytimes": "keyTimes", - "lengthadjust": "lengthAdjust", - "limitingconeangle": "limitingConeAngle", - "markerheight": "markerHeight", - "markerunits": "markerUnits", - "markerwidth": "markerWidth", - "maskcontentunits": "maskContentUnits", - "maskunits": "maskUnits", - "numoctaves": "numOctaves", - "pathlength": "pathLength", - "patterncontentunits": "patternContentUnits", - "patterntransform": "patternTransform", - "patternunits": "patternUnits", - "pointsatx": "pointsAtX", - "pointsaty": "pointsAtY", - "pointsatz": "pointsAtZ", - "preservealpha": "preserveAlpha", - "preserveaspectratio": "preserveAspectRatio", - "primitiveunits": "primitiveUnits", - "refx": "refX", - "refy": "refY", - "repeatcount": "repeatCount", - "repeatdur": "repeatDur", - "requiredextensions": "requiredExtensions", - "requiredfeatures": "requiredFeatures", - "specularconstant": "specularConstant", - "specularexponent": "specularExponent", - "spreadmethod": "spreadMethod", - "startoffset": "startOffset", - "stddeviation": "stdDeviation", - "stitchtiles": "stitchTiles", - "surfacescale": "surfaceScale", - "systemlanguage": "systemLanguage", - "tablevalues": "tableValues", - "targetx": "targetX", - "targety": "targetY", - "textlength": "textLength", - "viewbox": "viewBox", - "viewtarget": "viewTarget", - "xchannelselector": "xChannelSelector", - "ychannelselector": "yChannelSelector", - "zoomandpan": "zoomAndPan", + "attributename": "attributeName", + "attributetype": "attributeType", + "basefrequency": "baseFrequency", + "baseprofile": "baseProfile", + "calcmode": "calcMode", + "clippathunits": "clipPathUnits", + "diffuseconstant": "diffuseConstant", + "edgemode": "edgeMode", + "filterunits": "filterUnits", + "glyphref": "glyphRef", + "gradienttransform": "gradientTransform", + "gradientunits": "gradientUnits", + "kernelmatrix": "kernelMatrix", + "kernelunitlength": "kernelUnitLength", + "keypoints": "keyPoints", + "keysplines": "keySplines", + "keytimes": "keyTimes", + "lengthadjust": "lengthAdjust", + "limitingconeangle": "limitingConeAngle", + "markerheight": "markerHeight", + "markerunits": "markerUnits", + "markerwidth": "markerWidth", + "maskcontentunits": "maskContentUnits", + "maskunits": "maskUnits", + "numoctaves": "numOctaves", + "pathlength": "pathLength", + "patterncontentunits": "patternContentUnits", + "patterntransform": "patternTransform", + "patternunits": "patternUnits", + "pointsatx": "pointsAtX", + "pointsaty": "pointsAtY", + "pointsatz": "pointsAtZ", + "preservealpha": "preserveAlpha", + "preserveaspectratio": "preserveAspectRatio", + "primitiveunits": "primitiveUnits", + "refx": "refX", + "refy": "refY", + "repeatcount": "repeatCount", + "repeatdur": "repeatDur", + "requiredextensions": "requiredExtensions", + "requiredfeatures": "requiredFeatures", + "specularconstant": "specularConstant", + "specularexponent": "specularExponent", + "spreadmethod": "spreadMethod", + "startoffset": "startOffset", + "stddeviation": "stdDeviation", + "stitchtiles": "stitchTiles", + "surfacescale": "surfaceScale", + "systemlanguage": "systemLanguage", + "tablevalues": "tableValues", + "targetx": "targetX", + "targety": "targetY", + "textlength": "textLength", + "viewbox": "viewBox", + "viewtarget": "viewTarget", + "xchannelselector": "xChannelSelector", + "ychannelselector": "yChannelSelector", + "zoomandpan": "zoomAndPan", } diff --git a/vendor/golang.org/x/net/html/parse.go b/vendor/golang.org/x/net/html/parse.go index 2cd12fc81..f91466f7c 100644 --- a/vendor/golang.org/x/net/html/parse.go +++ b/vendor/golang.org/x/net/html/parse.go @@ -728,7 +728,13 @@ func inHeadNoscriptIM(p *parser) bool { return inBodyIM(p) case a.Basefont, a.Bgsound, a.Link, a.Meta, a.Noframes, a.Style: return inHeadIM(p) - case a.Head, a.Noscript: + case a.Head: + // Ignore the token. + return true + case a.Noscript: + // Don't let the tokenizer go into raw text mode even when a