diff --git a/go.mod b/go.mod index 8d71d630e..60bf56ca5 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.11.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 2293ee4dc..149754aa6 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.11.0 h1:O1Td0mQ8UFChQ3N9zFQqo6kTU2cJ+/it88gDB+zg0wo= +github.com/go-redis/redis/v8 v8.11.0/go.mod h1:DLomh7y2e3ggQXQLd1YgmvIfecPJoFl7WU5SOQ/r06M= 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.6/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= @@ -415,12 +418,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= @@ -620,6 +625,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= @@ -637,6 +645,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= @@ -683,6 +692,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= @@ -743,6 +755,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..d15b5ac58 100644 --- a/vendor/github.com/go-redis/redis/v8/.golangci.yml +++ b/vendor/github.com/go-redis/redis/v8/.golangci.yml @@ -17,5 +17,10 @@ linters: - gomnd - goerr113 - exhaustive - - gofumpt - nestif + - nlreturn + - exhaustivestruct + - wrapcheck + - errorlint + - cyclop + - forcetypeassert diff --git a/vendor/github.com/go-redis/redis/v8/.travis.yml b/vendor/github.com/go-redis/redis/v8/.travis.yml deleted file mode 100644 index adedd8df4..000000000 --- a/vendor/github.com/go-redis/redis/v8/.travis.yml +++ /dev/null @@ -1,20 +0,0 @@ -dist: xenial -language: go - -services: - - redis-server - -go: - - 1.14.x - - 1.15.x - - tip - -matrix: - allow_failures: - - go: tip - -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 diff --git a/vendor/github.com/go-redis/redis/v8/CHANGELOG.md b/vendor/github.com/go-redis/redis/v8/CHANGELOG.md index d0c4c8c1c..42d89b720 100644 --- a/vendor/github.com/go-redis/redis/v8/CHANGELOG.md +++ b/vendor/github.com/go-redis/redis/v8/CHANGELOG.md @@ -1,10 +1,51 @@ # Changelog -> :heart: [**Uptrace.dev** - distributed traces, logs, and errors in one place](https://uptrace.dev) +> :heart: +> [**Uptrace.dev** - All-in-one tool to optimize performance and monitor errors & logs](https://uptrace.dev) -## v8 +## v8.10 + +- Removed extra OpenTelemetry spans from go-redis core. Now go-redis instrumentation only adds a + single span with a Redis command (instead of 4 spans). There are multiple reasons behind this + decision: + + - Traces become smaller and less noisy. + - It may be costly to process those 3 extra spans for each query. + - go-redis no longer depends on OpenTelemetry. + + Eventually we hope to replace the information that we no longer collect with OpenTelemetry + Metrics. + +## v8.9 -- Documentation at https://redis.uptrace.dev/ +- Changed `PubSub.Channel` to only rely on `Ping` result. You can now use `WithChannelSize`, + `WithChannelHealthCheckInterval`, and `WithChannelSendTimeout` to override default settings. + +## v8.8 + +- To make updating easier, extra modules now have the same version as go-redis does. That means that + you need to update your imports: + +``` +github.com/go-redis/redis/extra/redisotel -> github.com/go-redis/redis/extra/redisotel/v8 +github.com/go-redis/redis/extra/rediscensus -> github.com/go-redis/redis/extra/rediscensus/v8 +``` + +## v8.5 + +- [knadh](https://github.com/knadh) contributed long-awaited ability to scan Redis Hash into a + struct: + +```go +err := rdb.HGetAll(ctx, "hash").Scan(&data) + +err := rdb.MGet(ctx, "key1", "key2").Scan(&data) +``` + +- Please check [redismock](https://github.com/go-redis/redismock) by + [monkey92t](https://github.com/monkey92t) if you are looking for mocking Redis Client. + +## v8 - 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 diff --git a/vendor/github.com/go-redis/redis/v8/Makefile b/vendor/github.com/go-redis/redis/v8/Makefile index 49e4c96f0..5501164f9 100644 --- a/vendor/github.com/go-redis/redis/v8/Makefile +++ b/vendor/github.com/go-redis/redis/v8/Makefile @@ -1,10 +1,9 @@ -all: testdeps +test: testdeps go test ./... go test ./... -short -race go test ./... -run=NONE -bench=. -benchmem env GOOS=linux GOARCH=386 go test ./... go vet - golangci-lint run testdeps: testdata/redis/src/redis-server @@ -15,7 +14,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.1.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..bc4624e0a 100644 --- a/vendor/github.com/go-redis/redis/v8/README.md +++ b/vendor/github.com/go-redis/redis/v8/README.md @@ -1,25 +1,34 @@ +

+ + All-in-one tool to optimize performance and monitor errors & logs + +

+ # Redis client for Golang -[![Build Status](https://travis-ci.org/go-redis/redis.png?branch=master)](https://travis-ci.org/go-redis/redis) +![build workflow](https://github.com/go-redis/redis/actions/workflows/build.yml/badge.svg) [![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) + +My other projects: + +- [Bun](https://bun.uptrace.dev) - fast and simple SQL client for PostgreSQL, MySQL, and SQLite. +- [treemux](https://github.com/vmihailenco/treemux) - high-speed, flexible, tree-based HTTP router + for Go. ## 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 +48,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 +74,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 +105,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 +140,29 @@ vals, err := rdb.Eval(ctx, "return {KEYS[1],ARGV[1]}", []string{"key"}, "hello") res, err := rdb.Do(ctx, "set", "key", "value").Result() ``` -## See also +## Run the test + +go-redis will start a redis-server and run the test cases. -- [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) +The paths of redis-server bin file and redis config file are defined 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 +``` diff --git a/vendor/github.com/go-redis/redis/v8/cluster.go b/vendor/github.com/go-redis/redis/v8/cluster.go index a6ce5c584..49b2d37bd 100644 --- a/vendor/github.com/go-redis/redis/v8/cluster.go +++ b/vendor/github.com/go-redis/redis/v8/cluster.go @@ -86,12 +86,12 @@ func (opt *ClusterOptions) init() { opt.MaxRedirects = 3 } - if (opt.RouteByLatency || opt.RouteRandomly) && opt.ClusterSlots == nil { + if opt.RouteByLatency || opt.RouteRandomly { opt.ReadOnly = true } if opt.PoolSize == 0 { - opt.PoolSize = 5 * runtime.NumCPU() + opt.PoolSize = 5 * runtime.GOMAXPROCS(0) } switch opt.ReadTimeout { @@ -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, } } @@ -291,8 +295,9 @@ func (c *clusterNodes) Close() error { func (c *clusterNodes) Addrs() ([]string, error) { var addrs []string + c.mu.RLock() - closed := c.closed + closed := c.closed //nolint:ifshort if !closed { if len(c.activeAddrs) > 0 { addrs = c.activeAddrs @@ -628,14 +633,14 @@ func (c *clusterStateHolder) Reload(ctx context.Context) (*clusterState, error) return state, nil } -func (c *clusterStateHolder) LazyReload(ctx context.Context) { +func (c *clusterStateHolder) LazyReload() { if !atomic.CompareAndSwapUint32(&c.reloading, 0, 1) { return } go func() { defer atomic.StoreUint32(&c.reloading, 0) - _, err := c.Reload(ctx) + _, err := c.Reload(context.Background()) if err != nil { return } @@ -645,14 +650,15 @@ func (c *clusterStateHolder) LazyReload(ctx context.Context) { func (c *clusterStateHolder) Get(ctx context.Context) (*clusterState, error) { v := c.state.Load() - if v != nil { - state := v.(*clusterState) - if time.Since(state.createdAt) > 10*time.Second { - c.LazyReload(ctx) - } - return state, nil + if v == nil { + return c.Reload(ctx) + } + + state := v.(*clusterState) + if time.Since(state.createdAt) > 10*time.Second { + c.LazyReload() } - return c.Reload(ctx) + return state, nil } func (c *clusterStateHolder) ReloadOrGet(ctx context.Context) (*clusterState, error) { @@ -728,7 +734,7 @@ func (c *ClusterClient) Options() *ClusterOptions { // ReloadState reloads cluster state. If available it calls ClusterSlots func // to get cluster slots information. func (c *ClusterClient) ReloadState(ctx context.Context) { - c.state.LazyReload(ctx) + c.state.LazyReload() } // Close closes the cluster client, releasing any open resources. @@ -789,7 +795,7 @@ func (c *ClusterClient) process(ctx context.Context, cmd Cmder) error { } if isReadOnly := isReadOnlyError(lastErr); isReadOnly || lastErr == pool.ErrClosed { if isReadOnly { - c.state.LazyReload(ctx) + c.state.LazyReload() } node = nil continue @@ -1224,7 +1230,7 @@ func (c *ClusterClient) checkMovedErr( } if moved { - c.state.LazyReload(ctx) + c.state.LazyReload() failedCmds.Add(node, cmd) return true } @@ -1252,10 +1258,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 +1300,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) @@ -1406,7 +1416,7 @@ func (c *ClusterClient) cmdsMoved( } if moved { - c.state.LazyReload(ctx) + c.state.LazyReload() for _, cmd := range cmds { failedCmds.Add(node, cmd) } @@ -1464,7 +1474,7 @@ func (c *ClusterClient) Watch(ctx context.Context, fn func(*Tx) error, keys ...s if isReadOnly := isReadOnlyError(err); isReadOnly || err == pool.ErrClosed { if isReadOnly { - c.state.LazyReload(ctx) + c.state.LazyReload() } node, err = c.slotMasterNode(ctx, slot) if err != nil { @@ -1631,7 +1641,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 +1665,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/cluster_commands.go b/vendor/github.com/go-redis/redis/v8/cluster_commands.go index 1f0bae067..336ea98dd 100644 --- a/vendor/github.com/go-redis/redis/v8/cluster_commands.go +++ b/vendor/github.com/go-redis/redis/v8/cluster_commands.go @@ -2,6 +2,7 @@ package redis import ( "context" + "sync" "sync/atomic" ) @@ -23,3 +24,76 @@ func (c *ClusterClient) DBSize(ctx context.Context) *IntCmd { cmd.val = size return cmd } + +func (c *ClusterClient) ScriptLoad(ctx context.Context, script string) *StringCmd { + cmd := NewStringCmd(ctx, "script", "load", script) + mu := &sync.Mutex{} + err := c.ForEachShard(ctx, func(ctx context.Context, shard *Client) error { + val, err := shard.ScriptLoad(ctx, script).Result() + if err != nil { + return err + } + + mu.Lock() + if cmd.Val() == "" { + cmd.val = val + } + mu.Unlock() + + return nil + }) + if err != nil { + cmd.SetErr(err) + } + + return cmd +} + +func (c *ClusterClient) ScriptFlush(ctx context.Context) *StatusCmd { + cmd := NewStatusCmd(ctx, "script", "flush") + _ = c.ForEachShard(ctx, func(ctx context.Context, shard *Client) error { + shard.ScriptFlush(ctx) + + return nil + }) + + return cmd +} + +func (c *ClusterClient) ScriptExists(ctx context.Context, hashes ...string) *BoolSliceCmd { + args := make([]interface{}, 2+len(hashes)) + args[0] = "script" + args[1] = "exists" + for i, hash := range hashes { + args[2+i] = hash + } + cmd := NewBoolSliceCmd(ctx, args...) + + result := make([]bool, len(hashes)) + for i := range result { + result[i] = true + } + + mu := &sync.Mutex{} + err := c.ForEachShard(ctx, func(ctx context.Context, shard *Client) error { + val, err := shard.ScriptExists(ctx, hashes...).Result() + if err != nil { + return err + } + + mu.Lock() + for i, v := range val { + result[i] = result[i] && v + } + mu.Unlock() + + return nil + }) + if err != nil { + cmd.SetErr(err) + } + + cmd.val = result + + return cmd +} diff --git a/vendor/github.com/go-redis/redis/v8/command.go b/vendor/github.com/go-redis/redis/v8/command.go index 5dd553325..77d0bada4 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 { @@ -689,6 +710,13 @@ func (cmd *StringCmd) Bytes() ([]byte, error) { return util.StringToBytes(cmd.val), cmd.err } +func (cmd *StringCmd) Bool() (bool, error) { + if cmd.err != nil { + return false, cmd.err + } + return strconv.ParseBool(cmd.val) +} + func (cmd *StringCmd) Int() (int, error) { if cmd.err != nil { return 0, cmd.err @@ -789,6 +817,55 @@ func (cmd *FloatCmd) readReply(rd *proto.Reader) (err error) { //------------------------------------------------------------------------------ +type FloatSliceCmd struct { + baseCmd + + val []float64 +} + +var _ Cmder = (*FloatSliceCmd)(nil) + +func NewFloatSliceCmd(ctx context.Context, args ...interface{}) *FloatSliceCmd { + return &FloatSliceCmd{ + baseCmd: baseCmd{ + ctx: ctx, + args: args, + }, + } +} + +func (cmd *FloatSliceCmd) Val() []float64 { + return cmd.val +} + +func (cmd *FloatSliceCmd) Result() ([]float64, error) { + return cmd.val, cmd.err +} + +func (cmd *FloatSliceCmd) String() string { + return cmdString(cmd, cmd.val) +} + +func (cmd *FloatSliceCmd) readReply(rd *proto.Reader) error { + _, err := rd.ReadArrayReply(func(rd *proto.Reader, n int64) (interface{}, error) { + cmd.val = make([]float64, n) + for i := 0; i < len(cmd.val); i++ { + switch num, err := rd.ReadFloatReply(); { + case err == Nil: + cmd.val[i] = 0 + case err != nil: + return nil, err + default: + cmd.val[i] = num + } + } + return nil, nil + }) + return err +} + +//------------------------------------------------------------------------------ + type StringSliceCmd struct { baseCmd @@ -917,6 +994,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 +1501,219 @@ func (cmd *XPendingExtCmd) readReply(rd *proto.Reader) error { //------------------------------------------------------------------------------ +type XAutoClaimCmd struct { + baseCmd + + start string + val []XMessage +} + +var _ Cmder = (*XAutoClaimCmd)(nil) + +func NewXAutoClaimCmd(ctx context.Context, args ...interface{}) *XAutoClaimCmd { + return &XAutoClaimCmd{ + baseCmd: baseCmd{ + ctx: ctx, + args: args, + }, + } +} + +func (cmd *XAutoClaimCmd) Val() (messages []XMessage, start string) { + return cmd.val, cmd.start +} + +func (cmd *XAutoClaimCmd) Result() (messages []XMessage, start string, err error) { + return cmd.val, cmd.start, cmd.err +} + +func (cmd *XAutoClaimCmd) String() string { + return cmdString(cmd, cmd.val) +} + +func (cmd *XAutoClaimCmd) readReply(rd *proto.Reader) error { + _, err := rd.ReadArrayReply(func(rd *proto.Reader, n int64) (interface{}, error) { + if n != 2 { + return nil, fmt.Errorf("got %d, wanted 2", n) + } + var err error + + cmd.start, err = rd.ReadString() + if err != nil { + return nil, err + } + + cmd.val, err = readXMessageSlice(rd) + if err != nil { + return nil, err + } + + return nil, nil + }) + return err +} + +//------------------------------------------------------------------------------ + +type XAutoClaimJustIDCmd struct { + baseCmd + + start string + val []string +} + +var _ Cmder = (*XAutoClaimJustIDCmd)(nil) + +func NewXAutoClaimJustIDCmd(ctx context.Context, args ...interface{}) *XAutoClaimJustIDCmd { + return &XAutoClaimJustIDCmd{ + baseCmd: baseCmd{ + ctx: ctx, + args: args, + }, + } +} + +func (cmd *XAutoClaimJustIDCmd) Val() (ids []string, start string) { + return cmd.val, cmd.start +} + +func (cmd *XAutoClaimJustIDCmd) Result() (ids []string, start string, err error) { + return cmd.val, cmd.start, cmd.err +} + +func (cmd *XAutoClaimJustIDCmd) String() string { + return cmdString(cmd, cmd.val) +} + +func (cmd *XAutoClaimJustIDCmd) readReply(rd *proto.Reader) error { + _, err := rd.ReadArrayReply(func(rd *proto.Reader, n int64) (interface{}, error) { + if n != 2 { + return nil, fmt.Errorf("got %d, wanted 2", n) + } + var err error + + cmd.start, err = rd.ReadString() + if err != nil { + return nil, err + } + + nn, err := rd.ReadArrayLen() + if err != nil { + return nil, err + } + + cmd.val = make([]string, nn) + for i := 0; i < nn; i++ { + cmd.val[i], err = rd.ReadString() + if err != nil { + return nil, err + } + } + + return nil, nil + }) + return err +} + +//------------------------------------------------------------------------------ + +type XInfoConsumersCmd struct { + baseCmd + val []XInfoConsumer +} + +type XInfoConsumer struct { + Name string + Pending int64 + Idle int64 +} + +var _ Cmder = (*XInfoConsumersCmd)(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 @@ -1574,8 +1885,14 @@ func xStreamInfoParser(rd *proto.Reader, n int64) (interface{}, error) { info.LastGeneratedID, err = rd.ReadString() case "first-entry": info.FirstEntry, err = readXMessage(rd) + if err == Nil { + err = nil + } case "last-entry": info.LastEntry, err = readXMessage(rd) + if err == Nil { + err = nil + } default: return nil, fmt.Errorf("redis: unexpected content %s "+ "in XINFO STREAM reply", key) @@ -1589,6 +1906,302 @@ func xStreamInfoParser(rd *proto.Reader, n int64) (interface{}, error) { //------------------------------------------------------------------------------ +type XInfoStreamFullCmd struct { + baseCmd + val *XInfoStreamFull +} + +type XInfoStreamFull struct { + Length int64 + RadixTreeKeys int64 + RadixTreeNodes int64 + LastGeneratedID string + Entries []XMessage + Groups []XInfoStreamGroup +} + +type XInfoStreamGroup struct { + Name string + LastDeliveredID string + PelCount int64 + Pending []XInfoStreamGroupPending + Consumers []XInfoStreamConsumer +} + +type XInfoStreamGroupPending struct { + ID string + Consumer string + DeliveryTime time.Time + DeliveryCount int64 +} + +type XInfoStreamConsumer struct { + Name string + SeenTime time.Time + PelCount int64 + Pending []XInfoStreamConsumerPending +} + +type XInfoStreamConsumerPending struct { + ID string + DeliveryTime time.Time + DeliveryCount int64 +} + +var _ Cmder = (*XInfoStreamFullCmd)(nil) + +func NewXInfoStreamFullCmd(ctx context.Context, args ...interface{}) *XInfoStreamFullCmd { + return &XInfoStreamFullCmd{ + baseCmd: baseCmd{ + ctx: ctx, + args: args, + }, + } +} + +func (cmd *XInfoStreamFullCmd) Val() *XInfoStreamFull { + return cmd.val +} + +func (cmd *XInfoStreamFullCmd) Result() (*XInfoStreamFull, error) { + return cmd.val, cmd.err +} + +func (cmd *XInfoStreamFullCmd) String() string { + return cmdString(cmd, cmd.val) +} + +func (cmd *XInfoStreamFullCmd) readReply(rd *proto.Reader) error { + n, err := rd.ReadArrayLen() + if err != nil { + return err + } + if n != 12 { + return fmt.Errorf("redis: got %d elements in XINFO STREAM FULL reply,"+ + "wanted 12", n) + } + + cmd.val = &XInfoStreamFull{} + + for i := 0; i < 6; i++ { + key, err := rd.ReadString() + if err != nil { + return err + } + + switch key { + case "length": + cmd.val.Length, err = rd.ReadIntReply() + case "radix-tree-keys": + cmd.val.RadixTreeKeys, err = rd.ReadIntReply() + case "radix-tree-nodes": + cmd.val.RadixTreeNodes, err = rd.ReadIntReply() + case "last-generated-id": + cmd.val.LastGeneratedID, err = rd.ReadString() + case "entries": + cmd.val.Entries, err = readXMessageSlice(rd) + case "groups": + cmd.val.Groups, err = readStreamGroups(rd) + default: + return fmt.Errorf("redis: unexpected content %s "+ + "in XINFO STREAM reply", key) + } + if err != nil { + return err + } + } + return nil +} + +func readStreamGroups(rd *proto.Reader) ([]XInfoStreamGroup, error) { + n, err := rd.ReadArrayLen() + if err != nil { + return nil, err + } + groups := make([]XInfoStreamGroup, 0, n) + for i := 0; i < n; i++ { + nn, err := rd.ReadArrayLen() + if err != nil { + return nil, err + } + if nn != 10 { + return nil, fmt.Errorf("redis: got %d elements in XINFO STREAM FULL reply,"+ + "wanted 10", nn) + } + + group := XInfoStreamGroup{} + + for f := 0; f < 5; f++ { + key, err := rd.ReadString() + if err != nil { + return nil, err + } + + switch key { + case "name": + group.Name, err = rd.ReadString() + case "last-delivered-id": + group.LastDeliveredID, err = rd.ReadString() + case "pel-count": + group.PelCount, err = rd.ReadIntReply() + case "pending": + group.Pending, err = readXInfoStreamGroupPending(rd) + case "consumers": + group.Consumers, err = readXInfoStreamConsumers(rd) + default: + return nil, fmt.Errorf("redis: unexpected content %s "+ + "in XINFO STREAM reply", key) + } + + if err != nil { + return nil, err + } + } + + groups = append(groups, group) + } + + return groups, nil +} + +func readXInfoStreamGroupPending(rd *proto.Reader) ([]XInfoStreamGroupPending, error) { + n, err := rd.ReadArrayLen() + if err != nil { + return nil, err + } + + pending := make([]XInfoStreamGroupPending, 0, n) + + for i := 0; i < n; i++ { + nn, err := rd.ReadArrayLen() + if err != nil { + return nil, err + } + if nn != 4 { + return nil, fmt.Errorf("redis: got %d elements in XINFO STREAM FULL reply,"+ + "wanted 4", nn) + } + + p := XInfoStreamGroupPending{} + + p.ID, err = rd.ReadString() + if err != nil { + return nil, err + } + + p.Consumer, err = rd.ReadString() + if err != nil { + return nil, err + } + + delivery, err := rd.ReadIntReply() + if err != nil { + return nil, err + } + p.DeliveryTime = time.Unix(delivery/1000, delivery%1000*int64(time.Millisecond)) + + p.DeliveryCount, err = rd.ReadIntReply() + if err != nil { + return nil, err + } + + pending = append(pending, p) + } + + return pending, nil +} + +func readXInfoStreamConsumers(rd *proto.Reader) ([]XInfoStreamConsumer, error) { + n, err := rd.ReadArrayLen() + if err != nil { + return nil, err + } + + consumers := make([]XInfoStreamConsumer, 0, n) + + for i := 0; i < n; i++ { + nn, err := rd.ReadArrayLen() + if err != nil { + return nil, err + } + if nn != 8 { + return nil, fmt.Errorf("redis: got %d elements in XINFO STREAM FULL reply,"+ + "wanted 8", nn) + } + + c := XInfoStreamConsumer{} + + for f := 0; f < 4; f++ { + cKey, err := rd.ReadString() + if err != nil { + return nil, err + } + + switch cKey { + case "name": + c.Name, err = rd.ReadString() + case "seen-time": + seen, err := rd.ReadIntReply() + if err != nil { + return nil, err + } + c.SeenTime = time.Unix(seen/1000, seen%1000*int64(time.Millisecond)) + case "pel-count": + c.PelCount, err = rd.ReadIntReply() + case "pending": + pendingNumber, err := rd.ReadArrayLen() + if err != nil { + return nil, err + } + + c.Pending = make([]XInfoStreamConsumerPending, 0, pendingNumber) + + for pn := 0; pn < pendingNumber; pn++ { + nn, err := rd.ReadArrayLen() + if err != nil { + return nil, err + } + if nn != 3 { + return nil, fmt.Errorf("redis: got %d elements in XINFO STREAM reply,"+ + "wanted 3", nn) + } + + p := XInfoStreamConsumerPending{} + + p.ID, err = rd.ReadString() + if err != nil { + return nil, err + } + + delivery, err := rd.ReadIntReply() + if err != nil { + return nil, err + } + p.DeliveryTime = time.Unix(delivery/1000, delivery%1000*int64(time.Millisecond)) + + p.DeliveryCount, err = rd.ReadIntReply() + if err != nil { + return nil, err + } + + c.Pending = append(c.Pending, p) + } + default: + return nil, fmt.Errorf("redis: unexpected content %s "+ + "in XINFO STREAM reply", cKey) + } + if err != nil { + return nil, err + } + } + consumers = append(consumers, c) + } + + return consumers, nil +} + +//------------------------------------------------------------------------------ + type ZSliceCmd struct { baseCmd diff --git a/vendor/github.com/go-redis/redis/v8/commands.go b/vendor/github.com/go-redis/redis/v8/commands.go index f4e6afc14..9e1e5ad25 100644 --- a/vendor/github.com/go-redis/redis/v8/commands.go +++ b/vendor/github.com/go-redis/redis/v8/commands.go @@ -9,7 +9,8 @@ import ( "github.com/go-redis/redis/v8/internal" ) -// KeepTTL is an option for Set command to keep key's existing TTL. +// KeepTTL is a Redis KEEPTTL option to keep existing TTL, it requires your redis-server version >= 6.0, +// otherwise you will receive an error: (error) ERR syntax error. // For example: // // rdb.Set(ctx, key, value, redis.KeepTTL) @@ -67,6 +68,11 @@ func appendArg(dst []interface{}, arg interface{}) []interface{} { dst = append(dst, k, v) } return dst + case map[string]string: + for k, v := range arg { + dst = append(dst, k, v) + } + return dst default: return append(dst, arg) } @@ -117,6 +123,8 @@ type Cmdable interface { Get(ctx context.Context, key string) *StringCmd GetRange(ctx context.Context, key string, start, end int64) *StringCmd GetSet(ctx context.Context, key string, value interface{}) *StringCmd + GetEx(ctx context.Context, key string, expiration time.Duration) *StringCmd + GetDel(ctx context.Context, key string) *StringCmd Incr(ctx context.Context, key string) *IntCmd IncrBy(ctx context.Context, key string, value int64) *IntCmd IncrByFloat(ctx context.Context, key string, value float64) *FloatCmd @@ -124,6 +132,9 @@ 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 + // TODO: rename to SetEx + 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 +151,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 @@ -157,6 +169,7 @@ type Cmdable interface { HMSet(ctx context.Context, key string, values ...interface{}) *BoolCmd HSetNX(ctx context.Context, key, field string, value interface{}) *BoolCmd HVals(ctx context.Context, key string) *StringSliceCmd + HRandField(ctx context.Context, key string, count int, withValues bool) *StringSliceCmd BLPop(ctx context.Context, timeout time.Duration, keys ...string) *StringSliceCmd BRPop(ctx context.Context, timeout time.Duration, keys ...string) *StringSliceCmd @@ -167,6 +180,9 @@ 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 + LPopCount(ctx context.Context, key string, count int) *StringSliceCmd + 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 @@ -177,6 +193,7 @@ type Cmdable interface { RPopLPush(ctx context.Context, source, destination string) *StringCmd RPush(ctx context.Context, key string, values ...interface{}) *IntCmd RPushX(ctx context.Context, key string, values ...interface{}) *IntCmd + LMove(ctx context.Context, source, destination, srcpos, destpos string) *StringCmd SAdd(ctx context.Context, key string, members ...interface{}) *IntCmd SCard(ctx context.Context, key string) *IntCmd @@ -185,6 +202,7 @@ type Cmdable interface { SInter(ctx context.Context, keys ...string) *StringSliceCmd SInterStore(ctx context.Context, destination string, keys ...string) *IntCmd SIsMember(ctx context.Context, key string, member interface{}) *BoolCmd + SMIsMember(ctx context.Context, key string, members ...interface{}) *BoolSliceCmd SMembers(ctx context.Context, key string) *StringSliceCmd SMembersMap(ctx context.Context, key string) *StringStructMapCmd SMove(ctx context.Context, source, destination string, member interface{}) *BoolCmd @@ -209,6 +227,7 @@ type Cmdable interface { XGroupCreateMkStream(ctx context.Context, stream, group, start string) *StatusCmd XGroupSetID(ctx context.Context, stream, group, start string) *StatusCmd XGroupDestroy(ctx context.Context, stream, group string) *IntCmd + XGroupCreateConsumer(ctx context.Context, stream, group, consumer string) *IntCmd XGroupDelConsumer(ctx context.Context, stream, group, consumer string) *IntCmd XReadGroup(ctx context.Context, a *XReadGroupArgs) *XStreamSliceCmd XAck(ctx context.Context, stream, group string, ids ...string) *IntCmd @@ -216,19 +235,39 @@ type Cmdable interface { XPendingExt(ctx context.Context, a *XPendingExtArgs) *XPendingExtCmd XClaim(ctx context.Context, a *XClaimArgs) *XMessageSliceCmd XClaimJustID(ctx context.Context, a *XClaimArgs) *StringSliceCmd + + // TODO: XTrim and XTrimApprox remove in v9. XTrim(ctx context.Context, key string, maxLen int64) *IntCmd XTrimApprox(ctx context.Context, key string, maxLen int64) *IntCmd + XTrimMaxLen(ctx context.Context, key string, maxLen int64) *IntCmd + XTrimMaxLenApprox(ctx context.Context, key string, maxLen, limit int64) *IntCmd + XTrimMinID(ctx context.Context, key string, minID string) *IntCmd + XTrimMinIDApprox(ctx context.Context, key string, minID string, limit int64) *IntCmd XInfoGroups(ctx context.Context, key string) *XInfoGroupsCmd XInfoStream(ctx context.Context, key string) *XInfoStreamCmd + XInfoConsumers(ctx context.Context, key string, group string) *XInfoConsumersCmd BZPopMax(ctx context.Context, timeout time.Duration, keys ...string) *ZWithKeyCmd BZPopMin(ctx context.Context, timeout time.Duration, keys ...string) *ZWithKeyCmd + + // TODO: remove + // ZAddCh + // ZIncr + // ZAddNXCh + // ZAddXXCh + // ZIncrNX + // ZIncrXX + // in v9. + // use ZAddArgs and ZAddArgsIncr. + ZAdd(ctx context.Context, key string, members ...*Z) *IntCmd ZAddNX(ctx context.Context, key string, members ...*Z) *IntCmd ZAddXX(ctx context.Context, key string, members ...*Z) *IntCmd ZAddCh(ctx context.Context, key string, members ...*Z) *IntCmd ZAddNXCh(ctx context.Context, key string, members ...*Z) *IntCmd ZAddXXCh(ctx context.Context, key string, members ...*Z) *IntCmd + ZAddArgs(ctx context.Context, key string, args ZAddArgs) *IntCmd + ZAddArgsIncr(ctx context.Context, key string, args ZAddArgs) *FloatCmd ZIncr(ctx context.Context, key string, member *Z) *FloatCmd ZIncrNX(ctx context.Context, key string, member *Z) *FloatCmd ZIncrXX(ctx context.Context, key string, member *Z) *FloatCmd @@ -236,7 +275,10 @@ type Cmdable interface { ZCount(ctx context.Context, key, min, max string) *IntCmd ZLexCount(ctx context.Context, key, min, max string) *IntCmd ZIncrBy(ctx context.Context, key string, increment float64, member string) *FloatCmd + ZInter(ctx context.Context, store *ZStore) *StringSliceCmd + ZInterWithScores(ctx context.Context, store *ZStore) *ZSliceCmd ZInterStore(ctx context.Context, destination string, store *ZStore) *IntCmd + ZMScore(ctx context.Context, key string, members ...string) *FloatSliceCmd ZPopMax(ctx context.Context, key string, count ...int64) *ZSliceCmd ZPopMin(ctx context.Context, key string, count ...int64) *ZSliceCmd ZRange(ctx context.Context, key string, start, stop int64) *StringSliceCmd @@ -244,6 +286,9 @@ type Cmdable interface { ZRangeByScore(ctx context.Context, key string, opt *ZRangeBy) *StringSliceCmd ZRangeByLex(ctx context.Context, key string, opt *ZRangeBy) *StringSliceCmd ZRangeByScoreWithScores(ctx context.Context, key string, opt *ZRangeBy) *ZSliceCmd + ZRangeArgs(ctx context.Context, z ZRangeArgs) *StringSliceCmd + ZRangeArgsWithScores(ctx context.Context, z ZRangeArgs) *ZSliceCmd + ZRangeStore(ctx context.Context, dst string, z ZRangeArgs) *IntCmd ZRank(ctx context.Context, key, member string) *IntCmd ZRem(ctx context.Context, key string, members ...interface{}) *IntCmd ZRemRangeByRank(ctx context.Context, key string, start, stop int64) *IntCmd @@ -257,6 +302,12 @@ type Cmdable interface { ZRevRank(ctx context.Context, key, member string) *IntCmd ZScore(ctx context.Context, key, member string) *FloatCmd ZUnionStore(ctx context.Context, dest string, store *ZStore) *IntCmd + ZUnion(ctx context.Context, store ZStore) *StringSliceCmd + ZUnionWithScores(ctx context.Context, store ZStore) *ZSliceCmd + ZRandMember(ctx context.Context, key string, count int, withScores bool) *StringSliceCmd + ZDiff(ctx context.Context, keys ...string) *StringSliceCmd + ZDiffWithScores(ctx context.Context, keys ...string) *ZSliceCmd + ZDiffStore(ctx context.Context, destination string, keys ...string) *IntCmd PFAdd(ctx context.Context, key string, els ...interface{}) *IntCmd PFCount(ctx context.Context, keys ...string) *IntCmd @@ -361,7 +412,7 @@ func (c statefulCmdable) Auth(ctx context.Context, password string) *StatusCmd { return cmd } -// Perform an AUTH command, using the given user and pass. +// AuthACL Perform an AUTH command, using the given user and pass. // Should be used to authenticate the current connection with one of the connections defined in the ACL list // when connecting to a Redis 6.0 instance, or greater, that is using the Redis ACL system. func (c statefulCmdable) AuthACL(ctx context.Context, username, password string) *StatusCmd { @@ -422,7 +473,7 @@ func (c cmdable) Ping(ctx context.Context) *StatusCmd { return cmd } -func (c cmdable) Quit(ctx context.Context) *StatusCmd { +func (c cmdable) Quit(_ context.Context) *StatusCmd { panic("not implemented") } @@ -685,7 +736,7 @@ func (c cmdable) DecrBy(ctx context.Context, key string, decrement int64) *IntCm return cmd } -// Redis `GET key` command. It returns redis.Nil error when key does not exist. +// Get Redis `GET key` command. It returns redis.Nil error when key does not exist. func (c cmdable) Get(ctx context.Context, key string) *StringCmd { cmd := NewStringCmd(ctx, "get", key) _ = c(ctx, cmd) @@ -704,6 +755,33 @@ func (c cmdable) GetSet(ctx context.Context, key string, value interface{}) *Str return cmd } +// GetEx An expiration of zero removes the TTL associated with the key (i.e. GETEX key persist). +// Requires Redis >= 6.2.0. +func (c cmdable) GetEx(ctx context.Context, key string, expiration time.Duration) *StringCmd { + args := make([]interface{}, 0, 4) + args = append(args, "getex", key) + if expiration > 0 { + if usePrecise(expiration) { + args = append(args, "px", formatMs(ctx, expiration)) + } else { + args = append(args, "ex", formatSec(ctx, expiration)) + } + } else if expiration == 0 { + args = append(args, "persist") + } + + cmd := NewStringCmd(ctx, args...) + _ = c(ctx, cmd) + return cmd +} + +// GetDel redis-server version >= 6.2.0. +func (c cmdable) GetDel(ctx context.Context, key string) *StringCmd { + cmd := NewStringCmd(ctx, "getdel", key) + _ = c(ctx, cmd) + return cmd +} + func (c cmdable) Incr(ctx context.Context, key string) *IntCmd { cmd := NewIntCmd(ctx, "incr", key) _ = c(ctx, cmd) @@ -759,11 +837,12 @@ func (c cmdable) MSetNX(ctx context.Context, values ...interface{}) *BoolCmd { return cmd } -// Redis `SET key value [expiration]` command. +// Set Redis `SET key value [expiration]` command. // Use expiration for `SETEX`-like behavior. // // Zero expiration means the key has no expiration time. -// KeepTTL(-1) expiration is a Redis KEEPTTL option to keep existing TTL. +// KeepTTL is a Redis KEEPTTL option to keep existing TTL, it requires your redis-server version >= 6.0, +// otherwise you will receive an error: (error) ERR syntax error. func (c cmdable) Set(ctx context.Context, key string, value interface{}, expiration time.Duration) *StatusCmd { args := make([]interface{}, 3, 5) args[0] = "set" @@ -784,10 +863,69 @@ func (c cmdable) Set(ctx context.Context, key string, value interface{}, expirat return cmd } -// Redis `SET key value [expiration] NX` command. +// 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, it requires your redis-server version >= 6.0, + // otherwise you will receive an error: (error) ERR syntax error. + 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 +} + +// SetEX 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 +} + +// SetNX Redis `SET key value [expiration] NX` command. // // Zero expiration means the key has no expiration time. -// KeepTTL(-1) expiration is a Redis KEEPTTL option to keep existing TTL. +// KeepTTL is a Redis KEEPTTL option to keep existing TTL, it requires your redis-server version >= 6.0, +// otherwise you will receive an error: (error) ERR syntax error. func (c cmdable) SetNX(ctx context.Context, key string, value interface{}, expiration time.Duration) *BoolCmd { var cmd *BoolCmd switch expiration { @@ -808,10 +946,11 @@ func (c cmdable) SetNX(ctx context.Context, key string, value interface{}, expir return cmd } -// Redis `SET key value [expiration] XX` command. +// SetXX Redis `SET key value [expiration] XX` command. // // Zero expiration means the key has no expiration time. -// KeepTTL(-1) expiration is a Redis KEEPTTL option to keep existing TTL. +// KeepTTL is a Redis KEEPTTL option to keep existing TTL, it requires your redis-server version >= 6.0, +// otherwise you will receive an error: (error) ERR syntax error. func (c cmdable) SetXX(ctx context.Context, key string, value interface{}, expiration time.Duration) *BoolCmd { var cmd *BoolCmd switch expiration { @@ -955,6 +1094,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 != "" { @@ -1103,6 +1258,21 @@ func (c cmdable) HVals(ctx context.Context, key string) *StringSliceCmd { return cmd } +// HRandField redis-server version >= 6.2.0. +func (c cmdable) HRandField(ctx context.Context, key string, count int, withValues bool) *StringSliceCmd { + args := make([]interface{}, 0, 4) + + // Although count=0 is meaningless, redis accepts count=0. + args = append(args, "hrandfield", key, count) + if withValues { + args = append(args, "withvalues") + } + + cmd := NewStringSliceCmd(ctx, args...) + _ = c(ctx, cmd) + return cmd +} + //------------------------------------------------------------------------------ func (c cmdable) BLPop(ctx context.Context, timeout time.Duration, keys ...string) *StringSliceCmd { @@ -1180,6 +1350,43 @@ func (c cmdable) LPop(ctx context.Context, key string) *StringCmd { return cmd } +func (c cmdable) LPopCount(ctx context.Context, key string, count int) *StringSliceCmd { + cmd := NewStringSliceCmd(ctx, "lpop", key, count) + _ = c(ctx, cmd) + 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" @@ -1268,6 +1475,12 @@ func (c cmdable) RPushX(ctx context.Context, key string, values ...interface{}) return cmd } +func (c cmdable) LMove(ctx context.Context, source, destination, srcpos, destpos string) *StringCmd { + cmd := NewStringCmd(ctx, "lmove", source, destination, srcpos, destpos) + _ = c(ctx, cmd) + return cmd +} + //------------------------------------------------------------------------------ func (c cmdable) SAdd(ctx context.Context, key string, members ...interface{}) *IntCmd { @@ -1338,14 +1551,25 @@ func (c cmdable) SIsMember(ctx context.Context, key string, member interface{}) return cmd } -// Redis `SMEMBERS key` command output as a slice. +// SMIsMember Redis `SMISMEMBER key member [member ...]` command. +func (c cmdable) SMIsMember(ctx context.Context, key string, members ...interface{}) *BoolSliceCmd { + args := make([]interface{}, 2, 2+len(members)) + args[0] = "smismember" + args[1] = key + args = appendArgs(args, members) + cmd := NewBoolSliceCmd(ctx, args...) + _ = c(ctx, cmd) + return cmd +} + +// SMembers Redis `SMEMBERS key` command output as a slice. func (c cmdable) SMembers(ctx context.Context, key string) *StringSliceCmd { cmd := NewStringSliceCmd(ctx, "smembers", key) _ = c(ctx, cmd) return cmd } -// Redis `SMEMBERS key` command output as a map. +// SMembersMap Redis `SMEMBERS key` command output as a map. func (c cmdable) SMembersMap(ctx context.Context, key string) *StringStructMapCmd { cmd := NewStringStructMapCmd(ctx, "smembers", key) _ = c(ctx, cmd) @@ -1358,28 +1582,28 @@ func (c cmdable) SMove(ctx context.Context, source, destination string, member i return cmd } -// Redis `SPOP key` command. +// SPop Redis `SPOP key` command. func (c cmdable) SPop(ctx context.Context, key string) *StringCmd { cmd := NewStringCmd(ctx, "spop", key) _ = c(ctx, cmd) return cmd } -// Redis `SPOP key count` command. +// SPopN Redis `SPOP key count` command. func (c cmdable) SPopN(ctx context.Context, key string, count int64) *StringSliceCmd { cmd := NewStringSliceCmd(ctx, "spop", key, count) _ = c(ctx, cmd) return cmd } -// Redis `SRANDMEMBER key` command. +// SRandMember Redis `SRANDMEMBER key` command. func (c cmdable) SRandMember(ctx context.Context, key string) *StringCmd { cmd := NewStringCmd(ctx, "srandmember", key) _ = c(ctx, cmd) return cmd } -// Redis `SRANDMEMBER key count` command. +// SRandMemberN Redis `SRANDMEMBER key count` command. func (c cmdable) SRandMemberN(ctx context.Context, key string, count int64) *StringSliceCmd { cmd := NewStringSliceCmd(ctx, "srandmember", key, count) _ = c(ctx, cmd) @@ -1427,22 +1651,50 @@ func (c cmdable) SUnionStore(ctx context.Context, destination string, keys ...st // - XAddArgs.Values = map[string]interface{}{"key1": "value1", "key2": "value2"} // // Note that map will not preserve the order of key-value pairs. +// MaxLen/MaxLenApprox and MinID are in conflict, only one of them can be used. type XAddArgs struct { - Stream string - MaxLen int64 // MAXLEN N + Stream string + NoMkStream bool + MaxLen int64 // MAXLEN N + + // Deprecated: use MaxLen+Approx, remove in v9. MaxLenApprox int64 // MAXLEN ~ N - ID string - Values interface{} + + MinID string + // Approx causes MaxLen and MinID to use "~" matcher (instead of "="). + Approx bool + Limit int64 + ID string + Values interface{} } +// XAdd a.Limit has a bug, please confirm it and use it. +// issue: https://github.com/redis/redis/issues/9046 func (c cmdable) XAdd(ctx context.Context, a *XAddArgs) *StringCmd { - args := make([]interface{}, 0, 8) - args = append(args, "xadd") - args = append(args, a.Stream) - if a.MaxLen > 0 { - args = append(args, "maxlen", a.MaxLen) - } else if a.MaxLenApprox > 0 { + args := make([]interface{}, 0, 11) + args = append(args, "xadd", a.Stream) + if a.NoMkStream { + args = append(args, "nomkstream") + } + switch { + case a.MaxLen > 0: + if a.Approx { + args = append(args, "maxlen", "~", a.MaxLen) + } else { + args = append(args, "maxlen", a.MaxLen) + } + case a.MaxLenApprox > 0: + // TODO remove in v9. args = append(args, "maxlen", "~", a.MaxLenApprox) + case a.MinID != "": + if a.Approx { + args = append(args, "minid", "~", a.MinID) + } else { + args = append(args, "minid", a.MinID) + } + } + if a.Limit > 0 { + args = append(args, "limit", a.Limit) } if a.ID != "" { args = append(args, a.ID) @@ -1563,6 +1815,12 @@ func (c cmdable) XGroupDestroy(ctx context.Context, stream, group string) *IntCm return cmd } +func (c cmdable) XGroupCreateConsumer(ctx context.Context, stream, group, consumer string) *IntCmd { + cmd := NewIntCmd(ctx, "xgroup", "createconsumer", stream, group, consumer) + _ = c(ctx, cmd) + return cmd +} + func (c cmdable) XGroupDelConsumer(ctx context.Context, stream, group, consumer string) *IntCmd { cmd := NewIntCmd(ctx, "xgroup", "delconsumer", stream, group, consumer) _ = c(ctx, cmd) @@ -1582,7 +1840,7 @@ func (c cmdable) XReadGroup(ctx context.Context, a *XReadGroupArgs) *XStreamSlic args := make([]interface{}, 0, 8+len(a.Streams)) args = append(args, "xreadgroup", "group", a.Group, a.Consumer) - keyPos := int8(1) + keyPos := int8(4) if a.Count > 0 { args = append(args, "count", a.Count) keyPos += 2 @@ -1629,6 +1887,7 @@ func (c cmdable) XPending(ctx context.Context, stream, group string) *XPendingCm type XPendingExtArgs struct { Stream string Group string + Idle time.Duration Start string End string Count int64 @@ -1636,8 +1895,12 @@ type XPendingExtArgs struct { } func (c cmdable) XPendingExt(ctx context.Context, a *XPendingExtArgs) *XPendingExtCmd { - args := make([]interface{}, 0, 7) - args = append(args, "xpending", a.Stream, a.Group, a.Start, a.End, a.Count) + args := make([]interface{}, 0, 9) + args = append(args, "xpending", a.Stream, a.Group) + if a.Idle != 0 { + args = append(args, "idle", formatMs(ctx, a.Idle)) + } + args = append(args, a.Start, a.End, a.Count) if a.Consumer != "" { args = append(args, a.Consumer) } @@ -1646,6 +1909,39 @@ func (c cmdable) XPendingExt(ctx context.Context, a *XPendingExtArgs) *XPendingE return cmd } +type XAutoClaimArgs struct { + Stream string + Group string + MinIdle time.Duration + Start string + Count int64 + Consumer string +} + +func (c cmdable) XAutoClaim(ctx context.Context, a *XAutoClaimArgs) *XAutoClaimCmd { + args := xAutoClaimArgs(ctx, a) + cmd := NewXAutoClaimCmd(ctx, args...) + _ = c(ctx, cmd) + return cmd +} + +func (c cmdable) XAutoClaimJustID(ctx context.Context, a *XAutoClaimArgs) *XAutoClaimJustIDCmd { + args := xAutoClaimArgs(ctx, a) + args = append(args, "justid") + cmd := NewXAutoClaimJustIDCmd(ctx, args...) + _ = c(ctx, cmd) + return cmd +} + +func xAutoClaimArgs(ctx context.Context, a *XAutoClaimArgs) []interface{} { + args := make([]interface{}, 0, 9) + args = append(args, "xautoclaim", a.Stream, a.Group, a.Consumer, formatMs(ctx, a.MinIdle), a.Start) + if a.Count > 0 { + args = append(args, "count", a.Count) + } + return args +} + type XClaimArgs struct { Stream string Group string @@ -1682,14 +1978,67 @@ func xClaimArgs(a *XClaimArgs) []interface{} { return args } -func (c cmdable) XTrim(ctx context.Context, key string, maxLen int64) *IntCmd { - cmd := NewIntCmd(ctx, "xtrim", key, "maxlen", maxLen) +// xTrim If approx is true, add the "~" parameter, otherwise it is the default "=" (redis default). +// example: +// XTRIM key MAXLEN/MINID threshold LIMIT limit. +// XTRIM key MAXLEN/MINID ~ threshold LIMIT limit. +// The redis-server version is lower than 6.2, please set limit to 0. +func (c cmdable) xTrim( + ctx context.Context, key, strategy string, + approx bool, threshold interface{}, limit int64, +) *IntCmd { + args := make([]interface{}, 0, 7) + args = append(args, "xtrim", key, strategy) + if approx { + args = append(args, "~") + } + args = append(args, threshold) + if limit > 0 { + args = append(args, "limit", limit) + } + cmd := NewIntCmd(ctx, args...) _ = c(ctx, cmd) return cmd } +// Deprecated: use XTrimMaxLen, remove in v9. +func (c cmdable) XTrim(ctx context.Context, key string, maxLen int64) *IntCmd { + return c.xTrim(ctx, key, "maxlen", false, maxLen, 0) +} + +// Deprecated: use XTrimMaxLenApprox, remove in v9. func (c cmdable) XTrimApprox(ctx context.Context, key string, maxLen int64) *IntCmd { - cmd := NewIntCmd(ctx, "xtrim", key, "maxlen", "~", maxLen) + return c.xTrim(ctx, key, "maxlen", true, maxLen, 0) +} + +// XTrimMaxLen No `~` rules are used, `limit` cannot be used. +// cmd: XTRIM key MAXLEN maxLen +func (c cmdable) XTrimMaxLen(ctx context.Context, key string, maxLen int64) *IntCmd { + return c.xTrim(ctx, key, "maxlen", false, maxLen, 0) +} + +// XTrimMaxLenApprox LIMIT has a bug, please confirm it and use it. +// issue: https://github.com/redis/redis/issues/9046 +// cmd: XTRIM key MAXLEN ~ maxLen LIMIT limit +func (c cmdable) XTrimMaxLenApprox(ctx context.Context, key string, maxLen, limit int64) *IntCmd { + return c.xTrim(ctx, key, "maxlen", true, maxLen, limit) +} + +// XTrimMinID No `~` rules are used, `limit` cannot be used. +// cmd: XTRIM key MINID minID +func (c cmdable) XTrimMinID(ctx context.Context, key string, minID string) *IntCmd { + return c.xTrim(ctx, key, "minid", false, minID, 0) +} + +// XTrimMinIDApprox LIMIT has a bug, please confirm it and use it. +// issue: https://github.com/redis/redis/issues/9046 +// cmd: XTRIM key MINID ~ minID LIMIT limit +func (c cmdable) XTrimMinIDApprox(ctx context.Context, key string, minID string, limit int64) *IntCmd { + return c.xTrim(ctx, key, "minid", true, minID, limit) +} + +func (c cmdable) XInfoConsumers(ctx context.Context, key string, group string) *XInfoConsumersCmd { + cmd := NewXInfoConsumersCmd(ctx, key, group) _ = c(ctx, cmd) return cmd } @@ -1706,6 +2055,19 @@ func (c cmdable) XInfoStream(ctx context.Context, key string) *XInfoStreamCmd { return cmd } +// XInfoStreamFull XINFO STREAM FULL [COUNT count] +// redis-server >= 6.0. +func (c cmdable) XInfoStreamFull(ctx context.Context, key string, count int) *XInfoStreamFullCmd { + args := make([]interface{}, 0, 6) + args = append(args, "xinfo", "stream", key, "full") + if count > 0 { + args = append(args, "count", count) + } + cmd := NewXInfoStreamFullCmd(ctx, args...) + _ = c(ctx, cmd) + return cmd +} + //------------------------------------------------------------------------------ // Z represents sorted set member. @@ -1720,7 +2082,7 @@ type ZWithKey struct { Key string } -// ZStore is used as an arg to ZInterStore and ZUnionStore. +// ZStore is used as an arg to ZInter/ZInterStore and ZUnion/ZUnionStore. type ZStore struct { Keys []string Weights []float64 @@ -1728,7 +2090,34 @@ type ZStore struct { Aggregate string } -// Redis `BZPOPMAX key [key ...] timeout` command. +func (z ZStore) len() (n int) { + n = len(z.Keys) + if len(z.Weights) > 0 { + n += 1 + len(z.Weights) + } + if z.Aggregate != "" { + n += 2 + } + return n +} + +func (z ZStore) appendArgs(args []interface{}) []interface{} { + for _, key := range z.Keys { + args = append(args, key) + } + if len(z.Weights) > 0 { + args = append(args, "weights") + for _, weights := range z.Weights { + args = append(args, weights) + } + } + if z.Aggregate != "" { + args = append(args, "aggregate", z.Aggregate) + } + return args +} + +// BZPopMax Redis `BZPOPMAX key [key ...] timeout` command. func (c cmdable) BZPopMax(ctx context.Context, timeout time.Duration, keys ...string) *ZWithKeyCmd { args := make([]interface{}, 1+len(keys)+1) args[0] = "bzpopmax" @@ -1742,7 +2131,7 @@ func (c cmdable) BZPopMax(ctx context.Context, timeout time.Duration, keys ...st return cmd } -// Redis `BZPOPMIN key [key ...] timeout` command. +// BZPopMin Redis `BZPOPMIN key [key ...] timeout` command. func (c cmdable) BZPopMin(ctx context.Context, timeout time.Duration, keys ...string) *ZWithKeyCmd { args := make([]interface{}, 1+len(keys)+1) args[0] = "bzpopmin" @@ -1756,96 +2145,169 @@ func (c cmdable) BZPopMin(ctx context.Context, timeout time.Duration, keys ...st return cmd } -func (c cmdable) zAdd(ctx context.Context, a []interface{}, n int, members ...*Z) *IntCmd { +// ZAddArgs WARN: The GT, LT and NX options are mutually exclusive. +type ZAddArgs struct { + NX bool + XX bool + LT bool + GT bool + Ch bool + Members []Z +} + +func (c cmdable) zAddArgs(key string, args ZAddArgs, incr bool) []interface{} { + a := make([]interface{}, 0, 6+2*len(args.Members)) + a = append(a, "zadd", key) + + // The GT, LT and NX options are mutually exclusive. + if args.NX { + a = append(a, "nx") + } else { + if args.XX { + a = append(a, "xx") + } + if args.GT { + a = append(a, "gt") + } else if args.LT { + a = append(a, "lt") + } + } + if args.Ch { + a = append(a, "ch") + } + if incr { + a = append(a, "incr") + } + for _, m := range args.Members { + a = append(a, m.Score) + a = append(a, m.Member) + } + return a +} + +func (c cmdable) ZAddArgs(ctx context.Context, key string, args ZAddArgs) *IntCmd { + cmd := NewIntCmd(ctx, c.zAddArgs(key, args, false)...) + _ = c(ctx, cmd) + return cmd +} + +func (c cmdable) ZAddArgsIncr(ctx context.Context, key string, args ZAddArgs) *FloatCmd { + cmd := NewFloatCmd(ctx, c.zAddArgs(key, args, true)...) + _ = c(ctx, cmd) + return cmd +} + +// TODO: Compatible with v8 api, will be removed in v9. +func (c cmdable) zAdd(ctx context.Context, key string, args ZAddArgs, members ...*Z) *IntCmd { + args.Members = make([]Z, len(members)) for i, m := range members { - a[n+2*i] = m.Score - a[n+2*i+1] = m.Member + args.Members[i] = *m } - cmd := NewIntCmd(ctx, a...) + cmd := NewIntCmd(ctx, c.zAddArgs(key, args, false)...) _ = c(ctx, cmd) return cmd } -// Redis `ZADD key score member [score member ...]` command. +// ZAdd Redis `ZADD key score member [score member ...]` command. func (c cmdable) ZAdd(ctx context.Context, key string, members ...*Z) *IntCmd { - const n = 2 - a := make([]interface{}, n+2*len(members)) - a[0], a[1] = "zadd", key - return c.zAdd(ctx, a, n, members...) + return c.zAdd(ctx, key, ZAddArgs{}, members...) } -// Redis `ZADD key NX score member [score member ...]` command. +// ZAddNX Redis `ZADD key NX score member [score member ...]` command. func (c cmdable) ZAddNX(ctx context.Context, key string, members ...*Z) *IntCmd { - const n = 3 - a := make([]interface{}, n+2*len(members)) - a[0], a[1], a[2] = "zadd", key, "nx" - return c.zAdd(ctx, a, n, members...) + return c.zAdd(ctx, key, ZAddArgs{ + NX: true, + }, members...) } -// Redis `ZADD key XX score member [score member ...]` command. +// ZAddXX Redis `ZADD key XX score member [score member ...]` command. func (c cmdable) ZAddXX(ctx context.Context, key string, members ...*Z) *IntCmd { - const n = 3 - a := make([]interface{}, n+2*len(members)) - a[0], a[1], a[2] = "zadd", key, "xx" - return c.zAdd(ctx, a, n, members...) -} - -// Redis `ZADD key CH score member [score member ...]` command. + return c.zAdd(ctx, key, ZAddArgs{ + XX: true, + }, members...) +} + +// ZAddCh Redis `ZADD key CH score member [score member ...]` command. +// Deprecated: Use +// client.ZAddArgs(ctx, ZAddArgs{ +// Ch: true, +// Members: []Z, +// }) +// remove in v9. func (c cmdable) ZAddCh(ctx context.Context, key string, members ...*Z) *IntCmd { - const n = 3 - a := make([]interface{}, n+2*len(members)) - a[0], a[1], a[2] = "zadd", key, "ch" - return c.zAdd(ctx, a, n, members...) -} - -// Redis `ZADD key NX CH score member [score member ...]` command. + return c.zAdd(ctx, key, ZAddArgs{ + Ch: true, + }, members...) +} + +// ZAddNXCh Redis `ZADD key NX CH score member [score member ...]` command. +// Deprecated: Use +// client.ZAddArgs(ctx, ZAddArgs{ +// NX: true, +// Ch: true, +// Members: []Z, +// }) +// remove in v9. func (c cmdable) ZAddNXCh(ctx context.Context, key string, members ...*Z) *IntCmd { - const n = 4 - a := make([]interface{}, n+2*len(members)) - a[0], a[1], a[2], a[3] = "zadd", key, "nx", "ch" - return c.zAdd(ctx, a, n, members...) -} - -// Redis `ZADD key XX CH score member [score member ...]` command. + return c.zAdd(ctx, key, ZAddArgs{ + NX: true, + Ch: true, + }, members...) +} + +// ZAddXXCh Redis `ZADD key XX CH score member [score member ...]` command. +// Deprecated: Use +// client.ZAddArgs(ctx, ZAddArgs{ +// XX: true, +// Ch: true, +// Members: []Z, +// }) +// remove in v9. func (c cmdable) ZAddXXCh(ctx context.Context, key string, members ...*Z) *IntCmd { - const n = 4 - a := make([]interface{}, n+2*len(members)) - a[0], a[1], a[2], a[3] = "zadd", key, "xx", "ch" - return c.zAdd(ctx, a, n, members...) -} - -func (c cmdable) zIncr(ctx context.Context, a []interface{}, n int, members ...*Z) *FloatCmd { - for i, m := range members { - a[n+2*i] = m.Score - a[n+2*i+1] = m.Member - } - cmd := NewFloatCmd(ctx, a...) - _ = c(ctx, cmd) - return cmd -} - -// Redis `ZADD key INCR score member` command. + return c.zAdd(ctx, key, ZAddArgs{ + XX: true, + Ch: true, + }, members...) +} + +// ZIncr Redis `ZADD key INCR score member` command. +// Deprecated: Use +// client.ZAddArgsIncr(ctx, ZAddArgs{ +// Members: []Z, +// }) +// remove in v9. func (c cmdable) ZIncr(ctx context.Context, key string, member *Z) *FloatCmd { - const n = 3 - a := make([]interface{}, n+2) - a[0], a[1], a[2] = "zadd", key, "incr" - return c.zIncr(ctx, a, n, member) + return c.ZAddArgsIncr(ctx, key, ZAddArgs{ + Members: []Z{*member}, + }) } -// Redis `ZADD key NX INCR score member` command. +// ZIncrNX Redis `ZADD key NX INCR score member` command. +// Deprecated: Use +// client.ZAddArgsIncr(ctx, ZAddArgs{ +// NX: true, +// Members: []Z, +// }) +// remove in v9. func (c cmdable) ZIncrNX(ctx context.Context, key string, member *Z) *FloatCmd { - const n = 4 - a := make([]interface{}, n+2) - a[0], a[1], a[2], a[3] = "zadd", key, "incr", "nx" - return c.zIncr(ctx, a, n, member) + return c.ZAddArgsIncr(ctx, key, ZAddArgs{ + NX: true, + Members: []Z{*member}, + }) } -// Redis `ZADD key XX INCR score member` command. +// ZIncrXX Redis `ZADD key XX INCR score member` command. +// Deprecated: Use +// client.ZAddArgsIncr(ctx, ZAddArgs{ +// XX: true, +// Members: []Z, +// }) +// remove in v9. func (c cmdable) ZIncrXX(ctx context.Context, key string, member *Z) *FloatCmd { - const n = 4 - a := make([]interface{}, n+2) - a[0], a[1], a[2], a[3] = "zadd", key, "incr", "xx" - return c.zIncr(ctx, a, n, member) + return c.ZAddArgsIncr(ctx, key, ZAddArgs{ + XX: true, + Members: []Z{*member}, + }) } func (c cmdable) ZCard(ctx context.Context, key string) *IntCmd { @@ -1873,28 +2335,48 @@ func (c cmdable) ZIncrBy(ctx context.Context, key string, increment float64, mem } func (c cmdable) ZInterStore(ctx context.Context, destination string, store *ZStore) *IntCmd { - args := make([]interface{}, 3+len(store.Keys)) - args[0] = "zinterstore" - args[1] = destination - args[2] = len(store.Keys) - for i, key := range store.Keys { - args[3+i] = key - } - if len(store.Weights) > 0 { - args = append(args, "weights") - for _, weight := range store.Weights { - args = append(args, weight) - } - } - if store.Aggregate != "" { - args = append(args, "aggregate", store.Aggregate) - } + args := make([]interface{}, 0, 3+store.len()) + args = append(args, "zinterstore", destination, len(store.Keys)) + args = store.appendArgs(args) cmd := NewIntCmd(ctx, args...) cmd.setFirstKeyPos(3) _ = c(ctx, cmd) return cmd } +func (c cmdable) ZInter(ctx context.Context, store *ZStore) *StringSliceCmd { + args := make([]interface{}, 0, 2+store.len()) + args = append(args, "zinter", len(store.Keys)) + args = store.appendArgs(args) + cmd := NewStringSliceCmd(ctx, args...) + cmd.setFirstKeyPos(2) + _ = c(ctx, cmd) + return cmd +} + +func (c cmdable) ZInterWithScores(ctx context.Context, store *ZStore) *ZSliceCmd { + args := make([]interface{}, 0, 3+store.len()) + args = append(args, "zinter", len(store.Keys)) + args = store.appendArgs(args) + args = append(args, "withscores") + cmd := NewZSliceCmd(ctx, args...) + cmd.setFirstKeyPos(2) + _ = c(ctx, cmd) + return cmd +} + +func (c cmdable) ZMScore(ctx context.Context, key string, members ...string) *FloatSliceCmd { + args := make([]interface{}, 2+len(members)) + args[0] = "zmscore" + args[1] = key + for i, member := range members { + args[2+i] = member + } + cmd := NewFloatSliceCmd(ctx, args...) + _ = c(ctx, cmd) + return cmd +} + func (c cmdable) ZPopMax(ctx context.Context, key string, count ...int64) *ZSliceCmd { args := []interface{}{ "zpopmax", @@ -1935,29 +2417,112 @@ func (c cmdable) ZPopMin(ctx context.Context, key string, count ...int64) *ZSlic return cmd } -func (c cmdable) zRange(ctx context.Context, key string, start, stop int64, withScores bool) *StringSliceCmd { - args := []interface{}{ - "zrange", - key, - start, - stop, +// ZRangeArgs is all the options of the ZRange command. +// In version> 6.2.0, you can replace the(cmd): +// ZREVRANGE, +// ZRANGEBYSCORE, +// ZREVRANGEBYSCORE, +// ZRANGEBYLEX, +// ZREVRANGEBYLEX. +// Please pay attention to your redis-server version. +// +// Rev, ByScore, ByLex and Offset+Count options require redis-server 6.2.0 and higher. +type ZRangeArgs struct { + Key string + + // When the ByScore option is provided, the open interval(exclusive) can be set. + // By default, the score intervals specified by and are closed (inclusive). + // It is similar to the deprecated(6.2.0+) ZRangeByScore command. + // For example: + // ZRangeArgs{ + // Key: "example-key", + // Start: "(3", + // Stop: 8, + // ByScore: true, + // } + // cmd: "ZRange example-key (3 8 ByScore" (3 < score <= 8). + // + // For the ByLex option, it is similar to the deprecated(6.2.0+) ZRangeByLex command. + // You can set the and options as follows: + // ZRangeArgs{ + // Key: "example-key", + // Start: "[abc", + // Stop: "(def", + // ByLex: true, + // } + // cmd: "ZRange example-key [abc (def ByLex" + // + // For normal cases (ByScore==false && ByLex==false), and should be set to the index range (int). + // You can read the documentation for more information: https://redis.io/commands/zrange + Start interface{} + Stop interface{} + + // The ByScore and ByLex options are mutually exclusive. + ByScore bool + ByLex bool + + Rev bool + + // limit offset count. + Offset int64 + Count int64 +} + +func (z ZRangeArgs) appendArgs(args []interface{}) []interface{} { + // For Rev+ByScore/ByLex, we need to adjust the position of and . + if z.Rev && (z.ByScore || z.ByLex) { + args = append(args, z.Key, z.Stop, z.Start) + } else { + args = append(args, z.Key, z.Start, z.Stop) } - if withScores { - args = append(args, "withscores") + + if z.ByScore { + args = append(args, "byscore") + } else if z.ByLex { + args = append(args, "bylex") + } + if z.Rev { + args = append(args, "rev") + } + if z.Offset != 0 || z.Count != 0 { + args = append(args, "limit", z.Offset, z.Count) } + return args +} + +func (c cmdable) ZRangeArgs(ctx context.Context, z ZRangeArgs) *StringSliceCmd { + args := make([]interface{}, 0, 9) + args = append(args, "zrange") + args = z.appendArgs(args) cmd := NewStringSliceCmd(ctx, args...) _ = c(ctx, cmd) return cmd } +func (c cmdable) ZRangeArgsWithScores(ctx context.Context, z ZRangeArgs) *ZSliceCmd { + args := make([]interface{}, 0, 10) + args = append(args, "zrange") + args = z.appendArgs(args) + args = append(args, "withscores") + cmd := NewZSliceCmd(ctx, args...) + _ = c(ctx, cmd) + return cmd +} + func (c cmdable) ZRange(ctx context.Context, key string, start, stop int64) *StringSliceCmd { - return c.zRange(ctx, key, start, stop, false) + return c.ZRangeArgs(ctx, ZRangeArgs{ + Key: key, + Start: start, + Stop: stop, + }) } func (c cmdable) ZRangeWithScores(ctx context.Context, key string, start, stop int64) *ZSliceCmd { - cmd := NewZSliceCmd(ctx, "zrange", key, start, stop, "withscores") - _ = c(ctx, cmd) - return cmd + return c.ZRangeArgsWithScores(ctx, ZRangeArgs{ + Key: key, + Start: start, + Stop: stop, + }) } type ZRangeBy struct { @@ -2006,6 +2571,15 @@ func (c cmdable) ZRangeByScoreWithScores(ctx context.Context, key string, opt *Z return cmd } +func (c cmdable) ZRangeStore(ctx context.Context, dst string, z ZRangeArgs) *IntCmd { + args := make([]interface{}, 0, 10) + args = append(args, "zrangestore", dst) + args = z.appendArgs(args) + cmd := NewIntCmd(ctx, args...) + _ = c(ctx, cmd) + return cmd +} + func (c cmdable) ZRank(ctx context.Context, key, member string) *IntCmd { cmd := NewIntCmd(ctx, "zrank", key, member) _ = c(ctx, cmd) @@ -2108,26 +2682,91 @@ func (c cmdable) ZScore(ctx context.Context, key, member string) *FloatCmd { return cmd } +func (c cmdable) ZUnion(ctx context.Context, store ZStore) *StringSliceCmd { + args := make([]interface{}, 0, 2+store.len()) + args = append(args, "zunion", len(store.Keys)) + args = store.appendArgs(args) + cmd := NewStringSliceCmd(ctx, args...) + cmd.setFirstKeyPos(2) + _ = c(ctx, cmd) + return cmd +} + +func (c cmdable) ZUnionWithScores(ctx context.Context, store ZStore) *ZSliceCmd { + args := make([]interface{}, 0, 3+store.len()) + args = append(args, "zunion", len(store.Keys)) + args = store.appendArgs(args) + args = append(args, "withscores") + cmd := NewZSliceCmd(ctx, args...) + cmd.setFirstKeyPos(2) + _ = c(ctx, cmd) + return cmd +} + func (c cmdable) ZUnionStore(ctx context.Context, dest string, store *ZStore) *IntCmd { - args := make([]interface{}, 3+len(store.Keys)) - args[0] = "zunionstore" - args[1] = dest - args[2] = len(store.Keys) - for i, key := range store.Keys { - args[3+i] = key + args := make([]interface{}, 0, 3+store.len()) + args = append(args, "zunionstore", dest, len(store.Keys)) + args = store.appendArgs(args) + cmd := NewIntCmd(ctx, args...) + cmd.setFirstKeyPos(3) + _ = c(ctx, cmd) + return cmd +} + +// ZRandMember redis-server version >= 6.2.0. +func (c cmdable) ZRandMember(ctx context.Context, key string, count int, withScores bool) *StringSliceCmd { + args := make([]interface{}, 0, 4) + + // Although count=0 is meaningless, redis accepts count=0. + args = append(args, "zrandmember", key, count) + if withScores { + args = append(args, "withscores") } - if len(store.Weights) > 0 { - args = append(args, "weights") - for _, weight := range store.Weights { - args = append(args, weight) - } + + cmd := NewStringSliceCmd(ctx, args...) + _ = c(ctx, cmd) + return cmd +} + +// ZDiff redis-server version >= 6.2.0. +func (c cmdable) ZDiff(ctx context.Context, keys ...string) *StringSliceCmd { + args := make([]interface{}, 2+len(keys)) + args[0] = "zdiff" + args[1] = len(keys) + for i, key := range keys { + args[i+2] = key } - if store.Aggregate != "" { - args = append(args, "aggregate", store.Aggregate) + + cmd := NewStringSliceCmd(ctx, args...) + cmd.setFirstKeyPos(2) + _ = c(ctx, cmd) + return cmd +} + +// ZDiffWithScores redis-server version >= 6.2.0. +func (c cmdable) ZDiffWithScores(ctx context.Context, keys ...string) *ZSliceCmd { + args := make([]interface{}, 3+len(keys)) + args[0] = "zdiff" + args[1] = len(keys) + for i, key := range keys { + args[i+2] = key } + args[len(keys)+2] = "withscores" + + cmd := NewZSliceCmd(ctx, args...) + cmd.setFirstKeyPos(2) + _ = c(ctx, cmd) + return cmd +} +// ZDiffStore redis-server version >=6.2.0. +func (c cmdable) ZDiffStore(ctx context.Context, destination string, keys ...string) *IntCmd { + args := make([]interface{}, 0, 3+len(keys)) + args = append(args, "zdiffstore", destination, len(keys)) + for _, key := range keys { + args = append(args, key) + } cmd := NewIntCmd(ctx, args...) - cmd.setFirstKeyPos(3) _ = c(ctx, cmd) return cmd } @@ -2354,7 +2993,7 @@ func (c cmdable) SlowLogGet(ctx context.Context, num int64) *SlowLogCmd { return cmd } -func (c cmdable) Sync(ctx context.Context) { +func (c cmdable) Sync(_ context.Context) { panic("not implemented") } @@ -2391,6 +3030,7 @@ func (c cmdable) MemoryUsage(ctx context.Context, key string, samples ...int) *I args = append(args, "SAMPLES", samples[0]) } cmd := NewIntCmd(ctx, args...) + cmd.setFirstKeyPos(2) _ = c(ctx, cmd) return cmd } @@ -2407,6 +3047,7 @@ func (c cmdable) Eval(ctx context.Context, script string, keys []string, args .. } cmdArgs = appendArgs(cmdArgs, args) cmd := NewCmd(ctx, cmdArgs...) + cmd.setFirstKeyPos(3) _ = c(ctx, cmd) return cmd } @@ -2421,6 +3062,7 @@ func (c cmdable) EvalSha(ctx context.Context, sha1 string, keys []string, args . } cmdArgs = appendArgs(cmdArgs, args) cmd := NewCmd(ctx, cmdArgs...) + cmd.setFirstKeyPos(3) _ = c(ctx, cmd) return cmd } @@ -2669,7 +3311,7 @@ func (c cmdable) GeoRadiusStore( return cmd } -// GeoRadius is a read-only GEORADIUSBYMEMBER_RO command. +// GeoRadiusByMember is a read-only GEORADIUSBYMEMBER_RO command. func (c cmdable) GeoRadiusByMember( ctx context.Context, key, member string, query *GeoRadiusQuery, ) *GeoLocationCmd { diff --git a/vendor/github.com/go-redis/redis/v8/error.go b/vendor/github.com/go-redis/redis/v8/error.go index d29c0c99f..ad9e173ea 100644 --- a/vendor/github.com/go-redis/redis/v8/error.go +++ b/vendor/github.com/go-redis/redis/v8/error.go @@ -10,6 +10,7 @@ import ( "github.com/go-redis/redis/v8/internal/proto" ) +// ErrClosed performs any operation on the closed client will return this error. var ErrClosed = pool.ErrClosed type Error interface { @@ -52,6 +53,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 +66,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..c5ac42689 100644 --- a/vendor/github.com/go-redis/redis/v8/go.mod +++ b/vendor/github.com/go-redis/redis/v8/go.mod @@ -1,11 +1,11 @@ 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/google/go-cmp v0.5.6 // indirect + github.com/onsi/ginkgo v1.15.0 + github.com/onsi/gomega v1.10.5 ) diff --git a/vendor/github.com/go-redis/redis/v8/go.sum b/vendor/github.com/go-redis/redis/v8/go.sum index 82fcc1683..76abf5b46 100644 --- a/vendor/github.com/go-redis/redis/v8/go.sum +++ b/vendor/github.com/go-redis/redis/v8/go.sum @@ -1,7 +1,5 @@ github.com/cespare/xxhash/v2 v2.1.1 h1:6MnRN8NT7+YBpUIWxHtefFZOKTAPgGjpQSxqLNn0+qY= github.com/cespare/xxhash/v2 v2.1.1/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= -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/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f h1:lO4WD4F/rVNCu3HqELle0jiPLLBs70cWOduZpkS1E78= github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f/go.mod h1:cuUVRXasLTGF7a8hSLbxyZXjz+1KgoB3wDUb6vlszIc= github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo= @@ -18,45 +16,55 @@ 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.6 h1:BKbKCqvP6I+rmFHt06ZmyQtvB8xAkWdhFyr0ZUNZcxQ= +github.com/google/go-cmp v0.5.6/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/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/onsi/gomega v1.10.5 h1:7n6FEkpFmfCoo2t+YYqXH0evK+a9ICQz0xcAy9dYcaQ= +github.com/onsi/gomega v1.10.5/go.mod h1:gza4q3jKQJijlu05nKWRCW/GavJumGt8aNRxWg7mt48= +github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= 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= @@ -72,5 +80,3 @@ gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWD gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.3.0 h1:clyUAQHOM3G0M3f5vQj7LuJrETvjVot3Z5el9nffUtU= gopkg.in/yaml.v2 v2.3.0/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= -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/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/hashtag/hashtag.go b/vendor/github.com/go-redis/redis/v8/internal/hashtag/hashtag.go index 2fc74ad1c..b3a4f211e 100644 --- a/vendor/github.com/go-redis/redis/v8/internal/hashtag/hashtag.go +++ b/vendor/github.com/go-redis/redis/v8/internal/hashtag/hashtag.go @@ -60,7 +60,7 @@ func RandomSlot() int { return rand.Intn(slotNumber) } -// hashSlot returns a consistent slot number between 0 and 16383 +// Slot returns a consistent slot number between 0 and 16383 // for any given string key. func Slot(key string) int { if key == "" { 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..852c8bd52 --- /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 destination 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 deleted file mode 100644 index e837526d8..000000000 --- a/vendor/github.com/go-redis/redis/v8/internal/instruments.go +++ /dev/null @@ -1,33 +0,0 @@ -package internal - -import ( - "context" - - "go.opentelemetry.io/otel/api/global" - "go.opentelemetry.io/otel/api/metric" -) - -var ( - // WritesCounter is a count of write commands performed. - WritesCounter metric.Int64Counter - // NewConnectionsCounter is a count of new connections. - NewConnectionsCounter metric.Int64Counter -) - -func init() { - defer func() { - if r := recover(); r != nil { - Logger.Printf(context.Background(), "Error creating meter github.com/go-redis/redis for Instruments", r) - } - }() - - meter := metric.Must(global.Meter("github.com/go-redis/redis")) - - WritesCounter = meter.NewInt64Counter("redis.writes", - metric.WithDescription("the number of writes initiated"), - ) - - NewConnectionsCounter = meter.NewInt64Counter("redis.new_connections", - metric.WithDescription("the number of connections created"), - ) -} 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/log.go b/vendor/github.com/go-redis/redis/v8/internal/log.go index 3810f9e4e..c8b9213de 100644 --- a/vendor/github.com/go-redis/redis/v8/internal/log.go +++ b/vendor/github.com/go-redis/redis/v8/internal/log.go @@ -19,6 +19,8 @@ func (l *logger) Printf(ctx context.Context, format string, v ...interface{}) { _ = l.log.Output(2, fmt.Sprintf(format, v...)) } +// Logger calls Output to print to the stderr. +// Arguments are handled in the manner of fmt.Print. var Logger Logging = &logger{ log: log.New(os.Stderr, "redis: ", log.LstdFlags|log.Lshortfile), } 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..566165986 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 @@ -7,7 +7,6 @@ import ( "sync/atomic" "time" - "github.com/go-redis/redis/v8/internal" "github.com/go-redis/redis/v8/internal/proto" ) @@ -58,45 +57,35 @@ 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 { - if err := cn.netConn.SetReadDeadline(cn.deadline(ctx, timeout)); err != nil { - return internal.RecordError(ctx, err) - } - if err := fn(cn.rd); err != nil { - return internal.RecordError(ctx, err) - } - return nil - }) + if err := cn.netConn.SetReadDeadline(cn.deadline(ctx, timeout)); err != nil { + return err + } + return fn(cn.rd) } 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 { - if err := cn.netConn.SetWriteDeadline(cn.deadline(ctx, timeout)); err != nil { - return internal.RecordError(ctx, err) - } - - if cn.bw.Buffered() > 0 { - cn.bw.Reset(cn.netConn) - } - - if err := fn(cn.wr); err != nil { - return internal.RecordError(ctx, err) - } + if err := cn.netConn.SetWriteDeadline(cn.deadline(ctx, timeout)); err != nil { + return err + } - if err := cn.bw.Flush(); err != nil { - return internal.RecordError(ctx, err) - } + if cn.bw.Buffered() > 0 { + cn.bw.Reset(cn.netConn) + } - internal.WritesCounter.Add(ctx, 1) + if err := fn(cn.wr); err != nil { + return err + } - return nil - }) + return cn.bw.Flush() } func (cn *Conn) Close() error { 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..a8f0a6d4e 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 @@ -12,7 +12,10 @@ import ( ) var ( - ErrClosed = errors.New("redis: client is closed") + // ErrClosed performs any operation on the closed client will return this error. + ErrClosed = errors.New("redis: client is closed") + + // ErrPoolTimeout timed out waiting to get a connection from the connection pool. ErrPoolTimeout = errors.New("redis: connection pool timeout") ) @@ -185,7 +188,6 @@ func (p *ConnPool) dialConn(ctx context.Context, pooled bool) (*Conn, error) { return nil, err } - internal.NewConnectionsCounter.Add(ctx, 1) cn := NewConn(netConn) cn.pooled = pooled return cn, nil @@ -228,8 +230,7 @@ func (p *ConnPool) Get(ctx context.Context) (*Conn, error) { return nil, ErrClosed } - err := p.waitTurn(ctx) - if err != nil { + if err := p.waitTurn(ctx); err != nil { return nil, err } @@ -477,6 +478,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/pool/pool_sticky.go b/vendor/github.com/go-redis/redis/v8/internal/pool/pool_sticky.go index c3e7e7c04..3adb99bc8 100644 --- a/vendor/github.com/go-redis/redis/v8/internal/pool/pool_sticky.go +++ b/vendor/github.com/go-redis/redis/v8/internal/pool/pool_sticky.go @@ -172,8 +172,7 @@ func (p *StickyConnPool) Reset(ctx context.Context) error { func (p *StickyConnPool) badConnError() error { if v := p._badConnError.Load(); v != nil { - err := v.(BadConnError) - if err.wrapped != nil { + if err := v.(BadConnError); err.wrapped != nil { return err } } 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..10d1b4235 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 @@ -8,6 +8,7 @@ import ( "github.com/go-redis/redis/v8/internal/util" ) +// redis resp protocol data type. const ( ErrorReply = '-' StatusReply = '+' @@ -71,13 +72,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...) //nolint:makezero + 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..7d7183c32 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,12 @@ import ( "encoding" "fmt" "reflect" + "time" "github.com/go-redis/redis/v8/internal/util" ) +// Scan parses bytes `b` to `v` with appropriate type. func Scan(b []byte, v interface{}) error { switch v := v.(type) { case nil: @@ -99,6 +101,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 +130,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..e34a7f032 100644 --- a/vendor/github.com/go-redis/redis/v8/internal/util.go +++ b/vendor/github.com/go-redis/redis/v8/internal/util.go @@ -4,24 +4,19 @@ import ( "context" "time" - "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" ) func Sleep(ctx context.Context, dur time.Duration) error { - return WithSpan(ctx, "sleep", func(ctx context.Context) error { - t := time.NewTimer(dur) - defer t.Stop() + t := time.NewTimer(dur) + defer t.Stop() - select { - case <-t.C: - return nil - case <-ctx.Done(): - return ctx.Err() - } - }) + select { + case <-t.C: + return nil + case <-ctx.Done(): + return ctx.Err() + } } func ToLower(s string) string { @@ -49,33 +44,3 @@ 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) - } - - ctx, span := global.Tracer("github.com/go-redis/redis").Start(ctx, name) - defer span.End() - - return fn(ctx) -} - -func RecordError(ctx context.Context, err error) error { - if err != proto.Nil { - trace.SpanFromContext(ctx).RecordError(ctx, 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..8bbc27b82 100644 --- a/vendor/github.com/go-redis/redis/v8/options.go +++ b/vendor/github.com/go-redis/redis/v8/options.go @@ -12,10 +12,7 @@ import ( "strings" "time" - "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" ) // Limiter is the interface of a rate limiter or a circuit breaker. @@ -29,6 +26,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 +55,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. @@ -79,7 +77,7 @@ type Options struct { WriteTimeout time.Duration // Maximum number of socket connections. - // Default is 10 connections per every CPU as reported by runtime.NumCPU. + // Default is 10 connections per every available CPU as reported by runtime.GOMAXPROCS. PoolSize int // Minimum number of idle connections which is useful when establishing // new connection is slow. @@ -138,7 +136,7 @@ func (opt *Options) init() { } } if opt.PoolSize == 0 { - opt.PoolSize = 10 * runtime.NumCPU() + opt.PoolSize = 10 * runtime.GOMAXPROCS(0) } switch opt.ReadTimeout { case -1: @@ -187,26 +185,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,35 +236,60 @@ 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), - ) - conn, err = opt.Dialer(ctx, opt.Network, opt.Addr) - if err != nil { - _ = internal.RecordError(ctx, err) - } - return err - }) - return conn, err + return opt.Dialer(ctx, opt.Network, opt.Addr) }, PoolSize: opt.PoolSize, MinIdleConns: opt.MinIdleConns, diff --git a/vendor/github.com/go-redis/redis/v8/pubsub.go b/vendor/github.com/go-redis/redis/v8/pubsub.go index c56270b44..c6ffb2562 100644 --- a/vendor/github.com/go-redis/redis/v8/pubsub.go +++ b/vendor/github.com/go-redis/redis/v8/pubsub.go @@ -2,7 +2,6 @@ package redis import ( "context" - "errors" "fmt" "strings" "sync" @@ -13,13 +12,6 @@ import ( "github.com/go-redis/redis/v8/internal/proto" ) -const ( - pingTimeout = time.Second - chanSendTimeout = time.Minute -) - -var errPingTimeout = errors.New("redis: ping timeout") - // PubSub implements Pub/Sub commands as described in // http://redis.io/topics/pubsub. Message receiving is NOT safe // for concurrent use by multiple goroutines. @@ -43,9 +35,12 @@ type PubSub struct { cmd *Cmd chOnce sync.Once - msgCh chan *Message - allCh chan interface{} - ping chan struct{} + msgCh *channel + allCh *channel +} + +func (c *PubSub) init() { + c.exit = make(chan struct{}) } func (c *PubSub) String() string { @@ -54,10 +49,6 @@ func (c *PubSub) String() string { return fmt.Sprintf("PubSub(%s)", strings.Join(channels, ", ")) } -func (c *PubSub) init() { - c.exit = make(chan struct{}) -} - func (c *PubSub) connWithLock(ctx context.Context) (*pool.Conn, error) { c.mu.Lock() cn, err := c.conn(ctx, nil) @@ -418,6 +409,15 @@ func (c *PubSub) ReceiveMessage(ctx context.Context) (*Message, error) { } } +func (c *PubSub) getContext() context.Context { + if c.cmd != nil { + return c.cmd.ctx + } + return context.Background() +} + +//------------------------------------------------------------------------------ + // Channel returns a Go channel for concurrently receiving messages. // The channel is closed together with the PubSub. If the Go channel // is blocked full for 30 seconds the message is dropped. @@ -425,26 +425,24 @@ func (c *PubSub) ReceiveMessage(ctx context.Context) (*Message, error) { // // go-redis periodically sends ping messages to test connection health // and re-subscribes if ping can not not received for 30 seconds. -func (c *PubSub) Channel() <-chan *Message { - return c.ChannelSize(100) -} - -// ChannelSize is like Channel, but creates a Go channel -// with specified buffer size. -func (c *PubSub) ChannelSize(size int) <-chan *Message { +func (c *PubSub) Channel(opts ...ChannelOption) <-chan *Message { c.chOnce.Do(func() { - c.initPing() - c.initMsgChan(size) + c.msgCh = newChannel(c, opts...) + c.msgCh.initMsgChan() }) if c.msgCh == nil { err := fmt.Errorf("redis: Channel can't be called after ChannelWithSubscriptions") panic(err) } - if cap(c.msgCh) != size { - err := fmt.Errorf("redis: PubSub.Channel size can not be changed once created") - panic(err) - } - return c.msgCh + return c.msgCh.msgCh +} + +// ChannelSize is like Channel, but creates a Go channel +// with specified buffer size. +// +// Deprecated: use Channel(WithChannelSize(size)), remove in v9. +func (c *PubSub) ChannelSize(size int) <-chan *Message { + return c.Channel(WithChannelSize(size)) } // ChannelWithSubscriptions is like Channel, but message type can be either @@ -452,59 +450,101 @@ func (c *PubSub) ChannelSize(size int) <-chan *Message { // reconnections. // // ChannelWithSubscriptions can not be used together with Channel or ChannelSize. -func (c *PubSub) ChannelWithSubscriptions(ctx context.Context, size int) <-chan interface{} { +func (c *PubSub) ChannelWithSubscriptions(_ context.Context, size int) <-chan interface{} { c.chOnce.Do(func() { - c.initPing() - c.initAllChan(size) + c.allCh = newChannel(c, WithChannelSize(size)) + c.allCh.initAllChan() }) if c.allCh == nil { err := fmt.Errorf("redis: ChannelWithSubscriptions can't be called after Channel") panic(err) } - if cap(c.allCh) != size { - err := fmt.Errorf("redis: PubSub.Channel size can not be changed once created") - panic(err) + return c.allCh.allCh +} + +type ChannelOption func(c *channel) + +// WithChannelSize specifies the Go chan size that is used to buffer incoming messages. +// +// The default is 100 messages. +func WithChannelSize(size int) ChannelOption { + return func(c *channel) { + c.chanSize = size } - return c.allCh } -func (c *PubSub) getContext() context.Context { - if c.cmd != nil { - return c.cmd.ctx +// WithChannelHealthCheckInterval specifies the health check interval. +// PubSub will ping Redis Server if it does not receive any messages within the interval. +// To disable health check, use zero interval. +// +// The default is 3 seconds. +func WithChannelHealthCheckInterval(d time.Duration) ChannelOption { + return func(c *channel) { + c.checkInterval = d } - return context.Background() } -func (c *PubSub) initPing() { +// WithChannelSendTimeout specifies the channel send timeout after which +// the message is dropped. +// +// The default is 60 seconds. +func WithChannelSendTimeout(d time.Duration) ChannelOption { + return func(c *channel) { + c.chanSendTimeout = d + } +} + +type channel struct { + pubSub *PubSub + + msgCh chan *Message + allCh chan interface{} + ping chan struct{} + + chanSize int + chanSendTimeout time.Duration + checkInterval time.Duration +} + +func newChannel(pubSub *PubSub, opts ...ChannelOption) *channel { + c := &channel{ + pubSub: pubSub, + + chanSize: 100, + chanSendTimeout: time.Minute, + checkInterval: 3 * time.Second, + } + for _, opt := range opts { + opt(c) + } + if c.checkInterval > 0 { + c.initHealthCheck() + } + return c +} + +func (c *channel) initHealthCheck() { ctx := context.TODO() c.ping = make(chan struct{}, 1) + go func() { timer := time.NewTimer(time.Minute) timer.Stop() - healthy := true for { - timer.Reset(pingTimeout) + timer.Reset(c.checkInterval) select { case <-c.ping: - healthy = true if !timer.Stop() { <-timer.C } case <-timer.C: - pingErr := c.Ping(ctx) - if healthy { - healthy = false - } else { - if pingErr == nil { - pingErr = errPingTimeout - } - c.mu.Lock() - c.reconnect(ctx, pingErr) - healthy = true - c.mu.Unlock() + if pingErr := c.pubSub.Ping(ctx); pingErr != nil { + c.pubSub.mu.Lock() + c.pubSub.reconnect(ctx, pingErr) + c.pubSub.mu.Unlock() } - case <-c.exit: + case <-c.pubSub.exit: return } } @@ -512,16 +552,17 @@ func (c *PubSub) initPing() { } // initMsgChan must be in sync with initAllChan. -func (c *PubSub) initMsgChan(size int) { +func (c *channel) initMsgChan() { ctx := context.TODO() - c.msgCh = make(chan *Message, size) + c.msgCh = make(chan *Message, c.chanSize) + go func() { timer := time.NewTimer(time.Minute) timer.Stop() var errCount int for { - msg, err := c.Receive(ctx) + msg, err := c.pubSub.Receive(ctx) if err != nil { if err == pool.ErrClosed { close(c.msgCh) @@ -548,7 +589,7 @@ func (c *PubSub) initMsgChan(size int) { case *Pong: // Ignore. case *Message: - timer.Reset(chanSendTimeout) + timer.Reset(c.chanSendTimeout) select { case c.msgCh <- msg: if !timer.Stop() { @@ -556,30 +597,28 @@ func (c *PubSub) initMsgChan(size int) { } case <-timer.C: internal.Logger.Printf( - c.getContext(), - "redis: %s channel is full for %s (message is dropped)", - c, - chanSendTimeout, - ) + ctx, "redis: %s channel is full for %s (message is dropped)", + c, c.chanSendTimeout) } default: - internal.Logger.Printf(c.getContext(), "redis: unknown message type: %T", msg) + internal.Logger.Printf(ctx, "redis: unknown message type: %T", msg) } } }() } // initAllChan must be in sync with initMsgChan. -func (c *PubSub) initAllChan(size int) { +func (c *channel) initAllChan() { ctx := context.TODO() - c.allCh = make(chan interface{}, size) + c.allCh = make(chan interface{}, c.chanSize) + go func() { - timer := time.NewTimer(pingTimeout) + timer := time.NewTimer(time.Minute) timer.Stop() var errCount int for { - msg, err := c.Receive(ctx) + msg, err := c.pubSub.Receive(ctx) if err != nil { if err == pool.ErrClosed { close(c.allCh) @@ -601,29 +640,23 @@ func (c *PubSub) initAllChan(size int) { } switch msg := msg.(type) { - case *Subscription: - c.sendMessage(msg, timer) case *Pong: // Ignore. - case *Message: - c.sendMessage(msg, timer) + case *Subscription, *Message: + timer.Reset(c.chanSendTimeout) + select { + case c.allCh <- msg: + if !timer.Stop() { + <-timer.C + } + case <-timer.C: + internal.Logger.Printf( + ctx, "redis: %s channel is full for %s (message is dropped)", + c, c.chanSendTimeout) + } default: - internal.Logger.Printf(c.getContext(), "redis: unknown message type: %T", msg) + internal.Logger.Printf(ctx, "redis: unknown message type: %T", msg) } } }() } - -func (c *PubSub) sendMessage(msg interface{}, timer *time.Timer) { - timer.Reset(pingTimeout) - select { - case c.allCh <- msg: - if !timer.Stop() { - <-timer.C - } - case <-timer.C: - internal.Logger.Printf( - c.getContext(), - "redis: %s channel is full for %s (message is dropped)", c, pingTimeout) - } -} diff --git a/vendor/github.com/go-redis/redis/v8/redis.go b/vendor/github.com/go-redis/redis/v8/redis.go index 3cff1b5e3..98d603497 100644 --- a/vendor/github.com/go-redis/redis/v8/redis.go +++ b/vendor/github.com/go-redis/redis/v8/redis.go @@ -2,7 +2,9 @@ package redis import ( "context" + "errors" "fmt" + "sync/atomic" "time" "github.com/go-redis/redis/v8/internal" @@ -127,20 +129,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 +212,9 @@ func (c *baseClient) _getConn(ctx context.Context) (*pool.Conn, error) { return cn, nil } - err = internal.WithSpan(ctx, "init_conn", func(ctx context.Context) error { - return c.initConn(ctx, cn) - }) - if err != nil { + if err := c.initConn(ctx, cn); 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,18 +283,36 @@ 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 { - cn, err := c.getConn(ctx) - if err != nil { - return err - } - defer func() { - c.releaseConn(ctx, cn, err) - }() + cn, err := c.getConn(ctx) + if err != nil { + return err + } + + defer func() { + c.releaseConn(ctx, cn, err) + }() + done := ctx.Done() //nolint:ifshort + + 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 + } } func (c *baseClient) process(ctx context.Context, cmd Cmder) error { @@ -316,45 +320,50 @@ func (c *baseClient) process(ctx context.Context, cmd Cmder) error { for attempt := 0; attempt <= c.opt.MaxRetries; attempt++ { attempt := attempt - var retry bool - err := internal.WithSpan(ctx, "process", func(ctx context.Context) error { - if attempt > 0 { - if err := internal.Sleep(ctx, c.retryBackoff(attempt)); err != nil { - return err - } - } - - retryTimeout := true - 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) - }) - if err != nil { - return err - } - - err = cn.WithReader(ctx, c.cmdTimeout(cmd), cmd.readReply) - if err != nil { - retryTimeout = cmd.readTimeout() == nil - return err - } - - return nil - }) - if err == nil { - return nil - } - retry = shouldRetry(err, retryTimeout) - return err - }) + retry, err := c._process(ctx, cmd, attempt) if err == nil || !retry { return err } + lastErr = err } return lastErr } +func (c *baseClient) _process(ctx context.Context, cmd Cmder, attempt int) (bool, error) { + if attempt > 0 { + if err := internal.Sleep(ctx, c.retryBackoff(attempt)); err != nil { + return false, err + } + } + + 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) + }) + if err != nil { + return err + } + + err = cn.WithReader(ctx, c.cmdTimeout(cmd), cmd.readReply) + if err != nil { + if cmd.readTimeout() == nil { + atomic.StoreUint32(&retryTimeout, 1) + } + return err + } + + return nil + }) + if err == nil { + return false, nil + } + + retry := shouldRetry(err, atomic.LoadUint32(&retryTimeout) == 1) + return retry, err +} + func (c *baseClient) retryBackoff(attempt int) time.Duration { return internal.RetryBackoff(attempt, c.opt.MinRetryBackoff, c.opt.MaxRetryBackoff) } @@ -710,6 +719,7 @@ type conn struct { baseClient cmdable statefulCmdable + hooks // TODO: inherit hooks } // Conn is like Client, but its pool contains single connection. @@ -734,7 +744,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..ca2e088a7 100644 --- a/vendor/github.com/go-redis/redis/v8/sentinel.go +++ b/vendor/github.com/go-redis/redis/v8/sentinel.go @@ -36,6 +36,10 @@ 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 + // Following options are copied from Options struct. Dialer func(ctx context.Context, network, addr string) (net.Conn, error) @@ -167,6 +171,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 +185,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), @@ -208,14 +219,21 @@ func masterSlaveDialer( failover.trySwitchMaster(ctx, addr) } } - if err != nil { return nil, err } if failover.opt.Dialer != nil { return failover.opt.Dialer(ctx, network, addr) } - return net.DialTimeout("tcp", addr, failover.opt.DialTimeout) + + netDialer := &net.Dialer{ + Timeout: failover.opt.DialTimeout, + KeepAlive: 5 * time.Minute, + } + if failover.opt.TLSConfig == nil { + return netDialer.DialContext(ctx, network, addr) + } + return tls.DialWithDialer(netDialer, network, addr, failover.opt.TLSConfig) } } @@ -430,10 +448,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 +512,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 +538,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 +550,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 +585,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 +611,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 + } } } @@ -589,7 +630,7 @@ func parseSlaveAddrs(addrs []interface{}) []string { func (c *sentinelFailover) trySwitchMaster(ctx context.Context, addr string) { c.mu.RLock() - currentAddr := c._masterAddr + currentAddr := c._masterAddr //nolint:ifshort c.mu.RUnlock() if addr == currentAddr { @@ -630,15 +671,22 @@ func (c *sentinelFailover) discoverSentinels(ctx context.Context) { } for _, sentinel := range sentinels { vals := sentinel.([]interface{}) + var ip, port string for i := 0; i < len(vals); i += 2 { key := vals[i].(string) - if key == "name" { - sentinelAddr := vals[i+1].(string) - if !contains(c.sentinelAddrs, sentinelAddr) { - internal.Logger.Printf(ctx, "sentinel: discovered new sentinel=%q for master=%q", - sentinelAddr, c.opt.MasterName) - c.sentinelAddrs = append(c.sentinelAddrs, sentinelAddr) - } + switch key { + case "ip": + ip = vals[i+1].(string) + case "port": + port = vals[i+1].(string) + } + } + if ip != "" && port != "" { + sentinelAddr := net.JoinHostPort(ip, port) + if !contains(c.sentinelAddrs, sentinelAddr) { + internal.Logger.Printf(ctx, "sentinel: discovered new sentinel=%q for master=%q", + sentinelAddr, c.opt.MasterName) + c.sentinelAddrs = append(c.sentinelAddrs, sentinelAddr) } } } @@ -646,6 +694,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 +750,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 +772,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..bb5f8b616 100644 --- a/vendor/github.com/go-redis/redis/v8/universal.go +++ b/vendor/github.com/go-redis/redis/v8/universal.go @@ -53,6 +53,7 @@ type UniversalOptions struct { // The sentinel master name. // Only failover clients. + MasterName string } @@ -168,9 +169,9 @@ func (o *UniversalOptions) Simple() *Options { // -------------------------------------------------------------------- // UniversalClient is an abstract client which - based on the provided options - -// can connect to either clusters, or sentinel-backed failover instances -// or simple single-instance servers. This can be useful for testing -// cluster-specific applications locally. +// represents either a ClusterClient, a FailoverClient, or a single-node Client. +// This can be useful for testing cluster-specific applications locally or having different +// clients in different environments. type UniversalClient interface { Cmdable Context() context.Context @@ -181,6 +182,7 @@ type UniversalClient interface { Subscribe(ctx context.Context, channels ...string) *PubSub PSubscribe(ctx context.Context, channels ...string) *PubSub Close() error + PoolStats() *PoolStats } var ( @@ -189,12 +191,12 @@ var ( _ UniversalClient = (*Ring)(nil) ) -// NewUniversalClient returns a new multi client. The type of client returned depends -// on the following three conditions: +// NewUniversalClient returns a new multi client. The type of the returned client depends +// on the following conditions: // -// 1. if a MasterName is passed a sentinel-backed FailoverClient will be returned -// 2. if the number of Addrs is two or more, a ClusterClient will be returned -// 3. otherwise, a single-node redis Client will be returned. +// 1. If the MasterName option is specified, a sentinel-backed FailoverClient is returned. +// 2. if the number of Addrs is two or more, a ClusterClient is returned. +// 3. Otherwise, a single-node Client is returned. func NewUniversalClient(opts *UniversalOptions) UniversalClient { if opts.MasterName != "" { return NewFailoverClient(opts.Failover()) diff --git a/vendor/go.opentelemetry.io/otel/.gitignore b/vendor/go.opentelemetry.io/otel/.gitignore deleted file mode 100644 index cbef19714..000000000 --- a/vendor/go.opentelemetry.io/otel/.gitignore +++ /dev/null @@ -1,22 +0,0 @@ -.DS_Store -Thumbs.db - -.tools/ -.idea/ -.vscode/ -*.iml -*.so -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/prometheus/prometheus -/example/zipkin/zipkin -/example/otel-collector/otel-collector diff --git a/vendor/go.opentelemetry.io/otel/.gitmodules b/vendor/go.opentelemetry.io/otel/.gitmodules deleted file mode 100644 index 38a1f5698..000000000 --- a/vendor/go.opentelemetry.io/otel/.gitmodules +++ /dev/null @@ -1,3 +0,0 @@ -[submodule "opentelemetry-proto"] - path = exporters/otlp/internal/opentelemetry-proto - url = https://github.com/open-telemetry/opentelemetry-proto diff --git a/vendor/go.opentelemetry.io/otel/.golangci.yml b/vendor/go.opentelemetry.io/otel/.golangci.yml deleted file mode 100644 index 2ef168198..000000000 --- a/vendor/go.opentelemetry.io/otel/.golangci.yml +++ /dev/null @@ -1,32 +0,0 @@ -# See https://github.com/golangci/golangci-lint#config-file -run: - issues-exit-code: 1 #Default - tests: true #Default - -linters: - enable: - - misspell - - goimports - - golint - - gofmt - -issues: - exclude-rules: - # helpers in tests often (rightfully) pass a *testing.T as their first argument - - path: _test\.go - text: "context.Context should be the first parameter of a function" - linters: - - golint - # Yes, they are, but it's okay in a test - - path: _test\.go - text: "exported func.*returns unexported type.*which can be annoying to use" - linters: - - golint - -linters-settings: - misspell: - locale: US - ignore-words: - - cancelled - goimports: - local-prefixes: go.opentelemetry.io diff --git a/vendor/go.opentelemetry.io/otel/CHANGELOG.md b/vendor/go.opentelemetry.io/otel/CHANGELOG.md deleted file mode 100644 index e553b56ae..000000000 --- a/vendor/go.opentelemetry.io/otel/CHANGELOG.md +++ /dev/null @@ -1,803 +0,0 @@ -# Changelog - -All notable changes to this project will be documented in this file. - -The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/). - -This project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). - -## [Unreleased] - -## [0.11.0] - 2020-08-24 - -### Added - -- `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) - -### Changed - -- Rename `sdk/metric/processor/test` to `sdk/metric/processor/processortest`. (#1049) -- Rename `sdk/metric/controller/test` to `sdk/metric/controller/controllertest`. (#1049) -- Rename `api/testharness` to `api/apitest`. (#1049) -- Rename `api/trace/testtrace` to `api/trace/tracetest`. (#1049) -- Change Metric Processor to merge multiple observations. (#1024) -- The `go.opentelemetry.io/otel/bridge/opentracing` bridge package has been made into its own module. - This removes the package dependencies of this bridge from the rest of the OpenTelemetry based project. (#1038) -- Renamed `go.opentelemetry.io/otel/api/standard` package to `go.opentelemetry.io/otel/semconv` to avoid the ambiguous and generic name `standard` and better describe the package as containing OpenTelemetry semantic conventions. (#1016) -- The environment variable used for resource detection has been changed from `OTEL_RESOURCE_LABELS` to `OTEL_RESOURCE_ATTRIBUTES` (#1042) -- Replace `WithSyncer` with `WithBatcher` in examples. (#1044) -- Replace the `google.golang.org/grpc/codes` dependency in the API with an equivalent `go.opentelemetry.io/otel/codes` package. (#1046) -- Merge the `go.opentelemetry.io/otel/api/label` and `go.opentelemetry.io/otel/api/kv` into the new `go.opentelemetry.io/otel/label` package. (#1060) -- 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) - -### Removed - -- Duplicate, unused API sampler interface. (#999) - Use the [`Sampler` interface](https://github.com/open-telemetry/opentelemetry-go/blob/v0.11.0/sdk/trace/sampling.go) provided by the SDK instead. -- The `grpctrace` instrumentation was moved to the `go.opentelemetry.io/contrib` repository and out of this repository. - This move includes moving the `grpc` example to the `go.opentelemetry.io/contrib` as well. (#1027) -- The `WithSpan` method of the `Tracer` interface. - The functionality this method provided was limited compared to what a user can provide themselves. - It was removed with the understanding that if there is sufficient user need it can be added back based on actual user usage. (#1043) -- The `RegisterSpanProcessor` and `UnregisterSpanProcessor` functions. - These were holdovers from an approach prior to the TracerProvider design. They were not used anymore. (#1077) -- The `oterror` package. (#1026) -- The `othttp` and `httptrace` instrumentations were moved to `go.opentelemetry.io/contrib`. (#1032) - -### Fixed - -- The `semconv.HTTPServerMetricAttributesFromHTTPRequest()` function no longer generates the high-cardinality `http.request.content.length` label. (#1031) -- Correct instrumentation version tag in Jaeger exporter. (#1037) -- The SDK span will now set an error event if the `End` method is called during a panic (i.e. it was deferred). (#1043) -- Move internally generated protobuf code from the `go.opentelemetry.io/otel` to the OTLP exporter to reduce dependency overhead. (#1050) -- The `otel-collector` example referenced outdated collector processors. (#1006) - -## [0.10.0] - 2020-07-29 - -This release migrates the default OpenTelemetry SDK into its own Go module, decoupling the SDK from the API and reducing dependencies for instrumentation packages. - -### Added - -- The Zipkin exporter now has `NewExportPipeline` and `InstallNewPipeline` constructor functions to match the common pattern. - These function build a new exporter with default SDK options and register the exporter with the `global` package respectively. (#944) -- Add propagator option for gRPC instrumentation. (#986) -- The `testtrace` package now tracks the `trace.SpanKind` for each span. (#987) - -### Changed - -- Replace the `RegisterGlobal` `Option` in the Jaeger exporter with an `InstallNewPipeline` constructor function. - This matches the other exporter constructor patterns and will register a new exporter after building it with default configuration. (#944) -- The trace (`go.opentelemetry.io/otel/exporters/trace/stdout`) and metric (`go.opentelemetry.io/otel/exporters/metric/stdout`) `stdout` exporters are now merged into a single exporter at `go.opentelemetry.io/otel/exporters/stdout`. - This new exporter was made into its own Go module to follow the pattern of all exporters and decouple it from the `go.opentelemetry.io/otel` module. (#956, #963) -- Move the `go.opentelemetry.io/otel/exporters/test` test package to `go.opentelemetry.io/otel/sdk/export/metric/metrictest`. (#962) -- The `go.opentelemetry.io/otel/api/kv/value` package was merged into the parent `go.opentelemetry.io/otel/api/kv` package. (#968) - - `value.Bool` was replaced with `kv.BoolValue`. - - `value.Int64` was replaced with `kv.Int64Value`. - - `value.Uint64` was replaced with `kv.Uint64Value`. - - `value.Float64` was replaced with `kv.Float64Value`. - - `value.Int32` was replaced with `kv.Int32Value`. - - `value.Uint32` was replaced with `kv.Uint32Value`. - - `value.Float32` was replaced with `kv.Float32Value`. - - `value.String` was replaced with `kv.StringValue`. - - `value.Int` was replaced with `kv.IntValue`. - - `value.Uint` was replaced with `kv.UintValue`. - - `value.Array` was replaced with `kv.ArrayValue`. -- Rename `Infer` to `Any` in the `go.opentelemetry.io/otel/api/kv` package. (#972) -- Change `othttp` to use the `httpsnoop` package to wrap the `ResponseWriter` so that optional interfaces (`http.Hijacker`, `http.Flusher`, etc.) that are implemented by the original `ResponseWriter`are also implemented by the wrapped `ResponseWriter`. (#979) -- Rename `go.opentelemetry.io/otel/sdk/metric/aggregator/test` package to `go.opentelemetry.io/otel/sdk/metric/aggregator/aggregatortest`. (#980) -- Make the SDK into its own Go module called `go.opentelemetry.io/otel/sdk`. (#985) -- Changed the default trace `Sampler` from `AlwaysOn` to `ParentOrElse(AlwaysOn)`. (#989) - -### Removed - -- The `IndexedAttribute` function from the `go.opentelemetry.io/otel/api/label` package was removed in favor of `IndexedLabel` which it was synonymous with. (#970) - -### Fixed - -- Bump github.com/golangci/golangci-lint from 1.28.3 to 1.29.0 in /tools. (#953) -- Bump github.com/google/go-cmp from 0.5.0 to 0.5.1. (#957) -- Use `global.Handle` for span export errors in the OTLP exporter. (#946) -- Correct Go language formatting in the README documentation. (#961) -- Remove default SDK dependencies from the `go.opentelemetry.io/otel/api` package. (#977) -- Remove default SDK dependencies from the `go.opentelemetry.io/otel/instrumentation` package. (#983) -- Move documented examples for `go.opentelemetry.io/otel/instrumentation/grpctrace` interceptors into Go example tests. (#984) - -## [0.9.0] - 2020-07-20 - -### Added - -- A new Resource Detector interface is included to allow resources to be automatically detected and included. (#939) -- A Detector to automatically detect resources from an environment variable. (#939) -- Github action to generate protobuf Go bindings locally in `internal/opentelemetry-proto-gen`. (#938) -- OTLP .proto files from `open-telemetry/opentelemetry-proto` imported as a git submodule under `internal/opentelemetry-proto`. - References to `github.com/open-telemetry/opentelemetry-proto` changed to `go.opentelemetry.io/otel/internal/opentelemetry-proto-gen`. (#942) - -### Changed - -- Non-nil value `struct`s for key-value pairs will be marshalled using JSON rather than `Sprintf`. (#948) - -### Removed - -- Removed dependency on `github.com/open-telemetry/opentelemetry-collector`. (#943) - -## [0.8.0] - 2020-07-09 - -### Added - -- The `B3Encoding` type to represent the B3 encoding(s) the B3 propagator can inject. - A value for HTTP supported encodings (Multiple Header: `MultipleHeader`, Single Header: `SingleHeader`) are included. (#882) -- The `FlagsDeferred` trace flag to indicate if the trace sampling decision has been deferred. (#882) -- The `FlagsDebug` trace flag to indicate if the trace is a debug trace. (#882) -- Add `peer.service` semantic attribute. (#898) -- Add database-specific semantic attributes. (#899) -- Add semantic convention for `faas.coldstart` and `container.id`. (#909) -- Add http content size semantic conventions. (#905) -- Include `http.request_content_length` in HTTP request basic attributes. (#905) -- Add semantic conventions for operating system process resource attribute keys. (#919) -- The Jaeger exporter now has a `WithBatchMaxCount` option to specify the maximum number of spans sent in a batch. (#931) - -### Changed - -- Update `CONTRIBUTING.md` to ask for updates to `CHANGELOG.md` with each pull request. (#879) -- Use lowercase header names for B3 Multiple Headers. (#881) -- The B3 propagator `SingleHeader` field has been replaced with `InjectEncoding`. - This new field can be set to combinations of the `B3Encoding` bitmasks and will inject trace information in these encodings. - If no encoding is set, the propagator will default to `MultipleHeader` encoding. (#882) -- The B3 propagator now extracts from either HTTP encoding of B3 (Single Header or Multiple Header) based on what is contained in the header. - Preference is given to Single Header encoding with Multiple Header being the fallback if Single Header is not found or is invalid. - This behavior change is made to dynamically support all correctly encoded traces received instead of having to guess the expected encoding prior to receiving. (#882) -- Extend semantic conventions for RPC. (#900) -- To match constant naming conventions in the `api/standard` package, the `FaaS*` key names are appended with a suffix of `Key`. (#920) - - `"api/standard".FaaSName` -> `FaaSNameKey` - - `"api/standard".FaaSID` -> `FaaSIDKey` - - `"api/standard".FaaSVersion` -> `FaaSVersionKey` - - `"api/standard".FaaSInstance` -> `FaaSInstanceKey` - -### Removed - -- The `FlagsUnused` trace flag is removed. - The purpose of this flag was to act as the inverse of `FlagsSampled`, the inverse of `FlagsSampled` is used instead. (#882) -- The B3 header constants (`B3SingleHeader`, `B3DebugFlagHeader`, `B3TraceIDHeader`, `B3SpanIDHeader`, `B3SampledHeader`, `B3ParentSpanIDHeader`) are removed. - If B3 header keys are needed [the authoritative OpenZipkin package constants](https://pkg.go.dev/github.com/openzipkin/zipkin-go@v0.2.2/propagation/b3?tab=doc#pkg-constants) should be used instead. (#882) - -### Fixed - -- The B3 Single Header name is now correctly `b3` instead of the previous `X-B3`. (#881) -- The B3 propagator now correctly supports sampling only values (`b3: 0`, `b3: 1`, or `b3: d`) for a Single B3 Header. (#882) -- The B3 propagator now propagates the debug flag. - This removes the behavior of changing the debug flag into a set sampling bit. - Instead, this now follow the B3 specification and omits the `X-B3-Sampling` header. (#882) -- The B3 propagator now tracks "unset" sampling state (meaning "defer the decision") and does not set the `X-B3-Sampling` header when injecting. (#882) -- Bump github.com/itchyny/gojq from 0.10.3 to 0.10.4 in /tools. (#883) -- Bump github.com/opentracing/opentracing-go from v1.1.1-0.20190913142402-a7454ce5950e to v1.2.0. (#885) -- The tracing time conversion for OTLP spans is now correctly set to `UnixNano`. (#896) -- Ensure span status is not set to `Unknown` when no HTTP status code is provided as it is assumed to be `200 OK`. (#908) -- Ensure `httptrace.clientTracer` closes `http.headers` span. (#912) -- Prometheus exporter will not apply stale updates or forget inactive metrics. (#903) -- Add test for api.standard `HTTPClientAttributesFromHTTPRequest`. (#905) -- Bump github.com/golangci/golangci-lint from 1.27.0 to 1.28.1 in /tools. (#901, #913) -- Update otel-colector example to use the v0.5.0 collector. (#915) -- The `grpctrace` instrumentation uses a span name conforming to the OpenTelemetry semantic conventions (does not contain a leading slash (`/`)). (#922) -- The `grpctrace` instrumentation includes an `rpc.method` attribute now set to the gRPC method name. (#900, #922) -- The `grpctrace` instrumentation `rpc.service` attribute now contains the package name if one exists. - This is in accordance with OpenTelemetry semantic conventions. (#922) -- Correlation Context extractor will no longer insert an empty map into the returned context when no valid values are extracted. (#923) -- Bump google.golang.org/api from 0.28.0 to 0.29.0 in /exporters/trace/jaeger. (#925) -- Bump github.com/itchyny/gojq from 0.10.4 to 0.11.0 in /tools. (#926) -- Bump github.com/golangci/golangci-lint from 1.28.1 to 1.28.2 in /tools. (#930) - -## [0.7.0] - 2020-06-26 - -This release implements the v0.5.0 version of the OpenTelemetry specification. - -### Added - -- The othttp instrumentation now includes default metrics. (#861) -- This CHANGELOG file to track all changes in the project going forward. -- Support for array type attributes. (#798) -- Apply transitive dependabot go.mod dependency updates as part of a new automatic Github workflow. (#844) -- Timestamps are now passed to exporters for each export. (#835) -- Add new `Accumulation` type to metric SDK to transport telemetry from `Accumulator`s to `Processor`s. - This replaces the prior `Record` `struct` use for this purpose. (#835) -- New dependabot integration to automate package upgrades. (#814) -- `Meter` and `Tracer` implementations accept instrumentation version version as an optional argument. - This instrumentation version is passed on to exporters. (#811) (#805) (#802) -- The OTLP exporter includes the instrumentation version in telemetry it exports. (#811) -- Environment variables for Jaeger exporter are supported. (#796) -- New `aggregation.Kind` in the export metric API. (#808) -- New example that uses OTLP and the collector. (#790) -- Handle errors in the span `SetName` during span initialization. (#791) -- Default service config to enable retries for retry-able failed requests in the OTLP exporter and an option to override this default. (#777) -- New `go.opentelemetry.io/otel/api/oterror` package to uniformly support error handling and definitions for the project. (#778) -- New `global` default implementation of the `go.opentelemetry.io/otel/api/oterror.Handler` interface to be used to handle errors prior to an user defined `Handler`. - There is also functionality for the user to register their `Handler` as well as a convenience function `Handle` to handle an error with this global `Handler`(#778) -- Options to specify propagators for httptrace and grpctrace instrumentation. (#784) -- The required `application/json` header for the Zipkin exporter is included in all exports. (#774) -- Integrate HTTP semantics helpers from the contrib repository into the `api/standard` package. #769 - -### Changed - -- Rename `Integrator` to `Processor` in the metric SDK. (#863) -- Rename `AggregationSelector` to `AggregatorSelector`. (#859) -- Rename `SynchronizedCopy` to `SynchronizedMove`. (#858) -- Rename `simple` integrator to `basic` integrator. (#857) -- Merge otlp collector examples. (#841) -- Change the metric SDK to support cumulative, delta, and pass-through exporters directly. - With these changes, cumulative and delta specific exporters are able to request the correct kind of aggregation from the SDK. (#840) -- The `Aggregator.Checkpoint` API is renamed to `SynchronizedCopy` and adds an argument, a different `Aggregator` into which the copy is stored. (#812) -- The `export.Aggregator` contract is that `Update()` and `SynchronizedCopy()` are synchronized with each other. - All the aggregation interfaces (`Sum`, `LastValue`, ...) are not meant to be synchronized, as the caller is expected to synchronize aggregators at a higher level after the `Accumulator`. - Some of the `Aggregators` used unnecessary locking and that has been cleaned up. (#812) -- Use of `metric.Number` was replaced by `int64` now that we use `sync.Mutex` in the `MinMaxSumCount` and `Histogram` `Aggregators`. (#812) -- Replace `AlwaysParentSample` with `ParentSample(fallback)` to match the OpenTelemetry v0.5.0 specification. (#810) -- Rename `sdk/export/metric/aggregator` to `sdk/export/metric/aggregation`. #808 -- Send configured headers with every request in the OTLP exporter, instead of just on connection creation. (#806) -- Update error handling for any one off error handlers, replacing, instead, with the `global.Handle` function. (#791) -- Rename `plugin` directory to `instrumentation` to match the OpenTelemetry specification. (#779) -- Makes the argument order to Histogram and DDSketch `New()` consistent. (#781) - -### Removed - -- `Uint64NumberKind` and related functions from the API. (#864) -- Context arguments from `Aggregator.Checkpoint` and `Integrator.Process` as they were unused. (#803) -- `SpanID` is no longer included in parameters for sampling decision to match the OpenTelemetry specification. (#775) - -### Fixed - -- Upgrade OTLP exporter to opentelemetry-proto matching the opentelemetry-collector v0.4.0 release. (#866) -- Allow changes to `go.sum` and `go.mod` when running dependabot tidy-up. (#871) -- Bump github.com/stretchr/testify from 1.4.0 to 1.6.1. (#824) -- Bump github.com/prometheus/client_golang from 1.7.0 to 1.7.1 in /exporters/metric/prometheus. (#867) -- Bump google.golang.org/grpc from 1.29.1 to 1.30.0 in /exporters/trace/jaeger. (#853) -- Bump google.golang.org/grpc from 1.29.1 to 1.30.0 in /exporters/trace/zipkin. (#854) -- Bumps github.com/golang/protobuf from 1.3.2 to 1.4.2 (#848) -- Bump github.com/stretchr/testify from 1.4.0 to 1.6.1 in /exporters/otlp (#817) -- Bump github.com/golangci/golangci-lint from 1.25.1 to 1.27.0 in /tools (#828) -- Bump github.com/prometheus/client_golang from 1.5.0 to 1.7.0 in /exporters/metric/prometheus (#838) -- Bump github.com/stretchr/testify from 1.4.0 to 1.6.1 in /exporters/trace/jaeger (#829) -- Bump github.com/benbjohnson/clock from 1.0.0 to 1.0.3 (#815) -- Bump github.com/stretchr/testify from 1.4.0 to 1.6.1 in /exporters/trace/zipkin (#823) -- Bump github.com/itchyny/gojq from 0.10.1 to 0.10.3 in /tools (#830) -- Bump github.com/stretchr/testify from 1.4.0 to 1.6.1 in /exporters/metric/prometheus (#822) -- Bump google.golang.org/grpc from 1.27.1 to 1.29.1 in /exporters/trace/zipkin (#820) -- Bump google.golang.org/grpc from 1.27.1 to 1.29.1 in /exporters/trace/jaeger (#831) -- Bump github.com/google/go-cmp from 0.4.0 to 0.5.0 (#836) -- Bump github.com/google/go-cmp from 0.4.0 to 0.5.0 in /exporters/trace/jaeger (#837) -- Bump github.com/google/go-cmp from 0.4.0 to 0.5.0 in /exporters/otlp (#839) -- Bump google.golang.org/api from 0.20.0 to 0.28.0 in /exporters/trace/jaeger (#843) -- Set span status from HTTP status code in the othttp instrumentation. (#832) -- Fixed typo in push controller comment. (#834) -- The `Aggregator` testing has been updated and cleaned. (#812) -- `metric.Number(0)` expressions are replaced by `0` where possible. (#812) -- Fixed `global` `handler_test.go` test failure. #804 -- Fixed `BatchSpanProcessor.Shutdown` to wait until all spans are processed. (#766) -- Fixed OTLP example's accidental early close of exporter. (#807) -- Ensure zipkin exporter reads and closes response body. (#788) -- Update instrumentation to use `api/standard` keys instead of custom keys. (#782) -- Clean up tools and RELEASING documentation. (#762) - -## [0.6.0] - 2020-05-21 - -### Added - -- Support for `Resource`s in the prometheus exporter. (#757) -- New pull controller. (#751) -- New `UpDownSumObserver` instrument. (#750) -- OpenTelemetry collector demo. (#711) -- New `SumObserver` instrument. (#747) -- New `UpDownCounter` instrument. (#745) -- New timeout `Option` and configuration function `WithTimeout` to the push controller. (#742) -- New `api/standards` package to implement semantic conventions and standard key-value generation. (#731) - -### Changed - -- Rename `Register*` functions in the metric API to `New*` for all `Observer` instruments. (#761) -- Use `[]float64` for histogram boundaries, not `[]metric.Number`. (#758) -- Change OTLP example to use exporter as a trace `Syncer` instead of as an unneeded `Batcher`. (#756) -- Replace `WithResourceAttributes()` with `WithResource()` in the trace SDK. (#754) -- The prometheus exporter now uses the new pull controller. (#751) -- Rename `ScheduleDelayMillis` to `BatchTimeout` in the trace `BatchSpanProcessor`.(#752) -- Support use of synchronous instruments in asynchronous callbacks (#725) -- Move `Resource` from the `Export` method parameter into the metric export `Record`. (#739) -- Rename `Observer` instrument to `ValueObserver`. (#734) -- The push controller now has a method (`Provider()`) to return a `metric.Provider` instead of the old `Meter` method that acted as a `metric.Provider`. (#738) -- Replace `Measure` instrument by `ValueRecorder` instrument. (#732) -- Rename correlation context header from `"Correlation-Context"` to `"otcorrelations"` to match the OpenTelemetry specification. 727) - -### Fixed - -- Ensure gRPC `ClientStream` override methods do not panic in grpctrace package. (#755) -- Disable parts of `BatchSpanProcessor` test until a fix is found. (#743) -- Fix `string` case in `kv` `Infer` function. (#746) -- Fix panic in grpctrace client interceptors. (#740) -- Refactor the `api/metrics` push controller and add `CheckpointSet` synchronization. (#737) -- Rewrite span batch process queue batching logic. (#719) -- Remove the push controller named Meter map. (#738) -- Fix Histogram aggregator initial state (fix #735). (#736) -- Ensure golang alpine image is running `golang-1.14` for examples. (#733) -- Added test for grpctrace `UnaryInterceptorClient`. (#695) -- Rearrange `api/metric` code layout. (#724) - -## [0.5.0] - 2020-05-13 - -### Added - -- Batch `Observer` callback support. (#717) -- Alias `api` types to root package of project. (#696) -- Create basic `othttp.Transport` for simple client instrumentation. (#678) -- `SetAttribute(string, interface{})` to the trace API. (#674) -- Jaeger exporter option that allows user to specify custom http client. (#671) -- `Stringer` and `Infer` methods to `key`s. (#662) - -### Changed - -- Rename `NewKey` in the `kv` package to just `Key`. (#721) -- Move `core` and `key` to `kv` package. (#720) -- Make the metric API `Meter` a `struct` so the abstract `MeterImpl` can be passed and simplify implementation. (#709) -- Rename SDK `Batcher` to `Integrator` to match draft OpenTelemetry SDK specification. (#710) -- Rename SDK `Ungrouped` integrator to `simple.Integrator` to match draft OpenTelemetry SDK specification. (#710) -- Rename SDK `SDK` `struct` to `Accumulator` to match draft OpenTelemetry SDK specification. (#710) -- Move `Number` from `core` to `api/metric` package. (#706) -- Move `SpanContext` from `core` to `trace` package. (#692) -- Change traceparent header from `Traceparent` to `traceparent` to implement the W3C specification. (#681) - -### Fixed - -- Update tooling to run generators in all submodules. (#705) -- gRPC interceptor regexp to match methods without a service name. (#683) -- Use a `const` for padding 64-bit B3 trace IDs. (#701) -- Update `mockZipkin` listen address from `:0` to `127.0.0.1:0`. (#700) -- Left-pad 64-bit B3 trace IDs with zero. (#698) -- Propagate at least the first W3C tracestate header. (#694) -- Remove internal `StateLocker` implementation. (#688) -- Increase instance size CI system uses. (#690) -- Add a `key` benchmark and use reflection in `key.Infer()`. (#679) -- Fix internal `global` test by using `global.Meter` with `RecordBatch()`. (#680) -- Reimplement histogram using mutex instead of `StateLocker`. (#669) -- Switch `MinMaxSumCount` to a mutex lock implementation instead of `StateLocker`. (#667) -- Update documentation to not include any references to `WithKeys`. (#672) -- Correct misspelling. (#668) -- Fix clobbering of the span context if extraction fails. (#656) -- Bump `golangci-lint` and work around the corrupting bug. (#666) (#670) - -## [0.4.3] - 2020-04-24 - -### Added - -- `Dockerfile` and `docker-compose.yml` to run example code. (#635) -- New `grpctrace` package that provides gRPC client and server interceptors for both unary and stream connections. (#621) -- New `api/label` package, providing common label set implementation. (#651) -- Support for JSON marshaling of `Resources`. (#654) -- `TraceID` and `SpanID` implementations for `Stringer` interface. (#642) -- `RemoteAddrKey` in the othttp plugin to include the HTTP client address in top-level spans. (#627) -- `WithSpanFormatter` option to the othttp plugin. (#617) -- Updated README to include section for compatible libraries and include reference to the contrib repository. (#612) -- The prometheus exporter now supports exporting histograms. (#601) -- A `String` method to the `Resource` to return a hashable identifier for a now unique resource. (#613) -- An `Iter` method to the `Resource` to return an array `AttributeIterator`. (#613) -- An `Equal` method to the `Resource` test the equivalence of resources. (#613) -- An iterable structure (`AttributeIterator`) for `Resource` attributes. - -### Changed - -- zipkin export's `NewExporter` now requires a `serviceName` argument to ensure this needed values is provided. (#644) -- Pass `Resources` through the metrics export pipeline. (#659) - -### Removed - -- `WithKeys` option from the metric API. (#639) - -### Fixed - -- Use the `label.Set.Equivalent` value instead of an encoding in the batcher. (#658) -- Correct typo `trace.Exporter` to `trace.SpanSyncer` in comments. (#653) -- Use type names for return values in jaeger exporter. (#648) -- Increase the visibility of the `api/key` package by updating comments and fixing usages locally. (#650) -- `Checkpoint` only after `Update`; Keep records in the `sync.Map` longer. (#647) -- Do not cache `reflect.ValueOf()` in metric Labels. (#649) -- Batch metrics exported from the OTLP exporter based on `Resource` and labels. (#626) -- Add error wrapping to the prometheus exporter. (#631) -- Update the OTLP exporter batching of traces to use a unique `string` representation of an associated `Resource` as the batching key. (#623) -- Update OTLP `SpanData` transform to only include the `ParentSpanID` if one exists. (#614) -- Update `Resource` internal representation to uniquely and reliably identify resources. (#613) -- Check return value from `CheckpointSet.ForEach` in prometheus exporter. (#622) -- Ensure spans created by httptrace client tracer reflect operation structure. (#618) -- Create a new recorder rather than reuse when multiple observations in same epoch for asynchronous instruments. #610 -- The default port the OTLP exporter uses to connect to the OpenTelemetry collector is updated to match the one the collector listens on by default. (#611) - - -## [0.4.2] - 2020-03-31 - -### Fixed - -- Fix `pre_release.sh` to update version in `sdk/opentelemetry.go`. (#607) -- Fix time conversion from internal to OTLP in OTLP exporter. (#606) - -## [0.4.1] - 2020-03-31 - -### Fixed - -- Update `tag.sh` to create signed tags. (#604) - -## [0.4.0] - 2020-03-30 - -### Added - -- New API package `api/metric/registry` that exposes a `MeterImpl` wrapper for use by SDKs to generate unique instruments. (#580) -- Script to verify examples after a new release. (#579) - -### Removed - -- The dogstatsd exporter due to lack of support. - This additionally removes support for statsd. (#591) -- `LabelSet` from the metric API. - This is replaced by a `[]core.KeyValue` slice. (#595) -- `Labels` from the metric API's `Meter` interface. (#595) - -### Changed - -- The metric `export.Labels` became an interface which the SDK implements and the `export` package provides a simple, immutable implementation of this interface intended for testing purposes. (#574) -- Renamed `internal/metric.Meter` to `MeterImpl`. (#580) -- Renamed `api/global/internal.obsImpl` to `asyncImpl`. (#580) - -### Fixed - -- Corrected missing return in mock span. (#582) -- Update License header for all source files to match CNCF guidelines and include a test to ensure it is present. (#586) (#596) -- Update to v0.3.0 of the OTLP in the OTLP exporter. (#588) -- Update pre-release script to be compatible between GNU and BSD based systems. (#592) -- Add a `RecordBatch` benchmark. (#594) -- Moved span transforms of the OTLP exporter to the internal package. (#593) -- Build both go-1.13 and go-1.14 in circleci to test for all supported versions of Go. (#569) -- Removed unneeded allocation on empty labels in OLTP exporter. (#597) -- Update `BatchedSpanProcessor` to process the queue until no data but respect max batch size. (#599) -- Update project documentation godoc.org links to pkg.go.dev. (#602) - -## [0.3.0] - 2020-03-21 - -This is a first official beta release, which provides almost fully complete metrics, tracing, and context propagation functionality. -There is still a possibility of breaking changes. - -### Added - -- Add `Observer` metric instrument. (#474) -- Add global `Propagators` functionality to enable deferred initialization for propagators registered before the first Meter SDK is installed. (#494) -- Simplified export setup pipeline for the jaeger exporter to match other exporters. (#459) -- The zipkin trace exporter. (#495) -- The OTLP exporter to export metric and trace telemetry to the OpenTelemetry collector. (#497) (#544) (#545) -- The `StatusMessage` field was add to the trace `Span`. (#524) -- Context propagation in OpenTracing bridge in terms of OpenTelemetry context propagation. (#525) -- The `Resource` type was added to the SDK. (#528) -- The global API now supports a `Tracer` and `Meter` function as shortcuts to getting a global `*Provider` and calling these methods directly. (#538) -- The metric API now defines a generic `MeterImpl` interface to support general purpose `Meter` construction. - Additionally, `SyncImpl` and `AsyncImpl` are added to support general purpose instrument construction. (#560) -- A metric `Kind` is added to represent the `MeasureKind`, `ObserverKind`, and `CounterKind`. (#560) -- Scripts to better automate the release process. (#576) - -### Changed - -- Default to to use `AlwaysSampler` instead of `ProbabilitySampler` to match OpenTelemetry specification. (#506) -- Renamed `AlwaysSampleSampler` to `AlwaysOnSampler` in the trace API. (#511) -- Renamed `NeverSampleSampler` to `AlwaysOffSampler` in the trace API. (#511) -- The `Status` field of the `Span` was changed to `StatusCode` to disambiguate with the added `StatusMessage`. (#524) -- Updated the trace `Sampler` interface conform to the OpenTelemetry specification. (#531) -- Rename metric API `Options` to `Config`. (#541) -- Rename metric `Counter` aggregator to be `Sum`. (#541) -- Unify metric options into `Option` from instrument specific options. (#541) -- The trace API's `TraceProvider` now support `Resource`s. (#545) -- Correct error in zipkin module name. (#548) -- The jaeger trace exporter now supports `Resource`s. (#551) -- Metric SDK now supports `Resource`s. - The `WithResource` option was added to configure a `Resource` on creation and the `Resource` method was added to the metric `Descriptor` to return the associated `Resource`. (#552) -- Replace `ErrNoLastValue` and `ErrEmptyDataSet` by `ErrNoData` in the metric SDK. (#557) -- The stdout trace exporter now supports `Resource`s. (#558) -- The metric `Descriptor` is now included at the API instead of the SDK. (#560) -- Replace `Ordered` with an iterator in `export.Labels`. (#567) - -### Removed - -- The vendor specific Stackdriver. It is now hosted on 3rd party vendor infrastructure. (#452) -- The `Unregister` method for metric observers as it is not in the OpenTelemetry specification. (#560) -- `GetDescriptor` from the metric SDK. (#575) -- The `Gauge` instrument from the metric API. (#537) - -### Fixed - -- Make histogram aggregator checkpoint consistent. (#438) -- Update README with import instructions and how to build and test. (#505) -- The default label encoding was updated to be unique. (#508) -- Use `NewRoot` in the othttp plugin for public endpoints. (#513) -- Fix data race in `BatchedSpanProcessor`. (#518) -- Skip test-386 for Mac OS 10.15.x (Catalina and upwards). #521 -- Use a variable-size array to represent ordered labels in maps. (#523) -- Update the OTLP protobuf and update changed import path. (#532) -- Use `StateLocker` implementation in `MinMaxSumCount`. (#546) -- Eliminate goroutine leak in histogram stress test. (#547) -- Update OTLP exporter with latest protobuf. (#550) -- Add filters to the othttp plugin. (#556) -- Provide an implementation of the `Header*` filters that do not depend on Go 1.14. (#565) -- Encode labels once during checkpoint. - The checkpoint function is executed in a single thread so we can do the encoding lazily before passing the encoded version of labels to the exporter. - This is a cheap and quick way to avoid encoding the labels on every collection interval. (#572) -- Run coverage over all packages in `COVERAGE_MOD_DIR`. (#573) - -## [0.2.3] - 2020-03-04 - -### Added - -- `RecordError` method on `Span`s in the trace API to Simplify adding error events to spans. (#473) -- Configurable push frequency for exporters setup pipeline. (#504) - -### Changed - -- Rename the `exporter` directory to `exporters`. - The `go.opentelemetry.io/otel/exporter/trace/jaeger` package was mistakenly released with a `v1.0.0` tag instead of `v0.1.0`. - This resulted in all subsequent releases not becoming the default latest. - A consequence of this was that all `go get`s pulled in the incompatible `v0.1.0` release of that package when pulling in more recent packages from other otel packages. - Renaming the `exporter` directory to `exporters` fixes this issue by renaming the package and therefore clearing any existing dependency tags. - Consequentially, this action also renames *all* exporter packages. (#502) - -### Removed - -- The `CorrelationContextHeader` constant in the `correlation` package is no longer exported. (#503) - -## [0.2.2] - 2020-02-27 - -### Added - -- `HTTPSupplier` interface in the propagation API to specify methods to retrieve and store a single value for a key to be associated with a carrier. (#467) -- `HTTPExtractor` interface in the propagation API to extract information from an `HTTPSupplier` into a context. (#467) -- `HTTPInjector` interface in the propagation API to inject information into an `HTTPSupplier.` (#467) -- `Config` and configuring `Option` to the propagator API. (#467) -- `Propagators` interface in the propagation API to contain the set of injectors and extractors for all supported carrier formats. (#467) -- `HTTPPropagator` interface in the propagation API to inject and extract from an `HTTPSupplier.` (#467) -- `WithInjectors` and `WithExtractors` functions to the propagator API to configure injectors and extractors to use. (#467) -- `ExtractHTTP` and `InjectHTTP` functions to apply configured HTTP extractors and injectors to a passed context. (#467) -- Histogram aggregator. (#433) -- `DefaultPropagator` function and have it return `trace.TraceContext` as the default context propagator. (#456) -- `AlwaysParentSample` sampler to the trace API. (#455) -- `WithNewRoot` option function to the trace API to specify the created span should be considered a root span. (#451) - - -### Changed - -- Renamed `WithMap` to `ContextWithMap` in the correlation package. (#481) -- Renamed `FromContext` to `MapFromContext` in the correlation package. (#481) -- Move correlation context propagation to correlation package. (#479) -- Do not default to putting remote span context into links. (#480) -- Propagators extrac -- `Tracer.WithSpan` updated to accept `StartOptions`. (#472) -- Renamed `MetricKind` to `Kind` to not stutter in the type usage. (#432) -- Renamed the `export` package to `metric` to match directory structure. (#432) -- Rename the `api/distributedcontext` package to `api/correlation`. (#444) -- Rename the `api/propagators` package to `api/propagation`. (#444) -- Move the propagators from the `propagators` package into the `trace` API package. (#444) -- Update `Float64Gauge`, `Int64Gauge`, `Float64Counter`, `Int64Counter`, `Float64Measure`, and `Int64Measure` metric methods to use value receivers instead of pointers. (#462) -- Moved all dependencies of tools package to a tools directory. (#466) - -### Removed - -- Binary propagators. (#467) -- NOOP propagator. (#467) - -### Fixed - -- Upgraded `github.com/golangci/golangci-lint` from `v1.21.0` to `v1.23.6` in `tools/`. (#492) -- Fix a possible nil-dereference crash (#478) -- Correct comments for `InstallNewPipeline` in the stdout exporter. (#483) -- Correct comments for `InstallNewPipeline` in the dogstatsd exporter. (#484) -- Correct comments for `InstallNewPipeline` in the prometheus exporter. (#482) -- Initialize `onError` based on `Config` in prometheus exporter. (#486) -- Correct module name in prometheus exporter README. (#475) -- Removed tracer name prefix from span names. (#430) -- Fix `aggregator_test.go` import package comment. (#431) -- Improved detail in stdout exporter. (#436) -- Fix a dependency issue (generate target should depend on stringer, not lint target) in Makefile. (#442) -- Reorders the Makefile targets within `precommit` target so we generate files and build the code before doing linting, so we can get much nicer errors about syntax errors from the compiler. (#442) -- Reword function documentation in gRPC plugin. (#446) -- Send the `span.kind` tag to Jaeger from the jaeger exporter. (#441) -- Fix `metadataSupplier` in the jaeger exporter to overwrite the header if existing instead of appending to it. (#441) -- Upgraded to Go 1.13 in CI. (#465) -- Correct opentelemetry.io URL in trace SDK documentation. (#464) -- Refactored reference counting logic in SDK determination of stale records. (#468) -- Add call to `runtime.Gosched` in instrument `acquireHandle` logic to not block the collector. (#469) - -## [0.2.1.1] - 2020-01-13 - -### Fixed - -- Use stateful batcher on Prometheus exporter fixing regresion introduced in #395. (#428) - -## [0.2.1] - 2020-01-08 - -### Added - -- Global meter forwarding implementation. - This enables deferred initialization for metric instruments registered before the first Meter SDK is installed. (#392) -- Global trace forwarding implementation. - This enables deferred initialization for tracers registered before the first Trace SDK is installed. (#406) -- Standardize export pipeline creation in all exporters. (#395) -- A testing, organization, and comments for 64-bit field alignment. (#418) -- Script to tag all modules in the project. (#414) - -### Changed - -- Renamed `propagation` package to `propagators`. (#362) -- Renamed `B3Propagator` propagator to `B3`. (#362) -- Renamed `TextFormatPropagator` propagator to `TextFormat`. (#362) -- Renamed `BinaryPropagator` propagator to `Binary`. (#362) -- Renamed `BinaryFormatPropagator` propagator to `BinaryFormat`. (#362) -- Renamed `NoopTextFormatPropagator` propagator to `NoopTextFormat`. (#362) -- Renamed `TraceContextPropagator` propagator to `TraceContext`. (#362) -- Renamed `SpanOption` to `StartOption` in the trace API. (#369) -- Renamed `StartOptions` to `StartConfig` in the trace API. (#369) -- Renamed `EndOptions` to `EndConfig` in the trace API. (#369) -- `Number` now has a pointer receiver for its methods. (#375) -- Renamed `CurrentSpan` to `SpanFromContext` in the trace API. (#379) -- Renamed `SetCurrentSpan` to `ContextWithSpan` in the trace API. (#379) -- Renamed `Message` in Event to `Name` in the trace API. (#389) -- Prometheus exporter no longer aggregates metrics, instead it only exports them. (#385) -- Renamed `HandleImpl` to `BoundInstrumentImpl` in the metric API. (#400) -- Renamed `Float64CounterHandle` to `Float64CounterBoundInstrument` in the metric API. (#400) -- Renamed `Int64CounterHandle` to `Int64CounterBoundInstrument` in the metric API. (#400) -- Renamed `Float64GaugeHandle` to `Float64GaugeBoundInstrument` in the metric API. (#400) -- Renamed `Int64GaugeHandle` to `Int64GaugeBoundInstrument` in the metric API. (#400) -- Renamed `Float64MeasureHandle` to `Float64MeasureBoundInstrument` in the metric API. (#400) -- Renamed `Int64MeasureHandle` to `Int64MeasureBoundInstrument` in the metric API. (#400) -- Renamed `Release` method for bound instruments in the metric API to `Unbind`. (#400) -- Renamed `AcquireHandle` method for bound instruments in the metric API to `Bind`. (#400) -- Renamed the `File` option in the stdout exporter to `Writer`. (#404) -- Renamed all `Options` to `Config` for all metric exports where this wasn't already the case. - -### Fixed - -- Aggregator import path corrected. (#421) -- Correct links in README. (#368) -- The README was updated to match latest code changes in its examples. (#374) -- Don't capitalize error statements. (#375) -- Fix ignored errors. (#375) -- Fix ambiguous variable naming. (#375) -- Removed unnecessary type casting. (#375) -- Use named parameters. (#375) -- Updated release schedule. (#378) -- Correct http-stackdriver example module name. (#394) -- Removed the `http.request` span in `httptrace` package. (#397) -- Add comments in the metrics SDK (#399) -- Initialize checkpoint when creating ddsketch aggregator to prevent panic when merging into a empty one. (#402) (#403) -- Add documentation of compatible exporters in the README. (#405) -- Typo fix. (#408) -- Simplify span check logic in SDK tracer implementation. (#419) - -## [0.2.0] - 2019-12-03 - -### Added - -- Unary gRPC tracing example. (#351) -- Prometheus exporter. (#334) -- Dogstatsd metrics exporter. (#326) - -### Changed - -- Rename `MaxSumCount` aggregation to `MinMaxSumCount` and add the `Min` interface for this aggregation. (#352) -- Rename `GetMeter` to `Meter`. (#357) -- Rename `HTTPTraceContextPropagator` to `TraceContextPropagator`. (#355) -- Rename `HTTPB3Propagator` to `B3Propagator`. (#355) -- Rename `HTTPTraceContextPropagator` to `TraceContextPropagator`. (#355) -- Move `/global` package to `/api/global`. (#356) -- Rename `GetTracer` to `Tracer`. (#347) - -### Removed - -- `SetAttribute` from the `Span` interface in the trace API. (#361) -- `AddLink` from the `Span` interface in the trace API. (#349) -- `Link` from the `Span` interface in the trace API. (#349) - -### Fixed - -- Exclude example directories from coverage report. (#365) -- Lint make target now implements automatic fixes with `golangci-lint` before a second run to report the remaining issues. (#360) -- Drop `GO111MODULE` environment variable in Makefile as Go 1.13 is the project specified minimum version and this is environment variable is not needed for that version of Go. (#359) -- Run the race checker for all test. (#354) -- Redundant commands in the Makefile are removed. (#354) -- Split the `generate` and `lint` targets of the Makefile. (#354) -- Renames `circle-ci` target to more generic `ci` in Makefile. (#354) -- Add example Prometheus binary to gitignore. (#358) -- Support negative numbers with the `MaxSumCount`. (#335) -- Resolve race conditions in `push_test.go` identified in #339. (#340) -- Use `/usr/bin/env bash` as a shebang in scripts rather than `/bin/bash`. (#336) -- Trace benchmark now tests both `AlwaysSample` and `NeverSample`. - Previously it was testing `AlwaysSample` twice. (#325) -- Trace benchmark now uses a `[]byte` for `TraceID` to fix failing test. (#325) -- Added a trace benchmark to test variadic functions in `setAttribute` vs `setAttributes` (#325) -- The `defaultkeys` batcher was only using the encoded label set as its map key while building a checkpoint. - This allowed distinct label sets through, but any metrics sharing a label set could be overwritten or merged incorrectly. - This was corrected. (#333) - - -## [0.1.2] - 2019-11-18 - -### Fixed - -- Optimized the `simplelru` map for attributes to reduce the number of allocations. (#328) -- Removed unnecessary unslicing of parameters that are already a slice. (#324) - -## [0.1.1] - 2019-11-18 - -This release contains a Metrics SDK with stdout exporter and supports basic aggregations such as counter, gauges, array, maxsumcount, and ddsketch. - -### Added - -- Metrics stdout export pipeline. (#265) -- Array aggregation for raw measure metrics. (#282) -- The core.Value now have a `MarshalJSON` method. (#281) - -### Removed - -- `WithService`, `WithResources`, and `WithComponent` methods of tracers. (#314) -- Prefix slash in `Tracer.Start()` for the Jaeger example. (#292) - -### Changed - -- Allocation in LabelSet construction to reduce GC overhead. (#318) -- `trace.WithAttributes` to append values instead of replacing (#315) -- Use a formula for tolerance in sampling tests. (#298) -- Move export types into trace and metric-specific sub-directories. (#289) -- `SpanKind` back to being based on an `int` type. (#288) - -### Fixed - -- URL to OpenTelemetry website in README. (#323) -- Name of othttp default tracer. (#321) -- `ExportSpans` for the stackdriver exporter now handles `nil` context. (#294) -- CI modules cache to correctly restore/save from/to the cache. (#316) -- Fix metric SDK race condition between `LoadOrStore` and the assignment `rec.recorder = i.meter.exporter.AggregatorFor(rec)`. (#293) -- README now reflects the new code structure introduced with these changes. (#291) -- Make the basic example work. (#279) - -## [0.1.0] - 2019-11-04 - -This is the first release of open-telemetry go library. -It contains api and sdk for trace and meter. - -### Added - -- Initial OpenTelemetry trace and metric API prototypes. -- Initial OpenTelemetry trace, metric, and export SDK packages. -- A wireframe bridge to support compatibility with OpenTracing. -- Example code for a basic, http-stackdriver, http, jaeger, and named tracer setup. -- Exporters for Jaeger, Stackdriver, and stdout. -- Propagators for binary, B3, and trace-context protocols. -- Project information and guidelines in the form of a README and CONTRIBUTING. -- Tools to build the project and a Makefile to automate the process. -- Apache-2.0 license. -- CircleCI build CI manifest files. -- CODEOWNERS file to track owners of this project. - - -[Unreleased]: https://github.com/open-telemetry/opentelemetry-go/compare/v0.11.0...HEAD -[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 -[0.8.0]: https://github.com/open-telemetry/opentelemetry-go/releases/tag/v0.8.0 -[0.7.0]: https://github.com/open-telemetry/opentelemetry-go/releases/tag/v0.7.0 -[0.6.0]: https://github.com/open-telemetry/opentelemetry-go/releases/tag/v0.6.0 -[0.5.0]: https://github.com/open-telemetry/opentelemetry-go/releases/tag/v0.5.0 -[0.4.3]: https://github.com/open-telemetry/opentelemetry-go/releases/tag/v0.4.3 -[0.4.2]: https://github.com/open-telemetry/opentelemetry-go/releases/tag/v0.4.2 -[0.4.1]: https://github.com/open-telemetry/opentelemetry-go/releases/tag/v0.4.1 -[0.4.0]: https://github.com/open-telemetry/opentelemetry-go/releases/tag/v0.4.0 -[0.3.0]: https://github.com/open-telemetry/opentelemetry-go/releases/tag/v0.3.0 -[0.2.3]: https://github.com/open-telemetry/opentelemetry-go/releases/tag/v0.2.3 -[0.2.2]: https://github.com/open-telemetry/opentelemetry-go/releases/tag/v0.2.2 -[0.2.1.1]: https://github.com/open-telemetry/opentelemetry-go/releases/tag/v0.2.1.1 -[0.2.1]: https://github.com/open-telemetry/opentelemetry-go/releases/tag/v0.2.1 -[0.2.0]: https://github.com/open-telemetry/opentelemetry-go/releases/tag/v0.2.0 -[0.1.2]: https://github.com/open-telemetry/opentelemetry-go/releases/tag/v0.1.2 -[0.1.1]: https://github.com/open-telemetry/opentelemetry-go/releases/tag/v0.1.1 -[0.1.0]: https://github.com/open-telemetry/opentelemetry-go/releases/tag/v0.1.0 diff --git a/vendor/go.opentelemetry.io/otel/CODEOWNERS b/vendor/go.opentelemetry.io/otel/CODEOWNERS deleted file mode 100644 index cbca5922a..000000000 --- a/vendor/go.opentelemetry.io/otel/CODEOWNERS +++ /dev/null @@ -1,17 +0,0 @@ -##################################################### -# -# List of approvers for this repository -# -##################################################### -# -# Learn about membership in OpenTelemetry community: -# https://github.com/open-telemetry/community/blob/master/community-membership.md -# -# -# Learn about CODEOWNERS file format: -# https://help.github.com/en/articles/about-code-owners -# - -* @jmacd @lizthegrey @MrAlias @Aneurysm9 @evantorrie - -CODEOWNERS @MrAlias @Aneurysm9 diff --git a/vendor/go.opentelemetry.io/otel/CONTRIBUTING.md b/vendor/go.opentelemetry.io/otel/CONTRIBUTING.md deleted file mode 100644 index 0059076af..000000000 --- a/vendor/go.opentelemetry.io/otel/CONTRIBUTING.md +++ /dev/null @@ -1,361 +0,0 @@ -# Contributing to opentelemetry-go - -The Go special interest group (SIG) meets regularly. See the -OpenTelemetry -[community](https://github.com/open-telemetry/community#golang-sdk) -repo for information on this and other language SIGs. - -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). - -## Development - -You can view and edit the source code by cloning this repository: - -```bash -git clone https://github.com/open-telemetry/opentelemetry-go.git -``` - -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). - -The `precommit` target also fixes the formatting of the code and -checks the status of the go module files. - -If after running `make precommit` the output of `git status` contains -`nothing to commit, working tree clean` then it means that everything -is up-to-date and properly formatted. - -## Pull Requests - -### How to Send Pull Requests - -Everyone is welcome to contribute code to `opentelemetry-go` via -GitHub pull requests (PRs). - -To create a new PR, fork the project in GitHub and clone the upstream -repo: - -```sh -$ go get -d go.opentelemetry.io/otel -``` - -(This may print some warning about "build constraints exclude all Go -files", just ignore it.) - -This will put the project in `${GOPATH}/src/go.opentelemetry.io/otel`. You -can alternatively use `git` directly with: - -```sh -$ git clone https://github.com/open-telemetry/opentelemetry-go -``` - -(Note that `git clone` is *not* using the `go.opentelemetry.io/otel` name - -that name is a kind of a redirector to GitHub that `go get` can -understand, but `git` does not.) - -This would put the project in the `opentelemetry-go` directory in -current working directory. - -Enter the newly created directory and add your fork as a new remote: - -```sh -$ git remote add git@github.com:/opentelemetry-go -``` - -Check out a new branch, make modifications, run linters and tests, update -`CHANGELOG.md`, and push the branch to your fork: - -```sh -$ git checkout -b -# edit files -# update changelog -$ make precommit -$ git add -p -$ git commit -$ git push -``` - -Open a pull request against the main `opentelemetry-go` repo. Be sure to add the pull -request ID to the entry you added to `CHANGELOG.md`. - -### How to Receive Comments - -* If the PR is not ready for review, please put `[WIP]` in the title, - tag it as `work-in-progress`, or mark it as - [`draft`](https://github.blog/2019-02-14-introducing-draft-pull-requests/). -* Make sure CLA is signed and CI is clear. - -### How to Get PRs Merged - -A PR is considered to be **ready to merge** when: - -* It has received two approvals from Collaborators/Maintainers (at - different companies). -* 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. -* `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**. - -## Design Choices - -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). - -### Focus on Capabilities, Not Structure Compliance - -OpenTelemetry is an evolving specification, one where the desires and -use cases are clear, but the method to satisfy those uses cases are -not. - -As such, Contributions should provide functionality and behavior that -conforms to the specification, but the interface and structure is -flexible. - -It is preferable to have contributions follow the idioms of the -language rather than conform to specific API names or argument -patterns in the spec. - -For a deeper discussion, see: -https://github.com/open-telemetry/opentelemetry-specification/issues/165 - -## Style Guide - -One of the primary goals of this project is that it is actually used by -developers. With this goal in mind the project strives to build -user-friendly and idiomatic Go code adhering to the Go community's best -practices. - -For a non-comprehensive but foundational overview of these best practices -the [Effective Go](https://golang.org/doc/effective_go.html) documentation -is an excellent starting place. - -As a convenience for developers building this project the `make precommit` -will format, lint, validate, and in some cases fix the changes you plan to -submit. This check will need to pass for your changes to be able to be -merged. - -In addition to idiomatic Go, the project has adopted certain standards for -implementations of common patterns. These standards should be followed as a -default, and if they are not followed documentation needs to be included as -to the reasons why. - -### Configuration - -When creating an instantiation function for a complex `struct` it is useful -to allow variable number of options to be applied. However, the strong type -system of Go restricts the function design options. There are a few ways to -solve this problem, but we have landed on the following design. - -#### `config` - -Configuration should be held in a `struct` named `config`, or prefixed with -specific type name this Configuration applies to if there are multiple -`config` in the package. This `struct` must contain configuration options. - -```go -// config contains configuration options for a thing. -type config struct { - // options ... -} -``` - -In general the `config` `struct` will not need to be used externally to the -package and should be unexported. If, however, it is expected that the user -will likely want to build custom options for the configuration, the `config` -should be exported. Please, include in the documentation for the `config` -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 -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 { - // Set default values for config. - config := config{/* […] */} - for _, option := range options { - option.Apply(&config) - } - // Preform any validation here. - return config -} -``` - -If validation of the `config` options is also preformed this can return an -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. - -#### `Option` - -To set the value of the options a `config` contains, a corresponding -`Option` interface type should be used. - -```go -type Option interface { - Apply(*Config) -} -``` - -The name of the interface should be prefixed in the same way the -corresponding `config` is (if at all). - -#### Options - -All user configurable options for a `config` must have a related unexported -implementation of the `Option` interface and an exported configuration -function that wraps this implementation. - -The wrapping function name should be prefixed with `With*` (or in the -special case of a boolean options `Without*`) and should have the following -function signature. - -```go -func With*(…) Option { … } -``` - -##### `bool` Options - -```go -type defaultFalseOption bool - -func (o defaultFalseOption) Apply(c *Config) { - c.Bool = bool(o) -} - -// WithOption sets a T* to have an option included. -func WithOption() Option { - return defaultFalseOption(true) -} -``` - -```go -type defaultTrueOption bool - -func (o defaultTrueOption) Apply(c *Config) { - c.Bool = bool(o) -} - -// WithoutOption sets a T* to have Bool option excluded. -func WithoutOption() Option { - return defaultTrueOption(false) -} -```` - -##### Declared Type Options - -```go -type myTypeOption struct { - MyType MyType -} - -func (o myTypeOption) Apply(c *Config) { - c.MyType = o.MyType -} - -// WithMyType sets T* to have include MyType. -func WithMyType(t MyType) Option { - return myTypeOption{t} -} -``` - -#### Instantiation - -Using this configuration pattern to configure instantiation with a `New*` -function. - -```go -func NewT*(options ...Option) T* {…} -``` - -Any required parameters can be declared before the variadic `options`. - -#### Dealing with Overlap - -Sometimes there are multiple complex `struct` that share common -configuration and also have distinct configuration. To avoid repeated -portions of `config`s, a common `config` can be used with the union of -options being handled with the `Option` interface. - -For example. - -```go -// config holds options for all animals. -type config struct { - Weight float64 - Color string - MaxAltitude float64 -} - -// DogOption apply Dog specific options. -type DogOption interface { - ApplyDog(*config) -} - -// BirdOption apply Bird specific options. -type BirdOption interface { - ApplyBird(*config) -} - -// Option apply options for all animals. -type Option interface { - BirdOption - DogOption -} - -type weightOption float64 -func (o weightOption) ApplyDog(c *config) { c.Weight = float64(o) } -func (o weightOption) ApplyBird(c *config) { c.Weight = float64(o) } -func WithWeight(w float64) Option { return weightOption(w) } - -type furColorOption string -func (o furColorOption) ApplyDog(c *config) { c.Color = string(o) } -func WithFurColor(c string) DogOption { return furColorOption(c) } - -type maxAltitudeOption float64 -func (o maxAltitudeOption) ApplyBird(c *config) { c.MaxAltitude = float64(o) } -func WithMaxAltitude(a float64) BirdOption { return maxAltitudeOption(a) } - -func NewDog(name string, o ...DogOption) Dog {…} -func NewBird(name string, o ...BirdOption) Bird {…} -``` - -## Approvers and Maintainers - -Approvers: - -- [Liz Fong-Jones](https://github.com/lizthegrey), Honeycomb -- [Evan Torrie](https://github.com/evantorrie), Verizon Media -- [Josh MacDonald](https://github.com/jmacd), LightStep - -Maintainers: - -- [Anthony Mirabella](https://github.com/Aneurysm9), Centene -- [Tyler Yahn](https://github.com/MrAlias), New Relic - -### 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). diff --git a/vendor/go.opentelemetry.io/otel/LICENSE b/vendor/go.opentelemetry.io/otel/LICENSE deleted file mode 100644 index 261eeb9e9..000000000 --- a/vendor/go.opentelemetry.io/otel/LICENSE +++ /dev/null @@ -1,201 +0,0 @@ - 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/Makefile b/vendor/go.opentelemetry.io/otel/Makefile deleted file mode 100644 index 9156960ca..000000000 --- a/vendor/go.opentelemetry.io/otel/Makefile +++ /dev/null @@ -1,157 +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. - -EXAMPLES := $(shell ./get_main_pkgs.sh ./example) -TOOLS_MOD_DIR := ./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_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=./... - -.DEFAULT_GOAL := precommit - -.PHONY: precommit - -TOOLS_DIR := $(abspath ./.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_DIR)/misspell: $(TOOLS_MOD_DIR)/go.mod $(TOOLS_MOD_DIR)/go.sum $(TOOLS_MOD_DIR)/tools.go - cd $(TOOLS_MOD_DIR) && \ - go build -o $(TOOLS_DIR)/misspell github.com/client9/misspell/cmd/misspell - -$(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 - -$(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 - -precommit: generate build lint examples test - -.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 - - -.PHONY: ci -ci: precommit check-clean-work-tree license-check test-with-coverage test-386 - -.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. - set -e; for dir in $(ALL_GO_MOD_DIRS); do \ - echo "compiling all packages in $${dir}"; \ - (cd "$${dir}" && \ - go build ./... && \ - go test -run xxxxxMatchNothingxxxxx ./... >/dev/null); \ - done - -.PHONY: test -test: - set -e; for dir in $(ALL_GO_MOD_DIRS); do \ - echo "go test ./... + race in $${dir}"; \ - (cd "$${dir}" && \ - $(GOTEST) ./...); \ - 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 - -.PHONY: examples -examples: - @set -e; for ex in $(EXAMPLES); do \ - echo "Building $${ex}"; \ - (cd "$${ex}" && \ - go build .); \ - done - -.PHONY: lint -lint: $(TOOLS_DIR)/golangci-lint $(TOOLS_DIR)/misspell - 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); \ - done - -generate: $(TOOLS_DIR)/stringer - set -e; for dir in $(ALL_GO_MOD_DIRS); do \ - echo "running generators in $${dir}"; \ - (cd "$${dir}" && \ - PATH="$(TOOLS_DIR):$${PATH}" go generate ./...); \ - done - -.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 \ - 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 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/README.md b/vendor/go.opentelemetry.io/otel/README.md deleted file mode 100644 index 55dbe2133..000000000 --- a/vendor/go.opentelemetry.io/otel/README.md +++ /dev/null @@ -1,80 +0,0 @@ -# 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) -[![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) - -The Go [OpenTelemetry](https://opentelemetry.io/) client. - -## Installation - -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. - -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. - -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. - -Additional resources: - -- [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) - -## Quick Start - -Below is a brief example of importing OpenTelemetry, initializing a tracer and creating some simple spans. - -```go -package main - -import ( - "context" - "log" - - "go.opentelemetry.io/otel/api/global" - "go.opentelemetry.io/otel/exporters/stdout" - sdktrace "go.opentelemetry.io/otel/sdk/trace" -) - -func main() { - pusher, err := stdout.InstallNewPipeline(nil, nil) - if err != nil { - log.Fatal(err) - } - defer pusher.Stop() - - tracer := global.Tracer("ex.com/basic") - ctx, span := tracer.Start(context.Background(), "main") - defer span.End() - /* … */ -} -``` - -See the [API -documentation](https://pkg.go.dev/go.opentelemetry.io/otel) for more -detail, and the -[opentelemetry examples](./example/). - -## Compatible Exporters - -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. - -## Compatible Libraries - -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. - -## Contributing - -See the [contributing file](CONTRIBUTING.md). diff --git a/vendor/go.opentelemetry.io/otel/RELEASING.md b/vendor/go.opentelemetry.io/otel/RELEASING.md deleted file mode 100644 index 0fba7f175..000000000 --- a/vendor/go.opentelemetry.io/otel/RELEASING.md +++ /dev/null @@ -1,81 +0,0 @@ -# Release Process - -## Pre-Release - -Update go.mod for submodules to depend on the new release which will happen in the next step. - -1. Run the pre-release script. It creates a branch `pre_release_` that will contain all release changes. - - ``` - ./pre_release.sh -t - ``` - -2. Verify the changes. - - ``` - git diff master - ``` - - This should have changed the version for all modules to be ``. - -3. Update the [Changelog](./CHANGELOG.md). - - Make sure all relevant changes for this release are included and are in language that non-contributors to the project can understand. - To verify this, you can look directly at the commits since the ``. - - ``` - git --no-pager log --pretty=oneline "..HEAD" - ``` - - - Move all the `Unreleased` changes into a new section following the title scheme (`[] - `). - - Update all the appropriate links at the bottom. - -4. Push the changes to upstream and create a Pull Request on GitHub. - Be sure to include the curated changes from the [Changelog](./CHANGELOG.md) in the description. - - -## Tag - -Once the Pull Request with all the version changes has been approved and merged it is time to tag the merged commit. - -***IMPORTANT***: It is critical you use the same tag that you used in the Pre-Release step! -Failure to do so will leave things in a broken state. - -***IMPORTANT***: [There is currently no way to remove an incorrectly tagged version of a Go module](https://github.com/golang/go/issues/34189). -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. - - ``` - ./tag.sh - ``` - -2. Push tags to the upstream remote (not your fork: `github.com/open-telemetry/opentelemetry-go.git`). - Make sure you push all sub-modules as well. - - ``` - git push upstream - git push upstream - ... - ``` - -## Release - -Finally create a Release for the new `` on GitHub. -The release body should include all the release notes from the Changelog for this release. -Additionally, the `tag.sh` script generates commit logs since last release which can be used to supplement the release notes. - -## Verify Examples - -After releasing verify that examples build outside of the repository. - -``` -./verify_examples.sh -``` - -The script copies examples into a different directory removes any `replace` declarations in `go.mod` and builds them. -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. diff --git a/vendor/go.opentelemetry.io/otel/api/correlation/context.go b/vendor/go.opentelemetry.io/otel/api/correlation/context.go deleted file mode 100644 index ee3841984..000000000 --- a/vendor/go.opentelemetry.io/otel/api/correlation/context.go +++ /dev/null @@ -1,172 +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 ( - "context" - - "go.opentelemetry.io/otel/label" -) - -type correlationsType struct{} - -// SetHookFunc describes a type of a callback that is called when -// storing baggage in the context. -type SetHookFunc func(context.Context) context.Context - -// GetHookFunc describes a type of a callback that is called when -// getting baggage from the context. -type GetHookFunc func(context.Context, Map) Map - -// value under this key is either of type Map or correlationsData -var correlationsKey = &correlationsType{} - -type correlationsData struct { - m Map - setHook SetHookFunc - getHook GetHookFunc -} - -func (d correlationsData) isHookless() bool { - return d.setHook == nil && d.getHook == nil -} - -type hookKind int - -const ( - hookKindSet hookKind = iota - hookKindGet -) - -func (d *correlationsData) overrideHook(kind hookKind, setHook SetHookFunc, getHook GetHookFunc) { - switch kind { - case hookKindSet: - d.setHook = setHook - case hookKindGet: - d.getHook = getHook - } -} - -// ContextWithSetHook installs a hook function that will be invoked -// every time ContextWithMap is called. To avoid unnecessary callback -// invocations (recursive or not), the callback can temporarily clear -// the hooks from the context with the ContextWithNoHooks function. -// -// Note that NewContext also calls ContextWithMap, so the hook will be -// invoked. -// -// Passing nil SetHookFunc creates a context with no set hook to call. -// -// This function should not be used by applications or libraries. It -// is mostly for interoperation with other observability APIs. -func ContextWithSetHook(ctx context.Context, hook SetHookFunc) context.Context { - return contextWithHook(ctx, hookKindSet, hook, nil) -} - -// ContextWithGetHook installs a hook function that will be invoked -// every time MapFromContext is called. To avoid unnecessary callback -// invocations (recursive or not), the callback can temporarily clear -// the hooks from the context with the ContextWithNoHooks function. -// -// Note that NewContext also calls MapFromContext, so the hook will be -// invoked. -// -// Passing nil GetHookFunc creates a context with no get hook to call. -// -// This function should not be used by applications or libraries. It -// is mostly for interoperation with other observability APIs. -func ContextWithGetHook(ctx context.Context, hook GetHookFunc) context.Context { - return contextWithHook(ctx, hookKindGet, nil, hook) -} - -func contextWithHook(ctx context.Context, kind hookKind, setHook SetHookFunc, getHook GetHookFunc) context.Context { - switch v := ctx.Value(correlationsKey).(type) { - case correlationsData: - v.overrideHook(kind, setHook, getHook) - if v.isHookless() { - return context.WithValue(ctx, correlationsKey, v.m) - } - return context.WithValue(ctx, correlationsKey, v) - case Map: - return contextWithOneHookAndMap(ctx, kind, setHook, getHook, v) - default: - m := NewEmptyMap() - return contextWithOneHookAndMap(ctx, kind, setHook, getHook, m) - } -} - -func contextWithOneHookAndMap(ctx context.Context, kind hookKind, setHook SetHookFunc, getHook GetHookFunc, m Map) context.Context { - d := correlationsData{m: m} - d.overrideHook(kind, setHook, getHook) - if d.isHookless() { - return ctx - } - return context.WithValue(ctx, correlationsKey, d) -} - -// ContextWithNoHooks creates a context with all the hooks -// disabled. Also returns old set and get hooks. This function can be -// used to temporarily clear the context from hooks and then reinstate -// them by calling ContextWithSetHook and ContextWithGetHook functions -// passing the hooks returned by this function. -// -// This function should not be used by applications or libraries. It -// is mostly for interoperation with other observability APIs. -func ContextWithNoHooks(ctx context.Context) (context.Context, SetHookFunc, GetHookFunc) { - switch v := ctx.Value(correlationsKey).(type) { - case correlationsData: - return context.WithValue(ctx, correlationsKey, v.m), v.setHook, v.getHook - default: - return ctx, nil, nil - } -} - -// ContextWithMap returns a context with the Map entered into it. -func ContextWithMap(ctx context.Context, m Map) context.Context { - switch v := ctx.Value(correlationsKey).(type) { - case correlationsData: - v.m = m - ctx = context.WithValue(ctx, correlationsKey, v) - if v.setHook != nil { - ctx = v.setHook(ctx) - } - return ctx - default: - return context.WithValue(ctx, correlationsKey, m) - } -} - -// 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 { - return ContextWithMap(ctx, MapFromContext(ctx).Apply(MapUpdate{ - MultiKV: keyvalues, - })) -} - -// MapFromContext gets the current Map from a Context. -func MapFromContext(ctx context.Context) Map { - switch v := ctx.Value(correlationsKey).(type) { - case correlationsData: - if v.getHook != nil { - return v.getHook(ctx, v.m) - } - return v.m - case Map: - return v - default: - return NewEmptyMap() - } -} diff --git a/vendor/go.opentelemetry.io/otel/api/correlation/correlation_context_propagator.go b/vendor/go.opentelemetry.io/otel/api/correlation/correlation_context_propagator.go deleted file mode 100644 index bf93e701f..000000000 --- a/vendor/go.opentelemetry.io/otel/api/correlation/correlation_context_propagator.go +++ /dev/null @@ -1,118 +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 ( - "context" - "net/url" - "strings" - - "go.opentelemetry.io/otel/api/propagation" - "go.opentelemetry.io/otel/label" -) - -// 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" - -// CorrelationContext propagates Key:Values in W3C CorrelationContext -// format. -// nolint:golint -type CorrelationContext struct{} - -var _ propagation.HTTPPropagator = CorrelationContext{} - -// DefaultHTTPPropagator returns the default context correlation HTTP -// propagator. -func DefaultHTTPPropagator() propagation.HTTPPropagator { - return CorrelationContext{} -} - -// Inject implements HTTPInjector. -func (CorrelationContext) Inject(ctx context.Context, supplier propagation.HTTPSupplier) { - correlationCtx := MapFromContext(ctx) - firstIter := true - var headerValueBuilder strings.Builder - correlationCtx.Foreach(func(kv label.KeyValue) bool { - if !firstIter { - headerValueBuilder.WriteRune(',') - } - firstIter = false - headerValueBuilder.WriteString(url.QueryEscape(strings.TrimSpace((string)(kv.Key)))) - headerValueBuilder.WriteRune('=') - headerValueBuilder.WriteString(url.QueryEscape(strings.TrimSpace(kv.Value.Emit()))) - return true - }) - if headerValueBuilder.Len() > 0 { - headerString := headerValueBuilder.String() - supplier.Set(correlationContextHeader, headerString) - } -} - -// Extract implements HTTPExtractor. -func (CorrelationContext) Extract(ctx context.Context, supplier propagation.HTTPSupplier) context.Context { - correlationContext := supplier.Get(correlationContextHeader) - if correlationContext == "" { - return ctx - } - - contextValues := strings.Split(correlationContext, ",") - keyValues := make([]label.KeyValue, 0, len(contextValues)) - for _, contextValue := range contextValues { - valueAndProps := strings.Split(contextValue, ";") - if len(valueAndProps) < 1 { - continue - } - nameValue := strings.Split(valueAndProps[0], "=") - if len(nameValue) < 2 { - continue - } - name, err := url.QueryUnescape(nameValue[0]) - if err != nil { - continue - } - trimmedName := strings.TrimSpace(name) - value, err := url.QueryUnescape(nameValue[1]) - if err != nil { - continue - } - trimmedValue := strings.TrimSpace(value) - - // TODO (skaris): properties defiend https://w3c.github.io/correlation-context/, are currently - // just put as part of the value. - var trimmedValueWithProps strings.Builder - trimmedValueWithProps.WriteString(trimmedValue) - for _, prop := range valueAndProps[1:] { - trimmedValueWithProps.WriteRune(';') - trimmedValueWithProps.WriteString(prop) - } - - keyValues = append(keyValues, label.String(trimmedName, trimmedValueWithProps.String())) - } - - if len(keyValues) > 0 { - // Only update the context if valid values were found - return ContextWithMap(ctx, NewMap(MapUpdate{ - MultiKV: keyValues, - })) - } - - return ctx -} - -// GetAllKeys implements HTTPPropagator. -func (CorrelationContext) GetAllKeys() []string { - return []string{correlationContextHeader} -} 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/global/handler.go b/vendor/go.opentelemetry.io/otel/api/global/handler.go deleted file mode 100644 index 83f3e523a..000000000 --- a/vendor/go.opentelemetry.io/otel/api/global/handler.go +++ /dev/null @@ -1,91 +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 global - -import ( - "log" - "os" - "sync" - "sync/atomic" - - "go.opentelemetry.io/otel" -) - -var ( - // globalErrorHandler provides an ErrorHandler that can be used - // throughout an OpenTelemetry instrumented project. When a user - // specified ErrorHandler is registered (`SetErrorHandler`) all calls to - // `Handle` and will be delegated to the registered ErrorHandler. - globalErrorHandler = &loggingErrorHandler{ - l: log.New(os.Stderr, "", log.LstdFlags), - } - - // delegateErrorHandlerOnce ensures that a user provided ErrorHandler is - // only ever registered once. - delegateErrorHandlerOnce sync.Once - - // Comiple time check that loggingErrorHandler implements ErrorHandler. - _ otel.ErrorHandler = (*loggingErrorHandler)(nil) -) - -// loggingErrorHandler logs all errors to STDERR. -type loggingErrorHandler struct { - delegate atomic.Value - - l *log.Logger -} - -// setDelegate sets the ErrorHandler delegate if one is not already set. -func (h *loggingErrorHandler) setDelegate(d otel.ErrorHandler) { - if h.delegate.Load() != nil { - // Delegate already registered - return - } - h.delegate.Store(d) -} - -// Handle implements otel.ErrorHandler. -func (h *loggingErrorHandler) Handle(err error) { - if d := h.delegate.Load(); d != nil { - d.(otel.ErrorHandler).Handle(err) - return - } - h.l.Print(err) -} - -// ErrorHandler 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 { - return globalErrorHandler -} - -// SetErrorHandler sets the global ErrorHandler to be h. -func SetErrorHandler(h otel.ErrorHandler) { - delegateErrorHandlerOnce.Do(func() { - current := ErrorHandler() - if current == h { - return - } - if internalHandler, ok := current.(*loggingErrorHandler); ok { - internalHandler.setDelegate(h) - } - }) -} - -// Handle is a convience function for ErrorHandler().Handle(err) -func Handle(err error) { - ErrorHandler().Handle(err) -} diff --git a/vendor/go.opentelemetry.io/otel/api/global/internal/meter.go b/vendor/go.opentelemetry.io/otel/api/global/internal/meter.go deleted file mode 100644 index ce3ed2099..000000000 --- a/vendor/go.opentelemetry.io/otel/api/global/internal/meter.go +++ /dev/null @@ -1,347 +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 internal - -import ( - "context" - "sync" - "sync/atomic" - "unsafe" - - "go.opentelemetry.io/otel/api/metric" - "go.opentelemetry.io/otel/api/metric/registry" - "go.opentelemetry.io/otel/label" -) - -// 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. -// -// 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. -// -// 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. -// -// Bound instrument operations are implemented by delegating to the -// instrument after it is registered, with a sync.Once initializer to -// protect against races with Release(). -// -// Metric uniqueness checking is implemented by calling the exported -// methods of the api/metric/registry package. - -type meterKey struct { - Name, Version string -} - -type meterProvider struct { - delegate metric.Provider - - // lock protects `delegate` and `meters`. - lock sync.Mutex - - // meters maintains a unique entry for every named Meter - // that has been registered through the global instance. - meters map[meterKey]*meterEntry -} - -type meterImpl struct { - delegate unsafe.Pointer // (*metric.MeterImpl) - - lock sync.Mutex - syncInsts []*syncImpl - asyncInsts []*asyncImpl -} - -type meterEntry struct { - unique metric.MeterImpl - impl meterImpl -} - -type instrument struct { - descriptor metric.Descriptor -} - -type syncImpl struct { - delegate unsafe.Pointer // (*metric.SyncImpl) - - instrument -} - -type asyncImpl struct { - delegate unsafe.Pointer // (*metric.AsyncImpl) - - instrument - - runner metric.AsyncRunner -} - -// SyncImpler is implemented by all of the sync metric -// instruments. -type SyncImpler interface { - SyncImpl() metric.SyncImpl -} - -// AsyncImpler is implemented by all of the async -// metric instruments. -type AsyncImpler interface { - AsyncImpl() metric.AsyncImpl -} - -type syncHandle struct { - delegate unsafe.Pointer // (*metric.HandleImpl) - - inst *syncImpl - labels []label.KeyValue - - initialize sync.Once -} - -var _ metric.Provider = &meterProvider{} -var _ metric.MeterImpl = &meterImpl{} -var _ metric.InstrumentImpl = &syncImpl{} -var _ metric.BoundSyncImpl = &syncHandle{} -var _ metric.AsyncImpl = &asyncImpl{} - -func (inst *instrument) Descriptor() metric.Descriptor { - return inst.descriptor -} - -// Provider interface and delegation - -func newMeterProvider() *meterProvider { - return &meterProvider{ - meters: map[meterKey]*meterEntry{}, - } -} - -func (p *meterProvider) setDelegate(provider metric.Provider) { - p.lock.Lock() - defer p.lock.Unlock() - - p.delegate = provider - for key, entry := range p.meters { - entry.impl.setDelegate(key.Name, key.Version, provider) - } - p.meters = nil -} - -func (p *meterProvider) Meter(instrumentationName string, opts ...metric.MeterOption) metric.Meter { - p.lock.Lock() - defer p.lock.Unlock() - - if p.delegate != nil { - return p.delegate.Meter(instrumentationName, opts...) - } - - key := meterKey{ - Name: instrumentationName, - Version: metric.ConfigureMeter(opts).InstrumentationVersion, - } - entry, ok := p.meters[key] - if !ok { - entry = &meterEntry{} - entry.unique = registry.NewUniqueInstrumentMeterImpl(&entry.impl) - p.meters[key] = entry - - } - return metric.WrapMeterImpl(entry.unique, key.Name, metric.WithInstrumentationVersion(key.Version)) -} - -// Meter interface and delegation - -func (m *meterImpl) setDelegate(name, version string, provider metric.Provider) { - m.lock.Lock() - defer m.lock.Unlock() - - d := new(metric.MeterImpl) - *d = provider.Meter(name, metric.WithInstrumentationVersion(version)).MeterImpl() - m.delegate = unsafe.Pointer(d) - - for _, inst := range m.syncInsts { - inst.setDelegate(*d) - } - m.syncInsts = nil - for _, obs := range m.asyncInsts { - obs.setDelegate(*d) - } - m.asyncInsts = nil -} - -func (m *meterImpl) NewSyncInstrument(desc metric.Descriptor) (metric.SyncImpl, error) { - m.lock.Lock() - defer m.lock.Unlock() - - if meterPtr := (*metric.MeterImpl)(atomic.LoadPointer(&m.delegate)); meterPtr != nil { - return (*meterPtr).NewSyncInstrument(desc) - } - - inst := &syncImpl{ - instrument: instrument{ - descriptor: desc, - }, - } - m.syncInsts = append(m.syncInsts, inst) - return inst, nil -} - -// Synchronous delegation - -func (inst *syncImpl) setDelegate(d metric.MeterImpl) { - implPtr := new(metric.SyncImpl) - - var err error - *implPtr, err = d.NewSyncInstrument(inst.descriptor) - - if err != nil { - // TODO: There is no standard way to deliver this error to the user. - // See https://github.com/open-telemetry/opentelemetry-go/issues/514 - // Note that the default SDK will not generate any errors yet, this is - // only for added safety. - panic(err) - } - - atomic.StorePointer(&inst.delegate, unsafe.Pointer(implPtr)) -} - -func (inst *syncImpl) Implementation() interface{} { - if implPtr := (*metric.SyncImpl)(atomic.LoadPointer(&inst.delegate)); implPtr != nil { - return (*implPtr).Implementation() - } - return inst -} - -func (inst *syncImpl) Bind(labels []label.KeyValue) metric.BoundSyncImpl { - if implPtr := (*metric.SyncImpl)(atomic.LoadPointer(&inst.delegate)); implPtr != nil { - return (*implPtr).Bind(labels) - } - return &syncHandle{ - inst: inst, - labels: labels, - } -} - -func (bound *syncHandle) Unbind() { - bound.initialize.Do(func() {}) - - implPtr := (*metric.BoundSyncImpl)(atomic.LoadPointer(&bound.delegate)) - - if implPtr == nil { - return - } - - (*implPtr).Unbind() -} - -// Async delegation - -func (m *meterImpl) NewAsyncInstrument( - desc metric.Descriptor, - runner metric.AsyncRunner, -) (metric.AsyncImpl, error) { - - m.lock.Lock() - defer m.lock.Unlock() - - if meterPtr := (*metric.MeterImpl)(atomic.LoadPointer(&m.delegate)); meterPtr != nil { - return (*meterPtr).NewAsyncInstrument(desc, runner) - } - - inst := &asyncImpl{ - instrument: instrument{ - descriptor: desc, - }, - runner: runner, - } - m.asyncInsts = append(m.asyncInsts, inst) - return inst, nil -} - -func (obs *asyncImpl) Implementation() interface{} { - if implPtr := (*metric.AsyncImpl)(atomic.LoadPointer(&obs.delegate)); implPtr != nil { - return (*implPtr).Implementation() - } - return obs -} - -func (obs *asyncImpl) setDelegate(d metric.MeterImpl) { - implPtr := new(metric.AsyncImpl) - - var err error - *implPtr, err = d.NewAsyncInstrument(obs.descriptor, obs.runner) - - if err != nil { - // TODO: There is no standard way to deliver this error to the user. - // See https://github.com/open-telemetry/opentelemetry-go/issues/514 - // Note that the default SDK will not generate any errors yet, this is - // only for added safety. - panic(err) - } - - atomic.StorePointer(&obs.delegate, unsafe.Pointer(implPtr)) -} - -// Metric updates - -func (m *meterImpl) RecordBatch(ctx context.Context, labels []label.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) { - if instPtr := (*metric.SyncImpl)(atomic.LoadPointer(&inst.delegate)); instPtr != nil { - (*instPtr).RecordOne(ctx, number, labels) - } -} - -// Bound instrument initialization - -func (bound *syncHandle) RecordOne(ctx context.Context, number metric.Number) { - instPtr := (*metric.SyncImpl)(atomic.LoadPointer(&bound.inst.delegate)) - if instPtr == nil { - return - } - var implPtr *metric.BoundSyncImpl - bound.initialize.Do(func() { - implPtr = new(metric.BoundSyncImpl) - *implPtr = (*instPtr).Bind(bound.labels) - atomic.StorePointer(&bound.delegate, unsafe.Pointer(implPtr)) - }) - if implPtr == nil { - implPtr = (*metric.BoundSyncImpl)(atomic.LoadPointer(&bound.delegate)) - } - // This may still be nil if instrument was created and bound - // without a delegate, then the instrument was set to have a - // delegate and unbound. - if implPtr == nil { - return - } - (*implPtr).RecordOne(ctx, number) -} - -func AtomicFieldOffsets() map[string]uintptr { - return map[string]uintptr{ - "meterProvider.delegate": unsafe.Offsetof(meterProvider{}.delegate), - "meterImpl.delegate": unsafe.Offsetof(meterImpl{}.delegate), - "syncImpl.delegate": unsafe.Offsetof(syncImpl{}.delegate), - "asyncImpl.delegate": unsafe.Offsetof(asyncImpl{}.delegate), - "syncHandle.delegate": unsafe.Offsetof(syncHandle{}.delegate), - } -} diff --git a/vendor/go.opentelemetry.io/otel/api/global/internal/state.go b/vendor/go.opentelemetry.io/otel/api/global/internal/state.go deleted file mode 100644 index f965aa9cc..000000000 --- a/vendor/go.opentelemetry.io/otel/api/global/internal/state.go +++ /dev/null @@ -1,140 +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 internal - -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" -) - -type ( - traceProviderHolder struct { - tp trace.Provider - } - - meterProviderHolder struct { - mp metric.Provider - } - - propagatorsHolder struct { - pr propagation.Propagators - } -) - -var ( - globalTracer = defaultTracerValue() - globalMeter = defaultMeterValue() - globalPropagators = defaultPropagatorsValue() - - delegateMeterOnce sync.Once - delegateTraceOnce sync.Once -) - -// TraceProvider is the internal implementation for global.TraceProvider. -func TraceProvider() trace.Provider { - return globalTracer.Load().(traceProviderHolder).tp -} - -// SetTraceProvider is the internal implementation for global.SetTraceProvider. -func SetTraceProvider(tp trace.Provider) { - delegateTraceOnce.Do(func() { - current := TraceProvider() - 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 { - def.setDelegate(tp) - } - - }) - globalTracer.Store(traceProviderHolder{tp: tp}) -} - -// MeterProvider is the internal implementation for global.MeterProvider. -func MeterProvider() metric.Provider { - return globalMeter.Load().(meterProviderHolder).mp -} - -// SetMeterProvider is the internal implementation for global.SetMeterProvider. -func SetMeterProvider(mp metric.Provider) { - delegateMeterOnce.Do(func() { - current := MeterProvider() - - if current == mp { - // 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.(*meterProvider); ok { - def.setDelegate(mp) - } - }) - globalMeter.Store(meterProviderHolder{mp: mp}) -} - -// Propagators is the internal implementation for global.Propagators. -func Propagators() propagation.Propagators { - return globalPropagators.Load().(propagatorsHolder).pr -} - -// SetPropagators is the internal implementation for global.SetPropagators. -func SetPropagators(pr propagation.Propagators) { - globalPropagators.Store(propagatorsHolder{pr: pr}) -} - -func defaultTracerValue() *atomic.Value { - v := &atomic.Value{} - v.Store(traceProviderHolder{tp: &traceProvider{}}) - return v -} - -func defaultMeterValue() *atomic.Value { - v := &atomic.Value{} - v.Store(meterProviderHolder{mp: newMeterProvider()}) - return v -} - -func defaultPropagatorsValue() *atomic.Value { - v := &atomic.Value{} - v.Store(propagatorsHolder{pr: getDefaultPropagators()}) - 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() - globalMeter = defaultMeterValue() - globalPropagators = defaultPropagatorsValue() - delegateMeterOnce = sync.Once{} - delegateTraceOnce = sync.Once{} -} diff --git a/vendor/go.opentelemetry.io/otel/api/global/internal/trace.go b/vendor/go.opentelemetry.io/otel/api/global/internal/trace.go deleted file mode 100644 index 69024b667..000000000 --- a/vendor/go.opentelemetry.io/otel/api/global/internal/trace.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 internal - -/* -This file contains the forwarding implementation of the trace.Provider 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. - -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. - -The implementation to track and swap Tracers locks all new Tracer creation -until the swap is complete. This assumes that this operation is not -performance-critical. If that assumption is incorrect, be sure to configure an -SDK prior to any Tracer creation. -*/ - -import ( - "context" - "sync" - - "go.opentelemetry.io/otel/api/trace" -) - -// traceProvider is a placeholder for a configured SDK Provider. -// -// All Provider functionality is forwarded to a delegate once configured. -type traceProvider struct { - mtx sync.Mutex - tracers []*tracer - - delegate trace.Provider -} - -// Compile-time guarantee that traceProvider implements the trace.Provider interface. -var _ trace.Provider = &traceProvider{} - -// setDelegate configures p to delegate all Provider 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) { - if p.delegate != nil { - return - } - - p.mtx.Lock() - defer p.mtx.Unlock() - - p.delegate = provider - for _, t := range p.tracers { - t.setDelegate(provider) - } - - p.tracers = nil -} - -// Tracer implements trace.Provider. -func (p *traceProvider) Tracer(name string, opts ...trace.TracerOption) trace.Tracer { - p.mtx.Lock() - defer p.mtx.Unlock() - - if p.delegate != nil { - return p.delegate.Tracer(name) - } - - t := &tracer{name: name, opts: opts} - p.tracers = append(p.tracers, t) - return t -} - -// tracer is a placeholder for a trace.Tracer. -// -// All Tracer functionality is forwarded to a delegate once configured. -// Otherwise, all functionality is forwarded to a NoopTracer. -type tracer struct { - once sync.Once - name string - opts []trace.TracerOption - - delegate trace.Tracer -} - -// Compile-time guarantee that tracer implements the trace.Tracer interface. -var _ trace.Tracer = &tracer{} - -// setDelegate configures t to delegate all Tracer functionality to Tracers -// created by provider. -// -// All subsequent calls to the Tracer methods will be passed to the delegate. -// -// 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) { - 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) { - if t.delegate != nil { - return t.delegate.Start(ctx, name, opts...) - } - return trace.NoopTracer{}.Start(ctx, name, opts...) -} diff --git a/vendor/go.opentelemetry.io/otel/api/global/metric.go b/vendor/go.opentelemetry.io/otel/api/global/metric.go deleted file mode 100644 index 04409c46e..000000000 --- a/vendor/go.opentelemetry.io/otel/api/global/metric.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. - -package global - -import ( - "go.opentelemetry.io/otel/api/global/internal" - "go.opentelemetry.io/otel/api/metric" -) - -// Meter creates an implementation of the Meter interface from the global -// Provider. 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. -// -// This is short for MeterProvider().Meter(name) -func Meter(instrumentationName string, opts ...metric.MeterOption) metric.Meter { - return MeterProvider().Meter(instrumentationName, opts...) -} - -// MeterProvider 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. -// -// Use the meter provider to create a named meter. E.g. -// meter := global.MeterProvider().Meter("example.com/foo") -// or -// meter := global.Meter("example.com/foo") -func MeterProvider() metric.Provider { - return internal.MeterProvider() -} - -// SetMeterProvider registers `mp` as the global meter provider. -func SetMeterProvider(mp metric.Provider) { - internal.SetMeterProvider(mp) -} diff --git a/vendor/go.opentelemetry.io/otel/api/global/propagation.go b/vendor/go.opentelemetry.io/otel/api/global/propagation.go deleted file mode 100644 index e3090293d..000000000 --- a/vendor/go.opentelemetry.io/otel/api/global/propagation.go +++ /dev/null @@ -1,32 +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 global - -import ( - "go.opentelemetry.io/otel/api/global/internal" - "go.opentelemetry.io/otel/api/propagation" -) - -// 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) -} diff --git a/vendor/go.opentelemetry.io/otel/api/global/trace.go b/vendor/go.opentelemetry.io/otel/api/global/trace.go deleted file mode 100644 index 5c23325b7..000000000 --- a/vendor/go.opentelemetry.io/otel/api/global/trace.go +++ /dev/null @@ -1,44 +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 global - -import ( - "go.opentelemetry.io/otel/api/global/internal" - "go.opentelemetry.io/otel/api/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) -func Tracer(name string) trace.Tracer { - return TraceProvider().Tracer(name) -} - -// TraceProvider returns the registered global trace provider. -// If none is registered then an instance of trace.NoopProvider is returned. -// -// Use the trace provider to create a named tracer. E.g. -// tracer := global.TraceProvider().Tracer("example.com/foo") -// or -// tracer := global.Tracer("example.com/foo") -func TraceProvider() trace.Provider { - return internal.TraceProvider() -} - -// SetTraceProvider registers `tp` as the global trace provider. -func SetTraceProvider(tp trace.Provider) { - internal.SetTraceProvider(tp) -} 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/config.go b/vendor/go.opentelemetry.io/otel/api/metric/config.go deleted file mode 100644 index b5d45f9ae..000000000 --- a/vendor/go.opentelemetry.io/otel/api/metric/config.go +++ /dev/null @@ -1,125 +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" - -// InstrumentConfig contains options for instrument descriptors. -type InstrumentConfig struct { - // Description describes the instrument in human-readable terms. - Description string - // Unit describes the measurement unit for a instrument. - Unit unit.Unit - // InstrumentationName is the name of the library providing - // instrumentation. - InstrumentationName string - // InstrumentationVersion is the version of the library providing - // instrumentation. - InstrumentationVersion string -} - -// InstrumentOption is an interface for applying 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 { - var config InstrumentConfig - for _, o := range opts { - o.ApplyInstrument(&config) - } - return config -} - -// WithDescription applies provided description. -func WithDescription(desc string) InstrumentOption { - return descriptionOption(desc) -} - -type descriptionOption string - -func (d descriptionOption) ApplyInstrument(config *InstrumentConfig) { - config.Description = string(d) -} - -// WithUnit applies provided unit. -func WithUnit(unit unit.Unit) InstrumentOption { - return unitOption(unit) -} - -type unitOption unit.Unit - -func (u unitOption) ApplyInstrument(config *InstrumentConfig) { - config.Unit = unit.Unit(u) -} - -// WithInstrumentationName sets the instrumentation name. -func WithInstrumentationName(name string) InstrumentOption { - return instrumentationNameOption(name) -} - -type instrumentationNameOption string - -func (i instrumentationNameOption) ApplyInstrument(config *InstrumentConfig) { - config.InstrumentationName = string(i) -} - -// MeterConfig contains options for Meters. -type MeterConfig struct { - // InstrumentationVersion is the version of the library providing - // instrumentation. - InstrumentationVersion string -} - -// MeterOption is an interface for applying Meter options. -type MeterOption interface { - // ApplyMeter is used to set a MeterOption value of a MeterConfig. - ApplyMeter(*MeterConfig) -} - -// ConfigureMeter is a helper that applies all the MeterOptions to a -// MeterConfig. -func ConfigureMeter(opts []MeterOption) MeterConfig { - var config MeterConfig - for _, o := range opts { - o.ApplyMeter(&config) - } - return config -} - -// Option is an interface for applying Instrument or Meter options. -type Option interface { - InstrumentOption - MeterOption -} - -// WithInstrumentationVersion sets the instrumentation version. -func WithInstrumentationVersion(version string) Option { - return instrumentationVersionOption(version) -} - -type instrumentationVersionOption string - -func (i instrumentationVersionOption) ApplyMeter(config *MeterConfig) { - config.InstrumentationVersion = string(i) -} - -func (i instrumentationVersionOption) ApplyInstrument(config *InstrumentConfig) { - config.InstrumentationVersion = string(i) -} 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/kind_string.go b/vendor/go.opentelemetry.io/otel/api/metric/kind_string.go deleted file mode 100644 index eb1a0d503..000000000 --- a/vendor/go.opentelemetry.io/otel/api/metric/kind_string.go +++ /dev/null @@ -1,28 +0,0 @@ -// Code generated by "stringer -type=Kind"; 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[ValueRecorderKind-0] - _ = x[ValueObserverKind-1] - _ = x[CounterKind-2] - _ = x[UpDownCounterKind-3] - _ = x[SumObserverKind-4] - _ = x[UpDownSumObserverKind-5] -} - -const _Kind_name = "ValueRecorderKindValueObserverKindCounterKindUpDownCounterKindSumObserverKindUpDownSumObserverKind" - -var _Kind_index = [...]uint8{0, 17, 34, 45, 62, 77, 98} - -func (i Kind) String() string { - if i < 0 || i >= Kind(len(_Kind_index)-1) { - return "Kind(" + strconv.FormatInt(int64(i), 10) + ")" - } - return _Kind_name[_Kind_index[i]:_Kind_index[i+1]] -} diff --git a/vendor/go.opentelemetry.io/otel/api/metric/meter.go b/vendor/go.opentelemetry.io/otel/api/metric/meter.go deleted file mode 100644 index 079c29477..000000000 --- a/vendor/go.opentelemetry.io/otel/api/metric/meter.go +++ /dev/null @@ -1,320 +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: -// -// - 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 { - // 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 - // only if that code provides built-in instrumentation. If the - // instrumentationName is empty, then a implementation defined default - // name will be used instead. - Meter(instrumentationName string, opts ...MeterOption) Meter -} - -// Meter is the OpenTelemetry metric API, based on a `MeterImpl` -// implementation and the `Meter` library name. -// -// An uninitialized Meter is a no-op implementation. -type Meter struct { - impl MeterImpl - name, version string -} - -// RecordBatch atomically records a batch of measurements. -func (m Meter) RecordBatch(ctx context.Context, ls []label.KeyValue, ms ...Measurement) { - if m.impl == nil { - return - } - m.impl.RecordBatch(ctx, ls, ms...) -} - -// NewBatchObserver creates a new BatchObserver that supports -// making batches of observations for multiple instruments. -func (m Meter) NewBatchObserver(callback BatchObserverFunc) BatchObserver { - return BatchObserver{ - meter: m, - runner: newBatchAsyncRunner(callback), - } -} - -// NewInt64Counter creates a new integer Counter instrument with the -// given name, customized with options. May return an error if the -// name is invalid (e.g., empty) or improperly registered (e.g., -// duplicate registration). -func (m Meter) NewInt64Counter(name string, options ...InstrumentOption) (Int64Counter, error) { - return wrapInt64CounterInstrument( - m.newSync(name, CounterKind, Int64NumberKind, options)) -} - -// NewFloat64Counter creates a new floating point Counter with the -// given name, customized with options. May return an error if the -// name is invalid (e.g., empty) or improperly registered (e.g., -// duplicate registration). -func (m Meter) NewFloat64Counter(name string, options ...InstrumentOption) (Float64Counter, error) { - return wrapFloat64CounterInstrument( - m.newSync(name, CounterKind, Float64NumberKind, options)) -} - -// NewInt64UpDownCounter creates a new integer UpDownCounter instrument with the -// given name, customized with options. May return an error if the -// name is invalid (e.g., empty) or improperly registered (e.g., -// duplicate registration). -func (m Meter) NewInt64UpDownCounter(name string, options ...InstrumentOption) (Int64UpDownCounter, error) { - return wrapInt64UpDownCounterInstrument( - m.newSync(name, UpDownCounterKind, Int64NumberKind, options)) -} - -// NewFloat64UpDownCounter creates a new floating point UpDownCounter with the -// given name, customized with options. May return an error if the -// name is invalid (e.g., empty) or improperly registered (e.g., -// duplicate registration). -func (m Meter) NewFloat64UpDownCounter(name string, options ...InstrumentOption) (Float64UpDownCounter, error) { - return wrapFloat64UpDownCounterInstrument( - m.newSync(name, UpDownCounterKind, Float64NumberKind, options)) -} - -// NewInt64ValueRecorder creates a new integer ValueRecorder instrument with the -// given name, customized with options. May return an error if the -// name is invalid (e.g., empty) or improperly registered (e.g., -// duplicate registration). -func (m Meter) NewInt64ValueRecorder(name string, opts ...InstrumentOption) (Int64ValueRecorder, error) { - return wrapInt64ValueRecorderInstrument( - m.newSync(name, ValueRecorderKind, Int64NumberKind, opts)) -} - -// NewFloat64ValueRecorder creates a new floating point ValueRecorder with the -// given name, customized with options. May return an error if the -// name is invalid (e.g., empty) or improperly registered (e.g., -// duplicate registration). -func (m Meter) NewFloat64ValueRecorder(name string, opts ...InstrumentOption) (Float64ValueRecorder, error) { - return wrapFloat64ValueRecorderInstrument( - m.newSync(name, ValueRecorderKind, Float64NumberKind, opts)) -} - -// NewInt64ValueObserver creates a new integer ValueObserver instrument -// with the given name, running a given callback, and customized with -// options. May return an error if the name is invalid (e.g., empty) -// or improperly registered (e.g., duplicate registration). -func (m Meter) NewInt64ValueObserver(name string, callback Int64ObserverFunc, opts ...InstrumentOption) (Int64ValueObserver, error) { - if callback == nil { - return wrapInt64ValueObserverInstrument(NoopAsync{}, nil) - } - return wrapInt64ValueObserverInstrument( - m.newAsync(name, ValueObserverKind, Int64NumberKind, opts, - newInt64AsyncRunner(callback))) -} - -// NewFloat64ValueObserver creates a new floating point ValueObserver with -// the given name, running a given callback, and customized with -// options. May return an error if the name is invalid (e.g., empty) -// or improperly registered (e.g., duplicate registration). -func (m Meter) NewFloat64ValueObserver(name string, callback Float64ObserverFunc, opts ...InstrumentOption) (Float64ValueObserver, error) { - if callback == nil { - return wrapFloat64ValueObserverInstrument(NoopAsync{}, nil) - } - return wrapFloat64ValueObserverInstrument( - m.newAsync(name, ValueObserverKind, Float64NumberKind, opts, - newFloat64AsyncRunner(callback))) -} - -// NewInt64SumObserver creates a new integer SumObserver instrument -// with the given name, running a given callback, and customized with -// options. May return an error if the name is invalid (e.g., empty) -// or improperly registered (e.g., duplicate registration). -func (m Meter) NewInt64SumObserver(name string, callback Int64ObserverFunc, opts ...InstrumentOption) (Int64SumObserver, error) { - if callback == nil { - return wrapInt64SumObserverInstrument(NoopAsync{}, nil) - } - return wrapInt64SumObserverInstrument( - m.newAsync(name, SumObserverKind, Int64NumberKind, opts, - newInt64AsyncRunner(callback))) -} - -// NewFloat64SumObserver creates a new floating point SumObserver with -// the given name, running a given callback, and customized with -// options. May return an error if the name is invalid (e.g., empty) -// or improperly registered (e.g., duplicate registration). -func (m Meter) NewFloat64SumObserver(name string, callback Float64ObserverFunc, opts ...InstrumentOption) (Float64SumObserver, error) { - if callback == nil { - return wrapFloat64SumObserverInstrument(NoopAsync{}, nil) - } - return wrapFloat64SumObserverInstrument( - m.newAsync(name, SumObserverKind, Float64NumberKind, opts, - newFloat64AsyncRunner(callback))) -} - -// NewInt64UpDownSumObserver creates a new integer UpDownSumObserver instrument -// with the given name, running a given callback, and customized with -// options. May return an error if the name is invalid (e.g., empty) -// or improperly registered (e.g., duplicate registration). -func (m Meter) NewInt64UpDownSumObserver(name string, callback Int64ObserverFunc, opts ...InstrumentOption) (Int64UpDownSumObserver, error) { - if callback == nil { - return wrapInt64UpDownSumObserverInstrument(NoopAsync{}, nil) - } - return wrapInt64UpDownSumObserverInstrument( - m.newAsync(name, UpDownSumObserverKind, Int64NumberKind, opts, - newInt64AsyncRunner(callback))) -} - -// NewFloat64UpDownSumObserver creates a new floating point UpDownSumObserver with -// the given name, running a given callback, and customized with -// options. May return an error if the name is invalid (e.g., empty) -// or improperly registered (e.g., duplicate registration). -func (m Meter) NewFloat64UpDownSumObserver(name string, callback Float64ObserverFunc, opts ...InstrumentOption) (Float64UpDownSumObserver, error) { - if callback == nil { - return wrapFloat64UpDownSumObserverInstrument(NoopAsync{}, nil) - } - return wrapFloat64UpDownSumObserverInstrument( - m.newAsync(name, UpDownSumObserverKind, Float64NumberKind, opts, - newFloat64AsyncRunner(callback))) -} - -// NewInt64ValueObserver creates a new integer ValueObserver instrument -// with the given name, running in a batch callback, and customized with -// options. May return an error if the name is invalid (e.g., empty) -// or improperly registered (e.g., duplicate registration). -func (b BatchObserver) NewInt64ValueObserver(name string, opts ...InstrumentOption) (Int64ValueObserver, error) { - if b.runner == nil { - return wrapInt64ValueObserverInstrument(NoopAsync{}, nil) - } - return wrapInt64ValueObserverInstrument( - b.meter.newAsync(name, ValueObserverKind, Int64NumberKind, opts, b.runner)) -} - -// NewFloat64ValueObserver creates a new floating point ValueObserver with -// the given name, running in a batch callback, and customized with -// options. May return an error if the name is invalid (e.g., empty) -// or improperly registered (e.g., duplicate registration). -func (b BatchObserver) NewFloat64ValueObserver(name string, opts ...InstrumentOption) (Float64ValueObserver, error) { - if b.runner == nil { - return wrapFloat64ValueObserverInstrument(NoopAsync{}, nil) - } - return wrapFloat64ValueObserverInstrument( - b.meter.newAsync(name, ValueObserverKind, Float64NumberKind, opts, - b.runner)) -} - -// NewInt64SumObserver creates a new integer SumObserver instrument -// with the given name, running in a batch callback, and customized with -// options. May return an error if the name is invalid (e.g., empty) -// or improperly registered (e.g., duplicate registration). -func (b BatchObserver) NewInt64SumObserver(name string, opts ...InstrumentOption) (Int64SumObserver, error) { - if b.runner == nil { - return wrapInt64SumObserverInstrument(NoopAsync{}, nil) - } - return wrapInt64SumObserverInstrument( - b.meter.newAsync(name, SumObserverKind, Int64NumberKind, opts, b.runner)) -} - -// NewFloat64SumObserver creates a new floating point SumObserver with -// the given name, running in a batch callback, and customized with -// options. May return an error if the name is invalid (e.g., empty) -// or improperly registered (e.g., duplicate registration). -func (b BatchObserver) NewFloat64SumObserver(name string, opts ...InstrumentOption) (Float64SumObserver, error) { - if b.runner == nil { - return wrapFloat64SumObserverInstrument(NoopAsync{}, nil) - } - return wrapFloat64SumObserverInstrument( - b.meter.newAsync(name, SumObserverKind, Float64NumberKind, opts, - b.runner)) -} - -// NewInt64UpDownSumObserver creates a new integer UpDownSumObserver instrument -// with the given name, running in a batch callback, and customized with -// options. May return an error if the name is invalid (e.g., empty) -// or improperly registered (e.g., duplicate registration). -func (b BatchObserver) NewInt64UpDownSumObserver(name string, opts ...InstrumentOption) (Int64UpDownSumObserver, error) { - if b.runner == nil { - return wrapInt64UpDownSumObserverInstrument(NoopAsync{}, nil) - } - return wrapInt64UpDownSumObserverInstrument( - b.meter.newAsync(name, UpDownSumObserverKind, Int64NumberKind, opts, b.runner)) -} - -// NewFloat64UpDownSumObserver creates a new floating point UpDownSumObserver with -// the given name, running in a batch callback, and customized with -// options. May return an error if the name is invalid (e.g., empty) -// or improperly registered (e.g., duplicate registration). -func (b BatchObserver) NewFloat64UpDownSumObserver(name string, opts ...InstrumentOption) (Float64UpDownSumObserver, error) { - if b.runner == nil { - return wrapFloat64UpDownSumObserverInstrument(NoopAsync{}, nil) - } - return wrapFloat64UpDownSumObserverInstrument( - b.meter.newAsync(name, UpDownSumObserverKind, Float64NumberKind, opts, - b.runner)) -} - -// MeterImpl returns the underlying MeterImpl of this Meter. -func (m Meter) MeterImpl() MeterImpl { - return m.impl -} - -// newAsync constructs one new asynchronous instrument. -func (m Meter) newAsync( - name string, - mkind Kind, - nkind NumberKind, - opts []InstrumentOption, - runner AsyncRunner, -) ( - AsyncImpl, - error, -) { - if m.impl == nil { - return NoopAsync{}, nil - } - desc := NewDescriptor(name, mkind, nkind, opts...) - desc.config.InstrumentationName = m.name - desc.config.InstrumentationVersion = m.version - return m.impl.NewAsyncInstrument(desc, runner) -} - -// newSync constructs one new synchronous instrument. -func (m Meter) newSync( - name string, - metricKind Kind, - numberKind NumberKind, - opts []InstrumentOption, -) ( - SyncImpl, - error, -) { - if m.impl == nil { - return NoopSync{}, nil - } - desc := NewDescriptor(name, metricKind, numberKind, opts...) - desc.config.InstrumentationName = m.name - desc.config.InstrumentationVersion = m.version - return m.impl.NewSyncInstrument(desc) -} 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/noop.go b/vendor/go.opentelemetry.io/otel/api/metric/noop.go deleted file mode 100644 index de2c5681a..000000000 --- a/vendor/go.opentelemetry.io/otel/api/metric/noop.go +++ /dev/null @@ -1,58 +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" -) - -type NoopProvider struct{} - -type noopInstrument struct{} -type noopBoundInstrument struct{} -type NoopSync struct{ noopInstrument } -type NoopAsync struct{ noopInstrument } - -var _ Provider = NoopProvider{} -var _ SyncImpl = NoopSync{} -var _ BoundSyncImpl = noopBoundInstrument{} -var _ AsyncImpl = NoopAsync{} - -func (NoopProvider) Meter(_ string, _ ...MeterOption) Meter { - return Meter{} -} - -func (noopInstrument) Implementation() interface{} { - return nil -} - -func (noopInstrument) Descriptor() Descriptor { - return Descriptor{} -} - -func (noopBoundInstrument) RecordOne(context.Context, Number) { -} - -func (noopBoundInstrument) Unbind() { -} - -func (NoopSync) Bind([]label.KeyValue) BoundSyncImpl { - return noopBoundInstrument{} -} - -func (NoopSync) RecordOne(context.Context, Number, []label.KeyValue) { -} diff --git a/vendor/go.opentelemetry.io/otel/api/metric/number.go b/vendor/go.opentelemetry.io/otel/api/metric/number.go deleted file mode 100644 index c3ca0ed79..000000000 --- a/vendor/go.opentelemetry.io/otel/api/metric/number.go +++ /dev/null @@ -1,540 +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 - -//go:generate stringer -type=NumberKind - -import ( - "fmt" - "math" - "sync/atomic" - - "go.opentelemetry.io/otel/internal" -) - -// NumberKind describes the data type of the Number. -type NumberKind int8 - -const ( - // Int64NumberKind means that the Number stores int64. - Int64NumberKind NumberKind = iota - // Float64NumberKind means that the Number stores float64. - Float64NumberKind -) - -// Zero returns a zero value for a given NumberKind -func (k NumberKind) Zero() Number { - switch k { - case Int64NumberKind: - return NewInt64Number(0) - case Float64NumberKind: - return NewFloat64Number(0.) - default: - return Number(0) - } -} - -// Minimum returns the minimum representable value -// for a given NumberKind -func (k NumberKind) Minimum() Number { - switch k { - case Int64NumberKind: - return NewInt64Number(math.MinInt64) - case Float64NumberKind: - return NewFloat64Number(-1. * math.MaxFloat64) - default: - return Number(0) - } -} - -// Maximum returns the maximum representable value -// for a given NumberKind -func (k NumberKind) Maximum() Number { - switch k { - case Int64NumberKind: - return NewInt64Number(math.MaxInt64) - case Float64NumberKind: - return NewFloat64Number(math.MaxFloat64) - default: - return Number(0) - } -} - -// Number represents either an integral or a floating point value. It -// needs to be accompanied with a source of NumberKind that describes -// the actual type of the value stored within Number. -type Number uint64 - -// - constructors - -// NewNumberFromRaw creates a new Number from a raw value. -func NewNumberFromRaw(r uint64) Number { - return Number(r) -} - -// NewInt64Number creates an integral Number. -func NewInt64Number(i int64) Number { - return NewNumberFromRaw(internal.Int64ToRaw(i)) -} - -// NewFloat64Number creates a floating point Number. -func NewFloat64Number(f float64) Number { - return NewNumberFromRaw(internal.Float64ToRaw(f)) -} - -// 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 { - switch kind { - case Int64NumberKind: - return NewInt64Number(-nn.AsInt64()) - case Float64NumberKind: - return NewFloat64Number(-nn.AsFloat64()) - } - return nn -} - -// - as x - -// AsNumber gets the Number. -func (n *Number) AsNumber() Number { - return *n -} - -// AsRaw gets the uninterpreted raw value. Might be useful for some -// atomic operations. -func (n *Number) AsRaw() uint64 { - return uint64(*n) -} - -// AsInt64 assumes that the value contains an int64 and returns it as -// such. -func (n *Number) AsInt64() int64 { - return internal.RawToInt64(n.AsRaw()) -} - -// AsFloat64 assumes that the measurement value contains a float64 and -// returns it as such. -func (n *Number) AsFloat64() float64 { - return internal.RawToFloat64(n.AsRaw()) -} - -// - as x atomic - -// AsNumberAtomic gets the Number atomically. -func (n *Number) AsNumberAtomic() Number { - return NewNumberFromRaw(n.AsRawAtomic()) -} - -// AsRawAtomic gets the uninterpreted raw value atomically. Might be -// useful for some atomic operations. -func (n *Number) AsRawAtomic() uint64 { - return atomic.LoadUint64(n.AsRawPtr()) -} - -// AsInt64Atomic assumes that the number contains an int64 and returns -// it as such atomically. -func (n *Number) AsInt64Atomic() int64 { - return atomic.LoadInt64(n.AsInt64Ptr()) -} - -// AsFloat64Atomic assumes that the measurement value contains a -// float64 and returns it as such atomically. -func (n *Number) AsFloat64Atomic() float64 { - return internal.RawToFloat64(n.AsRawAtomic()) -} - -// - as x ptr - -// AsRawPtr gets the pointer to the raw, uninterpreted raw -// value. Might be useful for some atomic operations. -func (n *Number) AsRawPtr() *uint64 { - return (*uint64)(n) -} - -// AsInt64Ptr assumes that the number contains an int64 and returns a -// pointer to it. -func (n *Number) AsInt64Ptr() *int64 { - return internal.RawPtrToInt64Ptr(n.AsRawPtr()) -} - -// AsFloat64Ptr assumes that the number contains a float64 and returns a -// pointer to it. -func (n *Number) AsFloat64Ptr() *float64 { - return internal.RawPtrToFloat64Ptr(n.AsRawPtr()) -} - -// - coerce - -// CoerceToInt64 casts the number to int64. May result in -// data/precision loss. -func (n *Number) CoerceToInt64(kind NumberKind) int64 { - switch kind { - case Int64NumberKind: - return n.AsInt64() - case Float64NumberKind: - return int64(n.AsFloat64()) - default: - // you get what you deserve - return 0 - } -} - -// CoerceToFloat64 casts the number to float64. May result in -// data/precision loss. -func (n *Number) CoerceToFloat64(kind NumberKind) float64 { - switch kind { - case Int64NumberKind: - return float64(n.AsInt64()) - case Float64NumberKind: - return n.AsFloat64() - default: - // you get what you deserve - return 0 - } -} - -// - set - -// SetNumber sets the number to the passed number. Both should be of -// the same kind. -func (n *Number) SetNumber(nn Number) { - *n.AsRawPtr() = nn.AsRaw() -} - -// SetRaw sets the number to the passed raw value. Both number and the -// raw number should represent the same kind. -func (n *Number) SetRaw(r uint64) { - *n.AsRawPtr() = r -} - -// SetInt64 assumes that the number contains an int64 and sets it to -// the passed value. -func (n *Number) SetInt64(i int64) { - *n.AsInt64Ptr() = i -} - -// SetFloat64 assumes that the number contains a float64 and sets it -// to the passed value. -func (n *Number) SetFloat64(f float64) { - *n.AsFloat64Ptr() = f -} - -// - set atomic - -// SetNumberAtomic sets the number to the passed number -// atomically. Both should be of the same kind. -func (n *Number) SetNumberAtomic(nn Number) { - atomic.StoreUint64(n.AsRawPtr(), nn.AsRaw()) -} - -// SetRawAtomic sets the number to the passed raw value -// atomically. Both number and the raw number should represent the -// same kind. -func (n *Number) SetRawAtomic(r uint64) { - atomic.StoreUint64(n.AsRawPtr(), r) -} - -// SetInt64Atomic assumes that the number contains an int64 and sets -// it to the passed value atomically. -func (n *Number) SetInt64Atomic(i int64) { - atomic.StoreInt64(n.AsInt64Ptr(), i) -} - -// SetFloat64Atomic assumes that the number contains a float64 and -// sets it to the passed value atomically. -func (n *Number) SetFloat64Atomic(f float64) { - atomic.StoreUint64(n.AsRawPtr(), internal.Float64ToRaw(f)) -} - -// - swap - -// SwapNumber sets the number to the passed number and returns the old -// number. Both this number and the passed number should be of the -// same kind. -func (n *Number) SwapNumber(nn Number) Number { - old := *n - n.SetNumber(nn) - return old -} - -// SwapRaw sets the number to the passed raw value and returns the old -// raw value. Both number and the raw number should represent the same -// kind. -func (n *Number) SwapRaw(r uint64) uint64 { - old := n.AsRaw() - n.SetRaw(r) - return old -} - -// SwapInt64 assumes that the number contains an int64, sets it to the -// passed value and returns the old int64 value. -func (n *Number) SwapInt64(i int64) int64 { - old := n.AsInt64() - n.SetInt64(i) - return old -} - -// SwapFloat64 assumes that the number contains an float64, sets it to -// the passed value and returns the old float64 value. -func (n *Number) SwapFloat64(f float64) float64 { - old := n.AsFloat64() - n.SetFloat64(f) - return old -} - -// - swap atomic - -// SwapNumberAtomic sets the number to the passed number and returns -// the old number atomically. Both this number and the passed number -// should be of the same kind. -func (n *Number) SwapNumberAtomic(nn Number) Number { - return NewNumberFromRaw(atomic.SwapUint64(n.AsRawPtr(), nn.AsRaw())) -} - -// SwapRawAtomic sets the number to the passed raw value and returns -// the old raw value atomically. Both number and the raw number should -// represent the same kind. -func (n *Number) SwapRawAtomic(r uint64) uint64 { - return atomic.SwapUint64(n.AsRawPtr(), r) -} - -// SwapInt64Atomic assumes that the number contains an int64, sets it -// to the passed value and returns the old int64 value atomically. -func (n *Number) SwapInt64Atomic(i int64) int64 { - return atomic.SwapInt64(n.AsInt64Ptr(), i) -} - -// SwapFloat64Atomic assumes that the number contains an float64, sets -// it to the passed value and returns the old float64 value -// atomically. -func (n *Number) SwapFloat64Atomic(f float64) float64 { - return internal.RawToFloat64(atomic.SwapUint64(n.AsRawPtr(), internal.Float64ToRaw(f))) -} - -// - add - -// 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) { - switch kind { - case Int64NumberKind: - n.AddInt64(nn.AsInt64()) - case Float64NumberKind: - 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) { - n.AddNumber(kind, NewNumberFromRaw(r)) -} - -// AddInt64 assumes that the number contains an int64 and adds the -// passed int64 to it. -func (n *Number) AddInt64(i int64) { - *n.AsInt64Ptr() += i -} - -// AddFloat64 assumes that the number contains a float64 and adds the -// passed float64 to it. -func (n *Number) AddFloat64(f float64) { - *n.AsFloat64Ptr() += f -} - -// - add atomic - -// 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) { - switch kind { - case Int64NumberKind: - n.AddInt64Atomic(nn.AsInt64()) - case Float64NumberKind: - n.AddFloat64Atomic(nn.AsFloat64()) - } -} - -// 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) { - n.AddNumberAtomic(kind, NewNumberFromRaw(r)) -} - -// AddInt64Atomic assumes that the number contains an int64 and adds -// the passed int64 to it atomically. -func (n *Number) AddInt64Atomic(i int64) { - atomic.AddInt64(n.AsInt64Ptr(), i) -} - -// AddFloat64Atomic assumes that the number contains a float64 and -// adds the passed float64 to it atomically. -func (n *Number) AddFloat64Atomic(f float64) { - for { - o := n.AsFloat64Atomic() - if n.CompareAndSwapFloat64(o, o+f) { - break - } - } -} - -// - compare and swap (atomic only) - -// CompareAndSwapNumber does the atomic CAS operation on this -// number. This number and passed old and new numbers should be of the -// same kind. -func (n *Number) CompareAndSwapNumber(on, nn Number) bool { - return atomic.CompareAndSwapUint64(n.AsRawPtr(), on.AsRaw(), nn.AsRaw()) -} - -// CompareAndSwapRaw does the atomic CAS operation on this -// number. This number and passed old and new raw values should be of -// the same kind. -func (n *Number) CompareAndSwapRaw(or, nr uint64) bool { - return atomic.CompareAndSwapUint64(n.AsRawPtr(), or, nr) -} - -// CompareAndSwapInt64 assumes that this number contains an int64 and -// does the atomic CAS operation on it. -func (n *Number) CompareAndSwapInt64(oi, ni int64) bool { - return atomic.CompareAndSwapInt64(n.AsInt64Ptr(), oi, ni) -} - -// CompareAndSwapFloat64 assumes that this number contains a float64 and -// does the atomic CAS operation on it. -func (n *Number) CompareAndSwapFloat64(of, nf float64) bool { - return atomic.CompareAndSwapUint64(n.AsRawPtr(), internal.Float64ToRaw(of), internal.Float64ToRaw(nf)) -} - -// - compare - -// CompareNumber compares two Numbers given their kind. Both numbers -// should have the same kind. This returns: -// 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 { - switch kind { - case Int64NumberKind: - return n.CompareInt64(nn.AsInt64()) - case Float64NumberKind: - return n.CompareFloat64(nn.AsFloat64()) - default: - // you get what you deserve - return 0 - } -} - -// 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 { - return n.CompareNumber(kind, NewNumberFromRaw(r)) -} - -// CompareInt64 assumes that the Number contains an int64 and performs -// a comparison between the value and the other value. It returns the -// typical result of the compare function: -1 if the value is less -// than the other, 0 if both are equal, 1 if the value is greater than -// the other. -func (n *Number) CompareInt64(i int64) int { - this := n.AsInt64() - if this < i { - return -1 - } else if this > i { - return 1 - } - return 0 -} - -// CompareFloat64 assumes that the Number contains a float64 and -// performs a comparison between the value and the other value. It -// returns the typical result of the compare function: -1 if the value -// is less than the other, 0 if both are equal, 1 if the value is -// greater than the other. -// -// Do not compare NaN values. -func (n *Number) CompareFloat64(f float64) int { - this := n.AsFloat64() - if this < f { - return -1 - } else if this > f { - return 1 - } - return 0 -} - -// - relations to zero - -// IsPositive returns true if the actual value is greater than zero. -func (n *Number) IsPositive(kind NumberKind) bool { - return n.compareWithZero(kind) > 0 -} - -// IsNegative returns true if the actual value is less than zero. -func (n *Number) IsNegative(kind NumberKind) bool { - return n.compareWithZero(kind) < 0 -} - -// IsZero returns true if the actual value is equal to zero. -func (n *Number) IsZero(kind NumberKind) bool { - return n.compareWithZero(kind) == 0 -} - -// - misc - -// 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 { - switch kind { - case Int64NumberKind: - return fmt.Sprintf("%d", n.AsInt64()) - case Float64NumberKind: - return fmt.Sprintf("%f", n.AsFloat64()) - default: - return "" - } -} - -// AsInterface returns the number as an interface{}, typically used -// for NumberKind-correct JSON conversion. -func (n *Number) AsInterface(kind NumberKind) interface{} { - switch kind { - case Int64NumberKind: - return n.AsInt64() - case Float64NumberKind: - return n.AsFloat64() - default: - return math.NaN() - } -} - -// - private stuff - -func (n *Number) compareWithZero(kind NumberKind) int { - switch kind { - case Int64NumberKind: - return n.CompareInt64(0) - case Float64NumberKind: - return n.CompareFloat64(0.) - default: - // you get what you deserve - return 0 - } -} 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/registry/registry.go b/vendor/go.opentelemetry.io/otel/api/metric/registry/registry.go deleted file mode 100644 index 16b6883a9..000000000 --- a/vendor/go.opentelemetry.io/otel/api/metric/registry/registry.go +++ /dev/null @@ -1,170 +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 registry // import "go.opentelemetry.io/otel/api/metric/registry" - -import ( - "context" - "fmt" - "sync" - - "go.opentelemetry.io/otel/api/metric" - "go.opentelemetry.io/otel/label" -) - -// Provider is a standard metric.Provider for wrapping `MeterImpl` -type Provider struct { - impl metric.MeterImpl -} - -var _ metric.Provider = (*Provider)(nil) - -// uniqueInstrumentMeterImpl implements the metric.MeterImpl interface, adding -// uniqueness checking for instrument descriptors. Use NewUniqueInstrumentMeter -// to wrap an implementation with uniqueness checking. -type uniqueInstrumentMeterImpl struct { - lock sync.Mutex - impl metric.MeterImpl - state map[key]metric.InstrumentImpl -} - -var _ metric.MeterImpl = (*uniqueInstrumentMeterImpl)(nil) - -type key struct { - instrumentName string - instrumentationName string - InstrumentationVersion string -} - -// NewProvider returns a new provider that implements instrument -// name-uniqueness checking. -func NewProvider(impl metric.MeterImpl) *Provider { - return &Provider{ - impl: NewUniqueInstrumentMeterImpl(impl), - } -} - -// Meter implements metric.Provider. -func (p *Provider) 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") - -// NewUniqueInstrumentMeterImpl returns a wrapped metric.MeterImpl with -// the addition of uniqueness checking. -func NewUniqueInstrumentMeterImpl(impl metric.MeterImpl) metric.MeterImpl { - return &uniqueInstrumentMeterImpl{ - impl: impl, - state: map[key]metric.InstrumentImpl{}, - } -} - -// RecordBatch implements metric.MeterImpl. -func (u *uniqueInstrumentMeterImpl) RecordBatch(ctx context.Context, labels []label.KeyValue, ms ...metric.Measurement) { - u.impl.RecordBatch(ctx, labels, ms...) -} - -func keyOf(descriptor metric.Descriptor) key { - return key{ - descriptor.Name(), - descriptor.InstrumentationName(), - descriptor.InstrumentationVersion(), - } -} - -// 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", - desc.Name(), - desc.InstrumentationName(), - desc.InstrumentationVersion(), - desc.NumberKind(), - desc.MetricKind(), - 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() && - candidate.NumberKind() == existing.NumberKind() -} - -// checkUniqueness returns an ErrMetricKindMismatch error if there is -// a conflict between a descriptor that was already registered and the -// `descriptor` argument. If there is an existing compatible -// registration, this returns the already-registered instrument. If -// there is no conflict and no prior registration, returns (nil, nil). -func (u *uniqueInstrumentMeterImpl) checkUniqueness(descriptor metric.Descriptor) (metric.InstrumentImpl, error) { - impl, ok := u.state[keyOf(descriptor)] - if !ok { - return nil, nil - } - - if !Compatible(descriptor, impl.Descriptor()) { - return nil, NewMetricKindMismatchError(impl.Descriptor()) - } - - return impl, nil -} - -// NewSyncInstrument implements metric.MeterImpl. -func (u *uniqueInstrumentMeterImpl) NewSyncInstrument(descriptor metric.Descriptor) (metric.SyncImpl, error) { - u.lock.Lock() - defer u.lock.Unlock() - - impl, err := u.checkUniqueness(descriptor) - - if err != nil { - return nil, err - } else if impl != nil { - return impl.(metric.SyncImpl), nil - } - - syncInst, err := u.impl.NewSyncInstrument(descriptor) - if err != nil { - return nil, err - } - u.state[keyOf(descriptor)] = syncInst - return syncInst, nil -} - -// NewAsyncInstrument implements metric.MeterImpl. -func (u *uniqueInstrumentMeterImpl) NewAsyncInstrument( - descriptor metric.Descriptor, - runner metric.AsyncRunner, -) (metric.AsyncImpl, error) { - u.lock.Lock() - defer u.lock.Unlock() - - impl, err := u.checkUniqueness(descriptor) - - if err != nil { - return nil, err - } else if impl != nil { - return impl.(metric.AsyncImpl), nil - } - - asyncInst, err := u.impl.NewAsyncInstrument(descriptor, runner) - if err != nil { - return nil, err - } - u.state[keyOf(descriptor)] = asyncInst - return asyncInst, nil -} diff --git a/vendor/go.opentelemetry.io/otel/api/metric/sdkapi.go b/vendor/go.opentelemetry.io/otel/api/metric/sdkapi.go deleted file mode 100644 index 3c4e11ee4..000000000 --- a/vendor/go.opentelemetry.io/otel/api/metric/sdkapi.go +++ /dev/null @@ -1,94 +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" -) - -// 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) - - // NewSyncInstrument returns a newly constructed - // synchronous instrument implementation or an error, should - // one occur. - NewSyncInstrument(descriptor Descriptor) (SyncImpl, error) - - // NewAsyncInstrument returns a newly constructed - // asynchronous instrument implementation or an error, should - // one occur. - NewAsyncInstrument( - descriptor Descriptor, - runner AsyncRunner, - ) (AsyncImpl, error) -} - -// InstrumentImpl is a common interface for synchronous and -// asynchronous instruments. -type InstrumentImpl interface { - // Implementation returns the underlying implementation of the - // instrument, which allows the implementation to gain access - // to its own representation especially from a `Measurement`. - Implementation() interface{} - - // Descriptor returns a copy of the instrument's Descriptor. - Descriptor() Descriptor -} - -// SyncImpl is the implementation-level interface to a generic -// synchronous instrument (e.g., ValueRecorder and Counter instruments). -type SyncImpl interface { - InstrumentImpl - - // Bind creates an implementation-level bound instrument, - // binding a label set with this instrument implementation. - Bind(labels []label.KeyValue) BoundSyncImpl - - // RecordOne captures a single synchronous metric event. - RecordOne(ctx context.Context, number Number, labels []label.KeyValue) -} - -// BoundSyncImpl is the implementation-level interface to a -// generic bound synchronous instrument -type BoundSyncImpl interface { - - // RecordOne captures a single synchronous metric event. - RecordOne(ctx context.Context, number Number) - - // Unbind frees the resources associated with this bound instrument. It - // does not affect the metric this bound instrument was created through. - Unbind() -} - -// AsyncImpl is an implementation-level interface to an -// asynchronous instrument (e.g., Observer instruments). -type AsyncImpl interface { - InstrumentImpl -} - -// WrapMeterImpl constructs a `Meter` implementation from a -// `MeterImpl` implementation. -func WrapMeterImpl(impl MeterImpl, instrumentatioName string, opts ...MeterOption) Meter { - return Meter{ - impl: impl, - name: instrumentatioName, - version: ConfigureMeter(opts).InstrumentationVersion, - } -} 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/doc.go b/vendor/go.opentelemetry.io/otel/api/propagation/doc.go deleted file mode 100644 index d2839f5be..000000000 --- a/vendor/go.opentelemetry.io/otel/api/propagation/doc.go +++ /dev/null @@ -1,16 +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 contains interface definition for HTTP propagators. -package propagation // import "go.opentelemetry.io/otel/api/propagation" 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/noop_trace.go b/vendor/go.opentelemetry.io/otel/api/trace/noop_trace.go deleted file mode 100644 index ffdb91318..000000000 --- a/vendor/go.opentelemetry.io/otel/api/trace/noop_trace.go +++ /dev/null @@ -1,29 +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 NoopTracer struct{} - -var _ Tracer = NoopTracer{} - -// 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 -} diff --git a/vendor/go.opentelemetry.io/otel/api/trace/noop_trace_provider.go b/vendor/go.opentelemetry.io/otel/api/trace/noop_trace_provider.go deleted file mode 100644 index 6a5f1a285..000000000 --- a/vendor/go.opentelemetry.io/otel/api/trace/noop_trace_provider.go +++ /dev/null @@ -1,24 +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 - -type NoopProvider struct{} - -var _ Provider = NoopProvider{} - -// Tracer returns noop implementation of Tracer. -func (p NoopProvider) Tracer(_ string, _ ...TracerOption) Tracer { - return NoopTracer{} -} 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/unit/doc.go b/vendor/go.opentelemetry.io/otel/api/unit/doc.go deleted file mode 100644 index f03ed5595..000000000 --- a/vendor/go.opentelemetry.io/otel/api/unit/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 unit // import "go.opentelemetry.io/otel/api/unit" diff --git a/vendor/go.opentelemetry.io/otel/api/unit/unit.go b/vendor/go.opentelemetry.io/otel/api/unit/unit.go deleted file mode 100644 index dcd39af02..000000000 --- a/vendor/go.opentelemetry.io/otel/api/unit/unit.go +++ /dev/null @@ -1,23 +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 unit - -type Unit string - -const ( - Dimensionless Unit = "1" - Bytes Unit = "By" - Milliseconds Unit = "ms" -) diff --git a/vendor/go.opentelemetry.io/otel/codes/codes.go b/vendor/go.opentelemetry.io/otel/codes/codes.go deleted file mode 100644 index 7d4aaee22..000000000 --- a/vendor/go.opentelemetry.io/otel/codes/codes.go +++ /dev/null @@ -1,89 +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 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 - -// Code is an 32-bit representation of a status state. -type Code uint32 - -// 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 -) diff --git a/vendor/go.opentelemetry.io/otel/doc.go b/vendor/go.opentelemetry.io/otel/doc.go deleted file mode 100644 index af2e5e4d3..000000000 --- a/vendor/go.opentelemetry.io/otel/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 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 deleted file mode 100644 index 3c5604917..000000000 --- a/vendor/go.opentelemetry.io/otel/error_handler.go +++ /dev/null @@ -1,22 +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 otel - -// ErrorHandler handles irremediable events. -type ErrorHandler interface { - // Handle handles any error deemed irremediable by an OpenTelemetry - // component. - Handle(error) -} diff --git a/vendor/go.opentelemetry.io/otel/get_main_pkgs.sh b/vendor/go.opentelemetry.io/otel/get_main_pkgs.sh deleted file mode 100644 index d1c892f0e..000000000 --- a/vendor/go.opentelemetry.io/otel/get_main_pkgs.sh +++ /dev/null @@ -1,36 +0,0 @@ -#!/usr/bin/env bash - -# 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. - -set -euo pipefail - -top_dir='.' -if [[ $# -gt 0 ]]; then - top_dir="${1}" -fi - -p=$(pwd) -mod_dirs=() -mapfile -t mod_dirs < <(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 - cd "${p}" -done diff --git a/vendor/go.opentelemetry.io/otel/go.mod b/vendor/go.opentelemetry.io/otel/go.mod deleted file mode 100644 index dc10203c6..000000000 --- a/vendor/go.opentelemetry.io/otel/go.mod +++ /dev/null @@ -1,8 +0,0 @@ -module go.opentelemetry.io/otel - -go 1.14 - -require ( - github.com/google/go-cmp v0.5.1 - github.com/stretchr/testify v1.6.1 -) diff --git a/vendor/go.opentelemetry.io/otel/go.sum b/vendor/go.opentelemetry.io/otel/go.sum deleted file mode 100644 index 741ca4ea2..000000000 --- a/vendor/go.opentelemetry.io/otel/go.sum +++ /dev/null @@ -1,15 +0,0 @@ -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/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= -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/internal/rawhelpers.go b/vendor/go.opentelemetry.io/otel/internal/rawhelpers.go deleted file mode 100644 index dae825ed8..000000000 --- a/vendor/go.opentelemetry.io/otel/internal/rawhelpers.go +++ /dev/null @@ -1,91 +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 internal - -import ( - "math" - "unsafe" -) - -func BoolToRaw(b bool) uint64 { - if b { - return 1 - } - return 0 -} - -func RawToBool(r uint64) bool { - return r != 0 -} - -func Int64ToRaw(i int64) uint64 { - return uint64(i) -} - -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) -} - -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)) -} - -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/label/doc.go b/vendor/go.opentelemetry.io/otel/label/doc.go deleted file mode 100644 index d631d2387..000000000 --- a/vendor/go.opentelemetry.io/otel/label/doc.go +++ /dev/null @@ -1,16 +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 label provides key and value labels. -package label // import "go.opentelemetry.io/otel/label" diff --git a/vendor/go.opentelemetry.io/otel/label/encoder.go b/vendor/go.opentelemetry.io/otel/label/encoder.go deleted file mode 100644 index 17e6d2dfb..000000000 --- a/vendor/go.opentelemetry.io/otel/label/encoder.go +++ /dev/null @@ -1,150 +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 label - -import ( - "bytes" - "sync" - "sync/atomic" -) - -type ( - // Encoder is a mechanism for serializing a label set into a - // specific string representation that supports caching, to - // avoid repeated serialization. An example could be an - // exporter encoding the label set into a wire representation. - 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 - - // ID returns a value that is unique for each class of - // label encoder. Label encoders allocate these using - // `NewEncoderID`. - ID() EncoderID - } - - // EncoderID is used to identify distinct Encoder - // implementations, for caching encoded results. - EncoderID struct { - value uint64 - } - - // defaultLabelEncoder uses a sync.Pool of buffers to reduce - // the number of allocations used in encoding labels. This - // implementation encodes a comma-separated list of key=value, - // with '/'-escaping of '=', ',', and '\'. - defaultLabelEncoder struct { - // pool is a pool of labelset builders. The buffers in this - // pool grow to a size that most label encodings will not - // allocate new memory. - pool sync.Pool // *bytes.Buffer - } -) - -// escapeChar is used to ensure uniqueness of the label encoding where -// keys or values contain either '=' or ','. Since there is no parser -// needed for this encoding and its only requirement is to be unique, -// this choice is arbitrary. Users will see these in some exporters -// (e.g., stdout), so the backslash ('\') is used as a conventional choice. -const escapeChar = '\\' - -var ( - _ Encoder = &defaultLabelEncoder{} - - // encoderIDCounter is for generating IDs for other label - // encoders. - encoderIDCounter uint64 - - defaultEncoderOnce sync.Once - defaultEncoderID = NewEncoderID() - defaultEncoderInstance *defaultLabelEncoder -) - -// NewEncoderID returns a unique label encoder ID. It should be -// called once per each type of label encoder. Preferably in init() or -// in var definition. -func NewEncoderID() EncoderID { - return EncoderID{value: atomic.AddUint64(&encoderIDCounter, 1)} -} - -// DefaultEncoder returns a label encoder that encodes labels -// in such a way that each escaped label's key is followed by an equal -// sign and then by an escaped label's value. All key-value pairs are -// separated by a comma. -// -// Escaping is done by prepending a backslash before either a -// backslash, equal sign or a comma. -func DefaultEncoder() Encoder { - defaultEncoderOnce.Do(func() { - defaultEncoderInstance = &defaultLabelEncoder{ - pool: sync.Pool{ - New: func() interface{} { - return &bytes.Buffer{} - }, - }, - } - }) - return defaultEncoderInstance -} - -// Encode is a part of an implementation of the LabelEncoder -// interface. -func (d *defaultLabelEncoder) Encode(iter Iterator) string { - buf := d.pool.Get().(*bytes.Buffer) - defer d.pool.Put(buf) - buf.Reset() - - for iter.Next() { - i, keyValue := iter.IndexedLabel() - if i > 0 { - _, _ = buf.WriteRune(',') - } - copyAndEscape(buf, string(keyValue.Key)) - - _, _ = buf.WriteRune('=') - - if keyValue.Value.Type() == STRING { - copyAndEscape(buf, keyValue.Value.AsString()) - } else { - _, _ = buf.WriteString(keyValue.Value.Emit()) - } - } - return buf.String() -} - -// ID is a part of an implementation of the LabelEncoder interface. -func (*defaultLabelEncoder) ID() EncoderID { - return defaultEncoderID -} - -// copyAndEscape escapes `=`, `,` and its own escape character (`\`), -// making the default encoding unique. -func copyAndEscape(buf *bytes.Buffer, val string) { - for _, ch := range val { - switch ch { - case '=', ',', escapeChar: - buf.WriteRune(escapeChar) - } - buf.WriteRune(ch) - } -} - -// Valid returns true if this encoder ID was allocated by -// `NewEncoderID`. Invalid encoder IDs will not be cached. -func (id EncoderID) Valid() bool { - return id.value != 0 -} diff --git a/vendor/go.opentelemetry.io/otel/label/iterator.go b/vendor/go.opentelemetry.io/otel/label/iterator.go deleted file mode 100644 index 9e7223998..000000000 --- a/vendor/go.opentelemetry.io/otel/label/iterator.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 label - -// Iterator allows iterating over the set of labels in order, -// sorted by key. -type Iterator struct { - storage *Set - idx int -} - -// 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 { - one oneIterator - two oneIterator - current KeyValue -} - -type oneIterator struct { - iter Iterator - done bool - label KeyValue -} - -// Next moves the iterator to the next position. Returns false if there -// are no more labels. -func (i *Iterator) Next() bool { - i.idx++ - return i.idx < i.Len() -} - -// Label returns current KeyValue. Must be called only after Next returns -// true. -func (i *Iterator) Label() KeyValue { - kv, _ := i.storage.Get(i.idx) - return kv -} - -// Attribute is a synonym for Label(). -func (i *Iterator) Attribute() KeyValue { - return i.Label() -} - -// IndexedLabel returns current index and label. Must be called only -// after Next returns true. -func (i *Iterator) IndexedLabel() (int, KeyValue) { - return i.idx, i.Label() -} - -// Len returns a number of labels in the iterator's `*Set`. -func (i *Iterator) Len() int { - return i.storage.Len() -} - -// ToSlice is a convenience function that creates a slice of labels -// from the passed iterator. The iterator is set up to start from the -// beginning before creating the slice. -func (i *Iterator) ToSlice() []KeyValue { - l := i.Len() - if l == 0 { - return nil - } - i.idx = -1 - slice := make([]KeyValue, 0, l) - for i.Next() { - slice = append(slice, i.Label()) - } - return slice -} - -// 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{ - one: makeOne(s1.Iter()), - two: makeOne(s2.Iter()), - } - return mi -} - -func makeOne(iter Iterator) oneIterator { - oi := oneIterator{ - iter: iter, - } - oi.advance() - return oi -} - -func (oi *oneIterator) advance() { - if oi.done = !oi.iter.Next(); !oi.done { - oi.label = oi.iter.Label() - } -} - -// Next returns true if there is another label available. -func (m *MergeItererator) Next() bool { - if m.one.done && m.two.done { - return false - } - if m.one.done { - m.current = m.two.label - m.two.advance() - return true - } - if m.two.done { - m.current = m.one.label - m.one.advance() - return true - } - if m.one.label.Key == m.two.label.Key { - m.current = m.one.label // first iterator label value wins - m.one.advance() - m.two.advance() - return true - } - if m.one.label.Key < m.two.label.Key { - m.current = m.one.label - m.one.advance() - return true - } - m.current = m.two.label - m.two.advance() - return true -} - -// Label returns the current value after Next() returns true. -func (m *MergeItererator) Label() KeyValue { - return m.current -} diff --git a/vendor/go.opentelemetry.io/otel/label/key.go b/vendor/go.opentelemetry.io/otel/label/key.go deleted file mode 100644 index 7d7237809..000000000 --- a/vendor/go.opentelemetry.io/otel/label/key.go +++ /dev/null @@ -1,169 +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 label - -// 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. -type Key string - -// Bool creates a KeyValue instance with a BOOL Value. -// -// If creating both key and a bool value at the same time, then -// instead of calling Key(name).Bool(value) consider using a -// convenience function provided by the api/key package - -// key.Bool(name, value). -func (k Key) Bool(v bool) KeyValue { - return KeyValue{ - Key: k, - Value: BoolValue(v), - } -} - -// Int64 creates a KeyValue instance with an INT64 Value. -// -// If creating both key and an int64 value at the same time, then -// instead of calling Key(name).Int64(value) consider using a -// convenience function provided by the api/key package - -// key.Int64(name, value). -func (k Key) Int64(v int64) KeyValue { - return KeyValue{ - Key: k, - Value: Int64Value(v), - } -} - -// 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 -// instead of calling Key(name).Float64(value) consider using a -// convenience function provided by the api/key package - -// key.Float64(name, value). -func (k Key) Float64(v float64) KeyValue { - return KeyValue{ - Key: k, - Value: Float64Value(v), - } -} - -// 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 -// instead of calling Key(name).String(value) consider using a -// convenience function provided by the api/key package - -// key.String(name, value). -func (k Key) String(v string) KeyValue { - return KeyValue{ - Key: k, - Value: StringValue(v), - } -} - -// 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. -// -// If creating both key and an int value at the same time, then -// instead of calling Key(name).Int(value) consider using a -// convenience function provided by the api/key package - -// key.Int(name, value). -func (k Key) Int(v int) KeyValue { - return KeyValue{ - Key: k, - Value: IntValue(v), - } -} - -// 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 -} - -// Array creates a KeyValue instance with a ARRAY Value. -// -// If creating both key and a array value at the same time, then -// instead of calling Key(name).String(value) consider using a -// convenience function provided by the api/key package - -// key.Array(name, value). -func (k Key) Array(v interface{}) KeyValue { - return KeyValue{ - Key: k, - Value: ArrayValue(v), - } -} diff --git a/vendor/go.opentelemetry.io/otel/label/kv.go b/vendor/go.opentelemetry.io/otel/label/kv.go deleted file mode 100644 index 3e2764f47..000000000 --- a/vendor/go.opentelemetry.io/otel/label/kv.go +++ /dev/null @@ -1,144 +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 label - -import ( - "encoding/json" - "fmt" - "reflect" -) - -// KeyValue holds a key and value pair. -type KeyValue struct { - Key Key - Value Value -} - -// Bool creates a new key-value pair with a passed name and a bool -// value. -func Bool(k string, v bool) KeyValue { - return Key(k).Bool(v) -} - -// Int64 creates a new key-value pair with a passed name and an int64 -// value. -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 { - return Key(k).String(v) -} - -// Stringer creates a new key-value pair with a passed name and a string -// value generated by the passed Stringer interface. -func Stringer(k string, v fmt.Stringer) KeyValue { - return Key(k).String(v.String()) -} - -// Int creates a new key-value pair instance with a passed name and -// either an int32 or an int64 value, depending on whether the int -// type is 32 or 64 bits wide. -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 { - return Key(k).Array(v) -} - -// Any creates a new key-value pair instance with a passed name and -// automatic type inference. This is slower, and not type-safe. -func Any(k string, value interface{}) KeyValue { - if value == nil { - return String(k, "") - } - - if stringer, ok := value.(fmt.Stringer); ok { - return String(k, stringer.String()) - } - - rv := reflect.ValueOf(value) - - switch rv.Kind() { - case reflect.Array, reflect.Slice: - return Array(k, value) - case reflect.Bool: - 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())) - 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 { - 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/label/set.go deleted file mode 100644 index 3bd5263cb..000000000 --- a/vendor/go.opentelemetry.io/otel/label/set.go +++ /dev/null @@ -1,468 +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 label - -import ( - "encoding/json" - "reflect" - "sort" - "sync" -) - -type ( - // Set is the representation for a distinct label set. It - // manages an immutable set of labels, with an internal cache - // for storing label encodings. - // - // This type supports the `Equivalent` method of comparison - // using values of type `Distinct`. - // - // This type is used to implement: - // 1. Metric labels - // 2. Resource sets - // 3. Correlation map (TODO) - Set struct { - equivalent Distinct - - lock sync.Mutex - encoders [maxConcurrentEncoders]EncoderID - encoded [maxConcurrentEncoders]string - } - - // Distinct wraps a variable-size array of `KeyValue`, - // constructed with keys in sorted order. This can be used as - // a map key or for equality checking between Sets. - Distinct struct { - iface interface{} - } - - // Filter supports removing certain labels from label sets. - // When the filter returns true, the label will be kept in - // the filtered label set. When the filter returns false, the - // label is excluded from the filtered label set, and the - // label instead appears in the `removed` list of excluded labels. - Filter func(KeyValue) bool - - // Sortable implements `sort.Interface`, used for sorting - // `KeyValue`. This is an exported type to support a - // memory optimization. A pointer to one of these is needed - // for the call to `sort.Stable()`, which the caller may - // provide in order to avoid an allocation. See - // `NewSetWithSortable()`. - Sortable []KeyValue -) - -var ( - // keyValueType is used in `computeDistinctReflect`. - keyValueType = reflect.TypeOf(KeyValue{}) - - // emptySet is returned for empty label sets. - emptySet = &Set{ - equivalent: Distinct{ - iface: [0]KeyValue{}, - }, - } -) - -const maxConcurrentEncoders = 3 - -func EmptySet() *Set { - return emptySet -} - -// reflect abbreviates `reflect.ValueOf`. -func (d Distinct) reflect() reflect.Value { - return reflect.ValueOf(d.iface) -} - -// Valid returns true if this value refers to a valid `*Set`. -func (d Distinct) Valid() bool { - return d.iface != nil -} - -// Len returns the number of labels in this set. -func (l *Set) Len() int { - if l == nil || !l.equivalent.Valid() { - return 0 - } - return l.equivalent.reflect().Len() -} - -// Get returns the KeyValue at ordered position `idx` in this set. -func (l *Set) Get(idx int) (KeyValue, bool) { - if l == nil { - return KeyValue{}, false - } - value := l.equivalent.reflect() - - if idx >= 0 && idx < value.Len() { - // Note: The Go compiler successfully avoids an allocation for - // the interface{} conversion here: - return value.Index(idx).Interface().(KeyValue), true - } - - return KeyValue{}, false -} - -// Value returns the value of a specified key in this set. -func (l *Set) Value(k Key) (Value, bool) { - if l == nil { - return Value{}, false - } - rValue := l.equivalent.reflect() - vlen := rValue.Len() - - idx := sort.Search(vlen, func(idx int) bool { - return rValue.Index(idx).Interface().(KeyValue).Key >= k - }) - if idx >= vlen { - return Value{}, false - } - keyValue := rValue.Index(idx).Interface().(KeyValue) - if k == keyValue.Key { - return keyValue.Value, true - } - return Value{}, false -} - -// HasValue tests whether a key is defined in this set. -func (l *Set) HasValue(k Key) bool { - if l == nil { - return false - } - _, ok := l.Value(k) - return ok -} - -// Iter returns an iterator for visiting the labels in this set. -func (l *Set) Iter() Iterator { - return Iterator{ - storage: l, - idx: -1, - } -} - -// ToSlice returns the set of labels belonging to this set, sorted, -// where keys appear no more than once. -func (l *Set) ToSlice() []KeyValue { - iter := l.Iter() - return iter.ToSlice() -} - -// Equivalent returns a value that may be used as a map key. The -// Distinct type guarantees that the result will equal the equivalent -// Distinct value of any label set with the same elements as this, -// where sets are made unique by choosing the last value in the input -// for any given key. -func (l *Set) Equivalent() Distinct { - if l == nil || !l.equivalent.Valid() { - return emptySet.equivalent - } - return l.equivalent -} - -// Equals returns true if the argument set is equivalent to this set. -func (l *Set) Equals(o *Set) bool { - return l.Equivalent() == o.Equivalent() -} - -// Encoded returns the encoded form of this set, according to -// `encoder`. The result will be cached in this `*Set`. -func (l *Set) Encoded(encoder Encoder) string { - if l == nil || encoder == nil { - return "" - } - - id := encoder.ID() - if !id.Valid() { - // Invalid IDs are not cached. - return encoder.Encode(l.Iter()) - } - - var lookup *string - l.lock.Lock() - for idx := 0; idx < maxConcurrentEncoders; idx++ { - if l.encoders[idx] == id { - lookup = &l.encoded[idx] - break - } - } - l.lock.Unlock() - - if lookup != nil { - return *lookup - } - - r := encoder.Encode(l.Iter()) - - l.lock.Lock() - defer l.lock.Unlock() - - for idx := 0; idx < maxConcurrentEncoders; idx++ { - if l.encoders[idx] == id { - return l.encoded[idx] - } - if !l.encoders[idx].Valid() { - l.encoders[idx] = id - l.encoded[idx] = r - return r - } - } - - // TODO: This is a performance cliff. Find a way for this to - // generate a warning. - return r -} - -func empty() Set { - return Set{ - equivalent: emptySet.equivalent, - } -} - -// NewSet returns a new `Set`. See the documentation for -// `NewSetWithSortableFiltered` for more details. -// -// Except for empty sets, this method adds an additional allocation -// compared with calls that include a `*Sortable`. -func NewSet(kvs ...KeyValue) Set { - // Check for empty set. - if len(kvs) == 0 { - return empty() - } - s, _ := NewSetWithSortableFiltered(kvs, new(Sortable), nil) - return s //nolint -} - -// NewSetWithSortable returns a new `Set`. See the documentation for -// `NewSetWithSortableFiltered` for more details. -// -// This call includes a `*Sortable` option as a memory optimization. -func NewSetWithSortable(kvs []KeyValue, tmp *Sortable) Set { - // Check for empty set. - if len(kvs) == 0 { - return empty() - } - s, _ := NewSetWithSortableFiltered(kvs, tmp, nil) - return s //nolint -} - -// NewSetWithFiltered returns a new `Set`. See the documentation for -// `NewSetWithSortableFiltered` for more details. -// -// This call includes a `Filter` to include/exclude label keys from -// the return value. Excluded keys are returned as a slice of label -// values. -func NewSetWithFiltered(kvs []KeyValue, filter Filter) (Set, []KeyValue) { - // Check for empty set. - if len(kvs) == 0 { - return empty(), nil - } - return NewSetWithSortableFiltered(kvs, new(Sortable), filter) -} - -// NewSetWithSortableFiltered returns a new `Set`. -// -// Duplicate keys are eliminated by taking the last value. This -// re-orders the input slice so that unique last-values are contiguous -// at the end of the slice. -// -// This ensures the following: -// -// - Last-value-wins semantics -// - Caller sees the reordering, but doesn't lose values -// - Repeated call preserve last-value wins. -// -// Note that methods are defined on `*Set`, although this returns `Set`. -// Callers can avoid memory allocations by: -// -// - allocating a `Sortable` for use as a temporary in this method -// - allocating a `Set` for storing the return value of this -// constructor. -// -// The result maintains a cache of encoded labels, by label.EncoderID. -// This value should not be copied after its first use. -// -// The second `[]KeyValue` return value is a list of labels that were -// excluded by the Filter (if non-nil). -func NewSetWithSortableFiltered(kvs []KeyValue, tmp *Sortable, filter Filter) (Set, []KeyValue) { - // Check for empty set. - if len(kvs) == 0 { - return empty(), nil - } - - *tmp = kvs - - // Stable sort so the following de-duplication can implement - // last-value-wins semantics. - sort.Stable(tmp) - - *tmp = nil - - position := len(kvs) - 1 - offset := position - 1 - - // The requirements stated above require that the stable - // result be placed in the end of the input slice, while - // overwritten values are swapped to the beginning. - // - // De-duplicate with last-value-wins semantics. Preserve - // duplicate values at the beginning of the input slice. - for ; offset >= 0; offset-- { - if kvs[offset].Key == kvs[position].Key { - continue - } - position-- - kvs[offset], kvs[position] = kvs[position], kvs[offset] - } - if filter != nil { - return filterSet(kvs[position:], filter) - } - return Set{ - equivalent: computeDistinct(kvs[position:]), - }, nil -} - -// filterSet reorders `kvs` so that included keys are contiguous at -// the end of the slice, while excluded keys precede the included keys. -func filterSet(kvs []KeyValue, filter Filter) (Set, []KeyValue) { - var excluded []KeyValue - - // Move labels that do not match the filter so - // they're adjacent before calling computeDistinct(). - distinctPosition := len(kvs) - - // Swap indistinct keys forward and distinct keys toward the - // end of the slice. - offset := len(kvs) - 1 - for ; offset >= 0; offset-- { - if filter(kvs[offset]) { - distinctPosition-- - kvs[offset], kvs[distinctPosition] = kvs[distinctPosition], kvs[offset] - continue - } - } - excluded = kvs[:distinctPosition] - - return Set{ - equivalent: computeDistinct(kvs[distinctPosition:]), - }, excluded -} - -// Filter returns a filtered copy of this `Set`. See the -// documentation for `NewSetWithSortableFiltered` for more details. -func (l *Set) Filter(re Filter) (Set, []KeyValue) { - if re == nil { - return Set{ - equivalent: l.equivalent, - }, nil - } - - // Note: This could be refactored to avoid the temporary slice - // allocation, if it proves to be expensive. - return filterSet(l.ToSlice(), re) -} - -// computeDistinct returns a `Distinct` using either the fixed- or -// reflect-oriented code path, depending on the size of the input. -// The input slice is assumed to already be sorted and de-duplicated. -func computeDistinct(kvs []KeyValue) Distinct { - iface := computeDistinctFixed(kvs) - if iface == nil { - iface = computeDistinctReflect(kvs) - } - return Distinct{ - iface: iface, - } -} - -// computeDistinctFixed computes a `Distinct` for small slices. It -// returns nil if the input is too large for this code path. -func computeDistinctFixed(kvs []KeyValue) interface{} { - switch len(kvs) { - case 1: - ptr := new([1]KeyValue) - copy((*ptr)[:], kvs) - return *ptr - case 2: - ptr := new([2]KeyValue) - copy((*ptr)[:], kvs) - return *ptr - case 3: - ptr := new([3]KeyValue) - copy((*ptr)[:], kvs) - return *ptr - case 4: - ptr := new([4]KeyValue) - copy((*ptr)[:], kvs) - return *ptr - case 5: - ptr := new([5]KeyValue) - copy((*ptr)[:], kvs) - return *ptr - case 6: - ptr := new([6]KeyValue) - copy((*ptr)[:], kvs) - return *ptr - case 7: - ptr := new([7]KeyValue) - copy((*ptr)[:], kvs) - return *ptr - case 8: - ptr := new([8]KeyValue) - copy((*ptr)[:], kvs) - return *ptr - case 9: - ptr := new([9]KeyValue) - copy((*ptr)[:], kvs) - return *ptr - case 10: - ptr := new([10]KeyValue) - copy((*ptr)[:], kvs) - return *ptr - default: - return nil - } -} - -// computeDistinctReflect computes a `Distinct` using reflection, -// works for any size input. -func computeDistinctReflect(kvs []KeyValue) interface{} { - at := reflect.New(reflect.ArrayOf(len(kvs), keyValueType)).Elem() - for i, keyValue := range kvs { - *(at.Index(i).Addr().Interface().(*KeyValue)) = keyValue - } - return at.Interface() -} - -// MarshalJSON returns the JSON encoding of the `*Set`. -func (l *Set) MarshalJSON() ([]byte, error) { - return json.Marshal(l.equivalent.iface) -} - -// Len implements `sort.Interface`. -func (l *Sortable) Len() int { - return len(*l) -} - -// Swap implements `sort.Interface`. -func (l *Sortable) Swap(i, j int) { - (*l)[i], (*l)[j] = (*l)[j], (*l)[i] -} - -// Less implements `sort.Interface`. -func (l *Sortable) Less(i, j int) bool { - return (*l)[i].Key < (*l)[j].Key -} diff --git a/vendor/go.opentelemetry.io/otel/label/type_string.go b/vendor/go.opentelemetry.io/otel/label/type_string.go deleted file mode 100644 index 62afeb60a..000000000 --- a/vendor/go.opentelemetry.io/otel/label/type_string.go +++ /dev/null @@ -1,32 +0,0 @@ -// Code generated by "stringer -type=Type"; DO NOT EDIT. - -package label - -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[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] -} - -const _Type_name = "INVALIDBOOLINT32INT64UINT32UINT64FLOAT32FLOAT64STRINGARRAY" - -var _Type_index = [...]uint8{0, 7, 11, 16, 21, 27, 33, 40, 47, 53, 58} - -func (i Type) String() string { - if i < 0 || i >= Type(len(_Type_index)-1) { - return "Type(" + strconv.FormatInt(int64(i), 10) + ")" - } - return _Type_name[_Type_index[i]:_Type_index[i+1]] -} diff --git a/vendor/go.opentelemetry.io/otel/label/value.go b/vendor/go.opentelemetry.io/otel/label/value.go deleted file mode 100644 index 633979f1b..000000000 --- a/vendor/go.opentelemetry.io/otel/label/value.go +++ /dev/null @@ -1,284 +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 label - -import ( - "encoding/json" - "fmt" - "reflect" - "strconv" - "strings" - "unsafe" - - "go.opentelemetry.io/otel/internal" -) - -//go:generate stringer -type=Type - -// Type describes the type of the data Value holds. -type Type int - -// Value represents the value part in key-value pairs. -type Value struct { - vtype Type - numeric uint64 - stringly string - // TODO Lazy value type? - - array interface{} -} - -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. -) - -// BoolValue creates a BOOL Value. -func BoolValue(v bool) Value { - return Value{ - vtype: BOOL, - numeric: internal.BoolToRaw(v), - } -} - -// Int64Value creates an INT64 Value. -func Int64Value(v int64) Value { - return Value{ - vtype: INT64, - numeric: internal.Int64ToRaw(v), - } -} - -// 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{ - vtype: FLOAT64, - numeric: internal.Float64ToRaw(v), - } -} - -// 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. -func StringValue(v string) Value { - return Value{ - vtype: STRING, - stringly: v, - } -} - -// Int creates either an INT32 or an INT64 Value, depending on whether -// the int type is 32 or 64 bits wide. -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() { - 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 { - return Value{ - vtype: ARRAY, - array: array, - } - } - } - return Value{vtype: INVALID} -} - -// Type returns a type of the Value. -func (v Value) Type() Type { - return v.vtype -} - -// AsBool returns the bool value. Make sure that the Value's type is -// BOOL. -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 { - return internal.RawToFloat64(v.numeric) -} - -// AsString returns the string value. Make sure that the Value's type -// is STRING. -func (v Value) AsString() string { - return v.stringly -} - -// AsArray returns the array Value as an interface{}. -func (v Value) AsArray() interface{} { - return v.array -} - -type unknownValueType struct{} - -// AsInterface returns Value's data as interface{}. -func (v Value) AsInterface() interface{} { - switch v.Type() { - case ARRAY: - 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: - return v.stringly - } - return unknownValueType{} -} - -// Emit returns a string representation of Value's data. -func (v Value) Emit() string { - switch v.Type() { - case ARRAY: - 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: - return v.stringly - default: - return "unknown" - } -} - -// MarshalJSON returns the JSON encoding of the Value. -func (v Value) MarshalJSON() ([]byte, error) { - var jsonVal struct { - Type string - Value interface{} - } - jsonVal.Type = v.Type().String() - jsonVal.Value = v.AsInterface() - return json.Marshal(jsonVal) -} diff --git a/vendor/go.opentelemetry.io/otel/otel.go b/vendor/go.opentelemetry.io/otel/otel.go deleted file mode 100644 index 7d1c424bf..000000000 --- a/vendor/go.opentelemetry.io/otel/otel.go +++ /dev/null @@ -1,27 +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 otel - -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 diff --git a/vendor/go.opentelemetry.io/otel/pre_release.sh b/vendor/go.opentelemetry.io/otel/pre_release.sh deleted file mode 100644 index e09924b77..000000000 --- a/vendor/go.opentelemetry.io/otel/pre_release.sh +++ /dev/null @@ -1,95 +0,0 @@ -#!/bin/bash - -# 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. - -set -e - -help() -{ - printf "\n" - printf "Usage: $0 -t tag\n" - printf "\t-t Unreleased tag. Update all go.mod with this tag.\n" - exit 1 # Exit script after printing help -} - -while getopts "t:" opt -do - case "$opt" in - t ) TAG="$OPTARG" ;; - ? ) help ;; # Print help - esac -done - -# Print help in case parameters are empty -if [ -z "$TAG" ] -then - printf "Tag is missing\n"; - help -fi - -# Validate semver -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-]+)*)?$" -if [[ "${TAG}" =~ ${SEMVER_REGEX} ]]; then - printf "${TAG} is valid semver tag.\n" -else - printf "${TAG} is not a valid semver tag.\n" - exit -1 -fi - -TAG_FOUND=`git tag --list ${TAG}` -if [[ ${TAG_FOUND} = ${TAG} ]] ; then - printf "Tag ${TAG} already exists\n" - exit -1 -fi - -# Get version for sdk/opentelemetry.go -OTEL_VERSION=$(echo "${TAG}" | grep -o '^v[0-9]\+\.[0-9]\+\.[0-9]\+') -# Strip leading v -OTEL_VERSION="${OTEL_VERSION#v}" - -cd $(dirname $0) - -if ! git diff --quiet; then \ - printf "Working tree is not clean, can't proceed with the release process\n" - git status - git diff - 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 go.mod -git checkout -b pre_release_${TAG} master -PACKAGE_DIRS=$(find . -mindepth 2 -type f -name 'go.mod' -exec dirname {} \; | egrep -v 'tools' | sed 's/^\.\///' | sort) - -for dir in $PACKAGE_DIRS; do - cp "${dir}/go.mod" "${dir}/go.mod.bak" - sed "s/opentelemetry.io\/otel\([^ ]*\) v[0-9]*\.[0-9]*\.[0-9]/opentelemetry.io\/otel\1 ${TAG}/" "${dir}/go.mod.bak" >"${dir}/go.mod" - rm -f "${dir}/go.mod.bak" -done - -# Run lint to update go.sum -make lint - -# Add changes and commit. -git add . -make ci -git commit -m "Prepare for releasing $TAG" - -printf "Now run following to verify the changes.\ngit diff master\n" -printf "\nThen push the changes to upstream\n" diff --git a/vendor/go.opentelemetry.io/otel/tag.sh b/vendor/go.opentelemetry.io/otel/tag.sh deleted file mode 100644 index 2a0ef1d26..000000000 --- a/vendor/go.opentelemetry.io/otel/tag.sh +++ /dev/null @@ -1,178 +0,0 @@ -#!/usr/bin/env bash - -# 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. - -readonly PROGNAME=$(basename "$0") -readonly PROGDIR=$(readlink -m "$(dirname "$0")") - -readonly EXCLUDE_PACKAGES="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() { - cat <<- EOF -Usage: $PROGNAME [OPTIONS] SEMVER_TAG COMMIT_HASH - -Creates git tag for all Go packages in project. - -OPTIONS: - -h --help Show this help. - -ARGUMENTS: - SEMVER_TAG Semantic version to tag with. - COMMIT_HASH Git commit hash to tag. -EOF -} - -cmdline() { - local arg commit - - for arg - do - local delim="" - case "$arg" in - # Translate long form options to short form. - --help) args="${args}-h ";; - # Pass through for everything else. - *) [[ "${arg:0:1}" == "-" ]] || delim="\"" - args="${args}${delim}${arg}${delim} ";; - esac - done - - # Reset and process short form options. - eval set -- "$args" - - while getopts "h" OPTION - do - case $OPTION in - h) - usage - exit 0 - ;; - *) - echo "unknown option: $OPTION" - usage - exit 1 - ;; - esac - done - - # Positional arguments. - shift $((OPTIND-1)) - readonly TAG="$1" - if [ -z "$TAG" ] - then - echo "missing SEMVER_TAG" - usage - exit 1 - fi - if [[ ! "$TAG" =~ $SEMVER_REGEX ]] - then - printf "invalid semantic version: %s\n" "$TAG" - exit 2 - fi - if [[ "$( git tag --list "$TAG" )" ]] - then - printf "tag already exists: %s\n" "$TAG" - exit 2 - fi - - shift - commit="$1" - if [ -z "$commit" ] - then - echo "missing COMMIT_HASH" - usage - exit 1 - fi - # Verify rev is for a commit and unify hashes into a complete SHA1. - readonly SHA="$( git rev-parse --quiet --verify "${commit}^{commit}" )" - if [ -z "$SHA" ] - then - printf "invalid commit hash: %s\n" "$commit" - exit 2 - fi - if [ "$( git merge-base "$SHA" HEAD )" != "$SHA" ] - then - printf "commit '%s' not found on this branch\n" "$commit" - exit 2 - fi -} - -package_dirs() { - # Return a list of package directories in the form: - # - # package/directory/a - # package/directory/b - # deeper/package/directory/a - # ... - # - # Making sure to exclude any packages in the EXCLUDE_PACKAGES regexp. - find . -mindepth 2 -type f -name 'go.mod' -exec dirname {} \; \ - | grep -E -v "$EXCLUDE_PACKAGES" \ - | sed 's/^\.\///' \ - | sort -} - -git_tag() { - local tag="$1" - local commit="$2" - - git tag -a "$tag" -s -m "Version $tag" "$commit" -} - -previous_version() { - local current="$1" - - # Requires git > 2.0 - git tag -l --sort=v:refname \ - | grep -E "^${SEMVER_REGEX}$" \ - | grep -v "$current" \ - | tail -1 -} - -print_changes() { - local tag="$1" - local previous - - previous="$( previous_version "$tag" )" - if [ -n "$previous" ] - then - printf "\nRaw changes made between %s and %s\n" "$previous" "$tag" - printf "======================================\n" - git --no-pager log --pretty=oneline "${previous}..$tag" - fi -} - -main() { - local dir - - cmdline "$@" - - cd "$PROGDIR" || exit 3 - - # Create tag for root package. - git_tag "$TAG" "$SHA" - printf "created tag: %s\n" "$TAG" - - # Create tag for all sub-packages. - for dir in $( package_dirs ) - do - git_tag "${dir}/$TAG" "$SHA" - printf "created tag: %s\n" "${dir}/$TAG" - done - - print_changes "$TAG" -} -main "$@" diff --git a/vendor/go.opentelemetry.io/otel/verify_examples.sh b/vendor/go.opentelemetry.io/otel/verify_examples.sh deleted file mode 100644 index dbb61a422..000000000 --- a/vendor/go.opentelemetry.io/otel/verify_examples.sh +++ /dev/null @@ -1,85 +0,0 @@ -#!/bin/bash - -# 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. - -set -euo pipefail - -cd $(dirname $0) -TOOLS_DIR=$(pwd)/.tools - -if [ -z "${GOPATH}" ] ; then - printf "GOPATH is not defined.\n" - exit -1 -fi - -if [ ! -d "${GOPATH}" ] ; then - printf "GOPATH ${GOPATH} is invalid \n" - exit -1 -fi - -# Pre-requisites -if ! git diff --quiet; then \ - git status - printf "\n\nError: working tree is not clean\n" - exit -1 -fi - -if [ "$(git tag --contains $(git log -1 --pretty=format:"%H"))" = "" ] ; then - printf "$(git log -1)" - printf "\n\nError: HEAD is not pointing to a tagged version" -fi - -make ${TOOLS_DIR}/gojq - -DIR_TMP="${GOPATH}/src/oteltmp/" -rm -rf $DIR_TMP -mkdir -p $DIR_TMP - -printf "Copy examples to ${DIR_TMP}\n" -cp -a ./example ${DIR_TMP} - -# Update go.mod files -printf "Update go.mod: rename module and remove replace\n" - -PACKAGE_DIRS=$(find . -mindepth 2 -type f -name 'go.mod' -exec dirname {} \; | egrep 'example' | sed 's/^\.\///' | sort) - -for dir in $PACKAGE_DIRS; do - printf " Update go.mod for $dir\n" - (cd "${DIR_TMP}/${dir}" && \ - # replaces is ("mod1" "mod2" …) - replaces=($(go mod edit -json | ${TOOLS_DIR}/gojq '.Replace[].Old.Path')) && \ - # strip double quotes - replaces=("${replaces[@]%\"}") && \ - replaces=("${replaces[@]#\"}") && \ - # make an array (-dropreplace=mod1 -dropreplace=mod2 …) - dropreplaces=("${replaces[@]/#/-dropreplace=}") && \ - go mod edit -module "oteltmp/${dir}" "${dropreplaces[@]}" && \ - go mod tidy) -done -printf "Update done:\n\n" - -# Build directories that contain main package. These directories are different than -# directories that contain go.mod files. -printf "Build examples:\n" -EXAMPLES=$(./get_main_pkgs.sh ./example) -for ex in $EXAMPLES; do - printf " Build $ex in ${DIR_TMP}/${ex}\n" - (cd "${DIR_TMP}/${ex}" && \ - go build .) -done - -# Cleanup -printf "Remove copied files.\n" -rm -rf $DIR_TMP 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