diff --git a/.github/workflows/helm-tagged-release-pr.yaml b/.github/workflows/helm-tagged-release-pr.yaml index fb6ed43154977..d237cb6af61bd 100644 --- a/.github/workflows/helm-tagged-release-pr.yaml +++ b/.github/workflows/helm-tagged-release-pr.yaml @@ -33,7 +33,7 @@ jobs: bash .github/workflows/scripts/helm-tagged-release.sh ${RELEASE_VERSION} - name: Create Pull Request - uses: peter-evans/create-pull-request@v5 + uses: peter-evans/create-pull-request@v7 with: token: ${{ steps.get_github_app_token.outputs.token }} title: "chore: release loki helm chart ${{ steps.update.outputs.new_chart_version }}" diff --git a/.github/workflows/helm-weekly-release-pr.yaml b/.github/workflows/helm-weekly-release-pr.yaml index 45f7d6e0288d5..f863baf749993 100644 --- a/.github/workflows/helm-weekly-release-pr.yaml +++ b/.github/workflows/helm-weekly-release-pr.yaml @@ -41,7 +41,7 @@ jobs: bash .github/workflows/scripts/helm-weekly-release.sh -k - name: Create Pull Request - uses: peter-evans/create-pull-request@v5 + uses: peter-evans/create-pull-request@v7 with: token: ${{ steps.get_github_app_token.outputs.token }} title: "chore: release loki helm chart ${{ steps.update-k.outputs.new_chart_version }}" @@ -57,7 +57,7 @@ jobs: bash .github/workflows/scripts/helm-weekly-release.sh - name: Create Pull Request - uses: peter-evans/create-pull-request@v5 + uses: peter-evans/create-pull-request@v7 with: token: ${{ steps.get_github_app_token.outputs.token }} title: "chore: release loki helm chart ${{ steps.update.outputs.new_chart_version }}" diff --git a/.github/workflows/operator.yaml b/.github/workflows/operator.yaml index e751dd0fd7f6c..38b3b61196de3 100644 --- a/.github/workflows/operator.yaml +++ b/.github/workflows/operator.yaml @@ -49,7 +49,7 @@ jobs: id: go - uses: actions/checkout@v4 - name: Lint - uses: golangci/golangci-lint-action@v3 + uses: golangci/golangci-lint-action@v6 with: version: v1.61.0 args: --timeout=5m diff --git a/clients/cmd/promtail/main.go b/clients/cmd/promtail/main.go index 7e00e7ff35db3..0fe973969008c 100644 --- a/clients/cmd/promtail/main.go +++ b/clients/cmd/promtail/main.go @@ -10,7 +10,7 @@ import ( // embed time zone data _ "time/tzdata" - "k8s.io/klog" + "k8s.io/klog/v2" "github.com/go-kit/log/level" "github.com/grafana/dskit/flagext" diff --git a/clients/pkg/promtail/targets/serverutils/config.go b/clients/pkg/promtail/targets/serverutils/config.go index 451a3d0953c76..add94dc8157f4 100644 --- a/clients/pkg/promtail/targets/serverutils/config.go +++ b/clients/pkg/promtail/targets/serverutils/config.go @@ -3,8 +3,8 @@ package serverutils import ( "flag" + "dario.cat/mergo" "github.com/grafana/dskit/server" - "github.com/imdario/mergo" ) // MergeWithDefaults applies server.Config defaults to a given and different server.Config. diff --git a/docs/sources/get-started/labels/structured-metadata.md b/docs/sources/get-started/labels/structured-metadata.md index f1877139fef70..d76d1129471f9 100644 --- a/docs/sources/get-started/labels/structured-metadata.md +++ b/docs/sources/get-started/labels/structured-metadata.md @@ -23,8 +23,10 @@ You should only use structured metadata in the following situations: - If you are ingesting data in OpenTelemetry format, using Grafana Alloy or an OpenTelemetry Collector. Structured metadata was designed to support native ingestion of OpenTelemetry data. - If you have high cardinality metadata that should not be used as a label and does not exist in the log line. Some examples might include `process_id` or `thread_id` or Kubernetes pod names. - -It is an antipattern to extract information that already exists in your log lines and put it into structured metadata. +- If you are using [Explore Logs](https://grafana.com/docs/grafana-cloud/visualizations/simplified-exploration/logs/) to visualize and explore your Loki logs. +- If you are a large-scale customer, who is ingesting more than 75TB of logs a month and are using [Bloom filters](https://grafana.com/docs/loki//operations/bloom-filters/) + +We do not recommend extracting information that already exists in your log lines and putting it into structured metadata. ## Attaching structured metadata to log lines @@ -37,9 +39,10 @@ See the [Promtail: Structured metadata stage](https://grafana.com/docs/loki//send-data/logstash/). {{< admonition type="warning" >}} -Structured metadata size is taken into account while asserting ingestion rate limiting. +Structured metadata size is taken into account while asserting ingestion rate limiting. Along with that, there are separate limits on how much structured metadata can be attached per log line. -``` + +```yaml # Maximum size accepted for structured metadata per log line. # CLI flag: -limits.max-structured-metadata-size [max_structured_metadata_size: | default = 64KB] @@ -48,6 +51,7 @@ Along with that, there are separate limits on how much structured metadata can b # CLI flag: -limits.max-structured-metadata-entries-count [max_structured_metadata_entries_count: | default = 128] ``` + {{< /admonition >}} ## Querying structured metadata diff --git a/docs/sources/query/query_accceleration.md b/docs/sources/query/query_accceleration.md index 9117ecb209f23..a760b9e66faa2 100644 --- a/docs/sources/query/query_accceleration.md +++ b/docs/sources/query/query_accceleration.md @@ -1,5 +1,5 @@ --- -title: Query acceleration (Experimental) +title: Query acceleration menuTitle: Query acceleration description: Provides instructions on how to write LogQL queries to benefit from query acceleration. weight: 900 @@ -8,10 +8,11 @@ keywords: - query acceleration --- -# Query acceleration (Experimental) +# Query acceleration {{< admonition type="warning" >}} -Query acceleration using blooms is an [experimental feature](/docs/release-life-cycle/). Engineering and on-call support is not available. No SLA is provided. +In Loki and Grafana Enterprise Logs (GEL), Query acceleration using blooms is an [experimental feature](/docs/release-life-cycle/). Engineering and on-call support is not available. No SLA is provided. +In Grafana Cloud, Query acceleration using blooms is enabled for large-scale customers that send more than 75TB of logs a month as a [public preview](/docs/release-life-cycle/) with limited support and no SLA. {{< /admonition >}} If [bloom filters][] are enabled, you can write LogQL queries using [structured metadata][] to benefit from query acceleration. @@ -26,19 +27,26 @@ If [bloom filters][] are enabled, you can write LogQL queries using [structured Queries will be accelerated for any [label filter expression][] that satisfies _all_ of the following criteria: * The label filter expression using **string equality**, such as `| key="value"`. - * `or` and `and` operators can be used to match multiple values, such as `| detected_level="error" or detected_level="warn"`. - * _Basic_ regular expressions are automatically simplified into a supported expression: - * `| key=~"value"` is converted to `| key="value"`. - * `| key=~"value1|value2"` is converted to `| key="value1" or key="value2"`. - * `| key=~".+"` checks for existence of `key`. `.*` is not supported. + * `or` and `and` operators can be used to match multiple values, such as `| detected_level="error" or detected_level="warn"`. + * _Basic_ regular expressions are automatically simplified into a supported expression: + * `| key=~"value"` is converted to `| key="value"`. + * `| key=~"value1|value2"` is converted to `| key="value1" or key="value2"`. + * `| key=~".+"` checks for existence of `key`. `.*` is not supported. * The label filter expression is querying for structured metadata and not a stream label. * The label filter expression is placed before any [parser expression][], [labels format expression][], [drop labels expression][], or [keep labels expression][]. -To take full advantage of query acceleration with blooms, ensure that filtering structured metadata is done before any parse expression: +To take full advantage of query acceleration with blooms, ensure that filtering structured metadata is done before any parser expression: + +In the following example, the query is not accelerated because the structured metadata filter, `detected_level="error"`, is after a parser stage, `json`. + +```logql +{cluster="prod"} | logfmt | json | detected_level="error" +``` + +In the following example, the query is accelerated because the structured metadata filter is before any parser stage. ```logql -{cluster="prod"} | logfmt | json | detected_level="error" # NOT ACCELERATED: structured metadata filter is after a parse stage -{cluster="prod"} | detected_level="error" | logfmt | json # ACCELERATED: structured metadata filter is before any parse stage +{cluster="prod"} | detected_level="error" | logfmt | json ``` [bloom filters]: https://grafana.com/docs/loki//operations/bloom-filters/ diff --git a/docs/sources/send-data/promtail/cloud/eks/values.yaml b/docs/sources/send-data/promtail/cloud/eks/values.yaml index a7d97ab2b83ed..8d8fcb7b87d23 100644 --- a/docs/sources/send-data/promtail/cloud/eks/values.yaml +++ b/docs/sources/send-data/promtail/cloud/eks/values.yaml @@ -17,7 +17,7 @@ initContainer: image: repository: grafana/promtail - tag: 3.2.1 + tag: 3.3.0 pullPolicy: IfNotPresent ## Optionally specify an array of imagePullSecrets. ## Secrets must be manually created in the namespace. diff --git a/docs/sources/setup/install/helm/reference.md b/docs/sources/setup/install/helm/reference.md index 23113b35a662e..5dfd74ea279d2 100644 --- a/docs/sources/setup/install/helm/reference.md +++ b/docs/sources/setup/install/helm/reference.md @@ -3062,7 +3062,7 @@ null "pullPolicy": "IfNotPresent", "registry": "docker.io", "repository": "grafana/enterprise-logs", - "tag": null + "tag": "3.3.0" }, "license": { "contents": "NOTAVALIDLICENSE" @@ -3235,7 +3235,7 @@ null string Docker image tag
-null
+"3.3.0"
 
@@ -6090,7 +6090,7 @@ null string Overrides the image tag whose default is the chart's appVersion
-null
+"3.3.0"
 
diff --git a/go.mod b/go.mod index 24bdc41341c7d..15bf63b859d42 100644 --- a/go.mod +++ b/go.mod @@ -8,6 +8,7 @@ require ( cloud.google.com/go/bigtable v1.33.0 cloud.google.com/go/pubsub v1.45.1 cloud.google.com/go/storage v1.47.0 + dario.cat/mergo v1.0.1 github.com/Azure/azure-pipeline-go v0.2.3 github.com/Azure/azure-storage-blob-go v0.15.0 github.com/Azure/go-autorest/autorest/adal v0.9.24 @@ -55,11 +56,10 @@ require ( github.com/grafana/gomemcache v0.0.0-20240229205252-cd6a66d6fb56 github.com/grafana/regexp v0.0.0-20240518133315-a468a5bfb3bc github.com/grafana/tail v0.0.0-20230510142333-77b18831edf0 - github.com/grpc-ecosystem/go-grpc-middleware v1.4.0 + github.com/grpc-ecosystem/go-grpc-middleware/v2 v2.1.0 github.com/grpc-ecosystem/grpc-opentracing v0.0.0-20180507213350-8e809c8a8645 github.com/hashicorp/consul/api v1.30.0 github.com/hashicorp/golang-lru/v2 v2.0.7 - github.com/imdario/mergo v0.3.16 github.com/influxdata/telegraf v1.16.3 github.com/jmespath/go-jmespath v0.4.0 github.com/joncrlsn/dque v0.0.0-20211108142734-c2ef48c5192a @@ -90,7 +90,7 @@ require ( github.com/segmentio/fasthash v1.0.3 github.com/shurcooL/httpfs v0.0.0-20230704072500-f1e31cf0ba5c github.com/shurcooL/vfsgen v0.0.0-20200824052919-0d455de96546 - github.com/sony/gobreaker v0.5.0 + github.com/sony/gobreaker/v2 v2.0.0 github.com/spf13/afero v1.11.0 github.com/stretchr/testify v1.9.0 github.com/uber/jaeger-client-go v2.30.0+incompatible @@ -103,11 +103,11 @@ require ( golang.org/x/sync v0.9.0 golang.org/x/sys v0.27.0 golang.org/x/time v0.8.0 - google.golang.org/api v0.206.0 + google.golang.org/api v0.207.0 google.golang.org/grpc v1.68.0 gopkg.in/yaml.v2 v2.4.0 gopkg.in/yaml.v3 v3.0.1 - k8s.io/klog v1.0.0 + k8s.io/klog/v2 v2.130.1 ) require ( @@ -151,7 +151,7 @@ require ( google.golang.org/protobuf v1.35.2 gotest.tools v2.2.0+incompatible k8s.io/apimachinery v0.31.2 - k8s.io/utils v0.0.0-20240902221715-702e33fdd3c3 + k8s.io/utils v0.0.0-20241104163129-6fe5fd82f078 ) require ( @@ -159,7 +159,6 @@ require ( cloud.google.com/go/auth v0.10.2 // indirect cloud.google.com/go/auth/oauth2adapt v0.2.5 // indirect cloud.google.com/go/monitoring v1.21.2 // indirect - dario.cat/mergo v1.0.1 // indirect github.com/AdaLogics/go-fuzz-headers v0.0.0-20230811130428-ced1acdcaa24 // indirect github.com/GoogleCloudPlatform/opentelemetry-operations-go/detectors/gcp v1.24.1 // indirect github.com/GoogleCloudPlatform/opentelemetry-operations-go/exporter/metric v0.48.1 // indirect @@ -173,6 +172,7 @@ require ( github.com/goccy/go-json v0.10.3 // indirect github.com/gorilla/handlers v1.5.2 // indirect github.com/hashicorp/golang-lru v0.6.0 // indirect + github.com/imdario/mergo v0.3.16 // indirect github.com/lufia/plan9stats v0.0.0-20220913051719-115f729f3c8c // indirect github.com/moby/docker-image-spec v1.3.1 // indirect github.com/moby/sys/userns v0.1.0 // indirect @@ -363,15 +363,14 @@ require ( golang.org/x/mod v0.19.0 // indirect golang.org/x/term v0.26.0 // indirect golang.org/x/tools v0.23.0 // indirect - google.golang.org/genproto v0.0.0-20241104194629-dd2ea8efbc28 // indirect + google.golang.org/genproto v0.0.0-20241113202542-65e8d215514f // indirect google.golang.org/genproto/googleapis/api v0.0.0-20241104194629-dd2ea8efbc28 // indirect - google.golang.org/genproto/googleapis/rpc v0.0.0-20241104194629-dd2ea8efbc28 // indirect + google.golang.org/genproto/googleapis/rpc v0.0.0-20241113202542-65e8d215514f // indirect gopkg.in/fsnotify/fsnotify.v1 v1.4.7 // indirect gopkg.in/inf.v0 v0.9.1 // indirect gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 // indirect k8s.io/api v0.29.3 // indirect k8s.io/client-go v0.29.3 // indirect - k8s.io/klog/v2 v2.130.1 // indirect k8s.io/kube-openapi v0.0.0-20240228011516-70dd3763d340 // indirect rsc.io/binaryregexp v0.2.0 // indirect sigs.k8s.io/json v0.0.0-20221116044647-bc3834ca7abd // indirect diff --git a/go.sum b/go.sum index ea298e1198a7e..b50d624279b46 100644 --- a/go.sum +++ b/go.sum @@ -1776,8 +1776,8 @@ github.com/gregjones/httpcache v0.0.0-20180305231024-9cad4c3443a7/go.mod h1:Fecb github.com/grpc-ecosystem/go-grpc-middleware v1.0.0/go.mod h1:FiyG127CGDf3tlThmgyCl78X/SZQqEOJBCDaAfeWzPs= github.com/grpc-ecosystem/go-grpc-middleware v1.0.1-0.20190118093823-f849b5445de4/go.mod h1:FiyG127CGDf3tlThmgyCl78X/SZQqEOJBCDaAfeWzPs= github.com/grpc-ecosystem/go-grpc-middleware v1.3.0/go.mod h1:z0ButlSOZa5vEBq9m2m2hlwIgKw+rp3sdCBRoJY+30Y= -github.com/grpc-ecosystem/go-grpc-middleware v1.4.0 h1:UH//fgunKIs4JdUbpDl1VZCDaL56wXCB/5+wF6uHfaI= -github.com/grpc-ecosystem/go-grpc-middleware v1.4.0/go.mod h1:g5qyo/la0ALbONm6Vbp88Yd8NsDy6rZz+RcrMPxvld8= +github.com/grpc-ecosystem/go-grpc-middleware/v2 v2.1.0 h1:pRhl55Yx1eC7BZ1N+BBWwnKaMyD8uC+34TLdndZMAKk= +github.com/grpc-ecosystem/go-grpc-middleware/v2 v2.1.0/go.mod h1:XKMd7iuf/RGPSMJ/U4HP0zS2Z9Fh8Ps9a+6X26m/tmI= github.com/grpc-ecosystem/go-grpc-prometheus v1.2.0/go.mod h1:8NvIoxWQoOIhqOTXgfV/d3M/q6VIi02HzZEHgUlZvzk= github.com/grpc-ecosystem/grpc-gateway v1.9.0/go.mod h1:vNeuVxBJEsws4ogUvrchl83t/GYV9WGTSLVdBhOQFDY= github.com/grpc-ecosystem/grpc-gateway v1.9.5/go.mod h1:vNeuVxBJEsws4ogUvrchl83t/GYV9WGTSLVdBhOQFDY= @@ -2540,6 +2540,8 @@ github.com/soniah/gosnmp v1.25.0/go.mod h1:8YvfZxH388NIIw2A+X5z2Oh97VcNhtmxDLt5Q github.com/sony/gobreaker v0.4.1/go.mod h1:ZKptC7FHNvhBz7dN2LGjPVBz2sZJmc0/PkyDJOjmxWY= github.com/sony/gobreaker v0.5.0 h1:dRCvqm0P490vZPmy7ppEk2qCnCieBooFJ+YoXGYB+yg= github.com/sony/gobreaker v0.5.0/go.mod h1:ZKptC7FHNvhBz7dN2LGjPVBz2sZJmc0/PkyDJOjmxWY= +github.com/sony/gobreaker/v2 v2.0.0 h1:23AaR4JQ65y4rz8JWMzgXw2gKOykZ/qfqYunll4OwJ4= +github.com/sony/gobreaker/v2 v2.0.0/go.mod h1:8JnRUz80DJ1/ne8M8v7nmTs2713i58nIt4s7XcGe/DI= github.com/spaolacci/murmur3 v0.0.0-20180118202830-f09979ecbc72/go.mod h1:JwIasOWyU6f++ZhiEuf87xNszmSA2myDM2Kzu9HwQUA= github.com/spaolacci/murmur3 v1.1.0 h1:7c1g84S4BPRrfL5Xrdp6fOJ206sU9y293DDHaoy0bLI= github.com/spaolacci/murmur3 v1.1.0/go.mod h1:JwIasOWyU6f++ZhiEuf87xNszmSA2myDM2Kzu9HwQUA= @@ -2811,7 +2813,6 @@ go.uber.org/tools v0.0.0-20190618225709-2cfd321de3ee/go.mod h1:vJERXedbb3MVM5f9E go.uber.org/zap v1.10.0/go.mod h1:vwi/ZaCAaUcBkycHslxD9B2zi4UTXhF60s6SWpuDF0Q= go.uber.org/zap v1.13.0/go.mod h1:zwrFLgMcdUuIBviXEYEH1YKNaOBnKXsx2IPda5bBwHM= go.uber.org/zap v1.17.0/go.mod h1:MXVU+bhUf/A7Xi2HNOnopQOrmycQ5Ih87HtOu4q5SSo= -go.uber.org/zap v1.18.1/go.mod h1:xg/QME4nWcxGxrpdeYfq7UvYrLh66cuVKdrbD1XF/NI= go.uber.org/zap v1.21.0 h1:WefMeulhovoZ2sYXz7st6K0sLj7bBhpiFaud4r4zST8= go.uber.org/zap v1.21.0/go.mod h1:wjWOCqI0f2ZZrJF/UufIOkiC8ii6tm1iqIsLo76RfJw= go4.org/netipx v0.0.0-20230125063823-8449b0a6169f h1:ketMxHg+vWm3yccyYiq+uK8D3fRmna2Fcj+awpQp84s= @@ -3206,7 +3207,6 @@ golang.org/x/sys v0.0.0-20210908233432-aa78b53d3365/go.mod h1:oPkhp1MJrh7nUepCBc golang.org/x/sys v0.0.0-20210927094055-39ccf1dd6fa6/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20211007075335-d3039528d8ac/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20211019181941-9d821ace8654/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20211025201205-69cdffdb9359/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20211124211545-fe61309f8881/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20211210111614-af8b64212486/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20211216021012-1d35b9e2eb4e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= @@ -3489,8 +3489,8 @@ google.golang.org/api v0.122.0/go.mod h1:gcitW0lvnyWjSp9nKxAbdHKIZ6vF4aajGueeslZ google.golang.org/api v0.124.0/go.mod h1:xu2HQurE5gi/3t1aFCvhPD781p0a3p11sdunTJ2BlP4= google.golang.org/api v0.125.0/go.mod h1:mBwVAtz+87bEN6CbA1GtZPDOqY2R5ONPqJeIlvyo4Aw= google.golang.org/api v0.126.0/go.mod h1:mBwVAtz+87bEN6CbA1GtZPDOqY2R5ONPqJeIlvyo4Aw= -google.golang.org/api v0.206.0 h1:A27GClesCSheW5P2BymVHjpEeQ2XHH8DI8Srs2HI2L8= -google.golang.org/api v0.206.0/go.mod h1:BtB8bfjTYIrai3d8UyvPmV9REGgox7coh+ZRwm0b+W8= +google.golang.org/api v0.207.0 h1:Fvt6IGCYjf7YLcQ+GCegeAI2QSQCfIWhRkmrMPj3JRM= +google.golang.org/api v0.207.0/go.mod h1:I53S168Yr/PNDNMi5yPnDc0/LGRZO6o7PoEbl/HY3CM= google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM= google.golang.org/appengine v1.2.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= @@ -3648,8 +3648,8 @@ google.golang.org/genproto v0.0.0-20230530153820-e85fd2cbaebc/go.mod h1:xZnkP7mR google.golang.org/genproto v0.0.0-20230629202037-9506855d4529/go.mod h1:xZnkP7mREFX5MORlOPEzLMr+90PPZQ2QWzrVTWfAq64= google.golang.org/genproto v0.0.0-20230706204954-ccb25ca9f130/go.mod h1:O9kGHb51iE/nOGvQaDUuadVYqovW56s5emA88lQnj6Y= google.golang.org/genproto v0.0.0-20230711160842-782d3b101e98/go.mod h1:S7mY02OqCJTD0E1OiQy1F72PWFB4bZJ87cAtLPYgDR0= -google.golang.org/genproto v0.0.0-20241104194629-dd2ea8efbc28 h1:KJjNNclfpIkVqrZlTWcgOOaVQ00LdBnoEaRfkUx760s= -google.golang.org/genproto v0.0.0-20241104194629-dd2ea8efbc28/go.mod h1:mt9/MofW7AWQ+Gy179ChOnvmJatV8YHUmrcedo9CIFI= +google.golang.org/genproto v0.0.0-20241113202542-65e8d215514f h1:zDoHYmMzMacIdjNe+P2XiTmPsLawi/pCbSPfxt6lTfw= +google.golang.org/genproto v0.0.0-20241113202542-65e8d215514f/go.mod h1:Q5m6g8b5KaFFzsQFIGdJkSJDGeJiybVenoYFMMa3ohI= google.golang.org/genproto/googleapis/api v0.0.0-20230525234020-1aefcd67740a/go.mod h1:ts19tUU+Z0ZShN1y3aPyq2+O3d5FUNNgT6FtOzmrNn8= google.golang.org/genproto/googleapis/api v0.0.0-20230525234035-dd9d682886f9/go.mod h1:vHYtlOoi6TsQ3Uk2yxR7NI5z8uoV+3pZtR4jmHIkRig= google.golang.org/genproto/googleapis/api v0.0.0-20230526203410-71b5a4ffd15e/go.mod h1:vHYtlOoi6TsQ3Uk2yxR7NI5z8uoV+3pZtR4jmHIkRig= @@ -3667,8 +3667,8 @@ google.golang.org/genproto/googleapis/rpc v0.0.0-20230530153820-e85fd2cbaebc/go. google.golang.org/genproto/googleapis/rpc v0.0.0-20230629202037-9506855d4529/go.mod h1:66JfowdXAEgad5O9NnYcsNPLCPZJD++2L9X0PCMODrA= google.golang.org/genproto/googleapis/rpc v0.0.0-20230706204954-ccb25ca9f130/go.mod h1:8mL13HKkDa+IuJ8yruA3ci0q+0vsUz4m//+ottjwS5o= google.golang.org/genproto/googleapis/rpc v0.0.0-20230711160842-782d3b101e98/go.mod h1:TUfxEVdsvPg18p6AslUXFoLdpED4oBnGwyqk3dV1XzM= -google.golang.org/genproto/googleapis/rpc v0.0.0-20241104194629-dd2ea8efbc28 h1:XVhgTWWV3kGQlwJHR3upFWZeTsei6Oks1apkZSeonIE= -google.golang.org/genproto/googleapis/rpc v0.0.0-20241104194629-dd2ea8efbc28/go.mod h1:GX3210XPVPUjJbTUbvwI8f2IpZDMZuPJWDzDuebbviI= +google.golang.org/genproto/googleapis/rpc v0.0.0-20241113202542-65e8d215514f h1:C1QccEa9kUwvMgEUORqQD9S17QesQijxjZ84sO82mfo= +google.golang.org/genproto/googleapis/rpc v0.0.0-20241113202542-65e8d215514f/go.mod h1:GX3210XPVPUjJbTUbvwI8f2IpZDMZuPJWDzDuebbviI= google.golang.org/grpc v1.8.0/go.mod h1:yo6s7OP7yaDglbqo1J04qKzAhqBH6lvTonzMVmEdcZw= google.golang.org/grpc v1.12.0/go.mod h1:yo6s7OP7yaDglbqo1J04qKzAhqBH6lvTonzMVmEdcZw= google.golang.org/grpc v1.17.0/go.mod h1:6QZJwpn2B+Zp71q/5VxRsJ6NXXVCE5NRUHRo+f3cWCs= @@ -3840,7 +3840,6 @@ k8s.io/gengo v0.0.0-20190128074634-0689ccc1d7d6/go.mod h1:ezvh/TsK7cY6rbqRK0oQQ8 k8s.io/gengo v0.0.0-20200413195148-3a45101e95ac/go.mod h1:ezvh/TsK7cY6rbqRK0oQQ8IAqLxYwwyPxAX1Pzy0ii0= k8s.io/gengo v0.0.0-20210813121822-485abfe95c7c/go.mod h1:FiNAH4ZV3gBg2Kwh89tzAEV2be7d5xI0vBa/VySYy3E= k8s.io/klog v0.0.0-20181102134211-b9b56d5dfc92/go.mod h1:Gq+BEi5rUBO/HRz0bTSXDUcqjScdoY3a9IHpCEIOOfk= -k8s.io/klog v1.0.0 h1:Pt+yjF5aB1xDSVbau4VsWe+dQNzA0qv1LlXdC2dF6Q8= k8s.io/klog v1.0.0/go.mod h1:4Bi6QPql/J/LkTDqv7R/cd3hPo4k2DG6Ptcz060Ez5I= k8s.io/klog/v2 v2.0.0/go.mod h1:PBfzABfn139FHAV07az/IF9Wp1bkk3vpT2XSJ76fSDE= k8s.io/klog/v2 v2.2.0/go.mod h1:Od+F08eJP+W3HUb4pSrPpgp9DGU4GzlpG/TmITuYh/Y= @@ -3858,8 +3857,8 @@ k8s.io/utils v0.0.0-20210802155522-efc7438f0176/go.mod h1:jPW/WVKK9YHAvNhRxK0md/ k8s.io/utils v0.0.0-20210819203725-bdf08cb9a70a/go.mod h1:jPW/WVKK9YHAvNhRxK0md/EJ228hCsBRufyofKtW8HA= k8s.io/utils v0.0.0-20221107191617-1a15be271d1d/go.mod h1:OLgZIPagt7ERELqWJFomSt595RzquPNLL48iOWgYOg0= k8s.io/utils v0.0.0-20230406110748-d93618cff8a2/go.mod h1:OLgZIPagt7ERELqWJFomSt595RzquPNLL48iOWgYOg0= -k8s.io/utils v0.0.0-20240902221715-702e33fdd3c3 h1:b2FmK8YH+QEwq/Sy2uAEhmqL5nPfGYbJOcaqjeYYZoA= -k8s.io/utils v0.0.0-20240902221715-702e33fdd3c3/go.mod h1:OLgZIPagt7ERELqWJFomSt595RzquPNLL48iOWgYOg0= +k8s.io/utils v0.0.0-20241104163129-6fe5fd82f078 h1:jGnCPejIetjiy2gqaJ5V0NLwTpF4wbQ6cZIItJCSHno= +k8s.io/utils v0.0.0-20241104163129-6fe5fd82f078/go.mod h1:OLgZIPagt7ERELqWJFomSt595RzquPNLL48iOWgYOg0= lukechampine.com/uint128 v1.1.1/go.mod h1:c4eWIwlEGaxC/+H1VguhU4PHXNWDCDMUlWdIWl2j1gk= lukechampine.com/uint128 v1.2.0/go.mod h1:c4eWIwlEGaxC/+H1VguhU4PHXNWDCDMUlWdIWl2j1gk= modernc.org/cc/v3 v3.36.0/go.mod h1:NFUHyPn4ekoC/JHeZFfZurN6ixxawE1BnVonP/oahEI= diff --git a/integration/util/merger.go b/integration/util/merger.go index dbd88a4205fc9..5458c1ce3f125 100644 --- a/integration/util/merger.go +++ b/integration/util/merger.go @@ -3,7 +3,7 @@ package util import ( "fmt" - "github.com/imdario/mergo" + "dario.cat/mergo" "gopkg.in/yaml.v2" ) diff --git a/operator/jsonnet/jsonnetfile.json b/operator/jsonnet/jsonnetfile.json index 6456bf5997c11..6064cf7d1f8d2 100644 --- a/operator/jsonnet/jsonnetfile.json +++ b/operator/jsonnet/jsonnetfile.json @@ -8,7 +8,7 @@ "subdir": "production/loki-mixin" } }, - "version": "v3.2.1" + "version": "v3.3.0" } ], "legacyImports": true diff --git a/operator/jsonnet/jsonnetfile.lock.json b/operator/jsonnet/jsonnetfile.lock.json index 2ba0c39bea391..31f064d701f53 100644 --- a/operator/jsonnet/jsonnetfile.lock.json +++ b/operator/jsonnet/jsonnetfile.lock.json @@ -38,8 +38,8 @@ "subdir": "production/loki-mixin" } }, - "version": "3c386cc5d13629a74cddb43c429ec290ba2e4a0a", - "sum": "mVKuwcuL1Wm+JMgt2MiwOAtKkmuClzE75+liMe0AGek=" + "version": "19bbc44845e8c90bd9a867348624967f62363a82", + "sum": "4DCfOphB9C37hqxU8fh8EPIfn1BXGiZnJaFR+EpjFCA=" }, { "source": { diff --git a/pkg/bloombuild/builder/metrics.go b/pkg/bloombuild/builder/metrics.go index 8d4545c00bf5e..c5d45b69fc4fc 100644 --- a/pkg/bloombuild/builder/metrics.go +++ b/pkg/bloombuild/builder/metrics.go @@ -3,10 +3,11 @@ package builder import ( "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus/promauto" + + "github.com/grafana/loki/v3/pkg/util/constants" ) const ( - metricsNamespace = "loki" metricsSubsystem = "bloombuilder" statusSuccess = "success" @@ -34,32 +35,32 @@ type Metrics struct { func NewMetrics(r prometheus.Registerer) *Metrics { return &Metrics{ running: promauto.With(r).NewGauge(prometheus.GaugeOpts{ - Namespace: metricsNamespace, + Namespace: constants.Loki, Subsystem: metricsSubsystem, Name: "running", Help: "Value will be 1 if the bloom builder is currently running on this instance", }), processingTask: promauto.With(r).NewGauge(prometheus.GaugeOpts{ - Namespace: metricsNamespace, + Namespace: constants.Loki, Subsystem: metricsSubsystem, Name: "processing_task", Help: "Value will be 1 if the bloom builder is currently processing a task", }), taskStarted: promauto.With(r).NewCounter(prometheus.CounterOpts{ - Namespace: metricsNamespace, + Namespace: constants.Loki, Subsystem: metricsSubsystem, Name: "task_started_total", Help: "Total number of task started", }), taskCompleted: promauto.With(r).NewCounterVec(prometheus.CounterOpts{ - Namespace: metricsNamespace, + Namespace: constants.Loki, Subsystem: metricsSubsystem, Name: "task_completed_total", Help: "Total number of task completed", }, []string{"status"}), taskDuration: promauto.With(r).NewHistogramVec(prometheus.HistogramOpts{ - Namespace: metricsNamespace, + Namespace: constants.Loki, Subsystem: metricsSubsystem, Name: "task_duration_seconds", Help: "Time spent processing a task.", @@ -73,26 +74,26 @@ func NewMetrics(r prometheus.Registerer) *Metrics { }, []string{"status"}), blocksReused: promauto.With(r).NewCounter(prometheus.CounterOpts{ - Namespace: metricsNamespace, + Namespace: constants.Loki, Subsystem: metricsSubsystem, Name: "blocks_reused_total", Help: "Number of overlapping bloom blocks reused when creating new blocks", }), blocksCreated: promauto.With(r).NewCounter(prometheus.CounterOpts{ - Namespace: metricsNamespace, + Namespace: constants.Loki, Subsystem: metricsSubsystem, Name: "blocks_created_total", Help: "Number of blocks created", }), metasCreated: promauto.With(r).NewCounter(prometheus.CounterOpts{ - Namespace: metricsNamespace, + Namespace: constants.Loki, Subsystem: metricsSubsystem, Name: "metas_created_total", Help: "Number of metas created", }), seriesPerTask: promauto.With(r).NewHistogram(prometheus.HistogramOpts{ - Namespace: metricsNamespace, + Namespace: constants.Loki, Subsystem: metricsSubsystem, Name: "series_per_task", Help: "Number of series during task processing. Includes series which copied from other blocks and don't need to be indexed", @@ -100,7 +101,7 @@ func NewMetrics(r prometheus.Registerer) *Metrics { Buckets: prometheus.ExponentialBucketsRange(1, 10e6, 10), }), bytesPerTask: promauto.With(r).NewHistogram(prometheus.HistogramOpts{ - Namespace: metricsNamespace, + Namespace: constants.Loki, Subsystem: metricsSubsystem, Name: "bytes_per_task", Help: "Number of source bytes from chunks added during a task processing.", @@ -109,7 +110,7 @@ func NewMetrics(r prometheus.Registerer) *Metrics { }), chunkSize: promauto.With(r).NewHistogram(prometheus.HistogramOpts{ - Namespace: metricsNamespace, + Namespace: constants.Loki, Subsystem: metricsSubsystem, Name: "chunk_series_size", Help: "Uncompressed size of chunks in a series", diff --git a/pkg/bloombuild/planner/metrics.go b/pkg/bloombuild/planner/metrics.go index 936515ad736f3..fd9efad2716b1 100644 --- a/pkg/bloombuild/planner/metrics.go +++ b/pkg/bloombuild/planner/metrics.go @@ -5,10 +5,11 @@ import ( "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus/promauto" + + "github.com/grafana/loki/v3/pkg/util/constants" ) const ( - metricsNamespace = "loki" metricsSubsystem = "bloomplanner" statusSuccess = "success" @@ -40,6 +41,7 @@ type Metrics struct { tenantsDiscovered prometheus.Counter tenantTasksPlanned *prometheus.GaugeVec tenantTasksCompleted *prometheus.GaugeVec + tenantTasksTiming *prometheus.HistogramVec // Retention metrics retentionRunning prometheus.Gauge @@ -55,26 +57,26 @@ func NewMetrics( ) *Metrics { return &Metrics{ running: promauto.With(r).NewGauge(prometheus.GaugeOpts{ - Namespace: metricsNamespace, + Namespace: constants.Loki, Subsystem: metricsSubsystem, Name: "running", Help: "Value will be 1 if bloom planner is currently running on this instance", }), connectedBuilders: promauto.With(r).NewGaugeFunc(prometheus.GaugeOpts{ - Namespace: metricsNamespace, + Namespace: constants.Loki, Subsystem: metricsSubsystem, Name: "connected_builders", Help: "Number of builders currently connected to the planner.", }, getConnectedBuilders), queueDuration: promauto.With(r).NewHistogram(prometheus.HistogramOpts{ - Namespace: metricsNamespace, + Namespace: constants.Loki, Subsystem: metricsSubsystem, Name: "queue_duration_seconds", Help: "Time spend by tasks in queue before getting picked up by a builder.", Buckets: prometheus.DefBuckets, }), inflightRequests: promauto.With(r).NewSummary(prometheus.SummaryOpts{ - Namespace: metricsNamespace, + Namespace: constants.Loki, Subsystem: metricsSubsystem, Name: "inflight_tasks", Help: "Number of inflight tasks (either queued or processing) sampled at a regular interval. Quantile buckets keep track of inflight tasks over the last 60s.", @@ -83,20 +85,20 @@ func NewMetrics( AgeBuckets: 6, }), tasksRequeued: promauto.With(r).NewCounter(prometheus.CounterOpts{ - Namespace: metricsNamespace, + Namespace: constants.Loki, Subsystem: metricsSubsystem, Name: "tasks_requeued_total", Help: "Total number of tasks requeued due to not being picked up by a builder.", }), taskLost: promauto.With(r).NewCounter(prometheus.CounterOpts{ - Namespace: metricsNamespace, + Namespace: constants.Loki, Subsystem: metricsSubsystem, Name: "tasks_lost_total", Help: "Total number of tasks lost due to not being picked up by a builder and failed to be requeued.", }), planningTime: promauto.With(r).NewHistogram(prometheus.HistogramOpts{ - Namespace: metricsNamespace, + Namespace: constants.Loki, Subsystem: metricsSubsystem, Name: "planning_time_seconds", Help: "Time spent planning a build cycle.", @@ -104,19 +106,19 @@ func NewMetrics( Buckets: prometheus.LinearBuckets(1, 60, 60), }), buildStarted: promauto.With(r).NewCounter(prometheus.CounterOpts{ - Namespace: metricsNamespace, + Namespace: constants.Loki, Subsystem: metricsSubsystem, Name: "build_started_total", Help: "Total number of builds started", }), buildCompleted: promauto.With(r).NewCounterVec(prometheus.CounterOpts{ - Namespace: metricsNamespace, + Namespace: constants.Loki, Subsystem: metricsSubsystem, Name: "build_completed_total", Help: "Total number of builds completed", }, []string{"status"}), buildTime: promauto.With(r).NewHistogramVec(prometheus.HistogramOpts{ - Namespace: metricsNamespace, + Namespace: constants.Loki, Subsystem: metricsSubsystem, Name: "build_time_seconds", Help: "Time spent during a builds cycle.", @@ -129,54 +131,62 @@ func NewMetrics( ), }, []string{"status"}), buildLastSuccess: promauto.With(r).NewGauge(prometheus.GaugeOpts{ - Namespace: metricsNamespace, + Namespace: constants.Loki, Subsystem: metricsSubsystem, Name: "build_last_successful_run_timestamp_seconds", Help: "Unix timestamp of the last successful build cycle.", }), blocksDeleted: promauto.With(r).NewCounterVec(prometheus.CounterOpts{ - Namespace: metricsNamespace, + Namespace: constants.Loki, Subsystem: metricsSubsystem, Name: "blocks_deleted_total", Help: "Number of blocks deleted", }, []string{"phase"}), metasDeleted: promauto.With(r).NewCounterVec(prometheus.CounterOpts{ - Namespace: metricsNamespace, + Namespace: constants.Loki, Subsystem: metricsSubsystem, Name: "metas_deleted_total", Help: "Number of metas deleted", }, []string{"phase"}), tenantsDiscovered: promauto.With(r).NewCounter(prometheus.CounterOpts{ - Namespace: metricsNamespace, + Namespace: constants.Loki, Subsystem: metricsSubsystem, Name: "tenants_discovered_total", Help: "Number of tenants discovered during the current build iteration", }), tenantTasksPlanned: promauto.With(r).NewGaugeVec(prometheus.GaugeOpts{ - Namespace: metricsNamespace, + Namespace: constants.Loki, Subsystem: metricsSubsystem, Name: "tenant_tasks_planned", Help: "Number of tasks planned for a tenant during the current build iteration.", }, []string{"tenant"}), tenantTasksCompleted: promauto.With(r).NewGaugeVec(prometheus.GaugeOpts{ - Namespace: metricsNamespace, + Namespace: constants.Loki, Subsystem: metricsSubsystem, Name: "tenant_tasks_completed", Help: "Number of tasks completed for a tenant during the current build iteration.", }, []string{"tenant", "status"}), + tenantTasksTiming: promauto.With(r).NewHistogramVec(prometheus.HistogramOpts{ + Namespace: constants.Loki, + Subsystem: metricsSubsystem, + Name: "tenant_tasks_time_seconds", + Help: "Time spent building tasks for a tenant during the current build iteration.", + // 1s --> 1h (steps of 1 minute) + Buckets: prometheus.LinearBuckets(1, 60, 60), + }, []string{"tenant", "status"}), // Retention retentionRunning: promauto.With(r).NewGauge(prometheus.GaugeOpts{ - Namespace: metricsNamespace, + Namespace: constants.Loki, Subsystem: metricsSubsystem, Name: "retention_running", Help: "1 if retention is running in this compactor.", }), retentionTime: promauto.With(r).NewHistogramVec(prometheus.HistogramOpts{ - Namespace: metricsNamespace, + Namespace: constants.Loki, Subsystem: metricsSubsystem, Name: "retention_time_seconds", Help: "Time this retention process took to complete.", @@ -184,7 +194,7 @@ func NewMetrics( }, []string{"status"}), retentionDaysPerIteration: promauto.With(r).NewHistogramVec(prometheus.HistogramOpts{ - Namespace: metricsNamespace, + Namespace: constants.Loki, Subsystem: metricsSubsystem, Name: "retention_days_processed", Help: "Number of days iterated over during the retention process.", @@ -193,7 +203,7 @@ func NewMetrics( }, []string{"status"}), retentionTenantsPerIteration: promauto.With(r).NewHistogramVec(prometheus.HistogramOpts{ - Namespace: metricsNamespace, + Namespace: constants.Loki, Subsystem: metricsSubsystem, Name: "retention_tenants_processed", Help: "Number of tenants on which retention was applied during the retention process.", @@ -202,7 +212,7 @@ func NewMetrics( }, []string{"status"}), retentionTenantsExceedingLookback: promauto.With(r).NewGauge(prometheus.GaugeOpts{ - Namespace: metricsNamespace, + Namespace: constants.Loki, Subsystem: metricsSubsystem, Name: "retention_tenants_exceeding_lookback", Help: "Number of tenants with a retention exceeding the configured retention lookback.", diff --git a/pkg/bloombuild/planner/planner.go b/pkg/bloombuild/planner/planner.go index 9ef59a9b7f855..4ec2aec389e57 100644 --- a/pkg/bloombuild/planner/planner.go +++ b/pkg/bloombuild/planner/planner.go @@ -26,6 +26,7 @@ import ( "github.com/grafana/loki/v3/pkg/storage/config" "github.com/grafana/loki/v3/pkg/storage/stores/shipper/bloomshipper" "github.com/grafana/loki/v3/pkg/storage/stores/shipper/indexshipper/tsdb" + "github.com/grafana/loki/v3/pkg/util/constants" utillog "github.com/grafana/loki/v3/pkg/util/log" "github.com/grafana/loki/v3/pkg/util/ring" ) @@ -49,7 +50,8 @@ type Planner struct { tsdbStore common.TSDBStore bloomStore bloomshipper.StoreBase - tasksQueue *queue.Queue + tasksQueue *queue.Queue + planFactory *strategies.Factory metrics *Metrics logger log.Logger @@ -78,7 +80,7 @@ func New( } // Queue to manage tasks - queueMetrics := queue.NewMetrics(r, metricsNamespace, metricsSubsystem) + queueMetrics := queue.NewMetrics(r, constants.Loki, metricsSubsystem) queueLimits := NewQueueLimits(limits) tasksQueue, err := queue.NewQueue(logger, cfg.Queue, queueLimits, queueMetrics, storageMetrics) if err != nil { @@ -86,14 +88,15 @@ func New( } p := &Planner{ - cfg: cfg, - limits: limits, - schemaCfg: schemaCfg, - tsdbStore: tsdbStore, - bloomStore: bloomStore, - tasksQueue: tasksQueue, - metrics: NewMetrics(r, tasksQueue.GetConnectedConsumersMetric), - logger: logger, + cfg: cfg, + limits: limits, + schemaCfg: schemaCfg, + tsdbStore: tsdbStore, + bloomStore: bloomStore, + tasksQueue: tasksQueue, + planFactory: strategies.NewFactory(limits, strategies.NewMetrics(r), logger), + metrics: NewMetrics(r, tasksQueue.GetConnectedConsumersMetric), + logger: logger, } p.retentionManager = NewRetentionManager( @@ -370,7 +373,7 @@ func (p *Planner) computeTasks( table config.DayTable, tenant string, ) ([]*protos.Task, []bloomshipper.Meta, error) { - strategy, err := strategies.NewStrategy(tenant, p.limits, p.logger) + strategy, err := p.planFactory.GetStrategy(tenant) if err != nil { return nil, nil, fmt.Errorf("error creating strategy: %w", err) } @@ -770,8 +773,10 @@ func (p *Planner) BuilderLoop(builder protos.PlannerForBuilder_BuilderLoopServer continue } + startTime := time.Now() result, err := p.forwardTaskToBuilder(builder, builderID, task) if err != nil { + p.metrics.tenantTasksTiming.WithLabelValues(task.Tenant, statusFailure).Observe(time.Since(startTime).Seconds()) maxRetries := p.limits.BloomTaskMaxRetries(task.Tenant) if maxRetries > 0 && int(task.timesEnqueued.Load()) >= maxRetries { p.tasksQueue.Release(task.ProtoTask) @@ -811,10 +816,12 @@ func (p *Planner) BuilderLoop(builder protos.PlannerForBuilder_BuilderLoopServer level.Debug(logger).Log( "msg", "task completed", - "duration", time.Since(task.queueTime).Seconds(), + "timeSinceEnqueued", time.Since(task.queueTime).Seconds(), + "buildTime", time.Since(startTime).Seconds(), "retries", task.timesEnqueued.Load()-1, // -1 because the first enqueue is not a retry ) p.tasksQueue.Release(task.ProtoTask) + p.metrics.tenantTasksTiming.WithLabelValues(task.Tenant, statusSuccess).Observe(time.Since(startTime).Seconds()) // Send the result back to the task. The channel is buffered, so this should not block. task.resultsChannel <- result @@ -866,7 +873,7 @@ func (p *Planner) forwardTaskToBuilder( case err := <-errCh: return nil, err case <-timeout: - return nil, fmt.Errorf("timeout waiting for response from builder (%s)", builderID) + return nil, fmt.Errorf("timeout (%s) waiting for response from builder (%s)", taskTimeout, builderID) } } diff --git a/pkg/bloombuild/planner/strategies/chunksize.go b/pkg/bloombuild/planner/strategies/chunksize.go index 456183aa62ef5..b21c90b6f2e28 100644 --- a/pkg/bloombuild/planner/strategies/chunksize.go +++ b/pkg/bloombuild/planner/strategies/chunksize.go @@ -9,6 +9,8 @@ import ( "github.com/dustin/go-humanize" "github.com/go-kit/log" "github.com/go-kit/log/level" + "github.com/prometheus/client_golang/prometheus" + "github.com/prometheus/client_golang/prometheus/promauto" "github.com/prometheus/common/model" "github.com/prometheus/prometheus/model/labels" @@ -19,24 +21,49 @@ import ( "github.com/grafana/loki/v3/pkg/storage/stores/shipper/bloomshipper" "github.com/grafana/loki/v3/pkg/storage/stores/shipper/indexshipper/tsdb" "github.com/grafana/loki/v3/pkg/storage/stores/shipper/indexshipper/tsdb/index" + "github.com/grafana/loki/v3/pkg/util/constants" ) +const ( + metricsSubsystem = "bloomplanner" +) + +type ChunkSizeStrategyMetrics struct { + tenantTaskSize *prometheus.HistogramVec +} + +func NewChunkSizeStrategyMetrics(r prometheus.Registerer) *ChunkSizeStrategyMetrics { + return &ChunkSizeStrategyMetrics{ + tenantTaskSize: promauto.With(r).NewHistogramVec(prometheus.HistogramOpts{ + Namespace: constants.Loki, + Subsystem: metricsSubsystem, + Name: "tenant_task_size_bytes", + Help: "Size of tasks generated by the chunk size strategy", + // 1GB --> 512GB + Buckets: prometheus.ExponentialBuckets(1e9, 2, 10), + }, []string{"tenant"}), + } +} + type ChunkSizeStrategyLimits interface { BloomTaskTargetSeriesChunksSizeBytes(tenantID string) uint64 } type ChunkSizeStrategy struct { - limits ChunkSizeStrategyLimits - logger log.Logger + limits ChunkSizeStrategyLimits + metrics *ChunkSizeStrategyMetrics + logger log.Logger } func NewChunkSizeStrategy( limits ChunkSizeStrategyLimits, + metrics *ChunkSizeStrategyMetrics, logger log.Logger, ) (*ChunkSizeStrategy, error) { return &ChunkSizeStrategy{ - limits: limits, - logger: logger, + limits: limits, + metrics: metrics, + logger: logger, }, nil } @@ -82,8 +109,9 @@ func (s *ChunkSizeStrategy) Plan( continue } - bounds := series.Bounds() + s.metrics.tenantTaskSize.WithLabelValues(tenant).Observe(float64(series.Size())) + bounds := series.Bounds() blocks, err := getBlocksMatchingBounds(metas, bounds) if err != nil { return nil, fmt.Errorf("failed to get blocks matching bounds: %w", err) diff --git a/pkg/bloombuild/planner/strategies/chunksize_test.go b/pkg/bloombuild/planner/strategies/chunksize_test.go index 951d033e5c100..c59e13fdfdd1c 100644 --- a/pkg/bloombuild/planner/strategies/chunksize_test.go +++ b/pkg/bloombuild/planner/strategies/chunksize_test.go @@ -5,6 +5,7 @@ import ( "testing" "github.com/go-kit/log" + "github.com/prometheus/client_golang/prometheus" "github.com/stretchr/testify/require" "github.com/grafana/loki/v3/pkg/bloombuild/planner/plannertest" @@ -228,7 +229,7 @@ func Test_ChunkSizeStrategy_Plan(t *testing.T) { logger := log.NewNopLogger() //logger := log.NewLogfmtLogger(os.Stdout) - strategy, err := NewChunkSizeStrategy(tc.limits, logger) + strategy, err := NewChunkSizeStrategy(tc.limits, NewChunkSizeStrategyMetrics(prometheus.NewPedanticRegistry()), logger) require.NoError(t, err) actual, err := strategy.Plan(context.Background(), plannertest.TestTable, "fake", tc.tsdbs, tc.originalMetas) diff --git a/pkg/bloombuild/planner/strategies/factory.go b/pkg/bloombuild/planner/strategies/factory.go index f58f91e51708d..d48d4e7f59f87 100644 --- a/pkg/bloombuild/planner/strategies/factory.go +++ b/pkg/bloombuild/planner/strategies/factory.go @@ -5,6 +5,7 @@ import ( "fmt" "github.com/go-kit/log" + "github.com/prometheus/client_golang/prometheus" "github.com/grafana/loki/v3/pkg/bloombuild/common" "github.com/grafana/loki/v3/pkg/bloombuild/protos" @@ -32,18 +33,42 @@ type PlanningStrategy interface { Plan(ctx context.Context, table config.DayTable, tenant string, tsdbs TSDBSet, metas []bloomshipper.Meta) ([]*protos.Task, error) } -func NewStrategy( - tenantID string, +type Metrics struct { + *ChunkSizeStrategyMetrics +} + +func NewMetrics(reg prometheus.Registerer) *Metrics { + return &Metrics{ + ChunkSizeStrategyMetrics: NewChunkSizeStrategyMetrics(reg), + } +} + +type Factory struct { + limits Limits + logger log.Logger + metrics *Metrics +} + +func NewFactory( limits Limits, + metrics *Metrics, logger log.Logger, -) (PlanningStrategy, error) { - strategy := limits.BloomPlanningStrategy(tenantID) +) *Factory { + return &Factory{ + limits: limits, + logger: logger, + metrics: metrics, + } +} + +func (f *Factory) GetStrategy(tenantID string) (PlanningStrategy, error) { + strategy := f.limits.BloomPlanningStrategy(tenantID) switch strategy { case SplitKeyspaceStrategyName: - return NewSplitKeyspaceStrategy(limits, logger) + return NewSplitKeyspaceStrategy(f.limits, f.logger) case SplitBySeriesChunkSizeStrategyName: - return NewChunkSizeStrategy(limits, logger) + return NewChunkSizeStrategy(f.limits, f.metrics.ChunkSizeStrategyMetrics, f.logger) default: return nil, fmt.Errorf("unknown bloom planning strategy (%s)", strategy) } diff --git a/pkg/ruler/evaluator_remote.go b/pkg/ruler/evaluator_remote.go index 8ef0fb88e4152..63aeebfa9d4f5 100644 --- a/pkg/ruler/evaluator_remote.go +++ b/pkg/ruler/evaluator_remote.go @@ -25,7 +25,6 @@ import ( "github.com/grafana/dskit/instrument" "github.com/grafana/dskit/middleware" "github.com/grafana/dskit/user" - grpc_middleware "github.com/grpc-ecosystem/go-grpc-middleware" otgrpc "github.com/opentracing-contrib/go-grpc" "github.com/opentracing/opentracing-go" "github.com/prometheus/client_golang/prometheus" @@ -182,11 +181,9 @@ func DialQueryFrontend(cfg *QueryFrontendConfig) (httpgrpc.HTTPClient, error) { PermitWithoutStream: true, }, ), - grpc.WithUnaryInterceptor( - grpc_middleware.ChainUnaryClient( - otgrpc.OpenTracingClientInterceptor(opentracing.GlobalTracer()), - middleware.ClientUserHeaderInterceptor, - ), + grpc.WithChainUnaryInterceptor( + otgrpc.OpenTracingClientInterceptor(opentracing.GlobalTracer()), + middleware.ClientUserHeaderInterceptor, ), grpc.WithDefaultServiceConfig(serviceConfig), }, diff --git a/pkg/ruler/registry.go b/pkg/ruler/registry.go index 29297fcab5a74..67ef1d9bbf32c 100644 --- a/pkg/ruler/registry.go +++ b/pkg/ruler/registry.go @@ -8,10 +8,10 @@ import ( "sync" "time" + "dario.cat/mergo" "github.com/go-kit/log" "github.com/go-kit/log/level" "github.com/grafana/dskit/user" - "github.com/imdario/mergo" "github.com/pkg/errors" "github.com/prometheus/client_golang/prometheus" promConfig "github.com/prometheus/common/config" diff --git a/pkg/storage/chunk/cache/memcached_client.go b/pkg/storage/chunk/cache/memcached_client.go index ffdc817b68b42..afd976babf365 100644 --- a/pkg/storage/chunk/cache/memcached_client.go +++ b/pkg/storage/chunk/cache/memcached_client.go @@ -19,7 +19,7 @@ import ( "github.com/pkg/errors" "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus/promauto" - "github.com/sony/gobreaker" + "github.com/sony/gobreaker/v2" "github.com/grafana/loki/v3/pkg/util/constants" "github.com/grafana/loki/v3/pkg/util/jumphash" @@ -50,7 +50,7 @@ type memcachedClient struct { addresses []string provider *dns.Provider - cbs map[ /*address*/ string]*gobreaker.CircuitBreaker + cbs map[string]*gobreaker.CircuitBreaker[interface{}] cbFailures uint cbTimeout time.Duration cbInterval time.Duration @@ -152,7 +152,7 @@ func NewMemcachedClient(cfg MemcachedClientConfig, name string, r prometheus.Reg service: cfg.Service, logger: logger, provider: dns.NewProvider(logger, dnsProviderRegisterer, dns.GolangResolverType), - cbs: make(map[string]*gobreaker.CircuitBreaker), + cbs: make(map[string]*gobreaker.CircuitBreaker[interface{}]), cbFailures: cfg.CBFailures, cbInterval: cfg.CBInterval, cbTimeout: cfg.CBTimeout, @@ -201,7 +201,7 @@ func (c *memcachedClient) dialViaCircuitBreaker(network, address string, timeout c.Lock() cb := c.cbs[address] if cb == nil { - cb = gobreaker.NewCircuitBreaker(gobreaker.Settings{ + cb = gobreaker.NewCircuitBreaker[interface{}](gobreaker.Settings{ Name: c.name + ":" + address, Interval: c.cbInterval, Timeout: c.cbTimeout, @@ -295,7 +295,7 @@ func (c *memcachedClient) updateMemcacheServers() error { // Copy across circuit-breakers for current set of addresses, thus // leaving behind any for servers we won't talk to again c.Lock() - newCBs := make(map[string]*gobreaker.CircuitBreaker, len(servers)) + newCBs := make(map[string]*gobreaker.CircuitBreaker[interface{}], len(servers)) for _, address := range servers { if cb, exists := c.cbs[address]; exists { newCBs[address] = cb diff --git a/pkg/util/server/recovery.go b/pkg/util/server/recovery.go index ce3ad109512b7..58eac396dd750 100644 --- a/pkg/util/server/recovery.go +++ b/pkg/util/server/recovery.go @@ -9,7 +9,7 @@ import ( "github.com/grafana/dskit/httpgrpc" "github.com/grafana/dskit/middleware" - grpc_recovery "github.com/grpc-ecosystem/go-grpc-middleware/recovery" + grpc_recovery "github.com/grpc-ecosystem/go-grpc-middleware/v2/interceptors/recovery" "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus/promauto" diff --git a/production/docker/docker-compose.yaml b/production/docker/docker-compose.yaml index 85c8f10f2600d..a29e5efbf4db2 100644 --- a/production/docker/docker-compose.yaml +++ b/production/docker/docker-compose.yaml @@ -24,7 +24,7 @@ services: - loki grafana: - image: grafana/grafana:11.3.0 + image: grafana/grafana:11.3.1 ports: - "3000:3000" environment: diff --git a/production/helm/loki/CHANGELOG.md b/production/helm/loki/CHANGELOG.md index e28e771da1549..b1273e533c1ea 100644 --- a/production/helm/loki/CHANGELOG.md +++ b/production/helm/loki/CHANGELOG.md @@ -15,6 +15,10 @@ Entries should include a reference to the pull request that introduced the chang ## 6.20.0 +- [CHANGE] Changed version of Grafana Loki to 3.3.0 + +## 6.19.0-weekly.227 + - [ENHANCEMENT] Expose Topology Spread Constraints in Helm chart templates and default values. ## 6.19.0 diff --git a/production/helm/loki/Chart.yaml b/production/helm/loki/Chart.yaml index 8879acef8e8e9..7e09fdbeee3bd 100644 --- a/production/helm/loki/Chart.yaml +++ b/production/helm/loki/Chart.yaml @@ -2,8 +2,8 @@ apiVersion: v2 name: loki description: Helm chart for Grafana Loki and Grafana Enterprise Logs supporting both simple, scalable and distributed modes. type: application -appVersion: 3.2.0 -version: 6.20.0 +appVersion: 3.3.0 +version: 6.21.0 home: https://grafana.github.io/helm-charts sources: - https://github.com/grafana/loki diff --git a/production/helm/loki/README.md b/production/helm/loki/README.md index 2d63e033585d0..58ff6ccc7a6c0 100644 --- a/production/helm/loki/README.md +++ b/production/helm/loki/README.md @@ -1,6 +1,6 @@ # loki -![Version: 6.20.0](https://img.shields.io/badge/Version-6.20.0-informational?style=flat-square) ![Type: application](https://img.shields.io/badge/Type-application-informational?style=flat-square) ![AppVersion: 3.2.0](https://img.shields.io/badge/AppVersion-3.2.0-informational?style=flat-square) +![Version: 6.21.0](https://img.shields.io/badge/Version-6.21.0-informational?style=flat-square) ![Type: application](https://img.shields.io/badge/Type-application-informational?style=flat-square) ![AppVersion: 3.3.0](https://img.shields.io/badge/AppVersion-3.3.0-informational?style=flat-square) Helm chart for Grafana Loki and Grafana Enterprise Logs supporting both simple, scalable and distributed modes. diff --git a/production/helm/loki/templates/index-gateway/poddisruptionbudget-index-gateway.yaml b/production/helm/loki/templates/index-gateway/poddisruptionbudget-index-gateway.yaml index 22ba1a0b4c336..cc230c2559f54 100644 --- a/production/helm/loki/templates/index-gateway/poddisruptionbudget-index-gateway.yaml +++ b/production/helm/loki/templates/index-gateway/poddisruptionbudget-index-gateway.yaml @@ -7,6 +7,7 @@ apiVersion: {{ include "loki.pdb.apiVersion" . }} kind: PodDisruptionBudget metadata: name: {{ include "loki.indexGatewayFullname" . }} + namespace: {{ $.Release.Namespace }} labels: {{- include "loki.indexGatewayLabels" . | nindent 4 }} spec: diff --git a/production/helm/loki/templates/index-gateway/service-index-gateway-headless.yaml b/production/helm/loki/templates/index-gateway/service-index-gateway-headless.yaml index 06506582f9e36..731a9844f8581 100644 --- a/production/helm/loki/templates/index-gateway/service-index-gateway-headless.yaml +++ b/production/helm/loki/templates/index-gateway/service-index-gateway-headless.yaml @@ -4,6 +4,7 @@ apiVersion: v1 kind: Service metadata: name: {{ include "loki.indexGatewayFullname" . }}-headless + namespace: {{ $.Release.Namespace }} labels: {{- include "loki.indexGatewaySelectorLabels" . | nindent 4 }} prometheus.io/service-monitor: "false" diff --git a/production/helm/loki/templates/index-gateway/service-index-gateway.yaml b/production/helm/loki/templates/index-gateway/service-index-gateway.yaml index 822a0ce692d3b..b1a3523a42f63 100644 --- a/production/helm/loki/templates/index-gateway/service-index-gateway.yaml +++ b/production/helm/loki/templates/index-gateway/service-index-gateway.yaml @@ -4,6 +4,7 @@ apiVersion: v1 kind: Service metadata: name: {{ include "loki.indexGatewayFullname" . }} + namespace: {{ $.Release.Namespace }} labels: {{- include "loki.indexGatewayLabels" . | nindent 4 }} {{- with .Values.indexGateway.serviceLabels }} diff --git a/production/helm/loki/templates/index-gateway/statefulset-index-gateway.yaml b/production/helm/loki/templates/index-gateway/statefulset-index-gateway.yaml index 8688a55bcb8f9..e249859005456 100644 --- a/production/helm/loki/templates/index-gateway/statefulset-index-gateway.yaml +++ b/production/helm/loki/templates/index-gateway/statefulset-index-gateway.yaml @@ -4,6 +4,7 @@ apiVersion: apps/v1 kind: StatefulSet metadata: name: {{ include "loki.indexGatewayFullname" . }} + namespace: {{ $.Release.Namespace }} labels: {{- include "loki.indexGatewayLabels" . | nindent 4 }} {{- with .Values.loki.annotations }} diff --git a/production/helm/loki/templates/ruler/configmap-ruler.yaml b/production/helm/loki/templates/ruler/configmap-ruler.yaml index b74f024b415f3..3a0c53397ccc9 100644 --- a/production/helm/loki/templates/ruler/configmap-ruler.yaml +++ b/production/helm/loki/templates/ruler/configmap-ruler.yaml @@ -6,6 +6,7 @@ apiVersion: v1 kind: ConfigMap metadata: name: {{ include "loki.rulerFullname" $ }}-{{ include "loki.rulerRulesDirName" $dir }} + namespace: {{ $.Release.Namespace }} labels: {{- include "loki.rulerLabels" $ | nindent 4 }} data: diff --git a/production/helm/loki/templates/ruler/poddisruptionbudget-ruler.yaml b/production/helm/loki/templates/ruler/poddisruptionbudget-ruler.yaml index 82417651862dd..b9c03cf12d34f 100644 --- a/production/helm/loki/templates/ruler/poddisruptionbudget-ruler.yaml +++ b/production/helm/loki/templates/ruler/poddisruptionbudget-ruler.yaml @@ -7,6 +7,7 @@ apiVersion: {{ include "loki.pdb.apiVersion" . }} kind: PodDisruptionBudget metadata: name: {{ include "loki.rulerFullname" . }} + namespace: {{ $.Release.Namespace }} labels: {{- include "loki.rulerLabels" . | nindent 4 }} spec: diff --git a/production/helm/loki/templates/ruler/service-ruler.yaml b/production/helm/loki/templates/ruler/service-ruler.yaml index 4d58ec85b42ad..88476832da1c4 100644 --- a/production/helm/loki/templates/ruler/service-ruler.yaml +++ b/production/helm/loki/templates/ruler/service-ruler.yaml @@ -4,6 +4,7 @@ apiVersion: v1 kind: Service metadata: name: {{ include "loki.rulerFullname" . }} + namespace: {{ $.Release.Namespace }} labels: {{- include "loki.rulerSelectorLabels" . | nindent 4 }} {{- with .Values.ruler.serviceLabels }} diff --git a/production/helm/loki/templates/ruler/statefulset-ruler.yaml b/production/helm/loki/templates/ruler/statefulset-ruler.yaml index cff41890f01ce..87b42f2219e7f 100644 --- a/production/helm/loki/templates/ruler/statefulset-ruler.yaml +++ b/production/helm/loki/templates/ruler/statefulset-ruler.yaml @@ -4,6 +4,7 @@ apiVersion: apps/v1 kind: StatefulSet metadata: name: {{ include "loki.rulerFullname" . }} + namespace: {{ $.Release.Namespace }} labels: {{- include "loki.rulerLabels" . | nindent 4 }} app.kubernetes.io/part-of: memberlist diff --git a/production/helm/loki/values.yaml b/production/helm/loki/values.yaml index 9ab4de54ba204..78961a7243009 100644 --- a/production/helm/loki/values.yaml +++ b/production/helm/loki/values.yaml @@ -56,7 +56,7 @@ loki: # -- Docker image repository repository: grafana/loki # -- Overrides the image tag whose default is the chart's appVersion - tag: null + tag: 3.3.0 # -- Overrides the image tag with an image digest digest: null # -- Docker image pull policy @@ -518,7 +518,7 @@ enterprise: # -- Docker image repository repository: grafana/enterprise-logs # -- Docker image tag - tag: null + tag: 3.3.0 # -- Overrides the image tag with an image digest digest: null # -- Docker image pull policy diff --git a/vendor/github.com/grpc-ecosystem/go-grpc-middleware/.gitignore b/vendor/github.com/grpc-ecosystem/go-grpc-middleware/.gitignore deleted file mode 100644 index 826caa3902bb8..0000000000000 --- a/vendor/github.com/grpc-ecosystem/go-grpc-middleware/.gitignore +++ /dev/null @@ -1,204 +0,0 @@ -# Created by .ignore support plugin (hsz.mobi) -### Go template -# Compiled Object files, Static and Dynamic libs (Shared Objects) -*.o -*.a -*.so - -# Folders -_obj -_test - -# Architecture specific extensions/prefixes -*.[568vq] -[568vq].out - -*.cgo1.go -*.cgo2.c -_cgo_defun.c -_cgo_gotypes.go -_cgo_export.* - -_testmain.go - -*.exe -*.test -*.prof -### Windows template -# Windows image file caches -Thumbs.db -ehthumbs.db - -# Folder config file -Desktop.ini - -# Recycle Bin used on file shares -$RECYCLE.BIN/ - -# Windows Installer files -*.cab -*.msi -*.msm -*.msp - -# Windows shortcuts -*.lnk -### Kate template -# Swap Files # -.*.kate-swp -.swp.* -### SublimeText template -# cache files for sublime text -*.tmlanguage.cache -*.tmPreferences.cache -*.stTheme.cache - -# workspace files are user-specific -*.sublime-workspace - -# project files should be checked into the repository, unless a significant -# proportion of contributors will probably not be using SublimeText -# *.sublime-project - -# sftp configuration file -sftp-config.json -### Linux template -*~ - -# temporary files which can be created if a process still has a handle open of a deleted file -.fuse_hidden* - -# KDE directory preferences -.directory - -# Linux trash folder which might appear on any partition or disk -.Trash-* -### JetBrains template -# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and Webstorm -# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 - -# User-specific stuff: -.idea -.idea/tasks.xml -.idea/dictionaries -.idea/vcs.xml -.idea/jsLibraryMappings.xml - -# Sensitive or high-churn files: -.idea/dataSources.ids -.idea/dataSources.xml -.idea/dataSources.local.xml -.idea/sqlDataSources.xml -.idea/dynamic.xml -.idea/uiDesigner.xml - -# Gradle: -.idea/gradle.xml -.idea/libraries - -# Mongo Explorer plugin: -.idea/mongoSettings.xml - -## File-based project format: -*.iws - -## Plugin-specific files: - -# IntelliJ -/out/ - -# mpeltonen/sbt-idea plugin -.idea_modules/ - -# JIRA plugin -atlassian-ide-plugin.xml - -# Crashlytics plugin (for Android Studio and IntelliJ) -com_crashlytics_export_strings.xml -crashlytics.properties -crashlytics-build.properties -fabric.properties -### Xcode template -# Xcode -# -# gitignore contributors: remember to update Global/Xcode.gitignore, Objective-C.gitignore & Swift.gitignore - -## Build generated -build/ -DerivedData/ - -## Various settings -*.pbxuser -!default.pbxuser -*.mode1v3 -!default.mode1v3 -*.mode2v3 -!default.mode2v3 -*.perspectivev3 -!default.perspectivev3 -xcuserdata/ - -## Other -*.moved-aside -*.xccheckout -*.xcscmblueprint -### Eclipse template - -.metadata -bin/ -tmp/ -*.tmp -*.bak -*.swp -*~.nib -local.properties -.settings/ -.loadpath -.recommenders - -# Eclipse Core -.project - -# External tool builders -.externalToolBuilders/ - -# Locally stored "Eclipse launch configurations" -*.launch - -# PyDev specific (Python IDE for Eclipse) -*.pydevproject - -# CDT-specific (C/C++ Development Tooling) -.cproject - -# JDT-specific (Eclipse Java Development Tools) -.classpath - -# Java annotation processor (APT) -.factorypath - -# PDT-specific (PHP Development Tools) -.buildpath - -# sbteclipse plugin -.target - -# Tern plugin -.tern-project - -# TeXlipse plugin -.texlipse - -# STS (Spring Tool Suite) -.springBeans - -# Code Recommenders -.recommenders/ - - -coverage.txt - -#vendor -vendor/ - -.envrc \ No newline at end of file diff --git a/vendor/github.com/grpc-ecosystem/go-grpc-middleware/CONTRIBUTING.md b/vendor/github.com/grpc-ecosystem/go-grpc-middleware/CONTRIBUTING.md deleted file mode 100644 index dd52ab8938e05..0000000000000 --- a/vendor/github.com/grpc-ecosystem/go-grpc-middleware/CONTRIBUTING.md +++ /dev/null @@ -1,20 +0,0 @@ -# Contributing - -We would love to have people submit pull requests and help make `grpc-ecosystem/go-grpc-middleware` even better 👍. - -Fork, then clone the repo: - -```bash -git clone git@github.com:your-username/go-grpc-middleware.git -``` - -Before checking in please run the following: - -```bash -make all -``` - -This will `vet`, `fmt`, regenerate documentation and run all tests. - - -Push to your fork and open a pull request. \ No newline at end of file diff --git a/vendor/github.com/grpc-ecosystem/go-grpc-middleware/README.md b/vendor/github.com/grpc-ecosystem/go-grpc-middleware/README.md deleted file mode 100644 index a12b40904bc26..0000000000000 --- a/vendor/github.com/grpc-ecosystem/go-grpc-middleware/README.md +++ /dev/null @@ -1,93 +0,0 @@ -# Go gRPC Middleware - -[![Travis Build](https://travis-ci.org/grpc-ecosystem/go-grpc-middleware.svg?branch=master)](https://travis-ci.org/grpc-ecosystem/go-grpc-middleware) -[![Go Report Card](https://goreportcard.com/badge/github.com/grpc-ecosystem/go-grpc-middleware)](https://goreportcard.com/report/github.com/grpc-ecosystem/go-grpc-middleware) -[![GoDoc](http://img.shields.io/badge/GoDoc-Reference-blue.svg)](https://godoc.org/github.com/grpc-ecosystem/go-grpc-middleware) -[![SourceGraph](https://sourcegraph.com/github.com/grpc-ecosystem/go-grpc-middleware/-/badge.svg)](https://sourcegraph.com/github.com/grpc-ecosystem/go-grpc-middleware/?badge) -[![codecov](https://codecov.io/gh/grpc-ecosystem/go-grpc-middleware/branch/master/graph/badge.svg)](https://codecov.io/gh/grpc-ecosystem/go-grpc-middleware) -[![Apache 2.0 License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](LICENSE) -[![quality: production](https://img.shields.io/badge/quality-production-orange.svg)](#status) -[![Slack](https://img.shields.io/badge/slack-%23grpc--middleware-brightgreen)](https://gophers.slack.com/archives/CNJL30P4P) - -[gRPC Go](https://github.com/grpc/grpc-go) Middleware: interceptors, helpers, utilities. - -## ⚠️ Status - -Version [v2](https://github.com/grpc-ecosystem/go-grpc-middleware/tree/v2) is about to be released, with migration guide, which will replace v1. Try v2 and give us feedback! - -Version v1 is currently in deprecation mode, which means only critical and safety bug fixes will be merged. - - -## Middleware - -[gRPC Go](https://github.com/grpc/grpc-go) recently acquired support for -Interceptors, i.e. [middleware](https://medium.com/@matryer/writing-middleware-in-golang-and-how-go-makes-it-so-much-fun-4375c1246e81#.gv7tdlghs) -that is executed either on the gRPC Server before the request is passed onto the user's application logic, or on the gRPC client around the user call. It is a perfect way to implement -common patterns: auth, logging, message, validation, retries, or monitoring. - -These are generic building blocks that make it easy to build multiple microservices easily. -The purpose of this repository is to act as a go-to point for such reusable functionality. It contains -some of them itself, but also will link to useful external repos. - -`grpc_middleware` itself provides support for chaining interceptors, here's an example: - -```go -import "github.com/grpc-ecosystem/go-grpc-middleware" - -myServer := grpc.NewServer( - grpc.StreamInterceptor(grpc_middleware.ChainStreamServer( - grpc_ctxtags.StreamServerInterceptor(), - grpc_opentracing.StreamServerInterceptor(), - grpc_prometheus.StreamServerInterceptor, - grpc_zap.StreamServerInterceptor(zapLogger), - grpc_auth.StreamServerInterceptor(myAuthFunction), - grpc_recovery.StreamServerInterceptor(), - )), - grpc.UnaryInterceptor(grpc_middleware.ChainUnaryServer( - grpc_ctxtags.UnaryServerInterceptor(), - grpc_opentracing.UnaryServerInterceptor(), - grpc_prometheus.UnaryServerInterceptor, - grpc_zap.UnaryServerInterceptor(zapLogger), - grpc_auth.UnaryServerInterceptor(myAuthFunction), - grpc_recovery.UnaryServerInterceptor(), - )), -) -``` - -## Interceptors - -_Please send a PR to add new interceptors or middleware to this list_ - -#### Auth - -- [`grpc_auth`](auth) - a customizable (via `AuthFunc`) piece of auth middleware - -#### Logging - -- [`grpc_ctxtags`](tags/) - a library that adds a `Tag` map to context, with data populated from request body -- [`grpc_zap`](logging/zap/) - integration of [zap](https://github.com/uber-go/zap) logging library into gRPC handlers. -- [`grpc_logrus`](logging/logrus/) - integration of [logrus](https://github.com/sirupsen/logrus) logging library into gRPC handlers. -- [`grpc_kit`](logging/kit/) - integration of [go-kit/log](https://github.com/go-kit/log) logging library into gRPC handlers. -- [`grpc_grpc_logsettable`](logging/settable/) - a wrapper around `grpclog.LoggerV2` that allows to replace loggers in runtime (thread-safe). - -#### Monitoring - -- [`grpc_prometheus`⚡](https://github.com/grpc-ecosystem/go-grpc-prometheus) - Prometheus client-side and server-side monitoring middleware -- [`otgrpc`⚡](https://github.com/grpc-ecosystem/grpc-opentracing/tree/master/go/otgrpc) - [OpenTracing](http://opentracing.io/) client-side and server-side interceptors -- [`grpc_opentracing`](tracing/opentracing) - [OpenTracing](http://opentracing.io/) client-side and server-side interceptors with support for streaming and handler-returned tags -- [`otelgrpc`](https://github.com/open-telemetry/opentelemetry-go-contrib/tree/main/instrumentation/google.golang.org/grpc/otelgrpc) - [OpenTelemetry](https://opentelemetry.io/) client-side and server-side interceptors - -#### Client - -- [`grpc_retry`](retry/) - a generic gRPC response code retry mechanism, client-side middleware - -#### Server - -- [`grpc_validator`](validator/) - codegen inbound message validation from `.proto` options -- [`grpc_recovery`](recovery/) - turn panics into gRPC errors -- [`ratelimit`](ratelimit/) - grpc rate limiting by your own limiter - - -## License - -`go-grpc-middleware` is released under the Apache 2.0 license. See the [LICENSE](LICENSE) file for details. diff --git a/vendor/github.com/grpc-ecosystem/go-grpc-middleware/chain.go b/vendor/github.com/grpc-ecosystem/go-grpc-middleware/chain.go deleted file mode 100644 index 407d9332c9b00..0000000000000 --- a/vendor/github.com/grpc-ecosystem/go-grpc-middleware/chain.go +++ /dev/null @@ -1,166 +0,0 @@ -// Copyright 2016 Michal Witkowski. All Rights Reserved. -// See LICENSE for licensing terms. - -// gRPC Server Interceptor chaining middleware. - -package grpc_middleware - -import ( - "context" - - "google.golang.org/grpc" -) - -// ChainUnaryServer creates a single interceptor out of a chain of many interceptors. -// -// Execution is done in left-to-right order, including passing of context. -// For example ChainUnaryServer(one, two, three) will execute one before two before three, and three -// will see context changes of one and two. -// -// While this can be useful in some scenarios, it is generally advisable to use google.golang.org/grpc.ChainUnaryInterceptor directly. -func ChainUnaryServer(interceptors ...grpc.UnaryServerInterceptor) grpc.UnaryServerInterceptor { - n := len(interceptors) - - // Dummy interceptor maintained for backward compatibility to avoid returning nil. - if n == 0 { - return func(ctx context.Context, req interface{}, _ *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) { - return handler(ctx, req) - } - } - - // The degenerate case, just return the single wrapped interceptor directly. - if n == 1 { - return interceptors[0] - } - - // Return a function which satisfies the interceptor interface, and which is - // a closure over the given list of interceptors to be chained. - return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) { - currHandler := handler - // Iterate backwards through all interceptors except the first (outermost). - // Wrap each one in a function which satisfies the handler interface, but - // is also a closure over the `info` and `handler` parameters. Then pass - // each pseudo-handler to the next outer interceptor as the handler to be called. - for i := n - 1; i > 0; i-- { - // Rebind to loop-local vars so they can be closed over. - innerHandler, i := currHandler, i - currHandler = func(currentCtx context.Context, currentReq interface{}) (interface{}, error) { - return interceptors[i](currentCtx, currentReq, info, innerHandler) - } - } - // Finally return the result of calling the outermost interceptor with the - // outermost pseudo-handler created above as its handler. - return interceptors[0](ctx, req, info, currHandler) - } -} - -// ChainStreamServer creates a single interceptor out of a chain of many interceptors. -// -// Execution is done in left-to-right order, including passing of context. -// For example ChainUnaryServer(one, two, three) will execute one before two before three. -// If you want to pass context between interceptors, use WrapServerStream. -// -// While this can be useful in some scenarios, it is generally advisable to use google.golang.org/grpc.ChainStreamInterceptor directly. -func ChainStreamServer(interceptors ...grpc.StreamServerInterceptor) grpc.StreamServerInterceptor { - n := len(interceptors) - - // Dummy interceptor maintained for backward compatibility to avoid returning nil. - if n == 0 { - return func(srv interface{}, stream grpc.ServerStream, _ *grpc.StreamServerInfo, handler grpc.StreamHandler) error { - return handler(srv, stream) - } - } - - if n == 1 { - return interceptors[0] - } - - return func(srv interface{}, stream grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error { - currHandler := handler - for i := n - 1; i > 0; i-- { - innerHandler, i := currHandler, i - currHandler = func(currentSrv interface{}, currentStream grpc.ServerStream) error { - return interceptors[i](currentSrv, currentStream, info, innerHandler) - } - } - return interceptors[0](srv, stream, info, currHandler) - } -} - -// ChainUnaryClient creates a single interceptor out of a chain of many interceptors. -// -// Execution is done in left-to-right order, including passing of context. -// For example ChainUnaryClient(one, two, three) will execute one before two before three. -func ChainUnaryClient(interceptors ...grpc.UnaryClientInterceptor) grpc.UnaryClientInterceptor { - n := len(interceptors) - - // Dummy interceptor maintained for backward compatibility to avoid returning nil. - if n == 0 { - return func(ctx context.Context, method string, req, reply interface{}, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error { - return invoker(ctx, method, req, reply, cc, opts...) - } - } - - if n == 1 { - return interceptors[0] - } - - return func(ctx context.Context, method string, req, reply interface{}, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error { - currInvoker := invoker - for i := n - 1; i > 0; i-- { - innerInvoker, i := currInvoker, i - currInvoker = func(currentCtx context.Context, currentMethod string, currentReq, currentRepl interface{}, currentConn *grpc.ClientConn, currentOpts ...grpc.CallOption) error { - return interceptors[i](currentCtx, currentMethod, currentReq, currentRepl, currentConn, innerInvoker, currentOpts...) - } - } - return interceptors[0](ctx, method, req, reply, cc, currInvoker, opts...) - } -} - -// ChainStreamClient creates a single interceptor out of a chain of many interceptors. -// -// Execution is done in left-to-right order, including passing of context. -// For example ChainStreamClient(one, two, three) will execute one before two before three. -func ChainStreamClient(interceptors ...grpc.StreamClientInterceptor) grpc.StreamClientInterceptor { - n := len(interceptors) - - // Dummy interceptor maintained for backward compatibility to avoid returning nil. - if n == 0 { - return func(ctx context.Context, desc *grpc.StreamDesc, cc *grpc.ClientConn, method string, streamer grpc.Streamer, opts ...grpc.CallOption) (grpc.ClientStream, error) { - return streamer(ctx, desc, cc, method, opts...) - } - } - - if n == 1 { - return interceptors[0] - } - - return func(ctx context.Context, desc *grpc.StreamDesc, cc *grpc.ClientConn, method string, streamer grpc.Streamer, opts ...grpc.CallOption) (grpc.ClientStream, error) { - currStreamer := streamer - for i := n - 1; i > 0; i-- { - innerStreamer, i := currStreamer, i - currStreamer = func(currentCtx context.Context, currentDesc *grpc.StreamDesc, currentConn *grpc.ClientConn, currentMethod string, currentOpts ...grpc.CallOption) (grpc.ClientStream, error) { - return interceptors[i](currentCtx, currentDesc, currentConn, currentMethod, innerStreamer, currentOpts...) - } - } - return interceptors[0](ctx, desc, cc, method, currStreamer, opts...) - } -} - -// Chain creates a single interceptor out of a chain of many interceptors. -// -// WithUnaryServerChain is a grpc.Server config option that accepts multiple unary interceptors. -// Basically syntactic sugar. -// -// Deprecated: use google.golang.org/grpc.ChainUnaryInterceptor instead. -func WithUnaryServerChain(interceptors ...grpc.UnaryServerInterceptor) grpc.ServerOption { - return grpc.ChainUnaryInterceptor(interceptors...) -} - -// WithStreamServerChain is a grpc.Server config option that accepts multiple stream interceptors. -// Basically syntactic sugar. -// -// Deprecated: use google.golang.org/grpc.ChainStreamInterceptor instead. -func WithStreamServerChain(interceptors ...grpc.StreamServerInterceptor) grpc.ServerOption { - return grpc.ChainStreamInterceptor(interceptors...) -} diff --git a/vendor/github.com/grpc-ecosystem/go-grpc-middleware/doc.go b/vendor/github.com/grpc-ecosystem/go-grpc-middleware/doc.go deleted file mode 100644 index 718e10046a224..0000000000000 --- a/vendor/github.com/grpc-ecosystem/go-grpc-middleware/doc.go +++ /dev/null @@ -1,69 +0,0 @@ -// Copyright 2016 Michal Witkowski. All Rights Reserved. -// See LICENSE for licensing terms. - -/* -`grpc_middleware` is a collection of gRPC middleware packages: interceptors, helpers and tools. - -Middleware - -gRPC is a fantastic RPC middleware, which sees a lot of adoption in the Golang world. However, the -upstream gRPC codebase is relatively bare bones. - -This package, and most of its child packages provides commonly needed middleware for gRPC: -client-side interceptors for retires, server-side interceptors for input validation and auth, -functions for chaining said interceptors, metadata convenience methods and more. - -Chaining - -By default, gRPC doesn't allow one to have more than one interceptor either on the client nor on -the server side. `grpc_middleware` provides convenient chaining methods - -Simple way of turning a multiple interceptors into a single interceptor. Here's an example for -server chaining: - - myServer := grpc.NewServer( - grpc.StreamInterceptor(grpc_middleware.ChainStreamServer(loggingStream, monitoringStream, authStream)), - grpc.UnaryInterceptor(grpc_middleware.ChainUnaryServer(loggingUnary, monitoringUnary, authUnary)), - ) - -These interceptors will be executed from left to right: logging, monitoring and auth. - -Here's an example for client side chaining: - - clientConn, err = grpc.Dial( - address, - grpc.WithUnaryInterceptor(grpc_middleware.ChainUnaryClient(monitoringClientUnary, retryUnary)), - grpc.WithStreamInterceptor(grpc_middleware.ChainStreamClient(monitoringClientStream, retryStream)), - ) - client = pb_testproto.NewTestServiceClient(clientConn) - resp, err := client.PingEmpty(s.ctx, &myservice.Request{Msg: "hello"}) - -These interceptors will be executed from left to right: monitoring and then retry logic. - -The retry interceptor will call every interceptor that follows it whenever when a retry happens. - -Writing Your Own - -Implementing your own interceptor is pretty trivial: there are interfaces for that. But the interesting -bit exposing common data to handlers (and other middleware), similarly to HTTP Middleware design. -For example, you may want to pass the identity of the caller from the auth interceptor all the way -to the handling function. - -For example, a client side interceptor example for auth looks like: - - func FakeAuthUnaryInterceptor(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) { - newCtx := context.WithValue(ctx, "user_id", "john@example.com") - return handler(newCtx, req) - } - -Unfortunately, it's not as easy for streaming RPCs. These have the `context.Context` embedded within -the `grpc.ServerStream` object. To pass values through context, a wrapper (`WrappedServerStream`) is -needed. For example: - - func FakeAuthStreamingInterceptor(srv interface{}, stream grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error { - newStream := grpc_middleware.WrapServerStream(stream) - newStream.WrappedContext = context.WithValue(ctx, "user_id", "john@example.com") - return handler(srv, newStream) - } -*/ -package grpc_middleware diff --git a/vendor/github.com/grpc-ecosystem/go-grpc-middleware/makefile b/vendor/github.com/grpc-ecosystem/go-grpc-middleware/makefile deleted file mode 100644 index b18d2d2bb1199..0000000000000 --- a/vendor/github.com/grpc-ecosystem/go-grpc-middleware/makefile +++ /dev/null @@ -1,17 +0,0 @@ -SHELL=/bin/bash - -GOFILES_NOVENDOR = $(shell go list ./... | grep -v /vendor/) - -all: vet fmt test - -fmt: - go fmt $(GOFILES_NOVENDOR) - -vet: - # do not check lostcancel, they are intentional. - go vet -lostcancel=false $(GOFILES_NOVENDOR) - -test: vet - ./scripts/test_all.sh - -.PHONY: all test diff --git a/vendor/github.com/grpc-ecosystem/go-grpc-middleware/recovery/interceptors.go b/vendor/github.com/grpc-ecosystem/go-grpc-middleware/recovery/interceptors.go deleted file mode 100644 index 15ee54da651bf..0000000000000 --- a/vendor/github.com/grpc-ecosystem/go-grpc-middleware/recovery/interceptors.go +++ /dev/null @@ -1,62 +0,0 @@ -// Copyright 2017 David Ackroyd. All Rights Reserved. -// See LICENSE for licensing terms. - -package grpc_recovery - -import ( - "context" - - "google.golang.org/grpc" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/status" -) - -// RecoveryHandlerFunc is a function that recovers from the panic `p` by returning an `error`. -type RecoveryHandlerFunc func(p interface{}) (err error) - -// RecoveryHandlerFuncContext is a function that recovers from the panic `p` by returning an `error`. -// The context can be used to extract request scoped metadata and context values. -type RecoveryHandlerFuncContext func(ctx context.Context, p interface{}) (err error) - -// UnaryServerInterceptor returns a new unary server interceptor for panic recovery. -func UnaryServerInterceptor(opts ...Option) grpc.UnaryServerInterceptor { - o := evaluateOptions(opts) - return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (_ interface{}, err error) { - panicked := true - - defer func() { - if r := recover(); r != nil || panicked { - err = recoverFrom(ctx, r, o.recoveryHandlerFunc) - } - }() - - resp, err := handler(ctx, req) - panicked = false - return resp, err - } -} - -// StreamServerInterceptor returns a new streaming server interceptor for panic recovery. -func StreamServerInterceptor(opts ...Option) grpc.StreamServerInterceptor { - o := evaluateOptions(opts) - return func(srv interface{}, stream grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) (err error) { - panicked := true - - defer func() { - if r := recover(); r != nil || panicked { - err = recoverFrom(stream.Context(), r, o.recoveryHandlerFunc) - } - }() - - err = handler(srv, stream) - panicked = false - return err - } -} - -func recoverFrom(ctx context.Context, p interface{}, r RecoveryHandlerFuncContext) error { - if r == nil { - return status.Errorf(codes.Internal, "%v", p) - } - return r(ctx, p) -} diff --git a/vendor/github.com/grpc-ecosystem/go-grpc-middleware/slack.png b/vendor/github.com/grpc-ecosystem/go-grpc-middleware/slack.png deleted file mode 100644 index cc8f9a68a9368..0000000000000 Binary files a/vendor/github.com/grpc-ecosystem/go-grpc-middleware/slack.png and /dev/null differ diff --git a/vendor/github.com/grpc-ecosystem/go-grpc-middleware/v2/COPYRIGHT b/vendor/github.com/grpc-ecosystem/go-grpc-middleware/v2/COPYRIGHT new file mode 100644 index 0000000000000..3b13627cdbb65 --- /dev/null +++ b/vendor/github.com/grpc-ecosystem/go-grpc-middleware/v2/COPYRIGHT @@ -0,0 +1,2 @@ +Copyright (c) The go-grpc-middleware Authors. +Licensed under the Apache License 2.0. diff --git a/vendor/github.com/grpc-ecosystem/go-grpc-middleware/LICENSE b/vendor/github.com/grpc-ecosystem/go-grpc-middleware/v2/LICENSE similarity index 100% rename from vendor/github.com/grpc-ecosystem/go-grpc-middleware/LICENSE rename to vendor/github.com/grpc-ecosystem/go-grpc-middleware/v2/LICENSE diff --git a/vendor/github.com/grpc-ecosystem/go-grpc-middleware/recovery/doc.go b/vendor/github.com/grpc-ecosystem/go-grpc-middleware/v2/interceptors/recovery/doc.go similarity index 50% rename from vendor/github.com/grpc-ecosystem/go-grpc-middleware/recovery/doc.go rename to vendor/github.com/grpc-ecosystem/go-grpc-middleware/v2/interceptors/recovery/doc.go index 2806de5e28fef..78021207902a5 100644 --- a/vendor/github.com/grpc-ecosystem/go-grpc-middleware/recovery/doc.go +++ b/vendor/github.com/grpc-ecosystem/go-grpc-middleware/v2/interceptors/recovery/doc.go @@ -1,10 +1,15 @@ +// Copyright (c) The go-grpc-middleware Authors. +// Licensed under the Apache License 2.0. + // Copyright 2017 David Ackroyd. All Rights Reserved. // See LICENSE for licensing terms. /* -`grpc_recovery` are interceptors that recover from gRPC handler panics. +Package recovery is a middleware that recovers from panics and logs the panic message. + +`recovery` are interceptors that recover from gRPC handler panics. -Server Side Recovery Middleware +# Server Side Recovery Middleware By default a panic will be converted into a gRPC error with `code.Internal`. @@ -12,4 +17,4 @@ Handling can be customised by providing an alternate recovery function. Please see examples for simple examples of use. */ -package grpc_recovery +package recovery diff --git a/vendor/github.com/grpc-ecosystem/go-grpc-middleware/v2/interceptors/recovery/interceptors.go b/vendor/github.com/grpc-ecosystem/go-grpc-middleware/v2/interceptors/recovery/interceptors.go new file mode 100644 index 0000000000000..6f0c8ffcd2169 --- /dev/null +++ b/vendor/github.com/grpc-ecosystem/go-grpc-middleware/v2/interceptors/recovery/interceptors.go @@ -0,0 +1,68 @@ +// Copyright (c) The go-grpc-middleware Authors. +// Licensed under the Apache License 2.0. + +// Copyright 2017 David Ackroyd. All Rights Reserved. +// See LICENSE for licensing terms. + +package recovery + +import ( + "context" + "fmt" + "runtime" + + "google.golang.org/grpc" +) + +// RecoveryHandlerFunc is a function that recovers from the panic `p` by returning an `error`. +type RecoveryHandlerFunc func(p any) (err error) + +// RecoveryHandlerFuncContext is a function that recovers from the panic `p` by returning an `error`. +// The context can be used to extract request scoped metadata and context values. +type RecoveryHandlerFuncContext func(ctx context.Context, p any) (err error) + +// UnaryServerInterceptor returns a new unary server interceptor for panic recovery. +func UnaryServerInterceptor(opts ...Option) grpc.UnaryServerInterceptor { + o := evaluateOptions(opts) + return func(ctx context.Context, req any, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (_ any, err error) { + defer func() { + if r := recover(); r != nil { + err = recoverFrom(ctx, r, o.recoveryHandlerFunc) + } + }() + + return handler(ctx, req) + } +} + +// StreamServerInterceptor returns a new streaming server interceptor for panic recovery. +func StreamServerInterceptor(opts ...Option) grpc.StreamServerInterceptor { + o := evaluateOptions(opts) + return func(srv any, stream grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) (err error) { + defer func() { + if r := recover(); r != nil { + err = recoverFrom(stream.Context(), r, o.recoveryHandlerFunc) + } + }() + + return handler(srv, stream) + } +} + +func recoverFrom(ctx context.Context, p any, r RecoveryHandlerFuncContext) error { + if r != nil { + return r(ctx, p) + } + stack := make([]byte, 64<<10) + stack = stack[:runtime.Stack(stack, false)] + return &PanicError{Panic: p, Stack: stack} +} + +type PanicError struct { + Panic any + Stack []byte +} + +func (e *PanicError) Error() string { + return fmt.Sprintf("panic caught: %v\n\n%s", e.Panic, e.Stack) +} diff --git a/vendor/github.com/grpc-ecosystem/go-grpc-middleware/recovery/options.go b/vendor/github.com/grpc-ecosystem/go-grpc-middleware/v2/interceptors/recovery/options.go similarity index 86% rename from vendor/github.com/grpc-ecosystem/go-grpc-middleware/recovery/options.go rename to vendor/github.com/grpc-ecosystem/go-grpc-middleware/v2/interceptors/recovery/options.go index ffe9c64c7d85e..2c55d68cc4fdd 100644 --- a/vendor/github.com/grpc-ecosystem/go-grpc-middleware/recovery/options.go +++ b/vendor/github.com/grpc-ecosystem/go-grpc-middleware/v2/interceptors/recovery/options.go @@ -1,7 +1,10 @@ +// Copyright (c) The go-grpc-middleware Authors. +// Licensed under the Apache License 2.0. + // Copyright 2017 David Ackroyd. All Rights Reserved. // See LICENSE for licensing terms. -package grpc_recovery +package recovery import "context" @@ -29,7 +32,7 @@ type Option func(*options) // WithRecoveryHandler customizes the function for recovering from a panic. func WithRecoveryHandler(f RecoveryHandlerFunc) Option { return func(o *options) { - o.recoveryHandlerFunc = RecoveryHandlerFuncContext(func(ctx context.Context, p interface{}) error { + o.recoveryHandlerFunc = RecoveryHandlerFuncContext(func(ctx context.Context, p any) error { return f(p) }) } diff --git a/vendor/github.com/grpc-ecosystem/go-grpc-middleware/wrappers.go b/vendor/github.com/grpc-ecosystem/go-grpc-middleware/wrappers.go deleted file mode 100644 index 05ccfb3f24a79..0000000000000 --- a/vendor/github.com/grpc-ecosystem/go-grpc-middleware/wrappers.go +++ /dev/null @@ -1,30 +0,0 @@ -// Copyright 2016 Michal Witkowski. All Rights Reserved. -// See LICENSE for licensing terms. - -package grpc_middleware - -import ( - "context" - - "google.golang.org/grpc" -) - -// WrappedServerStream is a thin wrapper around grpc.ServerStream that allows modifying context. -type WrappedServerStream struct { - grpc.ServerStream - // WrappedContext is the wrapper's own Context. You can assign it. - WrappedContext context.Context -} - -// Context returns the wrapper's WrappedContext, overwriting the nested grpc.ServerStream.Context() -func (w *WrappedServerStream) Context() context.Context { - return w.WrappedContext -} - -// WrapServerStream returns a ServerStream that has the ability to overwrite context. -func WrapServerStream(stream grpc.ServerStream) *WrappedServerStream { - if existing, ok := stream.(*WrappedServerStream); ok { - return existing - } - return &WrappedServerStream{ServerStream: stream, WrappedContext: stream.Context()} -} diff --git a/vendor/github.com/sony/gobreaker/README.md b/vendor/github.com/sony/gobreaker/README.md deleted file mode 100644 index bbc23769d6e90..0000000000000 --- a/vendor/github.com/sony/gobreaker/README.md +++ /dev/null @@ -1,132 +0,0 @@ -gobreaker -========= - -[![GoDoc](https://godoc.org/github.com/sony/gobreaker?status.svg)](http://godoc.org/github.com/sony/gobreaker) - -[gobreaker][repo-url] implements the [Circuit Breaker pattern](https://msdn.microsoft.com/en-us/library/dn589784.aspx) in Go. - -Installation ------------- - -``` -go get github.com/sony/gobreaker -``` - -Usage ------ - -The struct `CircuitBreaker` is a state machine to prevent sending requests that are likely to fail. -The function `NewCircuitBreaker` creates a new `CircuitBreaker`. - -```go -func NewCircuitBreaker(st Settings) *CircuitBreaker -``` - -You can configure `CircuitBreaker` by the struct `Settings`: - -```go -type Settings struct { - Name string - MaxRequests uint32 - Interval time.Duration - Timeout time.Duration - ReadyToTrip func(counts Counts) bool - OnStateChange func(name string, from State, to State) - IsSuccessful func(err error) bool -} -``` - -- `Name` is the name of the `CircuitBreaker`. - -- `MaxRequests` is the maximum number of requests allowed to pass through - when the `CircuitBreaker` is half-open. - If `MaxRequests` is 0, `CircuitBreaker` allows only 1 request. - -- `Interval` is the cyclic period of the closed state - for `CircuitBreaker` to clear the internal `Counts`, described later in this section. - If `Interval` is 0, `CircuitBreaker` doesn't clear the internal `Counts` during the closed state. - -- `Timeout` is the period of the open state, - after which the state of `CircuitBreaker` becomes half-open. - If `Timeout` is 0, the timeout value of `CircuitBreaker` is set to 60 seconds. - -- `ReadyToTrip` is called with a copy of `Counts` whenever a request fails in the closed state. - If `ReadyToTrip` returns true, `CircuitBreaker` will be placed into the open state. - If `ReadyToTrip` is `nil`, default `ReadyToTrip` is used. - Default `ReadyToTrip` returns true when the number of consecutive failures is more than 5. - -- `OnStateChange` is called whenever the state of `CircuitBreaker` changes. - -- `IsSuccessful` is called with the error returned from a request. - If `IsSuccessful` returns true, the error is counted as a success. - Otherwise the error is counted as a failure. - If `IsSuccessful` is nil, default `IsSuccessful` is used, which returns false for all non-nil errors. - -The struct `Counts` holds the numbers of requests and their successes/failures: - -```go -type Counts struct { - Requests uint32 - TotalSuccesses uint32 - TotalFailures uint32 - ConsecutiveSuccesses uint32 - ConsecutiveFailures uint32 -} -``` - -`CircuitBreaker` clears the internal `Counts` either -on the change of the state or at the closed-state intervals. -`Counts` ignores the results of the requests sent before clearing. - -`CircuitBreaker` can wrap any function to send a request: - -```go -func (cb *CircuitBreaker) Execute(req func() (interface{}, error)) (interface{}, error) -``` - -The method `Execute` runs the given request if `CircuitBreaker` accepts it. -`Execute` returns an error instantly if `CircuitBreaker` rejects the request. -Otherwise, `Execute` returns the result of the request. -If a panic occurs in the request, `CircuitBreaker` handles it as an error -and causes the same panic again. - -Example -------- - -```go -var cb *breaker.CircuitBreaker - -func Get(url string) ([]byte, error) { - body, err := cb.Execute(func() (interface{}, error) { - resp, err := http.Get(url) - if err != nil { - return nil, err - } - - defer resp.Body.Close() - body, err := ioutil.ReadAll(resp.Body) - if err != nil { - return nil, err - } - - return body, nil - }) - if err != nil { - return nil, err - } - - return body.([]byte), nil -} -``` - -See [example](https://github.com/sony/gobreaker/blob/master/example) for details. - -License -------- - -The MIT License (MIT) - -See [LICENSE](https://github.com/sony/gobreaker/blob/master/LICENSE) for details. - - -[repo-url]: https://github.com/sony/gobreaker diff --git a/vendor/github.com/sony/gobreaker/LICENSE b/vendor/github.com/sony/gobreaker/v2/LICENSE similarity index 100% rename from vendor/github.com/sony/gobreaker/LICENSE rename to vendor/github.com/sony/gobreaker/v2/LICENSE diff --git a/vendor/github.com/sony/gobreaker/gobreaker.go b/vendor/github.com/sony/gobreaker/v2/gobreaker.go similarity index 86% rename from vendor/github.com/sony/gobreaker/gobreaker.go rename to vendor/github.com/sony/gobreaker/v2/gobreaker.go index 7503a278b670d..c0382d1544a1d 100644 --- a/vendor/github.com/sony/gobreaker/gobreaker.go +++ b/vendor/github.com/sony/gobreaker/v2/gobreaker.go @@ -114,7 +114,7 @@ type Settings struct { } // CircuitBreaker is a state machine to prevent sending requests that are likely to fail. -type CircuitBreaker struct { +type CircuitBreaker[T any] struct { name string maxRequests uint32 interval time.Duration @@ -133,13 +133,13 @@ type CircuitBreaker struct { // TwoStepCircuitBreaker is like CircuitBreaker but instead of surrounding a function // with the breaker functionality, it only checks whether a request can proceed and // expects the caller to report the outcome in a separate step using a callback. -type TwoStepCircuitBreaker struct { - cb *CircuitBreaker +type TwoStepCircuitBreaker[T any] struct { + cb *CircuitBreaker[T] } // NewCircuitBreaker returns a new CircuitBreaker configured with the given Settings. -func NewCircuitBreaker(st Settings) *CircuitBreaker { - cb := new(CircuitBreaker) +func NewCircuitBreaker[T any](st Settings) *CircuitBreaker[T] { + cb := new(CircuitBreaker[T]) cb.name = st.Name cb.onStateChange = st.OnStateChange @@ -180,9 +180,9 @@ func NewCircuitBreaker(st Settings) *CircuitBreaker { } // NewTwoStepCircuitBreaker returns a new TwoStepCircuitBreaker configured with the given Settings. -func NewTwoStepCircuitBreaker(st Settings) *TwoStepCircuitBreaker { - return &TwoStepCircuitBreaker{ - cb: NewCircuitBreaker(st), +func NewTwoStepCircuitBreaker[T any](st Settings) *TwoStepCircuitBreaker[T] { + return &TwoStepCircuitBreaker[T]{ + cb: NewCircuitBreaker[T](st), } } @@ -198,12 +198,12 @@ func defaultIsSuccessful(err error) bool { } // Name returns the name of the CircuitBreaker. -func (cb *CircuitBreaker) Name() string { +func (cb *CircuitBreaker[T]) Name() string { return cb.name } // State returns the current state of the CircuitBreaker. -func (cb *CircuitBreaker) State() State { +func (cb *CircuitBreaker[T]) State() State { cb.mutex.Lock() defer cb.mutex.Unlock() @@ -213,7 +213,7 @@ func (cb *CircuitBreaker) State() State { } // Counts returns internal counters -func (cb *CircuitBreaker) Counts() Counts { +func (cb *CircuitBreaker[T]) Counts() Counts { cb.mutex.Lock() defer cb.mutex.Unlock() @@ -225,10 +225,11 @@ func (cb *CircuitBreaker) Counts() Counts { // Otherwise, Execute returns the result of the request. // If a panic occurs in the request, the CircuitBreaker handles it as an error // and causes the same panic again. -func (cb *CircuitBreaker) Execute(req func() (interface{}, error)) (interface{}, error) { +func (cb *CircuitBreaker[T]) Execute(req func() (T, error)) (T, error) { generation, err := cb.beforeRequest() if err != nil { - return nil, err + var defaultValue T + return defaultValue, err } defer func() { @@ -245,24 +246,24 @@ func (cb *CircuitBreaker) Execute(req func() (interface{}, error)) (interface{}, } // Name returns the name of the TwoStepCircuitBreaker. -func (tscb *TwoStepCircuitBreaker) Name() string { +func (tscb *TwoStepCircuitBreaker[T]) Name() string { return tscb.cb.Name() } // State returns the current state of the TwoStepCircuitBreaker. -func (tscb *TwoStepCircuitBreaker) State() State { +func (tscb *TwoStepCircuitBreaker[T]) State() State { return tscb.cb.State() } // Counts returns internal counters -func (tscb *TwoStepCircuitBreaker) Counts() Counts { +func (tscb *TwoStepCircuitBreaker[T]) Counts() Counts { return tscb.cb.Counts() } // Allow checks if a new request can proceed. It returns a callback that should be used to // register the success or failure in a separate step. If the circuit breaker doesn't allow // requests, it returns an error. -func (tscb *TwoStepCircuitBreaker) Allow() (done func(success bool), err error) { +func (tscb *TwoStepCircuitBreaker[T]) Allow() (done func(success bool), err error) { generation, err := tscb.cb.beforeRequest() if err != nil { return nil, err @@ -273,7 +274,7 @@ func (tscb *TwoStepCircuitBreaker) Allow() (done func(success bool), err error) }, nil } -func (cb *CircuitBreaker) beforeRequest() (uint64, error) { +func (cb *CircuitBreaker[T]) beforeRequest() (uint64, error) { cb.mutex.Lock() defer cb.mutex.Unlock() @@ -290,7 +291,7 @@ func (cb *CircuitBreaker) beforeRequest() (uint64, error) { return generation, nil } -func (cb *CircuitBreaker) afterRequest(before uint64, success bool) { +func (cb *CircuitBreaker[T]) afterRequest(before uint64, success bool) { cb.mutex.Lock() defer cb.mutex.Unlock() @@ -307,7 +308,7 @@ func (cb *CircuitBreaker) afterRequest(before uint64, success bool) { } } -func (cb *CircuitBreaker) onSuccess(state State, now time.Time) { +func (cb *CircuitBreaker[T]) onSuccess(state State, now time.Time) { switch state { case StateClosed: cb.counts.onSuccess() @@ -319,7 +320,7 @@ func (cb *CircuitBreaker) onSuccess(state State, now time.Time) { } } -func (cb *CircuitBreaker) onFailure(state State, now time.Time) { +func (cb *CircuitBreaker[T]) onFailure(state State, now time.Time) { switch state { case StateClosed: cb.counts.onFailure() @@ -331,7 +332,7 @@ func (cb *CircuitBreaker) onFailure(state State, now time.Time) { } } -func (cb *CircuitBreaker) currentState(now time.Time) (State, uint64) { +func (cb *CircuitBreaker[T]) currentState(now time.Time) (State, uint64) { switch cb.state { case StateClosed: if !cb.expiry.IsZero() && cb.expiry.Before(now) { @@ -345,7 +346,7 @@ func (cb *CircuitBreaker) currentState(now time.Time) (State, uint64) { return cb.state, cb.generation } -func (cb *CircuitBreaker) setState(state State, now time.Time) { +func (cb *CircuitBreaker[T]) setState(state State, now time.Time) { if cb.state == state { return } @@ -360,7 +361,7 @@ func (cb *CircuitBreaker) setState(state State, now time.Time) { } } -func (cb *CircuitBreaker) toNewGeneration(now time.Time) { +func (cb *CircuitBreaker[T]) toNewGeneration(now time.Time) { cb.generation++ cb.counts.clear() diff --git a/vendor/google.golang.org/api/internal/version.go b/vendor/google.golang.org/api/internal/version.go index cc0fd3c788758..294436d31c458 100644 --- a/vendor/google.golang.org/api/internal/version.go +++ b/vendor/google.golang.org/api/internal/version.go @@ -5,4 +5,4 @@ package internal // Version is the current tagged release of the library. -const Version = "0.206.0" +const Version = "0.207.0" diff --git a/vendor/google.golang.org/api/storage/v1/storage-api.json b/vendor/google.golang.org/api/storage/v1/storage-api.json index 09b7f6487aa07..96599143e6aeb 100644 --- a/vendor/google.golang.org/api/storage/v1/storage-api.json +++ b/vendor/google.golang.org/api/storage/v1/storage-api.json @@ -93,7 +93,7 @@ "location": "us-west4" } ], - "etag": "\"3132333635343336333933383332343134323139\"", + "etag": "\"3134393437363236373436353839383934323639\"", "icons": { "x16": "https://www.google.com/images/icons/product/cloud_storage-16.png", "x32": "https://www.google.com/images/icons/product/cloud_storage-32.png" @@ -1129,6 +1129,19 @@ "required": true, "type": "string" }, + "projection": { + "description": "Set of properties to return. Defaults to full.", + "enum": [ + "full", + "noAcl" + ], + "enumDescriptions": [ + "Include all properties.", + "Omit owner, acl and defaultObjectAcl properties." + ], + "location": "query", + "type": "string" + }, "userProject": { "description": "The project to be billed for this request. Required for Requester Pays buckets.", "location": "query", @@ -1136,6 +1149,9 @@ } }, "path": "b/{bucket}/restore", + "response": { + "$ref": "Bucket" + }, "scopes": [ "https://www.googleapis.com/auth/cloud-platform", "https://www.googleapis.com/auth/devstorage.full_control", @@ -4256,7 +4272,7 @@ } } }, - "revision": "20241008", + "revision": "20241113", "rootUrl": "https://storage.googleapis.com/", "schemas": { "AdvanceRelocateBucketOperationRequest": { @@ -5790,6 +5806,11 @@ "format": "date-time", "type": "string" }, + "timeFinalized": { + "description": "The time when the object was finalized.", + "format": "date-time", + "type": "string" + }, "timeStorageClassUpdated": { "description": "The time at which the object's storage class was last changed. When the object is initially created, it will be set to timeCreated.", "format": "date-time", diff --git a/vendor/google.golang.org/api/storage/v1/storage-gen.go b/vendor/google.golang.org/api/storage/v1/storage-gen.go index 2c11b2d8d61f7..8cb6c0771d5d6 100644 --- a/vendor/google.golang.org/api/storage/v1/storage-gen.go +++ b/vendor/google.golang.org/api/storage/v1/storage-gen.go @@ -2300,6 +2300,8 @@ type Object struct { // format. Will be returned if and only if this version of the object has been // deleted. TimeDeleted string `json:"timeDeleted,omitempty"` + // TimeFinalized: The time when the object was finalized. + TimeFinalized string `json:"timeFinalized,omitempty"` // TimeStorageClassUpdated: The time at which the object's storage class was // last changed. When the object is initially created, it will be set to // timeCreated. @@ -5537,6 +5539,18 @@ func (r *BucketsService) Restore(bucket string, generation int64) *BucketsRestor return c } +// Projection sets the optional parameter "projection": Set of properties to +// return. Defaults to full. +// +// Possible values: +// +// "full" - Include all properties. +// "noAcl" - Omit owner, acl and defaultObjectAcl properties. +func (c *BucketsRestoreCall) Projection(projection string) *BucketsRestoreCall { + c.urlParams_.Set("projection", projection) + return c +} + // UserProject sets the optional parameter "userProject": The project to be // billed for this request. Required for Requester Pays buckets. func (c *BucketsRestoreCall) UserProject(userProject string) *BucketsRestoreCall { @@ -5586,17 +5600,40 @@ func (c *BucketsRestoreCall) doRequest(alt string) (*http.Response, error) { } // Do executes the "storage.buckets.restore" call. -func (c *BucketsRestoreCall) Do(opts ...googleapi.CallOption) error { +// Any non-2xx status code is an error. Response headers are in either +// *Bucket.ServerResponse.Header or (if a response was returned at all) in +// error.(*googleapi.Error).Header. Use googleapi.IsNotModified to check +// whether the returned error was because http.StatusNotModified was returned. +func (c *BucketsRestoreCall) Do(opts ...googleapi.CallOption) (*Bucket, error) { gensupport.SetOptions(c.urlParams_, opts...) res, err := c.doRequest("json") + if res != nil && res.StatusCode == http.StatusNotModified { + if res.Body != nil { + res.Body.Close() + } + return nil, gensupport.WrapError(&googleapi.Error{ + Code: res.StatusCode, + Header: res.Header, + }) + } if err != nil { - return err + return nil, err } defer googleapi.CloseBody(res) if err := googleapi.CheckResponse(res); err != nil { - return gensupport.WrapError(err) + return nil, gensupport.WrapError(err) } - return nil + ret := &Bucket{ + ServerResponse: googleapi.ServerResponse{ + Header: res.Header, + HTTPStatusCode: res.StatusCode, + }, + } + target := &ret + if err := gensupport.DecodeResponse(target, res); err != nil { + return nil, err + } + return ret, nil } type BucketsSetIamPolicyCall struct { diff --git a/vendor/k8s.io/klog/.travis.yml b/vendor/k8s.io/klog/.travis.yml deleted file mode 100644 index 5677664c21836..0000000000000 --- a/vendor/k8s.io/klog/.travis.yml +++ /dev/null @@ -1,16 +0,0 @@ -language: go -go_import_path: k8s.io/klog -dist: xenial -go: - - 1.9.x - - 1.10.x - - 1.11.x - - 1.12.x -script: - - go get -t -v ./... - - diff -u <(echo -n) <(gofmt -d .) - - diff -u <(echo -n) <(golint $(go list -e ./...)) - - go tool vet . || go vet . - - go test -v -race ./... -install: - - go get golang.org/x/lint/golint diff --git a/vendor/k8s.io/klog/CONTRIBUTING.md b/vendor/k8s.io/klog/CONTRIBUTING.md deleted file mode 100644 index 574a56abbbecb..0000000000000 --- a/vendor/k8s.io/klog/CONTRIBUTING.md +++ /dev/null @@ -1,22 +0,0 @@ -# Contributing Guidelines - -Welcome to Kubernetes. We are excited about the prospect of you joining our [community](https://github.com/kubernetes/community)! The Kubernetes community abides by the CNCF [code of conduct](code-of-conduct.md). Here is an excerpt: - -_As contributors and maintainers of this project, and in the interest of fostering an open and welcoming community, we pledge to respect all people who contribute through reporting issues, posting feature requests, updating documentation, submitting pull requests or patches, and other activities._ - -## Getting Started - -We have full documentation on how to get started contributing here: - -- [Contributor License Agreement](https://git.k8s.io/community/CLA.md) Kubernetes projects require that you sign a Contributor License Agreement (CLA) before we can accept your pull requests -- [Kubernetes Contributor Guide](http://git.k8s.io/community/contributors/guide) - Main contributor documentation, or you can just jump directly to the [contributing section](http://git.k8s.io/community/contributors/guide#contributing) -- [Contributor Cheat Sheet](https://git.k8s.io/community/contributors/guide/contributor-cheatsheet.md) - Common resources for existing developers - -## Mentorship - -- [Mentoring Initiatives](https://git.k8s.io/community/mentoring) - We have a diverse set of mentorship programs available that are always looking for volunteers! - -## Contact Information - -- [Slack](https://kubernetes.slack.com/messages/sig-architecture) -- [Mailing List](https://groups.google.com/forum/#!forum/kubernetes-sig-architecture) diff --git a/vendor/k8s.io/klog/LICENSE b/vendor/k8s.io/klog/LICENSE deleted file mode 100644 index 37ec93a14fdcd..0000000000000 --- a/vendor/k8s.io/klog/LICENSE +++ /dev/null @@ -1,191 +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: - -You must give any other recipients of the Work or Derivative Works a copy of -this License; and -You must cause any modified files to carry prominent notices stating that You -changed the files; and -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 -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/k8s.io/klog/OWNERS b/vendor/k8s.io/klog/OWNERS deleted file mode 100644 index 380e514f2807b..0000000000000 --- a/vendor/k8s.io/klog/OWNERS +++ /dev/null @@ -1,19 +0,0 @@ -# See the OWNERS docs at https://go.k8s.io/owners -reviewers: - - jayunit100 - - hoegaarden - - andyxning - - neolit123 - - pohly - - yagonobre - - vincepri - - detiber -approvers: - - dims - - thockin - - justinsb - - tallclair - - piosz - - brancz - - DirectXMan12 - - lavalamp diff --git a/vendor/k8s.io/klog/README.md b/vendor/k8s.io/klog/README.md deleted file mode 100644 index 841468b4b65c4..0000000000000 --- a/vendor/k8s.io/klog/README.md +++ /dev/null @@ -1,97 +0,0 @@ -klog -==== - -klog is a permanent fork of https://github.com/golang/glog. - -## Why was klog created? - -The decision to create klog was one that wasn't made lightly, but it was necessary due to some -drawbacks that are present in [glog](https://github.com/golang/glog). Ultimately, the fork was created due to glog not being under active development; this can be seen in the glog README: - -> The code in this repo [...] is not itself under development - -This makes us unable to solve many use cases without a fork. The factors that contributed to needing feature development are listed below: - - * `glog` [presents a lot "gotchas"](https://github.com/kubernetes/kubernetes/issues/61006) and introduces challenges in containerized environments, all of which aren't well documented. - * `glog` doesn't provide an easy way to test logs, which detracts from the stability of software using it - * A long term goal is to implement a logging interface that allows us to add context, change output format, etc. - -Historical context is available here: - - * https://github.com/kubernetes/kubernetes/issues/61006 - * https://github.com/kubernetes/kubernetes/issues/70264 - * https://groups.google.com/forum/#!msg/kubernetes-sig-architecture/wCWiWf3Juzs/hXRVBH90CgAJ - * https://groups.google.com/forum/#!msg/kubernetes-dev/7vnijOMhLS0/1oRiNtigBgAJ - ----- - -How to use klog -=============== -- Replace imports for `github.com/golang/glog` with `k8s.io/klog` -- Use `klog.InitFlags(nil)` explicitly for initializing global flags as we no longer use `init()` method to register the flags -- You can now use `log-file` instead of `log-dir` for logging to a single file (See `examples/log_file/usage_log_file.go`) -- If you want to redirect everything logged using klog somewhere else (say syslog!), you can use `klog.SetOutput()` method and supply a `io.Writer`. (See `examples/set_output/usage_set_output.go`) -- For more logging conventions (See [Logging Conventions](https://github.com/kubernetes/community/blob/master/contributors/devel/sig-instrumentation/logging.md)) - -### Coexisting with glog -This package can be used side by side with glog. [This example](examples/coexist_glog/coexist_glog.go) shows how to initialize and syncronize flags from the global `flag.CommandLine` FlagSet. In addition, the example makes use of stderr as combined output by setting `alsologtostderr` (or `logtostderr`) to `true`. - -## Community, discussion, contribution, and support - -Learn how to engage with the Kubernetes community on the [community page](http://kubernetes.io/community/). - -You can reach the maintainers of this project at: - -- [Slack](https://kubernetes.slack.com/messages/sig-architecture) -- [Mailing List](https://groups.google.com/forum/#!forum/kubernetes-sig-architecture) - -### Code of conduct - -Participation in the Kubernetes community is governed by the [Kubernetes Code of Conduct](code-of-conduct.md). - ----- - -glog -==== - -Leveled execution logs for Go. - -This is an efficient pure Go implementation of leveled logs in the -manner of the open source C++ package - https://github.com/google/glog - -By binding methods to booleans it is possible to use the log package -without paying the expense of evaluating the arguments to the log. -Through the -vmodule flag, the package also provides fine-grained -control over logging at the file level. - -The comment from glog.go introduces the ideas: - - Package glog implements logging analogous to the Google-internal - C++ INFO/ERROR/V setup. It provides functions Info, Warning, - Error, Fatal, plus formatting variants such as Infof. It - also provides V-style logging controlled by the -v and - -vmodule=file=2 flags. - - Basic examples: - - glog.Info("Prepare to repel boarders") - - glog.Fatalf("Initialization failed: %s", err) - - See the documentation for the V function for an explanation - of these examples: - - if glog.V(2) { - glog.Info("Starting transaction...") - } - - glog.V(2).Infoln("Processed", nItems, "elements") - - -The repository contains an open source version of the log package -used inside Google. The master copy of the source lives inside -Google, not here. The code in this repo is for export only and is not itself -under development. Feature requests will be ignored. - -Send bug reports to golang-nuts@googlegroups.com. diff --git a/vendor/k8s.io/klog/RELEASE.md b/vendor/k8s.io/klog/RELEASE.md deleted file mode 100644 index b53eb960ce78f..0000000000000 --- a/vendor/k8s.io/klog/RELEASE.md +++ /dev/null @@ -1,9 +0,0 @@ -# Release Process - -The `klog` is released on an as-needed basis. The process is as follows: - -1. An issue is proposing a new release with a changelog since the last release -1. All [OWNERS](OWNERS) must LGTM this release -1. An OWNER runs `git tag -s $VERSION` and inserts the changelog and pushes the tag with `git push $VERSION` -1. The release issue is closed -1. An announcement email is sent to `kubernetes-dev@googlegroups.com` with the subject `[ANNOUNCE] kubernetes-template-project $VERSION is released` diff --git a/vendor/k8s.io/klog/SECURITY_CONTACTS b/vendor/k8s.io/klog/SECURITY_CONTACTS deleted file mode 100644 index 6128a586995b4..0000000000000 --- a/vendor/k8s.io/klog/SECURITY_CONTACTS +++ /dev/null @@ -1,20 +0,0 @@ -# Defined below are the security contacts for this repo. -# -# They are the contact point for the Product Security Committee to reach out -# to for triaging and handling of incoming issues. -# -# The below names agree to abide by the -# [Embargo Policy](https://git.k8s.io/security/private-distributors-list.md#embargo-policy) -# and will be removed and replaced if they violate that agreement. -# -# DO NOT REPORT SECURITY VULNERABILITIES DIRECTLY TO THESE NAMES, FOLLOW THE -# INSTRUCTIONS AT https://kubernetes.io/security/ - -dims -thockin -justinsb -tallclair -piosz -brancz -DirectXMan12 -lavalamp diff --git a/vendor/k8s.io/klog/code-of-conduct.md b/vendor/k8s.io/klog/code-of-conduct.md deleted file mode 100644 index 0d15c00cf3252..0000000000000 --- a/vendor/k8s.io/klog/code-of-conduct.md +++ /dev/null @@ -1,3 +0,0 @@ -# Kubernetes Community Code of Conduct - -Please refer to our [Kubernetes Community Code of Conduct](https://git.k8s.io/community/code-of-conduct.md) diff --git a/vendor/k8s.io/klog/klog.go b/vendor/k8s.io/klog/klog.go deleted file mode 100644 index 2712ce0afc11e..0000000000000 --- a/vendor/k8s.io/klog/klog.go +++ /dev/null @@ -1,1308 +0,0 @@ -// Go support for leveled logs, analogous to https://code.google.com/p/google-glog/ -// -// Copyright 2013 Google Inc. All Rights Reserved. -// -// 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 klog implements logging analogous to the Google-internal C++ INFO/ERROR/V setup. -// It provides functions Info, Warning, Error, Fatal, plus formatting variants such as -// Infof. It also provides V-style logging controlled by the -v and -vmodule=file=2 flags. -// -// Basic examples: -// -// klog.Info("Prepare to repel boarders") -// -// klog.Fatalf("Initialization failed: %s", err) -// -// See the documentation for the V function for an explanation of these examples: -// -// if klog.V(2) { -// klog.Info("Starting transaction...") -// } -// -// klog.V(2).Infoln("Processed", nItems, "elements") -// -// Log output is buffered and written periodically using Flush. Programs -// should call Flush before exiting to guarantee all log output is written. -// -// By default, all log statements write to standard error. -// This package provides several flags that modify this behavior. -// As a result, flag.Parse must be called before any logging is done. -// -// -logtostderr=true -// Logs are written to standard error instead of to files. -// -alsologtostderr=false -// Logs are written to standard error as well as to files. -// -stderrthreshold=ERROR -// Log events at or above this severity are logged to standard -// error as well as to files. -// -log_dir="" -// Log files will be written to this directory instead of the -// default temporary directory. -// -// Other flags provide aids to debugging. -// -// -log_backtrace_at="" -// When set to a file and line number holding a logging statement, -// such as -// -log_backtrace_at=gopherflakes.go:234 -// a stack trace will be written to the Info log whenever execution -// hits that statement. (Unlike with -vmodule, the ".go" must be -// present.) -// -v=0 -// Enable V-leveled logging at the specified level. -// -vmodule="" -// The syntax of the argument is a comma-separated list of pattern=N, -// where pattern is a literal file name (minus the ".go" suffix) or -// "glob" pattern and N is a V level. For instance, -// -vmodule=gopher*=3 -// sets the V level to 3 in all Go files whose names begin "gopher". -// -package klog - -import ( - "bufio" - "bytes" - "errors" - "flag" - "fmt" - "io" - stdLog "log" - "math" - "os" - "path/filepath" - "runtime" - "strconv" - "strings" - "sync" - "sync/atomic" - "time" -) - -// severity identifies the sort of log: info, warning etc. It also implements -// the flag.Value interface. The -stderrthreshold flag is of type severity and -// should be modified only through the flag.Value interface. The values match -// the corresponding constants in C++. -type severity int32 // sync/atomic int32 - -// These constants identify the log levels in order of increasing severity. -// A message written to a high-severity log file is also written to each -// lower-severity log file. -const ( - infoLog severity = iota - warningLog - errorLog - fatalLog - numSeverity = 4 -) - -const severityChar = "IWEF" - -var severityName = []string{ - infoLog: "INFO", - warningLog: "WARNING", - errorLog: "ERROR", - fatalLog: "FATAL", -} - -// get returns the value of the severity. -func (s *severity) get() severity { - return severity(atomic.LoadInt32((*int32)(s))) -} - -// set sets the value of the severity. -func (s *severity) set(val severity) { - atomic.StoreInt32((*int32)(s), int32(val)) -} - -// String is part of the flag.Value interface. -func (s *severity) String() string { - return strconv.FormatInt(int64(*s), 10) -} - -// Get is part of the flag.Value interface. -func (s *severity) Get() interface{} { - return *s -} - -// Set is part of the flag.Value interface. -func (s *severity) Set(value string) error { - var threshold severity - // Is it a known name? - if v, ok := severityByName(value); ok { - threshold = v - } else { - v, err := strconv.ParseInt(value, 10, 32) - if err != nil { - return err - } - threshold = severity(v) - } - logging.stderrThreshold.set(threshold) - return nil -} - -func severityByName(s string) (severity, bool) { - s = strings.ToUpper(s) - for i, name := range severityName { - if name == s { - return severity(i), true - } - } - return 0, false -} - -// OutputStats tracks the number of output lines and bytes written. -type OutputStats struct { - lines int64 - bytes int64 -} - -// Lines returns the number of lines written. -func (s *OutputStats) Lines() int64 { - return atomic.LoadInt64(&s.lines) -} - -// Bytes returns the number of bytes written. -func (s *OutputStats) Bytes() int64 { - return atomic.LoadInt64(&s.bytes) -} - -// Stats tracks the number of lines of output and number of bytes -// per severity level. Values must be read with atomic.LoadInt64. -var Stats struct { - Info, Warning, Error OutputStats -} - -var severityStats = [numSeverity]*OutputStats{ - infoLog: &Stats.Info, - warningLog: &Stats.Warning, - errorLog: &Stats.Error, -} - -// Level is exported because it appears in the arguments to V and is -// the type of the v flag, which can be set programmatically. -// It's a distinct type because we want to discriminate it from logType. -// Variables of type level are only changed under logging.mu. -// The -v flag is read only with atomic ops, so the state of the logging -// module is consistent. - -// Level is treated as a sync/atomic int32. - -// Level specifies a level of verbosity for V logs. *Level implements -// flag.Value; the -v flag is of type Level and should be modified -// only through the flag.Value interface. -type Level int32 - -// get returns the value of the Level. -func (l *Level) get() Level { - return Level(atomic.LoadInt32((*int32)(l))) -} - -// set sets the value of the Level. -func (l *Level) set(val Level) { - atomic.StoreInt32((*int32)(l), int32(val)) -} - -// String is part of the flag.Value interface. -func (l *Level) String() string { - return strconv.FormatInt(int64(*l), 10) -} - -// Get is part of the flag.Value interface. -func (l *Level) Get() interface{} { - return *l -} - -// Set is part of the flag.Value interface. -func (l *Level) Set(value string) error { - v, err := strconv.ParseInt(value, 10, 32) - if err != nil { - return err - } - logging.mu.Lock() - defer logging.mu.Unlock() - logging.setVState(Level(v), logging.vmodule.filter, false) - return nil -} - -// moduleSpec represents the setting of the -vmodule flag. -type moduleSpec struct { - filter []modulePat -} - -// modulePat contains a filter for the -vmodule flag. -// It holds a verbosity level and a file pattern to match. -type modulePat struct { - pattern string - literal bool // The pattern is a literal string - level Level -} - -// match reports whether the file matches the pattern. It uses a string -// comparison if the pattern contains no metacharacters. -func (m *modulePat) match(file string) bool { - if m.literal { - return file == m.pattern - } - match, _ := filepath.Match(m.pattern, file) - return match -} - -func (m *moduleSpec) String() string { - // Lock because the type is not atomic. TODO: clean this up. - logging.mu.Lock() - defer logging.mu.Unlock() - var b bytes.Buffer - for i, f := range m.filter { - if i > 0 { - b.WriteRune(',') - } - fmt.Fprintf(&b, "%s=%d", f.pattern, f.level) - } - return b.String() -} - -// Get is part of the (Go 1.2) flag.Getter interface. It always returns nil for this flag type since the -// struct is not exported. -func (m *moduleSpec) Get() interface{} { - return nil -} - -var errVmoduleSyntax = errors.New("syntax error: expect comma-separated list of filename=N") - -// Syntax: -vmodule=recordio=2,file=1,gfs*=3 -func (m *moduleSpec) Set(value string) error { - var filter []modulePat - for _, pat := range strings.Split(value, ",") { - if len(pat) == 0 { - // Empty strings such as from a trailing comma can be ignored. - continue - } - patLev := strings.Split(pat, "=") - if len(patLev) != 2 || len(patLev[0]) == 0 || len(patLev[1]) == 0 { - return errVmoduleSyntax - } - pattern := patLev[0] - v, err := strconv.ParseInt(patLev[1], 10, 32) - if err != nil { - return errors.New("syntax error: expect comma-separated list of filename=N") - } - if v < 0 { - return errors.New("negative value for vmodule level") - } - if v == 0 { - continue // Ignore. It's harmless but no point in paying the overhead. - } - // TODO: check syntax of filter? - filter = append(filter, modulePat{pattern, isLiteral(pattern), Level(v)}) - } - logging.mu.Lock() - defer logging.mu.Unlock() - logging.setVState(logging.verbosity, filter, true) - return nil -} - -// isLiteral reports whether the pattern is a literal string, that is, has no metacharacters -// that require filepath.Match to be called to match the pattern. -func isLiteral(pattern string) bool { - return !strings.ContainsAny(pattern, `\*?[]`) -} - -// traceLocation represents the setting of the -log_backtrace_at flag. -type traceLocation struct { - file string - line int -} - -// isSet reports whether the trace location has been specified. -// logging.mu is held. -func (t *traceLocation) isSet() bool { - return t.line > 0 -} - -// match reports whether the specified file and line matches the trace location. -// The argument file name is the full path, not the basename specified in the flag. -// logging.mu is held. -func (t *traceLocation) match(file string, line int) bool { - if t.line != line { - return false - } - if i := strings.LastIndex(file, "/"); i >= 0 { - file = file[i+1:] - } - return t.file == file -} - -func (t *traceLocation) String() string { - // Lock because the type is not atomic. TODO: clean this up. - logging.mu.Lock() - defer logging.mu.Unlock() - return fmt.Sprintf("%s:%d", t.file, t.line) -} - -// Get is part of the (Go 1.2) flag.Getter interface. It always returns nil for this flag type since the -// struct is not exported -func (t *traceLocation) Get() interface{} { - return nil -} - -var errTraceSyntax = errors.New("syntax error: expect file.go:234") - -// Syntax: -log_backtrace_at=gopherflakes.go:234 -// Note that unlike vmodule the file extension is included here. -func (t *traceLocation) Set(value string) error { - if value == "" { - // Unset. - t.line = 0 - t.file = "" - } - fields := strings.Split(value, ":") - if len(fields) != 2 { - return errTraceSyntax - } - file, line := fields[0], fields[1] - if !strings.Contains(file, ".") { - return errTraceSyntax - } - v, err := strconv.Atoi(line) - if err != nil { - return errTraceSyntax - } - if v <= 0 { - return errors.New("negative or zero value for level") - } - logging.mu.Lock() - defer logging.mu.Unlock() - t.line = v - t.file = file - return nil -} - -// flushSyncWriter is the interface satisfied by logging destinations. -type flushSyncWriter interface { - Flush() error - Sync() error - io.Writer -} - -// init sets up the defaults and runs flushDaemon. -func init() { - logging.stderrThreshold = errorLog // Default stderrThreshold is ERROR. - logging.setVState(0, nil, false) - logging.logDir = "" - logging.logFile = "" - logging.logFileMaxSizeMB = 1800 - logging.toStderr = true - logging.alsoToStderr = false - logging.skipHeaders = false - logging.addDirHeader = false - logging.skipLogHeaders = false - go logging.flushDaemon() -} - -// InitFlags is for explicitly initializing the flags. -func InitFlags(flagset *flag.FlagSet) { - if flagset == nil { - flagset = flag.CommandLine - } - - flagset.StringVar(&logging.logDir, "log_dir", logging.logDir, "If non-empty, write log files in this directory") - flagset.StringVar(&logging.logFile, "log_file", logging.logFile, "If non-empty, use this log file") - flagset.Uint64Var(&logging.logFileMaxSizeMB, "log_file_max_size", logging.logFileMaxSizeMB, - "Defines the maximum size a log file can grow to. Unit is megabytes. "+ - "If the value is 0, the maximum file size is unlimited.") - flagset.BoolVar(&logging.toStderr, "logtostderr", logging.toStderr, "log to standard error instead of files") - flagset.BoolVar(&logging.alsoToStderr, "alsologtostderr", logging.alsoToStderr, "log to standard error as well as files") - flagset.Var(&logging.verbosity, "v", "number for the log level verbosity") - flagset.BoolVar(&logging.skipHeaders, "add_dir_header", logging.addDirHeader, "If true, adds the file directory to the header") - flagset.BoolVar(&logging.skipHeaders, "skip_headers", logging.skipHeaders, "If true, avoid header prefixes in the log messages") - flagset.BoolVar(&logging.skipLogHeaders, "skip_log_headers", logging.skipLogHeaders, "If true, avoid headers when opening log files") - flagset.Var(&logging.stderrThreshold, "stderrthreshold", "logs at or above this threshold go to stderr") - flagset.Var(&logging.vmodule, "vmodule", "comma-separated list of pattern=N settings for file-filtered logging") - flagset.Var(&logging.traceLocation, "log_backtrace_at", "when logging hits line file:N, emit a stack trace") -} - -// Flush flushes all pending log I/O. -func Flush() { - logging.lockAndFlushAll() -} - -// loggingT collects all the global state of the logging setup. -type loggingT struct { - // Boolean flags. Not handled atomically because the flag.Value interface - // does not let us avoid the =true, and that shorthand is necessary for - // compatibility. TODO: does this matter enough to fix? Seems unlikely. - toStderr bool // The -logtostderr flag. - alsoToStderr bool // The -alsologtostderr flag. - - // Level flag. Handled atomically. - stderrThreshold severity // The -stderrthreshold flag. - - // freeList is a list of byte buffers, maintained under freeListMu. - freeList *buffer - // freeListMu maintains the free list. It is separate from the main mutex - // so buffers can be grabbed and printed to without holding the main lock, - // for better parallelization. - freeListMu sync.Mutex - - // mu protects the remaining elements of this structure and is - // used to synchronize logging. - mu sync.Mutex - // file holds writer for each of the log types. - file [numSeverity]flushSyncWriter - // pcs is used in V to avoid an allocation when computing the caller's PC. - pcs [1]uintptr - // vmap is a cache of the V Level for each V() call site, identified by PC. - // It is wiped whenever the vmodule flag changes state. - vmap map[uintptr]Level - // filterLength stores the length of the vmodule filter chain. If greater - // than zero, it means vmodule is enabled. It may be read safely - // using sync.LoadInt32, but is only modified under mu. - filterLength int32 - // traceLocation is the state of the -log_backtrace_at flag. - traceLocation traceLocation - // These flags are modified only under lock, although verbosity may be fetched - // safely using atomic.LoadInt32. - vmodule moduleSpec // The state of the -vmodule flag. - verbosity Level // V logging level, the value of the -v flag/ - - // If non-empty, overrides the choice of directory in which to write logs. - // See createLogDirs for the full list of possible destinations. - logDir string - - // If non-empty, specifies the path of the file to write logs. mutually exclusive - // with the log-dir option. - logFile string - - // When logFile is specified, this limiter makes sure the logFile won't exceeds a certain size. When exceeds, the - // logFile will be cleaned up. If this value is 0, no size limitation will be applied to logFile. - logFileMaxSizeMB uint64 - - // If true, do not add the prefix headers, useful when used with SetOutput - skipHeaders bool - - // If true, do not add the headers to log files - skipLogHeaders bool - - // If true, add the file directory to the header - addDirHeader bool -} - -// buffer holds a byte Buffer for reuse. The zero value is ready for use. -type buffer struct { - bytes.Buffer - tmp [64]byte // temporary byte array for creating headers. - next *buffer -} - -var logging loggingT - -// setVState sets a consistent state for V logging. -// l.mu is held. -func (l *loggingT) setVState(verbosity Level, filter []modulePat, setFilter bool) { - // Turn verbosity off so V will not fire while we are in transition. - logging.verbosity.set(0) - // Ditto for filter length. - atomic.StoreInt32(&logging.filterLength, 0) - - // Set the new filters and wipe the pc->Level map if the filter has changed. - if setFilter { - logging.vmodule.filter = filter - logging.vmap = make(map[uintptr]Level) - } - - // Things are consistent now, so enable filtering and verbosity. - // They are enabled in order opposite to that in V. - atomic.StoreInt32(&logging.filterLength, int32(len(filter))) - logging.verbosity.set(verbosity) -} - -// getBuffer returns a new, ready-to-use buffer. -func (l *loggingT) getBuffer() *buffer { - l.freeListMu.Lock() - b := l.freeList - if b != nil { - l.freeList = b.next - } - l.freeListMu.Unlock() - if b == nil { - b = new(buffer) - } else { - b.next = nil - b.Reset() - } - return b -} - -// putBuffer returns a buffer to the free list. -func (l *loggingT) putBuffer(b *buffer) { - if b.Len() >= 256 { - // Let big buffers die a natural death. - return - } - l.freeListMu.Lock() - b.next = l.freeList - l.freeList = b - l.freeListMu.Unlock() -} - -var timeNow = time.Now // Stubbed out for testing. - -/* -header formats a log header as defined by the C++ implementation. -It returns a buffer containing the formatted header and the user's file and line number. -The depth specifies how many stack frames above lives the source line to be identified in the log message. - -Log lines have this form: - Lmmdd hh:mm:ss.uuuuuu threadid file:line] msg... -where the fields are defined as follows: - L A single character, representing the log level (eg 'I' for INFO) - mm The month (zero padded; ie May is '05') - dd The day (zero padded) - hh:mm:ss.uuuuuu Time in hours, minutes and fractional seconds - threadid The space-padded thread ID as returned by GetTID() - file The file name - line The line number - msg The user-supplied message -*/ -func (l *loggingT) header(s severity, depth int) (*buffer, string, int) { - _, file, line, ok := runtime.Caller(3 + depth) - if !ok { - file = "???" - line = 1 - } else { - if slash := strings.LastIndex(file, "/"); slash >= 0 { - path := file - file = path[slash+1:] - if l.addDirHeader { - if dirsep := strings.LastIndex(path[:slash], "/"); dirsep >= 0 { - file = path[dirsep+1:] - } - } - } - } - return l.formatHeader(s, file, line), file, line -} - -// formatHeader formats a log header using the provided file name and line number. -func (l *loggingT) formatHeader(s severity, file string, line int) *buffer { - now := timeNow() - if line < 0 { - line = 0 // not a real line number, but acceptable to someDigits - } - if s > fatalLog { - s = infoLog // for safety. - } - buf := l.getBuffer() - if l.skipHeaders { - return buf - } - - // Avoid Fprintf, for speed. The format is so simple that we can do it quickly by hand. - // It's worth about 3X. Fprintf is hard. - _, month, day := now.Date() - hour, minute, second := now.Clock() - // Lmmdd hh:mm:ss.uuuuuu threadid file:line] - buf.tmp[0] = severityChar[s] - buf.twoDigits(1, int(month)) - buf.twoDigits(3, day) - buf.tmp[5] = ' ' - buf.twoDigits(6, hour) - buf.tmp[8] = ':' - buf.twoDigits(9, minute) - buf.tmp[11] = ':' - buf.twoDigits(12, second) - buf.tmp[14] = '.' - buf.nDigits(6, 15, now.Nanosecond()/1000, '0') - buf.tmp[21] = ' ' - buf.nDigits(7, 22, pid, ' ') // TODO: should be TID - buf.tmp[29] = ' ' - buf.Write(buf.tmp[:30]) - buf.WriteString(file) - buf.tmp[0] = ':' - n := buf.someDigits(1, line) - buf.tmp[n+1] = ']' - buf.tmp[n+2] = ' ' - buf.Write(buf.tmp[:n+3]) - return buf -} - -// Some custom tiny helper functions to print the log header efficiently. - -const digits = "0123456789" - -// twoDigits formats a zero-prefixed two-digit integer at buf.tmp[i]. -func (buf *buffer) twoDigits(i, d int) { - buf.tmp[i+1] = digits[d%10] - d /= 10 - buf.tmp[i] = digits[d%10] -} - -// nDigits formats an n-digit integer at buf.tmp[i], -// padding with pad on the left. -// It assumes d >= 0. -func (buf *buffer) nDigits(n, i, d int, pad byte) { - j := n - 1 - for ; j >= 0 && d > 0; j-- { - buf.tmp[i+j] = digits[d%10] - d /= 10 - } - for ; j >= 0; j-- { - buf.tmp[i+j] = pad - } -} - -// someDigits formats a zero-prefixed variable-width integer at buf.tmp[i]. -func (buf *buffer) someDigits(i, d int) int { - // Print into the top, then copy down. We know there's space for at least - // a 10-digit number. - j := len(buf.tmp) - for { - j-- - buf.tmp[j] = digits[d%10] - d /= 10 - if d == 0 { - break - } - } - return copy(buf.tmp[i:], buf.tmp[j:]) -} - -func (l *loggingT) println(s severity, args ...interface{}) { - buf, file, line := l.header(s, 0) - fmt.Fprintln(buf, args...) - l.output(s, buf, file, line, false) -} - -func (l *loggingT) print(s severity, args ...interface{}) { - l.printDepth(s, 1, args...) -} - -func (l *loggingT) printDepth(s severity, depth int, args ...interface{}) { - buf, file, line := l.header(s, depth) - fmt.Fprint(buf, args...) - if buf.Bytes()[buf.Len()-1] != '\n' { - buf.WriteByte('\n') - } - l.output(s, buf, file, line, false) -} - -func (l *loggingT) printf(s severity, format string, args ...interface{}) { - buf, file, line := l.header(s, 0) - fmt.Fprintf(buf, format, args...) - if buf.Bytes()[buf.Len()-1] != '\n' { - buf.WriteByte('\n') - } - l.output(s, buf, file, line, false) -} - -// printWithFileLine behaves like print but uses the provided file and line number. If -// alsoLogToStderr is true, the log message always appears on standard error; it -// will also appear in the log file unless --logtostderr is set. -func (l *loggingT) printWithFileLine(s severity, file string, line int, alsoToStderr bool, args ...interface{}) { - buf := l.formatHeader(s, file, line) - fmt.Fprint(buf, args...) - if buf.Bytes()[buf.Len()-1] != '\n' { - buf.WriteByte('\n') - } - l.output(s, buf, file, line, alsoToStderr) -} - -// redirectBuffer is used to set an alternate destination for the logs -type redirectBuffer struct { - w io.Writer -} - -func (rb *redirectBuffer) Sync() error { - return nil -} - -func (rb *redirectBuffer) Flush() error { - return nil -} - -func (rb *redirectBuffer) Write(bytes []byte) (n int, err error) { - return rb.w.Write(bytes) -} - -// SetOutput sets the output destination for all severities -func SetOutput(w io.Writer) { - logging.mu.Lock() - defer logging.mu.Unlock() - for s := fatalLog; s >= infoLog; s-- { - rb := &redirectBuffer{ - w: w, - } - logging.file[s] = rb - } -} - -// SetOutputBySeverity sets the output destination for specific severity -func SetOutputBySeverity(name string, w io.Writer) { - logging.mu.Lock() - defer logging.mu.Unlock() - sev, ok := severityByName(name) - if !ok { - panic(fmt.Sprintf("SetOutputBySeverity(%q): unrecognized severity name", name)) - } - rb := &redirectBuffer{ - w: w, - } - logging.file[sev] = rb -} - -// output writes the data to the log files and releases the buffer. -func (l *loggingT) output(s severity, buf *buffer, file string, line int, alsoToStderr bool) { - l.mu.Lock() - if l.traceLocation.isSet() { - if l.traceLocation.match(file, line) { - buf.Write(stacks(false)) - } - } - data := buf.Bytes() - if l.toStderr { - os.Stderr.Write(data) - } else { - if alsoToStderr || l.alsoToStderr || s >= l.stderrThreshold.get() { - os.Stderr.Write(data) - } - - if logging.logFile != "" { - // Since we are using a single log file, all of the items in l.file array - // will point to the same file, so just use one of them to write data. - if l.file[infoLog] == nil { - if err := l.createFiles(infoLog); err != nil { - os.Stderr.Write(data) // Make sure the message appears somewhere. - l.exit(err) - } - } - l.file[infoLog].Write(data) - } else { - if l.file[s] == nil { - if err := l.createFiles(s); err != nil { - os.Stderr.Write(data) // Make sure the message appears somewhere. - l.exit(err) - } - } - - switch s { - case fatalLog: - l.file[fatalLog].Write(data) - fallthrough - case errorLog: - l.file[errorLog].Write(data) - fallthrough - case warningLog: - l.file[warningLog].Write(data) - fallthrough - case infoLog: - l.file[infoLog].Write(data) - } - } - } - if s == fatalLog { - // If we got here via Exit rather than Fatal, print no stacks. - if atomic.LoadUint32(&fatalNoStacks) > 0 { - l.mu.Unlock() - timeoutFlush(10 * time.Second) - os.Exit(1) - } - // Dump all goroutine stacks before exiting. - // First, make sure we see the trace for the current goroutine on standard error. - // If -logtostderr has been specified, the loop below will do that anyway - // as the first stack in the full dump. - if !l.toStderr { - os.Stderr.Write(stacks(false)) - } - // Write the stack trace for all goroutines to the files. - trace := stacks(true) - logExitFunc = func(error) {} // If we get a write error, we'll still exit below. - for log := fatalLog; log >= infoLog; log-- { - if f := l.file[log]; f != nil { // Can be nil if -logtostderr is set. - f.Write(trace) - } - } - l.mu.Unlock() - timeoutFlush(10 * time.Second) - os.Exit(255) // C++ uses -1, which is silly because it's anded with 255 anyway. - } - l.putBuffer(buf) - l.mu.Unlock() - if stats := severityStats[s]; stats != nil { - atomic.AddInt64(&stats.lines, 1) - atomic.AddInt64(&stats.bytes, int64(len(data))) - } -} - -// timeoutFlush calls Flush and returns when it completes or after timeout -// elapses, whichever happens first. This is needed because the hooks invoked -// by Flush may deadlock when klog.Fatal is called from a hook that holds -// a lock. -func timeoutFlush(timeout time.Duration) { - done := make(chan bool, 1) - go func() { - Flush() // calls logging.lockAndFlushAll() - done <- true - }() - select { - case <-done: - case <-time.After(timeout): - fmt.Fprintln(os.Stderr, "klog: Flush took longer than", timeout) - } -} - -// stacks is a wrapper for runtime.Stack that attempts to recover the data for all goroutines. -func stacks(all bool) []byte { - // We don't know how big the traces are, so grow a few times if they don't fit. Start large, though. - n := 10000 - if all { - n = 100000 - } - var trace []byte - for i := 0; i < 5; i++ { - trace = make([]byte, n) - nbytes := runtime.Stack(trace, all) - if nbytes < len(trace) { - return trace[:nbytes] - } - n *= 2 - } - return trace -} - -// logExitFunc provides a simple mechanism to override the default behavior -// of exiting on error. Used in testing and to guarantee we reach a required exit -// for fatal logs. Instead, exit could be a function rather than a method but that -// would make its use clumsier. -var logExitFunc func(error) - -// exit is called if there is trouble creating or writing log files. -// It flushes the logs and exits the program; there's no point in hanging around. -// l.mu is held. -func (l *loggingT) exit(err error) { - fmt.Fprintf(os.Stderr, "log: exiting because of error: %s\n", err) - // If logExitFunc is set, we do that instead of exiting. - if logExitFunc != nil { - logExitFunc(err) - return - } - l.flushAll() - os.Exit(2) -} - -// syncBuffer joins a bufio.Writer to its underlying file, providing access to the -// file's Sync method and providing a wrapper for the Write method that provides log -// file rotation. There are conflicting methods, so the file cannot be embedded. -// l.mu is held for all its methods. -type syncBuffer struct { - logger *loggingT - *bufio.Writer - file *os.File - sev severity - nbytes uint64 // The number of bytes written to this file - maxbytes uint64 // The max number of bytes this syncBuffer.file can hold before cleaning up. -} - -func (sb *syncBuffer) Sync() error { - return sb.file.Sync() -} - -// CalculateMaxSize returns the real max size in bytes after considering the default max size and the flag options. -func CalculateMaxSize() uint64 { - if logging.logFile != "" { - if logging.logFileMaxSizeMB == 0 { - // If logFileMaxSizeMB is zero, we don't have limitations on the log size. - return math.MaxUint64 - } - // Flag logFileMaxSizeMB is in MB for user convenience. - return logging.logFileMaxSizeMB * 1024 * 1024 - } - // If "log_file" flag is not specified, the target file (sb.file) will be cleaned up when reaches a fixed size. - return MaxSize -} - -func (sb *syncBuffer) Write(p []byte) (n int, err error) { - if sb.nbytes+uint64(len(p)) >= sb.maxbytes { - if err := sb.rotateFile(time.Now(), false); err != nil { - sb.logger.exit(err) - } - } - n, err = sb.Writer.Write(p) - sb.nbytes += uint64(n) - if err != nil { - sb.logger.exit(err) - } - return -} - -// rotateFile closes the syncBuffer's file and starts a new one. -// The startup argument indicates whether this is the initial startup of klog. -// If startup is true, existing files are opened for appending instead of truncated. -func (sb *syncBuffer) rotateFile(now time.Time, startup bool) error { - if sb.file != nil { - sb.Flush() - sb.file.Close() - } - var err error - sb.file, _, err = create(severityName[sb.sev], now, startup) - sb.nbytes = 0 - if err != nil { - return err - } - - sb.Writer = bufio.NewWriterSize(sb.file, bufferSize) - - if sb.logger.skipLogHeaders { - return nil - } - - // Write header. - var buf bytes.Buffer - fmt.Fprintf(&buf, "Log file created at: %s\n", now.Format("2006/01/02 15:04:05")) - fmt.Fprintf(&buf, "Running on machine: %s\n", host) - fmt.Fprintf(&buf, "Binary: Built with %s %s for %s/%s\n", runtime.Compiler, runtime.Version(), runtime.GOOS, runtime.GOARCH) - fmt.Fprintf(&buf, "Log line format: [IWEF]mmdd hh:mm:ss.uuuuuu threadid file:line] msg\n") - n, err := sb.file.Write(buf.Bytes()) - sb.nbytes += uint64(n) - return err -} - -// bufferSize sizes the buffer associated with each log file. It's large -// so that log records can accumulate without the logging thread blocking -// on disk I/O. The flushDaemon will block instead. -const bufferSize = 256 * 1024 - -// createFiles creates all the log files for severity from sev down to infoLog. -// l.mu is held. -func (l *loggingT) createFiles(sev severity) error { - now := time.Now() - // Files are created in decreasing severity order, so as soon as we find one - // has already been created, we can stop. - for s := sev; s >= infoLog && l.file[s] == nil; s-- { - sb := &syncBuffer{ - logger: l, - sev: s, - maxbytes: CalculateMaxSize(), - } - if err := sb.rotateFile(now, true); err != nil { - return err - } - l.file[s] = sb - } - return nil -} - -const flushInterval = 5 * time.Second - -// flushDaemon periodically flushes the log file buffers. -func (l *loggingT) flushDaemon() { - for range time.NewTicker(flushInterval).C { - l.lockAndFlushAll() - } -} - -// lockAndFlushAll is like flushAll but locks l.mu first. -func (l *loggingT) lockAndFlushAll() { - l.mu.Lock() - l.flushAll() - l.mu.Unlock() -} - -// flushAll flushes all the logs and attempts to "sync" their data to disk. -// l.mu is held. -func (l *loggingT) flushAll() { - // Flush from fatal down, in case there's trouble flushing. - for s := fatalLog; s >= infoLog; s-- { - file := l.file[s] - if file != nil { - file.Flush() // ignore error - file.Sync() // ignore error - } - } -} - -// CopyStandardLogTo arranges for messages written to the Go "log" package's -// default logs to also appear in the Google logs for the named and lower -// severities. Subsequent changes to the standard log's default output location -// or format may break this behavior. -// -// Valid names are "INFO", "WARNING", "ERROR", and "FATAL". If the name is not -// recognized, CopyStandardLogTo panics. -func CopyStandardLogTo(name string) { - sev, ok := severityByName(name) - if !ok { - panic(fmt.Sprintf("log.CopyStandardLogTo(%q): unrecognized severity name", name)) - } - // Set a log format that captures the user's file and line: - // d.go:23: message - stdLog.SetFlags(stdLog.Lshortfile) - stdLog.SetOutput(logBridge(sev)) -} - -// logBridge provides the Write method that enables CopyStandardLogTo to connect -// Go's standard logs to the logs provided by this package. -type logBridge severity - -// Write parses the standard logging line and passes its components to the -// logger for severity(lb). -func (lb logBridge) Write(b []byte) (n int, err error) { - var ( - file = "???" - line = 1 - text string - ) - // Split "d.go:23: message" into "d.go", "23", and "message". - if parts := bytes.SplitN(b, []byte{':'}, 3); len(parts) != 3 || len(parts[0]) < 1 || len(parts[2]) < 1 { - text = fmt.Sprintf("bad log format: %s", b) - } else { - file = string(parts[0]) - text = string(parts[2][1:]) // skip leading space - line, err = strconv.Atoi(string(parts[1])) - if err != nil { - text = fmt.Sprintf("bad line number: %s", b) - line = 1 - } - } - // printWithFileLine with alsoToStderr=true, so standard log messages - // always appear on standard error. - logging.printWithFileLine(severity(lb), file, line, true, text) - return len(b), nil -} - -// setV computes and remembers the V level for a given PC -// when vmodule is enabled. -// File pattern matching takes the basename of the file, stripped -// of its .go suffix, and uses filepath.Match, which is a little more -// general than the *? matching used in C++. -// l.mu is held. -func (l *loggingT) setV(pc uintptr) Level { - fn := runtime.FuncForPC(pc) - file, _ := fn.FileLine(pc) - // The file is something like /a/b/c/d.go. We want just the d. - if strings.HasSuffix(file, ".go") { - file = file[:len(file)-3] - } - if slash := strings.LastIndex(file, "/"); slash >= 0 { - file = file[slash+1:] - } - for _, filter := range l.vmodule.filter { - if filter.match(file) { - l.vmap[pc] = filter.level - return filter.level - } - } - l.vmap[pc] = 0 - return 0 -} - -// Verbose is a boolean type that implements Infof (like Printf) etc. -// See the documentation of V for more information. -type Verbose bool - -// V reports whether verbosity at the call site is at least the requested level. -// The returned value is a boolean of type Verbose, which implements Info, Infoln -// and Infof. These methods will write to the Info log if called. -// Thus, one may write either -// if klog.V(2) { klog.Info("log this") } -// or -// klog.V(2).Info("log this") -// The second form is shorter but the first is cheaper if logging is off because it does -// not evaluate its arguments. -// -// Whether an individual call to V generates a log record depends on the setting of -// the -v and --vmodule flags; both are off by default. If the level in the call to -// V is at least the value of -v, or of -vmodule for the source file containing the -// call, the V call will log. -func V(level Level) Verbose { - // This function tries hard to be cheap unless there's work to do. - // The fast path is two atomic loads and compares. - - // Here is a cheap but safe test to see if V logging is enabled globally. - if logging.verbosity.get() >= level { - return Verbose(true) - } - - // It's off globally but it vmodule may still be set. - // Here is another cheap but safe test to see if vmodule is enabled. - if atomic.LoadInt32(&logging.filterLength) > 0 { - // Now we need a proper lock to use the logging structure. The pcs field - // is shared so we must lock before accessing it. This is fairly expensive, - // but if V logging is enabled we're slow anyway. - logging.mu.Lock() - defer logging.mu.Unlock() - if runtime.Callers(2, logging.pcs[:]) == 0 { - return Verbose(false) - } - v, ok := logging.vmap[logging.pcs[0]] - if !ok { - v = logging.setV(logging.pcs[0]) - } - return Verbose(v >= level) - } - return Verbose(false) -} - -// Info is equivalent to the global Info function, guarded by the value of v. -// See the documentation of V for usage. -func (v Verbose) Info(args ...interface{}) { - if v { - logging.print(infoLog, args...) - } -} - -// Infoln is equivalent to the global Infoln function, guarded by the value of v. -// See the documentation of V for usage. -func (v Verbose) Infoln(args ...interface{}) { - if v { - logging.println(infoLog, args...) - } -} - -// Infof is equivalent to the global Infof function, guarded by the value of v. -// See the documentation of V for usage. -func (v Verbose) Infof(format string, args ...interface{}) { - if v { - logging.printf(infoLog, format, args...) - } -} - -// Info logs to the INFO log. -// Arguments are handled in the manner of fmt.Print; a newline is appended if missing. -func Info(args ...interface{}) { - logging.print(infoLog, args...) -} - -// InfoDepth acts as Info but uses depth to determine which call frame to log. -// InfoDepth(0, "msg") is the same as Info("msg"). -func InfoDepth(depth int, args ...interface{}) { - logging.printDepth(infoLog, depth, args...) -} - -// Infoln logs to the INFO log. -// Arguments are handled in the manner of fmt.Println; a newline is always appended. -func Infoln(args ...interface{}) { - logging.println(infoLog, args...) -} - -// Infof logs to the INFO log. -// Arguments are handled in the manner of fmt.Printf; a newline is appended if missing. -func Infof(format string, args ...interface{}) { - logging.printf(infoLog, format, args...) -} - -// Warning logs to the WARNING and INFO logs. -// Arguments are handled in the manner of fmt.Print; a newline is appended if missing. -func Warning(args ...interface{}) { - logging.print(warningLog, args...) -} - -// WarningDepth acts as Warning but uses depth to determine which call frame to log. -// WarningDepth(0, "msg") is the same as Warning("msg"). -func WarningDepth(depth int, args ...interface{}) { - logging.printDepth(warningLog, depth, args...) -} - -// Warningln logs to the WARNING and INFO logs. -// Arguments are handled in the manner of fmt.Println; a newline is always appended. -func Warningln(args ...interface{}) { - logging.println(warningLog, args...) -} - -// Warningf logs to the WARNING and INFO logs. -// Arguments are handled in the manner of fmt.Printf; a newline is appended if missing. -func Warningf(format string, args ...interface{}) { - logging.printf(warningLog, format, args...) -} - -// Error logs to the ERROR, WARNING, and INFO logs. -// Arguments are handled in the manner of fmt.Print; a newline is appended if missing. -func Error(args ...interface{}) { - logging.print(errorLog, args...) -} - -// ErrorDepth acts as Error but uses depth to determine which call frame to log. -// ErrorDepth(0, "msg") is the same as Error("msg"). -func ErrorDepth(depth int, args ...interface{}) { - logging.printDepth(errorLog, depth, args...) -} - -// Errorln logs to the ERROR, WARNING, and INFO logs. -// Arguments are handled in the manner of fmt.Println; a newline is always appended. -func Errorln(args ...interface{}) { - logging.println(errorLog, args...) -} - -// Errorf logs to the ERROR, WARNING, and INFO logs. -// Arguments are handled in the manner of fmt.Printf; a newline is appended if missing. -func Errorf(format string, args ...interface{}) { - logging.printf(errorLog, format, args...) -} - -// Fatal logs to the FATAL, ERROR, WARNING, and INFO logs, -// including a stack trace of all running goroutines, then calls os.Exit(255). -// Arguments are handled in the manner of fmt.Print; a newline is appended if missing. -func Fatal(args ...interface{}) { - logging.print(fatalLog, args...) -} - -// FatalDepth acts as Fatal but uses depth to determine which call frame to log. -// FatalDepth(0, "msg") is the same as Fatal("msg"). -func FatalDepth(depth int, args ...interface{}) { - logging.printDepth(fatalLog, depth, args...) -} - -// Fatalln logs to the FATAL, ERROR, WARNING, and INFO logs, -// including a stack trace of all running goroutines, then calls os.Exit(255). -// Arguments are handled in the manner of fmt.Println; a newline is always appended. -func Fatalln(args ...interface{}) { - logging.println(fatalLog, args...) -} - -// Fatalf logs to the FATAL, ERROR, WARNING, and INFO logs, -// including a stack trace of all running goroutines, then calls os.Exit(255). -// Arguments are handled in the manner of fmt.Printf; a newline is appended if missing. -func Fatalf(format string, args ...interface{}) { - logging.printf(fatalLog, format, args...) -} - -// fatalNoStacks is non-zero if we are to exit without dumping goroutine stacks. -// It allows Exit and relatives to use the Fatal logs. -var fatalNoStacks uint32 - -// Exit logs to the FATAL, ERROR, WARNING, and INFO logs, then calls os.Exit(1). -// Arguments are handled in the manner of fmt.Print; a newline is appended if missing. -func Exit(args ...interface{}) { - atomic.StoreUint32(&fatalNoStacks, 1) - logging.print(fatalLog, args...) -} - -// ExitDepth acts as Exit but uses depth to determine which call frame to log. -// ExitDepth(0, "msg") is the same as Exit("msg"). -func ExitDepth(depth int, args ...interface{}) { - atomic.StoreUint32(&fatalNoStacks, 1) - logging.printDepth(fatalLog, depth, args...) -} - -// Exitln logs to the FATAL, ERROR, WARNING, and INFO logs, then calls os.Exit(1). -func Exitln(args ...interface{}) { - atomic.StoreUint32(&fatalNoStacks, 1) - logging.println(fatalLog, args...) -} - -// Exitf logs to the FATAL, ERROR, WARNING, and INFO logs, then calls os.Exit(1). -// Arguments are handled in the manner of fmt.Printf; a newline is appended if missing. -func Exitf(format string, args ...interface{}) { - atomic.StoreUint32(&fatalNoStacks, 1) - logging.printf(fatalLog, format, args...) -} diff --git a/vendor/k8s.io/klog/klog_file.go b/vendor/k8s.io/klog/klog_file.go deleted file mode 100644 index e4010ad4df06a..0000000000000 --- a/vendor/k8s.io/klog/klog_file.go +++ /dev/null @@ -1,139 +0,0 @@ -// Go support for leveled logs, analogous to https://code.google.com/p/google-glog/ -// -// Copyright 2013 Google Inc. All Rights Reserved. -// -// 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. - -// File I/O for logs. - -package klog - -import ( - "errors" - "fmt" - "os" - "os/user" - "path/filepath" - "strings" - "sync" - "time" -) - -// MaxSize is the maximum size of a log file in bytes. -var MaxSize uint64 = 1024 * 1024 * 1800 - -// logDirs lists the candidate directories for new log files. -var logDirs []string - -func createLogDirs() { - if logging.logDir != "" { - logDirs = append(logDirs, logging.logDir) - } - logDirs = append(logDirs, os.TempDir()) -} - -var ( - pid = os.Getpid() - program = filepath.Base(os.Args[0]) - host = "unknownhost" - userName = "unknownuser" -) - -func init() { - h, err := os.Hostname() - if err == nil { - host = shortHostname(h) - } - - current, err := user.Current() - if err == nil { - userName = current.Username - } - - // Sanitize userName since it may contain filepath separators on Windows. - userName = strings.Replace(userName, `\`, "_", -1) -} - -// shortHostname returns its argument, truncating at the first period. -// For instance, given "www.google.com" it returns "www". -func shortHostname(hostname string) string { - if i := strings.Index(hostname, "."); i >= 0 { - return hostname[:i] - } - return hostname -} - -// logName returns a new log file name containing tag, with start time t, and -// the name for the symlink for tag. -func logName(tag string, t time.Time) (name, link string) { - name = fmt.Sprintf("%s.%s.%s.log.%s.%04d%02d%02d-%02d%02d%02d.%d", - program, - host, - userName, - tag, - t.Year(), - t.Month(), - t.Day(), - t.Hour(), - t.Minute(), - t.Second(), - pid) - return name, program + "." + tag -} - -var onceLogDirs sync.Once - -// create creates a new log file and returns the file and its filename, which -// contains tag ("INFO", "FATAL", etc.) and t. If the file is created -// successfully, create also attempts to update the symlink for that tag, ignoring -// errors. -// The startup argument indicates whether this is the initial startup of klog. -// If startup is true, existing files are opened for appending instead of truncated. -func create(tag string, t time.Time, startup bool) (f *os.File, filename string, err error) { - if logging.logFile != "" { - f, err := openOrCreate(logging.logFile, startup) - if err == nil { - return f, logging.logFile, nil - } - return nil, "", fmt.Errorf("log: unable to create log: %v", err) - } - onceLogDirs.Do(createLogDirs) - if len(logDirs) == 0 { - return nil, "", errors.New("log: no log dirs") - } - name, link := logName(tag, t) - var lastErr error - for _, dir := range logDirs { - fname := filepath.Join(dir, name) - f, err := openOrCreate(fname, startup) - if err == nil { - symlink := filepath.Join(dir, link) - os.Remove(symlink) // ignore err - os.Symlink(name, symlink) // ignore err - return f, fname, nil - } - lastErr = err - } - return nil, "", fmt.Errorf("log: cannot create log: %v", lastErr) -} - -// The startup argument indicates whether this is the initial startup of klog. -// If startup is true, existing files are opened for appending instead of truncated. -func openOrCreate(name string, startup bool) (*os.File, error) { - if startup { - f, err := os.OpenFile(name, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666) - return f, err - } - f, err := os.Create(name) - return f, err -} diff --git a/vendor/k8s.io/utils/integer/integer.go b/vendor/k8s.io/utils/integer/integer.go index e0811e8344c52..f64d64955b4fc 100644 --- a/vendor/k8s.io/utils/integer/integer.go +++ b/vendor/k8s.io/utils/integer/integer.go @@ -18,7 +18,8 @@ package integer import "math" -// IntMax returns the maximum of the params +// IntMax returns the maximum of the params. +// Deprecated: for new code, use the max() builtin instead. func IntMax(a, b int) int { if b > a { return b @@ -26,7 +27,8 @@ func IntMax(a, b int) int { return a } -// IntMin returns the minimum of the params +// IntMin returns the minimum of the params. +// Deprecated: for new code, use the min() builtin instead. func IntMin(a, b int) int { if b < a { return b @@ -34,7 +36,8 @@ func IntMin(a, b int) int { return a } -// Int32Max returns the maximum of the params +// Int32Max returns the maximum of the params. +// Deprecated: for new code, use the max() builtin instead. func Int32Max(a, b int32) int32 { if b > a { return b @@ -42,7 +45,8 @@ func Int32Max(a, b int32) int32 { return a } -// Int32Min returns the minimum of the params +// Int32Min returns the minimum of the params. +// Deprecated: for new code, use the min() builtin instead. func Int32Min(a, b int32) int32 { if b < a { return b @@ -50,7 +54,8 @@ func Int32Min(a, b int32) int32 { return a } -// Int64Max returns the maximum of the params +// Int64Max returns the maximum of the params. +// Deprecated: for new code, use the max() builtin instead. func Int64Max(a, b int64) int64 { if b > a { return b @@ -58,7 +63,8 @@ func Int64Max(a, b int64) int64 { return a } -// Int64Min returns the minimum of the params +// Int64Min returns the minimum of the params. +// Deprecated: for new code, use the min() builtin instead. func Int64Min(a, b int64) int64 { if b < a { return b diff --git a/vendor/modules.txt b/vendor/modules.txt index 52b26a5beb8c6..d4483761ccbfa 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -1036,10 +1036,9 @@ github.com/grafana/tail/ratelimiter github.com/grafana/tail/util github.com/grafana/tail/watch github.com/grafana/tail/winfile -# github.com/grpc-ecosystem/go-grpc-middleware v1.4.0 -## explicit; go 1.14 -github.com/grpc-ecosystem/go-grpc-middleware -github.com/grpc-ecosystem/go-grpc-middleware/recovery +# github.com/grpc-ecosystem/go-grpc-middleware/v2 v2.1.0 +## explicit; go 1.19 +github.com/grpc-ecosystem/go-grpc-middleware/v2/interceptors/recovery # github.com/grpc-ecosystem/grpc-opentracing v0.0.0-20180507213350-8e809c8a8645 ## explicit github.com/grpc-ecosystem/grpc-opentracing/go/otgrpc @@ -1533,9 +1532,9 @@ github.com/shurcooL/vfsgen # github.com/sirupsen/logrus v1.9.3 ## explicit; go 1.13 github.com/sirupsen/logrus -# github.com/sony/gobreaker v0.5.0 -## explicit; go 1.12 -github.com/sony/gobreaker +# github.com/sony/gobreaker/v2 v2.0.0 +## explicit; go 1.21 +github.com/sony/gobreaker/v2 # github.com/spaolacci/murmur3 v1.1.0 ## explicit github.com/spaolacci/murmur3 @@ -1935,7 +1934,7 @@ golang.org/x/tools/internal/stdlib golang.org/x/tools/internal/tokeninternal golang.org/x/tools/internal/typesinternal golang.org/x/tools/internal/versions -# google.golang.org/api v0.206.0 +# google.golang.org/api v0.207.0 ## explicit; go 1.21 google.golang.org/api/cloudresourcemanager/v1 google.golang.org/api/compute/v1 @@ -1956,7 +1955,7 @@ google.golang.org/api/transport google.golang.org/api/transport/grpc google.golang.org/api/transport/http google.golang.org/api/transport/http/internal/propagation -# google.golang.org/genproto v0.0.0-20241104194629-dd2ea8efbc28 +# google.golang.org/genproto v0.0.0-20241113202542-65e8d215514f ## explicit; go 1.21 google.golang.org/genproto/googleapis/type/calendarperiod google.golang.org/genproto/googleapis/type/date @@ -1971,7 +1970,7 @@ google.golang.org/genproto/googleapis/api/expr/v1alpha1 google.golang.org/genproto/googleapis/api/label google.golang.org/genproto/googleapis/api/metric google.golang.org/genproto/googleapis/api/monitoredres -# google.golang.org/genproto/googleapis/rpc v0.0.0-20241104194629-dd2ea8efbc28 +# google.golang.org/genproto/googleapis/rpc v0.0.0-20241113202542-65e8d215514f ## explicit; go 1.21 google.golang.org/genproto/googleapis/rpc/code google.golang.org/genproto/googleapis/rpc/errdetails @@ -2417,9 +2416,6 @@ k8s.io/client-go/util/flowcontrol k8s.io/client-go/util/homedir k8s.io/client-go/util/keyutil k8s.io/client-go/util/workqueue -# k8s.io/klog v1.0.0 -## explicit; go 1.12 -k8s.io/klog # k8s.io/klog/v2 v2.130.1 ## explicit; go 1.18 k8s.io/klog/v2 @@ -2440,7 +2436,7 @@ k8s.io/kube-openapi/pkg/schemaconv k8s.io/kube-openapi/pkg/spec3 k8s.io/kube-openapi/pkg/util/proto k8s.io/kube-openapi/pkg/validation/spec -# k8s.io/utils v0.0.0-20240902221715-702e33fdd3c3 +# k8s.io/utils v0.0.0-20241104163129-6fe5fd82f078 ## explicit; go 1.18 k8s.io/utils/buffer k8s.io/utils/clock