diff --git a/.custom-gcl.yaml b/.custom-gcl.yaml index a9a8a587fbd..12b679bafd4 100644 --- a/.custom-gcl.yaml +++ b/.custom-gcl.yaml @@ -1,4 +1,4 @@ -version: v2.6.1 +version: v2.7.2 name: golangci-kube-api-linter destination: ./tmp/bin/ plugins: diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md index 0d3caacf1cc..0cf51842f38 100644 --- a/.github/PULL_REQUEST_TEMPLATE.md +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -2,9 +2,11 @@ _Describe the big picture of your changes here to communicate to the maintainers why we should accept this pull request._ -_If it fixes an existing issue (bug or feature), use the following keyword:_ + -_Closes: #ISSUE-NUMBER_ +Closes: #ISSUE-NUMBER + +If you're contributing for the first-time, check our [contribution guidelines](../CONTRIBUTING.md). ## Type of change diff --git a/.github/env b/.github/env index d2f562d887d..d4c4401e379 100644 --- a/.github/env +++ b/.github/env @@ -1,4 +1,4 @@ -golang-version=1.24 +golang-version=1.25 kind-version=v0.30.0 -kind-image=kindest/node:v1.34.0 -golangci-lint-version=v2.7.0 +kind-image=kindest/node:v1.34.2 +golangci-lint-version=v2.7.2 diff --git a/.github/workflows/actionlint.yml b/.github/workflows/actionlint.yml index 3f3e3a8ad9e..4df73d03f34 100644 --- a/.github/workflows/actionlint.yml +++ b/.github/workflows/actionlint.yml @@ -12,7 +12,7 @@ jobs: runs-on: ubuntu-latest steps: - name: Checkout code - uses: actions/checkout@v5 + uses: actions/checkout@v6 - name: Download actionlint id: get_actionlint run: bash <(curl https://raw.githubusercontent.com/rhysd/actionlint/v1.7.4/scripts/download-actionlint.bash) diff --git a/.github/workflows/changed-files.yaml b/.github/workflows/changed-files.yaml index 048f790fe98..dfb0ece005b 100644 --- a/.github/workflows/changed-files.yaml +++ b/.github/workflows/changed-files.yaml @@ -16,7 +16,7 @@ jobs: steps: - name: checkout repo id: checkout - uses: actions/checkout@v5 + uses: actions/checkout@v6 with: fetch-depth: 0 - name: get changed files diff --git a/.github/workflows/checks.yaml b/.github/workflows/checks.yaml index 34c7b05e8a3..70985544790 100644 --- a/.github/workflows/checks.yaml +++ b/.github/workflows/checks.yaml @@ -22,7 +22,7 @@ jobs: - ubuntu-latest name: Generate and format steps: - - uses: actions/checkout@v5 + - uses: actions/checkout@v6 - name: Import environment variables from file run: cat ".github/env" >> "$GITHUB_ENV" - uses: actions/setup-go@v6 @@ -37,7 +37,7 @@ jobs: runs-on: ubuntu-latest name: Check Documentation formatting and links steps: - - uses: actions/checkout@v5 + - uses: actions/checkout@v6 - name: Import environment variables from file run: cat ".github/env" >> "$GITHUB_ENV" - uses: actions/setup-go@v6 @@ -52,7 +52,7 @@ jobs: runs-on: ubuntu-latest name: Golang linter steps: - - uses: actions/checkout@v5 + - uses: actions/checkout@v6 - name: Import environment variables from file run: cat ".github/env" >> "$GITHUB_ENV" - uses: actions/setup-go@v6 @@ -62,7 +62,7 @@ jobs: - name: Check go.mod run: make tidy && git diff --exit-code - name: Run golangci-lint - uses: golangci/golangci-lint-action@v9.0.0 + uses: golangci/golangci-lint-action@v9.2.0 with: version: '${{ env.golangci-lint-version }}' args: --timeout 10m0s @@ -74,7 +74,7 @@ jobs: runs-on: ubuntu-latest name: Check prometheus metrics steps: - - uses: actions/checkout@v5 + - uses: actions/checkout@v6 - name: Import environment variables from file run: cat ".github/env" >> "$GITHUB_ENV" - uses: actions/setup-go@v6 @@ -92,7 +92,7 @@ jobs: - ubuntu-latest name: Build operator binary steps: - - uses: actions/checkout@v5 + - uses: actions/checkout@v6 - name: Import environment variables from file run: cat ".github/env" >> "$GITHUB_ENV" - uses: actions/setup-go@v6 @@ -105,7 +105,7 @@ jobs: runs-on: ubuntu-latest name: Build Prometheus Operator rule config map to rule file CRDs CLI tool steps: - - uses: actions/checkout@v5 + - uses: actions/checkout@v6 - name: Import environment variables from file run: cat ".github/env" >> "$GITHUB_ENV" - uses: actions/setup-go@v6 diff --git a/.github/workflows/cspell.json b/.github/workflows/cspell.json index 13e516098af..9e1d9ef2813 100644 --- a/.github/workflows/cspell.json +++ b/.github/workflows/cspell.json @@ -419,6 +419,7 @@ "finalizer", "selfsigned", "FIPS", - "FIPSSTS" + "FIPSSTS", + "checkmark" ] } diff --git a/.github/workflows/e2e-feature-gated.yaml b/.github/workflows/e2e-feature-gated.yaml index 09bb29bf167..610dbef5e58 100644 --- a/.github/workflows/e2e-feature-gated.yaml +++ b/.github/workflows/e2e-feature-gated.yaml @@ -22,7 +22,7 @@ jobs: if: ${{ needs.changed-files.outputs.non-markdown-files }} runs-on: ubuntu-latest steps: - - uses: actions/checkout@v5 + - uses: actions/checkout@v6 - name: Setup E2E environment uses: ./.github/actions/setup-e2e # composite action with your setup steps @@ -34,7 +34,7 @@ jobs: make test-e2e-feature-gates - name: Upload diagnostics artifact if: ${{ failure() }} - uses: actions/upload-artifact@v5 + uses: actions/upload-artifact@v6 with: name: cluster-state path: ${{ env.E2E_DIAGNOSTIC_DIRECTORY }} diff --git a/.github/workflows/e2e-prometheus-v2.yaml b/.github/workflows/e2e-prometheus-v2.yaml index 140a452ed5f..66649c3df5d 100644 --- a/.github/workflows/e2e-prometheus-v2.yaml +++ b/.github/workflows/e2e-prometheus-v2.yaml @@ -27,7 +27,7 @@ jobs: - suite: operatorUpgrade target: test-e2e-operator-upgrade steps: - - uses: actions/checkout@v5 + - uses: actions/checkout@v6 - name: Setup E2E environment uses: ./.github/actions/setup-e2e # composite action with your setup steps diff --git a/.github/workflows/e2e.yaml b/.github/workflows/e2e.yaml index aa7b078dfae..83082e8cc37 100644 --- a/.github/workflows/e2e.yaml +++ b/.github/workflows/e2e.yaml @@ -37,7 +37,7 @@ jobs: - suite: operatorUpgrade target: test-e2e-operator-upgrade steps: - - uses: actions/checkout@v5 + - uses: actions/checkout@v6 - name: Setup E2E environment uses: ./.github/actions/setup-e2e # composite action with your setup steps @@ -49,7 +49,7 @@ jobs: make ${{ matrix.target }} - name: Upload diagnostics artifact if: ${{ failure() }} - uses: actions/upload-artifact@v5 + uses: actions/upload-artifact@v6 with: name: cluster-state path: ${{ env.E2E_DIAGNOSTIC_DIRECTORY }} diff --git a/.github/workflows/publish.yaml b/.github/workflows/publish.yaml index 00ba67a1962..da756815a53 100644 --- a/.github/workflows/publish.yaml +++ b/.github/workflows/publish.yaml @@ -22,7 +22,7 @@ jobs: steps: - name: Checkout - uses: actions/checkout@v5 + uses: actions/checkout@v6 - name: Import environment variables from file run: cat ".github/env" >> "$GITHUB_ENV" - name: Reclaim disk space diff --git a/.github/workflows/release.yaml b/.github/workflows/release.yaml index e64dd0cb989..23dc9355c1a 100644 --- a/.github/workflows/release.yaml +++ b/.github/workflows/release.yaml @@ -10,7 +10,7 @@ jobs: name: Upload release assets steps: - name: Checkout - uses: actions/checkout@v5 + uses: actions/checkout@v6 - name: Import environment variables from file run: cat ".github/env" >> "$GITHUB_ENV" - name: Install Go diff --git a/.github/workflows/spell-check.yaml b/.github/workflows/spell-check.yaml index fcb173680a7..dfa46bdb516 100644 --- a/.github/workflows/spell-check.yaml +++ b/.github/workflows/spell-check.yaml @@ -13,9 +13,9 @@ jobs: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v5 + - uses: actions/checkout@v6 - name: Run cSpell - uses: streetsidesoftware/cspell-action@76c6f6d52abd57f4bcab5f3fde1bbd4f19a99eb0 + uses: streetsidesoftware/cspell-action@24fa8d3096a314ce263f39578744e9d9f8d80acf with: incremental_files_only: false files: "**/*.{md,yaml,yml}" diff --git a/.github/workflows/test-prom-version-upgrade.yaml b/.github/workflows/test-prom-version-upgrade.yaml index 793a3004e21..77a90853a85 100644 --- a/.github/workflows/test-prom-version-upgrade.yaml +++ b/.github/workflows/test-prom-version-upgrade.yaml @@ -15,7 +15,7 @@ jobs: docker image prune --force --all sudo rm -rf /usr/share/dotnet sudo rm -rf /usr/local/lib/android - - uses: actions/checkout@v5 + - uses: actions/checkout@v6 - name: Import environment variables from file run: | cat ".github/env" >> "$GITHUB_ENV" @@ -49,7 +49,7 @@ jobs: make test-e2e-prometheus-upgrade - name: Upload diagnostics artifact if: ${{ failure() }} - uses: actions/upload-artifact@v5 + uses: actions/upload-artifact@v6 with: name: cluster-state path: ${{ env.E2E_DIAGNOSTIC_DIRECTORY }} diff --git a/.github/workflows/unit.yaml b/.github/workflows/unit.yaml index f4bd07e2d74..8cec0e95329 100644 --- a/.github/workflows/unit.yaml +++ b/.github/workflows/unit.yaml @@ -21,7 +21,7 @@ jobs: needs: changed-files if: ${{ needs.changed-files.outputs.non-markdown-files }} steps: - - uses: actions/checkout@v5 + - uses: actions/checkout@v6 - name: Import environment variables from file run: cat ".github/env" >> "$GITHUB_ENV" - uses: actions/setup-go@v6 @@ -35,7 +35,7 @@ jobs: needs: changed-files if: ${{ needs.changed-files.outputs.non-markdown-files }} steps: - - uses: actions/checkout@v5 + - uses: actions/checkout@v6 - name: Import environment variables from file run: cat ".github/env" >> "$GITHUB_ENV" - uses: actions/setup-go@v6 diff --git a/.golangci-kal.yml b/.golangci-kal.yml index b3bac2df1c6..99fbfb5adf1 100644 --- a/.golangci-kal.yml +++ b/.golangci-kal.yml @@ -6,7 +6,7 @@ # https://github.com/kubernetes-sigs/kube-api-linter/blob/main/docs/linters.md version: "2" run: - go: "1.24" + go: "1.25" allow-parallel-runners: true linters: default: none @@ -23,6 +23,7 @@ linters: # Whenever a new linter is added, it should not break the backward # compatibility of existing APIs (at least for v1 APIs). enable: + - "nobools" - "commentstart" - "conflictingmarkers" - "duplicatemarkers" @@ -34,6 +35,8 @@ linters: - "statusoptional" - "nophase" - "nonullable" + - "forbiddenmarkers" + - "nomaps" disable: - "*" lintersConfig: @@ -44,7 +47,14 @@ linters: - ["default", "kubebuilder:default"] - ["required", "kubebuilder:validation:Required", "k8s:required"] description: "A field with a default value cannot be required" - + forbiddenmarkers: + markers: + - identifier: "+kubebuilder:pruning:PreserveUnknownFields" + - identifier: "+kubebuilder:validation:XPreserveUnknownFields" + - identifier: "+kubebuilder:validation:items:XPreserveUnknownFields" + - identifier: "+kubebuilder:validation:EmbeddedResource" + - identifier: "+kubebuilder:validation:XEmbeddedResource" + - identifier: "+kubebuilder:validation:items:XEmbeddedResource" exclusions: generated: strict paths: @@ -55,4 +65,4 @@ linters: # KAL only validates the API folders. - path-except: pkg/apis/monitoring/ linters: - - kubeapilinter + - kubeapilinter \ No newline at end of file diff --git a/.golangci.yml b/.golangci.yml index 6a6de721dc8..e16023ad5a1 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -1,6 +1,6 @@ version: "2" run: - go: "1.24" + go: "1.25" timeout: 10m modules-download-mode: readonly allow-parallel-runners: true diff --git a/.mdox.validate.yaml b/.mdox.validate.yaml index 442e04b17e4..908875eb2a5 100644 --- a/.mdox.validate.yaml +++ b/.mdox.validate.yaml @@ -6,51 +6,12 @@ random_delay: 1s explicitLocalValidators: true validators: - # Skip localhost examples. - - regex: 'localhost' - type: "ignore" - # docs.github.com returns 403 if not in browser. Cannot curl as well. - - regex: 'docs\.github\.com' - type: "ignore" - # Cloudflare protection, so returns 503 if not in browser. Cannot curl as well. - - regex: 'wise\.com' - type: "ignore" - # Adopters example link. - - regex: "our-link" - type: "ignore" - # 301 errors even when curl-ed. - - regex: "envoyproxy" - type: "ignore" - # Ignore release links. - - regex: 'https:\/\/github\.com\/prometheus-operator\/prometheus-operator\/releases' - type: "ignore" - # Ignore GitHub container packages link as it returns 404 in curl, but works in browser - - regex: 'https://github.com/prometheus-operator/prometheus-operator/pkgs/container/prometheus-operator' + # Ignore all external URLs because of rate-limiting protections which make the tests very flaky. + - regex: '^http(s)?://.+' type: "ignore" # Ignore links to /img/ because the generated content will resolve them correctly. - regex: '/img/.+' type: ignore - # Twitter changed their policy and now returns 403 if not authenticated. We can guarantee this link since we own the account. - - regex: 'https:\/\/twitter.com\/PromOperator' - type: ignore # Ignore anchor links pointing to the API documentation which are HTML tags and not supported by mdox. - regex: 'api\.md#monitoring\.coreos\.com/v1\.(BasicAuth|PrometheusSpec|StorageSpec)$' type: ignore - # Ignore dead links from Ambassador (soon to be removed). - - regex: 'getambassador' - type: ignore - # Ignore all github.com URLs because of rate limiting. - # TODO: find an alternative way to check these URLs avoiding the rate limiting. - - regex: 'github.com' - type: ignore - # Ignore all istio.io URLs because of http request timeout. - - regex: 'istio.io' - type: ignore - # Medium rejects bot's requests. - - regex: 'medium.com' - type: ignore - # Use the githubPullsIssues validator to avoid rate-limiting. - - regex: '(^http[s]?:\/\/)(www\.)?(github\.com\/)prometheus-operator\/prometheus-operator(\/pull\/|\/issues\/)' - type: githubPullsIssues - # The GitHub actions running mdox configure the GITHUB_TOKEN environment variable. - token: '$(GITHUB_TOKEN)' diff --git a/CHANGELOG.md b/CHANGELOG.md index 9407fa2aa78..14b81f8362b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,29 @@ +## 0.88.0 / 2026-01-09 + +* [CHANGE] Use narrower selectors for StatefulSet informers in `Alertmanager` and `ThanosRuler` controllers. It is recommended to upgrade from `v0.85.0` (at least). #8246 +* [CHANGE] Reject `EC2/Lightsail` SD for Prometheus >= 3.8.0 in `ScrapeConfig` CRD. #8175 +* [FEATURE] Add `podManagementPolicy` field to `Prometheus`, `PrometheusAgent`, `Alertmanager` and `ThanosRuler` CRDs. #8119 +* [FEATURE] Add `updateStrategy` field to `Prometheus`, `PrometheusAgent`, `Alertmanager` and `ThanosRuler` CRDs. #8202 +* [FEATURE] Add `scrapeNativeHistograms` field to `Prometheus`, `PrometheusAgent`, `ServiceMonitor`, `PodMonitor`, `Probe` and `ScrapeConfig` CRDs. #8102 +* [FEATURE] Add `scope` field to `AzureAD` remote write configuration. #8240 +* [FEATURE] Add `workloadIdentity` field to `AzureAD` remote write configuration. #7998 +* [FEATURE] Add support for PrometheusRule fields `groupLabels` and `queryOffset` in `ThanosRuler`. #8137 +* [FEATURE] Add `slackAppToken` and `slackAppUrl` fields to Alertmanager global config for Slack App support. #8238 +* [FEATURE] Add `incident.io` receiver support to `Alertmanager` config secret. #8190 #8245 #8228 +* [FEATURE] Add `Mattermost` receiver support to `Alertmanager` config secret. #8188 +* [FEATURE] Add `apiType` field to `Jira` receiver in `Alertmanager` config secret. #8218 +* [FEATURE] Add `timeout` field to `PagerDuty` receiver in `AlertmanagerConfig` CRD. #8162 +* [FEATURE] Add `timeout` field to `Slack` receiver in `AlertmanagerConfig` CRD. #8161 +* [ENHANCEMENT] Use `minReadySeconds` to set `--dispatch.start-delay` in `Alertmanager`. #8177 #8201 +* [ENHANCEMENT] Expose native histograms in operator metrics. #8194 +* [ENHANCEMENT] Add `NoSelectedResources` reason to status conditions. #8124 +* [ENHANCEMENT] Add `enableHttp2` and `followRedirects` fields to HTTP configuration for `Probe` CRD. #8112 +* [ENHANCEMENT] Add CEL validations for `DaemonSet` mode in `PrometheusAgent` CRD (requires the `PrometheusAgentDaemonSetFeature` featuregate). #7881 +* [ENHANCEMENT] Improve validation for `Pushover`, `PagerDuty` and `VictorOps` receivers in `AlertmanagerConfig` CRD. #8239 #8113 #8220 +* [ENHANCEMENT] Add `apiURL` validation for `WeChat`, `OpsGenie` and `Telegram` receivers in `AlertmanagerConfig` CRD. #8196 #8206 #8199 +* [ENHANCEMENT] Validate URL fields in `AlertmanagerConfig` receivers (`MSTeams`, `Webhook`). #8231 #8125 +* [ENHANCEMENT] Validate URL fields in `Alertmanager` configuration secret (`WeChat`, `Telegram`, `Pushover` receivers). #7977 #8233 #8232 + ## 0.87.1 / 2025-12-10 * [BUGFIX] Fix the generated Alertmanager configuration for `html` and `monospace` fields of `pushoverConfig` receiver in AlertmanagerConfig CRD. #8153 diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index ad7256f5b63..2501a9db63e 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -115,6 +115,30 @@ second line is always blank, and other lines should be wrapped at 80 characters. This allows the message to be easier to read on GitHub as well as in various Git tools. +## AI use policy + +We allow the use of AI tools when contributing to the project (issues and pull +requests). At the same time, you need to be mindful of maintainers' time and +attention which is why we ask you to comply with the following guidelines. + +### When using AI for learning + +* Keep in mind that while AI assistants help with navigating and understanding the code base, you need to take their claims with a grain of salt. +* Using AI tools doesn't prevent you from becoming familiar with the code and the development workflow. + +### When using AI for communication + +* Follow the proposed template when submitting GitHub issues. +* Avoid verbose descriptions, provide enough information for the maintainers to understand the request but do not overwhelm them with unrelated details. + +### When using AI for code contribution + +* Review the change by yourself before submitting the pull request. +* Ensure that you can explain the why, what and how of the change without help from the AI tool. +* If necessary call out the parts which are unclear to you. +* When AI tools have contributed significant parts of the code change, communicate the information in the pull request's description and/or the commit message. +* Don't submit changes which are unrelated to the purpose of the pull request. + ## Local Development If you want to run Prometheus Operator on your local environment, you can follow the steps below. diff --git a/Dockerfile b/Dockerfile index 6031fcf364b..ee43ddfa42d 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,6 +1,6 @@ ARG ARCH=amd64 ARG OS=linux -ARG GOLANG_BUILDER=1.24 +ARG GOLANG_BUILDER=1.25 FROM quay.io/prometheus/golang-builder:${GOLANG_BUILDER}-base AS builder WORKDIR /workspace diff --git a/Documentation/api-reference/api.md b/Documentation/api-reference/api.md index 820d4b9b96b..7b6cb46ca05 100644 --- a/Documentation/api-reference/api.md +++ b/Documentation/api-reference/api.md @@ -599,6 +599,43 @@ UI, not the gossip communication.

+podManagementPolicy
+ +
+PodManagementPolicyType + + + + +(Optional) +

podManagementPolicy defines the policy for creating/deleting pods when +scaling up and down.

+

Unlike the default StatefulSet behavior, the default policy is +Parallel to avoid manual intervention in case a pod gets stuck during +a rollout.

+

Note that updating this value implies the recreation of the StatefulSet +which incurs a service outage.

+ + + + +updateStrategy
+ + +StatefulSetUpdateStrategy + + + + +(Optional) +

updateStrategy indicates the strategy that will be employed to update +Pods in the StatefulSet when a revision is made to statefulset’s Pod +Template.

+

The default strategy is RollingUpdate.

+ + + + containers
@@ -812,9 +849,16 @@ int32 (Optional) -

minReadySeconds defines the minimum number of seconds for which a newly created pod should be ready -without any of its container crashing for it to be considered available.

+

minReadySeconds defines the minimum number of seconds for which a newly +created pod should be ready without any of its container crashing for it +to be considered available.

If unset, pods will be considered available as soon as they are ready.

+

When the Alertmanager version is greater than or equal to v0.30.0, the +duration is also used to delay the first flush of the aggregation +groups. This delay helps ensuring that all alerts have been resent by +the Prometheus instances to Alertmanager after a roll-out. It is +possible to override this behavior passing a custom value via +.spec.additionalArgs.

@@ -1246,6 +1290,19 @@ uint64 +scrapeNativeHistograms
+ +bool + + + +(Optional) +

scrapeNativeHistograms defines whether to enable scraping of native histograms. +It requires Prometheus >= v3.8.0.

+ + + + scrapeClassicHistograms
bool @@ -1534,65 +1591,6 @@ The value cannot be greater than the scrape interval otherwise the operator will -tlsConfig
- -
-SafeTLSConfig - - - - -(Optional) -

tlsConfig defines the TLS configuration to use when scraping the endpoint.

- - - - -bearerTokenSecret
- - -Kubernetes core/v1.SecretKeySelector - - - - -(Optional) -

bearerTokenSecret defines the secret to mount to read bearer token for scraping targets. The secret -needs to be in the same namespace as the probe and accessible by -the Prometheus Operator.

- - - - -basicAuth
- - -BasicAuth - - - - -(Optional) -

basicAuth allow an endpoint to authenticate over basic authentication. -More info: https://prometheus.io/docs/operating/configuration/#endpoint

- - - - -oauth2
- - -OAuth2 - - - - -(Optional) -

oauth2 for the URL. Only valid in Prometheus versions 2.27.0 and newer.

- - - - metricRelabelings
@@ -1716,6 +1714,19 @@ Only valid in Prometheus versions 2.27.0 and newer.

+scrapeNativeHistograms
+ +bool + + + +(Optional) +

scrapeNativeHistograms defines whether to enable scraping of native histograms. +It requires Prometheus >= v3.8.0.

+ + + + scrapeClassicHistograms
bool @@ -1813,6 +1824,112 @@ Please note that the .spec.module field takes precedence over the < The module name must be added using Module under ProbeSpec.

+ + +authorization
+ +
+SafeAuthorization + + + + +(Optional) +

authorization configures the Authorization header credentials used by +the client.

+

Cannot be set at the same time as basicAuth, bearerTokenSecret or oauth2.

+ + + + +basicAuth
+ + +BasicAuth + + + + +(Optional) +

basicAuth defines the Basic Authentication credentials used by the +client.

+

Cannot be set at the same time as authorization, bearerTokenSecret or oauth2.

+ + + + +oauth2
+ + +OAuth2 + + + + +(Optional) +

oauth2 defines the OAuth2 settings used by the client.

+

It requires Prometheus >= 2.27.0.

+

Cannot be set at the same time as authorization, basicAuth or bearerTokenSecret.

+ + + + +bearerTokenSecret
+ + +Kubernetes core/v1.SecretKeySelector + + + + +(Optional) +

bearerTokenSecret defines a key of a Secret containing the bearer token +used by the client for authentication. The secret needs to be in the +same namespace as the custom resource and readable by the Prometheus +Operator.

+

Cannot be set at the same time as authorization, basicAuth or oauth2.

+

Deprecated: use authorization instead.

+ + + + +followRedirects
+ +bool + + + +(Optional) +

followRedirects defines whether the client should follow HTTP 3xx +redirects.

+ + + + +enableHttp2
+ +bool + + + +(Optional) +

enableHttp2 can be used to disable HTTP2.

+ + + + +tlsConfig
+ + +SafeTLSConfig + + + + +(Optional) +

tlsConfig defines the TLS configuration used by the client.

+ + @@ -2709,6 +2826,43 @@ instead of the Pod IP’s address.

+podManagementPolicy
+ + +PodManagementPolicyType + + + + +(Optional) +

podManagementPolicy defines the policy for creating/deleting pods when +scaling up and down.

+

Unlike the default StatefulSet behavior, the default policy is +Parallel to avoid manual intervention in case a pod gets stuck during +a rollout.

+

Note that updating this value implies the recreation of the StatefulSet +which incurs a service outage.

+ + + + +updateStrategy
+ + +StatefulSetUpdateStrategy + + + + +(Optional) +

updateStrategy indicates the strategy that will be employed to update +Pods in the StatefulSet when a revision is made to statefulset’s Pod +Template.

+

The default strategy is RollingUpdate.

+ + + + enableServiceLinks
bool @@ -3129,6 +3283,19 @@ histogram with custom buckets.

+scrapeNativeHistograms
+ +bool + + + +(Optional) +

scrapeNativeHistograms defines whether to enable scraping of native histograms. +It requires Prometheus >= v3.8.0.

+ + + + scrapeClassicHistograms
bool @@ -3255,8 +3422,8 @@ PodMonitor and ServiceMonitor objects.

tracingConfig
- -PrometheusTracingConfig + +TracingConfig @@ -4284,6 +4451,19 @@ uint64 +scrapeNativeHistograms
+ +bool + + + +(Optional) +

scrapeNativeHistograms defines whether to enable scraping of native histograms. +It requires Prometheus >= v3.8.0.

+ + + + scrapeClassicHistograms
bool @@ -4856,6 +5036,43 @@ does not bind against the Pod IP.

+podManagementPolicy
+ + +PodManagementPolicyType + + + + +(Optional) +

podManagementPolicy defines the policy for creating/deleting pods when +scaling up and down.

+

Unlike the default StatefulSet behavior, the default policy is +Parallel to avoid manual intervention in case a pod gets stuck during +a rollout.

+

Note that updating this value implies the recreation of the StatefulSet +which incurs a service outage.

+ + + + +updateStrategy
+ + +StatefulSetUpdateStrategy + + + + +(Optional) +

updateStrategy indicates the strategy that will be employed to update +Pods in the StatefulSet when a revision is made to statefulset’s Pod +Template.

+

The default strategy is RollingUpdate.

+ + + + queryEndpoints
[]string @@ -6178,8 +6395,8 @@ This has no impact on alerts from Prometheus, as they always include EndsAt.

httpConfig
- -HTTPConfig + +HTTPConfigWithProxy @@ -6311,7 +6528,7 @@ GlobalWebexConfig (Optional) -

webex defines the default configuration for Jira.

+

webex defines the default configuration for Webex.

@@ -6894,6 +7111,43 @@ UI, not the gossip communication.

+podManagementPolicy
+ + +PodManagementPolicyType + + + + +(Optional) +

podManagementPolicy defines the policy for creating/deleting pods when +scaling up and down.

+

Unlike the default StatefulSet behavior, the default policy is +Parallel to avoid manual intervention in case a pod gets stuck during +a rollout.

+

Note that updating this value implies the recreation of the StatefulSet +which incurs a service outage.

+ + + + +updateStrategy
+ + +StatefulSetUpdateStrategy + + + + +(Optional) +

updateStrategy indicates the strategy that will be employed to update +Pods in the StatefulSet when a revision is made to statefulset’s Pod +Template.

+

The default strategy is RollingUpdate.

+ + + + containers
@@ -7107,9 +7361,16 @@ int32 (Optional) -

minReadySeconds defines the minimum number of seconds for which a newly created pod should be ready -without any of its container crashing for it to be considered available.

+

minReadySeconds defines the minimum number of seconds for which a newly +created pod should be ready without any of its container crashing for it +to be considered available.

If unset, pods will be considered available as soon as they are ready.

+

When the Alertmanager version is greater than or equal to v0.30.0, the +duration is also used to delay the first flush of the aggregation +groups. This delay helps ensuring that all alerts have been resent by +the Prometheus instances to Alertmanager after a roll-out. It is +possible to override this behavior passing a custom value via +.spec.additionalArgs.

@@ -7657,7 +7918,7 @@ ManagedIdentity (Optional)

managedIdentity defines the Azure User-assigned Managed identity. -Cannot be set at the same time as oauth or sdk.

+Cannot be set at the same time as oauth, sdk or workloadIdentity.

@@ -7672,7 +7933,7 @@ AzureOAuth (Optional)

oauth defines the oauth config that is being used to authenticate. -Cannot be set at the same time as managedIdentity or sdk.

+Cannot be set at the same time as managedIdentity, sdk or workloadIdentity.

It requires Prometheus >= v2.48.0 or Thanos >= v0.31.0.

@@ -7689,10 +7950,39 @@ AzureSDK (Optional)

sdk defines the Azure SDK config that is being used to authenticate. See https://learn.microsoft.com/en-us/azure/developer/go/azure-sdk-authentication -Cannot be set at the same time as oauth or managedIdentity.

+Cannot be set at the same time as oauth, managedIdentity or workloadIdentity.

It requires Prometheus >= v2.52.0 or Thanos >= v0.36.0.

+ + +workloadIdentity
+ + +AzureWorkloadIdentity + + + + +(Optional) +

workloadIdentity defines the Azure Workload Identity authentication. +Cannot be set at the same time as oauth, managedIdentity, or sdk.

+

It requires Prometheus >= 3.7.0. Currently not supported by Thanos.

+ + + + +scope
+ +string + + + +(Optional) +

scope is the custom OAuth 2.0 scope to request when acquiring tokens. +It requires Prometheus >= 3.9.0. Currently not supported by Thanos.

+ +

AzureOAuth @@ -7778,10 +8068,50 @@ string +

AzureWorkloadIdentity +

+

+(Appears on:AzureAD) +

+
+

AzureWorkloadIdentity defines the Azure Workload Identity authentication configuration.

+
+ + + + + + + + + + + + + + + + + +
FieldDescription
+clientId
+ +string + +
+

clientId is the clientID of the Azure Active Directory application.

+
+tenantId
+ +string + +
+

tenantId is the tenant ID of the Azure Active Directory application.

+

BasicAuth

-(Appears on:APIServerConfig, AlertmanagerEndpoints, Endpoint, HTTPConfig, ProbeSpec, RemoteReadSpec, RemoteWriteSpec, AzureSDConfig, ConsulSDConfig, DockerSDConfig, DockerSwarmSDConfig, EurekaSDConfig, HTTPConfig, HTTPSDConfig, HetznerSDConfig, KubernetesSDConfig, KumaSDConfig, LightSailSDConfig, NomadSDConfig, PuppetDBSDConfig, ScrapeConfigSpec, HTTPConfig) +(Appears on:APIServerConfig, AlertmanagerEndpoints, HTTPConfigWithoutTLS, RemoteReadSpec, RemoteWriteSpec, AzureSDConfig, ConsulSDConfig, DockerSDConfig, DockerSwarmSDConfig, EurekaSDConfig, HTTPConfig, HTTPSDConfig, HetznerSDConfig, KubernetesSDConfig, KumaSDConfig, LightSailSDConfig, NomadSDConfig, PuppetDBSDConfig, ScrapeConfigSpec, HTTPConfig)

BasicAuth configures HTTP Basic Authentication settings.

@@ -8704,6 +9034,43 @@ instead of the Pod IP’s address.

+podManagementPolicy
+ + +PodManagementPolicyType + + + + +(Optional) +

podManagementPolicy defines the policy for creating/deleting pods when +scaling up and down.

+

Unlike the default StatefulSet behavior, the default policy is +Parallel to avoid manual intervention in case a pod gets stuck during +a rollout.

+

Note that updating this value implies the recreation of the StatefulSet +which incurs a service outage.

+ + + + +updateStrategy
+ + +StatefulSetUpdateStrategy + + + + +(Optional) +

updateStrategy indicates the strategy that will be employed to update +Pods in the StatefulSet when a revision is made to statefulset’s Pod +Template.

+

The default strategy is RollingUpdate.

+ + + + enableServiceLinks
bool @@ -9124,6 +9491,19 @@ histogram with custom buckets.

+scrapeNativeHistograms
+ +bool + + + +(Optional) +

scrapeNativeHistograms defines whether to enable scraping of native histograms. +It requires Prometheus >= v3.8.0.

+ + + + scrapeClassicHistograms
bool @@ -9250,8 +9630,8 @@ PodMonitor and ServiceMonitor objects.

tracingConfig
- -PrometheusTracingConfig + +TracingConfig @@ -9791,7 +10171,7 @@ condition is out of date with respect to the current state of the object.

ConfigResourceStatus

-(Appears on:PodMonitor, Probe, PrometheusRule, ServiceMonitor, ScrapeConfig) +(Appears on:PodMonitor, Probe, PrometheusRule, ServiceMonitor, AlertmanagerConfig, ScrapeConfig, AlertmanagerConfig)

ConfigResourceStatus is the most recent observed status of the Configuration Resource (ServiceMonitor, PodMonitor, Probes, ScrapeConfig, PrometheusRule or AlertmanagerConfig). Read-only. @@ -10057,7 +10437,7 @@ DNSConfig.

Duration (string alias)

-(Appears on:AlertmanagerEndpoints, AlertmanagerGlobalConfig, CommonPrometheusFields, Endpoint, MetadataConfig, PodMetricsEndpoint, ProbeSpec, PrometheusSpec, PrometheusTracingConfig, QuerySpec, QueueConfig, RemoteReadSpec, RemoteWriteSpec, RetainConfig, Rule, RuleGroup, TSDBSpec, ThanosRulerSpec, ThanosSpec, AzureSDConfig, ConsulSDConfig, DNSSDConfig, DigitalOceanSDConfig, DockerSDConfig, DockerSwarmSDConfig, EC2SDConfig, EurekaSDConfig, FileSDConfig, GCESDConfig, HTTPSDConfig, HetznerSDConfig, IonosSDConfig, KumaSDConfig, LightSailSDConfig, LinodeSDConfig, NomadSDConfig, OVHCloudSDConfig, OpenStackSDConfig, PuppetDBSDConfig, PushoverConfig, ScalewaySDConfig, ScrapeConfigSpec, WebhookConfig, PushoverConfig, WebhookConfig) +(Appears on:AlertmanagerEndpoints, AlertmanagerGlobalConfig, CommonPrometheusFields, Endpoint, MetadataConfig, PodMetricsEndpoint, ProbeSpec, PrometheusSpec, QuerySpec, QueueConfig, RemoteReadSpec, RemoteWriteSpec, RetainConfig, Rule, RuleGroup, TSDBSpec, ThanosRulerSpec, ThanosSpec, TracingConfig, AzureSDConfig, ConsulSDConfig, DNSSDConfig, DigitalOceanSDConfig, DockerSDConfig, DockerSwarmSDConfig, EC2SDConfig, EurekaSDConfig, FileSDConfig, GCESDConfig, HTTPSDConfig, HetznerSDConfig, IonosSDConfig, KumaSDConfig, LightSailSDConfig, LinodeSDConfig, NomadSDConfig, OVHCloudSDConfig, OpenStackSDConfig, PagerDutyConfig, PuppetDBSDConfig, PushoverConfig, ScalewaySDConfig, ScrapeConfigSpec, SlackConfig, WebhookConfig, PagerDutyConfig, PushoverConfig, SlackConfig, WebhookConfig)

Duration is a valid time duration that can be parsed by Prometheus model.ParseDuration() function. @@ -10486,264 +10866,266 @@ The value cannot be greater than the scrape interval otherwise the operator will -tlsConfig
+honorLabels
- -TLSConfig - +bool (Optional) -

tlsConfig defines the TLS configuration to use when scraping the target.

+

honorLabels defines when true the metric’s labels when they collide +with the target’s labels.

-bearerTokenFile
+honorTimestamps
-string +bool (Optional) -

bearerTokenFile defines the file to read bearer token for scraping the target.

-

Deprecated: use authorization instead.

+

honorTimestamps defines whether Prometheus preserves the timestamps +when exposed by the target.

-bearerTokenSecret
+trackTimestampsStaleness
- -Kubernetes core/v1.SecretKeySelector - +bool (Optional) -

bearerTokenSecret defines a key of a Secret containing the bearer -token for scraping targets. The secret needs to be in the same namespace -as the ServiceMonitor object and readable by the Prometheus Operator.

-

Deprecated: use authorization instead.

+

trackTimestampsStaleness defines whether Prometheus tracks staleness of +the metrics that have an explicit timestamp present in scraped data. +Has no effect if honorTimestamps is false.

+

It requires Prometheus >= v2.48.0.

-authorization
+metricRelabelings
- -SafeAuthorization + +[]RelabelConfig (Optional) -

authorization configures the Authorization header credentials to use when -scraping the target.

-

Cannot be set at the same time as basicAuth, or oauth2.

+

metricRelabelings defines the relabeling rules to apply to the +samples before ingestion.

-honorLabels
+relabelings
-bool + +[]RelabelConfig + (Optional) -

honorLabels defines when true the metric’s labels when they collide -with the target’s labels.

+

relabelings defines the relabeling rules to apply the target’s +metadata labels.

+

The Operator automatically adds relabelings for a few standard Kubernetes fields.

+

The original scrape job’s name is available via the __tmp_prometheus_job_name label.

+

More info: https://prometheus.io/docs/prometheus/latest/configuration/configuration/#relabel_config

-honorTimestamps
+filterRunning
bool (Optional) -

honorTimestamps defines whether Prometheus preserves the timestamps -when exposed by the target.

+

filterRunning when true, the pods which are not running (e.g. either in Failed or +Succeeded state) are dropped during the target discovery.

+

If unset, the filtering is enabled.

+

More info: https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle/#pod-phase

-trackTimestampsStaleness
+bearerTokenFile
-bool +string (Optional) -

trackTimestampsStaleness defines whether Prometheus tracks staleness of -the metrics that have an explicit timestamp present in scraped data. -Has no effect if honorTimestamps is false.

-

It requires Prometheus >= v2.48.0.

+

bearerTokenFile defines the file to read bearer token for scraping the target.

+

Deprecated: use authorization instead.

-basicAuth
+authorization
- -BasicAuth + +SafeAuthorization (Optional) -

basicAuth defines the Basic Authentication credentials to use when -scraping the target.

-

Cannot be set at the same time as authorization, or oauth2.

+

authorization configures the Authorization header credentials used by +the client.

+

Cannot be set at the same time as basicAuth, bearerTokenSecret or oauth2.

-oauth2
+basicAuth
- -OAuth2 + +BasicAuth (Optional) -

oauth2 defines the OAuth2 settings to use when scraping the target.

-

It requires Prometheus >= 2.27.0.

-

Cannot be set at the same time as authorization, or basicAuth.

+

basicAuth defines the Basic Authentication credentials used by the +client.

+

Cannot be set at the same time as authorization, bearerTokenSecret or oauth2.

-metricRelabelings
+oauth2
- -[]RelabelConfig + +OAuth2 (Optional) -

metricRelabelings defines the relabeling rules to apply to the -samples before ingestion.

+

oauth2 defines the OAuth2 settings used by the client.

+

It requires Prometheus >= 2.27.0.

+

Cannot be set at the same time as authorization, basicAuth or bearerTokenSecret.

-relabelings
+bearerTokenSecret
- -[]RelabelConfig + +Kubernetes core/v1.SecretKeySelector (Optional) -

relabelings defines the relabeling rules to apply the target’s -metadata labels.

-

The Operator automatically adds relabelings for a few standard Kubernetes fields.

-

The original scrape job’s name is available via the __tmp_prometheus_job_name label.

-

More info: https://prometheus.io/docs/prometheus/latest/configuration/configuration/#relabel_config

+

bearerTokenSecret defines a key of a Secret containing the bearer token +used by the client for authentication. The secret needs to be in the +same namespace as the custom resource and readable by the Prometheus +Operator.

+

Cannot be set at the same time as authorization, basicAuth or oauth2.

+

Deprecated: use authorization instead.

-proxyUrl
+followRedirects
-string +bool (Optional) -

proxyUrl defines the HTTP proxy server to use.

+

followRedirects defines whether the client should follow HTTP 3xx +redirects.

-noProxy
+enableHttp2
-string +bool (Optional) -

noProxy defines a comma-separated string that can contain IPs, CIDR notation, domain names -that should be excluded from proxying. IP and domain names can -contain port numbers.

-

It requires Prometheus >= v2.43.0, Alertmanager >= v0.25.0 or Thanos >= v0.32.0.

+

enableHttp2 can be used to disable HTTP2.

-proxyFromEnvironment
+tlsConfig
-bool + +TLSConfig + (Optional) -

proxyFromEnvironment defines whether to use the proxy configuration defined by environment variables (HTTP_PROXY, HTTPS_PROXY, and NO_PROXY).

-

It requires Prometheus >= v2.43.0, Alertmanager >= v0.25.0 or Thanos >= v0.32.0.

+

tlsConfig defines TLS configuration used by the client.

-proxyConnectHeader
+proxyUrl
- -map[string][]Kubernetes core/v1.SecretKeySelector - +string (Optional) -

proxyConnectHeader optionally specifies headers to send to -proxies during CONNECT requests.

-

It requires Prometheus >= v2.43.0, Alertmanager >= v0.25.0 or Thanos >= v0.32.0.

+

proxyUrl defines the HTTP proxy server to use.

-followRedirects
+noProxy
-bool +string (Optional) -

followRedirects defines whether the scrape requests should follow HTTP -3xx redirects.

+

noProxy defines a comma-separated string that can contain IPs, CIDR notation, domain names +that should be excluded from proxying. IP and domain names can +contain port numbers.

+

It requires Prometheus >= v2.43.0, Alertmanager >= v0.25.0 or Thanos >= v0.32.0.

-enableHttp2
+proxyFromEnvironment
bool (Optional) -

enableHttp2 can be used to disable HTTP2 when scraping the target.

+

proxyFromEnvironment defines whether to use the proxy configuration defined by environment variables (HTTP_PROXY, HTTPS_PROXY, and NO_PROXY).

+

It requires Prometheus >= v2.43.0, Alertmanager >= v0.25.0 or Thanos >= v0.32.0.

-filterRunning
+proxyConnectHeader
-bool + +map[string][]Kubernetes core/v1.SecretKeySelector + (Optional) -

filterRunning when true, the pods which are not running (e.g. either in Failed or -Succeeded state) are dropped during the target discovery.

-

If unset, the filtering is enabled.

-

More info: https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle/#pod-phase

+

proxyConnectHeader optionally specifies headers to send to +proxies during CONNECT requests.

+

It requires Prometheus >= v2.43.0, Alertmanager >= v0.25.0 or Thanos >= v0.32.0.

@@ -11197,10 +11579,136 @@ Examples: 45ms, 30s, 1m, 1h20m15sHTTPConfig

+(Appears on:HTTPConfigWithProxy, ProbeSpec) +

+
+

HTTPConfig defines the HTTP configuration + TLS configuration (only from +secret/configmap references).

+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FieldDescription
+authorization
+ + +SafeAuthorization + + +
+(Optional) +

authorization configures the Authorization header credentials used by +the client.

+

Cannot be set at the same time as basicAuth, bearerTokenSecret or oauth2.

+
+basicAuth
+ + +BasicAuth + + +
+(Optional) +

basicAuth defines the Basic Authentication credentials used by the +client.

+

Cannot be set at the same time as authorization, bearerTokenSecret or oauth2.

+
+oauth2
+ + +OAuth2 + + +
+(Optional) +

oauth2 defines the OAuth2 settings used by the client.

+

It requires Prometheus >= 2.27.0.

+

Cannot be set at the same time as authorization, basicAuth or bearerTokenSecret.

+
+bearerTokenSecret
+ + +Kubernetes core/v1.SecretKeySelector + + +
+(Optional) +

bearerTokenSecret defines a key of a Secret containing the bearer token +used by the client for authentication. The secret needs to be in the +same namespace as the custom resource and readable by the Prometheus +Operator.

+

Cannot be set at the same time as authorization, basicAuth or oauth2.

+

Deprecated: use authorization instead.

+
+followRedirects
+ +bool + +
+(Optional) +

followRedirects defines whether the client should follow HTTP 3xx +redirects.

+
+enableHttp2
+ +bool + +
+(Optional) +

enableHttp2 can be used to disable HTTP2.

+
+tlsConfig
+ + +SafeTLSConfig + + +
+(Optional) +

tlsConfig defines the TLS configuration used by the client.

+
+

HTTPConfigWithProxy +

+

(Appears on:AlertmanagerGlobalConfig, PodMetricsEndpoint)

-

HTTPConfig defines the configuration for the HTTP client.

+

HTTPConfigWithProxy defines the configuration for the HTTP client with proxy +configuration. It is used for PodMonitor endpoints and Probes.

@@ -11279,6 +11787,31 @@ Operator.

+ + + + + + + + + +
+followRedirects
+ +bool + +
+(Optional) +

followRedirects defines whether the client should follow HTTP 3xx +redirects.

+
+enableHttp2
+ +bool + +
+(Optional) +

enableHttp2 can be used to disable HTTP2.

+
tlsConfig
@@ -11347,6 +11880,398 @@ proxies during CONNECT requests.

It requires Prometheus >= v2.43.0, Alertmanager >= v0.25.0 or Thanos >= v0.32.0.

+

HTTPConfigWithProxyAndTLSFiles +

+

+(Appears on:Endpoint) +

+
+

HTTPConfigWithProxyAndTLSFiles defines the configuration for the HTTP client +with proxy configuration and TLS configuration. It is used for +ServiceMonitor endpoints.

+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FieldDescription
+authorization
+ + +SafeAuthorization + + +
+(Optional) +

authorization configures the Authorization header credentials used by +the client.

+

Cannot be set at the same time as basicAuth, bearerTokenSecret or oauth2.

+
+basicAuth
+ + +BasicAuth + + +
+(Optional) +

basicAuth defines the Basic Authentication credentials used by the +client.

+

Cannot be set at the same time as authorization, bearerTokenSecret or oauth2.

+
+oauth2
+ + +OAuth2 + + +
+(Optional) +

oauth2 defines the OAuth2 settings used by the client.

+

It requires Prometheus >= 2.27.0.

+

Cannot be set at the same time as authorization, basicAuth or bearerTokenSecret.

+
+bearerTokenSecret
+ + +Kubernetes core/v1.SecretKeySelector + + +
+(Optional) +

bearerTokenSecret defines a key of a Secret containing the bearer token +used by the client for authentication. The secret needs to be in the +same namespace as the custom resource and readable by the Prometheus +Operator.

+

Cannot be set at the same time as authorization, basicAuth or oauth2.

+

Deprecated: use authorization instead.

+
+followRedirects
+ +bool + +
+(Optional) +

followRedirects defines whether the client should follow HTTP 3xx +redirects.

+
+enableHttp2
+ +bool + +
+(Optional) +

enableHttp2 can be used to disable HTTP2.

+
+tlsConfig
+ + +TLSConfig + + +
+(Optional) +

tlsConfig defines TLS configuration used by the client.

+
+proxyUrl
+ +string + +
+(Optional) +

proxyUrl defines the HTTP proxy server to use.

+
+noProxy
+ +string + +
+(Optional) +

noProxy defines a comma-separated string that can contain IPs, CIDR notation, domain names +that should be excluded from proxying. IP and domain names can +contain port numbers.

+

It requires Prometheus >= v2.43.0, Alertmanager >= v0.25.0 or Thanos >= v0.32.0.

+
+proxyFromEnvironment
+ +bool + +
+(Optional) +

proxyFromEnvironment defines whether to use the proxy configuration defined by environment variables (HTTP_PROXY, HTTPS_PROXY, and NO_PROXY).

+

It requires Prometheus >= v2.43.0, Alertmanager >= v0.25.0 or Thanos >= v0.32.0.

+
+proxyConnectHeader
+ + +map[string][]Kubernetes core/v1.SecretKeySelector + + +
+(Optional) +

proxyConnectHeader optionally specifies headers to send to +proxies during CONNECT requests.

+

It requires Prometheus >= v2.43.0, Alertmanager >= v0.25.0 or Thanos >= v0.32.0.

+
+

HTTPConfigWithTLSFiles +

+

+(Appears on:HTTPConfigWithProxyAndTLSFiles) +

+
+

HTTPConfigWithTLSFiles defines HTTP configuration + TLS configuration +(from secret/configmap references as well as files).

+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FieldDescription
+authorization
+ + +SafeAuthorization + + +
+(Optional) +

authorization configures the Authorization header credentials used by +the client.

+

Cannot be set at the same time as basicAuth, bearerTokenSecret or oauth2.

+
+basicAuth
+ + +BasicAuth + + +
+(Optional) +

basicAuth defines the Basic Authentication credentials used by the +client.

+

Cannot be set at the same time as authorization, bearerTokenSecret or oauth2.

+
+oauth2
+ + +OAuth2 + + +
+(Optional) +

oauth2 defines the OAuth2 settings used by the client.

+

It requires Prometheus >= 2.27.0.

+

Cannot be set at the same time as authorization, basicAuth or bearerTokenSecret.

+
+bearerTokenSecret
+ + +Kubernetes core/v1.SecretKeySelector + + +
+(Optional) +

bearerTokenSecret defines a key of a Secret containing the bearer token +used by the client for authentication. The secret needs to be in the +same namespace as the custom resource and readable by the Prometheus +Operator.

+

Cannot be set at the same time as authorization, basicAuth or oauth2.

+

Deprecated: use authorization instead.

+
+followRedirects
+ +bool + +
+(Optional) +

followRedirects defines whether the client should follow HTTP 3xx +redirects.

+
+enableHttp2
+ +bool + +
+(Optional) +

enableHttp2 can be used to disable HTTP2.

+
+tlsConfig
+ + +TLSConfig + + +
+(Optional) +

tlsConfig defines TLS configuration used by the client.

+
+

HTTPConfigWithoutTLS +

+

+(Appears on:HTTPConfig, HTTPConfigWithTLSFiles) +

+
+

HTTPConfigWithoutTLS defines the configuration for the HTTP client.

+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FieldDescription
+authorization
+ + +SafeAuthorization + + +
+(Optional) +

authorization configures the Authorization header credentials used by +the client.

+

Cannot be set at the same time as basicAuth, bearerTokenSecret or oauth2.

+
+basicAuth
+ + +BasicAuth + + +
+(Optional) +

basicAuth defines the Basic Authentication credentials used by the +client.

+

Cannot be set at the same time as authorization, bearerTokenSecret or oauth2.

+
+oauth2
+ + +OAuth2 + + +
+(Optional) +

oauth2 defines the OAuth2 settings used by the client.

+

It requires Prometheus >= 2.27.0.

+

Cannot be set at the same time as authorization, basicAuth or bearerTokenSecret.

+
+bearerTokenSecret
+ + +Kubernetes core/v1.SecretKeySelector + + +
+(Optional) +

bearerTokenSecret defines a key of a Secret containing the bearer token +used by the client for authentication. The secret needs to be in the +same namespace as the custom resource and readable by the Prometheus +Operator.

+

Cannot be set at the same time as authorization, basicAuth or oauth2.

+

Deprecated: use authorization instead.

+
followRedirects
@@ -11681,6 +12606,19 @@ list restricting them.

+scrapeNativeHistograms
+ +bool + +
+(Optional) +

scrapeNativeHistograms defines whether to enable scraping of native histograms. +It requires Prometheus >= v3.8.0.

+
scrapeClassicHistograms
bool @@ -11752,7 +12690,7 @@ Examples: 30s, 1m, 1h20m15s, 15dOAuth2

-(Appears on:Endpoint, HTTPConfig, ProbeSpec, RemoteReadSpec, RemoteWriteSpec, AzureSDConfig, ConsulSDConfig, DigitalOceanSDConfig, DockerSDConfig, DockerSwarmSDConfig, EurekaSDConfig, HTTPConfig, HTTPSDConfig, HetznerSDConfig, IonosSDConfig, KubernetesSDConfig, KumaSDConfig, LightSailSDConfig, LinodeSDConfig, NomadSDConfig, PuppetDBSDConfig, ScrapeConfigSpec, HTTPConfig) +(Appears on:HTTPConfigWithoutTLS, RemoteReadSpec, RemoteWriteSpec, AzureSDConfig, ConsulSDConfig, DigitalOceanSDConfig, DockerSDConfig, DockerSwarmSDConfig, EurekaSDConfig, HTTPConfig, HTTPSDConfig, HetznerSDConfig, IonosSDConfig, KubernetesSDConfig, KumaSDConfig, LightSailSDConfig, LinodeSDConfig, NomadSDConfig, PuppetDBSDConfig, ScrapeConfigSpec, HTTPConfig)

OAuth2 configures OAuth2 settings.

@@ -12184,6 +13122,33 @@ string
+

PodManagementPolicyType +(string alias)

+

+(Appears on:AlertmanagerSpec, CommonPrometheusFields, ThanosRulerSpec) +

+
+
+ + + + + + + + + + + + +
ValueDescription

"OrderedReady"

OrderedReadyPodManagement will create pods in strictly increasing order on +scale up and strictly decreasing order on scale down, progressing only when +the previous pod is ready or terminated. At most one pod will be changed +at any time.

+

"Parallel"

ParallelPodManagement will create and delete pods as soon as the stateful set +replica count is changed, and will not wait for pods to be ready or complete +termination.

+

PodMetricsEndpoint

@@ -12484,6 +13449,31 @@ Operator.

+followRedirects
+ +bool + + + +(Optional) +

followRedirects defines whether the client should follow HTTP 3xx +redirects.

+ + + + +enableHttp2
+ +bool + + + +(Optional) +

enableHttp2 can be used to disable HTTP2.

+ + + + tlsConfig
@@ -12552,31 +13542,6 @@ proxies during CONNECT requests.

It requires Prometheus >= v2.43.0, Alertmanager >= v0.25.0 or Thanos >= v0.32.0.

- - -followRedirects
- -bool - - - -(Optional) -

followRedirects defines whether the client should follow HTTP 3xx -redirects.

- - - - -enableHttp2
- -bool - - - -(Optional) -

enableHttp2 can be used to disable HTTP2.

- -

PodMonitorSpec @@ -12786,6 +13751,19 @@ uint64 +scrapeNativeHistograms
+ +bool + + + +(Optional) +

scrapeNativeHistograms defines whether to enable scraping of native histograms. +It requires Prometheus >= v3.8.0.

+ + + + scrapeClassicHistograms
bool @@ -13046,65 +14024,6 @@ The value cannot be greater than the scrape interval otherwise the operator will -tlsConfig
- -
-SafeTLSConfig - - - - -(Optional) -

tlsConfig defines the TLS configuration to use when scraping the endpoint.

- - - - -bearerTokenSecret
- - -Kubernetes core/v1.SecretKeySelector - - - - -(Optional) -

bearerTokenSecret defines the secret to mount to read bearer token for scraping targets. The secret -needs to be in the same namespace as the probe and accessible by -the Prometheus Operator.

- - - - -basicAuth
- - -BasicAuth - - - - -(Optional) -

basicAuth allow an endpoint to authenticate over basic authentication. -More info: https://prometheus.io/docs/operating/configuration/#endpoint

- - - - -oauth2
- - -OAuth2 - - - - -(Optional) -

oauth2 for the URL. Only valid in Prometheus versions 2.27.0 and newer.

- - - - metricRelabelings
@@ -13228,6 +14147,19 @@ Only valid in Prometheus versions 2.27.0 and newer.

+scrapeNativeHistograms
+ +bool + + + +(Optional) +

scrapeNativeHistograms defines whether to enable scraping of native histograms. +It requires Prometheus >= v3.8.0.

+ + + + scrapeClassicHistograms
bool @@ -13325,6 +14257,112 @@ Please note that the .spec.module field takes precedence over the < The module name must be added using Module under ProbeSpec.

+ + +authorization
+ +
+SafeAuthorization + + + + +(Optional) +

authorization configures the Authorization header credentials used by +the client.

+

Cannot be set at the same time as basicAuth, bearerTokenSecret or oauth2.

+ + + + +basicAuth
+ + +BasicAuth + + + + +(Optional) +

basicAuth defines the Basic Authentication credentials used by the +client.

+

Cannot be set at the same time as authorization, bearerTokenSecret or oauth2.

+ + + + +oauth2
+ + +OAuth2 + + + + +(Optional) +

oauth2 defines the OAuth2 settings used by the client.

+

It requires Prometheus >= 2.27.0.

+

Cannot be set at the same time as authorization, basicAuth or bearerTokenSecret.

+ + + + +bearerTokenSecret
+ + +Kubernetes core/v1.SecretKeySelector + + + + +(Optional) +

bearerTokenSecret defines a key of a Secret containing the bearer token +used by the client for authentication. The secret needs to be in the +same namespace as the custom resource and readable by the Prometheus +Operator.

+

Cannot be set at the same time as authorization, basicAuth or oauth2.

+

Deprecated: use authorization instead.

+ + + + +followRedirects
+ +bool + + + +(Optional) +

followRedirects defines whether the client should follow HTTP 3xx +redirects.

+ + + + +enableHttp2
+ +bool + + + +(Optional) +

enableHttp2 can be used to disable HTTP2.

+ + + + +tlsConfig
+ + +SafeTLSConfig + + + + +(Optional) +

tlsConfig defines the TLS configuration used by the client.

+ +

ProbeTargetIngress @@ -14520,6 +15558,43 @@ instead of the Pod IP’s address.

+podManagementPolicy
+ + +PodManagementPolicyType + + + + +(Optional) +

podManagementPolicy defines the policy for creating/deleting pods when +scaling up and down.

+

Unlike the default StatefulSet behavior, the default policy is +Parallel to avoid manual intervention in case a pod gets stuck during +a rollout.

+

Note that updating this value implies the recreation of the StatefulSet +which incurs a service outage.

+ + + + +updateStrategy
+ + +StatefulSetUpdateStrategy + + + + +(Optional) +

updateStrategy indicates the strategy that will be employed to update +Pods in the StatefulSet when a revision is made to statefulset’s Pod +Template.

+

The default strategy is RollingUpdate.

+ + + + enableServiceLinks
bool @@ -14940,6 +16015,19 @@ histogram with custom buckets.

+scrapeNativeHistograms
+ +bool + + + +(Optional) +

scrapeNativeHistograms defines whether to enable scraping of native histograms. +It requires Prometheus >= v3.8.0.

+ + + + scrapeClassicHistograms
bool @@ -15066,8 +16154,8 @@ PodMonitor and ServiceMonitor objects.

tracingConfig
- -PrometheusTracingConfig + +TracingConfig @@ -15842,124 +16930,6 @@ string -

PrometheusTracingConfig -

-

-(Appears on:CommonPrometheusFields) -

-
-
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
FieldDescription
-clientType
- -string - -
-(Optional) -

clientType defines the client used to export the traces. Supported values are http or grpc.

-
-endpoint
- -string - -
-

endpoint to send the traces to. Should be provided in format :.

-
-samplingFraction
- - -k8s.io/apimachinery/pkg/api/resource.Quantity - - -
-(Optional) -

samplingFraction defines the probability a given trace will be sampled. Must be a float from 0 through 1.

-
-insecure
- -bool - -
-(Optional) -

insecure if disabled, the client will use a secure connection.

-
-headers
- -map[string]string - -
-(Optional) -

headers defines the key-value pairs to be used as headers associated with gRPC or HTTP requests.

-
-compression
- -string - -
-(Optional) -

compression key for supported compression types. The only supported value is gzip.

-
-timeout
- - -Duration - - -
-(Optional) -

timeout defines the maximum time the exporter will wait for each batch export.

-
-tlsConfig
- - -TLSConfig - - -
-(Optional) -

tlsConfig to use when sending traces.

-

PrometheusWebSpec

@@ -16034,7 +17004,7 @@ A zero value means that Prometheus doesn’t accept any incoming connection.

ProxyConfig

-(Appears on:APIServerConfig, AlertmanagerEndpoints, Endpoint, HTTPConfig, OAuth2, ProberSpec, RemoteReadSpec, RemoteWriteSpec, AzureSDConfig, ConsulSDConfig, DigitalOceanSDConfig, DockerSDConfig, DockerSwarmSDConfig, EC2SDConfig, EurekaSDConfig, HTTPConfig, HTTPSDConfig, HetznerSDConfig, IonosSDConfig, KubernetesSDConfig, KumaSDConfig, LightSailSDConfig, LinodeSDConfig, NomadSDConfig, PuppetDBSDConfig, ScalewaySDConfig, ScrapeConfigSpec, HTTPConfig) +(Appears on:APIServerConfig, AlertmanagerEndpoints, HTTPConfigWithProxy, HTTPConfigWithProxyAndTLSFiles, OAuth2, ProberSpec, RemoteReadSpec, RemoteWriteSpec, AzureSDConfig, ConsulSDConfig, DigitalOceanSDConfig, DockerSDConfig, DockerSwarmSDConfig, EC2SDConfig, EurekaSDConfig, HTTPConfig, HTTPSDConfig, HetznerSDConfig, IonosSDConfig, KubernetesSDConfig, KumaSDConfig, LightSailSDConfig, LinodeSDConfig, NomadSDConfig, PuppetDBSDConfig, ScalewaySDConfig, ScrapeConfigSpec, HTTPConfig)

@@ -17174,6 +18144,45 @@ Duration +

RollingUpdateStatefulSetStrategy +

+

+(Appears on:StatefulSetUpdateStrategy) +

+
+

RollingUpdateStatefulSetStrategy is used to communicate parameter for the RollingUpdate strategy.

+
+ + + + + + + + + + + + + +
FieldDescription
+maxUnavailable
+ + +k8s.io/apimachinery/pkg/util/intstr.IntOrString + + +
+(Optional) +

maxUnavailable is the maximum number of pods that can be unavailable +during the update. The value can be an absolute number (ex: 5) or a +percentage of desired pods (ex: 10%). Absolute number is calculated from +percentage by rounding up. This can not be 0. Defaults to 1. This field +is alpha-level and is only honored by servers that enable the +MaxUnavailableStatefulSet feature. The field applies to all pods in the +range 0 to Replicas-1. That means if there is any unavailable pod in +the range 0 to Replicas-1, it will be counted towards MaxUnavailable.

+

Rule

@@ -17524,7 +18533,7 @@ See: https://tip.golang.org/d

SafeAuthorization

-(Appears on:AlertmanagerEndpoints, Authorization, Endpoint, HTTPConfig, ProbeSpec, AzureSDConfig, ConsulSDConfig, DigitalOceanSDConfig, DockerSDConfig, DockerSwarmSDConfig, EurekaSDConfig, HTTPConfig, HTTPSDConfig, HetznerSDConfig, IonosSDConfig, KubernetesSDConfig, KumaSDConfig, LightSailSDConfig, LinodeSDConfig, NomadSDConfig, PuppetDBSDConfig, ScrapeConfigSpec, HTTPConfig) +(Appears on:AlertmanagerEndpoints, Authorization, HTTPConfigWithoutTLS, ProbeSpec, AzureSDConfig, ConsulSDConfig, DigitalOceanSDConfig, DockerSDConfig, DockerSwarmSDConfig, EurekaSDConfig, HTTPConfig, HTTPSDConfig, HetznerSDConfig, IonosSDConfig, KubernetesSDConfig, KumaSDConfig, LightSailSDConfig, LinodeSDConfig, NomadSDConfig, PuppetDBSDConfig, ScrapeConfigSpec, HTTPConfig)

SafeAuthorization specifies a subset of the Authorization struct, that is @@ -17572,10 +18581,10 @@ Kubernetes core/v1.SecretKeySelector

SafeTLSConfig

-(Appears on:ClusterTLSConfig, GlobalSMTPConfig, HTTPConfig, OAuth2, ProbeSpec, TLSConfig, AzureSDConfig, ConsulSDConfig, DigitalOceanSDConfig, DockerSDConfig, DockerSwarmSDConfig, EC2SDConfig, EmailConfig, EurekaSDConfig, HTTPConfig, HTTPSDConfig, HetznerSDConfig, IonosSDConfig, KubernetesSDConfig, KumaSDConfig, LightSailSDConfig, LinodeSDConfig, NomadSDConfig, OpenStackSDConfig, PuppetDBSDConfig, ScalewaySDConfig, ScrapeConfigSpec, EmailConfig, HTTPConfig) +(Appears on:ClusterTLSConfig, GlobalSMTPConfig, HTTPConfig, OAuth2, TLSConfig, AzureSDConfig, ConsulSDConfig, DigitalOceanSDConfig, DockerSDConfig, DockerSwarmSDConfig, EC2SDConfig, EmailConfig, EurekaSDConfig, HTTPConfig, HTTPSDConfig, HetznerSDConfig, IonosSDConfig, KubernetesSDConfig, KumaSDConfig, LightSailSDConfig, LinodeSDConfig, NomadSDConfig, OpenStackSDConfig, PuppetDBSDConfig, ScalewaySDConfig, ScrapeConfigSpec, EmailConfig, HTTPConfig)

-

SafeTLSConfig specifies safe TLS configuration parameters.

+

SafeTLSConfig defines safe TLS configurations.

@@ -18189,6 +19198,19 @@ uint64 + + + +
+scrapeNativeHistograms
+ +bool + +
+(Optional) +

scrapeNativeHistograms defines whether to enable scraping of native histograms. +It requires Prometheus >= v3.8.0.

+
scrapeClassicHistograms
bool @@ -18542,6 +19564,87 @@ It requires Prometheus >= v2.54.0.

+

StatefulSetUpdateStrategy +

+

+(Appears on:AlertmanagerSpec, CommonPrometheusFields, ThanosRulerSpec) +

+
+

StatefulSetUpdateStrategy indicates the strategy used when updating the +StatefulSet. It includes any additional parameters necessary to perform the +update for the indicated strategy.

+
+ + + + + + + + + + + + + + + + + +
FieldDescription
+type
+ + +StatefulSetUpdateStrategyType + + +
+

type indicates the type of the StatefulSetUpdateStrategy.

+

Default is RollingUpdate.

+
+rollingUpdate
+ + +RollingUpdateStatefulSetStrategy + + +
+(Optional) +

rollingUpdate is used to communicate parameters when type is RollingUpdate.

+
+

StatefulSetUpdateStrategyType +(string alias)

+

+(Appears on:StatefulSetUpdateStrategy) +

+
+

StatefulSetUpdateStrategyType is a string enumeration type that enumerates +all possible update strategies for the StatefulSet pods.

+
+ + + + + + + + + + + + +
ValueDescription

"OnDelete"

OnDeleteStatefulSetStrategyType triggers the legacy behavior. Version +tracking and ordered rolling restarts are disabled. Pods are recreated +from the StatefulSetSpec when they are manually deleted. When a scale +operation is performed with this strategy, new Pods will be created from +the the specification version indicated by the StatefulSet’s +currentRevision.

+

"RollingUpdate"

RollingUpdateStatefulSetStrategyType indicates that update will be +applied to all Pods in the StatefulSet with respect to the StatefulSet +ordering constraints. When a scale operation is performed with this +strategy, new Pods will be created from the specification version indicated +by the StatefulSet’s updateRevision.

+

StorageSpec

@@ -18629,10 +19732,10 @@ is to use a label selector alongside manually created PersistentVolumes.

TLSConfig

-(Appears on:APIServerConfig, AlertmanagerEndpoints, Endpoint, PrometheusTracingConfig, RemoteReadSpec, RemoteWriteSpec, ScrapeClass, ThanosRulerSpec, ThanosSpec) +(Appears on:APIServerConfig, AlertmanagerEndpoints, HTTPConfigWithTLSFiles, RemoteReadSpec, RemoteWriteSpec, ScrapeClass, ThanosRulerSpec, ThanosSpec, TracingConfig)

-

TLSConfig extends the safe TLS configuration with file parameters.

+

TLSConfig defines full TLS configuration.

@@ -18776,6 +19879,60 @@ string
+

TLSFilesConfig +

+

+(Appears on:TLSConfig) +

+
+

TLSFilesConfig extends the TLS configuration with file parameters.

+
+ + + + + + + + + + + + + + + + + + + + + +
FieldDescription
+caFile
+ +string + +
+(Optional) +

caFile defines the path to the CA cert in the Prometheus container to use for the targets.

+
+certFile
+ +string + +
+(Optional) +

certFile defines the path to the client cert file in the Prometheus container for the targets.

+
+keyFile
+ +string + +
+(Optional) +

keyFile defines the path to the client key file in the Prometheus container for the targets.

+

TLSVersion (string alias)

@@ -19210,6 +20367,43 @@ does not bind against the Pod IP.

+podManagementPolicy
+ + +PodManagementPolicyType + + + + +(Optional) +

podManagementPolicy defines the policy for creating/deleting pods when +scaling up and down.

+

Unlike the default StatefulSet behavior, the default policy is +Parallel to avoid manual intervention in case a pod gets stuck during +a rollout.

+

Note that updating this value implies the recreation of the StatefulSet +which incurs a service outage.

+ + + + +updateStrategy
+ + +StatefulSetUpdateStrategy + + + + +(Optional) +

updateStrategy indicates the strategy that will be employed to update +Pods in the StatefulSet when a revision is made to statefulset’s Pod +Template.

+

The default strategy is RollingUpdate.

+ + + + queryEndpoints
[]string @@ -20532,6 +21726,124 @@ AdditionalLabelSelectors +

TracingConfig +

+

+(Appears on:CommonPrometheusFields) +

+
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FieldDescription
+clientType
+ +string + +
+(Optional) +

clientType defines the client used to export the traces. Supported values are HTTP and GRPC.

+
+endpoint
+ +string + +
+

endpoint to send the traces to. Should be provided in format :.

+
+samplingFraction
+ + +k8s.io/apimachinery/pkg/api/resource.Quantity + + +
+(Optional) +

samplingFraction defines the probability a given trace will be sampled. Must be a float from 0 through 1.

+
+insecure
+ +bool + +
+(Optional) +

insecure if disabled, the client will use a secure connection.

+
+headers
+ +map[string]string + +
+(Optional) +

headers defines the key-value pairs to be used as headers associated with gRPC or HTTP requests.

+
+compression
+ +string + +
+(Optional) +

compression key for supported compression types. The only supported value is Gzip.

+
+timeout
+ + +Duration + + +
+(Optional) +

timeout defines the maximum time the exporter will wait for each batch export.

+
+tlsConfig
+ + +TLSConfig + + +
+(Optional) +

tlsConfig to use when sending traces.

+

TranslationStrategyOption (string alias)

@@ -21161,6 +22473,24 @@ the resource’s namespace.

+ + +status
+ + +ConfigResourceStatus + + + + +(Optional) +

status defines the status subresource. It is under active development and is updated only when the +“StatusForConfigurationResources” feature gate is enabled.

+

Most recent observed status of the ServiceMonitor. Read-only. +More info: +https://github.com/kubernetes/community/blob/master/contributors/devel/sig-architecture/api-conventions.md#spec-and-status

+ +

PrometheusAgent @@ -22049,6 +23379,43 @@ instead of the Pod IP’s address.

+podManagementPolicy
+ + +PodManagementPolicyType + + + + +(Optional) +

podManagementPolicy defines the policy for creating/deleting pods when +scaling up and down.

+

Unlike the default StatefulSet behavior, the default policy is +Parallel to avoid manual intervention in case a pod gets stuck during +a rollout.

+

Note that updating this value implies the recreation of the StatefulSet +which incurs a service outage.

+ + + + +updateStrategy
+ + +StatefulSetUpdateStrategy + + + + +(Optional) +

updateStrategy indicates the strategy that will be employed to update +Pods in the StatefulSet when a revision is made to statefulset’s Pod +Template.

+

The default strategy is RollingUpdate.

+ + + + enableServiceLinks
bool @@ -22469,6 +23836,19 @@ histogram with custom buckets.

+scrapeNativeHistograms
+ +bool + + + +(Optional) +

scrapeNativeHistograms defines whether to enable scraping of native histograms. +It requires Prometheus >= v3.8.0.

+ + + + scrapeClassicHistograms
bool @@ -22595,8 +23975,8 @@ PodMonitor and ServiceMonitor objects.

tracingConfig
- -PrometheusTracingConfig + +TracingConfig @@ -23594,6 +24974,19 @@ Only valid in Prometheus versions 2.27.0 and newer.

+scrapeNativeHistograms
+ +bool + + + +(Optional) +

scrapeNativeHistograms defines whether to enable scraping of native histograms. +It requires Prometheus >= v3.8.0.

+ + + + scrapeClassicHistograms
bool @@ -29206,7 +30599,9 @@ object and accessible by the Prometheus Operator.

apiURL
-string + +URL + @@ -29517,7 +30912,9 @@ object and accessible by the Prometheus Operator.

url
-string + +URL + @@ -29541,7 +30938,9 @@ string clientURL
-string + +URL + @@ -29677,6 +31076,21 @@ string

source defines the unique location of the affected system.

+ + +timeout
+ + +Duration + + + + +(Optional) +

timeout is the maximum time allowed to invoke the pagerduty +It requires Alertmanager >= v0.30.0.

+ +

PagerDutyImageConfig @@ -29711,7 +31125,9 @@ string href
-string + +URL + @@ -29753,7 +31169,9 @@ string href
-string + +URL + @@ -30677,6 +32095,43 @@ instead of the Pod IP’s address.

+podManagementPolicy
+ + +PodManagementPolicyType + + + + +(Optional) +

podManagementPolicy defines the policy for creating/deleting pods when +scaling up and down.

+

Unlike the default StatefulSet behavior, the default policy is +Parallel to avoid manual intervention in case a pod gets stuck during +a rollout.

+

Note that updating this value implies the recreation of the StatefulSet +which incurs a service outage.

+ + + + +updateStrategy
+ + +StatefulSetUpdateStrategy + + + + +(Optional) +

updateStrategy indicates the strategy that will be employed to update +Pods in the StatefulSet when a revision is made to statefulset’s Pod +Template.

+

The default strategy is RollingUpdate.

+ + + + enableServiceLinks
bool @@ -31097,6 +32552,19 @@ histogram with custom buckets.

+scrapeNativeHistograms
+ +bool + + + +(Optional) +

scrapeNativeHistograms defines whether to enable scraping of native histograms. +It requires Prometheus >= v3.8.0.

+ + + + scrapeClassicHistograms
bool @@ -31223,8 +32691,8 @@ PodMonitor and ServiceMonitor objects.

tracingConfig
- -PrometheusTracingConfig + +TracingConfig @@ -31846,7 +33314,9 @@ This is the main body text of the Pushover notification.

url
-string + +URL + @@ -31958,7 +33428,8 @@ bool (Optional)

html defines whether notification message is HTML or plain text. -When true, the message can include HTML formatting tags.

+When true, the message can include HTML formatting tags. +html and monospace formatting are mutually exclusive.

@@ -33845,6 +35316,19 @@ Only valid in Prometheus versions 2.27.0 and newer.

+scrapeNativeHistograms
+ +bool + + + +(Optional) +

scrapeNativeHistograms defines whether to enable scraping of native histograms. +It requires Prometheus >= v3.8.0.

+ + + + scrapeClassicHistograms
bool @@ -34075,7 +35559,9 @@ For buttons, this is the button text. For select menus, this is the placeholder url
-string + +URL + @@ -34238,7 +35724,9 @@ string titleLink
-string + +URL + @@ -34349,7 +35837,9 @@ string iconURL
-string + +URL + @@ -34361,7 +35851,9 @@ string imageURL
-string + +URL + @@ -34373,7 +35865,9 @@ string thumbURL
-string + +URL + @@ -34436,6 +35930,22 @@ HTTPConfig

httpConfig defines the HTTP client configuration.

+ + +timeout
+ + +Duration + + + + +(Optional) +

timeout defines the maximum time to wait for a webhook request to complete, +before failing the request and allowing it to be retried. +It requires Alertmanager >= v0.30.0.

+ +

SlackConfirmationField @@ -34656,7 +36166,9 @@ bool apiURL
-string + +URL + @@ -34924,7 +36436,7 @@ Time

URL (string alias)

-(Appears on:DiscordConfig, KumaSDConfig, RocketChatActionConfig, RocketChatConfig, WebexConfig) +(Appears on:DiscordConfig, KumaSDConfig, OpsGenieConfig, PagerDutyConfig, PagerDutyImageConfig, PagerDutyLinkConfig, PushoverConfig, RocketChatActionConfig, RocketChatConfig, SlackAction, SlackConfig, TelegramConfig, VictorOpsConfig, WeChatConfig, WebexConfig, WebhookConfig)

URL represents a valid URL

@@ -34978,7 +36490,9 @@ object and accessible by the Prometheus Operator.

apiUrl
-string + +URL + @@ -34995,7 +36509,6 @@ string
-(Optional)

routingKey defines a key used to map the alert to a team. This determines which VictorOps team will receive the alert notification.

@@ -35132,7 +36645,9 @@ object and accessible by the Prometheus Operator.

apiURL
-string + +URL + @@ -35363,7 +36878,9 @@ bool url
-string + +URL + @@ -35608,6 +37125,24 @@ the resource’s namespace.

+ + +status
+ + +ConfigResourceStatus + + + + +(Optional) +

status defines the status subresource. It is under active development and is updated only when the +“StatusForConfigurationResources” feature gate is enabled.

+

Most recent observed status of the ServiceMonitor. Read-only. +More info: +https://github.com/kubernetes/community/blob/master/contributors/devel/sig-architecture/api-conventions.md#spec-and-status

+ +

AlertmanagerConfigSpec @@ -36726,7 +38261,9 @@ object and accessible by the Prometheus Operator.

apiURL
-string + +URL + @@ -37024,7 +38561,9 @@ object and accessible by the Prometheus Operator.

url
-string + +URL + @@ -37048,7 +38587,9 @@ string clientURL
-string + +URL + @@ -37184,6 +38725,21 @@ string

source defines the unique location of the affected system.

+ + +timeout
+ + +Duration + + + + +(Optional) +

timeout is the maximum time allowed to invoke the pagerduty +It requires Alertmanager >= v0.30.0.

+ +

PagerDutyImageConfig @@ -37218,7 +38774,9 @@ string href
-string + +URL + @@ -37260,7 +38818,9 @@ string href
-string + +URL + @@ -37444,7 +39004,9 @@ This is the main body text of the Pushover notification.

url
-string + +URL + @@ -37556,7 +39118,8 @@ bool (Optional)

html defines whether notification message is HTML or plain text. -When true, the message can include HTML formatting tags.

+When true, the message can include HTML formatting tags. +html and monospace formatting are mutually exclusive.

@@ -38607,7 +40170,9 @@ For buttons, this is the button text. For select menus, this is the placeholder url
-string + +URL + @@ -38770,7 +40335,9 @@ string titleLink
-string + +URL + @@ -38881,7 +40448,9 @@ string iconURL
-string + +URL + @@ -38893,7 +40462,9 @@ string imageURL
-string + +URL + @@ -38905,7 +40476,9 @@ string thumbURL
-string + +URL + @@ -38968,6 +40541,22 @@ HTTPConfig

httpConfig defines the HTTP client configuration.

+ + +timeout
+ + +Duration + + + + +(Optional) +

timeout defines the maximum time to wait for a webhook request to complete, +before failing the request and allowing it to be retried. +It requires Alertmanager >= v0.30.0.

+ +

SlackConfirmationField @@ -39135,7 +40724,9 @@ bool apiURL
-string + +URL + @@ -39446,7 +41037,7 @@ Time

URL (string alias)

-(Appears on:DiscordConfig, RocketChatActionConfig, RocketChatConfig, WebexConfig) +(Appears on:DiscordConfig, OpsGenieConfig, PagerDutyConfig, PagerDutyImageConfig, PagerDutyLinkConfig, PushoverConfig, RocketChatActionConfig, RocketChatConfig, SlackAction, SlackConfig, TelegramConfig, VictorOpsConfig, WeChatConfig, WebexConfig, WebhookConfig)

URL represents a valid URL

@@ -39500,7 +41091,9 @@ object and accessible by the Prometheus Operator.

apiUrl
-string + +URL + @@ -39517,7 +41110,6 @@ string
-(Optional)

routingKey defines a key used to map the alert to a team. This determines which VictorOps team will receive the alert notification.

@@ -39654,7 +41246,9 @@ object and accessible by the Prometheus Operator.

apiURL
-string + +URL + @@ -39886,7 +41480,9 @@ bool url
-string + +URL + diff --git a/Documentation/getting-started/compatibility.md b/Documentation/getting-started/compatibility.md index f534f927c1e..e072f643208 100644 --- a/Documentation/getting-started/compatibility.md +++ b/Documentation/getting-started/compatibility.md @@ -15,14 +15,16 @@ It is recommended to use versions of the components identical or close to the ve ## Kubernetes -Due to the use of apiextensions.k8s.io/v1 CustomResourceDefinitions, prometheus-operator requires Kubernetes >= v1.16.0. +Due to the use of [Common Expression Language](https://kubernetes.io/docs/reference/using-api/cel/) (CEL) in Custom Resource Definitions, prometheus-operator >= v0.84.0 requires Kubernetes >= v1.25.0 (or v1.23.0 with the `CustomResourceValidationExpressions` feature gate enabled). + +Releases before v0.84.0 require Kubernetes >= v1.16.0. The Prometheus Operator uses the official [Go client](https://github.com/kubernetes/client-go) for Kubernetes to communicate with the Kubernetes API. The compatibility matrix for client-go and Kubernetes clusters can be found [here](https://github.com/kubernetes/client-go#compatibility-matrix). All additional compatibility is only best effort, or happens to be still/already supported. The current version of the Prometheus operator uses the following Go client version: ```$ mdox-exec="go list -m -f '{{ .Version }}' k8s.io/client-go" -v0.34.2 +v0.34.3 ``` ## Prometheus @@ -69,12 +71,16 @@ Prometheus Operator supports all Prometheus versions >= v2.0.0. The operator's e * v3.7.1 * v3.7.2 * v3.7.3 +* v3.8.0 +* v3.8.1 +* v3.9.0 +* v3.9.1 ``` The end-to-end tests are mostly tested against ```$ mdox-exec="go run ./cmd/po-docgen/. compatibility defaultPrometheusVersion" -* v3.7.3 +* v3.9.1 ``` ## Alertmanager @@ -84,7 +90,7 @@ The Prometheus Operator is compatible with Alertmanager v0.15 and above. The end-to-end tests are mostly tested against ```$ mdox-exec="go run ./cmd/po-docgen/. compatibility defaultAlertmanagerVersion" -* v0.29.0 +* v0.30.0 ``` ## Thanos @@ -94,5 +100,5 @@ The Prometheus Operator is compatible with Thanos v0.10 and above. The end-to-end tests are mostly tested against ```$ mdox-exec="go run ./cmd/po-docgen/. compatibility defaultThanosVersion" -* v0.39.2 +* v0.40.1 ``` diff --git a/Documentation/getting-started/installation.md b/Documentation/getting-started/installation.md index dfe0c0affe6..23f8afe371a 100644 --- a/Documentation/getting-started/installation.md +++ b/Documentation/getting-started/installation.md @@ -19,9 +19,11 @@ There are different approaches to install Prometheus Operator in your Kubernetes ### Pre-requisites -For all the approaches listed on this page, you require access to a **Kubernetes cluster!** For this, you can check the official docs of Kubernetes available [here](https://kubernetes.io/docs/tasks/tools/). +Due to the use of [Common Expression Language](https://kubernetes.io/docs/reference/using-api/cel/) (CEL) in Custom Resource Definitions, version >= v0.84.0 of the Prometheus Operator requires a Kubernetes cluster of version >= v1.25.0 (or >= v1.23.0 with the `CustomResourceValidationExpressions` feature gate enabled). -Version `>=0.39.0` of the Prometheus Operator requires a Kubernetes cluster of version `>=1.16.0`. If you are just starting out with the Prometheus Operator, it is **highly recommended** to use the latest version. If you have an older version of Kubernetes and the Prometheus Operator running, we recommend upgrading Kubernetes first and then the Prometheus Operator. +Releases before v0.84.0 require Kubernetes >= v1.16.0. + +If you are just starting out with the Prometheus Operator, it is **highly recommended** to use the latest version. If you have an older version of Kubernetes and the Prometheus Operator running, we recommend upgrading Kubernetes first and then the Prometheus Operator. > Check the appropriate versions of each of the components in the [Compatibility]({{}}) page. diff --git a/Documentation/platform/operator.md b/Documentation/platform/operator.md index 3f13f5c9363..7b05d0de53e 100644 --- a/Documentation/platform/operator.md +++ b/Documentation/platform/operator.md @@ -85,7 +85,7 @@ Usage of ./operator: -namespaces value Namespaces to scope the interaction of the Prometheus Operator and the apiserver (allow list). This is mutually exclusive with --deny-namespaces. -prometheus-config-reloader string - Prometheus config reloader image (default "quay.io/prometheus-operator/prometheus-config-reloader:v0.87.1") + Prometheus config reloader image (default "quay.io/prometheus-operator/prometheus-config-reloader:v0.88.0") -prometheus-default-base-image string Prometheus default base image (path without tag/version) (default "quay.io/prometheus/prometheus") -prometheus-instance-namespaces value diff --git a/Documentation/platform/prometheus-agent.md b/Documentation/platform/prometheus-agent.md index 573339e27f1..38502ec5dbc 100644 --- a/Documentation/platform/prometheus-agent.md +++ b/Documentation/platform/prometheus-agent.md @@ -26,7 +26,7 @@ metadata: labels: app.kubernetes.io/component: controller app.kubernetes.io/name: prometheus-operator - app.kubernetes.io/version: 0.87.1 + app.kubernetes.io/version: 0.88.0 name: prometheus-operator rules: - apiGroups: diff --git a/Documentation/platform/rbac.md b/Documentation/platform/rbac.md index e0cb776e14f..7c206be99af 100644 --- a/Documentation/platform/rbac.md +++ b/Documentation/platform/rbac.md @@ -26,7 +26,7 @@ metadata: labels: app.kubernetes.io/component: controller app.kubernetes.io/name: prometheus-operator - app.kubernetes.io/version: 0.87.1 + app.kubernetes.io/version: 0.88.0 name: prometheus-operator rules: - apiGroups: @@ -212,7 +212,7 @@ metadata: labels: app.kubernetes.io/component: controller app.kubernetes.io/name: prometheus-operator - app.kubernetes.io/version: 0.87.1 + app.kubernetes.io/version: 0.88.0 name: prometheus-operator namespace: default ``` @@ -228,7 +228,7 @@ metadata: labels: app.kubernetes.io/component: controller app.kubernetes.io/name: prometheus-operator - app.kubernetes.io/version: 0.87.1 + app.kubernetes.io/version: 0.88.0 name: prometheus-operator roleRef: apiGroup: rbac.authorization.k8s.io diff --git a/Documentation/platform/troubleshooting.md b/Documentation/platform/troubleshooting.md index 116fb5a86ba..7dba3be4366 100644 --- a/Documentation/platform/troubleshooting.md +++ b/Documentation/platform/troubleshooting.md @@ -53,6 +53,7 @@ Example of Role definition required by the Prometheus operator's Service Account ```yaml apiVersion: rbac.authorization.k8s.io/v1 kind: Role +metadata: name: prometheus-operator-kubelet rules: - apiGroups: @@ -72,6 +73,7 @@ Example of Role definition required by the Prometheus's Service Account to disco ```yaml apiVersion: rbac.authorization.k8s.io/v1 kind: Role +metadata: name: prometheus-kubelet rules: - apiGroups: diff --git a/Documentation/platform/webhook.md b/Documentation/platform/webhook.md index 1daec711c45..df477168e21 100644 --- a/Documentation/platform/webhook.md +++ b/Documentation/platform/webhook.md @@ -86,7 +86,7 @@ kind: ServiceAccount metadata: labels: app.kubernetes.io/name: prometheus-operator-admission-webhook - app.kubernetes.io/version: 0.87.1 + app.kubernetes.io/version: 0.88.0 name: prometheus-operator-admission-webhook namespace: default ``` @@ -97,7 +97,7 @@ kind: Deployment metadata: labels: app.kubernetes.io/name: prometheus-operator-admission-webhook - app.kubernetes.io/version: 0.87.1 + app.kubernetes.io/version: 0.88.0 name: prometheus-operator-admission-webhook namespace: default spec: @@ -114,7 +114,7 @@ spec: kubectl.kubernetes.io/default-container: prometheus-operator-admission-webhook labels: app.kubernetes.io/name: prometheus-operator-admission-webhook - app.kubernetes.io/version: 0.87.1 + app.kubernetes.io/version: 0.88.0 spec: affinity: podAntiAffinity: @@ -131,7 +131,7 @@ spec: - --web.enable-tls=true - --web.cert-file=/etc/tls/private/tls.crt - --web.key-file=/etc/tls/private/tls.key - image: quay.io/prometheus-operator/admission-webhook:v0.87.1 + image: quay.io/prometheus-operator/admission-webhook:v0.88.0 name: prometheus-operator-admission-webhook ports: - containerPort: 8443 @@ -179,7 +179,7 @@ kind: Service metadata: labels: app.kubernetes.io/name: prometheus-operator-admission-webhook - app.kubernetes.io/version: 0.87.1 + app.kubernetes.io/version: 0.88.0 name: prometheus-operator-admission-webhook namespace: default spec: diff --git a/RELEASE.md b/RELEASE.md index 8677f1fd377..68ac39c4924 100644 --- a/RELEASE.md +++ b/RELEASE.md @@ -18,8 +18,11 @@ The release cycle for cutting releases is every 6 weeks | Release | Date of release (year-month-day) | Release shepherd | |---------|----------------------------------|-------------------------------------------| -| v0.89 | 2026-02-04 | **searching for volunteer** | -| v0.88 | 2025-12-24 | **searching for volunteer** | +| v0.92 | 2026-06-10 | **searching for volunteer** | +| v0.91 | 2026-04-29 | **searching for volunteer** | +| v0.90 | 2026-03-18 | **searching for volunteer** | +| v0.89 | 2026-02-04 | Simon Pasquier (GitHub: @simonpasquier) | +| v0.88 | 2025-12-24 | Jayapriya Pai (Github: @slashpai) | | v0.87 | 2025-11-12 | Simon Pasquier (GitHub: @simonpasquier) | | v0.86 | 2025-10-01 | Jayapriya Pai (Github: @slashpai) | | v0.85 | 2025-08-20 | Simon Pasquier (GitHub: @simonpasquier) | diff --git a/VERSION b/VERSION index 7921aa127f3..fe6d01c1a45 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -0.87.1 +0.88.0 diff --git a/bundle.yaml b/bundle.yaml index 444675444dc..2e0db11a94c 100644 --- a/bundle.yaml +++ b/bundle.yaml @@ -4,7 +4,7 @@ kind: CustomResourceDefinition metadata: annotations: controller-gen.kubebuilder.io/version: v0.19.0 - operator.prometheus.io/version: 0.87.1 + operator.prometheus.io/version: 0.88.0 name: alertmanagerconfigs.monitoring.coreos.com spec: group: monitoring.coreos.com @@ -63,6 +63,7 @@ spec: items: type: string type: array + x-kubernetes-list-type: atomic sourceMatch: description: |- sourceMatch defines matchers for which one or more alerts have to exist for the inhibition @@ -102,6 +103,7 @@ spec: - name type: object type: array + x-kubernetes-list-type: atomic targetMatch: description: |- targetMatch defines matchers that have to be fulfilled in the alerts to be muted. @@ -141,8 +143,10 @@ spec: - name type: object type: array + x-kubernetes-list-type: atomic type: object type: array + x-kubernetes-list-type: atomic muteTimeIntervals: description: muteTimeIntervals defines the list of MuteTimeInterval specifying when the routes should be muted. @@ -176,6 +180,7 @@ spec: type: integer type: object type: array + x-kubernetes-list-type: atomic months: description: months defines a list of MonthRange items: @@ -185,6 +190,7 @@ spec: pattern: ^((?i)january|february|march|april|may|june|july|august|september|october|november|december|1[0-2]|[1-9])(?:((:((?i)january|february|march|april|may|june|july|august|september|october|november|december|1[0-2]|[1-9]))$)|$) type: string type: array + x-kubernetes-list-type: atomic times: description: times defines a list of TimeRange items: @@ -203,6 +209,7 @@ spec: type: string type: object type: array + x-kubernetes-list-type: atomic weekdays: description: weekdays defines a list of WeekdayRange items: @@ -212,6 +219,7 @@ spec: pattern: ^((?i)sun|mon|tues|wednes|thurs|fri|satur)day(?:((:(sun|mon|tues|wednes|thurs|fri|satur)day)$)|$) type: string type: array + x-kubernetes-list-type: atomic years: description: years defines a list of YearRange items: @@ -219,12 +227,15 @@ spec: pattern: ^2\d{3}(?::2\d{3}|$) type: string type: array + x-kubernetes-list-type: atomic type: object type: array + x-kubernetes-list-type: atomic required: - name type: object type: array + x-kubernetes-list-type: atomic receivers: description: receivers defines the list of receivers. items: @@ -1000,6 +1011,7 @@ spec: - apiURL type: object type: array + x-kubernetes-list-type: atomic emailConfigs: description: emailConfigs defines the list of Email configurations. items: @@ -1098,6 +1110,7 @@ spec: - value type: object type: array + x-kubernetes-list-type: atomic hello: description: |- hello defines the hostname to identify to the SMTP server. @@ -1303,6 +1316,7 @@ spec: type: string type: object type: array + x-kubernetes-list-type: atomic msteamsConfigs: description: |- msteamsConfigs defines the list of MSTeams configurations. @@ -2068,6 +2082,7 @@ spec: - webhookUrl type: object type: array + x-kubernetes-list-type: atomic msteamsv2Configs: description: |- msteamsv2Configs defines the list of MSTeamsV2 configurations. @@ -2828,6 +2843,7 @@ spec: x-kubernetes-map-type: atomic type: object type: array + x-kubernetes-list-type: atomic name: description: name defines the name of the receiver. Must be unique across all items from the list. @@ -2876,6 +2892,7 @@ spec: description: |- apiURL defines the URL to send OpsGenie API requests to. When not specified, defaults to the standard OpsGenie API endpoint. + pattern: ^https?://.+$ type: string description: description: |- @@ -2905,6 +2922,7 @@ spec: - value type: object type: array + x-kubernetes-list-type: atomic entity: description: |- entity defines an optional field that can be used to specify which domain alert is related to. @@ -3672,6 +3690,7 @@ spec: - type type: object type: array + x-kubernetes-list-type: atomic sendResolved: description: sendResolved defines whether or not to notify about resolved alerts. @@ -3693,6 +3712,7 @@ spec: type: boolean type: object type: array + x-kubernetes-list-type: atomic pagerdutyConfigs: description: pagerdutyConfigs defines the List of PagerDuty configurations. @@ -3703,20 +3723,25 @@ spec: properties: class: description: class defines the class/type of the event. + minLength: 1 type: string client: description: client defines the client identification. + minLength: 1 type: string clientURL: description: clientURL defines the backlink to the sender of notification. + pattern: ^https?://.+$ type: string component: description: component defines the part or component of the affected system that is broken. + minLength: 1 type: string description: description: description of the incident. + minLength: 1 type: string details: description: details defines the arbitrary key/value pairs @@ -3740,8 +3765,10 @@ spec: - value type: object type: array + x-kubernetes-list-type: atomic group: description: group defines a cluster or grouping of sources. + minLength: 1 type: string httpConfig: description: httpConfig defines the HTTP client configuration. @@ -4459,17 +4486,21 @@ spec: alt: description: alt is the optional alternative text for the image. + minLength: 1 type: string href: description: href defines the optional URL; makes the image a clickable link. + pattern: ^https?://.+$ type: string src: description: src of the image being attached to the incident + minLength: 1 type: string type: object type: array + x-kubernetes-list-type: atomic pagerDutyLinkConfigs: description: pagerDutyLinkConfigs defines a list of link details to attach that provide further detail about @@ -4482,13 +4513,16 @@ spec: description: alt defines the text that describes the purpose of the link, and can be used as the link's text. + minLength: 1 type: string href: description: href defines the URL of the link to be attached + pattern: ^https?://.+$ type: string type: object type: array + x-kubernetes-list-type: atomic routingKey: description: |- routingKey defines the secret's key that contains the PagerDuty integration key (when using @@ -4552,16 +4586,26 @@ spec: x-kubernetes-map-type: atomic severity: description: severity of the incident. + minLength: 1 type: string source: description: source defines the unique location of the affected system. + minLength: 1 + type: string + timeout: + description: |- + timeout is the maximum time allowed to invoke the pagerduty + It requires Alertmanager >= v0.30.0. + pattern: ^(0|(([0-9]+)y)?(([0-9]+)w)?(([0-9]+)d)?(([0-9]+)h)?(([0-9]+)m)?(([0-9]+)s)?(([0-9]+)ms)?)$ type: string url: description: url defines the URL to send requests to. + pattern: ^https?://.+$ type: string type: object type: array + x-kubernetes-list-type: atomic pushoverConfigs: description: pushoverConfigs defines the list of Pushover configurations. items: @@ -4573,6 +4617,7 @@ spec: description: |- device defines the name of a specific device to send the notification to. If not specified, the notification is sent to all user's devices. + minLength: 1 type: string expire: description: |- @@ -4584,6 +4629,7 @@ spec: description: |- html defines whether notification message is HTML or plain text. When true, the message can include HTML formatting tags. + html and monospace formatting are mutually exclusive. type: boolean httpConfig: description: httpConfig defines the HTTP client configuration @@ -5295,6 +5341,7 @@ spec: description: |- message defines the notification message content. This is the main body text of the Pushover notification. + minLength: 1 type: string monospace: description: |- @@ -5305,6 +5352,7 @@ spec: description: |- priority defines the notification priority level. See https://pushover.net/api#priority for valid values and behavior. + minLength: 1 type: string retry: description: |- @@ -5320,11 +5368,13 @@ spec: description: |- sound defines the name of one of the sounds supported by device clients. This overrides the user's default sound choice for this notification. + minLength: 1 type: string title: description: |- title defines the notification title displayed in the Pushover message. This appears as the bold header text in the notification. + minLength: 1 type: string token: description: |- @@ -5361,6 +5411,7 @@ spec: See https://pushover.net/apps for application registration. Either `token` or `tokenFile` is required. It requires Alertmanager >= v0.26.0. + minLength: 1 type: string ttl: description: |- @@ -5372,11 +5423,13 @@ spec: description: |- url defines a supplementary URL shown alongside the message. This creates a clickable link within the Pushover notification. + pattern: ^https?://.+$ type: string urlTitle: description: |- urlTitle defines a title for the supplementary URL. If not specified, the raw URL is shown instead. + minLength: 1 type: string userKey: description: |- @@ -5411,9 +5464,11 @@ spec: userKeyFile defines the user key file that contains the recipient user's user key. Either `userKey` or `userKeyFile` is required. It requires Alertmanager >= v0.26.0. + minLength: 1 type: string type: object type: array + x-kubernetes-list-type: atomic rocketchatConfigs: description: |- rocketchatConfigs defines the list of RocketChat configurations. @@ -5452,6 +5507,7 @@ spec: type: object minItems: 1 type: array + x-kubernetes-list-type: atomic apiURL: description: |- apiURL defines the API URL for RocketChat. @@ -5504,6 +5560,7 @@ spec: type: object minItems: 1 type: array + x-kubernetes-list-type: atomic httpConfig: description: httpConfig defines the HTTP client configuration for RocketChat API requests. @@ -6317,6 +6374,7 @@ spec: - tokenID type: object type: array + x-kubernetes-list-type: atomic slackConfigs: description: slackConfigs defines the list of Slack configurations. items: @@ -6343,11 +6401,13 @@ spec: description: |- dismissText defines the label for the cancel button in the dialog. When not specified, defaults to "Cancel". This button cancels the action. + minLength: 1 type: string okText: description: |- okText defines the label for the confirmation button in the dialog. When not specified, defaults to "Okay". This button proceeds with the action. + minLength: 1 type: string text: description: |- @@ -6359,6 +6419,7 @@ spec: description: |- title defines the title text displayed at the top of the confirmation dialog. When not specified, a default title will be used. + minLength: 1 type: string required: - text @@ -6367,11 +6428,13 @@ spec: description: |- name defines a unique identifier for the action within the message. This value is sent back to your application when the action is triggered. + minLength: 1 type: string style: description: |- style defines the visual appearance of the action element. Valid values include "default", "primary" (green), and "danger" (red). + minLength: 1 type: string text: description: |- @@ -6389,17 +6452,21 @@ spec: description: |- url defines the URL to open when the action is triggered. Only applicable for button-type actions. When set, clicking the button opens this URL. + pattern: ^https?://.+$ type: string value: description: |- value defines the payload sent when the action is triggered. This data is included in the callback sent to your application. + minLength: 1 type: string required: - text - type type: object + minItems: 1 type: array + x-kubernetes-list-type: atomic apiURL: description: |- apiURL defines the secret's key that contains the Slack webhook URL. @@ -6430,19 +6497,23 @@ spec: callbackId: description: callbackId defines an identifier for the message used in interactive components. + minLength: 1 type: string channel: description: channel defines the channel or user to send notifications to. + minLength: 1 type: string color: description: |- color defines the color of the left border of the Slack message attachment. Can be a hex color code (e.g., "#ff0000") or a predefined color name. + minLength: 1 type: string fallback: description: fallback defines a plain-text summary of the attachment for clients that don't support attachments. + minLength: 1 type: string fields: description: fields defines a list of Slack fields that @@ -6476,10 +6547,13 @@ spec: - title - value type: object + minItems: 1 type: array + x-kubernetes-list-type: atomic footer: description: footer defines small text displayed at the bottom of the message attachment. + minLength: 1 type: string httpConfig: description: httpConfig defines the HTTP client configuration. @@ -7189,14 +7263,17 @@ spec: iconEmoji: description: iconEmoji defines the emoji to use as the bot's avatar (e.g., ":ghost:"). + minLength: 1 type: string iconURL: description: iconURL defines the URL to an image to use as the bot's avatar. + pattern: ^https?://.+$ type: string imageURL: description: imageURL defines the URL to an image file that will be displayed inside the message attachment. + pattern: ^https?://.+$ type: string linkNames: description: |- @@ -7208,11 +7285,15 @@ spec: mrkdwnIn defines which fields should be parsed as Slack markdown. Valid values include "pretext", "text", and "fields". items: + minLength: 1 type: string + minItems: 1 type: array + x-kubernetes-list-type: atomic pretext: description: pretext defines optional text that appears above the message attachment block. + minLength: 1 type: string sendResolved: description: sendResolved defines whether or not to notify @@ -7226,25 +7307,38 @@ spec: text: description: text defines the main text content of the Slack message attachment. + minLength: 1 type: string thumbURL: description: |- thumbURL defines the URL to an image file that will be displayed as a thumbnail on the right side of the message attachment. + pattern: ^https?://.+$ + type: string + timeout: + description: |- + timeout defines the maximum time to wait for a webhook request to complete, + before failing the request and allowing it to be retried. + It requires Alertmanager >= v0.30.0. + pattern: ^(0|(([0-9]+)y)?(([0-9]+)w)?(([0-9]+)d)?(([0-9]+)h)?(([0-9]+)m)?(([0-9]+)s)?(([0-9]+)ms)?)$ type: string title: description: title defines the title text displayed in the Slack message attachment. + minLength: 1 type: string titleLink: description: titleLink defines the URL that the title will link to when clicked. + pattern: ^https?://.+$ type: string username: description: username defines the slack bot user name. + minLength: 1 type: string type: object type: array + x-kubernetes-list-type: atomic snsConfigs: description: snsConfigs defines the list of SNS configurations items: @@ -8076,6 +8170,7 @@ spec: type: string type: object type: array + x-kubernetes-list-type: atomic telegramConfigs: description: telegramConfigs defines the list of Telegram configurations. items: @@ -8087,6 +8182,7 @@ spec: description: |- apiURL defines the Telegram API URL, e.g. https://api.telegram.org. If not specified, the default Telegram API URL will be used. + pattern: ^https?://.+$ type: string botToken: description: |- @@ -8870,6 +8966,7 @@ spec: - chatID type: object type: array + x-kubernetes-list-type: atomic victoropsConfigs: description: victoropsConfigs defines the list of VictorOps configurations. @@ -8909,6 +9006,7 @@ spec: description: |- apiUrl defines the VictorOps API URL. When not specified, defaults to the standard VictorOps API endpoint. + pattern: ^https?://.+$ type: string customFields: description: |- @@ -8933,10 +9031,12 @@ spec: - value type: object type: array + x-kubernetes-list-type: atomic entityDisplayName: description: |- entityDisplayName contains a summary of the alerted problem. This appears as the main title or identifier for the incident. + minLength: 1 type: string httpConfig: description: httpConfig defines the HTTP client's configuration @@ -9648,16 +9748,19 @@ spec: description: |- messageType describes the behavior of the alert. Valid values are "CRITICAL", "WARNING", and "INFO". + minLength: 1 type: string monitoringTool: description: |- monitoringTool defines the monitoring tool the state message is from. This helps identify the source system that generated the alert. + minLength: 1 type: string routingKey: description: |- routingKey defines a key used to map the alert to a team. This determines which VictorOps team will receive the alert notification. + minLength: 1 type: string sendResolved: description: sendResolved defines whether or not to notify @@ -9667,9 +9770,13 @@ spec: description: |- stateMessage contains a long explanation of the alerted problem. This provides detailed context about the incident. + minLength: 1 type: string + required: + - routingKey type: object type: array + x-kubernetes-list-type: atomic webexConfigs: description: webexConfigs defines the list of Webex configurations. items: @@ -10403,6 +10510,7 @@ spec: - roomID type: object type: array + x-kubernetes-list-type: atomic webhookConfigs: description: webhookConfigs defines the List of webhook configurations. items: @@ -11138,6 +11246,7 @@ spec: description: |- url defines the URL to send HTTP POST requests to. urlSecret takes precedence over url. One of urlSecret and url should be defined. + pattern: ^https?://.+$ type: string urlSecret: description: |- @@ -11169,6 +11278,7 @@ spec: x-kubernetes-map-type: atomic type: object type: array + x-kubernetes-list-type: atomic wechatConfigs: description: wechatConfigs defines the list of WeChat configurations. items: @@ -11212,6 +11322,7 @@ spec: description: |- apiURL defines the WeChat API URL. When not specified, defaults to the standard WeChat Work API endpoint. + pattern: ^https?://.+$ type: string corpID: description: |- @@ -11955,10 +12066,14 @@ spec: type: string type: object type: array + x-kubernetes-list-type: atomic required: - name type: object type: array + x-kubernetes-list-map-keys: + - name + x-kubernetes-list-type: map route: description: |- route defines the Alertmanager route definition for alerts matching the resource's @@ -11971,6 +12086,7 @@ spec: items: type: string type: array + x-kubernetes-list-type: set continue: description: |- continue defines the boolean indicating whether an alert should continue matching subsequent @@ -11985,6 +12101,7 @@ spec: items: type: string type: array + x-kubernetes-list-type: set groupInterval: description: |- groupInterval defines how long to wait before sending an updated notification. @@ -12037,12 +12154,14 @@ spec: - name type: object type: array + x-kubernetes-list-type: atomic muteTimeIntervals: description: muteTimeIntervals is a list of MuteTimeInterval names that will mute this route when matched, items: type: string type: array + x-kubernetes-list-type: set receiver: description: |- receiver defines the name of the receiver for this route. If not empty, it should be listed in @@ -12059,13 +12178,119 @@ spec: items: x-kubernetes-preserve-unknown-fields: true type: array + x-kubernetes-list-type: atomic type: object type: object + status: + description: |- + status defines the status subresource. It is under active development and is updated only when the + "StatusForConfigurationResources" feature gate is enabled. + + Most recent observed status of the ServiceMonitor. Read-only. + More info: + https://github.com/kubernetes/community/blob/master/contributors/devel/sig-architecture/api-conventions.md#spec-and-status + properties: + bindings: + description: bindings defines the list of workload resources (Prometheus, + PrometheusAgent, ThanosRuler or Alertmanager) which select the configuration + resource. + items: + description: WorkloadBinding is a link between a configuration resource + and a workload resource. + properties: + conditions: + description: conditions defines the current state of the configuration + resource when bound to the referenced Workload object. + items: + description: ConfigResourceCondition describes the status + of configuration resources linked to Prometheus, PrometheusAgent, + Alertmanager or ThanosRuler. + properties: + lastTransitionTime: + description: lastTransitionTime defines the time of the + last update to the current status property. + format: date-time + type: string + message: + description: message defines the human-readable message + indicating details for the condition's last transition. + type: string + observedGeneration: + description: |- + observedGeneration defines the .metadata.generation that the + condition was set based upon. For instance, if `.metadata.generation` is + currently 12, but the `.status.conditions[].observedGeneration` is 9, the + condition is out of date with respect to the current state of the object. + format: int64 + type: integer + reason: + description: reason for the condition's last transition. + type: string + status: + description: status of the condition. + minLength: 1 + type: string + type: + description: |- + type of the condition being reported. + Currently, only "Accepted" is supported. + enum: + - Accepted + minLength: 1 + type: string + required: + - lastTransitionTime + - status + - type + type: object + type: array + x-kubernetes-list-map-keys: + - type + x-kubernetes-list-type: map + group: + description: group defines the group of the referenced resource. + enum: + - monitoring.coreos.com + type: string + name: + description: name defines the name of the referenced object. + minLength: 1 + type: string + namespace: + description: namespace defines the namespace of the referenced + object. + minLength: 1 + type: string + resource: + description: resource defines the type of resource being referenced + (e.g. Prometheus, PrometheusAgent, ThanosRuler or Alertmanager). + enum: + - prometheuses + - prometheusagents + - thanosrulers + - alertmanagers + type: string + required: + - group + - name + - namespace + - resource + type: object + type: array + x-kubernetes-list-map-keys: + - group + - resource + - name + - namespace + x-kubernetes-list-type: map + type: object required: - spec type: object served: true storage: true + subresources: + status: {} --- --- apiVersion: apiextensions.k8s.io/v1 @@ -12073,7 +12298,7 @@ kind: CustomResourceDefinition metadata: annotations: controller-gen.kubebuilder.io/version: v0.19.0 - operator.prometheus.io/version: 0.87.1 + operator.prometheus.io/version: 0.88.0 name: alertmanagers.monitoring.coreos.com spec: group: monitoring.coreos.com @@ -14388,7 +14613,7 @@ spec: type: string type: object webex: - description: webex defines the default configuration for Jira. + description: webex defines the default configuration for Webex. properties: apiURL: description: |- @@ -18210,10 +18435,18 @@ spec: type: string minReadySeconds: description: |- - minReadySeconds defines the minimum number of seconds for which a newly created pod should be ready - without any of its container crashing for it to be considered available. + minReadySeconds defines the minimum number of seconds for which a newly + created pod should be ready without any of its container crashing for it + to be considered available. If unset, pods will be considered available as soon as they are ready. + + When the Alertmanager version is greater than or equal to v0.30.0, the + duration is also used to delay the first flush of the aggregation + groups. This delay helps ensuring that all alerts have been resent by + the Prometheus instances to Alertmanager after a roll-out. It is + possible to override this behavior passing a custom value via + `.spec.additionalArgs`. format: int32 minimum: 0 type: integer @@ -18251,6 +18484,21 @@ spec: the replica count to be deleted. type: string type: object + podManagementPolicy: + description: |- + podManagementPolicy defines the policy for creating/deleting pods when + scaling up and down. + + Unlike the default StatefulSet behavior, the default policy is + `Parallel` to avoid manual intervention in case a pod gets stuck during + a rollout. + + Note that updating this value implies the recreation of the StatefulSet + which incurs a service outage. + enum: + - OrderedReady + - Parallel + type: string podMetadata: description: |- podMetadata defines labels and annotations which are propagated to the Alertmanager pods. @@ -19590,6 +19838,48 @@ spec: - whenUnsatisfiable type: object type: array + updateStrategy: + description: |- + updateStrategy indicates the strategy that will be employed to update + Pods in the StatefulSet when a revision is made to statefulset's Pod + Template. + + The default strategy is RollingUpdate. + properties: + rollingUpdate: + description: rollingUpdate is used to communicate parameters when + type is RollingUpdate. + properties: + maxUnavailable: + anyOf: + - type: integer + - type: string + description: |- + maxUnavailable is the maximum number of pods that can be unavailable + during the update. The value can be an absolute number (ex: 5) or a + percentage of desired pods (ex: 10%). Absolute number is calculated from + percentage by rounding up. This can not be 0. Defaults to 1. This field + is alpha-level and is only honored by servers that enable the + MaxUnavailableStatefulSet feature. The field applies to all pods in the + range 0 to Replicas-1. That means if there is any unavailable pod in + the range 0 to Replicas-1, it will be counted towards MaxUnavailable. + x-kubernetes-int-or-string: true + type: object + type: + description: |- + type indicates the type of the StatefulSetUpdateStrategy. + + Default is RollingUpdate. + enum: + - OnDelete + - RollingUpdate + type: string + required: + - type + type: object + x-kubernetes-validations: + - message: rollingUpdate requires type to be RollingUpdate + rule: '!(self.type != ''RollingUpdate'' && has(self.rollingUpdate))' version: description: version the cluster should be on. type: string @@ -21936,7 +22226,7 @@ kind: CustomResourceDefinition metadata: annotations: controller-gen.kubebuilder.io/version: v0.19.0 - operator.prometheus.io/version: 0.87.1 + operator.prometheus.io/version: 0.88.0 name: podmonitors.monitoring.coreos.com spec: group: monitoring.coreos.com @@ -23119,6 +23409,11 @@ spec: Notice: `scrapeClassicHistograms` corresponds to the `always_scrape_classic_histograms` field in the Prometheus configuration. type: boolean + scrapeNativeHistograms: + description: |- + scrapeNativeHistograms defines whether to enable scraping of native histograms. + It requires Prometheus >= v3.8.0. + type: boolean scrapeProtocols: description: |- scrapeProtocols defines the protocols to negotiate during a scrape. It tells clients the @@ -23330,7 +23625,7 @@ kind: CustomResourceDefinition metadata: annotations: controller-gen.kubebuilder.io/version: v0.19.0 - operator.prometheus.io/version: 0.87.1 + operator.prometheus.io/version: 0.88.0 name: probes.monitoring.coreos.com spec: group: monitoring.coreos.com @@ -23379,7 +23674,11 @@ spec: for target discovery by Prometheus. properties: authorization: - description: authorization section for this endpoint + description: |- + authorization configures the Authorization header credentials used by + the client. + + Cannot be set at the same time as `basicAuth`, `bearerTokenSecret` or `oauth2`. properties: credentials: description: credentials defines a key of a Secret in the namespace @@ -23417,8 +23716,10 @@ spec: type: object basicAuth: description: |- - basicAuth allow an endpoint to authenticate over basic authentication. - More info: https://prometheus.io/docs/operating/configuration/#endpoint + basicAuth defines the Basic Authentication credentials used by the + client. + + Cannot be set at the same time as `authorization`, `bearerTokenSecret` or `oauth2`. properties: password: description: |- @@ -23475,9 +23776,14 @@ spec: type: object bearerTokenSecret: description: |- - bearerTokenSecret defines the secret to mount to read bearer token for scraping targets. The secret - needs to be in the same namespace as the probe and accessible by - the Prometheus Operator. + bearerTokenSecret defines a key of a Secret containing the bearer token + used by the client for authentication. The secret needs to be in the + same namespace as the custom resource and readable by the Prometheus + Operator. + + Cannot be set at the same time as `authorization`, `basicAuth` or `oauth2`. + + Deprecated: use `authorization` instead. properties: key: description: The key of the secret to select from. Must be a @@ -23504,6 +23810,9 @@ spec: convertClassicHistogramsToNHCB defines whether to convert all scraped classic histograms into a native histogram with custom buckets. It requires Prometheus >= v3.0.0. type: boolean + enableHttp2: + description: enableHttp2 can be used to disable HTTP2. + type: boolean fallbackScrapeProtocol: description: |- fallbackScrapeProtocol defines the protocol to use if a scrape returns blank, unparseable, or otherwise invalid Content-Type. @@ -23516,6 +23825,11 @@ spec: - PrometheusText0.0.4 - PrometheusText1.0.0 type: string + followRedirects: + description: |- + followRedirects defines whether the client should follow HTTP 3xx + redirects. + type: boolean interval: description: |- interval at which targets are probed using the configured prober. @@ -23663,8 +23977,12 @@ spec: pattern: ^(\+|-)?(([0-9]+(\.[0-9]*)?)|(\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\+|-)?(([0-9]+(\.[0-9]*)?)|(\.[0-9]+))))?$ x-kubernetes-int-or-string: true oauth2: - description: oauth2 for the URL. Only valid in Prometheus versions - 2.27.0 and newer. + description: |- + oauth2 defines the OAuth2 settings used by the client. + + It requires Prometheus >= 2.27.0. + + Cannot be set at the same time as `authorization`, `basicAuth` or `bearerTokenSecret`. properties: clientId: description: |- @@ -24118,6 +24436,11 @@ spec: Notice: `scrapeClassicHistograms` corresponds to the `always_scrape_classic_histograms` field in the Prometheus configuration. type: boolean + scrapeNativeHistograms: + description: |- + scrapeNativeHistograms defines whether to enable scraping of native histograms. + It requires Prometheus >= v3.8.0. + type: boolean scrapeProtocols: description: |- scrapeProtocols defines the protocols to negotiate during a scrape. It tells clients the @@ -24434,8 +24757,7 @@ spec: type: object type: object tlsConfig: - description: tlsConfig defines the TLS configuration to use when scraping - the endpoint. + description: tlsConfig defines the TLS configuration used by the client. properties: ca: description: ca defines the Certificate authority used when verifying @@ -24719,7 +25041,7 @@ kind: CustomResourceDefinition metadata: annotations: controller-gen.kubebuilder.io/version: v0.19.0 - operator.prometheus.io/version: 0.87.1 + operator.prometheus.io/version: 0.88.0 name: prometheusagents.monitoring.coreos.com spec: group: monitoring.coreos.com @@ -29851,6 +30173,21 @@ spec: the replica count to be deleted. type: string type: object + podManagementPolicy: + description: |- + podManagementPolicy defines the policy for creating/deleting pods when + scaling up and down. + + Unlike the default StatefulSet behavior, the default policy is + `Parallel` to avoid manual intervention in case a pod gets stuck during + a rollout. + + Note that updating this value implies the recreation of the StatefulSet + which incurs a service outage. + enum: + - OrderedReady + - Parallel + type: string podMetadata: description: |- podMetadata defines labels and annotations which are propagated to the Prometheus pods. @@ -30209,7 +30546,7 @@ spec: managedIdentity: description: |- managedIdentity defines the Azure User-assigned Managed identity. - Cannot be set at the same time as `oauth` or `sdk`. + Cannot be set at the same time as `oauth`, `sdk` or `workloadIdentity`. properties: clientId: description: |- @@ -30222,7 +30559,7 @@ spec: oauth: description: |- oauth defines the oauth config that is being used to authenticate. - Cannot be set at the same time as `managedIdentity` or `sdk`. + Cannot be set at the same time as `managedIdentity`, `sdk` or `workloadIdentity`. It requires Prometheus >= v2.48.0 or Thanos >= v0.31.0. properties: @@ -30270,11 +30607,17 @@ spec: - clientSecret - tenantId type: object + scope: + description: |- + scope is the custom OAuth 2.0 scope to request when acquiring tokens. + It requires Prometheus >= 3.9.0. Currently not supported by Thanos. + pattern: ^[\w\s:/.\\-]+$ + type: string sdk: description: |- sdk defines the Azure SDK config that is being used to authenticate. See https://learn.microsoft.com/en-us/azure/developer/go/azure-sdk-authentication - Cannot be set at the same time as `oauth` or `managedIdentity`. + Cannot be set at the same time as `oauth`, `managedIdentity` or `workloadIdentity`. It requires Prometheus >= v2.52.0 or Thanos >= v0.36.0. properties: @@ -30285,6 +30628,27 @@ spec: pattern: ^[0-9a-zA-Z-.]+$ type: string type: object + workloadIdentity: + description: |- + workloadIdentity defines the Azure Workload Identity authentication. + Cannot be set at the same time as `oauth`, `managedIdentity`, or `sdk`. + + It requires Prometheus >= 3.7.0. Currently not supported by Thanos. + properties: + clientId: + description: clientId is the clientID of the Azure Active + Directory application. + minLength: 1 + type: string + tenantId: + description: tenantId is the tenant ID of the Azure + Active Directory application. + minLength: 1 + type: string + required: + - clientId + - tenantId + type: object type: object basicAuth: description: |- @@ -31980,6 +32344,11 @@ spec: Default: "30s" pattern: ^(0|(([0-9]+)y)?(([0-9]+)w)?(([0-9]+)d)?(([0-9]+)h)?(([0-9]+)m)?(([0-9]+)s)?(([0-9]+)ms)?)$ type: string + scrapeNativeHistograms: + description: |- + scrapeNativeHistograms defines whether to enable scraping of native histograms. + It requires Prometheus >= v3.8.0. + type: boolean scrapeProtocols: description: |- scrapeProtocols defines the protocols to negotiate during a scrape. It tells clients the @@ -33381,16 +33750,19 @@ spec: properties: clientType: description: clientType defines the client used to export the - traces. Supported values are `http` or `grpc`. + traces. Supported values are `HTTP` and `GRPC`. enum: - http - grpc + - HTTP + - GRPC type: string compression: description: compression key for supported compression types. - The only supported value is `gzip`. + The only supported value is `Gzip`. enum: - gzip + - Gzip type: string endpoint: description: endpoint to send the traces to. Should be provided @@ -33622,6 +33994,48 @@ spec: pattern: ^(0|(([0-9]+)y)?(([0-9]+)w)?(([0-9]+)d)?(([0-9]+)h)?(([0-9]+)m)?(([0-9]+)s)?(([0-9]+)ms)?)$ type: string type: object + updateStrategy: + description: |- + updateStrategy indicates the strategy that will be employed to update + Pods in the StatefulSet when a revision is made to statefulset's Pod + Template. + + The default strategy is RollingUpdate. + properties: + rollingUpdate: + description: rollingUpdate is used to communicate parameters when + type is RollingUpdate. + properties: + maxUnavailable: + anyOf: + - type: integer + - type: string + description: |- + maxUnavailable is the maximum number of pods that can be unavailable + during the update. The value can be an absolute number (ex: 5) or a + percentage of desired pods (ex: 10%). Absolute number is calculated from + percentage by rounding up. This can not be 0. Defaults to 1. This field + is alpha-level and is only honored by servers that enable the + MaxUnavailableStatefulSet feature. The field applies to all pods in the + range 0 to Replicas-1. That means if there is any unavailable pod in + the range 0 to Replicas-1, it will be counted towards MaxUnavailable. + x-kubernetes-int-or-string: true + type: object + type: + description: |- + type indicates the type of the StatefulSetUpdateStrategy. + + Default is RollingUpdate. + enum: + - OnDelete + - RollingUpdate + type: string + required: + - type + type: object + x-kubernetes-validations: + - message: rollingUpdate requires type to be RollingUpdate + rule: '!(self.type != ''RollingUpdate'' && has(self.rollingUpdate))' version: description: |- version of Prometheus being deployed. The operator uses this information @@ -35892,6 +36306,17 @@ spec: rule: '!(has(self.mode) && self.mode == ''DaemonSet'' && has(self.scrapeConfigSelector))' - message: probeSelector cannot be set when mode is DaemonSet rule: '!(has(self.mode) && self.mode == ''DaemonSet'' && has(self.probeSelector))' + - message: scrapeConfigNamespaceSelector cannot be set when mode is DaemonSet + rule: '!(has(self.mode) && self.mode == ''DaemonSet'' && has(self.scrapeConfigNamespaceSelector))' + - message: probeNamespaceSelector cannot be set when mode is DaemonSet + rule: '!(has(self.mode) && self.mode == ''DaemonSet'' && has(self.probeNamespaceSelector))' + - message: serviceMonitorSelector cannot be set when mode is DaemonSet + rule: '!(has(self.mode) && self.mode == ''DaemonSet'' && has(self.serviceMonitorSelector))' + - message: serviceMonitorNamespaceSelector cannot be set when mode is + DaemonSet + rule: '!(has(self.mode) && self.mode == ''DaemonSet'' && has(self.serviceMonitorNamespaceSelector))' + - message: additionalScrapeConfigs cannot be set when mode is DaemonSet + rule: '!(has(self.mode) && self.mode == ''DaemonSet'' && has(self.additionalScrapeConfigs))' status: description: |- status defines the most recent observed status of the Prometheus cluster. Read-only. @@ -36040,7 +36465,7 @@ kind: CustomResourceDefinition metadata: annotations: controller-gen.kubebuilder.io/version: v0.19.0 - operator.prometheus.io/version: 0.87.1 + operator.prometheus.io/version: 0.88.0 name: prometheuses.monitoring.coreos.com spec: group: monitoring.coreos.com @@ -41956,6 +42381,21 @@ spec: the replica count to be deleted. type: string type: object + podManagementPolicy: + description: |- + podManagementPolicy defines the policy for creating/deleting pods when + scaling up and down. + + Unlike the default StatefulSet behavior, the default policy is + `Parallel` to avoid manual intervention in case a pod gets stuck during + a rollout. + + Note that updating this value implies the recreation of the StatefulSet + which incurs a service outage. + enum: + - OrderedReady + - Parallel + type: string podMetadata: description: |- podMetadata defines labels and annotations which are propagated to the Prometheus pods. @@ -43120,7 +43560,7 @@ spec: managedIdentity: description: |- managedIdentity defines the Azure User-assigned Managed identity. - Cannot be set at the same time as `oauth` or `sdk`. + Cannot be set at the same time as `oauth`, `sdk` or `workloadIdentity`. properties: clientId: description: |- @@ -43133,7 +43573,7 @@ spec: oauth: description: |- oauth defines the oauth config that is being used to authenticate. - Cannot be set at the same time as `managedIdentity` or `sdk`. + Cannot be set at the same time as `managedIdentity`, `sdk` or `workloadIdentity`. It requires Prometheus >= v2.48.0 or Thanos >= v0.31.0. properties: @@ -43181,11 +43621,17 @@ spec: - clientSecret - tenantId type: object + scope: + description: |- + scope is the custom OAuth 2.0 scope to request when acquiring tokens. + It requires Prometheus >= 3.9.0. Currently not supported by Thanos. + pattern: ^[\w\s:/.\\-]+$ + type: string sdk: description: |- sdk defines the Azure SDK config that is being used to authenticate. See https://learn.microsoft.com/en-us/azure/developer/go/azure-sdk-authentication - Cannot be set at the same time as `oauth` or `managedIdentity`. + Cannot be set at the same time as `oauth`, `managedIdentity` or `workloadIdentity`. It requires Prometheus >= v2.52.0 or Thanos >= v0.36.0. properties: @@ -43196,6 +43642,27 @@ spec: pattern: ^[0-9a-zA-Z-.]+$ type: string type: object + workloadIdentity: + description: |- + workloadIdentity defines the Azure Workload Identity authentication. + Cannot be set at the same time as `oauth`, `managedIdentity`, or `sdk`. + + It requires Prometheus >= 3.7.0. Currently not supported by Thanos. + properties: + clientId: + description: clientId is the clientID of the Azure Active + Directory application. + minLength: 1 + type: string + tenantId: + description: tenantId is the tenant ID of the Azure + Active Directory application. + minLength: 1 + type: string + required: + - clientId + - tenantId + type: object type: object basicAuth: description: |- @@ -45036,6 +45503,11 @@ spec: Default: "30s" pattern: ^(0|(([0-9]+)y)?(([0-9]+)w)?(([0-9]+)d)?(([0-9]+)h)?(([0-9]+)m)?(([0-9]+)s)?(([0-9]+)ms)?)$ type: string + scrapeNativeHistograms: + description: |- + scrapeNativeHistograms defines whether to enable scraping of native histograms. + It requires Prometheus >= v3.8.0. + type: boolean scrapeProtocols: description: |- scrapeProtocols defines the protocols to negotiate during a scrape. It tells clients the @@ -46999,16 +47471,19 @@ spec: properties: clientType: description: clientType defines the client used to export the - traces. Supported values are `http` or `grpc`. + traces. Supported values are `HTTP` and `GRPC`. enum: - http - grpc + - HTTP + - GRPC type: string compression: description: compression key for supported compression types. - The only supported value is `gzip`. + The only supported value is `Gzip`. enum: - gzip + - Gzip type: string endpoint: description: endpoint to send the traces to. Should be provided @@ -47240,6 +47715,48 @@ spec: pattern: ^(0|(([0-9]+)y)?(([0-9]+)w)?(([0-9]+)d)?(([0-9]+)h)?(([0-9]+)m)?(([0-9]+)s)?(([0-9]+)ms)?)$ type: string type: object + updateStrategy: + description: |- + updateStrategy indicates the strategy that will be employed to update + Pods in the StatefulSet when a revision is made to statefulset's Pod + Template. + + The default strategy is RollingUpdate. + properties: + rollingUpdate: + description: rollingUpdate is used to communicate parameters when + type is RollingUpdate. + properties: + maxUnavailable: + anyOf: + - type: integer + - type: string + description: |- + maxUnavailable is the maximum number of pods that can be unavailable + during the update. The value can be an absolute number (ex: 5) or a + percentage of desired pods (ex: 10%). Absolute number is calculated from + percentage by rounding up. This can not be 0. Defaults to 1. This field + is alpha-level and is only honored by servers that enable the + MaxUnavailableStatefulSet feature. The field applies to all pods in the + range 0 to Replicas-1. That means if there is any unavailable pod in + the range 0 to Replicas-1, it will be counted towards MaxUnavailable. + x-kubernetes-int-or-string: true + type: object + type: + description: |- + type indicates the type of the StatefulSetUpdateStrategy. + + Default is RollingUpdate. + enum: + - OnDelete + - RollingUpdate + type: string + required: + - type + type: object + x-kubernetes-validations: + - message: rollingUpdate requires type to be RollingUpdate + rule: '!(self.type != ''RollingUpdate'' && has(self.rollingUpdate))' version: description: |- version of Prometheus being deployed. The operator uses this information @@ -49643,7 +50160,7 @@ kind: CustomResourceDefinition metadata: annotations: controller-gen.kubebuilder.io/version: v0.19.0 - operator.prometheus.io/version: 0.87.1 + operator.prometheus.io/version: 0.88.0 name: prometheusrules.monitoring.coreos.com spec: group: monitoring.coreos.com @@ -49910,7 +50427,7 @@ kind: CustomResourceDefinition metadata: annotations: controller-gen.kubebuilder.io/version: v0.19.0 - operator.prometheus.io/version: 0.87.1 + operator.prometheus.io/version: 0.88.0 name: scrapeconfigs.monitoring.coreos.com spec: group: monitoring.coreos.com @@ -62443,6 +62960,11 @@ spec: scrapes. pattern: ^(0|(([0-9]+)y)?(([0-9]+)w)?(([0-9]+)d)?(([0-9]+)h)?(([0-9]+)m)?(([0-9]+)s)?(([0-9]+)ms)?)$ type: string + scrapeNativeHistograms: + description: |- + scrapeNativeHistograms defines whether to enable scraping of native histograms. + It requires Prometheus >= v3.8.0. + type: boolean scrapeProtocols: description: |- scrapeProtocols defines the protocols to negotiate during a scrape. It tells clients the @@ -62804,7 +63326,7 @@ kind: CustomResourceDefinition metadata: annotations: controller-gen.kubebuilder.io/version: v0.19.0 - operator.prometheus.io/version: 0.87.1 + operator.prometheus.io/version: 0.88.0 name: servicemonitors.monitoring.coreos.com spec: group: monitoring.coreos.com @@ -62895,10 +63417,10 @@ spec: properties: authorization: description: |- - authorization configures the Authorization header credentials to use when - scraping the target. + authorization configures the Authorization header credentials used by + the client. - Cannot be set at the same time as `basicAuth`, or `oauth2`. + Cannot be set at the same time as `basicAuth`, `bearerTokenSecret` or `oauth2`. properties: credentials: description: credentials defines a key of a Secret in the @@ -62936,10 +63458,10 @@ spec: type: object basicAuth: description: |- - basicAuth defines the Basic Authentication credentials to use when - scraping the target. + basicAuth defines the Basic Authentication credentials used by the + client. - Cannot be set at the same time as `authorization`, or `oauth2`. + Cannot be set at the same time as `authorization`, `bearerTokenSecret` or `oauth2`. properties: password: description: |- @@ -63002,9 +63524,12 @@ spec: type: string bearerTokenSecret: description: |- - bearerTokenSecret defines a key of a Secret containing the bearer - token for scraping targets. The secret needs to be in the same namespace - as the ServiceMonitor object and readable by the Prometheus Operator. + bearerTokenSecret defines a key of a Secret containing the bearer token + used by the client for authentication. The secret needs to be in the + same namespace as the custom resource and readable by the Prometheus + Operator. + + Cannot be set at the same time as `authorization`, `basicAuth` or `oauth2`. Deprecated: use `authorization` instead. properties: @@ -63030,8 +63555,7 @@ spec: type: object x-kubernetes-map-type: atomic enableHttp2: - description: enableHttp2 can be used to disable HTTP2 when scraping - the target. + description: enableHttp2 can be used to disable HTTP2. type: boolean filterRunning: description: |- @@ -63044,8 +63568,8 @@ spec: type: boolean followRedirects: description: |- - followRedirects defines whether the scrape requests should follow HTTP - 3xx redirects. + followRedirects defines whether the client should follow HTTP 3xx + redirects. type: boolean honorLabels: description: |- @@ -63163,11 +63687,11 @@ spec: type: string oauth2: description: |- - oauth2 defines the OAuth2 settings to use when scraping the target. + oauth2 defines the OAuth2 settings used by the client. It requires Prometheus >= 2.27.0. - Cannot be set at the same time as `authorization`, or `basicAuth`. + Cannot be set at the same time as `authorization`, `basicAuth` or `bearerTokenSecret`. properties: clientId: description: |- @@ -63679,8 +64203,8 @@ spec: Service. The port must be specified with the container's port property. x-kubernetes-int-or-string: true tlsConfig: - description: tlsConfig defines the TLS configuration to use - when scraping the target. + description: tlsConfig defines TLS configuration used by the + client. properties: ca: description: ca defines the Certificate authority used when @@ -63980,6 +64504,11 @@ spec: Notice: `scrapeClassicHistograms` corresponds to the `always_scrape_classic_histograms` field in the Prometheus configuration. type: boolean + scrapeNativeHistograms: + description: |- + scrapeNativeHistograms defines whether to enable scraping of native histograms. + It requires Prometheus >= v3.8.0. + type: boolean scrapeProtocols: description: |- scrapeProtocols defines the protocols to negotiate during a scrape. It tells clients the @@ -64210,7 +64739,7 @@ kind: CustomResourceDefinition metadata: annotations: controller-gen.kubebuilder.io/version: v0.19.0 - operator.prometheus.io/version: 0.87.1 + operator.prometheus.io/version: 0.88.0 name: thanosrulers.monitoring.coreos.com spec: group: monitoring.coreos.com @@ -68850,6 +69379,21 @@ spec: paused defines when a ThanosRuler deployment is paused, no actions except for deletion will be performed on the underlying objects. type: boolean + podManagementPolicy: + description: |- + podManagementPolicy defines the policy for creating/deleting pods when + scaling up and down. + + Unlike the default StatefulSet behavior, the default policy is + `Parallel` to avoid manual intervention in case a pod gets stuck during + a rollout. + + Note that updating this value implies the recreation of the StatefulSet + which incurs a service outage. + enum: + - OrderedReady + - Parallel + type: string podMetadata: description: |- podMetadata defines labels and annotations which are propagated to the ThanosRuler pods. @@ -69043,7 +69587,7 @@ spec: managedIdentity: description: |- managedIdentity defines the Azure User-assigned Managed identity. - Cannot be set at the same time as `oauth` or `sdk`. + Cannot be set at the same time as `oauth`, `sdk` or `workloadIdentity`. properties: clientId: description: |- @@ -69056,7 +69600,7 @@ spec: oauth: description: |- oauth defines the oauth config that is being used to authenticate. - Cannot be set at the same time as `managedIdentity` or `sdk`. + Cannot be set at the same time as `managedIdentity`, `sdk` or `workloadIdentity`. It requires Prometheus >= v2.48.0 or Thanos >= v0.31.0. properties: @@ -69104,11 +69648,17 @@ spec: - clientSecret - tenantId type: object + scope: + description: |- + scope is the custom OAuth 2.0 scope to request when acquiring tokens. + It requires Prometheus >= 3.9.0. Currently not supported by Thanos. + pattern: ^[\w\s:/.\\-]+$ + type: string sdk: description: |- sdk defines the Azure SDK config that is being used to authenticate. See https://learn.microsoft.com/en-us/azure/developer/go/azure-sdk-authentication - Cannot be set at the same time as `oauth` or `managedIdentity`. + Cannot be set at the same time as `oauth`, `managedIdentity` or `workloadIdentity`. It requires Prometheus >= v2.52.0 or Thanos >= v0.36.0. properties: @@ -69119,6 +69669,27 @@ spec: pattern: ^[0-9a-zA-Z-.]+$ type: string type: object + workloadIdentity: + description: |- + workloadIdentity defines the Azure Workload Identity authentication. + Cannot be set at the same time as `oauth`, `managedIdentity`, or `sdk`. + + It requires Prometheus >= 3.7.0. Currently not supported by Thanos. + properties: + clientId: + description: clientId is the clientID of the Azure Active + Directory application. + minLength: 1 + type: string + tenantId: + description: tenantId is the tenant ID of the Azure + Active Directory application. + minLength: 1 + type: string + required: + - clientId + - tenantId + type: object type: object basicAuth: description: |- @@ -71525,6 +72096,48 @@ spec: This field takes precedence over `tracingConfig`. type: string + updateStrategy: + description: |- + updateStrategy indicates the strategy that will be employed to update + Pods in the StatefulSet when a revision is made to statefulset's Pod + Template. + + The default strategy is RollingUpdate. + properties: + rollingUpdate: + description: rollingUpdate is used to communicate parameters when + type is RollingUpdate. + properties: + maxUnavailable: + anyOf: + - type: integer + - type: string + description: |- + maxUnavailable is the maximum number of pods that can be unavailable + during the update. The value can be an absolute number (ex: 5) or a + percentage of desired pods (ex: 10%). Absolute number is calculated from + percentage by rounding up. This can not be 0. Defaults to 1. This field + is alpha-level and is only honored by servers that enable the + MaxUnavailableStatefulSet feature. The field applies to all pods in the + range 0 to Replicas-1. That means if there is any unavailable pod in + the range 0 to Replicas-1, it will be counted towards MaxUnavailable. + x-kubernetes-int-or-string: true + type: object + type: + description: |- + type indicates the type of the StatefulSetUpdateStrategy. + + Default is RollingUpdate. + enum: + - OnDelete + - RollingUpdate + type: string + required: + - type + type: object + x-kubernetes-validations: + - message: rollingUpdate requires type to be RollingUpdate + rule: '!(self.type != ''RollingUpdate'' && has(self.rollingUpdate))' version: description: version of Thanos to be deployed. type: string @@ -73850,7 +74463,7 @@ metadata: labels: app.kubernetes.io/component: controller app.kubernetes.io/name: prometheus-operator - app.kubernetes.io/version: 0.87.1 + app.kubernetes.io/version: 0.88.0 name: prometheus-operator roleRef: apiGroup: rbac.authorization.k8s.io @@ -73867,7 +74480,7 @@ metadata: labels: app.kubernetes.io/component: controller app.kubernetes.io/name: prometheus-operator - app.kubernetes.io/version: 0.87.1 + app.kubernetes.io/version: 0.88.0 name: prometheus-operator rules: - apiGroups: @@ -73980,7 +74593,7 @@ metadata: labels: app.kubernetes.io/component: controller app.kubernetes.io/name: prometheus-operator - app.kubernetes.io/version: 0.87.1 + app.kubernetes.io/version: 0.88.0 name: prometheus-operator namespace: default spec: @@ -73996,19 +74609,21 @@ spec: labels: app.kubernetes.io/component: controller app.kubernetes.io/name: prometheus-operator - app.kubernetes.io/version: 0.87.1 + app.kubernetes.io/version: 0.88.0 spec: automountServiceAccountToken: true containers: - args: - --kubelet-service=kube-system/kubelet - - --prometheus-config-reloader=quay.io/prometheus-operator/prometheus-config-reloader:v0.87.1 + - --prometheus-config-reloader=quay.io/prometheus-operator/prometheus-config-reloader:v0.88.0 + - --watch-referenced-objects-in-all-namespaces=true + - --disable-unmanaged-prometheus-configuration=true - --kubelet-endpoints=true - --kubelet-endpointslice=false env: - name: GOGC value: "30" - image: quay.io/prometheus-operator/prometheus-operator:v0.87.1 + image: quay.io/prometheus-operator/prometheus-operator:v0.88.0 name: prometheus-operator ports: - containerPort: 8080 @@ -74042,7 +74657,7 @@ metadata: labels: app.kubernetes.io/component: controller app.kubernetes.io/name: prometheus-operator - app.kubernetes.io/version: 0.87.1 + app.kubernetes.io/version: 0.88.0 name: prometheus-operator namespace: default --- @@ -74052,7 +74667,7 @@ metadata: labels: app.kubernetes.io/component: controller app.kubernetes.io/name: prometheus-operator - app.kubernetes.io/version: 0.87.1 + app.kubernetes.io/version: 0.88.0 name: prometheus-operator namespace: default spec: diff --git a/cmd/admission-webhook/Dockerfile b/cmd/admission-webhook/Dockerfile index 7fd8f874318..71cd4ab158c 100644 --- a/cmd/admission-webhook/Dockerfile +++ b/cmd/admission-webhook/Dockerfile @@ -1,6 +1,6 @@ ARG ARCH=amd64 ARG OS=linux -ARG GOLANG_BUILDER=1.24 +ARG GOLANG_BUILDER=1.25 FROM quay.io/prometheus/golang-builder:${GOLANG_BUILDER}-base AS builder WORKDIR /workspace diff --git a/cmd/prometheus-config-reloader/Dockerfile b/cmd/prometheus-config-reloader/Dockerfile index d84cfb96541..74ed0f0bd0c 100644 --- a/cmd/prometheus-config-reloader/Dockerfile +++ b/cmd/prometheus-config-reloader/Dockerfile @@ -1,6 +1,6 @@ ARG ARCH=amd64 ARG OS=linux -ARG GOLANG_BUILDER=1.24 +ARG GOLANG_BUILDER=1.25 FROM quay.io/prometheus/golang-builder:${GOLANG_BUILDER}-base AS builder WORKDIR /workspace diff --git a/example/admission-webhook/deployment.yaml b/example/admission-webhook/deployment.yaml index 52508e8150b..bac9683be92 100644 --- a/example/admission-webhook/deployment.yaml +++ b/example/admission-webhook/deployment.yaml @@ -3,7 +3,7 @@ kind: Deployment metadata: labels: app.kubernetes.io/name: prometheus-operator-admission-webhook - app.kubernetes.io/version: 0.87.1 + app.kubernetes.io/version: 0.88.0 name: prometheus-operator-admission-webhook namespace: default spec: @@ -20,7 +20,7 @@ spec: kubectl.kubernetes.io/default-container: prometheus-operator-admission-webhook labels: app.kubernetes.io/name: prometheus-operator-admission-webhook - app.kubernetes.io/version: 0.87.1 + app.kubernetes.io/version: 0.88.0 spec: affinity: podAntiAffinity: @@ -37,7 +37,7 @@ spec: - --web.enable-tls=true - --web.cert-file=/etc/tls/private/tls.crt - --web.key-file=/etc/tls/private/tls.key - image: quay.io/prometheus-operator/admission-webhook:v0.87.1 + image: quay.io/prometheus-operator/admission-webhook:v0.88.0 name: prometheus-operator-admission-webhook ports: - containerPort: 8443 diff --git a/example/admission-webhook/pod-disruption-budget.yaml b/example/admission-webhook/pod-disruption-budget.yaml index 0cbb2e2475d..643d3529946 100644 --- a/example/admission-webhook/pod-disruption-budget.yaml +++ b/example/admission-webhook/pod-disruption-budget.yaml @@ -3,7 +3,7 @@ kind: PodDisruptionBudget metadata: labels: app.kubernetes.io/name: prometheus-operator-admission-webhook - app.kubernetes.io/version: 0.87.1 + app.kubernetes.io/version: 0.88.0 name: prometheus-operator-admission-webhook namespace: default spec: diff --git a/example/admission-webhook/service-account.yaml b/example/admission-webhook/service-account.yaml index 32d0f35cde1..3f3a21f047f 100644 --- a/example/admission-webhook/service-account.yaml +++ b/example/admission-webhook/service-account.yaml @@ -4,6 +4,6 @@ kind: ServiceAccount metadata: labels: app.kubernetes.io/name: prometheus-operator-admission-webhook - app.kubernetes.io/version: 0.87.1 + app.kubernetes.io/version: 0.88.0 name: prometheus-operator-admission-webhook namespace: default diff --git a/example/admission-webhook/service-monitor.yaml b/example/admission-webhook/service-monitor.yaml index 1b71c7ec742..8d8e8b330f7 100644 --- a/example/admission-webhook/service-monitor.yaml +++ b/example/admission-webhook/service-monitor.yaml @@ -3,7 +3,7 @@ kind: ServiceMonitor metadata: labels: app.kubernetes.io/name: prometheus-operator-admission-webhook - app.kubernetes.io/version: 0.87.1 + app.kubernetes.io/version: 0.88.0 name: prometheus-operator-admission-webhook namespace: default spec: @@ -13,4 +13,4 @@ spec: selector: matchLabels: app.kubernetes.io/name: prometheus-operator-admission-webhook - app.kubernetes.io/version: 0.87.1 + app.kubernetes.io/version: 0.88.0 diff --git a/example/admission-webhook/service.yaml b/example/admission-webhook/service.yaml index 8488e7a6071..b4596ad07fa 100644 --- a/example/admission-webhook/service.yaml +++ b/example/admission-webhook/service.yaml @@ -3,7 +3,7 @@ kind: Service metadata: labels: app.kubernetes.io/name: prometheus-operator-admission-webhook - app.kubernetes.io/version: 0.87.1 + app.kubernetes.io/version: 0.88.0 name: prometheus-operator-admission-webhook namespace: default spec: diff --git a/example/alertmanager-crd-conversion/patch.json b/example/alertmanager-crd-conversion/patch.json index 5b193b27789..b027a599057 100644 --- a/example/alertmanager-crd-conversion/patch.json +++ b/example/alertmanager-crd-conversion/patch.json @@ -4,7 +4,7 @@ "metadata": { "annotations": { "controller-gen.kubebuilder.io/version": "v0.19.0", - "operator.prometheus.io/version": "0.87.1" + "operator.prometheus.io/version": "0.88.0" }, "name": "alertmanagerconfigs.monitoring.coreos.com" }, diff --git a/example/prometheus-operator-crd-full/monitoring.coreos.com_alertmanagerconfigs.yaml b/example/prometheus-operator-crd-full/monitoring.coreos.com_alertmanagerconfigs.yaml index 6329516f04e..9ca318d28b1 100644 --- a/example/prometheus-operator-crd-full/monitoring.coreos.com_alertmanagerconfigs.yaml +++ b/example/prometheus-operator-crd-full/monitoring.coreos.com_alertmanagerconfigs.yaml @@ -62,6 +62,7 @@ spec: items: type: string type: array + x-kubernetes-list-type: atomic sourceMatch: description: |- sourceMatch defines matchers for which one or more alerts have to exist for the inhibition @@ -101,6 +102,7 @@ spec: - name type: object type: array + x-kubernetes-list-type: atomic targetMatch: description: |- targetMatch defines matchers that have to be fulfilled in the alerts to be muted. @@ -140,8 +142,10 @@ spec: - name type: object type: array + x-kubernetes-list-type: atomic type: object type: array + x-kubernetes-list-type: atomic muteTimeIntervals: description: muteTimeIntervals defines the list of MuteTimeInterval specifying when the routes should be muted. @@ -175,6 +179,7 @@ spec: type: integer type: object type: array + x-kubernetes-list-type: atomic months: description: months defines a list of MonthRange items: @@ -184,6 +189,7 @@ spec: pattern: ^((?i)january|february|march|april|may|june|july|august|september|october|november|december|1[0-2]|[1-9])(?:((:((?i)january|february|march|april|may|june|july|august|september|october|november|december|1[0-2]|[1-9]))$)|$) type: string type: array + x-kubernetes-list-type: atomic times: description: times defines a list of TimeRange items: @@ -202,6 +208,7 @@ spec: type: string type: object type: array + x-kubernetes-list-type: atomic weekdays: description: weekdays defines a list of WeekdayRange items: @@ -211,6 +218,7 @@ spec: pattern: ^((?i)sun|mon|tues|wednes|thurs|fri|satur)day(?:((:(sun|mon|tues|wednes|thurs|fri|satur)day)$)|$) type: string type: array + x-kubernetes-list-type: atomic years: description: years defines a list of YearRange items: @@ -218,12 +226,15 @@ spec: pattern: ^2\d{3}(?::2\d{3}|$) type: string type: array + x-kubernetes-list-type: atomic type: object type: array + x-kubernetes-list-type: atomic required: - name type: object type: array + x-kubernetes-list-type: atomic receivers: description: receivers defines the list of receivers. items: @@ -999,6 +1010,7 @@ spec: - apiURL type: object type: array + x-kubernetes-list-type: atomic emailConfigs: description: emailConfigs defines the list of Email configurations. items: @@ -1097,6 +1109,7 @@ spec: - value type: object type: array + x-kubernetes-list-type: atomic hello: description: |- hello defines the hostname to identify to the SMTP server. @@ -1302,6 +1315,7 @@ spec: type: string type: object type: array + x-kubernetes-list-type: atomic msteamsConfigs: description: |- msteamsConfigs defines the list of MSTeams configurations. @@ -2067,6 +2081,7 @@ spec: - webhookUrl type: object type: array + x-kubernetes-list-type: atomic msteamsv2Configs: description: |- msteamsv2Configs defines the list of MSTeamsV2 configurations. @@ -2827,6 +2842,7 @@ spec: x-kubernetes-map-type: atomic type: object type: array + x-kubernetes-list-type: atomic name: description: name defines the name of the receiver. Must be unique across all items from the list. @@ -2875,6 +2891,7 @@ spec: description: |- apiURL defines the URL to send OpsGenie API requests to. When not specified, defaults to the standard OpsGenie API endpoint. + pattern: ^https?://.+$ type: string description: description: |- @@ -2904,6 +2921,7 @@ spec: - value type: object type: array + x-kubernetes-list-type: atomic entity: description: |- entity defines an optional field that can be used to specify which domain alert is related to. @@ -3671,6 +3689,7 @@ spec: - type type: object type: array + x-kubernetes-list-type: atomic sendResolved: description: sendResolved defines whether or not to notify about resolved alerts. @@ -3692,6 +3711,7 @@ spec: type: boolean type: object type: array + x-kubernetes-list-type: atomic pagerdutyConfigs: description: pagerdutyConfigs defines the List of PagerDuty configurations. @@ -3702,20 +3722,25 @@ spec: properties: class: description: class defines the class/type of the event. + minLength: 1 type: string client: description: client defines the client identification. + minLength: 1 type: string clientURL: description: clientURL defines the backlink to the sender of notification. + pattern: ^https?://.+$ type: string component: description: component defines the part or component of the affected system that is broken. + minLength: 1 type: string description: description: description of the incident. + minLength: 1 type: string details: description: details defines the arbitrary key/value pairs @@ -3739,8 +3764,10 @@ spec: - value type: object type: array + x-kubernetes-list-type: atomic group: description: group defines a cluster or grouping of sources. + minLength: 1 type: string httpConfig: description: httpConfig defines the HTTP client configuration. @@ -4458,17 +4485,21 @@ spec: alt: description: alt is the optional alternative text for the image. + minLength: 1 type: string href: description: href defines the optional URL; makes the image a clickable link. + pattern: ^https?://.+$ type: string src: description: src of the image being attached to the incident + minLength: 1 type: string type: object type: array + x-kubernetes-list-type: atomic pagerDutyLinkConfigs: description: pagerDutyLinkConfigs defines a list of link details to attach that provide further detail about @@ -4481,13 +4512,16 @@ spec: description: alt defines the text that describes the purpose of the link, and can be used as the link's text. + minLength: 1 type: string href: description: href defines the URL of the link to be attached + pattern: ^https?://.+$ type: string type: object type: array + x-kubernetes-list-type: atomic routingKey: description: |- routingKey defines the secret's key that contains the PagerDuty integration key (when using @@ -4551,16 +4585,26 @@ spec: x-kubernetes-map-type: atomic severity: description: severity of the incident. + minLength: 1 type: string source: description: source defines the unique location of the affected system. + minLength: 1 + type: string + timeout: + description: |- + timeout is the maximum time allowed to invoke the pagerduty + It requires Alertmanager >= v0.30.0. + pattern: ^(0|(([0-9]+)y)?(([0-9]+)w)?(([0-9]+)d)?(([0-9]+)h)?(([0-9]+)m)?(([0-9]+)s)?(([0-9]+)ms)?)$ type: string url: description: url defines the URL to send requests to. + pattern: ^https?://.+$ type: string type: object type: array + x-kubernetes-list-type: atomic pushoverConfigs: description: pushoverConfigs defines the list of Pushover configurations. items: @@ -4572,6 +4616,7 @@ spec: description: |- device defines the name of a specific device to send the notification to. If not specified, the notification is sent to all user's devices. + minLength: 1 type: string expire: description: |- @@ -4583,6 +4628,7 @@ spec: description: |- html defines whether notification message is HTML or plain text. When true, the message can include HTML formatting tags. + html and monospace formatting are mutually exclusive. type: boolean httpConfig: description: httpConfig defines the HTTP client configuration @@ -5294,6 +5340,7 @@ spec: description: |- message defines the notification message content. This is the main body text of the Pushover notification. + minLength: 1 type: string monospace: description: |- @@ -5304,6 +5351,7 @@ spec: description: |- priority defines the notification priority level. See https://pushover.net/api#priority for valid values and behavior. + minLength: 1 type: string retry: description: |- @@ -5319,11 +5367,13 @@ spec: description: |- sound defines the name of one of the sounds supported by device clients. This overrides the user's default sound choice for this notification. + minLength: 1 type: string title: description: |- title defines the notification title displayed in the Pushover message. This appears as the bold header text in the notification. + minLength: 1 type: string token: description: |- @@ -5360,6 +5410,7 @@ spec: See https://pushover.net/apps for application registration. Either `token` or `tokenFile` is required. It requires Alertmanager >= v0.26.0. + minLength: 1 type: string ttl: description: |- @@ -5371,11 +5422,13 @@ spec: description: |- url defines a supplementary URL shown alongside the message. This creates a clickable link within the Pushover notification. + pattern: ^https?://.+$ type: string urlTitle: description: |- urlTitle defines a title for the supplementary URL. If not specified, the raw URL is shown instead. + minLength: 1 type: string userKey: description: |- @@ -5410,9 +5463,11 @@ spec: userKeyFile defines the user key file that contains the recipient user's user key. Either `userKey` or `userKeyFile` is required. It requires Alertmanager >= v0.26.0. + minLength: 1 type: string type: object type: array + x-kubernetes-list-type: atomic rocketchatConfigs: description: |- rocketchatConfigs defines the list of RocketChat configurations. @@ -5451,6 +5506,7 @@ spec: type: object minItems: 1 type: array + x-kubernetes-list-type: atomic apiURL: description: |- apiURL defines the API URL for RocketChat. @@ -5503,6 +5559,7 @@ spec: type: object minItems: 1 type: array + x-kubernetes-list-type: atomic httpConfig: description: httpConfig defines the HTTP client configuration for RocketChat API requests. @@ -6316,6 +6373,7 @@ spec: - tokenID type: object type: array + x-kubernetes-list-type: atomic slackConfigs: description: slackConfigs defines the list of Slack configurations. items: @@ -6342,11 +6400,13 @@ spec: description: |- dismissText defines the label for the cancel button in the dialog. When not specified, defaults to "Cancel". This button cancels the action. + minLength: 1 type: string okText: description: |- okText defines the label for the confirmation button in the dialog. When not specified, defaults to "Okay". This button proceeds with the action. + minLength: 1 type: string text: description: |- @@ -6358,6 +6418,7 @@ spec: description: |- title defines the title text displayed at the top of the confirmation dialog. When not specified, a default title will be used. + minLength: 1 type: string required: - text @@ -6366,11 +6427,13 @@ spec: description: |- name defines a unique identifier for the action within the message. This value is sent back to your application when the action is triggered. + minLength: 1 type: string style: description: |- style defines the visual appearance of the action element. Valid values include "default", "primary" (green), and "danger" (red). + minLength: 1 type: string text: description: |- @@ -6388,17 +6451,21 @@ spec: description: |- url defines the URL to open when the action is triggered. Only applicable for button-type actions. When set, clicking the button opens this URL. + pattern: ^https?://.+$ type: string value: description: |- value defines the payload sent when the action is triggered. This data is included in the callback sent to your application. + minLength: 1 type: string required: - text - type type: object + minItems: 1 type: array + x-kubernetes-list-type: atomic apiURL: description: |- apiURL defines the secret's key that contains the Slack webhook URL. @@ -6429,19 +6496,23 @@ spec: callbackId: description: callbackId defines an identifier for the message used in interactive components. + minLength: 1 type: string channel: description: channel defines the channel or user to send notifications to. + minLength: 1 type: string color: description: |- color defines the color of the left border of the Slack message attachment. Can be a hex color code (e.g., "#ff0000") or a predefined color name. + minLength: 1 type: string fallback: description: fallback defines a plain-text summary of the attachment for clients that don't support attachments. + minLength: 1 type: string fields: description: fields defines a list of Slack fields that @@ -6475,10 +6546,13 @@ spec: - title - value type: object + minItems: 1 type: array + x-kubernetes-list-type: atomic footer: description: footer defines small text displayed at the bottom of the message attachment. + minLength: 1 type: string httpConfig: description: httpConfig defines the HTTP client configuration. @@ -7188,14 +7262,17 @@ spec: iconEmoji: description: iconEmoji defines the emoji to use as the bot's avatar (e.g., ":ghost:"). + minLength: 1 type: string iconURL: description: iconURL defines the URL to an image to use as the bot's avatar. + pattern: ^https?://.+$ type: string imageURL: description: imageURL defines the URL to an image file that will be displayed inside the message attachment. + pattern: ^https?://.+$ type: string linkNames: description: |- @@ -7207,11 +7284,15 @@ spec: mrkdwnIn defines which fields should be parsed as Slack markdown. Valid values include "pretext", "text", and "fields". items: + minLength: 1 type: string + minItems: 1 type: array + x-kubernetes-list-type: atomic pretext: description: pretext defines optional text that appears above the message attachment block. + minLength: 1 type: string sendResolved: description: sendResolved defines whether or not to notify @@ -7225,25 +7306,38 @@ spec: text: description: text defines the main text content of the Slack message attachment. + minLength: 1 type: string thumbURL: description: |- thumbURL defines the URL to an image file that will be displayed as a thumbnail on the right side of the message attachment. + pattern: ^https?://.+$ + type: string + timeout: + description: |- + timeout defines the maximum time to wait for a webhook request to complete, + before failing the request and allowing it to be retried. + It requires Alertmanager >= v0.30.0. + pattern: ^(0|(([0-9]+)y)?(([0-9]+)w)?(([0-9]+)d)?(([0-9]+)h)?(([0-9]+)m)?(([0-9]+)s)?(([0-9]+)ms)?)$ type: string title: description: title defines the title text displayed in the Slack message attachment. + minLength: 1 type: string titleLink: description: titleLink defines the URL that the title will link to when clicked. + pattern: ^https?://.+$ type: string username: description: username defines the slack bot user name. + minLength: 1 type: string type: object type: array + x-kubernetes-list-type: atomic snsConfigs: description: snsConfigs defines the list of SNS configurations items: @@ -8075,6 +8169,7 @@ spec: type: string type: object type: array + x-kubernetes-list-type: atomic telegramConfigs: description: telegramConfigs defines the list of Telegram configurations. items: @@ -8086,6 +8181,7 @@ spec: description: |- apiURL defines the Telegram API URL, e.g. https://api.telegram.org. If not specified, the default Telegram API URL will be used. + pattern: ^https?://.+$ type: string botToken: description: |- @@ -8869,6 +8965,7 @@ spec: - chatID type: object type: array + x-kubernetes-list-type: atomic victoropsConfigs: description: victoropsConfigs defines the list of VictorOps configurations. @@ -8908,6 +9005,7 @@ spec: description: |- apiUrl defines the VictorOps API URL. When not specified, defaults to the standard VictorOps API endpoint. + pattern: ^https?://.+$ type: string customFields: description: |- @@ -8932,10 +9030,12 @@ spec: - value type: object type: array + x-kubernetes-list-type: atomic entityDisplayName: description: |- entityDisplayName contains a summary of the alerted problem. This appears as the main title or identifier for the incident. + minLength: 1 type: string httpConfig: description: httpConfig defines the HTTP client's configuration @@ -9647,16 +9747,19 @@ spec: description: |- messageType describes the behavior of the alert. Valid values are "CRITICAL", "WARNING", and "INFO". + minLength: 1 type: string monitoringTool: description: |- monitoringTool defines the monitoring tool the state message is from. This helps identify the source system that generated the alert. + minLength: 1 type: string routingKey: description: |- routingKey defines a key used to map the alert to a team. This determines which VictorOps team will receive the alert notification. + minLength: 1 type: string sendResolved: description: sendResolved defines whether or not to notify @@ -9666,9 +9769,13 @@ spec: description: |- stateMessage contains a long explanation of the alerted problem. This provides detailed context about the incident. + minLength: 1 type: string + required: + - routingKey type: object type: array + x-kubernetes-list-type: atomic webexConfigs: description: webexConfigs defines the list of Webex configurations. items: @@ -10402,6 +10509,7 @@ spec: - roomID type: object type: array + x-kubernetes-list-type: atomic webhookConfigs: description: webhookConfigs defines the List of webhook configurations. items: @@ -11137,6 +11245,7 @@ spec: description: |- url defines the URL to send HTTP POST requests to. urlSecret takes precedence over url. One of urlSecret and url should be defined. + pattern: ^https?://.+$ type: string urlSecret: description: |- @@ -11168,6 +11277,7 @@ spec: x-kubernetes-map-type: atomic type: object type: array + x-kubernetes-list-type: atomic wechatConfigs: description: wechatConfigs defines the list of WeChat configurations. items: @@ -11211,6 +11321,7 @@ spec: description: |- apiURL defines the WeChat API URL. When not specified, defaults to the standard WeChat Work API endpoint. + pattern: ^https?://.+$ type: string corpID: description: |- @@ -11954,10 +12065,14 @@ spec: type: string type: object type: array + x-kubernetes-list-type: atomic required: - name type: object type: array + x-kubernetes-list-map-keys: + - name + x-kubernetes-list-type: map route: description: |- route defines the Alertmanager route definition for alerts matching the resource's @@ -11970,6 +12085,7 @@ spec: items: type: string type: array + x-kubernetes-list-type: set continue: description: |- continue defines the boolean indicating whether an alert should continue matching subsequent @@ -11984,6 +12100,7 @@ spec: items: type: string type: array + x-kubernetes-list-type: set groupInterval: description: |- groupInterval defines how long to wait before sending an updated notification. @@ -12036,12 +12153,14 @@ spec: - name type: object type: array + x-kubernetes-list-type: atomic muteTimeIntervals: description: muteTimeIntervals is a list of MuteTimeInterval names that will mute this route when matched, items: type: string type: array + x-kubernetes-list-type: set receiver: description: |- receiver defines the name of the receiver for this route. If not empty, it should be listed in @@ -12058,13 +12177,119 @@ spec: items: x-kubernetes-preserve-unknown-fields: true type: array + x-kubernetes-list-type: atomic type: object type: object + status: + description: |- + status defines the status subresource. It is under active development and is updated only when the + "StatusForConfigurationResources" feature gate is enabled. + + Most recent observed status of the ServiceMonitor. Read-only. + More info: + https://github.com/kubernetes/community/blob/master/contributors/devel/sig-architecture/api-conventions.md#spec-and-status + properties: + bindings: + description: bindings defines the list of workload resources (Prometheus, + PrometheusAgent, ThanosRuler or Alertmanager) which select the configuration + resource. + items: + description: WorkloadBinding is a link between a configuration resource + and a workload resource. + properties: + conditions: + description: conditions defines the current state of the configuration + resource when bound to the referenced Workload object. + items: + description: ConfigResourceCondition describes the status + of configuration resources linked to Prometheus, PrometheusAgent, + Alertmanager or ThanosRuler. + properties: + lastTransitionTime: + description: lastTransitionTime defines the time of the + last update to the current status property. + format: date-time + type: string + message: + description: message defines the human-readable message + indicating details for the condition's last transition. + type: string + observedGeneration: + description: |- + observedGeneration defines the .metadata.generation that the + condition was set based upon. For instance, if `.metadata.generation` is + currently 12, but the `.status.conditions[].observedGeneration` is 9, the + condition is out of date with respect to the current state of the object. + format: int64 + type: integer + reason: + description: reason for the condition's last transition. + type: string + status: + description: status of the condition. + minLength: 1 + type: string + type: + description: |- + type of the condition being reported. + Currently, only "Accepted" is supported. + enum: + - Accepted + minLength: 1 + type: string + required: + - lastTransitionTime + - status + - type + type: object + type: array + x-kubernetes-list-map-keys: + - type + x-kubernetes-list-type: map + group: + description: group defines the group of the referenced resource. + enum: + - monitoring.coreos.com + type: string + name: + description: name defines the name of the referenced object. + minLength: 1 + type: string + namespace: + description: namespace defines the namespace of the referenced + object. + minLength: 1 + type: string + resource: + description: resource defines the type of resource being referenced + (e.g. Prometheus, PrometheusAgent, ThanosRuler or Alertmanager). + enum: + - prometheuses + - prometheusagents + - thanosrulers + - alertmanagers + type: string + required: + - group + - name + - namespace + - resource + type: object + type: array + x-kubernetes-list-map-keys: + - group + - resource + - name + - namespace + x-kubernetes-list-type: map + type: object required: - spec type: object served: true storage: true + subresources: + status: {} - name: v1beta1 schema: openAPIV3Schema: @@ -14789,6 +15014,7 @@ spec: description: |- apiURL defines the URL to send OpsGenie API requests to. When not specified, defaults to the standard OpsGenie API endpoint. + pattern: ^https?://.+$ type: string description: description: |- @@ -15604,20 +15830,25 @@ spec: properties: class: description: class defines the class/type of the event. + minLength: 1 type: string client: description: client defines the client identification. + minLength: 1 type: string clientURL: description: clientURL defines the backlink to the sender of notification. + pattern: ^https?://.+$ type: string component: description: component defines the part or component of the affected system that is broken. + minLength: 1 type: string description: description: description of the incident. + minLength: 1 type: string details: description: details defines the arbitrary key/value pairs @@ -15641,8 +15872,10 @@ spec: - value type: object type: array + x-kubernetes-list-type: atomic group: description: group defines a cluster or grouping of sources. + minLength: 1 type: string httpConfig: description: httpConfig defines the HTTP client configuration. @@ -16353,17 +16586,21 @@ spec: alt: description: alt is the optional alternative text for the image. + minLength: 1 type: string href: description: href defines the optional URL; makes the image a clickable link. + pattern: ^https?://.+$ type: string src: description: src of the image being attached to the incident + minLength: 1 type: string type: object type: array + x-kubernetes-list-type: atomic pagerDutyLinkConfigs: description: pagerDutyLinkConfigs defines a list of link details to attach that provide further detail about @@ -16376,13 +16613,16 @@ spec: description: alt defines the text that describes the purpose of the link, and can be used as the link's text. + minLength: 1 type: string href: description: href defines the URL of the link to be attached + pattern: ^https?://.+$ type: string type: object type: array + x-kubernetes-list-type: atomic routingKey: description: |- routingKey defines the secret's key that contains the PagerDuty integration key (when using @@ -16432,13 +16672,22 @@ spec: type: object severity: description: severity of the incident. + minLength: 1 type: string source: description: source defines the unique location of the affected system. + minLength: 1 + type: string + timeout: + description: |- + timeout is the maximum time allowed to invoke the pagerduty + It requires Alertmanager >= v0.30.0. + pattern: ^(0|(([0-9]+)y)?(([0-9]+)w)?(([0-9]+)d)?(([0-9]+)h)?(([0-9]+)m)?(([0-9]+)s)?(([0-9]+)ms)?)$ type: string url: description: url defines the URL to send requests to. + pattern: ^https?://.+$ type: string type: object type: array @@ -16453,6 +16702,7 @@ spec: description: |- device defines the name of a specific device to send the notification to. If not specified, the notification is sent to all user's devices. + minLength: 1 type: string expire: description: |- @@ -16464,6 +16714,7 @@ spec: description: |- html defines whether notification message is HTML or plain text. When true, the message can include HTML formatting tags. + html and monospace formatting are mutually exclusive. type: boolean httpConfig: description: httpConfig defines the HTTP client configuration @@ -17168,6 +17419,7 @@ spec: description: |- message defines the notification message content. This is the main body text of the Pushover notification. + minLength: 1 type: string monospace: description: |- @@ -17178,6 +17430,7 @@ spec: description: |- priority defines the notification priority level. See https://pushover.net/api#priority for valid values and behavior. + minLength: 1 type: string retry: description: |- @@ -17193,11 +17446,13 @@ spec: description: |- sound defines the name of one of the sounds supported by device clients. This overrides the user's default sound choice for this notification. + minLength: 1 type: string title: description: |- title defines the notification title displayed in the Pushover message. This appears as the bold header text in the notification. + minLength: 1 type: string token: description: |- @@ -17238,11 +17493,13 @@ spec: description: |- url defines a supplementary URL shown alongside the message. This creates a clickable link within the Pushover notification. + pattern: ^https?://.+$ type: string urlTitle: description: |- urlTitle defines a title for the supplementary URL. If not specified, the raw URL is shown instead. + minLength: 1 type: string userKey: description: |- @@ -18195,11 +18452,13 @@ spec: description: |- dismissText defines the label for the cancel button in the dialog. When not specified, defaults to "Cancel". This button cancels the action. + minLength: 1 type: string okText: description: |- okText defines the label for the confirmation button in the dialog. When not specified, defaults to "Okay". This button proceeds with the action. + minLength: 1 type: string text: description: |- @@ -18211,6 +18470,7 @@ spec: description: |- title defines the title text displayed at the top of the confirmation dialog. When not specified, a default title will be used. + minLength: 1 type: string required: - text @@ -18219,11 +18479,13 @@ spec: description: |- name defines a unique identifier for the action within the message. This value is sent back to your application when the action is triggered. + minLength: 1 type: string style: description: |- style defines the visual appearance of the action element. Valid values include "default", "primary" (green), and "danger" (red). + minLength: 1 type: string text: description: |- @@ -18241,17 +18503,21 @@ spec: description: |- url defines the URL to open when the action is triggered. Only applicable for button-type actions. When set, clicking the button opens this URL. + pattern: ^https?://.+$ type: string value: description: |- value defines the payload sent when the action is triggered. This data is included in the callback sent to your application. + minLength: 1 type: string required: - text - type type: object + minItems: 1 type: array + x-kubernetes-list-type: atomic apiURL: description: |- apiURL defines the secret's key that contains the Slack webhook URL. @@ -18275,19 +18541,23 @@ spec: callbackId: description: callbackId defines an identifier for the message used in interactive components. + minLength: 1 type: string channel: description: channel defines the channel or user to send notifications to. + minLength: 1 type: string color: description: |- color defines the color of the left border of the Slack message attachment. Can be a hex color code (e.g., "#ff0000") or a predefined color name. + minLength: 1 type: string fallback: description: fallback defines a plain-text summary of the attachment for clients that don't support attachments. + minLength: 1 type: string fields: description: fields defines a list of Slack fields that @@ -18321,10 +18591,13 @@ spec: - title - value type: object + minItems: 1 type: array + x-kubernetes-list-type: atomic footer: description: footer defines small text displayed at the bottom of the message attachment. + minLength: 1 type: string httpConfig: description: httpConfig defines the HTTP client configuration. @@ -19027,14 +19300,17 @@ spec: iconEmoji: description: iconEmoji defines the emoji to use as the bot's avatar (e.g., ":ghost:"). + minLength: 1 type: string iconURL: description: iconURL defines the URL to an image to use as the bot's avatar. + pattern: ^https?://.+$ type: string imageURL: description: imageURL defines the URL to an image file that will be displayed inside the message attachment. + pattern: ^https?://.+$ type: string linkNames: description: |- @@ -19046,11 +19322,15 @@ spec: mrkdwnIn defines which fields should be parsed as Slack markdown. Valid values include "pretext", "text", and "fields". items: + minLength: 1 type: string + minItems: 1 type: array + x-kubernetes-list-type: atomic pretext: description: pretext defines optional text that appears above the message attachment block. + minLength: 1 type: string sendResolved: description: sendResolved defines whether or not to notify @@ -19064,22 +19344,34 @@ spec: text: description: text defines the main text content of the Slack message attachment. + minLength: 1 type: string thumbURL: description: |- thumbURL defines the URL to an image file that will be displayed as a thumbnail on the right side of the message attachment. + pattern: ^https?://.+$ + type: string + timeout: + description: |- + timeout defines the maximum time to wait for a webhook request to complete, + before failing the request and allowing it to be retried. + It requires Alertmanager >= v0.30.0. + pattern: ^(0|(([0-9]+)y)?(([0-9]+)w)?(([0-9]+)d)?(([0-9]+)h)?(([0-9]+)m)?(([0-9]+)s)?(([0-9]+)ms)?)$ type: string title: description: title defines the title text displayed in the Slack message attachment. + minLength: 1 type: string titleLink: description: titleLink defines the URL that the title will link to when clicked. + pattern: ^https?://.+$ type: string username: description: username defines the slack bot user name. + minLength: 1 type: string type: object type: array @@ -19918,6 +20210,7 @@ spec: description: |- apiURL defines the Telegram API URL, e.g. https://api.telegram.org. If not specified, the default Telegram API URL will be used. + pattern: ^https?://.+$ type: string botToken: description: |- @@ -20719,6 +21012,7 @@ spec: description: |- apiUrl defines the VictorOps API URL. When not specified, defaults to the standard VictorOps API endpoint. + pattern: ^https?://.+$ type: string customFields: description: |- @@ -20743,10 +21037,12 @@ spec: - value type: object type: array + x-kubernetes-list-type: atomic entityDisplayName: description: |- entityDisplayName contains a summary of the alerted problem. This appears as the main title or identifier for the incident. + minLength: 1 type: string httpConfig: description: httpConfig defines the HTTP client's configuration @@ -21451,16 +21747,19 @@ spec: description: |- messageType describes the behavior of the alert. Valid values are "CRITICAL", "WARNING", and "INFO". + minLength: 1 type: string monitoringTool: description: |- monitoringTool defines the monitoring tool the state message is from. This helps identify the source system that generated the alert. + minLength: 1 type: string routingKey: description: |- routingKey defines a key used to map the alert to a team. This determines which VictorOps team will receive the alert notification. + minLength: 1 type: string sendResolved: description: sendResolved defines whether or not to notify @@ -21470,7 +21769,10 @@ spec: description: |- stateMessage contains a long explanation of the alerted problem. This provides detailed context about the incident. + minLength: 1 type: string + required: + - routingKey type: object type: array webexConfigs: @@ -22929,6 +23231,7 @@ spec: description: |- url defines the URL to send HTTP POST requests to. urlSecret takes precedence over url. One of urlSecret and url should be defined. + pattern: ^https?://.+$ type: string urlSecret: description: |- @@ -22989,6 +23292,7 @@ spec: description: |- apiURL defines the WeChat API URL. When not specified, defaults to the standard WeChat Work API endpoint. + pattern: ^https?://.+$ type: string corpID: description: |- @@ -23908,8 +24212,113 @@ spec: type: object type: array type: object + status: + description: |- + status defines the status subresource. It is under active development and is updated only when the + "StatusForConfigurationResources" feature gate is enabled. + + Most recent observed status of the ServiceMonitor. Read-only. + More info: + https://github.com/kubernetes/community/blob/master/contributors/devel/sig-architecture/api-conventions.md#spec-and-status + properties: + bindings: + description: bindings defines the list of workload resources (Prometheus, + PrometheusAgent, ThanosRuler or Alertmanager) which select the configuration + resource. + items: + description: WorkloadBinding is a link between a configuration resource + and a workload resource. + properties: + conditions: + description: conditions defines the current state of the configuration + resource when bound to the referenced Workload object. + items: + description: ConfigResourceCondition describes the status + of configuration resources linked to Prometheus, PrometheusAgent, + Alertmanager or ThanosRuler. + properties: + lastTransitionTime: + description: lastTransitionTime defines the time of the + last update to the current status property. + format: date-time + type: string + message: + description: message defines the human-readable message + indicating details for the condition's last transition. + type: string + observedGeneration: + description: |- + observedGeneration defines the .metadata.generation that the + condition was set based upon. For instance, if `.metadata.generation` is + currently 12, but the `.status.conditions[].observedGeneration` is 9, the + condition is out of date with respect to the current state of the object. + format: int64 + type: integer + reason: + description: reason for the condition's last transition. + type: string + status: + description: status of the condition. + minLength: 1 + type: string + type: + description: |- + type of the condition being reported. + Currently, only "Accepted" is supported. + enum: + - Accepted + minLength: 1 + type: string + required: + - lastTransitionTime + - status + - type + type: object + type: array + x-kubernetes-list-map-keys: + - type + x-kubernetes-list-type: map + group: + description: group defines the group of the referenced resource. + enum: + - monitoring.coreos.com + type: string + name: + description: name defines the name of the referenced object. + minLength: 1 + type: string + namespace: + description: namespace defines the namespace of the referenced + object. + minLength: 1 + type: string + resource: + description: resource defines the type of resource being referenced + (e.g. Prometheus, PrometheusAgent, ThanosRuler or Alertmanager). + enum: + - prometheuses + - prometheusagents + - thanosrulers + - alertmanagers + type: string + required: + - group + - name + - namespace + - resource + type: object + type: array + x-kubernetes-list-map-keys: + - group + - resource + - name + - namespace + x-kubernetes-list-type: map + type: object required: - spec type: object served: true storage: false + subresources: + status: {} diff --git a/example/prometheus-operator-crd-full/monitoring.coreos.com_alertmanagers.yaml b/example/prometheus-operator-crd-full/monitoring.coreos.com_alertmanagers.yaml index e57360088a4..9aaa86c0575 100644 --- a/example/prometheus-operator-crd-full/monitoring.coreos.com_alertmanagers.yaml +++ b/example/prometheus-operator-crd-full/monitoring.coreos.com_alertmanagers.yaml @@ -2318,7 +2318,7 @@ spec: type: string type: object webex: - description: webex defines the default configuration for Jira. + description: webex defines the default configuration for Webex. properties: apiURL: description: |- @@ -6140,10 +6140,18 @@ spec: type: string minReadySeconds: description: |- - minReadySeconds defines the minimum number of seconds for which a newly created pod should be ready - without any of its container crashing for it to be considered available. + minReadySeconds defines the minimum number of seconds for which a newly + created pod should be ready without any of its container crashing for it + to be considered available. If unset, pods will be considered available as soon as they are ready. + + When the Alertmanager version is greater than or equal to v0.30.0, the + duration is also used to delay the first flush of the aggregation + groups. This delay helps ensuring that all alerts have been resent by + the Prometheus instances to Alertmanager after a roll-out. It is + possible to override this behavior passing a custom value via + `.spec.additionalArgs`. format: int32 minimum: 0 type: integer @@ -6181,6 +6189,21 @@ spec: the replica count to be deleted. type: string type: object + podManagementPolicy: + description: |- + podManagementPolicy defines the policy for creating/deleting pods when + scaling up and down. + + Unlike the default StatefulSet behavior, the default policy is + `Parallel` to avoid manual intervention in case a pod gets stuck during + a rollout. + + Note that updating this value implies the recreation of the StatefulSet + which incurs a service outage. + enum: + - OrderedReady + - Parallel + type: string podMetadata: description: |- podMetadata defines labels and annotations which are propagated to the Alertmanager pods. @@ -7520,6 +7543,48 @@ spec: - whenUnsatisfiable type: object type: array + updateStrategy: + description: |- + updateStrategy indicates the strategy that will be employed to update + Pods in the StatefulSet when a revision is made to statefulset's Pod + Template. + + The default strategy is RollingUpdate. + properties: + rollingUpdate: + description: rollingUpdate is used to communicate parameters when + type is RollingUpdate. + properties: + maxUnavailable: + anyOf: + - type: integer + - type: string + description: |- + maxUnavailable is the maximum number of pods that can be unavailable + during the update. The value can be an absolute number (ex: 5) or a + percentage of desired pods (ex: 10%). Absolute number is calculated from + percentage by rounding up. This can not be 0. Defaults to 1. This field + is alpha-level and is only honored by servers that enable the + MaxUnavailableStatefulSet feature. The field applies to all pods in the + range 0 to Replicas-1. That means if there is any unavailable pod in + the range 0 to Replicas-1, it will be counted towards MaxUnavailable. + x-kubernetes-int-or-string: true + type: object + type: + description: |- + type indicates the type of the StatefulSetUpdateStrategy. + + Default is RollingUpdate. + enum: + - OnDelete + - RollingUpdate + type: string + required: + - type + type: object + x-kubernetes-validations: + - message: rollingUpdate requires type to be RollingUpdate + rule: '!(self.type != ''RollingUpdate'' && has(self.rollingUpdate))' version: description: version the cluster should be on. type: string diff --git a/example/prometheus-operator-crd-full/monitoring.coreos.com_podmonitors.yaml b/example/prometheus-operator-crd-full/monitoring.coreos.com_podmonitors.yaml index 74314849094..f2fd4a55ee3 100644 --- a/example/prometheus-operator-crd-full/monitoring.coreos.com_podmonitors.yaml +++ b/example/prometheus-operator-crd-full/monitoring.coreos.com_podmonitors.yaml @@ -1186,6 +1186,11 @@ spec: Notice: `scrapeClassicHistograms` corresponds to the `always_scrape_classic_histograms` field in the Prometheus configuration. type: boolean + scrapeNativeHistograms: + description: |- + scrapeNativeHistograms defines whether to enable scraping of native histograms. + It requires Prometheus >= v3.8.0. + type: boolean scrapeProtocols: description: |- scrapeProtocols defines the protocols to negotiate during a scrape. It tells clients the diff --git a/example/prometheus-operator-crd-full/monitoring.coreos.com_probes.yaml b/example/prometheus-operator-crd-full/monitoring.coreos.com_probes.yaml index 86ad94b44a6..d4deb2623a1 100644 --- a/example/prometheus-operator-crd-full/monitoring.coreos.com_probes.yaml +++ b/example/prometheus-operator-crd-full/monitoring.coreos.com_probes.yaml @@ -52,7 +52,11 @@ spec: for target discovery by Prometheus. properties: authorization: - description: authorization section for this endpoint + description: |- + authorization configures the Authorization header credentials used by + the client. + + Cannot be set at the same time as `basicAuth`, `bearerTokenSecret` or `oauth2`. properties: credentials: description: credentials defines a key of a Secret in the namespace @@ -90,8 +94,10 @@ spec: type: object basicAuth: description: |- - basicAuth allow an endpoint to authenticate over basic authentication. - More info: https://prometheus.io/docs/operating/configuration/#endpoint + basicAuth defines the Basic Authentication credentials used by the + client. + + Cannot be set at the same time as `authorization`, `bearerTokenSecret` or `oauth2`. properties: password: description: |- @@ -148,9 +154,14 @@ spec: type: object bearerTokenSecret: description: |- - bearerTokenSecret defines the secret to mount to read bearer token for scraping targets. The secret - needs to be in the same namespace as the probe and accessible by - the Prometheus Operator. + bearerTokenSecret defines a key of a Secret containing the bearer token + used by the client for authentication. The secret needs to be in the + same namespace as the custom resource and readable by the Prometheus + Operator. + + Cannot be set at the same time as `authorization`, `basicAuth` or `oauth2`. + + Deprecated: use `authorization` instead. properties: key: description: The key of the secret to select from. Must be a @@ -177,6 +188,9 @@ spec: convertClassicHistogramsToNHCB defines whether to convert all scraped classic histograms into a native histogram with custom buckets. It requires Prometheus >= v3.0.0. type: boolean + enableHttp2: + description: enableHttp2 can be used to disable HTTP2. + type: boolean fallbackScrapeProtocol: description: |- fallbackScrapeProtocol defines the protocol to use if a scrape returns blank, unparseable, or otherwise invalid Content-Type. @@ -189,6 +203,11 @@ spec: - PrometheusText0.0.4 - PrometheusText1.0.0 type: string + followRedirects: + description: |- + followRedirects defines whether the client should follow HTTP 3xx + redirects. + type: boolean interval: description: |- interval at which targets are probed using the configured prober. @@ -336,8 +355,12 @@ spec: pattern: ^(\+|-)?(([0-9]+(\.[0-9]*)?)|(\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\+|-)?(([0-9]+(\.[0-9]*)?)|(\.[0-9]+))))?$ x-kubernetes-int-or-string: true oauth2: - description: oauth2 for the URL. Only valid in Prometheus versions - 2.27.0 and newer. + description: |- + oauth2 defines the OAuth2 settings used by the client. + + It requires Prometheus >= 2.27.0. + + Cannot be set at the same time as `authorization`, `basicAuth` or `bearerTokenSecret`. properties: clientId: description: |- @@ -791,6 +814,11 @@ spec: Notice: `scrapeClassicHistograms` corresponds to the `always_scrape_classic_histograms` field in the Prometheus configuration. type: boolean + scrapeNativeHistograms: + description: |- + scrapeNativeHistograms defines whether to enable scraping of native histograms. + It requires Prometheus >= v3.8.0. + type: boolean scrapeProtocols: description: |- scrapeProtocols defines the protocols to negotiate during a scrape. It tells clients the @@ -1107,8 +1135,7 @@ spec: type: object type: object tlsConfig: - description: tlsConfig defines the TLS configuration to use when scraping - the endpoint. + description: tlsConfig defines the TLS configuration used by the client. properties: ca: description: ca defines the Certificate authority used when verifying diff --git a/example/prometheus-operator-crd-full/monitoring.coreos.com_prometheusagents.yaml b/example/prometheus-operator-crd-full/monitoring.coreos.com_prometheusagents.yaml index b7b5420c889..a85c29d69bc 100644 --- a/example/prometheus-operator-crd-full/monitoring.coreos.com_prometheusagents.yaml +++ b/example/prometheus-operator-crd-full/monitoring.coreos.com_prometheusagents.yaml @@ -5135,6 +5135,21 @@ spec: the replica count to be deleted. type: string type: object + podManagementPolicy: + description: |- + podManagementPolicy defines the policy for creating/deleting pods when + scaling up and down. + + Unlike the default StatefulSet behavior, the default policy is + `Parallel` to avoid manual intervention in case a pod gets stuck during + a rollout. + + Note that updating this value implies the recreation of the StatefulSet + which incurs a service outage. + enum: + - OrderedReady + - Parallel + type: string podMetadata: description: |- podMetadata defines labels and annotations which are propagated to the Prometheus pods. @@ -5493,7 +5508,7 @@ spec: managedIdentity: description: |- managedIdentity defines the Azure User-assigned Managed identity. - Cannot be set at the same time as `oauth` or `sdk`. + Cannot be set at the same time as `oauth`, `sdk` or `workloadIdentity`. properties: clientId: description: |- @@ -5506,7 +5521,7 @@ spec: oauth: description: |- oauth defines the oauth config that is being used to authenticate. - Cannot be set at the same time as `managedIdentity` or `sdk`. + Cannot be set at the same time as `managedIdentity`, `sdk` or `workloadIdentity`. It requires Prometheus >= v2.48.0 or Thanos >= v0.31.0. properties: @@ -5554,11 +5569,17 @@ spec: - clientSecret - tenantId type: object + scope: + description: |- + scope is the custom OAuth 2.0 scope to request when acquiring tokens. + It requires Prometheus >= 3.9.0. Currently not supported by Thanos. + pattern: ^[\w\s:/.\\-]+$ + type: string sdk: description: |- sdk defines the Azure SDK config that is being used to authenticate. See https://learn.microsoft.com/en-us/azure/developer/go/azure-sdk-authentication - Cannot be set at the same time as `oauth` or `managedIdentity`. + Cannot be set at the same time as `oauth`, `managedIdentity` or `workloadIdentity`. It requires Prometheus >= v2.52.0 or Thanos >= v0.36.0. properties: @@ -5569,6 +5590,27 @@ spec: pattern: ^[0-9a-zA-Z-.]+$ type: string type: object + workloadIdentity: + description: |- + workloadIdentity defines the Azure Workload Identity authentication. + Cannot be set at the same time as `oauth`, `managedIdentity`, or `sdk`. + + It requires Prometheus >= 3.7.0. Currently not supported by Thanos. + properties: + clientId: + description: clientId is the clientID of the Azure Active + Directory application. + minLength: 1 + type: string + tenantId: + description: tenantId is the tenant ID of the Azure + Active Directory application. + minLength: 1 + type: string + required: + - clientId + - tenantId + type: object type: object basicAuth: description: |- @@ -7264,6 +7306,11 @@ spec: Default: "30s" pattern: ^(0|(([0-9]+)y)?(([0-9]+)w)?(([0-9]+)d)?(([0-9]+)h)?(([0-9]+)m)?(([0-9]+)s)?(([0-9]+)ms)?)$ type: string + scrapeNativeHistograms: + description: |- + scrapeNativeHistograms defines whether to enable scraping of native histograms. + It requires Prometheus >= v3.8.0. + type: boolean scrapeProtocols: description: |- scrapeProtocols defines the protocols to negotiate during a scrape. It tells clients the @@ -8665,16 +8712,19 @@ spec: properties: clientType: description: clientType defines the client used to export the - traces. Supported values are `http` or `grpc`. + traces. Supported values are `HTTP` and `GRPC`. enum: - http - grpc + - HTTP + - GRPC type: string compression: description: compression key for supported compression types. - The only supported value is `gzip`. + The only supported value is `Gzip`. enum: - gzip + - Gzip type: string endpoint: description: endpoint to send the traces to. Should be provided @@ -8906,6 +8956,48 @@ spec: pattern: ^(0|(([0-9]+)y)?(([0-9]+)w)?(([0-9]+)d)?(([0-9]+)h)?(([0-9]+)m)?(([0-9]+)s)?(([0-9]+)ms)?)$ type: string type: object + updateStrategy: + description: |- + updateStrategy indicates the strategy that will be employed to update + Pods in the StatefulSet when a revision is made to statefulset's Pod + Template. + + The default strategy is RollingUpdate. + properties: + rollingUpdate: + description: rollingUpdate is used to communicate parameters when + type is RollingUpdate. + properties: + maxUnavailable: + anyOf: + - type: integer + - type: string + description: |- + maxUnavailable is the maximum number of pods that can be unavailable + during the update. The value can be an absolute number (ex: 5) or a + percentage of desired pods (ex: 10%). Absolute number is calculated from + percentage by rounding up. This can not be 0. Defaults to 1. This field + is alpha-level and is only honored by servers that enable the + MaxUnavailableStatefulSet feature. The field applies to all pods in the + range 0 to Replicas-1. That means if there is any unavailable pod in + the range 0 to Replicas-1, it will be counted towards MaxUnavailable. + x-kubernetes-int-or-string: true + type: object + type: + description: |- + type indicates the type of the StatefulSetUpdateStrategy. + + Default is RollingUpdate. + enum: + - OnDelete + - RollingUpdate + type: string + required: + - type + type: object + x-kubernetes-validations: + - message: rollingUpdate requires type to be RollingUpdate + rule: '!(self.type != ''RollingUpdate'' && has(self.rollingUpdate))' version: description: |- version of Prometheus being deployed. The operator uses this information @@ -11176,6 +11268,17 @@ spec: rule: '!(has(self.mode) && self.mode == ''DaemonSet'' && has(self.scrapeConfigSelector))' - message: probeSelector cannot be set when mode is DaemonSet rule: '!(has(self.mode) && self.mode == ''DaemonSet'' && has(self.probeSelector))' + - message: scrapeConfigNamespaceSelector cannot be set when mode is DaemonSet + rule: '!(has(self.mode) && self.mode == ''DaemonSet'' && has(self.scrapeConfigNamespaceSelector))' + - message: probeNamespaceSelector cannot be set when mode is DaemonSet + rule: '!(has(self.mode) && self.mode == ''DaemonSet'' && has(self.probeNamespaceSelector))' + - message: serviceMonitorSelector cannot be set when mode is DaemonSet + rule: '!(has(self.mode) && self.mode == ''DaemonSet'' && has(self.serviceMonitorSelector))' + - message: serviceMonitorNamespaceSelector cannot be set when mode is + DaemonSet + rule: '!(has(self.mode) && self.mode == ''DaemonSet'' && has(self.serviceMonitorNamespaceSelector))' + - message: additionalScrapeConfigs cannot be set when mode is DaemonSet + rule: '!(has(self.mode) && self.mode == ''DaemonSet'' && has(self.additionalScrapeConfigs))' status: description: |- status defines the most recent observed status of the Prometheus cluster. Read-only. diff --git a/example/prometheus-operator-crd-full/monitoring.coreos.com_prometheuses.yaml b/example/prometheus-operator-crd-full/monitoring.coreos.com_prometheuses.yaml index 36782dadceb..8f8a77622da 100644 --- a/example/prometheus-operator-crd-full/monitoring.coreos.com_prometheuses.yaml +++ b/example/prometheus-operator-crd-full/monitoring.coreos.com_prometheuses.yaml @@ -5919,6 +5919,21 @@ spec: the replica count to be deleted. type: string type: object + podManagementPolicy: + description: |- + podManagementPolicy defines the policy for creating/deleting pods when + scaling up and down. + + Unlike the default StatefulSet behavior, the default policy is + `Parallel` to avoid manual intervention in case a pod gets stuck during + a rollout. + + Note that updating this value implies the recreation of the StatefulSet + which incurs a service outage. + enum: + - OrderedReady + - Parallel + type: string podMetadata: description: |- podMetadata defines labels and annotations which are propagated to the Prometheus pods. @@ -7083,7 +7098,7 @@ spec: managedIdentity: description: |- managedIdentity defines the Azure User-assigned Managed identity. - Cannot be set at the same time as `oauth` or `sdk`. + Cannot be set at the same time as `oauth`, `sdk` or `workloadIdentity`. properties: clientId: description: |- @@ -7096,7 +7111,7 @@ spec: oauth: description: |- oauth defines the oauth config that is being used to authenticate. - Cannot be set at the same time as `managedIdentity` or `sdk`. + Cannot be set at the same time as `managedIdentity`, `sdk` or `workloadIdentity`. It requires Prometheus >= v2.48.0 or Thanos >= v0.31.0. properties: @@ -7144,11 +7159,17 @@ spec: - clientSecret - tenantId type: object + scope: + description: |- + scope is the custom OAuth 2.0 scope to request when acquiring tokens. + It requires Prometheus >= 3.9.0. Currently not supported by Thanos. + pattern: ^[\w\s:/.\\-]+$ + type: string sdk: description: |- sdk defines the Azure SDK config that is being used to authenticate. See https://learn.microsoft.com/en-us/azure/developer/go/azure-sdk-authentication - Cannot be set at the same time as `oauth` or `managedIdentity`. + Cannot be set at the same time as `oauth`, `managedIdentity` or `workloadIdentity`. It requires Prometheus >= v2.52.0 or Thanos >= v0.36.0. properties: @@ -7159,6 +7180,27 @@ spec: pattern: ^[0-9a-zA-Z-.]+$ type: string type: object + workloadIdentity: + description: |- + workloadIdentity defines the Azure Workload Identity authentication. + Cannot be set at the same time as `oauth`, `managedIdentity`, or `sdk`. + + It requires Prometheus >= 3.7.0. Currently not supported by Thanos. + properties: + clientId: + description: clientId is the clientID of the Azure Active + Directory application. + minLength: 1 + type: string + tenantId: + description: tenantId is the tenant ID of the Azure + Active Directory application. + minLength: 1 + type: string + required: + - clientId + - tenantId + type: object type: object basicAuth: description: |- @@ -8999,6 +9041,11 @@ spec: Default: "30s" pattern: ^(0|(([0-9]+)y)?(([0-9]+)w)?(([0-9]+)d)?(([0-9]+)h)?(([0-9]+)m)?(([0-9]+)s)?(([0-9]+)ms)?)$ type: string + scrapeNativeHistograms: + description: |- + scrapeNativeHistograms defines whether to enable scraping of native histograms. + It requires Prometheus >= v3.8.0. + type: boolean scrapeProtocols: description: |- scrapeProtocols defines the protocols to negotiate during a scrape. It tells clients the @@ -10962,16 +11009,19 @@ spec: properties: clientType: description: clientType defines the client used to export the - traces. Supported values are `http` or `grpc`. + traces. Supported values are `HTTP` and `GRPC`. enum: - http - grpc + - HTTP + - GRPC type: string compression: description: compression key for supported compression types. - The only supported value is `gzip`. + The only supported value is `Gzip`. enum: - gzip + - Gzip type: string endpoint: description: endpoint to send the traces to. Should be provided @@ -11203,6 +11253,48 @@ spec: pattern: ^(0|(([0-9]+)y)?(([0-9]+)w)?(([0-9]+)d)?(([0-9]+)h)?(([0-9]+)m)?(([0-9]+)s)?(([0-9]+)ms)?)$ type: string type: object + updateStrategy: + description: |- + updateStrategy indicates the strategy that will be employed to update + Pods in the StatefulSet when a revision is made to statefulset's Pod + Template. + + The default strategy is RollingUpdate. + properties: + rollingUpdate: + description: rollingUpdate is used to communicate parameters when + type is RollingUpdate. + properties: + maxUnavailable: + anyOf: + - type: integer + - type: string + description: |- + maxUnavailable is the maximum number of pods that can be unavailable + during the update. The value can be an absolute number (ex: 5) or a + percentage of desired pods (ex: 10%). Absolute number is calculated from + percentage by rounding up. This can not be 0. Defaults to 1. This field + is alpha-level and is only honored by servers that enable the + MaxUnavailableStatefulSet feature. The field applies to all pods in the + range 0 to Replicas-1. That means if there is any unavailable pod in + the range 0 to Replicas-1, it will be counted towards MaxUnavailable. + x-kubernetes-int-or-string: true + type: object + type: + description: |- + type indicates the type of the StatefulSetUpdateStrategy. + + Default is RollingUpdate. + enum: + - OnDelete + - RollingUpdate + type: string + required: + - type + type: object + x-kubernetes-validations: + - message: rollingUpdate requires type to be RollingUpdate + rule: '!(self.type != ''RollingUpdate'' && has(self.rollingUpdate))' version: description: |- version of Prometheus being deployed. The operator uses this information diff --git a/example/prometheus-operator-crd-full/monitoring.coreos.com_scrapeconfigs.yaml b/example/prometheus-operator-crd-full/monitoring.coreos.com_scrapeconfigs.yaml index b5a4e9dda9a..768553cfcd5 100644 --- a/example/prometheus-operator-crd-full/monitoring.coreos.com_scrapeconfigs.yaml +++ b/example/prometheus-operator-crd-full/monitoring.coreos.com_scrapeconfigs.yaml @@ -12536,6 +12536,11 @@ spec: scrapes. pattern: ^(0|(([0-9]+)y)?(([0-9]+)w)?(([0-9]+)d)?(([0-9]+)h)?(([0-9]+)m)?(([0-9]+)s)?(([0-9]+)ms)?)$ type: string + scrapeNativeHistograms: + description: |- + scrapeNativeHistograms defines whether to enable scraping of native histograms. + It requires Prometheus >= v3.8.0. + type: boolean scrapeProtocols: description: |- scrapeProtocols defines the protocols to negotiate during a scrape. It tells clients the diff --git a/example/prometheus-operator-crd-full/monitoring.coreos.com_servicemonitors.yaml b/example/prometheus-operator-crd-full/monitoring.coreos.com_servicemonitors.yaml index 81ddef4af18..666860894dd 100644 --- a/example/prometheus-operator-crd-full/monitoring.coreos.com_servicemonitors.yaml +++ b/example/prometheus-operator-crd-full/monitoring.coreos.com_servicemonitors.yaml @@ -94,10 +94,10 @@ spec: properties: authorization: description: |- - authorization configures the Authorization header credentials to use when - scraping the target. + authorization configures the Authorization header credentials used by + the client. - Cannot be set at the same time as `basicAuth`, or `oauth2`. + Cannot be set at the same time as `basicAuth`, `bearerTokenSecret` or `oauth2`. properties: credentials: description: credentials defines a key of a Secret in the @@ -135,10 +135,10 @@ spec: type: object basicAuth: description: |- - basicAuth defines the Basic Authentication credentials to use when - scraping the target. + basicAuth defines the Basic Authentication credentials used by the + client. - Cannot be set at the same time as `authorization`, or `oauth2`. + Cannot be set at the same time as `authorization`, `bearerTokenSecret` or `oauth2`. properties: password: description: |- @@ -201,9 +201,12 @@ spec: type: string bearerTokenSecret: description: |- - bearerTokenSecret defines a key of a Secret containing the bearer - token for scraping targets. The secret needs to be in the same namespace - as the ServiceMonitor object and readable by the Prometheus Operator. + bearerTokenSecret defines a key of a Secret containing the bearer token + used by the client for authentication. The secret needs to be in the + same namespace as the custom resource and readable by the Prometheus + Operator. + + Cannot be set at the same time as `authorization`, `basicAuth` or `oauth2`. Deprecated: use `authorization` instead. properties: @@ -229,8 +232,7 @@ spec: type: object x-kubernetes-map-type: atomic enableHttp2: - description: enableHttp2 can be used to disable HTTP2 when scraping - the target. + description: enableHttp2 can be used to disable HTTP2. type: boolean filterRunning: description: |- @@ -243,8 +245,8 @@ spec: type: boolean followRedirects: description: |- - followRedirects defines whether the scrape requests should follow HTTP - 3xx redirects. + followRedirects defines whether the client should follow HTTP 3xx + redirects. type: boolean honorLabels: description: |- @@ -362,11 +364,11 @@ spec: type: string oauth2: description: |- - oauth2 defines the OAuth2 settings to use when scraping the target. + oauth2 defines the OAuth2 settings used by the client. It requires Prometheus >= 2.27.0. - Cannot be set at the same time as `authorization`, or `basicAuth`. + Cannot be set at the same time as `authorization`, `basicAuth` or `bearerTokenSecret`. properties: clientId: description: |- @@ -878,8 +880,8 @@ spec: Service. The port must be specified with the container's port property. x-kubernetes-int-or-string: true tlsConfig: - description: tlsConfig defines the TLS configuration to use - when scraping the target. + description: tlsConfig defines TLS configuration used by the + client. properties: ca: description: ca defines the Certificate authority used when @@ -1179,6 +1181,11 @@ spec: Notice: `scrapeClassicHistograms` corresponds to the `always_scrape_classic_histograms` field in the Prometheus configuration. type: boolean + scrapeNativeHistograms: + description: |- + scrapeNativeHistograms defines whether to enable scraping of native histograms. + It requires Prometheus >= v3.8.0. + type: boolean scrapeProtocols: description: |- scrapeProtocols defines the protocols to negotiate during a scrape. It tells clients the diff --git a/example/prometheus-operator-crd-full/monitoring.coreos.com_thanosrulers.yaml b/example/prometheus-operator-crd-full/monitoring.coreos.com_thanosrulers.yaml index cc3a4b196a7..5dafe29fb0b 100644 --- a/example/prometheus-operator-crd-full/monitoring.coreos.com_thanosrulers.yaml +++ b/example/prometheus-operator-crd-full/monitoring.coreos.com_thanosrulers.yaml @@ -4643,6 +4643,21 @@ spec: paused defines when a ThanosRuler deployment is paused, no actions except for deletion will be performed on the underlying objects. type: boolean + podManagementPolicy: + description: |- + podManagementPolicy defines the policy for creating/deleting pods when + scaling up and down. + + Unlike the default StatefulSet behavior, the default policy is + `Parallel` to avoid manual intervention in case a pod gets stuck during + a rollout. + + Note that updating this value implies the recreation of the StatefulSet + which incurs a service outage. + enum: + - OrderedReady + - Parallel + type: string podMetadata: description: |- podMetadata defines labels and annotations which are propagated to the ThanosRuler pods. @@ -4836,7 +4851,7 @@ spec: managedIdentity: description: |- managedIdentity defines the Azure User-assigned Managed identity. - Cannot be set at the same time as `oauth` or `sdk`. + Cannot be set at the same time as `oauth`, `sdk` or `workloadIdentity`. properties: clientId: description: |- @@ -4849,7 +4864,7 @@ spec: oauth: description: |- oauth defines the oauth config that is being used to authenticate. - Cannot be set at the same time as `managedIdentity` or `sdk`. + Cannot be set at the same time as `managedIdentity`, `sdk` or `workloadIdentity`. It requires Prometheus >= v2.48.0 or Thanos >= v0.31.0. properties: @@ -4897,11 +4912,17 @@ spec: - clientSecret - tenantId type: object + scope: + description: |- + scope is the custom OAuth 2.0 scope to request when acquiring tokens. + It requires Prometheus >= 3.9.0. Currently not supported by Thanos. + pattern: ^[\w\s:/.\\-]+$ + type: string sdk: description: |- sdk defines the Azure SDK config that is being used to authenticate. See https://learn.microsoft.com/en-us/azure/developer/go/azure-sdk-authentication - Cannot be set at the same time as `oauth` or `managedIdentity`. + Cannot be set at the same time as `oauth`, `managedIdentity` or `workloadIdentity`. It requires Prometheus >= v2.52.0 or Thanos >= v0.36.0. properties: @@ -4912,6 +4933,27 @@ spec: pattern: ^[0-9a-zA-Z-.]+$ type: string type: object + workloadIdentity: + description: |- + workloadIdentity defines the Azure Workload Identity authentication. + Cannot be set at the same time as `oauth`, `managedIdentity`, or `sdk`. + + It requires Prometheus >= 3.7.0. Currently not supported by Thanos. + properties: + clientId: + description: clientId is the clientID of the Azure Active + Directory application. + minLength: 1 + type: string + tenantId: + description: tenantId is the tenant ID of the Azure + Active Directory application. + minLength: 1 + type: string + required: + - clientId + - tenantId + type: object type: object basicAuth: description: |- @@ -7318,6 +7360,48 @@ spec: This field takes precedence over `tracingConfig`. type: string + updateStrategy: + description: |- + updateStrategy indicates the strategy that will be employed to update + Pods in the StatefulSet when a revision is made to statefulset's Pod + Template. + + The default strategy is RollingUpdate. + properties: + rollingUpdate: + description: rollingUpdate is used to communicate parameters when + type is RollingUpdate. + properties: + maxUnavailable: + anyOf: + - type: integer + - type: string + description: |- + maxUnavailable is the maximum number of pods that can be unavailable + during the update. The value can be an absolute number (ex: 5) or a + percentage of desired pods (ex: 10%). Absolute number is calculated from + percentage by rounding up. This can not be 0. Defaults to 1. This field + is alpha-level and is only honored by servers that enable the + MaxUnavailableStatefulSet feature. The field applies to all pods in the + range 0 to Replicas-1. That means if there is any unavailable pod in + the range 0 to Replicas-1, it will be counted towards MaxUnavailable. + x-kubernetes-int-or-string: true + type: object + type: + description: |- + type indicates the type of the StatefulSetUpdateStrategy. + + Default is RollingUpdate. + enum: + - OnDelete + - RollingUpdate + type: string + required: + - type + type: object + x-kubernetes-validations: + - message: rollingUpdate requires type to be RollingUpdate + rule: '!(self.type != ''RollingUpdate'' && has(self.rollingUpdate))' version: description: version of Thanos to be deployed. type: string diff --git a/example/prometheus-operator-crd/monitoring.coreos.com_alertmanagerconfigs.yaml b/example/prometheus-operator-crd/monitoring.coreos.com_alertmanagerconfigs.yaml index ae40977b30d..ccb35e23f10 100644 --- a/example/prometheus-operator-crd/monitoring.coreos.com_alertmanagerconfigs.yaml +++ b/example/prometheus-operator-crd/monitoring.coreos.com_alertmanagerconfigs.yaml @@ -4,7 +4,7 @@ kind: CustomResourceDefinition metadata: annotations: controller-gen.kubebuilder.io/version: v0.19.0 - operator.prometheus.io/version: 0.87.1 + operator.prometheus.io/version: 0.88.0 name: alertmanagerconfigs.monitoring.coreos.com spec: group: monitoring.coreos.com @@ -63,6 +63,7 @@ spec: items: type: string type: array + x-kubernetes-list-type: atomic sourceMatch: description: |- sourceMatch defines matchers for which one or more alerts have to exist for the inhibition @@ -102,6 +103,7 @@ spec: - name type: object type: array + x-kubernetes-list-type: atomic targetMatch: description: |- targetMatch defines matchers that have to be fulfilled in the alerts to be muted. @@ -141,8 +143,10 @@ spec: - name type: object type: array + x-kubernetes-list-type: atomic type: object type: array + x-kubernetes-list-type: atomic muteTimeIntervals: description: muteTimeIntervals defines the list of MuteTimeInterval specifying when the routes should be muted. @@ -176,6 +180,7 @@ spec: type: integer type: object type: array + x-kubernetes-list-type: atomic months: description: months defines a list of MonthRange items: @@ -185,6 +190,7 @@ spec: pattern: ^((?i)january|february|march|april|may|june|july|august|september|october|november|december|1[0-2]|[1-9])(?:((:((?i)january|february|march|april|may|june|july|august|september|october|november|december|1[0-2]|[1-9]))$)|$) type: string type: array + x-kubernetes-list-type: atomic times: description: times defines a list of TimeRange items: @@ -203,6 +209,7 @@ spec: type: string type: object type: array + x-kubernetes-list-type: atomic weekdays: description: weekdays defines a list of WeekdayRange items: @@ -212,6 +219,7 @@ spec: pattern: ^((?i)sun|mon|tues|wednes|thurs|fri|satur)day(?:((:(sun|mon|tues|wednes|thurs|fri|satur)day)$)|$) type: string type: array + x-kubernetes-list-type: atomic years: description: years defines a list of YearRange items: @@ -219,12 +227,15 @@ spec: pattern: ^2\d{3}(?::2\d{3}|$) type: string type: array + x-kubernetes-list-type: atomic type: object type: array + x-kubernetes-list-type: atomic required: - name type: object type: array + x-kubernetes-list-type: atomic receivers: description: receivers defines the list of receivers. items: @@ -1000,6 +1011,7 @@ spec: - apiURL type: object type: array + x-kubernetes-list-type: atomic emailConfigs: description: emailConfigs defines the list of Email configurations. items: @@ -1098,6 +1110,7 @@ spec: - value type: object type: array + x-kubernetes-list-type: atomic hello: description: |- hello defines the hostname to identify to the SMTP server. @@ -1303,6 +1316,7 @@ spec: type: string type: object type: array + x-kubernetes-list-type: atomic msteamsConfigs: description: |- msteamsConfigs defines the list of MSTeams configurations. @@ -2068,6 +2082,7 @@ spec: - webhookUrl type: object type: array + x-kubernetes-list-type: atomic msteamsv2Configs: description: |- msteamsv2Configs defines the list of MSTeamsV2 configurations. @@ -2828,6 +2843,7 @@ spec: x-kubernetes-map-type: atomic type: object type: array + x-kubernetes-list-type: atomic name: description: name defines the name of the receiver. Must be unique across all items from the list. @@ -2876,6 +2892,7 @@ spec: description: |- apiURL defines the URL to send OpsGenie API requests to. When not specified, defaults to the standard OpsGenie API endpoint. + pattern: ^https?://.+$ type: string description: description: |- @@ -2905,6 +2922,7 @@ spec: - value type: object type: array + x-kubernetes-list-type: atomic entity: description: |- entity defines an optional field that can be used to specify which domain alert is related to. @@ -3672,6 +3690,7 @@ spec: - type type: object type: array + x-kubernetes-list-type: atomic sendResolved: description: sendResolved defines whether or not to notify about resolved alerts. @@ -3693,6 +3712,7 @@ spec: type: boolean type: object type: array + x-kubernetes-list-type: atomic pagerdutyConfigs: description: pagerdutyConfigs defines the List of PagerDuty configurations. @@ -3703,20 +3723,25 @@ spec: properties: class: description: class defines the class/type of the event. + minLength: 1 type: string client: description: client defines the client identification. + minLength: 1 type: string clientURL: description: clientURL defines the backlink to the sender of notification. + pattern: ^https?://.+$ type: string component: description: component defines the part or component of the affected system that is broken. + minLength: 1 type: string description: description: description of the incident. + minLength: 1 type: string details: description: details defines the arbitrary key/value pairs @@ -3740,8 +3765,10 @@ spec: - value type: object type: array + x-kubernetes-list-type: atomic group: description: group defines a cluster or grouping of sources. + minLength: 1 type: string httpConfig: description: httpConfig defines the HTTP client configuration. @@ -4459,17 +4486,21 @@ spec: alt: description: alt is the optional alternative text for the image. + minLength: 1 type: string href: description: href defines the optional URL; makes the image a clickable link. + pattern: ^https?://.+$ type: string src: description: src of the image being attached to the incident + minLength: 1 type: string type: object type: array + x-kubernetes-list-type: atomic pagerDutyLinkConfigs: description: pagerDutyLinkConfigs defines a list of link details to attach that provide further detail about @@ -4482,13 +4513,16 @@ spec: description: alt defines the text that describes the purpose of the link, and can be used as the link's text. + minLength: 1 type: string href: description: href defines the URL of the link to be attached + pattern: ^https?://.+$ type: string type: object type: array + x-kubernetes-list-type: atomic routingKey: description: |- routingKey defines the secret's key that contains the PagerDuty integration key (when using @@ -4552,16 +4586,26 @@ spec: x-kubernetes-map-type: atomic severity: description: severity of the incident. + minLength: 1 type: string source: description: source defines the unique location of the affected system. + minLength: 1 + type: string + timeout: + description: |- + timeout is the maximum time allowed to invoke the pagerduty + It requires Alertmanager >= v0.30.0. + pattern: ^(0|(([0-9]+)y)?(([0-9]+)w)?(([0-9]+)d)?(([0-9]+)h)?(([0-9]+)m)?(([0-9]+)s)?(([0-9]+)ms)?)$ type: string url: description: url defines the URL to send requests to. + pattern: ^https?://.+$ type: string type: object type: array + x-kubernetes-list-type: atomic pushoverConfigs: description: pushoverConfigs defines the list of Pushover configurations. items: @@ -4573,6 +4617,7 @@ spec: description: |- device defines the name of a specific device to send the notification to. If not specified, the notification is sent to all user's devices. + minLength: 1 type: string expire: description: |- @@ -4584,6 +4629,7 @@ spec: description: |- html defines whether notification message is HTML or plain text. When true, the message can include HTML formatting tags. + html and monospace formatting are mutually exclusive. type: boolean httpConfig: description: httpConfig defines the HTTP client configuration @@ -5295,6 +5341,7 @@ spec: description: |- message defines the notification message content. This is the main body text of the Pushover notification. + minLength: 1 type: string monospace: description: |- @@ -5305,6 +5352,7 @@ spec: description: |- priority defines the notification priority level. See https://pushover.net/api#priority for valid values and behavior. + minLength: 1 type: string retry: description: |- @@ -5320,11 +5368,13 @@ spec: description: |- sound defines the name of one of the sounds supported by device clients. This overrides the user's default sound choice for this notification. + minLength: 1 type: string title: description: |- title defines the notification title displayed in the Pushover message. This appears as the bold header text in the notification. + minLength: 1 type: string token: description: |- @@ -5361,6 +5411,7 @@ spec: See https://pushover.net/apps for application registration. Either `token` or `tokenFile` is required. It requires Alertmanager >= v0.26.0. + minLength: 1 type: string ttl: description: |- @@ -5372,11 +5423,13 @@ spec: description: |- url defines a supplementary URL shown alongside the message. This creates a clickable link within the Pushover notification. + pattern: ^https?://.+$ type: string urlTitle: description: |- urlTitle defines a title for the supplementary URL. If not specified, the raw URL is shown instead. + minLength: 1 type: string userKey: description: |- @@ -5411,9 +5464,11 @@ spec: userKeyFile defines the user key file that contains the recipient user's user key. Either `userKey` or `userKeyFile` is required. It requires Alertmanager >= v0.26.0. + minLength: 1 type: string type: object type: array + x-kubernetes-list-type: atomic rocketchatConfigs: description: |- rocketchatConfigs defines the list of RocketChat configurations. @@ -5452,6 +5507,7 @@ spec: type: object minItems: 1 type: array + x-kubernetes-list-type: atomic apiURL: description: |- apiURL defines the API URL for RocketChat. @@ -5504,6 +5560,7 @@ spec: type: object minItems: 1 type: array + x-kubernetes-list-type: atomic httpConfig: description: httpConfig defines the HTTP client configuration for RocketChat API requests. @@ -6317,6 +6374,7 @@ spec: - tokenID type: object type: array + x-kubernetes-list-type: atomic slackConfigs: description: slackConfigs defines the list of Slack configurations. items: @@ -6343,11 +6401,13 @@ spec: description: |- dismissText defines the label for the cancel button in the dialog. When not specified, defaults to "Cancel". This button cancels the action. + minLength: 1 type: string okText: description: |- okText defines the label for the confirmation button in the dialog. When not specified, defaults to "Okay". This button proceeds with the action. + minLength: 1 type: string text: description: |- @@ -6359,6 +6419,7 @@ spec: description: |- title defines the title text displayed at the top of the confirmation dialog. When not specified, a default title will be used. + minLength: 1 type: string required: - text @@ -6367,11 +6428,13 @@ spec: description: |- name defines a unique identifier for the action within the message. This value is sent back to your application when the action is triggered. + minLength: 1 type: string style: description: |- style defines the visual appearance of the action element. Valid values include "default", "primary" (green), and "danger" (red). + minLength: 1 type: string text: description: |- @@ -6389,17 +6452,21 @@ spec: description: |- url defines the URL to open when the action is triggered. Only applicable for button-type actions. When set, clicking the button opens this URL. + pattern: ^https?://.+$ type: string value: description: |- value defines the payload sent when the action is triggered. This data is included in the callback sent to your application. + minLength: 1 type: string required: - text - type type: object + minItems: 1 type: array + x-kubernetes-list-type: atomic apiURL: description: |- apiURL defines the secret's key that contains the Slack webhook URL. @@ -6430,19 +6497,23 @@ spec: callbackId: description: callbackId defines an identifier for the message used in interactive components. + minLength: 1 type: string channel: description: channel defines the channel or user to send notifications to. + minLength: 1 type: string color: description: |- color defines the color of the left border of the Slack message attachment. Can be a hex color code (e.g., "#ff0000") or a predefined color name. + minLength: 1 type: string fallback: description: fallback defines a plain-text summary of the attachment for clients that don't support attachments. + minLength: 1 type: string fields: description: fields defines a list of Slack fields that @@ -6476,10 +6547,13 @@ spec: - title - value type: object + minItems: 1 type: array + x-kubernetes-list-type: atomic footer: description: footer defines small text displayed at the bottom of the message attachment. + minLength: 1 type: string httpConfig: description: httpConfig defines the HTTP client configuration. @@ -7189,14 +7263,17 @@ spec: iconEmoji: description: iconEmoji defines the emoji to use as the bot's avatar (e.g., ":ghost:"). + minLength: 1 type: string iconURL: description: iconURL defines the URL to an image to use as the bot's avatar. + pattern: ^https?://.+$ type: string imageURL: description: imageURL defines the URL to an image file that will be displayed inside the message attachment. + pattern: ^https?://.+$ type: string linkNames: description: |- @@ -7208,11 +7285,15 @@ spec: mrkdwnIn defines which fields should be parsed as Slack markdown. Valid values include "pretext", "text", and "fields". items: + minLength: 1 type: string + minItems: 1 type: array + x-kubernetes-list-type: atomic pretext: description: pretext defines optional text that appears above the message attachment block. + minLength: 1 type: string sendResolved: description: sendResolved defines whether or not to notify @@ -7226,25 +7307,38 @@ spec: text: description: text defines the main text content of the Slack message attachment. + minLength: 1 type: string thumbURL: description: |- thumbURL defines the URL to an image file that will be displayed as a thumbnail on the right side of the message attachment. + pattern: ^https?://.+$ + type: string + timeout: + description: |- + timeout defines the maximum time to wait for a webhook request to complete, + before failing the request and allowing it to be retried. + It requires Alertmanager >= v0.30.0. + pattern: ^(0|(([0-9]+)y)?(([0-9]+)w)?(([0-9]+)d)?(([0-9]+)h)?(([0-9]+)m)?(([0-9]+)s)?(([0-9]+)ms)?)$ type: string title: description: title defines the title text displayed in the Slack message attachment. + minLength: 1 type: string titleLink: description: titleLink defines the URL that the title will link to when clicked. + pattern: ^https?://.+$ type: string username: description: username defines the slack bot user name. + minLength: 1 type: string type: object type: array + x-kubernetes-list-type: atomic snsConfigs: description: snsConfigs defines the list of SNS configurations items: @@ -8076,6 +8170,7 @@ spec: type: string type: object type: array + x-kubernetes-list-type: atomic telegramConfigs: description: telegramConfigs defines the list of Telegram configurations. items: @@ -8087,6 +8182,7 @@ spec: description: |- apiURL defines the Telegram API URL, e.g. https://api.telegram.org. If not specified, the default Telegram API URL will be used. + pattern: ^https?://.+$ type: string botToken: description: |- @@ -8870,6 +8966,7 @@ spec: - chatID type: object type: array + x-kubernetes-list-type: atomic victoropsConfigs: description: victoropsConfigs defines the list of VictorOps configurations. @@ -8909,6 +9006,7 @@ spec: description: |- apiUrl defines the VictorOps API URL. When not specified, defaults to the standard VictorOps API endpoint. + pattern: ^https?://.+$ type: string customFields: description: |- @@ -8933,10 +9031,12 @@ spec: - value type: object type: array + x-kubernetes-list-type: atomic entityDisplayName: description: |- entityDisplayName contains a summary of the alerted problem. This appears as the main title or identifier for the incident. + minLength: 1 type: string httpConfig: description: httpConfig defines the HTTP client's configuration @@ -9648,16 +9748,19 @@ spec: description: |- messageType describes the behavior of the alert. Valid values are "CRITICAL", "WARNING", and "INFO". + minLength: 1 type: string monitoringTool: description: |- monitoringTool defines the monitoring tool the state message is from. This helps identify the source system that generated the alert. + minLength: 1 type: string routingKey: description: |- routingKey defines a key used to map the alert to a team. This determines which VictorOps team will receive the alert notification. + minLength: 1 type: string sendResolved: description: sendResolved defines whether or not to notify @@ -9667,9 +9770,13 @@ spec: description: |- stateMessage contains a long explanation of the alerted problem. This provides detailed context about the incident. + minLength: 1 type: string + required: + - routingKey type: object type: array + x-kubernetes-list-type: atomic webexConfigs: description: webexConfigs defines the list of Webex configurations. items: @@ -10403,6 +10510,7 @@ spec: - roomID type: object type: array + x-kubernetes-list-type: atomic webhookConfigs: description: webhookConfigs defines the List of webhook configurations. items: @@ -11138,6 +11246,7 @@ spec: description: |- url defines the URL to send HTTP POST requests to. urlSecret takes precedence over url. One of urlSecret and url should be defined. + pattern: ^https?://.+$ type: string urlSecret: description: |- @@ -11169,6 +11278,7 @@ spec: x-kubernetes-map-type: atomic type: object type: array + x-kubernetes-list-type: atomic wechatConfigs: description: wechatConfigs defines the list of WeChat configurations. items: @@ -11212,6 +11322,7 @@ spec: description: |- apiURL defines the WeChat API URL. When not specified, defaults to the standard WeChat Work API endpoint. + pattern: ^https?://.+$ type: string corpID: description: |- @@ -11955,10 +12066,14 @@ spec: type: string type: object type: array + x-kubernetes-list-type: atomic required: - name type: object type: array + x-kubernetes-list-map-keys: + - name + x-kubernetes-list-type: map route: description: |- route defines the Alertmanager route definition for alerts matching the resource's @@ -11971,6 +12086,7 @@ spec: items: type: string type: array + x-kubernetes-list-type: set continue: description: |- continue defines the boolean indicating whether an alert should continue matching subsequent @@ -11985,6 +12101,7 @@ spec: items: type: string type: array + x-kubernetes-list-type: set groupInterval: description: |- groupInterval defines how long to wait before sending an updated notification. @@ -12037,12 +12154,14 @@ spec: - name type: object type: array + x-kubernetes-list-type: atomic muteTimeIntervals: description: muteTimeIntervals is a list of MuteTimeInterval names that will mute this route when matched, items: type: string type: array + x-kubernetes-list-type: set receiver: description: |- receiver defines the name of the receiver for this route. If not empty, it should be listed in @@ -12059,10 +12178,116 @@ spec: items: x-kubernetes-preserve-unknown-fields: true type: array + x-kubernetes-list-type: atomic type: object type: object + status: + description: |- + status defines the status subresource. It is under active development and is updated only when the + "StatusForConfigurationResources" feature gate is enabled. + + Most recent observed status of the ServiceMonitor. Read-only. + More info: + https://github.com/kubernetes/community/blob/master/contributors/devel/sig-architecture/api-conventions.md#spec-and-status + properties: + bindings: + description: bindings defines the list of workload resources (Prometheus, + PrometheusAgent, ThanosRuler or Alertmanager) which select the configuration + resource. + items: + description: WorkloadBinding is a link between a configuration resource + and a workload resource. + properties: + conditions: + description: conditions defines the current state of the configuration + resource when bound to the referenced Workload object. + items: + description: ConfigResourceCondition describes the status + of configuration resources linked to Prometheus, PrometheusAgent, + Alertmanager or ThanosRuler. + properties: + lastTransitionTime: + description: lastTransitionTime defines the time of the + last update to the current status property. + format: date-time + type: string + message: + description: message defines the human-readable message + indicating details for the condition's last transition. + type: string + observedGeneration: + description: |- + observedGeneration defines the .metadata.generation that the + condition was set based upon. For instance, if `.metadata.generation` is + currently 12, but the `.status.conditions[].observedGeneration` is 9, the + condition is out of date with respect to the current state of the object. + format: int64 + type: integer + reason: + description: reason for the condition's last transition. + type: string + status: + description: status of the condition. + minLength: 1 + type: string + type: + description: |- + type of the condition being reported. + Currently, only "Accepted" is supported. + enum: + - Accepted + minLength: 1 + type: string + required: + - lastTransitionTime + - status + - type + type: object + type: array + x-kubernetes-list-map-keys: + - type + x-kubernetes-list-type: map + group: + description: group defines the group of the referenced resource. + enum: + - monitoring.coreos.com + type: string + name: + description: name defines the name of the referenced object. + minLength: 1 + type: string + namespace: + description: namespace defines the namespace of the referenced + object. + minLength: 1 + type: string + resource: + description: resource defines the type of resource being referenced + (e.g. Prometheus, PrometheusAgent, ThanosRuler or Alertmanager). + enum: + - prometheuses + - prometheusagents + - thanosrulers + - alertmanagers + type: string + required: + - group + - name + - namespace + - resource + type: object + type: array + x-kubernetes-list-map-keys: + - group + - resource + - name + - namespace + x-kubernetes-list-type: map + type: object required: - spec type: object served: true storage: true + subresources: + status: {} diff --git a/example/prometheus-operator-crd/monitoring.coreos.com_alertmanagers.yaml b/example/prometheus-operator-crd/monitoring.coreos.com_alertmanagers.yaml index 799bd7eb203..a6b3a355a97 100644 --- a/example/prometheus-operator-crd/monitoring.coreos.com_alertmanagers.yaml +++ b/example/prometheus-operator-crd/monitoring.coreos.com_alertmanagers.yaml @@ -4,7 +4,7 @@ kind: CustomResourceDefinition metadata: annotations: controller-gen.kubebuilder.io/version: v0.19.0 - operator.prometheus.io/version: 0.87.1 + operator.prometheus.io/version: 0.88.0 name: alertmanagers.monitoring.coreos.com spec: group: monitoring.coreos.com @@ -2319,7 +2319,7 @@ spec: type: string type: object webex: - description: webex defines the default configuration for Jira. + description: webex defines the default configuration for Webex. properties: apiURL: description: |- @@ -6141,10 +6141,18 @@ spec: type: string minReadySeconds: description: |- - minReadySeconds defines the minimum number of seconds for which a newly created pod should be ready - without any of its container crashing for it to be considered available. + minReadySeconds defines the minimum number of seconds for which a newly + created pod should be ready without any of its container crashing for it + to be considered available. If unset, pods will be considered available as soon as they are ready. + + When the Alertmanager version is greater than or equal to v0.30.0, the + duration is also used to delay the first flush of the aggregation + groups. This delay helps ensuring that all alerts have been resent by + the Prometheus instances to Alertmanager after a roll-out. It is + possible to override this behavior passing a custom value via + `.spec.additionalArgs`. format: int32 minimum: 0 type: integer @@ -6182,6 +6190,21 @@ spec: the replica count to be deleted. type: string type: object + podManagementPolicy: + description: |- + podManagementPolicy defines the policy for creating/deleting pods when + scaling up and down. + + Unlike the default StatefulSet behavior, the default policy is + `Parallel` to avoid manual intervention in case a pod gets stuck during + a rollout. + + Note that updating this value implies the recreation of the StatefulSet + which incurs a service outage. + enum: + - OrderedReady + - Parallel + type: string podMetadata: description: |- podMetadata defines labels and annotations which are propagated to the Alertmanager pods. @@ -7521,6 +7544,48 @@ spec: - whenUnsatisfiable type: object type: array + updateStrategy: + description: |- + updateStrategy indicates the strategy that will be employed to update + Pods in the StatefulSet when a revision is made to statefulset's Pod + Template. + + The default strategy is RollingUpdate. + properties: + rollingUpdate: + description: rollingUpdate is used to communicate parameters when + type is RollingUpdate. + properties: + maxUnavailable: + anyOf: + - type: integer + - type: string + description: |- + maxUnavailable is the maximum number of pods that can be unavailable + during the update. The value can be an absolute number (ex: 5) or a + percentage of desired pods (ex: 10%). Absolute number is calculated from + percentage by rounding up. This can not be 0. Defaults to 1. This field + is alpha-level and is only honored by servers that enable the + MaxUnavailableStatefulSet feature. The field applies to all pods in the + range 0 to Replicas-1. That means if there is any unavailable pod in + the range 0 to Replicas-1, it will be counted towards MaxUnavailable. + x-kubernetes-int-or-string: true + type: object + type: + description: |- + type indicates the type of the StatefulSetUpdateStrategy. + + Default is RollingUpdate. + enum: + - OnDelete + - RollingUpdate + type: string + required: + - type + type: object + x-kubernetes-validations: + - message: rollingUpdate requires type to be RollingUpdate + rule: '!(self.type != ''RollingUpdate'' && has(self.rollingUpdate))' version: description: version the cluster should be on. type: string diff --git a/example/prometheus-operator-crd/monitoring.coreos.com_podmonitors.yaml b/example/prometheus-operator-crd/monitoring.coreos.com_podmonitors.yaml index a046c2d20b2..809cc597f26 100644 --- a/example/prometheus-operator-crd/monitoring.coreos.com_podmonitors.yaml +++ b/example/prometheus-operator-crd/monitoring.coreos.com_podmonitors.yaml @@ -4,7 +4,7 @@ kind: CustomResourceDefinition metadata: annotations: controller-gen.kubebuilder.io/version: v0.19.0 - operator.prometheus.io/version: 0.87.1 + operator.prometheus.io/version: 0.88.0 name: podmonitors.monitoring.coreos.com spec: group: monitoring.coreos.com @@ -1187,6 +1187,11 @@ spec: Notice: `scrapeClassicHistograms` corresponds to the `always_scrape_classic_histograms` field in the Prometheus configuration. type: boolean + scrapeNativeHistograms: + description: |- + scrapeNativeHistograms defines whether to enable scraping of native histograms. + It requires Prometheus >= v3.8.0. + type: boolean scrapeProtocols: description: |- scrapeProtocols defines the protocols to negotiate during a scrape. It tells clients the diff --git a/example/prometheus-operator-crd/monitoring.coreos.com_probes.yaml b/example/prometheus-operator-crd/monitoring.coreos.com_probes.yaml index 76cb66536b5..97fee23a0f8 100644 --- a/example/prometheus-operator-crd/monitoring.coreos.com_probes.yaml +++ b/example/prometheus-operator-crd/monitoring.coreos.com_probes.yaml @@ -4,7 +4,7 @@ kind: CustomResourceDefinition metadata: annotations: controller-gen.kubebuilder.io/version: v0.19.0 - operator.prometheus.io/version: 0.87.1 + operator.prometheus.io/version: 0.88.0 name: probes.monitoring.coreos.com spec: group: monitoring.coreos.com @@ -53,7 +53,11 @@ spec: for target discovery by Prometheus. properties: authorization: - description: authorization section for this endpoint + description: |- + authorization configures the Authorization header credentials used by + the client. + + Cannot be set at the same time as `basicAuth`, `bearerTokenSecret` or `oauth2`. properties: credentials: description: credentials defines a key of a Secret in the namespace @@ -91,8 +95,10 @@ spec: type: object basicAuth: description: |- - basicAuth allow an endpoint to authenticate over basic authentication. - More info: https://prometheus.io/docs/operating/configuration/#endpoint + basicAuth defines the Basic Authentication credentials used by the + client. + + Cannot be set at the same time as `authorization`, `bearerTokenSecret` or `oauth2`. properties: password: description: |- @@ -149,9 +155,14 @@ spec: type: object bearerTokenSecret: description: |- - bearerTokenSecret defines the secret to mount to read bearer token for scraping targets. The secret - needs to be in the same namespace as the probe and accessible by - the Prometheus Operator. + bearerTokenSecret defines a key of a Secret containing the bearer token + used by the client for authentication. The secret needs to be in the + same namespace as the custom resource and readable by the Prometheus + Operator. + + Cannot be set at the same time as `authorization`, `basicAuth` or `oauth2`. + + Deprecated: use `authorization` instead. properties: key: description: The key of the secret to select from. Must be a @@ -178,6 +189,9 @@ spec: convertClassicHistogramsToNHCB defines whether to convert all scraped classic histograms into a native histogram with custom buckets. It requires Prometheus >= v3.0.0. type: boolean + enableHttp2: + description: enableHttp2 can be used to disable HTTP2. + type: boolean fallbackScrapeProtocol: description: |- fallbackScrapeProtocol defines the protocol to use if a scrape returns blank, unparseable, or otherwise invalid Content-Type. @@ -190,6 +204,11 @@ spec: - PrometheusText0.0.4 - PrometheusText1.0.0 type: string + followRedirects: + description: |- + followRedirects defines whether the client should follow HTTP 3xx + redirects. + type: boolean interval: description: |- interval at which targets are probed using the configured prober. @@ -337,8 +356,12 @@ spec: pattern: ^(\+|-)?(([0-9]+(\.[0-9]*)?)|(\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\+|-)?(([0-9]+(\.[0-9]*)?)|(\.[0-9]+))))?$ x-kubernetes-int-or-string: true oauth2: - description: oauth2 for the URL. Only valid in Prometheus versions - 2.27.0 and newer. + description: |- + oauth2 defines the OAuth2 settings used by the client. + + It requires Prometheus >= 2.27.0. + + Cannot be set at the same time as `authorization`, `basicAuth` or `bearerTokenSecret`. properties: clientId: description: |- @@ -792,6 +815,11 @@ spec: Notice: `scrapeClassicHistograms` corresponds to the `always_scrape_classic_histograms` field in the Prometheus configuration. type: boolean + scrapeNativeHistograms: + description: |- + scrapeNativeHistograms defines whether to enable scraping of native histograms. + It requires Prometheus >= v3.8.0. + type: boolean scrapeProtocols: description: |- scrapeProtocols defines the protocols to negotiate during a scrape. It tells clients the @@ -1108,8 +1136,7 @@ spec: type: object type: object tlsConfig: - description: tlsConfig defines the TLS configuration to use when scraping - the endpoint. + description: tlsConfig defines the TLS configuration used by the client. properties: ca: description: ca defines the Certificate authority used when verifying diff --git a/example/prometheus-operator-crd/monitoring.coreos.com_prometheusagents.yaml b/example/prometheus-operator-crd/monitoring.coreos.com_prometheusagents.yaml index 46004468705..822c2b3fd16 100644 --- a/example/prometheus-operator-crd/monitoring.coreos.com_prometheusagents.yaml +++ b/example/prometheus-operator-crd/monitoring.coreos.com_prometheusagents.yaml @@ -4,7 +4,7 @@ kind: CustomResourceDefinition metadata: annotations: controller-gen.kubebuilder.io/version: v0.19.0 - operator.prometheus.io/version: 0.87.1 + operator.prometheus.io/version: 0.88.0 name: prometheusagents.monitoring.coreos.com spec: group: monitoring.coreos.com @@ -5136,6 +5136,21 @@ spec: the replica count to be deleted. type: string type: object + podManagementPolicy: + description: |- + podManagementPolicy defines the policy for creating/deleting pods when + scaling up and down. + + Unlike the default StatefulSet behavior, the default policy is + `Parallel` to avoid manual intervention in case a pod gets stuck during + a rollout. + + Note that updating this value implies the recreation of the StatefulSet + which incurs a service outage. + enum: + - OrderedReady + - Parallel + type: string podMetadata: description: |- podMetadata defines labels and annotations which are propagated to the Prometheus pods. @@ -5494,7 +5509,7 @@ spec: managedIdentity: description: |- managedIdentity defines the Azure User-assigned Managed identity. - Cannot be set at the same time as `oauth` or `sdk`. + Cannot be set at the same time as `oauth`, `sdk` or `workloadIdentity`. properties: clientId: description: |- @@ -5507,7 +5522,7 @@ spec: oauth: description: |- oauth defines the oauth config that is being used to authenticate. - Cannot be set at the same time as `managedIdentity` or `sdk`. + Cannot be set at the same time as `managedIdentity`, `sdk` or `workloadIdentity`. It requires Prometheus >= v2.48.0 or Thanos >= v0.31.0. properties: @@ -5555,11 +5570,17 @@ spec: - clientSecret - tenantId type: object + scope: + description: |- + scope is the custom OAuth 2.0 scope to request when acquiring tokens. + It requires Prometheus >= 3.9.0. Currently not supported by Thanos. + pattern: ^[\w\s:/.\\-]+$ + type: string sdk: description: |- sdk defines the Azure SDK config that is being used to authenticate. See https://learn.microsoft.com/en-us/azure/developer/go/azure-sdk-authentication - Cannot be set at the same time as `oauth` or `managedIdentity`. + Cannot be set at the same time as `oauth`, `managedIdentity` or `workloadIdentity`. It requires Prometheus >= v2.52.0 or Thanos >= v0.36.0. properties: @@ -5570,6 +5591,27 @@ spec: pattern: ^[0-9a-zA-Z-.]+$ type: string type: object + workloadIdentity: + description: |- + workloadIdentity defines the Azure Workload Identity authentication. + Cannot be set at the same time as `oauth`, `managedIdentity`, or `sdk`. + + It requires Prometheus >= 3.7.0. Currently not supported by Thanos. + properties: + clientId: + description: clientId is the clientID of the Azure Active + Directory application. + minLength: 1 + type: string + tenantId: + description: tenantId is the tenant ID of the Azure + Active Directory application. + minLength: 1 + type: string + required: + - clientId + - tenantId + type: object type: object basicAuth: description: |- @@ -7265,6 +7307,11 @@ spec: Default: "30s" pattern: ^(0|(([0-9]+)y)?(([0-9]+)w)?(([0-9]+)d)?(([0-9]+)h)?(([0-9]+)m)?(([0-9]+)s)?(([0-9]+)ms)?)$ type: string + scrapeNativeHistograms: + description: |- + scrapeNativeHistograms defines whether to enable scraping of native histograms. + It requires Prometheus >= v3.8.0. + type: boolean scrapeProtocols: description: |- scrapeProtocols defines the protocols to negotiate during a scrape. It tells clients the @@ -8666,16 +8713,19 @@ spec: properties: clientType: description: clientType defines the client used to export the - traces. Supported values are `http` or `grpc`. + traces. Supported values are `HTTP` and `GRPC`. enum: - http - grpc + - HTTP + - GRPC type: string compression: description: compression key for supported compression types. - The only supported value is `gzip`. + The only supported value is `Gzip`. enum: - gzip + - Gzip type: string endpoint: description: endpoint to send the traces to. Should be provided @@ -8907,6 +8957,48 @@ spec: pattern: ^(0|(([0-9]+)y)?(([0-9]+)w)?(([0-9]+)d)?(([0-9]+)h)?(([0-9]+)m)?(([0-9]+)s)?(([0-9]+)ms)?)$ type: string type: object + updateStrategy: + description: |- + updateStrategy indicates the strategy that will be employed to update + Pods in the StatefulSet when a revision is made to statefulset's Pod + Template. + + The default strategy is RollingUpdate. + properties: + rollingUpdate: + description: rollingUpdate is used to communicate parameters when + type is RollingUpdate. + properties: + maxUnavailable: + anyOf: + - type: integer + - type: string + description: |- + maxUnavailable is the maximum number of pods that can be unavailable + during the update. The value can be an absolute number (ex: 5) or a + percentage of desired pods (ex: 10%). Absolute number is calculated from + percentage by rounding up. This can not be 0. Defaults to 1. This field + is alpha-level and is only honored by servers that enable the + MaxUnavailableStatefulSet feature. The field applies to all pods in the + range 0 to Replicas-1. That means if there is any unavailable pod in + the range 0 to Replicas-1, it will be counted towards MaxUnavailable. + x-kubernetes-int-or-string: true + type: object + type: + description: |- + type indicates the type of the StatefulSetUpdateStrategy. + + Default is RollingUpdate. + enum: + - OnDelete + - RollingUpdate + type: string + required: + - type + type: object + x-kubernetes-validations: + - message: rollingUpdate requires type to be RollingUpdate + rule: '!(self.type != ''RollingUpdate'' && has(self.rollingUpdate))' version: description: |- version of Prometheus being deployed. The operator uses this information @@ -11177,6 +11269,17 @@ spec: rule: '!(has(self.mode) && self.mode == ''DaemonSet'' && has(self.scrapeConfigSelector))' - message: probeSelector cannot be set when mode is DaemonSet rule: '!(has(self.mode) && self.mode == ''DaemonSet'' && has(self.probeSelector))' + - message: scrapeConfigNamespaceSelector cannot be set when mode is DaemonSet + rule: '!(has(self.mode) && self.mode == ''DaemonSet'' && has(self.scrapeConfigNamespaceSelector))' + - message: probeNamespaceSelector cannot be set when mode is DaemonSet + rule: '!(has(self.mode) && self.mode == ''DaemonSet'' && has(self.probeNamespaceSelector))' + - message: serviceMonitorSelector cannot be set when mode is DaemonSet + rule: '!(has(self.mode) && self.mode == ''DaemonSet'' && has(self.serviceMonitorSelector))' + - message: serviceMonitorNamespaceSelector cannot be set when mode is + DaemonSet + rule: '!(has(self.mode) && self.mode == ''DaemonSet'' && has(self.serviceMonitorNamespaceSelector))' + - message: additionalScrapeConfigs cannot be set when mode is DaemonSet + rule: '!(has(self.mode) && self.mode == ''DaemonSet'' && has(self.additionalScrapeConfigs))' status: description: |- status defines the most recent observed status of the Prometheus cluster. Read-only. diff --git a/example/prometheus-operator-crd/monitoring.coreos.com_prometheuses.yaml b/example/prometheus-operator-crd/monitoring.coreos.com_prometheuses.yaml index aed4db1ad86..c1506098a39 100644 --- a/example/prometheus-operator-crd/monitoring.coreos.com_prometheuses.yaml +++ b/example/prometheus-operator-crd/monitoring.coreos.com_prometheuses.yaml @@ -4,7 +4,7 @@ kind: CustomResourceDefinition metadata: annotations: controller-gen.kubebuilder.io/version: v0.19.0 - operator.prometheus.io/version: 0.87.1 + operator.prometheus.io/version: 0.88.0 name: prometheuses.monitoring.coreos.com spec: group: monitoring.coreos.com @@ -5920,6 +5920,21 @@ spec: the replica count to be deleted. type: string type: object + podManagementPolicy: + description: |- + podManagementPolicy defines the policy for creating/deleting pods when + scaling up and down. + + Unlike the default StatefulSet behavior, the default policy is + `Parallel` to avoid manual intervention in case a pod gets stuck during + a rollout. + + Note that updating this value implies the recreation of the StatefulSet + which incurs a service outage. + enum: + - OrderedReady + - Parallel + type: string podMetadata: description: |- podMetadata defines labels and annotations which are propagated to the Prometheus pods. @@ -7084,7 +7099,7 @@ spec: managedIdentity: description: |- managedIdentity defines the Azure User-assigned Managed identity. - Cannot be set at the same time as `oauth` or `sdk`. + Cannot be set at the same time as `oauth`, `sdk` or `workloadIdentity`. properties: clientId: description: |- @@ -7097,7 +7112,7 @@ spec: oauth: description: |- oauth defines the oauth config that is being used to authenticate. - Cannot be set at the same time as `managedIdentity` or `sdk`. + Cannot be set at the same time as `managedIdentity`, `sdk` or `workloadIdentity`. It requires Prometheus >= v2.48.0 or Thanos >= v0.31.0. properties: @@ -7145,11 +7160,17 @@ spec: - clientSecret - tenantId type: object + scope: + description: |- + scope is the custom OAuth 2.0 scope to request when acquiring tokens. + It requires Prometheus >= 3.9.0. Currently not supported by Thanos. + pattern: ^[\w\s:/.\\-]+$ + type: string sdk: description: |- sdk defines the Azure SDK config that is being used to authenticate. See https://learn.microsoft.com/en-us/azure/developer/go/azure-sdk-authentication - Cannot be set at the same time as `oauth` or `managedIdentity`. + Cannot be set at the same time as `oauth`, `managedIdentity` or `workloadIdentity`. It requires Prometheus >= v2.52.0 or Thanos >= v0.36.0. properties: @@ -7160,6 +7181,27 @@ spec: pattern: ^[0-9a-zA-Z-.]+$ type: string type: object + workloadIdentity: + description: |- + workloadIdentity defines the Azure Workload Identity authentication. + Cannot be set at the same time as `oauth`, `managedIdentity`, or `sdk`. + + It requires Prometheus >= 3.7.0. Currently not supported by Thanos. + properties: + clientId: + description: clientId is the clientID of the Azure Active + Directory application. + minLength: 1 + type: string + tenantId: + description: tenantId is the tenant ID of the Azure + Active Directory application. + minLength: 1 + type: string + required: + - clientId + - tenantId + type: object type: object basicAuth: description: |- @@ -9000,6 +9042,11 @@ spec: Default: "30s" pattern: ^(0|(([0-9]+)y)?(([0-9]+)w)?(([0-9]+)d)?(([0-9]+)h)?(([0-9]+)m)?(([0-9]+)s)?(([0-9]+)ms)?)$ type: string + scrapeNativeHistograms: + description: |- + scrapeNativeHistograms defines whether to enable scraping of native histograms. + It requires Prometheus >= v3.8.0. + type: boolean scrapeProtocols: description: |- scrapeProtocols defines the protocols to negotiate during a scrape. It tells clients the @@ -10963,16 +11010,19 @@ spec: properties: clientType: description: clientType defines the client used to export the - traces. Supported values are `http` or `grpc`. + traces. Supported values are `HTTP` and `GRPC`. enum: - http - grpc + - HTTP + - GRPC type: string compression: description: compression key for supported compression types. - The only supported value is `gzip`. + The only supported value is `Gzip`. enum: - gzip + - Gzip type: string endpoint: description: endpoint to send the traces to. Should be provided @@ -11204,6 +11254,48 @@ spec: pattern: ^(0|(([0-9]+)y)?(([0-9]+)w)?(([0-9]+)d)?(([0-9]+)h)?(([0-9]+)m)?(([0-9]+)s)?(([0-9]+)ms)?)$ type: string type: object + updateStrategy: + description: |- + updateStrategy indicates the strategy that will be employed to update + Pods in the StatefulSet when a revision is made to statefulset's Pod + Template. + + The default strategy is RollingUpdate. + properties: + rollingUpdate: + description: rollingUpdate is used to communicate parameters when + type is RollingUpdate. + properties: + maxUnavailable: + anyOf: + - type: integer + - type: string + description: |- + maxUnavailable is the maximum number of pods that can be unavailable + during the update. The value can be an absolute number (ex: 5) or a + percentage of desired pods (ex: 10%). Absolute number is calculated from + percentage by rounding up. This can not be 0. Defaults to 1. This field + is alpha-level and is only honored by servers that enable the + MaxUnavailableStatefulSet feature. The field applies to all pods in the + range 0 to Replicas-1. That means if there is any unavailable pod in + the range 0 to Replicas-1, it will be counted towards MaxUnavailable. + x-kubernetes-int-or-string: true + type: object + type: + description: |- + type indicates the type of the StatefulSetUpdateStrategy. + + Default is RollingUpdate. + enum: + - OnDelete + - RollingUpdate + type: string + required: + - type + type: object + x-kubernetes-validations: + - message: rollingUpdate requires type to be RollingUpdate + rule: '!(self.type != ''RollingUpdate'' && has(self.rollingUpdate))' version: description: |- version of Prometheus being deployed. The operator uses this information diff --git a/example/prometheus-operator-crd/monitoring.coreos.com_prometheusrules.yaml b/example/prometheus-operator-crd/monitoring.coreos.com_prometheusrules.yaml index 8b53d6b618f..bc1805a07db 100644 --- a/example/prometheus-operator-crd/monitoring.coreos.com_prometheusrules.yaml +++ b/example/prometheus-operator-crd/monitoring.coreos.com_prometheusrules.yaml @@ -4,7 +4,7 @@ kind: CustomResourceDefinition metadata: annotations: controller-gen.kubebuilder.io/version: v0.19.0 - operator.prometheus.io/version: 0.87.1 + operator.prometheus.io/version: 0.88.0 name: prometheusrules.monitoring.coreos.com spec: group: monitoring.coreos.com diff --git a/example/prometheus-operator-crd/monitoring.coreos.com_scrapeconfigs.yaml b/example/prometheus-operator-crd/monitoring.coreos.com_scrapeconfigs.yaml index a9c6882cc9f..b509440b150 100644 --- a/example/prometheus-operator-crd/monitoring.coreos.com_scrapeconfigs.yaml +++ b/example/prometheus-operator-crd/monitoring.coreos.com_scrapeconfigs.yaml @@ -4,7 +4,7 @@ kind: CustomResourceDefinition metadata: annotations: controller-gen.kubebuilder.io/version: v0.19.0 - operator.prometheus.io/version: 0.87.1 + operator.prometheus.io/version: 0.88.0 name: scrapeconfigs.monitoring.coreos.com spec: group: monitoring.coreos.com @@ -12537,6 +12537,11 @@ spec: scrapes. pattern: ^(0|(([0-9]+)y)?(([0-9]+)w)?(([0-9]+)d)?(([0-9]+)h)?(([0-9]+)m)?(([0-9]+)s)?(([0-9]+)ms)?)$ type: string + scrapeNativeHistograms: + description: |- + scrapeNativeHistograms defines whether to enable scraping of native histograms. + It requires Prometheus >= v3.8.0. + type: boolean scrapeProtocols: description: |- scrapeProtocols defines the protocols to negotiate during a scrape. It tells clients the diff --git a/example/prometheus-operator-crd/monitoring.coreos.com_servicemonitors.yaml b/example/prometheus-operator-crd/monitoring.coreos.com_servicemonitors.yaml index 690e99efa68..3ee3b43678e 100644 --- a/example/prometheus-operator-crd/monitoring.coreos.com_servicemonitors.yaml +++ b/example/prometheus-operator-crd/monitoring.coreos.com_servicemonitors.yaml @@ -4,7 +4,7 @@ kind: CustomResourceDefinition metadata: annotations: controller-gen.kubebuilder.io/version: v0.19.0 - operator.prometheus.io/version: 0.87.1 + operator.prometheus.io/version: 0.88.0 name: servicemonitors.monitoring.coreos.com spec: group: monitoring.coreos.com @@ -95,10 +95,10 @@ spec: properties: authorization: description: |- - authorization configures the Authorization header credentials to use when - scraping the target. + authorization configures the Authorization header credentials used by + the client. - Cannot be set at the same time as `basicAuth`, or `oauth2`. + Cannot be set at the same time as `basicAuth`, `bearerTokenSecret` or `oauth2`. properties: credentials: description: credentials defines a key of a Secret in the @@ -136,10 +136,10 @@ spec: type: object basicAuth: description: |- - basicAuth defines the Basic Authentication credentials to use when - scraping the target. + basicAuth defines the Basic Authentication credentials used by the + client. - Cannot be set at the same time as `authorization`, or `oauth2`. + Cannot be set at the same time as `authorization`, `bearerTokenSecret` or `oauth2`. properties: password: description: |- @@ -202,9 +202,12 @@ spec: type: string bearerTokenSecret: description: |- - bearerTokenSecret defines a key of a Secret containing the bearer - token for scraping targets. The secret needs to be in the same namespace - as the ServiceMonitor object and readable by the Prometheus Operator. + bearerTokenSecret defines a key of a Secret containing the bearer token + used by the client for authentication. The secret needs to be in the + same namespace as the custom resource and readable by the Prometheus + Operator. + + Cannot be set at the same time as `authorization`, `basicAuth` or `oauth2`. Deprecated: use `authorization` instead. properties: @@ -230,8 +233,7 @@ spec: type: object x-kubernetes-map-type: atomic enableHttp2: - description: enableHttp2 can be used to disable HTTP2 when scraping - the target. + description: enableHttp2 can be used to disable HTTP2. type: boolean filterRunning: description: |- @@ -244,8 +246,8 @@ spec: type: boolean followRedirects: description: |- - followRedirects defines whether the scrape requests should follow HTTP - 3xx redirects. + followRedirects defines whether the client should follow HTTP 3xx + redirects. type: boolean honorLabels: description: |- @@ -363,11 +365,11 @@ spec: type: string oauth2: description: |- - oauth2 defines the OAuth2 settings to use when scraping the target. + oauth2 defines the OAuth2 settings used by the client. It requires Prometheus >= 2.27.0. - Cannot be set at the same time as `authorization`, or `basicAuth`. + Cannot be set at the same time as `authorization`, `basicAuth` or `bearerTokenSecret`. properties: clientId: description: |- @@ -879,8 +881,8 @@ spec: Service. The port must be specified with the container's port property. x-kubernetes-int-or-string: true tlsConfig: - description: tlsConfig defines the TLS configuration to use - when scraping the target. + description: tlsConfig defines TLS configuration used by the + client. properties: ca: description: ca defines the Certificate authority used when @@ -1180,6 +1182,11 @@ spec: Notice: `scrapeClassicHistograms` corresponds to the `always_scrape_classic_histograms` field in the Prometheus configuration. type: boolean + scrapeNativeHistograms: + description: |- + scrapeNativeHistograms defines whether to enable scraping of native histograms. + It requires Prometheus >= v3.8.0. + type: boolean scrapeProtocols: description: |- scrapeProtocols defines the protocols to negotiate during a scrape. It tells clients the diff --git a/example/prometheus-operator-crd/monitoring.coreos.com_thanosrulers.yaml b/example/prometheus-operator-crd/monitoring.coreos.com_thanosrulers.yaml index 697efae3197..a08410ed0c3 100644 --- a/example/prometheus-operator-crd/monitoring.coreos.com_thanosrulers.yaml +++ b/example/prometheus-operator-crd/monitoring.coreos.com_thanosrulers.yaml @@ -4,7 +4,7 @@ kind: CustomResourceDefinition metadata: annotations: controller-gen.kubebuilder.io/version: v0.19.0 - operator.prometheus.io/version: 0.87.1 + operator.prometheus.io/version: 0.88.0 name: thanosrulers.monitoring.coreos.com spec: group: monitoring.coreos.com @@ -4644,6 +4644,21 @@ spec: paused defines when a ThanosRuler deployment is paused, no actions except for deletion will be performed on the underlying objects. type: boolean + podManagementPolicy: + description: |- + podManagementPolicy defines the policy for creating/deleting pods when + scaling up and down. + + Unlike the default StatefulSet behavior, the default policy is + `Parallel` to avoid manual intervention in case a pod gets stuck during + a rollout. + + Note that updating this value implies the recreation of the StatefulSet + which incurs a service outage. + enum: + - OrderedReady + - Parallel + type: string podMetadata: description: |- podMetadata defines labels and annotations which are propagated to the ThanosRuler pods. @@ -4837,7 +4852,7 @@ spec: managedIdentity: description: |- managedIdentity defines the Azure User-assigned Managed identity. - Cannot be set at the same time as `oauth` or `sdk`. + Cannot be set at the same time as `oauth`, `sdk` or `workloadIdentity`. properties: clientId: description: |- @@ -4850,7 +4865,7 @@ spec: oauth: description: |- oauth defines the oauth config that is being used to authenticate. - Cannot be set at the same time as `managedIdentity` or `sdk`. + Cannot be set at the same time as `managedIdentity`, `sdk` or `workloadIdentity`. It requires Prometheus >= v2.48.0 or Thanos >= v0.31.0. properties: @@ -4898,11 +4913,17 @@ spec: - clientSecret - tenantId type: object + scope: + description: |- + scope is the custom OAuth 2.0 scope to request when acquiring tokens. + It requires Prometheus >= 3.9.0. Currently not supported by Thanos. + pattern: ^[\w\s:/.\\-]+$ + type: string sdk: description: |- sdk defines the Azure SDK config that is being used to authenticate. See https://learn.microsoft.com/en-us/azure/developer/go/azure-sdk-authentication - Cannot be set at the same time as `oauth` or `managedIdentity`. + Cannot be set at the same time as `oauth`, `managedIdentity` or `workloadIdentity`. It requires Prometheus >= v2.52.0 or Thanos >= v0.36.0. properties: @@ -4913,6 +4934,27 @@ spec: pattern: ^[0-9a-zA-Z-.]+$ type: string type: object + workloadIdentity: + description: |- + workloadIdentity defines the Azure Workload Identity authentication. + Cannot be set at the same time as `oauth`, `managedIdentity`, or `sdk`. + + It requires Prometheus >= 3.7.0. Currently not supported by Thanos. + properties: + clientId: + description: clientId is the clientID of the Azure Active + Directory application. + minLength: 1 + type: string + tenantId: + description: tenantId is the tenant ID of the Azure + Active Directory application. + minLength: 1 + type: string + required: + - clientId + - tenantId + type: object type: object basicAuth: description: |- @@ -7319,6 +7361,48 @@ spec: This field takes precedence over `tracingConfig`. type: string + updateStrategy: + description: |- + updateStrategy indicates the strategy that will be employed to update + Pods in the StatefulSet when a revision is made to statefulset's Pod + Template. + + The default strategy is RollingUpdate. + properties: + rollingUpdate: + description: rollingUpdate is used to communicate parameters when + type is RollingUpdate. + properties: + maxUnavailable: + anyOf: + - type: integer + - type: string + description: |- + maxUnavailable is the maximum number of pods that can be unavailable + during the update. The value can be an absolute number (ex: 5) or a + percentage of desired pods (ex: 10%). Absolute number is calculated from + percentage by rounding up. This can not be 0. Defaults to 1. This field + is alpha-level and is only honored by servers that enable the + MaxUnavailableStatefulSet feature. The field applies to all pods in the + range 0 to Replicas-1. That means if there is any unavailable pod in + the range 0 to Replicas-1, it will be counted towards MaxUnavailable. + x-kubernetes-int-or-string: true + type: object + type: + description: |- + type indicates the type of the StatefulSetUpdateStrategy. + + Default is RollingUpdate. + enum: + - OnDelete + - RollingUpdate + type: string + required: + - type + type: object + x-kubernetes-validations: + - message: rollingUpdate requires type to be RollingUpdate + rule: '!(self.type != ''RollingUpdate'' && has(self.rollingUpdate))' version: description: version of Thanos to be deployed. type: string diff --git a/example/rbac/prometheus-operator/prometheus-operator-cluster-role-binding.yaml b/example/rbac/prometheus-operator/prometheus-operator-cluster-role-binding.yaml index 99717c34ec4..0b8389f431f 100644 --- a/example/rbac/prometheus-operator/prometheus-operator-cluster-role-binding.yaml +++ b/example/rbac/prometheus-operator/prometheus-operator-cluster-role-binding.yaml @@ -4,7 +4,7 @@ metadata: labels: app.kubernetes.io/component: controller app.kubernetes.io/name: prometheus-operator - app.kubernetes.io/version: 0.87.1 + app.kubernetes.io/version: 0.88.0 name: prometheus-operator roleRef: apiGroup: rbac.authorization.k8s.io diff --git a/example/rbac/prometheus-operator/prometheus-operator-cluster-role.yaml b/example/rbac/prometheus-operator/prometheus-operator-cluster-role.yaml index 5586dda518e..345feaddacd 100644 --- a/example/rbac/prometheus-operator/prometheus-operator-cluster-role.yaml +++ b/example/rbac/prometheus-operator/prometheus-operator-cluster-role.yaml @@ -4,7 +4,7 @@ metadata: labels: app.kubernetes.io/component: controller app.kubernetes.io/name: prometheus-operator - app.kubernetes.io/version: 0.87.1 + app.kubernetes.io/version: 0.88.0 name: prometheus-operator rules: - apiGroups: diff --git a/example/rbac/prometheus-operator/prometheus-operator-deployment.yaml b/example/rbac/prometheus-operator/prometheus-operator-deployment.yaml index a0f81ec79a7..9ea5fb7770d 100644 --- a/example/rbac/prometheus-operator/prometheus-operator-deployment.yaml +++ b/example/rbac/prometheus-operator/prometheus-operator-deployment.yaml @@ -4,7 +4,7 @@ metadata: labels: app.kubernetes.io/component: controller app.kubernetes.io/name: prometheus-operator - app.kubernetes.io/version: 0.87.1 + app.kubernetes.io/version: 0.88.0 name: prometheus-operator namespace: default spec: @@ -20,19 +20,21 @@ spec: labels: app.kubernetes.io/component: controller app.kubernetes.io/name: prometheus-operator - app.kubernetes.io/version: 0.87.1 + app.kubernetes.io/version: 0.88.0 spec: automountServiceAccountToken: true containers: - args: - --kubelet-service=kube-system/kubelet - - --prometheus-config-reloader=quay.io/prometheus-operator/prometheus-config-reloader:v0.87.1 + - --prometheus-config-reloader=quay.io/prometheus-operator/prometheus-config-reloader:v0.88.0 + - --watch-referenced-objects-in-all-namespaces=true + - --disable-unmanaged-prometheus-configuration=true - --kubelet-endpoints=true - --kubelet-endpointslice=false env: - name: GOGC value: "30" - image: quay.io/prometheus-operator/prometheus-operator:v0.87.1 + image: quay.io/prometheus-operator/prometheus-operator:v0.88.0 name: prometheus-operator ports: - containerPort: 8080 diff --git a/example/rbac/prometheus-operator/prometheus-operator-service-account.yaml b/example/rbac/prometheus-operator/prometheus-operator-service-account.yaml index b7d6833cdaa..3ac5aec2307 100644 --- a/example/rbac/prometheus-operator/prometheus-operator-service-account.yaml +++ b/example/rbac/prometheus-operator/prometheus-operator-service-account.yaml @@ -5,6 +5,6 @@ metadata: labels: app.kubernetes.io/component: controller app.kubernetes.io/name: prometheus-operator - app.kubernetes.io/version: 0.87.1 + app.kubernetes.io/version: 0.88.0 name: prometheus-operator namespace: default diff --git a/example/rbac/prometheus-operator/prometheus-operator-service-monitor.yaml b/example/rbac/prometheus-operator/prometheus-operator-service-monitor.yaml index e20590755d6..39082dfdf18 100644 --- a/example/rbac/prometheus-operator/prometheus-operator-service-monitor.yaml +++ b/example/rbac/prometheus-operator/prometheus-operator-service-monitor.yaml @@ -4,7 +4,7 @@ metadata: labels: app.kubernetes.io/component: controller app.kubernetes.io/name: prometheus-operator - app.kubernetes.io/version: 0.87.1 + app.kubernetes.io/version: 0.88.0 name: prometheus-operator namespace: default spec: @@ -15,4 +15,4 @@ spec: matchLabels: app.kubernetes.io/component: controller app.kubernetes.io/name: prometheus-operator - app.kubernetes.io/version: 0.87.1 + app.kubernetes.io/version: 0.88.0 diff --git a/example/rbac/prometheus-operator/prometheus-operator-service.yaml b/example/rbac/prometheus-operator/prometheus-operator-service.yaml index eda2bd68125..e309359e8ff 100644 --- a/example/rbac/prometheus-operator/prometheus-operator-service.yaml +++ b/example/rbac/prometheus-operator/prometheus-operator-service.yaml @@ -4,7 +4,7 @@ metadata: labels: app.kubernetes.io/component: controller app.kubernetes.io/name: prometheus-operator - app.kubernetes.io/version: 0.87.1 + app.kubernetes.io/version: 0.88.0 name: prometheus-operator namespace: default spec: diff --git a/go.mod b/go.mod index cfac560f72a..d9608c3b2b4 100644 --- a/go.mod +++ b/go.mod @@ -1,8 +1,6 @@ module github.com/prometheus-operator/prometheus-operator -go 1.24.0 - -toolchain go1.24.3 +go 1.25.0 require ( github.com/KimMachineGun/automemlimit v0.7.5 @@ -21,27 +19,27 @@ require ( github.com/mitchellh/hashstructure v1.1.0 github.com/oklog/run v1.2.0 github.com/prometheus-community/prom-label-proxy v0.12.1 - github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring v0.87.1 - github.com/prometheus-operator/prometheus-operator/pkg/client v0.87.1 - github.com/prometheus/alertmanager v0.29.0 + github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring v0.88.0 + github.com/prometheus-operator/prometheus-operator/pkg/client v0.88.0 + github.com/prometheus/alertmanager v0.30.0 github.com/prometheus/client_golang v1.23.2 - github.com/prometheus/common v0.67.3 - github.com/prometheus/exporter-toolkit v0.15.0 + github.com/prometheus/common v0.67.5 + github.com/prometheus/exporter-toolkit v0.15.1 // Since we needed the change added in https://github.com/prometheus/prometheus/pull/16928 and it's not released yet. - github.com/prometheus/prometheus v0.307.3 + github.com/prometheus/prometheus v0.309.1 github.com/stretchr/testify v1.11.1 - github.com/thanos-io/thanos v0.39.2 + github.com/thanos-io/thanos v0.40.1 go.uber.org/automaxprocs v1.6.0 - golang.org/x/net v0.47.0 - golang.org/x/sync v0.18.0 - google.golang.org/protobuf v1.36.10 + golang.org/x/net v0.48.0 + golang.org/x/sync v0.19.0 + google.golang.org/protobuf v1.36.11 gopkg.in/yaml.v2 v2.4.0 - k8s.io/api v0.34.2 - k8s.io/apiextensions-apiserver v0.34.2 - k8s.io/apimachinery v0.34.2 - k8s.io/apiserver v0.34.2 - k8s.io/client-go v0.34.2 - k8s.io/component-base v0.34.2 + k8s.io/api v0.34.3 + k8s.io/apiextensions-apiserver v0.34.3 + k8s.io/apimachinery v0.34.3 + k8s.io/apiserver v0.34.3 + k8s.io/client-go v0.34.3 + k8s.io/component-base v0.34.3 k8s.io/klog/v2 v2.130.1 k8s.io/utils v0.0.0-20251002143259-bc988d571ff4 sigs.k8s.io/controller-runtime v0.22.4 @@ -49,34 +47,35 @@ require ( ) require ( - github.com/aws/aws-sdk-go-v2 v1.39.2 // indirect - github.com/aws/aws-sdk-go-v2/config v1.31.12 // indirect - github.com/aws/aws-sdk-go-v2/credentials v1.18.16 // indirect - github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.18.9 // indirect - github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.9 // indirect - github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.9 // indirect - github.com/aws/aws-sdk-go-v2/internal/ini v1.8.3 // indirect - github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.1 // indirect - github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.9 // indirect - github.com/aws/aws-sdk-go-v2/service/sso v1.29.6 // indirect - github.com/aws/aws-sdk-go-v2/service/ssooidc v1.35.1 // indirect - github.com/aws/aws-sdk-go-v2/service/sts v1.38.6 // indirect - github.com/aws/smithy-go v1.23.0 // indirect + github.com/aws/aws-sdk-go-v2 v1.41.0 // indirect + github.com/aws/aws-sdk-go-v2/config v1.32.6 // indirect + github.com/aws/aws-sdk-go-v2/credentials v1.19.6 // indirect + github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.18.16 // indirect + github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.16 // indirect + github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.16 // indirect + github.com/aws/aws-sdk-go-v2/internal/ini v1.8.4 // indirect + github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.4 // indirect + github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.16 // indirect + github.com/aws/aws-sdk-go-v2/service/signin v1.0.4 // indirect + github.com/aws/aws-sdk-go-v2/service/sso v1.30.8 // indirect + github.com/aws/aws-sdk-go-v2/service/ssooidc v1.35.12 // indirect + github.com/aws/aws-sdk-go-v2/service/sts v1.41.5 // indirect + github.com/aws/smithy-go v1.24.0 // indirect github.com/coreos/go-systemd/v22 v22.6.0 // indirect github.com/facette/natsort v0.0.0-20181210072756-2cd4dd1e2dcb // indirect github.com/fxamacker/cbor/v2 v2.9.0 // indirect - github.com/go-openapi/swag v0.25.1 // indirect - github.com/go-openapi/swag/cmdutils v0.25.1 // indirect - github.com/go-openapi/swag/conv v0.25.1 // indirect - github.com/go-openapi/swag/fileutils v0.25.1 // indirect - github.com/go-openapi/swag/jsonname v0.25.1 // indirect - github.com/go-openapi/swag/jsonutils v0.25.1 // indirect - github.com/go-openapi/swag/loading v0.25.1 // indirect - github.com/go-openapi/swag/mangling v0.25.1 // indirect - github.com/go-openapi/swag/netutils v0.25.1 // indirect - github.com/go-openapi/swag/stringutils v0.25.1 // indirect - github.com/go-openapi/swag/typeutils v0.25.1 // indirect - github.com/go-openapi/swag/yamlutils v0.25.1 // indirect + github.com/go-openapi/swag v0.25.4 // indirect + github.com/go-openapi/swag/cmdutils v0.25.4 // indirect + github.com/go-openapi/swag/conv v0.25.4 // indirect + github.com/go-openapi/swag/fileutils v0.25.4 // indirect + github.com/go-openapi/swag/jsonname v0.25.4 // indirect + github.com/go-openapi/swag/jsonutils v0.25.4 // indirect + github.com/go-openapi/swag/loading v0.25.4 // indirect + github.com/go-openapi/swag/mangling v0.25.4 // indirect + github.com/go-openapi/swag/netutils v0.25.4 // indirect + github.com/go-openapi/swag/stringutils v0.25.4 // indirect + github.com/go-openapi/swag/typeutils v0.25.4 // indirect + github.com/go-openapi/swag/yamlutils v0.25.4 // indirect github.com/go-viper/mapstructure/v2 v2.4.0 // indirect github.com/golang-jwt/jwt/v5 v5.3.0 // indirect github.com/google/gnostic-models v0.7.0 // indirect @@ -87,14 +86,12 @@ require ( github.com/mxk/go-flowrate v0.0.0-20140419014527-cca7078d478f // indirect github.com/pbnjay/memory v0.0.0-20210728143218-7b4eea64cf58 // indirect github.com/pkg/errors v0.9.1 // indirect - github.com/prometheus/sigv4 v0.2.1 // indirect + github.com/prometheus/sigv4 v0.3.0 // indirect github.com/x448/float16 v0.8.4 // indirect go.opentelemetry.io/auto/sdk v1.2.1 // indirect go.yaml.in/yaml/v2 v2.4.3 // indirect go.yaml.in/yaml/v3 v3.0.4 // indirect golang.org/x/exp v0.0.0-20251002181428-27f1f14c8bb9 // indirect - google.golang.org/genproto/googleapis/rpc v0.0.0-20251006185510-65f7160b3a87 // indirect - google.golang.org/grpc v1.76.0 // indirect gopkg.in/evanphx/json-patch.v4 v4.13.0 // indirect sigs.k8s.io/randfill v1.0.0 // indirect sigs.k8s.io/structured-merge-diff/v6 v6.3.0 // indirect @@ -111,15 +108,15 @@ require ( github.com/go-logfmt/logfmt v0.6.1 // indirect github.com/go-logr/logr v1.4.3 // indirect github.com/go-logr/stdr v1.2.2 // indirect - github.com/go-openapi/analysis v0.24.0 // indirect - github.com/go-openapi/errors v0.22.3 // indirect + github.com/go-openapi/analysis v0.24.1 // indirect + github.com/go-openapi/errors v0.22.4 // indirect github.com/go-openapi/jsonpointer v0.22.1 // indirect - github.com/go-openapi/jsonreference v0.21.2 // indirect - github.com/go-openapi/loads v0.23.1 // indirect - github.com/go-openapi/runtime v0.29.0 // indirect - github.com/go-openapi/spec v0.22.0 // indirect - github.com/go-openapi/strfmt v0.24.0 // indirect - github.com/go-openapi/validate v0.25.0 // indirect + github.com/go-openapi/jsonreference v0.21.3 // indirect + github.com/go-openapi/loads v0.23.2 // indirect + github.com/go-openapi/runtime v0.29.2 // indirect + github.com/go-openapi/spec v0.22.1 // indirect + github.com/go-openapi/strfmt v0.25.0 // indirect + github.com/go-openapi/validate v0.25.1 // indirect github.com/google/uuid v1.6.0 github.com/grafana/regexp v0.0.0-20250905093917-f7b3be9d1853 // indirect github.com/inconshreveable/mousetrap v1.1.0 // indirect @@ -141,17 +138,17 @@ require ( github.com/spf13/cobra v1.10.1 // indirect github.com/spf13/pflag v1.0.10 // indirect github.com/xhit/go-str2duration/v2 v2.1.0 // indirect - go.mongodb.org/mongo-driver v1.17.4 // indirect - go.opentelemetry.io/otel v1.38.0 // indirect - go.opentelemetry.io/otel/metric v1.38.0 // indirect - go.opentelemetry.io/otel/trace v1.38.0 // indirect + go.mongodb.org/mongo-driver v1.17.6 // indirect + go.opentelemetry.io/otel v1.39.0 // indirect + go.opentelemetry.io/otel/metric v1.39.0 // indirect + go.opentelemetry.io/otel/trace v1.39.0 // indirect go.uber.org/atomic v1.11.0 // indirect - golang.org/x/crypto v0.44.0 // indirect - golang.org/x/oauth2 v0.32.0 // indirect - golang.org/x/sys v0.38.0 // indirect - golang.org/x/term v0.37.0 // indirect - golang.org/x/text v0.31.0 // indirect - golang.org/x/time v0.13.0 // indirect + golang.org/x/crypto v0.46.0 // indirect + golang.org/x/oauth2 v0.34.0 // indirect + golang.org/x/sys v0.39.0 // indirect + golang.org/x/term v0.38.0 // indirect + golang.org/x/text v0.32.0 // indirect + golang.org/x/time v0.14.0 // indirect gopkg.in/inf.v0 v0.9.1 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect gotest.tools/v3 v3.5.2 diff --git a/go.sum b/go.sum index bdc5843b6bd..03b72c0c188 100644 --- a/go.sum +++ b/go.sum @@ -1,18 +1,18 @@ -cloud.google.com/go v0.118.0 h1:tvZe1mgqRxpiVa3XlIGMiPcEUbP1gNXELgD4y/IXmeQ= -cloud.google.com/go/auth v0.16.5 h1:mFWNQ2FEVWAliEQWpAdH80omXFokmrnbDhUS9cBywsI= -cloud.google.com/go/auth v0.16.5/go.mod h1:utzRfHMP+Vv0mpOkTRQoWD2q3BatTOoWbA7gCc2dUhQ= +cloud.google.com/go v0.120.0 h1:wc6bgG9DHyKqF5/vQvX1CiZrtHnxJjBlKUyF9nP6meA= +cloud.google.com/go/auth v0.17.0 h1:74yCm7hCj2rUyyAocqnFzsAYXgJhrG26XCFimrc/Kz4= +cloud.google.com/go/auth v0.17.0/go.mod h1:6wv/t5/6rOPAX4fJiRjKkJCvswLwdet7G8+UGXt7nCQ= cloud.google.com/go/auth/oauth2adapt v0.2.8 h1:keo8NaayQZ6wimpNSmW5OPc283g65QNIiLpZnkHRbnc= cloud.google.com/go/auth/oauth2adapt v0.2.8/go.mod h1:XQ9y31RkqZCcwJWNSx2Xvric3RrU88hAYYbjDWYDL+c= -cloud.google.com/go/compute/metadata v0.8.4 h1:oXMa1VMQBVCyewMIOm3WQsnVd9FbKBtm8reqWRaXnHQ= -cloud.google.com/go/compute/metadata v0.8.4/go.mod h1:E0bWwX5wTnLPedCKqk3pJmVgCBSM6qQI1yTBdEb3C10= -github.com/Azure/azure-sdk-for-go/sdk/azcore v1.19.1 h1:5YTBM8QDVIBN3sxBil89WfdAAqDZbyJTgh688DSxX5w= -github.com/Azure/azure-sdk-for-go/sdk/azcore v1.19.1/go.mod h1:YD5h/ldMsG0XiIw7PdyNhLxaM317eFh5yNLccNfGdyw= -github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.12.0 h1:wL5IEG5zb7BVv1Kv0Xm92orq+5hB5Nipn3B5tn4Rqfk= -github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.12.0/go.mod h1:J7MUC/wtRpfGVbQ5sIItY5/FuVWmvzlY21WAOfQnq/I= +cloud.google.com/go/compute/metadata v0.9.0 h1:pDUj4QMoPejqq20dK0Pg2N4yG9zIkYGdBtwLoEkH9Zs= +cloud.google.com/go/compute/metadata v0.9.0/go.mod h1:E0bWwX5wTnLPedCKqk3pJmVgCBSM6qQI1yTBdEb3C10= +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.20.0 h1:JXg2dwJUmPB9JmtVmdEB16APJ7jurfbY5jnfXpJoRMc= +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.20.0/go.mod h1:YD5h/ldMsG0XiIw7PdyNhLxaM317eFh5yNLccNfGdyw= +github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.13.1 h1:Hk5QBxZQC1jb2Fwj6mpzme37xbCDdNTxU7O9eb5+LB4= +github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.13.1/go.mod h1:IYus9qsFobWIc2YVwe/WPjcnyCkPKtnHAqUYeebc8z0= github.com/Azure/azure-sdk-for-go/sdk/internal v1.11.2 h1:9iefClla7iYpfYWdzPCRDozdmndjTm8DXdpCzPajMgA= github.com/Azure/azure-sdk-for-go/sdk/internal v1.11.2/go.mod h1:XtLgD3ZD34DAaVIIAyG3objl5DynM3CQ/vMcbBNJZGI= -github.com/AzureAD/microsoft-authentication-library-for-go v1.5.0 h1:XkkQbfMyuH2jTSjQjSoihryI8GINRcs4xp8lNawg0FI= -github.com/AzureAD/microsoft-authentication-library-for-go v1.5.0/go.mod h1:HKpQxkWaGLJ+D/5H8QRpyQXA1eKjxkFlOMwck5+33Jk= +github.com/AzureAD/microsoft-authentication-library-for-go v1.6.0 h1:XRzhVemXdgvJqCH0sFfrBUTnUJSBrBf7++ypk+twtRs= +github.com/AzureAD/microsoft-authentication-library-for-go v1.6.0/go.mod h1:HKpQxkWaGLJ+D/5H8QRpyQXA1eKjxkFlOMwck5+33Jk= github.com/DATA-DOG/go-sqlmock v1.4.1/go.mod h1:f/Ixk793poVmq4qj/V1dPUg2JEAKC73Q5eFN3EC/SaM= github.com/KimMachineGun/automemlimit v0.7.5 h1:RkbaC0MwhjL1ZuBKunGDjE/ggwAX43DwZrJqVwyveTk= github.com/KimMachineGun/automemlimit v0.7.5/go.mod h1:QZxpHaGOQoYvFhv/r4u3U0JTC2ZcOwbSr11UZF46UBM= @@ -28,32 +28,34 @@ github.com/armon/go-socks5 v0.0.0-20160902184237-e75332964ef5 h1:0CwZNZbxp69SHPd github.com/armon/go-socks5 v0.0.0-20160902184237-e75332964ef5/go.mod h1:wHh0iHkYZB8zMSxRWpUBQtwG5a7fFgvEO+odwuTv2gs= github.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2 h1:DklsrG3dyBCFEj5IhUbnKptjxatkF07cF2ak3yi77so= github.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2/go.mod h1:WaHUgvxTVq04UNunO+XhnAqY/wQc+bxr74GqbsZ/Jqw= -github.com/aws/aws-sdk-go-v2 v1.39.2 h1:EJLg8IdbzgeD7xgvZ+I8M1e0fL0ptn/M47lianzth0I= -github.com/aws/aws-sdk-go-v2 v1.39.2/go.mod h1:sDioUELIUO9Znk23YVmIk86/9DOpkbyyVb1i/gUNFXY= -github.com/aws/aws-sdk-go-v2/config v1.31.12 h1:pYM1Qgy0dKZLHX2cXslNacbcEFMkDMl+Bcj5ROuS6p8= -github.com/aws/aws-sdk-go-v2/config v1.31.12/go.mod h1:/MM0dyD7KSDPR+39p9ZNVKaHDLb9qnfDurvVS2KAhN8= -github.com/aws/aws-sdk-go-v2/credentials v1.18.16 h1:4JHirI4zp958zC026Sm+V4pSDwW4pwLefKrc0bF2lwI= -github.com/aws/aws-sdk-go-v2/credentials v1.18.16/go.mod h1:qQMtGx9OSw7ty1yLclzLxXCRbrkjWAM7JnObZjmCB7I= -github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.18.9 h1:Mv4Bc0mWmv6oDuSWTKnk+wgeqPL5DRFu5bQL9BGPQ8Y= -github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.18.9/go.mod h1:IKlKfRppK2a1y0gy1yH6zD+yX5uplJ6UuPlgd48dJiQ= -github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.9 h1:se2vOWGD3dWQUtfn4wEjRQJb1HK1XsNIt825gskZ970= -github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.9/go.mod h1:hijCGH2VfbZQxqCDN7bwz/4dzxV+hkyhjawAtdPWKZA= -github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.9 h1:6RBnKZLkJM4hQ+kN6E7yWFveOTg8NLPHAkqrs4ZPlTU= -github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.9/go.mod h1:V9rQKRmK7AWuEsOMnHzKj8WyrIir1yUJbZxDuZLFvXI= -github.com/aws/aws-sdk-go-v2/internal/ini v1.8.3 h1:bIqFDwgGXXN1Kpp99pDOdKMTTb5d2KyU5X/BZxjOkRo= -github.com/aws/aws-sdk-go-v2/internal/ini v1.8.3/go.mod h1:H5O/EsxDWyU+LP/V8i5sm8cxoZgc2fdNR9bxlOFrQTo= -github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.1 h1:oegbebPEMA/1Jny7kvwejowCaHz1FWZAQ94WXFNCyTM= -github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.1/go.mod h1:kemo5Myr9ac0U9JfSjMo9yHLtw+pECEHsFtJ9tqCEI8= -github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.9 h1:5r34CgVOD4WZudeEKZ9/iKpiT6cM1JyEROpXjOcdWv8= -github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.9/go.mod h1:dB12CEbNWPbzO2uC6QSWHteqOg4JfBVJOojbAoAUb5I= -github.com/aws/aws-sdk-go-v2/service/sso v1.29.6 h1:A1oRkiSQOWstGh61y4Wc/yQ04sqrQZr1Si/oAXj20/s= -github.com/aws/aws-sdk-go-v2/service/sso v1.29.6/go.mod h1:5PfYspyCU5Vw1wNPsxi15LZovOnULudOQuVxphSflQA= -github.com/aws/aws-sdk-go-v2/service/ssooidc v1.35.1 h1:5fm5RTONng73/QA73LhCNR7UT9RpFH3hR6HWL6bIgVY= -github.com/aws/aws-sdk-go-v2/service/ssooidc v1.35.1/go.mod h1:xBEjWD13h+6nq+z4AkqSfSvqRKFgDIQeaMguAJndOWo= -github.com/aws/aws-sdk-go-v2/service/sts v1.38.6 h1:p3jIvqYwUZgu/XYeI48bJxOhvm47hZb5HUQ0tn6Q9kA= -github.com/aws/aws-sdk-go-v2/service/sts v1.38.6/go.mod h1:WtKK+ppze5yKPkZ0XwqIVWD4beCwv056ZbPQNoeHqM8= -github.com/aws/smithy-go v1.23.0 h1:8n6I3gXzWJB2DxBDnfxgBaSX6oe0d/t10qGz7OKqMCE= -github.com/aws/smithy-go v1.23.0/go.mod h1:t1ufH5HMublsJYulve2RKmHDC15xu1f26kHCp/HgceI= +github.com/aws/aws-sdk-go-v2 v1.41.0 h1:tNvqh1s+v0vFYdA1xq0aOJH+Y5cRyZ5upu6roPgPKd4= +github.com/aws/aws-sdk-go-v2 v1.41.0/go.mod h1:MayyLB8y+buD9hZqkCW3kX1AKq07Y5pXxtgB+rRFhz0= +github.com/aws/aws-sdk-go-v2/config v1.32.6 h1:hFLBGUKjmLAekvi1evLi5hVvFQtSo3GYwi+Bx4lpJf8= +github.com/aws/aws-sdk-go-v2/config v1.32.6/go.mod h1:lcUL/gcd8WyjCrMnxez5OXkO3/rwcNmvfno62tnXNcI= +github.com/aws/aws-sdk-go-v2/credentials v1.19.6 h1:F9vWao2TwjV2MyiyVS+duza0NIRtAslgLUM0vTA1ZaE= +github.com/aws/aws-sdk-go-v2/credentials v1.19.6/go.mod h1:SgHzKjEVsdQr6Opor0ihgWtkWdfRAIwxYzSJ8O85VHY= +github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.18.16 h1:80+uETIWS1BqjnN9uJ0dBUaETh+P1XwFy5vwHwK5r9k= +github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.18.16/go.mod h1:wOOsYuxYuB/7FlnVtzeBYRcjSRtQpAW0hCP7tIULMwo= +github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.16 h1:rgGwPzb82iBYSvHMHXc8h9mRoOUBZIGFgKb9qniaZZc= +github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.16/go.mod h1:L/UxsGeKpGoIj6DxfhOWHWQ/kGKcd4I1VncE4++IyKA= +github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.16 h1:1jtGzuV7c82xnqOVfx2F0xmJcOw5374L7N6juGW6x6U= +github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.16/go.mod h1:M2E5OQf+XLe+SZGmmpaI2yy+J326aFf6/+54PoxSANc= +github.com/aws/aws-sdk-go-v2/internal/ini v1.8.4 h1:WKuaxf++XKWlHWu9ECbMlha8WOEGm0OUEZqm4K/Gcfk= +github.com/aws/aws-sdk-go-v2/internal/ini v1.8.4/go.mod h1:ZWy7j6v1vWGmPReu0iSGvRiise4YI5SkR3OHKTZ6Wuc= +github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.4 h1:0ryTNEdJbzUCEWkVXEXoqlXV72J5keC1GvILMOuD00E= +github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.4/go.mod h1:HQ4qwNZh32C3CBeO6iJLQlgtMzqeG17ziAA/3KDJFow= +github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.16 h1:oHjJHeUy0ImIV0bsrX0X91GkV5nJAyv1l1CC9lnO0TI= +github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.16/go.mod h1:iRSNGgOYmiYwSCXxXaKb9HfOEj40+oTKn8pTxMlYkRM= +github.com/aws/aws-sdk-go-v2/service/signin v1.0.4 h1:HpI7aMmJ+mm1wkSHIA2t5EaFFv5EFYXePW30p1EIrbQ= +github.com/aws/aws-sdk-go-v2/service/signin v1.0.4/go.mod h1:C5RdGMYGlfM0gYq/tifqgn4EbyX99V15P2V3R+VHbQU= +github.com/aws/aws-sdk-go-v2/service/sso v1.30.8 h1:aM/Q24rIlS3bRAhTyFurowU8A0SMyGDtEOY/l/s/1Uw= +github.com/aws/aws-sdk-go-v2/service/sso v1.30.8/go.mod h1:+fWt2UHSb4kS7Pu8y+BMBvJF0EWx+4H0hzNwtDNRTrg= +github.com/aws/aws-sdk-go-v2/service/ssooidc v1.35.12 h1:AHDr0DaHIAo8c9t1emrzAlVDFp+iMMKnPdYy6XO4MCE= +github.com/aws/aws-sdk-go-v2/service/ssooidc v1.35.12/go.mod h1:GQ73XawFFiWxyWXMHWfhiomvP3tXtdNar/fi8z18sx0= +github.com/aws/aws-sdk-go-v2/service/sts v1.41.5 h1:SciGFVNZ4mHdm7gpD1dgZYnCuVdX1s+lFTg4+4DOy70= +github.com/aws/aws-sdk-go-v2/service/sts v1.41.5/go.mod h1:iW40X4QBmUxdP+fZNOpfmkdMZqsovezbAeO+Ubiv2pk= +github.com/aws/smithy-go v1.24.0 h1:LpilSUItNPFr1eY85RYgTIg5eIEPtvFbskaFcmmIUnk= +github.com/aws/smithy-go v1.24.0/go.mod h1:LEj2LM3rBRQJxPZTB4KuzZkaZYnZPnvgIhb4pu07mx0= github.com/bboreham/go-loser v0.0.0-20230920113527-fcc2c21820a3 h1:6df1vn4bBlDDo4tARvBm7l6KA9iVMnE3NWizDeWSrps= github.com/bboreham/go-loser v0.0.0-20230920113527-fcc2c21820a3/go.mod h1:CIWtjkly68+yqLPbvwwR/fjNJA/idrtULjZWh2v1ys0= github.com/beorn7/perks v0.0.0-20180321164747-3a771d992973/go.mod h1:Dwedo/Wpr24TaqPxmxbtue+5NUziq4I4S80YR8gNf3Q= @@ -107,50 +109,54 @@ github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag= github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE= github.com/go-logr/zapr v1.3.0 h1:XGdV8XW8zdwFiwOA2Dryh1gj2KRQyOOoNmBy4EplIcQ= github.com/go-logr/zapr v1.3.0/go.mod h1:YKepepNBd1u/oyhd/yQmtjVXmm9uML4IXUgMOwR8/Gg= -github.com/go-openapi/analysis v0.24.0 h1:vE/VFFkICKyYuTWYnplQ+aVr45vlG6NcZKC7BdIXhsA= -github.com/go-openapi/analysis v0.24.0/go.mod h1:GLyoJA+bvmGGaHgpfeDh8ldpGo69fAJg7eeMDMRCIrw= -github.com/go-openapi/errors v0.22.3 h1:k6Hxa5Jg1TUyZnOwV2Lh81j8ayNw5VVYLvKrp4zFKFs= -github.com/go-openapi/errors v0.22.3/go.mod h1:+WvbaBBULWCOna//9B9TbLNGSFOfF8lY9dw4hGiEiKQ= +github.com/go-openapi/analysis v0.24.1 h1:Xp+7Yn/KOnVWYG8d+hPksOYnCYImE3TieBa7rBOesYM= +github.com/go-openapi/analysis v0.24.1/go.mod h1:dU+qxX7QGU1rl7IYhBC8bIfmWQdX4Buoea4TGtxXY84= +github.com/go-openapi/errors v0.22.4 h1:oi2K9mHTOb5DPW2Zjdzs/NIvwi2N3fARKaTJLdNabaM= +github.com/go-openapi/errors v0.22.4/go.mod h1:z9S8ASTUqx7+CP1Q8dD8ewGH/1JWFFLX/2PmAYNQLgk= github.com/go-openapi/jsonpointer v0.22.1 h1:sHYI1He3b9NqJ4wXLoJDKmUmHkWy/L7rtEo92JUxBNk= github.com/go-openapi/jsonpointer v0.22.1/go.mod h1:pQT9OsLkfz1yWoMgYFy4x3U5GY5nUlsOn1qSBH5MkCM= -github.com/go-openapi/jsonreference v0.21.2 h1:Wxjda4M/BBQllegefXrY/9aq1fxBA8sI5M/lFU6tSWU= -github.com/go-openapi/jsonreference v0.21.2/go.mod h1:pp3PEjIsJ9CZDGCNOyXIQxsNuroxm8FAJ/+quA0yKzQ= -github.com/go-openapi/loads v0.23.1 h1:H8A0dX2KDHxDzc797h0+uiCZ5kwE2+VojaQVaTlXvS0= -github.com/go-openapi/loads v0.23.1/go.mod h1:hZSXkyACCWzWPQqizAv/Ye0yhi2zzHwMmoXQ6YQml44= -github.com/go-openapi/runtime v0.29.0 h1:Y7iDTFarS9XaFQ+fA+lBLngMwH6nYfqig1G+pHxMRO0= -github.com/go-openapi/runtime v0.29.0/go.mod h1:52HOkEmLL/fE4Pg3Kf9nxc9fYQn0UsIWyGjGIJE9dkg= -github.com/go-openapi/spec v0.22.0 h1:xT/EsX4frL3U09QviRIZXvkh80yibxQmtoEvyqug0Tw= -github.com/go-openapi/spec v0.22.0/go.mod h1:K0FhKxkez8YNS94XzF8YKEMULbFrRw4m15i2YUht4L0= -github.com/go-openapi/strfmt v0.24.0 h1:dDsopqbI3wrrlIzeXRbqMihRNnjzGC+ez4NQaAAJLuc= -github.com/go-openapi/strfmt v0.24.0/go.mod h1:Lnn1Bk9rZjXxU9VMADbEEOo7D7CDyKGLsSKekhFr7s4= -github.com/go-openapi/swag v0.25.1 h1:6uwVsx+/OuvFVPqfQmOOPsqTcm5/GkBhNwLqIR916n8= -github.com/go-openapi/swag v0.25.1/go.mod h1:bzONdGlT0fkStgGPd3bhZf1MnuPkf2YAys6h+jZipOo= -github.com/go-openapi/swag/cmdutils v0.25.1 h1:nDke3nAFDArAa631aitksFGj2omusks88GF1VwdYqPY= -github.com/go-openapi/swag/cmdutils v0.25.1/go.mod h1:pdae/AFo6WxLl5L0rq87eRzVPm/XRHM3MoYgRMvG4A0= -github.com/go-openapi/swag/conv v0.25.1 h1:+9o8YUg6QuqqBM5X6rYL/p1dpWeZRhoIt9x7CCP+he0= -github.com/go-openapi/swag/conv v0.25.1/go.mod h1:Z1mFEGPfyIKPu0806khI3zF+/EUXde+fdeksUl2NiDs= -github.com/go-openapi/swag/fileutils v0.25.1 h1:rSRXapjQequt7kqalKXdcpIegIShhTPXx7yw0kek2uU= -github.com/go-openapi/swag/fileutils v0.25.1/go.mod h1:+NXtt5xNZZqmpIpjqcujqojGFek9/w55b3ecmOdtg8M= -github.com/go-openapi/swag/jsonname v0.25.1 h1:Sgx+qbwa4ej6AomWC6pEfXrA6uP2RkaNjA9BR8a1RJU= -github.com/go-openapi/swag/jsonname v0.25.1/go.mod h1:71Tekow6UOLBD3wS7XhdT98g5J5GR13NOTQ9/6Q11Zo= -github.com/go-openapi/swag/jsonutils v0.25.1 h1:AihLHaD0brrkJoMqEZOBNzTLnk81Kg9cWr+SPtxtgl8= -github.com/go-openapi/swag/jsonutils v0.25.1/go.mod h1:JpEkAjxQXpiaHmRO04N1zE4qbUEg3b7Udll7AMGTNOo= -github.com/go-openapi/swag/jsonutils/fixtures_test v0.25.1 h1:DSQGcdB6G0N9c/KhtpYc71PzzGEIc/fZ1no35x4/XBY= -github.com/go-openapi/swag/jsonutils/fixtures_test v0.25.1/go.mod h1:kjmweouyPwRUEYMSrbAidoLMGeJ5p6zdHi9BgZiqmsg= -github.com/go-openapi/swag/loading v0.25.1 h1:6OruqzjWoJyanZOim58iG2vj934TysYVptyaoXS24kw= -github.com/go-openapi/swag/loading v0.25.1/go.mod h1:xoIe2EG32NOYYbqxvXgPzne989bWvSNoWoyQVWEZicc= -github.com/go-openapi/swag/mangling v0.25.1 h1:XzILnLzhZPZNtmxKaz/2xIGPQsBsvmCjrJOWGNz/ync= -github.com/go-openapi/swag/mangling v0.25.1/go.mod h1:CdiMQ6pnfAgyQGSOIYnZkXvqhnnwOn997uXZMAd/7mQ= -github.com/go-openapi/swag/netutils v0.25.1 h1:2wFLYahe40tDUHfKT1GRC4rfa5T1B4GWZ+msEFA4Fl4= -github.com/go-openapi/swag/netutils v0.25.1/go.mod h1:CAkkvqnUJX8NV96tNhEQvKz8SQo2KF0f7LleiJwIeRE= -github.com/go-openapi/swag/stringutils v0.25.1 h1:Xasqgjvk30eUe8VKdmyzKtjkVjeiXx1Iz0zDfMNpPbw= -github.com/go-openapi/swag/stringutils v0.25.1/go.mod h1:JLdSAq5169HaiDUbTvArA2yQxmgn4D6h4A+4HqVvAYg= -github.com/go-openapi/swag/typeutils v0.25.1 h1:rD/9HsEQieewNt6/k+JBwkxuAHktFtH3I3ysiFZqukA= -github.com/go-openapi/swag/typeutils v0.25.1/go.mod h1:9McMC/oCdS4BKwk2shEB7x17P6HmMmA6dQRtAkSnNb8= -github.com/go-openapi/swag/yamlutils v0.25.1 h1:mry5ez8joJwzvMbaTGLhw8pXUnhDK91oSJLDPF1bmGk= -github.com/go-openapi/swag/yamlutils v0.25.1/go.mod h1:cm9ywbzncy3y6uPm/97ysW8+wZ09qsks+9RS8fLWKqg= -github.com/go-openapi/validate v0.25.0 h1:JD9eGX81hDTjoY3WOzh6WqxVBVl7xjsLnvDo1GL5WPU= -github.com/go-openapi/validate v0.25.0/go.mod h1:SUY7vKrN5FiwK6LyvSwKjDfLNirSfWwHNgxd2l29Mmw= +github.com/go-openapi/jsonreference v0.21.3 h1:96Dn+MRPa0nYAR8DR1E03SblB5FJvh7W6krPI0Z7qMc= +github.com/go-openapi/jsonreference v0.21.3/go.mod h1:RqkUP0MrLf37HqxZxrIAtTWW4ZJIK1VzduhXYBEeGc4= +github.com/go-openapi/loads v0.23.2 h1:rJXAcP7g1+lWyBHC7iTY+WAF0rprtM+pm8Jxv1uQJp4= +github.com/go-openapi/loads v0.23.2/go.mod h1:IEVw1GfRt/P2Pplkelxzj9BYFajiWOtY2nHZNj4UnWY= +github.com/go-openapi/runtime v0.29.2 h1:UmwSGWNmWQqKm1c2MGgXVpC2FTGwPDQeUsBMufc5Yj0= +github.com/go-openapi/runtime v0.29.2/go.mod h1:biq5kJXRJKBJxTDJXAa00DOTa/anflQPhT0/wmjuy+0= +github.com/go-openapi/spec v0.22.1 h1:beZMa5AVQzRspNjvhe5aG1/XyBSMeX1eEOs7dMoXh/k= +github.com/go-openapi/spec v0.22.1/go.mod h1:c7aeIQT175dVowfp7FeCvXXnjN/MrpaONStibD2WtDA= +github.com/go-openapi/strfmt v0.25.0 h1:7R0RX7mbKLa9EYCTHRcCuIPcaqlyQiWNPTXwClK0saQ= +github.com/go-openapi/strfmt v0.25.0/go.mod h1:nNXct7OzbwrMY9+5tLX4I21pzcmE6ccMGXl3jFdPfn8= +github.com/go-openapi/swag v0.25.4 h1:OyUPUFYDPDBMkqyxOTkqDYFnrhuhi9NR6QVUvIochMU= +github.com/go-openapi/swag v0.25.4/go.mod h1:zNfJ9WZABGHCFg2RnY0S4IOkAcVTzJ6z2Bi+Q4i6qFQ= +github.com/go-openapi/swag/cmdutils v0.25.4 h1:8rYhB5n6WawR192/BfUu2iVlxqVR9aRgGJP6WaBoW+4= +github.com/go-openapi/swag/cmdutils v0.25.4/go.mod h1:pdae/AFo6WxLl5L0rq87eRzVPm/XRHM3MoYgRMvG4A0= +github.com/go-openapi/swag/conv v0.25.4 h1:/Dd7p0LZXczgUcC/Ikm1+YqVzkEeCc9LnOWjfkpkfe4= +github.com/go-openapi/swag/conv v0.25.4/go.mod h1:3LXfie/lwoAv0NHoEuY1hjoFAYkvlqI/Bn5EQDD3PPU= +github.com/go-openapi/swag/fileutils v0.25.4 h1:2oI0XNW5y6UWZTC7vAxC8hmsK/tOkWXHJQH4lKjqw+Y= +github.com/go-openapi/swag/fileutils v0.25.4/go.mod h1:cdOT/PKbwcysVQ9Tpr0q20lQKH7MGhOEb6EwmHOirUk= +github.com/go-openapi/swag/jsonname v0.25.4 h1:bZH0+MsS03MbnwBXYhuTttMOqk+5KcQ9869Vye1bNHI= +github.com/go-openapi/swag/jsonname v0.25.4/go.mod h1:GPVEk9CWVhNvWhZgrnvRA6utbAltopbKwDu8mXNUMag= +github.com/go-openapi/swag/jsonutils v0.25.4 h1:VSchfbGhD4UTf4vCdR2F4TLBdLwHyUDTd1/q4i+jGZA= +github.com/go-openapi/swag/jsonutils v0.25.4/go.mod h1:7OYGXpvVFPn4PpaSdPHJBtF0iGnbEaTk8AvBkoWnaAY= +github.com/go-openapi/swag/jsonutils/fixtures_test v0.25.4 h1:IACsSvBhiNJwlDix7wq39SS2Fh7lUOCJRmx/4SN4sVo= +github.com/go-openapi/swag/jsonutils/fixtures_test v0.25.4/go.mod h1:Mt0Ost9l3cUzVv4OEZG+WSeoHwjWLnarzMePNDAOBiM= +github.com/go-openapi/swag/loading v0.25.4 h1:jN4MvLj0X6yhCDduRsxDDw1aHe+ZWoLjW+9ZQWIKn2s= +github.com/go-openapi/swag/loading v0.25.4/go.mod h1:rpUM1ZiyEP9+mNLIQUdMiD7dCETXvkkC30z53i+ftTE= +github.com/go-openapi/swag/mangling v0.25.4 h1:2b9kBJk9JvPgxr36V23FxJLdwBrpijI26Bx5JH4Hp48= +github.com/go-openapi/swag/mangling v0.25.4/go.mod h1:6dxwu6QyORHpIIApsdZgb6wBk/DPU15MdyYj/ikn0Hg= +github.com/go-openapi/swag/netutils v0.25.4 h1:Gqe6K71bGRb3ZQLusdI8p/y1KLgV4M/k+/HzVSqT8H0= +github.com/go-openapi/swag/netutils v0.25.4/go.mod h1:m2W8dtdaoX7oj9rEttLyTeEFFEBvnAx9qHd5nJEBzYg= +github.com/go-openapi/swag/stringutils v0.25.4 h1:O6dU1Rd8bej4HPA3/CLPciNBBDwZj9HiEpdVsb8B5A8= +github.com/go-openapi/swag/stringutils v0.25.4/go.mod h1:GTsRvhJW5xM5gkgiFe0fV3PUlFm0dr8vki6/VSRaZK0= +github.com/go-openapi/swag/typeutils v0.25.4 h1:1/fbZOUN472NTc39zpa+YGHn3jzHWhv42wAJSN91wRw= +github.com/go-openapi/swag/typeutils v0.25.4/go.mod h1:Ou7g//Wx8tTLS9vG0UmzfCsjZjKhpjxayRKTHXf2pTE= +github.com/go-openapi/swag/yamlutils v0.25.4 h1:6jdaeSItEUb7ioS9lFoCZ65Cne1/RZtPBZ9A56h92Sw= +github.com/go-openapi/swag/yamlutils v0.25.4/go.mod h1:MNzq1ulQu+yd8Kl7wPOut/YHAAU/H6hL91fF+E2RFwc= +github.com/go-openapi/testify/enable/yaml/v2 v2.0.2 h1:0+Y41Pz1NkbTHz8NngxTuAXxEodtNSI1WG1c/m5Akw4= +github.com/go-openapi/testify/enable/yaml/v2 v2.0.2/go.mod h1:kme83333GCtJQHXQ8UKX3IBZu6z8T5Dvy5+CW3NLUUg= +github.com/go-openapi/testify/v2 v2.0.2 h1:X999g3jeLcoY8qctY/c/Z8iBHTbwLz7R2WXd6Ub6wls= +github.com/go-openapi/testify/v2 v2.0.2/go.mod h1:HCPmvFFnheKK2BuwSA0TbbdxJ3I16pjwMkYkP4Ywn54= +github.com/go-openapi/validate v0.25.1 h1:sSACUI6Jcnbo5IWqbYHgjibrhhmt3vR6lCzKZnmAgBw= +github.com/go-openapi/validate v0.25.1/go.mod h1:RMVyVFYte0gbSTaZ0N4KmTn6u/kClvAFp+mAVfS/DQc= github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY= github.com/go-task/slim-sprig/v3 v3.0.0 h1:sUs3vkvUymDpBKi3qH1YSqBQk9+9D/8M2mN1vB6EwHI= github.com/go-task/slim-sprig/v3 v3.0.0/go.mod h1:W848ghGpv3Qj3dhTPRyJypKRiqCdHZiAzKg9hl15HA8= @@ -175,14 +181,14 @@ github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/ github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= -github.com/google/pprof v0.0.0-20250923004556-9e5a51aed1e8 h1:ZI8gCoCjGzPsum4L21jHdQs8shFBIQih1TM9Rd/c+EQ= -github.com/google/pprof v0.0.0-20250923004556-9e5a51aed1e8/go.mod h1:I6V7YzU0XDpsHqbsyrghnFZLO1gwK6NPTNvmetQIk9U= +github.com/google/pprof v0.0.0-20251213031049-b05bdaca462f h1:HU1RgM6NALf/KW9HEY6zry3ADbDKcmpQ+hJedoNGQYQ= +github.com/google/pprof v0.0.0-20251213031049-b05bdaca462f/go.mod h1:67FPmZWbr+KDT/VlpWtw6sO9XSjpJmLuHpoLmWiTGgY= github.com/google/s2a-go v0.1.9 h1:LGD7gtMgezd8a/Xak7mEWL0PjoTQFvpRudN895yqKW0= github.com/google/s2a-go v0.1.9/go.mod h1:YA0Ei2ZQL3acow2O62kdp9UlnvMmU7kA6Eutn0dXayM= github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= -github.com/googleapis/enterprise-certificate-proxy v0.3.6 h1:GW/XbdyBFQ8Qe+YAmFU9uHLo7OnF5tL52HFAgMmyrf4= -github.com/googleapis/enterprise-certificate-proxy v0.3.6/go.mod h1:MkHOF77EYAE7qfSuSS9PU6g4Nt4e11cnsDUowfwewLA= +github.com/googleapis/enterprise-certificate-proxy v0.3.7 h1:zrn2Ee/nWmHulBx5sAVrGgAa0f2/R35S4DJwfFaUPFQ= +github.com/googleapis/enterprise-certificate-proxy v0.3.7/go.mod h1:MkHOF77EYAE7qfSuSS9PU6g4Nt4e11cnsDUowfwewLA= github.com/googleapis/gax-go v2.0.2+incompatible h1:silFMLAnr330+NRuag/VjIGF7TLp/LBrV2CJKFLWEww= github.com/googleapis/gax-go/v2 v2.15.0 h1:SyjDc1mGgZU5LncH8gimWo9lW1DtIfPibOG81vgd/bo= github.com/googleapis/gax-go/v2 v2.15.0/go.mod h1:zVVkkxAQHa1RQpg9z2AUCMnKhi0Qld9rcmyfL1OZhoc= @@ -201,8 +207,8 @@ github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHm github.com/julienschmidt/httprouter v1.2.0/go.mod h1:SYymIcj16QtmaHHD7aYtjjsJG7VTCxuUUipMqKk8s4w= github.com/kisielk/errcheck v1.5.0/go.mod h1:pFxgyoBC7bSaBwPgfKdkLd5X25qrDl4LWUI2bnpBCr8= github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck= -github.com/klauspost/compress v1.18.0 h1:c/Cqfb0r+Yi+JtIEq73FWXVkRonBlf0CRNYc8Zttxdo= -github.com/klauspost/compress v1.18.0/go.mod h1:2Pp+KzxcywXVXMr50+X0Q/Lsb43OQHYWRCY2AiWywWQ= +github.com/klauspost/compress v1.18.2 h1:iiPHWW0YrcFgpBYhsA6D1+fqHssJscY/Tm/y2Uqnapk= +github.com/klauspost/compress v1.18.2/go.mod h1:R0h/fSBs8DE4ENlcrlib3PsXS61voFxhIs2DeRhCvJ4= github.com/klauspost/cpuid/v2 v2.2.10 h1:tBs3QSyvjDyFTq3uoc/9xFpCuOsJQFNPiAhYdw2skhE= github.com/klauspost/cpuid/v2 v2.2.10/go.mod h1:hqwkgyIinND0mEev00jJYCxPNVRVXFQeu1XKlok6oO0= github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= @@ -274,13 +280,15 @@ github.com/prashantv/gostub v1.1.0 h1:BTyx3RfQjRHnUWaGF9oQos79AlQ5k8WNktv7VGvVH4 github.com/prashantv/gostub v1.1.0/go.mod h1:A5zLQHz7ieHGG7is6LLXLz7I8+3LZzsrV0P1IAHhP5U= github.com/prometheus-community/prom-label-proxy v0.12.1 h1:vJ6tGz4NMge140Ua3T/zh3HO0CA3bmnCsfkWK/cujG0= github.com/prometheus-community/prom-label-proxy v0.12.1/go.mod h1:/tZNtOMcbPbE1VFcY8b48mPqT1bb2jVpXx2WdjjM8TY= -github.com/prometheus/alertmanager v0.29.0 h1:/ET4NmAGx2Dv9kStrXIBqBgHyiSgIk4OetY+hoZRfgc= -github.com/prometheus/alertmanager v0.29.0/go.mod h1:SjI2vhrfdWg10UaRUxTz27rgdJVG3HXrhI5WFjCdBgs= +github.com/prometheus/alertmanager v0.30.0 h1:E4dnxSFXK8V2Bb8iqudlisTmaIrF3hRJSWnliG08tBM= +github.com/prometheus/alertmanager v0.30.0/go.mod h1:93PBumcTLr/gNtNtM0m7BcCffbvYP5bKuLBWiOnISaA= github.com/prometheus/client_golang v0.9.1/go.mod h1:7SWBe2y4D6OKWSNQJUaRYU/AaXPKyh/dDVn+NZz0KFw= github.com/prometheus/client_golang v1.0.0/go.mod h1:db9x61etRT2tGnBNRi70OPL5FsnadC4Ky3P0J6CfImo= github.com/prometheus/client_golang v1.5.1/go.mod h1:e9GMxYsXl05ICDXkRhurwBS4Q3OK1iX/F2sw+iXX5zU= github.com/prometheus/client_golang v1.23.2 h1:Je96obch5RDVy3FDMndoUsjAhG5Edi49h0RJWRi/o0o= github.com/prometheus/client_golang v1.23.2/go.mod h1:Tb1a6LWHB3/SPIzCoaDXI4I8UHKeFTEQ1YCr+0Gyqmg= +github.com/prometheus/client_golang/exp v0.0.0-20251212205219-7ba246a648ca h1:BOxmsLoL2ymn8lXJtorca7N/m+2vDQUDoEtPjf0iAxA= +github.com/prometheus/client_golang/exp v0.0.0-20251212205219-7ba246a648ca/go.mod h1:gndBHh3ZdjBozGcGrjUYjN3UJLRS3l2drALtu4lUt+k= github.com/prometheus/client_model v0.0.0-20180712105110-5c3871d89910/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo= github.com/prometheus/client_model v0.0.0-20190129233127-fd36f4220a90/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= github.com/prometheus/client_model v0.2.0/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= @@ -288,10 +296,10 @@ github.com/prometheus/client_model v0.6.2 h1:oBsgwpGs7iVziMvrGhE53c/GrLUsZdHnqNw github.com/prometheus/client_model v0.6.2/go.mod h1:y3m2F6Gdpfy6Ut/GBsUqTWZqCUvMVzSfMLjcu6wAwpE= github.com/prometheus/common v0.4.1/go.mod h1:TNfzLD0ON7rHzMJeJkieUDPYmFC7Snx/y86RQel1bk4= github.com/prometheus/common v0.9.1/go.mod h1:yhUN8i9wzaXS3w1O07YhxHEBxD+W35wd8bs7vj7HSQ4= -github.com/prometheus/common v0.67.3 h1:shd26MlnwTw5jksTDhC7rTQIteBxy+ZZDr3t7F2xN2Q= -github.com/prometheus/common v0.67.3/go.mod h1:gP0fq6YjjNCLssJCQp0yk4M8W6ikLURwkdd/YKtTbyI= -github.com/prometheus/exporter-toolkit v0.15.0 h1:Pcle5sSViwR1x0gdPd0wtYrPQENBieQAM7TmT0qtb2U= -github.com/prometheus/exporter-toolkit v0.15.0/go.mod h1:OyRWd2iTo6Xge9Kedvv0IhCrJSBu36JCfJ2yVniRIYk= +github.com/prometheus/common v0.67.5 h1:pIgK94WWlQt1WLwAC5j2ynLaBRDiinoAb86HZHTUGI4= +github.com/prometheus/common v0.67.5/go.mod h1:SjE/0MzDEEAyrdr5Gqc6G+sXI67maCxzaT3A2+HqjUw= +github.com/prometheus/exporter-toolkit v0.15.1 h1:XrGGr/qWl8Gd+pqJqTkNLww9eG8vR/CoRk0FubOKfLE= +github.com/prometheus/exporter-toolkit v0.15.1/go.mod h1:P/NR9qFRGbCFgpklyhix9F6v6fFr/VQB/CVsrMDGKo4= github.com/prometheus/otlptranslator v1.0.0 h1:s0LJW/iN9dkIH+EnhiD3BlkkP5QVIUVEoIwkU+A6qos= github.com/prometheus/otlptranslator v1.0.0/go.mod h1:vRYWnXvI6aWGpsdY/mOT/cbeVRBlPWtBNDb7kGR3uKM= github.com/prometheus/procfs v0.0.0-20181005140218-185b4288413d/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk= @@ -299,10 +307,10 @@ github.com/prometheus/procfs v0.0.2/go.mod h1:TjEm7ze935MbeOT/UhFTIMYKhuLP4wbCsT github.com/prometheus/procfs v0.0.8/go.mod h1:7Qr8sr6344vo1JqZ6HhLceV9o3AJ1Ff+GxbHq6oeK9A= github.com/prometheus/procfs v0.17.0 h1:FuLQ+05u4ZI+SS/w9+BWEM2TXiHKsUQ9TADiRH7DuK0= github.com/prometheus/procfs v0.17.0/go.mod h1:oPQLaDAMRbA+u8H5Pbfq+dl3VDAvHxMUOVhe0wYB2zw= -github.com/prometheus/prometheus v0.307.3 h1:zGIN3EpiKacbMatcUL2i6wC26eRWXdoXfNPjoBc2l34= -github.com/prometheus/prometheus v0.307.3/go.mod h1:sPbNW+KTS7WmzFIafC3Inzb6oZVaGLnSvwqTdz2jxRQ= -github.com/prometheus/sigv4 v0.2.1 h1:hl8D3+QEzU9rRmbKIRwMKRwaFGyLkbPdH5ZerglRHY0= -github.com/prometheus/sigv4 v0.2.1/go.mod h1:ySk6TahIlsR2sxADuHy4IBFhwEjRGGsfbbLGhFYFj6Q= +github.com/prometheus/prometheus v0.309.1 h1:jutK6eCYDpWdPTUbVbkcQsNCMO9CCkSwjQRMLds4jSo= +github.com/prometheus/prometheus v0.309.1/go.mod h1:d+dOGiVhuNDa4MaFXHVdnUBy/CzqlcNTooR8oM1wdTU= +github.com/prometheus/sigv4 v0.3.0 h1:QIG7nTbu0JTnNidGI1Uwl5AGVIChWUACxn2B/BQ1kms= +github.com/prometheus/sigv4 v0.3.0/go.mod h1:fKtFYDus2M43CWKMNtGvFNHGXnAJJEGZbiYCmVp/F8I= github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ= github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc= github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= @@ -329,28 +337,28 @@ github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXl github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= -github.com/thanos-io/thanos v0.39.2 h1:edN03y7giEc6lD17HJhYcv8ELapXxElmhJnFIYJ2GqQ= -github.com/thanos-io/thanos v0.39.2/go.mod h1:bvUPJNIx2LBXme6yBinRiGqQinxlGikLlK7PGeFQPkQ= +github.com/thanos-io/thanos v0.40.1 h1:osjcmfQTXGoFeXTVLR56+RQo7bdtQmsNem73rflYwb0= +github.com/thanos-io/thanos v0.40.1/go.mod h1:TI/hLlnHK5XuHsycq5jNiQ9VrtjjejbG3lG2U3JJr1Y= github.com/x448/float16 v0.8.4 h1:qLwI1I70+NjRFUR3zs1JPUCgaCXSh3SW62uAKT1mSBM= github.com/x448/float16 v0.8.4/go.mod h1:14CWIYCyZA/cWjXOioeEpHeN/83MdbZDRQHoFcYsOfg= github.com/xhit/go-str2duration/v2 v2.1.0 h1:lxklc02Drh6ynqX+DdPyp5pCKLUQpRT8bp8Ydu2Bstc= github.com/xhit/go-str2duration/v2 v2.1.0/go.mod h1:ohY8p+0f07DiV6Em5LKB0s2YpLtXVyJfNt1+BlmyAsU= github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= -go.mongodb.org/mongo-driver v1.17.4 h1:jUorfmVzljjr0FLzYQsGP8cgN/qzzxlY9Vh0C9KFXVw= -go.mongodb.org/mongo-driver v1.17.4/go.mod h1:Hy04i7O2kC4RS06ZrhPRqj/u4DTYkFDAAccj+rVKqgQ= +go.mongodb.org/mongo-driver v1.17.6 h1:87JUG1wZfWsr6rIz3ZmpH90rL5tea7O3IHuSwHUpsss= +go.mongodb.org/mongo-driver v1.17.6/go.mod h1:Hy04i7O2kC4RS06ZrhPRqj/u4DTYkFDAAccj+rVKqgQ= go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64= go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y= -go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.63.0 h1:RbKq8BG0FI8OiXhBfcRtqqHcZcka+gU3cskNuf05R18= -go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.63.0/go.mod h1:h06DGIukJOevXaj/xrNjhi/2098RZzcLTbc0jDAUbsg= -go.opentelemetry.io/otel v1.38.0 h1:RkfdswUDRimDg0m2Az18RKOsnI8UDzppJAtj01/Ymk8= -go.opentelemetry.io/otel v1.38.0/go.mod h1:zcmtmQ1+YmQM9wrNsTGV/q/uyusom3P8RxwExxkZhjM= -go.opentelemetry.io/otel/metric v1.38.0 h1:Kl6lzIYGAh5M159u9NgiRkmoMKjvbsKtYRwgfrA6WpA= -go.opentelemetry.io/otel/metric v1.38.0/go.mod h1:kB5n/QoRM8YwmUahxvI3bO34eVtQf2i4utNVLr9gEmI= -go.opentelemetry.io/otel/sdk v1.38.0 h1:l48sr5YbNf2hpCUj/FoGhW9yDkl+Ma+LrVl8qaM5b+E= -go.opentelemetry.io/otel/sdk v1.38.0/go.mod h1:ghmNdGlVemJI3+ZB5iDEuk4bWA3GkTpW+DOoZMYBVVg= -go.opentelemetry.io/otel/trace v1.38.0 h1:Fxk5bKrDZJUH+AMyyIXGcFAPah0oRcT+LuNtJrmcNLE= -go.opentelemetry.io/otel/trace v1.38.0/go.mod h1:j1P9ivuFsTceSWe1oY+EeW3sc+Pp42sO++GHkg4wwhs= +go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.64.0 h1:ssfIgGNANqpVFCndZvcuyKbl0g+UAVcbBcqGkG28H0Y= +go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.64.0/go.mod h1:GQ/474YrbE4Jx8gZ4q5I4hrhUzM6UPzyrqJYV2AqPoQ= +go.opentelemetry.io/otel v1.39.0 h1:8yPrr/S0ND9QEfTfdP9V+SiwT4E0G7Y5MO7p85nis48= +go.opentelemetry.io/otel v1.39.0/go.mod h1:kLlFTywNWrFyEdH0oj2xK0bFYZtHRYUdv1NklR/tgc8= +go.opentelemetry.io/otel/metric v1.39.0 h1:d1UzonvEZriVfpNKEVmHXbdf909uGTOQjA0HF0Ls5Q0= +go.opentelemetry.io/otel/metric v1.39.0/go.mod h1:jrZSWL33sD7bBxg1xjrqyDjnuzTUB0x1nBERXd7Ftcs= +go.opentelemetry.io/otel/sdk v1.39.0 h1:nMLYcjVsvdui1B/4FRkwjzoRVsMK8uL/cj0OyhKzt18= +go.opentelemetry.io/otel/sdk v1.39.0/go.mod h1:vDojkC4/jsTJsE+kh+LXYQlbL8CgrEcwmt1ENZszdJE= +go.opentelemetry.io/otel/trace v1.39.0 h1:2d2vfpEDmCJ5zVYz7ijaJdOF59xLomrvj7bjt6/qCJI= +go.opentelemetry.io/otel/trace v1.39.0/go.mod h1:88w4/PnZSazkGzz/w84VHpQafiU4EtqqlVdxWy+rNOA= go.uber.org/atomic v1.11.0 h1:ZvwS0R+56ePWxUNi+Atn9dWONBPp/AUETXlHW0DxSjE= go.uber.org/atomic v1.11.0/go.mod h1:LUxbIzbOniOlMKjJjyPfpl4v+PKK2cNJn91OQbhoJI0= go.uber.org/automaxprocs v1.6.0 h1:O3y2/QNTOdbF+e/dpXNNW7Rx2hZ4sTIPyybbxyNqTUs= @@ -359,8 +367,8 @@ go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto= go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE= go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0= go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y= -go.uber.org/zap v1.27.0 h1:aJMhYGrd5QSmlpLMr2MftRKl7t8J8PTZPA732ud/XR8= -go.uber.org/zap v1.27.0/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E= +go.uber.org/zap v1.27.1 h1:08RqriUEv8+ArZRYSTXy1LeBScaMpVSTBhCeaZYfMYc= +go.uber.org/zap v1.27.1/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E= go.yaml.in/yaml/v2 v2.4.3 h1:6gvOSjQoTB3vt1l+CU+tSyi/HOjfOjRLJ4YwYZGwRO0= go.yaml.in/yaml/v2 v2.4.3/go.mod h1:zSxWcmIDjOzPXpjlTTbAsKokqkDNAVtZO0WOMiT90s8= go.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc= @@ -369,8 +377,8 @@ golang.org/x/crypto v0.0.0-20180904163835-0709b304e793/go.mod h1:6SG95UA2DQfeDnf golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= -golang.org/x/crypto v0.44.0 h1:A97SsFvM3AIwEEmTBiaxPPTYpDC47w720rdiiUvgoAU= -golang.org/x/crypto v0.44.0/go.mod h1:013i+Nw79BMiQiMsOPcVCB5ZIJbYkerPrGnOa00tvmc= +golang.org/x/crypto v0.46.0 h1:cKRW/pmt1pKAfetfu+RCEvjvZkA9RimPbh7bhFjGVBU= +golang.org/x/crypto v0.46.0/go.mod h1:Evb/oLKmMraqjZ2iQTwDwvCtJkczlDuTmdJXoZVzqU0= golang.org/x/exp v0.0.0-20251002181428-27f1f14c8bb9 h1:TQwNpfvNkxAVlItJf6Cr5JTsVZoC/Sj7K3OZv2Pc14A= golang.org/x/exp v0.0.0-20251002181428-27f1f14c8bb9/go.mod h1:TwQYMMnGpvZyc+JpB/UAuTNIsVJifOlSkrZkhcvpVUk= golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= @@ -381,17 +389,17 @@ golang.org/x/net v0.0.0-20190613194153-d28f0bde5980/go.mod h1:z5CRVTTTmAJ677TzLL golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20200226121028-0de0cce0169b/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= -golang.org/x/net v0.47.0 h1:Mx+4dIFzqraBXUugkia1OOvlD6LemFo1ALMHjrXDOhY= -golang.org/x/net v0.47.0/go.mod h1:/jNxtkgq5yWUGYkaZGqo27cfGZ1c5Nen03aYrrKpVRU= -golang.org/x/oauth2 v0.32.0 h1:jsCblLleRMDrxMN29H3z/k1KliIvpLgCkE6R8FXXNgY= -golang.org/x/oauth2 v0.32.0/go.mod h1:lzm5WQJQwKZ3nwavOZ3IS5Aulzxi68dUSgRHujetwEA= +golang.org/x/net v0.48.0 h1:zyQRTTrjc33Lhh0fBgT/H3oZq9WuvRR5gPC70xpDiQU= +golang.org/x/net v0.48.0/go.mod h1:+ndRgGjkh8FGtu1w1FGbEC31if4VrNVMuKTgcAAnQRY= +golang.org/x/oauth2 v0.34.0 h1:hqK/t4AKgbqWkdkcAeI8XLmbK+4m4G5YeQRrmiotGlw= +golang.org/x/oauth2 v0.34.0/go.mod h1:lzm5WQJQwKZ3nwavOZ3IS5Aulzxi68dUSgRHujetwEA= golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.18.0 h1:kr88TuHDroi+UVf+0hZnirlk8o8T+4MrK6mr60WkH/I= -golang.org/x/sync v0.18.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI= +golang.org/x/sync v0.19.0 h1:vV+1eWNmZ5geRlYjzm2adRgW2/mcpevXNg50YZtPCE4= +golang.org/x/sync v0.19.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI= golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20181116152217-5ac8a444bdc5/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= @@ -399,34 +407,35 @@ golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7w golang.org/x/sys v0.0.0-20190422165155-953cdadca894/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200122134326-e047566fdf82/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.38.0 h1:3yZWxaJjBmCWXqhN1qh02AkOnCQ1poK6oF+a7xWL6Gc= -golang.org/x/sys v0.38.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks= -golang.org/x/term v0.37.0 h1:8EGAD0qCmHYZg6J17DvsMy9/wJ7/D/4pV/wfnld5lTU= -golang.org/x/term v0.37.0/go.mod h1:5pB4lxRNYYVZuTLmy8oR2BH8dflOR+IbTYFD8fi3254= +golang.org/x/sys v0.39.0 h1:CvCKL8MeisomCi6qNZ+wbb0DN9E5AATixKsvNtMoMFk= +golang.org/x/sys v0.39.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks= +golang.org/x/term v0.38.0 h1:PQ5pkm/rLO6HnxFR7N2lJHOZX6Kez5Y1gDSJla6jo7Q= +golang.org/x/term v0.38.0/go.mod h1:bSEAKrOT1W+VSu9TSCMtoGEOUcKxOKgl3LE5QEF/xVg= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= -golang.org/x/text v0.31.0 h1:aC8ghyu4JhP8VojJ2lEHBnochRno1sgL6nEi9WGFGMM= -golang.org/x/text v0.31.0/go.mod h1:tKRAlv61yKIjGGHX/4tP1LTbc13YSec1pxVEWXzfoeM= -golang.org/x/time v0.13.0 h1:eUlYslOIt32DgYD6utsuUeHs4d7AsEYLuIAdg7FlYgI= -golang.org/x/time v0.13.0/go.mod h1:eL/Oa2bBBK0TkX57Fyni+NgnyQQN4LitPmob2Hjnqw4= +golang.org/x/text v0.32.0 h1:ZD01bjUt1FQ9WJ0ClOL5vxgxOI/sVCNgX1YtKwcY0mU= +golang.org/x/text v0.32.0/go.mod h1:o/rUWzghvpD5TXrTIBuJU77MTaN0ljMWE47kxGJQ7jY= +golang.org/x/time v0.14.0 h1:MRx4UaLrDotUKUdCIqzPC48t1Y9hANFKIRpNx+Te8PI= +golang.org/x/time v0.14.0/go.mod h1:eL/Oa2bBBK0TkX57Fyni+NgnyQQN4LitPmob2Hjnqw4= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.0.0-20200619180055-7c47624df98f/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= golang.org/x/tools v0.0.0-20210106214847-113979e3529a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= -golang.org/x/tools v0.38.0 h1:Hx2Xv8hISq8Lm16jvBZ2VQf+RLmbd7wVUsALibYI/IQ= -golang.org/x/tools v0.38.0/go.mod h1:yEsQ/d/YK8cjh0L6rZlY8tgtlKiBNTL14pGDJPJpYQs= +golang.org/x/tools v0.39.0 h1:ik4ho21kwuQln40uelmciQPp9SipgNDdrafrYA4TmQQ= +golang.org/x/tools v0.39.0/go.mod h1:JnefbkDPyD8UU2kI5fuf8ZX4/yUeh9W877ZeBONxUqQ= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= -google.golang.org/api v0.250.0 h1:qvkwrf/raASj82UegU2RSDGWi/89WkLckn4LuO4lVXM= -google.golang.org/api v0.250.0/go.mod h1:Y9Uup8bDLJJtMzJyQnu+rLRJLA0wn+wTtc6vTlOvfXo= -google.golang.org/genproto/googleapis/rpc v0.0.0-20251006185510-65f7160b3a87 h1:WgGZrMngVRRve7T3P5gbXdmedSmUpkf8uIUu1fg+biY= -google.golang.org/genproto/googleapis/rpc v0.0.0-20251006185510-65f7160b3a87/go.mod h1:7i2o+ce6H/6BluujYR+kqX3GKH+dChPTQU19wjRPiGk= -google.golang.org/grpc v1.76.0 h1:UnVkv1+uMLYXoIz6o7chp59WfQUYA2ex/BXQ9rHZu7A= -google.golang.org/grpc v1.76.0/go.mod h1:Ju12QI8M6iQJtbcsV+awF5a4hfJMLi4X0JLo94ULZ6c= -google.golang.org/protobuf v1.36.10 h1:AYd7cD/uASjIL6Q9LiTjz8JLcrh/88q5UObnmY3aOOE= -google.golang.org/protobuf v1.36.10/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco= +google.golang.org/api v0.257.0 h1:8Y0lzvHlZps53PEaw+G29SsQIkuKrumGWs9puiexNAA= +google.golang.org/api v0.257.0/go.mod h1:4eJrr+vbVaZSqs7vovFd1Jb/A6ml6iw2e6FBYf3GAO4= +google.golang.org/genproto v0.0.0-20250505200425-f936aa4a68b2 h1:1tXaIXCracvtsRxSBsYDiSBN0cuJvM7QYW+MrpIRY78= +google.golang.org/genproto/googleapis/rpc v0.0.0-20251202230838-ff82c1b0f217 h1:gRkg/vSppuSQoDjxyiGfN4Upv/h/DQmIR10ZU8dh4Ww= +google.golang.org/genproto/googleapis/rpc v0.0.0-20251202230838-ff82c1b0f217/go.mod h1:7i2o+ce6H/6BluujYR+kqX3GKH+dChPTQU19wjRPiGk= +google.golang.org/grpc v1.77.0 h1:wVVY6/8cGA6vvffn+wWK5ToddbgdU3d8MNENr4evgXM= +google.golang.org/grpc v1.77.0/go.mod h1:z0BY1iVj0q8E1uSQCjL9cppRj+gnZjzDnzV0dHhrNig= +google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE= +google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco= gopkg.in/alecthomas/kingpin.v2 v2.2.6/go.mod h1:FMv+mEhP44yOT+4EoQTLFTRgOQ1FBLkstjWtayDeSgw= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= @@ -447,18 +456,18 @@ gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gotest.tools/v3 v3.5.2 h1:7koQfIKdy+I8UTetycgUqXWSDwpgv193Ka+qRsmBY8Q= gotest.tools/v3 v3.5.2/go.mod h1:LtdLGcnqToBH83WByAAi/wiwSFCArdFIUV/xxN4pcjA= -k8s.io/api v0.34.2 h1:fsSUNZhV+bnL6Aqrp6O7lMTy6o5x2C4XLjnh//8SLYY= -k8s.io/api v0.34.2/go.mod h1:MMBPaWlED2a8w4RSeanD76f7opUoypY8TFYkSM+3XHw= -k8s.io/apiextensions-apiserver v0.34.2 h1:WStKftnGeoKP4AZRz/BaAAEJvYp4mlZGN0UCv+uvsqo= -k8s.io/apiextensions-apiserver v0.34.2/go.mod h1:398CJrsgXF1wytdaanynDpJ67zG4Xq7yj91GrmYN2SE= -k8s.io/apimachinery v0.34.2 h1:zQ12Uk3eMHPxrsbUJgNF8bTauTVR2WgqJsTmwTE/NW4= -k8s.io/apimachinery v0.34.2/go.mod h1:/GwIlEcWuTX9zKIg2mbw0LRFIsXwrfoVxn+ef0X13lw= -k8s.io/apiserver v0.34.2 h1:2/yu8suwkmES7IzwlehAovo8dDE07cFRC7KMDb1+MAE= -k8s.io/apiserver v0.34.2/go.mod h1:gqJQy2yDOB50R3JUReHSFr+cwJnL8G1dzTA0YLEqAPI= -k8s.io/client-go v0.34.2 h1:Co6XiknN+uUZqiddlfAjT68184/37PS4QAzYvQvDR8M= -k8s.io/client-go v0.34.2/go.mod h1:2VYDl1XXJsdcAxw7BenFslRQX28Dxz91U9MWKjX97fE= -k8s.io/component-base v0.34.2 h1:HQRqK9x2sSAsd8+R4xxRirlTjowsg6fWCPwWYeSvogQ= -k8s.io/component-base v0.34.2/go.mod h1:9xw2FHJavUHBFpiGkZoKuYZ5pdtLKe97DEByaA+hHbM= +k8s.io/api v0.34.3 h1:D12sTP257/jSH2vHV2EDYrb16bS7ULlHpdNdNhEw2S4= +k8s.io/api v0.34.3/go.mod h1:PyVQBF886Q5RSQZOim7DybQjAbVs8g7gwJNhGtY5MBk= +k8s.io/apiextensions-apiserver v0.34.3 h1:p10fGlkDY09eWKOTeUSioxwLukJnm+KuDZdrW71y40g= +k8s.io/apiextensions-apiserver v0.34.3/go.mod h1:aujxvqGFRdb/cmXYfcRTeppN7S2XV/t7WMEc64zB5A0= +k8s.io/apimachinery v0.34.3 h1:/TB+SFEiQvN9HPldtlWOTp0hWbJ+fjU+wkxysf/aQnE= +k8s.io/apimachinery v0.34.3/go.mod h1:/GwIlEcWuTX9zKIg2mbw0LRFIsXwrfoVxn+ef0X13lw= +k8s.io/apiserver v0.34.3 h1:uGH1qpDvSiYG4HVFqc6A3L4CKiX+aBWDrrsxHYK0Bdo= +k8s.io/apiserver v0.34.3/go.mod h1:QPnnahMO5C2m3lm6fPW3+JmyQbvHZQ8uudAu/493P2w= +k8s.io/client-go v0.34.3 h1:wtYtpzy/OPNYf7WyNBTj3iUA0XaBHVqhv4Iv3tbrF5A= +k8s.io/client-go v0.34.3/go.mod h1:OxxeYagaP9Kdf78UrKLa3YZixMCfP6bgPwPwNBQBzpM= +k8s.io/component-base v0.34.3 h1:zsEgw6ELqK0XncCQomgO9DpUIzlrYuZYA0Cgo+JWpVk= +k8s.io/component-base v0.34.3/go.mod h1:5iIlD8wPfWE/xSHTRfbjuvUul2WZbI2nOUK65XL0E/c= k8s.io/klog/v2 v2.130.1 h1:n9Xl7H1Xvksem4KFG4PYbdQCQxqc/tTUyrgXaOhHSzk= k8s.io/klog/v2 v2.130.1/go.mod h1:3Jpz1GvMt720eyJH1ckRHK1EDfpxISzJ7I9OYgaDtPE= k8s.io/kube-openapi v0.0.0-20250910181357-589584f1c912 h1:Y3gxNAuB0OBLImH611+UDZcmKS3g6CthxToOb37KgwE= diff --git a/jsonnet/prometheus-operator/alertmanagerconfigs-crd.json b/jsonnet/prometheus-operator/alertmanagerconfigs-crd.json index dd0fb08b279..ad7c5c25b25 100644 --- a/jsonnet/prometheus-operator/alertmanagerconfigs-crd.json +++ b/jsonnet/prometheus-operator/alertmanagerconfigs-crd.json @@ -4,7 +4,7 @@ "metadata": { "annotations": { "controller-gen.kubebuilder.io/version": "v0.19.0", - "operator.prometheus.io/version": "0.87.1" + "operator.prometheus.io/version": "0.88.0" }, "name": "alertmanagerconfigs.monitoring.coreos.com" }, @@ -54,7 +54,8 @@ "items": { "type": "string" }, - "type": "array" + "type": "array", + "x-kubernetes-list-type": "atomic" }, "sourceMatch": { "description": "sourceMatch defines matchers for which one or more alerts have to exist for the inhibition\nto take effect. The operator enforces that the alert matches the resource's namespace.\nThese are the \"trigger\" alerts that cause other alerts to be inhibited.", @@ -90,7 +91,8 @@ ], "type": "object" }, - "type": "array" + "type": "array", + "x-kubernetes-list-type": "atomic" }, "targetMatch": { "description": "targetMatch defines matchers that have to be fulfilled in the alerts to be muted.\nThe operator enforces that the alert matches the resource's namespace.\nWhen these conditions are met, matching alerts will be inhibited (silenced).", @@ -126,12 +128,14 @@ ], "type": "object" }, - "type": "array" + "type": "array", + "x-kubernetes-list-type": "atomic" } }, "type": "object" }, - "type": "array" + "type": "array", + "x-kubernetes-list-type": "atomic" }, "muteTimeIntervals": { "description": "muteTimeIntervals defines the list of MuteTimeInterval specifying when the routes should be muted.", @@ -167,7 +171,8 @@ }, "type": "object" }, - "type": "array" + "type": "array", + "x-kubernetes-list-type": "atomic" }, "months": { "description": "months defines a list of MonthRange", @@ -176,7 +181,8 @@ "pattern": "^((?i)january|february|march|april|may|june|july|august|september|october|november|december|1[0-2]|[1-9])(?:((:((?i)january|february|march|april|may|june|july|august|september|october|november|december|1[0-2]|[1-9]))$)|$)", "type": "string" }, - "type": "array" + "type": "array", + "x-kubernetes-list-type": "atomic" }, "times": { "description": "times defines a list of TimeRange", @@ -196,7 +202,8 @@ }, "type": "object" }, - "type": "array" + "type": "array", + "x-kubernetes-list-type": "atomic" }, "weekdays": { "description": "weekdays defines a list of WeekdayRange", @@ -205,7 +212,8 @@ "pattern": "^((?i)sun|mon|tues|wednes|thurs|fri|satur)day(?:((:(sun|mon|tues|wednes|thurs|fri|satur)day)$)|$)", "type": "string" }, - "type": "array" + "type": "array", + "x-kubernetes-list-type": "atomic" }, "years": { "description": "years defines a list of YearRange", @@ -214,12 +222,14 @@ "pattern": "^2\\d{3}(?::2\\d{3}|$)", "type": "string" }, - "type": "array" + "type": "array", + "x-kubernetes-list-type": "atomic" } }, "type": "object" }, - "type": "array" + "type": "array", + "x-kubernetes-list-type": "atomic" } }, "required": [ @@ -227,7 +237,8 @@ ], "type": "object" }, - "type": "array" + "type": "array", + "x-kubernetes-list-type": "atomic" }, "receivers": { "description": "receivers defines the list of receivers.", @@ -936,7 +947,8 @@ ], "type": "object" }, - "type": "array" + "type": "array", + "x-kubernetes-list-type": "atomic" }, "emailConfigs": { "description": "emailConfigs defines the list of Email configurations.", @@ -1022,7 +1034,8 @@ ], "type": "object" }, - "type": "array" + "type": "array", + "x-kubernetes-list-type": "atomic" }, "hello": { "description": "hello defines the hostname to identify to the SMTP server.\nThis is used in the SMTP HELO/EHLO command during the connection handshake.", @@ -1216,7 +1229,8 @@ }, "type": "object" }, - "type": "array" + "type": "array", + "x-kubernetes-list-type": "atomic" }, "msteamsConfigs": { "description": "msteamsConfigs defines the list of MSTeams configurations.\nIt requires Alertmanager >= 0.26.0.", @@ -1909,7 +1923,8 @@ ], "type": "object" }, - "type": "array" + "type": "array", + "x-kubernetes-list-type": "atomic" }, "msteamsv2Configs": { "description": "msteamsv2Configs defines the list of MSTeamsV2 configurations.\nIt requires Alertmanager >= 0.28.0.", @@ -2597,7 +2612,8 @@ }, "type": "object" }, - "type": "array" + "type": "array", + "x-kubernetes-list-type": "atomic" }, "name": { "description": "name defines the name of the receiver. Must be unique across all items from the list.", @@ -2638,6 +2654,7 @@ }, "apiURL": { "description": "apiURL defines the URL to send OpsGenie API requests to.\nWhen not specified, defaults to the standard OpsGenie API endpoint.", + "pattern": "^https?://.+$", "type": "string" }, "description": { @@ -2665,7 +2682,8 @@ ], "type": "object" }, - "type": "array" + "type": "array", + "x-kubernetes-list-type": "atomic" }, "entity": { "description": "entity defines an optional field that can be used to specify which domain alert is related to.\nThis helps group related alerts together in OpsGenie.", @@ -3359,7 +3377,8 @@ ], "type": "object" }, - "type": "array" + "type": "array", + "x-kubernetes-list-type": "atomic" }, "sendResolved": { "description": "sendResolved defines whether or not to notify about resolved alerts.", @@ -3380,7 +3399,8 @@ }, "type": "object" }, - "type": "array" + "type": "array", + "x-kubernetes-list-type": "atomic" }, "pagerdutyConfigs": { "description": "pagerdutyConfigs defines the List of PagerDuty configurations.", @@ -3389,22 +3409,27 @@ "properties": { "class": { "description": "class defines the class/type of the event.", + "minLength": 1, "type": "string" }, "client": { "description": "client defines the client identification.", + "minLength": 1, "type": "string" }, "clientURL": { "description": "clientURL defines the backlink to the sender of notification.", + "pattern": "^https?://.+$", "type": "string" }, "component": { "description": "component defines the part or component of the affected system that is broken.", + "minLength": 1, "type": "string" }, "description": { "description": "description of the incident.", + "minLength": 1, "type": "string" }, "details": { @@ -3428,10 +3453,12 @@ ], "type": "object" }, - "type": "array" + "type": "array", + "x-kubernetes-list-type": "atomic" }, "group": { "description": "group defines a cluster or grouping of sources.", + "minLength": 1, "type": "string" }, "httpConfig": { @@ -4082,20 +4109,24 @@ "properties": { "alt": { "description": "alt is the optional alternative text for the image.", + "minLength": 1, "type": "string" }, "href": { "description": "href defines the optional URL; makes the image a clickable link.", + "pattern": "^https?://.+$", "type": "string" }, "src": { "description": "src of the image being attached to the incident", + "minLength": 1, "type": "string" } }, "type": "object" }, - "type": "array" + "type": "array", + "x-kubernetes-list-type": "atomic" }, "pagerDutyLinkConfigs": { "description": "pagerDutyLinkConfigs defines a list of link details to attach that provide further detail about an incident.", @@ -4104,16 +4135,19 @@ "properties": { "alt": { "description": "alt defines the text that describes the purpose of the link, and can be used as the link's text.", + "minLength": 1, "type": "string" }, "href": { "description": "href defines the URL of the link to be attached", + "pattern": "^https?://.+$", "type": "string" } }, "type": "object" }, - "type": "array" + "type": "array", + "x-kubernetes-list-type": "atomic" }, "routingKey": { "description": "routingKey defines the secret's key that contains the PagerDuty integration key (when using\nEvents API v2). Either this field or `serviceKey` needs to be defined.\nThe secret needs to be in the same namespace as the AlertmanagerConfig\nobject and accessible by the Prometheus Operator.", @@ -4167,20 +4201,29 @@ }, "severity": { "description": "severity of the incident.", + "minLength": 1, "type": "string" }, "source": { "description": "source defines the unique location of the affected system.", + "minLength": 1, + "type": "string" + }, + "timeout": { + "description": "timeout is the maximum time allowed to invoke the pagerduty\nIt requires Alertmanager >= v0.30.0.", + "pattern": "^(0|(([0-9]+)y)?(([0-9]+)w)?(([0-9]+)d)?(([0-9]+)h)?(([0-9]+)m)?(([0-9]+)s)?(([0-9]+)ms)?)$", "type": "string" }, "url": { "description": "url defines the URL to send requests to.", + "pattern": "^https?://.+$", "type": "string" } }, "type": "object" }, - "type": "array" + "type": "array", + "x-kubernetes-list-type": "atomic" }, "pushoverConfigs": { "description": "pushoverConfigs defines the list of Pushover configurations.", @@ -4189,6 +4232,7 @@ "properties": { "device": { "description": "device defines the name of a specific device to send the notification to.\nIf not specified, the notification is sent to all user's devices.", + "minLength": 1, "type": "string" }, "expire": { @@ -4197,7 +4241,7 @@ "type": "string" }, "html": { - "description": "html defines whether notification message is HTML or plain text.\nWhen true, the message can include HTML formatting tags.", + "description": "html defines whether notification message is HTML or plain text.\nWhen true, the message can include HTML formatting tags.\nhtml and monospace formatting are mutually exclusive.", "type": "boolean" }, "httpConfig": { @@ -4843,6 +4887,7 @@ }, "message": { "description": "message defines the notification message content.\nThis is the main body text of the Pushover notification.", + "minLength": 1, "type": "string" }, "monospace": { @@ -4851,6 +4896,7 @@ }, "priority": { "description": "priority defines the notification priority level.\nSee https://pushover.net/api#priority for valid values and behavior.", + "minLength": 1, "type": "string" }, "retry": { @@ -4864,10 +4910,12 @@ }, "sound": { "description": "sound defines the name of one of the sounds supported by device clients.\nThis overrides the user's default sound choice for this notification.", + "minLength": 1, "type": "string" }, "title": { "description": "title defines the notification title displayed in the Pushover message.\nThis appears as the bold header text in the notification.", + "minLength": 1, "type": "string" }, "token": { @@ -4895,6 +4943,7 @@ }, "tokenFile": { "description": "tokenFile defines the token file that contains the registered application's API token.\nSee https://pushover.net/apps for application registration.\nEither `token` or `tokenFile` is required.\nIt requires Alertmanager >= v0.26.0.", + "minLength": 1, "type": "string" }, "ttl": { @@ -4904,10 +4953,12 @@ }, "url": { "description": "url defines a supplementary URL shown alongside the message.\nThis creates a clickable link within the Pushover notification.", + "pattern": "^https?://.+$", "type": "string" }, "urlTitle": { "description": "urlTitle defines a title for the supplementary URL.\nIf not specified, the raw URL is shown instead.", + "minLength": 1, "type": "string" }, "userKey": { @@ -4935,12 +4986,14 @@ }, "userKeyFile": { "description": "userKeyFile defines the user key file that contains the recipient user's user key.\nEither `userKey` or `userKeyFile` is required.\nIt requires Alertmanager >= v0.26.0.", + "minLength": 1, "type": "string" } }, "type": "object" }, - "type": "array" + "type": "array", + "x-kubernetes-list-type": "atomic" }, "rocketchatConfigs": { "description": "rocketchatConfigs defines the list of RocketChat configurations.\nIt requires Alertmanager >= 0.28.0.", @@ -4971,7 +5024,8 @@ "type": "object" }, "minItems": 1, - "type": "array" + "type": "array", + "x-kubernetes-list-type": "atomic" }, "apiURL": { "description": "apiURL defines the API URL for RocketChat.\nDefaults to https://open.rocket.chat/ if not specified.", @@ -5016,7 +5070,8 @@ "type": "object" }, "minItems": 1, - "type": "array" + "type": "array", + "x-kubernetes-list-type": "atomic" }, "httpConfig": { "description": "httpConfig defines the HTTP client configuration for RocketChat API requests.", @@ -5754,7 +5809,8 @@ ], "type": "object" }, - "type": "array" + "type": "array", + "x-kubernetes-list-type": "atomic" }, "slackConfigs": { "description": "slackConfigs defines the list of Slack configurations.", @@ -5771,10 +5827,12 @@ "properties": { "dismissText": { "description": "dismissText defines the label for the cancel button in the dialog.\nWhen not specified, defaults to \"Cancel\". This button cancels the action.", + "minLength": 1, "type": "string" }, "okText": { "description": "okText defines the label for the confirmation button in the dialog.\nWhen not specified, defaults to \"Okay\". This button proceeds with the action.", + "minLength": 1, "type": "string" }, "text": { @@ -5784,6 +5842,7 @@ }, "title": { "description": "title defines the title text displayed at the top of the confirmation dialog.\nWhen not specified, a default title will be used.", + "minLength": 1, "type": "string" } }, @@ -5794,10 +5853,12 @@ }, "name": { "description": "name defines a unique identifier for the action within the message.\nThis value is sent back to your application when the action is triggered.", + "minLength": 1, "type": "string" }, "style": { "description": "style defines the visual appearance of the action element.\nValid values include \"default\", \"primary\" (green), and \"danger\" (red).", + "minLength": 1, "type": "string" }, "text": { @@ -5812,10 +5873,12 @@ }, "url": { "description": "url defines the URL to open when the action is triggered.\nOnly applicable for button-type actions. When set, clicking the button opens this URL.", + "pattern": "^https?://.+$", "type": "string" }, "value": { "description": "value defines the payload sent when the action is triggered.\nThis data is included in the callback sent to your application.", + "minLength": 1, "type": "string" } }, @@ -5825,7 +5888,9 @@ ], "type": "object" }, - "type": "array" + "minItems": 1, + "type": "array", + "x-kubernetes-list-type": "atomic" }, "apiURL": { "description": "apiURL defines the secret's key that contains the Slack webhook URL.\nThe secret needs to be in the same namespace as the AlertmanagerConfig\nobject and accessible by the Prometheus Operator.", @@ -5852,18 +5917,22 @@ }, "callbackId": { "description": "callbackId defines an identifier for the message used in interactive components.", + "minLength": 1, "type": "string" }, "channel": { "description": "channel defines the channel or user to send notifications to.", + "minLength": 1, "type": "string" }, "color": { "description": "color defines the color of the left border of the Slack message attachment.\nCan be a hex color code (e.g., \"#ff0000\") or a predefined color name.", + "minLength": 1, "type": "string" }, "fallback": { "description": "fallback defines a plain-text summary of the attachment for clients that don't support attachments.", + "minLength": 1, "type": "string" }, "fields": { @@ -5892,10 +5961,13 @@ ], "type": "object" }, - "type": "array" + "minItems": 1, + "type": "array", + "x-kubernetes-list-type": "atomic" }, "footer": { "description": "footer defines small text displayed at the bottom of the message attachment.", + "minLength": 1, "type": "string" }, "httpConfig": { @@ -6541,14 +6613,17 @@ }, "iconEmoji": { "description": "iconEmoji defines the emoji to use as the bot's avatar (e.g., \":ghost:\").", + "minLength": 1, "type": "string" }, "iconURL": { "description": "iconURL defines the URL to an image to use as the bot's avatar.", + "pattern": "^https?://.+$", "type": "string" }, "imageURL": { "description": "imageURL defines the URL to an image file that will be displayed inside the message attachment.", + "pattern": "^https?://.+$", "type": "string" }, "linkNames": { @@ -6558,12 +6633,16 @@ "mrkdwnIn": { "description": "mrkdwnIn defines which fields should be parsed as Slack markdown.\nValid values include \"pretext\", \"text\", and \"fields\".", "items": { + "minLength": 1, "type": "string" }, - "type": "array" + "minItems": 1, + "type": "array", + "x-kubernetes-list-type": "atomic" }, "pretext": { "description": "pretext defines optional text that appears above the message attachment block.", + "minLength": 1, "type": "string" }, "sendResolved": { @@ -6576,28 +6655,39 @@ }, "text": { "description": "text defines the main text content of the Slack message attachment.", + "minLength": 1, "type": "string" }, "thumbURL": { "description": "thumbURL defines the URL to an image file that will be displayed as a thumbnail\non the right side of the message attachment.", + "pattern": "^https?://.+$", + "type": "string" + }, + "timeout": { + "description": "timeout defines the maximum time to wait for a webhook request to complete,\nbefore failing the request and allowing it to be retried.\nIt requires Alertmanager >= v0.30.0.", + "pattern": "^(0|(([0-9]+)y)?(([0-9]+)w)?(([0-9]+)d)?(([0-9]+)h)?(([0-9]+)m)?(([0-9]+)s)?(([0-9]+)ms)?)$", "type": "string" }, "title": { "description": "title defines the title text displayed in the Slack message attachment.", + "minLength": 1, "type": "string" }, "titleLink": { "description": "titleLink defines the URL that the title will link to when clicked.", + "pattern": "^https?://.+$", "type": "string" }, "username": { "description": "username defines the slack bot user name.", + "minLength": 1, "type": "string" } }, "type": "object" }, - "type": "array" + "type": "array", + "x-kubernetes-list-type": "atomic" }, "snsConfigs": { "description": "snsConfigs defines the list of SNS configurations", @@ -7351,7 +7441,8 @@ }, "type": "object" }, - "type": "array" + "type": "array", + "x-kubernetes-list-type": "atomic" }, "telegramConfigs": { "description": "telegramConfigs defines the list of Telegram configurations.", @@ -7360,6 +7451,7 @@ "properties": { "apiURL": { "description": "apiURL defines the Telegram API URL, e.g. https://api.telegram.org.\nIf not specified, the default Telegram API URL will be used.", + "pattern": "^https?://.+$", "type": "string" }, "botToken": { @@ -8067,7 +8159,8 @@ ], "type": "object" }, - "type": "array" + "type": "array", + "x-kubernetes-list-type": "atomic" }, "victoropsConfigs": { "description": "victoropsConfigs defines the list of VictorOps configurations.", @@ -8099,6 +8192,7 @@ }, "apiUrl": { "description": "apiUrl defines the VictorOps API URL.\nWhen not specified, defaults to the standard VictorOps API endpoint.", + "pattern": "^https?://.+$", "type": "string" }, "customFields": { @@ -8122,10 +8216,12 @@ ], "type": "object" }, - "type": "array" + "type": "array", + "x-kubernetes-list-type": "atomic" }, "entityDisplayName": { "description": "entityDisplayName contains a summary of the alerted problem.\nThis appears as the main title or identifier for the incident.", + "minLength": 1, "type": "string" }, "httpConfig": { @@ -8771,14 +8867,17 @@ }, "messageType": { "description": "messageType describes the behavior of the alert.\nValid values are \"CRITICAL\", \"WARNING\", and \"INFO\".", + "minLength": 1, "type": "string" }, "monitoringTool": { "description": "monitoringTool defines the monitoring tool the state message is from.\nThis helps identify the source system that generated the alert.", + "minLength": 1, "type": "string" }, "routingKey": { "description": "routingKey defines a key used to map the alert to a team.\nThis determines which VictorOps team will receive the alert notification.", + "minLength": 1, "type": "string" }, "sendResolved": { @@ -8787,12 +8886,17 @@ }, "stateMessage": { "description": "stateMessage contains a long explanation of the alerted problem.\nThis provides detailed context about the incident.", + "minLength": 1, "type": "string" } }, + "required": [ + "routingKey" + ], "type": "object" }, - "type": "array" + "type": "array", + "x-kubernetes-list-type": "atomic" }, "webexConfigs": { "description": "webexConfigs defines the list of Webex configurations.", @@ -9464,7 +9568,8 @@ ], "type": "object" }, - "type": "array" + "type": "array", + "x-kubernetes-list-type": "atomic" }, "webhookConfigs": { "description": "webhookConfigs defines the List of webhook configurations.", @@ -10129,6 +10234,7 @@ }, "url": { "description": "url defines the URL to send HTTP POST requests to.\nurlSecret takes precedence over url. One of urlSecret and url should be defined.", + "pattern": "^https?://.+$", "type": "string" }, "urlSecret": { @@ -10157,7 +10263,8 @@ }, "type": "object" }, - "type": "array" + "type": "array", + "x-kubernetes-list-type": "atomic" }, "wechatConfigs": { "description": "wechatConfigs defines the list of WeChat configurations.", @@ -10193,6 +10300,7 @@ }, "apiURL": { "description": "apiURL defines the WeChat API URL.\nWhen not specified, defaults to the standard WeChat Work API endpoint.", + "pattern": "^https?://.+$", "type": "string" }, "corpID": { @@ -10867,7 +10975,8 @@ }, "type": "object" }, - "type": "array" + "type": "array", + "x-kubernetes-list-type": "atomic" } }, "required": [ @@ -10875,7 +10984,11 @@ ], "type": "object" }, - "type": "array" + "type": "array", + "x-kubernetes-list-map-keys": [ + "name" + ], + "x-kubernetes-list-type": "map" }, "route": { "description": "route defines the Alertmanager route definition for alerts matching the resource's\nnamespace. If present, it will be added to the generated Alertmanager\nconfiguration as a first-level route.", @@ -10885,7 +10998,8 @@ "items": { "type": "string" }, - "type": "array" + "type": "array", + "x-kubernetes-list-type": "set" }, "continue": { "description": "continue defines the boolean indicating whether an alert should continue matching subsequent\nsibling nodes. It will always be overridden to true for the first-level\nroute by the Prometheus operator.", @@ -10896,7 +11010,8 @@ "items": { "type": "string" }, - "type": "array" + "type": "array", + "x-kubernetes-list-type": "set" }, "groupInterval": { "description": "groupInterval defines how long to wait before sending an updated notification.\nMust match the regular expression`^(([0-9]+)y)?(([0-9]+)w)?(([0-9]+)d)?(([0-9]+)h)?(([0-9]+)m)?(([0-9]+)s)?(([0-9]+)ms)?$`\nExample: \"5m\"", @@ -10940,14 +11055,16 @@ ], "type": "object" }, - "type": "array" + "type": "array", + "x-kubernetes-list-type": "atomic" }, "muteTimeIntervals": { "description": "muteTimeIntervals is a list of MuteTimeInterval names that will mute this route when matched,", "items": { "type": "string" }, - "type": "array" + "type": "array", + "x-kubernetes-list-type": "set" }, "receiver": { "description": "receiver defines the name of the receiver for this route. If not empty, it should be listed in\nthe `receivers` field.", @@ -10962,13 +11079,120 @@ "items": { "x-kubernetes-preserve-unknown-fields": true }, - "type": "array" + "type": "array", + "x-kubernetes-list-type": "atomic" } }, "type": "object" } }, "type": "object" + }, + "status": { + "description": "status defines the status subresource. It is under active development and is updated only when the\n\"StatusForConfigurationResources\" feature gate is enabled.\n\nMost recent observed status of the ServiceMonitor. Read-only.\nMore info:\nhttps://github.com/kubernetes/community/blob/master/contributors/devel/sig-architecture/api-conventions.md#spec-and-status", + "properties": { + "bindings": { + "description": "bindings defines the list of workload resources (Prometheus, PrometheusAgent, ThanosRuler or Alertmanager) which select the configuration resource.", + "items": { + "description": "WorkloadBinding is a link between a configuration resource and a workload resource.", + "properties": { + "conditions": { + "description": "conditions defines the current state of the configuration resource when bound to the referenced Workload object.", + "items": { + "description": "ConfigResourceCondition describes the status of configuration resources linked to Prometheus, PrometheusAgent, Alertmanager or ThanosRuler.", + "properties": { + "lastTransitionTime": { + "description": "lastTransitionTime defines the time of the last update to the current status property.", + "format": "date-time", + "type": "string" + }, + "message": { + "description": "message defines the human-readable message indicating details for the condition's last transition.", + "type": "string" + }, + "observedGeneration": { + "description": "observedGeneration defines the .metadata.generation that the\ncondition was set based upon. For instance, if `.metadata.generation` is\ncurrently 12, but the `.status.conditions[].observedGeneration` is 9, the\ncondition is out of date with respect to the current state of the object.", + "format": "int64", + "type": "integer" + }, + "reason": { + "description": "reason for the condition's last transition.", + "type": "string" + }, + "status": { + "description": "status of the condition.", + "minLength": 1, + "type": "string" + }, + "type": { + "description": "type of the condition being reported.\nCurrently, only \"Accepted\" is supported.", + "enum": [ + "Accepted" + ], + "minLength": 1, + "type": "string" + } + }, + "required": [ + "lastTransitionTime", + "status", + "type" + ], + "type": "object" + }, + "type": "array", + "x-kubernetes-list-map-keys": [ + "type" + ], + "x-kubernetes-list-type": "map" + }, + "group": { + "description": "group defines the group of the referenced resource.", + "enum": [ + "monitoring.coreos.com" + ], + "type": "string" + }, + "name": { + "description": "name defines the name of the referenced object.", + "minLength": 1, + "type": "string" + }, + "namespace": { + "description": "namespace defines the namespace of the referenced object.", + "minLength": 1, + "type": "string" + }, + "resource": { + "description": "resource defines the type of resource being referenced (e.g. Prometheus, PrometheusAgent, ThanosRuler or Alertmanager).", + "enum": [ + "prometheuses", + "prometheusagents", + "thanosrulers", + "alertmanagers" + ], + "type": "string" + } + }, + "required": [ + "group", + "name", + "namespace", + "resource" + ], + "type": "object" + }, + "type": "array", + "x-kubernetes-list-map-keys": [ + "group", + "resource", + "name", + "namespace" + ], + "x-kubernetes-list-type": "map" + } + }, + "type": "object" } }, "required": [ @@ -10978,7 +11202,10 @@ } }, "served": true, - "storage": true + "storage": true, + "subresources": { + "status": {} + } } ] } diff --git a/jsonnet/prometheus-operator/alertmanagerconfigs-v1beta1-crd.libsonnet b/jsonnet/prometheus-operator/alertmanagerconfigs-v1beta1-crd.libsonnet index df05e53a50c..8dd65b157b2 100644 --- a/jsonnet/prometheus-operator/alertmanagerconfigs-v1beta1-crd.libsonnet +++ b/jsonnet/prometheus-operator/alertmanagerconfigs-v1beta1-crd.libsonnet @@ -2492,6 +2492,7 @@ }, apiURL: { description: 'apiURL defines the URL to send OpsGenie API requests to.\nWhen not specified, defaults to the standard OpsGenie API endpoint.', + pattern: '^https?://.+$', type: 'string', }, description: { @@ -3236,22 +3237,27 @@ properties: { class: { description: 'class defines the class/type of the event.', + minLength: 1, type: 'string', }, client: { description: 'client defines the client identification.', + minLength: 1, type: 'string', }, clientURL: { description: 'clientURL defines the backlink to the sender of notification.', + pattern: '^https?://.+$', type: 'string', }, component: { description: 'component defines the part or component of the affected system that is broken.', + minLength: 1, type: 'string', }, description: { description: 'description of the incident.', + minLength: 1, type: 'string', }, details: { @@ -3276,9 +3282,11 @@ type: 'object', }, type: 'array', + 'x-kubernetes-list-type': 'atomic', }, group: { description: 'group defines a cluster or grouping of sources.', + minLength: 1, type: 'string', }, httpConfig: { @@ -3926,20 +3934,24 @@ properties: { alt: { description: 'alt is the optional alternative text for the image.', + minLength: 1, type: 'string', }, href: { description: 'href defines the optional URL; makes the image a clickable link.', + pattern: '^https?://.+$', type: 'string', }, src: { description: 'src of the image being attached to the incident', + minLength: 1, type: 'string', }, }, type: 'object', }, type: 'array', + 'x-kubernetes-list-type': 'atomic', }, pagerDutyLinkConfigs: { description: 'pagerDutyLinkConfigs defines a list of link details to attach that provide further detail about an incident.', @@ -3948,16 +3960,19 @@ properties: { alt: { description: "alt defines the text that describes the purpose of the link, and can be used as the link's text.", + minLength: 1, type: 'string', }, href: { description: 'href defines the URL of the link to be attached', + pattern: '^https?://.+$', type: 'string', }, }, type: 'object', }, type: 'array', + 'x-kubernetes-list-type': 'atomic', }, routingKey: { description: "routingKey defines the secret's key that contains the PagerDuty integration key (when using\nEvents API v2). Either this field or `serviceKey` needs to be defined.\nThe secret needs to be in the same namespace as the AlertmanagerConfig\nobject and accessible by the Prometheus Operator.", @@ -4005,14 +4020,22 @@ }, severity: { description: 'severity of the incident.', + minLength: 1, type: 'string', }, source: { description: 'source defines the unique location of the affected system.', + minLength: 1, + type: 'string', + }, + timeout: { + description: 'timeout is the maximum time allowed to invoke the pagerduty\nIt requires Alertmanager >= v0.30.0.', + pattern: '^(0|(([0-9]+)y)?(([0-9]+)w)?(([0-9]+)d)?(([0-9]+)h)?(([0-9]+)m)?(([0-9]+)s)?(([0-9]+)ms)?)$', type: 'string', }, url: { description: 'url defines the URL to send requests to.', + pattern: '^https?://.+$', type: 'string', }, }, @@ -4027,6 +4050,7 @@ properties: { device: { description: "device defines the name of a specific device to send the notification to.\nIf not specified, the notification is sent to all user's devices.", + minLength: 1, type: 'string', }, expire: { @@ -4035,7 +4059,7 @@ type: 'string', }, html: { - description: 'html defines whether notification message is HTML or plain text.\nWhen true, the message can include HTML formatting tags.', + description: 'html defines whether notification message is HTML or plain text.\nWhen true, the message can include HTML formatting tags.\nhtml and monospace formatting are mutually exclusive.', type: 'boolean', }, httpConfig: { @@ -4678,6 +4702,7 @@ }, message: { description: 'message defines the notification message content.\nThis is the main body text of the Pushover notification.', + minLength: 1, type: 'string', }, monospace: { @@ -4686,6 +4711,7 @@ }, priority: { description: 'priority defines the notification priority level.\nSee https://pushover.net/api#priority for valid values and behavior.', + minLength: 1, type: 'string', }, retry: { @@ -4699,10 +4725,12 @@ }, sound: { description: "sound defines the name of one of the sounds supported by device clients.\nThis overrides the user's default sound choice for this notification.", + minLength: 1, type: 'string', }, title: { description: 'title defines the notification title displayed in the Pushover message.\nThis appears as the bold header text in the notification.', + minLength: 1, type: 'string', }, token: { @@ -4736,10 +4764,12 @@ }, url: { description: 'url defines a supplementary URL shown alongside the message.\nThis creates a clickable link within the Pushover notification.', + pattern: '^https?://.+$', type: 'string', }, urlTitle: { description: 'urlTitle defines a title for the supplementary URL.\nIf not specified, the raw URL is shown instead.', + minLength: 1, type: 'string', }, userKey: { @@ -5597,10 +5627,12 @@ properties: { dismissText: { description: 'dismissText defines the label for the cancel button in the dialog.\nWhen not specified, defaults to "Cancel". This button cancels the action.', + minLength: 1, type: 'string', }, okText: { description: 'okText defines the label for the confirmation button in the dialog.\nWhen not specified, defaults to "Okay". This button proceeds with the action.', + minLength: 1, type: 'string', }, text: { @@ -5610,6 +5642,7 @@ }, title: { description: 'title defines the title text displayed at the top of the confirmation dialog.\nWhen not specified, a default title will be used.', + minLength: 1, type: 'string', }, }, @@ -5620,10 +5653,12 @@ }, name: { description: 'name defines a unique identifier for the action within the message.\nThis value is sent back to your application when the action is triggered.', + minLength: 1, type: 'string', }, style: { description: 'style defines the visual appearance of the action element.\nValid values include "default", "primary" (green), and "danger" (red).', + minLength: 1, type: 'string', }, text: { @@ -5638,10 +5673,12 @@ }, url: { description: 'url defines the URL to open when the action is triggered.\nOnly applicable for button-type actions. When set, clicking the button opens this URL.', + pattern: '^https?://.+$', type: 'string', }, value: { description: 'value defines the payload sent when the action is triggered.\nThis data is included in the callback sent to your application.', + minLength: 1, type: 'string', }, }, @@ -5651,7 +5688,9 @@ ], type: 'object', }, + minItems: 1, type: 'array', + 'x-kubernetes-list-type': 'atomic', }, apiURL: { description: "apiURL defines the secret's key that contains the Slack webhook URL.\nThe secret needs to be in the same namespace as the AlertmanagerConfig\nobject and accessible by the Prometheus Operator.", @@ -5675,18 +5714,22 @@ }, callbackId: { description: 'callbackId defines an identifier for the message used in interactive components.', + minLength: 1, type: 'string', }, channel: { description: 'channel defines the channel or user to send notifications to.', + minLength: 1, type: 'string', }, color: { description: 'color defines the color of the left border of the Slack message attachment.\nCan be a hex color code (e.g., "#ff0000") or a predefined color name.', + minLength: 1, type: 'string', }, fallback: { description: "fallback defines a plain-text summary of the attachment for clients that don't support attachments.", + minLength: 1, type: 'string', }, fields: { @@ -5715,10 +5758,13 @@ ], type: 'object', }, + minItems: 1, type: 'array', + 'x-kubernetes-list-type': 'atomic', }, footer: { description: 'footer defines small text displayed at the bottom of the message attachment.', + minLength: 1, type: 'string', }, httpConfig: { @@ -6361,14 +6407,17 @@ }, iconEmoji: { description: "iconEmoji defines the emoji to use as the bot's avatar (e.g., \":ghost:\").", + minLength: 1, type: 'string', }, iconURL: { description: "iconURL defines the URL to an image to use as the bot's avatar.", + pattern: '^https?://.+$', type: 'string', }, imageURL: { description: 'imageURL defines the URL to an image file that will be displayed inside the message attachment.', + pattern: '^https?://.+$', type: 'string', }, linkNames: { @@ -6378,12 +6427,16 @@ mrkdwnIn: { description: 'mrkdwnIn defines which fields should be parsed as Slack markdown.\nValid values include "pretext", "text", and "fields".', items: { + minLength: 1, type: 'string', }, + minItems: 1, type: 'array', + 'x-kubernetes-list-type': 'atomic', }, pretext: { description: 'pretext defines optional text that appears above the message attachment block.', + minLength: 1, type: 'string', }, sendResolved: { @@ -6396,22 +6449,32 @@ }, text: { description: 'text defines the main text content of the Slack message attachment.', + minLength: 1, type: 'string', }, thumbURL: { description: 'thumbURL defines the URL to an image file that will be displayed as a thumbnail\non the right side of the message attachment.', + pattern: '^https?://.+$', + type: 'string', + }, + timeout: { + description: 'timeout defines the maximum time to wait for a webhook request to complete,\nbefore failing the request and allowing it to be retried.\nIt requires Alertmanager >= v0.30.0.', + pattern: '^(0|(([0-9]+)y)?(([0-9]+)w)?(([0-9]+)d)?(([0-9]+)h)?(([0-9]+)m)?(([0-9]+)s)?(([0-9]+)ms)?)$', type: 'string', }, title: { description: 'title defines the title text displayed in the Slack message attachment.', + minLength: 1, type: 'string', }, titleLink: { description: 'titleLink defines the URL that the title will link to when clicked.', + pattern: '^https?://.+$', type: 'string', }, username: { description: 'username defines the slack bot user name.', + minLength: 1, type: 'string', }, }, @@ -7177,6 +7240,7 @@ properties: { apiURL: { description: 'apiURL defines the Telegram API URL, e.g. https://api.telegram.org.\nIf not specified, the default Telegram API URL will be used.', + pattern: '^https?://.+$', type: 'string', }, botToken: { @@ -7907,6 +7971,7 @@ }, apiUrl: { description: 'apiUrl defines the VictorOps API URL.\nWhen not specified, defaults to the standard VictorOps API endpoint.', + pattern: '^https?://.+$', type: 'string', }, customFields: { @@ -7931,9 +7996,11 @@ type: 'object', }, type: 'array', + 'x-kubernetes-list-type': 'atomic', }, entityDisplayName: { description: 'entityDisplayName contains a summary of the alerted problem.\nThis appears as the main title or identifier for the incident.', + minLength: 1, type: 'string', }, httpConfig: { @@ -8576,14 +8643,17 @@ }, messageType: { description: 'messageType describes the behavior of the alert.\nValid values are "CRITICAL", "WARNING", and "INFO".', + minLength: 1, type: 'string', }, monitoringTool: { description: 'monitoringTool defines the monitoring tool the state message is from.\nThis helps identify the source system that generated the alert.', + minLength: 1, type: 'string', }, routingKey: { description: 'routingKey defines a key used to map the alert to a team.\nThis determines which VictorOps team will receive the alert notification.', + minLength: 1, type: 'string', }, sendResolved: { @@ -8592,9 +8662,13 @@ }, stateMessage: { description: 'stateMessage contains a long explanation of the alerted problem.\nThis provides detailed context about the incident.', + minLength: 1, type: 'string', }, }, + required: [ + 'routingKey', + ], type: 'object', }, type: 'array', @@ -9928,6 +10002,7 @@ }, url: { description: 'url defines the URL to send HTTP POST requests to.\nurlSecret takes precedence over url. One of urlSecret and url should be defined.', + pattern: '^https?://.+$', type: 'string', }, urlSecret: { @@ -9986,6 +10061,7 @@ }, apiURL: { description: 'apiURL defines the WeChat API URL.\nWhen not specified, defaults to the standard WeChat Work API endpoint.', + pattern: '^https?://.+$', type: 'string', }, corpID: { @@ -10852,6 +10928,112 @@ }, type: 'object', }, + status: { + description: 'status defines the status subresource. It is under active development and is updated only when the\n"StatusForConfigurationResources" feature gate is enabled.\n\nMost recent observed status of the ServiceMonitor. Read-only.\nMore info:\nhttps://github.com/kubernetes/community/blob/master/contributors/devel/sig-architecture/api-conventions.md#spec-and-status', + properties: { + bindings: { + description: 'bindings defines the list of workload resources (Prometheus, PrometheusAgent, ThanosRuler or Alertmanager) which select the configuration resource.', + items: { + description: 'WorkloadBinding is a link between a configuration resource and a workload resource.', + properties: { + conditions: { + description: 'conditions defines the current state of the configuration resource when bound to the referenced Workload object.', + items: { + description: 'ConfigResourceCondition describes the status of configuration resources linked to Prometheus, PrometheusAgent, Alertmanager or ThanosRuler.', + properties: { + lastTransitionTime: { + description: 'lastTransitionTime defines the time of the last update to the current status property.', + format: 'date-time', + type: 'string', + }, + message: { + description: "message defines the human-readable message indicating details for the condition's last transition.", + type: 'string', + }, + observedGeneration: { + description: 'observedGeneration defines the .metadata.generation that the\ncondition was set based upon. For instance, if `.metadata.generation` is\ncurrently 12, but the `.status.conditions[].observedGeneration` is 9, the\ncondition is out of date with respect to the current state of the object.', + format: 'int64', + type: 'integer', + }, + reason: { + description: "reason for the condition's last transition.", + type: 'string', + }, + status: { + description: 'status of the condition.', + minLength: 1, + type: 'string', + }, + type: { + description: 'type of the condition being reported.\nCurrently, only "Accepted" is supported.', + enum: [ + 'Accepted', + ], + minLength: 1, + type: 'string', + }, + }, + required: [ + 'lastTransitionTime', + 'status', + 'type', + ], + type: 'object', + }, + type: 'array', + 'x-kubernetes-list-map-keys': [ + 'type', + ], + 'x-kubernetes-list-type': 'map', + }, + group: { + description: 'group defines the group of the referenced resource.', + enum: [ + 'monitoring.coreos.com', + ], + type: 'string', + }, + name: { + description: 'name defines the name of the referenced object.', + minLength: 1, + type: 'string', + }, + namespace: { + description: 'namespace defines the namespace of the referenced object.', + minLength: 1, + type: 'string', + }, + resource: { + description: 'resource defines the type of resource being referenced (e.g. Prometheus, PrometheusAgent, ThanosRuler or Alertmanager).', + enum: [ + 'prometheuses', + 'prometheusagents', + 'thanosrulers', + 'alertmanagers', + ], + type: 'string', + }, + }, + required: [ + 'group', + 'name', + 'namespace', + 'resource', + ], + type: 'object', + }, + type: 'array', + 'x-kubernetes-list-map-keys': [ + 'group', + 'resource', + 'name', + 'namespace', + ], + 'x-kubernetes-list-type': 'map', + }, + }, + type: 'object', + }, }, required: [ 'spec', @@ -10861,5 +11043,8 @@ }, served: true, storage: false, + subresources: { + status: {}, + }, }, ] } } diff --git a/jsonnet/prometheus-operator/alertmanagers-crd.json b/jsonnet/prometheus-operator/alertmanagers-crd.json index 4d33aac2f13..b2f83691158 100644 --- a/jsonnet/prometheus-operator/alertmanagers-crd.json +++ b/jsonnet/prometheus-operator/alertmanagers-crd.json @@ -4,7 +4,7 @@ "metadata": { "annotations": { "controller-gen.kubebuilder.io/version": "v0.19.0", - "operator.prometheus.io/version": "0.87.1" + "operator.prometheus.io/version": "0.88.0" }, "name": "alertmanagers.monitoring.coreos.com" }, @@ -2065,7 +2065,7 @@ "type": "object" }, "webex": { - "description": "webex defines the default configuration for Jira.", + "description": "webex defines the default configuration for Webex.", "properties": { "apiURL": { "description": "apiURL defines the is the default Webex API URL.\n\nIt requires Alertmanager >= v0.25.0.", @@ -5429,7 +5429,7 @@ "type": "string" }, "minReadySeconds": { - "description": "minReadySeconds defines the minimum number of seconds for which a newly created pod should be ready\nwithout any of its container crashing for it to be considered available.\n\nIf unset, pods will be considered available as soon as they are ready.", + "description": "minReadySeconds defines the minimum number of seconds for which a newly\ncreated pod should be ready without any of its container crashing for it\nto be considered available.\n\nIf unset, pods will be considered available as soon as they are ready.\n\nWhen the Alertmanager version is greater than or equal to v0.30.0, the\nduration is also used to delay the first flush of the aggregation\ngroups. This delay helps ensuring that all alerts have been resent by\nthe Prometheus instances to Alertmanager after a roll-out. It is\npossible to override this behavior passing a custom value via\n`.spec.additionalArgs`.", "format": "int32", "minimum": 0, "type": "integer" @@ -5459,6 +5459,14 @@ }, "type": "object" }, + "podManagementPolicy": { + "description": "podManagementPolicy defines the policy for creating/deleting pods when\nscaling up and down.\n\nUnlike the default StatefulSet behavior, the default policy is\n`Parallel` to avoid manual intervention in case a pod gets stuck during\na rollout.\n\nNote that updating this value implies the recreation of the StatefulSet\nwhich incurs a service outage.", + "enum": [ + "OrderedReady", + "Parallel" + ], + "type": "string" + }, "podMetadata": { "description": "podMetadata defines labels and annotations which are propagated to the Alertmanager pods.\n\nThe following items are reserved and cannot be overridden:\n* \"alertmanager\" label, set to the name of the Alertmanager instance.\n* \"app.kubernetes.io/instance\" label, set to the name of the Alertmanager instance.\n* \"app.kubernetes.io/managed-by\" label, set to \"prometheus-operator\".\n* \"app.kubernetes.io/name\" label, set to \"alertmanager\".\n* \"app.kubernetes.io/version\" label, set to the Alertmanager version.\n* \"kubectl.kubernetes.io/default-container\" annotation, set to \"alertmanager\".", "properties": { @@ -6410,6 +6418,47 @@ }, "type": "array" }, + "updateStrategy": { + "description": "updateStrategy indicates the strategy that will be employed to update\nPods in the StatefulSet when a revision is made to statefulset's Pod\nTemplate.\n\nThe default strategy is RollingUpdate.", + "properties": { + "rollingUpdate": { + "description": "rollingUpdate is used to communicate parameters when type is RollingUpdate.", + "properties": { + "maxUnavailable": { + "anyOf": [ + { + "type": "integer" + }, + { + "type": "string" + } + ], + "description": "maxUnavailable is the maximum number of pods that can be unavailable\nduring the update. The value can be an absolute number (ex: 5) or a\npercentage of desired pods (ex: 10%). Absolute number is calculated from\npercentage by rounding up. This can not be 0. Defaults to 1. This field\nis alpha-level and is only honored by servers that enable the\nMaxUnavailableStatefulSet feature. The field applies to all pods in the\nrange 0 to Replicas-1. That means if there is any unavailable pod in\nthe range 0 to Replicas-1, it will be counted towards MaxUnavailable.", + "x-kubernetes-int-or-string": true + } + }, + "type": "object" + }, + "type": { + "description": "type indicates the type of the StatefulSetUpdateStrategy.\n\nDefault is RollingUpdate.", + "enum": [ + "OnDelete", + "RollingUpdate" + ], + "type": "string" + } + }, + "required": [ + "type" + ], + "type": "object", + "x-kubernetes-validations": [ + { + "message": "rollingUpdate requires type to be RollingUpdate", + "rule": "!(self.type != 'RollingUpdate' && has(self.rollingUpdate))" + } + ] + }, "version": { "description": "version the cluster should be on.", "type": "string" diff --git a/jsonnet/prometheus-operator/podmonitors-crd.json b/jsonnet/prometheus-operator/podmonitors-crd.json index 6473c801997..5e23edf3fc8 100644 --- a/jsonnet/prometheus-operator/podmonitors-crd.json +++ b/jsonnet/prometheus-operator/podmonitors-crd.json @@ -4,7 +4,7 @@ "metadata": { "annotations": { "controller-gen.kubebuilder.io/version": "v0.19.0", - "operator.prometheus.io/version": "0.87.1" + "operator.prometheus.io/version": "0.88.0" }, "name": "podmonitors.monitoring.coreos.com" }, @@ -1004,6 +1004,10 @@ "description": "scrapeClassicHistograms defines whether to scrape a classic histogram that is also exposed as a native histogram.\nIt requires Prometheus >= v2.45.0.\n\nNotice: `scrapeClassicHistograms` corresponds to the `always_scrape_classic_histograms` field in the Prometheus configuration.", "type": "boolean" }, + "scrapeNativeHistograms": { + "description": "scrapeNativeHistograms defines whether to enable scraping of native histograms.\nIt requires Prometheus >= v3.8.0.", + "type": "boolean" + }, "scrapeProtocols": { "description": "scrapeProtocols defines the protocols to negotiate during a scrape. It tells clients the\nprotocols supported by Prometheus in order of preference (from most to least preferred).\n\nIf unset, Prometheus uses its default value.\n\nIt requires Prometheus >= v2.49.0.", "items": { diff --git a/jsonnet/prometheus-operator/probes-crd.json b/jsonnet/prometheus-operator/probes-crd.json index 94c26ad5110..379a45112bd 100644 --- a/jsonnet/prometheus-operator/probes-crd.json +++ b/jsonnet/prometheus-operator/probes-crd.json @@ -4,7 +4,7 @@ "metadata": { "annotations": { "controller-gen.kubebuilder.io/version": "v0.19.0", - "operator.prometheus.io/version": "0.87.1" + "operator.prometheus.io/version": "0.88.0" }, "name": "probes.monitoring.coreos.com" }, @@ -45,7 +45,7 @@ "description": "spec defines the specification of desired Ingress selection for target discovery by Prometheus.", "properties": { "authorization": { - "description": "authorization section for this endpoint", + "description": "authorization configures the Authorization header credentials used by\nthe client.\n\nCannot be set at the same time as `basicAuth`, `bearerTokenSecret` or `oauth2`.", "properties": { "credentials": { "description": "credentials defines a key of a Secret in the namespace that contains the credentials for authentication.", @@ -78,7 +78,7 @@ "type": "object" }, "basicAuth": { - "description": "basicAuth allow an endpoint to authenticate over basic authentication.\nMore info: https://prometheus.io/docs/operating/configuration/#endpoint", + "description": "basicAuth defines the Basic Authentication credentials used by the\nclient.\n\nCannot be set at the same time as `authorization`, `bearerTokenSecret` or `oauth2`.", "properties": { "password": { "description": "password defines a key of a Secret containing the password for\nauthentication.", @@ -130,7 +130,7 @@ "type": "object" }, "bearerTokenSecret": { - "description": "bearerTokenSecret defines the secret to mount to read bearer token for scraping targets. The secret\nneeds to be in the same namespace as the probe and accessible by\nthe Prometheus Operator.", + "description": "bearerTokenSecret defines a key of a Secret containing the bearer token\nused by the client for authentication. The secret needs to be in the\nsame namespace as the custom resource and readable by the Prometheus\nOperator.\n\nCannot be set at the same time as `authorization`, `basicAuth` or `oauth2`.\n\nDeprecated: use `authorization` instead.", "properties": { "key": { "description": "The key of the secret to select from. Must be a valid secret key.", @@ -156,6 +156,10 @@ "description": "convertClassicHistogramsToNHCB defines whether to convert all scraped classic histograms into a native histogram with custom buckets.\nIt requires Prometheus >= v3.0.0.", "type": "boolean" }, + "enableHttp2": { + "description": "enableHttp2 can be used to disable HTTP2.", + "type": "boolean" + }, "fallbackScrapeProtocol": { "description": "fallbackScrapeProtocol defines the protocol to use if a scrape returns blank, unparseable, or otherwise invalid Content-Type.\n\nIt requires Prometheus >= v3.0.0.", "enum": [ @@ -167,6 +171,10 @@ ], "type": "string" }, + "followRedirects": { + "description": "followRedirects defines whether the client should follow HTTP 3xx\nredirects.", + "type": "boolean" + }, "interval": { "description": "interval at which targets are probed using the configured prober.\nIf not specified Prometheus' global scrape interval is used.", "pattern": "^(0|(([0-9]+)y)?(([0-9]+)w)?(([0-9]+)d)?(([0-9]+)h)?(([0-9]+)m)?(([0-9]+)s)?(([0-9]+)ms)?)$", @@ -287,7 +295,7 @@ "x-kubernetes-int-or-string": true }, "oauth2": { - "description": "oauth2 for the URL. Only valid in Prometheus versions 2.27.0 and newer.", + "description": "oauth2 defines the OAuth2 settings used by the client.\n\nIt requires Prometheus >= 2.27.0.\n\nCannot be set at the same time as `authorization`, `basicAuth` or `bearerTokenSecret`.", "properties": { "clientId": { "description": "clientId defines a key of a Secret or ConfigMap containing the\nOAuth2 client's ID.", @@ -715,6 +723,10 @@ "description": "scrapeClassicHistograms defines whether to scrape a classic histogram that is also exposed as a native histogram.\nIt requires Prometheus >= v2.45.0.\n\nNotice: `scrapeClassicHistograms` corresponds to the `always_scrape_classic_histograms` field in the Prometheus configuration.", "type": "boolean" }, + "scrapeNativeHistograms": { + "description": "scrapeNativeHistograms defines whether to enable scraping of native histograms.\nIt requires Prometheus >= v3.8.0.", + "type": "boolean" + }, "scrapeProtocols": { "description": "scrapeProtocols defines the protocols to negotiate during a scrape. It tells clients the\nprotocols supported by Prometheus in order of preference (from most to least preferred).\n\nIf unset, Prometheus uses its default value.\n\nIt requires Prometheus >= v2.49.0.", "items": { @@ -972,7 +984,7 @@ "type": "object" }, "tlsConfig": { - "description": "tlsConfig defines the TLS configuration to use when scraping the endpoint.", + "description": "tlsConfig defines the TLS configuration used by the client.", "properties": { "ca": { "description": "ca defines the Certificate authority used when verifying server certificates.", diff --git a/jsonnet/prometheus-operator/prometheus-operator.libsonnet b/jsonnet/prometheus-operator/prometheus-operator.libsonnet index 46d2adb6bb1..3dece63ef10 100644 --- a/jsonnet/prometheus-operator/prometheus-operator.libsonnet +++ b/jsonnet/prometheus-operator/prometheus-operator.libsonnet @@ -197,6 +197,8 @@ function(params) { args: [ '--kubelet-service=' + po.config.kubeletService, '--prometheus-config-reloader=' + po.config.configReloaderImage, + '--watch-referenced-objects-in-all-namespaces=true', + '--disable-unmanaged-prometheus-configuration=true', ] + [std.format('--kubelet-endpoints=%s', po.config.kubeletEndpointsEnabled)] + [std.format('--kubelet-endpointslice=%s', po.config.kubeletEndpointSliceEnabled)] + diff --git a/jsonnet/prometheus-operator/prometheusagents-crd.json b/jsonnet/prometheus-operator/prometheusagents-crd.json index 15bd6947784..b6cc7e9804a 100644 --- a/jsonnet/prometheus-operator/prometheusagents-crd.json +++ b/jsonnet/prometheus-operator/prometheusagents-crd.json @@ -4,7 +4,7 @@ "metadata": { "annotations": { "controller-gen.kubebuilder.io/version": "v0.19.0", - "operator.prometheus.io/version": "0.87.1" + "operator.prometheus.io/version": "0.88.0" }, "name": "prometheusagents.monitoring.coreos.com" }, @@ -4330,6 +4330,14 @@ }, "type": "object" }, + "podManagementPolicy": { + "description": "podManagementPolicy defines the policy for creating/deleting pods when\nscaling up and down.\n\nUnlike the default StatefulSet behavior, the default policy is\n`Parallel` to avoid manual intervention in case a pod gets stuck during\na rollout.\n\nNote that updating this value implies the recreation of the StatefulSet\nwhich incurs a service outage.", + "enum": [ + "OrderedReady", + "Parallel" + ], + "type": "string" + }, "podMetadata": { "description": "podMetadata defines labels and annotations which are propagated to the Prometheus pods.\n\nThe following items are reserved and cannot be overridden:\n* \"prometheus\" label, set to the name of the Prometheus object.\n* \"app.kubernetes.io/instance\" label, set to the name of the Prometheus object.\n* \"app.kubernetes.io/managed-by\" label, set to \"prometheus-operator\".\n* \"app.kubernetes.io/name\" label, set to \"prometheus\".\n* \"app.kubernetes.io/version\" label, set to the Prometheus version.\n* \"operator.prometheus.io/name\" label, set to the name of the Prometheus object.\n* \"operator.prometheus.io/shard\" label, set to the shard number of the Prometheus object.\n* \"kubectl.kubernetes.io/default-container\" annotation, set to \"prometheus\".", "properties": { @@ -4617,7 +4625,7 @@ "type": "string" }, "managedIdentity": { - "description": "managedIdentity defines the Azure User-assigned Managed identity.\nCannot be set at the same time as `oauth` or `sdk`.", + "description": "managedIdentity defines the Azure User-assigned Managed identity.\nCannot be set at the same time as `oauth`, `sdk` or `workloadIdentity`.", "properties": { "clientId": { "description": "clientId defines the Azure User-assigned Managed identity.\n\nFor Prometheus >= 3.5.0 and Thanos >= 0.40.0, this field is allowed to be empty to support system-assigned managed identities.", @@ -4628,7 +4636,7 @@ "type": "object" }, "oauth": { - "description": "oauth defines the oauth config that is being used to authenticate.\nCannot be set at the same time as `managedIdentity` or `sdk`.\n\nIt requires Prometheus >= v2.48.0 or Thanos >= v0.31.0.", + "description": "oauth defines the oauth config that is being used to authenticate.\nCannot be set at the same time as `managedIdentity`, `sdk` or `workloadIdentity`.\n\nIt requires Prometheus >= v2.48.0 or Thanos >= v0.31.0.", "properties": { "clientId": { "description": "clientId defines the clientId of the Azure Active Directory application that is being used to authenticate.", @@ -4672,8 +4680,13 @@ ], "type": "object" }, + "scope": { + "description": "scope is the custom OAuth 2.0 scope to request when acquiring tokens.\nIt requires Prometheus >= 3.9.0. Currently not supported by Thanos.", + "pattern": "^[\\w\\s:/.\\\\-]+$", + "type": "string" + }, "sdk": { - "description": "sdk defines the Azure SDK config that is being used to authenticate.\nSee https://learn.microsoft.com/en-us/azure/developer/go/azure-sdk-authentication\nCannot be set at the same time as `oauth` or `managedIdentity`.\n\nIt requires Prometheus >= v2.52.0 or Thanos >= v0.36.0.", + "description": "sdk defines the Azure SDK config that is being used to authenticate.\nSee https://learn.microsoft.com/en-us/azure/developer/go/azure-sdk-authentication\nCannot be set at the same time as `oauth`, `managedIdentity` or `workloadIdentity`.\n\nIt requires Prometheus >= v2.52.0 or Thanos >= v0.36.0.", "properties": { "tenantId": { "description": "tenantId defines the tenant ID of the azure active directory application that is being used to authenticate.", @@ -4682,6 +4695,26 @@ } }, "type": "object" + }, + "workloadIdentity": { + "description": "workloadIdentity defines the Azure Workload Identity authentication.\nCannot be set at the same time as `oauth`, `managedIdentity`, or `sdk`.\n\nIt requires Prometheus >= 3.7.0. Currently not supported by Thanos.", + "properties": { + "clientId": { + "description": "clientId is the clientID of the Azure Active Directory application.", + "minLength": 1, + "type": "string" + }, + "tenantId": { + "description": "tenantId is the tenant ID of the Azure Active Directory application.", + "minLength": 1, + "type": "string" + } + }, + "required": [ + "clientId", + "tenantId" + ], + "type": "object" } }, "type": "object" @@ -6140,6 +6173,10 @@ "pattern": "^(0|(([0-9]+)y)?(([0-9]+)w)?(([0-9]+)d)?(([0-9]+)h)?(([0-9]+)m)?(([0-9]+)s)?(([0-9]+)ms)?)$", "type": "string" }, + "scrapeNativeHistograms": { + "description": "scrapeNativeHistograms defines whether to enable scraping of native histograms.\nIt requires Prometheus >= v3.8.0.", + "type": "boolean" + }, "scrapeProtocols": { "description": "scrapeProtocols defines the protocols to negotiate during a scrape. It tells clients the\nprotocols supported by Prometheus in order of preference (from most to least preferred).\n\nIf unset, Prometheus uses its default value.\n\nIt requires Prometheus >= v2.49.0.\n\n`PrometheusText1.0.0` requires Prometheus >= v3.0.0.", "items": { @@ -7113,17 +7150,20 @@ "description": "tracingConfig defines tracing in Prometheus.\n\nThis is an *experimental feature*, it may change in any upcoming release\nin a breaking way.", "properties": { "clientType": { - "description": "clientType defines the client used to export the traces. Supported values are `http` or `grpc`.", + "description": "clientType defines the client used to export the traces. Supported values are `HTTP` and `GRPC`.", "enum": [ "http", - "grpc" + "grpc", + "HTTP", + "GRPC" ], "type": "string" }, "compression": { - "description": "compression key for supported compression types. The only supported value is `gzip`.", + "description": "compression key for supported compression types. The only supported value is `Gzip`.", "enum": [ - "gzip" + "gzip", + "Gzip" ], "type": "string" }, @@ -7351,6 +7391,47 @@ }, "type": "object" }, + "updateStrategy": { + "description": "updateStrategy indicates the strategy that will be employed to update\nPods in the StatefulSet when a revision is made to statefulset's Pod\nTemplate.\n\nThe default strategy is RollingUpdate.", + "properties": { + "rollingUpdate": { + "description": "rollingUpdate is used to communicate parameters when type is RollingUpdate.", + "properties": { + "maxUnavailable": { + "anyOf": [ + { + "type": "integer" + }, + { + "type": "string" + } + ], + "description": "maxUnavailable is the maximum number of pods that can be unavailable\nduring the update. The value can be an absolute number (ex: 5) or a\npercentage of desired pods (ex: 10%). Absolute number is calculated from\npercentage by rounding up. This can not be 0. Defaults to 1. This field\nis alpha-level and is only honored by servers that enable the\nMaxUnavailableStatefulSet feature. The field applies to all pods in the\nrange 0 to Replicas-1. That means if there is any unavailable pod in\nthe range 0 to Replicas-1, it will be counted towards MaxUnavailable.", + "x-kubernetes-int-or-string": true + } + }, + "type": "object" + }, + "type": { + "description": "type indicates the type of the StatefulSetUpdateStrategy.\n\nDefault is RollingUpdate.", + "enum": [ + "OnDelete", + "RollingUpdate" + ], + "type": "string" + } + }, + "required": [ + "type" + ], + "type": "object", + "x-kubernetes-validations": [ + { + "message": "rollingUpdate requires type to be RollingUpdate", + "rule": "!(self.type != 'RollingUpdate' && has(self.rollingUpdate))" + } + ] + }, "version": { "description": "version of Prometheus being deployed. The operator uses this information\nto generate the Prometheus StatefulSet + configuration files.\n\nIf not specified, the operator assumes the latest upstream version of\nPrometheus available at the time when the version of the operator was\nreleased.", "type": "string" @@ -9126,6 +9207,26 @@ { "message": "probeSelector cannot be set when mode is DaemonSet", "rule": "!(has(self.mode) && self.mode == 'DaemonSet' && has(self.probeSelector))" + }, + { + "message": "scrapeConfigNamespaceSelector cannot be set when mode is DaemonSet", + "rule": "!(has(self.mode) && self.mode == 'DaemonSet' && has(self.scrapeConfigNamespaceSelector))" + }, + { + "message": "probeNamespaceSelector cannot be set when mode is DaemonSet", + "rule": "!(has(self.mode) && self.mode == 'DaemonSet' && has(self.probeNamespaceSelector))" + }, + { + "message": "serviceMonitorSelector cannot be set when mode is DaemonSet", + "rule": "!(has(self.mode) && self.mode == 'DaemonSet' && has(self.serviceMonitorSelector))" + }, + { + "message": "serviceMonitorNamespaceSelector cannot be set when mode is DaemonSet", + "rule": "!(has(self.mode) && self.mode == 'DaemonSet' && has(self.serviceMonitorNamespaceSelector))" + }, + { + "message": "additionalScrapeConfigs cannot be set when mode is DaemonSet", + "rule": "!(has(self.mode) && self.mode == 'DaemonSet' && has(self.additionalScrapeConfigs))" } ] }, diff --git a/jsonnet/prometheus-operator/prometheuses-crd.json b/jsonnet/prometheus-operator/prometheuses-crd.json index 20269972d18..b5c15e3aa46 100644 --- a/jsonnet/prometheus-operator/prometheuses-crd.json +++ b/jsonnet/prometheus-operator/prometheuses-crd.json @@ -4,7 +4,7 @@ "metadata": { "annotations": { "controller-gen.kubebuilder.io/version": "v0.19.0", - "operator.prometheus.io/version": "0.87.1" + "operator.prometheus.io/version": "0.88.0" }, "name": "prometheuses.monitoring.coreos.com" }, @@ -4990,6 +4990,14 @@ }, "type": "object" }, + "podManagementPolicy": { + "description": "podManagementPolicy defines the policy for creating/deleting pods when\nscaling up and down.\n\nUnlike the default StatefulSet behavior, the default policy is\n`Parallel` to avoid manual intervention in case a pod gets stuck during\na rollout.\n\nNote that updating this value implies the recreation of the StatefulSet\nwhich incurs a service outage.", + "enum": [ + "OrderedReady", + "Parallel" + ], + "type": "string" + }, "podMetadata": { "description": "podMetadata defines labels and annotations which are propagated to the Prometheus pods.\n\nThe following items are reserved and cannot be overridden:\n* \"prometheus\" label, set to the name of the Prometheus object.\n* \"app.kubernetes.io/instance\" label, set to the name of the Prometheus object.\n* \"app.kubernetes.io/managed-by\" label, set to \"prometheus-operator\".\n* \"app.kubernetes.io/name\" label, set to \"prometheus\".\n* \"app.kubernetes.io/version\" label, set to the Prometheus version.\n* \"operator.prometheus.io/name\" label, set to the name of the Prometheus object.\n* \"operator.prometheus.io/shard\" label, set to the shard number of the Prometheus object.\n* \"kubectl.kubernetes.io/default-container\" annotation, set to \"prometheus\".", "properties": { @@ -6005,7 +6013,7 @@ "type": "string" }, "managedIdentity": { - "description": "managedIdentity defines the Azure User-assigned Managed identity.\nCannot be set at the same time as `oauth` or `sdk`.", + "description": "managedIdentity defines the Azure User-assigned Managed identity.\nCannot be set at the same time as `oauth`, `sdk` or `workloadIdentity`.", "properties": { "clientId": { "description": "clientId defines the Azure User-assigned Managed identity.\n\nFor Prometheus >= 3.5.0 and Thanos >= 0.40.0, this field is allowed to be empty to support system-assigned managed identities.", @@ -6016,7 +6024,7 @@ "type": "object" }, "oauth": { - "description": "oauth defines the oauth config that is being used to authenticate.\nCannot be set at the same time as `managedIdentity` or `sdk`.\n\nIt requires Prometheus >= v2.48.0 or Thanos >= v0.31.0.", + "description": "oauth defines the oauth config that is being used to authenticate.\nCannot be set at the same time as `managedIdentity`, `sdk` or `workloadIdentity`.\n\nIt requires Prometheus >= v2.48.0 or Thanos >= v0.31.0.", "properties": { "clientId": { "description": "clientId defines the clientId of the Azure Active Directory application that is being used to authenticate.", @@ -6060,8 +6068,13 @@ ], "type": "object" }, + "scope": { + "description": "scope is the custom OAuth 2.0 scope to request when acquiring tokens.\nIt requires Prometheus >= 3.9.0. Currently not supported by Thanos.", + "pattern": "^[\\w\\s:/.\\\\-]+$", + "type": "string" + }, "sdk": { - "description": "sdk defines the Azure SDK config that is being used to authenticate.\nSee https://learn.microsoft.com/en-us/azure/developer/go/azure-sdk-authentication\nCannot be set at the same time as `oauth` or `managedIdentity`.\n\nIt requires Prometheus >= v2.52.0 or Thanos >= v0.36.0.", + "description": "sdk defines the Azure SDK config that is being used to authenticate.\nSee https://learn.microsoft.com/en-us/azure/developer/go/azure-sdk-authentication\nCannot be set at the same time as `oauth`, `managedIdentity` or `workloadIdentity`.\n\nIt requires Prometheus >= v2.52.0 or Thanos >= v0.36.0.", "properties": { "tenantId": { "description": "tenantId defines the tenant ID of the azure active directory application that is being used to authenticate.", @@ -6070,6 +6083,26 @@ } }, "type": "object" + }, + "workloadIdentity": { + "description": "workloadIdentity defines the Azure Workload Identity authentication.\nCannot be set at the same time as `oauth`, `managedIdentity`, or `sdk`.\n\nIt requires Prometheus >= 3.7.0. Currently not supported by Thanos.", + "properties": { + "clientId": { + "description": "clientId is the clientID of the Azure Active Directory application.", + "minLength": 1, + "type": "string" + }, + "tenantId": { + "description": "tenantId is the tenant ID of the Azure Active Directory application.", + "minLength": 1, + "type": "string" + } + }, + "required": [ + "clientId", + "tenantId" + ], + "type": "object" } }, "type": "object" @@ -7657,6 +7690,10 @@ "pattern": "^(0|(([0-9]+)y)?(([0-9]+)w)?(([0-9]+)d)?(([0-9]+)h)?(([0-9]+)m)?(([0-9]+)s)?(([0-9]+)ms)?)$", "type": "string" }, + "scrapeNativeHistograms": { + "description": "scrapeNativeHistograms defines whether to enable scraping of native histograms.\nIt requires Prometheus >= v3.8.0.", + "type": "boolean" + }, "scrapeProtocols": { "description": "scrapeProtocols defines the protocols to negotiate during a scrape. It tells clients the\nprotocols supported by Prometheus in order of preference (from most to least preferred).\n\nIf unset, Prometheus uses its default value.\n\nIt requires Prometheus >= v2.49.0.\n\n`PrometheusText1.0.0` requires Prometheus >= v3.0.0.", "items": { @@ -9103,17 +9140,20 @@ "description": "tracingConfig defines tracing in Prometheus.\n\nThis is an *experimental feature*, it may change in any upcoming release\nin a breaking way.", "properties": { "clientType": { - "description": "clientType defines the client used to export the traces. Supported values are `http` or `grpc`.", + "description": "clientType defines the client used to export the traces. Supported values are `HTTP` and `GRPC`.", "enum": [ "http", - "grpc" + "grpc", + "HTTP", + "GRPC" ], "type": "string" }, "compression": { - "description": "compression key for supported compression types. The only supported value is `gzip`.", + "description": "compression key for supported compression types. The only supported value is `Gzip`.", "enum": [ - "gzip" + "gzip", + "Gzip" ], "type": "string" }, @@ -9341,6 +9381,47 @@ }, "type": "object" }, + "updateStrategy": { + "description": "updateStrategy indicates the strategy that will be employed to update\nPods in the StatefulSet when a revision is made to statefulset's Pod\nTemplate.\n\nThe default strategy is RollingUpdate.", + "properties": { + "rollingUpdate": { + "description": "rollingUpdate is used to communicate parameters when type is RollingUpdate.", + "properties": { + "maxUnavailable": { + "anyOf": [ + { + "type": "integer" + }, + { + "type": "string" + } + ], + "description": "maxUnavailable is the maximum number of pods that can be unavailable\nduring the update. The value can be an absolute number (ex: 5) or a\npercentage of desired pods (ex: 10%). Absolute number is calculated from\npercentage by rounding up. This can not be 0. Defaults to 1. This field\nis alpha-level and is only honored by servers that enable the\nMaxUnavailableStatefulSet feature. The field applies to all pods in the\nrange 0 to Replicas-1. That means if there is any unavailable pod in\nthe range 0 to Replicas-1, it will be counted towards MaxUnavailable.", + "x-kubernetes-int-or-string": true + } + }, + "type": "object" + }, + "type": { + "description": "type indicates the type of the StatefulSetUpdateStrategy.\n\nDefault is RollingUpdate.", + "enum": [ + "OnDelete", + "RollingUpdate" + ], + "type": "string" + } + }, + "required": [ + "type" + ], + "type": "object", + "x-kubernetes-validations": [ + { + "message": "rollingUpdate requires type to be RollingUpdate", + "rule": "!(self.type != 'RollingUpdate' && has(self.rollingUpdate))" + } + ] + }, "version": { "description": "version of Prometheus being deployed. The operator uses this information\nto generate the Prometheus StatefulSet + configuration files.\n\nIf not specified, the operator assumes the latest upstream version of\nPrometheus available at the time when the version of the operator was\nreleased.", "type": "string" diff --git a/jsonnet/prometheus-operator/prometheusrules-crd.json b/jsonnet/prometheus-operator/prometheusrules-crd.json index dcced716fad..6a9f4f5237a 100644 --- a/jsonnet/prometheus-operator/prometheusrules-crd.json +++ b/jsonnet/prometheus-operator/prometheusrules-crd.json @@ -4,7 +4,7 @@ "metadata": { "annotations": { "controller-gen.kubebuilder.io/version": "v0.19.0", - "operator.prometheus.io/version": "0.87.1" + "operator.prometheus.io/version": "0.88.0" }, "name": "prometheusrules.monitoring.coreos.com" }, diff --git a/jsonnet/prometheus-operator/scrapeconfigs-crd.json b/jsonnet/prometheus-operator/scrapeconfigs-crd.json index 69955b19531..71c712b9442 100644 --- a/jsonnet/prometheus-operator/scrapeconfigs-crd.json +++ b/jsonnet/prometheus-operator/scrapeconfigs-crd.json @@ -4,7 +4,7 @@ "metadata": { "annotations": { "controller-gen.kubebuilder.io/version": "v0.19.0", - "operator.prometheus.io/version": "0.87.1" + "operator.prometheus.io/version": "0.88.0" }, "name": "scrapeconfigs.monitoring.coreos.com" }, @@ -11668,6 +11668,10 @@ "pattern": "^(0|(([0-9]+)y)?(([0-9]+)w)?(([0-9]+)d)?(([0-9]+)h)?(([0-9]+)m)?(([0-9]+)s)?(([0-9]+)ms)?)$", "type": "string" }, + "scrapeNativeHistograms": { + "description": "scrapeNativeHistograms defines whether to enable scraping of native histograms.\nIt requires Prometheus >= v3.8.0.", + "type": "boolean" + }, "scrapeProtocols": { "description": "scrapeProtocols defines the protocols to negotiate during a scrape. It tells clients the\nprotocols supported by Prometheus in order of preference (from most to least preferred).\n\nIf unset, Prometheus uses its default value.\n\nIt requires Prometheus >= v2.49.0.", "items": { diff --git a/jsonnet/prometheus-operator/servicemonitors-crd.json b/jsonnet/prometheus-operator/servicemonitors-crd.json index 60abe73e087..b7e85bba305 100644 --- a/jsonnet/prometheus-operator/servicemonitors-crd.json +++ b/jsonnet/prometheus-operator/servicemonitors-crd.json @@ -4,7 +4,7 @@ "metadata": { "annotations": { "controller-gen.kubebuilder.io/version": "v0.19.0", - "operator.prometheus.io/version": "0.87.1" + "operator.prometheus.io/version": "0.88.0" }, "name": "servicemonitors.monitoring.coreos.com" }, @@ -69,7 +69,7 @@ "description": "Endpoint defines an endpoint serving Prometheus metrics to be scraped by\nPrometheus.", "properties": { "authorization": { - "description": "authorization configures the Authorization header credentials to use when\nscraping the target.\n\nCannot be set at the same time as `basicAuth`, or `oauth2`.", + "description": "authorization configures the Authorization header credentials used by\nthe client.\n\nCannot be set at the same time as `basicAuth`, `bearerTokenSecret` or `oauth2`.", "properties": { "credentials": { "description": "credentials defines a key of a Secret in the namespace that contains the credentials for authentication.", @@ -102,7 +102,7 @@ "type": "object" }, "basicAuth": { - "description": "basicAuth defines the Basic Authentication credentials to use when\nscraping the target.\n\nCannot be set at the same time as `authorization`, or `oauth2`.", + "description": "basicAuth defines the Basic Authentication credentials used by the\nclient.\n\nCannot be set at the same time as `authorization`, `bearerTokenSecret` or `oauth2`.", "properties": { "password": { "description": "password defines a key of a Secret containing the password for\nauthentication.", @@ -158,7 +158,7 @@ "type": "string" }, "bearerTokenSecret": { - "description": "bearerTokenSecret defines a key of a Secret containing the bearer\ntoken for scraping targets. The secret needs to be in the same namespace\nas the ServiceMonitor object and readable by the Prometheus Operator.\n\nDeprecated: use `authorization` instead.", + "description": "bearerTokenSecret defines a key of a Secret containing the bearer token\nused by the client for authentication. The secret needs to be in the\nsame namespace as the custom resource and readable by the Prometheus\nOperator.\n\nCannot be set at the same time as `authorization`, `basicAuth` or `oauth2`.\n\nDeprecated: use `authorization` instead.", "properties": { "key": { "description": "The key of the secret to select from. Must be a valid secret key.", @@ -181,7 +181,7 @@ "x-kubernetes-map-type": "atomic" }, "enableHttp2": { - "description": "enableHttp2 can be used to disable HTTP2 when scraping the target.", + "description": "enableHttp2 can be used to disable HTTP2.", "type": "boolean" }, "filterRunning": { @@ -189,7 +189,7 @@ "type": "boolean" }, "followRedirects": { - "description": "followRedirects defines whether the scrape requests should follow HTTP\n3xx redirects.", + "description": "followRedirects defines whether the client should follow HTTP 3xx\nredirects.", "type": "boolean" }, "honorLabels": { @@ -278,7 +278,7 @@ "type": "string" }, "oauth2": { - "description": "oauth2 defines the OAuth2 settings to use when scraping the target.\n\nIt requires Prometheus >= 2.27.0.\n\nCannot be set at the same time as `authorization`, or `basicAuth`.", + "description": "oauth2 defines the OAuth2 settings used by the client.\n\nIt requires Prometheus >= 2.27.0.\n\nCannot be set at the same time as `authorization`, `basicAuth` or `bearerTokenSecret`.", "properties": { "clientId": { "description": "clientId defines a key of a Secret or ConfigMap containing the\nOAuth2 client's ID.", @@ -741,7 +741,7 @@ "x-kubernetes-int-or-string": true }, "tlsConfig": { - "description": "tlsConfig defines the TLS configuration to use when scraping the target.", + "description": "tlsConfig defines TLS configuration used by the client.", "properties": { "ca": { "description": "ca defines the Certificate authority used when verifying server certificates.", @@ -1013,6 +1013,10 @@ "description": "scrapeClassicHistograms defines whether to scrape a classic histogram that is also exposed as a native histogram.\nIt requires Prometheus >= v2.45.0.\n\nNotice: `scrapeClassicHistograms` corresponds to the `always_scrape_classic_histograms` field in the Prometheus configuration.", "type": "boolean" }, + "scrapeNativeHistograms": { + "description": "scrapeNativeHistograms defines whether to enable scraping of native histograms.\nIt requires Prometheus >= v3.8.0.", + "type": "boolean" + }, "scrapeProtocols": { "description": "scrapeProtocols defines the protocols to negotiate during a scrape. It tells clients the\nprotocols supported by Prometheus in order of preference (from most to least preferred).\n\nIf unset, Prometheus uses its default value.\n\nIt requires Prometheus >= v2.49.0.", "items": { diff --git a/jsonnet/prometheus-operator/thanosrulers-crd.json b/jsonnet/prometheus-operator/thanosrulers-crd.json index 8f6b0eeccc5..4eeeca0dad2 100644 --- a/jsonnet/prometheus-operator/thanosrulers-crd.json +++ b/jsonnet/prometheus-operator/thanosrulers-crd.json @@ -4,7 +4,7 @@ "metadata": { "annotations": { "controller-gen.kubebuilder.io/version": "v0.19.0", - "operator.prometheus.io/version": "0.87.1" + "operator.prometheus.io/version": "0.88.0" }, "name": "thanosrulers.monitoring.coreos.com" }, @@ -4047,6 +4047,14 @@ "description": "paused defines when a ThanosRuler deployment is paused, no actions except for deletion\nwill be performed on the underlying objects.", "type": "boolean" }, + "podManagementPolicy": { + "description": "podManagementPolicy defines the policy for creating/deleting pods when\nscaling up and down.\n\nUnlike the default StatefulSet behavior, the default policy is\n`Parallel` to avoid manual intervention in case a pod gets stuck during\na rollout.\n\nNote that updating this value implies the recreation of the StatefulSet\nwhich incurs a service outage.", + "enum": [ + "OrderedReady", + "Parallel" + ], + "type": "string" + }, "podMetadata": { "description": "podMetadata defines labels and annotations which are propagated to the ThanosRuler pods.\n\nThe following items are reserved and cannot be overridden:\n* \"app.kubernetes.io/name\" label, set to \"thanos-ruler\".\n* \"app.kubernetes.io/managed-by\" label, set to \"prometheus-operator\".\n* \"app.kubernetes.io/instance\" label, set to the name of the ThanosRuler instance.\n* \"thanos-ruler\" label, set to the name of the ThanosRuler instance.\n* \"kubectl.kubernetes.io/default-container\" annotation, set to \"thanos-ruler\".", "properties": { @@ -4187,7 +4195,7 @@ "type": "string" }, "managedIdentity": { - "description": "managedIdentity defines the Azure User-assigned Managed identity.\nCannot be set at the same time as `oauth` or `sdk`.", + "description": "managedIdentity defines the Azure User-assigned Managed identity.\nCannot be set at the same time as `oauth`, `sdk` or `workloadIdentity`.", "properties": { "clientId": { "description": "clientId defines the Azure User-assigned Managed identity.\n\nFor Prometheus >= 3.5.0 and Thanos >= 0.40.0, this field is allowed to be empty to support system-assigned managed identities.", @@ -4198,7 +4206,7 @@ "type": "object" }, "oauth": { - "description": "oauth defines the oauth config that is being used to authenticate.\nCannot be set at the same time as `managedIdentity` or `sdk`.\n\nIt requires Prometheus >= v2.48.0 or Thanos >= v0.31.0.", + "description": "oauth defines the oauth config that is being used to authenticate.\nCannot be set at the same time as `managedIdentity`, `sdk` or `workloadIdentity`.\n\nIt requires Prometheus >= v2.48.0 or Thanos >= v0.31.0.", "properties": { "clientId": { "description": "clientId defines the clientId of the Azure Active Directory application that is being used to authenticate.", @@ -4242,8 +4250,13 @@ ], "type": "object" }, + "scope": { + "description": "scope is the custom OAuth 2.0 scope to request when acquiring tokens.\nIt requires Prometheus >= 3.9.0. Currently not supported by Thanos.", + "pattern": "^[\\w\\s:/.\\\\-]+$", + "type": "string" + }, "sdk": { - "description": "sdk defines the Azure SDK config that is being used to authenticate.\nSee https://learn.microsoft.com/en-us/azure/developer/go/azure-sdk-authentication\nCannot be set at the same time as `oauth` or `managedIdentity`.\n\nIt requires Prometheus >= v2.52.0 or Thanos >= v0.36.0.", + "description": "sdk defines the Azure SDK config that is being used to authenticate.\nSee https://learn.microsoft.com/en-us/azure/developer/go/azure-sdk-authentication\nCannot be set at the same time as `oauth`, `managedIdentity` or `workloadIdentity`.\n\nIt requires Prometheus >= v2.52.0 or Thanos >= v0.36.0.", "properties": { "tenantId": { "description": "tenantId defines the tenant ID of the azure active directory application that is being used to authenticate.", @@ -4252,6 +4265,26 @@ } }, "type": "object" + }, + "workloadIdentity": { + "description": "workloadIdentity defines the Azure Workload Identity authentication.\nCannot be set at the same time as `oauth`, `managedIdentity`, or `sdk`.\n\nIt requires Prometheus >= 3.7.0. Currently not supported by Thanos.", + "properties": { + "clientId": { + "description": "clientId is the clientID of the Azure Active Directory application.", + "minLength": 1, + "type": "string" + }, + "tenantId": { + "description": "tenantId is the tenant ID of the Azure Active Directory application.", + "minLength": 1, + "type": "string" + } + }, + "required": [ + "clientId", + "tenantId" + ], + "type": "object" } }, "type": "object" @@ -6153,6 +6186,47 @@ "description": "tracingConfigFile defines the path of the tracing configuration file.\n\nThe configuration format is defined at https://thanos.io/tip/thanos/tracing.md/#configuration\n\nThis is an *experimental feature*, it may change in any upcoming release\nin a breaking way.\n\nThe operator performs no validation of the configuration file.\n\nThis field takes precedence over `tracingConfig`.", "type": "string" }, + "updateStrategy": { + "description": "updateStrategy indicates the strategy that will be employed to update\nPods in the StatefulSet when a revision is made to statefulset's Pod\nTemplate.\n\nThe default strategy is RollingUpdate.", + "properties": { + "rollingUpdate": { + "description": "rollingUpdate is used to communicate parameters when type is RollingUpdate.", + "properties": { + "maxUnavailable": { + "anyOf": [ + { + "type": "integer" + }, + { + "type": "string" + } + ], + "description": "maxUnavailable is the maximum number of pods that can be unavailable\nduring the update. The value can be an absolute number (ex: 5) or a\npercentage of desired pods (ex: 10%). Absolute number is calculated from\npercentage by rounding up. This can not be 0. Defaults to 1. This field\nis alpha-level and is only honored by servers that enable the\nMaxUnavailableStatefulSet feature. The field applies to all pods in the\nrange 0 to Replicas-1. That means if there is any unavailable pod in\nthe range 0 to Replicas-1, it will be counted towards MaxUnavailable.", + "x-kubernetes-int-or-string": true + } + }, + "type": "object" + }, + "type": { + "description": "type indicates the type of the StatefulSetUpdateStrategy.\n\nDefault is RollingUpdate.", + "enum": [ + "OnDelete", + "RollingUpdate" + ], + "type": "string" + } + }, + "required": [ + "type" + ], + "type": "object", + "x-kubernetes-validations": [ + { + "message": "rollingUpdate requires type to be RollingUpdate", + "rule": "!(self.type != 'RollingUpdate' && has(self.rollingUpdate))" + } + ] + }, "version": { "description": "version of Thanos to be deployed.", "type": "string" diff --git a/pkg/alertmanager/amcfg.go b/pkg/alertmanager/amcfg.go index ef087526d0c..f68046cb436 100644 --- a/pkg/alertmanager/amcfg.go +++ b/pkg/alertmanager/amcfg.go @@ -282,7 +282,7 @@ func (cb *ConfigBuilder) initializeFromAlertmanagerConfig(ctx context.Context, g return err } - if err := validationv1.ValidateAlertmanagerGlobalConfig(globalConfig); err != nil { + if err := cb.checkAlertmanagerGlobalConfigResource(ctx, globalConfig, crKey.Namespace); err != nil { return err } @@ -434,17 +434,17 @@ func (cb *ConfigBuilder) convertGlobalConfig(ctx context.Context, in *monitoring } } - if in.HTTPConfig != nil { + if in.HTTPConfigWithProxy != nil { v1alpha1Config := monitoringv1alpha1.HTTPConfig{ - Authorization: in.HTTPConfig.Authorization, - BasicAuth: in.HTTPConfig.BasicAuth, - OAuth2: in.HTTPConfig.OAuth2, + Authorization: in.HTTPConfigWithProxy.Authorization, + BasicAuth: in.HTTPConfigWithProxy.BasicAuth, + OAuth2: in.HTTPConfigWithProxy.OAuth2, //nolint:staticcheck // Ignore SA1019 this field is marked as deprecated. - BearerTokenSecret: in.HTTPConfig.BearerTokenSecret, - TLSConfig: in.HTTPConfig.TLSConfig, - ProxyConfig: in.HTTPConfig.ProxyConfig, - FollowRedirects: in.HTTPConfig.FollowRedirects, - EnableHTTP2: in.HTTPConfig.EnableHTTP2, + BearerTokenSecret: in.HTTPConfigWithProxy.BearerTokenSecret, + TLSConfig: in.HTTPConfigWithProxy.TLSConfig, + ProxyConfig: in.HTTPConfigWithProxy.ProxyConfig, + FollowRedirects: in.HTTPConfigWithProxy.FollowRedirects, + EnableHTTP2: in.HTTPConfigWithProxy.EnableHTTP2, } httpConfig, err := cb.convertHTTPConfig(ctx, &v1alpha1Config, crKey) @@ -828,7 +828,7 @@ func (cb *ConfigBuilder) convertWebhookConfig(ctx context.Context, in monitoring } out.URL = url } else if in.URL != nil { - url, err := validation.ValidateURL(*in.URL) + url, err := validation.ValidateURL(string(*in.URL)) if err != nil { return nil, err } @@ -901,22 +901,18 @@ func (cb *ConfigBuilder) convertDiscordConfig(ctx context.Context, in monitoring func (cb *ConfigBuilder) convertSlackConfig(ctx context.Context, in monitoringv1alpha1.SlackConfig, crKey types.NamespacedName) (*slackConfig, error) { out := &slackConfig{ VSendResolved: in.SendResolved, - Channel: in.Channel, - Username: in.Username, - Color: in.Color, - Title: in.Title, - TitleLink: in.TitleLink, - Pretext: in.Pretext, - Text: in.Text, - ShortFields: in.ShortFields, - Footer: in.Footer, - Fallback: in.Fallback, - CallbackID: in.CallbackID, - IconEmoji: in.IconEmoji, - IconURL: in.IconURL, - ImageURL: in.ImageURL, - ThumbURL: in.ThumbURL, - LinkNames: in.LinkNames, + Channel: ptr.Deref(in.Channel, ""), + Username: ptr.Deref(in.Username, ""), + Color: ptr.Deref(in.Color, ""), + Title: ptr.Deref(in.Title, ""), + Pretext: ptr.Deref(in.Pretext, ""), + Text: ptr.Deref(in.Text, ""), + ShortFields: ptr.Deref(in.ShortFields, false), + Footer: ptr.Deref(in.Footer, ""), + Fallback: ptr.Deref(in.Fallback, ""), + CallbackID: ptr.Deref(in.CallbackID, ""), + IconEmoji: ptr.Deref(in.IconEmoji, ""), + LinkNames: ptr.Deref(in.LinkNames, false), MrkdwnIn: in.MrkdwnIn, } @@ -928,6 +924,19 @@ func (cb *ConfigBuilder) convertSlackConfig(ctx context.Context, in monitoringv1 out.APIURL = url } + if ptr.Deref(in.TitleLink, "") != "" { + out.TitleLink = string(*in.TitleLink) + } + if ptr.Deref(in.IconURL, "") != "" { + out.TitleLink = string(*in.IconURL) + } + if ptr.Deref(in.ImageURL, "") != "" { + out.TitleLink = string(*in.ImageURL) + } + if ptr.Deref(in.ThumbURL, "") != "" { + out.TitleLink = string(*in.ThumbURL) + } + var actions []slackAction if l := len(in.Actions); l > 0 { actions = make([]slackAction, l) @@ -935,18 +944,21 @@ func (cb *ConfigBuilder) convertSlackConfig(ctx context.Context, in monitoringv1 action := slackAction{ Type: a.Type, Text: a.Text, - URL: a.URL, - Style: a.Style, - Name: a.Name, - Value: a.Value, + Style: ptr.Deref(a.Style, ""), + Name: ptr.Deref(a.Name, ""), + Value: ptr.Deref(a.Value, ""), + } + + if ptr.Deref(a.URL, "") != "" { + action.URL = string(*a.URL) } if a.ConfirmField != nil { action.ConfirmField = &slackConfirmationField{ Text: a.ConfirmField.Text, - Title: a.ConfirmField.Title, - OkText: a.ConfirmField.OkText, - DismissText: a.ConfirmField.DismissText, + Title: ptr.Deref(a.ConfirmField.Title, ""), + OkText: ptr.Deref(a.ConfirmField.OkText, ""), + DismissText: ptr.Deref(a.ConfirmField.DismissText, ""), } } @@ -977,20 +989,36 @@ func (cb *ConfigBuilder) convertSlackConfig(ctx context.Context, in monitoringv1 } out.HTTPConfig = httpConfig + if in.Timeout != nil { + if *in.Timeout != "" { + timeout, err := model.ParseDuration(string(*in.Timeout)) + if err != nil { + return nil, err + } + out.Timeout = &timeout + } + } + return out, nil } func (cb *ConfigBuilder) convertPagerdutyConfig(ctx context.Context, in monitoringv1alpha1.PagerDutyConfig, crKey types.NamespacedName) (*pagerdutyConfig, error) { out := &pagerdutyConfig{ VSendResolved: in.SendResolved, - Class: in.Class, - Client: in.Client, - ClientURL: in.ClientURL, - Component: in.Component, - Description: in.Description, - Group: in.Group, - Severity: in.Severity, - URL: in.URL, + Class: ptr.Deref(in.Class, ""), + Client: ptr.Deref(in.Client, ""), + Component: ptr.Deref(in.Component, ""), + Description: ptr.Deref(in.Description, ""), + Group: ptr.Deref(in.Group, ""), + Severity: ptr.Deref(in.Severity, ""), + } + + if in.URL != nil { + out.URL = string(*in.URL) + } + + if in.ClientURL != nil { + out.ClientURL = string(*in.ClientURL) } if in.RoutingKey != nil { @@ -1023,8 +1051,10 @@ func (cb *ConfigBuilder) convertPagerdutyConfig(ctx context.Context, in monitori linkConfigs = make([]pagerdutyLink, l) for i, lc := range in.PagerDutyLinkConfigs { linkConfigs[i] = pagerdutyLink{ - Href: lc.Href, - Text: lc.Text, + Text: ptr.Deref(lc.Text, ""), + } + if lc.Href != nil { + linkConfigs[i].Href = string(*lc.Href) } } } @@ -1035,9 +1065,11 @@ func (cb *ConfigBuilder) convertPagerdutyConfig(ctx context.Context, in monitori imageConfig = make([]pagerdutyImage, l) for i, ic := range in.PagerDutyImageConfigs { imageConfig[i] = pagerdutyImage{ - Src: ic.Src, - Alt: ic.Alt, - Href: ic.Href, + Src: ptr.Deref(ic.Src, ""), + Alt: ptr.Deref(ic.Alt, ""), + } + if ic.Href != nil { + imageConfig[i].Href = string(*ic.Href) } } } @@ -1053,13 +1085,22 @@ func (cb *ConfigBuilder) convertPagerdutyConfig(ctx context.Context, in monitori out.Source = *in.Source } + if in.Timeout != nil { + if *in.Timeout != "" { + timeout, err := model.ParseDuration(string(*in.Timeout)) + if err != nil { + return nil, err + } + out.Timeout = &timeout + } + } + return out, nil } func (cb *ConfigBuilder) convertOpsgenieConfig(ctx context.Context, in monitoringv1alpha1.OpsGenieConfig, crKey types.NamespacedName) (*opsgenieConfig, error) { out := &opsgenieConfig{ VSendResolved: in.SendResolved, - APIURL: in.APIURL, Message: in.Message, Description: in.Description, Source: in.Source, @@ -1071,6 +1112,10 @@ func (cb *ConfigBuilder) convertOpsgenieConfig(ctx context.Context, in monitorin UpdateAlerts: in.UpdateAlerts, } + if in.APIURL != nil { + out.APIURL = string(*in.APIURL) + } + if in.APIKey != nil { apiKey, err := cb.store.GetSecretKey(ctx, crKey.Namespace, *in.APIKey) if err != nil { @@ -1115,7 +1160,6 @@ func (cb *ConfigBuilder) convertOpsgenieConfig(ctx context.Context, in monitorin func (cb *ConfigBuilder) convertWeChatConfig(ctx context.Context, in monitoringv1alpha1.WeChatConfig, crKey types.NamespacedName) (*weChatConfig, error) { out := &weChatConfig{ VSendResolved: in.SendResolved, - APIURL: in.APIURL, CorpID: in.CorpID, AgentID: in.AgentID, ToUser: in.ToUser, @@ -1125,6 +1169,10 @@ func (cb *ConfigBuilder) convertWeChatConfig(ctx context.Context, in monitoringv MessageType: in.MessageType, } + if in.APIURL != nil { + out.APIURL = string(*in.APIURL) + } + if in.APISecret != nil { apiSecret, err := cb.store.GetSecretKey(ctx, crKey.Namespace, *in.APISecret) if err != nil { @@ -1228,12 +1276,11 @@ func (cb *ConfigBuilder) convertEmailConfig(ctx context.Context, in monitoringv1 func (cb *ConfigBuilder) convertVictorOpsConfig(ctx context.Context, in monitoringv1alpha1.VictorOpsConfig, crKey types.NamespacedName) (*victorOpsConfig, error) { out := &victorOpsConfig{ VSendResolved: in.SendResolved, - APIURL: in.APIURL, RoutingKey: in.RoutingKey, - MessageType: in.MessageType, - EntityDisplayName: in.EntityDisplayName, - StateMessage: in.StateMessage, - MonitoringTool: in.MonitoringTool, + MessageType: ptr.Deref(in.MessageType, ""), + EntityDisplayName: ptr.Deref(in.EntityDisplayName, ""), + StateMessage: ptr.Deref(in.StateMessage, ""), + MonitoringTool: ptr.Deref(in.MonitoringTool, ""), } if in.APIKey != nil { @@ -1244,6 +1291,10 @@ func (cb *ConfigBuilder) convertVictorOpsConfig(ctx context.Context, in monitori out.APIKey = apiKey } + if in.APIURL != nil { + out.APIURL = string(*in.APIURL) + } + var customFields map[string]string if l := len(in.CustomFields); l > 0 { // from https://github.com/prometheus/alertmanager/blob/a7f9fdadbecbb7e692d2cd8d3334e3d6de1602e1/config/notifiers.go#L497 @@ -1278,15 +1329,18 @@ func (cb *ConfigBuilder) convertVictorOpsConfig(ctx context.Context, in monitori func (cb *ConfigBuilder) convertPushoverConfig(ctx context.Context, in monitoringv1alpha1.PushoverConfig, crKey types.NamespacedName) (*pushoverConfig, error) { out := &pushoverConfig{ VSendResolved: in.SendResolved, - Title: in.Title, - Message: in.Message, - URL: in.URL, - URLTitle: in.URLTitle, - Priority: in.Priority, + Title: ptr.Deref(in.Title, ""), + Message: ptr.Deref(in.Message, ""), + URLTitle: ptr.Deref(in.URLTitle, ""), + Priority: ptr.Deref(in.Priority, ""), HTML: in.HTML, Monospace: in.Monospace, } + if ptr.Deref(in.URL, "") != "" { + out.URL = string(*in.URL) + } + if in.TTL != nil { out.TTL = string(*in.TTL) } @@ -1318,16 +1372,16 @@ func (cb *ConfigBuilder) convertPushoverConfig(ctx context.Context, in monitorin } { - if in.Retry != "" { - retry, err := model.ParseDuration(in.Retry) + if ptr.Deref(in.Retry, "") != "" { + retry, err := model.ParseDuration(*in.Retry) if err != nil { return nil, fmt.Errorf("parse resolve retry: %w", err) } out.Retry = &retry } - if in.Expire != "" { - expire, err := model.ParseDuration(in.Expire) + if ptr.Deref(in.Expire, "") != "" { + expire, err := model.ParseDuration(*in.Expire) if err != nil { return nil, fmt.Errorf("parse resolve expire: %w", err) } @@ -1347,13 +1401,16 @@ func (cb *ConfigBuilder) convertPushoverConfig(ctx context.Context, in monitorin func (cb *ConfigBuilder) convertTelegramConfig(ctx context.Context, in monitoringv1alpha1.TelegramConfig, crKey types.NamespacedName) (*telegramConfig, error) { out := &telegramConfig{ VSendResolved: in.SendResolved, - APIUrl: in.APIURL, ChatID: in.ChatID, Message: in.Message, DisableNotifications: false, ParseMode: in.ParseMode, } + if in.APIURL != nil { + out.APIUrl = string(*in.APIURL) + } + httpConfig, err := cb.convertHTTPConfig(ctx, in.HTTPConfig, crKey) if err != nil { return nil, err @@ -2058,6 +2115,36 @@ func (gc *globalConfig) sanitize(amVersion semver.Version, logger *slog.Logger) } } + if gc.SlackAppToken != "" && amVersion.LT(semver.MustParse("0.30.0")) { + msg := "'slack_app_token' supported in Alertmanager >= 0.30.0 only - dropping field from provided config" + logger.Warn(msg, "current_version", amVersion.String()) + gc.SlackAppToken = "" + } + + if gc.SlackAppTokenFile != "" && amVersion.LT(semver.MustParse("0.30.0")) { + msg := "'slack_app_token_file' supported in Alertmanager >= 0.30.0 only - dropping field from provided config" + logger.Warn(msg, "current_version", amVersion.String()) + gc.SlackAppTokenFile = "" + } + + if gc.SlackAppURL != nil && amVersion.LT(semver.MustParse("0.30.0")) { + msg := "'slack_app_url' supported in Alertmanager >= 0.30.0 only - dropping field from provided config" + logger.Warn(msg, "current_version", amVersion.String()) + gc.SlackAppURL = nil + } + + if gc.SlackAppToken != "" && gc.SlackAppTokenFile != "" { + msg := "'slack_app_token' and 'slack_app_token_file' are mutually exclusive - 'slack_app_token' has taken precedence" + logger.Warn(msg) + gc.SlackAppTokenFile = "" + } + + if (gc.SlackAppToken != "" || gc.SlackAppTokenFile != "") && (gc.SlackAPIURL != nil || gc.SlackAPIURLFile != "") { + if gc.SlackAPIURL != nil && gc.SlackAppURL != nil && gc.SlackAPIURL.String() != gc.SlackAppURL.String() { + return fmt.Errorf("at most one of slack_app_token/slack_app_token_file & slack_api_url/slack_api_url_file must be configured (unless slack_api_url matches slack_app_url)") + } + } + if gc.OpsGenieAPIKeyFile != "" && amVersion.LT(semver.MustParse("0.24.0")) { msg := "'opsgenie_api_key_file' supported in Alertmanager >= 0.24.0 only - dropping field from provided config" logger.Warn(msg, "current_version", amVersion.String()) @@ -2337,6 +2424,19 @@ func (r *receiver) sanitize(amVersion semver.Version, logger *slog.Logger) error return err } } + + for _, conf := range r.MattermostConfigs { + if err := conf.sanitize(amVersion, withLogger); err != nil { + return err + } + } + + for _, conf := range r.IncidentioConfigs { + if err := conf.sanitize(amVersion, withLogger); err != nil { + return err + } + } + return nil } @@ -2411,6 +2511,7 @@ func (ops *opsgenieResponder) sanitize(amVersion semver.Version) error { func (pdc *pagerdutyConfig) sanitize(amVersion semver.Version, logger *slog.Logger) error { lessThanV0_25 := amVersion.LT(semver.MustParse("0.25.0")) + lessThanV0_30 := amVersion.LT(semver.MustParse("0.30.0")) if pdc.Source != "" && lessThanV0_25 { msg := "'source' supported in Alertmanager >= 0.25.0 only - dropping field from provided config" @@ -2442,6 +2543,12 @@ func (pdc *pagerdutyConfig) sanitize(amVersion semver.Version, logger *slog.Logg pdc.RoutingKeyFile = "" } + if pdc.Timeout != nil && lessThanV0_30 { + msg := "'timeout' supported in Alertmanager >= 0.30.0 only - dropping field from provided config" + logger.Warn(msg, "current_version", amVersion.String()) + pdc.Timeout = nil + } + return pdc.HTTPConfig.sanitize(amVersion, logger) } @@ -2504,14 +2611,56 @@ func (poc *pushoverConfig) sanitize(amVersion semver.Version, logger *slog.Logge return errors.New("either monospace or html must be configured") } + if poc.URL != "" { + if _, err := validation.ValidateURL(poc.URL); err != nil { + return fmt.Errorf("invalid 'url': %w", err) + } + } + return poc.HTTPConfig.sanitize(amVersion, logger) } func (sc *slackConfig) sanitize(amVersion semver.Version, logger *slog.Logger) error { + lessThanV0_30 := amVersion.LT(semver.MustParse("0.30.0")) + if err := sc.HTTPConfig.sanitize(amVersion, logger); err != nil { return err } + if sc.Timeout != nil && lessThanV0_30 { + msg := "'timeout' supported in Alertmanager >= 0.30.0 only - dropping field from provided config" + logger.Warn(msg, "current_version", amVersion.String()) + sc.Timeout = nil + } + + if sc.AppToken != "" && lessThanV0_30 { + msg := "'app_token' supported in Alertmanager >= 0.30.0 only - dropping field from provided config" + logger.Warn(msg, "current_version", amVersion.String()) + sc.AppToken = "" + } + + if sc.AppTokenFile != "" && lessThanV0_30 { + msg := "'app_token_file' supported in Alertmanager >= 0.30.0 only - dropping field from provided config" + logger.Warn(msg, "current_version", amVersion.String()) + sc.AppTokenFile = "" + } + + if sc.AppURL != "" && lessThanV0_30 { + msg := "'app_url' supported in Alertmanager >= 0.30.0 only - dropping field from provided config" + logger.Warn(msg, "current_version", amVersion.String()) + sc.AppURL = "" + } + + if sc.AppToken != "" && sc.AppTokenFile != "" { + msg := "'app_token' and 'app_token_file' are mutually exclusive for slack receiver config - 'app_token' has taken precedence" + logger.Warn(msg) + sc.AppTokenFile = "" + } + + if (sc.AppToken != "" || sc.AppTokenFile != "") && (sc.APIURL != "" || sc.APIURLFile != "") { + return fmt.Errorf("at most one of app_token/app_token_file & api_url/api_url_file must be configured") + } + if sc.APIURLFile == "" { return nil } @@ -2576,6 +2725,12 @@ func (whc *webhookConfig) sanitize(amVersion semver.Version, logger *slog.Logger whc.Timeout = nil } + if whc.URL != "" { + if _, err := validation.ValidateURL(whc.URL); err != nil { + return fmt.Errorf("invalid 'url': %w", err) + } + } + return nil } @@ -2588,6 +2743,10 @@ func (tc *msTeamsConfig) sanitize(amVersion semver.Version, logger *slog.Logger) return fmt.Errorf("mandatory field %q is empty", "webhook_url") } + if _, err := validation.ValidateURL(tc.WebhookURL); err != nil { + return fmt.Errorf("invalid 'webhook_url': %w", err) + } + if tc.Summary != "" && amVersion.LT(semver.MustParse("0.27.0")) { msg := "'summary' supported in Alertmanager >= 0.27.0 only - dropping field `summary` from msteams config" logger.Warn(msg, "current_version", amVersion.String()) @@ -2656,6 +2815,12 @@ func (tc *telegramConfig) sanitize(amVersion semver.Version, logger *slog.Logger tc.MessageThreadID = 0 } + if tc.APIUrl != "" { + if _, err := validation.ValidateURL(tc.APIUrl); err != nil { + return fmt.Errorf("invalid 'api_url': %w", err) + } + } + return tc.HTTPConfig.sanitize(amVersion, logger) } @@ -2714,6 +2879,19 @@ func (jc *jiraConfig) sanitize(amVersion semver.Version, logger *slog.Logger) er return errors.New("missing issue_type in jira_config") } + apiTypeAllowed := amVersion.GTE(semver.MustParse("0.29.0")) + if jc.APIType != "" { + if !apiTypeAllowed { + msg := "'api_type' supported in Alertmanager >= 0.29.0 only - dropping field from provided config" + logger.Warn(msg, "current_version", amVersion.String()) + jc.APIType = "" + } else { + if jc.APIType != "auto" && jc.APIType != "cloud" && jc.APIType != "datacenter" { + return fmt.Errorf("invalid 'api_type': a value must be 'auto', 'cloud' or 'datacenter'") + } + } + } + return jc.HTTPConfig.sanitize(amVersion, logger) } @@ -2733,6 +2911,60 @@ func (rc *rocketChatConfig) sanitize(amVersion semver.Version, logger *slog.Logg return rc.HTTPConfig.sanitize(amVersion, logger) } +func (mc *mattermostConfig) sanitize(amVersion semver.Version, logger *slog.Logger) error { + mattermostAllowed := amVersion.GTE(semver.MustParse("0.30.0")) + if !mattermostAllowed { + return fmt.Errorf(`invalid syntax in receivers config; mattermost integration is available in Alertmanager >= 0.30.0`) + } + + if mc.WebhookURL == "" && mc.WebhookURLFile == "" { + return fmt.Errorf(`one of 'webhook_url' or 'webhook_url_file' must be configured`) + } + + if mc.WebhookURL != "" && mc.WebhookURLFile != "" { + msg := "'webhook_url' and 'webhook_url_file' are mutually exclusive for mattermost receiver config - 'webhook_url' has taken precedence" + logger.Warn(msg) + mc.WebhookURLFile = "" + } + + return mc.HTTPConfig.sanitize(amVersion, logger) +} + +func (ic *incidentioConfig) sanitize(amVersion semver.Version, logger *slog.Logger) error { + incidentioAllowed := amVersion.GTE(semver.MustParse("0.29.0")) + if !incidentioAllowed { + return fmt.Errorf("invalid syntax in receivers config; incident.io integration is available in Alertmanager >= 0.29.0") + } + + if ic.URL == "" && ic.URLFile == "" { + return errors.New("one of url or url_file must be configured") + } + + if ic.URL != "" && ic.URLFile != "" { + return errors.New("at most one of url & url_file must be configured") + } + + if ic.URL != "" { + if _, err := validation.ValidateURL(ic.URL); err != nil { + return fmt.Errorf("invalid url: %w", err) + } + } + + if ic.AlertSourceToken != "" && ic.AlertSourceTokenFile != "" { + return errors.New("at most one of alert_source_token & alert_source_token_file must be configured") + } + + if ic.HTTPConfig != nil && ic.HTTPConfig.Authorization != nil && (ic.AlertSourceToken != "" || ic.AlertSourceTokenFile != "") { + return errors.New("cannot specify alert_source_token or alert_source_token_file when using http_config.authorization") + } + + if ic.AlertSourceToken == "" && ic.AlertSourceTokenFile == "" && (ic.HTTPConfig == nil || ic.HTTPConfig.Authorization == nil) { + return errors.New("at least one of alert_source_token, alert_source_token_file or http_config.authorization must be configured") + } + + return ic.HTTPConfig.sanitize(amVersion, logger) +} + func (ir *inhibitRule) sanitize(amVersion semver.Version, logger *slog.Logger) error { matchersV2Allowed := amVersion.GTE(semver.MustParse("0.22.0")) @@ -2894,3 +3126,45 @@ func checkIsV2Matcher(in ...[]monitoringv1alpha1.Matcher) bool { } return false } + +func (cb *ConfigBuilder) checkAlertmanagerGlobalConfigResource( + ctx context.Context, + gc *monitoringv1.AlertmanagerGlobalConfig, + namespace string, +) error { + if gc == nil { + return nil + } + + // Perform semantic validation irrespective of the Alertmanager version. + if err := validationv1.ValidateAlertmanagerGlobalConfig(gc); err != nil { + return err + } + + // Perform more specific validations which depend on the Alertmanager + // version. It also retrieves data from referenced secrets and configmaps + // (and fails in case of missing/invalid references). + if err := cb.checkGlobalWeChatConfig(ctx, gc.WeChatConfig, namespace); err != nil { + return err + } + + return nil +} + +func (cb *ConfigBuilder) checkGlobalWeChatConfig( + ctx context.Context, + wc *monitoringv1.GlobalWeChatConfig, + namespace string, +) error { + if wc == nil { + return nil + } + + if wc.APISecret != nil { + if _, err := cb.store.GetSecretKey(ctx, namespace, *wc.APISecret); err != nil { + return err + } + } + + return nil +} diff --git a/pkg/alertmanager/amcfg_test.go b/pkg/alertmanager/amcfg_test.go index 36d98e43399..5c663b72110 100644 --- a/pkg/alertmanager/amcfg_test.go +++ b/pkg/alertmanager/amcfg_test.go @@ -146,29 +146,33 @@ func TestInitializeFromAlertmanagerConfig(t *testing.T) { }, }, ResolveTimeout: "30s", - HTTPConfig: &monitoringv1.HTTPConfig{ - OAuth2: &monitoringv1.OAuth2{ - ClientID: monitoringv1.SecretOrConfigMap{ - ConfigMap: &corev1.ConfigMapKeySelector{ - LocalObjectReference: corev1.LocalObjectReference{ - Name: "webhook-client-id", + HTTPConfigWithProxy: &monitoringv1.HTTPConfigWithProxy{ + HTTPConfig: monitoringv1.HTTPConfig{ + HTTPConfigWithoutTLS: monitoringv1.HTTPConfigWithoutTLS{ + OAuth2: &monitoringv1.OAuth2{ + ClientID: monitoringv1.SecretOrConfigMap{ + ConfigMap: &corev1.ConfigMapKeySelector{ + LocalObjectReference: corev1.LocalObjectReference{ + Name: "webhook-client-id", + }, + Key: "test", + }, + }, + ClientSecret: corev1.SecretKeySelector{ + LocalObjectReference: corev1.LocalObjectReference{ + Name: "webhook-client-secret", + }, + Key: "test", + }, + TokenURL: "https://test.com", + Scopes: []string{"any"}, + EndpointParams: map[string]string{ + "some": "value", }, - Key: "test", - }, - }, - ClientSecret: corev1.SecretKeySelector{ - LocalObjectReference: corev1.LocalObjectReference{ - Name: "webhook-client-secret", }, - Key: "test", - }, - TokenURL: "https://test.com", - Scopes: []string{"any"}, - EndpointParams: map[string]string{ - "some": "value", + FollowRedirects: ptr.To(true), }, }, - FollowRedirects: ptr.To(true), }, }, amConfig: &monitoringv1alpha1.AlertmanagerConfig{ @@ -204,18 +208,22 @@ func TestInitializeFromAlertmanagerConfig(t *testing.T) { name: "valid global config with global HTTPConfig CA", amVersion: &version28, globalConfig: &monitoringv1.AlertmanagerGlobalConfig{ - HTTPConfig: &monitoringv1.HTTPConfig{ - TLSConfig: &monitoringv1.SafeTLSConfig{ - CA: monitoringv1.SecretOrConfigMap{ - ConfigMap: &corev1.ConfigMapKeySelector{ - LocalObjectReference: corev1.LocalObjectReference{ - Name: "proxy-ca-certificate", + HTTPConfigWithProxy: &monitoringv1.HTTPConfigWithProxy{ + HTTPConfig: monitoringv1.HTTPConfig{ + HTTPConfigWithoutTLS: monitoringv1.HTTPConfigWithoutTLS{ + FollowRedirects: ptr.To(true), + }, + TLSConfig: &monitoringv1.SafeTLSConfig{ + CA: monitoringv1.SecretOrConfigMap{ + ConfigMap: &corev1.ConfigMapKeySelector{ + LocalObjectReference: corev1.LocalObjectReference{ + Name: "proxy-ca-certificate", + }, + Key: "certificate", }, - Key: "certificate", }, }, }, - FollowRedirects: ptr.To(true), }, }, amConfig: &monitoringv1alpha1.AlertmanagerConfig{ @@ -622,8 +630,12 @@ func TestInitializeFromAlertmanagerConfig(t *testing.T) { { name: "globalConfig has null resolve timeout", globalConfig: &monitoringv1.AlertmanagerGlobalConfig{ - HTTPConfig: &monitoringv1.HTTPConfig{ - FollowRedirects: ptr.To(true), + HTTPConfigWithProxy: &monitoringv1.HTTPConfigWithProxy{ + HTTPConfig: monitoringv1.HTTPConfig{ + HTTPConfigWithoutTLS: monitoringv1.HTTPConfigWithoutTLS{ + FollowRedirects: ptr.To(true), + }, + }, }, }, amConfig: &monitoringv1alpha1.AlertmanagerConfig{ @@ -650,7 +662,12 @@ func TestInitializeFromAlertmanagerConfig(t *testing.T) { { name: "globalConfig httpconfig/proxyconfig has null secretKey for proxyConnectHeader", globalConfig: &monitoringv1.AlertmanagerGlobalConfig{ - HTTPConfig: &monitoringv1.HTTPConfig{ + HTTPConfigWithProxy: &monitoringv1.HTTPConfigWithProxy{ + HTTPConfig: monitoringv1.HTTPConfig{ + HTTPConfigWithoutTLS: monitoringv1.HTTPConfigWithoutTLS{ + FollowRedirects: ptr.To(true), + }, + }, ProxyConfig: monitoringv1.ProxyConfig{ ProxyURL: ptr.To("http://example.com"), NoProxy: ptr.To("svc.cluster.local"), @@ -665,7 +682,6 @@ func TestInitializeFromAlertmanagerConfig(t *testing.T) { }, }, }, - FollowRedirects: ptr.To(true), }, }, amConfig: &monitoringv1alpha1.AlertmanagerConfig{ @@ -693,7 +709,7 @@ func TestInitializeFromAlertmanagerConfig(t *testing.T) { name: "valid globalConfig httpconfig/proxyconfig/proxyConnectHeader with amVersion24", amVersion: &version24, globalConfig: &monitoringv1.AlertmanagerGlobalConfig{ - HTTPConfig: &monitoringv1.HTTPConfig{ + HTTPConfigWithProxy: &monitoringv1.HTTPConfigWithProxy{ ProxyConfig: monitoringv1.ProxyConfig{ ProxyURL: ptr.To("http://example.com"), NoProxy: ptr.To("svc.cluster.local"), @@ -708,7 +724,11 @@ func TestInitializeFromAlertmanagerConfig(t *testing.T) { }, }, }, - FollowRedirects: ptr.To(true), + HTTPConfig: monitoringv1.HTTPConfig{ + HTTPConfigWithoutTLS: monitoringv1.HTTPConfigWithoutTLS{ + FollowRedirects: ptr.To(true), + }, + }, }, }, amConfig: &monitoringv1alpha1.AlertmanagerConfig{ @@ -736,7 +756,7 @@ func TestInitializeFromAlertmanagerConfig(t *testing.T) { name: "valid globalConfig httpconfig/proxyconfig/proxyConnectHeader with amVersion26", amVersion: &version26, globalConfig: &monitoringv1.AlertmanagerGlobalConfig{ - HTTPConfig: &monitoringv1.HTTPConfig{ + HTTPConfigWithProxy: &monitoringv1.HTTPConfigWithProxy{ ProxyConfig: monitoringv1.ProxyConfig{ ProxyURL: ptr.To("http://example.com"), NoProxy: ptr.To("svc.cluster.local"), @@ -751,7 +771,11 @@ func TestInitializeFromAlertmanagerConfig(t *testing.T) { }, }, }, - FollowRedirects: ptr.To(true), + HTTPConfig: monitoringv1.HTTPConfig{ + HTTPConfigWithoutTLS: monitoringv1.HTTPConfigWithoutTLS{ + FollowRedirects: ptr.To(true), + }, + }, }, }, amConfig: &monitoringv1alpha1.AlertmanagerConfig{ @@ -907,29 +931,33 @@ func TestInitializeFromAlertmanagerConfig(t *testing.T) { }, }, ResolveTimeout: "30s", - HTTPConfig: &monitoringv1.HTTPConfig{ - OAuth2: &monitoringv1.OAuth2{ - ClientID: monitoringv1.SecretOrConfigMap{ - ConfigMap: &corev1.ConfigMapKeySelector{ - LocalObjectReference: corev1.LocalObjectReference{ - Name: "webhook-client-id", + HTTPConfigWithProxy: &monitoringv1.HTTPConfigWithProxy{ + HTTPConfig: monitoringv1.HTTPConfig{ + HTTPConfigWithoutTLS: monitoringv1.HTTPConfigWithoutTLS{ + OAuth2: &monitoringv1.OAuth2{ + ClientID: monitoringv1.SecretOrConfigMap{ + ConfigMap: &corev1.ConfigMapKeySelector{ + LocalObjectReference: corev1.LocalObjectReference{ + Name: "webhook-client-id", + }, + Key: "test", + }, + }, + ClientSecret: corev1.SecretKeySelector{ + LocalObjectReference: corev1.LocalObjectReference{ + Name: "webhook-client-secret", + }, + Key: "test", + }, + TokenURL: "https://test.com", + Scopes: []string{"any"}, + EndpointParams: map[string]string{ + "some": "value", }, - Key: "test", - }, - }, - ClientSecret: corev1.SecretKeySelector{ - LocalObjectReference: corev1.LocalObjectReference{ - Name: "webhook-client-secret", }, - Key: "test", - }, - TokenURL: "https://test.com", - Scopes: []string{"any"}, - EndpointParams: map[string]string{ - "some": "value", + FollowRedirects: ptr.To(true), }, }, - FollowRedirects: ptr.To(true), }, }, amConfig: &monitoringv1alpha1.AlertmanagerConfig{ @@ -1805,43 +1833,47 @@ func TestInitializeFromAlertmanagerConfig(t *testing.T) { amVersion: &version28, globalConfig: &monitoringv1.AlertmanagerGlobalConfig{ ResolveTimeout: "30s", - HTTPConfig: &monitoringv1.HTTPConfig{ - OAuth2: &monitoringv1.OAuth2{ - ClientID: monitoringv1.SecretOrConfigMap{ - ConfigMap: &corev1.ConfigMapKeySelector{ - LocalObjectReference: corev1.LocalObjectReference{ - Name: "webhook-client-id", + HTTPConfigWithProxy: &monitoringv1.HTTPConfigWithProxy{ + HTTPConfig: monitoringv1.HTTPConfig{ + HTTPConfigWithoutTLS: monitoringv1.HTTPConfigWithoutTLS{ + OAuth2: &monitoringv1.OAuth2{ + ClientID: monitoringv1.SecretOrConfigMap{ + ConfigMap: &corev1.ConfigMapKeySelector{ + LocalObjectReference: corev1.LocalObjectReference{ + Name: "webhook-client-id", + }, + Key: "test", + }, + }, + ClientSecret: corev1.SecretKeySelector{ + LocalObjectReference: corev1.LocalObjectReference{ + Name: "webhook-client-secret", + }, + Key: "test", + }, + TokenURL: "https://test.com", + Scopes: []string{"any"}, + EndpointParams: map[string]string{ + "some": "value", }, - Key: "test", - }, - }, - ClientSecret: corev1.SecretKeySelector{ - LocalObjectReference: corev1.LocalObjectReference{ - Name: "webhook-client-secret", - }, - Key: "test", - }, - TokenURL: "https://test.com", - Scopes: []string{"any"}, - EndpointParams: map[string]string{ - "some": "value", - }, - }, - BasicAuth: &monitoringv1.BasicAuth{ - Username: corev1.SecretKeySelector{ - LocalObjectReference: corev1.LocalObjectReference{ - Name: "webhook-client-secret", }, - Key: "test", - }, - Password: corev1.SecretKeySelector{ - LocalObjectReference: corev1.LocalObjectReference{ - Name: "webhook-client-secret", + BasicAuth: &monitoringv1.BasicAuth{ + Username: corev1.SecretKeySelector{ + LocalObjectReference: corev1.LocalObjectReference{ + Name: "webhook-client-secret", + }, + Key: "test", + }, + Password: corev1.SecretKeySelector{ + LocalObjectReference: corev1.LocalObjectReference{ + Name: "webhook-client-secret", + }, + Key: "test", + }, }, - Key: "test", + FollowRedirects: ptr.To(true), }, }, - FollowRedirects: ptr.To(true), }, }, amConfig: &monitoringv1alpha1.AlertmanagerConfig{ @@ -2633,15 +2665,15 @@ func TestGenerateConfig(t *testing.T) { }, PagerDutyImageConfigs: []monitoringv1alpha1.PagerDutyImageConfig{ { - Src: "https://some-image.com", - Href: "https://some-image.com", - Alt: "some-image", + Src: ptr.To("https://some-image.com"), + Href: ptr.To(monitoringv1alpha1.URL("https://some-image.com")), + Alt: ptr.To("some-image"), }, }, PagerDutyLinkConfigs: []monitoringv1alpha1.PagerDutyLinkConfig{ { - Href: "https://some-link.com", - Text: "some-link", + Href: ptr.To(monitoringv1alpha1.URL("https://some-link.com")), + Text: ptr.To("some-link"), }, }, }}, @@ -2692,7 +2724,7 @@ func TestGenerateConfig(t *testing.T) { Receivers: []monitoringv1alpha1.Receiver{{ Name: "test", WebhookConfigs: []monitoringv1alpha1.WebhookConfig{{ - URL: ptr.To("http://test.url"), + URL: ptr.To(monitoringv1alpha1.URL("http://test.url")), HTTPConfig: &monitoringv1alpha1.HTTPConfig{ OAuth2: &monitoringv1.OAuth2{ ClientID: monitoringv1.SecretOrConfigMap{ @@ -2818,6 +2850,52 @@ func TestGenerateConfig(t *testing.T) { }, golden: "CR_with_Opsgenie_Team_Responder.golden", }, + { + name: "CR with Opsgenie Receiver", + kclient: fake.NewSimpleClientset( + &corev1.Secret{ + ObjectMeta: metav1.ObjectMeta{ + Name: "am-og-test-receiver", + Namespace: "mynamespace", + }, + Data: map[string][]byte{ + "apiKey": []byte("1234abc"), + }, + }, + ), + baseConfig: alertmanagerConfig{ + Route: &route{ + Receiver: "null", + }, + Receivers: []*receiver{{Name: "null"}}, + }, + amConfigs: map[string]*monitoringv1alpha1.AlertmanagerConfig{ + "mynamespace": { + ObjectMeta: metav1.ObjectMeta{ + Name: "myamc", + Namespace: "mynamespace", + }, + Spec: monitoringv1alpha1.AlertmanagerConfigSpec{ + Route: &monitoringv1alpha1.Route{ + Receiver: "test", + }, + Receivers: []monitoringv1alpha1.Receiver{{ + Name: "test", + OpsGenieConfigs: []monitoringv1alpha1.OpsGenieConfig{{ + APIKey: &corev1.SecretKeySelector{ + LocalObjectReference: corev1.LocalObjectReference{ + Name: "am-og-test-receiver", + }, + Key: "apiKey", + }, + APIURL: ptr.To(monitoringv1alpha1.URL("https://example.com/")), + }}, + }}, + }, + }, + }, + golden: "CR_with_Opsgenie_Receiver_Valid_APIURL.golden", + }, { name: "CR with WeChat Receiver", kclient: fake.NewSimpleClientset( @@ -2917,8 +2995,8 @@ func TestGenerateConfig(t *testing.T) { }, Key: "token", }, - Retry: "5m", - Expire: "30s", + Retry: ptr.To("5m"), + Expire: ptr.To("30s"), HTML: ptr.To(true), }}, }}, @@ -2960,7 +3038,7 @@ func TestGenerateConfig(t *testing.T) { Receivers: []monitoringv1alpha1.Receiver{{ Name: "test", TelegramConfigs: []monitoringv1alpha1.TelegramConfig{{ - APIURL: "https://api.telegram.org", + APIURL: ptr.To(monitoringv1alpha1.URL("https://api.telegram.org")), BotToken: &corev1.SecretKeySelector{ LocalObjectReference: corev1.LocalObjectReference{ Name: "am-telegram-test-receiver", @@ -3005,7 +3083,7 @@ func TestGenerateConfig(t *testing.T) { { Type: "type", Text: "text", - Name: "my-action", + Name: ptr.To("my-action"), ConfirmField: &monitoringv1alpha1.SlackConfirmationField{ Text: "text", }, @@ -3053,7 +3131,7 @@ func TestGenerateConfig(t *testing.T) { { Type: "type", Text: "text", - Name: "my-action", + Name: ptr.To("my-action"), ConfirmField: &monitoringv1alpha1.SlackConfirmationField{ Text: "text", }, @@ -3238,7 +3316,7 @@ func TestGenerateConfig(t *testing.T) { { Type: "type", Text: "text", - Name: "my-action", + Name: ptr.To("my-action"), ConfirmField: &monitoringv1alpha1.SlackConfirmationField{ Text: "text", }, @@ -3319,7 +3397,7 @@ func TestGenerateConfig(t *testing.T) { { Type: "type", Text: "text", - Name: "my-action", + Name: ptr.To("my-action"), ConfirmField: &monitoringv1alpha1.SlackConfirmationField{ Text: "text", }, @@ -3771,7 +3849,7 @@ func TestGenerateConfig(t *testing.T) { Name: "test", WebhookConfigs: []monitoringv1alpha1.WebhookConfig{ { - URL: ptr.To("https://example.com/"), + URL: ptr.To(monitoringv1alpha1.URL("https://example.com/")), Timeout: ptr.To(monitoringv1.Duration("5s")), }, }, @@ -3807,7 +3885,7 @@ func TestGenerateConfig(t *testing.T) { Name: "test", WebhookConfigs: []monitoringv1alpha1.WebhookConfig{ { - URL: ptr.To("https://example.com/"), + URL: ptr.To(monitoringv1alpha1.URL("https://example.com/")), Timeout: ptr.To(monitoringv1.Duration("5s")), }, }, @@ -3893,6 +3971,15 @@ func TestSanitizeConfig(t *testing.T) { versionSMTPTLSConfigAllowed := semver.Version{Major: 0, Minor: 28} versionSMTPTLSConfigNotAllowed := semver.Version{Major: 0, Minor: 27} + versionMattermostConfigAllowed := semver.Version{Major: 0, Minor: 30} + versionMattermostConfigNotAllowed := semver.Version{Major: 0, Minor: 29} + + versionTimeoutConfigAllowed := semver.Version{Major: 0, Minor: 30} + versionTimeoutConfigNotAllowed := semver.Version{Major: 0, Minor: 29} + + versionSlackAppConfigAllowed := semver.Version{Major: 0, Minor: 30} + versionSlackAppConfigNotAllowed := semver.Version{Major: 0, Minor: 29} + for _, tc := range []struct { name string againstVersion semver.Version @@ -4002,6 +4089,38 @@ func TestSanitizeConfig(t *testing.T) { }, golden: "test_slack_config_happy_path.golden", }, + { + name: "Test timeout is dropped in slack config for unsupported versions", + againstVersion: versionTimeoutConfigNotAllowed, + in: &alertmanagerConfig{ + Receivers: []*receiver{ + { + SlackConfigs: []*slackConfig{ + { + Timeout: ptr.To(model.Duration(time.Minute)), + }, + }, + }, + }, + }, + golden: "test_slack_timeout_is_dropped_in_slack_config_for_unsupported_versions.golden", + }, + { + name: "Test timeout is added in slack config for supported versions", + againstVersion: versionTimeoutConfigAllowed, + in: &alertmanagerConfig{ + Receivers: []*receiver{ + { + SlackConfigs: []*slackConfig{ + { + Timeout: ptr.To(model.Duration(time.Minute)), + }, + }, + }, + }, + }, + golden: "test_slack_timeout_is_added_in_slack_config_for_supported_versions.golden", + }, { name: "Test inhibit rules error with unsupported syntax", againstVersion: matcherV2SyntaxNotAllowed, @@ -4553,6 +4672,207 @@ func TestSanitizeConfig(t *testing.T) { }, golden: "summary_add_in_supported_versions_for_MSTeams_config.golden", }, + { + name: "Test config version mattermost allowed", + againstVersion: versionMattermostConfigAllowed, + in: &alertmanagerConfig{ + Receivers: []*receiver{ + { + MattermostConfigs: []*mattermostConfig{ + { + WebhookURL: "www.test.com", + Text: "test text", + }, + }, + }, + }, + }, + golden: "test_config_version_mattermost_allowed.golden", + }, + { + name: "Test drop config version mattermost not allowed", + againstVersion: versionMattermostConfigNotAllowed, + in: &alertmanagerConfig{ + Receivers: []*receiver{ + { + MattermostConfigs: []*mattermostConfig{ + { + WebhookURL: "www.test.com", + Text: "test text", + }, + }, + }, + }, + }, + expectErr: true, + }, + { + name: "Test webhook_url takes precedence in mattermost config", + againstVersion: versionMattermostConfigAllowed, + in: &alertmanagerConfig{ + Receivers: []*receiver{ + { + MattermostConfigs: []*mattermostConfig{ + { + WebhookURL: "www.test.com", + WebhookURLFile: "/test", + Text: "test text", + }, + }, + }, + }, + }, + golden: "test_webhook_url_takes_precedence_in_mattermost_config.golden", + }, + { + name: "Test timeout is dropped in pagerduty config for unsupported versions", + againstVersion: versionTimeoutConfigNotAllowed, + + in: &alertmanagerConfig{ + Receivers: []*receiver{ + { + PagerdutyConfigs: []*pagerdutyConfig{ + { + Timeout: ptr.To(model.Duration(time.Minute)), + }, + }, + }, + }, + }, + golden: "test_pagerduty_timeout_is_dropped_in_pagerduty_config_for_unsupported_versions.golden", + }, + { + name: "Test timeout is added in pagerduty config for supported versions", + againstVersion: versionTimeoutConfigAllowed, + in: &alertmanagerConfig{ + Receivers: []*receiver{ + { + PagerdutyConfigs: []*pagerdutyConfig{ + { + Timeout: ptr.To(model.Duration(time.Minute)), + }, + }, + }, + }, + }, + golden: "test_pagerduty_timeout_is_added_in_pagerduty_config_for_supported_versions.golden", + }, + { + name: "Test slack_app_token is dropped for unsupported versions", + againstVersion: versionSlackAppConfigNotAllowed, + in: &alertmanagerConfig{ + Global: &globalConfig{ + SlackAppToken: "xoxb-token", + SlackAppURL: &config.URL{ + URL: &url.URL{ + Scheme: "https", + Host: "slack.com", + Path: "/api/chat.postMessage", + }, + }, + }, + }, + golden: "test_slack_app_token_is_dropped_for_unsupported_versions.golden", + }, + { + name: "Test slack_app_url is dropped for unsupported versions", + againstVersion: versionSlackAppConfigNotAllowed, + in: &alertmanagerConfig{ + Global: &globalConfig{ + SlackAppURL: &config.URL{ + URL: &url.URL{ + Scheme: "https", + Host: "slack.com", + Path: "/api/chat.postMessage", + }, + }, + }, + }, + golden: "test_slack_app_url_is_dropped_for_unsupported_versions.golden", + }, + { + name: "Test slack_app_token and slack_app_url preserved for supported versions", + againstVersion: versionSlackAppConfigAllowed, + in: &alertmanagerConfig{ + Global: &globalConfig{ + SlackAppToken: "xoxb-token", + SlackAppURL: &config.URL{ + URL: &url.URL{ + Scheme: "https", + Host: "slack.com", + Path: "/api/chat.postMessage", + }, + }, + }, + }, + golden: "test_slack_app_token_and_slack_app_url_preserved_for_supported_versions.golden", + }, + { + name: "Test slack_app_token takes precedence over slack_app_token_file", + againstVersion: versionSlackAppConfigAllowed, + in: &alertmanagerConfig{ + Global: &globalConfig{ + SlackAppToken: "xoxb-token", + SlackAppTokenFile: "/var/secrets/token", + SlackAppURL: &config.URL{ + URL: &url.URL{ + Scheme: "https", + Host: "slack.com", + Path: "/api/chat.postMessage", + }, + }, + }, + }, + golden: "test_slack_app_token_takes_precedence_over_slack_app_token_file.golden", + }, + { + name: "Test slack_app_token and slack_api_url both configured with different URLs fails", + againstVersion: versionSlackAppConfigAllowed, + in: &alertmanagerConfig{ + Global: &globalConfig{ + SlackAPIURL: &config.URL{ + URL: &url.URL{ + Scheme: "https", + Host: "hooks.slack.com", + Path: "/services/XXX", + }, + }, + SlackAppToken: "xoxb-token", + SlackAppURL: &config.URL{ + URL: &url.URL{ + Scheme: "https", + Host: "slack.com", + Path: "/api/chat.postMessage", + }, + }, + }, + }, + expectErr: true, + }, + { + name: "Test slack_app_token and slack_api_url with same URL is allowed", + againstVersion: versionSlackAppConfigAllowed, + in: &alertmanagerConfig{ + Global: &globalConfig{ + SlackAPIURL: &config.URL{ + URL: &url.URL{ + Scheme: "https", + Host: "slack.com", + Path: "/api/chat.postMessage", + }, + }, + SlackAppToken: "xoxb-token", + SlackAppURL: &config.URL{ + URL: &url.URL{ + Scheme: "https", + Host: "slack.com", + Path: "/api/chat.postMessage", + }, + }, + }, + }, + golden: "test_slack_app_token_and_slack_api_url_with_same_url_is_allowed.golden", + }, } { t.Run(tc.name, func(t *testing.T) { err := tc.in.sanitize(tc.againstVersion, logger) @@ -5348,6 +5668,7 @@ func TestSanitizeWebhookConfig(t *testing.T) { againstVersion semver.Version in *alertmanagerConfig golden string + expectErr bool }{ { name: "Test webhook_url_file is dropped in webhook config for unsupported versions", @@ -5373,7 +5694,7 @@ func TestSanitizeWebhookConfig(t *testing.T) { { WebhookConfigs: []*webhookConfig{ { - URL: "foo", + URL: "http://example.com/foo", URLFile: "bar", }, }, @@ -5414,14 +5735,50 @@ func TestSanitizeWebhookConfig(t *testing.T) { }, golden: "test_webhook_timeout_is_added_in_webhook_config_for_supported_versions.golden", }, - } { - t.Run(tc.name, func(t *testing.T) { - err := tc.in.sanitize(tc.againstVersion, logger) - require.NoError(t, err) - - amConfigs, err := yaml.Marshal(tc.in) - require.NoError(t, err) - + { + name: "Test invalid url returns error", + againstVersion: semver.Version{Major: 0, Minor: 26}, + in: &alertmanagerConfig{ + Receivers: []*receiver{ + { + WebhookConfigs: []*webhookConfig{ + { + URL: "not-a-valid-url", + }, + }, + }, + }, + }, + expectErr: true, + }, + { + name: "Test valid url passes validation", + againstVersion: semver.Version{Major: 0, Minor: 26}, + in: &alertmanagerConfig{ + Receivers: []*receiver{ + { + WebhookConfigs: []*webhookConfig{ + { + URL: "http://example.com/webhook", + }, + }, + }, + }, + }, + golden: "test_webhook_valid_url_passes.golden", + }, + } { + t.Run(tc.name, func(t *testing.T) { + err := tc.in.sanitize(tc.againstVersion, logger) + if tc.expectErr { + require.Error(t, err) + return + } + require.NoError(t, err) + + amConfigs, err := yaml.Marshal(tc.in) + require.NoError(t, err) + golden.Assert(t, string(amConfigs), tc.golden) }) } @@ -5435,6 +5792,7 @@ func TestSanitizePushoverConfig(t *testing.T) { againstVersion semver.Version in *alertmanagerConfig golden string + expectErr bool }{ { name: "Test pushover_user_key_file is dropped in pushover config for unsupported versions", @@ -5508,9 +5866,49 @@ func TestSanitizePushoverConfig(t *testing.T) { }, golden: "test_token_takes_precedence_in_pushover_config.golden", }, + { + name: "Test invalid url returns error", + againstVersion: semver.Version{Major: 0, Minor: 26}, + in: &alertmanagerConfig{ + Receivers: []*receiver{ + { + PushoverConfigs: []*pushoverConfig{ + { + UserKey: "key", + Token: "token", + URL: "not-a-valid-url", + }, + }, + }, + }, + }, + expectErr: true, + }, + { + name: "Test valid url passes validation", + againstVersion: semver.Version{Major: 0, Minor: 26}, + in: &alertmanagerConfig{ + Receivers: []*receiver{ + { + PushoverConfigs: []*pushoverConfig{ + { + UserKey: "key", + Token: "token", + URL: "http://example.com", + }, + }, + }, + }, + }, + golden: "test_pushover_valid_url_passes.golden", + }, } { t.Run(tc.name, func(t *testing.T) { err := tc.in.sanitize(tc.againstVersion, logger) + if tc.expectErr { + require.Error(t, err) + return + } require.NoError(t, err) amConfigs, err := yaml.Marshal(tc.in) @@ -5645,6 +6043,9 @@ func TestSanitizeJiraConfig(t *testing.T) { logger := newNopLogger(t) versionJiraAllowed := semver.Version{Major: 0, Minor: 28} versionJiraNotAllowed := semver.Version{Major: 0, Minor: 27} + + versionAPITypeAllowed := semver.Version{Major: 0, Minor: 29} + versionAPITypeNotAllowed := semver.Version{Major: 0, Minor: 28} for _, tc := range []struct { name string againstVersion semver.Version @@ -5721,6 +6122,63 @@ func TestSanitizeJiraConfig(t *testing.T) { }, golden: "jira_configs_with_send_resolved.golden", }, + { + name: "jira_configs with api_type", + againstVersion: versionAPITypeAllowed, + in: &alertmanagerConfig{ + Receivers: []*receiver{ + { + JiraConfigs: []*jiraConfig{ + { + APIURL: "http://issues.example.com", + Project: "Monitoring", + APIType: "datacenter", + IssueType: "Bug", + }, + }, + }, + }, + }, + golden: "jira_config_with_api_type.golden", + }, + { + name: "jira_configs with api_type version not supported", + againstVersion: versionAPITypeNotAllowed, + in: &alertmanagerConfig{ + Receivers: []*receiver{ + { + JiraConfigs: []*jiraConfig{ + { + APIURL: "http://issues.example.com", + Project: "Monitoring", + APIType: "datacenter", + IssueType: "Bug", + }, + }, + }, + }, + }, + golden: "jira_config_with_api_type_version_not_supported.golden", + }, + { + name: "jira_configs with invalid api_type", + againstVersion: versionAPITypeAllowed, + in: &alertmanagerConfig{ + Receivers: []*receiver{ + { + JiraConfigs: []*jiraConfig{ + { + APIURL: "http://issues.example.com", + Project: "Monitoring", + APIType: "onpremise", + IssueType: "Bug", + }, + }, + }, + }, + }, + expectErr: true, + }, } { t.Run(tc.name, func(t *testing.T) { err := tc.in.sanitize(tc.againstVersion, logger) @@ -5990,6 +6448,198 @@ func TestSanitizeRocketChatConfig(t *testing.T) { } } +func TestSanitizeIncidentioConfig(t *testing.T) { + logger := newNopLogger(t) + versionIncidentioAllowed := semver.Version{Major: 0, Minor: 29} + versionIncidentioNotAllowed := semver.Version{Major: 0, Minor: 28} + for _, tc := range []struct { + name string + againstVersion semver.Version + in *alertmanagerConfig + golden string + expectErr bool + }{ + { + name: "incidentio_configs returns error for unsupported versions", + againstVersion: versionIncidentioNotAllowed, + in: &alertmanagerConfig{ + Receivers: []*receiver{ + { + IncidentioConfigs: []*incidentioConfig{ + { + URL: "http://example.com", + AlertSourceToken: "token123", + }, + }, + }, + }, + }, + expectErr: true, + }, + { + name: "incidentio_configs allows for supported versions", + againstVersion: versionIncidentioAllowed, + in: &alertmanagerConfig{ + Receivers: []*receiver{ + { + IncidentioConfigs: []*incidentioConfig{ + { + URL: "http://example.com", + AlertSourceToken: "token123", + }, + }, + }, + }, + }, + golden: "incidentio_configs_for_supported_versions.golden", + }, + { + name: "incidentio_configs invalid url returns error", + againstVersion: versionIncidentioAllowed, + in: &alertmanagerConfig{ + Receivers: []*receiver{ + { + IncidentioConfigs: []*incidentioConfig{ + { + URL: "not-a-valid-url", + AlertSourceToken: "token123", + }, + }, + }, + }, + }, + expectErr: true, + }, + { + name: "incidentio_configs both url and url_file set", + againstVersion: versionIncidentioAllowed, + in: &alertmanagerConfig{ + Receivers: []*receiver{ + { + IncidentioConfigs: []*incidentioConfig{ + { + URL: "http://example.com", + URLFile: "/var/kubernetes/secrets/url", + AlertSourceToken: "token123", + }, + }, + }, + }, + }, + expectErr: true, + }, + { + name: "incidentio_configs both alert_source_token and alert_source_token_file set", + againstVersion: versionIncidentioAllowed, + in: &alertmanagerConfig{ + Receivers: []*receiver{ + { + IncidentioConfigs: []*incidentioConfig{ + { + URL: "http://example.com", + AlertSourceToken: "token123", + AlertSourceTokenFile: "/var/kubernetes/secrets/token", + }, + }, + }, + }, + }, + expectErr: true, + }, + { + name: "incidentio_configs missing url and url_file", + againstVersion: versionIncidentioAllowed, + in: &alertmanagerConfig{ + Receivers: []*receiver{ + { + IncidentioConfigs: []*incidentioConfig{ + { + AlertSourceToken: "token123", + }, + }, + }, + }, + }, + expectErr: true, + }, + { + name: "incidentio_configs missing authentication", + againstVersion: versionIncidentioAllowed, + in: &alertmanagerConfig{ + Receivers: []*receiver{ + { + IncidentioConfigs: []*incidentioConfig{ + { + URL: "http://example.com", + }, + }, + }, + }, + }, + expectErr: true, + }, + { + name: "incidentio_configs with http_config.authorization and alert_source_token", + againstVersion: versionIncidentioAllowed, + in: &alertmanagerConfig{ + Receivers: []*receiver{ + { + IncidentioConfigs: []*incidentioConfig{ + { + URL: "http://example.com", + AlertSourceToken: "token123", + HTTPConfig: &httpClientConfig{ + Authorization: &authorization{ + Type: "Bearer", + Credentials: "creds123", + }, + }, + }, + }, + }, + }, + }, + expectErr: true, + }, + { + name: "incidentio_configs with http_config.authorization only", + againstVersion: versionIncidentioAllowed, + in: &alertmanagerConfig{ + Receivers: []*receiver{ + { + IncidentioConfigs: []*incidentioConfig{ + { + URL: "http://example.com", + HTTPConfig: &httpClientConfig{ + Authorization: &authorization{ + Type: "Bearer", + Credentials: "creds123", + }, + }, + }, + }, + }, + }, + }, + golden: "incidentio_configs_with_http_authorization.golden", + }, + } { + t.Run(tc.name, func(t *testing.T) { + err := tc.in.sanitize(tc.againstVersion, logger) + if tc.expectErr { + require.Error(t, err) + return + } + + require.NoError(t, err) + + amConfigs, err := yaml.Marshal(tc.in) + require.NoError(t, err) + + golden.Assert(t, string(amConfigs), tc.golden) + }) + } +} func TestSanitizeRoute(t *testing.T) { logger := newNopLogger(t) matcherV2SyntaxAllowed := semver.Version{Major: 0, Minor: 22} @@ -6318,6 +6968,130 @@ func TestConvertHTTPConfig(t *testing.T) { } } +func TestSanitizeTelegramConfig(t *testing.T) { + logger := newNopLogger(t) + versionTelegramExampleAllowed := semver.Version{Major: 0, Minor: 26} + + for _, tc := range []struct { + name string + againstVersion semver.Version + in *alertmanagerConfig + golden string + expectErr bool + }{ + { + name: "telegram invalid api_url returns error", + againstVersion: versionTelegramExampleAllowed, + in: &alertmanagerConfig{ + Receivers: []*receiver{ + { + TelegramConfigs: []*telegramConfig{ + { + APIUrl: "not-a-valid-url", + BotToken: "token", + ChatID: 12345, + }, + }, + }, + }, + }, + expectErr: true, + }, + { + name: "telegram valid api_url passes validation", + againstVersion: versionTelegramExampleAllowed, + in: &alertmanagerConfig{ + Receivers: []*receiver{ + { + TelegramConfigs: []*telegramConfig{ + { + APIUrl: "http://example.com", + BotToken: "token", + ChatID: 12345, + }, + }, + }, + }, + }, + golden: "telegram_valid_url_passes.golden", + }, + } { + t.Run(tc.name, func(t *testing.T) { + err := tc.in.sanitize(tc.againstVersion, logger) + if tc.expectErr { + require.Error(t, err) + return + } + require.NoError(t, err) + + amConfigs, err := yaml.Marshal(tc.in) + require.NoError(t, err) + + golden.Assert(t, string(amConfigs), tc.golden) + }) + } +} + +func TestSanitizeMSTeamsConfig(t *testing.T) { + logger := newNopLogger(t) + versionMSTeamsExampleAllowed := semver.Version{Major: 0, Minor: 27} + + for _, tc := range []struct { + name string + againstVersion semver.Version + in *alertmanagerConfig + golden string + expectErr bool + }{ + { + name: "msteams invalid webhook_url returns error", + againstVersion: versionMSTeamsExampleAllowed, + in: &alertmanagerConfig{ + Receivers: []*receiver{ + { + MSTeamsConfigs: []*msTeamsConfig{ + { + WebhookURL: "not-a-valid-url", + }, + }, + }, + }, + }, + expectErr: true, + }, + { + name: "msteams valid webhook_url passes validation", + againstVersion: versionMSTeamsExampleAllowed, + in: &alertmanagerConfig{ + Receivers: []*receiver{ + { + MSTeamsConfigs: []*msTeamsConfig{ + { + WebhookURL: "http://example.com/webhook", + }, + }, + }, + }, + }, + golden: "msteams_valid_url_passes.golden", + }, + } { + t.Run(tc.name, func(t *testing.T) { + err := tc.in.sanitize(tc.againstVersion, logger) + if tc.expectErr { + require.Error(t, err) + return + } + require.NoError(t, err) + + amConfigs, err := yaml.Marshal(tc.in) + require.NoError(t, err) + + golden.Assert(t, string(amConfigs), tc.golden) + }) + } +} + func newNopLogger(t *testing.T) *slog.Logger { t.Helper() return slog.New(slog.DiscardHandler) diff --git a/pkg/alertmanager/operator.go b/pkg/alertmanager/operator.go index 247df148ce7..65e3dba8f6c 100644 --- a/pkg/alertmanager/operator.go +++ b/pkg/alertmanager/operator.go @@ -39,6 +39,7 @@ import ( "k8s.io/client-go/metadata" "k8s.io/client-go/rest" "k8s.io/client-go/tools/cache" + "k8s.io/utils/ptr" "github.com/prometheus-operator/prometheus-operator/pkg/alertmanager/clustertlsconfig" "github.com/prometheus-operator/prometheus-operator/pkg/alertmanager/validation" @@ -284,17 +285,7 @@ func (c *Operator) bootstrap(ctx context.Context, config operator.Config) error c.kclient, resyncPeriod, func(options *metav1.ListOptions) { - // TODO(simonpasquier): use a more restrictive label selector - // selecting only Alertmanager statefulsets (e.g. - // "app.kubernetes.io/name in (alertmanager)"). - // - // We need to wait for a couple of releases after [1] merges to - // ensure that the expected labels have been propagated to the - // Alertmanager statefulsets otherwise the informer won't - // select any object. - // - // [1] https://github.com/prometheus-operator/prometheus-operator/pull/7786 - options.LabelSelector = operator.ManagedByOperatorLabelSelector() + options.LabelSelector = labelSelectorForStatefulSets() }, ), appsv1.SchemeGroupVersion.WithResource("statefulsets"), @@ -692,28 +683,11 @@ func (c *Operator) sync(ctx context.Context, key string) error { return nil } - err = k8sutil.UpdateStatefulSet(ctx, ssetClient, sset) - sErr, ok := err.(*apierrors.StatusError) - - if ok && sErr.ErrStatus.Code == 422 && sErr.ErrStatus.Reason == metav1.StatusReasonInvalid { + if err = k8sutil.ForceUpdateStatefulSet(ctx, ssetClient, sset, func(reason string) { c.metrics.StsDeleteCreateCounter().Inc() - - // Gather only reason for failed update - failMsg := make([]string, len(sErr.ErrStatus.Details.Causes)) - for i, cause := range sErr.ErrStatus.Details.Causes { - failMsg[i] = cause.Message - } - - logger.Info("recreating Alertmanager StatefulSet because the update operation wasn't possible", "reason", strings.Join(failMsg, ", ")) - propagationPolicy := metav1.DeletePropagationForeground - if err := ssetClient.Delete(ctx, sset.GetName(), metav1.DeleteOptions{PropagationPolicy: &propagationPolicy}); err != nil { - return fmt.Errorf("failed to delete StatefulSet to avoid forbidden action: %w", err) - } - return nil - } - - if err != nil { - return fmt.Errorf("updating StatefulSet failed: %w", err) + logger.Info("recreating StatefulSet because the update operation wasn't possible", "reason", reason) + }); err != nil { + return err } return nil @@ -791,6 +765,7 @@ func (c *Operator) UpdateStatus(ctx context.Context, key string) error { return nil } +// makeSelectorLabels returns the default selector for the pods of the Alertmanager statefulset. func makeSelectorLabels(name string) map[string]string { return map[string]string{ operator.ApplicationNameLabelKey: applicationNameLabelValue, @@ -800,6 +775,16 @@ func makeSelectorLabels(name string) map[string]string { } } +// labelSelectorForStatefulSets returns a label selector which selects +// all Alertmanager statefulsets. +func labelSelectorForStatefulSets() string { + return fmt.Sprintf( + "%s in (%s),%s in (%s)", + operator.ManagedByLabelKey, operator.ManagedByLabelValue, + operator.ApplicationNameLabelKey, applicationNameLabelValue, + ) +} + func createSSetInputHash(a monitoringv1.Alertmanager, c Config, tlsAssets *operator.ShardedSecret, s appsv1.StatefulSetSpec) (string, error) { var http2 *bool if a.Spec.Web != nil && a.Spec.Web.HTTPConfig != nil { @@ -1278,13 +1263,6 @@ func checkPagerDutyConfigs( } } - if config.URL != "" { - if _, err := validation.ValidateURL(strings.TrimSpace(config.URL)); err != nil { - return fmt.Errorf("failed to validate URL: %w ", err) - } - - } - if err := configureHTTPConfigInStore(ctx, config.HTTPConfig, namespace, store); err != nil { return err } @@ -1606,14 +1584,14 @@ func checkPushoverConfigs( return errors.New("html and monospace options are mutually exclusive") } - if config.Expire != "" { - if _, err := model.ParseDuration(config.Expire); err != nil { + if ptr.Deref(config.Expire, "") != "" { + if _, err := model.ParseDuration(*config.Expire); err != nil { return err } } - if config.Retry != "" { - if _, err := model.ParseDuration(config.Retry); err != nil { + if ptr.Deref(config.Retry, "") != "" { + if _, err := model.ParseDuration(*config.Retry); err != nil { return err } } diff --git a/pkg/alertmanager/operator_test.go b/pkg/alertmanager/operator_test.go index 5cecdaa7824..ecd00ef3953 100644 --- a/pkg/alertmanager/operator_test.go +++ b/pkg/alertmanager/operator_test.go @@ -470,7 +470,7 @@ func TestCheckAlertmanagerConfig(t *testing.T) { Name: "recv1", WebhookConfigs: []monitoringv1alpha1.WebhookConfig{ { - URL: ptr.To("http://test.local"), + URL: ptr.To(monitoringv1alpha1.URL("http://test.local")), }, }, }}, @@ -565,7 +565,7 @@ func TestCheckAlertmanagerConfig(t *testing.T) { WeChatConfigs: []monitoringv1alpha1.WeChatConfig{ { CorpID: "testingCorpID", - APIURL: "http://::invalid-url", + APIURL: ptr.To(monitoringv1alpha1.URL("http://::invalid-url")), }, }, }}, @@ -743,7 +743,7 @@ func TestCheckAlertmanagerConfig(t *testing.T) { { Type: "type", Text: "text", - URL: "http://localhost", + URL: ptr.To(monitoringv1alpha1.URL("http://localhost")), }, }, }, @@ -771,7 +771,7 @@ func TestCheckAlertmanagerConfig(t *testing.T) { { Type: "type", Text: "text", - Name: "my-action", + Name: ptr.To("my-action"), }, }, }, @@ -799,7 +799,7 @@ func TestCheckAlertmanagerConfig(t *testing.T) { { Type: "type", Text: "text", - Name: "my-action", + Name: ptr.To("my-action"), ConfirmField: &monitoringv1alpha1.SlackConfirmationField{ Text: "", }, @@ -830,7 +830,7 @@ func TestCheckAlertmanagerConfig(t *testing.T) { { Type: "type", Text: "text", - Name: "my-action", + Name: ptr.To("my-action"), ConfirmField: &monitoringv1alpha1.SlackConfirmationField{ Text: "text", }, @@ -940,7 +940,7 @@ func TestCheckAlertmanagerConfig(t *testing.T) { { Type: "type", Text: "text", - Name: "my-action", + Name: ptr.To("my-action"), ConfirmField: &monitoringv1alpha1.SlackConfirmationField{ Text: "text", }, diff --git a/pkg/alertmanager/statefulset.go b/pkg/alertmanager/statefulset.go index 07b34cb9434..51b2ed904c6 100644 --- a/pkg/alertmanager/statefulset.go +++ b/pkg/alertmanager/statefulset.go @@ -303,6 +303,16 @@ func makeStatefulSetSpec(logger *slog.Logger, a *monitoringv1.Alertmanager, conf } + if version.GTE(semver.MustParse("0.30.0")) && a.Spec.MinReadySeconds != nil { + startDelayArg := monitoringv1.Argument{ + Name: "dispatch.start-delay", + Value: fmt.Sprintf("%ds", *a.Spec.MinReadySeconds), + } + if i := operator.ArgumentsIntersection([]monitoringv1.Argument{startDelayArg}, a.Spec.AdditionalArgs); len(i) == 0 { + amArgs = append(amArgs, startDelayArg) + } + } + if a.Spec.LogLevel != "" && a.Spec.LogLevel != "info" { amArgs = append(amArgs, monitoringv1.Argument{Name: "log.level", Value: a.Spec.LogLevel}) } @@ -767,16 +777,18 @@ func makeStatefulSetSpec(logger *slog.Logger, a *monitoringv1.Alertmanager, conf return nil, fmt.Errorf("failed to merge init containers spec: %w", err) } + // By default, podManagementPolicy is set to Parallel to mitigate rollout + // issues in Kubernetes (see https://github.com/kubernetes/kubernetes/issues/60164). + // This is also mentioned as one of limitations of StatefulSets: + // https://kubernetes.io/docs/concepts/workloads/controllers/statefulset/#limitations + podManagementPolicy := ptr.Deref(a.Spec.PodManagementPolicy, monitoringv1.ParallelPodManagement) + spec := appsv1.StatefulSetSpec{ - ServiceName: getServiceName(a), - Replicas: a.Spec.Replicas, - MinReadySeconds: ptr.Deref(a.Spec.MinReadySeconds, 0), - // PodManagementPolicy is set to Parallel to mitigate issues in kubernetes: https://github.com/kubernetes/kubernetes/issues/60164 - // This is also mentioned as one of limitations of StatefulSets: https://kubernetes.io/docs/concepts/workloads/controllers/statefulset/#limitations - PodManagementPolicy: appsv1.ParallelPodManagement, - UpdateStrategy: appsv1.StatefulSetUpdateStrategy{ - Type: appsv1.RollingUpdateStatefulSetStrategyType, - }, + ServiceName: getServiceName(a), + Replicas: a.Spec.Replicas, + MinReadySeconds: ptr.Deref(a.Spec.MinReadySeconds, 0), + PodManagementPolicy: appsv1.PodManagementPolicyType(podManagementPolicy), + UpdateStrategy: operator.UpdateStrategyForStatefulSet(a.Spec.UpdateStrategy), Selector: &metav1.LabelSelector{ MatchLabels: finalSelectorLabels, }, diff --git a/pkg/alertmanager/statefulset_test.go b/pkg/alertmanager/statefulset_test.go index e4d8daf97ee..97b498c983e 100644 --- a/pkg/alertmanager/statefulset_test.go +++ b/pkg/alertmanager/statefulset_test.go @@ -1525,3 +1525,147 @@ func TestStatefulSetEnableServiceLinks(t *testing.T) { } } } + +func TestStatefulSetPodManagementPolicy(t *testing.T) { + for _, tc := range []struct { + podManagementPolicy *monitoringv1.PodManagementPolicyType + exp appsv1.PodManagementPolicyType + }{ + { + podManagementPolicy: nil, + exp: appsv1.ParallelPodManagement, + }, + { + podManagementPolicy: ptr.To(monitoringv1.ParallelPodManagement), + exp: appsv1.ParallelPodManagement, + }, + { + podManagementPolicy: ptr.To(monitoringv1.OrderedReadyPodManagement), + exp: appsv1.OrderedReadyPodManagement, + }, + } { + t.Run("", func(t *testing.T) { + sset, err := makeStatefulSet(nil, &monitoringv1.Alertmanager{ + Spec: monitoringv1.AlertmanagerSpec{ + PodManagementPolicy: tc.podManagementPolicy, + }, + }, defaultTestConfig, "", &operator.ShardedSecret{}) + + require.NoError(t, err) + require.Equal(t, tc.exp, sset.Spec.PodManagementPolicy) + }) + } +} + +func TestStatefulSetUpdateStrategy(t *testing.T) { + for _, tc := range []struct { + updateStrategy *monitoringv1.StatefulSetUpdateStrategy + exp appsv1.StatefulSetUpdateStrategy + }{ + { + updateStrategy: nil, + exp: appsv1.StatefulSetUpdateStrategy{ + Type: appsv1.RollingUpdateStatefulSetStrategyType, + }, + }, + { + updateStrategy: &monitoringv1.StatefulSetUpdateStrategy{ + Type: monitoringv1.RollingUpdateStatefulSetStrategyType, + }, + exp: appsv1.StatefulSetUpdateStrategy{ + Type: appsv1.RollingUpdateStatefulSetStrategyType, + }, + }, + { + updateStrategy: &monitoringv1.StatefulSetUpdateStrategy{ + Type: monitoringv1.RollingUpdateStatefulSetStrategyType, + RollingUpdate: &monitoringv1.RollingUpdateStatefulSetStrategy{ + MaxUnavailable: ptr.To(intstr.FromInt(1)), + }, + }, + exp: appsv1.StatefulSetUpdateStrategy{ + Type: appsv1.RollingUpdateStatefulSetStrategyType, + RollingUpdate: &appsv1.RollingUpdateStatefulSetStrategy{ + MaxUnavailable: ptr.To(intstr.FromInt(1)), + }, + }, + }, + { + updateStrategy: &monitoringv1.StatefulSetUpdateStrategy{ + Type: monitoringv1.OnDeleteStatefulSetStrategyType, + }, + exp: appsv1.StatefulSetUpdateStrategy{ + Type: appsv1.OnDeleteStatefulSetStrategyType, + }, + }, + } { + t.Run("", func(t *testing.T) { + sset, err := makeStatefulSet(nil, &monitoringv1.Alertmanager{ + Spec: monitoringv1.AlertmanagerSpec{ + UpdateStrategy: tc.updateStrategy, + }, + }, defaultTestConfig, "", &operator.ShardedSecret{}) + + require.NoError(t, err) + require.Equal(t, tc.exp, sset.Spec.UpdateStrategy) + }) + } +} + +func TestMakeStatefulSetSpecDispatchStartDelay(t *testing.T) { + for _, tc := range []struct { + version string + minReadySeconds *int32 + additionalArgs []monitoringv1.Argument + + expContains string + expNotContains string + }{ + { + version: "v0.30.0", + expNotContains: "dispatch.start-delay", + }, + { + version: "v0.30.0", + additionalArgs: []monitoringv1.Argument{{Name: "dispatch.start-delay", Value: "1m"}}, + expContains: "--dispatch.start-delay=1m", + }, + { + version: "v0.29.0", + minReadySeconds: ptr.To(int32(60)), + expNotContains: "dispatch.start-delay", + }, + { + version: "v0.30.0", + minReadySeconds: ptr.To(int32(60)), + expContains: "--dispatch.start-delay=60s", + }, + { + version: "v0.30.0", + minReadySeconds: ptr.To(int32(60)), + additionalArgs: []monitoringv1.Argument{{Name: "dispatch.start-delay", Value: "10s"}}, + expContains: "--dispatch.start-delay=10s", + }, + } { + t.Run("", func(t *testing.T) { + a := monitoringv1.Alertmanager{ + Spec: monitoringv1.AlertmanagerSpec{ + Replicas: ptr.To(int32(1)), + Version: tc.version, + MinReadySeconds: tc.minReadySeconds, + AdditionalArgs: tc.additionalArgs, + }, + } + + statefulSet, err := makeStatefulSetSpec(nil, &a, defaultTestConfig, &operator.ShardedSecret{}) + require.NoError(t, err) + + if tc.expContains != "" { + require.Contains(t, statefulSet.Template.Spec.Containers[0].Args, tc.expContains) + } + if tc.expNotContains != "" { + require.NotContains(t, statefulSet.Template.Spec.Containers[0].Args, tc.expNotContains) + } + }) + } +} diff --git a/pkg/alertmanager/testdata/CR_with_Mattermost_Reeceiver_Bare_Minimum.golden b/pkg/alertmanager/testdata/CR_with_Mattermost_Reeceiver_Bare_Minimum.golden new file mode 100644 index 00000000000..339b9833ddd --- /dev/null +++ b/pkg/alertmanager/testdata/CR_with_Mattermost_Reeceiver_Bare_Minimum.golden @@ -0,0 +1,14 @@ +route: + receiver: "null" + routes: + - receiver: mynamespace/myamc/test + matchers: + - namespace="mynamespace" + continue: true +receivers: +- name: "null" +- name: mynamespace/myamc/test + mattermost_configs: + - webhook_url: https://mattermost.example.com + text: test text +templates: [] diff --git a/pkg/alertmanager/testdata/CR_with_Opsgenie_Receiver_Valid_APIURL.golden b/pkg/alertmanager/testdata/CR_with_Opsgenie_Receiver_Valid_APIURL.golden new file mode 100644 index 00000000000..2ae484ce774 --- /dev/null +++ b/pkg/alertmanager/testdata/CR_with_Opsgenie_Receiver_Valid_APIURL.golden @@ -0,0 +1,14 @@ +route: + receiver: "null" + routes: + - receiver: mynamespace/myamc/test + matchers: + - namespace="mynamespace" + continue: true +receivers: +- name: "null" +- name: mynamespace/myamc/test + opsgenie_configs: + - api_key: 1234abc + api_url: https://example.com/ +templates: [] diff --git a/pkg/alertmanager/testdata/incidentio_configs_for_supported_versions.golden b/pkg/alertmanager/testdata/incidentio_configs_for_supported_versions.golden new file mode 100644 index 00000000000..a2d4092c7aa --- /dev/null +++ b/pkg/alertmanager/testdata/incidentio_configs_for_supported_versions.golden @@ -0,0 +1,6 @@ +receivers: +- name: "" + incidentio_configs: + - url: http://example.com + alert_source_token: token123 +templates: [] diff --git a/pkg/alertmanager/testdata/incidentio_configs_with_http_authorization.golden b/pkg/alertmanager/testdata/incidentio_configs_with_http_authorization.golden new file mode 100644 index 00000000000..63b0cf0e021 --- /dev/null +++ b/pkg/alertmanager/testdata/incidentio_configs_with_http_authorization.golden @@ -0,0 +1,9 @@ +receivers: +- name: "" + incidentio_configs: + - http_config: + authorization: + type: Bearer + credentials: creds123 + url: http://example.com +templates: [] diff --git a/pkg/alertmanager/testdata/jira_config_with_api_type.golden b/pkg/alertmanager/testdata/jira_config_with_api_type.golden new file mode 100644 index 00000000000..d015b86d58f --- /dev/null +++ b/pkg/alertmanager/testdata/jira_config_with_api_type.golden @@ -0,0 +1,8 @@ +receivers: +- name: "" + jira_configs: + - api_url: http://issues.example.com + project: Monitoring + issue_type: Bug + api_type: datacenter +templates: [] diff --git a/pkg/alertmanager/testdata/jira_config_with_api_type_version_not_supported.golden b/pkg/alertmanager/testdata/jira_config_with_api_type_version_not_supported.golden new file mode 100644 index 00000000000..635652cc73b --- /dev/null +++ b/pkg/alertmanager/testdata/jira_config_with_api_type_version_not_supported.golden @@ -0,0 +1,7 @@ +receivers: +- name: "" + jira_configs: + - api_url: http://issues.example.com + project: Monitoring + issue_type: Bug +templates: [] diff --git a/pkg/alertmanager/testdata/msteams_valid_url_passes.golden b/pkg/alertmanager/testdata/msteams_valid_url_passes.golden new file mode 100644 index 00000000000..417954f37a0 --- /dev/null +++ b/pkg/alertmanager/testdata/msteams_valid_url_passes.golden @@ -0,0 +1,5 @@ +receivers: +- name: "" + msteams_configs: + - webhook_url: http://example.com/webhook +templates: [] diff --git a/pkg/alertmanager/testdata/telegram_valid_url_passes.golden b/pkg/alertmanager/testdata/telegram_valid_url_passes.golden new file mode 100644 index 00000000000..f046dee0676 --- /dev/null +++ b/pkg/alertmanager/testdata/telegram_valid_url_passes.golden @@ -0,0 +1,7 @@ +receivers: +- name: "" + telegram_configs: + - api_url: http://example.com + bot_token: token + chat_id: 12345 +templates: [] diff --git a/pkg/alertmanager/testdata/test_config_version_mattermost_allowed.golden b/pkg/alertmanager/testdata/test_config_version_mattermost_allowed.golden new file mode 100644 index 00000000000..4e4f640f618 --- /dev/null +++ b/pkg/alertmanager/testdata/test_config_version_mattermost_allowed.golden @@ -0,0 +1,6 @@ +receivers: +- name: "" + mattermost_configs: + - webhook_url: www.test.com + text: test text +templates: [] diff --git a/pkg/alertmanager/testdata/test_pagerduty_timeout_is_added_in_pagerduty_config_for_supported_versions.golden b/pkg/alertmanager/testdata/test_pagerduty_timeout_is_added_in_pagerduty_config_for_supported_versions.golden new file mode 100644 index 00000000000..c008410a546 --- /dev/null +++ b/pkg/alertmanager/testdata/test_pagerduty_timeout_is_added_in_pagerduty_config_for_supported_versions.golden @@ -0,0 +1,5 @@ +receivers: +- name: "" + pagerduty_configs: + - timeout: 1m +templates: [] diff --git a/pkg/alertmanager/testdata/test_pagerduty_timeout_is_dropped_in_pagerduty_config_for_unsupported_versions.golden b/pkg/alertmanager/testdata/test_pagerduty_timeout_is_dropped_in_pagerduty_config_for_unsupported_versions.golden new file mode 100644 index 00000000000..448ec7eb969 --- /dev/null +++ b/pkg/alertmanager/testdata/test_pagerduty_timeout_is_dropped_in_pagerduty_config_for_unsupported_versions.golden @@ -0,0 +1,5 @@ +receivers: +- name: "" + pagerduty_configs: + - {} +templates: [] diff --git a/pkg/alertmanager/testdata/test_pushover_valid_url_passes.golden b/pkg/alertmanager/testdata/test_pushover_valid_url_passes.golden new file mode 100644 index 00000000000..24131a416c4 --- /dev/null +++ b/pkg/alertmanager/testdata/test_pushover_valid_url_passes.golden @@ -0,0 +1,7 @@ +receivers: +- name: "" + pushover_configs: + - user_key: key + token: token + url: http://example.com +templates: [] diff --git a/pkg/alertmanager/testdata/test_slack_app_token_and_slack_api_url_with_same_url_is_allowed.golden b/pkg/alertmanager/testdata/test_slack_app_token_and_slack_api_url_with_same_url_is_allowed.golden new file mode 100644 index 00000000000..b3b3c23d9d9 --- /dev/null +++ b/pkg/alertmanager/testdata/test_slack_app_token_and_slack_api_url_with_same_url_is_allowed.golden @@ -0,0 +1,5 @@ +global: + slack_api_url: https://slack.com/api/chat.postMessage + slack_app_token: xoxb-token + slack_app_url: https://slack.com/api/chat.postMessage +templates: [] diff --git a/pkg/alertmanager/testdata/test_slack_app_token_and_slack_app_url_preserved_for_supported_versions.golden b/pkg/alertmanager/testdata/test_slack_app_token_and_slack_app_url_preserved_for_supported_versions.golden new file mode 100644 index 00000000000..e3287c8364a --- /dev/null +++ b/pkg/alertmanager/testdata/test_slack_app_token_and_slack_app_url_preserved_for_supported_versions.golden @@ -0,0 +1,4 @@ +global: + slack_app_token: xoxb-token + slack_app_url: https://slack.com/api/chat.postMessage +templates: [] diff --git a/pkg/alertmanager/testdata/test_slack_app_token_is_dropped_for_unsupported_versions.golden b/pkg/alertmanager/testdata/test_slack_app_token_is_dropped_for_unsupported_versions.golden new file mode 100644 index 00000000000..3ee534b4b8c --- /dev/null +++ b/pkg/alertmanager/testdata/test_slack_app_token_is_dropped_for_unsupported_versions.golden @@ -0,0 +1,2 @@ +global: {} +templates: [] diff --git a/pkg/alertmanager/testdata/test_slack_app_token_takes_precedence_over_slack_app_token_file.golden b/pkg/alertmanager/testdata/test_slack_app_token_takes_precedence_over_slack_app_token_file.golden new file mode 100644 index 00000000000..e3287c8364a --- /dev/null +++ b/pkg/alertmanager/testdata/test_slack_app_token_takes_precedence_over_slack_app_token_file.golden @@ -0,0 +1,4 @@ +global: + slack_app_token: xoxb-token + slack_app_url: https://slack.com/api/chat.postMessage +templates: [] diff --git a/pkg/alertmanager/testdata/test_slack_app_url_is_dropped_for_unsupported_versions.golden b/pkg/alertmanager/testdata/test_slack_app_url_is_dropped_for_unsupported_versions.golden new file mode 100644 index 00000000000..3ee534b4b8c --- /dev/null +++ b/pkg/alertmanager/testdata/test_slack_app_url_is_dropped_for_unsupported_versions.golden @@ -0,0 +1,2 @@ +global: {} +templates: [] diff --git a/pkg/alertmanager/testdata/test_slack_timeout_is_added_in_slack_config_for_supported_versions.golden b/pkg/alertmanager/testdata/test_slack_timeout_is_added_in_slack_config_for_supported_versions.golden new file mode 100644 index 00000000000..679a39be898 --- /dev/null +++ b/pkg/alertmanager/testdata/test_slack_timeout_is_added_in_slack_config_for_supported_versions.golden @@ -0,0 +1,5 @@ +receivers: +- name: "" + slack_configs: + - timeout: 1m +templates: [] diff --git a/pkg/alertmanager/testdata/test_slack_timeout_is_dropped_in_slack_config_for_unsupported_versions.golden b/pkg/alertmanager/testdata/test_slack_timeout_is_dropped_in_slack_config_for_unsupported_versions.golden new file mode 100644 index 00000000000..dff50ed53aa --- /dev/null +++ b/pkg/alertmanager/testdata/test_slack_timeout_is_dropped_in_slack_config_for_unsupported_versions.golden @@ -0,0 +1,5 @@ +receivers: +- name: "" + slack_configs: + - {} +templates: [] diff --git a/pkg/alertmanager/testdata/test_url_takes_precedence_in_webhook_config.golden b/pkg/alertmanager/testdata/test_url_takes_precedence_in_webhook_config.golden index 0e49c47783e..1649b1dc8a8 100644 --- a/pkg/alertmanager/testdata/test_url_takes_precedence_in_webhook_config.golden +++ b/pkg/alertmanager/testdata/test_url_takes_precedence_in_webhook_config.golden @@ -1,5 +1,5 @@ receivers: - name: "" webhook_configs: - - url: foo + - url: http://example.com/foo templates: [] diff --git a/pkg/alertmanager/testdata/test_webhook_url_takes_precedence_in_mattermost_config.golden b/pkg/alertmanager/testdata/test_webhook_url_takes_precedence_in_mattermost_config.golden new file mode 100644 index 00000000000..4e4f640f618 --- /dev/null +++ b/pkg/alertmanager/testdata/test_webhook_url_takes_precedence_in_mattermost_config.golden @@ -0,0 +1,6 @@ +receivers: +- name: "" + mattermost_configs: + - webhook_url: www.test.com + text: test text +templates: [] diff --git a/pkg/alertmanager/testdata/test_webhook_valid_url_passes.golden b/pkg/alertmanager/testdata/test_webhook_valid_url_passes.golden new file mode 100644 index 00000000000..61fad045168 --- /dev/null +++ b/pkg/alertmanager/testdata/test_webhook_valid_url_passes.golden @@ -0,0 +1,5 @@ +receivers: +- name: "" + webhook_configs: + - url: http://example.com/webhook +templates: [] diff --git a/pkg/alertmanager/types.go b/pkg/alertmanager/types.go index ea425cd1eac..b245a87f054 100644 --- a/pkg/alertmanager/types.go +++ b/pkg/alertmanager/types.go @@ -26,188 +26,198 @@ import ( // marshalling. See the following issue for details: // https://github.com/prometheus/alertmanager/issues/1985 type alertmanagerConfig struct { - Global *globalConfig `yaml:"global,omitempty" json:"global,omitempty"` - Route *route `yaml:"route,omitempty" json:"route,omitempty"` - InhibitRules []*inhibitRule `yaml:"inhibit_rules,omitempty" json:"inhibit_rules,omitempty"` - Receivers []*receiver `yaml:"receivers,omitempty" json:"receivers,omitempty"` - MuteTimeIntervals []*timeInterval `yaml:"mute_time_intervals,omitempty" json:"mute_time_intervals,omitempty"` - TimeIntervals []*timeInterval `yaml:"time_intervals,omitempty" json:"time_intervals,omitempty"` - Templates []string `yaml:"templates" json:"templates"` + Global *globalConfig `yaml:"global,omitempty"` + Route *route `yaml:"route,omitempty"` + InhibitRules []*inhibitRule `yaml:"inhibit_rules,omitempty"` + Receivers []*receiver `yaml:"receivers,omitempty"` + MuteTimeIntervals []*timeInterval `yaml:"mute_time_intervals,omitempty"` + TimeIntervals []*timeInterval `yaml:"time_intervals,omitempty"` + Templates []string `yaml:"templates"` } type globalConfig struct { // ResolveTimeout is the time after which an alert is declared resolved // if it has not been updated. - ResolveTimeout *model.Duration `yaml:"resolve_timeout,omitempty" json:"resolve_timeout,omitempty"` - - HTTPConfig *httpClientConfig `yaml:"http_config,omitempty" json:"http_config,omitempty"` - - SMTPFrom string `yaml:"smtp_from,omitempty" json:"smtp_from,omitempty"` - SMTPHello string `yaml:"smtp_hello,omitempty" json:"smtp_hello,omitempty"` - SMTPSmarthost config.HostPort `yaml:"smtp_smarthost,omitempty" json:"smtp_smarthost,omitempty"` - SMTPAuthUsername string `yaml:"smtp_auth_username,omitempty" json:"smtp_auth_username,omitempty"` - SMTPAuthPassword string `yaml:"smtp_auth_password,omitempty" json:"smtp_auth_password,omitempty"` - SMTPAuthPasswordFile string `yaml:"smtp_auth_password_file,omitempty" json:"smtp_auth_password_file,omitempty"` - SMTPAuthSecret string `yaml:"smtp_auth_secret,omitempty" json:"smtp_auth_secret,omitempty"` - SMTPAuthIdentity string `yaml:"smtp_auth_identity,omitempty" json:"smtp_auth_identity,omitempty"` - SMTPRequireTLS *bool `yaml:"smtp_require_tls,omitempty" json:"smtp_require_tls,omitempty"` - SMTPTLSConfig *tlsConfig `yaml:"smtp_tls_config,omitempty" json:"smtp_tls_config,omitempty"` - SlackAPIURL *config.URL `yaml:"slack_api_url,omitempty" json:"slack_api_url,omitempty"` - SlackAPIURLFile string `yaml:"slack_api_url_file,omitempty" json:"slack_api_url_file,omitempty"` - PagerdutyURL *config.URL `yaml:"pagerduty_url,omitempty" json:"pagerduty_url,omitempty"` - HipchatAPIURL *config.URL `yaml:"hipchat_api_url,omitempty" json:"hipchat_api_url,omitempty"` - HipchatAuthToken string `yaml:"hipchat_auth_token,omitempty" json:"hipchat_auth_token,omitempty"` - OpsGenieAPIURL *config.URL `yaml:"opsgenie_api_url,omitempty" json:"opsgenie_api_url,omitempty"` - OpsGenieAPIKey string `yaml:"opsgenie_api_key,omitempty" json:"opsgenie_api_key,omitempty"` - OpsGenieAPIKeyFile string `yaml:"opsgenie_api_key_file,omitempty" json:"opsgenie_api_key_file,omitempty"` - WeChatAPIURL *config.URL `yaml:"wechat_api_url,omitempty" json:"wechat_api_url,omitempty"` - WeChatAPISecret string `yaml:"wechat_api_secret,omitempty" json:"wechat_api_secret,omitempty"` - WeChatAPICorpID string `yaml:"wechat_api_corp_id,omitempty" json:"wechat_api_corp_id,omitempty"` - VictorOpsAPIURL *config.URL `yaml:"victorops_api_url,omitempty" json:"victorops_api_url,omitempty"` - VictorOpsAPIKey string `yaml:"victorops_api_key,omitempty" json:"victorops_api_key,omitempty"` - VictorOpsAPIKeyFile string `yaml:"victorops_api_key_file,omitempty" json:"victorops_api_key_file,omitempty"` - TelegramAPIURL *config.URL `yaml:"telegram_api_url,omitempty" json:"telegram_api_url,omitempty"` - WebexAPIURL *config.URL `yaml:"webex_api_url,omitempty" json:"webex_api_url,omitempty"` - JiraAPIURL *config.URL `yaml:"jira_api_url,omitempty" json:"jira_api_url,omitempty"` - RocketChatAPIURL *config.URL `yaml:"rocketchat_api_url,omitempty" json:"rocketchat_api_url,omitempty"` - RocketChatToken string `yaml:"rocketchat_token,omitempty" json:"rocketchat_token,omitempty"` - RocketChatTokenFile string `yaml:"rocketchat_token_file,omitempty" json:"rocketchat_token_file,omitempty"` - RocketChatTokenID string `yaml:"rocketchat_token_id,omitempty" json:"rocketchat_token_id,omitempty"` - RocketChatTokenIDFile string `yaml:"rocketchat_token_id_file,omitempty" json:"rocketchat_token_id_file,omitempty"` + ResolveTimeout *model.Duration `yaml:"resolve_timeout,omitempty"` + + HTTPConfig *httpClientConfig `yaml:"http_config,omitempty"` + + SMTPFrom string `yaml:"smtp_from,omitempty"` + SMTPHello string `yaml:"smtp_hello,omitempty"` + SMTPSmarthost config.HostPort `yaml:"smtp_smarthost,omitempty"` + SMTPAuthUsername string `yaml:"smtp_auth_username,omitempty"` + SMTPAuthPassword string `yaml:"smtp_auth_password,omitempty"` + SMTPAuthPasswordFile string `yaml:"smtp_auth_password_file,omitempty"` + SMTPAuthSecret string `yaml:"smtp_auth_secret,omitempty"` + SMTPAuthIdentity string `yaml:"smtp_auth_identity,omitempty"` + SMTPRequireTLS *bool `yaml:"smtp_require_tls,omitempty"` + SMTPTLSConfig *tlsConfig `yaml:"smtp_tls_config,omitempty"` + SlackAPIURL *config.URL `yaml:"slack_api_url,omitempty"` + SlackAPIURLFile string `yaml:"slack_api_url_file,omitempty"` + PagerdutyURL *config.URL `yaml:"pagerduty_url,omitempty"` + HipchatAPIURL *config.URL `yaml:"hipchat_api_url,omitempty"` + HipchatAuthToken string `yaml:"hipchat_auth_token,omitempty"` + OpsGenieAPIURL *config.URL `yaml:"opsgenie_api_url,omitempty"` + OpsGenieAPIKey string `yaml:"opsgenie_api_key,omitempty"` + OpsGenieAPIKeyFile string `yaml:"opsgenie_api_key_file,omitempty"` + WeChatAPIURL *config.URL `yaml:"wechat_api_url,omitempty"` + WeChatAPISecret string `yaml:"wechat_api_secret,omitempty"` + WeChatAPICorpID string `yaml:"wechat_api_corp_id,omitempty"` + VictorOpsAPIURL *config.URL `yaml:"victorops_api_url,omitempty"` + VictorOpsAPIKey string `yaml:"victorops_api_key,omitempty"` + VictorOpsAPIKeyFile string `yaml:"victorops_api_key_file,omitempty"` + TelegramAPIURL *config.URL `yaml:"telegram_api_url,omitempty"` + WebexAPIURL *config.URL `yaml:"webex_api_url,omitempty"` + JiraAPIURL *config.URL `yaml:"jira_api_url,omitempty"` + RocketChatAPIURL *config.URL `yaml:"rocketchat_api_url,omitempty"` + RocketChatToken string `yaml:"rocketchat_token,omitempty"` + RocketChatTokenFile string `yaml:"rocketchat_token_file,omitempty"` + RocketChatTokenID string `yaml:"rocketchat_token_id,omitempty"` + RocketChatTokenIDFile string `yaml:"rocketchat_token_id_file,omitempty"` + SlackAppToken string `yaml:"slack_app_token,omitempty"` + SlackAppTokenFile string `yaml:"slack_app_token_file,omitempty"` + SlackAppURL *config.URL `yaml:"slack_app_url,omitempty"` } type route struct { - Receiver string `yaml:"receiver,omitempty" json:"receiver,omitempty"` - GroupByStr []string `yaml:"group_by,omitempty" json:"group_by,omitempty"` - Match map[string]string `yaml:"match,omitempty" json:"match,omitempty"` - MatchRE map[string]string `yaml:"match_re,omitempty" json:"match_re,omitempty"` - Matchers []string `yaml:"matchers,omitempty" json:"matchers,omitempty"` - Continue bool `yaml:"continue,omitempty" json:"continue,omitempty"` - Routes []*route `yaml:"routes,omitempty" json:"routes,omitempty"` - GroupWait string `yaml:"group_wait,omitempty" json:"group_wait,omitempty"` - GroupInterval string `yaml:"group_interval,omitempty" json:"group_interval,omitempty"` - RepeatInterval string `yaml:"repeat_interval,omitempty" json:"repeat_interval,omitempty"` - MuteTimeIntervals []string `yaml:"mute_time_intervals,omitempty" json:"mute_time_intervals,omitempty"` - ActiveTimeIntervals []string `yaml:"active_time_intervals,omitempty" json:"active_time_intervals,omitempty"` + Receiver string `yaml:"receiver,omitempty"` + GroupByStr []string `yaml:"group_by,omitempty"` + Match map[string]string `yaml:"match,omitempty"` + MatchRE map[string]string `yaml:"match_re,omitempty"` + Matchers []string `yaml:"matchers,omitempty"` + Continue bool `yaml:"continue,omitempty"` + Routes []*route `yaml:"routes,omitempty"` + GroupWait string `yaml:"group_wait,omitempty"` + GroupInterval string `yaml:"group_interval,omitempty"` + RepeatInterval string `yaml:"repeat_interval,omitempty"` + MuteTimeIntervals []string `yaml:"mute_time_intervals,omitempty"` + ActiveTimeIntervals []string `yaml:"active_time_intervals,omitempty"` } type inhibitRule struct { - TargetMatch map[string]string `yaml:"target_match,omitempty" json:"target_match,omitempty"` - TargetMatchRE map[string]string `yaml:"target_match_re,omitempty" json:"target_match_re,omitempty"` - TargetMatchers []string `yaml:"target_matchers,omitempty" json:"target_matchers,omitempty"` - SourceMatch map[string]string `yaml:"source_match,omitempty" json:"source_match,omitempty"` - SourceMatchRE map[string]string `yaml:"source_match_re,omitempty" json:"source_match_re,omitempty"` - SourceMatchers []string `yaml:"source_matchers,omitempty" json:"source_matchers,omitempty"` - Equal []string `yaml:"equal,omitempty" json:"equal,omitempty"` + TargetMatch map[string]string `yaml:"target_match,omitempty"` + TargetMatchRE map[string]string `yaml:"target_match_re,omitempty"` + TargetMatchers []string `yaml:"target_matchers,omitempty"` + SourceMatch map[string]string `yaml:"source_match,omitempty"` + SourceMatchRE map[string]string `yaml:"source_match_re,omitempty"` + SourceMatchers []string `yaml:"source_matchers,omitempty"` + Equal []string `yaml:"equal,omitempty"` } type receiver struct { - Name string `yaml:"name" json:"name"` - OpsgenieConfigs []*opsgenieConfig `yaml:"opsgenie_configs,omitempty" json:"opsgenie_configs,omitempty"` - PagerdutyConfigs []*pagerdutyConfig `yaml:"pagerduty_configs,omitempty" json:"pagerduty_configs,omitempty"` - SlackConfigs []*slackConfig `yaml:"slack_configs,omitempty" json:"slack_configs,omitempty"` - WebhookConfigs []*webhookConfig `yaml:"webhook_configs,omitempty" json:"webhook_configs,omitempty"` - WeChatConfigs []*weChatConfig `yaml:"wechat_configs,omitempty" json:"wechat_config,omitempty"` - EmailConfigs []*emailConfig `yaml:"email_configs,omitempty" json:"email_configs,omitempty"` - PushoverConfigs []*pushoverConfig `yaml:"pushover_configs,omitempty" json:"pushover_configs,omitempty"` - VictorOpsConfigs []*victorOpsConfig `yaml:"victorops_configs,omitempty" json:"victorops_configs,omitempty"` - SNSConfigs []*snsConfig `yaml:"sns_configs,omitempty" json:"sns_configs,omitempty"` - TelegramConfigs []*telegramConfig `yaml:"telegram_configs,omitempty" json:"telegram_configs,omitempty"` + Name string `yaml:"name"` + OpsgenieConfigs []*opsgenieConfig `yaml:"opsgenie_configs,omitempty"` + PagerdutyConfigs []*pagerdutyConfig `yaml:"pagerduty_configs,omitempty"` + SlackConfigs []*slackConfig `yaml:"slack_configs,omitempty"` + WebhookConfigs []*webhookConfig `yaml:"webhook_configs,omitempty"` + WeChatConfigs []*weChatConfig `yaml:"wechat_configs,omitempty"` + EmailConfigs []*emailConfig `yaml:"email_configs,omitempty"` + PushoverConfigs []*pushoverConfig `yaml:"pushover_configs,omitempty"` + VictorOpsConfigs []*victorOpsConfig `yaml:"victorops_configs,omitempty"` + SNSConfigs []*snsConfig `yaml:"sns_configs,omitempty"` + TelegramConfigs []*telegramConfig `yaml:"telegram_configs,omitempty"` DiscordConfigs []*discordConfig `yaml:"discord_configs,omitempty"` WebexConfigs []*webexConfig `yaml:"webex_configs,omitempty"` MSTeamsConfigs []*msTeamsConfig `yaml:"msteams_configs,omitempty"` MSTeamsV2Configs []*msTeamsV2Config `yaml:"msteamsv2_configs,omitempty"` JiraConfigs []*jiraConfig `yaml:"jira_configs,omitempty"` RocketChatConfigs []*rocketChatConfig `yaml:"rocketchat_configs,omitempty"` + MattermostConfigs []*mattermostConfig `yaml:"mattermost_configs,omitempty"` + IncidentioConfigs []*incidentioConfig `yaml:"incidentio_configs,omitempty"` } type webhookConfig struct { - VSendResolved *bool `yaml:"send_resolved,omitempty" json:"send_resolved,omitempty"` - URL string `yaml:"url,omitempty" json:"url,omitempty"` - URLFile string `yaml:"url_file,omitempty" json:"url_file,omitempty"` - HTTPConfig *httpClientConfig `yaml:"http_config,omitempty" json:"http_config,omitempty"` - MaxAlerts int32 `yaml:"max_alerts,omitempty" json:"max_alerts,omitempty"` - Timeout *model.Duration `yaml:"timeout,omitempty" json:"timeout,omitempty"` + VSendResolved *bool `yaml:"send_resolved,omitempty"` + URL string `yaml:"url,omitempty"` + URLFile string `yaml:"url_file,omitempty"` + HTTPConfig *httpClientConfig `yaml:"http_config,omitempty"` + MaxAlerts int32 `yaml:"max_alerts,omitempty"` + Timeout *model.Duration `yaml:"timeout,omitempty"` } type pagerdutyConfig struct { - VSendResolved *bool `yaml:"send_resolved,omitempty" json:"send_resolved,omitempty"` - HTTPConfig *httpClientConfig `yaml:"http_config,omitempty" json:"http_config,omitempty"` - ServiceKey string `yaml:"service_key,omitempty" json:"service_key,omitempty"` - ServiceKeyFile string `yaml:"service_key_file,omitempty" json:"service_key_file,omitempty"` - RoutingKey string `yaml:"routing_key,omitempty" json:"routing_key,omitempty"` - RoutingKeyFile string `yaml:"routing_key_file,omitempty" json:"routing_key_file,omitempty"` - URL string `yaml:"url,omitempty" json:"url,omitempty"` - Client string `yaml:"client,omitempty" json:"client,omitempty"` - ClientURL string `yaml:"client_url,omitempty" json:"client_url,omitempty"` - Description string `yaml:"description,omitempty" json:"description,omitempty"` - Details map[string]string `yaml:"details,omitempty" json:"details,omitempty"` - Images []pagerdutyImage `yaml:"images,omitempty" json:"images,omitempty"` - Links []pagerdutyLink `yaml:"links,omitempty" json:"links,omitempty"` - Severity string `yaml:"severity,omitempty" json:"severity,omitempty"` - Class string `yaml:"class,omitempty" json:"class,omitempty"` - Component string `yaml:"component,omitempty" json:"component,omitempty"` - Group string `yaml:"group,omitempty" json:"group,omitempty"` - Source string `yaml:"source,omitempty" json:"source,omitempty"` + VSendResolved *bool `yaml:"send_resolved,omitempty"` + HTTPConfig *httpClientConfig `yaml:"http_config,omitempty"` + ServiceKey string `yaml:"service_key,omitempty"` + ServiceKeyFile string `yaml:"service_key_file,omitempty"` + RoutingKey string `yaml:"routing_key,omitempty"` + RoutingKeyFile string `yaml:"routing_key_file,omitempty"` + URL string `yaml:"url,omitempty"` + Client string `yaml:"client,omitempty"` + ClientURL string `yaml:"client_url,omitempty"` + Description string `yaml:"description,omitempty"` + Details map[string]string `yaml:"details,omitempty"` + Images []pagerdutyImage `yaml:"images,omitempty"` + Links []pagerdutyLink `yaml:"links,omitempty"` + Severity string `yaml:"severity,omitempty"` + Class string `yaml:"class,omitempty"` + Component string `yaml:"component,omitempty"` + Group string `yaml:"group,omitempty"` + Source string `yaml:"source,omitempty"` + Timeout *model.Duration `yaml:"timeout,omitempty"` } type opsgenieConfig struct { - VSendResolved *bool `yaml:"send_resolved,omitempty" json:"send_resolved,omitempty"` - HTTPConfig *httpClientConfig `yaml:"http_config,omitempty" json:"http_config,omitempty"` - APIKey string `yaml:"api_key,omitempty" json:"api_key,omitempty"` - APIKeyFile string `yaml:"api_key_file,omitempty" json:"api_key_file,omitempty"` - APIURL string `yaml:"api_url,omitempty" json:"api_url,omitempty"` - Message string `yaml:"message,omitempty" json:"message,omitempty"` - Description string `yaml:"description,omitempty" json:"description,omitempty"` - Source string `yaml:"source,omitempty" json:"source,omitempty"` - Details map[string]string `yaml:"details,omitempty" json:"details,omitempty"` - Responders []opsgenieResponder `yaml:"responders,omitempty" json:"responders,omitempty"` - Tags string `yaml:"tags,omitempty" json:"tags,omitempty"` - Note string `yaml:"note,omitempty" json:"note,omitempty"` - Priority string `yaml:"priority,omitempty" json:"priority,omitempty"` - UpdateAlerts *bool `yaml:"update_alerts,omitempty" json:"update_alerts,omitempty"` - Entity string `yaml:"entity,omitempty" json:"entity,omitempty"` - Actions string `yaml:"actions,omitempty" json:"actions,omitempty"` + VSendResolved *bool `yaml:"send_resolved,omitempty"` + HTTPConfig *httpClientConfig `yaml:"http_config,omitempty"` + APIKey string `yaml:"api_key,omitempty"` + APIKeyFile string `yaml:"api_key_file,omitempty"` + APIURL string `yaml:"api_url,omitempty"` + Message string `yaml:"message,omitempty"` + Description string `yaml:"description,omitempty"` + Source string `yaml:"source,omitempty"` + Details map[string]string `yaml:"details,omitempty"` + Responders []opsgenieResponder `yaml:"responders,omitempty"` + Tags string `yaml:"tags,omitempty"` + Note string `yaml:"note,omitempty"` + Priority string `yaml:"priority,omitempty"` + UpdateAlerts *bool `yaml:"update_alerts,omitempty"` + Entity string `yaml:"entity,omitempty"` + Actions string `yaml:"actions,omitempty"` } type weChatConfig struct { - VSendResolved *bool `yaml:"send_resolved,omitempty" json:"send_resolved,omitempty"` - APISecret string `yaml:"api_secret,omitempty" json:"api_secret,omitempty"` - APIURL string `yaml:"api_url,omitempty" json:"api_url,omitempty"` - CorpID string `yaml:"corp_id,omitempty" json:"corp_id,omitempty"` - AgentID string `yaml:"agent_id,omitempty" json:"agent_id,omitempty"` - ToUser string `yaml:"to_user,omitempty" json:"to_user,omitempty"` - ToParty string `yaml:"to_party,omitempty" json:"to_party,omitempty"` - ToTag string `yaml:"to_tag,omitempty" json:"to_tag,omitempty"` - Message string `yaml:"message,omitempty" json:"message,omitempty"` - MessageType string `yaml:"message_type,omitempty" json:"message_type,omitempty"` - HTTPConfig *httpClientConfig `yaml:"http_config,omitempty" json:"http_config,omitempty"` + VSendResolved *bool `yaml:"send_resolved,omitempty"` + APISecret string `yaml:"api_secret,omitempty"` + APIURL string `yaml:"api_url,omitempty"` + CorpID string `yaml:"corp_id,omitempty"` + AgentID string `yaml:"agent_id,omitempty"` + ToUser string `yaml:"to_user,omitempty"` + ToParty string `yaml:"to_party,omitempty"` + ToTag string `yaml:"to_tag,omitempty"` + Message string `yaml:"message,omitempty"` + MessageType string `yaml:"message_type,omitempty"` + HTTPConfig *httpClientConfig `yaml:"http_config,omitempty"` } type slackConfig struct { - VSendResolved *bool `yaml:"send_resolved,omitempty" json:"send_resolved,omitempty"` - HTTPConfig *httpClientConfig `yaml:"http_config,omitempty" json:"http_config,omitempty"` - APIURL string `yaml:"api_url,omitempty" json:"api_url,omitempty"` - APIURLFile string `yaml:"api_url_file,omitempty" json:"api_url_file,omitempty"` - Channel string `yaml:"channel,omitempty" json:"channel,omitempty"` - Username string `yaml:"username,omitempty" json:"username,omitempty"` - Color string `yaml:"color,omitempty" json:"color,omitempty"` - Title string `yaml:"title,omitempty" json:"title,omitempty"` - TitleLink string `yaml:"title_link,omitempty" json:"title_link,omitempty"` - Pretext string `yaml:"pretext,omitempty" json:"pretext,omitempty"` - Text string `yaml:"text,omitempty" json:"text,omitempty"` - Fields []slackField `yaml:"fields,omitempty" json:"fields,omitempty"` - ShortFields bool `yaml:"short_fields,omitempty" json:"short_fields,omitempty"` - Footer string `yaml:"footer,omitempty" json:"footer,omitempty"` - Fallback string `yaml:"fallback,omitempty" json:"fallback,omitempty"` - CallbackID string `yaml:"callback_id,omitempty" json:"callback_id,omitempty"` - IconEmoji string `yaml:"icon_emoji,omitempty" json:"icon_emoji,omitempty"` - IconURL string `yaml:"icon_url,omitempty" json:"icon_url,omitempty"` - ImageURL string `yaml:"image_url,omitempty" json:"image_url,omitempty"` - ThumbURL string `yaml:"thumb_url,omitempty" json:"thumb_url,omitempty"` - LinkNames bool `yaml:"link_names,omitempty" json:"link_names,omitempty"` - MrkdwnIn []string `yaml:"mrkdwn_in,omitempty" json:"mrkdwn_in,omitempty"` - Actions []slackAction `yaml:"actions,omitempty" json:"actions,omitempty"` + VSendResolved *bool `yaml:"send_resolved,omitempty"` + HTTPConfig *httpClientConfig `yaml:"http_config,omitempty"` + APIURL string `yaml:"api_url,omitempty"` + APIURLFile string `yaml:"api_url_file,omitempty"` + AppToken string `yaml:"app_token,omitempty"` + AppTokenFile string `yaml:"app_token_file,omitempty"` + AppURL string `yaml:"app_url,omitempty"` + Channel string `yaml:"channel,omitempty"` + Username string `yaml:"username,omitempty"` + Color string `yaml:"color,omitempty"` + Title string `yaml:"title,omitempty"` + TitleLink string `yaml:"title_link,omitempty"` + Pretext string `yaml:"pretext,omitempty"` + Text string `yaml:"text,omitempty"` + Fields []slackField `yaml:"fields,omitempty"` + ShortFields bool `yaml:"short_fields,omitempty"` + Footer string `yaml:"footer,omitempty"` + Fallback string `yaml:"fallback,omitempty"` + CallbackID string `yaml:"callback_id,omitempty"` + IconEmoji string `yaml:"icon_emoji,omitempty"` + IconURL string `yaml:"icon_url,omitempty"` + ImageURL string `yaml:"image_url,omitempty"` + ThumbURL string `yaml:"thumb_url,omitempty"` + LinkNames bool `yaml:"link_names,omitempty"` + MrkdwnIn []string `yaml:"mrkdwn_in,omitempty"` + Actions []slackAction `yaml:"actions,omitempty"` + Timeout *model.Duration `yaml:"timeout,omitempty"` } type httpClientConfig struct { @@ -247,7 +257,7 @@ type authorization struct { } type basicAuth struct { - Username string `yaml:"username"` + Username string `yaml:"username,omitempty"` Password string `yaml:"password,omitempty"` PasswordFile string `yaml:"password_file,omitempty"` } @@ -265,109 +275,109 @@ type oauth2 struct { } type pagerdutyLink struct { - Href string `yaml:"href,omitempty" json:"href,omitempty"` - Text string `yaml:"text,omitempty" json:"text,omitempty"` + Href string `yaml:"href,omitempty"` + Text string `yaml:"text,omitempty"` } type pagerdutyImage struct { - Src string `yaml:"src,omitempty" json:"src,omitempty"` - Alt string `yaml:"alt,omitempty" json:"alt,omitempty"` - Href string `yaml:"href,omitempty" json:"href,omitempty"` + Src string `yaml:"src,omitempty"` + Alt string `yaml:"alt,omitempty"` + Href string `yaml:"href,omitempty"` } type opsgenieResponder struct { - ID string `yaml:"id,omitempty" json:"id,omitempty"` - Name string `yaml:"name,omitempty" json:"name,omitempty"` - Username string `yaml:"username,omitempty" json:"username,omitempty"` - Type string `yaml:"type,omitempty" json:"type,omitempty"` + ID string `yaml:"id,omitempty"` + Name string `yaml:"name,omitempty"` + Username string `yaml:"username,omitempty"` + Type string `yaml:"type,omitempty"` } type slackField struct { - Title string `yaml:"title,omitempty" json:"title,omitempty"` - Value string `yaml:"value,omitempty" json:"value,omitempty"` - Short bool `yaml:"short,omitempty" json:"short,omitempty"` + Title string `yaml:"title,omitempty"` + Value string `yaml:"value,omitempty"` + Short bool `yaml:"short,omitempty"` } type slackAction struct { - Type string `yaml:"type,omitempty" json:"type,omitempty"` - Text string `yaml:"text,omitempty" json:"text,omitempty"` - URL string `yaml:"url,omitempty" json:"url,omitempty"` - Style string `yaml:"style,omitempty" json:"style,omitempty"` - Name string `yaml:"name,omitempty" json:"name,omitempty"` - Value string `yaml:"value,omitempty" json:"value,omitempty"` - ConfirmField *slackConfirmationField `yaml:"confirm,omitempty" json:"confirm,omitempty"` + Type string `yaml:"type,omitempty"` + Text string `yaml:"text,omitempty"` + URL string `yaml:"url,omitempty"` + Style string `yaml:"style,omitempty"` + Name string `yaml:"name,omitempty"` + Value string `yaml:"value,omitempty"` + ConfirmField *slackConfirmationField `yaml:"confirm,omitempty"` } type slackConfirmationField struct { - Text string `yaml:"text,omitempty" json:"text,omitempty"` - Title string `yaml:"title,omitempty" json:"title,omitempty"` - OkText string `yaml:"ok_text,omitempty" json:"ok_text,omitempty"` - DismissText string `yaml:"dismiss_text,omitempty" json:"dismiss_text,omitempty"` + Text string `yaml:"text,omitempty"` + Title string `yaml:"title,omitempty"` + OkText string `yaml:"ok_text,omitempty"` + DismissText string `yaml:"dismiss_text,omitempty"` } type emailConfig struct { - VSendResolved *bool `yaml:"send_resolved,omitempty" json:"send_resolved,omitempty"` - To string `yaml:"to,omitempty" json:"to,omitempty"` - From string `yaml:"from,omitempty" json:"from,omitempty"` - Hello string `yaml:"hello,omitempty" json:"hello,omitempty"` - Smarthost config.HostPort `yaml:"smarthost,omitempty" json:"smarthost,omitempty"` - AuthUsername string `yaml:"auth_username,omitempty" json:"auth_username,omitempty"` - AuthPassword string `yaml:"auth_password,omitempty" json:"auth_password,omitempty"` - AuthPasswordFile string `yaml:"auth_password_file,omitempty" json:"auth_password_file,omitempty"` - AuthSecret string `yaml:"auth_secret,omitempty" json:"auth_secret,omitempty"` - AuthIdentity string `yaml:"auth_identity,omitempty" json:"auth_identity,omitempty"` - Headers map[string]string `yaml:"headers,omitempty" json:"headers,omitempty"` - HTML *string `yaml:"html,omitempty" json:"html,omitempty"` - Text *string `yaml:"text,omitempty" json:"text,omitempty"` - RequireTLS *bool `yaml:"require_tls,omitempty" json:"require_tls,omitempty"` - TLSConfig *tlsConfig `yaml:"tls_config,omitempty" json:"tls_config,omitempty"` + VSendResolved *bool `yaml:"send_resolved,omitempty"` + To string `yaml:"to,omitempty"` + From string `yaml:"from,omitempty"` + Hello string `yaml:"hello,omitempty"` + Smarthost config.HostPort `yaml:"smarthost,omitempty"` + AuthUsername string `yaml:"auth_username,omitempty"` + AuthPassword string `yaml:"auth_password,omitempty"` + AuthPasswordFile string `yaml:"auth_password_file,omitempty"` + AuthSecret string `yaml:"auth_secret,omitempty"` + AuthIdentity string `yaml:"auth_identity,omitempty"` + Headers map[string]string `yaml:"headers,omitempty"` + HTML *string `yaml:"html,omitempty"` + Text *string `yaml:"text,omitempty"` + RequireTLS *bool `yaml:"require_tls,omitempty"` + TLSConfig *tlsConfig `yaml:"tls_config,omitempty"` } type pushoverConfig struct { - VSendResolved *bool `yaml:"send_resolved,omitempty" json:"send_resolved,omitempty"` - HTTPConfig *httpClientConfig `yaml:"http_config,omitempty" json:"http_config,omitempty"` - UserKey string `yaml:"user_key,omitempty" json:"user_key,omitempty"` - UserKeyFile string `yaml:"user_key_file,omitempty" json:"user_key_file,omitempty"` - Token string `yaml:"token,omitempty" json:"token,omitempty"` - TokenFile string `yaml:"token_file,omitempty" json:"token_file,omitempty"` - Title string `yaml:"title,omitempty" json:"title,omitempty"` - Message string `yaml:"message,omitempty" json:"message,omitempty"` - URL string `yaml:"url,omitempty" json:"url,omitempty"` - URLTitle string `yaml:"url_title,omitempty" json:"url_title,omitempty"` - TTL string `yaml:"ttl,omitempty" json:"ttl,omitempty"` - Device string `yaml:"device,omitempty" json:"device,omitempty"` - Sound string `yaml:"sound,omitempty" json:"sound,omitempty"` - Priority string `yaml:"priority,omitempty" json:"priority,omitempty"` - Retry *model.Duration `yaml:"retry,omitempty" json:"retry,omitempty"` - Expire *model.Duration `yaml:"expire,omitempty" json:"expire,omitempty"` - HTML *bool `yaml:"html,omitempty" json:"html,omitempty"` - Monospace *bool `yaml:"monospace,omitempty" json:"monospace,omitempty"` + VSendResolved *bool `yaml:"send_resolved,omitempty"` + HTTPConfig *httpClientConfig `yaml:"http_config,omitempty"` + UserKey string `yaml:"user_key,omitempty"` + UserKeyFile string `yaml:"user_key_file,omitempty"` + Token string `yaml:"token,omitempty"` + TokenFile string `yaml:"token_file,omitempty"` + Title string `yaml:"title,omitempty"` + Message string `yaml:"message,omitempty"` + URL string `yaml:"url,omitempty"` + URLTitle string `yaml:"url_title,omitempty"` + TTL string `yaml:"ttl,omitempty"` + Device string `yaml:"device,omitempty"` + Sound string `yaml:"sound,omitempty"` + Priority string `yaml:"priority,omitempty"` + Retry *model.Duration `yaml:"retry,omitempty"` + Expire *model.Duration `yaml:"expire,omitempty"` + HTML *bool `yaml:"html,omitempty"` + Monospace *bool `yaml:"monospace,omitempty"` } type snsConfig struct { - VSendResolved *bool `yaml:"send_resolved,omitempty" json:"send_resolved,omitempty"` - HTTPConfig *httpClientConfig `yaml:"http_config,omitempty" json:"http_config,omitempty"` - APIUrl string `yaml:"api_url,omitempty" json:"api_url,omitempty"` - Sigv4 sigV4Config `yaml:"sigv4,omitempty" json:"sigv4,omitempty"` - TopicARN string `yaml:"topic_arn,omitempty" json:"topic_arn,omitempty"` - PhoneNumber string `yaml:"phone_number,omitempty" json:"phone_number,omitempty"` - TargetARN string `yaml:"target_arn,omitempty" json:"target_arn,omitempty"` - Subject string `yaml:"subject,omitempty" json:"subject,omitempty"` - Message string `yaml:"message,omitempty" json:"message,omitempty"` - Attributes map[string]string `yaml:"attributes,omitempty" json:"attributes,omitempty"` + VSendResolved *bool `yaml:"send_resolved,omitempty"` + HTTPConfig *httpClientConfig `yaml:"http_config,omitempty"` + APIUrl string `yaml:"api_url,omitempty"` + Sigv4 sigV4Config `yaml:"sigv4,omitempty"` + TopicARN string `yaml:"topic_arn,omitempty"` + PhoneNumber string `yaml:"phone_number,omitempty"` + TargetARN string `yaml:"target_arn,omitempty"` + Subject string `yaml:"subject,omitempty"` + Message string `yaml:"message,omitempty"` + Attributes map[string]string `yaml:"attributes,omitempty"` } type telegramConfig struct { - VSendResolved *bool `yaml:"send_resolved,omitempty" json:"send_resolved,omitempty"` - APIUrl string `yaml:"api_url,omitempty" json:"api_url,omitempty"` - BotToken string `yaml:"bot_token,omitempty" json:"bot_token,omitempty"` - BotTokenFile string `yaml:"bot_token_file,omitempty" json:"bot_token_file,omitempty"` - ChatID int64 `yaml:"chat_id,omitempty" json:"chat_id,omitempty"` - MessageThreadID int `yaml:"message_thread_id,omitempty" json:"message_thread_id,omitempty"` - Message string `yaml:"message,omitempty" json:"message,omitempty"` - DisableNotifications bool `yaml:"disable_notifications,omitempty" json:"disable_notifications,omitempty"` - ParseMode string `yaml:"parse_mode,omitempty" json:"parse_mode,omitempty"` - HTTPConfig *httpClientConfig `yaml:"http_config,omitempty" json:"http_config,omitempty"` + VSendResolved *bool `yaml:"send_resolved,omitempty"` + APIUrl string `yaml:"api_url,omitempty"` + BotToken string `yaml:"bot_token,omitempty"` + BotTokenFile string `yaml:"bot_token_file,omitempty"` + ChatID int64 `yaml:"chat_id,omitempty"` + MessageThreadID int `yaml:"message_thread_id,omitempty"` + Message string `yaml:"message,omitempty"` + DisableNotifications bool `yaml:"disable_notifications,omitempty"` + ParseMode string `yaml:"parse_mode,omitempty"` + HTTPConfig *httpClientConfig `yaml:"http_config,omitempty"` } type discordConfig struct { @@ -390,25 +400,25 @@ type webexConfig struct { } type sigV4Config struct { - Region string `yaml:"region,omitempty" json:"region,omitempty"` - AccessKey string `yaml:"access_key,omitempty" json:"access_key,omitempty"` - SecretKey string `yaml:"secret_key,omitempty" json:"secret_key,omitempty"` - Profile string `yaml:"profile,omitempty" json:"profile,omitempty"` - RoleARN string `yaml:"role_arn,omitempty" json:"role_arn,omitempty"` + Region string `yaml:"region,omitempty"` + AccessKey string `yaml:"access_key,omitempty"` + SecretKey string `yaml:"secret_key,omitempty"` + Profile string `yaml:"profile,omitempty"` + RoleARN string `yaml:"role_arn,omitempty"` } type victorOpsConfig struct { - VSendResolved *bool `yaml:"send_resolved,omitempty" json:"send_resolved,omitempty"` - HTTPConfig *httpClientConfig `yaml:"http_config,omitempty" json:"http_config,omitempty"` - APIKey string `yaml:"api_key,omitempty" json:"api_key,omitempty"` - APIKeyFile string `yaml:"api_key_file,omitempty" json:"api_key_file,omitempty"` - APIURL string `yaml:"api_url,omitempty" json:"api_url,omitempty"` - RoutingKey string `yaml:"routing_key,omitempty" json:"routing_key,omitempty"` - MessageType string `yaml:"message_type,omitempty" json:"message_type,omitempty"` - StateMessage string `yaml:"state_message,omitempty" json:"state_message,omitempty"` - EntityDisplayName string `yaml:"entity_display_name,omitempty" json:"entity_display_name,omitempty"` - MonitoringTool string `yaml:"monitoring_tool,omitempty" json:"monitoring_tool,omitempty"` - CustomFields map[string]string `yaml:"custom_fields,omitempty" json:"custom_fields,omitempty"` + VSendResolved *bool `yaml:"send_resolved,omitempty"` + HTTPConfig *httpClientConfig `yaml:"http_config,omitempty"` + APIKey string `yaml:"api_key,omitempty"` + APIKeyFile string `yaml:"api_key_file,omitempty"` + APIURL string `yaml:"api_url,omitempty"` + RoutingKey string `yaml:"routing_key,omitempty"` + MessageType string `yaml:"message_type,omitempty"` + StateMessage string `yaml:"state_message,omitempty"` + EntityDisplayName string `yaml:"entity_display_name,omitempty"` + MonitoringTool string `yaml:"monitoring_tool,omitempty"` + CustomFields map[string]string `yaml:"custom_fields,omitempty"` } type msTeamsConfig struct { @@ -444,6 +454,7 @@ type jiraConfig struct { WontFixResolution string `yaml:"wont_fix_resolution,omitempty"` ReopenDuration model.Duration `yaml:"reopen_duration,omitempty"` Fields map[string]any `yaml:"fields,omitempty"` + APIType string `yaml:"api_type,omitempty"` } type rocketchatAttachmentField struct { @@ -488,4 +499,63 @@ type rocketChatConfig struct { Actions []*rocketchatAttachmentAction `yaml:"actions,omitempty"` } +type mattermostConfig struct { + SendResolved *bool `yaml:"send_resolved,omitempty" json:"send_resolved,omitempty"` + WebhookURL string `yaml:"webhook_url,omitempty" json:"webhook_url,omitempty"` + WebhookURLFile string `yaml:"webhook_url_file,omitempty" json:"webhook_url_file,omitempty"` + Channel string `yaml:"channel,omitempty" json:"channel,omitempty"` + Username string `yaml:"username,omitempty" json:"username,omitempty"` + Text string `yaml:"text" json:"text"` + IconURL string `yaml:"icon_url,omitempty" json:"icon_url,omitempty"` + IconEmoji string `yaml:"icon_emoji,omitempty" json:"icon_emoji,omitempty"` + Attachments []*mattermostAttachmentConfig `yaml:"attachments,omitempty" json:"attachments,omitempty"` + Props *mattermostPropsConfig `yaml:"props,omitempty" json:"props,omitempty"` + Priority *mattermostPriorityConfig `yaml:"priority,omitempty" json:"priority,omitempty"` + HTTPConfig *httpClientConfig `yaml:"http_config,omitempty" json:"http_config,omitempty"` +} + +type mattermostAttachmentConfig struct { + Fallback string `yaml:"fallback,omitempty" json:"fallback,omitempty"` + Color string `yaml:"color,omitempty" json:"color,omitempty"` + Pretext string `yaml:"pretext,omitempty" json:"pretext,omitempty"` + Text string `yaml:"text,omitempty" json:"text,omitempty"` + AuthorName string `yaml:"author_name,omitempty" json:"author_name,omitempty"` + AuthorLink string `yaml:"author_link,omitempty" json:"author_link,omitempty"` + AuthorIcon string `yaml:"author_icon,omitempty" json:"author_icon,omitempty"` + Title string `yaml:"title,omitempty" json:"title,omitempty"` + TitleLink string `yaml:"title_link,omitempty" json:"title_link,omitempty"` + Fields []mattermostField `yaml:"fields,omitempty" json:"fields,omitempty"` + ThumbURL string `yaml:"thumb_url,omitempty" json:"thumb_url,omitempty"` + Footer string `yaml:"footer,omitempty" json:"footer,omitempty"` + FooterIcon string `yaml:"footer_icon,omitempty" json:"footer_icon,omitempty"` + ImageURL string `yaml:"image_url,omitempty" json:"image_url,omitempty"` +} + +type mattermostField struct { + Title string `yaml:"title,omitempty" json:"title,omitempty"` + Value string `yaml:"value,omitempty" json:"value,omitempty"` + Short bool `yaml:"short,omitempty" json:"short,omitempty"` +} + +type mattermostPropsConfig struct { + Card *string `yaml:"card,omitempty" json:"card,omitempty"` +} + +type mattermostPriorityConfig struct { + Priority string `yaml:"priority,omitempty" json:"priority,omitempty"` + RequestedAck *bool `yaml:"requested_ack,omitempty" json:"requested_ack,omitempty"` + PersistentNotifications *bool `yaml:"persistent_notifications,omitempty" json:"persistent_notifications,omitempty"` +} + +type incidentioConfig struct { + VSendResolved *bool `yaml:"send_resolved,omitempty"` + HTTPConfig *httpClientConfig `yaml:"http_config,omitempty"` + URL string `yaml:"url,omitempty"` + URLFile string `yaml:"url_file,omitempty"` + AlertSourceToken string `yaml:"alert_source_token,omitempty"` + AlertSourceTokenFile string `yaml:"alert_source_token_file,omitempty"` + MaxAlerts *int32 `yaml:"max_alerts,omitempty"` + Timeout *model.Duration `yaml:"timeout,omitempty"` +} + type timeInterval config.TimeInterval diff --git a/pkg/alertmanager/validation/v1/validation.go b/pkg/alertmanager/validation/v1/validation.go index c8e64d72fd9..31eec6d27ff 100644 --- a/pkg/alertmanager/validation/v1/validation.go +++ b/pkg/alertmanager/validation/v1/validation.go @@ -17,6 +17,7 @@ package v1 import ( "fmt" + "github.com/prometheus-operator/prometheus-operator/pkg/alertmanager/validation" monitoringv1 "github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1" ) @@ -25,9 +26,25 @@ func ValidateAlertmanagerGlobalConfig(gc *monitoringv1.AlertmanagerGlobalConfig) return nil } - if err := gc.HTTPConfig.Validate(); err != nil { + if err := gc.HTTPConfigWithProxy.Validate(); err != nil { return fmt.Errorf("httpConfig: %w", err) } + if err := validateGlobalWeChatConfig(gc.WeChatConfig); err != nil { + return fmt.Errorf("wechatConfig: %w", err) + } + + return nil +} + +func validateGlobalWeChatConfig(wc *monitoringv1.GlobalWeChatConfig) error { + if wc == nil { + return nil + } + + if err := validation.ValidateURLPtr((*string)(wc.APIURL)); err != nil { + return fmt.Errorf("invalid apiURL: %w", err) + } + return nil } diff --git a/pkg/alertmanager/validation/v1alpha1/validation.go b/pkg/alertmanager/validation/v1alpha1/validation.go index a0b7dc22257..3fc0d5365fd 100644 --- a/pkg/alertmanager/validation/v1alpha1/validation.go +++ b/pkg/alertmanager/validation/v1alpha1/validation.go @@ -114,23 +114,37 @@ func validateReceivers(receivers []monitoringv1alpha1.Receiver) (map[string]stru if err := validateMSTeamsV2Configs(receiver.MSTeamsV2Configs); err != nil { return nil, fmt.Errorf("failed to validate 'msteamsv2Config' - receiver %s: %w", receiver.Name, err) } - } return receiverNames, nil } func validatePagerDutyConfigs(configs []monitoringv1alpha1.PagerDutyConfig) error { - for _, conf := range configs { - if conf.URL != "" { - if _, err := validation.ValidateURL(conf.URL); err != nil { - return fmt.Errorf("pagerduty validation failed for 'url': %w", err) - } + for i, conf := range configs { + if err := validation.ValidateURLPtr((*string)(conf.URL)); err != nil { + return fmt.Errorf("[%d]: url: %w", i, err) + } + + if err := validation.ValidateURLPtr((*string)(conf.ClientURL)); err != nil { + return fmt.Errorf("[%d]: clientURL: %w", i, err) } + if conf.RoutingKey == nil && conf.ServiceKey == nil { return errors.New("one of 'routingKey' or 'serviceKey' is required") } + for j, lc := range conf.PagerDutyLinkConfigs { + if err := validation.ValidateURLPtr((*string)(lc.Href)); err != nil { + return fmt.Errorf("[%d]: pagerDutyLinkConfigs[%d]: href: %w", i, j, err) + } + } + + for j, ic := range conf.PagerDutyImageConfigs { + if err := validation.ValidateURLPtr((*string)(ic.Href)); err != nil { + return fmt.Errorf("[%d]: pagerDutyImageConfigs[%d]: href: %w", i, j, err) + } + } + if err := conf.HTTPConfig.Validate(); err != nil { return err } @@ -139,20 +153,20 @@ func validatePagerDutyConfigs(configs []monitoringv1alpha1.PagerDutyConfig) erro } func validateOpsGenieConfigs(configs []monitoringv1alpha1.OpsGenieConfig) error { - for _, config := range configs { + for i, config := range configs { if err := config.Validate(); err != nil { - return err + return fmt.Errorf("[%d]: %w", i, err) } - if config.APIURL != "" { - if _, err := validation.ValidateURL(config.APIURL); err != nil { - return fmt.Errorf("invalid 'apiURL': %w", err) - } + + if err := validation.ValidateURLPtr((*string)(config.APIURL)); err != nil { + return fmt.Errorf("[%d]: apiURL: %w", i, err) } if err := config.HTTPConfig.Validate(); err != nil { - return err + return fmt.Errorf("[%d]: %w", i, err) } } + return nil } @@ -166,26 +180,43 @@ func validateDiscordConfigs(configs []monitoringv1alpha1.DiscordConfig) error { } func validateRocketchatConfigs(configs []monitoringv1alpha1.RocketChatConfig) error { - for _, config := range configs { - if config.APIURL != nil && *config.APIURL != "" { - if _, err := validation.ValidateURL(string(*config.APIURL)); err != nil { - return fmt.Errorf("invalid 'apiURL': %w", err) - } + for i, config := range configs { + if err := validation.ValidateURLPtr((*string)(config.APIURL)); err != nil { + return fmt.Errorf("[%d]: apiURL: %w", i, err) } if err := config.HTTPConfig.Validate(); err != nil { - return err + return fmt.Errorf("[%d]: %w", i, err) } } + return nil } func validateSlackConfigs(configs []monitoringv1alpha1.SlackConfig) error { - for _, config := range configs { + for i, config := range configs { if err := config.Validate(); err != nil { return err } + if err := validation.ValidateURLPtr((*string)(config.IconURL)); err != nil { + return fmt.Errorf("[%d]: iconURL: %w", i, err) + } + + if err := validation.ValidateURLPtr((*string)(config.ImageURL)); err != nil { + return fmt.Errorf("[%d]: imageURL: %w", i, err) + } + + if err := validation.ValidateURLPtr((*string)(config.ThumbURL)); err != nil { + return fmt.Errorf("[%d]: thumbURL: %w", i, err) + } + + for j, sa := range config.Actions { + if err := validation.ValidateURLPtr((*string)(sa.URL)); err != nil { + return fmt.Errorf("[%d]: invalid 'action'[%d]: url: %w", i, j, err) + } + } + if err := config.HTTPConfig.Validate(); err != nil { return err } @@ -194,35 +225,34 @@ func validateSlackConfigs(configs []monitoringv1alpha1.SlackConfig) error { } func validateWebhookConfigs(configs []monitoringv1alpha1.WebhookConfig) error { - for _, config := range configs { + for i, config := range configs { if config.URL == nil && config.URLSecret == nil { - return errors.New("one of 'url' or 'urlSecret' must be specified") + return fmt.Errorf("[%d]: one of 'url' or 'urlSecret' must be specified", i) } - if config.URL != nil { - if _, err := validation.ValidateURL(*config.URL); err != nil { - return fmt.Errorf("invalid 'url': %w", err) - } + + if err := validation.ValidateURLPtr((*string)(config.URL)); err != nil { + return fmt.Errorf("[%d]: url: %w", i, err) } if err := config.HTTPConfig.Validate(); err != nil { - return err + return fmt.Errorf("[%d]: %w", i, err) } } + return nil } func validateWechatConfigs(configs []monitoringv1alpha1.WeChatConfig) error { - for _, config := range configs { - if config.APIURL != "" { - if _, err := validation.ValidateURL(config.APIURL); err != nil { - return fmt.Errorf("invalid 'apiURL': %w", err) - } + for i, config := range configs { + if err := validation.ValidateURLPtr((*string)(config.APIURL)); err != nil { + return fmt.Errorf("[%d]: apiURL: %w", i, err) } if err := config.HTTPConfig.Validate(); err != nil { - return err + return fmt.Errorf("[%d]: %w", i, err) } } + return nil } @@ -255,7 +285,7 @@ func validateEmailConfig(configs []monitoringv1alpha1.EmailConfig) error { } func validateVictorOpsConfigs(configs []monitoringv1alpha1.VictorOpsConfig) error { - for _, config := range configs { + for i, config := range configs { // from https://github.com/prometheus/alertmanager/blob/a7f9fdadbecbb7e692d2cd8d3334e3d6de1602e1/config/notifiers.go#L497 reservedFields := map[string]struct{}{ @@ -280,10 +310,8 @@ func validateVictorOpsConfigs(configs []monitoringv1alpha1.VictorOpsConfig) erro return errors.New("missing 'routingKey' key") } - if config.APIURL != "" { - if _, err := validation.ValidateURL(config.APIURL); err != nil { - return fmt.Errorf("'apiURL' %s invalid: %w", config.APIURL, err) - } + if err := validation.ValidateURLPtr((*string)(config.APIURL)); err != nil { + return fmt.Errorf("[%d]: apiURL: %w", i, err) } if err := config.HTTPConfig.Validate(); err != nil { @@ -294,7 +322,7 @@ func validateVictorOpsConfigs(configs []monitoringv1alpha1.VictorOpsConfig) erro } func validatePushoverConfigs(configs []monitoringv1alpha1.PushoverConfig) error { - for _, config := range configs { + for i, config := range configs { if config.UserKey == nil && config.UserKeyFile == nil { return fmt.Errorf("one of userKey or userKeyFile must be configured") } @@ -307,6 +335,10 @@ func validatePushoverConfigs(configs []monitoringv1alpha1.PushoverConfig) error return fmt.Errorf("html and monospace options are mutually exclusive") } + if err := validation.ValidateURLPtr((*string)(config.URL)); err != nil { + return fmt.Errorf("[%d]: url: %w", i, err) + } + if err := config.HTTPConfig.Validate(); err != nil { return err } @@ -329,18 +361,21 @@ func validateSnsConfigs(configs []monitoringv1alpha1.SNSConfig) error { } func validateTelegramConfigs(configs []monitoringv1alpha1.TelegramConfig) error { - for _, config := range configs { - + for i, config := range configs { if config.BotToken == nil && config.BotTokenFile == nil { - return fmt.Errorf("mandatory field botToken or botTokenfile is empty") + return fmt.Errorf("[%d]: mandatory field botToken or botTokenfile is empty", i) } if config.ChatID == 0 { - return fmt.Errorf("mandatory field %q is empty", "chatID") + return fmt.Errorf("[%d]: mandatory field %q is empty", i, "chatID") + } + + if err := validation.ValidateURLPtr((*string)(config.APIURL)); err != nil { + return fmt.Errorf("[%d]: apiURL: %w", i, err) } if err := config.HTTPConfig.Validate(); err != nil { - return err + return fmt.Errorf("[%d]: %w", i, err) } } @@ -348,15 +383,13 @@ func validateTelegramConfigs(configs []monitoringv1alpha1.TelegramConfig) error } func validateWebexConfigs(configs []monitoringv1alpha1.WebexConfig) error { - for _, config := range configs { - if config.APIURL != nil && *config.APIURL != "" { - if _, err := validation.ValidateURL(string(*config.APIURL)); err != nil { - return fmt.Errorf("invalid 'apiURL': %w", err) - } + for i, config := range configs { + if err := validation.ValidateURLPtr((*string)(config.APIURL)); err != nil { + return fmt.Errorf("[%d]: apiURL: %w", i, err) } if err := config.HTTPConfig.Validate(); err != nil { - return err + return fmt.Errorf("[%d]: %w", i, err) } } diff --git a/pkg/alertmanager/validation/v1beta1/validation.go b/pkg/alertmanager/validation/v1beta1/validation.go index 154128ebe0a..f0dcfbf186a 100644 --- a/pkg/alertmanager/validation/v1beta1/validation.go +++ b/pkg/alertmanager/validation/v1beta1/validation.go @@ -114,23 +114,37 @@ func validateReceivers(receivers []monitoringv1beta1.Receiver) (map[string]struc if err := validateMSTeamsV2Configs(receiver.MSTeamsV2Configs); err != nil { return nil, fmt.Errorf("failed to validate 'msteamsv2Config' - receiver %s: %w", receiver.Name, err) } - } return receiverNames, nil } func validatePagerDutyConfigs(configs []monitoringv1beta1.PagerDutyConfig) error { - for _, conf := range configs { - if conf.URL != "" { - if _, err := validation.ValidateURL(conf.URL); err != nil { - return fmt.Errorf("pagerduty validation failed for 'url': %w", err) - } + for i, conf := range configs { + if err := validation.ValidateURLPtr((*string)(conf.URL)); err != nil { + return fmt.Errorf("[%d]: url: %w", i, err) + } + + if err := validation.ValidateURLPtr((*string)(conf.ClientURL)); err != nil { + return fmt.Errorf("[%d]: clientURL: %w", i, err) } + if conf.RoutingKey == nil && conf.ServiceKey == nil { return errors.New("one of 'routingKey' or 'serviceKey' is required") } + for j, lc := range conf.PagerDutyLinkConfigs { + if err := validation.ValidateURLPtr((*string)(lc.Href)); err != nil { + return fmt.Errorf("[%d]: pagerDutyLinkConfigs[%d]: href: %w", i, j, err) + } + } + + for j, ic := range conf.PagerDutyImageConfigs { + if err := validation.ValidateURLPtr((*string)(ic.Href)); err != nil { + return fmt.Errorf("[%d]: pagerDutyImageConfigs[%d]: href: %w", i, j, err) + } + } + if err := conf.HTTPConfig.Validate(); err != nil { return err } @@ -139,29 +153,47 @@ func validatePagerDutyConfigs(configs []monitoringv1beta1.PagerDutyConfig) error } func validateOpsGenieConfigs(configs []monitoringv1beta1.OpsGenieConfig) error { - for _, config := range configs { + for i, config := range configs { if err := config.Validate(); err != nil { - return err + return fmt.Errorf("[%d]: %w", i, err) } - if config.APIURL != "" { - if _, err := validation.ValidateURL(config.APIURL); err != nil { - return fmt.Errorf("invalid 'apiURL': %w", err) - } + + if err := validation.ValidateURLPtr((*string)(config.APIURL)); err != nil { + return fmt.Errorf("[%d]: apiURL: %w", i, err) } if err := config.HTTPConfig.Validate(); err != nil { - return err + return fmt.Errorf("[%d]: %w", i, err) } } + return nil } func validateSlackConfigs(configs []monitoringv1beta1.SlackConfig) error { - for _, config := range configs { + for i, config := range configs { if err := config.Validate(); err != nil { return err } + if err := validation.ValidateURLPtr((*string)(config.IconURL)); err != nil { + return fmt.Errorf("[%d]: iconURL: %w", i, err) + } + + if err := validation.ValidateURLPtr((*string)(config.ImageURL)); err != nil { + return fmt.Errorf("[%d]: imageURL: %w", i, err) + } + + if err := validation.ValidateURLPtr((*string)(config.ThumbURL)); err != nil { + return fmt.Errorf("[%d]: thumbURL: %w", i, err) + } + + for j, sa := range config.Actions { + if err := validation.ValidateURLPtr((*string)(sa.URL)); err != nil { + return fmt.Errorf("[%d]: invalid 'action'[%d]: url: %w", i, j, err) + } + } + if err := config.HTTPConfig.Validate(); err != nil { return err } @@ -170,35 +202,34 @@ func validateSlackConfigs(configs []monitoringv1beta1.SlackConfig) error { } func validateWebhookConfigs(configs []monitoringv1beta1.WebhookConfig) error { - for _, config := range configs { + for i, config := range configs { if config.URL == nil && config.URLSecret == nil { - return errors.New("one of 'url' or 'urlSecret' must be specified") + return fmt.Errorf("[%d]: one of 'url' or 'urlSecret' must be specified", i) } - if config.URL != nil { - if _, err := validation.ValidateURL(*config.URL); err != nil { - return fmt.Errorf("invalid 'url': %w", err) - } + + if err := validation.ValidateURLPtr((*string)(config.URL)); err != nil { + return fmt.Errorf("[%d]: url: %w", i, err) } if err := config.HTTPConfig.Validate(); err != nil { - return err + return fmt.Errorf("[%d]: %w", i, err) } } + return nil } func validateWechatConfigs(configs []monitoringv1beta1.WeChatConfig) error { - for _, config := range configs { - if config.APIURL != "" { - if _, err := validation.ValidateURL(config.APIURL); err != nil { - return fmt.Errorf("invalid 'apiURL': %w", err) - } + for i, config := range configs { + if err := validation.ValidateURLPtr((*string)(config.APIURL)); err != nil { + return fmt.Errorf("[%d]: apiURL: %w", i, err) } if err := config.HTTPConfig.Validate(); err != nil { - return err + return fmt.Errorf("[%d]: %w", i, err) } } + return nil } @@ -231,7 +262,7 @@ func validateEmailConfig(configs []monitoringv1beta1.EmailConfig) error { } func validateVictorOpsConfigs(configs []monitoringv1beta1.VictorOpsConfig) error { - for _, config := range configs { + for i, config := range configs { // from https://github.com/prometheus/alertmanager/blob/a7f9fdadbecbb7e692d2cd8d3334e3d6de1602e1/config/notifiers.go#L497 reservedFields := map[string]struct{}{ @@ -256,10 +287,8 @@ func validateVictorOpsConfigs(configs []monitoringv1beta1.VictorOpsConfig) error return errors.New("missing 'routingKey' key") } - if config.APIURL != "" { - if _, err := validation.ValidateURL(config.APIURL); err != nil { - return fmt.Errorf("'apiURL' %s invalid: %w", config.APIURL, err) - } + if err := validation.ValidateURLPtr((*string)(config.APIURL)); err != nil { + return fmt.Errorf("[%d]: apiURL: %w", i, err) } if err := config.HTTPConfig.Validate(); err != nil { @@ -270,7 +299,7 @@ func validateVictorOpsConfigs(configs []monitoringv1beta1.VictorOpsConfig) error } func validatePushoverConfigs(configs []monitoringv1beta1.PushoverConfig) error { - for _, config := range configs { + for i, config := range configs { if config.UserKey == nil && config.UserKeyFile == nil { return fmt.Errorf("one of userKey or userKeyFile must be configured") } @@ -283,6 +312,10 @@ func validatePushoverConfigs(configs []monitoringv1beta1.PushoverConfig) error { return fmt.Errorf("html and monospace options are mutually exclusive") } + if err := validation.ValidateURLPtr((*string)(config.URL)); err != nil { + return fmt.Errorf("[%d]: url: %w", i, err) + } + if err := config.HTTPConfig.Validate(); err != nil { return err } @@ -305,18 +338,21 @@ func validateSnsConfigs(configs []monitoringv1beta1.SNSConfig) error { } func validateTelegramConfigs(configs []monitoringv1beta1.TelegramConfig) error { - for _, config := range configs { - + for i, config := range configs { if config.BotToken == nil && config.BotTokenFile == nil { - return fmt.Errorf("mandatory field botToken or botTokenfile is empty") + return fmt.Errorf("[%d]: mandatory field botToken or botTokenfile is empty", i) } if config.ChatID == 0 { - return fmt.Errorf("mandatory field %q is empty", "chatID") + return fmt.Errorf("[%d]: mandatory field %q is empty", i, "chatID") + } + + if err := validation.ValidateURLPtr((*string)(config.APIURL)); err != nil { + return fmt.Errorf("[%d]: apiURL: %w", i, err) } if err := config.HTTPConfig.Validate(); err != nil { - return err + return fmt.Errorf("[%d]: %w", i, err) } } @@ -324,15 +360,13 @@ func validateTelegramConfigs(configs []monitoringv1beta1.TelegramConfig) error { } func validateWebexConfigs(configs []monitoringv1beta1.WebexConfig) error { - for _, config := range configs { - if config.APIURL != nil && *config.APIURL != "" { - if _, err := validation.ValidateURL(string(*config.APIURL)); err != nil { - return fmt.Errorf("invalid 'apiURL': %w", err) - } + for i, config := range configs { + if err := validation.ValidateURLPtr((*string)(config.APIURL)); err != nil { + return fmt.Errorf("[%d]: apiURL: %w", i, err) } if err := config.HTTPConfig.Validate(); err != nil { - return err + return fmt.Errorf("[%d]: %w", i, err) } } @@ -350,15 +384,13 @@ func validateDiscordConfigs(configs []monitoringv1beta1.DiscordConfig) error { } func validateRocketchatConfigs(configs []monitoringv1beta1.RocketChatConfig) error { - for _, config := range configs { - if config.APIURL != nil && *config.APIURL != "" { - if _, err := validation.ValidateURL(string(*config.APIURL)); err != nil { - return fmt.Errorf("invalid 'apiURL': %w", err) - } + for i, config := range configs { + if err := validation.ValidateURLPtr((*string)(config.APIURL)); err != nil { + return fmt.Errorf("[%d]: apiURL: %w", i, err) } if err := config.HTTPConfig.Validate(); err != nil { - return err + return fmt.Errorf("[%d]: %w", i, err) } } diff --git a/pkg/alertmanager/validation/v1beta1/validation_test.go b/pkg/alertmanager/validation/v1beta1/validation_test.go index 74fea8c05c5..fd267183014 100644 --- a/pkg/alertmanager/validation/v1beta1/validation_test.go +++ b/pkg/alertmanager/validation/v1beta1/validation_test.go @@ -83,8 +83,8 @@ func TestValidateAlertmanagerConfig(t *testing.T) { { Type: "a", Text: "b", - URL: "www.test.com", - Name: "c", + URL: ptr.To(monitoringv1beta1.URL("www.test.com")), + Name: ptr.To("c"), ConfirmField: &monitoringv1beta1.SlackConfirmationField{ Text: "d", }, @@ -132,7 +132,7 @@ func TestValidateAlertmanagerConfig(t *testing.T) { Name: "different", WeChatConfigs: []monitoringv1beta1.WeChatConfig{ { - APIURL: "http://%>= 0.24.0. @@ -349,7 +382,7 @@ type AlertmanagerSpec struct { // automountServiceAccountToken defines whether a service account token should be automatically mounted in the pod. // If the service account has `automountServiceAccountToken: true`, set the field to `false` to opt out of automounting API credentials. // +optional - AutomountServiceAccountToken *bool `json:"automountServiceAccountToken,omitempty"` + AutomountServiceAccountToken *bool `json:"automountServiceAccountToken,omitempty"` // nolint:kubeapilinter // enableFeatures defines the Alertmanager's feature flags. By default, no features are enabled. // Enabling features which are disabled by default is entirely outside the // scope of what the maintainers will support and by doing so, you accept @@ -385,7 +418,7 @@ type AlertmanagerSpec struct { // Starting Kubernetes 1.33, the feature is enabled by default. // // +optional - HostUsers *bool `json:"hostUsers,omitempty"` + HostUsers *bool `json:"hostUsers,omitempty"` // nolint:kubeapilinter } type AlertmanagerConfigMatcherStrategy struct { @@ -452,7 +485,7 @@ type AlertmanagerGlobalConfig struct { // httpConfig defines the default HTTP configuration. // +optional - HTTPConfig *HTTPConfig `json:"httpConfig,omitempty"` + HTTPConfigWithProxy *HTTPConfigWithProxy `json:"httpConfig,omitempty"` // slackApiUrl defines the default Slack API URL. // +optional @@ -486,7 +519,7 @@ type AlertmanagerGlobalConfig struct { // +optional RocketChatConfig *GlobalRocketChatConfig `json:"rocketChat,omitempty"` - // webex defines the default configuration for Jira. + // webex defines the default configuration for Webex. // +optional WebexConfig *GlobalWebexConfig `json:"webex,omitempty"` @@ -503,7 +536,7 @@ type AlertmanagerStatus struct { // paused defines whether any actions on the underlying managed objects are // being performed. Only delete actions will be performed. // +optional - Paused bool `json:"paused"` + Paused bool `json:"paused"` // nolint:kubeapilinter // replicas defines the total number of non-terminated pods targeted by this Alertmanager // object (their labels match the selector). // +optional @@ -607,7 +640,7 @@ type GlobalSMTPConfig struct { // requireTLS defines the default SMTP TLS requirement. // Note that Go does not support unencrypted connections to remote SMTP endpoints. // +optional - RequireTLS *bool `json:"requireTLS,omitempty"` + RequireTLS *bool `json:"requireTLS,omitempty"` // nolint:kubeapilinter // tlsConfig defines the default TLS configuration for SMTP receivers // +optional diff --git a/pkg/apis/monitoring/v1/http_config.go b/pkg/apis/monitoring/v1/http_config.go index 3d7a0b82300..1590d23e097 100644 --- a/pkg/apis/monitoring/v1/http_config.go +++ b/pkg/apis/monitoring/v1/http_config.go @@ -21,8 +21,49 @@ import ( v1 "k8s.io/api/core/v1" ) -// HTTPConfig defines the configuration for the HTTP client. -type HTTPConfig struct { +// HTTPConfigWithProxyAndTLSFiles defines the configuration for the HTTP client +// with proxy configuration and TLS configuration. It is used for +// ServiceMonitor endpoints. +type HTTPConfigWithProxyAndTLSFiles struct { + HTTPConfigWithTLSFiles `json:",inline"` + ProxyConfig `json:",inline"` +} + +// Validate semantically validates the given TLSConfig. +func (c *HTTPConfigWithProxyAndTLSFiles) Validate() error { + if err := c.HTTPConfigWithTLSFiles.Validate(); err != nil { + return err + } + + if err := c.ProxyConfig.Validate(); err != nil { + return err + } + + return nil +} + +// HTTPConfigWithProxy defines the configuration for the HTTP client with proxy +// configuration. It is used for PodMonitor endpoints and Probes. +type HTTPConfigWithProxy struct { + HTTPConfig `json:",inline"` + ProxyConfig `json:",inline"` +} + +// Validate semantically validates the given HTTPConfigWithProxy. +func (hc *HTTPConfigWithProxy) Validate() error { + if hc == nil { + return nil + } + + if err := hc.HTTPConfig.Validate(); err != nil { + return err + } + + return hc.ProxyConfig.Validate() +} + +// HTTPConfigWithoutTLS defines the configuration for the HTTP client. +type HTTPConfigWithoutTLS struct { // authorization configures the Authorization header credentials used by // the client. // @@ -60,27 +101,20 @@ type HTTPConfig struct { // Deprecated: use `authorization` instead. BearerTokenSecret *v1.SecretKeySelector `json:"bearerTokenSecret,omitempty"` - // tlsConfig defines the TLS configuration used by the client. - // - // +optional - TLSConfig *SafeTLSConfig `json:"tlsConfig,omitempty"` - - ProxyConfig `json:",inline"` - // followRedirects defines whether the client should follow HTTP 3xx // redirects. // // +optional - FollowRedirects *bool `json:"followRedirects,omitempty"` + FollowRedirects *bool `json:"followRedirects,omitempty"` // nolint:kubeapilinter // enableHttp2 can be used to disable HTTP2. // // +optional - EnableHTTP2 *bool `json:"enableHttp2,omitempty"` + EnableHTTP2 *bool `json:"enableHttp2,omitempty"` // nolint:kubeapilinter } -// Validate semantically validates the given HTTPConfig. -func (hc *HTTPConfig) Validate() error { +// Validate semantically validates the given HTTPConfigWithoutTLS. +func (hc *HTTPConfigWithoutTLS) Validate() error { if hc == nil { return nil } @@ -118,13 +152,56 @@ func (hc *HTTPConfig) Validate() error { return fmt.Errorf("oauth2: %w", err) } + return nil +} + +// HTTPConfig defines the HTTP configuration + TLS configuration (only from +// secret/configmap references). +type HTTPConfig struct { + HTTPConfigWithoutTLS `json:",inline"` + + // tlsConfig defines the TLS configuration used by the client. + // + // +optional + TLSConfig *SafeTLSConfig `json:"tlsConfig,omitempty"` +} + +// Validate semantically validates the given HTTPConfig. +func (hc *HTTPConfig) Validate() error { + if hc == nil { + return nil + } + + if err := hc.HTTPConfigWithoutTLS.Validate(); err != nil { + return err + } if err := hc.TLSConfig.Validate(); err != nil { return fmt.Errorf("tlsConfig: %w", err) } - if err := hc.ProxyConfig.Validate(); err != nil { + return nil +} + +// HTTPConfigWithTLSFiles defines HTTP configuration + TLS configuration +// (from secret/configmap references as well as files). +type HTTPConfigWithTLSFiles struct { + HTTPConfigWithoutTLS `json:",inline"` + + // tlsConfig defines TLS configuration used by the client. + // + // +optional + TLSConfig *TLSConfig `json:"tlsConfig,omitempty"` +} + +// Validate semantically validates the given HTTPConfigWithTLSFiles. +func (c *HTTPConfigWithTLSFiles) Validate() error { + if err := c.HTTPConfigWithoutTLS.Validate(); err != nil { return err } + if err := c.TLSConfig.Validate(); err != nil { + return fmt.Errorf("tlsConfig: %w", err) + } + return nil } diff --git a/pkg/apis/monitoring/v1/podmonitor_types.go b/pkg/apis/monitoring/v1/podmonitor_types.go index 8f439fd11cb..d7da9bdcaa2 100644 --- a/pkg/apis/monitoring/v1/podmonitor_types.go +++ b/pkg/apis/monitoring/v1/podmonitor_types.go @@ -267,6 +267,7 @@ type PodMetricsEndpoint struct { // params define optional HTTP URL parameters. // +optional + //nolint:kubeapilinter Params map[string][]string `json:"params,omitempty"` // interval at which Prometheus scrapes the metrics from the target. @@ -286,13 +287,13 @@ type PodMetricsEndpoint struct { // honorLabels when true preserves the metric's labels when they collide // with the target's labels. // +optional - HonorLabels bool `json:"honorLabels,omitempty"` + HonorLabels bool `json:"honorLabels,omitempty"` // nolint:kubeapilinter // honorTimestamps defines whether Prometheus preserves the timestamps // when exposed by the target. // // +optional - HonorTimestamps *bool `json:"honorTimestamps,omitempty"` + HonorTimestamps *bool `json:"honorTimestamps,omitempty"` // nolint:kubeapilinter // trackTimestampsStaleness defines whether Prometheus tracks staleness of // the metrics that have an explicit timestamp present in scraped data. @@ -301,7 +302,7 @@ type PodMetricsEndpoint struct { // It requires Prometheus >= v2.48.0. // // +optional - TrackTimestampsStaleness *bool `json:"trackTimestampsStaleness,omitempty"` + TrackTimestampsStaleness *bool `json:"trackTimestampsStaleness,omitempty"` // nolint:kubeapilinter // metricRelabelings defines the relabeling rules to apply to the // samples before ingestion. @@ -329,7 +330,7 @@ type PodMetricsEndpoint struct { // More info: https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle/#pod-phase // // +optional - FilterRunning *bool `json:"filterRunning,omitempty"` + FilterRunning *bool `json:"filterRunning,omitempty"` // nolint:kubeapilinter - HTTPConfig `json:",inline"` + HTTPConfigWithProxy `json:",inline"` } diff --git a/pkg/apis/monitoring/v1/probe_types.go b/pkg/apis/monitoring/v1/probe_types.go index 34218f4ca58..dc7ad44ee99 100644 --- a/pkg/apis/monitoring/v1/probe_types.go +++ b/pkg/apis/monitoring/v1/probe_types.go @@ -17,7 +17,6 @@ package v1 import ( "errors" - v1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" ) @@ -75,10 +74,12 @@ type ProbeSpec struct { // jobName assigned to scraped metrics by default. // +optional JobName string `json:"jobName,omitempty"` + // prober defines the specification for the prober to use for probing targets. // The prober.URL parameter is required. Targets cannot be probed if left empty. // +optional ProberSpec ProberSpec `json:"prober,omitempty"` + // module to use for probing specifying how to probe the target. // Example module configuring in the blackbox exporter: // https://github.com/prometheus/blackbox_exporter/blob/master/example.yml @@ -96,21 +97,7 @@ type ProbeSpec struct { // The value cannot be greater than the scrape interval otherwise the operator will reject the resource. // +optional ScrapeTimeout Duration `json:"scrapeTimeout,omitempty"` - // tlsConfig defines the TLS configuration to use when scraping the endpoint. - // +optional - TLSConfig *SafeTLSConfig `json:"tlsConfig,omitempty"` - // bearerTokenSecret defines the secret to mount to read bearer token for scraping targets. The secret - // needs to be in the same namespace as the probe and accessible by - // the Prometheus Operator. - // +optional - BearerTokenSecret v1.SecretKeySelector `json:"bearerTokenSecret,omitempty"` - // basicAuth allow an endpoint to authenticate over basic authentication. - // More info: https://prometheus.io/docs/operating/configuration/#endpoint - // +optional - BasicAuth *BasicAuth `json:"basicAuth,omitempty"` - // oauth2 for the URL. Only valid in Prometheus versions 2.27.0 and newer. - // +optional - OAuth2 *OAuth2 `json:"oauth2,omitempty"` + // metricRelabelings defines the RelabelConfig to apply to samples before ingestion. // +optional MetricRelabelConfigs []RelabelConfig `json:"metricRelabelings,omitempty"` @@ -133,19 +120,23 @@ type ProbeSpec struct { // +listType=set // +optional ScrapeProtocols []ScrapeProtocol `json:"scrapeProtocols,omitempty"` + // fallbackScrapeProtocol defines the protocol to use if a scrape returns blank, unparseable, or otherwise invalid Content-Type. // // It requires Prometheus >= v3.0.0. // +optional FallbackScrapeProtocol *ScrapeProtocol `json:"fallbackScrapeProtocol,omitempty"` + // labelLimit defines the per-scrape limit on number of labels that will be accepted for a sample. // Only valid in Prometheus versions 2.27.0 and newer. // +optional LabelLimit *uint64 `json:"labelLimit,omitempty"` + // labelNameLengthLimit defines the per-scrape limit on length of labels name that will be accepted for a sample. // Only valid in Prometheus versions 2.27.0 and newer. // +optional LabelNameLengthLimit *uint64 `json:"labelNameLengthLimit,omitempty"` + // labelValueLengthLimit defines the per-scrape limit on length of labels value that will be accepted for a sample. // Only valid in Prometheus versions 2.27.0 and newer. // +optional @@ -153,6 +144,7 @@ type ProbeSpec struct { // +optional NativeHistogramConfig `json:",inline"` + // keepDroppedTargets defines the per-scrape limit on the number of targets dropped by relabeling // that will be kept in memory. 0 means no limit. // @@ -174,6 +166,8 @@ type ProbeSpec struct { // +listType=map // +listMapKey=name Params []ProbeParam `json:"params,omitempty"` + + HTTPConfig `json:",inline"` } // ProbeParam defines specification of extra parameters for a Probe. @@ -225,6 +219,7 @@ type ProbeTargetStaticConfig struct { Targets []string `json:"static,omitempty"` // labels defines all labels assigned to all metrics scraped from the targets. // +optional + //nolint:kubeapilinter Labels map[string]string `json:"labels,omitempty"` // relabelingConfigs defines relabelings to be apply to the label set of the targets before it gets // scraped. diff --git a/pkg/apis/monitoring/v1/probe_types_test.go b/pkg/apis/monitoring/v1/probe_types_test.go index 46351373f00..85d777a7725 100644 --- a/pkg/apis/monitoring/v1/probe_types_test.go +++ b/pkg/apis/monitoring/v1/probe_types_test.go @@ -89,7 +89,7 @@ func TestMarshallProbe(t *testing.T) { }, }, } - expected := `{"metadata":{"name":"test","namespace":"default","labels":{"group":"group1"}},"spec":{"prober":{"url":""},"targets":{"staticConfig":{"static":["prometheus.io"],"labels":{"env":"prometheus"}}},"bearerTokenSecret":{"key":""}}}` + expected := `{"metadata":{"name":"test","namespace":"default","labels":{"group":"group1"}},"spec":{"prober":{"url":""},"targets":{"staticConfig":{"static":["prometheus.io"],"labels":{"env":"prometheus"}}}}}` r, err := json.Marshal(sm) if err != nil { @@ -97,6 +97,6 @@ func TestMarshallProbe(t *testing.T) { } rs := string(r) if rs != expected { - t.Fatalf("Got %s expected: %s ", rs, expected) + t.Fatalf("Got %s\nExpected: %s ", rs, expected) } } diff --git a/pkg/apis/monitoring/v1/prometheus_types.go b/pkg/apis/monitoring/v1/prometheus_types.go index 2122906ac9f..812f6efbc80 100644 --- a/pkg/apis/monitoring/v1/prometheus_types.go +++ b/pkg/apis/monitoring/v1/prometheus_types.go @@ -21,7 +21,6 @@ import ( appsv1 "k8s.io/api/apps/v1" v1 "k8s.io/api/core/v1" - "k8s.io/apimachinery/pkg/api/resource" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime/schema" @@ -222,7 +221,7 @@ type CommonPrometheusFields struct { // paused defines when a Prometheus deployment is paused, no actions except for deletion // will be performed on the underlying objects. // +optional - Paused bool `json:"paused,omitempty"` + Paused bool `json:"paused,omitempty"` // nolint:kubeapilinter // image defines the container image name for Prometheus. If specified, it takes precedence // over the `spec.baseImage`, `spec.tag` and `spec.sha` fields. @@ -337,6 +336,7 @@ type CommonPrometheusFields struct { // Labels defined by `spec.replicaExternalLabelName` and // `spec.prometheusExternalLabelName` take precedence over this list. // +optional + //nolint:kubeapilinter ExternalLabels map[string]string `json:"externalLabels,omitempty"` // enableRemoteWriteReceiver defines the Prometheus to be used as a receiver for the Prometheus remote @@ -350,7 +350,7 @@ type CommonPrometheusFields struct { // // It requires Prometheus >= v2.33.0. // +optional - EnableRemoteWriteReceiver bool `json:"enableRemoteWriteReceiver,omitempty"` + EnableRemoteWriteReceiver bool `json:"enableRemoteWriteReceiver,omitempty"` // nolint:kubeapilinter // enableOTLPReceiver defines the Prometheus to be used as a receiver for the OTLP Metrics protocol. // @@ -358,7 +358,7 @@ type CommonPrometheusFields struct { // // It requires Prometheus >= v2.47.0. // +optional - EnableOTLPReceiver *bool `json:"enableOTLPReceiver,omitempty"` + EnableOTLPReceiver *bool `json:"enableOTLPReceiver,omitempty"` // nolint:kubeapilinter // remoteWriteReceiverMessageVersions list of the protobuf message versions to accept when receiving the // remote writes. @@ -430,6 +430,7 @@ type CommonPrometheusFields struct { // nodeSelector defines on which Nodes the Pods are scheduled. // +optional + //nolint:kubeapilinter NodeSelector map[string]string `json:"nodeSelector,omitempty"` // serviceAccountName is the name of the ServiceAccount to use to run the @@ -443,7 +444,7 @@ type CommonPrometheusFields struct { // **Warning:** be aware that by default, Prometheus requires the service account token for Kubernetes service discovery. // It is possible to use strategic merge patch to project the service account token into the 'prometheus' container. // +optional - AutomountServiceAccountToken *bool `json:"automountServiceAccountToken,omitempty"` + AutomountServiceAccountToken *bool `json:"automountServiceAccountToken,omitempty"` // nolint:kubeapilinter // secrets defines a list of Secrets in the same namespace as the Prometheus // object, which shall be mounted into the Prometheus Pods. @@ -497,11 +498,33 @@ type CommonPrometheusFields struct { // instead of the Pod IP's address. // // +optional - ListenLocal bool `json:"listenLocal,omitempty"` + ListenLocal bool `json:"listenLocal,omitempty"` // nolint:kubeapilinter + + // podManagementPolicy defines the policy for creating/deleting pods when + // scaling up and down. + // + // Unlike the default StatefulSet behavior, the default policy is + // `Parallel` to avoid manual intervention in case a pod gets stuck during + // a rollout. + // + // Note that updating this value implies the recreation of the StatefulSet + // which incurs a service outage. + // + // +optional + PodManagementPolicy *PodManagementPolicyType `json:"podManagementPolicy,omitempty"` + + // updateStrategy indicates the strategy that will be employed to update + // Pods in the StatefulSet when a revision is made to statefulset's Pod + // Template. + // + // The default strategy is RollingUpdate. + // + // +optional + UpdateStrategy *StatefulSetUpdateStrategy `json:"updateStrategy,omitempty"` // enableServiceLinks defines whether information about services should be injected into pod's environment variables // +optional - EnableServiceLinks *bool `json:"enableServiceLinks,omitempty"` + EnableServiceLinks *bool `json:"enableServiceLinks,omitempty"` // nolint:kubeapilinter // containers allows injecting additional containers or modifying operator // generated containers. This can be used to allow adding an authentication @@ -588,19 +611,19 @@ type CommonPrometheusFields struct { // In practice,`OverrideHonorLabels:true` enforces `honorLabels:false` // for all ServiceMonitor, PodMonitor and ScrapeConfig objects. // +optional - OverrideHonorLabels bool `json:"overrideHonorLabels,omitempty"` + OverrideHonorLabels bool `json:"overrideHonorLabels,omitempty"` // nolint:kubeapilinter // overrideHonorTimestamps when true, Prometheus ignores the timestamps for all the targets created // from service and pod monitors. // Otherwise the HonorTimestamps field of the service or pod monitor applies. // +optional - OverrideHonorTimestamps bool `json:"overrideHonorTimestamps,omitempty"` + OverrideHonorTimestamps bool `json:"overrideHonorTimestamps,omitempty"` // nolint:kubeapilinter // ignoreNamespaceSelectors when true, `spec.namespaceSelector` from all PodMonitor, ServiceMonitor // and Probe objects will be ignored. They will only discover targets // within the namespace of the PodMonitor, ServiceMonitor and Probe // object. // +optional - IgnoreNamespaceSelectors bool `json:"ignoreNamespaceSelectors,omitempty"` + IgnoreNamespaceSelectors bool `json:"ignoreNamespaceSelectors,omitempty"` // nolint:kubeapilinter // enforcedNamespaceLabel when not empty, a label will be added to: // @@ -755,7 +778,13 @@ type CommonPrometheusFields struct { // It requires Prometheus >= v3.4.0. // // +optional - ConvertClassicHistogramsToNHCB *bool `json:"convertClassicHistogramsToNHCB,omitempty"` + ConvertClassicHistogramsToNHCB *bool `json:"convertClassicHistogramsToNHCB,omitempty"` // nolint:kubeapilinter + + // scrapeNativeHistograms defines whether to enable scraping of native histograms. + // It requires Prometheus >= v3.8.0. + // + // +optional + ScrapeNativeHistograms *bool `json:"scrapeNativeHistograms,omitempty"` // nolint:kubeapilinter // scrapeClassicHistograms defines whether to scrape a classic histogram that is also exposed as a native histogram. // @@ -764,7 +793,7 @@ type CommonPrometheusFields struct { // It requires Prometheus >= v3.5.0. // // +optional - ScrapeClassicHistograms *bool `json:"scrapeClassicHistograms,omitempty"` + ScrapeClassicHistograms *bool `json:"scrapeClassicHistograms,omitempty"` // nolint:kubeapilinter // minReadySeconds defines the minimum number of seconds for which a newly created Pod should be ready // without any of its container crashing for it to be considered available. @@ -804,7 +833,7 @@ type CommonPrometheusFields struct { // Requires Prometheus v2.11.0 and above. // // +optional - WALCompression *bool `json:"walCompression,omitempty"` + WALCompression *bool `json:"walCompression,omitempty"` // nolint:kubeapilinter // excludedFromEnforcement defines the list of references to PodMonitor, ServiceMonitor, Probe and PrometheusRule objects // to be excluded from enforcing a namespace label of origin. @@ -824,7 +853,7 @@ type CommonPrometheusFields struct { // to a different value). // // +optional - HostNetwork bool `json:"hostNetwork,omitempty"` + HostNetwork bool `json:"hostNetwork,omitempty"` // nolint:kubeapilinter // podTargetLabels are appended to the `spec.podTargetLabels` field of all // PodMonitor and ServiceMonitor objects. @@ -838,7 +867,7 @@ type CommonPrometheusFields struct { // in a breaking way. // // +optional - TracingConfig *PrometheusTracingConfig `json:"tracingConfig,omitempty"` + TracingConfig *TracingConfig `json:"tracingConfig,omitempty"` // bodySizeLimit defines per-scrape on response body size. // Only valid in Prometheus versions 2.45.0 and newer. // @@ -981,7 +1010,7 @@ type CommonPrometheusFields struct { // Starting Kubernetes 1.33, the feature is enabled by default. // // +optional - HostUsers *bool `json:"hostUsers,omitempty"` + HostUsers *bool `json:"hostUsers,omitempty"` // nolint:kubeapilinter } // Specifies the validation scheme for metric and label names. @@ -1162,7 +1191,7 @@ type PrometheusSpec struct { // When `spec.thanos.objectStorageConfig` or `spec.objectStorageConfigFile` are defined, the operator automatically // disables block compaction to avoid race conditions during block uploads (as the Thanos documentation recommends). // +optional - DisableCompaction bool `json:"disableCompaction,omitempty"` + DisableCompaction bool `json:"disableCompaction,omitempty"` // nolint:kubeapilinter // rules defines the configuration of the Prometheus rules' engine. // +optional @@ -1252,7 +1281,7 @@ type PrometheusSpec struct { // // Deprecated: this flag has no effect for Prometheus >= 2.39.0 where overlapping blocks are enabled by default. // +optional - AllowOverlappingBlocks bool `json:"allowOverlappingBlocks,omitempty"` + AllowOverlappingBlocks bool `json:"allowOverlappingBlocks,omitempty"` // nolint:kubeapilinter // exemplars related settings that are runtime reloadable. // It requires to enable the `exemplar-storage` feature flag to be effective. @@ -1280,7 +1309,7 @@ type PrometheusSpec struct { // For more information: // https://prometheus.io/docs/prometheus/latest/querying/api/#tsdb-admin-apis // +optional - EnableAdminAPI bool `json:"enableAdminAPI,omitempty"` + EnableAdminAPI bool `json:"enableAdminAPI,omitempty"` // nolint:kubeapilinter } type WhenScaledRetentionType string @@ -1311,43 +1340,6 @@ type ShardRetentionPolicy struct { Retain *RetainConfig `json:"retain,omitempty"` } -type PrometheusTracingConfig struct { - // clientType defines the client used to export the traces. Supported values are `http` or `grpc`. - // +kubebuilder:validation:Enum=http;grpc - // +optional - ClientType *string `json:"clientType"` - - // endpoint to send the traces to. Should be provided in format :. - // +kubebuilder:validation:MinLength:=1 - // +required - Endpoint string `json:"endpoint"` - - // samplingFraction defines the probability a given trace will be sampled. Must be a float from 0 through 1. - // +optional - SamplingFraction *resource.Quantity `json:"samplingFraction"` - - // insecure if disabled, the client will use a secure connection. - // +optional - Insecure *bool `json:"insecure"` - - // headers defines the key-value pairs to be used as headers associated with gRPC or HTTP requests. - // +optional - Headers map[string]string `json:"headers"` - - // compression key for supported compression types. The only supported value is `gzip`. - // +kubebuilder:validation:Enum=gzip - // +optional - Compression *string `json:"compression"` - - // timeout defines the maximum time the exporter will wait for each batch export. - // +optional - Timeout *Duration `json:"timeout"` - - // tlsConfig to use when sending traces. - // +optional - TLSConfig *TLSConfig `json:"tlsConfig"` -} - // PrometheusStatus is the most recent observed status of the Prometheus cluster. // More info: // https://github.com/kubernetes/community/blob/master/contributors/devel/sig-architecture/api-conventions.md#spec-and-status @@ -1356,7 +1348,7 @@ type PrometheusStatus struct { // paused defines whether any actions on the underlying managed objects are // being performed. Only delete actions will be performed. // +optional - Paused bool `json:"paused"` + Paused bool `json:"paused"` // nolint:kubeapilinter // replicas defines the total number of non-terminated pods targeted by this Prometheus deployment // (their labels match the selector). // +optional @@ -1410,7 +1402,7 @@ type AlertingSpec struct { type StorageSpec struct { // disableMountSubPath deprecated: subPath usage will be removed in a future release. // +optional - DisableMountSubPath bool `json:"disableMountSubPath,omitempty"` + DisableMountSubPath bool `json:"disableMountSubPath,omitempty"` // nolint:kubeapilinter // emptyDir to be used by the StatefulSet. // If specified, it takes precedence over `ephemeral` and `volumeClaimTemplate`. // More info: https://kubernetes.io/docs/concepts/storage/volumes/#emptydir @@ -1522,21 +1514,21 @@ type ThanosSpec struct { // listenLocal is deprecated: use `grpcListenLocal` and `httpListenLocal` instead. // +optional - ListenLocal bool `json:"listenLocal,omitempty"` + ListenLocal bool `json:"listenLocal,omitempty"` // nolint:kubeapilinter // grpcListenLocal defines when true, the Thanos sidecar listens on the loopback interface instead // of the Pod IP's address for the gRPC endpoints. // // It has no effect if `listenLocal` is true. // +optional - GRPCListenLocal bool `json:"grpcListenLocal,omitempty"` + GRPCListenLocal bool `json:"grpcListenLocal,omitempty"` // nolint:kubeapilinter // httpListenLocal when true, the Thanos sidecar listens on the loopback interface instead // of the Pod IP's address for the HTTP endpoints. // // It has no effect if `listenLocal` is true. // +optional - HTTPListenLocal bool `json:"httpListenLocal,omitempty"` + HTTPListenLocal bool `json:"httpListenLocal,omitempty"` // nolint:kubeapilinter // tracingConfig defines the tracing configuration for the Thanos sidecar. // @@ -1663,7 +1655,7 @@ type RemoteWriteSpec struct { // It requires Prometheus >= v2.27.0 or Thanos >= v0.24.0. // // +optional - SendExemplars *bool `json:"sendExemplars,omitempty"` + SendExemplars *bool `json:"sendExemplars,omitempty"` // nolint:kubeapilinter // sendNativeHistograms enables sending of native histograms, also known as sparse histograms // over remote write. @@ -1671,7 +1663,7 @@ type RemoteWriteSpec struct { // It requires Prometheus >= v2.40.0 or Thanos >= v0.30.0. // // +optional - SendNativeHistograms *bool `json:"sendNativeHistograms,omitempty"` + SendNativeHistograms *bool `json:"sendNativeHistograms,omitempty"` // nolint:kubeapilinter // remoteTimeout defines the timeout for requests to the remote write endpoint. // +optional @@ -1683,6 +1675,7 @@ type RemoteWriteSpec struct { // It requires Prometheus >= v2.25.0 or Thanos >= v0.24.0. // // +optional + //nolint:kubeapilinter Headers map[string]string `json:"headers,omitempty"` // writeRelabelConfigs defines the list of remote write relabel configurations. @@ -1757,7 +1750,7 @@ type RemoteWriteSpec struct { // It requires Prometheus >= v2.26.0 or Thanos >= v0.24.0. // // +optional - FollowRedirects *bool `json:"followRedirects,omitempty"` + FollowRedirects *bool `json:"followRedirects,omitempty"` // nolint:kubeapilinter // queueConfig allows tuning of the remote write queue parameters. // +optional @@ -1773,7 +1766,7 @@ type RemoteWriteSpec struct { // enableHTTP2 defines whether to enable HTTP2. // +optional - EnableHttp2 *bool `json:"enableHTTP2,omitempty"` + EnableHttp2 *bool `json:"enableHTTP2,omitempty"` // nolint:kubeapilinter // roundRobinDNS controls the DNS resolution behavior for remote-write connections. // When enabled: @@ -1791,7 +1784,7 @@ type RemoteWriteSpec struct { // It requires Prometheus >= v3.1.0 or Thanos >= v0.38.0. // // +optional - RoundRobinDNS *bool `json:"roundRobinDNS,omitempty"` + RoundRobinDNS *bool `json:"roundRobinDNS,omitempty"` // nolint:kubeapilinter } // +kubebuilder:validation:Enum=V1.0;V2.0 @@ -1838,7 +1831,7 @@ type QueueConfig struct { // This is an *experimental feature*, it may change in any upcoming release // in a breaking way. // +optional - RetryOnRateLimit bool `json:"retryOnRateLimit,omitempty"` + RetryOnRateLimit bool `json:"retryOnRateLimit,omitempty"` // nolint:kubeapilinter // sampleAgeLimit drops samples older than the limit. // It requires Prometheus >= v2.50.0 or Thanos >= v0.32.0. // @@ -1871,7 +1864,7 @@ type Sigv4 struct { // It requires Prometheus >= v2.54.0. // // +optional - UseFIPSSTSEndpoint *bool `json:"useFIPSSTSEndpoint,omitempty"` + UseFIPSSTSEndpoint *bool `json:"useFIPSSTSEndpoint,omitempty"` // nolint:kubeapilinter } // AzureAD defines the configuration for remote write's azuread parameters. @@ -1882,11 +1875,11 @@ type AzureAD struct { // +optional Cloud *string `json:"cloud,omitempty"` // managedIdentity defines the Azure User-assigned Managed identity. - // Cannot be set at the same time as `oauth` or `sdk`. + // Cannot be set at the same time as `oauth`, `sdk` or `workloadIdentity`. // +optional ManagedIdentity *ManagedIdentity `json:"managedIdentity,omitempty"` // oauth defines the oauth config that is being used to authenticate. - // Cannot be set at the same time as `managedIdentity` or `sdk`. + // Cannot be set at the same time as `managedIdentity`, `sdk` or `workloadIdentity`. // // It requires Prometheus >= v2.48.0 or Thanos >= v0.31.0. // @@ -1894,11 +1887,22 @@ type AzureAD struct { OAuth *AzureOAuth `json:"oauth,omitempty"` // sdk defines the Azure SDK config that is being used to authenticate. // See https://learn.microsoft.com/en-us/azure/developer/go/azure-sdk-authentication - // Cannot be set at the same time as `oauth` or `managedIdentity`. + // Cannot be set at the same time as `oauth`, `managedIdentity` or `workloadIdentity`. // // It requires Prometheus >= v2.52.0 or Thanos >= v0.36.0. // +optional SDK *AzureSDK `json:"sdk,omitempty"` + // workloadIdentity defines the Azure Workload Identity authentication. + // Cannot be set at the same time as `oauth`, `managedIdentity`, or `sdk`. + // + // It requires Prometheus >= 3.7.0. Currently not supported by Thanos. + // +optional + WorkloadIdentity *AzureWorkloadIdentity `json:"workloadIdentity,omitempty"` + // scope is the custom OAuth 2.0 scope to request when acquiring tokens. + // It requires Prometheus >= 3.9.0. Currently not supported by Thanos. + // +kubebuilder:validation:Pattern=`^[\w\s:/.\\-]+$` + // +optional + Scope *string `json:"scope,omitempty"` } // AzureOAuth defines the Azure OAuth settings. @@ -1938,6 +1942,19 @@ type AzureSDK struct { TenantID *string `json:"tenantId,omitempty"` } +// AzureWorkloadIdentity defines the Azure Workload Identity authentication configuration. +type AzureWorkloadIdentity struct { + // clientId is the clientID of the Azure Active Directory application. + // +kubebuilder:validation:MinLength=1 + // +required + ClientID string `json:"clientId"` + + // tenantId is the tenant ID of the Azure Active Directory application. + // +kubebuilder:validation:MinLength=1 + // +required + TenantID string `json:"tenantId"` +} + // RemoteReadSpec defines the configuration for Prometheus to read back samples // from a remote endpoint. // +k8s:openapi-gen=true @@ -1958,6 +1975,7 @@ type RemoteReadSpec struct { // requiredMatchers defines an optional list of equality matchers which have to be present // in a selector to query the remote read endpoint. // +optional + //nolint:kubeapilinter RequiredMatchers map[string]string `json:"requiredMatchers,omitempty"` // remoteTimeout defines the timeout for requests to the remote read endpoint. @@ -1968,12 +1986,13 @@ type RemoteReadSpec struct { // Be aware that headers that are set by Prometheus itself can't be overwritten. // Only valid in Prometheus versions 2.26.0 and newer. // +optional + //nolint:kubeapilinter Headers map[string]string `json:"headers,omitempty"` // readRecent defines whether reads should be made for queries for time ranges that // the local storage should have complete data for. // +optional - ReadRecent bool `json:"readRecent,omitempty"` + ReadRecent bool `json:"readRecent,omitempty"` // nolint:kubeapilinter // oauth2 configuration for the URL. // @@ -2023,14 +2042,14 @@ type RemoteReadSpec struct { // It requires Prometheus >= v2.26.0. // // +optional - FollowRedirects *bool `json:"followRedirects,omitempty"` + FollowRedirects *bool `json:"followRedirects,omitempty"` // nolint:kubeapilinter // filterExternalLabels defines whether to use the external labels as selectors for the remote read endpoint. // // It requires Prometheus >= v2.34.0. // // +optional - FilterExternalLabels *bool `json:"filterExternalLabels,omitempty"` + FilterExternalLabels *bool `json:"filterExternalLabels,omitempty"` // nolint:kubeapilinter } // RelabelConfig allows dynamic rewriting of the label set for targets, alerts, @@ -2240,7 +2259,7 @@ type AlertmanagerEndpoints struct { // enableHttp2 defines whether to enable HTTP2. // // +optional - EnableHttp2 *bool `json:"enableHttp2,omitempty"` + EnableHttp2 *bool `json:"enableHttp2,omitempty"` // nolint:kubeapilinter // relabelings defines the relabel configuration applied to the discovered Alertmanagers. // @@ -2290,7 +2309,7 @@ type MetadataConfig struct { // send defines whether metric metadata is sent to the remote storage or not. // // +optional - Send bool `json:"send,omitempty"` + Send bool `json:"send,omitempty"` // nolint:kubeapilinter // sendInterval defines how frequently metric metadata is sent to the remote storage. // @@ -2429,7 +2448,7 @@ type ScrapeClass struct { // Only one scrape class can be set as the default. // // +optional - Default *bool `json:"default,omitempty"` + Default *bool `json:"default,omitempty"` // nolint:kubeapilinter // fallbackScrapeProtocol defines the protocol to use if a scrape returns blank, unparseable, or otherwise invalid Content-Type. // It will only apply if the scrape resource doesn't specify any FallbackScrapeProtocol @@ -2510,7 +2529,7 @@ type OTLPConfig struct { // Cannot be true when `promoteResourceAttributes` is defined. // It requires Prometheus >= v3.5.0. // +optional - PromoteAllResourceAttributes *bool `json:"promoteAllResourceAttributes,omitempty"` + PromoteAllResourceAttributes *bool `json:"promoteAllResourceAttributes,omitempty"` // nolint:kubeapilinter // ignoreResourceAttributes defines the list of OpenTelemetry resource attributes to ignore when `promoteAllResourceAttributes` is true. // @@ -2542,18 +2561,18 @@ type OTLPConfig struct { // // It requires Prometheus >= v3.1.0. // +optional - KeepIdentifyingResourceAttributes *bool `json:"keepIdentifyingResourceAttributes,omitempty"` + KeepIdentifyingResourceAttributes *bool `json:"keepIdentifyingResourceAttributes,omitempty"` // nolint:kubeapilinter // convertHistogramsToNHCB defines optional translation of OTLP explicit bucket histograms into native histograms with custom buckets. // It requires Prometheus >= v3.4.0. // +optional - ConvertHistogramsToNHCB *bool `json:"convertHistogramsToNHCB,omitempty"` + ConvertHistogramsToNHCB *bool `json:"convertHistogramsToNHCB,omitempty"` // nolint:kubeapilinter // promoteScopeMetadata controls whether to promote OpenTelemetry scope metadata (i.e. name, version, schema URL, and attributes) to metric labels. // As per the OpenTelemetry specification, the aforementioned scope metadata should be identifying, i.e. made into metric labels. // It requires Prometheus >= v3.6.0. // +optional - PromoteScopeMetadata *bool `json:"promoteScopeMetadata,omitempty"` + PromoteScopeMetadata *bool `json:"promoteScopeMetadata,omitempty"` // nolint:kubeapilinter } // Validate semantically validates the given OTLPConfig section. diff --git a/pkg/apis/monitoring/v1/prometheusrule_types.go b/pkg/apis/monitoring/v1/prometheusrule_types.go index 576f8d38925..439b57c53f6 100644 --- a/pkg/apis/monitoring/v1/prometheusrule_types.go +++ b/pkg/apis/monitoring/v1/prometheusrule_types.go @@ -88,6 +88,7 @@ type RuleGroup struct { // It requires Prometheus >= 3.0.0. // The field is ignored for Thanos Ruler. // +optional + //nolint:kubeapilinter Labels map[string]string `json:"labels,omitempty"` // interval defines how often rules in the group are evaluated. // +optional @@ -141,10 +142,12 @@ type Rule struct { KeepFiringFor *NonEmptyDuration `json:"keep_firing_for,omitempty"` // labels defines labels to add or overwrite. // +optional + //nolint:kubeapilinter Labels map[string]string `json:"labels,omitempty"` // annotations defines annotations to add to each alert. // Only valid for alerting rules. // +optional + //nolint:kubeapilinter Annotations map[string]string `json:"annotations,omitempty"` } diff --git a/pkg/apis/monitoring/v1/thanos_types.go b/pkg/apis/monitoring/v1/thanos_types.go index 434664c23bb..49dd72f0bd5 100644 --- a/pkg/apis/monitoring/v1/thanos_types.go +++ b/pkg/apis/monitoring/v1/thanos_types.go @@ -111,7 +111,7 @@ type ThanosRulerSpec struct { // paused defines when a ThanosRuler deployment is paused, no actions except for deletion // will be performed on the underlying objects. // +optional - Paused bool `json:"paused,omitempty"` + Paused bool `json:"paused,omitempty"` // nolint:kubeapilinter // replicas defines the number of thanos ruler instances to deploy. // +optional @@ -119,6 +119,7 @@ type ThanosRulerSpec struct { // nodeSelector defines which Nodes the Pods are scheduled on. // +optional + //nolint:kubeapilinter NodeSelector map[string]string `json:"nodeSelector,omitempty"` // resources defines the resource requirements for single Pods. @@ -154,7 +155,7 @@ type ThanosRulerSpec struct { // enableServiceLinks defines whether information about services should be injected into pod's environment variables // +optional - EnableServiceLinks *bool `json:"enableServiceLinks,omitempty"` + EnableServiceLinks *bool `json:"enableServiceLinks,omitempty"` // nolint:kubeapilinter // priorityClassName defines the priority class assigned to the Pods // +optional @@ -210,7 +211,29 @@ type ThanosRulerSpec struct { // listenLocal defines the Thanos ruler listen on loopback, so that it // does not bind against the Pod IP. // +optional - ListenLocal bool `json:"listenLocal,omitempty"` + ListenLocal bool `json:"listenLocal,omitempty"` // nolint:kubeapilinter + + // podManagementPolicy defines the policy for creating/deleting pods when + // scaling up and down. + // + // Unlike the default StatefulSet behavior, the default policy is + // `Parallel` to avoid manual intervention in case a pod gets stuck during + // a rollout. + // + // Note that updating this value implies the recreation of the StatefulSet + // which incurs a service outage. + // + // +optional + PodManagementPolicy *PodManagementPolicyType `json:"podManagementPolicy,omitempty"` + + // updateStrategy indicates the strategy that will be employed to update + // Pods in the StatefulSet when a revision is made to statefulset's Pod + // Template. + // + // The default strategy is RollingUpdate. + // + // +optional + UpdateStrategy *StatefulSetUpdateStrategy `json:"updateStrategy,omitempty"` // queryEndpoints defines the list of Thanos Query endpoints from which to query metrics. // @@ -395,6 +418,7 @@ type ThanosRulerSpec struct { // label with the value of the pod's name. // // +optional + //nolint:kubeapilinter Labels map[string]string `json:"labels,omitempty"` // alertDropLabels defines the label names which should be dropped in Thanos Ruler @@ -523,7 +547,7 @@ type ThanosRulerSpec struct { // Starting Kubernetes 1.33, the feature is enabled by default. // // +optional - HostUsers *bool `json:"hostUsers,omitempty"` + HostUsers *bool `json:"hostUsers,omitempty"` // nolint:kubeapilinter } // ThanosRulerWebSpec defines the configuration of the ThanosRuler web server. @@ -541,7 +565,7 @@ type ThanosRulerStatus struct { // paused defines whether any actions on the underlying managed objects are // being performed. Only delete actions will be performed. // +optional - Paused bool `json:"paused"` + Paused bool `json:"paused"` // nolint:kubeapilinter // replicas defines the total number of non-terminated pods targeted by this ThanosRuler deployment // (their labels match the selector). // +optional diff --git a/pkg/apis/monitoring/v1/tls_types.go b/pkg/apis/monitoring/v1/tls_types.go new file mode 100644 index 00000000000..51e6835279f --- /dev/null +++ b/pkg/apis/monitoring/v1/tls_types.go @@ -0,0 +1,173 @@ +// Copyright 2025 The prometheus-operator Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package v1 + +import ( + "fmt" + "reflect" + "strings" + + v1 "k8s.io/api/core/v1" +) + +// +kubebuilder:validation:Enum=TLS10;TLS11;TLS12;TLS13 +type TLSVersion string + +const ( + TLSVersion10 TLSVersion = "TLS10" + TLSVersion11 TLSVersion = "TLS11" + TLSVersion12 TLSVersion = "TLS12" + TLSVersion13 TLSVersion = "TLS13" +) + +// TLSConfig defines full TLS configuration. +type TLSConfig struct { + SafeTLSConfig `json:",inline"` + TLSFilesConfig `json:",inline"` +} + +// Validate semantically validates the given TLSConfig. +func (c *TLSConfig) Validate() error { + if c == nil { + return nil + } + + if !reflect.ValueOf(c.CA).IsZero() { + if c.CAFile != "" { + return fmt.Errorf("cannot specify both 'caFile' and 'ca'") + } + + if err := c.CA.Validate(); err != nil { + return fmt.Errorf("ca: %w", err) + } + } + + hasCert := !reflect.ValueOf(c.Cert).IsZero() + if hasCert { + if c.CertFile != "" { + return fmt.Errorf("cannot specify both 'certFile' and 'cert'") + } + + if err := c.Cert.Validate(); err != nil { + return fmt.Errorf("cert: %w", err) + } + } + + if c.KeyFile != "" && c.KeySecret != nil { + return fmt.Errorf("cannot specify both 'keyFile' and 'keySecret'") + } + + hasCert = hasCert || c.CertFile != "" + hasKey := c.KeyFile != "" || c.KeySecret != nil + + if hasCert && !hasKey { + return fmt.Errorf("cannot specify client cert without client key") + } + + if hasKey && !hasCert { + return fmt.Errorf("cannot specify client key without client cert") + } + + if c.MaxVersion != nil && c.MinVersion != nil && strings.Compare(string(*c.MaxVersion), string(*c.MinVersion)) == -1 { + return fmt.Errorf("'maxVersion' must greater than or equal to 'minVersion'") + } + + return nil +} + +// SafeTLSConfig defines safe TLS configurations. +// +k8s:openapi-gen=true +type SafeTLSConfig struct { + // ca defines the Certificate authority used when verifying server certificates. + // +optional + CA SecretOrConfigMap `json:"ca,omitempty"` + + // cert defines the Client certificate to present when doing client-authentication. + // +optional + Cert SecretOrConfigMap `json:"cert,omitempty"` + + // keySecret defines the Secret containing the client key file for the targets. + // +optional + KeySecret *v1.SecretKeySelector `json:"keySecret,omitempty"` + + // serverName is used to verify the hostname for the targets. + // +optional + ServerName *string `json:"serverName,omitempty"` + + // insecureSkipVerify defines how to disable target certificate validation. + // +optional + InsecureSkipVerify *bool `json:"insecureSkipVerify,omitempty"` // nolint:kubeapilinter + + // minVersion defines the minimum acceptable TLS version. + // + // It requires Prometheus >= v2.35.0 or Thanos >= v0.28.0. + // +optional + MinVersion *TLSVersion `json:"minVersion,omitempty"` + + // maxVersion defines the maximum acceptable TLS version. + // + // It requires Prometheus >= v2.41.0 or Thanos >= v0.31.0. + // +optional + MaxVersion *TLSVersion `json:"maxVersion,omitempty"` +} + +// Validate semantically validates the given SafeTLSConfig. +func (c *SafeTLSConfig) Validate() error { + if c == nil { + return nil + } + + if c.CA != (SecretOrConfigMap{}) { + if err := c.CA.Validate(); err != nil { + return fmt.Errorf("ca %s: %w", c.CA.String(), err) + } + } + + if c.Cert != (SecretOrConfigMap{}) { + if err := c.Cert.Validate(); err != nil { + return fmt.Errorf("cert %s: %w", c.Cert.String(), err) + } + } + + if c.Cert != (SecretOrConfigMap{}) && c.KeySecret == nil { + return fmt.Errorf("client cert specified without client key") + } + + if c.KeySecret != nil && c.Cert == (SecretOrConfigMap{}) { + return fmt.Errorf("client key specified without client cert") + } + + if c.MaxVersion != nil && c.MinVersion != nil && strings.Compare(string(*c.MaxVersion), string(*c.MinVersion)) == -1 { + return fmt.Errorf("maxVersion must more than or equal to minVersion") + } + + return nil +} + +// TLSFilesConfig extends the TLS configuration with file parameters. +// +k8s:openapi-gen=true +type TLSFilesConfig struct { + // caFile defines the path to the CA cert in the Prometheus container to use for the targets. + // +optional + CAFile string `json:"caFile,omitempty"` + // certFile defines the path to the client cert file in the Prometheus container for the targets. + // +optional + CertFile string `json:"certFile,omitempty"` + // keyFile defines the path to the client key file in the Prometheus container for the targets. + // +optional + KeyFile string `json:"keyFile,omitempty"` +} + +// diff --git a/pkg/apis/monitoring/v1/types.go b/pkg/apis/monitoring/v1/types.go index bddbed14bb6..2f1cd1f1e6e 100644 --- a/pkg/apis/monitoring/v1/types.go +++ b/pkg/apis/monitoring/v1/types.go @@ -109,14 +109,14 @@ type ProxyConfig struct { // // It requires Prometheus >= v2.43.0, Alertmanager >= v0.25.0 or Thanos >= v0.32.0. // +optional - ProxyFromEnvironment *bool `json:"proxyFromEnvironment,omitempty"` + ProxyFromEnvironment *bool `json:"proxyFromEnvironment,omitempty"` // nolint:kubeapilinter // proxyConnectHeader optionally specifies headers to send to // proxies during CONNECT requests. // // It requires Prometheus >= v2.43.0, Alertmanager >= v0.25.0 or Thanos >= v0.32.0. // +optional // +mapType:=atomic - ProxyConnectHeader map[string][]v1.SecretKeySelector `json:"proxyConnectHeader,omitempty"` + ProxyConnectHeader map[string][]v1.SecretKeySelector `json:"proxyConnectHeader,omitempty"` //nolint:kubeapilinter } // Validate semantically validates the given ProxyConfig. @@ -227,7 +227,7 @@ type ArbitraryFSAccessThroughSMsConfig struct { // Setting this to true enhances security by preventing potential credential theft attacks. // // +optional - Deny bool `json:"deny,omitempty"` + Deny bool `json:"deny,omitempty"` // nolint:kubeapilinter } // Condition represents the state of the resources associated with the @@ -330,6 +330,7 @@ type EmbeddedObjectMetadata struct { // and services. // More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/labels/ // +optional + //nolint:kubeapilinter Labels map[string]string `json:"labels,omitempty" protobuf:"bytes,11,rep,name=labels"` // annotations defines an unstructured key value map stored with a resource that may be @@ -337,6 +338,7 @@ type EmbeddedObjectMetadata struct { // queryable and should be preserved when modifying objects. // More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/annotations/ // +optional + //nolint:kubeapilinter Annotations map[string]string `json:"annotations,omitempty" protobuf:"bytes,12,rep,name=annotations"` } @@ -358,7 +360,7 @@ type WebHTTPConfig struct { // When TLSConfig is not configured, HTTP/2 will be disabled. // Whenever the value of the field changes, a rolling update will be triggered. // +optional - HTTP2 *bool `json:"http2,omitempty"` + HTTP2 *bool `json:"http2,omitempty"` // nolint:kubeapilinter // headers defines a list of headers that can be added to HTTP responses. // +optional Headers *WebHTTPHeaders `json:"headers,omitempty"` @@ -483,7 +485,7 @@ type WebTLSConfig struct { // the order of elements in cipherSuites, is used. // // +optional - PreferServerCipherSuites *bool `json:"preferServerCipherSuites,omitempty"` + PreferServerCipherSuites *bool `json:"preferServerCipherSuites,omitempty"` // nolint:kubeapilinter // curvePreferences defines elliptic curves that will be used in an ECDHE handshake, in preference // order. @@ -572,6 +574,7 @@ type Endpoint struct { // params define optional HTTP URL parameters. // +optional + //nolint:kubeapilinter Params map[string][]string `json:"params,omitempty"` // interval at which Prometheus scrapes the metrics from the target. @@ -588,44 +591,16 @@ type Endpoint struct { // +optional ScrapeTimeout Duration `json:"scrapeTimeout,omitempty"` - // tlsConfig defines the TLS configuration to use when scraping the target. - // - // +optional - TLSConfig *TLSConfig `json:"tlsConfig,omitempty"` - - // bearerTokenFile defines the file to read bearer token for scraping the target. - // - // Deprecated: use `authorization` instead. - // +optional - BearerTokenFile string `json:"bearerTokenFile,omitempty"` - - // bearerTokenSecret defines a key of a Secret containing the bearer - // token for scraping targets. The secret needs to be in the same namespace - // as the ServiceMonitor object and readable by the Prometheus Operator. - // - // +optional - // - // Deprecated: use `authorization` instead. - BearerTokenSecret *v1.SecretKeySelector `json:"bearerTokenSecret,omitempty"` - - // authorization configures the Authorization header credentials to use when - // scraping the target. - // - // Cannot be set at the same time as `basicAuth`, or `oauth2`. - // - // +optional - Authorization *SafeAuthorization `json:"authorization,omitempty"` - // honorLabels defines when true the metric's labels when they collide // with the target's labels. // +optional - HonorLabels bool `json:"honorLabels,omitempty"` + HonorLabels bool `json:"honorLabels,omitempty"` // nolint:kubeapilinter // honorTimestamps defines whether Prometheus preserves the timestamps // when exposed by the target. // // +optional - HonorTimestamps *bool `json:"honorTimestamps,omitempty"` + HonorTimestamps *bool `json:"honorTimestamps,omitempty"` // nolint:kubeapilinter // trackTimestampsStaleness defines whether Prometheus tracks staleness of // the metrics that have an explicit timestamp present in scraped data. @@ -634,24 +609,7 @@ type Endpoint struct { // It requires Prometheus >= v2.48.0. // // +optional - TrackTimestampsStaleness *bool `json:"trackTimestampsStaleness,omitempty"` - - // basicAuth defines the Basic Authentication credentials to use when - // scraping the target. - // - // Cannot be set at the same time as `authorization`, or `oauth2`. - // - // +optional - BasicAuth *BasicAuth `json:"basicAuth,omitempty"` - - // oauth2 defines the OAuth2 settings to use when scraping the target. - // - // It requires Prometheus >= 2.27.0. - // - // Cannot be set at the same time as `authorization`, or `basicAuth`. - // - // +optional - OAuth2 *OAuth2 `json:"oauth2,omitempty"` + TrackTimestampsStaleness *bool `json:"trackTimestampsStaleness,omitempty"` // nolint:kubeapilinter // metricRelabelings defines the relabeling rules to apply to the // samples before ingestion. @@ -671,20 +629,6 @@ type Endpoint struct { // +optional RelabelConfigs []RelabelConfig `json:"relabelings,omitempty"` - // +optional - ProxyConfig `json:",inline"` - - // followRedirects defines whether the scrape requests should follow HTTP - // 3xx redirects. - // - // +optional - FollowRedirects *bool `json:"followRedirects,omitempty"` - - // enableHttp2 can be used to disable HTTP2 when scraping the target. - // - // +optional - EnableHttp2 *bool `json:"enableHttp2,omitempty"` - // filterRunning when true, the pods which are not running (e.g. either in Failed or // Succeeded state) are dropped during the target discovery. // @@ -693,7 +637,15 @@ type Endpoint struct { // More info: https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle/#pod-phase // // +optional - FilterRunning *bool `json:"filterRunning,omitempty"` + FilterRunning *bool `json:"filterRunning,omitempty"` // nolint:kubeapilinter + + // bearerTokenFile defines the file to read bearer token for scraping the target. + // + // Deprecated: use `authorization` instead. + // +optional + BearerTokenFile string `json:"bearerTokenFile,omitempty"` + + HTTPConfigWithProxyAndTLSFiles `json:",inline"` } type AttachMetadata struct { @@ -704,7 +656,7 @@ type AttachMetadata struct { // permissions on the `Nodes` objects. // // +optional - Node *bool `json:"node,omitempty"` + Node *bool `json:"node,omitempty"` // nolint:kubeapilinter } // OAuth2 configures OAuth2 settings. @@ -736,6 +688,7 @@ type OAuth2 struct { // URL. // // +optional + //nolint:kubeapilinter EndpointParams map[string]string `json:"endpointParams,omitempty"` // tlsConfig defines the TLS configuration to use when connecting to the OAuth2 server. @@ -828,147 +781,6 @@ func (c *SecretOrConfigMap) String() string { return "" } -// +kubebuilder:validation:Enum=TLS10;TLS11;TLS12;TLS13 -type TLSVersion string - -const ( - TLSVersion10 TLSVersion = "TLS10" - TLSVersion11 TLSVersion = "TLS11" - TLSVersion12 TLSVersion = "TLS12" - TLSVersion13 TLSVersion = "TLS13" -) - -// SafeTLSConfig specifies safe TLS configuration parameters. -// +k8s:openapi-gen=true -type SafeTLSConfig struct { - // ca defines the Certificate authority used when verifying server certificates. - // +optional - CA SecretOrConfigMap `json:"ca,omitempty"` - - // cert defines the Client certificate to present when doing client-authentication. - // +optional - Cert SecretOrConfigMap `json:"cert,omitempty"` - - // keySecret defines the Secret containing the client key file for the targets. - // +optional - KeySecret *v1.SecretKeySelector `json:"keySecret,omitempty"` - - // serverName is used to verify the hostname for the targets. - // +optional - ServerName *string `json:"serverName,omitempty"` - - // insecureSkipVerify defines how to disable target certificate validation. - // +optional - InsecureSkipVerify *bool `json:"insecureSkipVerify,omitempty"` - - // minVersion defines the minimum acceptable TLS version. - // - // It requires Prometheus >= v2.35.0 or Thanos >= v0.28.0. - // +optional - MinVersion *TLSVersion `json:"minVersion,omitempty"` - - // maxVersion defines the maximum acceptable TLS version. - // - // It requires Prometheus >= v2.41.0 or Thanos >= v0.31.0. - // +optional - MaxVersion *TLSVersion `json:"maxVersion,omitempty"` -} - -// Validate semantically validates the given SafeTLSConfig. -func (c *SafeTLSConfig) Validate() error { - if c == nil { - return nil - } - - if c.CA != (SecretOrConfigMap{}) { - if err := c.CA.Validate(); err != nil { - return fmt.Errorf("ca %s: %w", c.CA.String(), err) - } - } - - if c.Cert != (SecretOrConfigMap{}) { - if err := c.Cert.Validate(); err != nil { - return fmt.Errorf("cert %s: %w", c.Cert.String(), err) - } - } - - if c.Cert != (SecretOrConfigMap{}) && c.KeySecret == nil { - return fmt.Errorf("client cert specified without client key") - } - - if c.KeySecret != nil && c.Cert == (SecretOrConfigMap{}) { - return fmt.Errorf("client key specified without client cert") - } - - if c.MaxVersion != nil && c.MinVersion != nil && strings.Compare(string(*c.MaxVersion), string(*c.MinVersion)) == -1 { - return fmt.Errorf("maxVersion must more than or equal to minVersion") - } - - return nil -} - -// TLSConfig extends the safe TLS configuration with file parameters. -// +k8s:openapi-gen=true -type TLSConfig struct { - // +optional - SafeTLSConfig `json:",inline"` - // caFile defines the path to the CA cert in the Prometheus container to use for the targets. - // +optional - CAFile string `json:"caFile,omitempty"` - // certFile defines the path to the client cert file in the Prometheus container for the targets. - // +optional - CertFile string `json:"certFile,omitempty"` - // keyFile defines the path to the client key file in the Prometheus container for the targets. - // +optional - KeyFile string `json:"keyFile,omitempty"` -} - -// Validate semantically validates the given TLSConfig. -func (c *TLSConfig) Validate() error { - if c == nil { - return nil - } - - if c.CA != (SecretOrConfigMap{}) { - if c.CAFile != "" { - return fmt.Errorf("cannot specify both caFile and ca") - } - if err := c.CA.Validate(); err != nil { - return fmt.Errorf("SecretOrConfigMap ca: %w", err) - } - } - - if c.Cert != (SecretOrConfigMap{}) { - if c.CertFile != "" { - return fmt.Errorf("cannot specify both certFile and cert") - } - if err := c.Cert.Validate(); err != nil { - return fmt.Errorf("SecretOrConfigMap cert: %w", err) - } - } - - if c.KeyFile != "" && c.KeySecret != nil { - return fmt.Errorf("cannot specify both keyFile and keySecret") - } - - hasCert := c.CertFile != "" || c.Cert != (SecretOrConfigMap{}) - hasKey := c.KeyFile != "" || c.KeySecret != nil - - if hasCert && !hasKey { - return fmt.Errorf("cannot specify client cert without client key") - } - - if hasKey && !hasCert { - return fmt.Errorf("cannot specify client key without client cert") - } - - if c.MaxVersion != nil && c.MinVersion != nil && strings.Compare(string(*c.MaxVersion), string(*c.MinVersion)) == -1 { - return fmt.Errorf("maxVersion must more than or equal to minVersion") - } - - return nil -} - // NamespaceSelector is a selector for selecting either all namespaces or a // list of namespaces. // If `any` is true, it takes precedence over `matchNames`. @@ -979,7 +791,7 @@ type NamespaceSelector struct { // any defines the boolean describing whether all namespaces are selected in contrast to a // list restricting them. // +optional - Any bool `json:"any,omitempty"` + Any bool `json:"any,omitempty"` // nolint:kubeapilinter // matchNames defines the list of namespace names to select from. // +optional MatchNames []string `json:"matchNames,omitempty"` @@ -1014,13 +826,19 @@ const ( // NativeHistogramConfig extends the native histogram configuration settings. // +k8s:openapi-gen=true type NativeHistogramConfig struct { + // scrapeNativeHistograms defines whether to enable scraping of native histograms. + // It requires Prometheus >= v3.8.0. + // + // +optional + ScrapeNativeHistograms *bool `json:"scrapeNativeHistograms,omitempty"` // nolint:kubeapilinter + // scrapeClassicHistograms defines whether to scrape a classic histogram that is also exposed as a native histogram. // It requires Prometheus >= v2.45.0. // // Notice: `scrapeClassicHistograms` corresponds to the `always_scrape_classic_histograms` field in the Prometheus configuration. // // +optional - ScrapeClassicHistograms *bool `json:"scrapeClassicHistograms,omitempty"` + ScrapeClassicHistograms *bool `json:"scrapeClassicHistograms,omitempty"` // nolint:kubeapilinter // nativeHistogramBucketLimit defines ff there are more than this many buckets in a native histogram, // buckets will be merged to stay within the limit. @@ -1040,7 +858,7 @@ type NativeHistogramConfig struct { // It requires Prometheus >= v3.0.0. // // +optional - ConvertClassicHistogramsToNHCB *bool `json:"convertClassicHistogramsToNHCB,omitempty"` + ConvertClassicHistogramsToNHCB *bool `json:"convertClassicHistogramsToNHCB,omitempty"` // nolint:kubeapilinter } // +kubebuilder:validation:Enum=RelabelConfig;RoleSelector @@ -1140,3 +958,135 @@ const ( SchemeHTTP Scheme = "HTTP" SchemeHTTPS Scheme = "HTTPS" ) + +// +kubebuilder:validation:Enum=OrderedReady;Parallel +type PodManagementPolicyType string + +const ( + // OrderedReadyPodManagement will create pods in strictly increasing order on + // scale up and strictly decreasing order on scale down, progressing only when + // the previous pod is ready or terminated. At most one pod will be changed + // at any time. + OrderedReadyPodManagement PodManagementPolicyType = "OrderedReady" + // ParallelPodManagement will create and delete pods as soon as the stateful set + // replica count is changed, and will not wait for pods to be ready or complete + // termination. + ParallelPodManagement PodManagementPolicyType = "Parallel" +) + +// StatefulSetUpdateStrategy indicates the strategy used when updating the +// StatefulSet. It includes any additional parameters necessary to perform the +// update for the indicated strategy. +// +// +kubebuilder:validation:XValidation:rule="!(self.type != 'RollingUpdate' && has(self.rollingUpdate))",message="rollingUpdate requires type to be RollingUpdate" +type StatefulSetUpdateStrategy struct { + // type indicates the type of the StatefulSetUpdateStrategy. + // + // Default is RollingUpdate. + // + // +required + Type StatefulSetUpdateStrategyType `json:"type"` + + // rollingUpdate is used to communicate parameters when type is RollingUpdate. + // + // +optional + RollingUpdate *RollingUpdateStatefulSetStrategy `json:"rollingUpdate,omitempty"` +} + +// RollingUpdateStatefulSetStrategy is used to communicate parameter for the RollingUpdate strategy. +type RollingUpdateStatefulSetStrategy struct { + // maxUnavailable is the maximum number of pods that can be unavailable + // during the update. The value can be an absolute number (ex: 5) or a + // percentage of desired pods (ex: 10%). Absolute number is calculated from + // percentage by rounding up. This can not be 0. Defaults to 1. This field + // is alpha-level and is only honored by servers that enable the + // MaxUnavailableStatefulSet feature. The field applies to all pods in the + // range 0 to Replicas-1. That means if there is any unavailable pod in + // the range 0 to Replicas-1, it will be counted towards MaxUnavailable. + // + // +kubebuilder:validation:XIntOrString + // +optional + MaxUnavailable *intstr.IntOrString `json:"maxUnavailable,omitempty" protobuf:"varint,2,opt,name=maxUnavailable"` +} + +// StatefulSetUpdateStrategyType is a string enumeration type that enumerates +// all possible update strategies for the StatefulSet pods. +// +// +kubebuilder:validation:Enum=OnDelete;RollingUpdate +type StatefulSetUpdateStrategyType string + +const ( + // RollingUpdateStatefulSetStrategyType indicates that update will be + // applied to all Pods in the StatefulSet with respect to the StatefulSet + // ordering constraints. When a scale operation is performed with this + // strategy, new Pods will be created from the specification version indicated + // by the StatefulSet's updateRevision. + RollingUpdateStatefulSetStrategyType StatefulSetUpdateStrategyType = "RollingUpdate" + + // OnDeleteStatefulSetStrategyType triggers the legacy behavior. Version + // tracking and ordered rolling restarts are disabled. Pods are recreated + // from the StatefulSetSpec when they are manually deleted. When a scale + // operation is performed with this strategy, new Pods will be created from + // the the specification version indicated by the StatefulSet's + // currentRevision. + OnDeleteStatefulSetStrategyType StatefulSetUpdateStrategyType = "OnDelete" +) + +type TracingConfig struct { + // clientType defines the client used to export the traces. Supported values are `HTTP` and `GRPC`. + // +kubebuilder:validation:Enum=http;grpc;HTTP;GRPC + // +optional + ClientType *string `json:"clientType",omitempty` + + // endpoint to send the traces to. Should be provided in format :. + // +kubebuilder:validation:MinLength:=1 + // +required + Endpoint string `json:"endpoint"` + + // samplingFraction defines the probability a given trace will be sampled. Must be a float from 0 through 1. + // +optional + SamplingFraction *resource.Quantity `json:"samplingFraction",omitempty` + + // insecure if disabled, the client will use a secure connection. + // +optional + Insecure *bool `json:"insecure",omitempty` // nolint:kubeapilinter + + // headers defines the key-value pairs to be used as headers associated with gRPC or HTTP requests. + // +optional + Headers map[string]string `json:"headers"` + + // compression key for supported compression types. The only supported value is `Gzip`. + // +kubebuilder:validation:Enum=gzip;Gzip + // +optional + Compression *string `json:"compression",omitempty` + + // timeout defines the maximum time the exporter will wait for each batch export. + // +optional + Timeout *Duration `json:"timeout",omitempty` + + // tlsConfig to use when sending traces. + // +optional + TLSConfig *TLSConfig `json:"tlsConfig",omitempty` +} + +// Validate semantically validates the given TracingConfig. +func (tc *TracingConfig) Validate() error { + if tc == nil { + return nil + } + + if err := tc.TLSConfig.Validate(); err != nil { + return err + } + + if tc.SamplingFraction != nil { + min, _ := resource.ParseQuantity("0") + max, _ := resource.ParseQuantity("1") + + if tc.SamplingFraction.Cmp(min) < 0 || tc.SamplingFraction.Cmp(max) > 0 { + return fmt.Errorf("`samplingFraction` must be between 0 and 1") + } + } + + return nil +} diff --git a/pkg/apis/monitoring/v1/types_test.go b/pkg/apis/monitoring/v1/types_test.go index c3ac43cbf0f..9264eba2990 100644 --- a/pkg/apis/monitoring/v1/types_test.go +++ b/pkg/apis/monitoring/v1/types_test.go @@ -19,6 +19,7 @@ import ( "testing" v1 "k8s.io/api/core/v1" + "k8s.io/apimachinery/pkg/api/resource" ) func TestValidateSecretOrConfigMap(t *testing.T) { @@ -138,41 +139,51 @@ func TestValidateTLSConfig(t *testing.T) { { name: "caFile, certFile and keyFile", config: &TLSConfig{ - CAFile: "cafile", - CertFile: "certfile", - KeyFile: "keyfile", + TLSFilesConfig: TLSFilesConfig{ + CAFile: "cafile", + CertFile: "certfile", + KeyFile: "keyfile", + }, }, err: false, }, { name: "certFile and keyFile", config: &TLSConfig{ - CertFile: "certfile", - KeyFile: "keyfile", + TLSFilesConfig: TLSFilesConfig{ + CertFile: "certfile", + KeyFile: "keyfile", + }, }, err: false, }, { name: "caFile and keyFile", config: &TLSConfig{ - CAFile: "cafile", - KeyFile: "keyfile", + TLSFilesConfig: TLSFilesConfig{ + CAFile: "cafile", + KeyFile: "keyfile", + }, }, err: true, }, { name: "caFile and certFile", config: &TLSConfig{ - CAFile: "cafile", - CertFile: "certfile", + TLSFilesConfig: TLSFilesConfig{ + CAFile: "cafile", + CertFile: "certfile", + }, }, err: true, }, { name: "caFile, cert and keyFile", config: &TLSConfig{ - CAFile: "cafile", - KeyFile: "keyfile", + TLSFilesConfig: TLSFilesConfig{ + CAFile: "cafile", + KeyFile: "keyfile", + }, SafeTLSConfig: SafeTLSConfig{ Cert: SecretOrConfigMap{Secret: &v1.SecretKeySelector{}}, }, @@ -182,8 +193,10 @@ func TestValidateTLSConfig(t *testing.T) { { name: "caFile, certFile and keySecret", config: &TLSConfig{ - CAFile: "cafile", - CertFile: "certfile", + TLSFilesConfig: TLSFilesConfig{ + CAFile: "cafile", + CertFile: "certfile", + }, SafeTLSConfig: SafeTLSConfig{ KeySecret: &v1.SecretKeySelector{}, }, @@ -517,3 +530,68 @@ func TestDurationPointer(t *testing.T) { t.Fatalf("wanted %v, but got %v", &oneMinuteDuration, got) } } + +func TestValidateTracingConfig(t *testing.T) { + for _, tc := range []struct { + name string + config *TracingConfig + err bool + }{ + { + name: "TLSConfig nil", + config: &TracingConfig{ + TLSConfig: nil, + }, + err: false, + }, + { + name: "SamplingFraction simple value", + config: &TracingConfig{ + SamplingFraction: func(v resource.Quantity) *resource.Quantity { return &v }(resource.MustParse("0.56")), + }, + err: false, + }, + { + name: "SamplingFraction > 1", + config: &TracingConfig{ + SamplingFraction: resource.NewQuantity(10, resource.DecimalSI), + }, + err: true, + }, + { + name: "SamplingFraction < 0", + config: &TracingConfig{ + SamplingFraction: resource.NewQuantity(-1, resource.DecimalSI), + }, + err: true, + }, + { + name: "SamplingFraction == 0", + config: &TracingConfig{ + SamplingFraction: resource.NewQuantity(0, resource.DecimalSI), + }, + err: false, + }, + { + name: "SamplingFraction == 1", + config: &TracingConfig{ + SamplingFraction: resource.NewQuantity(1, resource.DecimalSI), + }, + err: false, + }, + } { + t.Run(tc.name, func(t *testing.T) { + err := tc.config.Validate() + if tc.err { + if err == nil { + t.Fatal("expected error but got none") + } + return + } + + if err != nil { + t.Fatalf("expected no error but got: %s", err) + } + }) + } +} diff --git a/pkg/apis/monitoring/v1/zz_generated.deepcopy.go b/pkg/apis/monitoring/v1/zz_generated.deepcopy.go index 03b17df8bcb..73314958dc9 100644 --- a/pkg/apis/monitoring/v1/zz_generated.deepcopy.go +++ b/pkg/apis/monitoring/v1/zz_generated.deepcopy.go @@ -228,9 +228,9 @@ func (in *AlertmanagerGlobalConfig) DeepCopyInto(out *AlertmanagerGlobalConfig) *out = new(GlobalSMTPConfig) (*in).DeepCopyInto(*out) } - if in.HTTPConfig != nil { - in, out := &in.HTTPConfig, &out.HTTPConfig - *out = new(HTTPConfig) + if in.HTTPConfigWithProxy != nil { + in, out := &in.HTTPConfigWithProxy, &out.HTTPConfigWithProxy + *out = new(HTTPConfigWithProxy) (*in).DeepCopyInto(*out) } if in.SlackAPIURL != nil { @@ -453,6 +453,16 @@ func (in *AlertmanagerSpec) DeepCopyInto(out *AlertmanagerSpec) { *out = new(string) **out = **in } + if in.PodManagementPolicy != nil { + in, out := &in.PodManagementPolicy, &out.PodManagementPolicy + *out = new(PodManagementPolicyType) + **out = **in + } + if in.UpdateStrategy != nil { + in, out := &in.UpdateStrategy, &out.UpdateStrategy + *out = new(StatefulSetUpdateStrategy) + (*in).DeepCopyInto(*out) + } if in.Containers != nil { in, out := &in.Containers, &out.Containers *out = make([]corev1.Container, len(*in)) @@ -694,6 +704,16 @@ func (in *AzureAD) DeepCopyInto(out *AzureAD) { *out = new(AzureSDK) (*in).DeepCopyInto(*out) } + if in.WorkloadIdentity != nil { + in, out := &in.WorkloadIdentity, &out.WorkloadIdentity + *out = new(AzureWorkloadIdentity) + **out = **in + } + if in.Scope != nil { + in, out := &in.Scope, &out.Scope + *out = new(string) + **out = **in + } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new AzureAD. @@ -742,6 +762,21 @@ func (in *AzureSDK) DeepCopy() *AzureSDK { return out } +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *AzureWorkloadIdentity) DeepCopyInto(out *AzureWorkloadIdentity) { + *out = *in +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new AzureWorkloadIdentity. +func (in *AzureWorkloadIdentity) DeepCopy() *AzureWorkloadIdentity { + if in == nil { + return nil + } + out := new(AzureWorkloadIdentity) + in.DeepCopyInto(out) + return out +} + // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *BasicAuth) DeepCopyInto(out *BasicAuth) { *out = *in @@ -979,6 +1014,16 @@ func (in *CommonPrometheusFields) DeepCopyInto(out *CommonPrometheusFields) { *out = new(PodDNSConfig) (*in).DeepCopyInto(*out) } + if in.PodManagementPolicy != nil { + in, out := &in.PodManagementPolicy, &out.PodManagementPolicy + *out = new(PodManagementPolicyType) + **out = **in + } + if in.UpdateStrategy != nil { + in, out := &in.UpdateStrategy, &out.UpdateStrategy + *out = new(StatefulSetUpdateStrategy) + (*in).DeepCopyInto(*out) + } if in.EnableServiceLinks != nil { in, out := &in.EnableServiceLinks, &out.EnableServiceLinks *out = new(bool) @@ -1054,6 +1099,11 @@ func (in *CommonPrometheusFields) DeepCopyInto(out *CommonPrometheusFields) { *out = new(bool) **out = **in } + if in.ScrapeNativeHistograms != nil { + in, out := &in.ScrapeNativeHistograms, &out.ScrapeNativeHistograms + *out = new(bool) + **out = **in + } if in.ScrapeClassicHistograms != nil { in, out := &in.ScrapeClassicHistograms, &out.ScrapeClassicHistograms *out = new(bool) @@ -1093,7 +1143,7 @@ func (in *CommonPrometheusFields) DeepCopyInto(out *CommonPrometheusFields) { } if in.TracingConfig != nil { in, out := &in.TracingConfig, &out.TracingConfig - *out = new(PrometheusTracingConfig) + *out = new(TracingConfig) (*in).DeepCopyInto(*out) } if in.BodySizeLimit != nil { @@ -1366,21 +1416,6 @@ func (in *Endpoint) DeepCopyInto(out *Endpoint) { (*out)[key] = outVal } } - if in.TLSConfig != nil { - in, out := &in.TLSConfig, &out.TLSConfig - *out = new(TLSConfig) - (*in).DeepCopyInto(*out) - } - if in.BearerTokenSecret != nil { - in, out := &in.BearerTokenSecret, &out.BearerTokenSecret - *out = new(corev1.SecretKeySelector) - (*in).DeepCopyInto(*out) - } - if in.Authorization != nil { - in, out := &in.Authorization, &out.Authorization - *out = new(SafeAuthorization) - (*in).DeepCopyInto(*out) - } if in.HonorTimestamps != nil { in, out := &in.HonorTimestamps, &out.HonorTimestamps *out = new(bool) @@ -1391,16 +1426,6 @@ func (in *Endpoint) DeepCopyInto(out *Endpoint) { *out = new(bool) **out = **in } - if in.BasicAuth != nil { - in, out := &in.BasicAuth, &out.BasicAuth - *out = new(BasicAuth) - (*in).DeepCopyInto(*out) - } - if in.OAuth2 != nil { - in, out := &in.OAuth2, &out.OAuth2 - *out = new(OAuth2) - (*in).DeepCopyInto(*out) - } if in.MetricRelabelConfigs != nil { in, out := &in.MetricRelabelConfigs, &out.MetricRelabelConfigs *out = make([]RelabelConfig, len(*in)) @@ -1415,22 +1440,12 @@ func (in *Endpoint) DeepCopyInto(out *Endpoint) { (*in)[i].DeepCopyInto(&(*out)[i]) } } - in.ProxyConfig.DeepCopyInto(&out.ProxyConfig) - if in.FollowRedirects != nil { - in, out := &in.FollowRedirects, &out.FollowRedirects - *out = new(bool) - **out = **in - } - if in.EnableHttp2 != nil { - in, out := &in.EnableHttp2, &out.EnableHttp2 - *out = new(bool) - **out = **in - } if in.FilterRunning != nil { in, out := &in.FilterRunning, &out.FilterRunning *out = new(bool) **out = **in } + in.HTTPConfigWithProxyAndTLSFiles.DeepCopyInto(&out.HTTPConfigWithProxyAndTLSFiles) } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Endpoint. @@ -1670,6 +1685,82 @@ func (in *GlobalWebexConfig) DeepCopy() *GlobalWebexConfig { // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *HTTPConfig) DeepCopyInto(out *HTTPConfig) { + *out = *in + in.HTTPConfigWithoutTLS.DeepCopyInto(&out.HTTPConfigWithoutTLS) + if in.TLSConfig != nil { + in, out := &in.TLSConfig, &out.TLSConfig + *out = new(SafeTLSConfig) + (*in).DeepCopyInto(*out) + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new HTTPConfig. +func (in *HTTPConfig) DeepCopy() *HTTPConfig { + if in == nil { + return nil + } + out := new(HTTPConfig) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *HTTPConfigWithProxy) DeepCopyInto(out *HTTPConfigWithProxy) { + *out = *in + in.HTTPConfig.DeepCopyInto(&out.HTTPConfig) + in.ProxyConfig.DeepCopyInto(&out.ProxyConfig) +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new HTTPConfigWithProxy. +func (in *HTTPConfigWithProxy) DeepCopy() *HTTPConfigWithProxy { + if in == nil { + return nil + } + out := new(HTTPConfigWithProxy) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *HTTPConfigWithProxyAndTLSFiles) DeepCopyInto(out *HTTPConfigWithProxyAndTLSFiles) { + *out = *in + in.HTTPConfigWithTLSFiles.DeepCopyInto(&out.HTTPConfigWithTLSFiles) + in.ProxyConfig.DeepCopyInto(&out.ProxyConfig) +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new HTTPConfigWithProxyAndTLSFiles. +func (in *HTTPConfigWithProxyAndTLSFiles) DeepCopy() *HTTPConfigWithProxyAndTLSFiles { + if in == nil { + return nil + } + out := new(HTTPConfigWithProxyAndTLSFiles) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *HTTPConfigWithTLSFiles) DeepCopyInto(out *HTTPConfigWithTLSFiles) { + *out = *in + in.HTTPConfigWithoutTLS.DeepCopyInto(&out.HTTPConfigWithoutTLS) + if in.TLSConfig != nil { + in, out := &in.TLSConfig, &out.TLSConfig + *out = new(TLSConfig) + (*in).DeepCopyInto(*out) + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new HTTPConfigWithTLSFiles. +func (in *HTTPConfigWithTLSFiles) DeepCopy() *HTTPConfigWithTLSFiles { + if in == nil { + return nil + } + out := new(HTTPConfigWithTLSFiles) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *HTTPConfigWithoutTLS) DeepCopyInto(out *HTTPConfigWithoutTLS) { *out = *in if in.Authorization != nil { in, out := &in.Authorization, &out.Authorization @@ -1691,12 +1782,6 @@ func (in *HTTPConfig) DeepCopyInto(out *HTTPConfig) { *out = new(corev1.SecretKeySelector) (*in).DeepCopyInto(*out) } - if in.TLSConfig != nil { - in, out := &in.TLSConfig, &out.TLSConfig - *out = new(SafeTLSConfig) - (*in).DeepCopyInto(*out) - } - in.ProxyConfig.DeepCopyInto(&out.ProxyConfig) if in.FollowRedirects != nil { in, out := &in.FollowRedirects, &out.FollowRedirects *out = new(bool) @@ -1709,12 +1794,12 @@ func (in *HTTPConfig) DeepCopyInto(out *HTTPConfig) { } } -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new HTTPConfig. -func (in *HTTPConfig) DeepCopy() *HTTPConfig { +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new HTTPConfigWithoutTLS. +func (in *HTTPConfigWithoutTLS) DeepCopy() *HTTPConfigWithoutTLS { if in == nil { return nil } - out := new(HTTPConfig) + out := new(HTTPConfigWithoutTLS) in.DeepCopyInto(out) return out } @@ -1817,6 +1902,11 @@ func (in *NamespaceSelector) DeepCopy() *NamespaceSelector { // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *NativeHistogramConfig) DeepCopyInto(out *NativeHistogramConfig) { *out = *in + if in.ScrapeNativeHistograms != nil { + in, out := &in.ScrapeNativeHistograms, &out.ScrapeNativeHistograms + *out = new(bool) + **out = **in + } if in.ScrapeClassicHistograms != nil { in, out := &in.ScrapeClassicHistograms, &out.ScrapeClassicHistograms *out = new(bool) @@ -2069,7 +2159,7 @@ func (in *PodMetricsEndpoint) DeepCopyInto(out *PodMetricsEndpoint) { *out = new(bool) **out = **in } - in.HTTPConfig.DeepCopyInto(&out.HTTPConfig) + in.HTTPConfigWithProxy.DeepCopyInto(&out.HTTPConfigWithProxy) } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PodMetricsEndpoint. @@ -2283,22 +2373,6 @@ func (in *ProbeSpec) DeepCopyInto(out *ProbeSpec) { *out = *in in.ProberSpec.DeepCopyInto(&out.ProberSpec) in.Targets.DeepCopyInto(&out.Targets) - if in.TLSConfig != nil { - in, out := &in.TLSConfig, &out.TLSConfig - *out = new(SafeTLSConfig) - (*in).DeepCopyInto(*out) - } - in.BearerTokenSecret.DeepCopyInto(&out.BearerTokenSecret) - if in.BasicAuth != nil { - in, out := &in.BasicAuth, &out.BasicAuth - *out = new(BasicAuth) - (*in).DeepCopyInto(*out) - } - if in.OAuth2 != nil { - in, out := &in.OAuth2, &out.OAuth2 - *out = new(OAuth2) - (*in).DeepCopyInto(*out) - } if in.MetricRelabelConfigs != nil { in, out := &in.MetricRelabelConfigs, &out.MetricRelabelConfigs *out = make([]RelabelConfig, len(*in)) @@ -2364,6 +2438,7 @@ func (in *ProbeSpec) DeepCopyInto(out *ProbeSpec) { (*in)[i].DeepCopyInto(&(*out)[i]) } } + in.HTTPConfig.DeepCopyInto(&out.HTTPConfig) } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ProbeSpec. @@ -2709,58 +2784,6 @@ func (in *PrometheusStatus) DeepCopy() *PrometheusStatus { return out } -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *PrometheusTracingConfig) DeepCopyInto(out *PrometheusTracingConfig) { - *out = *in - if in.ClientType != nil { - in, out := &in.ClientType, &out.ClientType - *out = new(string) - **out = **in - } - if in.SamplingFraction != nil { - in, out := &in.SamplingFraction, &out.SamplingFraction - x := (*in).DeepCopy() - *out = &x - } - if in.Insecure != nil { - in, out := &in.Insecure, &out.Insecure - *out = new(bool) - **out = **in - } - if in.Headers != nil { - in, out := &in.Headers, &out.Headers - *out = make(map[string]string, len(*in)) - for key, val := range *in { - (*out)[key] = val - } - } - if in.Compression != nil { - in, out := &in.Compression, &out.Compression - *out = new(string) - **out = **in - } - if in.Timeout != nil { - in, out := &in.Timeout, &out.Timeout - *out = new(Duration) - **out = **in - } - if in.TLSConfig != nil { - in, out := &in.TLSConfig, &out.TLSConfig - *out = new(TLSConfig) - (*in).DeepCopyInto(*out) - } -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PrometheusTracingConfig. -func (in *PrometheusTracingConfig) DeepCopy() *PrometheusTracingConfig { - if in == nil { - return nil - } - out := new(PrometheusTracingConfig) - in.DeepCopyInto(out) - return out -} - // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *PrometheusWebSpec) DeepCopyInto(out *PrometheusWebSpec) { *out = *in @@ -3125,6 +3148,26 @@ func (in *RetainConfig) DeepCopy() *RetainConfig { return out } +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *RollingUpdateStatefulSetStrategy) DeepCopyInto(out *RollingUpdateStatefulSetStrategy) { + *out = *in + if in.MaxUnavailable != nil { + in, out := &in.MaxUnavailable, &out.MaxUnavailable + *out = new(intstr.IntOrString) + **out = **in + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new RollingUpdateStatefulSetStrategy. +func (in *RollingUpdateStatefulSetStrategy) DeepCopy() *RollingUpdateStatefulSetStrategy { + if in == nil { + return nil + } + out := new(RollingUpdateStatefulSetStrategy) + in.DeepCopyInto(out) + return out +} + // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *Rule) DeepCopyInto(out *Rule) { *out = *in @@ -3614,6 +3657,26 @@ func (in *Sigv4) DeepCopy() *Sigv4 { return out } +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *StatefulSetUpdateStrategy) DeepCopyInto(out *StatefulSetUpdateStrategy) { + *out = *in + if in.RollingUpdate != nil { + in, out := &in.RollingUpdate, &out.RollingUpdate + *out = new(RollingUpdateStatefulSetStrategy) + (*in).DeepCopyInto(*out) + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new StatefulSetUpdateStrategy. +func (in *StatefulSetUpdateStrategy) DeepCopy() *StatefulSetUpdateStrategy { + if in == nil { + return nil + } + out := new(StatefulSetUpdateStrategy) + in.DeepCopyInto(out) + return out +} + // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *StorageSpec) DeepCopyInto(out *StorageSpec) { *out = *in @@ -3644,6 +3707,7 @@ func (in *StorageSpec) DeepCopy() *StorageSpec { func (in *TLSConfig) DeepCopyInto(out *TLSConfig) { *out = *in in.SafeTLSConfig.DeepCopyInto(&out.SafeTLSConfig) + out.TLSFilesConfig = in.TLSFilesConfig } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new TLSConfig. @@ -3656,6 +3720,21 @@ func (in *TLSConfig) DeepCopy() *TLSConfig { return out } +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *TLSFilesConfig) DeepCopyInto(out *TLSFilesConfig) { + *out = *in +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new TLSFilesConfig. +func (in *TLSFilesConfig) DeepCopy() *TLSFilesConfig { + if in == nil { + return nil + } + out := new(TLSFilesConfig) + in.DeepCopyInto(out) + return out +} + // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *TSDBSpec) DeepCopyInto(out *TSDBSpec) { *out = *in @@ -3823,6 +3902,16 @@ func (in *ThanosRulerSpec) DeepCopyInto(out *ThanosRulerSpec) { *out = new(string) **out = **in } + if in.PodManagementPolicy != nil { + in, out := &in.PodManagementPolicy, &out.PodManagementPolicy + *out = new(PodManagementPolicyType) + **out = **in + } + if in.UpdateStrategy != nil { + in, out := &in.UpdateStrategy, &out.UpdateStrategy + *out = new(StatefulSetUpdateStrategy) + (*in).DeepCopyInto(*out) + } if in.QueryEndpoints != nil { in, out := &in.QueryEndpoints, &out.QueryEndpoints *out = make([]string, len(*in)) @@ -4122,6 +4211,58 @@ func (in *TopologySpreadConstraint) DeepCopy() *TopologySpreadConstraint { return out } +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *TracingConfig) DeepCopyInto(out *TracingConfig) { + *out = *in + if in.ClientType != nil { + in, out := &in.ClientType, &out.ClientType + *out = new(string) + **out = **in + } + if in.SamplingFraction != nil { + in, out := &in.SamplingFraction, &out.SamplingFraction + x := (*in).DeepCopy() + *out = &x + } + if in.Insecure != nil { + in, out := &in.Insecure, &out.Insecure + *out = new(bool) + **out = **in + } + if in.Headers != nil { + in, out := &in.Headers, &out.Headers + *out = make(map[string]string, len(*in)) + for key, val := range *in { + (*out)[key] = val + } + } + if in.Compression != nil { + in, out := &in.Compression, &out.Compression + *out = new(string) + **out = **in + } + if in.Timeout != nil { + in, out := &in.Timeout, &out.Timeout + *out = new(Duration) + **out = **in + } + if in.TLSConfig != nil { + in, out := &in.TLSConfig, &out.TLSConfig + *out = new(TLSConfig) + (*in).DeepCopyInto(*out) + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new TracingConfig. +func (in *TracingConfig) DeepCopy() *TracingConfig { + if in == nil { + return nil + } + out := new(TracingConfig) + in.DeepCopyInto(out) + return out +} + // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *WebConfigFileFields) DeepCopyInto(out *WebConfigFileFields) { *out = *in diff --git a/pkg/apis/monitoring/v1alpha1/alertmanager_config_types.go b/pkg/apis/monitoring/v1alpha1/alertmanager_config_types.go index e17e7fc02d9..4b0512c8bd1 100644 --- a/pkg/apis/monitoring/v1alpha1/alertmanager_config_types.go +++ b/pkg/apis/monitoring/v1alpha1/alertmanager_config_types.go @@ -29,6 +29,7 @@ import ( apiextensionsv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" + "k8s.io/utils/ptr" ) const ( @@ -43,6 +44,7 @@ const ( // +k8s:openapi-gen=true // +kubebuilder:resource:categories="prometheus-operator",shortName="amcfg" // +kubebuilder:storageversion +// +kubebuilder:subresource:status // AlertmanagerConfig configures the Prometheus Alertmanager, // specifying how alerts should be grouped, inhibited and notified to external systems. @@ -55,6 +57,14 @@ type AlertmanagerConfig struct { // spec defines the specification of AlertmanagerConfigSpec // +required Spec AlertmanagerConfigSpec `json:"spec"` + // status defines the status subresource. It is under active development and is updated only when the + // "StatusForConfigurationResources" feature gate is enabled. + // + // Most recent observed status of the ServiceMonitor. Read-only. + // More info: + // https://github.com/kubernetes/community/blob/master/contributors/devel/sig-architecture/api-conventions.md#spec-and-status + // +optional + Status monitoringv1.ConfigResourceStatus `json:"status,omitempty,omitzero"` } // AlertmanagerConfigList is a list of AlertmanagerConfig. @@ -81,13 +91,17 @@ type AlertmanagerConfigSpec struct { // +optional Route *Route `json:"route"` // receivers defines the list of receivers. + // +listType=map + // +listMapKey=name // +optional Receivers []Receiver `json:"receivers"` // inhibitRules defines the list of inhibition rules. The rules will only apply to alerts matching // the resource's namespace. + // +listType=atomic // +optional InhibitRules []InhibitRule `json:"inhibitRules,omitempty"` // muteTimeIntervals defines the list of MuteTimeInterval specifying when the routes should be muted. + // +listType=atomic // +optional MuteTimeIntervals []MuteTimeInterval `json:"muteTimeIntervals,omitempty"` } @@ -101,6 +115,7 @@ type Route struct { // groupBy defines the list of labels to group by. // Labels must not be repeated (unique list). // Special label "..." (aggregate by all possible labels), if provided, must be the only element in the list. + // +listType=set // +optional GroupBy []string `json:"groupBy,omitempty"` // groupWait defines how long to wait before sending the initial notification. @@ -122,14 +137,16 @@ type Route struct { // level route, the operator removes any existing equality and regexp // matcher on the `namespace` label and adds a `namespace: ` matcher. + // +listType=atomic // +optional Matchers []Matcher `json:"matchers,omitempty"` // continue defines the boolean indicating whether an alert should continue matching subsequent // sibling nodes. It will always be overridden to true for the first-level // route by the Prometheus operator. // +optional - Continue bool `json:"continue,omitempty"` + Continue bool `json:"continue,omitempty"` // nolint:kubeapilinter // routes defines the child routes. + // +listType=atomic // +optional Routes []apiextensionsv1.JSON `json:"routes,omitempty"` // Note: this comment applies to the field definition above but appears @@ -141,9 +158,11 @@ type Route struct { // JSON representation. // muteTimeIntervals is a list of MuteTimeInterval names that will mute this route when matched, + // +listType=set // +optional MuteTimeIntervals []string `json:"muteTimeIntervals,omitempty"` // activeTimeIntervals is a list of MuteTimeInterval names when this route should be active. + // +listType=set // +optional ActiveTimeIntervals []string `json:"activeTimeIntervals,omitempty"` } @@ -170,51 +189,66 @@ type Receiver struct { // +required Name string `json:"name"` // opsgenieConfigs defines the list of OpsGenie configurations. + // +listType=atomic // +optional OpsGenieConfigs []OpsGenieConfig `json:"opsgenieConfigs,omitempty"` // pagerdutyConfigs defines the List of PagerDuty configurations. + // +listType=atomic // +optional PagerDutyConfigs []PagerDutyConfig `json:"pagerdutyConfigs,omitempty"` // discordConfigs defines the list of Slack configurations. + // +listType=atomic // +optional DiscordConfigs []DiscordConfig `json:"discordConfigs,omitempty"` // slackConfigs defines the list of Slack configurations. + // +listType=atomic // +optional SlackConfigs []SlackConfig `json:"slackConfigs,omitempty"` // webhookConfigs defines the List of webhook configurations. + // +listType=atomic // +optional WebhookConfigs []WebhookConfig `json:"webhookConfigs,omitempty"` // wechatConfigs defines the list of WeChat configurations. + // +listType=atomic // +optional WeChatConfigs []WeChatConfig `json:"wechatConfigs,omitempty"` // emailConfigs defines the list of Email configurations. + // +listType=atomic // +optional EmailConfigs []EmailConfig `json:"emailConfigs,omitempty"` // victoropsConfigs defines the list of VictorOps configurations. + // +listType=atomic // +optional VictorOpsConfigs []VictorOpsConfig `json:"victoropsConfigs,omitempty"` // pushoverConfigs defines the list of Pushover configurations. + // +listType=atomic // +optional PushoverConfigs []PushoverConfig `json:"pushoverConfigs,omitempty"` // snsConfigs defines the list of SNS configurations + // +listType=atomic // +optional SNSConfigs []SNSConfig `json:"snsConfigs,omitempty"` // telegramConfigs defines the list of Telegram configurations. + // +listType=atomic // +optional TelegramConfigs []TelegramConfig `json:"telegramConfigs,omitempty"` // webexConfigs defines the list of Webex configurations. + // +listType=atomic // +optional WebexConfigs []WebexConfig `json:"webexConfigs,omitempty"` // msteamsConfigs defines the list of MSTeams configurations. // It requires Alertmanager >= 0.26.0. + // +listType=atomic // +optional MSTeamsConfigs []MSTeamsConfig `json:"msteamsConfigs,omitempty"` // msteamsv2Configs defines the list of MSTeamsV2 configurations. // It requires Alertmanager >= 0.28.0. + // +listType=atomic // +optional MSTeamsV2Configs []MSTeamsV2Config `json:"msteamsv2Configs,omitempty"` // rocketchatConfigs defines the list of RocketChat configurations. // It requires Alertmanager >= 0.28.0. + // +listType=atomic // +optional RocketChatConfigs []RocketChatConfig `json:"rocketchatConfigs,omitempty"` } @@ -224,7 +258,7 @@ type Receiver struct { type PagerDutyConfig struct { // sendResolved defines whether or not to notify about resolved alerts. // +optional - SendResolved *bool `json:"sendResolved,omitempty"` + SendResolved *bool `json:"sendResolved,omitempty"` // nolint:kubeapilinter // routingKey defines the secret's key that contains the PagerDuty integration key (when using // Events API v2). Either this field or `serviceKey` needs to be defined. // The secret needs to be in the same namespace as the AlertmanagerConfig @@ -240,66 +274,83 @@ type PagerDutyConfig struct { ServiceKey *v1.SecretKeySelector `json:"serviceKey,omitempty"` // url defines the URL to send requests to. // +optional - URL string `json:"url,omitempty"` + URL *URL `json:"url,omitempty"` // client defines the client identification. + // +kubebuilder:validation:MinLength=1 // +optional - Client string `json:"client,omitempty"` + Client *string `json:"client,omitempty"` // clientURL defines the backlink to the sender of notification. // +optional - ClientURL string `json:"clientURL,omitempty"` + ClientURL *URL `json:"clientURL,omitempty"` // description of the incident. + // +kubebuilder:validation:MinLength=1 // +optional - Description string `json:"description,omitempty"` + Description *string `json:"description,omitempty"` // severity of the incident. + // +kubebuilder:validation:MinLength=1 // +optional - Severity string `json:"severity,omitempty"` + Severity *string `json:"severity,omitempty"` // class defines the class/type of the event. + // +kubebuilder:validation:MinLength=1 // +optional - Class string `json:"class,omitempty"` + Class *string `json:"class,omitempty"` // group defines a cluster or grouping of sources. + // +kubebuilder:validation:MinLength=1 // +optional - Group string `json:"group,omitempty"` + Group *string `json:"group,omitempty"` // component defines the part or component of the affected system that is broken. + // +kubebuilder:validation:MinLength=1 // +optional - Component string `json:"component,omitempty"` + Component *string `json:"component,omitempty"` // details defines the arbitrary key/value pairs that provide further detail about the incident. + // +listType=atomic // +optional Details []KeyValue `json:"details,omitempty"` // pagerDutyImageConfigs defines a list of image details to attach that provide further detail about an incident. + // +listType=atomic // +optional PagerDutyImageConfigs []PagerDutyImageConfig `json:"pagerDutyImageConfigs,omitempty"` // pagerDutyLinkConfigs defines a list of link details to attach that provide further detail about an incident. + // +listType=atomic // +optional PagerDutyLinkConfigs []PagerDutyLinkConfig `json:"pagerDutyLinkConfigs,omitempty"` // httpConfig defines the HTTP client configuration. // +optional HTTPConfig *HTTPConfig `json:"httpConfig,omitempty"` // source defines the unique location of the affected system. + // +kubebuilder:validation:MinLength=1 + // +optional + Source *string `json:"source,omitempty"` + // timeout is the maximum time allowed to invoke the pagerduty + // It requires Alertmanager >= v0.30.0. // +optional - Source *string `yaml:"source,omitempty" json:"source,omitempty"` + Timeout *monitoringv1.Duration `json:"timeout,omitempty"` } // PagerDutyImageConfig attaches images to an incident type PagerDutyImageConfig struct { // src of the image being attached to the incident + // +kubebuilder:validation:MinLength=1 // +optional - Src string `json:"src,omitempty"` + Src *string `json:"src,omitempty"` // href defines the optional URL; makes the image a clickable link. // +optional - Href string `json:"href,omitempty"` + Href *URL `json:"href,omitempty"` // alt is the optional alternative text for the image. + // +kubebuilder:validation:MinLength=1 // +optional - Alt string `json:"alt,omitempty"` + Alt *string `json:"alt,omitempty"` } // PagerDutyLinkConfig attaches text links to an incident type PagerDutyLinkConfig struct { // href defines the URL of the link to be attached // +optional - Href string `json:"href,omitempty"` + Href *URL `json:"href,omitempty"` // alt defines the text that describes the purpose of the link, and can be used as the link's text. + // +kubebuilder:validation:MinLength=1 // +optional - Text string `json:"alt,omitempty"` + Text *string `json:"alt,omitempty"` } // DiscordConfig configures notifications via Discord. @@ -307,7 +358,7 @@ type PagerDutyLinkConfig struct { type DiscordConfig struct { // sendResolved defines whether or not to notify about resolved alerts. // +optional - SendResolved *bool `json:"sendResolved,omitempty"` + SendResolved *bool `json:"sendResolved,omitempty"` // nolint:kubeapilinter // apiURL defines the secret's key that contains the Discord webhook URL. // The secret needs to be in the same namespace as the AlertmanagerConfig // object and accessible by the Prometheus Operator. @@ -340,77 +391,99 @@ type DiscordConfig struct { type SlackConfig struct { // sendResolved defines whether or not to notify about resolved alerts. // +optional - SendResolved *bool `json:"sendResolved,omitempty"` + SendResolved *bool `json:"sendResolved,omitempty"` // nolint:kubeapilinter // apiURL defines the secret's key that contains the Slack webhook URL. // The secret needs to be in the same namespace as the AlertmanagerConfig // object and accessible by the Prometheus Operator. // +optional APIURL *v1.SecretKeySelector `json:"apiURL,omitempty"` // channel defines the channel or user to send notifications to. + // +kubebuilder:validation:MinLength=1 // +optional - Channel string `json:"channel,omitempty"` + Channel *string `json:"channel,omitempty"` // username defines the slack bot user name. + // +kubebuilder:validation:MinLength=1 // +optional - Username string `json:"username,omitempty"` + Username *string `json:"username,omitempty"` // color defines the color of the left border of the Slack message attachment. // Can be a hex color code (e.g., "#ff0000") or a predefined color name. + // +kubebuilder:validation:MinLength=1 // +optional - Color string `json:"color,omitempty"` + Color *string `json:"color,omitempty"` // title defines the title text displayed in the Slack message attachment. + // +kubebuilder:validation:MinLength=1 // +optional - Title string `json:"title,omitempty"` + Title *string `json:"title,omitempty"` // titleLink defines the URL that the title will link to when clicked. // +optional - TitleLink string `json:"titleLink,omitempty"` + TitleLink *URL `json:"titleLink,omitempty"` // pretext defines optional text that appears above the message attachment block. + // +kubebuilder:validation:MinLength=1 // +optional - Pretext string `json:"pretext,omitempty"` + Pretext *string `json:"pretext,omitempty"` // text defines the main text content of the Slack message attachment. + // +kubebuilder:validation:MinLength=1 // +optional - Text string `json:"text,omitempty"` + Text *string `json:"text,omitempty"` // fields defines a list of Slack fields that are sent with each notification. + // +kubebuilder:validation:MinItems=1 + // +listType=atomic // +optional Fields []SlackField `json:"fields,omitempty"` // shortFields determines whether fields are displayed in a compact format. // When true, fields are shown side by side when possible. // +optional - ShortFields bool `json:"shortFields,omitempty"` + ShortFields *bool `json:"shortFields,omitempty"` // nolint:kubeapilinter // footer defines small text displayed at the bottom of the message attachment. + // +kubebuilder:validation:MinLength=1 // +optional - Footer string `json:"footer,omitempty"` + Footer *string `json:"footer,omitempty"` // fallback defines a plain-text summary of the attachment for clients that don't support attachments. + // +kubebuilder:validation:MinLength=1 // +optional - Fallback string `json:"fallback,omitempty"` + Fallback *string `json:"fallback,omitempty"` // callbackId defines an identifier for the message used in interactive components. + // +kubebuilder:validation:MinLength=1 // +optional - CallbackID string `json:"callbackId,omitempty"` + CallbackID *string `json:"callbackId,omitempty"` // iconEmoji defines the emoji to use as the bot's avatar (e.g., ":ghost:"). + // +kubebuilder:validation:MinLength=1 // +optional - IconEmoji string `json:"iconEmoji,omitempty"` + IconEmoji *string `json:"iconEmoji,omitempty"` // iconURL defines the URL to an image to use as the bot's avatar. // +optional - IconURL string `json:"iconURL,omitempty"` + IconURL *URL `json:"iconURL,omitempty"` // imageURL defines the URL to an image file that will be displayed inside the message attachment. // +optional - ImageURL string `json:"imageURL,omitempty"` + ImageURL *URL `json:"imageURL,omitempty"` // thumbURL defines the URL to an image file that will be displayed as a thumbnail // on the right side of the message attachment. // +optional - ThumbURL string `json:"thumbURL,omitempty"` + ThumbURL *URL `json:"thumbURL,omitempty"` // linkNames enables automatic linking of channel names and usernames in the message. // When true, @channel and @username will be converted to clickable links. // +optional - LinkNames bool `json:"linkNames,omitempty"` + LinkNames *bool `json:"linkNames,omitempty"` // nolint:kubeapilinter // mrkdwnIn defines which fields should be parsed as Slack markdown. // Valid values include "pretext", "text", and "fields". + // +listType=atomic + // +kubebuilder:validation:MinItems=1 + // +kubebuilder:validation:items:MinLength=1 // +optional MrkdwnIn []string `json:"mrkdwnIn,omitempty"` // actions defines a list of Slack actions that are sent with each notification. + // +kubebuilder:validation:MinItems=1 + // +listType=atomic // +optional Actions []SlackAction `json:"actions,omitempty"` // httpConfig defines the HTTP client configuration. // +optional HTTPConfig *HTTPConfig `json:"httpConfig,omitempty"` + // timeout defines the maximum time to wait for a webhook request to complete, + // before failing the request and allowing it to be retried. + // It requires Alertmanager >= v0.30.0. + // +optional + Timeout *monitoringv1.Duration `json:"timeout,omitempty"` } // Validate ensures SlackConfig is valid. @@ -448,19 +521,22 @@ type SlackAction struct { // url defines the URL to open when the action is triggered. // Only applicable for button-type actions. When set, clicking the button opens this URL. // +optional - URL string `json:"url,omitempty"` + URL *URL `json:"url,omitempty"` // style defines the visual appearance of the action element. // Valid values include "default", "primary" (green), and "danger" (red). + // +kubebuilder:validation:MinLength=1 // +optional - Style string `json:"style,omitempty"` + Style *string `json:"style,omitempty"` // name defines a unique identifier for the action within the message. // This value is sent back to your application when the action is triggered. + // +kubebuilder:validation:MinLength=1 // +optional - Name string `json:"name,omitempty"` + Name *string `json:"name,omitempty"` // value defines the payload sent when the action is triggered. // This data is included in the callback sent to your application. + // +kubebuilder:validation:MinLength=1 // +optional - Value string `json:"value,omitempty"` + Value *string `json:"value,omitempty"` // confirm defines an optional confirmation dialog that appears before the action is executed. // When set, users must confirm their intent before the action proceeds. // +optional @@ -477,7 +553,7 @@ func (sa *SlackAction) Validate() error { return errors.New("missing text in Slack action configuration") } - if sa.URL == "" && sa.Name == "" { + if ptr.Deref(sa.URL, "") == "" && ptr.Deref(sa.Name, "") == "" { return errors.New("missing name or url in Slack action configuration") } @@ -503,16 +579,19 @@ type SlackConfirmationField struct { Text string `json:"text"` // title defines the title text displayed at the top of the confirmation dialog. // When not specified, a default title will be used. + // +kubebuilder:validation:MinLength=1 // +optional - Title string `json:"title,omitempty"` + Title *string `json:"title,omitempty"` // okText defines the label for the confirmation button in the dialog. // When not specified, defaults to "Okay". This button proceeds with the action. + // +kubebuilder:validation:MinLength=1 // +optional - OkText string `json:"okText,omitempty"` + OkText *string `json:"okText,omitempty"` // dismissText defines the label for the cancel button in the dialog. // When not specified, defaults to "Cancel". This button cancels the action. + // +kubebuilder:validation:MinLength=1 // +optional - DismissText string `json:"dismissText,omitempty"` + DismissText *string `json:"dismissText,omitempty"` } // Validate ensures SlackConfirmationField is valid. @@ -542,7 +621,7 @@ type SlackField struct { // When true, Slack may display this field side by side with other short fields. // When false or not specified, the field takes the full width of the message. // +optional - Short *bool `json:"short,omitempty"` + Short *bool `json:"short,omitempty"` // nolint:kubeapilinter } // Validate ensures SlackField is valid @@ -563,11 +642,11 @@ func (sf *SlackField) Validate() error { type WebhookConfig struct { // sendResolved defines whether or not to notify about resolved alerts. // +optional - SendResolved *bool `json:"sendResolved,omitempty"` + SendResolved *bool `json:"sendResolved,omitempty"` // nolint:kubeapilinter // url defines the URL to send HTTP POST requests to. // urlSecret takes precedence over url. One of urlSecret and url should be defined. // +optional - URL *string `json:"url,omitempty"` + URL *URL `json:"url,omitempty"` // urlSecret defines the secret's key that contains the webhook URL to send HTTP requests to. // urlSecret takes precedence over url. One of urlSecret and url should be defined. // The secret needs to be in the same namespace as the AlertmanagerConfig @@ -594,7 +673,7 @@ type WebhookConfig struct { type OpsGenieConfig struct { // sendResolved defines whether or not to notify about resolved alerts. // +optional - SendResolved *bool `json:"sendResolved,omitempty"` + SendResolved *bool `json:"sendResolved,omitempty"` // nolint:kubeapilinter // apiKey defines the secret's key that contains the OpsGenie API key. // The secret needs to be in the same namespace as the AlertmanagerConfig // object and accessible by the Prometheus Operator. @@ -603,7 +682,7 @@ type OpsGenieConfig struct { // apiURL defines the URL to send OpsGenie API requests to. // When not specified, defaults to the standard OpsGenie API endpoint. // +optional - APIURL string `json:"apiURL,omitempty"` + APIURL *URL `json:"apiURL,omitempty"` // message defines the alert text limited to 130 characters. // This appears as the main alert title in OpsGenie. // +optional @@ -631,13 +710,15 @@ type OpsGenieConfig struct { // updateAlerts defines Whether to update message and description of the alert in OpsGenie if it already exists // By default, the alert is never updated in OpsGenie, the new message only appears in activity log. // +optional - UpdateAlerts *bool `json:"updateAlerts,omitempty"` + UpdateAlerts *bool `json:"updateAlerts,omitempty"` // nolint:kubeapilinter // details defines a set of arbitrary key/value pairs that provide further detail about the incident. // These appear as additional fields in the OpsGenie alert. + // +listType=atomic // +optional Details []KeyValue `json:"details,omitempty"` // responders defines the list of responders responsible for notifications. // These determine who gets notified when the alert is created. + // +listType=atomic // +optional Responders []OpsGenieConfigResponder `json:"responders,omitempty"` // httpConfig defines the HTTP client configuration for OpsGenie API requests. @@ -748,12 +829,12 @@ type HTTPConfig struct { // followRedirects specifies whether the client should follow HTTP 3xx redirects. // When true, the client will automatically follow redirect responses. // +optional - FollowRedirects *bool `json:"followRedirects,omitempty"` + FollowRedirects *bool `json:"followRedirects,omitempty"` // nolint:kubeapilinter // enableHttp2 can be used to disable HTTP2. // // +optional - EnableHTTP2 *bool `json:"enableHttp2,omitempty"` + EnableHTTP2 *bool `json:"enableHttp2,omitempty"` // nolint:kubeapilinter } // WebexConfig configures notification via Cisco Webex @@ -761,7 +842,7 @@ type HTTPConfig struct { type WebexConfig struct { // sendResolved defines whether or not to notify about resolved alerts. // +optional - SendResolved *bool `json:"sendResolved,omitempty"` + SendResolved *bool `json:"sendResolved,omitempty"` // nolint:kubeapilinter // apiURL defines the Webex Teams API URL i.e. https://webexapis.com/v1/messages // +optional @@ -786,7 +867,7 @@ type WebexConfig struct { type WeChatConfig struct { // sendResolved defines whether or not to notify about resolved alerts. // +optional - SendResolved *bool `json:"sendResolved,omitempty"` + SendResolved *bool `json:"sendResolved,omitempty"` // nolint:kubeapilinter // apiSecret defines the secret's key that contains the WeChat API key. // The secret needs to be in the same namespace as the AlertmanagerConfig // object and accessible by the Prometheus Operator. @@ -795,7 +876,7 @@ type WeChatConfig struct { // apiURL defines the WeChat API URL. // When not specified, defaults to the standard WeChat Work API endpoint. // +optional - APIURL string `json:"apiURL,omitempty"` + APIURL *URL `json:"apiURL,omitempty"` // corpID defines the corp id for authentication. // This is the unique identifier for your WeChat Work organization. // +optional @@ -833,7 +914,7 @@ type WeChatConfig struct { type EmailConfig struct { // sendResolved defines whether or not to notify about resolved alerts. // +optional - SendResolved *bool `json:"sendResolved,omitempty"` + SendResolved *bool `json:"sendResolved,omitempty"` // nolint:kubeapilinter // to defines the email address to send notifications to. // This is the recipient address for alert notifications. // +optional @@ -871,6 +952,7 @@ type EmailConfig struct { AuthIdentity string `json:"authIdentity,omitempty"` // headers defines additional email header key/value pairs. // These override any headers previously set by the notification implementation. + // +listType=atomic // +optional Headers []KeyValue `json:"headers,omitempty"` // html defines the HTML body of the email notification. @@ -884,7 +966,7 @@ type EmailConfig struct { // requireTLS defines the SMTP TLS requirement. // Note that Go does not support unencrypted connections to remote SMTP endpoints. // +optional - RequireTLS *bool `json:"requireTLS,omitempty"` + RequireTLS *bool `json:"requireTLS,omitempty"` // nolint:kubeapilinter // tlsConfig defines the TLS configuration for SMTP connections. // This includes settings for certificates, CA validation, and TLS protocol options. // +optional @@ -896,7 +978,7 @@ type EmailConfig struct { type VictorOpsConfig struct { // sendResolved defines whether or not to notify about resolved alerts. // +optional - SendResolved *bool `json:"sendResolved,omitempty"` + SendResolved *bool `json:"sendResolved,omitempty"` // nolint:kubeapilinter // apiKey defines the secret's key that contains the API key to use when talking to the VictorOps API. // The secret needs to be in the same namespace as the AlertmanagerConfig // object and accessible by the Prometheus Operator. @@ -905,29 +987,35 @@ type VictorOpsConfig struct { // apiUrl defines the VictorOps API URL. // When not specified, defaults to the standard VictorOps API endpoint. // +optional - APIURL string `json:"apiUrl,omitempty"` + APIURL *URL `json:"apiUrl,omitempty"` // routingKey defines a key used to map the alert to a team. // This determines which VictorOps team will receive the alert notification. - // +optional + // +kubebuilder:validation:MinLength=1 + // +required RoutingKey string `json:"routingKey"` // messageType describes the behavior of the alert. // Valid values are "CRITICAL", "WARNING", and "INFO". + // +kubebuilder:validation:MinLength=1 // +optional - MessageType string `json:"messageType,omitempty"` + MessageType *string `json:"messageType,omitempty"` // entityDisplayName contains a summary of the alerted problem. // This appears as the main title or identifier for the incident. + // +kubebuilder:validation:MinLength=1 // +optional - EntityDisplayName string `json:"entityDisplayName,omitempty"` + EntityDisplayName *string `json:"entityDisplayName,omitempty"` // stateMessage contains a long explanation of the alerted problem. // This provides detailed context about the incident. + // +kubebuilder:validation:MinLength=1 // +optional - StateMessage string `json:"stateMessage,omitempty"` + StateMessage *string `json:"stateMessage,omitempty"` // monitoringTool defines the monitoring tool the state message is from. // This helps identify the source system that generated the alert. + // +kubebuilder:validation:MinLength=1 // +optional - MonitoringTool string `json:"monitoringTool,omitempty"` + MonitoringTool *string `json:"monitoringTool,omitempty"` // customFields defines additional custom fields for notification. // These provide extra metadata that will be included with the VictorOps incident. + // +listType=atomic // +optional CustomFields []KeyValue `json:"customFields,omitempty"` // httpConfig defines the HTTP client's configuration for VictorOps API requests. @@ -940,7 +1028,7 @@ type VictorOpsConfig struct { type PushoverConfig struct { // sendResolved defines whether or not to notify about resolved alerts. // +optional - SendResolved *bool `json:"sendResolved,omitempty"` + SendResolved *bool `json:"sendResolved,omitempty"` // nolint:kubeapilinter // userKey defines the secret's key that contains the recipient user's user key. // The secret needs to be in the same namespace as the AlertmanagerConfig // object and accessible by the Prometheus Operator. @@ -950,6 +1038,7 @@ type PushoverConfig struct { // userKeyFile defines the user key file that contains the recipient user's user key. // Either `userKey` or `userKeyFile` is required. // It requires Alertmanager >= v0.26.0. + // +kubebuilder:validation:MinLength=1 // +optional UserKeyFile *string `json:"userKeyFile,omitempty"` // token defines the secret's key that contains the registered application's API token. @@ -963,58 +1052,66 @@ type PushoverConfig struct { // See https://pushover.net/apps for application registration. // Either `token` or `tokenFile` is required. // It requires Alertmanager >= v0.26.0. + // +kubebuilder:validation:MinLength=1 // +optional TokenFile *string `json:"tokenFile,omitempty"` // title defines the notification title displayed in the Pushover message. // This appears as the bold header text in the notification. + // +kubebuilder:validation:MinLength=1 // +optional - Title string `json:"title,omitempty"` + Title *string `json:"title,omitempty"` // message defines the notification message content. // This is the main body text of the Pushover notification. + // +kubebuilder:validation:MinLength=1 // +optional - Message string `json:"message,omitempty"` + Message *string `json:"message,omitempty"` // url defines a supplementary URL shown alongside the message. // This creates a clickable link within the Pushover notification. // +optional - URL string `json:"url,omitempty"` + URL *URL `json:"url,omitempty"` // urlTitle defines a title for the supplementary URL. // If not specified, the raw URL is shown instead. + // +kubebuilder:validation:MinLength=1 // +optional - URLTitle string `json:"urlTitle,omitempty"` + URLTitle *string `json:"urlTitle,omitempty"` // ttl defines the time to live for the alert notification. // This determines how long the notification remains active before expiring. // +optional TTL *monitoringv1.Duration `json:"ttl,omitempty"` // device defines the name of a specific device to send the notification to. // If not specified, the notification is sent to all user's devices. + // +kubebuilder:validation:MinLength=1 // +optional Device *string `json:"device,omitempty"` // sound defines the name of one of the sounds supported by device clients. // This overrides the user's default sound choice for this notification. + // +kubebuilder:validation:MinLength=1 // +optional - Sound string `json:"sound,omitempty"` + Sound *string `json:"sound,omitempty"` // priority defines the notification priority level. // See https://pushover.net/api#priority for valid values and behavior. + // +kubebuilder:validation:MinLength=1 // +optional - Priority string `json:"priority,omitempty"` + Priority *string `json:"priority,omitempty"` // retry defines how often the Pushover servers will send the same notification to the user. // Must be at least 30 seconds. Only applies to priority 2 notifications. // +kubebuilder:validation:Pattern=`^(([0-9]+)y)?(([0-9]+)w)?(([0-9]+)d)?(([0-9]+)h)?(([0-9]+)m)?(([0-9]+)s)?(([0-9]+)ms)?$` // +optional - Retry string `json:"retry,omitempty"` + Retry *string `json:"retry,omitempty"` // expire defines how long your notification will continue to be retried for, // unless the user acknowledges the notification. Only applies to priority 2 notifications. // +kubebuilder:validation:Pattern=`^(([0-9]+)y)?(([0-9]+)w)?(([0-9]+)d)?(([0-9]+)h)?(([0-9]+)m)?(([0-9]+)s)?(([0-9]+)ms)?$` // +optional - Expire string `json:"expire,omitempty"` + Expire *string `json:"expire,omitempty"` // html defines whether notification message is HTML or plain text. // When true, the message can include HTML formatting tags. + // html and monospace formatting are mutually exclusive. // +optional - HTML *bool `json:"html,omitempty"` + HTML *bool `json:"html,omitempty"` //nolint:kubeapilinter // monospace optional HTML/monospace formatting for the message, see https://pushover.net/api#html // html and monospace formatting are mutually exclusive. // +optional - Monospace *bool `json:"monospace,omitempty"` + Monospace *bool `json:"monospace,omitempty"` //nolint:kubeapilinter // httpConfig defines the HTTP client configuration for Pushover API requests. // +optional HTTPConfig *HTTPConfig `json:"httpConfig,omitempty"` @@ -1025,7 +1122,7 @@ type PushoverConfig struct { type SNSConfig struct { // sendResolved defines whether or not to notify about resolved alerts. // +optional - SendResolved *bool `json:"sendResolved,omitempty"` + SendResolved *bool `json:"sendResolved,omitempty"` // nolint:kubeapilinter // apiURL defines the SNS API URL, e.g. https://sns.us-east-2.amazonaws.com. // If not specified, the SNS API URL from the SNS SDK will be used. // +optional @@ -1057,6 +1154,7 @@ type SNSConfig struct { // attributes defines SNS message attributes as key-value pairs. // These provide additional metadata that can be used for message filtering and routing. // +optional + //nolint:kubeapilinter Attributes map[string]string `json:"attributes,omitempty"` // httpConfig defines the HTTP client configuration for SNS API requests. // +optional @@ -1068,11 +1166,11 @@ type SNSConfig struct { type TelegramConfig struct { // sendResolved defines whether or not to notify about resolved alerts. // +optional - SendResolved *bool `json:"sendResolved,omitempty"` + SendResolved *bool `json:"sendResolved,omitempty"` // nolint:kubeapilinter // apiURL defines the Telegram API URL, e.g. https://api.telegram.org. // If not specified, the default Telegram API URL will be used. // +optional - APIURL string `json:"apiURL,omitempty"` + APIURL *URL `json:"apiURL,omitempty"` // botToken defines the Telegram bot token. It is mutually exclusive with `botTokenFile`. // The secret needs to be in the same namespace as the AlertmanagerConfig // object and accessible by the Prometheus Operator. @@ -1101,7 +1199,7 @@ type TelegramConfig struct { // disableNotifications controls whether Telegram notifications are sent silently. // When true, users will receive the message without notification sounds. // +optional - DisableNotifications *bool `json:"disableNotifications,omitempty"` + DisableNotifications *bool `json:"disableNotifications,omitempty"` // nolint:kubeapilinter // parseMode defines the parse mode for telegram message formatting. // Valid values are "MarkdownV2", "Markdown", and "HTML". // This determines how text formatting is interpreted in the message. @@ -1118,7 +1216,7 @@ type TelegramConfig struct { type MSTeamsConfig struct { // sendResolved defines whether or not to notify about resolved alerts. // +optional - SendResolved *bool `json:"sendResolved,omitempty"` + SendResolved *bool `json:"sendResolved,omitempty"` // nolint:kubeapilinter // webhookUrl defines the MSTeams webhook URL for sending notifications. // This is the incoming webhook URL configured in your Teams channel. // +required @@ -1147,7 +1245,7 @@ type MSTeamsConfig struct { type MSTeamsV2Config struct { // sendResolved defines whether or not to notify about resolved alerts. // +optional - SendResolved *bool `json:"sendResolved,omitempty"` + SendResolved *bool `json:"sendResolved,omitempty"` // nolint:kubeapilinter // webhookURL defines the MSTeams incoming webhook URL for adaptive card notifications. // This webhook must support the newer adaptive cards format required by Teams flows. // +optional @@ -1172,7 +1270,7 @@ type MSTeamsV2Config struct { type RocketChatConfig struct { // sendResolved defines whether or not to notify about resolved alerts. // +optional - SendResolved *bool `json:"sendResolved,omitempty"` + SendResolved *bool `json:"sendResolved,omitempty"` // nolint:kubeapilinter // apiURL defines the API URL for RocketChat. // Defaults to https://open.rocket.chat/ if not specified. // +optional @@ -1221,13 +1319,14 @@ type RocketChatConfig struct { TitleLink *string `json:"titleLink,omitempty"` // fields defines additional fields for the message attachment. // These appear as structured key-value pairs within the message. + // +listType=atomic // +kubebuilder:validation:MinItems=1 // +optional Fields []RocketChatFieldConfig `json:"fields,omitempty"` // shortFields defines whether to use short fields in the message layout. // When true, fields may be displayed side by side to save space. // +optional - ShortFields *bool `json:"shortFields,omitempty"` + ShortFields *bool `json:"shortFields,omitempty"` // nolint:kubeapilinter // imageURL defines the image URL to display within the message. // This embeds an image directly in the message attachment. // +optional @@ -1239,9 +1338,10 @@ type RocketChatConfig struct { // linkNames defines whether to enable automatic linking of usernames and channels. // When true, @username and #channel references become clickable links. // +optional - LinkNames *bool `json:"linkNames,omitempty"` + LinkNames *bool `json:"linkNames,omitempty"` // nolint:kubeapilinter // actions defines interactive actions to include in the message. // These appear as buttons that users can click to trigger responses. + // +listType=atomic // +kubebuilder:validation:MinItems=1 // +optional Actions []RocketChatActionConfig `json:"actions,omitempty"` @@ -1265,7 +1365,7 @@ type RocketChatFieldConfig struct { // short defines whether this field should be a short field. // When true, the field may be displayed inline with other short fields to save space. // +optional - Short *bool `json:"short,omitempty"` + Short *bool `json:"short,omitempty"` // nolint:kubeapilinter } // RocketChatActionConfig defines actions for RocketChat messages. @@ -1293,15 +1393,18 @@ type InhibitRule struct { // targetMatch defines matchers that have to be fulfilled in the alerts to be muted. // The operator enforces that the alert matches the resource's namespace. // When these conditions are met, matching alerts will be inhibited (silenced). + // +listType=atomic // +optional TargetMatch []Matcher `json:"targetMatch,omitempty"` // sourceMatch defines matchers for which one or more alerts have to exist for the inhibition // to take effect. The operator enforces that the alert matches the resource's namespace. // These are the "trigger" alerts that cause other alerts to be inhibited. + // +listType=atomic // +optional SourceMatch []Matcher `json:"sourceMatch,omitempty"` // equal defines labels that must have an equal value in the source and target alert // for the inhibition to take effect. This ensures related alerts are properly grouped. + // +listType=atomic // +optional Equal []string `json:"equal,omitempty"` } @@ -1339,7 +1442,7 @@ type Matcher struct { // regex defines whether to match on equality (false) or regular-expression (true). // Deprecated: for AlertManager >= v0.22.0, `matchType` should be used instead. // +optional - Regex bool `json:"regex,omitempty"` + Regex bool `json:"regex,omitempty"` // nolint:kubeapilinter } // String returns Matcher as a string @@ -1420,6 +1523,7 @@ type MuteTimeInterval struct { // +required Name string `json:"name,omitempty"` // timeIntervals defines a list of TimeInterval + // +listType=atomic // +optional TimeIntervals []TimeInterval `json:"timeIntervals,omitempty"` } @@ -1427,18 +1531,23 @@ type MuteTimeInterval struct { // TimeInterval describes intervals of time type TimeInterval struct { // times defines a list of TimeRange + // +listType=atomic // +optional Times []TimeRange `json:"times,omitempty"` // weekdays defines a list of WeekdayRange + // +listType=atomic // +optional Weekdays []WeekdayRange `json:"weekdays,omitempty"` // daysOfMonth defines a list of DayOfMonthRange + // +listType=atomic // +optional DaysOfMonth []DayOfMonthRange `json:"daysOfMonth,omitempty"` // months defines a list of MonthRange + // +listType=atomic // +optional Months []MonthRange `json:"months,omitempty"` // years defines a list of YearRange + // +listType=atomic // +optional Years []YearRange `json:"years,omitempty"` } diff --git a/pkg/apis/monitoring/v1alpha1/prometheusagent_types.go b/pkg/apis/monitoring/v1alpha1/prometheusagent_types.go index 5172a5ce8e8..e9dfdad6959 100644 --- a/pkg/apis/monitoring/v1alpha1/prometheusagent_types.go +++ b/pkg/apis/monitoring/v1alpha1/prometheusagent_types.go @@ -103,6 +103,11 @@ func (l *PrometheusAgentList) DeepCopyObject() runtime.Object { // +kubebuilder:validation:XValidation:rule="!(has(self.mode) && self.mode == 'DaemonSet' && has(self.persistentVolumeClaimRetentionPolicy))",message="persistentVolumeClaimRetentionPolicy cannot be set when mode is DaemonSet" // +kubebuilder:validation:XValidation:rule="!(has(self.mode) && self.mode == 'DaemonSet' && has(self.scrapeConfigSelector))",message="scrapeConfigSelector cannot be set when mode is DaemonSet" // +kubebuilder:validation:XValidation:rule="!(has(self.mode) && self.mode == 'DaemonSet' && has(self.probeSelector))",message="probeSelector cannot be set when mode is DaemonSet" +// +kubebuilder:validation:XValidation:rule="!(has(self.mode) && self.mode == 'DaemonSet' && has(self.scrapeConfigNamespaceSelector))",message="scrapeConfigNamespaceSelector cannot be set when mode is DaemonSet" +// +kubebuilder:validation:XValidation:rule="!(has(self.mode) && self.mode == 'DaemonSet' && has(self.probeNamespaceSelector))",message="probeNamespaceSelector cannot be set when mode is DaemonSet" +// +kubebuilder:validation:XValidation:rule="!(has(self.mode) && self.mode == 'DaemonSet' && has(self.serviceMonitorSelector))",message="serviceMonitorSelector cannot be set when mode is DaemonSet" +// +kubebuilder:validation:XValidation:rule="!(has(self.mode) && self.mode == 'DaemonSet' && has(self.serviceMonitorNamespaceSelector))",message="serviceMonitorNamespaceSelector cannot be set when mode is DaemonSet" +// +kubebuilder:validation:XValidation:rule="!(has(self.mode) && self.mode == 'DaemonSet' && has(self.additionalScrapeConfigs))",message="additionalScrapeConfigs cannot be set when mode is DaemonSet" type PrometheusAgentSpec struct { // mode defines how the Prometheus operator deploys the PrometheusAgent pod(s). // diff --git a/pkg/apis/monitoring/v1alpha1/scrapeconfig_types.go b/pkg/apis/monitoring/v1alpha1/scrapeconfig_types.go index 828a05abcce..972ac16dedc 100644 --- a/pkg/apis/monitoring/v1alpha1/scrapeconfig_types.go +++ b/pkg/apis/monitoring/v1alpha1/scrapeconfig_types.go @@ -40,7 +40,7 @@ type SDFile string type NamespaceDiscovery struct { // ownNamespace includes the namespace in which the Prometheus pod runs to the list of watched namespaces. // +optional - IncludeOwnNamespace *bool `json:"ownNamespace,omitempty"` + IncludeOwnNamespace *bool `json:"ownNamespace,omitempty"` // nolint:kubeapilinter // names defines a list of namespaces where to watch for resources. // If empty and `ownNamespace` isn't true, Prometheus watches for resources in all namespaces. // +listType=set @@ -55,7 +55,7 @@ type AttachMetadata struct { // Only valid for Pod, Endpoint and Endpointslice roles. // // +optional - Node *bool `json:"node,omitempty"` + Node *bool `json:"node,omitempty"` // nolint:kubeapilinter } // Filter name and value pairs to limit the discovery process to a subset of available resources. @@ -279,21 +279,22 @@ type ScrapeConfigSpec struct { // honorTimestamps defines whether Prometheus preserves the timestamps // when exposed by the target. // +optional - HonorTimestamps *bool `json:"honorTimestamps,omitempty"` + HonorTimestamps *bool `json:"honorTimestamps,omitempty"` // nolint:kubeapilinter // trackTimestampsStaleness defines whether Prometheus tracks staleness of // the metrics that have an explicit timestamp present in scraped data. // Has no effect if `honorTimestamps` is false. // It requires Prometheus >= v2.48.0. // // +optional - TrackTimestampsStaleness *bool `json:"trackTimestampsStaleness,omitempty"` + TrackTimestampsStaleness *bool `json:"trackTimestampsStaleness,omitempty"` // nolint:kubeapilinter // honorLabels defines when true the metric's labels when they collide // with the target's labels. // +optional - HonorLabels *bool `json:"honorLabels,omitempty"` + HonorLabels *bool `json:"honorLabels,omitempty"` // nolint:kubeapilinter // params defines optional HTTP URL parameters // +mapType:=atomic // +optional + //nolint:kubeapilinter Params map[string][]string `json:"params,omitempty"` // scheme defines the protocol scheme used for requests. // +optional @@ -304,10 +305,10 @@ type ScrapeConfigSpec struct { // // If unset, Prometheus uses true by default. // +optional - EnableCompression *bool `json:"enableCompression,omitempty"` + EnableCompression *bool `json:"enableCompression,omitempty"` // nolint:kubeapilinter // enableHTTP2 defines whether to enable HTTP2. // +optional - EnableHTTP2 *bool `json:"enableHTTP2,omitempty"` + EnableHTTP2 *bool `json:"enableHTTP2,omitempty"` // nolint:kubeapilinter // basicAuth defines information to use on every scrape request. // +optional BasicAuth *v1.BasicAuth `json:"basicAuth,omitempty"` @@ -384,6 +385,7 @@ type StaticConfig struct { // labels defines labels assigned to all metrics scraped from the targets. // +mapType:=atomic // +optional + //nolint:kubeapilinter Labels map[string]string `json:"labels,omitempty"` } @@ -437,10 +439,10 @@ type HTTPSDConfig struct { TLSConfig *v1.SafeTLSConfig `json:"tlsConfig,omitempty"` // followRedirects defines whether HTTP requests follow HTTP 3xx redirects. // +optional - FollowRedirects *bool `json:"followRedirects,omitempty"` + FollowRedirects *bool `json:"followRedirects,omitempty"` // nolint:kubeapilinter // enableHTTP2 defines whether to enable HTTP2. // +optional - EnableHTTP2 *bool `json:"enableHTTP2,omitempty"` + EnableHTTP2 *bool `json:"enableHTTP2,omitempty"` // nolint:kubeapilinter } // KubernetesSDConfig allows retrieving scrape targets from Kubernetes' REST API. @@ -488,10 +490,10 @@ type KubernetesSDConfig struct { v1.ProxyConfig `json:",inline"` // followRedirects defines whether HTTP requests follow HTTP 3xx redirects. // +optional - FollowRedirects *bool `json:"followRedirects,omitempty"` + FollowRedirects *bool `json:"followRedirects,omitempty"` // nolint:kubeapilinter // enableHTTP2 defines whether to enable HTTP2. // +optional - EnableHTTP2 *bool `json:"enableHTTP2,omitempty"` + EnableHTTP2 *bool `json:"enableHTTP2,omitempty"` // nolint:kubeapilinter // tlsConfig defines the TLS configuration to connect to the Kubernetes API. // +optional TLSConfig *v1.SafeTLSConfig `json:"tlsConfig,omitempty"` @@ -549,6 +551,7 @@ type ConsulSDConfig struct { // Starting with Consul 1.14, it is recommended to use `filter` with the `NodeMeta` selector instead. // +mapType:=atomic // +optional + //nolint:kubeapilinter NodeMeta map[string]string `json:"nodeMeta,omitempty"` // filter defines the filter expression used to filter the catalog results. // See https://www.consul.io/api-docs/catalog#list-services @@ -559,7 +562,7 @@ type ConsulSDConfig struct { // allowStale Consul results (see https://www.consul.io/api/features/consistency.html). Will reduce load on Consul. // If unset, Prometheus uses its default value. // +optional - AllowStale *bool `json:"allowStale,omitempty"` + AllowStale *bool `json:"allowStale,omitempty"` // nolint:kubeapilinter // refreshInterval defines the time after which the provided names are refreshed. // If not set, Prometheus uses its default value. // +optional @@ -580,10 +583,10 @@ type ConsulSDConfig struct { v1.ProxyConfig `json:",inline"` // followRedirects defines whether HTTP requests follow HTTP 3xx redirects. // +optional - FollowRedirects *bool `json:"followRedirects,omitempty"` + FollowRedirects *bool `json:"followRedirects,omitempty"` // nolint:kubeapilinter // enableHTTP2 defines whether to enable HTTP2. // +optional - EnableHttp2 *bool `json:"enableHTTP2,omitempty"` + EnableHttp2 *bool `json:"enableHTTP2,omitempty"` // nolint:kubeapilinter // tlsConfig defines the TLS configuration to connect to the Consul API. // +optional TLSConfig *v1.SafeTLSConfig `json:"tlsConfig,omitempty"` @@ -679,11 +682,11 @@ type EC2SDConfig struct { // followRedirects defines whether HTTP requests follow HTTP 3xx redirects. // It requires Prometheus >= v2.41.0 // +optional - FollowRedirects *bool `json:"followRedirects,omitempty"` + FollowRedirects *bool `json:"followRedirects,omitempty"` // nolint:kubeapilinter // enableHTTP2 defines whether to enable HTTP2. // It requires Prometheus >= v2.41.0 // +optional - EnableHTTP2 *bool `json:"enableHTTP2,omitempty"` + EnableHTTP2 *bool `json:"enableHTTP2,omitempty"` // nolint:kubeapilinter } // +kubebuilder:validation:Enum=OAuth;ManagedIdentity;SDK @@ -756,10 +759,10 @@ type AzureSDConfig struct { v1.ProxyConfig `json:",inline"` // followRedirects defines whether HTTP requests follow HTTP 3xx redirects. // +optional - FollowRedirects *bool `json:"followRedirects,omitempty"` + FollowRedirects *bool `json:"followRedirects,omitempty"` // nolint:kubeapilinter // enableHTTP2 defines whether to enable HTTP2. // +optional - EnableHTTP2 *bool `json:"enableHTTP2,omitempty"` + EnableHTTP2 *bool `json:"enableHTTP2,omitempty"` // nolint:kubeapilinter // tlsConfig defies the TLS configuration applying to the target HTTP endpoint. // +optional TLSConfig *v1.SafeTLSConfig `json:"tlsConfig,omitempty"` @@ -890,7 +893,7 @@ type OpenStackSDConfig struct { // allTenants defines whether the service discovery should list all instances for all projects. // It is only relevant for the 'instance' role and usually requires admin permissions. // +optional - AllTenants *bool `json:"allTenants,omitempty"` + AllTenants *bool `json:"allTenants,omitempty"` // nolint:kubeapilinter // refreshInterval defines the time after which the provided names are refreshed. // If not set, Prometheus uses its default value. // +optional @@ -927,10 +930,10 @@ type DigitalOceanSDConfig struct { v1.ProxyConfig `json:",inline"` // followRedirects defines whether HTTP requests follow HTTP 3xx redirects. // +optional - FollowRedirects *bool `json:"followRedirects,omitempty"` + FollowRedirects *bool `json:"followRedirects,omitempty"` // nolint:kubeapilinter // enableHTTP2 defines whether to enable HTTP2. // +optional - EnableHTTP2 *bool `json:"enableHTTP2,omitempty"` + EnableHTTP2 *bool `json:"enableHTTP2,omitempty"` // nolint:kubeapilinter // tlsConfig defines the TLS configuration to connect to the Consul API. // +optional TLSConfig *v1.SafeTLSConfig `json:"tlsConfig,omitempty"` @@ -982,10 +985,10 @@ type KumaSDConfig struct { OAuth2 *v1.OAuth2 `json:"oauth2,omitempty"` // followRedirects defines whether HTTP requests follow HTTP 3xx redirects. // +optional - FollowRedirects *bool `json:"followRedirects,omitempty"` + FollowRedirects *bool `json:"followRedirects,omitempty"` // nolint:kubeapilinter // enableHTTP2 defines whether to enable HTTP2. // +optional - EnableHTTP2 *bool `json:"enableHTTP2,omitempty"` + EnableHTTP2 *bool `json:"enableHTTP2,omitempty"` // nolint:kubeapilinter } // Eureka SD configurations allow retrieving scrape targets using the Eureka REST API. @@ -1016,10 +1019,10 @@ type EurekaSDConfig struct { v1.ProxyConfig `json:",inline"` // followRedirects defines whether HTTP requests follow HTTP 3xx redirects. // +optional - FollowRedirects *bool `json:"followRedirects,omitempty"` + FollowRedirects *bool `json:"followRedirects,omitempty"` // nolint:kubeapilinter // enableHTTP2 defines whether to enable HTTP2. // +optional - EnableHTTP2 *bool `json:"enableHTTP2,omitempty"` + EnableHTTP2 *bool `json:"enableHTTP2,omitempty"` // nolint:kubeapilinter // refreshInterval defines the time after which the provided names are refreshed. // If not set, Prometheus uses its default value. // +optional @@ -1056,7 +1059,7 @@ type DockerSDConfig struct { // It requires Prometheus >= v2.54.1. // // +optional - MatchFirstNetwork *bool `json:"matchFirstNetwork,omitempty"` + MatchFirstNetwork *bool `json:"matchFirstNetwork,omitempty"` // nolint:kubeapilinter // filters defines filters to limit the discovery process to a subset of the available resources. // +optional Filters Filters `json:"filters,omitempty"` @@ -1076,10 +1079,10 @@ type DockerSDConfig struct { OAuth2 *v1.OAuth2 `json:"oauth2,omitempty"` // followRedirects defines whether HTTP requests follow HTTP 3xx redirects. // +optional - FollowRedirects *bool `json:"followRedirects,omitempty"` + FollowRedirects *bool `json:"followRedirects,omitempty"` // nolint:kubeapilinter // enableHTTP2 defines whether to enable HTTP2. // +optional - EnableHTTP2 *bool `json:"enableHTTP2,omitempty"` + EnableHTTP2 *bool `json:"enableHTTP2,omitempty"` // nolint:kubeapilinter } // HetznerSDConfig allow retrieving scrape targets from Hetzner Cloud API and Robot API. @@ -1106,10 +1109,10 @@ type HetznerSDConfig struct { v1.ProxyConfig `json:",inline"` // followRedirects defines whether HTTP requests follow HTTP 3xx redirects. // +optional - FollowRedirects *bool `json:"followRedirects,omitempty"` + FollowRedirects *bool `json:"followRedirects,omitempty"` // nolint:kubeapilinter // enableHTTP2 defines whether to enable HTTP2. // +optional - EnableHTTP2 *bool `json:"enableHTTP2,omitempty"` + EnableHTTP2 *bool `json:"enableHTTP2,omitempty"` // nolint:kubeapilinter // tlsConfig defines the TLS configuration to connect to the Consul API. // +optional TLSConfig *v1.SafeTLSConfig `json:"tlsConfig,omitempty"` @@ -1136,7 +1139,7 @@ type NomadSDConfig struct { // allowStale defines the information to access the Nomad API. It is to be defined // as the Nomad documentation requires. // +optional - AllowStale *bool `json:"allowStale,omitempty"` + AllowStale *bool `json:"allowStale,omitempty"` // nolint:kubeapilinter // namespace defines the Nomad namespace to query for service discovery. // When specified, only resources within this namespace will be discovered. // +optional @@ -1176,10 +1179,10 @@ type NomadSDConfig struct { v1.ProxyConfig `json:",inline"` // followRedirects defines whether HTTP requests follow HTTP 3xx redirects. // +optional - FollowRedirects *bool `json:"followRedirects,omitempty"` + FollowRedirects *bool `json:"followRedirects,omitempty"` // nolint:kubeapilinter // enableHTTP2 defines whether to enable HTTP2. // +optional - EnableHTTP2 *bool `json:"enableHTTP2,omitempty"` + EnableHTTP2 *bool `json:"enableHTTP2,omitempty"` // nolint:kubeapilinter } // Service of the targets to retrieve. Must be `VPS` or `DedicatedServer`. @@ -1270,10 +1273,10 @@ type DockerSwarmSDConfig struct { TLSConfig *v1.SafeTLSConfig `json:"tlsConfig,omitempty"` // followRedirects defines whether HTTP requests follow HTTP 3xx redirects. // +optional - FollowRedirects *bool `json:"followRedirects,omitempty"` + FollowRedirects *bool `json:"followRedirects,omitempty"` // nolint:kubeapilinter // enableHTTP2 defines whether to enable HTTP2. // +optional - EnableHTTP2 *bool `json:"enableHTTP2,omitempty"` + EnableHTTP2 *bool `json:"enableHTTP2,omitempty"` // nolint:kubeapilinter } // LinodeSDConfig configurations allow retrieving scrape targets from Linode's Linode APIv4. @@ -1308,13 +1311,13 @@ type LinodeSDConfig struct { v1.ProxyConfig `json:",inline"` // followRedirects defines whether HTTP requests follow HTTP 3xx redirects. // +optional - FollowRedirects *bool `json:"followRedirects,omitempty"` + FollowRedirects *bool `json:"followRedirects,omitempty"` // nolint:kubeapilinter // tlsConfig defines the TLS configuration to connect to the Consul API. // +optional TLSConfig *v1.SafeTLSConfig `json:"tlsConfig,omitempty"` // enableHTTP2 defines whether to enable HTTP2. // +optional - EnableHTTP2 *bool `json:"enableHTTP2,omitempty"` + EnableHTTP2 *bool `json:"enableHTTP2,omitempty"` // nolint:kubeapilinter } // PuppetDBSDConfig configurations allow retrieving scrape targets from PuppetDB resources. @@ -1334,7 +1337,7 @@ type PuppetDBSDConfig struct { // Note: Enabling this exposes parameters in the Prometheus UI and API. Make sure // that you don't have secrets exposed as parameters if you enable this. // +optional - IncludeParameters *bool `json:"includeParameters,omitempty"` + IncludeParameters *bool `json:"includeParameters,omitempty"` // nolint:kubeapilinter // refreshInterval defines the time after which the provided names are refreshed. // If not set, Prometheus uses its default value. // +optional @@ -1362,10 +1365,10 @@ type PuppetDBSDConfig struct { TLSConfig *v1.SafeTLSConfig `json:"tlsConfig,omitempty"` // followRedirects defines whether HTTP requests follow HTTP 3xx redirects. // +optional - FollowRedirects *bool `json:"followRedirects,omitempty"` + FollowRedirects *bool `json:"followRedirects,omitempty"` // nolint:kubeapilinter // enableHTTP2 defines whether to enable HTTP2. // +optional - EnableHTTP2 *bool `json:"enableHTTP2,omitempty"` + EnableHTTP2 *bool `json:"enableHTTP2,omitempty"` // nolint:kubeapilinter } // LightSailSDConfig configurations allow retrieving scrape targets from AWS Lightsail instances. @@ -1416,10 +1419,10 @@ type LightSailSDConfig struct { TLSConfig *v1.SafeTLSConfig `json:"tlsConfig,omitempty"` // followRedirects defines whether HTTP requests follow HTTP 3xx redirects. // +optional - FollowRedirects *bool `json:"followRedirects,omitempty"` + FollowRedirects *bool `json:"followRedirects,omitempty"` // nolint:kubeapilinter // enableHTTP2 defines whether to enable HTTP2. // +optional - EnableHTTP2 *bool `json:"enableHTTP2,omitempty"` + EnableHTTP2 *bool `json:"enableHTTP2,omitempty"` // nolint:kubeapilinter } // Role of the targets to retrieve. Must be `Instance` or `Baremetal`. @@ -1480,10 +1483,10 @@ type ScalewaySDConfig struct { v1.ProxyConfig `json:",inline"` // followRedirects defines whether HTTP requests follow HTTP 3xx redirects. // +optional - FollowRedirects *bool `json:"followRedirects,omitempty"` + FollowRedirects *bool `json:"followRedirects,omitempty"` // nolint:kubeapilinter // enableHTTP2 defines whether to enable HTTP2. // +optional - EnableHTTP2 *bool `json:"enableHTTP2,omitempty"` + EnableHTTP2 *bool `json:"enableHTTP2,omitempty"` // nolint:kubeapilinter // tlsConfig defines the TLS configuration to connect to the Consul API. // +optional TLSConfig *v1.SafeTLSConfig `json:"tlsConfig,omitempty"` @@ -1515,10 +1518,10 @@ type IonosSDConfig struct { TLSConfig *v1.SafeTLSConfig `json:"tlsConfig,omitempty"` // followRedirects defines whether HTTP requests follow HTTP 3xx redirects. // +optional - FollowRedirects *bool `json:"followRedirects,omitempty"` + FollowRedirects *bool `json:"followRedirects,omitempty"` // nolint:kubeapilinter // enableHTTP2 defines whether to enable HTTP2. // +optional - EnableHTTP2 *bool `json:"enableHTTP2,omitempty"` + EnableHTTP2 *bool `json:"enableHTTP2,omitempty"` // nolint:kubeapilinter // oauth2 defines the configuration to use on every scrape request. // +optional OAuth2 *v1.OAuth2 `json:"oauth2,omitempty"` diff --git a/pkg/apis/monitoring/v1alpha1/zz_generated.deepcopy.go b/pkg/apis/monitoring/v1alpha1/zz_generated.deepcopy.go index f703c33a7ad..a83ae23b42b 100644 --- a/pkg/apis/monitoring/v1alpha1/zz_generated.deepcopy.go +++ b/pkg/apis/monitoring/v1alpha1/zz_generated.deepcopy.go @@ -30,6 +30,7 @@ func (in *AlertmanagerConfig) DeepCopyInto(out *AlertmanagerConfig) { out.TypeMeta = in.TypeMeta in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) in.Spec.DeepCopyInto(&out.Spec) + in.Status.DeepCopyInto(&out.Status) } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new AlertmanagerConfig. @@ -1794,6 +1795,11 @@ func (in *OpsGenieConfig) DeepCopyInto(out *OpsGenieConfig) { *out = new(corev1.SecretKeySelector) (*in).DeepCopyInto(*out) } + if in.APIURL != nil { + in, out := &in.APIURL, &out.APIURL + *out = new(URL) + **out = **in + } if in.UpdateAlerts != nil { in, out := &in.UpdateAlerts, &out.UpdateAlerts *out = new(bool) @@ -1859,6 +1865,46 @@ func (in *PagerDutyConfig) DeepCopyInto(out *PagerDutyConfig) { *out = new(corev1.SecretKeySelector) (*in).DeepCopyInto(*out) } + if in.URL != nil { + in, out := &in.URL, &out.URL + *out = new(URL) + **out = **in + } + if in.Client != nil { + in, out := &in.Client, &out.Client + *out = new(string) + **out = **in + } + if in.ClientURL != nil { + in, out := &in.ClientURL, &out.ClientURL + *out = new(URL) + **out = **in + } + if in.Description != nil { + in, out := &in.Description, &out.Description + *out = new(string) + **out = **in + } + if in.Severity != nil { + in, out := &in.Severity, &out.Severity + *out = new(string) + **out = **in + } + if in.Class != nil { + in, out := &in.Class, &out.Class + *out = new(string) + **out = **in + } + if in.Group != nil { + in, out := &in.Group, &out.Group + *out = new(string) + **out = **in + } + if in.Component != nil { + in, out := &in.Component, &out.Component + *out = new(string) + **out = **in + } if in.Details != nil { in, out := &in.Details, &out.Details *out = make([]KeyValue, len(*in)) @@ -1867,12 +1913,16 @@ func (in *PagerDutyConfig) DeepCopyInto(out *PagerDutyConfig) { if in.PagerDutyImageConfigs != nil { in, out := &in.PagerDutyImageConfigs, &out.PagerDutyImageConfigs *out = make([]PagerDutyImageConfig, len(*in)) - copy(*out, *in) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } } if in.PagerDutyLinkConfigs != nil { in, out := &in.PagerDutyLinkConfigs, &out.PagerDutyLinkConfigs *out = make([]PagerDutyLinkConfig, len(*in)) - copy(*out, *in) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } } if in.HTTPConfig != nil { in, out := &in.HTTPConfig, &out.HTTPConfig @@ -1884,6 +1934,11 @@ func (in *PagerDutyConfig) DeepCopyInto(out *PagerDutyConfig) { *out = new(string) **out = **in } + if in.Timeout != nil { + in, out := &in.Timeout, &out.Timeout + *out = new(monitoringv1.Duration) + **out = **in + } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PagerDutyConfig. @@ -1899,6 +1954,21 @@ func (in *PagerDutyConfig) DeepCopy() *PagerDutyConfig { // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *PagerDutyImageConfig) DeepCopyInto(out *PagerDutyImageConfig) { *out = *in + if in.Src != nil { + in, out := &in.Src, &out.Src + *out = new(string) + **out = **in + } + if in.Href != nil { + in, out := &in.Href, &out.Href + *out = new(URL) + **out = **in + } + if in.Alt != nil { + in, out := &in.Alt, &out.Alt + *out = new(string) + **out = **in + } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PagerDutyImageConfig. @@ -1914,6 +1984,16 @@ func (in *PagerDutyImageConfig) DeepCopy() *PagerDutyImageConfig { // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *PagerDutyLinkConfig) DeepCopyInto(out *PagerDutyLinkConfig) { *out = *in + if in.Href != nil { + in, out := &in.Href, &out.Href + *out = new(URL) + **out = **in + } + if in.Text != nil { + in, out := &in.Text, &out.Text + *out = new(string) + **out = **in + } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PagerDutyLinkConfig. @@ -2079,6 +2159,26 @@ func (in *PushoverConfig) DeepCopyInto(out *PushoverConfig) { *out = new(string) **out = **in } + if in.Title != nil { + in, out := &in.Title, &out.Title + *out = new(string) + **out = **in + } + if in.Message != nil { + in, out := &in.Message, &out.Message + *out = new(string) + **out = **in + } + if in.URL != nil { + in, out := &in.URL, &out.URL + *out = new(URL) + **out = **in + } + if in.URLTitle != nil { + in, out := &in.URLTitle, &out.URLTitle + *out = new(string) + **out = **in + } if in.TTL != nil { in, out := &in.TTL, &out.TTL *out = new(monitoringv1.Duration) @@ -2089,6 +2189,26 @@ func (in *PushoverConfig) DeepCopyInto(out *PushoverConfig) { *out = new(string) **out = **in } + if in.Sound != nil { + in, out := &in.Sound, &out.Sound + *out = new(string) + **out = **in + } + if in.Priority != nil { + in, out := &in.Priority, &out.Priority + *out = new(string) + **out = **in + } + if in.Retry != nil { + in, out := &in.Retry, &out.Retry + *out = new(string) + **out = **in + } + if in.Expire != nil { + in, out := &in.Expire, &out.Expire + *out = new(string) + **out = **in + } if in.HTML != nil { in, out := &in.HTML, &out.HTML *out = new(bool) @@ -2917,10 +3037,30 @@ func (in *ScrapeConfigSpec) DeepCopy() *ScrapeConfigSpec { // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *SlackAction) DeepCopyInto(out *SlackAction) { *out = *in + if in.URL != nil { + in, out := &in.URL, &out.URL + *out = new(URL) + **out = **in + } + if in.Style != nil { + in, out := &in.Style, &out.Style + *out = new(string) + **out = **in + } + if in.Name != nil { + in, out := &in.Name, &out.Name + *out = new(string) + **out = **in + } + if in.Value != nil { + in, out := &in.Value, &out.Value + *out = new(string) + **out = **in + } if in.ConfirmField != nil { in, out := &in.ConfirmField, &out.ConfirmField *out = new(SlackConfirmationField) - **out = **in + (*in).DeepCopyInto(*out) } } @@ -2947,6 +3087,41 @@ func (in *SlackConfig) DeepCopyInto(out *SlackConfig) { *out = new(corev1.SecretKeySelector) (*in).DeepCopyInto(*out) } + if in.Channel != nil { + in, out := &in.Channel, &out.Channel + *out = new(string) + **out = **in + } + if in.Username != nil { + in, out := &in.Username, &out.Username + *out = new(string) + **out = **in + } + if in.Color != nil { + in, out := &in.Color, &out.Color + *out = new(string) + **out = **in + } + if in.Title != nil { + in, out := &in.Title, &out.Title + *out = new(string) + **out = **in + } + if in.TitleLink != nil { + in, out := &in.TitleLink, &out.TitleLink + *out = new(URL) + **out = **in + } + if in.Pretext != nil { + in, out := &in.Pretext, &out.Pretext + *out = new(string) + **out = **in + } + if in.Text != nil { + in, out := &in.Text, &out.Text + *out = new(string) + **out = **in + } if in.Fields != nil { in, out := &in.Fields, &out.Fields *out = make([]SlackField, len(*in)) @@ -2954,6 +3129,51 @@ func (in *SlackConfig) DeepCopyInto(out *SlackConfig) { (*in)[i].DeepCopyInto(&(*out)[i]) } } + if in.ShortFields != nil { + in, out := &in.ShortFields, &out.ShortFields + *out = new(bool) + **out = **in + } + if in.Footer != nil { + in, out := &in.Footer, &out.Footer + *out = new(string) + **out = **in + } + if in.Fallback != nil { + in, out := &in.Fallback, &out.Fallback + *out = new(string) + **out = **in + } + if in.CallbackID != nil { + in, out := &in.CallbackID, &out.CallbackID + *out = new(string) + **out = **in + } + if in.IconEmoji != nil { + in, out := &in.IconEmoji, &out.IconEmoji + *out = new(string) + **out = **in + } + if in.IconURL != nil { + in, out := &in.IconURL, &out.IconURL + *out = new(URL) + **out = **in + } + if in.ImageURL != nil { + in, out := &in.ImageURL, &out.ImageURL + *out = new(URL) + **out = **in + } + if in.ThumbURL != nil { + in, out := &in.ThumbURL, &out.ThumbURL + *out = new(URL) + **out = **in + } + if in.LinkNames != nil { + in, out := &in.LinkNames, &out.LinkNames + *out = new(bool) + **out = **in + } if in.MrkdwnIn != nil { in, out := &in.MrkdwnIn, &out.MrkdwnIn *out = make([]string, len(*in)) @@ -2971,6 +3191,11 @@ func (in *SlackConfig) DeepCopyInto(out *SlackConfig) { *out = new(HTTPConfig) (*in).DeepCopyInto(*out) } + if in.Timeout != nil { + in, out := &in.Timeout, &out.Timeout + *out = new(monitoringv1.Duration) + **out = **in + } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new SlackConfig. @@ -2986,6 +3211,21 @@ func (in *SlackConfig) DeepCopy() *SlackConfig { // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *SlackConfirmationField) DeepCopyInto(out *SlackConfirmationField) { *out = *in + if in.Title != nil { + in, out := &in.Title, &out.Title + *out = new(string) + **out = **in + } + if in.OkText != nil { + in, out := &in.OkText, &out.OkText + *out = new(string) + **out = **in + } + if in.DismissText != nil { + in, out := &in.DismissText, &out.DismissText + *out = new(string) + **out = **in + } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new SlackConfirmationField. @@ -3053,6 +3293,11 @@ func (in *TelegramConfig) DeepCopyInto(out *TelegramConfig) { *out = new(bool) **out = **in } + if in.APIURL != nil { + in, out := &in.APIURL, &out.APIURL + *out = new(URL) + **out = **in + } if in.BotToken != nil { in, out := &in.BotToken, &out.BotToken *out = new(corev1.SecretKeySelector) @@ -3158,6 +3403,31 @@ func (in *VictorOpsConfig) DeepCopyInto(out *VictorOpsConfig) { *out = new(corev1.SecretKeySelector) (*in).DeepCopyInto(*out) } + if in.APIURL != nil { + in, out := &in.APIURL, &out.APIURL + *out = new(URL) + **out = **in + } + if in.MessageType != nil { + in, out := &in.MessageType, &out.MessageType + *out = new(string) + **out = **in + } + if in.EntityDisplayName != nil { + in, out := &in.EntityDisplayName, &out.EntityDisplayName + *out = new(string) + **out = **in + } + if in.StateMessage != nil { + in, out := &in.StateMessage, &out.StateMessage + *out = new(string) + **out = **in + } + if in.MonitoringTool != nil { + in, out := &in.MonitoringTool, &out.MonitoringTool + *out = new(string) + **out = **in + } if in.CustomFields != nil { in, out := &in.CustomFields, &out.CustomFields *out = make([]KeyValue, len(*in)) @@ -3193,6 +3463,11 @@ func (in *WeChatConfig) DeepCopyInto(out *WeChatConfig) { *out = new(corev1.SecretKeySelector) (*in).DeepCopyInto(*out) } + if in.APIURL != nil { + in, out := &in.APIURL, &out.APIURL + *out = new(URL) + **out = **in + } if in.HTTPConfig != nil { in, out := &in.HTTPConfig, &out.HTTPConfig *out = new(HTTPConfig) @@ -3255,7 +3530,7 @@ func (in *WebhookConfig) DeepCopyInto(out *WebhookConfig) { } if in.URL != nil { in, out := &in.URL, &out.URL - *out = new(string) + *out = new(URL) **out = **in } if in.URLSecret != nil { diff --git a/pkg/apis/monitoring/v1beta1/alertmanager_config_types.go b/pkg/apis/monitoring/v1beta1/alertmanager_config_types.go index 38b4ec820ed..f43068e4281 100644 --- a/pkg/apis/monitoring/v1beta1/alertmanager_config_types.go +++ b/pkg/apis/monitoring/v1beta1/alertmanager_config_types.go @@ -29,6 +29,7 @@ import ( apiextensionsv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" + "k8s.io/utils/ptr" ) const ( @@ -42,6 +43,7 @@ const ( // +genclient // +k8s:openapi-gen=true // +kubebuilder:resource:categories="prometheus-operator",shortName="amcfg" +// +kubebuilder:subresource:status // The `AlertmanagerConfig` custom resource definition (CRD) defines how `Alertmanager` objects process Prometheus alerts. It allows to specify alert grouping and routing, notification receivers and inhibition rules. // @@ -55,6 +57,14 @@ type AlertmanagerConfig struct { // spec defines the specification of AlertmanagerConfigSpec // +required Spec AlertmanagerConfigSpec `json:"spec"` + // status defines the status subresource. It is under active development and is updated only when the + // "StatusForConfigurationResources" feature gate is enabled. + // + // Most recent observed status of the ServiceMonitor. Read-only. + // More info: + // https://github.com/kubernetes/community/blob/master/contributors/devel/sig-architecture/api-conventions.md#spec-and-status + // +optional + Status monitoringv1.ConfigResourceStatus `json:"status,omitempty,omitzero"` } // AlertmanagerConfigList is a list of AlertmanagerConfig. @@ -125,7 +135,7 @@ type Route struct { // sibling nodes. It will always be overridden to true for the first-level // route by the Prometheus operator. // +optional - Continue bool `json:"continue,omitempty"` + Continue bool `json:"continue,omitempty"` // nolint:kubeapilinter // routes defines the child routes. // +optional Routes []apiextensionsv1.JSON `json:"routes,omitempty"` @@ -221,7 +231,7 @@ type Receiver struct { type PagerDutyConfig struct { // sendResolved defines whether or not to notify about resolved alerts. // +optional - SendResolved *bool `json:"sendResolved,omitempty"` + SendResolved *bool `json:"sendResolved,omitempty"` // nolint:kubeapilinter // routingKey defines the secret's key that contains the PagerDuty integration key (when using // Events API v2). Either this field or `serviceKey` needs to be defined. // The secret needs to be in the same namespace as the AlertmanagerConfig @@ -237,66 +247,83 @@ type PagerDutyConfig struct { ServiceKey *SecretKeySelector `json:"serviceKey,omitempty"` // url defines the URL to send requests to. // +optional - URL string `json:"url,omitempty"` + URL *URL `json:"url,omitempty"` // client defines the client identification. + // +kubebuilder:validation:MinLength=1 // +optional - Client string `json:"client,omitempty"` + Client *string `json:"client,omitempty"` // clientURL defines the backlink to the sender of notification. // +optional - ClientURL string `json:"clientURL,omitempty"` + ClientURL *URL `json:"clientURL,omitempty"` // description of the incident. + // +kubebuilder:validation:MinLength=1 // +optional - Description string `json:"description,omitempty"` + Description *string `json:"description,omitempty"` // severity of the incident. + // +kubebuilder:validation:MinLength=1 // +optional - Severity string `json:"severity,omitempty"` + Severity *string `json:"severity,omitempty"` // class defines the class/type of the event. + // +kubebuilder:validation:MinLength=1 // +optional - Class string `json:"class,omitempty"` + Class *string `json:"class,omitempty"` // group defines a cluster or grouping of sources. + // +kubebuilder:validation:MinLength=1 // +optional - Group string `json:"group,omitempty"` + Group *string `json:"group,omitempty"` // component defines the part or component of the affected system that is broken. + // +kubebuilder:validation:MinLength=1 // +optional - Component string `json:"component,omitempty"` + Component *string `json:"component,omitempty"` // details defines the arbitrary key/value pairs that provide further detail about the incident. + // +listType=atomic // +optional Details []KeyValue `json:"details,omitempty"` // pagerDutyImageConfigs defines a list of image details to attach that provide further detail about an incident. + // +listType=atomic // +optional PagerDutyImageConfigs []PagerDutyImageConfig `json:"pagerDutyImageConfigs,omitempty"` // pagerDutyLinkConfigs defines a list of link details to attach that provide further detail about an incident. + // +listType=atomic // +optional PagerDutyLinkConfigs []PagerDutyLinkConfig `json:"pagerDutyLinkConfigs,omitempty"` // httpConfig defines the HTTP client configuration. // +optional HTTPConfig *HTTPConfig `json:"httpConfig,omitempty"` // source defines the unique location of the affected system. + // +kubebuilder:validation:MinLength=1 + // +optional + Source *string `json:"source,omitempty"` + // timeout is the maximum time allowed to invoke the pagerduty + // It requires Alertmanager >= v0.30.0. // +optional - Source *string `yaml:"source,omitempty" json:"source,omitempty"` + Timeout *monitoringv1.Duration `json:"timeout,omitempty"` } // PagerDutyImageConfig attaches images to an incident type PagerDutyImageConfig struct { // src of the image being attached to the incident + // +kubebuilder:validation:MinLength=1 // +optional - Src string `json:"src,omitempty"` + Src *string `json:"src,omitempty"` // href defines the optional URL; makes the image a clickable link. // +optional - Href string `json:"href,omitempty"` + Href *URL `json:"href,omitempty"` // alt is the optional alternative text for the image. + // +kubebuilder:validation:MinLength=1 // +optional - Alt string `json:"alt,omitempty"` + Alt *string `json:"alt,omitempty"` } // PagerDutyLinkConfig attaches text links to an incident type PagerDutyLinkConfig struct { // href defines the URL of the link to be attached // +optional - Href string `json:"href,omitempty"` + Href *URL `json:"href,omitempty"` // alt defines the text that describes the purpose of the link, and can be used as the link's text. + // +kubebuilder:validation:MinLength=1 // +optional - Text string `json:"alt,omitempty"` + Text *string `json:"alt,omitempty"` } // DiscordConfig configures notifications via Discord. @@ -304,7 +331,7 @@ type PagerDutyLinkConfig struct { type DiscordConfig struct { // sendResolved defines whether or not to notify about resolved alerts. // +optional - SendResolved *bool `json:"sendResolved,omitempty"` + SendResolved *bool `json:"sendResolved,omitempty"` // nolint:kubeapilinter // apiURL defines the secret's key that contains the Discord webhook URL. // The secret needs to be in the same namespace as the AlertmanagerConfig // object and accessible by the Prometheus Operator. @@ -337,77 +364,99 @@ type DiscordConfig struct { type SlackConfig struct { // sendResolved defines whether or not to notify about resolved alerts. // +optional - SendResolved *bool `json:"sendResolved,omitempty"` + SendResolved *bool `json:"sendResolved,omitempty"` // nolint:kubeapilinter // apiURL defines the secret's key that contains the Slack webhook URL. // The secret needs to be in the same namespace as the AlertmanagerConfig // object and accessible by the Prometheus Operator. // +optional APIURL *SecretKeySelector `json:"apiURL,omitempty"` // channel defines the channel or user to send notifications to. + // +kubebuilder:validation:MinLength=1 // +optional - Channel string `json:"channel,omitempty"` + Channel *string `json:"channel,omitempty"` // username defines the slack bot user name. + // +kubebuilder:validation:MinLength=1 // +optional - Username string `json:"username,omitempty"` + Username *string `json:"username,omitempty"` // color defines the color of the left border of the Slack message attachment. // Can be a hex color code (e.g., "#ff0000") or a predefined color name. + // +kubebuilder:validation:MinLength=1 // +optional - Color string `json:"color,omitempty"` + Color *string `json:"color,omitempty"` // title defines the title text displayed in the Slack message attachment. + // +kubebuilder:validation:MinLength=1 // +optional - Title string `json:"title,omitempty"` + Title *string `json:"title,omitempty"` // titleLink defines the URL that the title will link to when clicked. // +optional - TitleLink string `json:"titleLink,omitempty"` + TitleLink *URL `json:"titleLink,omitempty"` // pretext defines optional text that appears above the message attachment block. + // +kubebuilder:validation:MinLength=1 // +optional - Pretext string `json:"pretext,omitempty"` + Pretext *string `json:"pretext,omitempty"` // text defines the main text content of the Slack message attachment. + // +kubebuilder:validation:MinLength=1 // +optional - Text string `json:"text,omitempty"` + Text *string `json:"text,omitempty"` // fields defines a list of Slack fields that are sent with each notification. + // +kubebuilder:validation:MinItems=1 + // +listType=atomic // +optional Fields []SlackField `json:"fields,omitempty"` // shortFields determines whether fields are displayed in a compact format. // When true, fields are shown side by side when possible. // +optional - ShortFields bool `json:"shortFields,omitempty"` + ShortFields *bool `json:"shortFields,omitempty"` // nolint:kubeapilinter // footer defines small text displayed at the bottom of the message attachment. + // +kubebuilder:validation:MinLength=1 // +optional - Footer string `json:"footer,omitempty"` + Footer *string `json:"footer,omitempty"` // fallback defines a plain-text summary of the attachment for clients that don't support attachments. + // +kubebuilder:validation:MinLength=1 // +optional - Fallback string `json:"fallback,omitempty"` + Fallback *string `json:"fallback,omitempty"` // callbackId defines an identifier for the message used in interactive components. + // +kubebuilder:validation:MinLength=1 // +optional - CallbackID string `json:"callbackId,omitempty"` + CallbackID *string `json:"callbackId,omitempty"` // iconEmoji defines the emoji to use as the bot's avatar (e.g., ":ghost:"). + // +kubebuilder:validation:MinLength=1 // +optional - IconEmoji string `json:"iconEmoji,omitempty"` + IconEmoji *string `json:"iconEmoji,omitempty"` // iconURL defines the URL to an image to use as the bot's avatar. // +optional - IconURL string `json:"iconURL,omitempty"` + IconURL *URL `json:"iconURL,omitempty"` // imageURL defines the URL to an image file that will be displayed inside the message attachment. // +optional - ImageURL string `json:"imageURL,omitempty"` + ImageURL *URL `json:"imageURL,omitempty"` // thumbURL defines the URL to an image file that will be displayed as a thumbnail // on the right side of the message attachment. // +optional - ThumbURL string `json:"thumbURL,omitempty"` + ThumbURL *URL `json:"thumbURL,omitempty"` // linkNames enables automatic linking of channel names and usernames in the message. // When true, @channel and @username will be converted to clickable links. // +optional - LinkNames bool `json:"linkNames,omitempty"` + LinkNames *bool `json:"linkNames,omitempty"` // nolint:kubeapilinter // mrkdwnIn defines which fields should be parsed as Slack markdown. // Valid values include "pretext", "text", and "fields". + // +listType=atomic + // +kubebuilder:validation:MinItems=1 + // +kubebuilder:validation:items:MinLength=1 // +optional MrkdwnIn []string `json:"mrkdwnIn,omitempty"` // actions defines a list of Slack actions that are sent with each notification. + // +kubebuilder:validation:MinItems=1 + // +listType=atomic // +optional Actions []SlackAction `json:"actions,omitempty"` // httpConfig defines the HTTP client configuration. // +optional HTTPConfig *HTTPConfig `json:"httpConfig,omitempty"` + // timeout defines the maximum time to wait for a webhook request to complete, + // before failing the request and allowing it to be retried. + // It requires Alertmanager >= v0.30.0. + // +optional + Timeout *monitoringv1.Duration `json:"timeout,omitempty"` } // Validate ensures SlackConfig is valid. @@ -445,19 +494,22 @@ type SlackAction struct { // url defines the URL to open when the action is triggered. // Only applicable for button-type actions. When set, clicking the button opens this URL. // +optional - URL string `json:"url,omitempty"` + URL *URL `json:"url,omitempty"` // style defines the visual appearance of the action element. // Valid values include "default", "primary" (green), and "danger" (red). + // +kubebuilder:validation:MinLength=1 // +optional - Style string `json:"style,omitempty"` + Style *string `json:"style,omitempty"` // name defines a unique identifier for the action within the message. // This value is sent back to your application when the action is triggered. + // +kubebuilder:validation:MinLength=1 // +optional - Name string `json:"name,omitempty"` + Name *string `json:"name,omitempty"` // value defines the payload sent when the action is triggered. // This data is included in the callback sent to your application. + // +kubebuilder:validation:MinLength=1 // +optional - Value string `json:"value,omitempty"` + Value *string `json:"value,omitempty"` // confirm defines an optional confirmation dialog that appears before the action is executed. // When set, users must confirm their intent before the action proceeds. // +optional @@ -474,7 +526,7 @@ func (sa *SlackAction) Validate() error { return errors.New("missing text in Slack action configuration") } - if sa.URL == "" && sa.Name == "" { + if ptr.Deref(sa.URL, "") == "" && ptr.Deref(sa.Name, "") == "" { return errors.New("missing name or url in Slack action configuration") } @@ -500,16 +552,19 @@ type SlackConfirmationField struct { Text string `json:"text"` // title defines the title text displayed at the top of the confirmation dialog. // When not specified, a default title will be used. + // +kubebuilder:validation:MinLength=1 // +optional - Title string `json:"title,omitempty"` + Title *string `json:"title,omitempty"` // okText defines the label for the confirmation button in the dialog. // When not specified, defaults to "Okay". This button proceeds with the action. + // +kubebuilder:validation:MinLength=1 // +optional - OkText string `json:"okText,omitempty"` + OkText *string `json:"okText,omitempty"` // dismissText defines the label for the cancel button in the dialog. // When not specified, defaults to "Cancel". This button cancels the action. + // +kubebuilder:validation:MinLength=1 // +optional - DismissText string `json:"dismissText,omitempty"` + DismissText *string `json:"dismissText,omitempty"` } // Validate ensures SlackConfirmationField is valid. @@ -539,7 +594,7 @@ type SlackField struct { // When true, Slack may display this field side by side with other short fields. // When false or not specified, the field takes the full width of the message. // +optional - Short *bool `json:"short,omitempty"` + Short *bool `json:"short,omitempty"` // nolint:kubeapilinter } // Validate ensures SlackField is valid @@ -560,11 +615,11 @@ func (sf *SlackField) Validate() error { type WebhookConfig struct { // sendResolved defines whether or not to notify about resolved alerts. // +optional - SendResolved *bool `json:"sendResolved,omitempty"` + SendResolved *bool `json:"sendResolved,omitempty"` // nolint:kubeapilinter // url defines the URL to send HTTP POST requests to. // urlSecret takes precedence over url. One of urlSecret and url should be defined. // +optional - URL *string `json:"url,omitempty"` + URL *URL `json:"url,omitempty"` // urlSecret defines the secret's key that contains the webhook URL to send HTTP requests to. // urlSecret takes precedence over url. One of urlSecret and url should be defined. // The secret needs to be in the same namespace as the AlertmanagerConfig @@ -591,7 +646,7 @@ type WebhookConfig struct { type OpsGenieConfig struct { // sendResolved defines whether or not to notify about resolved alerts. // +optional - SendResolved *bool `json:"sendResolved,omitempty"` + SendResolved *bool `json:"sendResolved,omitempty"` // nolint:kubeapilinter // apiKey defines the secret's key that contains the OpsGenie API key. // The secret needs to be in the same namespace as the AlertmanagerConfig // object and accessible by the Prometheus Operator. @@ -600,7 +655,7 @@ type OpsGenieConfig struct { // apiURL defines the URL to send OpsGenie API requests to. // When not specified, defaults to the standard OpsGenie API endpoint. // +optional - APIURL string `json:"apiURL,omitempty"` + APIURL *URL `json:"apiURL,omitempty"` // message defines the alert text limited to 130 characters. // This appears as the main alert title in OpsGenie. // +optional @@ -742,12 +797,12 @@ type HTTPConfig struct { // followRedirects defines whether HTTP requests follow HTTP 3xx redirects. // When true, the client will automatically follow redirect responses. // +optional - FollowRedirects *bool `json:"followRedirects,omitempty"` + FollowRedirects *bool `json:"followRedirects,omitempty"` // nolint:kubeapilinter // enableHttp2 can be used to disable HTTP2. // // +optional - EnableHTTP2 *bool `json:"enableHttp2,omitempty"` + EnableHTTP2 *bool `json:"enableHttp2,omitempty"` // nolint:kubeapilinter } // WebexConfig configures notification via Cisco Webex @@ -755,7 +810,7 @@ type HTTPConfig struct { type WebexConfig struct { // sendResolved defines whether or not to notify about resolved alerts. // +optional - SendResolved *bool `json:"sendResolved,omitempty"` + SendResolved *bool `json:"sendResolved,omitempty"` // nolint:kubeapilinter // apiURL defines the Webex Teams API URL i.e. https://webexapis.com/v1/messages // +optional @@ -781,7 +836,7 @@ type WebexConfig struct { type WeChatConfig struct { // sendResolved defines whether or not to notify about resolved alerts. // +optional - SendResolved *bool `json:"sendResolved,omitempty"` + SendResolved *bool `json:"sendResolved,omitempty"` // nolint:kubeapilinter // apiSecret defines the secret's key that contains the WeChat API key. // The secret needs to be in the same namespace as the AlertmanagerConfig // object and accessible by the Prometheus Operator. @@ -790,7 +845,7 @@ type WeChatConfig struct { // apiURL defines the WeChat API URL. // When not specified, defaults to the standard WeChat Work API endpoint. // +optional - APIURL string `json:"apiURL,omitempty"` + APIURL *URL `json:"apiURL,omitempty"` // corpID defines the corp id for authentication. // This is the unique identifier for your WeChat Work organization. // +optional @@ -828,7 +883,7 @@ type WeChatConfig struct { type EmailConfig struct { // sendResolved defines whether or not to notify about resolved alerts. // +optional - SendResolved *bool `json:"sendResolved,omitempty"` + SendResolved *bool `json:"sendResolved,omitempty"` // nolint:kubeapilinter // to defines the email address to send notifications to. // This is the recipient address for alert notifications. // +optional @@ -879,7 +934,7 @@ type EmailConfig struct { // requireTLS defines the SMTP TLS requirement. // Note that Go does not support unencrypted connections to remote SMTP endpoints. // +optional - RequireTLS *bool `json:"requireTLS,omitempty"` + RequireTLS *bool `json:"requireTLS,omitempty"` // nolint:kubeapilinter // tlsConfig defines the TLS configuration for SMTP connections. // This includes settings for certificates, CA validation, and TLS protocol options. // +optional @@ -891,7 +946,7 @@ type EmailConfig struct { type VictorOpsConfig struct { // sendResolved defines whether or not to notify about resolved alerts. // +optional - SendResolved *bool `json:"sendResolved,omitempty"` + SendResolved *bool `json:"sendResolved,omitempty"` // nolint:kubeapilinter // apiKey defines the secret's key that contains the API key to use when talking to the VictorOps API. // The secret needs to be in the same namespace as the AlertmanagerConfig // object and accessible by the Prometheus Operator. @@ -900,29 +955,35 @@ type VictorOpsConfig struct { // apiUrl defines the VictorOps API URL. // When not specified, defaults to the standard VictorOps API endpoint. // +optional - APIURL string `json:"apiUrl,omitempty"` + APIURL *URL `json:"apiUrl,omitempty"` // routingKey defines a key used to map the alert to a team. // This determines which VictorOps team will receive the alert notification. - // +optional + // +kubebuilder:validation:MinLength=1 + // +required RoutingKey string `json:"routingKey"` // messageType describes the behavior of the alert. // Valid values are "CRITICAL", "WARNING", and "INFO". + // +kubebuilder:validation:MinLength=1 // +optional - MessageType string `json:"messageType,omitempty"` + MessageType *string `json:"messageType,omitempty"` // entityDisplayName contains a summary of the alerted problem. // This appears as the main title or identifier for the incident. + // +kubebuilder:validation:MinLength=1 // +optional - EntityDisplayName string `json:"entityDisplayName,omitempty"` + EntityDisplayName *string `json:"entityDisplayName,omitempty"` // stateMessage contains a long explanation of the alerted problem. // This provides detailed context about the incident. + // +kubebuilder:validation:MinLength=1 // +optional - StateMessage string `json:"stateMessage,omitempty"` + StateMessage *string `json:"stateMessage,omitempty"` // monitoringTool defines the monitoring tool the state message is from. // This helps identify the source system that generated the alert. + // +kubebuilder:validation:MinLength=1 // +optional - MonitoringTool string `json:"monitoringTool,omitempty"` + MonitoringTool *string `json:"monitoringTool,omitempty"` // customFields defines additional custom fields for notification. // These provide extra metadata that will be included with the VictorOps incident. + // +listType=atomic // +optional CustomFields []KeyValue `json:"customFields,omitempty"` // httpConfig defines the HTTP client's configuration for VictorOps API requests. @@ -935,7 +996,7 @@ type VictorOpsConfig struct { type PushoverConfig struct { // sendResolved defines whether or not to notify about resolved alerts. // +optional - SendResolved *bool `json:"sendResolved,omitempty"` + SendResolved *bool `json:"sendResolved,omitempty"` // nolint:kubeapilinter // userKey defines the secret's key that contains the recipient user's user key. // The secret needs to be in the same namespace as the AlertmanagerConfig // object and accessible by the Prometheus Operator. @@ -962,54 +1023,61 @@ type PushoverConfig struct { TokenFile *string `json:"tokenFile,omitempty"` // title defines the notification title displayed in the Pushover message. // This appears as the bold header text in the notification. + // +kubebuilder:validation:MinLength=1 // +optional - Title string `json:"title,omitempty"` + Title *string `json:"title,omitempty"` // message defines the notification message content. // This is the main body text of the Pushover notification. + // +kubebuilder:validation:MinLength=1 // +optional - Message string `json:"message,omitempty"` + Message *string `json:"message,omitempty"` // url defines a supplementary URL shown alongside the message. // This creates a clickable link within the Pushover notification. // +optional - URL string `json:"url,omitempty"` + URL *URL `json:"url,omitempty"` // urlTitle defines a title for the supplementary URL. // If not specified, the raw URL is shown instead. + // +kubebuilder:validation:MinLength=1 // +optional - URLTitle string `json:"urlTitle,omitempty"` + URLTitle *string `json:"urlTitle,omitempty"` // ttl defines the time to live for the alert notification. // This determines how long the notification remains active before expiring. // +optional TTL *monitoringv1.Duration `json:"ttl,omitempty"` // device defines the name of a specific device to send the notification to. // If not specified, the notification is sent to all user's devices. + // +kubebuilder:validation:MinLength=1 // +optional Device *string `json:"device,omitempty"` // sound defines the name of one of the sounds supported by device clients. // This overrides the user's default sound choice for this notification. + // +kubebuilder:validation:MinLength=1 // +optional - Sound string `json:"sound,omitempty"` + Sound *string `json:"sound,omitempty"` // priority defines the notification priority level. // See https://pushover.net/api#priority for valid values and behavior. + // +kubebuilder:validation:MinLength=1 // +optional - Priority string `json:"priority,omitempty"` + Priority *string `json:"priority,omitempty"` // retry defines how often the Pushover servers will send the same notification to the user. // Must be at least 30 seconds. Only applies to priority 2 notifications. // +kubebuilder:validation:Pattern=`^(([0-9]+)y)?(([0-9]+)w)?(([0-9]+)d)?(([0-9]+)h)?(([0-9]+)m)?(([0-9]+)s)?(([0-9]+)ms)?$` // +optional - Retry string `json:"retry,omitempty"` + Retry *string `json:"retry,omitempty"` // expire defines how long your notification will continue to be retried for, // unless the user acknowledges the notification. Only applies to priority 2 notifications. // +kubebuilder:validation:Pattern=`^(([0-9]+)y)?(([0-9]+)w)?(([0-9]+)d)?(([0-9]+)h)?(([0-9]+)m)?(([0-9]+)s)?(([0-9]+)ms)?$` // +optional - Expire string `json:"expire,omitempty"` + Expire *string `json:"expire,omitempty"` // html defines whether notification message is HTML or plain text. // When true, the message can include HTML formatting tags. + // html and monospace formatting are mutually exclusive. // +optional - HTML *bool `json:"html,omitempty"` + HTML *bool `json:"html,omitempty"` //nolint:kubeapilinter // monospace optional HTML/monospace formatting for the message, see https://pushover.net/api#html // html and monospace formatting are mutually exclusive. // +optional - Monospace *bool `json:"monospace,omitempty"` + Monospace *bool `json:"monospace,omitempty"` //nolint:kubeapilinter // httpConfig defines the HTTP client configuration for Pushover API requests. // +optional HTTPConfig *HTTPConfig `json:"httpConfig,omitempty"` @@ -1020,7 +1088,7 @@ type PushoverConfig struct { type SNSConfig struct { // sendResolved defines whether or not to notify about resolved alerts. // +optional - SendResolved *bool `json:"sendResolved,omitempty"` + SendResolved *bool `json:"sendResolved,omitempty"` // nolint:kubeapilinter // apiURL defines the SNS API URL, e.g. https://sns.us-east-2.amazonaws.com. // If not specified, the SNS API URL from the SNS SDK will be used. // +optional @@ -1052,6 +1120,7 @@ type SNSConfig struct { // attributes defines SNS message attributes as key-value pairs. // These provide additional metadata that can be used for message filtering and routing. // +optional + //nolint:kubeapilinter Attributes map[string]string `json:"attributes,omitempty"` // httpConfig defines the HTTP client configuration for SNS API requests. // +optional @@ -1063,11 +1132,11 @@ type SNSConfig struct { type TelegramConfig struct { // sendResolved defines whether or not to notify about resolved alerts. // +optional - SendResolved *bool `json:"sendResolved,omitempty"` + SendResolved *bool `json:"sendResolved,omitempty"` // nolint:kubeapilinter // apiURL defines the Telegram API URL, e.g. https://api.telegram.org. // If not specified, the default Telegram API URL will be used. // +optional - APIURL string `json:"apiURL,omitempty"` + APIURL *URL `json:"apiURL,omitempty"` // botToken defines the Telegram bot token. It is mutually exclusive with `botTokenFile`. // The secret needs to be in the same namespace as the AlertmanagerConfig // object and accessible by the Prometheus Operator. @@ -1096,7 +1165,7 @@ type TelegramConfig struct { // disableNotifications controls whether Telegram notifications are sent silently. // When true, users will receive the message without notification sounds. // +optional - DisableNotifications *bool `json:"disableNotifications,omitempty"` + DisableNotifications *bool `json:"disableNotifications,omitempty"` // nolint:kubeapilinter // parseMode defines the parse mode for telegram message formatting. // Valid values are "MarkdownV2", "Markdown", and "HTML". // This determines how text formatting is interpreted in the message. @@ -1113,7 +1182,7 @@ type TelegramConfig struct { type MSTeamsConfig struct { // sendResolved defines whether or not to notify about resolved alerts. // +optional - SendResolved *bool `json:"sendResolved,omitempty"` + SendResolved *bool `json:"sendResolved,omitempty"` // nolint:kubeapilinter // webhookUrl defines the MSTeams webhook URL for sending notifications. // This is the incoming webhook URL configured in your Teams channel. // +required @@ -1142,7 +1211,7 @@ type MSTeamsConfig struct { type MSTeamsV2Config struct { // sendResolved defines whether or not to notify about resolved alerts. // +optional - SendResolved *bool `json:"sendResolved,omitempty"` + SendResolved *bool `json:"sendResolved,omitempty"` // nolint:kubeapilinter // webhookURL defines the MSTeams incoming webhook URL for adaptive card notifications. // This webhook must support the newer adaptive cards format required by Teams flows. // +optional @@ -1167,7 +1236,7 @@ type MSTeamsV2Config struct { type RocketChatConfig struct { // sendResolved defines whether or not to notify about resolved alerts. // +optional - SendResolved *bool `json:"sendResolved,omitempty"` + SendResolved *bool `json:"sendResolved,omitempty"` // nolint:kubeapilinter // apiURL defines the API URL for RocketChat. // Defaults to https://open.rocket.chat/ if not specified. // +optional @@ -1222,7 +1291,7 @@ type RocketChatConfig struct { // shortFields defines whether to use short fields in the message layout. // When true, fields may be displayed side by side to save space. // +optional - ShortFields *bool `json:"shortFields,omitempty"` + ShortFields *bool `json:"shortFields,omitempty"` // nolint:kubeapilinter // imageURL defines the image URL to display within the message. // This embeds an image directly in the message attachment. // +optional @@ -1234,7 +1303,7 @@ type RocketChatConfig struct { // linkNames defines whether to enable automatic linking of usernames and channels. // When true, @username and #channel references become clickable links. // +optional - LinkNames *bool `json:"linkNames,omitempty"` + LinkNames *bool `json:"linkNames,omitempty"` // nolint:kubeapilinter // actions defines interactive actions to include in the message. // These appear as buttons that users can click to trigger responses. // +kubebuilder:validation:MinItems=1 @@ -1260,7 +1329,7 @@ type RocketChatFieldConfig struct { // short defines whether this field should be a short field. // When true, the field may be displayed inline with other short fields to save space. // +optional - Short *bool `json:"short,omitempty"` + Short *bool `json:"short,omitempty"` // nolint:kubeapilinter } // RocketChatActionConfig defines actions for RocketChat messages. diff --git a/pkg/apis/monitoring/v1beta1/conversion_from.go b/pkg/apis/monitoring/v1beta1/conversion_from.go index 8d2241b16a0..714dde3943f 100644 --- a/pkg/apis/monitoring/v1beta1/conversion_from.go +++ b/pkg/apis/monitoring/v1beta1/conversion_from.go @@ -198,7 +198,7 @@ func convertOpsGenieConfigFrom(in v1alpha1.OpsGenieConfig) OpsGenieConfig { return OpsGenieConfig{ SendResolved: in.SendResolved, APIKey: convertSecretKeySelectorFrom(in.APIKey), - APIURL: in.APIURL, + APIURL: (*URL)(in.APIURL), Message: in.Message, Description: in.Description, Source: in.Source, @@ -219,7 +219,7 @@ func convertPagerDutyImageConfigsFrom(in []v1alpha1.PagerDutyImageConfig) []Page for i := range in { out[i] = PagerDutyImageConfig{ Src: in[i].Src, - Href: in[i].Href, + Href: (*URL)(in[i].Href), Alt: in[i].Alt, } } @@ -232,7 +232,7 @@ func convertPagerDutyLinkConfigsFrom(in []v1alpha1.PagerDutyLinkConfig) []PagerD for i := range in { out[i] = PagerDutyLinkConfig{ - Href: in[i].Href, + Href: (*URL)(in[i].Href), Text: in[i].Text, } } @@ -245,9 +245,9 @@ func convertPagerDutyConfigFrom(in v1alpha1.PagerDutyConfig) PagerDutyConfig { SendResolved: in.SendResolved, RoutingKey: convertSecretKeySelectorFrom(in.RoutingKey), ServiceKey: convertSecretKeySelectorFrom(in.ServiceKey), - URL: in.URL, + URL: (*URL)(in.URL), Client: in.Client, - ClientURL: in.ClientURL, + ClientURL: (*URL)(in.ClientURL), Description: in.Description, Severity: in.Severity, Class: in.Class, @@ -258,6 +258,7 @@ func convertPagerDutyConfigFrom(in v1alpha1.PagerDutyConfig) PagerDutyConfig { PagerDutyLinkConfigs: convertPagerDutyLinkConfigsFrom(in.PagerDutyLinkConfigs), HTTPConfig: convertHTTPConfigFrom(in.HTTPConfig), Source: in.Source, + Timeout: in.Timeout, } } @@ -348,7 +349,7 @@ func convertSlackActionsFrom(in []v1alpha1.SlackAction) []SlackAction { out[i] = SlackAction{ Type: in[i].Type, Text: in[i].Text, - URL: in[i].URL, + URL: (*URL)(in[i].URL), Style: in[i].Style, Name: in[i].Name, Value: in[i].Value, @@ -374,7 +375,7 @@ func convertSlackConfigFrom(in v1alpha1.SlackConfig) SlackConfig { Username: in.Username, Color: in.Color, Title: in.Title, - TitleLink: in.TitleLink, + TitleLink: (*URL)(in.TitleLink), Pretext: in.Pretext, Text: in.Text, Fields: convertSlackFieldsFrom(in.Fields), @@ -383,13 +384,14 @@ func convertSlackConfigFrom(in v1alpha1.SlackConfig) SlackConfig { Fallback: in.Fallback, CallbackID: in.CallbackID, IconEmoji: in.IconEmoji, - IconURL: in.IconURL, - ImageURL: in.ImageURL, - ThumbURL: in.ThumbURL, + IconURL: (*URL)(in.IconURL), + ImageURL: (*URL)(in.ImageURL), + ThumbURL: (*URL)(in.ThumbURL), LinkNames: in.LinkNames, MrkdwnIn: in.MrkdwnIn, Actions: convertSlackActionsFrom(in.Actions), HTTPConfig: convertHTTPConfigFrom(in.HTTPConfig), + Timeout: in.Timeout, } } @@ -406,7 +408,7 @@ func convertWebexConfigFrom(in v1alpha1.WebexConfig) WebexConfig { func convertWebhookConfigFrom(in v1alpha1.WebhookConfig) WebhookConfig { return WebhookConfig{ SendResolved: in.SendResolved, - URL: in.URL, + URL: (*URL)(in.URL), URLSecret: convertSecretKeySelectorFrom(in.URLSecret), HTTPConfig: convertHTTPConfigFrom(in.HTTPConfig), MaxAlerts: in.MaxAlerts, @@ -418,7 +420,7 @@ func convertWeChatConfigFrom(in v1alpha1.WeChatConfig) WeChatConfig { return WeChatConfig{ SendResolved: in.SendResolved, APISecret: convertSecretKeySelectorFrom(in.APISecret), - APIURL: in.APIURL, + APIURL: (*URL)(in.APIURL), CorpID: in.CorpID, AgentID: in.AgentID, ToUser: in.ToUser, @@ -453,7 +455,7 @@ func convertVictorOpsConfigFrom(in v1alpha1.VictorOpsConfig) VictorOpsConfig { return VictorOpsConfig{ SendResolved: in.SendResolved, APIKey: convertSecretKeySelectorFrom(in.APIKey), - APIURL: in.APIURL, + APIURL: (*URL)(in.APIURL), RoutingKey: in.RoutingKey, MessageType: in.MessageType, EntityDisplayName: in.EntityDisplayName, @@ -473,7 +475,7 @@ func convertPushoverConfigFrom(in v1alpha1.PushoverConfig) PushoverConfig { TokenFile: in.TokenFile, Title: in.Title, Message: in.Message, - URL: in.URL, + URL: (*URL)(in.URL), URLTitle: in.URLTitle, Device: in.Device, Sound: in.Sound, @@ -504,7 +506,7 @@ func convertSNSConfigFrom(in v1alpha1.SNSConfig) SNSConfig { func convertTelegramConfigFrom(in v1alpha1.TelegramConfig) TelegramConfig { return TelegramConfig{ SendResolved: in.SendResolved, - APIURL: in.APIURL, + APIURL: (*URL)(in.APIURL), BotToken: convertSecretKeySelectorFrom(in.BotToken), BotTokenFile: in.BotTokenFile, ChatID: in.ChatID, diff --git a/pkg/apis/monitoring/v1beta1/conversion_to.go b/pkg/apis/monitoring/v1beta1/conversion_to.go index 2a9d2afe484..931b5373b9e 100644 --- a/pkg/apis/monitoring/v1beta1/conversion_to.go +++ b/pkg/apis/monitoring/v1beta1/conversion_to.go @@ -194,7 +194,7 @@ func convertOpsGenieConfigTo(in OpsGenieConfig) v1alpha1.OpsGenieConfig { return v1alpha1.OpsGenieConfig{ SendResolved: in.SendResolved, APIKey: convertSecretKeySelectorTo(in.APIKey), - APIURL: in.APIURL, + APIURL: (*v1alpha1.URL)(in.APIURL), Message: in.Message, Description: in.Description, Source: in.Source, @@ -215,7 +215,7 @@ func convertPagerDutyImageConfigsTo(in []PagerDutyImageConfig) []v1alpha1.PagerD for i := range in { out[i] = v1alpha1.PagerDutyImageConfig{ Src: in[i].Src, - Href: in[i].Href, + Href: (*v1alpha1.URL)(in[i].Href), Alt: in[i].Alt, } } @@ -228,7 +228,7 @@ func convertPagerDutyLinkConfigsTo(in []PagerDutyLinkConfig) []v1alpha1.PagerDut for i := range in { out[i] = v1alpha1.PagerDutyLinkConfig{ - Href: in[i].Href, + Href: (*v1alpha1.URL)(in[i].Href), Text: in[i].Text, } } @@ -241,9 +241,9 @@ func convertPagerDutyConfigTo(in PagerDutyConfig) v1alpha1.PagerDutyConfig { SendResolved: in.SendResolved, RoutingKey: convertSecretKeySelectorTo(in.RoutingKey), ServiceKey: convertSecretKeySelectorTo(in.ServiceKey), - URL: in.URL, + URL: (*v1alpha1.URL)(in.URL), Client: in.Client, - ClientURL: in.ClientURL, + ClientURL: (*v1alpha1.URL)(in.ClientURL), Description: in.Description, Severity: in.Severity, Class: in.Class, @@ -254,6 +254,7 @@ func convertPagerDutyConfigTo(in PagerDutyConfig) v1alpha1.PagerDutyConfig { PagerDutyLinkConfigs: convertPagerDutyLinkConfigsTo(in.PagerDutyLinkConfigs), HTTPConfig: convertHTTPConfigTo(in.HTTPConfig), Source: in.Source, + Timeout: in.Timeout, } } @@ -344,7 +345,7 @@ func convertSlackActionsTo(in []SlackAction) []v1alpha1.SlackAction { out[i] = v1alpha1.SlackAction{ Type: in[i].Type, Text: in[i].Text, - URL: in[i].URL, + URL: (*v1alpha1.URL)(in[i].URL), Style: in[i].Style, Name: in[i].Name, Value: in[i].Value, @@ -370,7 +371,7 @@ func convertSlackConfigTo(in SlackConfig) v1alpha1.SlackConfig { Username: in.Username, Color: in.Color, Title: in.Title, - TitleLink: in.TitleLink, + TitleLink: (*v1alpha1.URL)(in.TitleLink), Pretext: in.Pretext, Text: in.Text, Fields: convertSlackFieldsTo(in.Fields), @@ -379,13 +380,14 @@ func convertSlackConfigTo(in SlackConfig) v1alpha1.SlackConfig { Fallback: in.Fallback, CallbackID: in.CallbackID, IconEmoji: in.IconEmoji, - IconURL: in.IconURL, - ImageURL: in.ImageURL, - ThumbURL: in.ThumbURL, + IconURL: (*v1alpha1.URL)(in.IconURL), + ImageURL: (*v1alpha1.URL)(in.ImageURL), + ThumbURL: (*v1alpha1.URL)(in.ThumbURL), LinkNames: in.LinkNames, MrkdwnIn: in.MrkdwnIn, Actions: convertSlackActionsTo(in.Actions), HTTPConfig: convertHTTPConfigTo(in.HTTPConfig), + Timeout: in.Timeout, } } @@ -402,7 +404,7 @@ func convertWebexConfigTo(in WebexConfig) v1alpha1.WebexConfig { func convertWebhookConfigTo(in WebhookConfig) v1alpha1.WebhookConfig { return v1alpha1.WebhookConfig{ SendResolved: in.SendResolved, - URL: in.URL, + URL: (*v1alpha1.URL)(in.URL), URLSecret: convertSecretKeySelectorTo(in.URLSecret), HTTPConfig: convertHTTPConfigTo(in.HTTPConfig), MaxAlerts: in.MaxAlerts, @@ -414,7 +416,7 @@ func convertWeChatConfigTo(in WeChatConfig) v1alpha1.WeChatConfig { return v1alpha1.WeChatConfig{ SendResolved: in.SendResolved, APISecret: convertSecretKeySelectorTo(in.APISecret), - APIURL: in.APIURL, + APIURL: (*v1alpha1.URL)(in.APIURL), CorpID: in.CorpID, AgentID: in.AgentID, ToUser: in.ToUser, @@ -449,7 +451,7 @@ func convertVictorOpsConfigTo(in VictorOpsConfig) v1alpha1.VictorOpsConfig { return v1alpha1.VictorOpsConfig{ SendResolved: in.SendResolved, APIKey: convertSecretKeySelectorTo(in.APIKey), - APIURL: in.APIURL, + APIURL: (*v1alpha1.URL)(in.APIURL), RoutingKey: in.RoutingKey, MessageType: in.MessageType, EntityDisplayName: in.EntityDisplayName, @@ -469,7 +471,7 @@ func convertPushoverConfigTo(in PushoverConfig) v1alpha1.PushoverConfig { TokenFile: in.TokenFile, Title: in.Title, Message: in.Message, - URL: in.URL, + URL: (*v1alpha1.URL)(in.URL), URLTitle: in.URLTitle, Device: in.Device, Sound: in.Sound, @@ -500,7 +502,7 @@ func convertSNSConfigTo(in SNSConfig) v1alpha1.SNSConfig { func convertTelegramConfigTo(in TelegramConfig) v1alpha1.TelegramConfig { return v1alpha1.TelegramConfig{ SendResolved: in.SendResolved, - APIURL: in.APIURL, + APIURL: (*v1alpha1.URL)(in.APIURL), BotToken: convertSecretKeySelectorTo(in.BotToken), BotTokenFile: in.BotTokenFile, ChatID: in.ChatID, diff --git a/pkg/apis/monitoring/v1beta1/zz_generated.deepcopy.go b/pkg/apis/monitoring/v1beta1/zz_generated.deepcopy.go index 2b7c061ff6b..fbb8f218333 100644 --- a/pkg/apis/monitoring/v1beta1/zz_generated.deepcopy.go +++ b/pkg/apis/monitoring/v1beta1/zz_generated.deepcopy.go @@ -30,6 +30,7 @@ func (in *AlertmanagerConfig) DeepCopyInto(out *AlertmanagerConfig) { out.TypeMeta = in.TypeMeta in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) in.Spec.DeepCopyInto(&out.Spec) + in.Status.DeepCopyInto(&out.Status) } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new AlertmanagerConfig. @@ -438,6 +439,11 @@ func (in *OpsGenieConfig) DeepCopyInto(out *OpsGenieConfig) { *out = new(SecretKeySelector) **out = **in } + if in.APIURL != nil { + in, out := &in.APIURL, &out.APIURL + *out = new(URL) + **out = **in + } if in.Details != nil { in, out := &in.Details, &out.Details *out = make([]KeyValue, len(*in)) @@ -498,6 +504,46 @@ func (in *PagerDutyConfig) DeepCopyInto(out *PagerDutyConfig) { *out = new(SecretKeySelector) **out = **in } + if in.URL != nil { + in, out := &in.URL, &out.URL + *out = new(URL) + **out = **in + } + if in.Client != nil { + in, out := &in.Client, &out.Client + *out = new(string) + **out = **in + } + if in.ClientURL != nil { + in, out := &in.ClientURL, &out.ClientURL + *out = new(URL) + **out = **in + } + if in.Description != nil { + in, out := &in.Description, &out.Description + *out = new(string) + **out = **in + } + if in.Severity != nil { + in, out := &in.Severity, &out.Severity + *out = new(string) + **out = **in + } + if in.Class != nil { + in, out := &in.Class, &out.Class + *out = new(string) + **out = **in + } + if in.Group != nil { + in, out := &in.Group, &out.Group + *out = new(string) + **out = **in + } + if in.Component != nil { + in, out := &in.Component, &out.Component + *out = new(string) + **out = **in + } if in.Details != nil { in, out := &in.Details, &out.Details *out = make([]KeyValue, len(*in)) @@ -506,12 +552,16 @@ func (in *PagerDutyConfig) DeepCopyInto(out *PagerDutyConfig) { if in.PagerDutyImageConfigs != nil { in, out := &in.PagerDutyImageConfigs, &out.PagerDutyImageConfigs *out = make([]PagerDutyImageConfig, len(*in)) - copy(*out, *in) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } } if in.PagerDutyLinkConfigs != nil { in, out := &in.PagerDutyLinkConfigs, &out.PagerDutyLinkConfigs *out = make([]PagerDutyLinkConfig, len(*in)) - copy(*out, *in) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } } if in.HTTPConfig != nil { in, out := &in.HTTPConfig, &out.HTTPConfig @@ -523,6 +573,11 @@ func (in *PagerDutyConfig) DeepCopyInto(out *PagerDutyConfig) { *out = new(string) **out = **in } + if in.Timeout != nil { + in, out := &in.Timeout, &out.Timeout + *out = new(monitoringv1.Duration) + **out = **in + } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PagerDutyConfig. @@ -538,6 +593,21 @@ func (in *PagerDutyConfig) DeepCopy() *PagerDutyConfig { // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *PagerDutyImageConfig) DeepCopyInto(out *PagerDutyImageConfig) { *out = *in + if in.Src != nil { + in, out := &in.Src, &out.Src + *out = new(string) + **out = **in + } + if in.Href != nil { + in, out := &in.Href, &out.Href + *out = new(URL) + **out = **in + } + if in.Alt != nil { + in, out := &in.Alt, &out.Alt + *out = new(string) + **out = **in + } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PagerDutyImageConfig. @@ -553,6 +623,16 @@ func (in *PagerDutyImageConfig) DeepCopy() *PagerDutyImageConfig { // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *PagerDutyLinkConfig) DeepCopyInto(out *PagerDutyLinkConfig) { *out = *in + if in.Href != nil { + in, out := &in.Href, &out.Href + *out = new(URL) + **out = **in + } + if in.Text != nil { + in, out := &in.Text, &out.Text + *out = new(string) + **out = **in + } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PagerDutyLinkConfig. @@ -593,6 +673,26 @@ func (in *PushoverConfig) DeepCopyInto(out *PushoverConfig) { *out = new(string) **out = **in } + if in.Title != nil { + in, out := &in.Title, &out.Title + *out = new(string) + **out = **in + } + if in.Message != nil { + in, out := &in.Message, &out.Message + *out = new(string) + **out = **in + } + if in.URL != nil { + in, out := &in.URL, &out.URL + *out = new(URL) + **out = **in + } + if in.URLTitle != nil { + in, out := &in.URLTitle, &out.URLTitle + *out = new(string) + **out = **in + } if in.TTL != nil { in, out := &in.TTL, &out.TTL *out = new(monitoringv1.Duration) @@ -603,6 +703,26 @@ func (in *PushoverConfig) DeepCopyInto(out *PushoverConfig) { *out = new(string) **out = **in } + if in.Sound != nil { + in, out := &in.Sound, &out.Sound + *out = new(string) + **out = **in + } + if in.Priority != nil { + in, out := &in.Priority, &out.Priority + *out = new(string) + **out = **in + } + if in.Retry != nil { + in, out := &in.Retry, &out.Retry + *out = new(string) + **out = **in + } + if in.Expire != nil { + in, out := &in.Expire, &out.Expire + *out = new(string) + **out = **in + } if in.HTML != nil { in, out := &in.HTML, &out.HTML *out = new(bool) @@ -1008,10 +1128,30 @@ func (in *SecretKeySelector) DeepCopy() *SecretKeySelector { // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *SlackAction) DeepCopyInto(out *SlackAction) { *out = *in + if in.URL != nil { + in, out := &in.URL, &out.URL + *out = new(URL) + **out = **in + } + if in.Style != nil { + in, out := &in.Style, &out.Style + *out = new(string) + **out = **in + } + if in.Name != nil { + in, out := &in.Name, &out.Name + *out = new(string) + **out = **in + } + if in.Value != nil { + in, out := &in.Value, &out.Value + *out = new(string) + **out = **in + } if in.ConfirmField != nil { in, out := &in.ConfirmField, &out.ConfirmField *out = new(SlackConfirmationField) - **out = **in + (*in).DeepCopyInto(*out) } } @@ -1038,6 +1178,41 @@ func (in *SlackConfig) DeepCopyInto(out *SlackConfig) { *out = new(SecretKeySelector) **out = **in } + if in.Channel != nil { + in, out := &in.Channel, &out.Channel + *out = new(string) + **out = **in + } + if in.Username != nil { + in, out := &in.Username, &out.Username + *out = new(string) + **out = **in + } + if in.Color != nil { + in, out := &in.Color, &out.Color + *out = new(string) + **out = **in + } + if in.Title != nil { + in, out := &in.Title, &out.Title + *out = new(string) + **out = **in + } + if in.TitleLink != nil { + in, out := &in.TitleLink, &out.TitleLink + *out = new(URL) + **out = **in + } + if in.Pretext != nil { + in, out := &in.Pretext, &out.Pretext + *out = new(string) + **out = **in + } + if in.Text != nil { + in, out := &in.Text, &out.Text + *out = new(string) + **out = **in + } if in.Fields != nil { in, out := &in.Fields, &out.Fields *out = make([]SlackField, len(*in)) @@ -1045,6 +1220,51 @@ func (in *SlackConfig) DeepCopyInto(out *SlackConfig) { (*in)[i].DeepCopyInto(&(*out)[i]) } } + if in.ShortFields != nil { + in, out := &in.ShortFields, &out.ShortFields + *out = new(bool) + **out = **in + } + if in.Footer != nil { + in, out := &in.Footer, &out.Footer + *out = new(string) + **out = **in + } + if in.Fallback != nil { + in, out := &in.Fallback, &out.Fallback + *out = new(string) + **out = **in + } + if in.CallbackID != nil { + in, out := &in.CallbackID, &out.CallbackID + *out = new(string) + **out = **in + } + if in.IconEmoji != nil { + in, out := &in.IconEmoji, &out.IconEmoji + *out = new(string) + **out = **in + } + if in.IconURL != nil { + in, out := &in.IconURL, &out.IconURL + *out = new(URL) + **out = **in + } + if in.ImageURL != nil { + in, out := &in.ImageURL, &out.ImageURL + *out = new(URL) + **out = **in + } + if in.ThumbURL != nil { + in, out := &in.ThumbURL, &out.ThumbURL + *out = new(URL) + **out = **in + } + if in.LinkNames != nil { + in, out := &in.LinkNames, &out.LinkNames + *out = new(bool) + **out = **in + } if in.MrkdwnIn != nil { in, out := &in.MrkdwnIn, &out.MrkdwnIn *out = make([]string, len(*in)) @@ -1062,6 +1282,11 @@ func (in *SlackConfig) DeepCopyInto(out *SlackConfig) { *out = new(HTTPConfig) (*in).DeepCopyInto(*out) } + if in.Timeout != nil { + in, out := &in.Timeout, &out.Timeout + *out = new(monitoringv1.Duration) + **out = **in + } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new SlackConfig. @@ -1077,6 +1302,21 @@ func (in *SlackConfig) DeepCopy() *SlackConfig { // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *SlackConfirmationField) DeepCopyInto(out *SlackConfirmationField) { *out = *in + if in.Title != nil { + in, out := &in.Title, &out.Title + *out = new(string) + **out = **in + } + if in.OkText != nil { + in, out := &in.OkText, &out.OkText + *out = new(string) + **out = **in + } + if in.DismissText != nil { + in, out := &in.DismissText, &out.DismissText + *out = new(string) + **out = **in + } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new SlackConfirmationField. @@ -1117,6 +1357,11 @@ func (in *TelegramConfig) DeepCopyInto(out *TelegramConfig) { *out = new(bool) **out = **in } + if in.APIURL != nil { + in, out := &in.APIURL, &out.APIURL + *out = new(URL) + **out = **in + } if in.BotToken != nil { in, out := &in.BotToken, &out.BotToken *out = new(SecretKeySelector) @@ -1244,6 +1489,31 @@ func (in *VictorOpsConfig) DeepCopyInto(out *VictorOpsConfig) { *out = new(SecretKeySelector) **out = **in } + if in.APIURL != nil { + in, out := &in.APIURL, &out.APIURL + *out = new(URL) + **out = **in + } + if in.MessageType != nil { + in, out := &in.MessageType, &out.MessageType + *out = new(string) + **out = **in + } + if in.EntityDisplayName != nil { + in, out := &in.EntityDisplayName, &out.EntityDisplayName + *out = new(string) + **out = **in + } + if in.StateMessage != nil { + in, out := &in.StateMessage, &out.StateMessage + *out = new(string) + **out = **in + } + if in.MonitoringTool != nil { + in, out := &in.MonitoringTool, &out.MonitoringTool + *out = new(string) + **out = **in + } if in.CustomFields != nil { in, out := &in.CustomFields, &out.CustomFields *out = make([]KeyValue, len(*in)) @@ -1279,6 +1549,11 @@ func (in *WeChatConfig) DeepCopyInto(out *WeChatConfig) { *out = new(SecretKeySelector) **out = **in } + if in.APIURL != nil { + in, out := &in.APIURL, &out.APIURL + *out = new(URL) + **out = **in + } if in.HTTPConfig != nil { in, out := &in.HTTPConfig, &out.HTTPConfig *out = new(HTTPConfig) @@ -1341,7 +1616,7 @@ func (in *WebhookConfig) DeepCopyInto(out *WebhookConfig) { } if in.URL != nil { in, out := &in.URL, &out.URL - *out = new(string) + *out = new(URL) **out = **in } if in.URLSecret != nil { diff --git a/pkg/client/applyconfiguration/monitoring/v1/alertmanagerglobalconfig.go b/pkg/client/applyconfiguration/monitoring/v1/alertmanagerglobalconfig.go index a9cd77c60a9..47a3582cfa2 100644 --- a/pkg/client/applyconfiguration/monitoring/v1/alertmanagerglobalconfig.go +++ b/pkg/client/applyconfiguration/monitoring/v1/alertmanagerglobalconfig.go @@ -24,19 +24,19 @@ import ( // AlertmanagerGlobalConfigApplyConfiguration represents a declarative configuration of the AlertmanagerGlobalConfig type for use // with apply. type AlertmanagerGlobalConfigApplyConfiguration struct { - SMTPConfig *GlobalSMTPConfigApplyConfiguration `json:"smtp,omitempty"` - ResolveTimeout *monitoringv1.Duration `json:"resolveTimeout,omitempty"` - HTTPConfig *HTTPConfigApplyConfiguration `json:"httpConfig,omitempty"` - SlackAPIURL *corev1.SecretKeySelector `json:"slackApiUrl,omitempty"` - OpsGenieAPIURL *corev1.SecretKeySelector `json:"opsGenieApiUrl,omitempty"` - OpsGenieAPIKey *corev1.SecretKeySelector `json:"opsGenieApiKey,omitempty"` - PagerdutyURL *monitoringv1.URL `json:"pagerdutyUrl,omitempty"` - TelegramConfig *GlobalTelegramConfigApplyConfiguration `json:"telegram,omitempty"` - JiraConfig *GlobalJiraConfigApplyConfiguration `json:"jira,omitempty"` - VictorOpsConfig *GlobalVictorOpsConfigApplyConfiguration `json:"victorops,omitempty"` - RocketChatConfig *GlobalRocketChatConfigApplyConfiguration `json:"rocketChat,omitempty"` - WebexConfig *GlobalWebexConfigApplyConfiguration `json:"webex,omitempty"` - WeChatConfig *GlobalWeChatConfigApplyConfiguration `json:"wechat,omitempty"` + SMTPConfig *GlobalSMTPConfigApplyConfiguration `json:"smtp,omitempty"` + ResolveTimeout *monitoringv1.Duration `json:"resolveTimeout,omitempty"` + HTTPConfigWithProxy *HTTPConfigWithProxyApplyConfiguration `json:"httpConfig,omitempty"` + SlackAPIURL *corev1.SecretKeySelector `json:"slackApiUrl,omitempty"` + OpsGenieAPIURL *corev1.SecretKeySelector `json:"opsGenieApiUrl,omitempty"` + OpsGenieAPIKey *corev1.SecretKeySelector `json:"opsGenieApiKey,omitempty"` + PagerdutyURL *monitoringv1.URL `json:"pagerdutyUrl,omitempty"` + TelegramConfig *GlobalTelegramConfigApplyConfiguration `json:"telegram,omitempty"` + JiraConfig *GlobalJiraConfigApplyConfiguration `json:"jira,omitempty"` + VictorOpsConfig *GlobalVictorOpsConfigApplyConfiguration `json:"victorops,omitempty"` + RocketChatConfig *GlobalRocketChatConfigApplyConfiguration `json:"rocketChat,omitempty"` + WebexConfig *GlobalWebexConfigApplyConfiguration `json:"webex,omitempty"` + WeChatConfig *GlobalWeChatConfigApplyConfiguration `json:"wechat,omitempty"` } // AlertmanagerGlobalConfigApplyConfiguration constructs a declarative configuration of the AlertmanagerGlobalConfig type for use with @@ -61,11 +61,11 @@ func (b *AlertmanagerGlobalConfigApplyConfiguration) WithResolveTimeout(value mo return b } -// WithHTTPConfig sets the HTTPConfig field in the declarative configuration to the given value +// WithHTTPConfigWithProxy sets the HTTPConfigWithProxy field in the declarative configuration to the given value // and returns the receiver, so that objects can be built by chaining "With" function invocations. -// If called multiple times, the HTTPConfig field is set to the value of the last call. -func (b *AlertmanagerGlobalConfigApplyConfiguration) WithHTTPConfig(value *HTTPConfigApplyConfiguration) *AlertmanagerGlobalConfigApplyConfiguration { - b.HTTPConfig = value +// If called multiple times, the HTTPConfigWithProxy field is set to the value of the last call. +func (b *AlertmanagerGlobalConfigApplyConfiguration) WithHTTPConfigWithProxy(value *HTTPConfigWithProxyApplyConfiguration) *AlertmanagerGlobalConfigApplyConfiguration { + b.HTTPConfigWithProxy = value return b } diff --git a/pkg/client/applyconfiguration/monitoring/v1/alertmanagerspec.go b/pkg/client/applyconfiguration/monitoring/v1/alertmanagerspec.go index ef35441316d..89f7e447387 100644 --- a/pkg/client/applyconfiguration/monitoring/v1/alertmanagerspec.go +++ b/pkg/client/applyconfiguration/monitoring/v1/alertmanagerspec.go @@ -60,6 +60,8 @@ type AlertmanagerSpecApplyConfiguration struct { ServiceName *string `json:"serviceName,omitempty"` ServiceAccountName *string `json:"serviceAccountName,omitempty"` ListenLocal *bool `json:"listenLocal,omitempty"` + PodManagementPolicy *monitoringv1.PodManagementPolicyType `json:"podManagementPolicy,omitempty"` + UpdateStrategy *StatefulSetUpdateStrategyApplyConfiguration `json:"updateStrategy,omitempty"` Containers []corev1.Container `json:"containers,omitempty"` InitContainers []corev1.Container `json:"initContainers,omitempty"` PriorityClassName *string `json:"priorityClassName,omitempty"` @@ -385,6 +387,22 @@ func (b *AlertmanagerSpecApplyConfiguration) WithListenLocal(value bool) *Alertm return b } +// WithPodManagementPolicy sets the PodManagementPolicy field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the PodManagementPolicy field is set to the value of the last call. +func (b *AlertmanagerSpecApplyConfiguration) WithPodManagementPolicy(value monitoringv1.PodManagementPolicyType) *AlertmanagerSpecApplyConfiguration { + b.PodManagementPolicy = &value + return b +} + +// WithUpdateStrategy sets the UpdateStrategy field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the UpdateStrategy field is set to the value of the last call. +func (b *AlertmanagerSpecApplyConfiguration) WithUpdateStrategy(value *StatefulSetUpdateStrategyApplyConfiguration) *AlertmanagerSpecApplyConfiguration { + b.UpdateStrategy = value + return b +} + // WithContainers adds the given value to the Containers field in the declarative configuration // and returns the receiver, so that objects can be build by chaining "With" function invocations. // If called multiple times, values provided by each call will be appended to the Containers field. diff --git a/pkg/client/applyconfiguration/monitoring/v1/azuread.go b/pkg/client/applyconfiguration/monitoring/v1/azuread.go index 758881efe3b..22e0b20ef85 100644 --- a/pkg/client/applyconfiguration/monitoring/v1/azuread.go +++ b/pkg/client/applyconfiguration/monitoring/v1/azuread.go @@ -19,10 +19,12 @@ package v1 // AzureADApplyConfiguration represents a declarative configuration of the AzureAD type for use // with apply. type AzureADApplyConfiguration struct { - Cloud *string `json:"cloud,omitempty"` - ManagedIdentity *ManagedIdentityApplyConfiguration `json:"managedIdentity,omitempty"` - OAuth *AzureOAuthApplyConfiguration `json:"oauth,omitempty"` - SDK *AzureSDKApplyConfiguration `json:"sdk,omitempty"` + Cloud *string `json:"cloud,omitempty"` + ManagedIdentity *ManagedIdentityApplyConfiguration `json:"managedIdentity,omitempty"` + OAuth *AzureOAuthApplyConfiguration `json:"oauth,omitempty"` + SDK *AzureSDKApplyConfiguration `json:"sdk,omitempty"` + WorkloadIdentity *AzureWorkloadIdentityApplyConfiguration `json:"workloadIdentity,omitempty"` + Scope *string `json:"scope,omitempty"` } // AzureADApplyConfiguration constructs a declarative configuration of the AzureAD type for use with @@ -62,3 +64,19 @@ func (b *AzureADApplyConfiguration) WithSDK(value *AzureSDKApplyConfiguration) * b.SDK = value return b } + +// WithWorkloadIdentity sets the WorkloadIdentity field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the WorkloadIdentity field is set to the value of the last call. +func (b *AzureADApplyConfiguration) WithWorkloadIdentity(value *AzureWorkloadIdentityApplyConfiguration) *AzureADApplyConfiguration { + b.WorkloadIdentity = value + return b +} + +// WithScope sets the Scope field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the Scope field is set to the value of the last call. +func (b *AzureADApplyConfiguration) WithScope(value string) *AzureADApplyConfiguration { + b.Scope = &value + return b +} diff --git a/pkg/client/applyconfiguration/monitoring/v1/azureworkloadidentity.go b/pkg/client/applyconfiguration/monitoring/v1/azureworkloadidentity.go new file mode 100644 index 00000000000..0db86616bf3 --- /dev/null +++ b/pkg/client/applyconfiguration/monitoring/v1/azureworkloadidentity.go @@ -0,0 +1,46 @@ +// Copyright The prometheus-operator Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// Code generated by applyconfiguration-gen. DO NOT EDIT. + +package v1 + +// AzureWorkloadIdentityApplyConfiguration represents a declarative configuration of the AzureWorkloadIdentity type for use +// with apply. +type AzureWorkloadIdentityApplyConfiguration struct { + ClientID *string `json:"clientId,omitempty"` + TenantID *string `json:"tenantId,omitempty"` +} + +// AzureWorkloadIdentityApplyConfiguration constructs a declarative configuration of the AzureWorkloadIdentity type for use with +// apply. +func AzureWorkloadIdentity() *AzureWorkloadIdentityApplyConfiguration { + return &AzureWorkloadIdentityApplyConfiguration{} +} + +// WithClientID sets the ClientID field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the ClientID field is set to the value of the last call. +func (b *AzureWorkloadIdentityApplyConfiguration) WithClientID(value string) *AzureWorkloadIdentityApplyConfiguration { + b.ClientID = &value + return b +} + +// WithTenantID sets the TenantID field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the TenantID field is set to the value of the last call. +func (b *AzureWorkloadIdentityApplyConfiguration) WithTenantID(value string) *AzureWorkloadIdentityApplyConfiguration { + b.TenantID = &value + return b +} diff --git a/pkg/client/applyconfiguration/monitoring/v1/commonprometheusfields.go b/pkg/client/applyconfiguration/monitoring/v1/commonprometheusfields.go index a476b86e73d..07d2e308979 100644 --- a/pkg/client/applyconfiguration/monitoring/v1/commonprometheusfields.go +++ b/pkg/client/applyconfiguration/monitoring/v1/commonprometheusfields.go @@ -76,6 +76,8 @@ type CommonPrometheusFieldsApplyConfiguration struct { DNSPolicy *monitoringv1.DNSPolicy `json:"dnsPolicy,omitempty"` DNSConfig *PodDNSConfigApplyConfiguration `json:"dnsConfig,omitempty"` ListenLocal *bool `json:"listenLocal,omitempty"` + PodManagementPolicy *monitoringv1.PodManagementPolicyType `json:"podManagementPolicy,omitempty"` + UpdateStrategy *StatefulSetUpdateStrategyApplyConfiguration `json:"updateStrategy,omitempty"` EnableServiceLinks *bool `json:"enableServiceLinks,omitempty"` Containers []corev1.Container `json:"containers,omitempty"` InitContainers []corev1.Container `json:"initContainers,omitempty"` @@ -98,6 +100,7 @@ type CommonPrometheusFieldsApplyConfiguration struct { NameValidationScheme *monitoringv1.NameValidationSchemeOptions `json:"nameValidationScheme,omitempty"` NameEscapingScheme *monitoringv1.NameEscapingSchemeOptions `json:"nameEscapingScheme,omitempty"` ConvertClassicHistogramsToNHCB *bool `json:"convertClassicHistogramsToNHCB,omitempty"` + ScrapeNativeHistograms *bool `json:"scrapeNativeHistograms,omitempty"` ScrapeClassicHistograms *bool `json:"scrapeClassicHistograms,omitempty"` MinReadySeconds *int32 `json:"minReadySeconds,omitempty"` HostAliases []HostAliasApplyConfiguration `json:"hostAliases,omitempty"` @@ -106,7 +109,7 @@ type CommonPrometheusFieldsApplyConfiguration struct { ExcludedFromEnforcement []ObjectReferenceApplyConfiguration `json:"excludedFromEnforcement,omitempty"` HostNetwork *bool `json:"hostNetwork,omitempty"` PodTargetLabels []string `json:"podTargetLabels,omitempty"` - TracingConfig *PrometheusTracingConfigApplyConfiguration `json:"tracingConfig,omitempty"` + TracingConfig *TracingConfigApplyConfiguration `json:"tracingConfig,omitempty"` BodySizeLimit *monitoringv1.ByteSize `json:"bodySizeLimit,omitempty"` SampleLimit *uint64 `json:"sampleLimit,omitempty"` TargetLimit *uint64 `json:"targetLimit,omitempty"` @@ -572,6 +575,22 @@ func (b *CommonPrometheusFieldsApplyConfiguration) WithListenLocal(value bool) * return b } +// WithPodManagementPolicy sets the PodManagementPolicy field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the PodManagementPolicy field is set to the value of the last call. +func (b *CommonPrometheusFieldsApplyConfiguration) WithPodManagementPolicy(value monitoringv1.PodManagementPolicyType) *CommonPrometheusFieldsApplyConfiguration { + b.PodManagementPolicy = &value + return b +} + +// WithUpdateStrategy sets the UpdateStrategy field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the UpdateStrategy field is set to the value of the last call. +func (b *CommonPrometheusFieldsApplyConfiguration) WithUpdateStrategy(value *StatefulSetUpdateStrategyApplyConfiguration) *CommonPrometheusFieldsApplyConfiguration { + b.UpdateStrategy = value + return b +} + // WithEnableServiceLinks sets the EnableServiceLinks field in the declarative configuration to the given value // and returns the receiver, so that objects can be built by chaining "With" function invocations. // If called multiple times, the EnableServiceLinks field is set to the value of the last call. @@ -752,6 +771,14 @@ func (b *CommonPrometheusFieldsApplyConfiguration) WithConvertClassicHistogramsT return b } +// WithScrapeNativeHistograms sets the ScrapeNativeHistograms field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the ScrapeNativeHistograms field is set to the value of the last call. +func (b *CommonPrometheusFieldsApplyConfiguration) WithScrapeNativeHistograms(value bool) *CommonPrometheusFieldsApplyConfiguration { + b.ScrapeNativeHistograms = &value + return b +} + // WithScrapeClassicHistograms sets the ScrapeClassicHistograms field in the declarative configuration to the given value // and returns the receiver, so that objects can be built by chaining "With" function invocations. // If called multiple times, the ScrapeClassicHistograms field is set to the value of the last call. @@ -836,7 +863,7 @@ func (b *CommonPrometheusFieldsApplyConfiguration) WithPodTargetLabels(values .. // WithTracingConfig sets the TracingConfig field in the declarative configuration to the given value // and returns the receiver, so that objects can be built by chaining "With" function invocations. // If called multiple times, the TracingConfig field is set to the value of the last call. -func (b *CommonPrometheusFieldsApplyConfiguration) WithTracingConfig(value *PrometheusTracingConfigApplyConfiguration) *CommonPrometheusFieldsApplyConfiguration { +func (b *CommonPrometheusFieldsApplyConfiguration) WithTracingConfig(value *TracingConfigApplyConfiguration) *CommonPrometheusFieldsApplyConfiguration { b.TracingConfig = value return b } diff --git a/pkg/client/applyconfiguration/monitoring/v1/endpoint.go b/pkg/client/applyconfiguration/monitoring/v1/endpoint.go index 84ff92f6b71..0deb3e8d17d 100644 --- a/pkg/client/applyconfiguration/monitoring/v1/endpoint.go +++ b/pkg/client/applyconfiguration/monitoring/v1/endpoint.go @@ -25,28 +25,21 @@ import ( // EndpointApplyConfiguration represents a declarative configuration of the Endpoint type for use // with apply. type EndpointApplyConfiguration struct { - Port *string `json:"port,omitempty"` - TargetPort *intstr.IntOrString `json:"targetPort,omitempty"` - Path *string `json:"path,omitempty"` - Scheme *monitoringv1.Scheme `json:"scheme,omitempty"` - Params map[string][]string `json:"params,omitempty"` - Interval *monitoringv1.Duration `json:"interval,omitempty"` - ScrapeTimeout *monitoringv1.Duration `json:"scrapeTimeout,omitempty"` - TLSConfig *TLSConfigApplyConfiguration `json:"tlsConfig,omitempty"` - BearerTokenFile *string `json:"bearerTokenFile,omitempty"` - BearerTokenSecret *corev1.SecretKeySelector `json:"bearerTokenSecret,omitempty"` - Authorization *SafeAuthorizationApplyConfiguration `json:"authorization,omitempty"` - HonorLabels *bool `json:"honorLabels,omitempty"` - HonorTimestamps *bool `json:"honorTimestamps,omitempty"` - TrackTimestampsStaleness *bool `json:"trackTimestampsStaleness,omitempty"` - BasicAuth *BasicAuthApplyConfiguration `json:"basicAuth,omitempty"` - OAuth2 *OAuth2ApplyConfiguration `json:"oauth2,omitempty"` - MetricRelabelConfigs []RelabelConfigApplyConfiguration `json:"metricRelabelings,omitempty"` - RelabelConfigs []RelabelConfigApplyConfiguration `json:"relabelings,omitempty"` - ProxyConfigApplyConfiguration `json:",inline"` - FollowRedirects *bool `json:"followRedirects,omitempty"` - EnableHttp2 *bool `json:"enableHttp2,omitempty"` - FilterRunning *bool `json:"filterRunning,omitempty"` + Port *string `json:"port,omitempty"` + TargetPort *intstr.IntOrString `json:"targetPort,omitempty"` + Path *string `json:"path,omitempty"` + Scheme *monitoringv1.Scheme `json:"scheme,omitempty"` + Params map[string][]string `json:"params,omitempty"` + Interval *monitoringv1.Duration `json:"interval,omitempty"` + ScrapeTimeout *monitoringv1.Duration `json:"scrapeTimeout,omitempty"` + HonorLabels *bool `json:"honorLabels,omitempty"` + HonorTimestamps *bool `json:"honorTimestamps,omitempty"` + TrackTimestampsStaleness *bool `json:"trackTimestampsStaleness,omitempty"` + MetricRelabelConfigs []RelabelConfigApplyConfiguration `json:"metricRelabelings,omitempty"` + RelabelConfigs []RelabelConfigApplyConfiguration `json:"relabelings,omitempty"` + FilterRunning *bool `json:"filterRunning,omitempty"` + BearerTokenFile *string `json:"bearerTokenFile,omitempty"` + HTTPConfigWithProxyAndTLSFilesApplyConfiguration `json:",inline"` } // EndpointApplyConfiguration constructs a declarative configuration of the Endpoint type for use with @@ -117,38 +110,6 @@ func (b *EndpointApplyConfiguration) WithScrapeTimeout(value monitoringv1.Durati return b } -// WithTLSConfig sets the TLSConfig field in the declarative configuration to the given value -// and returns the receiver, so that objects can be built by chaining "With" function invocations. -// If called multiple times, the TLSConfig field is set to the value of the last call. -func (b *EndpointApplyConfiguration) WithTLSConfig(value *TLSConfigApplyConfiguration) *EndpointApplyConfiguration { - b.TLSConfig = value - return b -} - -// WithBearerTokenFile sets the BearerTokenFile field in the declarative configuration to the given value -// and returns the receiver, so that objects can be built by chaining "With" function invocations. -// If called multiple times, the BearerTokenFile field is set to the value of the last call. -func (b *EndpointApplyConfiguration) WithBearerTokenFile(value string) *EndpointApplyConfiguration { - b.BearerTokenFile = &value - return b -} - -// WithBearerTokenSecret sets the BearerTokenSecret field in the declarative configuration to the given value -// and returns the receiver, so that objects can be built by chaining "With" function invocations. -// If called multiple times, the BearerTokenSecret field is set to the value of the last call. -func (b *EndpointApplyConfiguration) WithBearerTokenSecret(value corev1.SecretKeySelector) *EndpointApplyConfiguration { - b.BearerTokenSecret = &value - return b -} - -// WithAuthorization sets the Authorization field in the declarative configuration to the given value -// and returns the receiver, so that objects can be built by chaining "With" function invocations. -// If called multiple times, the Authorization field is set to the value of the last call. -func (b *EndpointApplyConfiguration) WithAuthorization(value *SafeAuthorizationApplyConfiguration) *EndpointApplyConfiguration { - b.Authorization = value - return b -} - // WithHonorLabels sets the HonorLabels field in the declarative configuration to the given value // and returns the receiver, so that objects can be built by chaining "With" function invocations. // If called multiple times, the HonorLabels field is set to the value of the last call. @@ -173,22 +134,6 @@ func (b *EndpointApplyConfiguration) WithTrackTimestampsStaleness(value bool) *E return b } -// WithBasicAuth sets the BasicAuth field in the declarative configuration to the given value -// and returns the receiver, so that objects can be built by chaining "With" function invocations. -// If called multiple times, the BasicAuth field is set to the value of the last call. -func (b *EndpointApplyConfiguration) WithBasicAuth(value *BasicAuthApplyConfiguration) *EndpointApplyConfiguration { - b.BasicAuth = value - return b -} - -// WithOAuth2 sets the OAuth2 field in the declarative configuration to the given value -// and returns the receiver, so that objects can be built by chaining "With" function invocations. -// If called multiple times, the OAuth2 field is set to the value of the last call. -func (b *EndpointApplyConfiguration) WithOAuth2(value *OAuth2ApplyConfiguration) *EndpointApplyConfiguration { - b.OAuth2 = value - return b -} - // WithMetricRelabelConfigs adds the given value to the MetricRelabelConfigs field in the declarative configuration // and returns the receiver, so that objects can be build by chaining "With" function invocations. // If called multiple times, values provided by each call will be appended to the MetricRelabelConfigs field. @@ -215,6 +160,78 @@ func (b *EndpointApplyConfiguration) WithRelabelConfigs(values ...*RelabelConfig return b } +// WithFilterRunning sets the FilterRunning field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the FilterRunning field is set to the value of the last call. +func (b *EndpointApplyConfiguration) WithFilterRunning(value bool) *EndpointApplyConfiguration { + b.FilterRunning = &value + return b +} + +// WithBearerTokenFile sets the BearerTokenFile field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the BearerTokenFile field is set to the value of the last call. +func (b *EndpointApplyConfiguration) WithBearerTokenFile(value string) *EndpointApplyConfiguration { + b.BearerTokenFile = &value + return b +} + +// WithAuthorization sets the Authorization field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the Authorization field is set to the value of the last call. +func (b *EndpointApplyConfiguration) WithAuthorization(value *SafeAuthorizationApplyConfiguration) *EndpointApplyConfiguration { + b.HTTPConfigWithoutTLSApplyConfiguration.Authorization = value + return b +} + +// WithBasicAuth sets the BasicAuth field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the BasicAuth field is set to the value of the last call. +func (b *EndpointApplyConfiguration) WithBasicAuth(value *BasicAuthApplyConfiguration) *EndpointApplyConfiguration { + b.HTTPConfigWithoutTLSApplyConfiguration.BasicAuth = value + return b +} + +// WithOAuth2 sets the OAuth2 field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the OAuth2 field is set to the value of the last call. +func (b *EndpointApplyConfiguration) WithOAuth2(value *OAuth2ApplyConfiguration) *EndpointApplyConfiguration { + b.HTTPConfigWithoutTLSApplyConfiguration.OAuth2 = value + return b +} + +// WithBearerTokenSecret sets the BearerTokenSecret field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the BearerTokenSecret field is set to the value of the last call. +func (b *EndpointApplyConfiguration) WithBearerTokenSecret(value corev1.SecretKeySelector) *EndpointApplyConfiguration { + b.HTTPConfigWithoutTLSApplyConfiguration.BearerTokenSecret = &value + return b +} + +// WithFollowRedirects sets the FollowRedirects field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the FollowRedirects field is set to the value of the last call. +func (b *EndpointApplyConfiguration) WithFollowRedirects(value bool) *EndpointApplyConfiguration { + b.HTTPConfigWithoutTLSApplyConfiguration.FollowRedirects = &value + return b +} + +// WithEnableHTTP2 sets the EnableHTTP2 field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the EnableHTTP2 field is set to the value of the last call. +func (b *EndpointApplyConfiguration) WithEnableHTTP2(value bool) *EndpointApplyConfiguration { + b.HTTPConfigWithoutTLSApplyConfiguration.EnableHTTP2 = &value + return b +} + +// WithTLSConfig sets the TLSConfig field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the TLSConfig field is set to the value of the last call. +func (b *EndpointApplyConfiguration) WithTLSConfig(value *TLSConfigApplyConfiguration) *EndpointApplyConfiguration { + b.HTTPConfigWithTLSFilesApplyConfiguration.TLSConfig = value + return b +} + // WithProxyURL sets the ProxyURL field in the declarative configuration to the given value // and returns the receiver, so that objects can be built by chaining "With" function invocations. // If called multiple times, the ProxyURL field is set to the value of the last call. @@ -252,27 +269,3 @@ func (b *EndpointApplyConfiguration) WithProxyConnectHeader(entries map[string][ } return b } - -// WithFollowRedirects sets the FollowRedirects field in the declarative configuration to the given value -// and returns the receiver, so that objects can be built by chaining "With" function invocations. -// If called multiple times, the FollowRedirects field is set to the value of the last call. -func (b *EndpointApplyConfiguration) WithFollowRedirects(value bool) *EndpointApplyConfiguration { - b.FollowRedirects = &value - return b -} - -// WithEnableHttp2 sets the EnableHttp2 field in the declarative configuration to the given value -// and returns the receiver, so that objects can be built by chaining "With" function invocations. -// If called multiple times, the EnableHttp2 field is set to the value of the last call. -func (b *EndpointApplyConfiguration) WithEnableHttp2(value bool) *EndpointApplyConfiguration { - b.EnableHttp2 = &value - return b -} - -// WithFilterRunning sets the FilterRunning field in the declarative configuration to the given value -// and returns the receiver, so that objects can be built by chaining "With" function invocations. -// If called multiple times, the FilterRunning field is set to the value of the last call. -func (b *EndpointApplyConfiguration) WithFilterRunning(value bool) *EndpointApplyConfiguration { - b.FilterRunning = &value - return b -} diff --git a/pkg/client/applyconfiguration/monitoring/v1/httpconfig.go b/pkg/client/applyconfiguration/monitoring/v1/httpconfig.go index 3e724da1b6f..b2eddc0eca3 100644 --- a/pkg/client/applyconfiguration/monitoring/v1/httpconfig.go +++ b/pkg/client/applyconfiguration/monitoring/v1/httpconfig.go @@ -23,14 +23,8 @@ import ( // HTTPConfigApplyConfiguration represents a declarative configuration of the HTTPConfig type for use // with apply. type HTTPConfigApplyConfiguration struct { - Authorization *SafeAuthorizationApplyConfiguration `json:"authorization,omitempty"` - BasicAuth *BasicAuthApplyConfiguration `json:"basicAuth,omitempty"` - OAuth2 *OAuth2ApplyConfiguration `json:"oauth2,omitempty"` - BearerTokenSecret *corev1.SecretKeySelector `json:"bearerTokenSecret,omitempty"` - TLSConfig *SafeTLSConfigApplyConfiguration `json:"tlsConfig,omitempty"` - ProxyConfigApplyConfiguration `json:",inline"` - FollowRedirects *bool `json:"followRedirects,omitempty"` - EnableHTTP2 *bool `json:"enableHttp2,omitempty"` + HTTPConfigWithoutTLSApplyConfiguration `json:",inline"` + TLSConfig *SafeTLSConfigApplyConfiguration `json:"tlsConfig,omitempty"` } // HTTPConfigApplyConfiguration constructs a declarative configuration of the HTTPConfig type for use with @@ -43,7 +37,7 @@ func HTTPConfig() *HTTPConfigApplyConfiguration { // and returns the receiver, so that objects can be built by chaining "With" function invocations. // If called multiple times, the Authorization field is set to the value of the last call. func (b *HTTPConfigApplyConfiguration) WithAuthorization(value *SafeAuthorizationApplyConfiguration) *HTTPConfigApplyConfiguration { - b.Authorization = value + b.HTTPConfigWithoutTLSApplyConfiguration.Authorization = value return b } @@ -51,7 +45,7 @@ func (b *HTTPConfigApplyConfiguration) WithAuthorization(value *SafeAuthorizatio // and returns the receiver, so that objects can be built by chaining "With" function invocations. // If called multiple times, the BasicAuth field is set to the value of the last call. func (b *HTTPConfigApplyConfiguration) WithBasicAuth(value *BasicAuthApplyConfiguration) *HTTPConfigApplyConfiguration { - b.BasicAuth = value + b.HTTPConfigWithoutTLSApplyConfiguration.BasicAuth = value return b } @@ -59,7 +53,7 @@ func (b *HTTPConfigApplyConfiguration) WithBasicAuth(value *BasicAuthApplyConfig // and returns the receiver, so that objects can be built by chaining "With" function invocations. // If called multiple times, the OAuth2 field is set to the value of the last call. func (b *HTTPConfigApplyConfiguration) WithOAuth2(value *OAuth2ApplyConfiguration) *HTTPConfigApplyConfiguration { - b.OAuth2 = value + b.HTTPConfigWithoutTLSApplyConfiguration.OAuth2 = value return b } @@ -67,53 +61,7 @@ func (b *HTTPConfigApplyConfiguration) WithOAuth2(value *OAuth2ApplyConfiguratio // and returns the receiver, so that objects can be built by chaining "With" function invocations. // If called multiple times, the BearerTokenSecret field is set to the value of the last call. func (b *HTTPConfigApplyConfiguration) WithBearerTokenSecret(value corev1.SecretKeySelector) *HTTPConfigApplyConfiguration { - b.BearerTokenSecret = &value - return b -} - -// WithTLSConfig sets the TLSConfig field in the declarative configuration to the given value -// and returns the receiver, so that objects can be built by chaining "With" function invocations. -// If called multiple times, the TLSConfig field is set to the value of the last call. -func (b *HTTPConfigApplyConfiguration) WithTLSConfig(value *SafeTLSConfigApplyConfiguration) *HTTPConfigApplyConfiguration { - b.TLSConfig = value - return b -} - -// WithProxyURL sets the ProxyURL field in the declarative configuration to the given value -// and returns the receiver, so that objects can be built by chaining "With" function invocations. -// If called multiple times, the ProxyURL field is set to the value of the last call. -func (b *HTTPConfigApplyConfiguration) WithProxyURL(value string) *HTTPConfigApplyConfiguration { - b.ProxyConfigApplyConfiguration.ProxyURL = &value - return b -} - -// WithNoProxy sets the NoProxy field in the declarative configuration to the given value -// and returns the receiver, so that objects can be built by chaining "With" function invocations. -// If called multiple times, the NoProxy field is set to the value of the last call. -func (b *HTTPConfigApplyConfiguration) WithNoProxy(value string) *HTTPConfigApplyConfiguration { - b.ProxyConfigApplyConfiguration.NoProxy = &value - return b -} - -// WithProxyFromEnvironment sets the ProxyFromEnvironment field in the declarative configuration to the given value -// and returns the receiver, so that objects can be built by chaining "With" function invocations. -// If called multiple times, the ProxyFromEnvironment field is set to the value of the last call. -func (b *HTTPConfigApplyConfiguration) WithProxyFromEnvironment(value bool) *HTTPConfigApplyConfiguration { - b.ProxyConfigApplyConfiguration.ProxyFromEnvironment = &value - return b -} - -// WithProxyConnectHeader puts the entries into the ProxyConnectHeader field in the declarative configuration -// and returns the receiver, so that objects can be build by chaining "With" function invocations. -// If called multiple times, the entries provided by each call will be put on the ProxyConnectHeader field, -// overwriting an existing map entries in ProxyConnectHeader field with the same key. -func (b *HTTPConfigApplyConfiguration) WithProxyConnectHeader(entries map[string][]corev1.SecretKeySelector) *HTTPConfigApplyConfiguration { - if b.ProxyConfigApplyConfiguration.ProxyConnectHeader == nil && len(entries) > 0 { - b.ProxyConfigApplyConfiguration.ProxyConnectHeader = make(map[string][]corev1.SecretKeySelector, len(entries)) - } - for k, v := range entries { - b.ProxyConfigApplyConfiguration.ProxyConnectHeader[k] = v - } + b.HTTPConfigWithoutTLSApplyConfiguration.BearerTokenSecret = &value return b } @@ -121,7 +69,7 @@ func (b *HTTPConfigApplyConfiguration) WithProxyConnectHeader(entries map[string // and returns the receiver, so that objects can be built by chaining "With" function invocations. // If called multiple times, the FollowRedirects field is set to the value of the last call. func (b *HTTPConfigApplyConfiguration) WithFollowRedirects(value bool) *HTTPConfigApplyConfiguration { - b.FollowRedirects = &value + b.HTTPConfigWithoutTLSApplyConfiguration.FollowRedirects = &value return b } @@ -129,6 +77,14 @@ func (b *HTTPConfigApplyConfiguration) WithFollowRedirects(value bool) *HTTPConf // and returns the receiver, so that objects can be built by chaining "With" function invocations. // If called multiple times, the EnableHTTP2 field is set to the value of the last call. func (b *HTTPConfigApplyConfiguration) WithEnableHTTP2(value bool) *HTTPConfigApplyConfiguration { - b.EnableHTTP2 = &value + b.HTTPConfigWithoutTLSApplyConfiguration.EnableHTTP2 = &value + return b +} + +// WithTLSConfig sets the TLSConfig field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the TLSConfig field is set to the value of the last call. +func (b *HTTPConfigApplyConfiguration) WithTLSConfig(value *SafeTLSConfigApplyConfiguration) *HTTPConfigApplyConfiguration { + b.TLSConfig = value return b } diff --git a/pkg/client/applyconfiguration/monitoring/v1/httpconfigwithouttls.go b/pkg/client/applyconfiguration/monitoring/v1/httpconfigwithouttls.go new file mode 100644 index 00000000000..2c4e7835e56 --- /dev/null +++ b/pkg/client/applyconfiguration/monitoring/v1/httpconfigwithouttls.go @@ -0,0 +1,86 @@ +// Copyright The prometheus-operator Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// Code generated by applyconfiguration-gen. DO NOT EDIT. + +package v1 + +import ( + corev1 "k8s.io/api/core/v1" +) + +// HTTPConfigWithoutTLSApplyConfiguration represents a declarative configuration of the HTTPConfigWithoutTLS type for use +// with apply. +type HTTPConfigWithoutTLSApplyConfiguration struct { + Authorization *SafeAuthorizationApplyConfiguration `json:"authorization,omitempty"` + BasicAuth *BasicAuthApplyConfiguration `json:"basicAuth,omitempty"` + OAuth2 *OAuth2ApplyConfiguration `json:"oauth2,omitempty"` + BearerTokenSecret *corev1.SecretKeySelector `json:"bearerTokenSecret,omitempty"` + FollowRedirects *bool `json:"followRedirects,omitempty"` + EnableHTTP2 *bool `json:"enableHttp2,omitempty"` +} + +// HTTPConfigWithoutTLSApplyConfiguration constructs a declarative configuration of the HTTPConfigWithoutTLS type for use with +// apply. +func HTTPConfigWithoutTLS() *HTTPConfigWithoutTLSApplyConfiguration { + return &HTTPConfigWithoutTLSApplyConfiguration{} +} + +// WithAuthorization sets the Authorization field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the Authorization field is set to the value of the last call. +func (b *HTTPConfigWithoutTLSApplyConfiguration) WithAuthorization(value *SafeAuthorizationApplyConfiguration) *HTTPConfigWithoutTLSApplyConfiguration { + b.Authorization = value + return b +} + +// WithBasicAuth sets the BasicAuth field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the BasicAuth field is set to the value of the last call. +func (b *HTTPConfigWithoutTLSApplyConfiguration) WithBasicAuth(value *BasicAuthApplyConfiguration) *HTTPConfigWithoutTLSApplyConfiguration { + b.BasicAuth = value + return b +} + +// WithOAuth2 sets the OAuth2 field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the OAuth2 field is set to the value of the last call. +func (b *HTTPConfigWithoutTLSApplyConfiguration) WithOAuth2(value *OAuth2ApplyConfiguration) *HTTPConfigWithoutTLSApplyConfiguration { + b.OAuth2 = value + return b +} + +// WithBearerTokenSecret sets the BearerTokenSecret field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the BearerTokenSecret field is set to the value of the last call. +func (b *HTTPConfigWithoutTLSApplyConfiguration) WithBearerTokenSecret(value corev1.SecretKeySelector) *HTTPConfigWithoutTLSApplyConfiguration { + b.BearerTokenSecret = &value + return b +} + +// WithFollowRedirects sets the FollowRedirects field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the FollowRedirects field is set to the value of the last call. +func (b *HTTPConfigWithoutTLSApplyConfiguration) WithFollowRedirects(value bool) *HTTPConfigWithoutTLSApplyConfiguration { + b.FollowRedirects = &value + return b +} + +// WithEnableHTTP2 sets the EnableHTTP2 field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the EnableHTTP2 field is set to the value of the last call. +func (b *HTTPConfigWithoutTLSApplyConfiguration) WithEnableHTTP2(value bool) *HTTPConfigWithoutTLSApplyConfiguration { + b.EnableHTTP2 = &value + return b +} diff --git a/pkg/client/applyconfiguration/monitoring/v1/httpconfigwithproxy.go b/pkg/client/applyconfiguration/monitoring/v1/httpconfigwithproxy.go new file mode 100644 index 00000000000..9e4666d233a --- /dev/null +++ b/pkg/client/applyconfiguration/monitoring/v1/httpconfigwithproxy.go @@ -0,0 +1,128 @@ +// Copyright The prometheus-operator Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// Code generated by applyconfiguration-gen. DO NOT EDIT. + +package v1 + +import ( + corev1 "k8s.io/api/core/v1" +) + +// HTTPConfigWithProxyApplyConfiguration represents a declarative configuration of the HTTPConfigWithProxy type for use +// with apply. +type HTTPConfigWithProxyApplyConfiguration struct { + HTTPConfigApplyConfiguration `json:",inline"` + ProxyConfigApplyConfiguration `json:",inline"` +} + +// HTTPConfigWithProxyApplyConfiguration constructs a declarative configuration of the HTTPConfigWithProxy type for use with +// apply. +func HTTPConfigWithProxy() *HTTPConfigWithProxyApplyConfiguration { + return &HTTPConfigWithProxyApplyConfiguration{} +} + +// WithAuthorization sets the Authorization field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the Authorization field is set to the value of the last call. +func (b *HTTPConfigWithProxyApplyConfiguration) WithAuthorization(value *SafeAuthorizationApplyConfiguration) *HTTPConfigWithProxyApplyConfiguration { + b.HTTPConfigWithoutTLSApplyConfiguration.Authorization = value + return b +} + +// WithBasicAuth sets the BasicAuth field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the BasicAuth field is set to the value of the last call. +func (b *HTTPConfigWithProxyApplyConfiguration) WithBasicAuth(value *BasicAuthApplyConfiguration) *HTTPConfigWithProxyApplyConfiguration { + b.HTTPConfigWithoutTLSApplyConfiguration.BasicAuth = value + return b +} + +// WithOAuth2 sets the OAuth2 field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the OAuth2 field is set to the value of the last call. +func (b *HTTPConfigWithProxyApplyConfiguration) WithOAuth2(value *OAuth2ApplyConfiguration) *HTTPConfigWithProxyApplyConfiguration { + b.HTTPConfigWithoutTLSApplyConfiguration.OAuth2 = value + return b +} + +// WithBearerTokenSecret sets the BearerTokenSecret field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the BearerTokenSecret field is set to the value of the last call. +func (b *HTTPConfigWithProxyApplyConfiguration) WithBearerTokenSecret(value corev1.SecretKeySelector) *HTTPConfigWithProxyApplyConfiguration { + b.HTTPConfigWithoutTLSApplyConfiguration.BearerTokenSecret = &value + return b +} + +// WithFollowRedirects sets the FollowRedirects field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the FollowRedirects field is set to the value of the last call. +func (b *HTTPConfigWithProxyApplyConfiguration) WithFollowRedirects(value bool) *HTTPConfigWithProxyApplyConfiguration { + b.HTTPConfigWithoutTLSApplyConfiguration.FollowRedirects = &value + return b +} + +// WithEnableHTTP2 sets the EnableHTTP2 field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the EnableHTTP2 field is set to the value of the last call. +func (b *HTTPConfigWithProxyApplyConfiguration) WithEnableHTTP2(value bool) *HTTPConfigWithProxyApplyConfiguration { + b.HTTPConfigWithoutTLSApplyConfiguration.EnableHTTP2 = &value + return b +} + +// WithTLSConfig sets the TLSConfig field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the TLSConfig field is set to the value of the last call. +func (b *HTTPConfigWithProxyApplyConfiguration) WithTLSConfig(value *SafeTLSConfigApplyConfiguration) *HTTPConfigWithProxyApplyConfiguration { + b.HTTPConfigApplyConfiguration.TLSConfig = value + return b +} + +// WithProxyURL sets the ProxyURL field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the ProxyURL field is set to the value of the last call. +func (b *HTTPConfigWithProxyApplyConfiguration) WithProxyURL(value string) *HTTPConfigWithProxyApplyConfiguration { + b.ProxyConfigApplyConfiguration.ProxyURL = &value + return b +} + +// WithNoProxy sets the NoProxy field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the NoProxy field is set to the value of the last call. +func (b *HTTPConfigWithProxyApplyConfiguration) WithNoProxy(value string) *HTTPConfigWithProxyApplyConfiguration { + b.ProxyConfigApplyConfiguration.NoProxy = &value + return b +} + +// WithProxyFromEnvironment sets the ProxyFromEnvironment field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the ProxyFromEnvironment field is set to the value of the last call. +func (b *HTTPConfigWithProxyApplyConfiguration) WithProxyFromEnvironment(value bool) *HTTPConfigWithProxyApplyConfiguration { + b.ProxyConfigApplyConfiguration.ProxyFromEnvironment = &value + return b +} + +// WithProxyConnectHeader puts the entries into the ProxyConnectHeader field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, the entries provided by each call will be put on the ProxyConnectHeader field, +// overwriting an existing map entries in ProxyConnectHeader field with the same key. +func (b *HTTPConfigWithProxyApplyConfiguration) WithProxyConnectHeader(entries map[string][]corev1.SecretKeySelector) *HTTPConfigWithProxyApplyConfiguration { + if b.ProxyConfigApplyConfiguration.ProxyConnectHeader == nil && len(entries) > 0 { + b.ProxyConfigApplyConfiguration.ProxyConnectHeader = make(map[string][]corev1.SecretKeySelector, len(entries)) + } + for k, v := range entries { + b.ProxyConfigApplyConfiguration.ProxyConnectHeader[k] = v + } + return b +} diff --git a/pkg/client/applyconfiguration/monitoring/v1/httpconfigwithproxyandtlsfiles.go b/pkg/client/applyconfiguration/monitoring/v1/httpconfigwithproxyandtlsfiles.go new file mode 100644 index 00000000000..eae11b14c7d --- /dev/null +++ b/pkg/client/applyconfiguration/monitoring/v1/httpconfigwithproxyandtlsfiles.go @@ -0,0 +1,128 @@ +// Copyright The prometheus-operator Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// Code generated by applyconfiguration-gen. DO NOT EDIT. + +package v1 + +import ( + corev1 "k8s.io/api/core/v1" +) + +// HTTPConfigWithProxyAndTLSFilesApplyConfiguration represents a declarative configuration of the HTTPConfigWithProxyAndTLSFiles type for use +// with apply. +type HTTPConfigWithProxyAndTLSFilesApplyConfiguration struct { + HTTPConfigWithTLSFilesApplyConfiguration `json:",inline"` + ProxyConfigApplyConfiguration `json:",inline"` +} + +// HTTPConfigWithProxyAndTLSFilesApplyConfiguration constructs a declarative configuration of the HTTPConfigWithProxyAndTLSFiles type for use with +// apply. +func HTTPConfigWithProxyAndTLSFiles() *HTTPConfigWithProxyAndTLSFilesApplyConfiguration { + return &HTTPConfigWithProxyAndTLSFilesApplyConfiguration{} +} + +// WithAuthorization sets the Authorization field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the Authorization field is set to the value of the last call. +func (b *HTTPConfigWithProxyAndTLSFilesApplyConfiguration) WithAuthorization(value *SafeAuthorizationApplyConfiguration) *HTTPConfigWithProxyAndTLSFilesApplyConfiguration { + b.HTTPConfigWithoutTLSApplyConfiguration.Authorization = value + return b +} + +// WithBasicAuth sets the BasicAuth field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the BasicAuth field is set to the value of the last call. +func (b *HTTPConfigWithProxyAndTLSFilesApplyConfiguration) WithBasicAuth(value *BasicAuthApplyConfiguration) *HTTPConfigWithProxyAndTLSFilesApplyConfiguration { + b.HTTPConfigWithoutTLSApplyConfiguration.BasicAuth = value + return b +} + +// WithOAuth2 sets the OAuth2 field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the OAuth2 field is set to the value of the last call. +func (b *HTTPConfigWithProxyAndTLSFilesApplyConfiguration) WithOAuth2(value *OAuth2ApplyConfiguration) *HTTPConfigWithProxyAndTLSFilesApplyConfiguration { + b.HTTPConfigWithoutTLSApplyConfiguration.OAuth2 = value + return b +} + +// WithBearerTokenSecret sets the BearerTokenSecret field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the BearerTokenSecret field is set to the value of the last call. +func (b *HTTPConfigWithProxyAndTLSFilesApplyConfiguration) WithBearerTokenSecret(value corev1.SecretKeySelector) *HTTPConfigWithProxyAndTLSFilesApplyConfiguration { + b.HTTPConfigWithoutTLSApplyConfiguration.BearerTokenSecret = &value + return b +} + +// WithFollowRedirects sets the FollowRedirects field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the FollowRedirects field is set to the value of the last call. +func (b *HTTPConfigWithProxyAndTLSFilesApplyConfiguration) WithFollowRedirects(value bool) *HTTPConfigWithProxyAndTLSFilesApplyConfiguration { + b.HTTPConfigWithoutTLSApplyConfiguration.FollowRedirects = &value + return b +} + +// WithEnableHTTP2 sets the EnableHTTP2 field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the EnableHTTP2 field is set to the value of the last call. +func (b *HTTPConfigWithProxyAndTLSFilesApplyConfiguration) WithEnableHTTP2(value bool) *HTTPConfigWithProxyAndTLSFilesApplyConfiguration { + b.HTTPConfigWithoutTLSApplyConfiguration.EnableHTTP2 = &value + return b +} + +// WithTLSConfig sets the TLSConfig field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the TLSConfig field is set to the value of the last call. +func (b *HTTPConfigWithProxyAndTLSFilesApplyConfiguration) WithTLSConfig(value *TLSConfigApplyConfiguration) *HTTPConfigWithProxyAndTLSFilesApplyConfiguration { + b.HTTPConfigWithTLSFilesApplyConfiguration.TLSConfig = value + return b +} + +// WithProxyURL sets the ProxyURL field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the ProxyURL field is set to the value of the last call. +func (b *HTTPConfigWithProxyAndTLSFilesApplyConfiguration) WithProxyURL(value string) *HTTPConfigWithProxyAndTLSFilesApplyConfiguration { + b.ProxyConfigApplyConfiguration.ProxyURL = &value + return b +} + +// WithNoProxy sets the NoProxy field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the NoProxy field is set to the value of the last call. +func (b *HTTPConfigWithProxyAndTLSFilesApplyConfiguration) WithNoProxy(value string) *HTTPConfigWithProxyAndTLSFilesApplyConfiguration { + b.ProxyConfigApplyConfiguration.NoProxy = &value + return b +} + +// WithProxyFromEnvironment sets the ProxyFromEnvironment field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the ProxyFromEnvironment field is set to the value of the last call. +func (b *HTTPConfigWithProxyAndTLSFilesApplyConfiguration) WithProxyFromEnvironment(value bool) *HTTPConfigWithProxyAndTLSFilesApplyConfiguration { + b.ProxyConfigApplyConfiguration.ProxyFromEnvironment = &value + return b +} + +// WithProxyConnectHeader puts the entries into the ProxyConnectHeader field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, the entries provided by each call will be put on the ProxyConnectHeader field, +// overwriting an existing map entries in ProxyConnectHeader field with the same key. +func (b *HTTPConfigWithProxyAndTLSFilesApplyConfiguration) WithProxyConnectHeader(entries map[string][]corev1.SecretKeySelector) *HTTPConfigWithProxyAndTLSFilesApplyConfiguration { + if b.ProxyConfigApplyConfiguration.ProxyConnectHeader == nil && len(entries) > 0 { + b.ProxyConfigApplyConfiguration.ProxyConnectHeader = make(map[string][]corev1.SecretKeySelector, len(entries)) + } + for k, v := range entries { + b.ProxyConfigApplyConfiguration.ProxyConnectHeader[k] = v + } + return b +} diff --git a/pkg/client/applyconfiguration/monitoring/v1/httpconfigwithtlsfiles.go b/pkg/client/applyconfiguration/monitoring/v1/httpconfigwithtlsfiles.go new file mode 100644 index 00000000000..fba1aab365b --- /dev/null +++ b/pkg/client/applyconfiguration/monitoring/v1/httpconfigwithtlsfiles.go @@ -0,0 +1,90 @@ +// Copyright The prometheus-operator Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// Code generated by applyconfiguration-gen. DO NOT EDIT. + +package v1 + +import ( + corev1 "k8s.io/api/core/v1" +) + +// HTTPConfigWithTLSFilesApplyConfiguration represents a declarative configuration of the HTTPConfigWithTLSFiles type for use +// with apply. +type HTTPConfigWithTLSFilesApplyConfiguration struct { + HTTPConfigWithoutTLSApplyConfiguration `json:",inline"` + TLSConfig *TLSConfigApplyConfiguration `json:"tlsConfig,omitempty"` +} + +// HTTPConfigWithTLSFilesApplyConfiguration constructs a declarative configuration of the HTTPConfigWithTLSFiles type for use with +// apply. +func HTTPConfigWithTLSFiles() *HTTPConfigWithTLSFilesApplyConfiguration { + return &HTTPConfigWithTLSFilesApplyConfiguration{} +} + +// WithAuthorization sets the Authorization field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the Authorization field is set to the value of the last call. +func (b *HTTPConfigWithTLSFilesApplyConfiguration) WithAuthorization(value *SafeAuthorizationApplyConfiguration) *HTTPConfigWithTLSFilesApplyConfiguration { + b.HTTPConfigWithoutTLSApplyConfiguration.Authorization = value + return b +} + +// WithBasicAuth sets the BasicAuth field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the BasicAuth field is set to the value of the last call. +func (b *HTTPConfigWithTLSFilesApplyConfiguration) WithBasicAuth(value *BasicAuthApplyConfiguration) *HTTPConfigWithTLSFilesApplyConfiguration { + b.HTTPConfigWithoutTLSApplyConfiguration.BasicAuth = value + return b +} + +// WithOAuth2 sets the OAuth2 field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the OAuth2 field is set to the value of the last call. +func (b *HTTPConfigWithTLSFilesApplyConfiguration) WithOAuth2(value *OAuth2ApplyConfiguration) *HTTPConfigWithTLSFilesApplyConfiguration { + b.HTTPConfigWithoutTLSApplyConfiguration.OAuth2 = value + return b +} + +// WithBearerTokenSecret sets the BearerTokenSecret field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the BearerTokenSecret field is set to the value of the last call. +func (b *HTTPConfigWithTLSFilesApplyConfiguration) WithBearerTokenSecret(value corev1.SecretKeySelector) *HTTPConfigWithTLSFilesApplyConfiguration { + b.HTTPConfigWithoutTLSApplyConfiguration.BearerTokenSecret = &value + return b +} + +// WithFollowRedirects sets the FollowRedirects field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the FollowRedirects field is set to the value of the last call. +func (b *HTTPConfigWithTLSFilesApplyConfiguration) WithFollowRedirects(value bool) *HTTPConfigWithTLSFilesApplyConfiguration { + b.HTTPConfigWithoutTLSApplyConfiguration.FollowRedirects = &value + return b +} + +// WithEnableHTTP2 sets the EnableHTTP2 field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the EnableHTTP2 field is set to the value of the last call. +func (b *HTTPConfigWithTLSFilesApplyConfiguration) WithEnableHTTP2(value bool) *HTTPConfigWithTLSFilesApplyConfiguration { + b.HTTPConfigWithoutTLSApplyConfiguration.EnableHTTP2 = &value + return b +} + +// WithTLSConfig sets the TLSConfig field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the TLSConfig field is set to the value of the last call. +func (b *HTTPConfigWithTLSFilesApplyConfiguration) WithTLSConfig(value *TLSConfigApplyConfiguration) *HTTPConfigWithTLSFilesApplyConfiguration { + b.TLSConfig = value + return b +} diff --git a/pkg/client/applyconfiguration/monitoring/v1/nativehistogramconfig.go b/pkg/client/applyconfiguration/monitoring/v1/nativehistogramconfig.go index 8ca307498f3..a6831e87799 100644 --- a/pkg/client/applyconfiguration/monitoring/v1/nativehistogramconfig.go +++ b/pkg/client/applyconfiguration/monitoring/v1/nativehistogramconfig.go @@ -23,6 +23,7 @@ import ( // NativeHistogramConfigApplyConfiguration represents a declarative configuration of the NativeHistogramConfig type for use // with apply. type NativeHistogramConfigApplyConfiguration struct { + ScrapeNativeHistograms *bool `json:"scrapeNativeHistograms,omitempty"` ScrapeClassicHistograms *bool `json:"scrapeClassicHistograms,omitempty"` NativeHistogramBucketLimit *uint64 `json:"nativeHistogramBucketLimit,omitempty"` NativeHistogramMinBucketFactor *resource.Quantity `json:"nativeHistogramMinBucketFactor,omitempty"` @@ -35,6 +36,14 @@ func NativeHistogramConfig() *NativeHistogramConfigApplyConfiguration { return &NativeHistogramConfigApplyConfiguration{} } +// WithScrapeNativeHistograms sets the ScrapeNativeHistograms field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the ScrapeNativeHistograms field is set to the value of the last call. +func (b *NativeHistogramConfigApplyConfiguration) WithScrapeNativeHistograms(value bool) *NativeHistogramConfigApplyConfiguration { + b.ScrapeNativeHistograms = &value + return b +} + // WithScrapeClassicHistograms sets the ScrapeClassicHistograms field in the declarative configuration to the given value // and returns the receiver, so that objects can be built by chaining "With" function invocations. // If called multiple times, the ScrapeClassicHistograms field is set to the value of the last call. diff --git a/pkg/client/applyconfiguration/monitoring/v1/podmetricsendpoint.go b/pkg/client/applyconfiguration/monitoring/v1/podmetricsendpoint.go index 263727a3868..2d0a81428bc 100644 --- a/pkg/client/applyconfiguration/monitoring/v1/podmetricsendpoint.go +++ b/pkg/client/applyconfiguration/monitoring/v1/podmetricsendpoint.go @@ -25,21 +25,21 @@ import ( // PodMetricsEndpointApplyConfiguration represents a declarative configuration of the PodMetricsEndpoint type for use // with apply. type PodMetricsEndpointApplyConfiguration struct { - Port *string `json:"port,omitempty"` - PortNumber *int32 `json:"portNumber,omitempty"` - TargetPort *intstr.IntOrString `json:"targetPort,omitempty"` - Path *string `json:"path,omitempty"` - Scheme *monitoringv1.Scheme `json:"scheme,omitempty"` - Params map[string][]string `json:"params,omitempty"` - Interval *monitoringv1.Duration `json:"interval,omitempty"` - ScrapeTimeout *monitoringv1.Duration `json:"scrapeTimeout,omitempty"` - HonorLabels *bool `json:"honorLabels,omitempty"` - HonorTimestamps *bool `json:"honorTimestamps,omitempty"` - TrackTimestampsStaleness *bool `json:"trackTimestampsStaleness,omitempty"` - MetricRelabelConfigs []RelabelConfigApplyConfiguration `json:"metricRelabelings,omitempty"` - RelabelConfigs []RelabelConfigApplyConfiguration `json:"relabelings,omitempty"` - FilterRunning *bool `json:"filterRunning,omitempty"` - HTTPConfigApplyConfiguration `json:",inline"` + Port *string `json:"port,omitempty"` + PortNumber *int32 `json:"portNumber,omitempty"` + TargetPort *intstr.IntOrString `json:"targetPort,omitempty"` + Path *string `json:"path,omitempty"` + Scheme *monitoringv1.Scheme `json:"scheme,omitempty"` + Params map[string][]string `json:"params,omitempty"` + Interval *monitoringv1.Duration `json:"interval,omitempty"` + ScrapeTimeout *monitoringv1.Duration `json:"scrapeTimeout,omitempty"` + HonorLabels *bool `json:"honorLabels,omitempty"` + HonorTimestamps *bool `json:"honorTimestamps,omitempty"` + TrackTimestampsStaleness *bool `json:"trackTimestampsStaleness,omitempty"` + MetricRelabelConfigs []RelabelConfigApplyConfiguration `json:"metricRelabelings,omitempty"` + RelabelConfigs []RelabelConfigApplyConfiguration `json:"relabelings,omitempty"` + FilterRunning *bool `json:"filterRunning,omitempty"` + HTTPConfigWithProxyApplyConfiguration `json:",inline"` } // PodMetricsEndpointApplyConfiguration constructs a declarative configuration of the PodMetricsEndpoint type for use with @@ -180,7 +180,7 @@ func (b *PodMetricsEndpointApplyConfiguration) WithFilterRunning(value bool) *Po // and returns the receiver, so that objects can be built by chaining "With" function invocations. // If called multiple times, the Authorization field is set to the value of the last call. func (b *PodMetricsEndpointApplyConfiguration) WithAuthorization(value *SafeAuthorizationApplyConfiguration) *PodMetricsEndpointApplyConfiguration { - b.HTTPConfigApplyConfiguration.Authorization = value + b.HTTPConfigWithoutTLSApplyConfiguration.Authorization = value return b } @@ -188,7 +188,7 @@ func (b *PodMetricsEndpointApplyConfiguration) WithAuthorization(value *SafeAuth // and returns the receiver, so that objects can be built by chaining "With" function invocations. // If called multiple times, the BasicAuth field is set to the value of the last call. func (b *PodMetricsEndpointApplyConfiguration) WithBasicAuth(value *BasicAuthApplyConfiguration) *PodMetricsEndpointApplyConfiguration { - b.HTTPConfigApplyConfiguration.BasicAuth = value + b.HTTPConfigWithoutTLSApplyConfiguration.BasicAuth = value return b } @@ -196,7 +196,7 @@ func (b *PodMetricsEndpointApplyConfiguration) WithBasicAuth(value *BasicAuthApp // and returns the receiver, so that objects can be built by chaining "With" function invocations. // If called multiple times, the OAuth2 field is set to the value of the last call. func (b *PodMetricsEndpointApplyConfiguration) WithOAuth2(value *OAuth2ApplyConfiguration) *PodMetricsEndpointApplyConfiguration { - b.HTTPConfigApplyConfiguration.OAuth2 = value + b.HTTPConfigWithoutTLSApplyConfiguration.OAuth2 = value return b } @@ -204,7 +204,23 @@ func (b *PodMetricsEndpointApplyConfiguration) WithOAuth2(value *OAuth2ApplyConf // and returns the receiver, so that objects can be built by chaining "With" function invocations. // If called multiple times, the BearerTokenSecret field is set to the value of the last call. func (b *PodMetricsEndpointApplyConfiguration) WithBearerTokenSecret(value corev1.SecretKeySelector) *PodMetricsEndpointApplyConfiguration { - b.HTTPConfigApplyConfiguration.BearerTokenSecret = &value + b.HTTPConfigWithoutTLSApplyConfiguration.BearerTokenSecret = &value + return b +} + +// WithFollowRedirects sets the FollowRedirects field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the FollowRedirects field is set to the value of the last call. +func (b *PodMetricsEndpointApplyConfiguration) WithFollowRedirects(value bool) *PodMetricsEndpointApplyConfiguration { + b.HTTPConfigWithoutTLSApplyConfiguration.FollowRedirects = &value + return b +} + +// WithEnableHTTP2 sets the EnableHTTP2 field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the EnableHTTP2 field is set to the value of the last call. +func (b *PodMetricsEndpointApplyConfiguration) WithEnableHTTP2(value bool) *PodMetricsEndpointApplyConfiguration { + b.HTTPConfigWithoutTLSApplyConfiguration.EnableHTTP2 = &value return b } @@ -253,19 +269,3 @@ func (b *PodMetricsEndpointApplyConfiguration) WithProxyConnectHeader(entries ma } return b } - -// WithFollowRedirects sets the FollowRedirects field in the declarative configuration to the given value -// and returns the receiver, so that objects can be built by chaining "With" function invocations. -// If called multiple times, the FollowRedirects field is set to the value of the last call. -func (b *PodMetricsEndpointApplyConfiguration) WithFollowRedirects(value bool) *PodMetricsEndpointApplyConfiguration { - b.HTTPConfigApplyConfiguration.FollowRedirects = &value - return b -} - -// WithEnableHTTP2 sets the EnableHTTP2 field in the declarative configuration to the given value -// and returns the receiver, so that objects can be built by chaining "With" function invocations. -// If called multiple times, the EnableHTTP2 field is set to the value of the last call. -func (b *PodMetricsEndpointApplyConfiguration) WithEnableHTTP2(value bool) *PodMetricsEndpointApplyConfiguration { - b.HTTPConfigApplyConfiguration.EnableHTTP2 = &value - return b -} diff --git a/pkg/client/applyconfiguration/monitoring/v1/podmonitorspec.go b/pkg/client/applyconfiguration/monitoring/v1/podmonitorspec.go index a7477e029d0..3daf46fc261 100644 --- a/pkg/client/applyconfiguration/monitoring/v1/podmonitorspec.go +++ b/pkg/client/applyconfiguration/monitoring/v1/podmonitorspec.go @@ -164,6 +164,14 @@ func (b *PodMonitorSpecApplyConfiguration) WithLabelValueLengthLimit(value uint6 return b } +// WithScrapeNativeHistograms sets the ScrapeNativeHistograms field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the ScrapeNativeHistograms field is set to the value of the last call. +func (b *PodMonitorSpecApplyConfiguration) WithScrapeNativeHistograms(value bool) *PodMonitorSpecApplyConfiguration { + b.NativeHistogramConfigApplyConfiguration.ScrapeNativeHistograms = &value + return b +} + // WithScrapeClassicHistograms sets the ScrapeClassicHistograms field in the declarative configuration to the given value // and returns the receiver, so that objects can be built by chaining "With" function invocations. // If called multiple times, the ScrapeClassicHistograms field is set to the value of the last call. diff --git a/pkg/client/applyconfiguration/monitoring/v1/probespec.go b/pkg/client/applyconfiguration/monitoring/v1/probespec.go index 68fc056d2a6..6be60f3a137 100644 --- a/pkg/client/applyconfiguration/monitoring/v1/probespec.go +++ b/pkg/client/applyconfiguration/monitoring/v1/probespec.go @@ -31,10 +31,6 @@ type ProbeSpecApplyConfiguration struct { Targets *ProbeTargetsApplyConfiguration `json:"targets,omitempty"` Interval *monitoringv1.Duration `json:"interval,omitempty"` ScrapeTimeout *monitoringv1.Duration `json:"scrapeTimeout,omitempty"` - TLSConfig *SafeTLSConfigApplyConfiguration `json:"tlsConfig,omitempty"` - BearerTokenSecret *corev1.SecretKeySelector `json:"bearerTokenSecret,omitempty"` - BasicAuth *BasicAuthApplyConfiguration `json:"basicAuth,omitempty"` - OAuth2 *OAuth2ApplyConfiguration `json:"oauth2,omitempty"` MetricRelabelConfigs []RelabelConfigApplyConfiguration `json:"metricRelabelings,omitempty"` Authorization *SafeAuthorizationApplyConfiguration `json:"authorization,omitempty"` SampleLimit *uint64 `json:"sampleLimit,omitempty"` @@ -48,6 +44,7 @@ type ProbeSpecApplyConfiguration struct { KeepDroppedTargets *uint64 `json:"keepDroppedTargets,omitempty"` ScrapeClassName *string `json:"scrapeClass,omitempty"` Params []ProbeParamApplyConfiguration `json:"params,omitempty"` + HTTPConfigApplyConfiguration `json:",inline"` } // ProbeSpecApplyConfiguration constructs a declarative configuration of the ProbeSpec type for use with @@ -104,38 +101,6 @@ func (b *ProbeSpecApplyConfiguration) WithScrapeTimeout(value monitoringv1.Durat return b } -// WithTLSConfig sets the TLSConfig field in the declarative configuration to the given value -// and returns the receiver, so that objects can be built by chaining "With" function invocations. -// If called multiple times, the TLSConfig field is set to the value of the last call. -func (b *ProbeSpecApplyConfiguration) WithTLSConfig(value *SafeTLSConfigApplyConfiguration) *ProbeSpecApplyConfiguration { - b.TLSConfig = value - return b -} - -// WithBearerTokenSecret sets the BearerTokenSecret field in the declarative configuration to the given value -// and returns the receiver, so that objects can be built by chaining "With" function invocations. -// If called multiple times, the BearerTokenSecret field is set to the value of the last call. -func (b *ProbeSpecApplyConfiguration) WithBearerTokenSecret(value corev1.SecretKeySelector) *ProbeSpecApplyConfiguration { - b.BearerTokenSecret = &value - return b -} - -// WithBasicAuth sets the BasicAuth field in the declarative configuration to the given value -// and returns the receiver, so that objects can be built by chaining "With" function invocations. -// If called multiple times, the BasicAuth field is set to the value of the last call. -func (b *ProbeSpecApplyConfiguration) WithBasicAuth(value *BasicAuthApplyConfiguration) *ProbeSpecApplyConfiguration { - b.BasicAuth = value - return b -} - -// WithOAuth2 sets the OAuth2 field in the declarative configuration to the given value -// and returns the receiver, so that objects can be built by chaining "With" function invocations. -// If called multiple times, the OAuth2 field is set to the value of the last call. -func (b *ProbeSpecApplyConfiguration) WithOAuth2(value *OAuth2ApplyConfiguration) *ProbeSpecApplyConfiguration { - b.OAuth2 = value - return b -} - // WithMetricRelabelConfigs adds the given value to the MetricRelabelConfigs field in the declarative configuration // and returns the receiver, so that objects can be build by chaining "With" function invocations. // If called multiple times, values provided by each call will be appended to the MetricRelabelConfigs field. @@ -215,6 +180,14 @@ func (b *ProbeSpecApplyConfiguration) WithLabelValueLengthLimit(value uint64) *P return b } +// WithScrapeNativeHistograms sets the ScrapeNativeHistograms field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the ScrapeNativeHistograms field is set to the value of the last call. +func (b *ProbeSpecApplyConfiguration) WithScrapeNativeHistograms(value bool) *ProbeSpecApplyConfiguration { + b.NativeHistogramConfigApplyConfiguration.ScrapeNativeHistograms = &value + return b +} + // WithScrapeClassicHistograms sets the ScrapeClassicHistograms field in the declarative configuration to the given value // and returns the receiver, so that objects can be built by chaining "With" function invocations. // If called multiple times, the ScrapeClassicHistograms field is set to the value of the last call. @@ -275,3 +248,51 @@ func (b *ProbeSpecApplyConfiguration) WithParams(values ...*ProbeParamApplyConfi } return b } + +// WithBasicAuth sets the BasicAuth field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the BasicAuth field is set to the value of the last call. +func (b *ProbeSpecApplyConfiguration) WithBasicAuth(value *BasicAuthApplyConfiguration) *ProbeSpecApplyConfiguration { + b.HTTPConfigWithoutTLSApplyConfiguration.BasicAuth = value + return b +} + +// WithOAuth2 sets the OAuth2 field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the OAuth2 field is set to the value of the last call. +func (b *ProbeSpecApplyConfiguration) WithOAuth2(value *OAuth2ApplyConfiguration) *ProbeSpecApplyConfiguration { + b.HTTPConfigWithoutTLSApplyConfiguration.OAuth2 = value + return b +} + +// WithBearerTokenSecret sets the BearerTokenSecret field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the BearerTokenSecret field is set to the value of the last call. +func (b *ProbeSpecApplyConfiguration) WithBearerTokenSecret(value corev1.SecretKeySelector) *ProbeSpecApplyConfiguration { + b.HTTPConfigWithoutTLSApplyConfiguration.BearerTokenSecret = &value + return b +} + +// WithFollowRedirects sets the FollowRedirects field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the FollowRedirects field is set to the value of the last call. +func (b *ProbeSpecApplyConfiguration) WithFollowRedirects(value bool) *ProbeSpecApplyConfiguration { + b.HTTPConfigWithoutTLSApplyConfiguration.FollowRedirects = &value + return b +} + +// WithEnableHTTP2 sets the EnableHTTP2 field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the EnableHTTP2 field is set to the value of the last call. +func (b *ProbeSpecApplyConfiguration) WithEnableHTTP2(value bool) *ProbeSpecApplyConfiguration { + b.HTTPConfigWithoutTLSApplyConfiguration.EnableHTTP2 = &value + return b +} + +// WithTLSConfig sets the TLSConfig field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the TLSConfig field is set to the value of the last call. +func (b *ProbeSpecApplyConfiguration) WithTLSConfig(value *SafeTLSConfigApplyConfiguration) *ProbeSpecApplyConfiguration { + b.HTTPConfigApplyConfiguration.TLSConfig = value + return b +} diff --git a/pkg/client/applyconfiguration/monitoring/v1/prometheusspec.go b/pkg/client/applyconfiguration/monitoring/v1/prometheusspec.go index a8f878e0ec8..9c6b6c6b2a7 100644 --- a/pkg/client/applyconfiguration/monitoring/v1/prometheusspec.go +++ b/pkg/client/applyconfiguration/monitoring/v1/prometheusspec.go @@ -498,6 +498,22 @@ func (b *PrometheusSpecApplyConfiguration) WithListenLocal(value bool) *Promethe return b } +// WithPodManagementPolicy sets the PodManagementPolicy field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the PodManagementPolicy field is set to the value of the last call. +func (b *PrometheusSpecApplyConfiguration) WithPodManagementPolicy(value monitoringv1.PodManagementPolicyType) *PrometheusSpecApplyConfiguration { + b.CommonPrometheusFieldsApplyConfiguration.PodManagementPolicy = &value + return b +} + +// WithUpdateStrategy sets the UpdateStrategy field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the UpdateStrategy field is set to the value of the last call. +func (b *PrometheusSpecApplyConfiguration) WithUpdateStrategy(value *StatefulSetUpdateStrategyApplyConfiguration) *PrometheusSpecApplyConfiguration { + b.CommonPrometheusFieldsApplyConfiguration.UpdateStrategy = value + return b +} + // WithEnableServiceLinks sets the EnableServiceLinks field in the declarative configuration to the given value // and returns the receiver, so that objects can be built by chaining "With" function invocations. // If called multiple times, the EnableServiceLinks field is set to the value of the last call. @@ -678,6 +694,14 @@ func (b *PrometheusSpecApplyConfiguration) WithConvertClassicHistogramsToNHCB(va return b } +// WithScrapeNativeHistograms sets the ScrapeNativeHistograms field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the ScrapeNativeHistograms field is set to the value of the last call. +func (b *PrometheusSpecApplyConfiguration) WithScrapeNativeHistograms(value bool) *PrometheusSpecApplyConfiguration { + b.CommonPrometheusFieldsApplyConfiguration.ScrapeNativeHistograms = &value + return b +} + // WithScrapeClassicHistograms sets the ScrapeClassicHistograms field in the declarative configuration to the given value // and returns the receiver, so that objects can be built by chaining "With" function invocations. // If called multiple times, the ScrapeClassicHistograms field is set to the value of the last call. @@ -762,7 +786,7 @@ func (b *PrometheusSpecApplyConfiguration) WithPodTargetLabels(values ...string) // WithTracingConfig sets the TracingConfig field in the declarative configuration to the given value // and returns the receiver, so that objects can be built by chaining "With" function invocations. // If called multiple times, the TracingConfig field is set to the value of the last call. -func (b *PrometheusSpecApplyConfiguration) WithTracingConfig(value *PrometheusTracingConfigApplyConfiguration) *PrometheusSpecApplyConfiguration { +func (b *PrometheusSpecApplyConfiguration) WithTracingConfig(value *TracingConfigApplyConfiguration) *PrometheusSpecApplyConfiguration { b.CommonPrometheusFieldsApplyConfiguration.TracingConfig = value return b } diff --git a/pkg/client/applyconfiguration/monitoring/v1/rollingupdatestatefulsetstrategy.go b/pkg/client/applyconfiguration/monitoring/v1/rollingupdatestatefulsetstrategy.go new file mode 100644 index 00000000000..5c09187f4ac --- /dev/null +++ b/pkg/client/applyconfiguration/monitoring/v1/rollingupdatestatefulsetstrategy.go @@ -0,0 +1,41 @@ +// Copyright The prometheus-operator Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// Code generated by applyconfiguration-gen. DO NOT EDIT. + +package v1 + +import ( + intstr "k8s.io/apimachinery/pkg/util/intstr" +) + +// RollingUpdateStatefulSetStrategyApplyConfiguration represents a declarative configuration of the RollingUpdateStatefulSetStrategy type for use +// with apply. +type RollingUpdateStatefulSetStrategyApplyConfiguration struct { + MaxUnavailable *intstr.IntOrString `json:"maxUnavailable,omitempty"` +} + +// RollingUpdateStatefulSetStrategyApplyConfiguration constructs a declarative configuration of the RollingUpdateStatefulSetStrategy type for use with +// apply. +func RollingUpdateStatefulSetStrategy() *RollingUpdateStatefulSetStrategyApplyConfiguration { + return &RollingUpdateStatefulSetStrategyApplyConfiguration{} +} + +// WithMaxUnavailable sets the MaxUnavailable field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the MaxUnavailable field is set to the value of the last call. +func (b *RollingUpdateStatefulSetStrategyApplyConfiguration) WithMaxUnavailable(value intstr.IntOrString) *RollingUpdateStatefulSetStrategyApplyConfiguration { + b.MaxUnavailable = &value + return b +} diff --git a/pkg/client/applyconfiguration/monitoring/v1/servicemonitorspec.go b/pkg/client/applyconfiguration/monitoring/v1/servicemonitorspec.go index 2800a7e0502..b0b7887644d 100644 --- a/pkg/client/applyconfiguration/monitoring/v1/servicemonitorspec.go +++ b/pkg/client/applyconfiguration/monitoring/v1/servicemonitorspec.go @@ -176,6 +176,14 @@ func (b *ServiceMonitorSpecApplyConfiguration) WithLabelValueLengthLimit(value u return b } +// WithScrapeNativeHistograms sets the ScrapeNativeHistograms field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the ScrapeNativeHistograms field is set to the value of the last call. +func (b *ServiceMonitorSpecApplyConfiguration) WithScrapeNativeHistograms(value bool) *ServiceMonitorSpecApplyConfiguration { + b.NativeHistogramConfigApplyConfiguration.ScrapeNativeHistograms = &value + return b +} + // WithScrapeClassicHistograms sets the ScrapeClassicHistograms field in the declarative configuration to the given value // and returns the receiver, so that objects can be built by chaining "With" function invocations. // If called multiple times, the ScrapeClassicHistograms field is set to the value of the last call. diff --git a/pkg/client/applyconfiguration/monitoring/v1/statefulsetupdatestrategy.go b/pkg/client/applyconfiguration/monitoring/v1/statefulsetupdatestrategy.go new file mode 100644 index 00000000000..f5e00d979cb --- /dev/null +++ b/pkg/client/applyconfiguration/monitoring/v1/statefulsetupdatestrategy.go @@ -0,0 +1,50 @@ +// Copyright The prometheus-operator Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// Code generated by applyconfiguration-gen. DO NOT EDIT. + +package v1 + +import ( + monitoringv1 "github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1" +) + +// StatefulSetUpdateStrategyApplyConfiguration represents a declarative configuration of the StatefulSetUpdateStrategy type for use +// with apply. +type StatefulSetUpdateStrategyApplyConfiguration struct { + Type *monitoringv1.StatefulSetUpdateStrategyType `json:"type,omitempty"` + RollingUpdate *RollingUpdateStatefulSetStrategyApplyConfiguration `json:"rollingUpdate,omitempty"` +} + +// StatefulSetUpdateStrategyApplyConfiguration constructs a declarative configuration of the StatefulSetUpdateStrategy type for use with +// apply. +func StatefulSetUpdateStrategy() *StatefulSetUpdateStrategyApplyConfiguration { + return &StatefulSetUpdateStrategyApplyConfiguration{} +} + +// WithType sets the Type field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the Type field is set to the value of the last call. +func (b *StatefulSetUpdateStrategyApplyConfiguration) WithType(value monitoringv1.StatefulSetUpdateStrategyType) *StatefulSetUpdateStrategyApplyConfiguration { + b.Type = &value + return b +} + +// WithRollingUpdate sets the RollingUpdate field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the RollingUpdate field is set to the value of the last call. +func (b *StatefulSetUpdateStrategyApplyConfiguration) WithRollingUpdate(value *RollingUpdateStatefulSetStrategyApplyConfiguration) *StatefulSetUpdateStrategyApplyConfiguration { + b.RollingUpdate = value + return b +} diff --git a/pkg/client/applyconfiguration/monitoring/v1/thanosrulerspec.go b/pkg/client/applyconfiguration/monitoring/v1/thanosrulerspec.go index 461086e213d..f0608d96ceb 100644 --- a/pkg/client/applyconfiguration/monitoring/v1/thanosrulerspec.go +++ b/pkg/client/applyconfiguration/monitoring/v1/thanosrulerspec.go @@ -50,6 +50,8 @@ type ThanosRulerSpecApplyConfiguration struct { ObjectStorageConfig *corev1.SecretKeySelector `json:"objectStorageConfig,omitempty"` ObjectStorageConfigFile *string `json:"objectStorageConfigFile,omitempty"` ListenLocal *bool `json:"listenLocal,omitempty"` + PodManagementPolicy *monitoringv1.PodManagementPolicyType `json:"podManagementPolicy,omitempty"` + UpdateStrategy *StatefulSetUpdateStrategyApplyConfiguration `json:"updateStrategy,omitempty"` QueryEndpoints []string `json:"queryEndpoints,omitempty"` QueryConfig *corev1.SecretKeySelector `json:"queryConfig,omitempty"` AlertManagersURL []string `json:"alertmanagersUrl,omitempty"` @@ -313,6 +315,22 @@ func (b *ThanosRulerSpecApplyConfiguration) WithListenLocal(value bool) *ThanosR return b } +// WithPodManagementPolicy sets the PodManagementPolicy field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the PodManagementPolicy field is set to the value of the last call. +func (b *ThanosRulerSpecApplyConfiguration) WithPodManagementPolicy(value monitoringv1.PodManagementPolicyType) *ThanosRulerSpecApplyConfiguration { + b.PodManagementPolicy = &value + return b +} + +// WithUpdateStrategy sets the UpdateStrategy field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the UpdateStrategy field is set to the value of the last call. +func (b *ThanosRulerSpecApplyConfiguration) WithUpdateStrategy(value *StatefulSetUpdateStrategyApplyConfiguration) *ThanosRulerSpecApplyConfiguration { + b.UpdateStrategy = value + return b +} + // WithQueryEndpoints adds the given value to the QueryEndpoints field in the declarative configuration // and returns the receiver, so that objects can be build by chaining "With" function invocations. // If called multiple times, values provided by each call will be appended to the QueryEndpoints field. diff --git a/pkg/client/applyconfiguration/monitoring/v1/tlsconfig.go b/pkg/client/applyconfiguration/monitoring/v1/tlsconfig.go index fe1b8bfc500..d18d96de216 100644 --- a/pkg/client/applyconfiguration/monitoring/v1/tlsconfig.go +++ b/pkg/client/applyconfiguration/monitoring/v1/tlsconfig.go @@ -24,10 +24,8 @@ import ( // TLSConfigApplyConfiguration represents a declarative configuration of the TLSConfig type for use // with apply. type TLSConfigApplyConfiguration struct { - SafeTLSConfigApplyConfiguration `json:",inline"` - CAFile *string `json:"caFile,omitempty"` - CertFile *string `json:"certFile,omitempty"` - KeyFile *string `json:"keyFile,omitempty"` + SafeTLSConfigApplyConfiguration `json:",inline"` + TLSFilesConfigApplyConfiguration `json:",inline"` } // TLSConfigApplyConfiguration constructs a declarative configuration of the TLSConfig type for use with @@ -96,7 +94,7 @@ func (b *TLSConfigApplyConfiguration) WithMaxVersion(value monitoringv1.TLSVersi // and returns the receiver, so that objects can be built by chaining "With" function invocations. // If called multiple times, the CAFile field is set to the value of the last call. func (b *TLSConfigApplyConfiguration) WithCAFile(value string) *TLSConfigApplyConfiguration { - b.CAFile = &value + b.TLSFilesConfigApplyConfiguration.CAFile = &value return b } @@ -104,7 +102,7 @@ func (b *TLSConfigApplyConfiguration) WithCAFile(value string) *TLSConfigApplyCo // and returns the receiver, so that objects can be built by chaining "With" function invocations. // If called multiple times, the CertFile field is set to the value of the last call. func (b *TLSConfigApplyConfiguration) WithCertFile(value string) *TLSConfigApplyConfiguration { - b.CertFile = &value + b.TLSFilesConfigApplyConfiguration.CertFile = &value return b } @@ -112,6 +110,6 @@ func (b *TLSConfigApplyConfiguration) WithCertFile(value string) *TLSConfigApply // and returns the receiver, so that objects can be built by chaining "With" function invocations. // If called multiple times, the KeyFile field is set to the value of the last call. func (b *TLSConfigApplyConfiguration) WithKeyFile(value string) *TLSConfigApplyConfiguration { - b.KeyFile = &value + b.TLSFilesConfigApplyConfiguration.KeyFile = &value return b } diff --git a/pkg/client/applyconfiguration/monitoring/v1/tlsfilesconfig.go b/pkg/client/applyconfiguration/monitoring/v1/tlsfilesconfig.go new file mode 100644 index 00000000000..24581704955 --- /dev/null +++ b/pkg/client/applyconfiguration/monitoring/v1/tlsfilesconfig.go @@ -0,0 +1,55 @@ +// Copyright The prometheus-operator Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// Code generated by applyconfiguration-gen. DO NOT EDIT. + +package v1 + +// TLSFilesConfigApplyConfiguration represents a declarative configuration of the TLSFilesConfig type for use +// with apply. +type TLSFilesConfigApplyConfiguration struct { + CAFile *string `json:"caFile,omitempty"` + CertFile *string `json:"certFile,omitempty"` + KeyFile *string `json:"keyFile,omitempty"` +} + +// TLSFilesConfigApplyConfiguration constructs a declarative configuration of the TLSFilesConfig type for use with +// apply. +func TLSFilesConfig() *TLSFilesConfigApplyConfiguration { + return &TLSFilesConfigApplyConfiguration{} +} + +// WithCAFile sets the CAFile field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the CAFile field is set to the value of the last call. +func (b *TLSFilesConfigApplyConfiguration) WithCAFile(value string) *TLSFilesConfigApplyConfiguration { + b.CAFile = &value + return b +} + +// WithCertFile sets the CertFile field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the CertFile field is set to the value of the last call. +func (b *TLSFilesConfigApplyConfiguration) WithCertFile(value string) *TLSFilesConfigApplyConfiguration { + b.CertFile = &value + return b +} + +// WithKeyFile sets the KeyFile field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the KeyFile field is set to the value of the last call. +func (b *TLSFilesConfigApplyConfiguration) WithKeyFile(value string) *TLSFilesConfigApplyConfiguration { + b.KeyFile = &value + return b +} diff --git a/pkg/client/applyconfiguration/monitoring/v1/prometheustracingconfig.go b/pkg/client/applyconfiguration/monitoring/v1/tracingconfig.go similarity index 73% rename from pkg/client/applyconfiguration/monitoring/v1/prometheustracingconfig.go rename to pkg/client/applyconfiguration/monitoring/v1/tracingconfig.go index c461a133240..a75c8f18848 100644 --- a/pkg/client/applyconfiguration/monitoring/v1/prometheustracingconfig.go +++ b/pkg/client/applyconfiguration/monitoring/v1/tracingconfig.go @@ -21,9 +21,9 @@ import ( resource "k8s.io/apimachinery/pkg/api/resource" ) -// PrometheusTracingConfigApplyConfiguration represents a declarative configuration of the PrometheusTracingConfig type for use +// TracingConfigApplyConfiguration represents a declarative configuration of the TracingConfig type for use // with apply. -type PrometheusTracingConfigApplyConfiguration struct { +type TracingConfigApplyConfiguration struct { ClientType *string `json:"clientType,omitempty"` Endpoint *string `json:"endpoint,omitempty"` SamplingFraction *resource.Quantity `json:"samplingFraction,omitempty"` @@ -34,16 +34,16 @@ type PrometheusTracingConfigApplyConfiguration struct { TLSConfig *TLSConfigApplyConfiguration `json:"tlsConfig,omitempty"` } -// PrometheusTracingConfigApplyConfiguration constructs a declarative configuration of the PrometheusTracingConfig type for use with +// TracingConfigApplyConfiguration constructs a declarative configuration of the TracingConfig type for use with // apply. -func PrometheusTracingConfig() *PrometheusTracingConfigApplyConfiguration { - return &PrometheusTracingConfigApplyConfiguration{} +func TracingConfig() *TracingConfigApplyConfiguration { + return &TracingConfigApplyConfiguration{} } // WithClientType sets the ClientType field in the declarative configuration to the given value // and returns the receiver, so that objects can be built by chaining "With" function invocations. // If called multiple times, the ClientType field is set to the value of the last call. -func (b *PrometheusTracingConfigApplyConfiguration) WithClientType(value string) *PrometheusTracingConfigApplyConfiguration { +func (b *TracingConfigApplyConfiguration) WithClientType(value string) *TracingConfigApplyConfiguration { b.ClientType = &value return b } @@ -51,7 +51,7 @@ func (b *PrometheusTracingConfigApplyConfiguration) WithClientType(value string) // WithEndpoint sets the Endpoint field in the declarative configuration to the given value // and returns the receiver, so that objects can be built by chaining "With" function invocations. // If called multiple times, the Endpoint field is set to the value of the last call. -func (b *PrometheusTracingConfigApplyConfiguration) WithEndpoint(value string) *PrometheusTracingConfigApplyConfiguration { +func (b *TracingConfigApplyConfiguration) WithEndpoint(value string) *TracingConfigApplyConfiguration { b.Endpoint = &value return b } @@ -59,7 +59,7 @@ func (b *PrometheusTracingConfigApplyConfiguration) WithEndpoint(value string) * // WithSamplingFraction sets the SamplingFraction field in the declarative configuration to the given value // and returns the receiver, so that objects can be built by chaining "With" function invocations. // If called multiple times, the SamplingFraction field is set to the value of the last call. -func (b *PrometheusTracingConfigApplyConfiguration) WithSamplingFraction(value resource.Quantity) *PrometheusTracingConfigApplyConfiguration { +func (b *TracingConfigApplyConfiguration) WithSamplingFraction(value resource.Quantity) *TracingConfigApplyConfiguration { b.SamplingFraction = &value return b } @@ -67,7 +67,7 @@ func (b *PrometheusTracingConfigApplyConfiguration) WithSamplingFraction(value r // WithInsecure sets the Insecure field in the declarative configuration to the given value // and returns the receiver, so that objects can be built by chaining "With" function invocations. // If called multiple times, the Insecure field is set to the value of the last call. -func (b *PrometheusTracingConfigApplyConfiguration) WithInsecure(value bool) *PrometheusTracingConfigApplyConfiguration { +func (b *TracingConfigApplyConfiguration) WithInsecure(value bool) *TracingConfigApplyConfiguration { b.Insecure = &value return b } @@ -76,7 +76,7 @@ func (b *PrometheusTracingConfigApplyConfiguration) WithInsecure(value bool) *Pr // and returns the receiver, so that objects can be build by chaining "With" function invocations. // If called multiple times, the entries provided by each call will be put on the Headers field, // overwriting an existing map entries in Headers field with the same key. -func (b *PrometheusTracingConfigApplyConfiguration) WithHeaders(entries map[string]string) *PrometheusTracingConfigApplyConfiguration { +func (b *TracingConfigApplyConfiguration) WithHeaders(entries map[string]string) *TracingConfigApplyConfiguration { if b.Headers == nil && len(entries) > 0 { b.Headers = make(map[string]string, len(entries)) } @@ -89,7 +89,7 @@ func (b *PrometheusTracingConfigApplyConfiguration) WithHeaders(entries map[stri // WithCompression sets the Compression field in the declarative configuration to the given value // and returns the receiver, so that objects can be built by chaining "With" function invocations. // If called multiple times, the Compression field is set to the value of the last call. -func (b *PrometheusTracingConfigApplyConfiguration) WithCompression(value string) *PrometheusTracingConfigApplyConfiguration { +func (b *TracingConfigApplyConfiguration) WithCompression(value string) *TracingConfigApplyConfiguration { b.Compression = &value return b } @@ -97,7 +97,7 @@ func (b *PrometheusTracingConfigApplyConfiguration) WithCompression(value string // WithTimeout sets the Timeout field in the declarative configuration to the given value // and returns the receiver, so that objects can be built by chaining "With" function invocations. // If called multiple times, the Timeout field is set to the value of the last call. -func (b *PrometheusTracingConfigApplyConfiguration) WithTimeout(value monitoringv1.Duration) *PrometheusTracingConfigApplyConfiguration { +func (b *TracingConfigApplyConfiguration) WithTimeout(value monitoringv1.Duration) *TracingConfigApplyConfiguration { b.Timeout = &value return b } @@ -105,7 +105,7 @@ func (b *PrometheusTracingConfigApplyConfiguration) WithTimeout(value monitoring // WithTLSConfig sets the TLSConfig field in the declarative configuration to the given value // and returns the receiver, so that objects can be built by chaining "With" function invocations. // If called multiple times, the TLSConfig field is set to the value of the last call. -func (b *PrometheusTracingConfigApplyConfiguration) WithTLSConfig(value *TLSConfigApplyConfiguration) *PrometheusTracingConfigApplyConfiguration { +func (b *TracingConfigApplyConfiguration) WithTLSConfig(value *TLSConfigApplyConfiguration) *TracingConfigApplyConfiguration { b.TLSConfig = value return b } diff --git a/pkg/client/applyconfiguration/monitoring/v1alpha1/alertmanagerconfig.go b/pkg/client/applyconfiguration/monitoring/v1alpha1/alertmanagerconfig.go index dd7e9dfbed8..157a4f25ec0 100644 --- a/pkg/client/applyconfiguration/monitoring/v1alpha1/alertmanagerconfig.go +++ b/pkg/client/applyconfiguration/monitoring/v1alpha1/alertmanagerconfig.go @@ -17,6 +17,7 @@ package v1alpha1 import ( + monitoringv1 "github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" types "k8s.io/apimachinery/pkg/types" v1 "k8s.io/client-go/applyconfigurations/meta/v1" @@ -27,7 +28,8 @@ import ( type AlertmanagerConfigApplyConfiguration struct { v1.TypeMetaApplyConfiguration `json:",inline"` *v1.ObjectMetaApplyConfiguration `json:"metadata,omitempty"` - Spec *AlertmanagerConfigSpecApplyConfiguration `json:"spec,omitempty"` + Spec *AlertmanagerConfigSpecApplyConfiguration `json:"spec,omitempty"` + Status *monitoringv1.ConfigResourceStatusApplyConfiguration `json:"status,omitempty"` } // AlertmanagerConfig constructs a declarative configuration of the AlertmanagerConfig type for use with @@ -208,6 +210,14 @@ func (b *AlertmanagerConfigApplyConfiguration) WithSpec(value *AlertmanagerConfi return b } +// WithStatus sets the Status field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the Status field is set to the value of the last call. +func (b *AlertmanagerConfigApplyConfiguration) WithStatus(value *monitoringv1.ConfigResourceStatusApplyConfiguration) *AlertmanagerConfigApplyConfiguration { + b.Status = value + return b +} + // GetKind retrieves the value of the Kind field in the declarative configuration. func (b *AlertmanagerConfigApplyConfiguration) GetKind() *string { return b.TypeMetaApplyConfiguration.Kind diff --git a/pkg/client/applyconfiguration/monitoring/v1alpha1/opsgenieconfig.go b/pkg/client/applyconfiguration/monitoring/v1alpha1/opsgenieconfig.go index d8bbd7d8810..2ddb9b240b6 100644 --- a/pkg/client/applyconfiguration/monitoring/v1alpha1/opsgenieconfig.go +++ b/pkg/client/applyconfiguration/monitoring/v1alpha1/opsgenieconfig.go @@ -17,6 +17,7 @@ package v1alpha1 import ( + monitoringv1alpha1 "github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1alpha1" v1 "k8s.io/api/core/v1" ) @@ -25,7 +26,7 @@ import ( type OpsGenieConfigApplyConfiguration struct { SendResolved *bool `json:"sendResolved,omitempty"` APIKey *v1.SecretKeySelector `json:"apiKey,omitempty"` - APIURL *string `json:"apiURL,omitempty"` + APIURL *monitoringv1alpha1.URL `json:"apiURL,omitempty"` Message *string `json:"message,omitempty"` Description *string `json:"description,omitempty"` Source *string `json:"source,omitempty"` @@ -65,7 +66,7 @@ func (b *OpsGenieConfigApplyConfiguration) WithAPIKey(value v1.SecretKeySelector // WithAPIURL sets the APIURL field in the declarative configuration to the given value // and returns the receiver, so that objects can be built by chaining "With" function invocations. // If called multiple times, the APIURL field is set to the value of the last call. -func (b *OpsGenieConfigApplyConfiguration) WithAPIURL(value string) *OpsGenieConfigApplyConfiguration { +func (b *OpsGenieConfigApplyConfiguration) WithAPIURL(value monitoringv1alpha1.URL) *OpsGenieConfigApplyConfiguration { b.APIURL = &value return b } diff --git a/pkg/client/applyconfiguration/monitoring/v1alpha1/pagerdutyconfig.go b/pkg/client/applyconfiguration/monitoring/v1alpha1/pagerdutyconfig.go index b33e6802d91..36229445469 100644 --- a/pkg/client/applyconfiguration/monitoring/v1alpha1/pagerdutyconfig.go +++ b/pkg/client/applyconfiguration/monitoring/v1alpha1/pagerdutyconfig.go @@ -17,6 +17,8 @@ package v1alpha1 import ( + monitoringv1 "github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1" + monitoringv1alpha1 "github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1alpha1" v1 "k8s.io/api/core/v1" ) @@ -26,9 +28,9 @@ type PagerDutyConfigApplyConfiguration struct { SendResolved *bool `json:"sendResolved,omitempty"` RoutingKey *v1.SecretKeySelector `json:"routingKey,omitempty"` ServiceKey *v1.SecretKeySelector `json:"serviceKey,omitempty"` - URL *string `json:"url,omitempty"` + URL *monitoringv1alpha1.URL `json:"url,omitempty"` Client *string `json:"client,omitempty"` - ClientURL *string `json:"clientURL,omitempty"` + ClientURL *monitoringv1alpha1.URL `json:"clientURL,omitempty"` Description *string `json:"description,omitempty"` Severity *string `json:"severity,omitempty"` Class *string `json:"class,omitempty"` @@ -39,6 +41,7 @@ type PagerDutyConfigApplyConfiguration struct { PagerDutyLinkConfigs []PagerDutyLinkConfigApplyConfiguration `json:"pagerDutyLinkConfigs,omitempty"` HTTPConfig *HTTPConfigApplyConfiguration `json:"httpConfig,omitempty"` Source *string `json:"source,omitempty"` + Timeout *monitoringv1.Duration `json:"timeout,omitempty"` } // PagerDutyConfigApplyConfiguration constructs a declarative configuration of the PagerDutyConfig type for use with @@ -74,7 +77,7 @@ func (b *PagerDutyConfigApplyConfiguration) WithServiceKey(value v1.SecretKeySel // WithURL sets the URL field in the declarative configuration to the given value // and returns the receiver, so that objects can be built by chaining "With" function invocations. // If called multiple times, the URL field is set to the value of the last call. -func (b *PagerDutyConfigApplyConfiguration) WithURL(value string) *PagerDutyConfigApplyConfiguration { +func (b *PagerDutyConfigApplyConfiguration) WithURL(value monitoringv1alpha1.URL) *PagerDutyConfigApplyConfiguration { b.URL = &value return b } @@ -90,7 +93,7 @@ func (b *PagerDutyConfigApplyConfiguration) WithClient(value string) *PagerDutyC // WithClientURL sets the ClientURL field in the declarative configuration to the given value // and returns the receiver, so that objects can be built by chaining "With" function invocations. // If called multiple times, the ClientURL field is set to the value of the last call. -func (b *PagerDutyConfigApplyConfiguration) WithClientURL(value string) *PagerDutyConfigApplyConfiguration { +func (b *PagerDutyConfigApplyConfiguration) WithClientURL(value monitoringv1alpha1.URL) *PagerDutyConfigApplyConfiguration { b.ClientURL = &value return b } @@ -189,3 +192,11 @@ func (b *PagerDutyConfigApplyConfiguration) WithSource(value string) *PagerDutyC b.Source = &value return b } + +// WithTimeout sets the Timeout field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the Timeout field is set to the value of the last call. +func (b *PagerDutyConfigApplyConfiguration) WithTimeout(value monitoringv1.Duration) *PagerDutyConfigApplyConfiguration { + b.Timeout = &value + return b +} diff --git a/pkg/client/applyconfiguration/monitoring/v1alpha1/pagerdutyimageconfig.go b/pkg/client/applyconfiguration/monitoring/v1alpha1/pagerdutyimageconfig.go index a0759824b88..d4325e80a72 100644 --- a/pkg/client/applyconfiguration/monitoring/v1alpha1/pagerdutyimageconfig.go +++ b/pkg/client/applyconfiguration/monitoring/v1alpha1/pagerdutyimageconfig.go @@ -16,12 +16,16 @@ package v1alpha1 +import ( + monitoringv1alpha1 "github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1alpha1" +) + // PagerDutyImageConfigApplyConfiguration represents a declarative configuration of the PagerDutyImageConfig type for use // with apply. type PagerDutyImageConfigApplyConfiguration struct { - Src *string `json:"src,omitempty"` - Href *string `json:"href,omitempty"` - Alt *string `json:"alt,omitempty"` + Src *string `json:"src,omitempty"` + Href *monitoringv1alpha1.URL `json:"href,omitempty"` + Alt *string `json:"alt,omitempty"` } // PagerDutyImageConfigApplyConfiguration constructs a declarative configuration of the PagerDutyImageConfig type for use with @@ -41,7 +45,7 @@ func (b *PagerDutyImageConfigApplyConfiguration) WithSrc(value string) *PagerDut // WithHref sets the Href field in the declarative configuration to the given value // and returns the receiver, so that objects can be built by chaining "With" function invocations. // If called multiple times, the Href field is set to the value of the last call. -func (b *PagerDutyImageConfigApplyConfiguration) WithHref(value string) *PagerDutyImageConfigApplyConfiguration { +func (b *PagerDutyImageConfigApplyConfiguration) WithHref(value monitoringv1alpha1.URL) *PagerDutyImageConfigApplyConfiguration { b.Href = &value return b } diff --git a/pkg/client/applyconfiguration/monitoring/v1alpha1/pagerdutylinkconfig.go b/pkg/client/applyconfiguration/monitoring/v1alpha1/pagerdutylinkconfig.go index 418c322ac38..7693d89aade 100644 --- a/pkg/client/applyconfiguration/monitoring/v1alpha1/pagerdutylinkconfig.go +++ b/pkg/client/applyconfiguration/monitoring/v1alpha1/pagerdutylinkconfig.go @@ -16,11 +16,15 @@ package v1alpha1 +import ( + monitoringv1alpha1 "github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1alpha1" +) + // PagerDutyLinkConfigApplyConfiguration represents a declarative configuration of the PagerDutyLinkConfig type for use // with apply. type PagerDutyLinkConfigApplyConfiguration struct { - Href *string `json:"href,omitempty"` - Text *string `json:"alt,omitempty"` + Href *monitoringv1alpha1.URL `json:"href,omitempty"` + Text *string `json:"alt,omitempty"` } // PagerDutyLinkConfigApplyConfiguration constructs a declarative configuration of the PagerDutyLinkConfig type for use with @@ -32,7 +36,7 @@ func PagerDutyLinkConfig() *PagerDutyLinkConfigApplyConfiguration { // WithHref sets the Href field in the declarative configuration to the given value // and returns the receiver, so that objects can be built by chaining "With" function invocations. // If called multiple times, the Href field is set to the value of the last call. -func (b *PagerDutyLinkConfigApplyConfiguration) WithHref(value string) *PagerDutyLinkConfigApplyConfiguration { +func (b *PagerDutyLinkConfigApplyConfiguration) WithHref(value monitoringv1alpha1.URL) *PagerDutyLinkConfigApplyConfiguration { b.Href = &value return b } diff --git a/pkg/client/applyconfiguration/monitoring/v1alpha1/prometheusagentspec.go b/pkg/client/applyconfiguration/monitoring/v1alpha1/prometheusagentspec.go index 7255e57c114..347ef88661b 100644 --- a/pkg/client/applyconfiguration/monitoring/v1alpha1/prometheusagentspec.go +++ b/pkg/client/applyconfiguration/monitoring/v1alpha1/prometheusagentspec.go @@ -486,6 +486,22 @@ func (b *PrometheusAgentSpecApplyConfiguration) WithListenLocal(value bool) *Pro return b } +// WithPodManagementPolicy sets the PodManagementPolicy field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the PodManagementPolicy field is set to the value of the last call. +func (b *PrometheusAgentSpecApplyConfiguration) WithPodManagementPolicy(value monitoringv1.PodManagementPolicyType) *PrometheusAgentSpecApplyConfiguration { + b.CommonPrometheusFieldsApplyConfiguration.PodManagementPolicy = &value + return b +} + +// WithUpdateStrategy sets the UpdateStrategy field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the UpdateStrategy field is set to the value of the last call. +func (b *PrometheusAgentSpecApplyConfiguration) WithUpdateStrategy(value *v1.StatefulSetUpdateStrategyApplyConfiguration) *PrometheusAgentSpecApplyConfiguration { + b.CommonPrometheusFieldsApplyConfiguration.UpdateStrategy = value + return b +} + // WithEnableServiceLinks sets the EnableServiceLinks field in the declarative configuration to the given value // and returns the receiver, so that objects can be built by chaining "With" function invocations. // If called multiple times, the EnableServiceLinks field is set to the value of the last call. @@ -666,6 +682,14 @@ func (b *PrometheusAgentSpecApplyConfiguration) WithConvertClassicHistogramsToNH return b } +// WithScrapeNativeHistograms sets the ScrapeNativeHistograms field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the ScrapeNativeHistograms field is set to the value of the last call. +func (b *PrometheusAgentSpecApplyConfiguration) WithScrapeNativeHistograms(value bool) *PrometheusAgentSpecApplyConfiguration { + b.CommonPrometheusFieldsApplyConfiguration.ScrapeNativeHistograms = &value + return b +} + // WithScrapeClassicHistograms sets the ScrapeClassicHistograms field in the declarative configuration to the given value // and returns the receiver, so that objects can be built by chaining "With" function invocations. // If called multiple times, the ScrapeClassicHistograms field is set to the value of the last call. @@ -750,7 +774,7 @@ func (b *PrometheusAgentSpecApplyConfiguration) WithPodTargetLabels(values ...st // WithTracingConfig sets the TracingConfig field in the declarative configuration to the given value // and returns the receiver, so that objects can be built by chaining "With" function invocations. // If called multiple times, the TracingConfig field is set to the value of the last call. -func (b *PrometheusAgentSpecApplyConfiguration) WithTracingConfig(value *v1.PrometheusTracingConfigApplyConfiguration) *PrometheusAgentSpecApplyConfiguration { +func (b *PrometheusAgentSpecApplyConfiguration) WithTracingConfig(value *v1.TracingConfigApplyConfiguration) *PrometheusAgentSpecApplyConfiguration { b.CommonPrometheusFieldsApplyConfiguration.TracingConfig = value return b } diff --git a/pkg/client/applyconfiguration/monitoring/v1alpha1/pushoverconfig.go b/pkg/client/applyconfiguration/monitoring/v1alpha1/pushoverconfig.go index c51188be5cb..da1f1c17230 100644 --- a/pkg/client/applyconfiguration/monitoring/v1alpha1/pushoverconfig.go +++ b/pkg/client/applyconfiguration/monitoring/v1alpha1/pushoverconfig.go @@ -18,6 +18,7 @@ package v1alpha1 import ( monitoringv1 "github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1" + monitoringv1alpha1 "github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1alpha1" v1 "k8s.io/api/core/v1" ) @@ -31,7 +32,7 @@ type PushoverConfigApplyConfiguration struct { TokenFile *string `json:"tokenFile,omitempty"` Title *string `json:"title,omitempty"` Message *string `json:"message,omitempty"` - URL *string `json:"url,omitempty"` + URL *monitoringv1alpha1.URL `json:"url,omitempty"` URLTitle *string `json:"urlTitle,omitempty"` TTL *monitoringv1.Duration `json:"ttl,omitempty"` Device *string `json:"device,omitempty"` @@ -109,7 +110,7 @@ func (b *PushoverConfigApplyConfiguration) WithMessage(value string) *PushoverCo // WithURL sets the URL field in the declarative configuration to the given value // and returns the receiver, so that objects can be built by chaining "With" function invocations. // If called multiple times, the URL field is set to the value of the last call. -func (b *PushoverConfigApplyConfiguration) WithURL(value string) *PushoverConfigApplyConfiguration { +func (b *PushoverConfigApplyConfiguration) WithURL(value monitoringv1alpha1.URL) *PushoverConfigApplyConfiguration { b.URL = &value return b } diff --git a/pkg/client/applyconfiguration/monitoring/v1alpha1/scrapeconfigspec.go b/pkg/client/applyconfiguration/monitoring/v1alpha1/scrapeconfigspec.go index 8f8078f0ae2..8e212b53691 100644 --- a/pkg/client/applyconfiguration/monitoring/v1alpha1/scrapeconfigspec.go +++ b/pkg/client/applyconfiguration/monitoring/v1alpha1/scrapeconfigspec.go @@ -583,6 +583,14 @@ func (b *ScrapeConfigSpecApplyConfiguration) WithLabelValueLengthLimit(value uin return b } +// WithScrapeNativeHistograms sets the ScrapeNativeHistograms field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the ScrapeNativeHistograms field is set to the value of the last call. +func (b *ScrapeConfigSpecApplyConfiguration) WithScrapeNativeHistograms(value bool) *ScrapeConfigSpecApplyConfiguration { + b.NativeHistogramConfigApplyConfiguration.ScrapeNativeHistograms = &value + return b +} + // WithScrapeClassicHistograms sets the ScrapeClassicHistograms field in the declarative configuration to the given value // and returns the receiver, so that objects can be built by chaining "With" function invocations. // If called multiple times, the ScrapeClassicHistograms field is set to the value of the last call. diff --git a/pkg/client/applyconfiguration/monitoring/v1alpha1/slackaction.go b/pkg/client/applyconfiguration/monitoring/v1alpha1/slackaction.go index 39878c54a6b..5837e098789 100644 --- a/pkg/client/applyconfiguration/monitoring/v1alpha1/slackaction.go +++ b/pkg/client/applyconfiguration/monitoring/v1alpha1/slackaction.go @@ -16,12 +16,16 @@ package v1alpha1 +import ( + monitoringv1alpha1 "github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1alpha1" +) + // SlackActionApplyConfiguration represents a declarative configuration of the SlackAction type for use // with apply. type SlackActionApplyConfiguration struct { Type *string `json:"type,omitempty"` Text *string `json:"text,omitempty"` - URL *string `json:"url,omitempty"` + URL *monitoringv1alpha1.URL `json:"url,omitempty"` Style *string `json:"style,omitempty"` Name *string `json:"name,omitempty"` Value *string `json:"value,omitempty"` @@ -53,7 +57,7 @@ func (b *SlackActionApplyConfiguration) WithText(value string) *SlackActionApply // WithURL sets the URL field in the declarative configuration to the given value // and returns the receiver, so that objects can be built by chaining "With" function invocations. // If called multiple times, the URL field is set to the value of the last call. -func (b *SlackActionApplyConfiguration) WithURL(value string) *SlackActionApplyConfiguration { +func (b *SlackActionApplyConfiguration) WithURL(value monitoringv1alpha1.URL) *SlackActionApplyConfiguration { b.URL = &value return b } diff --git a/pkg/client/applyconfiguration/monitoring/v1alpha1/slackconfig.go b/pkg/client/applyconfiguration/monitoring/v1alpha1/slackconfig.go index d0c9904f15a..0b07c752ed1 100644 --- a/pkg/client/applyconfiguration/monitoring/v1alpha1/slackconfig.go +++ b/pkg/client/applyconfiguration/monitoring/v1alpha1/slackconfig.go @@ -17,6 +17,8 @@ package v1alpha1 import ( + monitoringv1 "github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1" + monitoringv1alpha1 "github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1alpha1" v1 "k8s.io/api/core/v1" ) @@ -29,7 +31,7 @@ type SlackConfigApplyConfiguration struct { Username *string `json:"username,omitempty"` Color *string `json:"color,omitempty"` Title *string `json:"title,omitempty"` - TitleLink *string `json:"titleLink,omitempty"` + TitleLink *monitoringv1alpha1.URL `json:"titleLink,omitempty"` Pretext *string `json:"pretext,omitempty"` Text *string `json:"text,omitempty"` Fields []SlackFieldApplyConfiguration `json:"fields,omitempty"` @@ -38,13 +40,14 @@ type SlackConfigApplyConfiguration struct { Fallback *string `json:"fallback,omitempty"` CallbackID *string `json:"callbackId,omitempty"` IconEmoji *string `json:"iconEmoji,omitempty"` - IconURL *string `json:"iconURL,omitempty"` - ImageURL *string `json:"imageURL,omitempty"` - ThumbURL *string `json:"thumbURL,omitempty"` + IconURL *monitoringv1alpha1.URL `json:"iconURL,omitempty"` + ImageURL *monitoringv1alpha1.URL `json:"imageURL,omitempty"` + ThumbURL *monitoringv1alpha1.URL `json:"thumbURL,omitempty"` LinkNames *bool `json:"linkNames,omitempty"` MrkdwnIn []string `json:"mrkdwnIn,omitempty"` Actions []SlackActionApplyConfiguration `json:"actions,omitempty"` HTTPConfig *HTTPConfigApplyConfiguration `json:"httpConfig,omitempty"` + Timeout *monitoringv1.Duration `json:"timeout,omitempty"` } // SlackConfigApplyConfiguration constructs a declarative configuration of the SlackConfig type for use with @@ -104,7 +107,7 @@ func (b *SlackConfigApplyConfiguration) WithTitle(value string) *SlackConfigAppl // WithTitleLink sets the TitleLink field in the declarative configuration to the given value // and returns the receiver, so that objects can be built by chaining "With" function invocations. // If called multiple times, the TitleLink field is set to the value of the last call. -func (b *SlackConfigApplyConfiguration) WithTitleLink(value string) *SlackConfigApplyConfiguration { +func (b *SlackConfigApplyConfiguration) WithTitleLink(value monitoringv1alpha1.URL) *SlackConfigApplyConfiguration { b.TitleLink = &value return b } @@ -181,7 +184,7 @@ func (b *SlackConfigApplyConfiguration) WithIconEmoji(value string) *SlackConfig // WithIconURL sets the IconURL field in the declarative configuration to the given value // and returns the receiver, so that objects can be built by chaining "With" function invocations. // If called multiple times, the IconURL field is set to the value of the last call. -func (b *SlackConfigApplyConfiguration) WithIconURL(value string) *SlackConfigApplyConfiguration { +func (b *SlackConfigApplyConfiguration) WithIconURL(value monitoringv1alpha1.URL) *SlackConfigApplyConfiguration { b.IconURL = &value return b } @@ -189,7 +192,7 @@ func (b *SlackConfigApplyConfiguration) WithIconURL(value string) *SlackConfigAp // WithImageURL sets the ImageURL field in the declarative configuration to the given value // and returns the receiver, so that objects can be built by chaining "With" function invocations. // If called multiple times, the ImageURL field is set to the value of the last call. -func (b *SlackConfigApplyConfiguration) WithImageURL(value string) *SlackConfigApplyConfiguration { +func (b *SlackConfigApplyConfiguration) WithImageURL(value monitoringv1alpha1.URL) *SlackConfigApplyConfiguration { b.ImageURL = &value return b } @@ -197,7 +200,7 @@ func (b *SlackConfigApplyConfiguration) WithImageURL(value string) *SlackConfigA // WithThumbURL sets the ThumbURL field in the declarative configuration to the given value // and returns the receiver, so that objects can be built by chaining "With" function invocations. // If called multiple times, the ThumbURL field is set to the value of the last call. -func (b *SlackConfigApplyConfiguration) WithThumbURL(value string) *SlackConfigApplyConfiguration { +func (b *SlackConfigApplyConfiguration) WithThumbURL(value monitoringv1alpha1.URL) *SlackConfigApplyConfiguration { b.ThumbURL = &value return b } @@ -240,3 +243,11 @@ func (b *SlackConfigApplyConfiguration) WithHTTPConfig(value *HTTPConfigApplyCon b.HTTPConfig = value return b } + +// WithTimeout sets the Timeout field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the Timeout field is set to the value of the last call. +func (b *SlackConfigApplyConfiguration) WithTimeout(value monitoringv1.Duration) *SlackConfigApplyConfiguration { + b.Timeout = &value + return b +} diff --git a/pkg/client/applyconfiguration/monitoring/v1alpha1/telegramconfig.go b/pkg/client/applyconfiguration/monitoring/v1alpha1/telegramconfig.go index 37cb9107425..34ad12e97ad 100644 --- a/pkg/client/applyconfiguration/monitoring/v1alpha1/telegramconfig.go +++ b/pkg/client/applyconfiguration/monitoring/v1alpha1/telegramconfig.go @@ -17,6 +17,7 @@ package v1alpha1 import ( + monitoringv1alpha1 "github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1alpha1" v1 "k8s.io/api/core/v1" ) @@ -24,7 +25,7 @@ import ( // with apply. type TelegramConfigApplyConfiguration struct { SendResolved *bool `json:"sendResolved,omitempty"` - APIURL *string `json:"apiURL,omitempty"` + APIURL *monitoringv1alpha1.URL `json:"apiURL,omitempty"` BotToken *v1.SecretKeySelector `json:"botToken,omitempty"` BotTokenFile *string `json:"botTokenFile,omitempty"` ChatID *int64 `json:"chatID,omitempty"` @@ -52,7 +53,7 @@ func (b *TelegramConfigApplyConfiguration) WithSendResolved(value bool) *Telegra // WithAPIURL sets the APIURL field in the declarative configuration to the given value // and returns the receiver, so that objects can be built by chaining "With" function invocations. // If called multiple times, the APIURL field is set to the value of the last call. -func (b *TelegramConfigApplyConfiguration) WithAPIURL(value string) *TelegramConfigApplyConfiguration { +func (b *TelegramConfigApplyConfiguration) WithAPIURL(value monitoringv1alpha1.URL) *TelegramConfigApplyConfiguration { b.APIURL = &value return b } diff --git a/pkg/client/applyconfiguration/monitoring/v1alpha1/victoropsconfig.go b/pkg/client/applyconfiguration/monitoring/v1alpha1/victoropsconfig.go index b1632d5f4ff..bbd54cb314f 100644 --- a/pkg/client/applyconfiguration/monitoring/v1alpha1/victoropsconfig.go +++ b/pkg/client/applyconfiguration/monitoring/v1alpha1/victoropsconfig.go @@ -17,6 +17,7 @@ package v1alpha1 import ( + monitoringv1alpha1 "github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1alpha1" v1 "k8s.io/api/core/v1" ) @@ -25,7 +26,7 @@ import ( type VictorOpsConfigApplyConfiguration struct { SendResolved *bool `json:"sendResolved,omitempty"` APIKey *v1.SecretKeySelector `json:"apiKey,omitempty"` - APIURL *string `json:"apiUrl,omitempty"` + APIURL *monitoringv1alpha1.URL `json:"apiUrl,omitempty"` RoutingKey *string `json:"routingKey,omitempty"` MessageType *string `json:"messageType,omitempty"` EntityDisplayName *string `json:"entityDisplayName,omitempty"` @@ -60,7 +61,7 @@ func (b *VictorOpsConfigApplyConfiguration) WithAPIKey(value v1.SecretKeySelecto // WithAPIURL sets the APIURL field in the declarative configuration to the given value // and returns the receiver, so that objects can be built by chaining "With" function invocations. // If called multiple times, the APIURL field is set to the value of the last call. -func (b *VictorOpsConfigApplyConfiguration) WithAPIURL(value string) *VictorOpsConfigApplyConfiguration { +func (b *VictorOpsConfigApplyConfiguration) WithAPIURL(value monitoringv1alpha1.URL) *VictorOpsConfigApplyConfiguration { b.APIURL = &value return b } diff --git a/pkg/client/applyconfiguration/monitoring/v1alpha1/webhookconfig.go b/pkg/client/applyconfiguration/monitoring/v1alpha1/webhookconfig.go index 214064e981c..d7190b51008 100644 --- a/pkg/client/applyconfiguration/monitoring/v1alpha1/webhookconfig.go +++ b/pkg/client/applyconfiguration/monitoring/v1alpha1/webhookconfig.go @@ -18,6 +18,7 @@ package v1alpha1 import ( monitoringv1 "github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1" + monitoringv1alpha1 "github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1alpha1" v1 "k8s.io/api/core/v1" ) @@ -25,7 +26,7 @@ import ( // with apply. type WebhookConfigApplyConfiguration struct { SendResolved *bool `json:"sendResolved,omitempty"` - URL *string `json:"url,omitempty"` + URL *monitoringv1alpha1.URL `json:"url,omitempty"` URLSecret *v1.SecretKeySelector `json:"urlSecret,omitempty"` HTTPConfig *HTTPConfigApplyConfiguration `json:"httpConfig,omitempty"` MaxAlerts *int32 `json:"maxAlerts,omitempty"` @@ -49,7 +50,7 @@ func (b *WebhookConfigApplyConfiguration) WithSendResolved(value bool) *WebhookC // WithURL sets the URL field in the declarative configuration to the given value // and returns the receiver, so that objects can be built by chaining "With" function invocations. // If called multiple times, the URL field is set to the value of the last call. -func (b *WebhookConfigApplyConfiguration) WithURL(value string) *WebhookConfigApplyConfiguration { +func (b *WebhookConfigApplyConfiguration) WithURL(value monitoringv1alpha1.URL) *WebhookConfigApplyConfiguration { b.URL = &value return b } diff --git a/pkg/client/applyconfiguration/monitoring/v1alpha1/wechatconfig.go b/pkg/client/applyconfiguration/monitoring/v1alpha1/wechatconfig.go index de747f63391..3f3b134af72 100644 --- a/pkg/client/applyconfiguration/monitoring/v1alpha1/wechatconfig.go +++ b/pkg/client/applyconfiguration/monitoring/v1alpha1/wechatconfig.go @@ -17,6 +17,7 @@ package v1alpha1 import ( + monitoringv1alpha1 "github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1alpha1" v1 "k8s.io/api/core/v1" ) @@ -25,7 +26,7 @@ import ( type WeChatConfigApplyConfiguration struct { SendResolved *bool `json:"sendResolved,omitempty"` APISecret *v1.SecretKeySelector `json:"apiSecret,omitempty"` - APIURL *string `json:"apiURL,omitempty"` + APIURL *monitoringv1alpha1.URL `json:"apiURL,omitempty"` CorpID *string `json:"corpID,omitempty"` AgentID *string `json:"agentID,omitempty"` ToUser *string `json:"toUser,omitempty"` @@ -61,7 +62,7 @@ func (b *WeChatConfigApplyConfiguration) WithAPISecret(value v1.SecretKeySelecto // WithAPIURL sets the APIURL field in the declarative configuration to the given value // and returns the receiver, so that objects can be built by chaining "With" function invocations. // If called multiple times, the APIURL field is set to the value of the last call. -func (b *WeChatConfigApplyConfiguration) WithAPIURL(value string) *WeChatConfigApplyConfiguration { +func (b *WeChatConfigApplyConfiguration) WithAPIURL(value monitoringv1alpha1.URL) *WeChatConfigApplyConfiguration { b.APIURL = &value return b } diff --git a/pkg/client/applyconfiguration/monitoring/v1beta1/alertmanagerconfig.go b/pkg/client/applyconfiguration/monitoring/v1beta1/alertmanagerconfig.go index 2d95b225a07..0c8972507d7 100644 --- a/pkg/client/applyconfiguration/monitoring/v1beta1/alertmanagerconfig.go +++ b/pkg/client/applyconfiguration/monitoring/v1beta1/alertmanagerconfig.go @@ -17,6 +17,7 @@ package v1beta1 import ( + monitoringv1 "github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" types "k8s.io/apimachinery/pkg/types" v1 "k8s.io/client-go/applyconfigurations/meta/v1" @@ -27,7 +28,8 @@ import ( type AlertmanagerConfigApplyConfiguration struct { v1.TypeMetaApplyConfiguration `json:",inline"` *v1.ObjectMetaApplyConfiguration `json:"metadata,omitempty"` - Spec *AlertmanagerConfigSpecApplyConfiguration `json:"spec,omitempty"` + Spec *AlertmanagerConfigSpecApplyConfiguration `json:"spec,omitempty"` + Status *monitoringv1.ConfigResourceStatusApplyConfiguration `json:"status,omitempty"` } // AlertmanagerConfig constructs a declarative configuration of the AlertmanagerConfig type for use with @@ -208,6 +210,14 @@ func (b *AlertmanagerConfigApplyConfiguration) WithSpec(value *AlertmanagerConfi return b } +// WithStatus sets the Status field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the Status field is set to the value of the last call. +func (b *AlertmanagerConfigApplyConfiguration) WithStatus(value *monitoringv1.ConfigResourceStatusApplyConfiguration) *AlertmanagerConfigApplyConfiguration { + b.Status = value + return b +} + // GetKind retrieves the value of the Kind field in the declarative configuration. func (b *AlertmanagerConfigApplyConfiguration) GetKind() *string { return b.TypeMetaApplyConfiguration.Kind diff --git a/pkg/client/applyconfiguration/monitoring/v1beta1/opsgenieconfig.go b/pkg/client/applyconfiguration/monitoring/v1beta1/opsgenieconfig.go index 9fafd3b4658..aa811b8d47b 100644 --- a/pkg/client/applyconfiguration/monitoring/v1beta1/opsgenieconfig.go +++ b/pkg/client/applyconfiguration/monitoring/v1beta1/opsgenieconfig.go @@ -16,12 +16,16 @@ package v1beta1 +import ( + monitoringv1beta1 "github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1beta1" +) + // OpsGenieConfigApplyConfiguration represents a declarative configuration of the OpsGenieConfig type for use // with apply. type OpsGenieConfigApplyConfiguration struct { SendResolved *bool `json:"sendResolved,omitempty"` APIKey *SecretKeySelectorApplyConfiguration `json:"apiKey,omitempty"` - APIURL *string `json:"apiURL,omitempty"` + APIURL *monitoringv1beta1.URL `json:"apiURL,omitempty"` Message *string `json:"message,omitempty"` Description *string `json:"description,omitempty"` Source *string `json:"source,omitempty"` @@ -60,7 +64,7 @@ func (b *OpsGenieConfigApplyConfiguration) WithAPIKey(value *SecretKeySelectorAp // WithAPIURL sets the APIURL field in the declarative configuration to the given value // and returns the receiver, so that objects can be built by chaining "With" function invocations. // If called multiple times, the APIURL field is set to the value of the last call. -func (b *OpsGenieConfigApplyConfiguration) WithAPIURL(value string) *OpsGenieConfigApplyConfiguration { +func (b *OpsGenieConfigApplyConfiguration) WithAPIURL(value monitoringv1beta1.URL) *OpsGenieConfigApplyConfiguration { b.APIURL = &value return b } diff --git a/pkg/client/applyconfiguration/monitoring/v1beta1/pagerdutyconfig.go b/pkg/client/applyconfiguration/monitoring/v1beta1/pagerdutyconfig.go index 653e53ebbf4..8978e021a70 100644 --- a/pkg/client/applyconfiguration/monitoring/v1beta1/pagerdutyconfig.go +++ b/pkg/client/applyconfiguration/monitoring/v1beta1/pagerdutyconfig.go @@ -16,15 +16,20 @@ package v1beta1 +import ( + v1 "github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1" + monitoringv1beta1 "github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1beta1" +) + // PagerDutyConfigApplyConfiguration represents a declarative configuration of the PagerDutyConfig type for use // with apply. type PagerDutyConfigApplyConfiguration struct { SendResolved *bool `json:"sendResolved,omitempty"` RoutingKey *SecretKeySelectorApplyConfiguration `json:"routingKey,omitempty"` ServiceKey *SecretKeySelectorApplyConfiguration `json:"serviceKey,omitempty"` - URL *string `json:"url,omitempty"` + URL *monitoringv1beta1.URL `json:"url,omitempty"` Client *string `json:"client,omitempty"` - ClientURL *string `json:"clientURL,omitempty"` + ClientURL *monitoringv1beta1.URL `json:"clientURL,omitempty"` Description *string `json:"description,omitempty"` Severity *string `json:"severity,omitempty"` Class *string `json:"class,omitempty"` @@ -35,6 +40,7 @@ type PagerDutyConfigApplyConfiguration struct { PagerDutyLinkConfigs []PagerDutyLinkConfigApplyConfiguration `json:"pagerDutyLinkConfigs,omitempty"` HTTPConfig *HTTPConfigApplyConfiguration `json:"httpConfig,omitempty"` Source *string `json:"source,omitempty"` + Timeout *v1.Duration `json:"timeout,omitempty"` } // PagerDutyConfigApplyConfiguration constructs a declarative configuration of the PagerDutyConfig type for use with @@ -70,7 +76,7 @@ func (b *PagerDutyConfigApplyConfiguration) WithServiceKey(value *SecretKeySelec // WithURL sets the URL field in the declarative configuration to the given value // and returns the receiver, so that objects can be built by chaining "With" function invocations. // If called multiple times, the URL field is set to the value of the last call. -func (b *PagerDutyConfigApplyConfiguration) WithURL(value string) *PagerDutyConfigApplyConfiguration { +func (b *PagerDutyConfigApplyConfiguration) WithURL(value monitoringv1beta1.URL) *PagerDutyConfigApplyConfiguration { b.URL = &value return b } @@ -86,7 +92,7 @@ func (b *PagerDutyConfigApplyConfiguration) WithClient(value string) *PagerDutyC // WithClientURL sets the ClientURL field in the declarative configuration to the given value // and returns the receiver, so that objects can be built by chaining "With" function invocations. // If called multiple times, the ClientURL field is set to the value of the last call. -func (b *PagerDutyConfigApplyConfiguration) WithClientURL(value string) *PagerDutyConfigApplyConfiguration { +func (b *PagerDutyConfigApplyConfiguration) WithClientURL(value monitoringv1beta1.URL) *PagerDutyConfigApplyConfiguration { b.ClientURL = &value return b } @@ -185,3 +191,11 @@ func (b *PagerDutyConfigApplyConfiguration) WithSource(value string) *PagerDutyC b.Source = &value return b } + +// WithTimeout sets the Timeout field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the Timeout field is set to the value of the last call. +func (b *PagerDutyConfigApplyConfiguration) WithTimeout(value v1.Duration) *PagerDutyConfigApplyConfiguration { + b.Timeout = &value + return b +} diff --git a/pkg/client/applyconfiguration/monitoring/v1beta1/pagerdutyimageconfig.go b/pkg/client/applyconfiguration/monitoring/v1beta1/pagerdutyimageconfig.go index d49bc2442cd..62602cef883 100644 --- a/pkg/client/applyconfiguration/monitoring/v1beta1/pagerdutyimageconfig.go +++ b/pkg/client/applyconfiguration/monitoring/v1beta1/pagerdutyimageconfig.go @@ -16,12 +16,16 @@ package v1beta1 +import ( + monitoringv1beta1 "github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1beta1" +) + // PagerDutyImageConfigApplyConfiguration represents a declarative configuration of the PagerDutyImageConfig type for use // with apply. type PagerDutyImageConfigApplyConfiguration struct { - Src *string `json:"src,omitempty"` - Href *string `json:"href,omitempty"` - Alt *string `json:"alt,omitempty"` + Src *string `json:"src,omitempty"` + Href *monitoringv1beta1.URL `json:"href,omitempty"` + Alt *string `json:"alt,omitempty"` } // PagerDutyImageConfigApplyConfiguration constructs a declarative configuration of the PagerDutyImageConfig type for use with @@ -41,7 +45,7 @@ func (b *PagerDutyImageConfigApplyConfiguration) WithSrc(value string) *PagerDut // WithHref sets the Href field in the declarative configuration to the given value // and returns the receiver, so that objects can be built by chaining "With" function invocations. // If called multiple times, the Href field is set to the value of the last call. -func (b *PagerDutyImageConfigApplyConfiguration) WithHref(value string) *PagerDutyImageConfigApplyConfiguration { +func (b *PagerDutyImageConfigApplyConfiguration) WithHref(value monitoringv1beta1.URL) *PagerDutyImageConfigApplyConfiguration { b.Href = &value return b } diff --git a/pkg/client/applyconfiguration/monitoring/v1beta1/pagerdutylinkconfig.go b/pkg/client/applyconfiguration/monitoring/v1beta1/pagerdutylinkconfig.go index b4f12a652b4..50eb84b78c4 100644 --- a/pkg/client/applyconfiguration/monitoring/v1beta1/pagerdutylinkconfig.go +++ b/pkg/client/applyconfiguration/monitoring/v1beta1/pagerdutylinkconfig.go @@ -16,11 +16,15 @@ package v1beta1 +import ( + monitoringv1beta1 "github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1beta1" +) + // PagerDutyLinkConfigApplyConfiguration represents a declarative configuration of the PagerDutyLinkConfig type for use // with apply. type PagerDutyLinkConfigApplyConfiguration struct { - Href *string `json:"href,omitempty"` - Text *string `json:"alt,omitempty"` + Href *monitoringv1beta1.URL `json:"href,omitempty"` + Text *string `json:"alt,omitempty"` } // PagerDutyLinkConfigApplyConfiguration constructs a declarative configuration of the PagerDutyLinkConfig type for use with @@ -32,7 +36,7 @@ func PagerDutyLinkConfig() *PagerDutyLinkConfigApplyConfiguration { // WithHref sets the Href field in the declarative configuration to the given value // and returns the receiver, so that objects can be built by chaining "With" function invocations. // If called multiple times, the Href field is set to the value of the last call. -func (b *PagerDutyLinkConfigApplyConfiguration) WithHref(value string) *PagerDutyLinkConfigApplyConfiguration { +func (b *PagerDutyLinkConfigApplyConfiguration) WithHref(value monitoringv1beta1.URL) *PagerDutyLinkConfigApplyConfiguration { b.Href = &value return b } diff --git a/pkg/client/applyconfiguration/monitoring/v1beta1/pushoverconfig.go b/pkg/client/applyconfiguration/monitoring/v1beta1/pushoverconfig.go index ac15ac00604..910b6a07054 100644 --- a/pkg/client/applyconfiguration/monitoring/v1beta1/pushoverconfig.go +++ b/pkg/client/applyconfiguration/monitoring/v1beta1/pushoverconfig.go @@ -18,6 +18,7 @@ package v1beta1 import ( v1 "github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1" + monitoringv1beta1 "github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1beta1" ) // PushoverConfigApplyConfiguration represents a declarative configuration of the PushoverConfig type for use @@ -30,7 +31,7 @@ type PushoverConfigApplyConfiguration struct { TokenFile *string `json:"tokenFile,omitempty"` Title *string `json:"title,omitempty"` Message *string `json:"message,omitempty"` - URL *string `json:"url,omitempty"` + URL *monitoringv1beta1.URL `json:"url,omitempty"` URLTitle *string `json:"urlTitle,omitempty"` TTL *v1.Duration `json:"ttl,omitempty"` Device *string `json:"device,omitempty"` @@ -108,7 +109,7 @@ func (b *PushoverConfigApplyConfiguration) WithMessage(value string) *PushoverCo // WithURL sets the URL field in the declarative configuration to the given value // and returns the receiver, so that objects can be built by chaining "With" function invocations. // If called multiple times, the URL field is set to the value of the last call. -func (b *PushoverConfigApplyConfiguration) WithURL(value string) *PushoverConfigApplyConfiguration { +func (b *PushoverConfigApplyConfiguration) WithURL(value monitoringv1beta1.URL) *PushoverConfigApplyConfiguration { b.URL = &value return b } diff --git a/pkg/client/applyconfiguration/monitoring/v1beta1/slackaction.go b/pkg/client/applyconfiguration/monitoring/v1beta1/slackaction.go index 45511920100..a4f936f3553 100644 --- a/pkg/client/applyconfiguration/monitoring/v1beta1/slackaction.go +++ b/pkg/client/applyconfiguration/monitoring/v1beta1/slackaction.go @@ -16,12 +16,16 @@ package v1beta1 +import ( + monitoringv1beta1 "github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1beta1" +) + // SlackActionApplyConfiguration represents a declarative configuration of the SlackAction type for use // with apply. type SlackActionApplyConfiguration struct { Type *string `json:"type,omitempty"` Text *string `json:"text,omitempty"` - URL *string `json:"url,omitempty"` + URL *monitoringv1beta1.URL `json:"url,omitempty"` Style *string `json:"style,omitempty"` Name *string `json:"name,omitempty"` Value *string `json:"value,omitempty"` @@ -53,7 +57,7 @@ func (b *SlackActionApplyConfiguration) WithText(value string) *SlackActionApply // WithURL sets the URL field in the declarative configuration to the given value // and returns the receiver, so that objects can be built by chaining "With" function invocations. // If called multiple times, the URL field is set to the value of the last call. -func (b *SlackActionApplyConfiguration) WithURL(value string) *SlackActionApplyConfiguration { +func (b *SlackActionApplyConfiguration) WithURL(value monitoringv1beta1.URL) *SlackActionApplyConfiguration { b.URL = &value return b } diff --git a/pkg/client/applyconfiguration/monitoring/v1beta1/slackconfig.go b/pkg/client/applyconfiguration/monitoring/v1beta1/slackconfig.go index 4c86d5287d3..69e888942b0 100644 --- a/pkg/client/applyconfiguration/monitoring/v1beta1/slackconfig.go +++ b/pkg/client/applyconfiguration/monitoring/v1beta1/slackconfig.go @@ -16,6 +16,11 @@ package v1beta1 +import ( + v1 "github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1" + monitoringv1beta1 "github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1beta1" +) + // SlackConfigApplyConfiguration represents a declarative configuration of the SlackConfig type for use // with apply. type SlackConfigApplyConfiguration struct { @@ -25,7 +30,7 @@ type SlackConfigApplyConfiguration struct { Username *string `json:"username,omitempty"` Color *string `json:"color,omitempty"` Title *string `json:"title,omitempty"` - TitleLink *string `json:"titleLink,omitempty"` + TitleLink *monitoringv1beta1.URL `json:"titleLink,omitempty"` Pretext *string `json:"pretext,omitempty"` Text *string `json:"text,omitempty"` Fields []SlackFieldApplyConfiguration `json:"fields,omitempty"` @@ -34,13 +39,14 @@ type SlackConfigApplyConfiguration struct { Fallback *string `json:"fallback,omitempty"` CallbackID *string `json:"callbackId,omitempty"` IconEmoji *string `json:"iconEmoji,omitempty"` - IconURL *string `json:"iconURL,omitempty"` - ImageURL *string `json:"imageURL,omitempty"` - ThumbURL *string `json:"thumbURL,omitempty"` + IconURL *monitoringv1beta1.URL `json:"iconURL,omitempty"` + ImageURL *monitoringv1beta1.URL `json:"imageURL,omitempty"` + ThumbURL *monitoringv1beta1.URL `json:"thumbURL,omitempty"` LinkNames *bool `json:"linkNames,omitempty"` MrkdwnIn []string `json:"mrkdwnIn,omitempty"` Actions []SlackActionApplyConfiguration `json:"actions,omitempty"` HTTPConfig *HTTPConfigApplyConfiguration `json:"httpConfig,omitempty"` + Timeout *v1.Duration `json:"timeout,omitempty"` } // SlackConfigApplyConfiguration constructs a declarative configuration of the SlackConfig type for use with @@ -100,7 +106,7 @@ func (b *SlackConfigApplyConfiguration) WithTitle(value string) *SlackConfigAppl // WithTitleLink sets the TitleLink field in the declarative configuration to the given value // and returns the receiver, so that objects can be built by chaining "With" function invocations. // If called multiple times, the TitleLink field is set to the value of the last call. -func (b *SlackConfigApplyConfiguration) WithTitleLink(value string) *SlackConfigApplyConfiguration { +func (b *SlackConfigApplyConfiguration) WithTitleLink(value monitoringv1beta1.URL) *SlackConfigApplyConfiguration { b.TitleLink = &value return b } @@ -177,7 +183,7 @@ func (b *SlackConfigApplyConfiguration) WithIconEmoji(value string) *SlackConfig // WithIconURL sets the IconURL field in the declarative configuration to the given value // and returns the receiver, so that objects can be built by chaining "With" function invocations. // If called multiple times, the IconURL field is set to the value of the last call. -func (b *SlackConfigApplyConfiguration) WithIconURL(value string) *SlackConfigApplyConfiguration { +func (b *SlackConfigApplyConfiguration) WithIconURL(value monitoringv1beta1.URL) *SlackConfigApplyConfiguration { b.IconURL = &value return b } @@ -185,7 +191,7 @@ func (b *SlackConfigApplyConfiguration) WithIconURL(value string) *SlackConfigAp // WithImageURL sets the ImageURL field in the declarative configuration to the given value // and returns the receiver, so that objects can be built by chaining "With" function invocations. // If called multiple times, the ImageURL field is set to the value of the last call. -func (b *SlackConfigApplyConfiguration) WithImageURL(value string) *SlackConfigApplyConfiguration { +func (b *SlackConfigApplyConfiguration) WithImageURL(value monitoringv1beta1.URL) *SlackConfigApplyConfiguration { b.ImageURL = &value return b } @@ -193,7 +199,7 @@ func (b *SlackConfigApplyConfiguration) WithImageURL(value string) *SlackConfigA // WithThumbURL sets the ThumbURL field in the declarative configuration to the given value // and returns the receiver, so that objects can be built by chaining "With" function invocations. // If called multiple times, the ThumbURL field is set to the value of the last call. -func (b *SlackConfigApplyConfiguration) WithThumbURL(value string) *SlackConfigApplyConfiguration { +func (b *SlackConfigApplyConfiguration) WithThumbURL(value monitoringv1beta1.URL) *SlackConfigApplyConfiguration { b.ThumbURL = &value return b } @@ -236,3 +242,11 @@ func (b *SlackConfigApplyConfiguration) WithHTTPConfig(value *HTTPConfigApplyCon b.HTTPConfig = value return b } + +// WithTimeout sets the Timeout field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the Timeout field is set to the value of the last call. +func (b *SlackConfigApplyConfiguration) WithTimeout(value v1.Duration) *SlackConfigApplyConfiguration { + b.Timeout = &value + return b +} diff --git a/pkg/client/applyconfiguration/monitoring/v1beta1/telegramconfig.go b/pkg/client/applyconfiguration/monitoring/v1beta1/telegramconfig.go index 1c8ea3fddab..474e462ec75 100644 --- a/pkg/client/applyconfiguration/monitoring/v1beta1/telegramconfig.go +++ b/pkg/client/applyconfiguration/monitoring/v1beta1/telegramconfig.go @@ -16,11 +16,15 @@ package v1beta1 +import ( + monitoringv1beta1 "github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1beta1" +) + // TelegramConfigApplyConfiguration represents a declarative configuration of the TelegramConfig type for use // with apply. type TelegramConfigApplyConfiguration struct { SendResolved *bool `json:"sendResolved,omitempty"` - APIURL *string `json:"apiURL,omitempty"` + APIURL *monitoringv1beta1.URL `json:"apiURL,omitempty"` BotToken *SecretKeySelectorApplyConfiguration `json:"botToken,omitempty"` BotTokenFile *string `json:"botTokenFile,omitempty"` ChatID *int64 `json:"chatID,omitempty"` @@ -48,7 +52,7 @@ func (b *TelegramConfigApplyConfiguration) WithSendResolved(value bool) *Telegra // WithAPIURL sets the APIURL field in the declarative configuration to the given value // and returns the receiver, so that objects can be built by chaining "With" function invocations. // If called multiple times, the APIURL field is set to the value of the last call. -func (b *TelegramConfigApplyConfiguration) WithAPIURL(value string) *TelegramConfigApplyConfiguration { +func (b *TelegramConfigApplyConfiguration) WithAPIURL(value monitoringv1beta1.URL) *TelegramConfigApplyConfiguration { b.APIURL = &value return b } diff --git a/pkg/client/applyconfiguration/monitoring/v1beta1/victoropsconfig.go b/pkg/client/applyconfiguration/monitoring/v1beta1/victoropsconfig.go index ffd1be84957..0286668ed20 100644 --- a/pkg/client/applyconfiguration/monitoring/v1beta1/victoropsconfig.go +++ b/pkg/client/applyconfiguration/monitoring/v1beta1/victoropsconfig.go @@ -16,12 +16,16 @@ package v1beta1 +import ( + monitoringv1beta1 "github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1beta1" +) + // VictorOpsConfigApplyConfiguration represents a declarative configuration of the VictorOpsConfig type for use // with apply. type VictorOpsConfigApplyConfiguration struct { SendResolved *bool `json:"sendResolved,omitempty"` APIKey *SecretKeySelectorApplyConfiguration `json:"apiKey,omitempty"` - APIURL *string `json:"apiUrl,omitempty"` + APIURL *monitoringv1beta1.URL `json:"apiUrl,omitempty"` RoutingKey *string `json:"routingKey,omitempty"` MessageType *string `json:"messageType,omitempty"` EntityDisplayName *string `json:"entityDisplayName,omitempty"` @@ -56,7 +60,7 @@ func (b *VictorOpsConfigApplyConfiguration) WithAPIKey(value *SecretKeySelectorA // WithAPIURL sets the APIURL field in the declarative configuration to the given value // and returns the receiver, so that objects can be built by chaining "With" function invocations. // If called multiple times, the APIURL field is set to the value of the last call. -func (b *VictorOpsConfigApplyConfiguration) WithAPIURL(value string) *VictorOpsConfigApplyConfiguration { +func (b *VictorOpsConfigApplyConfiguration) WithAPIURL(value monitoringv1beta1.URL) *VictorOpsConfigApplyConfiguration { b.APIURL = &value return b } diff --git a/pkg/client/applyconfiguration/monitoring/v1beta1/webhookconfig.go b/pkg/client/applyconfiguration/monitoring/v1beta1/webhookconfig.go index 61a59b26132..be6879ed6db 100644 --- a/pkg/client/applyconfiguration/monitoring/v1beta1/webhookconfig.go +++ b/pkg/client/applyconfiguration/monitoring/v1beta1/webhookconfig.go @@ -18,13 +18,14 @@ package v1beta1 import ( v1 "github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1" + monitoringv1beta1 "github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1beta1" ) // WebhookConfigApplyConfiguration represents a declarative configuration of the WebhookConfig type for use // with apply. type WebhookConfigApplyConfiguration struct { SendResolved *bool `json:"sendResolved,omitempty"` - URL *string `json:"url,omitempty"` + URL *monitoringv1beta1.URL `json:"url,omitempty"` URLSecret *SecretKeySelectorApplyConfiguration `json:"urlSecret,omitempty"` HTTPConfig *HTTPConfigApplyConfiguration `json:"httpConfig,omitempty"` MaxAlerts *int32 `json:"maxAlerts,omitempty"` @@ -48,7 +49,7 @@ func (b *WebhookConfigApplyConfiguration) WithSendResolved(value bool) *WebhookC // WithURL sets the URL field in the declarative configuration to the given value // and returns the receiver, so that objects can be built by chaining "With" function invocations. // If called multiple times, the URL field is set to the value of the last call. -func (b *WebhookConfigApplyConfiguration) WithURL(value string) *WebhookConfigApplyConfiguration { +func (b *WebhookConfigApplyConfiguration) WithURL(value monitoringv1beta1.URL) *WebhookConfigApplyConfiguration { b.URL = &value return b } diff --git a/pkg/client/applyconfiguration/monitoring/v1beta1/wechatconfig.go b/pkg/client/applyconfiguration/monitoring/v1beta1/wechatconfig.go index 8ce8441b918..92af08e3180 100644 --- a/pkg/client/applyconfiguration/monitoring/v1beta1/wechatconfig.go +++ b/pkg/client/applyconfiguration/monitoring/v1beta1/wechatconfig.go @@ -16,12 +16,16 @@ package v1beta1 +import ( + monitoringv1beta1 "github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1beta1" +) + // WeChatConfigApplyConfiguration represents a declarative configuration of the WeChatConfig type for use // with apply. type WeChatConfigApplyConfiguration struct { SendResolved *bool `json:"sendResolved,omitempty"` APISecret *SecretKeySelectorApplyConfiguration `json:"apiSecret,omitempty"` - APIURL *string `json:"apiURL,omitempty"` + APIURL *monitoringv1beta1.URL `json:"apiURL,omitempty"` CorpID *string `json:"corpID,omitempty"` AgentID *string `json:"agentID,omitempty"` ToUser *string `json:"toUser,omitempty"` @@ -57,7 +61,7 @@ func (b *WeChatConfigApplyConfiguration) WithAPISecret(value *SecretKeySelectorA // WithAPIURL sets the APIURL field in the declarative configuration to the given value // and returns the receiver, so that objects can be built by chaining "With" function invocations. // If called multiple times, the APIURL field is set to the value of the last call. -func (b *WeChatConfigApplyConfiguration) WithAPIURL(value string) *WeChatConfigApplyConfiguration { +func (b *WeChatConfigApplyConfiguration) WithAPIURL(value monitoringv1beta1.URL) *WeChatConfigApplyConfiguration { b.APIURL = &value return b } diff --git a/pkg/client/applyconfiguration/utils.go b/pkg/client/applyconfiguration/utils.go index f0002d79779..eb697c40e7f 100644 --- a/pkg/client/applyconfiguration/utils.go +++ b/pkg/client/applyconfiguration/utils.go @@ -70,6 +70,8 @@ func ForKind(kind schema.GroupVersionKind) interface{} { return &monitoringv1.AzureOAuthApplyConfiguration{} case v1.SchemeGroupVersion.WithKind("AzureSDK"): return &monitoringv1.AzureSDKApplyConfiguration{} + case v1.SchemeGroupVersion.WithKind("AzureWorkloadIdentity"): + return &monitoringv1.AzureWorkloadIdentityApplyConfiguration{} case v1.SchemeGroupVersion.WithKind("BasicAuth"): return &monitoringv1.BasicAuthApplyConfiguration{} case v1.SchemeGroupVersion.WithKind("ClusterTLSConfig"): @@ -112,6 +114,14 @@ func ForKind(kind schema.GroupVersionKind) interface{} { return &monitoringv1.HostPortApplyConfiguration{} case v1.SchemeGroupVersion.WithKind("HTTPConfig"): return &monitoringv1.HTTPConfigApplyConfiguration{} + case v1.SchemeGroupVersion.WithKind("HTTPConfigWithoutTLS"): + return &monitoringv1.HTTPConfigWithoutTLSApplyConfiguration{} + case v1.SchemeGroupVersion.WithKind("HTTPConfigWithProxy"): + return &monitoringv1.HTTPConfigWithProxyApplyConfiguration{} + case v1.SchemeGroupVersion.WithKind("HTTPConfigWithProxyAndTLSFiles"): + return &monitoringv1.HTTPConfigWithProxyAndTLSFilesApplyConfiguration{} + case v1.SchemeGroupVersion.WithKind("HTTPConfigWithTLSFiles"): + return &monitoringv1.HTTPConfigWithTLSFilesApplyConfiguration{} case v1.SchemeGroupVersion.WithKind("ManagedIdentity"): return &monitoringv1.ManagedIdentityApplyConfiguration{} case v1.SchemeGroupVersion.WithKind("MetadataConfig"): @@ -162,8 +172,6 @@ func ForKind(kind schema.GroupVersionKind) interface{} { return &monitoringv1.PrometheusSpecApplyConfiguration{} case v1.SchemeGroupVersion.WithKind("PrometheusStatus"): return &monitoringv1.PrometheusStatusApplyConfiguration{} - case v1.SchemeGroupVersion.WithKind("PrometheusTracingConfig"): - return &monitoringv1.PrometheusTracingConfigApplyConfiguration{} case v1.SchemeGroupVersion.WithKind("PrometheusWebSpec"): return &monitoringv1.PrometheusWebSpecApplyConfiguration{} case v1.SchemeGroupVersion.WithKind("ProxyConfig"): @@ -180,6 +188,8 @@ func ForKind(kind schema.GroupVersionKind) interface{} { return &monitoringv1.RemoteWriteSpecApplyConfiguration{} case v1.SchemeGroupVersion.WithKind("RetainConfig"): return &monitoringv1.RetainConfigApplyConfiguration{} + case v1.SchemeGroupVersion.WithKind("RollingUpdateStatefulSetStrategy"): + return &monitoringv1.RollingUpdateStatefulSetStrategyApplyConfiguration{} case v1.SchemeGroupVersion.WithKind("Rule"): return &monitoringv1.RuleApplyConfiguration{} case v1.SchemeGroupVersion.WithKind("RuleGroup"): @@ -208,6 +218,8 @@ func ForKind(kind schema.GroupVersionKind) interface{} { return &monitoringv1.ShardStatusApplyConfiguration{} case v1.SchemeGroupVersion.WithKind("Sigv4"): return &monitoringv1.Sigv4ApplyConfiguration{} + case v1.SchemeGroupVersion.WithKind("StatefulSetUpdateStrategy"): + return &monitoringv1.StatefulSetUpdateStrategyApplyConfiguration{} case v1.SchemeGroupVersion.WithKind("StorageSpec"): return &monitoringv1.StorageSpecApplyConfiguration{} case v1.SchemeGroupVersion.WithKind("ThanosRuler"): @@ -222,8 +234,12 @@ func ForKind(kind schema.GroupVersionKind) interface{} { return &monitoringv1.ThanosSpecApplyConfiguration{} case v1.SchemeGroupVersion.WithKind("TLSConfig"): return &monitoringv1.TLSConfigApplyConfiguration{} + case v1.SchemeGroupVersion.WithKind("TLSFilesConfig"): + return &monitoringv1.TLSFilesConfigApplyConfiguration{} case v1.SchemeGroupVersion.WithKind("TopologySpreadConstraint"): return &monitoringv1.TopologySpreadConstraintApplyConfiguration{} + case v1.SchemeGroupVersion.WithKind("TracingConfig"): + return &monitoringv1.TracingConfigApplyConfiguration{} case v1.SchemeGroupVersion.WithKind("TSDBSpec"): return &monitoringv1.TSDBSpecApplyConfiguration{} case v1.SchemeGroupVersion.WithKind("WebConfigFileFields"): diff --git a/pkg/client/go.mod b/pkg/client/go.mod index 8541e461f7a..d3b5e5aa12c 100644 --- a/pkg/client/go.mod +++ b/pkg/client/go.mod @@ -5,11 +5,11 @@ go 1.24.0 toolchain go1.24.3 require ( - github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring v0.87.1 - k8s.io/api v0.34.2 - k8s.io/apiextensions-apiserver v0.34.2 - k8s.io/apimachinery v0.34.2 - k8s.io/client-go v0.34.2 + github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring v0.88.0 + k8s.io/api v0.34.3 + k8s.io/apiextensions-apiserver v0.34.3 + k8s.io/apimachinery v0.34.3 + k8s.io/client-go v0.34.3 sigs.k8s.io/structured-merge-diff/v6 v6.3.0 ) diff --git a/pkg/client/go.sum b/pkg/client/go.sum index db2d722f59b..6ef50aeb22d 100644 --- a/pkg/client/go.sum +++ b/pkg/client/go.sum @@ -143,14 +143,14 @@ gopkg.in/inf.v0 v0.9.1 h1:73M5CoZyi3ZLMOyDlQh031Cx6N9NDJ2Vvfl76EDAgDc= gopkg.in/inf.v0 v0.9.1/go.mod h1:cWUDdTG/fYaXco+Dcufb5Vnc6Gp2YChqWtbxRZE0mXw= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= -k8s.io/api v0.34.2 h1:fsSUNZhV+bnL6Aqrp6O7lMTy6o5x2C4XLjnh//8SLYY= -k8s.io/api v0.34.2/go.mod h1:MMBPaWlED2a8w4RSeanD76f7opUoypY8TFYkSM+3XHw= -k8s.io/apiextensions-apiserver v0.34.2 h1:WStKftnGeoKP4AZRz/BaAAEJvYp4mlZGN0UCv+uvsqo= -k8s.io/apiextensions-apiserver v0.34.2/go.mod h1:398CJrsgXF1wytdaanynDpJ67zG4Xq7yj91GrmYN2SE= -k8s.io/apimachinery v0.34.2 h1:zQ12Uk3eMHPxrsbUJgNF8bTauTVR2WgqJsTmwTE/NW4= -k8s.io/apimachinery v0.34.2/go.mod h1:/GwIlEcWuTX9zKIg2mbw0LRFIsXwrfoVxn+ef0X13lw= -k8s.io/client-go v0.34.2 h1:Co6XiknN+uUZqiddlfAjT68184/37PS4QAzYvQvDR8M= -k8s.io/client-go v0.34.2/go.mod h1:2VYDl1XXJsdcAxw7BenFslRQX28Dxz91U9MWKjX97fE= +k8s.io/api v0.34.3 h1:D12sTP257/jSH2vHV2EDYrb16bS7ULlHpdNdNhEw2S4= +k8s.io/api v0.34.3/go.mod h1:PyVQBF886Q5RSQZOim7DybQjAbVs8g7gwJNhGtY5MBk= +k8s.io/apiextensions-apiserver v0.34.3 h1:p10fGlkDY09eWKOTeUSioxwLukJnm+KuDZdrW71y40g= +k8s.io/apiextensions-apiserver v0.34.3/go.mod h1:aujxvqGFRdb/cmXYfcRTeppN7S2XV/t7WMEc64zB5A0= +k8s.io/apimachinery v0.34.3 h1:/TB+SFEiQvN9HPldtlWOTp0hWbJ+fjU+wkxysf/aQnE= +k8s.io/apimachinery v0.34.3/go.mod h1:/GwIlEcWuTX9zKIg2mbw0LRFIsXwrfoVxn+ef0X13lw= +k8s.io/client-go v0.34.3 h1:wtYtpzy/OPNYf7WyNBTj3iUA0XaBHVqhv4Iv3tbrF5A= +k8s.io/client-go v0.34.3/go.mod h1:OxxeYagaP9Kdf78UrKLa3YZixMCfP6bgPwPwNBQBzpM= k8s.io/klog/v2 v2.130.1 h1:n9Xl7H1Xvksem4KFG4PYbdQCQxqc/tTUyrgXaOhHSzk= k8s.io/klog/v2 v2.130.1/go.mod h1:3Jpz1GvMt720eyJH1ckRHK1EDfpxISzJ7I9OYgaDtPE= k8s.io/kube-openapi v0.0.0-20250910181357-589584f1c912 h1:Y3gxNAuB0OBLImH611+UDZcmKS3g6CthxToOb37KgwE= diff --git a/pkg/client/versioned/typed/monitoring/v1alpha1/alertmanagerconfig.go b/pkg/client/versioned/typed/monitoring/v1alpha1/alertmanagerconfig.go index d9ca01a91c0..bfc032ed528 100644 --- a/pkg/client/versioned/typed/monitoring/v1alpha1/alertmanagerconfig.go +++ b/pkg/client/versioned/typed/monitoring/v1alpha1/alertmanagerconfig.go @@ -38,6 +38,8 @@ type AlertmanagerConfigsGetter interface { type AlertmanagerConfigInterface interface { Create(ctx context.Context, alertmanagerConfig *monitoringv1alpha1.AlertmanagerConfig, opts v1.CreateOptions) (*monitoringv1alpha1.AlertmanagerConfig, error) Update(ctx context.Context, alertmanagerConfig *monitoringv1alpha1.AlertmanagerConfig, opts v1.UpdateOptions) (*monitoringv1alpha1.AlertmanagerConfig, error) + // Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus(). + UpdateStatus(ctx context.Context, alertmanagerConfig *monitoringv1alpha1.AlertmanagerConfig, opts v1.UpdateOptions) (*monitoringv1alpha1.AlertmanagerConfig, error) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error Get(ctx context.Context, name string, opts v1.GetOptions) (*monitoringv1alpha1.AlertmanagerConfig, error) @@ -45,6 +47,8 @@ type AlertmanagerConfigInterface interface { Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *monitoringv1alpha1.AlertmanagerConfig, err error) Apply(ctx context.Context, alertmanagerConfig *applyconfigurationmonitoringv1alpha1.AlertmanagerConfigApplyConfiguration, opts v1.ApplyOptions) (result *monitoringv1alpha1.AlertmanagerConfig, err error) + // Add a +genclient:noStatus comment above the type to avoid generating ApplyStatus(). + ApplyStatus(ctx context.Context, alertmanagerConfig *applyconfigurationmonitoringv1alpha1.AlertmanagerConfigApplyConfiguration, opts v1.ApplyOptions) (result *monitoringv1alpha1.AlertmanagerConfig, err error) AlertmanagerConfigExpansion } diff --git a/pkg/client/versioned/typed/monitoring/v1beta1/alertmanagerconfig.go b/pkg/client/versioned/typed/monitoring/v1beta1/alertmanagerconfig.go index 3c8bf2da37d..1e14605efc1 100644 --- a/pkg/client/versioned/typed/monitoring/v1beta1/alertmanagerconfig.go +++ b/pkg/client/versioned/typed/monitoring/v1beta1/alertmanagerconfig.go @@ -38,6 +38,8 @@ type AlertmanagerConfigsGetter interface { type AlertmanagerConfigInterface interface { Create(ctx context.Context, alertmanagerConfig *monitoringv1beta1.AlertmanagerConfig, opts v1.CreateOptions) (*monitoringv1beta1.AlertmanagerConfig, error) Update(ctx context.Context, alertmanagerConfig *monitoringv1beta1.AlertmanagerConfig, opts v1.UpdateOptions) (*monitoringv1beta1.AlertmanagerConfig, error) + // Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus(). + UpdateStatus(ctx context.Context, alertmanagerConfig *monitoringv1beta1.AlertmanagerConfig, opts v1.UpdateOptions) (*monitoringv1beta1.AlertmanagerConfig, error) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error Get(ctx context.Context, name string, opts v1.GetOptions) (*monitoringv1beta1.AlertmanagerConfig, error) @@ -45,6 +47,8 @@ type AlertmanagerConfigInterface interface { Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *monitoringv1beta1.AlertmanagerConfig, err error) Apply(ctx context.Context, alertmanagerConfig *applyconfigurationmonitoringv1beta1.AlertmanagerConfigApplyConfiguration, opts v1.ApplyOptions) (result *monitoringv1beta1.AlertmanagerConfig, err error) + // Add a +genclient:noStatus comment above the type to avoid generating ApplyStatus(). + ApplyStatus(ctx context.Context, alertmanagerConfig *applyconfigurationmonitoringv1beta1.AlertmanagerConfigApplyConfiguration, opts v1.ApplyOptions) (result *monitoringv1beta1.AlertmanagerConfig, err error) AlertmanagerConfigExpansion } diff --git a/pkg/k8sutil/k8sutil.go b/pkg/k8sutil/k8sutil.go index 8ec19a94c04..b03f02ab574 100644 --- a/pkg/k8sutil/k8sutil.go +++ b/pkg/k8sutil/k8sutil.go @@ -48,6 +48,7 @@ import ( "k8s.io/client-go/rest" "k8s.io/client-go/tools/clientcmd" "k8s.io/client-go/util/retry" + "k8s.io/utils/ptr" monitoringv1 "github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1" monitoringv1alpha1 "github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1alpha1" @@ -315,8 +316,8 @@ func CreateOrUpdateEndpointSlice(ctx context.Context, c clientdiscoveryv1.Endpoi }) } -// UpdateStatefulSet merges metadata of existing StatefulSet with new one and updates it. -func UpdateStatefulSet(ctx context.Context, sstClient clientappsv1.StatefulSetInterface, sset *appsv1.StatefulSet) error { +// updateStatefulSet updates a StatefulSet resource preserving custom labels and annotations from the current resource. +func updateStatefulSet(ctx context.Context, sstClient clientappsv1.StatefulSetInterface, sset *appsv1.StatefulSet) error { // As stated in the RetryOnConflict's documentation, the returned error shouldn't be wrapped. return retry.RetryOnConflict(retry.DefaultRetry, func() error { existingSset, err := sstClient.Get(ctx, sset.Name, metav1.GetOptions{}) @@ -333,6 +334,39 @@ func UpdateStatefulSet(ctx context.Context, sstClient clientappsv1.StatefulSetIn }) } +// ForceUpdateStatefulSet updates a StatefulSet resource preserving custom +// labels and annotations. But when the update operation tries to update +// immutable fields for example, `.spec.selector`), the function will delete +// the statefulset (relying on the higher-level controller to re-create the +// resource during the next reconciliation). +// +// It calls onDeleteFunc when the deletion of the resource is required. The +// function is given a string explaining the reason why the update was not +// possible. +func ForceUpdateStatefulSet(ctx context.Context, ssetClient clientappsv1.StatefulSetInterface, sset *appsv1.StatefulSet, onDeleteFunc func(string)) error { + err := updateStatefulSet(ctx, ssetClient, sset) + if err == nil { + return err + } + + // When trying to update immutable fields, the API server returns a 422 status code. + sErr, ok := err.(*apierrors.StatusError) + if !ok || (sErr.ErrStatus.Code != 422 || sErr.ErrStatus.Reason != metav1.StatusReasonInvalid) { + return fmt.Errorf("failed to update StatefulSet: %w", err) + } + + // Gather the reason(s) why the update failed. + failMsg := make([]string, len(sErr.ErrStatus.Details.Causes)) + for i, cause := range sErr.ErrStatus.Details.Causes { + failMsg[i] = cause.Message + } + if onDeleteFunc != nil { + onDeleteFunc(strings.Join(failMsg, ", ")) + } + + return ssetClient.Delete(ctx, sset.GetName(), metav1.DeleteOptions{PropagationPolicy: ptr.To(metav1.DeletePropagationForeground)}) +} + // UpdateDaemonSet merges metadata of existing DaemonSet with new one and updates it. func UpdateDaemonSet(ctx context.Context, dmsClient clientappsv1.DaemonSetInterface, dset *appsv1.DaemonSet) error { // As stated in the RetryOnConflict's documentation, the returned error shouldn't be wrapped. diff --git a/pkg/k8sutil/k8sutil_test.go b/pkg/k8sutil/k8sutil_test.go index 67f89bde1ba..668fe5a9711 100644 --- a/pkg/k8sutil/k8sutil_test.go +++ b/pkg/k8sutil/k8sutil_test.go @@ -230,7 +230,7 @@ func TestPropagateKubectlTemplateAnnotations(t *testing.T) { modifiedSset := sset.DeepCopy() modifiedSset.Spec.Template.Annotations = tc.new - err := UpdateStatefulSet(ctx, ssetClient, modifiedSset) + err := updateStatefulSet(ctx, ssetClient, modifiedSset) require.NoError(t, err) updatedSset, err := ssetClient.Get(ctx, "prometheus", metav1.GetOptions{}) @@ -390,7 +390,7 @@ func TestMergeMetadata(t *testing.T) { _, err := ssetClient.Update(context.Background(), modifiedSset, metav1.UpdateOptions{}) require.NoError(t, err) - err = UpdateStatefulSet(context.Background(), ssetClient, sset) + err = updateStatefulSet(context.Background(), ssetClient, sset) require.NoError(t, err) updatedSset, err := ssetClient.Get(context.Background(), "prometheus", metav1.GetOptions{}) diff --git a/pkg/operator/argument.go b/pkg/operator/argument.go index df60594e7e7..eb7d7250592 100644 --- a/pkg/operator/argument.go +++ b/pkg/operator/argument.go @@ -16,65 +16,62 @@ package operator import ( "fmt" + "iter" "strings" monitoringv1 "github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1" ) -func intersection(a, b []string) (i []string) { +// ArgumentsIntersection returns the list of arguments which intersect between a and b. +func ArgumentsIntersection(a, b []monitoringv1.Argument) []string { m := make(map[string]struct{}) - - for _, item := range a { + for item := range argumentNameIter(a) { m[item] = struct{}{} } - for _, item := range b { - if _, ok := m[item]; ok { - i = append(i, item) + var intersection []string + for name := range argumentNameIter(b) { + if _, ok := m[name]; ok { + intersection = append(intersection, name) + continue } - negatedItem := strings.TrimPrefix(item, "no-") - if item == negatedItem { - negatedItem = fmt.Sprintf("no-%s", item) + negated, found := strings.CutPrefix(name, "no-") + if !found { + negated = fmt.Sprintf("no-%s", name) } - if _, ok := m[negatedItem]; ok { - i = append(i, item) + if _, ok := m[negated]; ok { + intersection = append(intersection, negated) } } - return i + + return intersection } -func extractArgKeys(args []monitoringv1.Argument) []string { - var k []string - for _, arg := range args { - key := arg.Name - k = append(k, key) +func argumentNameIter(args []monitoringv1.Argument) iter.Seq[string] { + return func(yield func(string) bool) { + for _, arg := range args { + if !yield(arg.Name) { + return + } + } } - - return k } -// BuildArgs takes a list of arguments and a list of additional arguments and returns a []string to use in a container Args. +// BuildArgs returns the concatenation of the 2 argument lists of arguments. +// It returns an error if the 2 lists intersect. func BuildArgs(args []monitoringv1.Argument, additionalArgs []monitoringv1.Argument) ([]string, error) { - var containerArgs []string - - argKeys := extractArgKeys(args) - additionalArgKeys := extractArgKeys(additionalArgs) - - i := intersection(argKeys, additionalArgKeys) - if len(i) > 0 { + if i := ArgumentsIntersection(args, additionalArgs); len(i) > 0 { return nil, fmt.Errorf("can't set arguments which are already managed by the operator: %s", strings.Join(i, ",")) } - args = append(args, additionalArgs...) - - for _, arg := range args { + var containerArgs []string + for _, arg := range append(args, additionalArgs...) { if arg.Value != "" { containerArgs = append(containerArgs, fmt.Sprintf("--%s=%s", arg.Name, arg.Value)) } else { containerArgs = append(containerArgs, fmt.Sprintf("--%s", arg.Name)) - } } diff --git a/pkg/operator/argument_test.go b/pkg/operator/argument_test.go index 644984e0489..dbabd4edd75 100644 --- a/pkg/operator/argument_test.go +++ b/pkg/operator/argument_test.go @@ -15,7 +15,6 @@ package operator import ( - "fmt" "testing" "github.com/stretchr/testify/require" @@ -24,30 +23,63 @@ import ( ) func TestBuildArgs(t *testing.T) { - args := []v1.Argument{ - {Name: "test", Value: "value"}, - {Name: "test2-test", Value: "value2"}, - {Name: "test3.test", Value: "value3"}, - } - - additionalArgs := []v1.Argument{ - {Name: "addtest", Value: "value"}, - {Name: "addtest2-test", Value: "value2"}, - {Name: "addtest3.test", Value: "value3"}, - } - - containerArgs, err := BuildArgs(args, additionalArgs) - if err != nil { - t.Errorf("BuildArgs returned an error: %s", err.Error()) - } - - for _, arg := range args { - argString := fmt.Sprintf("--%s=%s", arg.Name, arg.Value) - require.Contains(t, containerArgs, argString, "expected containerArgs to contain arg %v, got %v", argString, containerArgs) - } - - for _, arg := range additionalArgs { - argString := fmt.Sprintf("--%s=%s", arg.Name, arg.Value) - require.Contains(t, containerArgs, argString, "expected containerArgs to contain additionalArg %v, got %v", argString, containerArgs) + for _, tc := range []struct { + a []v1.Argument + b []v1.Argument + exp []string + err bool + }{ + { + a: []v1.Argument{ + {Name: "test", Value: "value"}, + {Name: "test2-test", Value: "value2"}, + {Name: "test3.test", Value: "value3"}, + }, + b: []v1.Argument{ + {Name: "addtest", Value: "value"}, + {Name: "addtest2-test", Value: "value2"}, + {Name: "addtest3.test", Value: "value3"}, + }, + exp: []string{ + "--test=value", + "--test2-test=value2", + "--test3.test=value3", + "--addtest=value", + "--addtest2-test=value2", + "--addtest3.test=value3", + }, + }, + { + a: []v1.Argument{ + {Name: "test", Value: "value"}, + {Name: "test2", Value: "value2"}, + }, + b: []v1.Argument{ + {Name: "addtest", Value: "value"}, + {Name: "test2", Value: "value3"}, + }, + err: true, + }, + { + a: []v1.Argument{ + {Name: "test", Value: "value"}, + {Name: "test2", Value: ""}, + }, + b: []v1.Argument{ + {Name: "addtest", Value: "value"}, + {Name: "no-test2", Value: ""}, + }, + err: true, + }, + } { + t.Run("", func(t *testing.T) { + args, err := BuildArgs(tc.a, tc.b) + if tc.err { + require.Error(t, err) + return + } + require.NoError(t, err) + require.Equal(t, tc.exp, args) + }) } } diff --git a/pkg/operator/defaults.go b/pkg/operator/defaults.go index fe602627819..17d2cd02a39 100644 --- a/pkg/operator/defaults.go +++ b/pkg/operator/defaults.go @@ -22,14 +22,14 @@ import ( const ( // DefaultAlertmanagerVersion is a default image tag for the prometheus alertmanager. - DefaultAlertmanagerVersion = "v0.29.0" + DefaultAlertmanagerVersion = "v0.30.0" // DefaultAlertmanagerBaseImage is a base container registry address for the prometheus alertmanager. DefaultAlertmanagerBaseImage = "quay.io/prometheus/alertmanager" // DefaultAlertmanagerImage is a default image pulling address for the prometheus alertmanager. DefaultAlertmanagerImage = DefaultAlertmanagerBaseImage + ":" + DefaultAlertmanagerVersion // DefaultThanosVersion is a default image tag for the Thanos long-term prometheus storage collector. - DefaultThanosVersion = "v0.39.2" + DefaultThanosVersion = "v0.40.1" // DefaultThanosBaseImage is a base container registry address for the Thanos long-term prometheus // storage collector. DefaultThanosBaseImage = "quay.io/thanos/thanos" @@ -95,6 +95,10 @@ var ( "v3.7.1", "v3.7.2", "v3.7.3", + "v3.8.0", + "v3.8.1", + "v3.9.0", + "v3.9.1", } ) diff --git a/pkg/operator/operator.go b/pkg/operator/operator.go index e21b067e435..f41513458ff 100644 --- a/pkg/operator/operator.go +++ b/pkg/operator/operator.go @@ -59,12 +59,14 @@ var ( ) type ReconciliationStatus struct { - err error + err error + reason string + message string } func (rs ReconciliationStatus) Reason() string { if rs.Ok() { - return "" + return rs.reason } return "ReconciliationFailed" @@ -72,7 +74,7 @@ func (rs ReconciliationStatus) Reason() string { func (rs ReconciliationStatus) Message() string { if rs.Ok() { - return "" + return rs.message } return rs.err.Error() @@ -131,13 +133,37 @@ func (rt *ReconciliationTracker) UpdateReferenceTracker(key string, refTracker R rt.refTracker[key] = refTracker } +// ResetStatus resets the reconciliation status for the object identified by key. +func (rt *ReconciliationTracker) ResetStatus(key string) { + rt.init() + rt.mtx.Lock() + defer rt.mtx.Unlock() + + rt.statusByObject[key] = ReconciliationStatus{} +} + // SetStatus updates the last reconciliation status for the object identified by key. func (rt *ReconciliationTracker) SetStatus(key string, err error) { rt.init() rt.mtx.Lock() defer rt.mtx.Unlock() - rt.statusByObject[key] = ReconciliationStatus{err: err} + rs := rt.statusByObject[key] + rs.err = err + rt.statusByObject[key] = rs +} + +// SetReasonAndMessage updates the reason and message for the object identified by key. +// The reason and message are only used when the reconciliation returned no error. +func (rt *ReconciliationTracker) SetReasonAndMessage(key string, reason, message string) { + rt.init() + rt.mtx.Lock() + defer rt.mtx.Unlock() + + rs := rt.statusByObject[key] + rs.reason = reason + rs.message = message + rt.statusByObject[key] = rs } // GetStatus returns the last reconciliation status for the given object. diff --git a/pkg/operator/resource_reconciler.go b/pkg/operator/resource_reconciler.go index fbe790a54d2..60f3c610945 100644 --- a/pkg/operator/resource_reconciler.go +++ b/pkg/operator/resource_reconciler.go @@ -29,7 +29,6 @@ import ( "k8s.io/apimachinery/pkg/api/meta" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" - "k8s.io/apimachinery/pkg/types" utilruntime "k8s.io/apimachinery/pkg/util/runtime" "k8s.io/client-go/tools/cache" "k8s.io/client-go/util/workqueue" @@ -134,17 +133,23 @@ func newWorkQueueMetricsProvider(reg prometheus.Registerer) *workQueueMetricsPro ), latency: prometheus.NewHistogramVec( prometheus.HistogramOpts{ - Name: "prometheus_operator_workqueue_latency_seconds", - Help: "Histogram of latency for the queue", - Buckets: []float64{.1, .5, 1, 5, 10}, + Name: "prometheus_operator_workqueue_latency_seconds", + Help: "Histogram of latency for the queue", + Buckets: []float64{.1, .5, 1, 5, 10}, + NativeHistogramBucketFactor: 1.1, + NativeHistogramMaxBucketNumber: 100, + NativeHistogramMinResetDuration: 1 * time.Hour, }, []string{"name"}, ), workDuration: prometheus.NewHistogramVec( prometheus.HistogramOpts{ - Name: "prometheus_operator_workqueue_work_duration_seconds", - Help: "Histogram of work duration for the queue", - Buckets: []float64{.1, .5, 1, 5, 10}, + Name: "prometheus_operator_workqueue_work_duration_seconds", + Help: "Histogram of work duration for the queue", + Buckets: []float64{.1, .5, 1, 5, 10}, + NativeHistogramBucketFactor: 1.1, + NativeHistogramMaxBucketNumber: 100, + NativeHistogramMinResetDuration: 1 * time.Hour, }, []string{"name"}, ), @@ -233,9 +238,12 @@ func NewResourceReconciler( }) reconcileDuration := prometheus.NewHistogram(prometheus.HistogramOpts{ - Name: "prometheus_operator_reconcile_duration_seconds", - Help: "Histogram of reconcile operations", - Buckets: []float64{.1, .5, 1, 5, 10}, + Name: "prometheus_operator_reconcile_duration_seconds", + Help: "Histogram of reconcile operations", + Buckets: []float64{.1, .5, 1, 5, 10}, + NativeHistogramBucketFactor: 1.1, + NativeHistogramMaxBucketNumber: 100, + NativeHistogramMinResetDuration: 1 * time.Hour, }) statusTotal := prometheus.NewCounter(prometheus.CounterOpts{ @@ -295,7 +303,7 @@ func NewResourceReconciler( func (rr *ResourceReconciler) DeletionInProgress(o metav1.Object) bool { if o.GetDeletionTimestamp() != nil { rr.logger.Debug("object deletion in progress", - "object", fmt.Sprintf("%s/%s", o.GetNamespace(), o.GetName()), + "object", KeyForObject(o), ) return true } @@ -308,7 +316,7 @@ func (rr *ResourceReconciler) hasObjectChanged(old, cur metav1.Object) bool { rr.logger.Debug("different resource versions", "current", cur.GetResourceVersion(), "old", old.GetResourceVersion(), - "object", fmt.Sprintf("%s/%s", cur.GetNamespace(), cur.GetName()), + "object", KeyForObject(cur), ) return true } @@ -325,7 +333,7 @@ func (rr *ResourceReconciler) hasStateChanged(old, cur metav1.Object) bool { rr.logger.Debug("different generations", "current", cur.GetGeneration(), "old", old.GetGeneration(), - "object", fmt.Sprintf("%s/%s", cur.GetNamespace(), cur.GetName()), + "object", KeyForObject(cur), ) return true } @@ -334,7 +342,7 @@ func (rr *ResourceReconciler) hasStateChanged(old, cur metav1.Object) bool { rr.logger.Debug("different labels", "current", fmt.Sprintf("%v", cur.GetLabels()), "old", fmt.Sprintf("%v", old.GetLabels()), - "object", fmt.Sprintf("%s/%s", cur.GetNamespace(), cur.GetName()), + "object", KeyForObject(cur), ) return true @@ -343,7 +351,7 @@ func (rr *ResourceReconciler) hasStateChanged(old, cur metav1.Object) bool { rr.logger.Debug("different annotations", "current", fmt.Sprintf("%v", cur.GetAnnotations()), "old", fmt.Sprintf("%v", old.GetAnnotations()), - "object", fmt.Sprintf("%s/%s", cur.GetNamespace(), cur.GetName()), + "object", KeyForObject(cur), ) return true } @@ -373,7 +381,7 @@ func (rr *ResourceReconciler) resolve(obj metav1.Object) metav1.Object { continue } - owner, err := rr.getter.Get(types.NamespacedName{Namespace: obj.GetNamespace(), Name: or.Name}.String()) + owner, err := rr.getter.Get(KeyForObject(&metav1.ObjectMeta{Name: or.Name, Namespace: obj.GetNamespace()})) if err != nil { if !apierrors.IsNotFound(err) { rr.logger.Error("failed to resolve controller owner", "err", err, "namespace", obj.GetNamespace(), "name", obj.GetName(), "kind", rr.resourceKind) @@ -613,7 +621,7 @@ func (rr *ResourceReconciler) EnqueueForReconciliation(obj metav1.Object) { return } - rr.reconcileQ.Add(obj.GetNamespace() + "/" + obj.GetName()) + rr.reconcileQ.Add(KeyForObject(obj)) } // EnqueueForStatus asks for updating the status of the object. @@ -622,7 +630,7 @@ func (rr *ResourceReconciler) EnqueueForStatus(obj metav1.Object) { return } - rr.statusQ.Add(obj.GetNamespace() + "/" + obj.GetName()) + rr.statusQ.Add(KeyForObject(obj)) } // Run the goroutines responsible for processing the reconciliation and status @@ -714,9 +722,20 @@ func (rr *ResourceReconciler) isManagedByController(obj metav1.Object) bool { } if controllerID != rr.controllerID { - rr.logger.Debug("skipping object not managed by the controller", "object", fmt.Sprintf("%s/%s", obj.GetNamespace(), obj.GetName()), "object_id", controllerID, "controller_id", rr.controllerID) + rr.logger.Debug("skipping object not managed by the controller", "object", KeyForObject(obj), "object_id", controllerID, "controller_id", rr.controllerID) return false } return true } + +// KeyForObject returns a string key identifying the given object. +// For cluster-scoped resources, the key is ``. +// For namespace-scoped resources, the key is `/`. +func KeyForObject(o metav1.Object) string { + if o.GetNamespace() == "" { + return o.GetName() + } + + return o.GetNamespace() + "/" + o.GetName() +} diff --git a/pkg/operator/rules.go b/pkg/operator/rules.go index 30129cc8120..c8dec55501b 100644 --- a/pkg/operator/rules.go +++ b/pkg/operator/rules.go @@ -160,8 +160,8 @@ func (prs *PrometheusRuleSelector) sanitizePrometheusRulesSpec(promRuleSpec moni if prs.ruleFormat == ThanosFormat { minVersionKeepFiringFor = semver.MustParse("0.34.0") minVersionLimits = semver.MustParse("0.24.0") - minVersionQueryOffset = semver.MustParse("100.0.0") // Arbitrary very high major version because it's not yet supported by Thanos. - minVersionRuleGroupLabels = semver.MustParse("100.0.0") // Arbitrary very high major version because it's not yet supported by Thanos. + minVersionQueryOffset = semver.MustParse("0.38.0") + minVersionRuleGroupLabels = semver.MustParse("0.39.0") component = "Thanos" } diff --git a/pkg/operator/rules_test.go b/pkg/operator/rules_test.go index 002f8db7c75..397d5dfed8a 100644 --- a/pkg/operator/rules_test.go +++ b/pkg/operator/rules_test.go @@ -57,6 +57,10 @@ func TestMakeRulesConfigMaps(t *testing.T) { t.Run("shouldDropLimitFieldForUnsupportedThanosVersion", shouldDropLimitFieldForUnsupportedThanosVersion) t.Run("shouldDropRuleFiringForThanos", shouldDropRuleFiringForThanos) t.Run("shouldAcceptRuleFiringForThanos", shouldAcceptRuleFiringForThanos) + t.Run("shouldAcceptRuleWithQueryOffsetThanos", shouldAcceptRuleWithQueryOffsetThanos) + t.Run("shouldDropQueryOffsetFieldForUnsupportedThanosVersion", shouldDropQueryOffsetFieldForUnsupportedThanosVersion) + t.Run("shouldDropGroupLabelsForUnsupportedThanosVersion", shouldDropGroupLabelsForUnsupportedThanosVersion) + t.Run("shouldAcceptRuleWithGroupLabelsThanos", shouldAcceptRuleWithGroupLabelsThanos) // UTF-8 validation. t.Run("UTF8Validation", TestUTF8Validation) @@ -350,6 +354,30 @@ func shouldAcceptRuleWithLimitThanos(t *testing.T) { require.Contains(t, content, "limit", "expected `limit` to be present in PrometheusRule") } +func shouldAcceptRuleWithQueryOffsetThanos(t *testing.T) { + var queryOffset monitoringv1.Duration = "30s" + rules := &monitoringv1.PrometheusRule{ + Spec: monitoringv1.PrometheusRuleSpec{Groups: []monitoringv1.RuleGroup{ + { + Name: "group", + Rules: []monitoringv1.Rule{ + { + Alert: "alert", + Expr: intstr.FromString("vector(1)"), + }, + }, + QueryOffset: &queryOffset, + }, + }}, + } + + thanosVersion, _ := semver.ParseTolerant(DefaultThanosVersion) + pr := newRuleSelectorForConfigGeneration(ThanosFormat, thanosVersion) + content, err := pr.generateRulesConfiguration(rules) + require.NoError(t, err) + require.Contains(t, content, "query_offset", "expected `query_offset` to be present in PrometheusRule") +} + func shouldAcceptRuleWithQueryOffsetPrometheus(t *testing.T) { var queryOffset monitoringv1.Duration = "30s" rules := &monitoringv1.PrometheusRule{ @@ -423,6 +451,31 @@ func shouldDropLimitFieldForUnsupportedThanosVersion(t *testing.T) { require.NotContains(t, content, "limit", "expected `limit` not to be present in PrometheusRule") } +func shouldDropQueryOffsetFieldForUnsupportedThanosVersion(t *testing.T) { + var queryOffset monitoringv1.Duration = "30s" + rules := &monitoringv1.PrometheusRule{ + Spec: monitoringv1.PrometheusRuleSpec{Groups: []monitoringv1.RuleGroup{ + { + Name: "group", + Rules: []monitoringv1.Rule{ + { + Alert: "alert", + Expr: intstr.FromString("vector(1)"), + }, + }, + QueryOffset: &queryOffset, + }, + }}, + } + + thanosVersion, _ := semver.ParseTolerant("0.37.0") + pr := newRuleSelectorForConfigGeneration(ThanosFormat, thanosVersion) + content, err := pr.generateRulesConfiguration(rules) + require.NoError(t, err) + + require.NotContains(t, content, "query_offset", "expected `query_offset` not to be present in PrometheusRule") +} + func shouldDropQueryOffsetFieldForUnsupportedPrometheusVersion(t *testing.T) { var queryOffset monitoringv1.Duration = "30s" rules := &monitoringv1.PrometheusRule{ @@ -477,6 +530,33 @@ func shouldErrorOnTooLargePrometheusRule(t *testing.T) { require.NotEmpty(t, err, "expected ValidateRule to return error of size limit with LegacyValidation") } +func shouldDropGroupLabelsForUnsupportedThanosVersion(t *testing.T) { + labels := map[string]string{ + "key": "value", + } + rules := &monitoringv1.PrometheusRule{ + Spec: monitoringv1.PrometheusRuleSpec{Groups: []monitoringv1.RuleGroup{ + { + Name: "group", + Labels: labels, + Rules: []monitoringv1.Rule{ + { + Alert: "alert", + Expr: intstr.FromString("vector(1)"), + }, + }, + }, + }}, + } + + thanosVersion, _ := semver.ParseTolerant("0.38.0") + pr := newRuleSelectorForConfigGeneration(ThanosFormat, thanosVersion) + content, _ := pr.generateRulesConfiguration(rules) + + require.NotContains(t, content, "key", "expected group labels not to be present in PrometheusRule") + require.NotContains(t, content, "value", "expected group labels not to be present in PrometheusRule") +} + func shouldDropGroupLabelsForUnsupportedPrometheusVersion(t *testing.T) { labels := map[string]string{ "key": "value", @@ -504,6 +584,33 @@ func shouldDropGroupLabelsForUnsupportedPrometheusVersion(t *testing.T) { require.NotContains(t, content, "value", "expected group labels not to be present in PrometheusRule") } +func shouldAcceptRuleWithGroupLabelsThanos(t *testing.T) { + labels := map[string]string{ + "key": "value", + } + rules := &monitoringv1.PrometheusRule{ + Spec: monitoringv1.PrometheusRuleSpec{Groups: []monitoringv1.RuleGroup{ + { + Name: "group", + Labels: labels, + Rules: []monitoringv1.Rule{ + { + Alert: "alert", + Expr: intstr.FromString("vector(1)"), + }, + }, + }, + }}, + } + + thanosVersion, _ := semver.ParseTolerant(DefaultThanosVersion) + pr := newRuleSelectorForConfigGeneration(ThanosFormat, thanosVersion) + content, err := pr.generateRulesConfiguration(rules) + require.NoError(t, err) + require.Contains(t, content, "key", "expected group labels to be present in PrometheusRule") + require.Contains(t, content, "value", "expected group labels to be present in PrometheusRule") +} + func shouldAcceptRuleWithGroupLabels(t *testing.T) { labels := map[string]string{ "key": "value", @@ -525,8 +632,10 @@ func shouldAcceptRuleWithGroupLabels(t *testing.T) { promVersion, _ := semver.ParseTolerant(DefaultPrometheusVersion) pr := newRuleSelectorForConfigGeneration(PrometheusFormat, promVersion) - _, err := pr.generateRulesConfiguration(rules) + content, err := pr.generateRulesConfiguration(rules) require.NoError(t, err) + require.Contains(t, content, "key", "expected group labels to be present in PrometheusRule") + require.Contains(t, content, "value", "expected group labels to be present in PrometheusRule") } func TestUTF8Validation(t *testing.T) { diff --git a/pkg/operator/statefulset.go b/pkg/operator/statefulset.go new file mode 100644 index 00000000000..3920ccdc172 --- /dev/null +++ b/pkg/operator/statefulset.go @@ -0,0 +1,41 @@ +// Copyright 2025 The prometheus-operator Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package operator + +import ( + appsv1 "k8s.io/api/apps/v1" + + monitoringv1 "github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1" +) + +// UpdateStrategyForStatefulSet converts a monitoring update strategy to a statefulset update strategy. +func UpdateStrategyForStatefulSet(updateStrategy *monitoringv1.StatefulSetUpdateStrategy) appsv1.StatefulSetUpdateStrategy { + if updateStrategy == nil { + return appsv1.StatefulSetUpdateStrategy{ + Type: appsv1.RollingUpdateStatefulSetStrategyType, + } + } + + converted := appsv1.StatefulSetUpdateStrategy{ + Type: appsv1.StatefulSetUpdateStrategyType(updateStrategy.Type), + } + if updateStrategy.RollingUpdate != nil { + converted.RollingUpdate = &appsv1.RollingUpdateStatefulSetStrategy{ + MaxUnavailable: updateStrategy.RollingUpdate.MaxUnavailable, + } + } + + return converted +} diff --git a/pkg/operator/status.go b/pkg/operator/status.go index 34d2ac6dace..f1bf826a321 100644 --- a/pkg/operator/status.go +++ b/pkg/operator/status.go @@ -23,6 +23,12 @@ import ( monitoringv1 "github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1" ) +const ( + // NoSelectedResourcesReason is used in status conditions to indicate that + // a workload resource selected no configuration resources. + NoSelectedResourcesReason = "NoSelectedResources" +) + type StatusReconciler interface { Iterate(func(metav1.Object, []monitoringv1.Condition)) RefreshStatusFor(metav1.Object) diff --git a/pkg/prometheus/agent/operator.go b/pkg/prometheus/agent/operator.go index 9bc7955f752..8c5e751d589 100644 --- a/pkg/prometheus/agent/operator.go +++ b/pkg/prometheus/agent/operator.go @@ -50,6 +50,8 @@ const ( resyncPeriod = 5 * time.Minute controllerName = "prometheusagent-controller" applicationNameLabelValue = "prometheus-agent" + + noSelectedResourcesMessage = "No ServiceMonitor, PodMonitor, Probe, and ScrapeConfig have been selected." ) // Operator manages life cycle of Prometheus agent deployments and @@ -852,29 +854,11 @@ func (c *Operator) syncStatefulSet(ctx context.Context, key string, p *monitorin "existing_hash", existingStatefulSet.Annotations[operator.InputHashAnnotationKey], ) - err = k8sutil.UpdateStatefulSet(ctx, ssetClient, sset) - sErr, ok := err.(*apierrors.StatusError) - - if ok && sErr.ErrStatus.Code == 422 && sErr.ErrStatus.Reason == metav1.StatusReasonInvalid { + if err = k8sutil.ForceUpdateStatefulSet(ctx, ssetClient, sset, func(reason string) { c.metrics.StsDeleteCreateCounter().Inc() - - // Gather only reason for failed update - failMsg := make([]string, len(sErr.ErrStatus.Details.Causes)) - for i, cause := range sErr.ErrStatus.Details.Causes { - failMsg[i] = cause.Message - } - - logger.Info("recreating StatefulSet because the update operation wasn't possible", "reason", strings.Join(failMsg, ", ")) - - propagationPolicy := metav1.DeletePropagationForeground - if err := ssetClient.Delete(ctx, sset.GetName(), metav1.DeleteOptions{PropagationPolicy: &propagationPolicy}); err != nil { - return fmt.Errorf("failed to delete StatefulSet to avoid forbidden action: %w", err) - } - continue - } - - if err != nil { - return fmt.Errorf("updating StatefulSet failed: %w", err) + logger.Info("recreating StatefulSet because the update operation wasn't possible", "reason", reason) + }); err != nil { + return err } } @@ -936,6 +920,10 @@ func (c *Operator) createOrUpdateConfigurationSecret(ctx context.Context, logger } } + if len(smons)+len(pmons)+len(bmons)+len(scrapeConfigs) == 0 { + c.reconciliations.SetReasonAndMessage(operator.KeyForObject(p), operator.NoSelectedResourcesReason, noSelectedResourcesMessage) + } + if err := cg.AddRemoteWriteToStore(ctx, store, p.GetNamespace(), p.Spec.RemoteWrite); err != nil { return err } diff --git a/pkg/prometheus/agent/statefulset.go b/pkg/prometheus/agent/statefulset.go index 28e4b8b6ae1..bd813545a4d 100644 --- a/pkg/prometheus/agent/statefulset.go +++ b/pkg/prometheus/agent/statefulset.go @@ -290,16 +290,18 @@ func makeStatefulSetSpec( k8sutil.UpdateDNSPolicy(&spec, cpf.DNSPolicy) k8sutil.UpdateDNSConfig(&spec, cpf.DNSConfig) - // PodManagementPolicy is set to Parallel to mitigate issues in kubernetes: https://github.com/kubernetes/kubernetes/issues/60164 - // This is also mentioned as one of limitations of StatefulSets: https://kubernetes.io/docs/concepts/workloads/controllers/statefulset/#limitations + // By default, podManagementPolicy is set to Parallel to mitigate rollout + // issues in Kubernetes (see https://github.com/kubernetes/kubernetes/issues/60164). + // This is also mentioned as one of limitations of StatefulSets: + // https://kubernetes.io/docs/concepts/workloads/controllers/statefulset/#limitations + podManagementPolicy := ptr.Deref(cpf.PodManagementPolicy, monitoringv1.ParallelPodManagement) + return &appsv1.StatefulSetSpec{ ServiceName: ptr.Deref(cpf.ServiceName, governingServiceName), Replicas: cpf.Replicas, - PodManagementPolicy: appsv1.ParallelPodManagement, - UpdateStrategy: appsv1.StatefulSetUpdateStrategy{ - Type: appsv1.RollingUpdateStatefulSetStrategyType, - }, - MinReadySeconds: ptr.Deref(p.Spec.MinReadySeconds, 0), + PodManagementPolicy: appsv1.PodManagementPolicyType(podManagementPolicy), + UpdateStrategy: operator.UpdateStrategyForStatefulSet(cpf.UpdateStrategy), + MinReadySeconds: ptr.Deref(p.Spec.MinReadySeconds, 0), Selector: &metav1.LabelSelector{ MatchLabels: finalSelectorLabels, }, diff --git a/pkg/prometheus/agent/statefulset_test.go b/pkg/prometheus/agent/statefulset_test.go index 18c7aef8247..8d4d5a726c4 100644 --- a/pkg/prometheus/agent/statefulset_test.go +++ b/pkg/prometheus/agent/statefulset_test.go @@ -24,6 +24,7 @@ import ( appsv1 "k8s.io/api/apps/v1" v1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/util/intstr" "k8s.io/utils/ptr" monitoringv1 "github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1" @@ -401,3 +402,93 @@ func TestStatefulSetenableServiceLinks(t *testing.T) { } } } + +func TestStatefulPodManagementPolicy(t *testing.T) { + for _, tc := range []struct { + podManagementPolicy *monitoringv1.PodManagementPolicyType + exp appsv1.PodManagementPolicyType + }{ + { + podManagementPolicy: nil, + exp: appsv1.ParallelPodManagement, + }, + { + podManagementPolicy: ptr.To(monitoringv1.ParallelPodManagement), + exp: appsv1.ParallelPodManagement, + }, + { + podManagementPolicy: ptr.To(monitoringv1.OrderedReadyPodManagement), + exp: appsv1.OrderedReadyPodManagement, + }, + } { + t.Run("", func(t *testing.T) { + sset, err := makeStatefulSetFromPrometheus(monitoringv1alpha1.PrometheusAgent{ + Spec: monitoringv1alpha1.PrometheusAgentSpec{ + CommonPrometheusFields: monitoringv1.CommonPrometheusFields{ + PodManagementPolicy: tc.podManagementPolicy, + }, + }, + }) + + require.NoError(t, err) + require.Equal(t, tc.exp, sset.Spec.PodManagementPolicy) + }) + } +} + +func TestStatefulSetUpdateStrategy(t *testing.T) { + for _, tc := range []struct { + updateStrategy *monitoringv1.StatefulSetUpdateStrategy + exp appsv1.StatefulSetUpdateStrategy + }{ + { + updateStrategy: nil, + exp: appsv1.StatefulSetUpdateStrategy{ + Type: appsv1.RollingUpdateStatefulSetStrategyType, + }, + }, + { + updateStrategy: &monitoringv1.StatefulSetUpdateStrategy{ + Type: monitoringv1.RollingUpdateStatefulSetStrategyType, + }, + exp: appsv1.StatefulSetUpdateStrategy{ + Type: appsv1.RollingUpdateStatefulSetStrategyType, + }, + }, + { + updateStrategy: &monitoringv1.StatefulSetUpdateStrategy{ + Type: monitoringv1.RollingUpdateStatefulSetStrategyType, + RollingUpdate: &monitoringv1.RollingUpdateStatefulSetStrategy{ + MaxUnavailable: ptr.To(intstr.FromInt(1)), + }, + }, + exp: appsv1.StatefulSetUpdateStrategy{ + Type: appsv1.RollingUpdateStatefulSetStrategyType, + RollingUpdate: &appsv1.RollingUpdateStatefulSetStrategy{ + MaxUnavailable: ptr.To(intstr.FromInt(1)), + }, + }, + }, + { + updateStrategy: &monitoringv1.StatefulSetUpdateStrategy{ + Type: monitoringv1.OnDeleteStatefulSetStrategyType, + }, + exp: appsv1.StatefulSetUpdateStrategy{ + Type: appsv1.OnDeleteStatefulSetStrategyType, + }, + }, + } { + t.Run("", func(t *testing.T) { + sset, err := makeStatefulSetFromPrometheus(monitoringv1alpha1.PrometheusAgent{ + Spec: monitoringv1alpha1.PrometheusAgentSpec{ + CommonPrometheusFields: monitoringv1.CommonPrometheusFields{ + UpdateStrategy: tc.updateStrategy, + }, + }, + }) + + require.NoError(t, err) + require.Equal(t, tc.exp, sset.Spec.UpdateStrategy) + }) + } +} diff --git a/pkg/prometheus/common.go b/pkg/prometheus/common.go index 497134ba8f6..21433846479 100644 --- a/pkg/prometheus/common.go +++ b/pkg/prometheus/common.go @@ -73,7 +73,8 @@ var ( LabelPrometheusName = "prometheus-name" ) -// LabelSelectorForStatefulSets returns a label selector which selects statefulsets deployed with the server or agent mode. +// LabelSelectorForStatefulSets returns a label selector which selects +// statefulsets deployed with the server or agent mode. func LabelSelectorForStatefulSets(mode string) string { return fmt.Sprintf( "%s,%s,%s,%s in (%s)", diff --git a/pkg/prometheus/operator.go b/pkg/prometheus/operator.go index 3c63f8de1d2..928ae2fa9a5 100644 --- a/pkg/prometheus/operator.go +++ b/pkg/prometheus/operator.go @@ -109,8 +109,8 @@ func (cg *ConfigGenerator) validateRemoteWriteSpec(spec monitoringv1.RemoteWrite } if spec.AzureAD != nil { - if spec.AzureAD.ManagedIdentity == nil && spec.AzureAD.OAuth == nil && spec.AzureAD.SDK == nil { - return fmt.Errorf("must provide Azure Managed Identity or Azure OAuth or Azure SDK in the Azure AD config") + if spec.AzureAD.ManagedIdentity == nil && spec.AzureAD.OAuth == nil && spec.AzureAD.SDK == nil && spec.AzureAD.WorkloadIdentity == nil { + return fmt.Errorf("must provide Azure Managed Identity, Azure OAuth, Azure SDK, or Azure Workload Identity in the Azure AD config") } if spec.AzureAD.ManagedIdentity != nil && spec.AzureAD.OAuth != nil { @@ -125,7 +125,18 @@ func (cg *ConfigGenerator) validateRemoteWriteSpec(spec monitoringv1.RemoteWrite return fmt.Errorf("cannot provide both Azure Managed Identity and Azure SDK in the Azure AD config") } - // check azure managed identity client id + if spec.AzureAD.ManagedIdentity != nil && spec.AzureAD.WorkloadIdentity != nil { + return fmt.Errorf("cannot provide both Azure Managed Identity and Azure Workload Identity in the Azure AD config") + } + + if spec.AzureAD.OAuth != nil && spec.AzureAD.WorkloadIdentity != nil { + return fmt.Errorf("cannot provide both Azure OAuth and Azure Workload Identity in the Azure AD config") + } + + if spec.AzureAD.SDK != nil && spec.AzureAD.WorkloadIdentity != nil { + return fmt.Errorf("cannot provide both Azure SDK and Azure Workload Identity in the Azure AD config") + } + if spec.AzureAD.ManagedIdentity != nil { if err := cg.checkAzureADManagedIdentity(spec.AzureAD.ManagedIdentity); err != nil { return err @@ -138,6 +149,17 @@ func (cg *ConfigGenerator) validateRemoteWriteSpec(spec monitoringv1.RemoteWrite return fmt.Errorf("the provided Azure OAuth clientId is invalid") } } + + if spec.AzureAD.WorkloadIdentity != nil { + _, err := uuid.Parse(spec.AzureAD.WorkloadIdentity.ClientID) + if err != nil { + return fmt.Errorf("the provided Azure Workload Identity clientId is invalid") + } + _, err = uuid.Parse(spec.AzureAD.WorkloadIdentity.TenantID) + if err != nil { + return fmt.Errorf("the provided Azure Workload Identity tenantId is invalid") + } + } } return spec.Validate() diff --git a/pkg/prometheus/operator_test.go b/pkg/prometheus/operator_test.go index abf35e8d5cd..7176ee83855 100644 --- a/pkg/prometheus/operator_test.go +++ b/pkg/prometheus/operator_test.go @@ -220,6 +220,115 @@ func TestValidateRemoteWriteConfig(t *testing.T) { }, expectErr: true, }, + { + name: "rw_azuread_with_workload_identity", + spec: monitoringv1.RemoteWriteSpec{ + URL: "http://example.com", + AzureAD: &monitoringv1.AzureAD{ + Cloud: ptr.To("AzureGovernment"), + WorkloadIdentity: &monitoringv1.AzureWorkloadIdentity{ + ClientID: "00000000-a12b-3cd4-e56f-000000000000", + TenantID: "11111111-a12b-3cd4-e56f-000000000000", + }, + }, + }, + }, + { + name: "with_invalid_workload_identity_clientID", + spec: monitoringv1.RemoteWriteSpec{ + URL: "http://example.com", + AzureAD: &monitoringv1.AzureAD{ + Cloud: ptr.To("AzureGovernment"), + WorkloadIdentity: &monitoringv1.AzureWorkloadIdentity{ + ClientID: "invalid-uuid", + TenantID: "11111111-a12b-3cd4-e56f-000000000000", + }, + }, + }, + expectErr: true, + }, + { + name: "with_invalid_workload_identity_tenantID", + spec: monitoringv1.RemoteWriteSpec{ + URL: "http://example.com", + AzureAD: &monitoringv1.AzureAD{ + Cloud: ptr.To("AzureGovernment"), + WorkloadIdentity: &monitoringv1.AzureWorkloadIdentity{ + ClientID: "00000000-a12b-3cd4-e56f-000000000000", + TenantID: "invalid-uuid", + }, + }, + }, + expectErr: true, + }, + { + name: "with_workload_identity_and_managed_identity", + spec: monitoringv1.RemoteWriteSpec{ + URL: "http://example.com", + AzureAD: &monitoringv1.AzureAD{ + Cloud: ptr.To("AzureGovernment"), + ManagedIdentity: &monitoringv1.ManagedIdentity{ + ClientID: ptr.To("00000000-a12b-3cd4-e56f-000000000000"), + }, + WorkloadIdentity: &monitoringv1.AzureWorkloadIdentity{ + ClientID: "00000000-a12b-3cd4-e56f-000000000000", + TenantID: "11111111-a12b-3cd4-e56f-000000000000", + }, + }, + }, + expectErr: true, + }, + { + name: "with_workload_identity_and_oauth", + spec: monitoringv1.RemoteWriteSpec{ + URL: "http://example.com", + AzureAD: &monitoringv1.AzureAD{ + Cloud: ptr.To("AzureGovernment"), + OAuth: &monitoringv1.AzureOAuth{ + TenantID: "00000000-a12b-3cd4-e56f-000000000000", + ClientID: "00000000-0000-0000-0000-000000000000", + ClientSecret: v1.SecretKeySelector{ + LocalObjectReference: v1.LocalObjectReference{ + Name: "azure-oauth-secret", + }, + Key: "secret-key", + }, + }, + WorkloadIdentity: &monitoringv1.AzureWorkloadIdentity{ + ClientID: "00000000-a12b-3cd4-e56f-000000000000", + TenantID: "11111111-a12b-3cd4-e56f-000000000000", + }, + }, + }, + expectErr: true, + }, + { + name: "with_workload_identity_and_sdk", + spec: monitoringv1.RemoteWriteSpec{ + URL: "http://example.com", + AzureAD: &monitoringv1.AzureAD{ + Cloud: ptr.To("AzureGovernment"), + SDK: &monitoringv1.AzureSDK{ + TenantID: ptr.To("00000000-a12b-3cd4-e56f-000000000000"), + }, + WorkloadIdentity: &monitoringv1.AzureWorkloadIdentity{ + ClientID: "00000000-a12b-3cd4-e56f-000000000000", + TenantID: "11111111-a12b-3cd4-e56f-000000000000", + }, + }, + }, + expectErr: true, + }, + { + name: "with_no_azure_auth_method_including_workload_identity", + spec: monitoringv1.RemoteWriteSpec{ + URL: "http://example.com", + AzureAD: &monitoringv1.AzureAD{ + Cloud: ptr.To("AzureGovernment"), + }, + }, + expectErr: true, + }, } for _, tc := range cases { t.Run(tc.name, func(t *testing.T) { diff --git a/pkg/prometheus/promcfg.go b/pkg/prometheus/promcfg.go index 7fb293f1abc..cacf742a2c9 100644 --- a/pkg/prometheus/promcfg.go +++ b/pkg/prometheus/promcfg.go @@ -44,6 +44,7 @@ import ( "github.com/prometheus-operator/prometheus-operator/pkg/assets" namespacelabeler "github.com/prometheus-operator/prometheus-operator/pkg/namespacelabeler" "github.com/prometheus-operator/prometheus-operator/pkg/operator" + "github.com/prometheus-operator/prometheus-operator/pkg/prometheus/validation" ) const ( @@ -198,7 +199,7 @@ func getScrapeClassConfig(p monitoringv1.PrometheusInterface) (map[string]monito ) for _, scrapeClass := range cpf.ScrapeClasses { - lcv, err := NewLabelConfigValidator(p) + lcv, err := validation.NewLabelConfigValidator(p) if err != nil { return nil, "", err } @@ -475,6 +476,10 @@ func (cg *ConfigGenerator) addNativeHistogramConfig(cfg yaml.MapSlice, nhc monit return cfg } + if nhc.ScrapeNativeHistograms != nil { + cfg = cg.WithMinimumVersion("3.8.0").AppendMapItem(cfg, "scrape_native_histograms", nhc.ScrapeNativeHistograms) + } + if nhc.NativeHistogramBucketLimit != nil { cfg = cg.WithMinimumVersion("2.45.0").AppendMapItem(cfg, "native_histogram_bucket_limit", nhc.NativeHistogramBucketLimit) } @@ -1804,8 +1809,8 @@ func (cg *ConfigGenerator) generateProbeConfig( cfg = cg.addTLStoYaml(cfg, s, mergeSafeTLSConfigWithScrapeClass(m.Spec.TLSConfig, scrapeClass)) - if m.Spec.BearerTokenSecret.Name != "" { - b, err := s.GetSecretKey(m.Spec.BearerTokenSecret) + if m.Spec.BearerTokenSecret != nil { //nolint:staticcheck // Ignore SA1019 this field is marked as deprecated. + b, err := s.GetSecretKey(*m.Spec.BearerTokenSecret) //nolint:staticcheck // Ignore SA1019 this field is marked as deprecated. if err != nil { cg.logger.Error("invalid bearer token reference", "err", err) } else { @@ -1887,8 +1892,8 @@ func (cg *ConfigGenerator) generateServiceMonitorConfig( if ep.FollowRedirects != nil { cfg = cg.WithMinimumVersion("2.26.0").AppendMapItem(cfg, "follow_redirects", *ep.FollowRedirects) } - if ep.EnableHttp2 != nil { - cfg = cg.WithMinimumVersion("2.35.0").AppendMapItem(cfg, "enable_http2", *ep.EnableHttp2) + if ep.EnableHTTP2 != nil { + cfg = cg.WithMinimumVersion("2.35.0").AppendMapItem(cfg, "enable_http2", *ep.EnableHTTP2) } cfg = cg.addProxyConfigtoYaml(cfg, s, ep.ProxyConfig) @@ -2798,10 +2803,23 @@ func (cg *ConfigGenerator) GenerateRemoteWriteConfig(rws []monitoringv1.RemoteWr }) } + if spec.AzureAD.WorkloadIdentity != nil { + workloadIdentityConfig := yaml.MapSlice{ + {Key: "client_id", Value: spec.AzureAD.WorkloadIdentity.ClientID}, + {Key: "tenant_id", Value: spec.AzureAD.WorkloadIdentity.TenantID}, + } + + azureAd = cg.WithMinimumVersion("3.7.0").AppendMapItem(azureAd, "workload_identity", workloadIdentityConfig) + } + if spec.AzureAD.Cloud != nil { azureAd = append(azureAd, yaml.MapItem{Key: "cloud", Value: spec.AzureAD.Cloud}) } + if scope := ptr.Deref(spec.AzureAD.Scope, ""); scope != "" { + azureAd = cg.WithMinimumVersion("3.9.0").AppendMapItem(azureAd, "scope", scope) + } + cfg = cg.WithMinimumVersion("2.45.0").AppendMapItem(cfg, "azuread", azureAd) } @@ -4902,6 +4920,11 @@ func (cg *ConfigGenerator) appendTracingConfig(cfg yaml.MapSlice, s assets.Store return cfg, nil } + err := tracingConfig.Validate() + if err != nil { + return cfg, err + } + var tracing yaml.MapSlice tracing = append(tracing, yaml.MapItem{ Key: "endpoint", @@ -4911,7 +4934,7 @@ func (cg *ConfigGenerator) appendTracingConfig(cfg yaml.MapSlice, s assets.Store if tracingConfig.ClientType != nil { tracing = append(tracing, yaml.MapItem{ Key: "client_type", - Value: tracingConfig.ClientType, + Value: strings.ToLower(*tracingConfig.ClientType), }) } @@ -4947,7 +4970,7 @@ func (cg *ConfigGenerator) appendTracingConfig(cfg yaml.MapSlice, s assets.Store if tracingConfig.Compression != nil { tracing = append(tracing, yaml.MapItem{ Key: "compression", - Value: tracingConfig.Compression, + Value: strings.ToLower(*tracingConfig.Compression), }) } @@ -5019,6 +5042,16 @@ func (cg *ConfigGenerator) appendConvertScrapeClassicHistograms(cfg yaml.MapSlic return cg.WithMinimumVersion("3.5.0").AppendMapItem(cfg, "always_scrape_classic_histograms", *cpf.ScrapeClassicHistograms) } +func (cg *ConfigGenerator) appendScrapeNativeHistograms(cfg yaml.MapSlice) yaml.MapSlice { + cpf := cg.prom.GetCommonPrometheusFields() + + if cpf.ScrapeNativeHistograms == nil { + return cfg + } + + return cg.WithMinimumVersion("3.8.0").AppendMapItem(cfg, "scrape_native_histograms", *cpf.ScrapeNativeHistograms) +} + func (cg *ConfigGenerator) getScrapeClassOrDefault(name *string) monitoringv1.ScrapeClass { if name != nil { if scrapeClass, found := cg.scrapeClasses[*name]; found { @@ -5096,6 +5129,7 @@ func (cg *ConfigGenerator) buildGlobalConfig() yaml.MapSlice { cfg = cg.appendNameEscapingScheme(cfg, cpf.NameEscapingScheme) cfg = cg.appendConvertClassicHistogramsToNHCB(cfg) cfg = cg.appendConvertScrapeClassicHistograms(cfg) + cfg = cg.appendScrapeNativeHistograms(cfg) return cfg } diff --git a/pkg/prometheus/promcfg_test.go b/pkg/prometheus/promcfg_test.go index 53989b8c646..6598aa8fedb 100644 --- a/pkg/prometheus/promcfg_test.go +++ b/pkg/prometheus/promcfg_test.go @@ -2692,8 +2692,14 @@ func TestEndpointOAuth2(t *testing.T) { Spec: monitoringv1.ServiceMonitorSpec{ Endpoints: []monitoringv1.Endpoint{ { - Port: "web", - OAuth2: &oauth2, + Port: "web", + HTTPConfigWithProxyAndTLSFiles: monitoringv1.HTTPConfigWithProxyAndTLSFiles{ + HTTPConfigWithTLSFiles: monitoringv1.HTTPConfigWithTLSFiles{ + HTTPConfigWithoutTLS: monitoringv1.HTTPConfigWithoutTLS{ + OAuth2: &oauth2, + }, + }, + }, }, }, }, @@ -2715,8 +2721,14 @@ func TestEndpointOAuth2(t *testing.T) { Spec: monitoringv1.PodMonitorSpec{ PodMetricsEndpoints: []monitoringv1.PodMetricsEndpoint{ { - Port: ptr.To("web"), - HTTPConfig: monitoringv1.HTTPConfig{OAuth2: &oauth2}, + Port: ptr.To("web"), + HTTPConfigWithProxy: monitoringv1.HTTPConfigWithProxy{ + HTTPConfig: monitoringv1.HTTPConfig{ + HTTPConfigWithoutTLS: monitoringv1.HTTPConfigWithoutTLS{ + OAuth2: &oauth2, + }, + }, + }, }, }, }, @@ -2736,7 +2748,11 @@ func TestEndpointOAuth2(t *testing.T) { }, }, Spec: monitoringv1.ProbeSpec{ - OAuth2: &oauth2, + HTTPConfig: monitoringv1.HTTPConfig{ + HTTPConfigWithoutTLS: monitoringv1.HTTPConfigWithoutTLS{ + OAuth2: &oauth2, + }, + }, Targets: monitoringv1.ProbeTargets{ StaticConfig: &monitoringv1.ProbeTargetStaticConfig{ Targets: []string{"127.0.0.1"}, @@ -4108,6 +4124,34 @@ func TestRemoteWriteConfig(t *testing.T) { }, golden: "RemoteWriteConfig_AzureADManagedIdentity_v3.5.0.golden", }, + { + version: "v3.7.0", + remoteWrite: monitoringv1.RemoteWriteSpec{ + URL: "http://example.com", + AzureAD: &monitoringv1.AzureAD{ + Cloud: ptr.To("AzureGovernment"), + WorkloadIdentity: &monitoringv1.AzureWorkloadIdentity{ + ClientID: "00000000-a12b-3cd4-e56f-000000000000", + TenantID: "11111111-a12b-3cd4-e56f-000000000000", + }, + }, + }, + golden: "RemoteWriteConfigAzureADWorkloadIdentity_v3.7.0.golden", + }, + { + version: "v3.6.0", + remoteWrite: monitoringv1.RemoteWriteSpec{ + URL: "http://example.com", + AzureAD: &monitoringv1.AzureAD{ + Cloud: ptr.To("AzureGovernment"), + WorkloadIdentity: &monitoringv1.AzureWorkloadIdentity{ + ClientID: "00000000-a12b-3cd4-e56f-000000000000", + TenantID: "11111111-a12b-3cd4-e56f-000000000000", + }, + }, + }, + golden: "RemoteWriteConfigAzureADWorkloadIdentity_v3.6.0.golden", + }, { version: "v2.26.0", remoteWrite: monitoringv1.RemoteWriteSpec{ @@ -4463,6 +4507,34 @@ func TestRemoteWriteConfig(t *testing.T) { }, golden: "RemoteWriteConfigWithEmptyMetadataConfig.golden", }, + { + version: "v3.8.0", + remoteWrite: monitoringv1.RemoteWriteSpec{ + URL: "http://example.com", + AzureAD: &monitoringv1.AzureAD{ + Cloud: ptr.To("AzurePublic"), + ManagedIdentity: &monitoringv1.ManagedIdentity{ + ClientID: ptr.To("00000000-a12b-3cd4-e56f-000000000000"), + }, + Scope: ptr.To("https://custom.monitor.azure.com/.default"), + }, + }, + golden: "RemoteWriteConfig_AzureADScope_v3.8.0.golden", + }, + { + version: "v3.9.0", + remoteWrite: monitoringv1.RemoteWriteSpec{ + URL: "http://example.com", + AzureAD: &monitoringv1.AzureAD{ + Cloud: ptr.To("AzurePublic"), + ManagedIdentity: &monitoringv1.ManagedIdentity{ + ClientID: ptr.To("00000000-a12b-3cd4-e56f-000000000000"), + }, + Scope: ptr.To("https://custom.monitor.azure.com/.default"), + }, + }, + golden: "RemoteWriteConfig_AzureADScope_v3.9.0.golden", + }, } { t.Run(fmt.Sprintf("i=%d,version=%s", i, tc.version), func(t *testing.T) { p := defaultPrometheus() @@ -5054,6 +5126,35 @@ func TestNativeHistogramConfig(t *testing.T) { }, golden: "NativeHistogramConfigAlwaysScrapeClassicHistograms.golden", }, + { + version: "v3.8.0", + nativeHistogramConfig: monitoringv1.NativeHistogramConfig{ + ScrapeNativeHistograms: ptr.To(true), + NativeHistogramBucketLimit: ptr.To(uint64(10)), + ScrapeClassicHistograms: ptr.To(true), + NativeHistogramMinBucketFactor: ptr.To(resource.MustParse("12.124")), + ConvertClassicHistogramsToNHCB: ptr.To(true), + }, + golden: "NativeHistogramConfigWithScrapeNativeHistograms.golden", + }, + { + version: "v3.7.0", + nativeHistogramConfig: monitoringv1.NativeHistogramConfig{ + ScrapeNativeHistograms: ptr.To(true), + NativeHistogramBucketLimit: ptr.To(uint64(10)), + ScrapeClassicHistograms: ptr.To(true), + NativeHistogramMinBucketFactor: ptr.To(resource.MustParse("12.124")), + ConvertClassicHistogramsToNHCB: ptr.To(true), + }, + golden: "NativeHistogramConfigMissScrapeNativeHistograms.golden", + }, + { + version: "v3.8.0", + nativeHistogramConfig: monitoringv1.NativeHistogramConfig{ + ScrapeNativeHistograms: ptr.To(true), + }, + golden: "NativeHistogramConfigOnlyScrapeNativeHistograms.golden", + }, } { t.Run(fmt.Sprintf("version=%s", tc.version), func(t *testing.T) { p := defaultPrometheus() @@ -5273,9 +5374,15 @@ func TestServiceMonitorEndpointFollowRedirects(t *testing.T) { Spec: monitoringv1.ServiceMonitorSpec{ Endpoints: []monitoringv1.Endpoint{ { - Port: "web", - Interval: "30s", - FollowRedirects: ptr.To(tc.followRedirects), + Port: "web", + Interval: "30s", + HTTPConfigWithProxyAndTLSFiles: monitoringv1.HTTPConfigWithProxyAndTLSFiles{ + HTTPConfigWithTLSFiles: monitoringv1.HTTPConfigWithTLSFiles{ + HTTPConfigWithoutTLS: monitoringv1.HTTPConfigWithoutTLS{ + FollowRedirects: ptr.To(tc.followRedirects), + }, + }, + }, }, }, }, @@ -5344,9 +5451,15 @@ func TestPodMonitorEndpointFollowRedirects(t *testing.T) { Spec: monitoringv1.PodMonitorSpec{ PodMetricsEndpoints: []monitoringv1.PodMetricsEndpoint{ { - Port: ptr.To("web"), - Interval: "30s", - HTTPConfig: monitoringv1.HTTPConfig{FollowRedirects: ptr.To(tc.followRedirects)}, + Port: ptr.To("web"), + Interval: "30s", + HTTPConfigWithProxy: monitoringv1.HTTPConfigWithProxy{ + HTTPConfig: monitoringv1.HTTPConfig{ + HTTPConfigWithoutTLS: monitoringv1.HTTPConfigWithoutTLS{ + FollowRedirects: ptr.To(tc.followRedirects), + }, + }, + }, }, }, }, @@ -5416,9 +5529,15 @@ func TestServiceMonitorEndpointEnableHttp2(t *testing.T) { Spec: monitoringv1.ServiceMonitorSpec{ Endpoints: []monitoringv1.Endpoint{ { - Port: "web", - Interval: "30s", - EnableHttp2: ptr.To(tc.enableHTTP2), + Port: "web", + Interval: "30s", + HTTPConfigWithProxyAndTLSFiles: monitoringv1.HTTPConfigWithProxyAndTLSFiles{ + HTTPConfigWithTLSFiles: monitoringv1.HTTPConfigWithTLSFiles{ + HTTPConfigWithoutTLS: monitoringv1.HTTPConfigWithoutTLS{ + EnableHTTP2: ptr.To(tc.enableHTTP2), + }, + }, + }, }, }, }, @@ -5525,9 +5644,15 @@ func TestPodMonitorEndpointEnableHttp2(t *testing.T) { Spec: monitoringv1.PodMonitorSpec{ PodMetricsEndpoints: []monitoringv1.PodMetricsEndpoint{ { - Port: ptr.To("web"), - Interval: "30s", - HTTPConfig: monitoringv1.HTTPConfig{EnableHTTP2: ptr.To(tc.enableHTTP2)}, + Port: ptr.To("web"), + Interval: "30s", + HTTPConfigWithProxy: monitoringv1.HTTPConfigWithProxy{ + HTTPConfig: monitoringv1.HTTPConfig{ + HTTPConfigWithoutTLS: monitoringv1.HTTPConfigWithoutTLS{ + EnableHTTP2: ptr.To(tc.enableHTTP2), + }, + }, + }, }, }, }, @@ -10001,21 +10126,21 @@ func TestOTLPConfig(t *testing.T) { func TestTracingConfig(t *testing.T) { samplingTwo := resource.MustParse("0.5") testCases := []struct { - tracingConfig *monitoringv1.PrometheusTracingConfig + tracingConfig *monitoringv1.TracingConfig name string expectedErr bool golden string }{ { name: "Config only with endpoint", - tracingConfig: &monitoringv1.PrometheusTracingConfig{ + tracingConfig: &monitoringv1.TracingConfig{ Endpoint: "https://otel-collector.default.svc.local:3333", }, golden: "TracingConfig_Config_only_with_endpoint.golden", expectedErr: false, }, { - tracingConfig: &monitoringv1.PrometheusTracingConfig{ + tracingConfig: &monitoringv1.TracingConfig{ ClientType: ptr.To("grpc"), Endpoint: "https://otel-collector.default.svc.local:3333", SamplingFraction: &samplingTwo, @@ -10416,9 +10541,11 @@ func TestScrapeClass(t *testing.T) { { Name: "test-tls-scrape-class", TLSConfig: &monitoringv1.TLSConfig{ - CAFile: "/etc/prometheus/secrets/ca.crt", - CertFile: "/etc/prometheus/secrets/tls.crt", - KeyFile: "/etc/prometheus/secrets/tls.key", + TLSFilesConfig: monitoringv1.TLSFilesConfig{ + CAFile: "/etc/prometheus/secrets/ca.crt", + CertFile: "/etc/prometheus/secrets/tls.crt", + KeyFile: "/etc/prometheus/secrets/tls.key", + }, }, }, }, @@ -10431,9 +10558,11 @@ func TestScrapeClass(t *testing.T) { Name: "test-tls-scrape-class", Default: ptr.To(true), TLSConfig: &monitoringv1.TLSConfig{ - CAFile: "/etc/prometheus/secrets/default/ca.crt", - CertFile: "/etc/prometheus/secrets/default/tls.crt", - KeyFile: "/etc/prometheus/secrets/default/tls.key", + TLSFilesConfig: monitoringv1.TLSFilesConfig{ + CAFile: "/etc/prometheus/secrets/default/ca.crt", + CertFile: "/etc/prometheus/secrets/default/tls.crt", + KeyFile: "/etc/prometheus/secrets/default/tls.key", + }, }, }, }, @@ -10492,9 +10621,11 @@ func TestServiceMonitorScrapeClassWithDefaultTLS(t *testing.T) { { Name: "test-tls-scrape-class", TLSConfig: &monitoringv1.TLSConfig{ - CAFile: "/etc/prometheus/secrets/ca.crt", - CertFile: "/etc/prometheus/secrets/tls.crt", - KeyFile: "/etc/prometheus/secrets/tls.key", + TLSFilesConfig: monitoringv1.TLSFilesConfig{ + CAFile: "/etc/prometheus/secrets/ca.crt", + CertFile: "/etc/prometheus/secrets/tls.crt", + KeyFile: "/etc/prometheus/secrets/tls.key", + }, }, }, }, @@ -10532,9 +10663,11 @@ func TestServiceMonitorScrapeClassWithDefaultTLS(t *testing.T) { { Name: "test-tls-scrape-class", TLSConfig: &monitoringv1.TLSConfig{ - CAFile: "/etc/prometheus/secrets/ca.crt", - CertFile: "/etc/prometheus/secrets/tls.crt", - KeyFile: "/etc/prometheus/secrets/tls.key", + TLSFilesConfig: monitoringv1.TLSFilesConfig{ + CAFile: "/etc/prometheus/secrets/ca.crt", + CertFile: "/etc/prometheus/secrets/tls.crt", + KeyFile: "/etc/prometheus/secrets/tls.key", + }, }, }, }, @@ -10604,9 +10737,11 @@ func TestPodMonitorScrapeClassWithDefaultTLS(t *testing.T) { { Name: "test-tls-scrape-class", TLSConfig: &monitoringv1.TLSConfig{ - CAFile: "/etc/prometheus/secrets/ca.crt", - CertFile: "/etc/prometheus/secrets/tls.crt", - KeyFile: "/etc/prometheus/secrets/tls.key", + TLSFilesConfig: monitoringv1.TLSFilesConfig{ + CAFile: "/etc/prometheus/secrets/ca.crt", + CertFile: "/etc/prometheus/secrets/tls.crt", + KeyFile: "/etc/prometheus/secrets/tls.key", + }, }, }, }, @@ -10642,9 +10777,11 @@ func TestPodMonitorScrapeClassWithDefaultTLS(t *testing.T) { { Name: "test-tls-scrape-class", TLSConfig: &monitoringv1.TLSConfig{ - CAFile: "/etc/prometheus/secrets/ca.crt", - CertFile: "/etc/prometheus/secrets/tls.crt", - KeyFile: "/etc/prometheus/secrets/tls.key", + TLSFilesConfig: monitoringv1.TLSFilesConfig{ + CAFile: "/etc/prometheus/secrets/ca.crt", + CertFile: "/etc/prometheus/secrets/tls.crt", + KeyFile: "/etc/prometheus/secrets/tls.key", + }, }, }, }, @@ -10769,18 +10906,22 @@ func TestNewConfigGeneratorWithMultipleDefaultScrapeClass(t *testing.T) { Name: "test-default-scrape-class", Default: ptr.To(true), TLSConfig: &monitoringv1.TLSConfig{ - CAFile: "/etc/prometheus/secrets/ca.crt", - CertFile: "/etc/prometheus/secrets/tls.crt", - KeyFile: "/etc/prometheus/secrets/tls.key", + TLSFilesConfig: monitoringv1.TLSFilesConfig{ + CAFile: "/etc/prometheus/secrets/ca.crt", + CertFile: "/etc/prometheus/secrets/tls.crt", + KeyFile: "/etc/prometheus/secrets/tls.key", + }, }, }, { Name: "test-default-scrape-class-2", Default: ptr.To(true), TLSConfig: &monitoringv1.TLSConfig{ - CAFile: "/etc/prometheus/secrets/ca.crt", - CertFile: "/etc/prometheus/secrets/tls.crt", - KeyFile: "/etc/prometheus/secrets/tls.key", + TLSFilesConfig: monitoringv1.TLSFilesConfig{ + CAFile: "/etc/prometheus/secrets/ca.crt", + CertFile: "/etc/prometheus/secrets/tls.crt", + KeyFile: "/etc/prometheus/secrets/tls.key", + }, }, }, } @@ -10801,16 +10942,20 @@ func TestMergeTLSConfigWithScrapeClass(t *testing.T) { name: "nil TLSConfig and ScrapeClass", scrapeClass: monitoringv1.ScrapeClass{ TLSConfig: &monitoringv1.TLSConfig{ - CAFile: "defaultCAFile", - CertFile: "defaultCertFile", - KeyFile: "defaultKeyFile", + TLSFilesConfig: monitoringv1.TLSFilesConfig{ + CAFile: "defaultCAFile", + CertFile: "defaultCertFile", + KeyFile: "defaultKeyFile", + }, }, }, expectedConfig: &monitoringv1.TLSConfig{ - CAFile: "defaultCAFile", - CertFile: "defaultCertFile", - KeyFile: "defaultKeyFile", + TLSFilesConfig: monitoringv1.TLSFilesConfig{ + CAFile: "defaultCAFile", + CertFile: "defaultCertFile", + KeyFile: "defaultKeyFile", + }, }, }, { @@ -10819,37 +10964,47 @@ func TestMergeTLSConfigWithScrapeClass(t *testing.T) { { name: "non-nil TLSConfig and empty ScrapeClass", tlsConfig: &monitoringv1.TLSConfig{ - CAFile: "caFile", - CertFile: "certFile", - KeyFile: "keyFile", + TLSFilesConfig: monitoringv1.TLSFilesConfig{ + CAFile: "caFile", + CertFile: "certFile", + KeyFile: "keyFile", + }, }, scrapeClass: monitoringv1.ScrapeClass{}, expectedConfig: &monitoringv1.TLSConfig{ - CAFile: "caFile", - CertFile: "certFile", - KeyFile: "keyFile", + TLSFilesConfig: monitoringv1.TLSFilesConfig{ + CAFile: "caFile", + CertFile: "certFile", + KeyFile: "keyFile", + }, }, }, { name: "non-nil TLSConfig and ScrapeClass", tlsConfig: &monitoringv1.TLSConfig{ - CAFile: "caFile", - CertFile: "certFile", - KeyFile: "keyFile", + TLSFilesConfig: monitoringv1.TLSFilesConfig{ + CAFile: "caFile", + CertFile: "certFile", + KeyFile: "keyFile", + }, }, scrapeClass: monitoringv1.ScrapeClass{ TLSConfig: &monitoringv1.TLSConfig{ - CAFile: "defaultCAFile", - CertFile: "defaultCertFile", - KeyFile: "defaultKeyFile", + TLSFilesConfig: monitoringv1.TLSFilesConfig{ + CAFile: "defaultCAFile", + CertFile: "defaultCertFile", + KeyFile: "defaultKeyFile", + }, }, }, expectedConfig: &monitoringv1.TLSConfig{ - CAFile: "caFile", - CertFile: "certFile", - KeyFile: "keyFile", + TLSFilesConfig: monitoringv1.TLSFilesConfig{ + CAFile: "caFile", + CertFile: "certFile", + KeyFile: "keyFile", + }, }, }, } @@ -13904,3 +14059,60 @@ func TestAppendConvertScrapeClassicHistograms(t *testing.T) { }) } } + +func TestAppendScrapeNativeHistograms(t *testing.T) { + testCases := []struct { + name string + version string + ScrapeNativeHistograms *bool + expectedCfg string + }{ + { + name: "ScrapeNativeHistograms true with Prometheus Version 3.8", + version: "v3.8.0", + ScrapeNativeHistograms: ptr.To(true), + expectedCfg: "ScrapeNativeHistogramsTrueProperPromVersion.golden", + }, + { + name: "ScrapeNativeHistograms false with Prometheus Version 3.8", + version: "v3.8.0", + ScrapeNativeHistograms: ptr.To(false), + expectedCfg: "ScrapeNativeHistogramsFalseProperPromVersion.golden", + }, + { + name: "ScrapeNativeHistograms true with Lower Prometheus version", + version: "v3.7.0", + ScrapeNativeHistograms: ptr.To(true), + expectedCfg: "ScrapeNativeHistogramsTrueWrongPromVersion.golden", + }, + } + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + + p := defaultPrometheus() + if tc.version != "" { + p.Spec.CommonPrometheusFields.Version = tc.version + } + if tc.ScrapeNativeHistograms != nil { + p.Spec.CommonPrometheusFields.ScrapeNativeHistograms = tc.ScrapeNativeHistograms + } + + cg := mustNewConfigGenerator(t, p) + cfg, err := cg.GenerateServerConfiguration( + p, + nil, + nil, + nil, + nil, + &assets.StoreBuilder{}, + nil, + nil, + nil, + nil, + ) + require.NoError(t, err) + + golden.Assert(t, string(cfg), tc.expectedCfg) + }) + } +} diff --git a/pkg/prometheus/resource_selector.go b/pkg/prometheus/resource_selector.go index db71881fde4..ed2bece0305 100644 --- a/pkg/prometheus/resource_selector.go +++ b/pkg/prometheus/resource_selector.go @@ -25,7 +25,6 @@ import ( "github.com/asaskevich/govalidator" "github.com/blang/semver/v4" - "github.com/prometheus/prometheus/model/relabel" v1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/fields" @@ -39,6 +38,7 @@ import ( "github.com/prometheus-operator/prometheus-operator/pkg/assets" "github.com/prometheus-operator/prometheus-operator/pkg/k8sutil" "github.com/prometheus-operator/prometheus-operator/pkg/operator" + "github.com/prometheus-operator/prometheus-operator/pkg/prometheus/validation" ) const ( @@ -209,6 +209,10 @@ func (rs *ResourceSelector) checkServiceMonitor(ctx context.Context, sm *monitor } } + if err := endpoint.Validate(); err != nil { + return fmt.Errorf("%w: %w", epErr, err) + } + //nolint:staticcheck // Ignore SA1019 this field is marked as deprecated. if endpoint.BearerTokenSecret != nil && endpoint.BearerTokenSecret.Name != "" { if _, err := rs.store.GetSecretKey(ctx, sm.GetNamespace(), *endpoint.BearerTokenSecret); err != nil { @@ -257,7 +261,10 @@ func (rs *ResourceSelector) checkServiceMonitor(ctx context.Context, sm *monitor } func (rs *ResourceSelector) ValidateRelabelConfigs(rcs []monitoringv1.RelabelConfig) error { - lcv := &LabelConfigValidator{v: rs.version} + lcv, err := validation.NewLabelConfigValidatorFromVersion(rs.version) + if err != nil { + return err + } return lcv.Validate(rcs) } @@ -289,121 +296,6 @@ func validateScrapeIntervalAndTimeout(p monitoringv1.PrometheusInterface, scrape return CompareScrapeTimeoutToScrapeInterval(scrapeTimeout, scrapeInterval) } -type LabelConfigValidator struct { - v semver.Version -} - -func NewLabelConfigValidator(p monitoringv1.PrometheusInterface) (*LabelConfigValidator, error) { - promVersion := operator.StringValOrDefault(p.GetCommonPrometheusFields().Version, operator.DefaultPrometheusVersion) - v, err := semver.ParseTolerant(promVersion) - if err != nil { - return nil, fmt.Errorf("failed to parse Prometheus version: %w", err) - } - - return &LabelConfigValidator{ - v: v, - }, nil -} - -func (lcv *LabelConfigValidator) Validate(rcs []monitoringv1.RelabelConfig) error { - for i, rc := range rcs { - if err := lcv.validate(rc); err != nil { - return fmt.Errorf("[%d]: %w", i, err) - } - } - - return nil -} - -// From https://github.com/prometheus/prometheus/blob/747c5ee2b19a9e6a51acfafae9fa2c77e224803d/model/relabel/relabel.go#L378-L380 -func varInRegexTemplate(template string) bool { - return strings.Contains(template, "$") -} - -func (lcv *LabelConfigValidator) isValidLabelName(labelName string) bool { - validationScheme := operator.ValidationSchemeForPrometheus(lcv.v) - return validationScheme.IsValidLabelName(labelName) -} - -func (lcv *LabelConfigValidator) validate(rc monitoringv1.RelabelConfig) error { - minimumVersionCaseActions := lcv.v.GTE(semver.MustParse("2.36.0")) - minimumVersionEqualActions := lcv.v.GTE(semver.MustParse("2.41.0")) - if rc.Action == "" { - rc.Action = string(relabel.Replace) - } - action := strings.ToLower(rc.Action) - - if (action == string(relabel.Lowercase) || action == string(relabel.Uppercase)) && !minimumVersionCaseActions { - return fmt.Errorf("%s relabel action is only supported from Prometheus version 2.36.0", rc.Action) - } - - if (action == string(relabel.KeepEqual) || action == string(relabel.DropEqual)) && !minimumVersionEqualActions { - return fmt.Errorf("%s relabel action is only supported from Prometheus version 2.41.0", rc.Action) - } - - if _, err := relabel.NewRegexp(rc.Regex); err != nil { - return fmt.Errorf("invalid regex %s for relabel configuration: %w", rc.Regex, err) - } - - if rc.Modulus == 0 && action == string(relabel.HashMod) { - return fmt.Errorf("relabel configuration for hashmod requires non-zero modulus") - } - - if (action == string(relabel.Replace) || action == string(relabel.HashMod) || action == string(relabel.Lowercase) || action == string(relabel.Uppercase) || action == string(relabel.KeepEqual) || action == string(relabel.DropEqual)) && rc.TargetLabel == "" { - return fmt.Errorf("relabel configuration for %s action needs targetLabel value", rc.Action) - } - - if (action == string(relabel.Replace)) && !varInRegexTemplate(rc.TargetLabel) && !lcv.isValidLabelName(rc.TargetLabel) { - return fmt.Errorf("%q is invalid 'target_label' for %s action", rc.TargetLabel, rc.Action) - } - - if (action == string(relabel.Replace)) && varInRegexTemplate(rc.TargetLabel) && !lcv.isValidLabelName(rc.TargetLabel) { - return fmt.Errorf("%q is invalid 'target_label' for %s action", rc.TargetLabel, rc.Action) - } - - if (action == string(relabel.Lowercase) || action == string(relabel.Uppercase) || action == string(relabel.KeepEqual) || action == string(relabel.DropEqual)) && !lcv.isValidLabelName(rc.TargetLabel) { - return fmt.Errorf("%q is invalid 'target_label' for %s action", rc.TargetLabel, rc.Action) - } - - if (action == string(relabel.Lowercase) || action == string(relabel.Uppercase) || action == string(relabel.KeepEqual) || action == string(relabel.DropEqual)) && (rc.Replacement != nil && *rc.Replacement != relabel.DefaultRelabelConfig.Replacement) { - return fmt.Errorf("'replacement' can not be set for %s action", rc.Action) - } - - if action == string(relabel.LabelMap) && (rc.Replacement != nil) && !lcv.isValidLabelName(*rc.Replacement) { - return fmt.Errorf("%q is invalid 'replacement' for %s action", *rc.Replacement, rc.Action) - } - - if action == string(relabel.HashMod) && !lcv.isValidLabelName(rc.TargetLabel) { - return fmt.Errorf("%q is invalid 'target_label' for %s action", rc.TargetLabel, rc.Action) - } - - if action == string(relabel.KeepEqual) || action == string(relabel.DropEqual) { - if (rc.Regex != "" && rc.Regex != relabel.DefaultRelabelConfig.Regex.String()) || - (rc.Modulus != uint64(0) && - rc.Modulus != relabel.DefaultRelabelConfig.Modulus) || - (rc.Separator != nil && - *rc.Separator != relabel.DefaultRelabelConfig.Separator) || - (rc.Replacement != nil && *rc.Replacement != relabel.DefaultRelabelConfig.Replacement) { - return fmt.Errorf("%s action requires only 'source_labels' and `target_label`, and no other fields", rc.Action) - } - } - - if action == string(relabel.LabelDrop) || action == string(relabel.LabelKeep) { - if len(rc.SourceLabels) != 0 || - (rc.TargetLabel != "" && - rc.TargetLabel != relabel.DefaultRelabelConfig.TargetLabel) || - (rc.Modulus != uint64(0) && - rc.Modulus != relabel.DefaultRelabelConfig.Modulus) || - (rc.Separator != nil && - *rc.Separator != relabel.DefaultRelabelConfig.Separator) || - (rc.Replacement != nil && - *rc.Replacement != relabel.DefaultRelabelConfig.Replacement) { - return fmt.Errorf("%s action requires only 'regex', and no other fields", rc.Action) - } - } - return nil -} - func validateScrapeClass(p monitoringv1.PrometheusInterface, sc *string) error { if ptr.Deref(sc, "") == "" { return nil @@ -468,7 +360,7 @@ func (rs *ResourceSelector) checkPodMonitor(ctx context.Context, pm *monitoringv return fmt.Errorf("%w: metricRelabelConfigs: %w", epErr, err) } - if err := rs.addHTTPConfigToStore(ctx, endpoint.HTTPConfig, pm.GetNamespace()); err != nil { + if err := rs.addHTTPConfigToStore(ctx, endpoint.HTTPConfigWithProxy, pm.GetNamespace()); err != nil { return fmt.Errorf("%w: %w", epErr, err) } } @@ -482,7 +374,7 @@ func (rs *ResourceSelector) checkPodMonitor(ctx context.Context, pm *monitoringv func (rs *ResourceSelector) addHTTPConfigToStore( ctx context.Context, - httpConfig monitoringv1.HTTPConfig, + httpConfig monitoringv1.HTTPConfigWithProxy, namespace string) error { if err := httpConfig.Validate(); err != nil { return err @@ -546,8 +438,8 @@ func (rs *ResourceSelector) checkProbe(ctx context.Context, probe *monitoringv1. return err } - if probe.Spec.BearerTokenSecret.Name != "" && probe.Spec.BearerTokenSecret.Key != "" { - if _, err := rs.store.GetSecretKey(ctx, probe.GetNamespace(), probe.Spec.BearerTokenSecret); err != nil { + if probe.Spec.BearerTokenSecret != nil { //nolint:staticcheck // Ignore SA1019 this field is marked as deprecated. + if _, err := rs.store.GetSecretKey(ctx, probe.GetNamespace(), *probe.Spec.BearerTokenSecret); err != nil { //nolint:staticcheck // Ignore SA1019 this field is marked as deprecated. return fmt.Errorf("bearerTokenSecret: %w", err) } } @@ -935,7 +827,15 @@ func (rs *ResourceSelector) validateDNSSDConfigs(sc *monitoringv1alpha1.ScrapeCo } func (rs *ResourceSelector) validateEC2SDConfigs(ctx context.Context, sc *monitoringv1alpha1.ScrapeConfig) error { + + if len(sc.Spec.EC2SDConfigs) > 0 { + if rs.version.GTE(semver.MustParse("3.8.0")) { + return fmt.Errorf("EC2 SD configuration is only supported for Prometheus version < 3.8.0. For Prometheus 3.8.0 onwards, please use AWS SD") + } + } + for i, config := range sc.Spec.EC2SDConfigs { + if config.AccessKey != nil { if _, err := rs.store.GetSecretKey(ctx, sc.GetNamespace(), *config.AccessKey); err != nil { return fmt.Errorf("[%d]: %w", i, err) @@ -1306,8 +1206,14 @@ func (rs *ResourceSelector) validatePuppetDBSDConfigs(ctx context.Context, sc *m } func (rs *ResourceSelector) validateLightSailSDConfigs(ctx context.Context, sc *monitoringv1alpha1.ScrapeConfig) error { - if rs.version.LT(semver.MustParse("2.27.0")) { - return fmt.Errorf("lightSail SD configuration is only supported for Prometheus version >= 2.27.0") + if len(sc.Spec.LightSailSDConfigs) > 0 { + if rs.version.LT(semver.MustParse("2.27.0")) { + return fmt.Errorf("lightSail SD configuration is only supported for Prometheus version >= 2.27.0") + } + + if rs.version.GTE(semver.MustParse("3.8.0")) { + return fmt.Errorf("lightSail SD configuration is only supported for Prometheus version < 3.8.0. For Prometheus 3.8.0 onwards, please use AWS SD") + } } for i, config := range sc.Spec.LightSailSDConfigs { diff --git a/pkg/prometheus/resource_selector_test.go b/pkg/prometheus/resource_selector_test.go index b492366b362..965d1902073 100644 --- a/pkg/prometheus/resource_selector_test.go +++ b/pkg/prometheus/resource_selector_test.go @@ -21,7 +21,6 @@ import ( "testing" "github.com/prometheus/client_golang/prometheus" - "github.com/prometheus/prometheus/model/relabel" "github.com/stretchr/testify/require" v1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" @@ -44,396 +43,6 @@ func newLogger() *slog.Logger { return slog.New(slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{Level: slog.LevelWarn})) } -func TestValidateRelabelConfig(t *testing.T) { - defaultRegexp, err := relabel.DefaultRelabelConfig.Regex.MarshalYAML() - if err != nil { - t.Errorf("Could not marshal relabel.DefaultRelabelConfig.Regex: %v", err) - } - defaultRegex, ok := defaultRegexp.(string) - if !ok { - t.Errorf("Could not assert marshaled defaultRegexp as string: %v", defaultRegexp) - } - - defaultSourceLabels := []monitoringv1.LabelName{} - for _, label := range relabel.DefaultRelabelConfig.SourceLabels { - defaultSourceLabels = append(defaultSourceLabels, monitoringv1.LabelName(label)) - } - - defaultPrometheusSpec := monitoringv1.Prometheus{ - Spec: monitoringv1.PrometheusSpec{ - CommonPrometheusFields: monitoringv1.CommonPrometheusFields{ - Version: "v2.36.0", - }, - }, - } - - for _, tc := range []struct { - scenario string - relabelConfig monitoringv1.RelabelConfig - prometheus monitoringv1.Prometheus - expectedErr bool - }{ - // Test invalid regex expression - { - scenario: "Invalid regex", - relabelConfig: monitoringv1.RelabelConfig{ - Regex: "invalid regex)", - }, - prometheus: defaultPrometheusSpec, - expectedErr: true, - }, - // Test invalid target label - { - scenario: "invalid target label", - relabelConfig: monitoringv1.RelabelConfig{ - Action: "replace", - TargetLabel: "l\\${3}", - }, - prometheus: defaultPrometheusSpec, - expectedErr: true, - }, - // Test empty target label for action replace - { - scenario: "empty target label for replace action", - relabelConfig: monitoringv1.RelabelConfig{ - Action: "replace", - TargetLabel: "", - }, - prometheus: defaultPrometheusSpec, - expectedErr: true, - }, - // Test empty target label for action hashmod - { - scenario: "empty target label for hashmod action", - relabelConfig: monitoringv1.RelabelConfig{ - Action: "hashmod", - TargetLabel: "", - }, - prometheus: defaultPrometheusSpec, - expectedErr: true, - }, - // Test empty target label for action uppercase - { - scenario: "empty target label for uppercase action", - relabelConfig: monitoringv1.RelabelConfig{ - Action: "uppercase", - TargetLabel: "", - }, - prometheus: defaultPrometheusSpec, - expectedErr: true, - }, - // Test empty target label for action lowercase - { - scenario: "empty target label for lowercase action", - relabelConfig: monitoringv1.RelabelConfig{ - Action: "lowercase", - TargetLabel: "", - }, - prometheus: defaultPrometheusSpec, - expectedErr: true, - }, - // Test replacement set for action uppercase - { - scenario: "replacement set for uppercase action", - relabelConfig: monitoringv1.RelabelConfig{ - Action: "uppercase", - Replacement: ptr.To("some-replace-value"), - }, - prometheus: defaultPrometheusSpec, - expectedErr: true, - }, - // Test invalid hashmod relabel config - { - scenario: "invalid hashmod config", - relabelConfig: monitoringv1.RelabelConfig{ - SourceLabels: []monitoringv1.LabelName{"instance"}, - Action: "hashmod", - Modulus: 0, - TargetLabel: "__tmp_hashmod", - }, - prometheus: defaultPrometheusSpec, - expectedErr: true, - }, - // Test invalid labelmap relabel config - { - scenario: "invalid labelmap config", - relabelConfig: monitoringv1.RelabelConfig{ - Action: "labelmap", - Regex: "__meta_kubernetes_service_label_(.+)", - Replacement: ptr.To("some-name-value"), - }, - prometheus: defaultPrometheusSpec, - expectedErr: true, - }, - // Test valid labelmap relabel config when replacement not specified - { - scenario: "valid labelmap config", - relabelConfig: monitoringv1.RelabelConfig{ - Action: "labelmap", - Regex: "__meta_kubernetes_service_label_(.+)", - }, - prometheus: defaultPrometheusSpec, - }, - // Test valid labelmap relabel config with replacement specified - { - scenario: "valid labelmap config with replacement", - relabelConfig: monitoringv1.RelabelConfig{ - Action: "labelmap", - Regex: "__meta_kubernetes_service_label_(.+)", - Replacement: ptr.To("abc"), - }, - prometheus: defaultPrometheusSpec, - }, - // Test invalid labelkeep relabel config - { - scenario: "invalid labelkeep config", - relabelConfig: monitoringv1.RelabelConfig{ - SourceLabels: []monitoringv1.LabelName{"instance"}, - Action: "labelkeep", - TargetLabel: "__tmp_labelkeep", - }, - prometheus: defaultPrometheusSpec, - expectedErr: true, - }, - // Test valid labelkeep relabel config - { - scenario: "valid labelkeep config", - relabelConfig: monitoringv1.RelabelConfig{ - Action: "labelkeep", - }, - prometheus: defaultPrometheusSpec, - }, - // Test valid labeldrop relabel config - { - scenario: "valid labeldrop config", - relabelConfig: monitoringv1.RelabelConfig{ - Action: "labeldrop", - Regex: "replica", - }, - prometheus: defaultPrometheusSpec, - }, - // Test valid relabel config with empty replacement - { - scenario: "valid replace config with empty replacement", - relabelConfig: monitoringv1.RelabelConfig{ - Action: "replace", - TargetLabel: "dummyTarget", - Regex: "replica", - Replacement: ptr.To(""), - }, - prometheus: defaultPrometheusSpec, - }, - { - scenario: "valid labeldrop config with default values", - relabelConfig: monitoringv1.RelabelConfig{ - SourceLabels: defaultSourceLabels, - Separator: ptr.To(relabel.DefaultRelabelConfig.Separator), - TargetLabel: relabel.DefaultRelabelConfig.TargetLabel, - Regex: defaultRegex, - Modulus: relabel.DefaultRelabelConfig.Modulus, - Replacement: &relabel.DefaultRelabelConfig.Replacement, - Action: "labeldrop", - }, - prometheus: defaultPrometheusSpec, - }, - // Test valid hashmod relabel config - { - scenario: "valid hashmod config", - relabelConfig: monitoringv1.RelabelConfig{ - SourceLabels: []monitoringv1.LabelName{"instance"}, - Action: "hashmod", - Modulus: 10, - TargetLabel: "__tmp_hashmod", - }, - prometheus: defaultPrometheusSpec, - }, - // Test valid replace relabel config - { - scenario: "valid replace config", - relabelConfig: monitoringv1.RelabelConfig{ - SourceLabels: []monitoringv1.LabelName{"__address__"}, - Action: "replace", - Regex: "([^:]+)(?::\\d+)?", - Replacement: ptr.To("$1:80"), - TargetLabel: "__address__", - }, - prometheus: defaultPrometheusSpec, - }, - // Test valid uppercase relabel config - { - scenario: "valid uppercase config", - relabelConfig: monitoringv1.RelabelConfig{ - SourceLabels: []monitoringv1.LabelName{"foo"}, - Action: "uppercase", - TargetLabel: "foo_uppercase", - }, - prometheus: defaultPrometheusSpec, - }, - // Test valid lowercase relabel config - { - scenario: "valid lowercase config", - relabelConfig: monitoringv1.RelabelConfig{ - SourceLabels: []monitoringv1.LabelName{"bar"}, - Action: "lowercase", - TargetLabel: "bar_lowercase", - }, - prometheus: defaultPrometheusSpec, - }, - // Test uppercase relabel config but lower prometheus version - { - scenario: "uppercase config with lower prometheus version", - relabelConfig: monitoringv1.RelabelConfig{ - SourceLabels: []monitoringv1.LabelName{"foo"}, - Action: "uppercase", - TargetLabel: "foo_uppercase", - }, - prometheus: monitoringv1.Prometheus{ - Spec: monitoringv1.PrometheusSpec{ - CommonPrometheusFields: monitoringv1.CommonPrometheusFields{ - Version: "v2.35.0", - }, - }, - }, - expectedErr: true, - }, - // Test lowercase relabel config but lower prometheus version - { - scenario: "lowercase config with lower prometheus version", - relabelConfig: monitoringv1.RelabelConfig{ - SourceLabels: []monitoringv1.LabelName{"bar"}, - Action: "lowercase", - TargetLabel: "bar_lowercase", - }, - prometheus: monitoringv1.Prometheus{ - Spec: monitoringv1.PrometheusSpec{ - CommonPrometheusFields: monitoringv1.CommonPrometheusFields{ - Version: "v2.35.0", - }, - }, - }, - expectedErr: true, - }, - // Test keepequal relabel config but lower prometheus version - { - scenario: "keepequal config with lower prometheus version", - relabelConfig: monitoringv1.RelabelConfig{ - SourceLabels: []monitoringv1.LabelName{"foo"}, - Action: "keepequal", - TargetLabel: "foo_keepequal", - }, - prometheus: monitoringv1.Prometheus{ - Spec: monitoringv1.PrometheusSpec{ - CommonPrometheusFields: monitoringv1.CommonPrometheusFields{ - Version: "v2.37.0", - }, - }, - }, - expectedErr: true, - }, - // Test dropequal relabel config but lower prometheus version - { - scenario: "dropequal config with lower prometheus version", - relabelConfig: monitoringv1.RelabelConfig{ - SourceLabels: []monitoringv1.LabelName{"bar"}, - Action: "keepequal", - TargetLabel: "bar_keepequal", - }, - prometheus: monitoringv1.Prometheus{ - Spec: monitoringv1.PrometheusSpec{ - CommonPrometheusFields: monitoringv1.CommonPrometheusFields{ - Version: "v2.37.0", - }, - }, - }, - expectedErr: true, - }, - // Test valid keepequal config - { - scenario: "valid keepequal config", - relabelConfig: monitoringv1.RelabelConfig{ - SourceLabels: []monitoringv1.LabelName{"__tmp_port"}, - TargetLabel: "__port1", - Action: "keepequal", - }, - prometheus: monitoringv1.Prometheus{ - Spec: monitoringv1.PrometheusSpec{ - CommonPrometheusFields: monitoringv1.CommonPrometheusFields{ - Version: "v2.41.0", - }, - }, - }, - }, - // Test valid dropequal config - { - scenario: "valid dropequal config", - relabelConfig: monitoringv1.RelabelConfig{ - SourceLabels: []monitoringv1.LabelName{"__tmp_port"}, - TargetLabel: "__port2", - Action: "dropequal", - }, - prometheus: monitoringv1.Prometheus{ - Spec: monitoringv1.PrometheusSpec{ - CommonPrometheusFields: monitoringv1.CommonPrometheusFields{ - Version: "v2.41.0", - }, - }, - }, - }, - // Test valid keepequal with non default values for other fields - { - scenario: "valid keepequal config with non default values for other fields", - relabelConfig: monitoringv1.RelabelConfig{ - SourceLabels: []monitoringv1.LabelName{"__tmp_port"}, - TargetLabel: "__port1", - Separator: ptr.To("^"), - Regex: "validregex", - Replacement: ptr.To("replacevalue"), - Action: "keepequal", - }, - prometheus: monitoringv1.Prometheus{ - Spec: monitoringv1.PrometheusSpec{ - CommonPrometheusFields: monitoringv1.CommonPrometheusFields{ - Version: "v2.41.0", - }, - }, - }, - expectedErr: true, - }, - // Test valid keepequal with default values for other fields - { - scenario: "valid keepequal config with default values for other fields", - relabelConfig: monitoringv1.RelabelConfig{ - SourceLabels: []monitoringv1.LabelName{"__tmp_port"}, - TargetLabel: "__port1", - Separator: ptr.To(relabel.DefaultRelabelConfig.Separator), - Regex: relabel.DefaultRelabelConfig.Regex.String(), - Modulus: relabel.DefaultRelabelConfig.Modulus, - Replacement: &relabel.DefaultRelabelConfig.Replacement, - Action: "keepequal", - }, - prometheus: monitoringv1.Prometheus{ - Spec: monitoringv1.PrometheusSpec{ - CommonPrometheusFields: monitoringv1.CommonPrometheusFields{ - Version: "v2.41.0", - }, - }, - }, - }, - } { - t.Run(tc.scenario, func(t *testing.T) { - lcv, err := NewLabelConfigValidator(&tc.prometheus) - require.NoError(t, err) - - err = lcv.validate(tc.relabelConfig) - if tc.expectedErr { - require.Error(t, err) - return - } - require.NoError(t, err) - }) - } -} - func TestSelectProbes(t *testing.T) { for _, tc := range []struct { scenario string @@ -1067,28 +676,32 @@ func TestSelectServiceMonitors(t *testing.T) { scenario: "valid TLS config with CA, cert and key", updateSpec: func(sm *monitoringv1.ServiceMonitorSpec) { sm.Endpoints = append(sm.Endpoints, monitoringv1.Endpoint{ - TLSConfig: &monitoringv1.TLSConfig{ - SafeTLSConfig: monitoringv1.SafeTLSConfig{ - CA: monitoringv1.SecretOrConfigMap{ - Secret: &v1.SecretKeySelector{ - Key: "ca", - LocalObjectReference: v1.LocalObjectReference{ - Name: "secret", + HTTPConfigWithProxyAndTLSFiles: monitoringv1.HTTPConfigWithProxyAndTLSFiles{ + HTTPConfigWithTLSFiles: monitoringv1.HTTPConfigWithTLSFiles{ + TLSConfig: &monitoringv1.TLSConfig{ + SafeTLSConfig: monitoringv1.SafeTLSConfig{ + CA: monitoringv1.SecretOrConfigMap{ + Secret: &v1.SecretKeySelector{ + Key: "ca", + LocalObjectReference: v1.LocalObjectReference{ + Name: "secret", + }, + }, }, - }, - }, - Cert: monitoringv1.SecretOrConfigMap{ - Secret: &v1.SecretKeySelector{ - Key: "cert", - LocalObjectReference: v1.LocalObjectReference{ - Name: "secret", + Cert: monitoringv1.SecretOrConfigMap{ + Secret: &v1.SecretKeySelector{ + Key: "cert", + LocalObjectReference: v1.LocalObjectReference{ + Name: "secret", + }, + }, + }, + KeySecret: &v1.SecretKeySelector{ + Key: "key", + LocalObjectReference: v1.LocalObjectReference{ + Name: "secret", + }, }, - }, - }, - KeySecret: &v1.SecretKeySelector{ - Key: "key", - LocalObjectReference: v1.LocalObjectReference{ - Name: "secret", }, }, }, @@ -1101,16 +714,22 @@ func TestSelectServiceMonitors(t *testing.T) { scenario: "invalid TLS config with both CA and CAFile", updateSpec: func(sm *monitoringv1.ServiceMonitorSpec) { sm.Endpoints = append(sm.Endpoints, monitoringv1.Endpoint{ - TLSConfig: &monitoringv1.TLSConfig{ - CAFile: "/etc/secrets/tls/ca.crt", - SafeTLSConfig: monitoringv1.SafeTLSConfig{ - CA: monitoringv1.SecretOrConfigMap{ - Secret: &v1.SecretKeySelector{ - Key: "ca", - LocalObjectReference: v1.LocalObjectReference{ - Name: "secret", + HTTPConfigWithProxyAndTLSFiles: monitoringv1.HTTPConfigWithProxyAndTLSFiles{ + HTTPConfigWithTLSFiles: monitoringv1.HTTPConfigWithTLSFiles{ + TLSConfig: &monitoringv1.TLSConfig{ + SafeTLSConfig: monitoringv1.SafeTLSConfig{ + CA: monitoringv1.SecretOrConfigMap{ + Secret: &v1.SecretKeySelector{ + Key: "ca", + LocalObjectReference: v1.LocalObjectReference{ + Name: "secret", + }, + }, }, }, + TLSFilesConfig: monitoringv1.TLSFilesConfig{ + CAFile: "/etc/secrets/tls/ca.crt", + }, }, }, }, @@ -1122,19 +741,23 @@ func TestSelectServiceMonitors(t *testing.T) { scenario: "invalid TLS config with both CA Secret and Configmap", updateSpec: func(sm *monitoringv1.ServiceMonitorSpec) { sm.Endpoints = append(sm.Endpoints, monitoringv1.Endpoint{ - TLSConfig: &monitoringv1.TLSConfig{ - SafeTLSConfig: monitoringv1.SafeTLSConfig{ - CA: monitoringv1.SecretOrConfigMap{ - Secret: &v1.SecretKeySelector{ - Key: "ca", - LocalObjectReference: v1.LocalObjectReference{ - Name: "secret", - }, - }, - ConfigMap: &v1.ConfigMapKeySelector{ - Key: "ca", - LocalObjectReference: v1.LocalObjectReference{ - Name: "configmap", + HTTPConfigWithProxyAndTLSFiles: monitoringv1.HTTPConfigWithProxyAndTLSFiles{ + HTTPConfigWithTLSFiles: monitoringv1.HTTPConfigWithTLSFiles{ + TLSConfig: &monitoringv1.TLSConfig{ + SafeTLSConfig: monitoringv1.SafeTLSConfig{ + CA: monitoringv1.SecretOrConfigMap{ + Secret: &v1.SecretKeySelector{ + Key: "ca", + LocalObjectReference: v1.LocalObjectReference{ + Name: "secret", + }, + }, + ConfigMap: &v1.ConfigMapKeySelector{ + Key: "ca", + LocalObjectReference: v1.LocalObjectReference{ + Name: "configmap", + }, + }, }, }, }, @@ -1148,13 +771,17 @@ func TestSelectServiceMonitors(t *testing.T) { scenario: "invalid TLS config with invalid CA data", updateSpec: func(sm *monitoringv1.ServiceMonitorSpec) { sm.Endpoints = append(sm.Endpoints, monitoringv1.Endpoint{ - TLSConfig: &monitoringv1.TLSConfig{ - SafeTLSConfig: monitoringv1.SafeTLSConfig{ - CA: monitoringv1.SecretOrConfigMap{ - Secret: &v1.SecretKeySelector{ - Key: "invalid_ca", - LocalObjectReference: v1.LocalObjectReference{ - Name: "secret", + HTTPConfigWithProxyAndTLSFiles: monitoringv1.HTTPConfigWithProxyAndTLSFiles{ + HTTPConfigWithTLSFiles: monitoringv1.HTTPConfigWithTLSFiles{ + TLSConfig: &monitoringv1.TLSConfig{ + SafeTLSConfig: monitoringv1.SafeTLSConfig{ + CA: monitoringv1.SecretOrConfigMap{ + Secret: &v1.SecretKeySelector{ + Key: "invalid_ca", + LocalObjectReference: v1.LocalObjectReference{ + Name: "secret", + }, + }, }, }, }, @@ -1168,13 +795,17 @@ func TestSelectServiceMonitors(t *testing.T) { scenario: "invalid TLS config with cert and missing key", updateSpec: func(sm *monitoringv1.ServiceMonitorSpec) { sm.Endpoints = append(sm.Endpoints, monitoringv1.Endpoint{ - TLSConfig: &monitoringv1.TLSConfig{ - SafeTLSConfig: monitoringv1.SafeTLSConfig{ - Cert: monitoringv1.SecretOrConfigMap{ - Secret: &v1.SecretKeySelector{ - Key: "cert", - LocalObjectReference: v1.LocalObjectReference{ - Name: "secret", + HTTPConfigWithProxyAndTLSFiles: monitoringv1.HTTPConfigWithProxyAndTLSFiles{ + HTTPConfigWithTLSFiles: monitoringv1.HTTPConfigWithTLSFiles{ + TLSConfig: &monitoringv1.TLSConfig{ + SafeTLSConfig: monitoringv1.SafeTLSConfig{ + Cert: monitoringv1.SecretOrConfigMap{ + Secret: &v1.SecretKeySelector{ + Key: "cert", + LocalObjectReference: v1.LocalObjectReference{ + Name: "secret", + }, + }, }, }, }, @@ -1188,12 +819,16 @@ func TestSelectServiceMonitors(t *testing.T) { scenario: "invalid TLS config with key and missing cert", updateSpec: func(sm *monitoringv1.ServiceMonitorSpec) { sm.Endpoints = append(sm.Endpoints, monitoringv1.Endpoint{ - TLSConfig: &monitoringv1.TLSConfig{ - SafeTLSConfig: monitoringv1.SafeTLSConfig{ - KeySecret: &v1.SecretKeySelector{ - Key: "key", - LocalObjectReference: v1.LocalObjectReference{ - Name: "secret", + HTTPConfigWithProxyAndTLSFiles: monitoringv1.HTTPConfigWithProxyAndTLSFiles{ + HTTPConfigWithTLSFiles: monitoringv1.HTTPConfigWithTLSFiles{ + TLSConfig: &monitoringv1.TLSConfig{ + SafeTLSConfig: monitoringv1.SafeTLSConfig{ + KeySecret: &v1.SecretKeySelector{ + Key: "key", + LocalObjectReference: v1.LocalObjectReference{ + Name: "secret", + }, + }, }, }, }, @@ -1206,20 +841,24 @@ func TestSelectServiceMonitors(t *testing.T) { scenario: "invalid TLS config with key and invalid cert", updateSpec: func(sm *monitoringv1.ServiceMonitorSpec) { sm.Endpoints = append(sm.Endpoints, monitoringv1.Endpoint{ - TLSConfig: &monitoringv1.TLSConfig{ - SafeTLSConfig: monitoringv1.SafeTLSConfig{ - Cert: monitoringv1.SecretOrConfigMap{ - Secret: &v1.SecretKeySelector{ - Key: "invalid_ca", - LocalObjectReference: v1.LocalObjectReference{ - Name: "secret", + HTTPConfigWithProxyAndTLSFiles: monitoringv1.HTTPConfigWithProxyAndTLSFiles{ + HTTPConfigWithTLSFiles: monitoringv1.HTTPConfigWithTLSFiles{ + TLSConfig: &monitoringv1.TLSConfig{ + SafeTLSConfig: monitoringv1.SafeTLSConfig{ + Cert: monitoringv1.SecretOrConfigMap{ + Secret: &v1.SecretKeySelector{ + Key: "invalid_ca", + LocalObjectReference: v1.LocalObjectReference{ + Name: "secret", + }, + }, + }, + KeySecret: &v1.SecretKeySelector{ + Key: "key", + LocalObjectReference: v1.LocalObjectReference{ + Name: "secret", + }, }, - }, - }, - KeySecret: &v1.SecretKeySelector{ - Key: "key", - LocalObjectReference: v1.LocalObjectReference{ - Name: "secret", }, }, }, @@ -1232,17 +871,19 @@ func TestSelectServiceMonitors(t *testing.T) { scenario: "valid proxy config", updateSpec: func(sm *monitoringv1.ServiceMonitorSpec) { sm.Endpoints = append(sm.Endpoints, monitoringv1.Endpoint{ - ProxyConfig: monitoringv1.ProxyConfig{ - ProxyURL: ptr.To("http://no-proxy.com"), - NoProxy: ptr.To("0.0.0.0"), - ProxyFromEnvironment: ptr.To(false), - ProxyConnectHeader: map[string][]v1.SecretKeySelector{ - "header": { - { - LocalObjectReference: v1.LocalObjectReference{ - Name: "secret", + HTTPConfigWithProxyAndTLSFiles: monitoringv1.HTTPConfigWithProxyAndTLSFiles{ + ProxyConfig: monitoringv1.ProxyConfig{ + ProxyURL: ptr.To("http://no-proxy.com"), + NoProxy: ptr.To("0.0.0.0"), + ProxyFromEnvironment: ptr.To(false), + ProxyConnectHeader: map[string][]v1.SecretKeySelector{ + "header": { + { + LocalObjectReference: v1.LocalObjectReference{ + Name: "secret", + }, + Key: "key1", }, - Key: "key1", }, }, }, @@ -1255,17 +896,19 @@ func TestSelectServiceMonitors(t *testing.T) { scenario: "invalid proxy config with invalid secret key", updateSpec: func(sm *monitoringv1.ServiceMonitorSpec) { sm.Endpoints = append(sm.Endpoints, monitoringv1.Endpoint{ - ProxyConfig: monitoringv1.ProxyConfig{ - ProxyURL: ptr.To("http://no-proxy.com"), - NoProxy: ptr.To("0.0.0.0"), - ProxyFromEnvironment: ptr.To(false), - ProxyConnectHeader: map[string][]v1.SecretKeySelector{ - "header": { - { - LocalObjectReference: v1.LocalObjectReference{ - Name: "secret", + HTTPConfigWithProxyAndTLSFiles: monitoringv1.HTTPConfigWithProxyAndTLSFiles{ + ProxyConfig: monitoringv1.ProxyConfig{ + ProxyURL: ptr.To("http://no-proxy.com"), + NoProxy: ptr.To("0.0.0.0"), + ProxyFromEnvironment: ptr.To(false), + ProxyConnectHeader: map[string][]v1.SecretKeySelector{ + "header": { + { + LocalObjectReference: v1.LocalObjectReference{ + Name: "secret", + }, + Key: "invalid_key", }, - Key: "invalid_key", }, }, }, @@ -1278,17 +921,19 @@ func TestSelectServiceMonitors(t *testing.T) { scenario: "invalid proxy config due to invalid proxy url", updateSpec: func(sm *monitoringv1.ServiceMonitorSpec) { sm.Endpoints = append(sm.Endpoints, monitoringv1.Endpoint{ - ProxyConfig: monitoringv1.ProxyConfig{ - ProxyURL: ptr.To("http://xxx-${dev}.svc.cluster.local:80"), - NoProxy: ptr.To("0.0.0.0"), - ProxyFromEnvironment: ptr.To(false), - ProxyConnectHeader: map[string][]v1.SecretKeySelector{ - "header": { - { - LocalObjectReference: v1.LocalObjectReference{ - Name: "secret", + HTTPConfigWithProxyAndTLSFiles: monitoringv1.HTTPConfigWithProxyAndTLSFiles{ + ProxyConfig: monitoringv1.ProxyConfig{ + ProxyURL: ptr.To("http://xxx-${dev}.svc.cluster.local:80"), + NoProxy: ptr.To("0.0.0.0"), + ProxyFromEnvironment: ptr.To(false), + ProxyConnectHeader: map[string][]v1.SecretKeySelector{ + "header": { + { + LocalObjectReference: v1.LocalObjectReference{ + Name: "secret", + }, + Key: "key1", }, - Key: "key1", }, }, }, @@ -1301,16 +946,18 @@ func TestSelectServiceMonitors(t *testing.T) { scenario: "invalid proxy config with noProxy defined but proxy from environment set to true", updateSpec: func(sm *monitoringv1.ServiceMonitorSpec) { sm.Endpoints = append(sm.Endpoints, monitoringv1.Endpoint{ - ProxyConfig: monitoringv1.ProxyConfig{ - NoProxy: ptr.To("0.0.0.0"), - ProxyFromEnvironment: ptr.To(true), - ProxyConnectHeader: map[string][]v1.SecretKeySelector{ - "header": { - { - LocalObjectReference: v1.LocalObjectReference{ - Name: "secret", + HTTPConfigWithProxyAndTLSFiles: monitoringv1.HTTPConfigWithProxyAndTLSFiles{ + ProxyConfig: monitoringv1.ProxyConfig{ + NoProxy: ptr.To("0.0.0.0"), + ProxyFromEnvironment: ptr.To(true), + ProxyConnectHeader: map[string][]v1.SecretKeySelector{ + "header": { + { + LocalObjectReference: v1.LocalObjectReference{ + Name: "secret", + }, + Key: "key1", }, - Key: "key1", }, }, }, @@ -1323,16 +970,18 @@ func TestSelectServiceMonitors(t *testing.T) { scenario: "invalid proxy config with proxy url defined but proxy from environment set to true", updateSpec: func(sm *monitoringv1.ServiceMonitorSpec) { sm.Endpoints = append(sm.Endpoints, monitoringv1.Endpoint{ - ProxyConfig: monitoringv1.ProxyConfig{ - ProxyURL: ptr.To("http://no-proxy.com"), - ProxyFromEnvironment: ptr.To(true), - ProxyConnectHeader: map[string][]v1.SecretKeySelector{ - "header": { - { - LocalObjectReference: v1.LocalObjectReference{ - Name: "secret", + HTTPConfigWithProxyAndTLSFiles: monitoringv1.HTTPConfigWithProxyAndTLSFiles{ + ProxyConfig: monitoringv1.ProxyConfig{ + ProxyURL: ptr.To("http://no-proxy.com"), + ProxyFromEnvironment: ptr.To(true), + ProxyConnectHeader: map[string][]v1.SecretKeySelector{ + "header": { + { + LocalObjectReference: v1.LocalObjectReference{ + Name: "secret", + }, + Key: "key1", }, - Key: "key1", }, }, }, @@ -1345,14 +994,16 @@ func TestSelectServiceMonitors(t *testing.T) { scenario: "invalid proxy config only with proxy connect header defined", updateSpec: func(sm *monitoringv1.ServiceMonitorSpec) { sm.Endpoints = append(sm.Endpoints, monitoringv1.Endpoint{ - ProxyConfig: monitoringv1.ProxyConfig{ - ProxyConnectHeader: map[string][]v1.SecretKeySelector{ - "header": { - { - LocalObjectReference: v1.LocalObjectReference{ - Name: "secret", + HTTPConfigWithProxyAndTLSFiles: monitoringv1.HTTPConfigWithProxyAndTLSFiles{ + ProxyConfig: monitoringv1.ProxyConfig{ + ProxyConnectHeader: map[string][]v1.SecretKeySelector{ + "header": { + { + LocalObjectReference: v1.LocalObjectReference{ + Name: "secret", + }, + Key: "key1", }, - Key: "key1", }, }, }, @@ -1613,7 +1264,7 @@ func TestSelectPodMonitors(t *testing.T) { scenario: "valid proxy config", updateSpec: func(pm *monitoringv1.PodMonitorSpec) { pm.PodMetricsEndpoints = append(pm.PodMetricsEndpoints, monitoringv1.PodMetricsEndpoint{ - HTTPConfig: monitoringv1.HTTPConfig{ + HTTPConfigWithProxy: monitoringv1.HTTPConfigWithProxy{ ProxyConfig: monitoringv1.ProxyConfig{ ProxyURL: ptr.To("http://no-proxy.com"), NoProxy: ptr.To("0.0.0.0"), @@ -1638,7 +1289,7 @@ func TestSelectPodMonitors(t *testing.T) { scenario: "invalid proxy config with invalid secret key", updateSpec: func(pm *monitoringv1.PodMonitorSpec) { pm.PodMetricsEndpoints = append(pm.PodMetricsEndpoints, monitoringv1.PodMetricsEndpoint{ - HTTPConfig: monitoringv1.HTTPConfig{ + HTTPConfigWithProxy: monitoringv1.HTTPConfigWithProxy{ ProxyConfig: monitoringv1.ProxyConfig{ ProxyURL: ptr.To("http://no-proxy.com"), NoProxy: ptr.To("0.0.0.0"), @@ -1663,7 +1314,7 @@ func TestSelectPodMonitors(t *testing.T) { scenario: "invalid proxy config due to invalid proxy url", updateSpec: func(pm *monitoringv1.PodMonitorSpec) { pm.PodMetricsEndpoints = append(pm.PodMetricsEndpoints, monitoringv1.PodMetricsEndpoint{ - HTTPConfig: monitoringv1.HTTPConfig{ + HTTPConfigWithProxy: monitoringv1.HTTPConfigWithProxy{ ProxyConfig: monitoringv1.ProxyConfig{ ProxyURL: ptr.To("http://xxx-${dev}.svc.cluster.local:80"), NoProxy: ptr.To("0.0.0.0"), @@ -1688,7 +1339,7 @@ func TestSelectPodMonitors(t *testing.T) { scenario: "invalid proxy config with noProxy defined but proxy from environment set to true", updateSpec: func(pm *monitoringv1.PodMonitorSpec) { pm.PodMetricsEndpoints = append(pm.PodMetricsEndpoints, monitoringv1.PodMetricsEndpoint{ - HTTPConfig: monitoringv1.HTTPConfig{ + HTTPConfigWithProxy: monitoringv1.HTTPConfigWithProxy{ ProxyConfig: monitoringv1.ProxyConfig{ NoProxy: ptr.To("0.0.0.0"), ProxyFromEnvironment: ptr.To(true), @@ -1712,7 +1363,7 @@ func TestSelectPodMonitors(t *testing.T) { scenario: "invalid proxy config with proxy url defined but proxy from environment set to true", updateSpec: func(pm *monitoringv1.PodMonitorSpec) { pm.PodMetricsEndpoints = append(pm.PodMetricsEndpoints, monitoringv1.PodMetricsEndpoint{ - HTTPConfig: monitoringv1.HTTPConfig{ + HTTPConfigWithProxy: monitoringv1.HTTPConfigWithProxy{ ProxyConfig: monitoringv1.ProxyConfig{ ProxyURL: ptr.To("http://no-proxy.com"), ProxyFromEnvironment: ptr.To(true), @@ -1736,7 +1387,7 @@ func TestSelectPodMonitors(t *testing.T) { scenario: "invalid proxy config only with proxy connect header defined", updateSpec: func(pm *monitoringv1.PodMonitorSpec) { pm.PodMetricsEndpoints = append(pm.PodMetricsEndpoints, monitoringv1.PodMetricsEndpoint{ - HTTPConfig: monitoringv1.HTTPConfig{ + HTTPConfigWithProxy: monitoringv1.HTTPConfigWithProxy{ ProxyConfig: monitoringv1.ProxyConfig{ ProxyConnectHeader: map[string][]v1.SecretKeySelector{ "header": { @@ -2995,7 +2646,8 @@ func TestSelectScrapeConfigs(t *testing.T) { }, } }, - valid: true, + promVersion: "3.7.0", + valid: true, }, { scenario: "EC2 SD config with no secret ref provided", @@ -3006,7 +2658,8 @@ func TestSelectScrapeConfigs(t *testing.T) { }, } }, - valid: true, + promVersion: "3.7.0", + valid: true, }, { scenario: "EC2 SD config with invalid secret ref for secretKey", @@ -3029,7 +2682,8 @@ func TestSelectScrapeConfigs(t *testing.T) { }, } }, - valid: false, + promVersion: "3.7.0", + valid: false, }, { scenario: "EC2 SD config with valid TLS Config", @@ -3064,7 +2718,8 @@ func TestSelectScrapeConfigs(t *testing.T) { }, } }, - valid: true, + promVersion: "3.7.0", + valid: true, }, { scenario: "EC2 SD config with valid HTTPS Config", @@ -3123,7 +2778,8 @@ func TestSelectScrapeConfigs(t *testing.T) { }, } }, - valid: false, + promVersion: "3.7.0", + valid: false, }, { scenario: "EC2 SD config with valid proxy settings", @@ -3152,6 +2808,18 @@ func TestSelectScrapeConfigs(t *testing.T) { promVersion: "2.52.0", valid: true, }, + { + scenario: "EC2 SD config with unsupported version", + updateSpec: func(sc *monitoringv1alpha1.ScrapeConfigSpec) { + sc.EC2SDConfigs = []monitoringv1alpha1.EC2SDConfig{ + { + Region: ptr.To("us-east-1"), + }, + } + }, + promVersion: "3.8.0", + valid: false, + }, { scenario: "Azure SD config with valid options for OAuth authentication method", updateSpec: func(sc *monitoringv1alpha1.ScrapeConfigSpec) { @@ -4389,7 +4057,8 @@ func TestSelectScrapeConfigs(t *testing.T) { }, } }, - valid: true, + promVersion: "3.7.0", + valid: true, }, { scenario: "LightSail SD config with invalid TLS config with invalid CA data", @@ -4409,7 +4078,8 @@ func TestSelectScrapeConfigs(t *testing.T) { }, } }, - valid: false, + promVersion: "3.7.0", + valid: false, }, { scenario: "LightSail SD config with valid proxy settings", @@ -4434,7 +4104,8 @@ func TestSelectScrapeConfigs(t *testing.T) { }, } }, - valid: true, + promVersion: "3.7.0", + valid: true, }, { scenario: "LightSail SD config with invalid proxy settings", @@ -4458,7 +4129,8 @@ func TestSelectScrapeConfigs(t *testing.T) { }, } }, - valid: false, + promVersion: "3.7.0", + valid: false, }, { scenario: "LightSail SD config with invalid secret ref", @@ -4476,7 +4148,8 @@ func TestSelectScrapeConfigs(t *testing.T) { }, } }, - valid: false, + promVersion: "3.7.0", + valid: false, }, { @@ -4500,7 +4173,8 @@ func TestSelectScrapeConfigs(t *testing.T) { }, } }, - valid: true, + promVersion: "3.7.0", + valid: true, }, { scenario: "LightSail SD config with no secret ref provided", @@ -4511,7 +4185,8 @@ func TestSelectScrapeConfigs(t *testing.T) { }, } }, - valid: true, + promVersion: "3.7.0", + valid: true, }, { scenario: "LightSail SD config with invalid secret ref for accessKey", @@ -4534,7 +4209,8 @@ func TestSelectScrapeConfigs(t *testing.T) { }, } }, - valid: false, + promVersion: "3.7.0", + valid: false, }, { scenario: "LightSail SD config with invalid secret ref for secretKey", @@ -4557,7 +4233,20 @@ func TestSelectScrapeConfigs(t *testing.T) { }, } }, - valid: false, + promVersion: "3.7.0", + valid: false, + }, + { + scenario: "LightSail SD config with unsupported version", + updateSpec: func(sc *monitoringv1alpha1.ScrapeConfigSpec) { + sc.LightSailSDConfigs = []monitoringv1alpha1.LightSailSDConfig{ + { + Region: ptr.To("us-east-1"), + }, + } + }, + promVersion: "3.8.0", + valid: false, }, { scenario: "OVHCloud SD config", diff --git a/pkg/prometheus/server/operator.go b/pkg/prometheus/server/operator.go index 59d7b4d8063..23223ad6ae5 100644 --- a/pkg/prometheus/server/operator.go +++ b/pkg/prometheus/server/operator.go @@ -46,6 +46,7 @@ import ( "github.com/prometheus-operator/prometheus-operator/pkg/listwatch" "github.com/prometheus-operator/prometheus-operator/pkg/operator" prompkg "github.com/prometheus-operator/prometheus-operator/pkg/prometheus" + "github.com/prometheus-operator/prometheus-operator/pkg/prometheus/validation" "github.com/prometheus-operator/prometheus-operator/pkg/webconfig" ) @@ -54,11 +55,13 @@ const ( controllerName = "prometheus-controller" applicationNameLabelValue = "prometheus" - unmanagedConfigurationReason = "ConfigurationUnmanaged" - unmanagedConfigurationMessage string = "the operator doesn't manage the Prometheus configuration secret because neither serviceMonitorSelector nor podMonitorSelector, nor probeSelector is specified. Unmanaged Prometheus configuration is deprecated, use additionalScrapeConfigs or the ScrapeConfig instead." + noSelectedResourcesMessage = "No ServiceMonitor, PodMonitor, Probe, ScrapeConfig, and PrometheusRule have been selected." + + unmanagedConfigurationReason = "ConfigurationUnmanaged" + unmanagedConfigurationMessage = "the operator doesn't manage the Prometheus configuration secret because neither serviceMonitorSelector nor podMonitorSelector, nor probeSelector, nor scrapeConfigSelector is specified. Unmanaged Prometheus configuration is deprecated, use additionalScrapeConfigs or the ScrapeConfig Custom Resource Definition instead." ) -// Operator manages life cycle of Prometheus deployments and +// Operator manages the life cycle of Prometheus deployments and // monitoring configurations. type Operator struct { kclient kubernetes.Interface @@ -114,6 +117,14 @@ type selectedConfigResources struct { rules operator.PrometheusRuleSelection } +func (s *selectedConfigResources) Len() int { + return len(s.sMons) + + len(s.pMons) + + len(s.bMons) + + len(s.scrapeConfigs) + + s.rules.SelectedLen() +} + // WithEndpointSlice tells that the Kubernetes API supports the Endpointslice resource. func WithEndpointSlice() ControllerOption { return func(o *Operator) { @@ -801,6 +812,7 @@ func (c *Operator) handleMonitorNamespaceUpdate(oldo, curo any) { // Sync implements the operator.Syncer interface. func (c *Operator) Sync(ctx context.Context, key string) error { + c.reconciliations.ResetStatus(key) err := c.sync(ctx, key) c.reconciliations.SetStatus(key, err) @@ -870,6 +882,10 @@ func (c *Operator) sync(ctx context.Context, key string) error { return err } + if resources.Len() == 0 { + c.reconciliations.SetReasonAndMessage(key, operator.NoSelectedResourcesReason, noSelectedResourcesMessage) + } + ruleConfigMapNames, err := c.createOrUpdateRuleConfigMaps(ctx, p, resources.rules, logger) if err != nil { return err @@ -994,29 +1010,11 @@ func (c *Operator) sync(ctx context.Context, key string) error { "existing_hash", existingStatefulSet.Annotations[operator.InputHashAnnotationKey], ) - err = k8sutil.UpdateStatefulSet(ctx, ssetClient, sset) - sErr, ok := err.(*apierrors.StatusError) - - if ok && sErr.ErrStatus.Code == 422 && sErr.ErrStatus.Reason == metav1.StatusReasonInvalid { + if err = k8sutil.ForceUpdateStatefulSet(ctx, ssetClient, sset, func(reason string) { c.metrics.StsDeleteCreateCounter().Inc() - - // Gather only reason for failed update - failMsg := make([]string, len(sErr.ErrStatus.Details.Causes)) - for i, cause := range sErr.ErrStatus.Details.Causes { - failMsg[i] = cause.Message - } - - logger.Info("recreating StatefulSet because the update operation wasn't possible", "reason", strings.Join(failMsg, ", ")) - - propagationPolicy := metav1.DeletePropagationForeground - if err := ssetClient.Delete(ctx, sset.GetName(), metav1.DeleteOptions{PropagationPolicy: &propagationPolicy}); err != nil { - return fmt.Errorf("failed to delete StatefulSet to avoid forbidden action: %w", err) - } - continue - } - - if err != nil { - return fmt.Errorf("updating StatefulSet failed: %w", err) + logger.Info("recreating StatefulSet because the update operation wasn't possible", "reason", reason) + }); err != nil { + return err } } @@ -1207,16 +1205,6 @@ func (c *Operator) UpdateStatus(ctx context.Context, key string) error { return fmt.Errorf("failed to get prometheus status: %w", err) } - if c.unmanagedPrometheusConfiguration(p) { - for i, condition := range pStatus.Conditions { - if condition.Type == monitoringv1.Reconciled && condition.Status == monitoringv1.ConditionTrue { - condition.Reason = unmanagedConfigurationReason - condition.Message = unmanagedConfigurationMessage - pStatus.Conditions[i] = condition - } - } - } - p.Status = *pStatus selectorLabels := makeSelectorLabels(p.Name) selector, err := metav1.LabelSelectorAsSelector(&metav1.LabelSelector{MatchLabels: selectorLabels}) @@ -1375,6 +1363,8 @@ func (c *Operator) createOrUpdateConfigurationSecret(ctx context.Context, logger // wants to manage configuration themselves. Let's create an empty Secret // if it doesn't exist. if c.unmanagedPrometheusConfiguration(p) { + c.reconciliations.SetReasonAndMessage(operator.KeyForObject(p), unmanagedConfigurationReason, unmanagedConfigurationMessage) + s, err := prompkg.MakeConfigurationSecret(p, c.config, nil) if err != nil { return fmt.Errorf("failed to generate empty configuration secret: %w", err) @@ -1544,7 +1534,7 @@ func validateAlertmanagerEndpoints(p *monitoringv1.Prometheus, am monitoringv1.A return fmt.Errorf("%s can't be set at the same time, at most one of them must be defined", strings.Join(nonNilFields, " and ")) } - lcv, err := prompkg.NewLabelConfigValidator(p) + lcv, err := validation.NewLabelConfigValidator(p) if err != nil { return err } diff --git a/pkg/prometheus/server/statefulset.go b/pkg/prometheus/server/statefulset.go index 983f4bdb555..b96fcc27202 100644 --- a/pkg/prometheus/server/statefulset.go +++ b/pkg/prometheus/server/statefulset.go @@ -325,16 +325,18 @@ func makeStatefulSetSpec( return nil, fmt.Errorf("failed to merge containers spec: %w", err) } + // By default, podManagementPolicy is set to Parallel to mitigate rollout + // issues in Kubernetes (see https://github.com/kubernetes/kubernetes/issues/60164). + // This is also mentioned as one of limitations of StatefulSets: + // https://kubernetes.io/docs/concepts/workloads/controllers/statefulset/#limitations + podManagementPolicy := ptr.Deref(cpf.PodManagementPolicy, monitoringv1.ParallelPodManagement) + spec := appsv1.StatefulSetSpec{ - ServiceName: ptr.Deref(cpf.ServiceName, governingServiceName), - Replicas: cpf.Replicas, - // PodManagementPolicy is set to Parallel to mitigate issues in kubernetes: https://github.com/kubernetes/kubernetes/issues/60164 - // This is also mentioned as one of limitations of StatefulSets: https://kubernetes.io/docs/concepts/workloads/controllers/statefulset/#limitations - PodManagementPolicy: appsv1.ParallelPodManagement, - UpdateStrategy: appsv1.StatefulSetUpdateStrategy{ - Type: appsv1.RollingUpdateStatefulSetStrategyType, - }, - MinReadySeconds: ptr.Deref(p.Spec.MinReadySeconds, 0), + ServiceName: ptr.Deref(cpf.ServiceName, governingServiceName), + Replicas: cpf.Replicas, + PodManagementPolicy: appsv1.PodManagementPolicyType(podManagementPolicy), + UpdateStrategy: operator.UpdateStrategyForStatefulSet(cpf.UpdateStrategy), + MinReadySeconds: ptr.Deref(p.Spec.MinReadySeconds, 0), Selector: &metav1.LabelSelector{ MatchLabels: finalSelectorLabels, }, diff --git a/pkg/prometheus/server/statefulset_test.go b/pkg/prometheus/server/statefulset_test.go index d441be9874d..12550f3b7e2 100644 --- a/pkg/prometheus/server/statefulset_test.go +++ b/pkg/prometheus/server/statefulset_test.go @@ -2480,7 +2480,7 @@ func TestPrometheusAdditionalBinaryArgsDuplicate(t *testing.T) { } func TestPrometheusAdditionalNoPrefixArgsDuplicate(t *testing.T) { - expectedErrorMsg := "can't set arguments which are already managed by the operator: no-storage.tsdb.wal-compression" + expectedErrorMsg := "can't set arguments which are already managed by the operator: storage.tsdb.wal-compression" walCompression := new(bool) *walCompression = true @@ -3188,3 +3188,93 @@ func TestStatefulSetenableServiceLinks(t *testing.T) { } } } + +func TestStatefulPodManagementPolicy(t *testing.T) { + for _, tc := range []struct { + podManagementPolicy *monitoringv1.PodManagementPolicyType + exp appsv1.PodManagementPolicyType + }{ + { + podManagementPolicy: nil, + exp: appsv1.ParallelPodManagement, + }, + { + podManagementPolicy: ptr.To(monitoringv1.ParallelPodManagement), + exp: appsv1.ParallelPodManagement, + }, + { + podManagementPolicy: ptr.To(monitoringv1.OrderedReadyPodManagement), + exp: appsv1.OrderedReadyPodManagement, + }, + } { + t.Run("", func(t *testing.T) { + sset, err := makeStatefulSetFromPrometheus(monitoringv1.Prometheus{ + Spec: monitoringv1.PrometheusSpec{ + CommonPrometheusFields: monitoringv1.CommonPrometheusFields{ + PodManagementPolicy: tc.podManagementPolicy, + }, + }, + }) + + require.NoError(t, err) + require.Equal(t, tc.exp, sset.Spec.PodManagementPolicy) + }) + } +} + +func TestStatefulSetUpdateStrategy(t *testing.T) { + for _, tc := range []struct { + updateStrategy *monitoringv1.StatefulSetUpdateStrategy + exp appsv1.StatefulSetUpdateStrategy + }{ + { + updateStrategy: nil, + exp: appsv1.StatefulSetUpdateStrategy{ + Type: appsv1.RollingUpdateStatefulSetStrategyType, + }, + }, + { + updateStrategy: &monitoringv1.StatefulSetUpdateStrategy{ + Type: monitoringv1.RollingUpdateStatefulSetStrategyType, + }, + exp: appsv1.StatefulSetUpdateStrategy{ + Type: appsv1.RollingUpdateStatefulSetStrategyType, + }, + }, + { + updateStrategy: &monitoringv1.StatefulSetUpdateStrategy{ + Type: monitoringv1.RollingUpdateStatefulSetStrategyType, + RollingUpdate: &monitoringv1.RollingUpdateStatefulSetStrategy{ + MaxUnavailable: ptr.To(intstr.FromInt(1)), + }, + }, + exp: appsv1.StatefulSetUpdateStrategy{ + Type: appsv1.RollingUpdateStatefulSetStrategyType, + RollingUpdate: &appsv1.RollingUpdateStatefulSetStrategy{ + MaxUnavailable: ptr.To(intstr.FromInt(1)), + }, + }, + }, + { + updateStrategy: &monitoringv1.StatefulSetUpdateStrategy{ + Type: monitoringv1.OnDeleteStatefulSetStrategyType, + }, + exp: appsv1.StatefulSetUpdateStrategy{ + Type: appsv1.OnDeleteStatefulSetStrategyType, + }, + }, + } { + t.Run("", func(t *testing.T) { + sset, err := makeStatefulSetFromPrometheus(monitoringv1.Prometheus{ + Spec: monitoringv1.PrometheusSpec{ + CommonPrometheusFields: monitoringv1.CommonPrometheusFields{ + UpdateStrategy: tc.updateStrategy, + }, + }, + }) + + require.NoError(t, err) + require.Equal(t, tc.exp, sset.Spec.UpdateStrategy) + }) + } +} diff --git a/pkg/prometheus/testdata/NativeHistogramConfigMissScrapeNativeHistograms.golden b/pkg/prometheus/testdata/NativeHistogramConfigMissScrapeNativeHistograms.golden new file mode 100644 index 00000000000..a72d404c5e4 --- /dev/null +++ b/pkg/prometheus/testdata/NativeHistogramConfigMissScrapeNativeHistograms.golden @@ -0,0 +1,80 @@ +global: + scrape_interval: 30s + external_labels: + prometheus: default/test + prometheus_replica: $(POD_NAME) + evaluation_interval: 30s +scrape_configs: +- job_name: serviceMonitor/default/testservicemonitor1/0 + honor_labels: false + kubernetes_sd_configs: + - role: endpoints + namespaces: + names: + - default + scrape_interval: 30s + relabel_configs: + - source_labels: + - job + target_label: __tmp_prometheus_job_name + - action: keep + source_labels: + - __meta_kubernetes_endpoint_port_name + regex: web + - source_labels: + - __meta_kubernetes_endpoint_address_target_kind + - __meta_kubernetes_endpoint_address_target_name + separator: ; + regex: Node;(.*) + replacement: ${1} + target_label: node + - source_labels: + - __meta_kubernetes_endpoint_address_target_kind + - __meta_kubernetes_endpoint_address_target_name + separator: ; + regex: Pod;(.*) + replacement: ${1} + target_label: pod + - source_labels: + - __meta_kubernetes_namespace + target_label: namespace + - source_labels: + - __meta_kubernetes_service_name + target_label: service + - source_labels: + - __meta_kubernetes_pod_name + target_label: pod + - source_labels: + - __meta_kubernetes_pod_container_name + target_label: container + - action: drop + source_labels: + - __meta_kubernetes_pod_phase + regex: (Failed|Succeeded) + - source_labels: + - __meta_kubernetes_service_name + target_label: job + replacement: ${1} + - target_label: endpoint + replacement: web + - source_labels: + - __address__ + - __tmp_hash + target_label: __tmp_hash + regex: (.+); + replacement: $1 + action: replace + - source_labels: + - __tmp_hash + target_label: __tmp_hash + modulus: 1 + action: hashmod + - source_labels: + - __tmp_hash + - __tmp_disable_sharding + regex: $(SHARD);|.+;.+ + action: keep + native_histogram_bucket_limit: 10 + native_histogram_min_bucket_factor: 12.124 + always_scrape_classic_histograms: true + convert_classic_histograms_to_nhcb: true diff --git a/pkg/prometheus/testdata/NativeHistogramConfigOnlyScrapeNativeHistograms.golden b/pkg/prometheus/testdata/NativeHistogramConfigOnlyScrapeNativeHistograms.golden new file mode 100644 index 00000000000..22e7d2f2312 --- /dev/null +++ b/pkg/prometheus/testdata/NativeHistogramConfigOnlyScrapeNativeHistograms.golden @@ -0,0 +1,77 @@ +global: + scrape_interval: 30s + external_labels: + prometheus: default/test + prometheus_replica: $(POD_NAME) + evaluation_interval: 30s +scrape_configs: +- job_name: serviceMonitor/default/testservicemonitor1/0 + honor_labels: false + kubernetes_sd_configs: + - role: endpoints + namespaces: + names: + - default + scrape_interval: 30s + relabel_configs: + - source_labels: + - job + target_label: __tmp_prometheus_job_name + - action: keep + source_labels: + - __meta_kubernetes_endpoint_port_name + regex: web + - source_labels: + - __meta_kubernetes_endpoint_address_target_kind + - __meta_kubernetes_endpoint_address_target_name + separator: ; + regex: Node;(.*) + replacement: ${1} + target_label: node + - source_labels: + - __meta_kubernetes_endpoint_address_target_kind + - __meta_kubernetes_endpoint_address_target_name + separator: ; + regex: Pod;(.*) + replacement: ${1} + target_label: pod + - source_labels: + - __meta_kubernetes_namespace + target_label: namespace + - source_labels: + - __meta_kubernetes_service_name + target_label: service + - source_labels: + - __meta_kubernetes_pod_name + target_label: pod + - source_labels: + - __meta_kubernetes_pod_container_name + target_label: container + - action: drop + source_labels: + - __meta_kubernetes_pod_phase + regex: (Failed|Succeeded) + - source_labels: + - __meta_kubernetes_service_name + target_label: job + replacement: ${1} + - target_label: endpoint + replacement: web + - source_labels: + - __address__ + - __tmp_hash + target_label: __tmp_hash + regex: (.+); + replacement: $1 + action: replace + - source_labels: + - __tmp_hash + target_label: __tmp_hash + modulus: 1 + action: hashmod + - source_labels: + - __tmp_hash + - __tmp_disable_sharding + regex: $(SHARD);|.+;.+ + action: keep + scrape_native_histograms: true diff --git a/pkg/prometheus/testdata/NativeHistogramConfigWithScrapeNativeHistograms.golden b/pkg/prometheus/testdata/NativeHistogramConfigWithScrapeNativeHistograms.golden new file mode 100644 index 00000000000..58ddd84b1bb --- /dev/null +++ b/pkg/prometheus/testdata/NativeHistogramConfigWithScrapeNativeHistograms.golden @@ -0,0 +1,81 @@ +global: + scrape_interval: 30s + external_labels: + prometheus: default/test + prometheus_replica: $(POD_NAME) + evaluation_interval: 30s +scrape_configs: +- job_name: serviceMonitor/default/testservicemonitor1/0 + honor_labels: false + kubernetes_sd_configs: + - role: endpoints + namespaces: + names: + - default + scrape_interval: 30s + relabel_configs: + - source_labels: + - job + target_label: __tmp_prometheus_job_name + - action: keep + source_labels: + - __meta_kubernetes_endpoint_port_name + regex: web + - source_labels: + - __meta_kubernetes_endpoint_address_target_kind + - __meta_kubernetes_endpoint_address_target_name + separator: ; + regex: Node;(.*) + replacement: ${1} + target_label: node + - source_labels: + - __meta_kubernetes_endpoint_address_target_kind + - __meta_kubernetes_endpoint_address_target_name + separator: ; + regex: Pod;(.*) + replacement: ${1} + target_label: pod + - source_labels: + - __meta_kubernetes_namespace + target_label: namespace + - source_labels: + - __meta_kubernetes_service_name + target_label: service + - source_labels: + - __meta_kubernetes_pod_name + target_label: pod + - source_labels: + - __meta_kubernetes_pod_container_name + target_label: container + - action: drop + source_labels: + - __meta_kubernetes_pod_phase + regex: (Failed|Succeeded) + - source_labels: + - __meta_kubernetes_service_name + target_label: job + replacement: ${1} + - target_label: endpoint + replacement: web + - source_labels: + - __address__ + - __tmp_hash + target_label: __tmp_hash + regex: (.+); + replacement: $1 + action: replace + - source_labels: + - __tmp_hash + target_label: __tmp_hash + modulus: 1 + action: hashmod + - source_labels: + - __tmp_hash + - __tmp_disable_sharding + regex: $(SHARD);|.+;.+ + action: keep + scrape_native_histograms: true + native_histogram_bucket_limit: 10 + native_histogram_min_bucket_factor: 12.124 + always_scrape_classic_histograms: true + convert_classic_histograms_to_nhcb: true diff --git a/pkg/prometheus/testdata/RemoteWriteConfigAzureADWorkloadIdentity_v3.6.0.golden b/pkg/prometheus/testdata/RemoteWriteConfigAzureADWorkloadIdentity_v3.6.0.golden new file mode 100644 index 00000000000..e3b4de0042a --- /dev/null +++ b/pkg/prometheus/testdata/RemoteWriteConfigAzureADWorkloadIdentity_v3.6.0.golden @@ -0,0 +1,11 @@ +global: + scrape_interval: 30s + external_labels: + prometheus: default/test + prometheus_replica: $(POD_NAME) + evaluation_interval: 30s +scrape_configs: [] +remote_write: +- url: http://example.com + azuread: + cloud: AzureGovernment diff --git a/pkg/prometheus/testdata/RemoteWriteConfigAzureADWorkloadIdentity_v3.7.0.golden b/pkg/prometheus/testdata/RemoteWriteConfigAzureADWorkloadIdentity_v3.7.0.golden new file mode 100644 index 00000000000..9c240f72418 --- /dev/null +++ b/pkg/prometheus/testdata/RemoteWriteConfigAzureADWorkloadIdentity_v3.7.0.golden @@ -0,0 +1,14 @@ +global: + scrape_interval: 30s + external_labels: + prometheus: default/test + prometheus_replica: $(POD_NAME) + evaluation_interval: 30s +scrape_configs: [] +remote_write: +- url: http://example.com + azuread: + workload_identity: + client_id: 00000000-a12b-3cd4-e56f-000000000000 + tenant_id: 11111111-a12b-3cd4-e56f-000000000000 + cloud: AzureGovernment diff --git a/pkg/prometheus/testdata/RemoteWriteConfig_AzureADScope_v3.8.0.golden b/pkg/prometheus/testdata/RemoteWriteConfig_AzureADScope_v3.8.0.golden new file mode 100644 index 00000000000..b37d4a055c4 --- /dev/null +++ b/pkg/prometheus/testdata/RemoteWriteConfig_AzureADScope_v3.8.0.golden @@ -0,0 +1,13 @@ +global: + scrape_interval: 30s + external_labels: + prometheus: default/test + prometheus_replica: $(POD_NAME) + evaluation_interval: 30s +scrape_configs: [] +remote_write: +- url: http://example.com + azuread: + managed_identity: + client_id: 00000000-a12b-3cd4-e56f-000000000000 + cloud: AzurePublic diff --git a/pkg/prometheus/testdata/RemoteWriteConfig_AzureADScope_v3.9.0.golden b/pkg/prometheus/testdata/RemoteWriteConfig_AzureADScope_v3.9.0.golden new file mode 100644 index 00000000000..753dc3ec65e --- /dev/null +++ b/pkg/prometheus/testdata/RemoteWriteConfig_AzureADScope_v3.9.0.golden @@ -0,0 +1,14 @@ +global: + scrape_interval: 30s + external_labels: + prometheus: default/test + prometheus_replica: $(POD_NAME) + evaluation_interval: 30s +scrape_configs: [] +remote_write: +- url: http://example.com + azuread: + managed_identity: + client_id: 00000000-a12b-3cd4-e56f-000000000000 + cloud: AzurePublic + scope: https://custom.monitor.azure.com/.default diff --git a/pkg/prometheus/testdata/ScrapeNativeHistogramsFalseProperPromVersion.golden b/pkg/prometheus/testdata/ScrapeNativeHistogramsFalseProperPromVersion.golden new file mode 100644 index 00000000000..369621e54f9 --- /dev/null +++ b/pkg/prometheus/testdata/ScrapeNativeHistogramsFalseProperPromVersion.golden @@ -0,0 +1,8 @@ +global: + scrape_interval: 30s + external_labels: + prometheus: default/test + prometheus_replica: $(POD_NAME) + scrape_native_histograms: false + evaluation_interval: 30s +scrape_configs: [] diff --git a/pkg/prometheus/testdata/ScrapeNativeHistogramsTrueProperPromVersion.golden b/pkg/prometheus/testdata/ScrapeNativeHistogramsTrueProperPromVersion.golden new file mode 100644 index 00000000000..1d3d57001ec --- /dev/null +++ b/pkg/prometheus/testdata/ScrapeNativeHistogramsTrueProperPromVersion.golden @@ -0,0 +1,8 @@ +global: + scrape_interval: 30s + external_labels: + prometheus: default/test + prometheus_replica: $(POD_NAME) + scrape_native_histograms: true + evaluation_interval: 30s +scrape_configs: [] diff --git a/pkg/prometheus/testdata/ScrapeNativeHistogramsTrueWrongPromVersion.golden b/pkg/prometheus/testdata/ScrapeNativeHistogramsTrueWrongPromVersion.golden new file mode 100644 index 00000000000..609303fe82c --- /dev/null +++ b/pkg/prometheus/testdata/ScrapeNativeHistogramsTrueWrongPromVersion.golden @@ -0,0 +1,7 @@ +global: + scrape_interval: 30s + external_labels: + prometheus: default/test + prometheus_replica: $(POD_NAME) + evaluation_interval: 30s +scrape_configs: [] diff --git a/pkg/prometheus/validation/validator.go b/pkg/prometheus/validation/validator.go new file mode 100644 index 00000000000..c4ad5e27bfc --- /dev/null +++ b/pkg/prometheus/validation/validator.go @@ -0,0 +1,150 @@ +// Copyright 2025 The prometheus-operator Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package validation + +import ( + "fmt" + "strings" + + "github.com/blang/semver/v4" + "github.com/prometheus/prometheus/model/relabel" + + monitoringv1 "github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1" + "github.com/prometheus-operator/prometheus-operator/pkg/operator" +) + +// LabelConfigValidator validates relabel configurations. +type LabelConfigValidator struct { + v semver.Version +} + +// NewLabelConfigValidator creates a new LabelConfigValidator. +func NewLabelConfigValidator(p monitoringv1.PrometheusInterface) (*LabelConfigValidator, error) { + promVersion := operator.StringValOrDefault(p.GetCommonPrometheusFields().Version, operator.DefaultPrometheusVersion) + v, err := semver.ParseTolerant(promVersion) + if err != nil { + return nil, fmt.Errorf("failed to parse Prometheus version: %w", err) + } + + return NewLabelConfigValidatorFromVersion(v) +} + +// NewLabelConfigValidatorFromVersion creates a new LabelConfigValidator from a semver.Version. +func NewLabelConfigValidatorFromVersion(v semver.Version) (*LabelConfigValidator, error) { + return &LabelConfigValidator{ + v: v, + }, nil +} + +// Validate validates a list of relabel configurations. +func (lcv *LabelConfigValidator) Validate(rcs []monitoringv1.RelabelConfig) error { + for i, rc := range rcs { + if err := lcv.ValidateRelabelConfig(rc); err != nil { + return fmt.Errorf("[%d]: %w", i, err) + } + } + + return nil +} + +// From https://github.com/prometheus/prometheus/blob/747c5ee2b19a9e6a51acfafae9fa2c77e224803d/model/relabel/relabel.go#L378-L380 +func varInRegexTemplate(template string) bool { + return strings.Contains(template, "$") +} + +func (lcv *LabelConfigValidator) isValidLabelName(labelName string) bool { + validationScheme := operator.ValidationSchemeForPrometheus(lcv.v) + return validationScheme.IsValidLabelName(labelName) +} + +// ValidateRelabelConfig validates a single relabel configuration. +func (lcv *LabelConfigValidator) ValidateRelabelConfig(rc monitoringv1.RelabelConfig) error { + minimumVersionCaseActions := lcv.v.GTE(semver.MustParse("2.36.0")) + minimumVersionEqualActions := lcv.v.GTE(semver.MustParse("2.41.0")) + if rc.Action == "" { + rc.Action = string(relabel.Replace) + } + action := strings.ToLower(rc.Action) + + if (action == string(relabel.Lowercase) || action == string(relabel.Uppercase)) && !minimumVersionCaseActions { + return fmt.Errorf("%s relabel action is only supported from Prometheus version 2.36.0", rc.Action) + } + + if (action == string(relabel.KeepEqual) || action == string(relabel.DropEqual)) && !minimumVersionEqualActions { + return fmt.Errorf("%s relabel action is only supported from Prometheus version 2.41.0", rc.Action) + } + + if _, err := relabel.NewRegexp(rc.Regex); err != nil { + return fmt.Errorf("invalid regex %s for relabel configuration: %w", rc.Regex, err) + } + + if rc.Modulus == 0 && action == string(relabel.HashMod) { + return fmt.Errorf("relabel configuration for hashmod requires non-zero modulus") + } + + if (action == string(relabel.Replace) || action == string(relabel.HashMod) || action == string(relabel.Lowercase) || action == string(relabel.Uppercase) || action == string(relabel.KeepEqual) || action == string(relabel.DropEqual)) && rc.TargetLabel == "" { + return fmt.Errorf("relabel configuration for %s action needs targetLabel value", rc.Action) + } + + if (action == string(relabel.Replace)) && !varInRegexTemplate(rc.TargetLabel) && !lcv.isValidLabelName(rc.TargetLabel) { + return fmt.Errorf("%q is invalid 'target_label' for %s action", rc.TargetLabel, rc.Action) + } + + if (action == string(relabel.Replace)) && varInRegexTemplate(rc.TargetLabel) && !lcv.isValidLabelName(rc.TargetLabel) { + return fmt.Errorf("%q is invalid 'target_label' for %s action", rc.TargetLabel, rc.Action) + } + + if (action == string(relabel.Lowercase) || action == string(relabel.Uppercase) || action == string(relabel.KeepEqual) || action == string(relabel.DropEqual)) && !lcv.isValidLabelName(rc.TargetLabel) { + return fmt.Errorf("%q is invalid 'target_label' for %s action", rc.TargetLabel, rc.Action) + } + + if (action == string(relabel.Lowercase) || action == string(relabel.Uppercase) || action == string(relabel.KeepEqual) || action == string(relabel.DropEqual)) && (rc.Replacement != nil && *rc.Replacement != relabel.DefaultRelabelConfig.Replacement) { + return fmt.Errorf("'replacement' can not be set for %s action", rc.Action) + } + + if action == string(relabel.LabelMap) && (rc.Replacement != nil) && !lcv.isValidLabelName(*rc.Replacement) { + return fmt.Errorf("%q is invalid 'replacement' for %s action", *rc.Replacement, rc.Action) + } + + if action == string(relabel.HashMod) && !lcv.isValidLabelName(rc.TargetLabel) { + return fmt.Errorf("%q is invalid 'target_label' for %s action", rc.TargetLabel, rc.Action) + } + + if action == string(relabel.KeepEqual) || action == string(relabel.DropEqual) { + if (rc.Regex != "" && rc.Regex != relabel.DefaultRelabelConfig.Regex.String()) || + (rc.Modulus != uint64(0) && + rc.Modulus != relabel.DefaultRelabelConfig.Modulus) || + (rc.Separator != nil && + *rc.Separator != relabel.DefaultRelabelConfig.Separator) || + (rc.Replacement != nil && *rc.Replacement != relabel.DefaultRelabelConfig.Replacement) { + return fmt.Errorf("%s action requires only 'source_labels' and `target_label`, and no other fields", rc.Action) + } + } + + if action == string(relabel.LabelDrop) || action == string(relabel.LabelKeep) { + if len(rc.SourceLabels) != 0 || + (rc.TargetLabel != "" && + rc.TargetLabel != relabel.DefaultRelabelConfig.TargetLabel) || + (rc.Modulus != uint64(0) && + rc.Modulus != relabel.DefaultRelabelConfig.Modulus) || + (rc.Separator != nil && + *rc.Separator != relabel.DefaultRelabelConfig.Separator) || + (rc.Replacement != nil && + *rc.Replacement != relabel.DefaultRelabelConfig.Replacement) { + return fmt.Errorf("%s action requires only 'regex', and no other fields", rc.Action) + } + } + return nil +} diff --git a/pkg/prometheus/validation/validator_test.go b/pkg/prometheus/validation/validator_test.go new file mode 100644 index 00000000000..84c71dad148 --- /dev/null +++ b/pkg/prometheus/validation/validator_test.go @@ -0,0 +1,401 @@ +// Copyright 2025 The prometheus-operator Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package validation + +import ( + "testing" + + "github.com/prometheus/prometheus/model/relabel" + "github.com/stretchr/testify/require" + "k8s.io/utils/ptr" + + monitoringv1 "github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1" +) + +func TestValidateRelabelConfig(t *testing.T) { + defaultRegexp, err := relabel.DefaultRelabelConfig.Regex.MarshalYAML() + if err != nil { + t.Errorf("Could not marshal relabel.DefaultRelabelConfig.Regex: %v", err) + } + defaultRegex, ok := defaultRegexp.(string) + if !ok { + t.Errorf("Could not assert marshaled defaultRegexp as string: %v", defaultRegexp) + } + + defaultSourceLabels := []monitoringv1.LabelName{} + for _, label := range relabel.DefaultRelabelConfig.SourceLabels { + defaultSourceLabels = append(defaultSourceLabels, monitoringv1.LabelName(label)) + } + + defaultPrometheusSpec := monitoringv1.Prometheus{ + Spec: monitoringv1.PrometheusSpec{ + CommonPrometheusFields: monitoringv1.CommonPrometheusFields{ + Version: "v2.36.0", + }, + }, + } + + for _, tc := range []struct { + scenario string + relabelConfig monitoringv1.RelabelConfig + prometheus monitoringv1.Prometheus + expectedErr bool + }{ + // Test invalid regex expression + { + scenario: "Invalid regex", + relabelConfig: monitoringv1.RelabelConfig{ + Regex: "invalid regex)", + }, + prometheus: defaultPrometheusSpec, + expectedErr: true, + }, + // Test invalid target label + { + scenario: "invalid target label", + relabelConfig: monitoringv1.RelabelConfig{ + Action: "replace", + TargetLabel: "l\\${3}", + }, + prometheus: defaultPrometheusSpec, + expectedErr: true, + }, + // Test empty target label for action replace + { + scenario: "empty target label for replace action", + relabelConfig: monitoringv1.RelabelConfig{ + Action: "replace", + TargetLabel: "", + }, + prometheus: defaultPrometheusSpec, + expectedErr: true, + }, + // Test empty target label for action hashmod + { + scenario: "empty target label for hashmod action", + relabelConfig: monitoringv1.RelabelConfig{ + Action: "hashmod", + TargetLabel: "", + }, + prometheus: defaultPrometheusSpec, + expectedErr: true, + }, + // Test empty target label for action uppercase + { + scenario: "empty target label for uppercase action", + relabelConfig: monitoringv1.RelabelConfig{ + Action: "uppercase", + TargetLabel: "", + }, + prometheus: defaultPrometheusSpec, + expectedErr: true, + }, + // Test empty target label for action lowercase + { + scenario: "empty target label for lowercase action", + relabelConfig: monitoringv1.RelabelConfig{ + Action: "lowercase", + TargetLabel: "", + }, + prometheus: defaultPrometheusSpec, + expectedErr: true, + }, + // Test replacement set for action uppercase + { + scenario: "replacement set for uppercase action", + relabelConfig: monitoringv1.RelabelConfig{ + Action: "uppercase", + Replacement: ptr.To("some-replace-value"), + }, + prometheus: defaultPrometheusSpec, + expectedErr: true, + }, + // Test invalid hashmod relabel config + { + scenario: "invalid hashmod config", + relabelConfig: monitoringv1.RelabelConfig{ + SourceLabels: []monitoringv1.LabelName{"instance"}, + Action: "hashmod", + Modulus: 0, + TargetLabel: "__tmp_hashmod", + }, + prometheus: defaultPrometheusSpec, + expectedErr: true, + }, + // Test invalid labelmap relabel config + { + scenario: "invalid labelmap config", + relabelConfig: monitoringv1.RelabelConfig{ + Action: "labelmap", + Regex: "__meta_kubernetes_service_label_(.+)", + Replacement: ptr.To("some-name-value"), + }, + prometheus: defaultPrometheusSpec, + expectedErr: true, + }, + // Test valid labelmap relabel config when replacement not specified + { + scenario: "valid labelmap config", + relabelConfig: monitoringv1.RelabelConfig{ + Action: "labelmap", + Regex: "__meta_kubernetes_service_label_(.+)", + }, + prometheus: defaultPrometheusSpec, + }, + // Test valid labelmap relabel config with replacement specified + { + scenario: "valid labelmap config with replacement", + relabelConfig: monitoringv1.RelabelConfig{ + Action: "labelmap", + Regex: "__meta_kubernetes_service_label_(.+)", + Replacement: ptr.To("abc"), + }, + prometheus: defaultPrometheusSpec, + }, + // Test invalid labelkeep relabel config + { + scenario: "invalid labelkeep config", + relabelConfig: monitoringv1.RelabelConfig{ + SourceLabels: []monitoringv1.LabelName{"instance"}, + Action: "labelkeep", + TargetLabel: "__tmp_labelkeep", + }, + prometheus: defaultPrometheusSpec, + expectedErr: true, + }, + // Test valid labelkeep relabel config + { + scenario: "valid labelkeep config", + relabelConfig: monitoringv1.RelabelConfig{ + Action: "labelkeep", + }, + prometheus: defaultPrometheusSpec, + }, + // Test valid labeldrop relabel config + { + scenario: "valid labeldrop config", + relabelConfig: monitoringv1.RelabelConfig{ + Action: "labeldrop", + Regex: "replica", + }, + prometheus: defaultPrometheusSpec, + }, + // Test valid replace config with empty replacement + { + scenario: "valid replace config with empty replacement", + relabelConfig: monitoringv1.RelabelConfig{ + Action: "replace", + Replacement: ptr.To(""), + TargetLabel: "abc", + }, + prometheus: defaultPrometheusSpec, + }, + // Test valid labeldrop relabel config with default value + { + scenario: "valid labeldrop config with default values", + relabelConfig: monitoringv1.RelabelConfig{ + Action: "labeldrop", + Regex: defaultRegex, + }, + prometheus: defaultPrometheusSpec, + }, + // Test valid hashmod relabel config + { + scenario: "valid hashmod config", + relabelConfig: monitoringv1.RelabelConfig{ + SourceLabels: defaultSourceLabels, + Action: "hashmod", + Modulus: 1, + TargetLabel: "abc", + }, + prometheus: defaultPrometheusSpec, + }, + // Test valid replace relabel config + { + scenario: "valid replace config", + relabelConfig: monitoringv1.RelabelConfig{ + Action: "replace", + TargetLabel: "abc", + }, + prometheus: defaultPrometheusSpec, + }, + // Test valid uppercase relabel config + { + scenario: "valid uppercase config", + relabelConfig: monitoringv1.RelabelConfig{ + Action: "uppercase", + TargetLabel: "ABC", + }, + prometheus: defaultPrometheusSpec, + }, + // Test valid lowercase relabel config + { + scenario: "valid lowercase config", + relabelConfig: monitoringv1.RelabelConfig{ + Action: "lowercase", + TargetLabel: "abc", + }, + prometheus: defaultPrometheusSpec, + }, + // Test uppercase relabel config with lower prometheus version + { + scenario: "uppercase config with lower prometheus version", + relabelConfig: monitoringv1.RelabelConfig{ + Action: "uppercase", + TargetLabel: "abc", + }, + prometheus: monitoringv1.Prometheus{ + Spec: monitoringv1.PrometheusSpec{ + CommonPrometheusFields: monitoringv1.CommonPrometheusFields{ + Version: "v2.30.0", + }, + }, + }, + expectedErr: true, + }, + // Test lowercase relabel config with lower prometheus version + { + scenario: "lowercase config with lower prometheus version", + relabelConfig: monitoringv1.RelabelConfig{ + Action: "lowercase", + TargetLabel: "abc", + }, + prometheus: monitoringv1.Prometheus{ + Spec: monitoringv1.PrometheusSpec{ + CommonPrometheusFields: monitoringv1.CommonPrometheusFields{ + Version: "v2.30.0", + }, + }, + }, + expectedErr: true, + }, + // Test keepequal relabel config with lower prometheus version + { + scenario: "keepequal config with lower prometheus version", + relabelConfig: monitoringv1.RelabelConfig{ + Action: "keepequal", + TargetLabel: "abc", + }, + prometheus: monitoringv1.Prometheus{ + Spec: monitoringv1.PrometheusSpec{ + CommonPrometheusFields: monitoringv1.CommonPrometheusFields{ + Version: "v2.30.0", + }, + }, + }, + expectedErr: true, + }, + // Test dropequal relabel config with lower prometheus version + { + scenario: "dropequal config with lower prometheus version", + relabelConfig: monitoringv1.RelabelConfig{ + Action: "dropequal", + TargetLabel: "abc", + }, + prometheus: monitoringv1.Prometheus{ + Spec: monitoringv1.PrometheusSpec{ + CommonPrometheusFields: monitoringv1.CommonPrometheusFields{ + Version: "v2.30.0", + }, + }, + }, + expectedErr: true, + }, + // Test valid keepequal relabel config + { + scenario: "valid keepequal config", + relabelConfig: monitoringv1.RelabelConfig{ + SourceLabels: []monitoringv1.LabelName{"__tmp_port"}, + TargetLabel: "__port1", + Action: "keepequal", + }, + prometheus: monitoringv1.Prometheus{ + Spec: monitoringv1.PrometheusSpec{ + CommonPrometheusFields: monitoringv1.CommonPrometheusFields{ + Version: "v2.41.0", + }, + }, + }, + }, + // Test valid dropequal relabel config + { + scenario: "valid dropequal config", + relabelConfig: monitoringv1.RelabelConfig{ + SourceLabels: []monitoringv1.LabelName{"__tmp_port"}, + TargetLabel: "__port1", + Action: "dropequal", + }, + prometheus: monitoringv1.Prometheus{ + Spec: monitoringv1.PrometheusSpec{ + CommonPrometheusFields: monitoringv1.CommonPrometheusFields{ + Version: "v2.41.0", + }, + }, + }, + }, + // Test valid keepequal with non default values for other fields + { + scenario: "valid keepequal config with non default values for other fields", + relabelConfig: monitoringv1.RelabelConfig{ + SourceLabels: []monitoringv1.LabelName{"__tmp_port"}, + TargetLabel: "__port1", + Separator: ptr.To("^"), + Regex: "validregex", + Replacement: ptr.To("replacevalue"), + Action: "keepequal", + }, + prometheus: monitoringv1.Prometheus{ + Spec: monitoringv1.PrometheusSpec{ + CommonPrometheusFields: monitoringv1.CommonPrometheusFields{ + Version: "v2.41.0", + }, + }, + }, + expectedErr: true, + }, + // Test valid keepequal with default values for other fields + { + scenario: "valid keepequal config with default values for other fields", + relabelConfig: monitoringv1.RelabelConfig{ + SourceLabels: []monitoringv1.LabelName{"__tmp_port"}, + TargetLabel: "__port1", + Separator: ptr.To(relabel.DefaultRelabelConfig.Separator), + Regex: relabel.DefaultRelabelConfig.Regex.String(), + Modulus: relabel.DefaultRelabelConfig.Modulus, + Replacement: &relabel.DefaultRelabelConfig.Replacement, + Action: "keepequal", + }, + prometheus: monitoringv1.Prometheus{ + Spec: monitoringv1.PrometheusSpec{ + CommonPrometheusFields: monitoringv1.CommonPrometheusFields{ + Version: "v2.41.0", + }, + }, + }, + }, + } { + t.Run(tc.scenario, func(t *testing.T) { + lcv, err := NewLabelConfigValidator(&tc.prometheus) + require.NoError(t, err) + + err = lcv.ValidateRelabelConfig(tc.relabelConfig) + if tc.expectedErr { + require.Error(t, err) + return + } + require.NoError(t, err) + }) + } +} diff --git a/pkg/thanos/operator.go b/pkg/thanos/operator.go index 73586e4b13f..39bb18cce44 100644 --- a/pkg/thanos/operator.go +++ b/pkg/thanos/operator.go @@ -55,6 +55,8 @@ const ( applicationNameLabelValue = "thanos-ruler" controllerName = "thanos-controller" rwConfigFile = "remote-write.yaml" + + noSelectedResourcesMessage = "No PrometheusRule have been selected." ) var minRemoteWriteVersion = semver.MustParse("0.24.0") @@ -248,17 +250,7 @@ func New(ctx context.Context, restConfig *rest.Config, c operator.Config, logger o.kclient, resyncPeriod, func(options *metav1.ListOptions) { - // TODO(simonpasquier): use a more restrictive label selector - // selecting only ThanosRuler statefulsets (e.g. - // "app.kubernetes.io/name in (thanos-ruler)"). - // - // We need to wait for a couple of releases after [1] to ensure - // that the expected labels have been propagated to the - // ThanosRuler statefulsets otherwise the informer won't select - // any object. - // - // [1] https://github.com/prometheus-operator/prometheus-operator/pull/7786 - options.LabelSelector = operator.ManagedByOperatorLabelSelector() + options.LabelSelector = labelSelectorForStatefulSets() }, ), appsv1.SchemeGroupVersion.WithResource("statefulsets"), @@ -529,6 +521,10 @@ func (o *Operator) sync(ctx context.Context, key string) error { return err } + if selectedRules.SelectedLen() == 0 { + o.reconciliations.SetReasonAndMessage(key, operator.NoSelectedResourcesReason, noSelectedResourcesMessage) + } + ruleConfigMapNames, err := o.createOrUpdateRuleConfigMaps(ctx, tr, selectedRules, logger) if err != nil { return err @@ -611,28 +607,11 @@ func (o *Operator) sync(ctx context.Context, key string) error { logger.Debug("new hash differs from the existing value", "new", newSSetInputHash, "existing", existingStatefulSet.Annotations[operator.InputHashAnnotationKey]) ssetClient := o.kclient.AppsV1().StatefulSets(tr.Namespace) - err = k8sutil.UpdateStatefulSet(ctx, ssetClient, sset) - sErr, ok := err.(*apierrors.StatusError) - - if ok && sErr.ErrStatus.Code == 422 && sErr.ErrStatus.Reason == metav1.StatusReasonInvalid { + if err = k8sutil.ForceUpdateStatefulSet(ctx, ssetClient, sset, func(reason string) { o.metrics.StsDeleteCreateCounter().Inc() - - // Gather only reason for failed update - failMsg := make([]string, len(sErr.ErrStatus.Details.Causes)) - for i, cause := range sErr.ErrStatus.Details.Causes { - failMsg[i] = cause.Message - } - - logger.Info("recreating ThanosRuler StatefulSet because the update operation wasn't possible", "reason", strings.Join(failMsg, ", ")) - propagationPolicy := metav1.DeletePropagationForeground - if err := ssetClient.Delete(ctx, sset.GetName(), metav1.DeleteOptions{PropagationPolicy: &propagationPolicy}); err != nil { - return fmt.Errorf("failed to delete StatefulSet to avoid forbidden action: %w", err) - } - return nil - } - - if err != nil { - return fmt.Errorf("updating StatefulSet failed: %w", err) + logger.Info("recreating StatefulSet because the update operation wasn't possible", "reason", reason) + }); err != nil { + return err } return nil @@ -907,6 +886,16 @@ func makeSelectorLabels(name string) map[string]string { } } +// labelSelectorForStatefulSets returns a label selector which selects +// all ThanosRuler statefulsets. +func labelSelectorForStatefulSets() string { + return fmt.Sprintf( + "%s in (%s),%s in (%s)", + operator.ManagedByLabelKey, operator.ManagedByLabelValue, + operator.ApplicationNameLabelKey, applicationNameLabelValue, + ) +} + func (o *Operator) createOrUpdateRulerConfigSecret(ctx context.Context, store *assets.StoreBuilder, tr *monitoringv1.ThanosRuler) error { sClient := o.kclient.CoreV1().Secrets(tr.GetNamespace()) @@ -949,6 +938,18 @@ func (o *Operator) createOrUpdateRulerConfigSecret(ctx context.Context, store *a } for i, rw := range tr.Spec.RemoteWrite { + // Thanos does not support azureAD.workloadIdentity in any version + if rw.AzureAD != nil && rw.AzureAD.WorkloadIdentity != nil { + reset := resetFieldFn("none") + reset("azureAD.workloadIdentity", &rw.AzureAD.WorkloadIdentity) + } + + // Thanos does not support azureAD.scope in any version + if rw.AzureAD != nil && rw.AzureAD.Scope != nil { + reset := resetFieldFn("none") + reset("azureAD.scope", &rw.AzureAD.Scope) + } + // Thanos v0.40.0 is equivalent to Prometheus v3.5.1 which allows empty clientId values. if version.LT(semver.MustParse("0.40.0")) { if rw.AzureAD != nil && rw.AzureAD.ManagedIdentity != nil { @@ -957,7 +958,6 @@ func (o *Operator) createOrUpdateRulerConfigSecret(ctx context.Context, store *a } } } - // Thanos v0.38.0 is equivalent to Prometheus v3.1.0. if version.LT(semver.MustParse("0.38.0")) { reset := resetFieldFn("0.38.0") diff --git a/pkg/thanos/operator_test.go b/pkg/thanos/operator_test.go index 4191da106a7..8bb78352571 100644 --- a/pkg/thanos/operator_test.go +++ b/pkg/thanos/operator_test.go @@ -35,6 +35,7 @@ func TestCreateOrUpdateRulerConfigSecret(t *testing.T) { version string remoteWrite []monitoringv1.RemoteWriteSpec golden string + expectErr bool }{ { name: "empty config", @@ -81,6 +82,10 @@ func TestCreateOrUpdateRulerConfigSecret(t *testing.T) { sb := &assets.StoreBuilder{} err := o.createOrUpdateRulerConfigSecret(context.Background(), sb, tr) + if tc.expectErr { + require.Error(t, err) + return + } require.NoError(t, err) sec, err := cs.CoreV1().Secrets(tr.Namespace).Get(context.Background(), "thanos-ruler-foo-config", metav1.GetOptions{}) diff --git a/pkg/thanos/statefulset.go b/pkg/thanos/statefulset.go index 21264648729..3440a8e4eaf 100644 --- a/pkg/thanos/statefulset.go +++ b/pkg/thanos/statefulset.go @@ -478,16 +478,18 @@ func makeStatefulSetSpec(tr *monitoringv1.ThanosRuler, config Config, ruleConfig return nil, fmt.Errorf("failed to merge containers spec: %w", err) } + // By default, podManagementPolicy is set to Parallel to mitigate rollout + // issues in Kubernetes (see https://github.com/kubernetes/kubernetes/issues/60164). + // This is also mentioned as one of limitations of StatefulSets: + // https://kubernetes.io/docs/concepts/workloads/controllers/statefulset/#limitations + podManagementPolicy := ptr.Deref(tr.Spec.PodManagementPolicy, monitoringv1.ParallelPodManagement) + spec := appsv1.StatefulSetSpec{ - ServiceName: ptr.Deref(tr.Spec.ServiceName, governingServiceName), - Replicas: tr.Spec.Replicas, - MinReadySeconds: ptr.Deref(tr.Spec.MinReadySeconds, 0), - // PodManagementPolicy is set to Parallel to mitigate issues in kubernetes: https://github.com/kubernetes/kubernetes/issues/60164 - // This is also mentioned as one of limitations of StatefulSets: https://kubernetes.io/docs/concepts/workloads/controllers/statefulset/#limitations - PodManagementPolicy: appsv1.ParallelPodManagement, - UpdateStrategy: appsv1.StatefulSetUpdateStrategy{ - Type: appsv1.RollingUpdateStatefulSetStrategyType, - }, + ServiceName: ptr.Deref(tr.Spec.ServiceName, governingServiceName), + Replicas: tr.Spec.Replicas, + MinReadySeconds: ptr.Deref(tr.Spec.MinReadySeconds, 0), + PodManagementPolicy: appsv1.PodManagementPolicyType(podManagementPolicy), + UpdateStrategy: operator.UpdateStrategyForStatefulSet(tr.Spec.UpdateStrategy), Selector: &metav1.LabelSelector{ MatchLabels: finalLabels, }, diff --git a/pkg/thanos/statefulset_test.go b/pkg/thanos/statefulset_test.go index 89d898980ea..ca862c66b50 100644 --- a/pkg/thanos/statefulset_test.go +++ b/pkg/thanos/statefulset_test.go @@ -25,6 +25,7 @@ import ( appsv1 "k8s.io/api/apps/v1" v1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/util/intstr" "k8s.io/utils/ptr" monitoringv1 "github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1" @@ -1373,3 +1374,91 @@ func TestEnableFeatures(t *testing.T) { }) } } + +func TestStatefulSetPodManagementPolicy(t *testing.T) { + for _, tc := range []struct { + podManagementPolicy *monitoringv1.PodManagementPolicyType + exp appsv1.PodManagementPolicyType + }{ + { + podManagementPolicy: nil, + exp: appsv1.ParallelPodManagement, + }, + { + podManagementPolicy: ptr.To(monitoringv1.ParallelPodManagement), + exp: appsv1.ParallelPodManagement, + }, + { + podManagementPolicy: ptr.To(monitoringv1.OrderedReadyPodManagement), + exp: appsv1.OrderedReadyPodManagement, + }, + } { + t.Run("", func(t *testing.T) { + sset, err := makeStatefulSet(&monitoringv1.ThanosRuler{ + Spec: monitoringv1.ThanosRulerSpec{ + PodManagementPolicy: tc.podManagementPolicy, + QueryEndpoints: emptyQueryEndpoints, + }, + }, defaultTestConfig, nil, "", &operator.ShardedSecret{}) + + require.NoError(t, err) + require.Equal(t, tc.exp, sset.Spec.PodManagementPolicy) + }) + } +} + +func TestStatefulSetUpdateStrategy(t *testing.T) { + for _, tc := range []struct { + updateStrategy *monitoringv1.StatefulSetUpdateStrategy + exp appsv1.StatefulSetUpdateStrategy + }{ + { + updateStrategy: nil, + exp: appsv1.StatefulSetUpdateStrategy{ + Type: appsv1.RollingUpdateStatefulSetStrategyType, + }, + }, + { + updateStrategy: &monitoringv1.StatefulSetUpdateStrategy{ + Type: monitoringv1.RollingUpdateStatefulSetStrategyType, + }, + exp: appsv1.StatefulSetUpdateStrategy{ + Type: appsv1.RollingUpdateStatefulSetStrategyType, + }, + }, + { + updateStrategy: &monitoringv1.StatefulSetUpdateStrategy{ + Type: monitoringv1.RollingUpdateStatefulSetStrategyType, + RollingUpdate: &monitoringv1.RollingUpdateStatefulSetStrategy{ + MaxUnavailable: ptr.To(intstr.FromInt(1)), + }, + }, + exp: appsv1.StatefulSetUpdateStrategy{ + Type: appsv1.RollingUpdateStatefulSetStrategyType, + RollingUpdate: &appsv1.RollingUpdateStatefulSetStrategy{ + MaxUnavailable: ptr.To(intstr.FromInt(1)), + }, + }, + }, + { + updateStrategy: &monitoringv1.StatefulSetUpdateStrategy{ + Type: monitoringv1.OnDeleteStatefulSetStrategyType, + }, + exp: appsv1.StatefulSetUpdateStrategy{ + Type: appsv1.OnDeleteStatefulSetStrategyType, + }, + }, + } { + t.Run("", func(t *testing.T) { + sset, err := makeStatefulSet(&monitoringv1.ThanosRuler{ + Spec: monitoringv1.ThanosRulerSpec{ + UpdateStrategy: tc.updateStrategy, + QueryEndpoints: emptyQueryEndpoints, + }, + }, defaultTestConfig, nil, "", &operator.ShardedSecret{}) + + require.NoError(t, err) + require.Equal(t, tc.exp, sset.Spec.UpdateStrategy) + }) + } +} diff --git a/scripts/go.mod b/scripts/go.mod index 6d4a7162e80..6085d161f8c 100644 --- a/scripts/go.mod +++ b/scripts/go.mod @@ -8,7 +8,7 @@ require ( github.com/ahmetb/gen-crd-api-reference-docs v0.3.1-0.20241111191808-71fefeed8910 github.com/brancz/gojsontoyaml v0.1.0 github.com/bwplotka/mdox v0.9.1-0.20220713080221-769034ad8cfe - github.com/golangci/golangci-lint/v2 v2.7.0 + github.com/golangci/golangci-lint/v2 v2.7.2 github.com/google/go-jsonnet v0.21.0 github.com/jsonnet-bundler/jsonnet-bundler v0.6.0 github.com/yeya24/promlinter v0.3.0 @@ -221,7 +221,7 @@ require ( github.com/santhosh-tekuri/jsonschema/v6 v6.0.2 // indirect github.com/sashamelentyev/interfacebloat v1.1.0 // indirect github.com/sashamelentyev/usestdlibvars v1.29.0 // indirect - github.com/securego/gosec/v2 v2.22.10 // indirect + github.com/securego/gosec/v2 v2.22.11-0.20251204091113-daccba6b93d7 // indirect github.com/sergi/go-diff v1.3.1 // indirect github.com/sirupsen/logrus v1.9.3 // indirect github.com/sivchari/containedctx v1.0.3 // indirect @@ -229,7 +229,7 @@ require ( github.com/sourcegraph/go-diff v0.7.0 // indirect github.com/spf13/afero v1.15.0 // indirect github.com/spf13/cast v1.5.0 // indirect - github.com/spf13/cobra v1.10.1 // indirect + github.com/spf13/cobra v1.10.2 // indirect github.com/spf13/jwalterweatherman v1.1.0 // indirect github.com/spf13/pflag v1.0.10 // indirect github.com/spf13/viper v1.13.0 // indirect @@ -267,7 +267,7 @@ require ( go.uber.org/zap v1.27.0 // indirect go.yaml.in/yaml/v2 v2.4.2 // indirect go.yaml.in/yaml/v3 v3.0.4 // indirect - golang.org/x/crypto v0.44.0 // indirect + golang.org/x/crypto v0.45.0 // indirect golang.org/x/exp/typeparams v0.0.0-20251023183803-a4bb9ffd2546 // indirect golang.org/x/mod v0.30.0 // indirect golang.org/x/net v0.47.0 // indirect diff --git a/scripts/go.sum b/scripts/go.sum index ef02f1944e0..70db0c7904d 100644 --- a/scripts/go.sum +++ b/scripts/go.sum @@ -973,8 +973,8 @@ github.com/golangci/go-printf-func-name v0.1.1 h1:hIYTFJqAGp1iwoIfsNTpoq1xZAarog github.com/golangci/go-printf-func-name v0.1.1/go.mod h1:Es64MpWEZbh0UBtTAICOZiB+miW53w/K9Or/4QogJss= github.com/golangci/gofmt v0.0.0-20250106114630-d62b90e6713d h1:viFft9sS/dxoYY0aiOTsLKO2aZQAPT4nlQCsimGcSGE= github.com/golangci/gofmt v0.0.0-20250106114630-d62b90e6713d/go.mod h1:ivJ9QDg0XucIkmwhzCDsqcnxxlDStoTl89jDMIoNxKY= -github.com/golangci/golangci-lint/v2 v2.7.0 h1:jcjBA3azjzV0VEsQaBaH/27WHeEQbnKzbWUhXQs+4DU= -github.com/golangci/golangci-lint/v2 v2.7.0/go.mod h1:ekW32uOX47mpRlfPlSscuJPprm6pCEYIDagudfLrx34= +github.com/golangci/golangci-lint/v2 v2.7.2 h1:AhBC+YeEueec4AGlIbvPym5C70Thx0JykIqXbdIXWx0= +github.com/golangci/golangci-lint/v2 v2.7.2/go.mod h1:pDijleoBu7e8sejMqyZ3L5n6geqe+cVvOAz2QImqqVc= github.com/golangci/golines v0.0.0-20250217134842-442fd0091d95 h1:AkK+w9FZBXlU/xUmBtSJN1+tAI4FIvy5WtnUnY8e4p8= github.com/golangci/golines v0.0.0-20250217134842-442fd0091d95/go.mod h1:k9mmcyWKSTMcPPvQUCfRWWQ9VHJ1U9Dc0R7kaXAgtnQ= github.com/golangci/misspell v0.7.0 h1:4GOHr/T1lTW0hhR4tgaaV1WS/lJ+ncvYCoFKmqJsj0c= @@ -1416,8 +1416,8 @@ github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+W github.com/onsi/ginkgo v1.7.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= github.com/onsi/ginkgo v1.16.5 h1:8xi0RTUf59SOSfEtZMvwTvXYMzG4gV23XVHOZiXNtnE= github.com/onsi/ginkgo v1.16.5/go.mod h1:+E8gABHa3K6zRBolWtd+ROzc/U5bkGt0FwiG042wbpU= -github.com/onsi/ginkgo/v2 v2.26.0 h1:1J4Wut1IlYZNEAWIV3ALrT9NfiaGW2cDCJQSFQMs/gE= -github.com/onsi/ginkgo/v2 v2.26.0/go.mod h1:qhEywmzWTBUY88kfO0BRvX4py7scov9yR+Az2oavUzw= +github.com/onsi/ginkgo/v2 v2.27.2 h1:LzwLj0b89qtIy6SSASkzlNvX6WktqurSHwkk2ipF/Ns= +github.com/onsi/ginkgo/v2 v2.27.2/go.mod h1:ArE1D/XhNXBXCBkKOLkbsb2c81dQHCRcF5zwn/ykDRo= github.com/onsi/gomega v1.4.3/go.mod h1:ex+gbHU/CVuBBDIJjb2X0qEXbFg53c61hWP/1CpauHY= github.com/onsi/gomega v1.38.2 h1:eZCjf2xjZAqe+LeWvKb5weQ+NcPwX84kqJ0cZNxok2A= github.com/onsi/gomega v1.38.2/go.mod h1:W2MJcYxRGV63b418Ai34Ud0hEdTVXq9NW9+Sx6uXf3k= @@ -1563,8 +1563,8 @@ github.com/sashamelentyev/interfacebloat v1.1.0/go.mod h1:+Y9yU5YdTkrNvoX0xHc84d github.com/sashamelentyev/usestdlibvars v1.29.0 h1:8J0MoRrw4/NAXtjQqTHrbW9NN+3iMf7Knkq057v4XOQ= github.com/sashamelentyev/usestdlibvars v1.29.0/go.mod h1:8PpnjHMk5VdeWlVb4wCdrB8PNbLqZ3wBZTZWkrpZZL8= github.com/sean-/seed v0.0.0-20170313163322-e2103e2c3529/go.mod h1:DxrIzT+xaE7yg65j358z/aeFdxmN0P9QXhEzd20vsDc= -github.com/securego/gosec/v2 v2.22.10 h1:ntbBqdWXnu46DUOXn+R2SvPo3PiJCDugTCgTW2g4tQg= -github.com/securego/gosec/v2 v2.22.10/go.mod h1:9UNjK3tLpv/w2b0+7r82byV43wCJDNtEDQMeS+H/g2w= +github.com/securego/gosec/v2 v2.22.11-0.20251204091113-daccba6b93d7 h1:rZg6IGn0ySYZwCX8LHwZoYm03JhG/cVAJJ3O+u3Vclo= +github.com/securego/gosec/v2 v2.22.11-0.20251204091113-daccba6b93d7/go.mod h1:9sr22NZO5Kfh7unW/xZxkGYTmj2484/fCiE54gw7UTY= github.com/sergi/go-diff v1.0.0/go.mod h1:0CfEIISq7TuYL3j771MWULgwwjU+GofnZX9QAmXWZgo= github.com/sergi/go-diff v1.3.1 h1:xkr+Oxo4BOQKmkn/B9eMK0g5Kg/983T9DqqPHwYqD+8= github.com/sergi/go-diff v1.3.1/go.mod h1:aMJSSKb2lpPvRNec0+w3fl7LP9IOFzdc9Pa4NFbPK1I= @@ -1600,8 +1600,8 @@ github.com/spf13/cast v1.5.0 h1:rj3WzYc11XZaIZMPKmwP96zkFEnnAmV8s6XbB2aY32w= github.com/spf13/cast v1.5.0/go.mod h1:SpXXQ5YoyJw6s3/6cMTQuxvgRl3PCJiyaX9p6b155UU= github.com/spf13/cobra v0.0.3/go.mod h1:1l0Ry5zgKvJasoi3XT1TypsSe7PqH0Sj9dhYf7v3XqQ= github.com/spf13/cobra v1.4.0/go.mod h1:Wo4iy3BUC+X2Fybo0PDqwJIv3dNRiZLHQymsfxlB84g= -github.com/spf13/cobra v1.10.1 h1:lJeBwCfmrnXthfAupyUTzJ/J4Nc1RsHC/mSRU2dll/s= -github.com/spf13/cobra v1.10.1/go.mod h1:7SmJGaTHFVBY0jW4NXGluQoLvhqFQM+6XSKD+P4XaB0= +github.com/spf13/cobra v1.10.2 h1:DMTTonx5m65Ic0GOoRY2c16WCbHxOOw6xxezuLaBpcU= +github.com/spf13/cobra v1.10.2/go.mod h1:7C1pvHqHw5A4vrJfjNwvOdzYu0Gml16OCs2GRiTUUS4= github.com/spf13/fsync v0.9.0/go.mod h1:fNtJEfG3HiltN3y4cPOz6MLjos9+2pIEqLIgszqhp/0= github.com/spf13/jwalterweatherman v1.1.0 h1:ue6voC5bR5F8YxI5S67j9i582FU4Qvo2bmqnqMYADFk= github.com/spf13/jwalterweatherman v1.1.0/go.mod h1:aNWZUN0dPAAO/Ljvb5BEdw96iTZ0EXowPYD95IqWIGo= @@ -1927,8 +1927,8 @@ golang.org/x/crypto v0.35.0/go.mod h1:dy7dXNW32cAb/6/PRuTNsix8T+vJAqvuIy5Bli/x0Y golang.org/x/crypto v0.36.0/go.mod h1:Y4J0ReaxCR1IMaabaSMugxJES1EpwhBHhv2bDHklZvc= golang.org/x/crypto v0.37.0/go.mod h1:vg+k43peMZ0pUMhYmVAWysMK35e6ioLh3wB8ZCAfbVc= golang.org/x/crypto v0.38.0/go.mod h1:MvrbAqul58NNYPKnOra203SB9vpuZW0e+RRZV+Ggqjw= -golang.org/x/crypto v0.44.0 h1:A97SsFvM3AIwEEmTBiaxPPTYpDC47w720rdiiUvgoAU= -golang.org/x/crypto v0.44.0/go.mod h1:013i+Nw79BMiQiMsOPcVCB5ZIJbYkerPrGnOa00tvmc= +golang.org/x/crypto v0.45.0 h1:jMBrvKuj23MTlT0bQEOBcAE0mjg8mK9RXFhRH6nyF3Q= +golang.org/x/crypto v0.45.0/go.mod h1:XTGrrkGJve7CYK7J8PEww4aY7gM3qMCElcJQ8n8JdX4= golang.org/x/exp v0.0.0-20180321215751-8460e604b9de/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/exp v0.0.0-20180807140117-3d87b88a115f/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= diff --git a/test/e2e/alertmanager_test.go b/test/e2e/alertmanager_test.go index ad0352f6e69..fecfb404671 100644 --- a/test/e2e/alertmanager_test.go +++ b/test/e2e/alertmanager_test.go @@ -1104,6 +1104,7 @@ func testAlertmanagerConfigCRD(t *testing.T) { }, Key: testingSecretKey, }, + URL: ptr.To(monitoringv1alpha1.URL("https://pagerduty.example.com")), }}, SlackConfigs: []monitoringv1alpha1.SlackConfig{{ APIURL: &v1.SecretKeySelector{ @@ -1116,7 +1117,7 @@ func testAlertmanagerConfigCRD(t *testing.T) { { Type: "type", Text: "text", - Name: "my-action", + Name: ptr.To("my-action"), ConfirmField: &monitoringv1alpha1.SlackConfirmationField{ Text: "text", }, @@ -1130,9 +1131,7 @@ func testAlertmanagerConfigCRD(t *testing.T) { }, }}, WebhookConfigs: []monitoringv1alpha1.WebhookConfig{{ - URL: func(s string) *string { - return &s - }("http://test.url"), + URL: ptr.To(monitoringv1alpha1.URL("http://test.url")), }}, WeChatConfigs: []monitoringv1alpha1.WeChatConfig{{ APISecret: &v1.SecretKeySelector{ @@ -1194,7 +1193,7 @@ func testAlertmanagerConfigCRD(t *testing.T) { }, }}, TelegramConfigs: []monitoringv1alpha1.TelegramConfig{{ - APIURL: "https://telegram.api.url", + APIURL: ptr.To(monitoringv1alpha1.URL("https://telegram.api.url")), BotToken: &v1.SecretKeySelector{ LocalObjectReference: v1.LocalObjectReference{ Name: telegramTestingSecret, @@ -1304,9 +1303,7 @@ func testAlertmanagerConfigCRD(t *testing.T) { Receivers: []monitoringv1alpha1.Receiver{{ Name: "e2e", WebhookConfigs: []monitoringv1alpha1.WebhookConfig{{ - URL: func(s string) *string { - return &s - }("http://test.url"), + URL: ptr.To(monitoringv1alpha1.URL("http://test.url")), }}, }}, MuteTimeIntervals: []monitoringv1alpha1.MuteTimeInterval{ @@ -1361,9 +1358,7 @@ func testAlertmanagerConfigCRD(t *testing.T) { Receivers: []monitoringv1alpha1.Receiver{{ Name: "e2e", WebhookConfigs: []monitoringv1alpha1.WebhookConfig{{ - URL: func(s string) *string { - return &s - }("http://test.url"), + URL: ptr.To(monitoringv1alpha1.URL("http://test.url")), }}, }}, MuteTimeIntervals: []monitoringv1alpha1.MuteTimeInterval{ @@ -1542,6 +1537,7 @@ receivers: - api_key: 1234abc pagerduty_configs: - routing_key: 1234abc + url: https://pagerduty.example.com slack_configs: - api_url: http://slack.example.com fields: @@ -1783,29 +1779,33 @@ func testUserDefinedAlertmanagerConfigFromCustomResource(t *testing.T) { RequireTLS: ptr.To(true), }, ResolveTimeout: "30s", - HTTPConfig: &monitoringv1.HTTPConfig{ - OAuth2: &monitoringv1.OAuth2{ - ClientID: monitoringv1.SecretOrConfigMap{ - ConfigMap: &v1.ConfigMapKeySelector{ - LocalObjectReference: v1.LocalObjectReference{ - Name: "webhook-client-id", + HTTPConfigWithProxy: &monitoringv1.HTTPConfigWithProxy{ + HTTPConfig: monitoringv1.HTTPConfig{ + HTTPConfigWithoutTLS: monitoringv1.HTTPConfigWithoutTLS{ + OAuth2: &monitoringv1.OAuth2{ + ClientID: monitoringv1.SecretOrConfigMap{ + ConfigMap: &v1.ConfigMapKeySelector{ + LocalObjectReference: v1.LocalObjectReference{ + Name: "webhook-client-id", + }, + Key: "test", + }, + }, + ClientSecret: v1.SecretKeySelector{ + LocalObjectReference: v1.LocalObjectReference{ + Name: "webhook-client-secret", + }, + Key: "test", + }, + TokenURL: "https://test.com", + Scopes: []string{"any"}, + EndpointParams: map[string]string{ + "some": "value", }, - Key: "test", - }, - }, - ClientSecret: v1.SecretKeySelector{ - LocalObjectReference: v1.LocalObjectReference{ - Name: "webhook-client-secret", }, - Key: "test", - }, - TokenURL: "https://test.com", - Scopes: []string{"any"}, - EndpointParams: map[string]string{ - "some": "value", + FollowRedirects: ptr.To(true), }, }, - FollowRedirects: ptr.To(true), }, }, Templates: []monitoringv1.SecretOrConfigMap{ diff --git a/test/e2e/main_test.go b/test/e2e/main_test.go index ead06f60899..d508f80ef06 100644 --- a/test/e2e/main_test.go +++ b/test/e2e/main_test.go @@ -180,8 +180,6 @@ func TestAllNS(t *testing.T) { EnableAdmissionWebhook: true, ClusterRoleBindings: true, EnableScrapeConfigs: true, - // testPrometheusReconciliationOnSecretChanges needs this flag to be turned on. - AdditionalArgs: []string{"--watch-referenced-objects-in-all-namespaces=true"}, }, ) require.NoError(t, err) @@ -322,6 +320,7 @@ func testAllNSPrometheus(t *testing.T) { "PrometheusReconciliationOnSecretChanges": testPrometheusReconciliationOnSecretChanges, "PrometheusUTF8MetricsSupport": testPrometheusUTF8MetricsSupport, "PrometheusUTF8LabelSupport": testPrometheusUTF8LabelSupport, + "StuckStatefulSetRollout": testStuckStatefulSetRollout, } for name, f := range testFuncs { diff --git a/test/e2e/prometheus_test.go b/test/e2e/prometheus_test.go index f9e7a9289e3..eedc4624dcb 100644 --- a/test/e2e/prometheus_test.go +++ b/test/e2e/prometheus_test.go @@ -139,30 +139,35 @@ func deployInstrumentedApplicationWithTLS(name, ns string) error { Port: "mtls", Interval: "1s", Scheme: ptr.To(monitoringv1.SchemeHTTPS), - TLSConfig: &monitoringv1.TLSConfig{ - SafeTLSConfig: monitoringv1.SafeTLSConfig{ - ServerName: ptr.To("caandserver.com"), - CA: monitoringv1.SecretOrConfigMap{ - Secret: &v1.SecretKeySelector{ - LocalObjectReference: v1.LocalObjectReference{ - Name: testFramework.ScrapingTLSSecret, + HTTPConfigWithProxyAndTLSFiles: monitoringv1.HTTPConfigWithProxyAndTLSFiles{ + HTTPConfigWithTLSFiles: monitoringv1.HTTPConfigWithTLSFiles{ + + TLSConfig: &monitoringv1.TLSConfig{ + SafeTLSConfig: monitoringv1.SafeTLSConfig{ + ServerName: ptr.To("caandserver.com"), + CA: monitoringv1.SecretOrConfigMap{ + Secret: &v1.SecretKeySelector{ + LocalObjectReference: v1.LocalObjectReference{ + Name: testFramework.ScrapingTLSSecret, + }, + Key: testFramework.CAKey, + }, }, - Key: testFramework.CAKey, - }, - }, - Cert: monitoringv1.SecretOrConfigMap{ - Secret: &v1.SecretKeySelector{ - LocalObjectReference: v1.LocalObjectReference{ - Name: testFramework.ScrapingTLSSecret, + Cert: monitoringv1.SecretOrConfigMap{ + Secret: &v1.SecretKeySelector{ + LocalObjectReference: v1.LocalObjectReference{ + Name: testFramework.ScrapingTLSSecret, + }, + Key: testFramework.CertKey, + }, + }, + KeySecret: &v1.SecretKeySelector{ + LocalObjectReference: v1.LocalObjectReference{ + Name: testFramework.ScrapingTLSSecret, + }, + Key: testFramework.PrivateKey, }, - Key: testFramework.CertKey, - }, - }, - KeySecret: &v1.SecretKeySelector{ - LocalObjectReference: v1.LocalObjectReference{ - Name: testFramework.ScrapingTLSSecret, }, - Key: testFramework.PrivateKey, }, }, }, @@ -1124,6 +1129,10 @@ func testPromStorageUpdate(t *testing.T) { } } +// testPromReloadConfig checks that the Prometheus configuration gets reloaded +// when users provision the configuration only via additionalScrapeConfigs. +// The test also ensures that the Reconciled condition highlights that no +// resources have been selected. func testPromReloadConfig(t *testing.T) { for _, tc := range []struct { reloadStrategy monitoringv1.ReloadStrategyType @@ -1146,86 +1155,65 @@ func testPromReloadConfig(t *testing.T) { p := framework.MakeBasicPrometheus(ns, name, name, 1) p.Spec.ServiceMonitorSelector = nil p.Spec.PodMonitorSelector = nil + p.Spec.AdditionalScrapeConfigs = &v1.SecretKeySelector{ + LocalObjectReference: v1.LocalObjectReference{ + Name: fmt.Sprintf("additional-config-%s", name), + }, + Key: "config.yaml", + } p.Spec.ReloadStrategy = ptr.To(tc.reloadStrategy) - firstConfig := ` -global: - scrape_interval: 1m -scrape_configs: - - job_name: testReloadConfig - metrics_path: /metrics - static_configs: - - targets: - - 111.111.111.111:9090 -` - - var bufOne bytes.Buffer - if err := operator.GzipConfig(&bufOne, []byte(firstConfig)); err != nil { - t.Fatal(err) - } - firstConfigCompressed := bufOne.Bytes() + svc := framework.MakePrometheusService(p.Name, "not-relevant", v1.ServiceTypeClusterIP) cfg := &v1.Secret{ ObjectMeta: metav1.ObjectMeta{ - Name: fmt.Sprintf("prometheus-%s", name), + Name: fmt.Sprintf("additional-config-%s", name), }, Data: map[string][]byte{ - "prometheus.yaml.gz": firstConfigCompressed, - "configmaps.json": []byte("{}"), + "config.yaml": []byte(` +- job_name: testReloadConfig + metrics_path: /metrics + static_configs: + - targets: + - 111.111.111.111:9090 +`), }, } - svc := framework.MakePrometheusService(p.Name, "not-relevant", v1.ServiceTypeClusterIP) - - if _, err := framework.KubeClient.CoreV1().Secrets(ns).Create(context.Background(), cfg, metav1.CreateOptions{}); err != nil { - t.Fatal(err) - } - - if _, err := framework.CreatePrometheusAndWaitUntilReady(context.Background(), ns, p); err != nil { - t.Fatal(err) - } - - if finalizerFn, err := framework.CreateOrUpdateServiceAndWaitUntilReady(context.Background(), ns, svc); err != nil { - t.Fatal(err) - } else { - testCtx.AddFinalizerFn(finalizerFn) - } + cfg, err := framework.KubeClient.CoreV1().Secrets(ns).Create(context.Background(), cfg, metav1.CreateOptions{}) + require.NoError(t, err) - if err := framework.WaitForActiveTargets(context.Background(), ns, svc.Name, 1); err != nil { - t.Fatal(err) - } - - secondConfig := ` -global: - scrape_interval: 1m -scrape_configs: - - job_name: testReloadConfig - metrics_path: /metrics - static_configs: - - targets: - - 111.111.111.111:9090 - - 111.111.111.112:9090 -` + p, err = framework.CreatePrometheusAndWaitUntilReady(context.Background(), ns, p) + require.NoError(t, err) - var bufTwo bytes.Buffer - if err := operator.GzipConfig(&bufTwo, []byte(secondConfig)); err != nil { - t.Fatal(err) + var found bool + for _, cond := range p.Status.Conditions { + if cond.Type == monitoringv1.Reconciled { + require.Equal(t, operator.NoSelectedResourcesReason, cond.Reason) + found = true + } } - secondConfigCompressed := bufTwo.Bytes() + require.True(t, found) - cfg, err := framework.KubeClient.CoreV1().Secrets(ns).Get(context.Background(), cfg.Name, metav1.GetOptions{}) - if err != nil { - t.Fatal(fmt.Errorf("could not retrieve previous secret: %w", err)) - } + _, err = framework.CreateOrUpdateServiceAndWaitUntilReady(context.Background(), ns, svc) + require.NoError(t, err) - cfg.Data["prometheus.yaml.gz"] = secondConfigCompressed - if _, err := framework.KubeClient.CoreV1().Secrets(ns).Update(context.Background(), cfg, metav1.UpdateOptions{}); err != nil { - t.Fatal(err) - } + err = framework.WaitForActiveTargets(context.Background(), ns, svc.Name, 1) + require.NoError(t, err) - if err := framework.WaitForActiveTargets(context.Background(), ns, svc.Name, 2); err != nil { - t.Fatal(err) - } + cfg.Data["config.yaml"] = []byte(` +- job_name: testReloadConfig + metrics_path: /metrics + static_configs: + - targets: + - 111.111.111.111:9090 + - 111.111.111.112:9090 +`) + _, err = framework.KubeClient.CoreV1().Secrets(ns).Update(context.Background(), cfg, metav1.UpdateOptions{}) + require.NoError(t, err) + + err = framework.WaitForActiveTargets(context.Background(), ns, svc.Name, 2) + require.NoError(t, err) }) } } @@ -2997,11 +2985,17 @@ func testPromArbitraryFSAcc(t *testing.T) { }, endpoint: monitoringv1.Endpoint{ Port: "web", - BearerTokenSecret: &v1.SecretKeySelector{ - LocalObjectReference: v1.LocalObjectReference{ - Name: name, + HTTPConfigWithProxyAndTLSFiles: monitoringv1.HTTPConfigWithProxyAndTLSFiles{ + HTTPConfigWithTLSFiles: monitoringv1.HTTPConfigWithTLSFiles{ + HTTPConfigWithoutTLS: monitoringv1.HTTPConfigWithoutTLS{ + BearerTokenSecret: &v1.SecretKeySelector{ + LocalObjectReference: v1.LocalObjectReference{ + Name: name, + }, + Key: "bearer-token", + }, + }, }, - Key: "bearer-token", }, }, expectTargets: true, @@ -3016,10 +3010,16 @@ func testPromArbitraryFSAcc(t *testing.T) { }, endpoint: monitoringv1.Endpoint{ Port: "web", - TLSConfig: &monitoringv1.TLSConfig{ - CAFile: "/etc/ca-certificates/cert.pem", - CertFile: "/etc/ca-certificates/cert.pem", - KeyFile: "/etc/ca-certificates/key.pem", + HTTPConfigWithProxyAndTLSFiles: monitoringv1.HTTPConfigWithProxyAndTLSFiles{ + HTTPConfigWithTLSFiles: monitoringv1.HTTPConfigWithTLSFiles{ + TLSConfig: &monitoringv1.TLSConfig{ + TLSFilesConfig: monitoringv1.TLSFilesConfig{ + CAFile: "/etc/ca-certificates/cert.pem", + CertFile: "/etc/ca-certificates/cert.pem", + KeyFile: "/etc/ca-certificates/key.pem", + }, + }, + }, }, }, expectTargets: true, @@ -3031,10 +3031,16 @@ func testPromArbitraryFSAcc(t *testing.T) { }, endpoint: monitoringv1.Endpoint{ Port: "web", - TLSConfig: &monitoringv1.TLSConfig{ - CAFile: "/etc/ca-certificates/cert.pem", - CertFile: "/etc/ca-certificates/cert.pem", - KeyFile: "/etc/ca-certificates/key.pem", + HTTPConfigWithProxyAndTLSFiles: monitoringv1.HTTPConfigWithProxyAndTLSFiles{ + HTTPConfigWithTLSFiles: monitoringv1.HTTPConfigWithTLSFiles{ + TLSConfig: &monitoringv1.TLSConfig{ + TLSFilesConfig: monitoringv1.TLSFilesConfig{ + CAFile: "/etc/ca-certificates/cert.pem", + CertFile: "/etc/ca-certificates/cert.pem", + KeyFile: "/etc/ca-certificates/key.pem", + }, + }, + }, }, }, expectTargets: false, @@ -3046,30 +3052,34 @@ func testPromArbitraryFSAcc(t *testing.T) { }, endpoint: monitoringv1.Endpoint{ Port: "web", - TLSConfig: &monitoringv1.TLSConfig{ - SafeTLSConfig: monitoringv1.SafeTLSConfig{ - InsecureSkipVerify: ptr.To(true), - CA: monitoringv1.SecretOrConfigMap{ - Secret: &v1.SecretKeySelector{ - LocalObjectReference: v1.LocalObjectReference{ - Name: name, + HTTPConfigWithProxyAndTLSFiles: monitoringv1.HTTPConfigWithProxyAndTLSFiles{ + HTTPConfigWithTLSFiles: monitoringv1.HTTPConfigWithTLSFiles{ + TLSConfig: &monitoringv1.TLSConfig{ + SafeTLSConfig: monitoringv1.SafeTLSConfig{ + InsecureSkipVerify: ptr.To(true), + CA: monitoringv1.SecretOrConfigMap{ + Secret: &v1.SecretKeySelector{ + LocalObjectReference: v1.LocalObjectReference{ + Name: name, + }, + Key: "cert.pem", + }, }, - Key: "cert.pem", - }, - }, - Cert: monitoringv1.SecretOrConfigMap{ - Secret: &v1.SecretKeySelector{ - LocalObjectReference: v1.LocalObjectReference{ - Name: name, + Cert: monitoringv1.SecretOrConfigMap{ + Secret: &v1.SecretKeySelector{ + LocalObjectReference: v1.LocalObjectReference{ + Name: name, + }, + Key: "cert.pem", + }, + }, + KeySecret: &v1.SecretKeySelector{ + LocalObjectReference: v1.LocalObjectReference{ + Name: name, + }, + Key: "key.pem", }, - Key: "cert.pem", - }, - }, - KeySecret: &v1.SecretKeySelector{ - LocalObjectReference: v1.LocalObjectReference{ - Name: name, }, - Key: "key.pem", }, }, }, @@ -3083,30 +3093,34 @@ func testPromArbitraryFSAcc(t *testing.T) { }, endpoint: monitoringv1.Endpoint{ Port: "web", - TLSConfig: &monitoringv1.TLSConfig{ - SafeTLSConfig: monitoringv1.SafeTLSConfig{ - InsecureSkipVerify: ptr.To(true), - CA: monitoringv1.SecretOrConfigMap{ - ConfigMap: &v1.ConfigMapKeySelector{ - LocalObjectReference: v1.LocalObjectReference{ - Name: name, + HTTPConfigWithProxyAndTLSFiles: monitoringv1.HTTPConfigWithProxyAndTLSFiles{ + HTTPConfigWithTLSFiles: monitoringv1.HTTPConfigWithTLSFiles{ + TLSConfig: &monitoringv1.TLSConfig{ + SafeTLSConfig: monitoringv1.SafeTLSConfig{ + InsecureSkipVerify: ptr.To(true), + CA: monitoringv1.SecretOrConfigMap{ + ConfigMap: &v1.ConfigMapKeySelector{ + LocalObjectReference: v1.LocalObjectReference{ + Name: name, + }, + Key: "cert.pem", + }, }, - Key: "cert.pem", - }, - }, - Cert: monitoringv1.SecretOrConfigMap{ - ConfigMap: &v1.ConfigMapKeySelector{ - LocalObjectReference: v1.LocalObjectReference{ - Name: name, + Cert: monitoringv1.SecretOrConfigMap{ + ConfigMap: &v1.ConfigMapKeySelector{ + LocalObjectReference: v1.LocalObjectReference{ + Name: name, + }, + Key: "cert.pem", + }, + }, + KeySecret: &v1.SecretKeySelector{ + LocalObjectReference: v1.LocalObjectReference{ + Name: name, + }, + Key: "key.pem", }, - Key: "cert.pem", - }, - }, - KeySecret: &v1.SecretKeySelector{ - LocalObjectReference: v1.LocalObjectReference{ - Name: name, }, - Key: "key.pem", }, }, }, @@ -3339,22 +3353,26 @@ func testPromTLSConfigViaSecret(t *testing.T) { Port: "mtls", Interval: "30s", Scheme: ptr.To(monitoringv1.SchemeHTTPS), - TLSConfig: &monitoringv1.TLSConfig{ - SafeTLSConfig: monitoringv1.SafeTLSConfig{ - InsecureSkipVerify: ptr.To(true), - Cert: monitoringv1.SecretOrConfigMap{ - Secret: &v1.SecretKeySelector{ - LocalObjectReference: v1.LocalObjectReference{ - Name: tlsCertsSecret.Name, + HTTPConfigWithProxyAndTLSFiles: monitoringv1.HTTPConfigWithProxyAndTLSFiles{ + HTTPConfigWithTLSFiles: monitoringv1.HTTPConfigWithTLSFiles{ + TLSConfig: &monitoringv1.TLSConfig{ + SafeTLSConfig: monitoringv1.SafeTLSConfig{ + InsecureSkipVerify: ptr.To(true), + Cert: monitoringv1.SecretOrConfigMap{ + Secret: &v1.SecretKeySelector{ + LocalObjectReference: v1.LocalObjectReference{ + Name: tlsCertsSecret.Name, + }, + Key: "cert.pem", + }, + }, + KeySecret: &v1.SecretKeySelector{ + LocalObjectReference: v1.LocalObjectReference{ + Name: tlsCertsSecret.Name, + }, + Key: "key.pem", }, - Key: "cert.pem", - }, - }, - KeySecret: &v1.SecretKeySelector{ - LocalObjectReference: v1.LocalObjectReference{ - Name: tlsCertsSecret.Name, }, - Key: "key.pem", }, }, }, @@ -3500,19 +3518,23 @@ func testPromSecurePodMonitor(t *testing.T) { name: "basic-auth-secret", endpoint: monitoringv1.PodMetricsEndpoint{ Port: ptr.To("web"), - HTTPConfig: monitoringv1.HTTPConfig{ - BasicAuth: &monitoringv1.BasicAuth{ - Username: v1.SecretKeySelector{ - LocalObjectReference: v1.LocalObjectReference{ - Name: name, - }, - Key: "user", - }, - Password: v1.SecretKeySelector{ - LocalObjectReference: v1.LocalObjectReference{ - Name: name, + HTTPConfigWithProxy: monitoringv1.HTTPConfigWithProxy{ + HTTPConfig: monitoringv1.HTTPConfig{ + HTTPConfigWithoutTLS: monitoringv1.HTTPConfigWithoutTLS{ + BasicAuth: &monitoringv1.BasicAuth{ + Username: v1.SecretKeySelector{ + LocalObjectReference: v1.LocalObjectReference{ + Name: name, + }, + Key: "user", + }, + Password: v1.SecretKeySelector{ + LocalObjectReference: v1.LocalObjectReference{ + Name: name, + }, + Key: "password", + }, }, - Key: "password", }, }, }, @@ -3525,12 +3547,16 @@ func testPromSecurePodMonitor(t *testing.T) { name: "bearer-secret", endpoint: monitoringv1.PodMetricsEndpoint{ Port: ptr.To("web"), - HTTPConfig: monitoringv1.HTTPConfig{ - BearerTokenSecret: &v1.SecretKeySelector{ - LocalObjectReference: v1.LocalObjectReference{ - Name: name, + HTTPConfigWithProxy: monitoringv1.HTTPConfigWithProxy{ + HTTPConfig: monitoringv1.HTTPConfig{ + HTTPConfigWithoutTLS: monitoringv1.HTTPConfigWithoutTLS{ + BearerTokenSecret: &v1.SecretKeySelector{ + LocalObjectReference: v1.LocalObjectReference{ + Name: name, + }, + Key: "bearer-token", + }, }, - Key: "bearer-token", }, }, Path: "/bearer-metrics", @@ -3544,30 +3570,32 @@ func testPromSecurePodMonitor(t *testing.T) { endpoint: monitoringv1.PodMetricsEndpoint{ Port: ptr.To("mtls"), Scheme: ptr.To(monitoringv1.SchemeHTTPS), - HTTPConfig: monitoringv1.HTTPConfig{ - TLSConfig: &monitoringv1.SafeTLSConfig{ - InsecureSkipVerify: ptr.To(true), - CA: monitoringv1.SecretOrConfigMap{ - Secret: &v1.SecretKeySelector{ - LocalObjectReference: v1.LocalObjectReference{ - Name: name, + HTTPConfigWithProxy: monitoringv1.HTTPConfigWithProxy{ + HTTPConfig: monitoringv1.HTTPConfig{ + TLSConfig: &monitoringv1.SafeTLSConfig{ + InsecureSkipVerify: ptr.To(true), + CA: monitoringv1.SecretOrConfigMap{ + Secret: &v1.SecretKeySelector{ + LocalObjectReference: v1.LocalObjectReference{ + Name: name, + }, + Key: "cert.pem", }, - Key: "cert.pem", }, - }, - Cert: monitoringv1.SecretOrConfigMap{ - Secret: &v1.SecretKeySelector{ + Cert: monitoringv1.SecretOrConfigMap{ + Secret: &v1.SecretKeySelector{ + LocalObjectReference: v1.LocalObjectReference{ + Name: name, + }, + Key: "cert.pem", + }, + }, + KeySecret: &v1.SecretKeySelector{ LocalObjectReference: v1.LocalObjectReference{ Name: name, }, - Key: "cert.pem", - }, - }, - KeySecret: &v1.SecretKeySelector{ - LocalObjectReference: v1.LocalObjectReference{ - Name: name, + Key: "key.pem", }, - Key: "key.pem", }, }, }, @@ -3579,30 +3607,32 @@ func testPromSecurePodMonitor(t *testing.T) { endpoint: monitoringv1.PodMetricsEndpoint{ Port: ptr.To("mtls"), Scheme: ptr.To(monitoringv1.SchemeHTTPS), - HTTPConfig: monitoringv1.HTTPConfig{ - TLSConfig: &monitoringv1.SafeTLSConfig{ - InsecureSkipVerify: ptr.To(true), - CA: monitoringv1.SecretOrConfigMap{ - ConfigMap: &v1.ConfigMapKeySelector{ - LocalObjectReference: v1.LocalObjectReference{ - Name: name, + HTTPConfigWithProxy: monitoringv1.HTTPConfigWithProxy{ + HTTPConfig: monitoringv1.HTTPConfig{ + TLSConfig: &monitoringv1.SafeTLSConfig{ + InsecureSkipVerify: ptr.To(true), + CA: monitoringv1.SecretOrConfigMap{ + ConfigMap: &v1.ConfigMapKeySelector{ + LocalObjectReference: v1.LocalObjectReference{ + Name: name, + }, + Key: "cert.pem", }, - Key: "cert.pem", }, - }, - Cert: monitoringv1.SecretOrConfigMap{ - ConfigMap: &v1.ConfigMapKeySelector{ + Cert: monitoringv1.SecretOrConfigMap{ + ConfigMap: &v1.ConfigMapKeySelector{ + LocalObjectReference: v1.LocalObjectReference{ + Name: name, + }, + Key: "cert.pem", + }, + }, + KeySecret: &v1.SecretKeySelector{ LocalObjectReference: v1.LocalObjectReference{ Name: name, }, - Key: "cert.pem", - }, - }, - KeySecret: &v1.SecretKeySelector{ - LocalObjectReference: v1.LocalObjectReference{ - Name: name, + Key: "key.pem", }, - Key: "key.pem", }, }, }, @@ -4847,6 +4877,31 @@ func testPrometheusCRDValidation(t *testing.T) { }, }, }, + { + name: "invalid-updateStrategy", + prometheusSpec: monitoringv1.PrometheusSpec{ + CommonPrometheusFields: monitoringv1.CommonPrometheusFields{ + Replicas: &replicas, + UpdateStrategy: &monitoringv1.StatefulSetUpdateStrategy{ + Type: monitoringv1.StatefulSetUpdateStrategyType(""), + }, + }, + }, + expectedError: true, + }, + { + name: "invalid-ondelete-with-rollingupdate", + prometheusSpec: monitoringv1.PrometheusSpec{ + CommonPrometheusFields: monitoringv1.CommonPrometheusFields{ + Replicas: &replicas, + UpdateStrategy: &monitoringv1.StatefulSetUpdateStrategy{ + Type: monitoringv1.OnDeleteStatefulSetStrategyType, + RollingUpdate: &monitoringv1.RollingUpdateStatefulSetStrategy{}, + }, + }, + }, + expectedError: true, + }, } for _, test := range tests { @@ -5579,14 +5634,20 @@ func testPrometheusUTF8MetricsSupport(t *testing.T) { Endpoints: []monitoringv1.Endpoint{{ Port: "web", Interval: "30s", - BasicAuth: &monitoringv1.BasicAuth{ - Username: v1.SecretKeySelector{ - LocalObjectReference: v1.LocalObjectReference{Name: "basic-auth"}, - Key: "username", - }, - Password: v1.SecretKeySelector{ - LocalObjectReference: v1.LocalObjectReference{Name: "basic-auth"}, - Key: "password", + HTTPConfigWithProxyAndTLSFiles: monitoringv1.HTTPConfigWithProxyAndTLSFiles{ + HTTPConfigWithTLSFiles: monitoringv1.HTTPConfigWithTLSFiles{ + HTTPConfigWithoutTLS: monitoringv1.HTTPConfigWithoutTLS{ + BasicAuth: &monitoringv1.BasicAuth{ + Username: v1.SecretKeySelector{ + LocalObjectReference: v1.LocalObjectReference{Name: "basic-auth"}, + Key: "username", + }, + Password: v1.SecretKeySelector{ + LocalObjectReference: v1.LocalObjectReference{Name: "basic-auth"}, + Key: "password", + }, + }, + }, }, }, }}, @@ -5810,14 +5871,20 @@ func testPrometheusUTF8LabelSupport(t *testing.T) { TargetLabel: "service_clustér_label", Action: "replace", }}, - BasicAuth: &monitoringv1.BasicAuth{ - Username: v1.SecretKeySelector{ - LocalObjectReference: v1.LocalObjectReference{Name: "basic-auth"}, - Key: "username", - }, - Password: v1.SecretKeySelector{ - LocalObjectReference: v1.LocalObjectReference{Name: "basic-auth"}, - Key: "password", + HTTPConfigWithProxyAndTLSFiles: monitoringv1.HTTPConfigWithProxyAndTLSFiles{ + HTTPConfigWithTLSFiles: monitoringv1.HTTPConfigWithTLSFiles{ + HTTPConfigWithoutTLS: monitoringv1.HTTPConfigWithoutTLS{ + BasicAuth: &monitoringv1.BasicAuth{ + Username: v1.SecretKeySelector{ + LocalObjectReference: v1.LocalObjectReference{Name: "basic-auth"}, + Key: "username", + }, + Password: v1.SecretKeySelector{ + LocalObjectReference: v1.LocalObjectReference{Name: "basic-auth"}, + Key: "password", + }, + }, + }, }, }, }}, @@ -5873,6 +5940,103 @@ func testPrometheusUTF8LabelSupport(t *testing.T) { require.NoError(t, err, "UTF-8 label queries should work in Prometheus 3.0+ queries") } +// testStuckStatefulSetRollout ensures that when the rollout of a statefulset +// pod gets stuck, it will get unstuck after fixing the spec. +func testStuckStatefulSetRollout(t *testing.T) { + t.Parallel() + + testCtx := framework.NewTestCtx(t) + defer testCtx.Cleanup(t) + ns := framework.CreateNamespace(context.Background(), t, testCtx) + + framework.SetupPrometheusRBAC(context.Background(), t, testCtx, ns) + + prom, err := framework.CreatePrometheusAndWaitUntilReady( + context.Background(), + ns, + framework.MakeBasicPrometheus(ns, "statefulset-rollout", "test", 2), + ) + require.NoError(t, err) + + badImage := "quay.io/prometheus/prometheus:foobar" + prom, err = framework.PatchPrometheus( + context.Background(), + prom.Name, + prom.Namespace, + monitoringv1.PrometheusSpec{ + CommonPrometheusFields: monitoringv1.CommonPrometheusFields{ + Image: &badImage, + }, + }, + ) + require.NoError(t, err) + + var loopError error + err = wait.PollUntilContextTimeout(context.Background(), time.Second, framework.DefaultTimeout, true, func(_ context.Context) (bool, error) { + ctx := context.Background() + current, err := framework.MonClientV1.Prometheuses(prom.Namespace).Get(ctx, prom.Name, metav1.GetOptions{}) + if err != nil { + loopError = fmt.Errorf("failed to get object: %w", err) + return false, nil + } + + if err := framework.AssertCondition(current.Status.Conditions, monitoringv1.Reconciled, monitoringv1.ConditionTrue); err != nil { + loopError = err + return false, nil + } + + if err := framework.AssertCondition(current.Status.Conditions, monitoringv1.Available, monitoringv1.ConditionDegraded); err != nil { + loopError = err + return false, nil + } + + // The rollout should start from the highest pod ordinal. + pod, err := framework.KubeClient.CoreV1().Pods(prom.Namespace).Get(ctx, "prometheus-"+prom.Name+"-1", metav1.GetOptions{}) + if err != nil { + loopError = err + return false, nil + } + + // Ensure that the Prometheus container is stuck on ErrImagePull or ImagePullBackOff. + for _, cs := range pod.Status.ContainerStatuses { + if cs.Image != badImage { + continue + } + + if cs.State.Waiting == nil { + loopError = fmt.Errorf("container not waiting") + return false, nil + } + + if cs.State.Waiting.Reason != "ErrPullImage" && cs.State.Waiting.Reason != "ImagePullBackOff" { + loopError = fmt.Errorf("container waiting with reason %q", cs.State.Waiting.Reason) + return false, nil + } + + return true, nil + } + + loopError = fmt.Errorf("found no container with image %q", badImage) + return false, nil + }) + if err != nil { + t.Fatalf("%v: %v", err, loopError) + } + + // Fix the bad image location and ensure that the resource goes back to ready. + prom, err = framework.PatchPrometheusAndWaitUntilReady( + context.Background(), + prom.Name, + prom.Namespace, + monitoringv1.PrometheusSpec{ + CommonPrometheusFields: monitoringv1.CommonPrometheusFields{ + Image: ptr.To(operator.DefaultPrometheusImage), + }, + }, + ) + require.NoError(t, err) +} + func isAlertmanagerDiscoveryWorking(ns, promSVCName, alertmanagerName string) func(ctx context.Context) (bool, error) { return func(ctx context.Context) (bool, error) { pods, err := framework.KubeClient.CoreV1().Pods(ns).List( diff --git a/test/e2e/prometheusagent_test.go b/test/e2e/prometheusagent_test.go index 11a4fe87743..31edac5a71b 100644 --- a/test/e2e/prometheusagent_test.go +++ b/test/e2e/prometheusagent_test.go @@ -310,7 +310,8 @@ func testPromAgentReconcileDaemonSetResourceUpdate(t *testing.T) { framework.KubeClient.AppsV1().DaemonSets(ns).Update(ctx, dms, metav1.UpdateOptions{}) var pollErr error - err = wait.PollUntilContextTimeout(context.Background(), 5*time.Second, 5*time.Minute, false, func(ctx context.Context) (bool, error) { + err = wait.PollUntilContextTimeout(context.Background(), 5*time.Second, 5*time.Minute, false, func(_ context.Context) (bool, error) { + ctx := context.Background() dms, err = framework.KubeClient.AppsV1().DaemonSets(ns).Get(ctx, dmsName, metav1.GetOptions{}) if err != nil { pollErr = fmt.Errorf("failed to get Prometheus Agent DaemonSet: %w", err) @@ -657,6 +658,11 @@ func testPrometheusAgentDaemonSetCELValidations(t *testing.T) { t.Run("DaemonSetInvalidPVCRetentionPolicy", testDaemonSetInvalidPVCRetentionPolicy) t.Run("DaemonSetInvalidScrapeConfigSelector", testDaemonSetInvalidScrapeConfigSelector) t.Run("DaemonSetInvalidProbeSelector", testDaemonSetInvalidProbeSelector) + t.Run("DaemonSetInvalidScrapeConfigNamespaceSelector", testDaemonSetInvalidScrapeConfigNamespaceSelector) + t.Run("DaemonSetInvalidProbeNamespaceSelector", testDaemonSetInvalidProbeNamespaceSelector) + t.Run("DaemonSetInvalidServiceMonitorSelector", testDaemonSetInvalidServiceMonitorSelector) + t.Run("DaemonSetInvalidServiceMonitorNamespaceSelector", testDaemonSetInvalidServiceMonitorNamespaceSelector) + t.Run("DaemonSetInvalidAdditionalScrapeConfigs", testDaemonSetInvalidAdditionalScrapeConfigs) } func testDaemonSetInvalidReplicas(t *testing.T) { @@ -847,3 +853,159 @@ func testDaemonSetInvalidProbeSelector(t *testing.T) { require.Error(t, err) require.Contains(t, err.Error(), "probeSelector cannot be set when mode is DaemonSet") } + +func testDaemonSetInvalidScrapeConfigNamespaceSelector(t *testing.T) { + t.Parallel() + ctx := context.Background() + testCtx := framework.NewTestCtx(t) + defer testCtx.Cleanup(t) + + ns := framework.CreateNamespace(ctx, t, testCtx) + framework.SetupPrometheusRBAC(ctx, t, testCtx, ns) + _, err := framework.CreateOrUpdatePrometheusOperatorWithOpts( + ctx, testFramework.PrometheusOperatorOpts{ + Namespace: ns, + AllowedNamespaces: []string{ns}, + EnabledFeatureGates: []operator.FeatureGateName{operator.PrometheusAgentDaemonSetFeature}, + }, + ) + require.NoError(t, err) + + name := "test-invalid-scrape-config-namespace-selector" + p := framework.MakeBasicPrometheusAgentDaemonSet(ns, name) + + p.Spec.ScrapeConfigNamespaceSelector = &metav1.LabelSelector{ + MatchLabels: map[string]string{ + "app": "test", + }, + } + + _, err = framework.CreatePrometheusAgentAndWaitUntilReady(ctx, ns, p) + require.Error(t, err) + require.Contains(t, err.Error(), "scrapeConfigNamespaceSelector cannot be set when mode is DaemonSet") +} + +func testDaemonSetInvalidProbeNamespaceSelector(t *testing.T) { + t.Parallel() + ctx := context.Background() + testCtx := framework.NewTestCtx(t) + defer testCtx.Cleanup(t) + + ns := framework.CreateNamespace(ctx, t, testCtx) + framework.SetupPrometheusRBAC(ctx, t, testCtx, ns) + _, err := framework.CreateOrUpdatePrometheusOperatorWithOpts( + ctx, testFramework.PrometheusOperatorOpts{ + Namespace: ns, + AllowedNamespaces: []string{ns}, + EnabledFeatureGates: []operator.FeatureGateName{operator.PrometheusAgentDaemonSetFeature}, + }, + ) + require.NoError(t, err) + + name := "test-invalid-probe-namespace-selector" + p := framework.MakeBasicPrometheusAgentDaemonSet(ns, name) + + p.Spec.ProbeNamespaceSelector = &metav1.LabelSelector{ + MatchLabels: map[string]string{ + "app": "test", + }, + } + + _, err = framework.CreatePrometheusAgentAndWaitUntilReady(ctx, ns, p) + require.Error(t, err) + require.Contains(t, err.Error(), "probeNamespaceSelector cannot be set when mode is DaemonSet") +} + +func testDaemonSetInvalidServiceMonitorSelector(t *testing.T) { + t.Parallel() + ctx := context.Background() + testCtx := framework.NewTestCtx(t) + defer testCtx.Cleanup(t) + + ns := framework.CreateNamespace(ctx, t, testCtx) + framework.SetupPrometheusRBAC(ctx, t, testCtx, ns) + _, err := framework.CreateOrUpdatePrometheusOperatorWithOpts( + ctx, testFramework.PrometheusOperatorOpts{ + Namespace: ns, + AllowedNamespaces: []string{ns}, + EnabledFeatureGates: []operator.FeatureGateName{operator.PrometheusAgentDaemonSetFeature}, + }, + ) + require.NoError(t, err) + + name := "test-invalid-service-monitor-selector" + p := framework.MakeBasicPrometheusAgentDaemonSet(ns, name) + + p.Spec.ServiceMonitorSelector = &metav1.LabelSelector{ + MatchLabels: map[string]string{ + "app": "test", + }, + } + + _, err = framework.CreatePrometheusAgentAndWaitUntilReady(ctx, ns, p) + require.Error(t, err) + require.Contains(t, err.Error(), "serviceMonitorSelector cannot be set when mode is DaemonSet") +} + +func testDaemonSetInvalidServiceMonitorNamespaceSelector(t *testing.T) { + t.Parallel() + ctx := context.Background() + testCtx := framework.NewTestCtx(t) + defer testCtx.Cleanup(t) + + ns := framework.CreateNamespace(ctx, t, testCtx) + framework.SetupPrometheusRBAC(ctx, t, testCtx, ns) + _, err := framework.CreateOrUpdatePrometheusOperatorWithOpts( + ctx, testFramework.PrometheusOperatorOpts{ + Namespace: ns, + AllowedNamespaces: []string{ns}, + EnabledFeatureGates: []operator.FeatureGateName{operator.PrometheusAgentDaemonSetFeature}, + }, + ) + require.NoError(t, err) + + name := "test-invalid-service-monitor-namespace-selector" + p := framework.MakeBasicPrometheusAgentDaemonSet(ns, name) + + p.Spec.ServiceMonitorNamespaceSelector = &metav1.LabelSelector{ + MatchLabels: map[string]string{ + "app": "test", + }, + } + + _, err = framework.CreatePrometheusAgentAndWaitUntilReady(ctx, ns, p) + require.Error(t, err) + require.Contains(t, err.Error(), "serviceMonitorNamespaceSelector cannot be set when mode is DaemonSet") +} + +func testDaemonSetInvalidAdditionalScrapeConfigs(t *testing.T) { + t.Parallel() + ctx := context.Background() + testCtx := framework.NewTestCtx(t) + defer testCtx.Cleanup(t) + + ns := framework.CreateNamespace(ctx, t, testCtx) + framework.SetupPrometheusRBAC(ctx, t, testCtx, ns) + _, err := framework.CreateOrUpdatePrometheusOperatorWithOpts( + ctx, testFramework.PrometheusOperatorOpts{ + Namespace: ns, + AllowedNamespaces: []string{ns}, + EnabledFeatureGates: []operator.FeatureGateName{operator.PrometheusAgentDaemonSetFeature}, + }, + ) + require.NoError(t, err) + + name := "test-invalid-additional-scrape-configs" + p := framework.MakeBasicPrometheusAgentDaemonSet(ns, name) + + p.Spec.AdditionalScrapeConfigs = &v1.SecretKeySelector{ + LocalObjectReference: v1.LocalObjectReference{ + Name: "test-secret", + }, + Key: "key", + } + + _, err = framework.CreatePrometheusAgentAndWaitUntilReady(ctx, ns, p) + require.Error(t, err) + require.Contains(t, err.Error(), "additionalScrapeConfigs cannot be set when mode is DaemonSet") +} diff --git a/test/framework/prometheus.go b/test/framework/prometheus.go index 9e8099fc083..b414b8119b8 100644 --- a/test/framework/prometheus.go +++ b/test/framework/prometheus.go @@ -351,9 +351,8 @@ func (f *Framework) MakeBasicServiceMonitor(name string) *monitoringv1.ServiceMo }, Endpoints: []monitoringv1.Endpoint{ { - Port: "web", - Interval: "30s", - BearerTokenSecret: &v1.SecretKeySelector{}, + Port: "web", + Interval: "30s", }, }, }, diff --git a/test/framework/status.go b/test/framework/status.go index 1a88d118927..07fff93eebc 100644 --- a/test/framework/status.go +++ b/test/framework/status.go @@ -52,8 +52,11 @@ func (f *Framework) AssertCondition(conds []monitoringv1.Condition, expectedType // If the resource isn't available within the given timeout, it returns an error. func (f *Framework) WaitForResourceAvailable(ctx context.Context, getResourceStatus func(context.Context) (resourceStatus, error), timeout time.Duration) error { var pollErr error - if err := wait.PollUntilContextTimeout(ctx, 5*time.Second, timeout, false, func(ctx context.Context) (bool, error) { - var status resourceStatus + if err := wait.PollUntilContextTimeout(ctx, 5*time.Second, timeout, false, func(_ context.Context) (bool, error) { + var ( + ctx = context.Background() + status resourceStatus + ) status, pollErr = getResourceStatus(ctx) if pollErr != nil { return false, nil diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/credentials.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/credentials.go index 4ad2ee4405d..9f94cfe0046 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/aws/credentials.go +++ b/vendor/github.com/aws/aws-sdk-go-v2/aws/credentials.go @@ -118,6 +118,10 @@ const ( CredentialSourceHTTP // CredentialSourceIMDS credentials resolved from the instance metadata service (IMDS) CredentialSourceIMDS + // CredentialSourceProfileLogin credentials resolved from an `aws login` session sourced from a profile + CredentialSourceProfileLogin + // CredentialSourceLogin credentials resolved from an `aws login` session + CredentialSourceLogin ) // A Credentials is the AWS credentials value for individual credential fields. diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/go_module_metadata.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/go_module_metadata.go index 1820ff0fba3..c9d0bdc4cd0 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/aws/go_module_metadata.go +++ b/vendor/github.com/aws/aws-sdk-go-v2/aws/go_module_metadata.go @@ -3,4 +3,4 @@ package aws // goModuleVersion is the tagged release for this module -const goModuleVersion = "1.39.2" +const goModuleVersion = "1.41.0" diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/middleware/user_agent.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/middleware/user_agent.go index 3314230fd8c..157a71505cd 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/aws/middleware/user_agent.go +++ b/vendor/github.com/aws/aws-sdk-go-v2/aws/middleware/user_agent.go @@ -137,6 +137,9 @@ const ( UserAgentFeatureCredentialsIMDS = "0" UserAgentFeatureBearerServiceEnvVars = "3" + + UserAgentFeatureCredentialsProfileLogin = "AC" + UserAgentFeatureCredentialsLogin = "AD" ) var credentialSourceToFeature = map[aws.CredentialSource]UserAgentFeature{ @@ -160,6 +163,8 @@ var credentialSourceToFeature = map[aws.CredentialSource]UserAgentFeature{ aws.CredentialSourceProcess: UserAgentFeatureCredentialsProcess, aws.CredentialSourceHTTP: UserAgentFeatureCredentialsHTTP, aws.CredentialSourceIMDS: UserAgentFeatureCredentialsIMDS, + aws.CredentialSourceProfileLogin: UserAgentFeatureCredentialsProfileLogin, + aws.CredentialSourceLogin: UserAgentFeatureCredentialsLogin, } // RequestUserAgent is a build middleware that set the User-Agent for the request. diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/transport/http/client.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/transport/http/client.go index 8d7c35a9ec8..c7ef0acc4d2 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/aws/transport/http/client.go +++ b/vendor/github.com/aws/aws-sdk-go-v2/aws/transport/http/client.go @@ -18,6 +18,7 @@ var ( // Default connection pool options DefaultHTTPTransportMaxIdleConns = 100 DefaultHTTPTransportMaxIdleConnsPerHost = 10 + DefaultHTTPTransportMaxConnsPerHost = 2048 // Default connection timeouts DefaultHTTPTransportIdleConnTimeout = 90 * time.Second @@ -186,6 +187,7 @@ func defaultHTTPTransport() *http.Transport { TLSHandshakeTimeout: DefaultHTTPTransportTLSHandleshakeTimeout, MaxIdleConns: DefaultHTTPTransportMaxIdleConns, MaxIdleConnsPerHost: DefaultHTTPTransportMaxIdleConnsPerHost, + MaxConnsPerHost: DefaultHTTPTransportMaxConnsPerHost, IdleConnTimeout: DefaultHTTPTransportIdleConnTimeout, ExpectContinueTimeout: DefaultHTTPTransportExpectContinueTimeout, ForceAttemptHTTP2: true, diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/transport/http/timeout_read_closer.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/transport/http/timeout_read_closer.go index 993929bd9b7..4881ae1445b 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/aws/transport/http/timeout_read_closer.go +++ b/vendor/github.com/aws/aws-sdk-go-v2/aws/transport/http/timeout_read_closer.go @@ -64,6 +64,11 @@ func (r *timeoutReadCloser) Close() error { // AddResponseReadTimeoutMiddleware adds a middleware to the stack that wraps the // response body so that a read that takes too long will return an error. +// +// Deprecated: This API was previously exposed to customize behavior of the +// Kinesis service. That customization has been removed and this middleware's +// implementation can cause panics within the standard library networking loop. +// See #2752. func AddResponseReadTimeoutMiddleware(stack *middleware.Stack, duration time.Duration) error { return stack.Deserialize.Add(&readTimeout{duration: duration}, middleware.After) } diff --git a/vendor/github.com/aws/aws-sdk-go-v2/config/CHANGELOG.md b/vendor/github.com/aws/aws-sdk-go-v2/config/CHANGELOG.md index 526537b8bb7..ba568ed25bb 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/config/CHANGELOG.md +++ b/vendor/github.com/aws/aws-sdk-go-v2/config/CHANGELOG.md @@ -1,3 +1,71 @@ +# v1.32.6 (2025-12-16) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.32.5 (2025-12-09) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.32.4 (2025-12-08) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.32.3 (2025-12-02) + +* **Dependency Update**: Updated to the latest SDK module versions +* **Dependency Update**: Upgrade to smithy-go v1.24.0. Notably this version of the library reduces the allocation footprint of the middleware system. We observe a ~10% reduction in allocations per SDK call with this change. + +# v1.32.2 (2025-11-25) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.32.1 (2025-11-21) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.32.0 (2025-11-19.2) + +* **Feature**: Add support for AWS Login credentials (package credentials/logincreds) to the default credential chain. +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.31.21 (2025-11-19) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.31.20 (2025-11-12) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.31.19 (2025-11-11) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.31.18 (2025-11-10) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.31.17 (2025-11-04) + +* **Dependency Update**: Updated to the latest SDK module versions +* **Dependency Update**: Upgrade to smithy-go v1.23.2 which should convey some passive reduction of overall allocations, especially when not using the metrics system. + +# v1.31.16 (2025-10-30) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.31.15 (2025-10-23) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.31.14 (2025-10-22) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.31.13 (2025-10-16) + +* **Dependency Update**: Bump minimum Go version to 1.23. +* **Dependency Update**: Updated to the latest SDK module versions + # v1.31.12 (2025-09-29) * **Dependency Update**: Updated to the latest SDK module versions diff --git a/vendor/github.com/aws/aws-sdk-go-v2/config/go_module_metadata.go b/vendor/github.com/aws/aws-sdk-go-v2/config/go_module_metadata.go index 8274236780f..effc38ea6d3 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/config/go_module_metadata.go +++ b/vendor/github.com/aws/aws-sdk-go-v2/config/go_module_metadata.go @@ -3,4 +3,4 @@ package config // goModuleVersion is the tagged release for this module -const goModuleVersion = "1.31.12" +const goModuleVersion = "1.32.6" diff --git a/vendor/github.com/aws/aws-sdk-go-v2/config/resolve_credentials.go b/vendor/github.com/aws/aws-sdk-go-v2/config/resolve_credentials.go index b00259df03a..de839859991 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/config/resolve_credentials.go +++ b/vendor/github.com/aws/aws-sdk-go-v2/config/resolve_credentials.go @@ -13,10 +13,12 @@ import ( "github.com/aws/aws-sdk-go-v2/credentials" "github.com/aws/aws-sdk-go-v2/credentials/ec2rolecreds" "github.com/aws/aws-sdk-go-v2/credentials/endpointcreds" + "github.com/aws/aws-sdk-go-v2/credentials/logincreds" "github.com/aws/aws-sdk-go-v2/credentials/processcreds" "github.com/aws/aws-sdk-go-v2/credentials/ssocreds" "github.com/aws/aws-sdk-go-v2/credentials/stscreds" "github.com/aws/aws-sdk-go-v2/feature/ec2/imds" + "github.com/aws/aws-sdk-go-v2/service/signin" "github.com/aws/aws-sdk-go-v2/service/sso" "github.com/aws/aws-sdk-go-v2/service/ssooidc" "github.com/aws/aws-sdk-go-v2/service/sts" @@ -172,7 +174,10 @@ func resolveCredsFromProfile(ctx context.Context, cfg *aws.Config, envConfig *En ctx = addCredentialSource(ctx, aws.CredentialSourceProfileSSO) } err = resolveSSOCredentials(ctx, cfg, sharedConfig, configs) - + case len(sharedConfig.LoginSession) > 0: + ctx = addCredentialSource(ctx, aws.CredentialSourceProfileLogin) + ctx = addCredentialSource(ctx, aws.CredentialSourceLogin) + err = resolveLoginCredentials(ctx, cfg, sharedConfig, configs) case len(sharedConfig.CredentialProcess) != 0: // Get credentials from CredentialProcess ctx = addCredentialSource(ctx, aws.CredentialSourceProfileProcess) @@ -625,3 +630,21 @@ func addCredentialSource(ctx context.Context, source aws.CredentialSource) conte func getCredentialSources(ctx context.Context) []aws.CredentialSource { return ctx.Value(credentialSource{}).([]aws.CredentialSource) } + +func resolveLoginCredentials(ctx context.Context, cfg *aws.Config, sharedCfg *SharedConfig, configs configs) error { + cacheDir := os.Getenv("AWS_LOGIN_CACHE_DIRECTORY") + tokenPath, err := logincreds.StandardCachedTokenFilepath(sharedCfg.LoginSession, cacheDir) + if err != nil { + return err + } + + svc := signin.NewFromConfig(*cfg) + provider := logincreds.New(svc, tokenPath, func(o *logincreds.Options) { + o.CredentialSources = getCredentialSources(ctx) + }) + cfg.Credentials, err = wrapWithCredentialsCache(ctx, configs, provider) + if err != nil { + return err + } + return nil +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/config/shared_config.go b/vendor/github.com/aws/aws-sdk-go-v2/config/shared_config.go index 97be3f75694..5a0fea22200 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/config/shared_config.go +++ b/vendor/github.com/aws/aws-sdk-go-v2/config/shared_config.go @@ -125,6 +125,8 @@ const ( checksumWhenRequired = "when_required" authSchemePreferenceKey = "auth_scheme_preference" + + loginSessionKey = "login_session" ) // defaultSharedConfigProfile allows for swapping the default profile for testing @@ -362,6 +364,9 @@ type SharedConfig struct { // Priority list of preferred auth scheme names (e.g. sigv4a). AuthSchemePreference []string + + // Session ARN from an `aws login` session. + LoginSession string } func (c SharedConfig) getDefaultsMode(ctx context.Context) (value aws.DefaultsMode, ok bool, err error) { @@ -897,6 +902,8 @@ func mergeSections(dst *ini.Sections, src ini.Sections) error { ssoStartURLKey, authSchemePreferenceKey, + + loginSessionKey, } for i := range stringKeys { if err := mergeStringKey(&srcSection, &dstSection, sectionName, stringKeys[i]); err != nil { @@ -1175,6 +1182,8 @@ func (c *SharedConfig) setFromIniSection(profile string, section ini.Section) er c.AuthSchemePreference = toAuthSchemePreferenceList(section.String(authSchemePreferenceKey)) + updateString(&c.LoginSession, section, loginSessionKey) + return nil } diff --git a/vendor/github.com/aws/aws-sdk-go-v2/credentials/CHANGELOG.md b/vendor/github.com/aws/aws-sdk-go-v2/credentials/CHANGELOG.md index 015f24d3be7..210fb2e5bd2 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/credentials/CHANGELOG.md +++ b/vendor/github.com/aws/aws-sdk-go-v2/credentials/CHANGELOG.md @@ -1,3 +1,71 @@ +# v1.19.6 (2025-12-16) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.19.5 (2025-12-09) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.19.4 (2025-12-08) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.19.3 (2025-12-02) + +* **Dependency Update**: Updated to the latest SDK module versions +* **Dependency Update**: Upgrade to smithy-go v1.24.0. Notably this version of the library reduces the allocation footprint of the middleware system. We observe a ~10% reduction in allocations per SDK call with this change. + +# v1.19.2 (2025-11-25) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.19.1 (2025-11-21) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.19.0 (2025-11-19.2) + +* **Feature**: Add support for AWS Login credentials (package credentials/logincreds) to the default credential chain. +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.18.25 (2025-11-19) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.18.24 (2025-11-12) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.18.23 (2025-11-11) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.18.22 (2025-11-10) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.18.21 (2025-11-04) + +* **Dependency Update**: Updated to the latest SDK module versions +* **Dependency Update**: Upgrade to smithy-go v1.23.2 which should convey some passive reduction of overall allocations, especially when not using the metrics system. + +# v1.18.20 (2025-10-30) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.18.19 (2025-10-23) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.18.18 (2025-10-22) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.18.17 (2025-10-16) + +* **Dependency Update**: Bump minimum Go version to 1.23. +* **Dependency Update**: Updated to the latest SDK module versions + # v1.18.16 (2025-09-29) * **Dependency Update**: Updated to the latest SDK module versions diff --git a/vendor/github.com/aws/aws-sdk-go-v2/credentials/go_module_metadata.go b/vendor/github.com/aws/aws-sdk-go-v2/credentials/go_module_metadata.go index 03357b7603e..4e620d43dd3 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/credentials/go_module_metadata.go +++ b/vendor/github.com/aws/aws-sdk-go-v2/credentials/go_module_metadata.go @@ -3,4 +3,4 @@ package credentials // goModuleVersion is the tagged release for this module -const goModuleVersion = "1.18.16" +const goModuleVersion = "1.19.6" diff --git a/vendor/github.com/aws/aws-sdk-go-v2/credentials/logincreds/dpop.go b/vendor/github.com/aws/aws-sdk-go-v2/credentials/logincreds/dpop.go new file mode 100644 index 00000000000..6dc0845fdfd --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/credentials/logincreds/dpop.go @@ -0,0 +1,150 @@ +package logincreds + +import ( + "context" + "crypto/ecdsa" + cryptorand "crypto/rand" + "crypto/sha256" + "crypto/x509" + "encoding/base64" + "encoding/json" + "encoding/pem" + "fmt" + + "github.com/aws/aws-sdk-go-v2/internal/sdk" + "github.com/aws/aws-sdk-go-v2/service/signin" + "github.com/aws/smithy-go/middleware" + smithyrand "github.com/aws/smithy-go/rand" + smithyhttp "github.com/aws/smithy-go/transport/http" +) + +// AWS signin DPOP always uses the P256 curve +const curvelen = 256 / 8 // bytes + +// https://datatracker.ietf.org/doc/html/rfc9449 +func mkdpop(token *loginToken, htu string) (string, error) { + key, err := parseKey(token.DPOPKey) + if err != nil { + return "", fmt.Errorf("parse key: %w", err) + } + + header, err := jsonb64(&dpopHeader{ + Typ: "dpop+jwt", + Alg: "ES256", + Jwk: &dpopHeaderJwk{ + Kty: "EC", + X: base64.RawURLEncoding.EncodeToString(key.X.Bytes()), + Y: base64.RawURLEncoding.EncodeToString(key.Y.Bytes()), + Crv: "P-256", + }, + }) + if err != nil { + return "", fmt.Errorf("marshal header: %w", err) + } + + uuid, err := smithyrand.NewUUID(cryptorand.Reader).GetUUID() + if err != nil { + return "", fmt.Errorf("uuid: %w", err) + } + + payload, err := jsonb64(&dpopPayload{ + Jti: uuid, + Htm: "POST", + Htu: htu, + Iat: sdk.NowTime().Unix(), + }) + if err != nil { + return "", fmt.Errorf("marshal payload: %w", err) + } + + msg := fmt.Sprintf("%s.%s", header, payload) + + h := sha256.New() + h.Write([]byte(msg)) + + r, s, err := ecdsa.Sign(cryptorand.Reader, key, h.Sum(nil)) + if err != nil { + return "", fmt.Errorf("sign: %w", err) + } + + // DPOP signatures are formatted in RAW r || s form (with each value padded + // to fit in curve size which in our case is always the 256 bits) - rather + // than encoded in something like asn.1 + sig := make([]byte, curvelen*2) + r.FillBytes(sig[0:curvelen]) + s.FillBytes(sig[curvelen:]) + + dpop := fmt.Sprintf("%s.%s", msg, base64.RawURLEncoding.EncodeToString(sig)) + return dpop, nil +} + +func parseKey(pemBlock string) (*ecdsa.PrivateKey, error) { + block, _ := pem.Decode([]byte(pemBlock)) + priv, err := x509.ParseECPrivateKey(block.Bytes) + if err != nil { + return nil, fmt.Errorf("parse ec private key: %w", err) + } + + return priv, nil +} + +func jsonb64(v any) (string, error) { + j, err := json.MarshalIndent(v, "", " ") + if err != nil { + return "", err + } + + return base64.RawURLEncoding.EncodeToString(j), nil +} + +type dpopHeader struct { + Typ string `json:"typ"` + Alg string `json:"alg"` + Jwk *dpopHeaderJwk `json:"jwk"` +} + +type dpopHeaderJwk struct { + Kty string `json:"kty"` + X string `json:"x"` + Y string `json:"y"` + Crv string `json:"crv"` +} + +type dpopPayload struct { + Jti string `json:"jti"` + Htm string `json:"htm"` + Htu string `json:"htu"` + Iat int64 `json:"iat"` +} + +type signDPOP struct { + Token *loginToken +} + +func addSignDPOP(token *loginToken) func(o *signin.Options) { + return signin.WithAPIOptions(func(stack *middleware.Stack) error { + return stack.Finalize.Add(&signDPOP{token}, middleware.After) + }) +} + +func (*signDPOP) ID() string { + return "signDPOP" +} + +func (m *signDPOP) HandleFinalize( + ctx context.Context, in middleware.FinalizeInput, next middleware.FinalizeHandler) ( + out middleware.FinalizeOutput, md middleware.Metadata, err error, +) { + req, ok := in.Request.(*smithyhttp.Request) + if !ok { + return out, md, fmt.Errorf("unexpected transport type %T", req) + } + + dpop, err := mkdpop(m.Token, req.URL.String()) + if err != nil { + return out, md, fmt.Errorf("sign dpop: %w", err) + } + + req.Header.Set("DPoP", dpop) + return next.HandleFinalize(ctx, in) +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/credentials/logincreds/file.go b/vendor/github.com/aws/aws-sdk-go-v2/credentials/logincreds/file.go new file mode 100644 index 00000000000..6cd5281d49f --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/credentials/logincreds/file.go @@ -0,0 +1,14 @@ +package logincreds + +import ( + "io" + "os" +) + +var openFile func(string) (io.ReadCloser, error) = func(name string) (io.ReadCloser, error) { + return os.Open(name) +} + +var createFile func(string) (io.WriteCloser, error) = func(name string) (io.WriteCloser, error) { + return os.Create(name) +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/credentials/logincreds/provider.go b/vendor/github.com/aws/aws-sdk-go-v2/credentials/logincreds/provider.go new file mode 100644 index 00000000000..3e6357b87c7 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/credentials/logincreds/provider.go @@ -0,0 +1,172 @@ +// Package logincreds implements AWS credential provision for sessions created +// via an `aws login` command. +package logincreds + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "io" + "os" + + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/internal/sdk" + "github.com/aws/aws-sdk-go-v2/service/signin" + "github.com/aws/aws-sdk-go-v2/service/signin/types" +) + +// ProviderName identifies the login provider. +const ProviderName = "LoginProvider" + +// TokenAPIClient provides the interface for the login session's token +// retrieval operation. +type TokenAPIClient interface { + CreateOAuth2Token(context.Context, *signin.CreateOAuth2TokenInput, ...func(*signin.Options)) (*signin.CreateOAuth2TokenOutput, error) +} + +// Provider supplies credentials for an `aws login` session. +type Provider struct { + options Options +} + +var _ aws.CredentialsProvider = (*Provider)(nil) + +// Options configures the Provider. +type Options struct { + Client TokenAPIClient + + // APIOptions to pass to the underlying CreateOAuth2Token operation. + ClientOptions []func(*signin.Options) + + // The path to the cached login token. + CachedTokenFilepath string + + // The chain of providers that was used to create this provider. + // + // These values are for reporting purposes and are not meant to be set up + // directly. + CredentialSources []aws.CredentialSource +} + +// New returns a new login session credentials provider. +func New(client TokenAPIClient, path string, opts ...func(*Options)) *Provider { + options := Options{ + Client: client, + CachedTokenFilepath: path, + } + + for _, opt := range opts { + opt(&options) + } + + return &Provider{options} +} + +// Retrieve generates a new set of temporary credentials using an `aws login` +// session. +func (p *Provider) Retrieve(ctx context.Context) (aws.Credentials, error) { + token, err := p.loadToken() + if err != nil { + return aws.Credentials{}, fmt.Errorf("load login token: %w", err) + } + if err := token.Validate(); err != nil { + return aws.Credentials{}, fmt.Errorf("validate login token: %w", err) + } + + // the token may have been refreshed elsewhere or the login session might + // have just been created + if sdk.NowTime().Before(token.AccessToken.ExpiresAt) { + return token.Credentials(), nil + } + + opts := make([]func(*signin.Options), len(p.options.ClientOptions)+1) + opts[0] = addSignDPOP(token) + copy(opts[1:], p.options.ClientOptions) + + out, err := p.options.Client.CreateOAuth2Token(ctx, &signin.CreateOAuth2TokenInput{ + TokenInput: &types.CreateOAuth2TokenRequestBody{ + ClientId: aws.String(token.ClientID), + GrantType: aws.String("refresh_token"), + RefreshToken: aws.String(token.RefreshToken), + }, + }, opts...) + if err != nil { + var terr *types.AccessDeniedException + if errors.As(err, &terr) { + err = toAccessDeniedError(terr) + } + return aws.Credentials{}, fmt.Errorf("create oauth2 token: %w", err) + } + + token.Update(out) + if err := p.saveToken(token); err != nil { + return aws.Credentials{}, fmt.Errorf("save token: %w", err) + } + + return token.Credentials(), nil +} + +// ProviderSources returns the credential chain that was used to construct this +// provider. +func (p *Provider) ProviderSources() []aws.CredentialSource { + if p.options.CredentialSources == nil { + return []aws.CredentialSource{aws.CredentialSourceLogin} + } + return p.options.CredentialSources +} + +func (p *Provider) loadToken() (*loginToken, error) { + f, err := openFile(p.options.CachedTokenFilepath) + if err != nil && os.IsNotExist(err) { + return nil, fmt.Errorf("token file not found, please reauthenticate") + } + if err != nil { + return nil, err + } + defer f.Close() + + j, err := io.ReadAll(f) + if err != nil { + return nil, err + } + + var t *loginToken + if err := json.Unmarshal(j, &t); err != nil { + return nil, err + } + + return t, nil +} + +func (p *Provider) saveToken(token *loginToken) error { + j, err := json.Marshal(token) + if err != nil { + return err + } + + f, err := createFile(p.options.CachedTokenFilepath) + if err != nil { + return err + } + defer f.Close() + + if _, err := f.Write(j); err != nil { + return err + } + + return nil +} + +func toAccessDeniedError(err *types.AccessDeniedException) error { + switch err.Error_ { + case types.OAuth2ErrorCodeTokenExpired: + return fmt.Errorf("login session has expired, please reauthenticate") + case types.OAuth2ErrorCodeUserCredentialsChanged: + return fmt.Errorf("login session password has changed, please reauthenticate") + case types.OAuth2ErrorCodeInsufficientPermissions: + return fmt.Errorf("insufficient permissions, you may be missing permissions for the CreateOAuth2Token action") + default: + return err + } +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/credentials/logincreds/token.go b/vendor/github.com/aws/aws-sdk-go-v2/credentials/logincreds/token.go new file mode 100644 index 00000000000..1a97b98cdc2 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/credentials/logincreds/token.go @@ -0,0 +1,110 @@ +package logincreds + +import ( + "crypto/sha256" + "encoding/hex" + "errors" + "fmt" + "path/filepath" + "strings" + "time" + + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/internal/sdk" + "github.com/aws/aws-sdk-go-v2/internal/shareddefaults" + "github.com/aws/aws-sdk-go-v2/service/signin" +) + +var userHomeDir = shareddefaults.UserHomeDir + +// StandardCachedTokenFilepath returns the filepath for the cached login token +// file. Key that will be used to compute a SHA256 value that is hex encoded. +// +// An overriden root dir can be provided, if not set the path defaults to +// ~/.aws/sso/cache. +func StandardCachedTokenFilepath(session, dir string) (string, error) { + session = strings.TrimSpace(session) + + if len(dir) == 0 { + dir = userHomeDir() + if len(dir) == 0 { + return "", errors.New("user home dir is blank") + } + dir = filepath.Join(dir, ".aws", "login", "cache") + } + + h := sha256.New() + h.Write([]byte(session)) + + filename := strings.ToLower(hex.EncodeToString(h.Sum(nil))) + ".json" + return filepath.Join(dir, filename), nil +} + +// contents of the token as they appear on disk +type loginToken struct { + AccessToken *loginTokenAccessToken `json:"accessToken"` + TokenType string `json:"tokenType"` + RefreshToken string `json:"refreshToken"` + IdentityToken string `json:"identityToken"` + ClientID string `json:"clientId"` + DPOPKey string `json:"dpopKey"` +} + +type loginTokenAccessToken struct { + AccessKeyID string `json:"accessKeyId"` + SecretAccessKey string `json:"secretAccessKey"` + SessionToken string `json:"sessionToken"` + AccountID string `json:"accountId"` + ExpiresAt time.Time `json:"expiresAt"` +} + +func (t *loginToken) Validate() error { + if t.AccessToken == nil { + return fmt.Errorf("missing accessToken") + } + if t.AccessToken.AccessKeyID == "" { + return fmt.Errorf("missing accessToken.accessKeyId") + } + if t.AccessToken.SecretAccessKey == "" { + return fmt.Errorf("missing accessToken.secretAccessKey") + } + if t.AccessToken.SessionToken == "" { + return fmt.Errorf("missing accessToken.sessionToken") + } + if t.AccessToken.AccountID == "" { + return fmt.Errorf("missing accessToken.accountId") + } + if t.AccessToken.ExpiresAt.IsZero() { + return fmt.Errorf("missing accessToken.expiresAt") + } + if t.ClientID == "" { + return fmt.Errorf("missing clientId") + } + if t.RefreshToken == "" { + return fmt.Errorf("missing refreshToken") + } + if t.DPOPKey == "" { + return fmt.Errorf("missing dpopKey") + } + return nil +} + +func (t *loginToken) Credentials() aws.Credentials { + return aws.Credentials{ + AccessKeyID: t.AccessToken.AccessKeyID, + SecretAccessKey: t.AccessToken.SecretAccessKey, + SessionToken: t.AccessToken.SessionToken, + Source: ProviderName, + CanExpire: true, + Expires: t.AccessToken.ExpiresAt, + AccountID: t.AccessToken.AccountID, + } +} + +func (t *loginToken) Update(out *signin.CreateOAuth2TokenOutput) { + t.AccessToken.AccessKeyID = *out.TokenOutput.AccessToken.AccessKeyId + t.AccessToken.SecretAccessKey = *out.TokenOutput.AccessToken.SecretAccessKey + t.AccessToken.SessionToken = *out.TokenOutput.AccessToken.SessionToken + t.AccessToken.ExpiresAt = sdk.NowTime().Add(time.Duration(*out.TokenOutput.ExpiresIn) * time.Second) + t.RefreshToken = *out.TokenOutput.RefreshToken +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/feature/ec2/imds/CHANGELOG.md b/vendor/github.com/aws/aws-sdk-go-v2/feature/ec2/imds/CHANGELOG.md index 6b8c454739d..5b9f6cc16a7 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/feature/ec2/imds/CHANGELOG.md +++ b/vendor/github.com/aws/aws-sdk-go-v2/feature/ec2/imds/CHANGELOG.md @@ -1,3 +1,34 @@ +# v1.18.16 (2025-12-08) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.18.15 (2025-12-02) + +* **Dependency Update**: Updated to the latest SDK module versions +* **Dependency Update**: Upgrade to smithy-go v1.24.0. Notably this version of the library reduces the allocation footprint of the middleware system. We observe a ~10% reduction in allocations per SDK call with this change. + +# v1.18.14 (2025-11-19.2) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.18.13 (2025-11-04) + +* **Dependency Update**: Updated to the latest SDK module versions +* **Dependency Update**: Upgrade to smithy-go v1.23.2 which should convey some passive reduction of overall allocations, especially when not using the metrics system. + +# v1.18.12 (2025-10-30) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.18.11 (2025-10-23) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.18.10 (2025-10-16) + +* **Dependency Update**: Bump minimum Go version to 1.23. +* **Dependency Update**: Updated to the latest SDK module versions + # v1.18.9 (2025-09-26) * **Dependency Update**: Updated to the latest SDK module versions diff --git a/vendor/github.com/aws/aws-sdk-go-v2/feature/ec2/imds/go_module_metadata.go b/vendor/github.com/aws/aws-sdk-go-v2/feature/ec2/imds/go_module_metadata.go index ce89f5829de..630ccb34d15 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/feature/ec2/imds/go_module_metadata.go +++ b/vendor/github.com/aws/aws-sdk-go-v2/feature/ec2/imds/go_module_metadata.go @@ -3,4 +3,4 @@ package imds // goModuleVersion is the tagged release for this module -const goModuleVersion = "1.18.9" +const goModuleVersion = "1.18.16" diff --git a/vendor/github.com/aws/aws-sdk-go-v2/internal/configsources/CHANGELOG.md b/vendor/github.com/aws/aws-sdk-go-v2/internal/configsources/CHANGELOG.md index b34f47c9151..6ffdf061086 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/internal/configsources/CHANGELOG.md +++ b/vendor/github.com/aws/aws-sdk-go-v2/internal/configsources/CHANGELOG.md @@ -1,3 +1,34 @@ +# v1.4.16 (2025-12-08) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.4.15 (2025-12-02) + +* **Dependency Update**: Updated to the latest SDK module versions +* **Dependency Update**: Upgrade to smithy-go v1.24.0. Notably this version of the library reduces the allocation footprint of the middleware system. We observe a ~10% reduction in allocations per SDK call with this change. + +# v1.4.14 (2025-11-19.2) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.4.13 (2025-11-04) + +* **Dependency Update**: Updated to the latest SDK module versions +* **Dependency Update**: Upgrade to smithy-go v1.23.2 which should convey some passive reduction of overall allocations, especially when not using the metrics system. + +# v1.4.12 (2025-10-30) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.4.11 (2025-10-23) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.4.10 (2025-10-16) + +* **Dependency Update**: Bump minimum Go version to 1.23. +* **Dependency Update**: Updated to the latest SDK module versions + # v1.4.9 (2025-09-26) * **Dependency Update**: Updated to the latest SDK module versions diff --git a/vendor/github.com/aws/aws-sdk-go-v2/internal/configsources/go_module_metadata.go b/vendor/github.com/aws/aws-sdk-go-v2/internal/configsources/go_module_metadata.go index ebc2f6a7651..72df7b81bf0 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/internal/configsources/go_module_metadata.go +++ b/vendor/github.com/aws/aws-sdk-go-v2/internal/configsources/go_module_metadata.go @@ -3,4 +3,4 @@ package configsources // goModuleVersion is the tagged release for this module -const goModuleVersion = "1.4.9" +const goModuleVersion = "1.4.16" diff --git a/vendor/github.com/aws/aws-sdk-go-v2/internal/endpoints/awsrulesfn/partitions.go b/vendor/github.com/aws/aws-sdk-go-v2/internal/endpoints/awsrulesfn/partitions.go index 6ad5df64691..6ab4d9669fb 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/internal/endpoints/awsrulesfn/partitions.go +++ b/vendor/github.com/aws/aws-sdk-go-v2/internal/endpoints/awsrulesfn/partitions.go @@ -386,6 +386,13 @@ var partitions = []Partition{ SupportsFIPS: nil, SupportsDualStack: nil, }, + "us-isob-west-1": { + Name: nil, + DnsSuffix: nil, + DualStackDnsSuffix: nil, + SupportsFIPS: nil, + SupportsDualStack: nil, + }, }, }, { diff --git a/vendor/github.com/aws/aws-sdk-go-v2/internal/endpoints/awsrulesfn/partitions.json b/vendor/github.com/aws/aws-sdk-go-v2/internal/endpoints/awsrulesfn/partitions.json index b346b0be9b9..c789264d2b0 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/internal/endpoints/awsrulesfn/partitions.json +++ b/vendor/github.com/aws/aws-sdk-go-v2/internal/endpoints/awsrulesfn/partitions.json @@ -194,6 +194,9 @@ }, "us-isob-east-1" : { "description" : "US ISOB East (Ohio)" + }, + "us-isob-west-1" : { + "description" : "US ISOB West" } } }, { diff --git a/vendor/github.com/aws/aws-sdk-go-v2/internal/endpoints/v2/CHANGELOG.md b/vendor/github.com/aws/aws-sdk-go-v2/internal/endpoints/v2/CHANGELOG.md index 8de3bfec8c7..b2d34779110 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/internal/endpoints/v2/CHANGELOG.md +++ b/vendor/github.com/aws/aws-sdk-go-v2/internal/endpoints/v2/CHANGELOG.md @@ -1,3 +1,34 @@ +# v2.7.16 (2025-12-08) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v2.7.15 (2025-12-02) + +* **Dependency Update**: Updated to the latest SDK module versions +* **Dependency Update**: Upgrade to smithy-go v1.24.0. Notably this version of the library reduces the allocation footprint of the middleware system. We observe a ~10% reduction in allocations per SDK call with this change. + +# v2.7.14 (2025-11-19.2) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v2.7.13 (2025-11-04) + +* **Dependency Update**: Updated to the latest SDK module versions +* **Dependency Update**: Upgrade to smithy-go v1.23.2 which should convey some passive reduction of overall allocations, especially when not using the metrics system. + +# v2.7.12 (2025-10-30) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v2.7.11 (2025-10-23) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v2.7.10 (2025-10-16) + +* **Dependency Update**: Bump minimum Go version to 1.23. +* **Dependency Update**: Updated to the latest SDK module versions + # v2.7.9 (2025-09-26) * **Dependency Update**: Updated to the latest SDK module versions diff --git a/vendor/github.com/aws/aws-sdk-go-v2/internal/endpoints/v2/go_module_metadata.go b/vendor/github.com/aws/aws-sdk-go-v2/internal/endpoints/v2/go_module_metadata.go index c5168da33a3..1a524ae2e57 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/internal/endpoints/v2/go_module_metadata.go +++ b/vendor/github.com/aws/aws-sdk-go-v2/internal/endpoints/v2/go_module_metadata.go @@ -3,4 +3,4 @@ package endpoints // goModuleVersion is the tagged release for this module -const goModuleVersion = "2.7.9" +const goModuleVersion = "2.7.16" diff --git a/vendor/github.com/aws/aws-sdk-go-v2/internal/ini/CHANGELOG.md b/vendor/github.com/aws/aws-sdk-go-v2/internal/ini/CHANGELOG.md index f729db535b7..4791d328c04 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/internal/ini/CHANGELOG.md +++ b/vendor/github.com/aws/aws-sdk-go-v2/internal/ini/CHANGELOG.md @@ -1,3 +1,7 @@ +# v1.8.4 (2025-10-16) + +* **Dependency Update**: Bump minimum Go version to 1.23. + # v1.8.3 (2025-02-18) * **Bug Fix**: Bump go version to 1.22 diff --git a/vendor/github.com/aws/aws-sdk-go-v2/internal/ini/go_module_metadata.go b/vendor/github.com/aws/aws-sdk-go-v2/internal/ini/go_module_metadata.go index 00df0e3cb9b..f94970e7742 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/internal/ini/go_module_metadata.go +++ b/vendor/github.com/aws/aws-sdk-go-v2/internal/ini/go_module_metadata.go @@ -3,4 +3,4 @@ package ini // goModuleVersion is the tagged release for this module -const goModuleVersion = "1.8.3" +const goModuleVersion = "1.8.4" diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding/CHANGELOG.md b/vendor/github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding/CHANGELOG.md index 607fc092204..6ffbf3fe4ac 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding/CHANGELOG.md +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding/CHANGELOG.md @@ -1,3 +1,15 @@ +# v1.13.4 (2025-12-02) + +* **Dependency Update**: Upgrade to smithy-go v1.24.0. Notably this version of the library reduces the allocation footprint of the middleware system. We observe a ~10% reduction in allocations per SDK call with this change. + +# v1.13.3 (2025-11-04) + +* **Dependency Update**: Upgrade to smithy-go v1.23.2 which should convey some passive reduction of overall allocations, especially when not using the metrics system. + +# v1.13.2 (2025-10-16) + +* **Dependency Update**: Bump minimum Go version to 1.23. + # v1.13.1 (2025-08-27) * **Dependency Update**: Update to smithy-go v1.23.0. diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding/go_module_metadata.go b/vendor/github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding/go_module_metadata.go index 7a0b6aae29a..970bb210ec9 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding/go_module_metadata.go +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding/go_module_metadata.go @@ -3,4 +3,4 @@ package acceptencoding // goModuleVersion is the tagged release for this module -const goModuleVersion = "1.13.1" +const goModuleVersion = "1.13.4" diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/internal/presigned-url/CHANGELOG.md b/vendor/github.com/aws/aws-sdk-go-v2/service/internal/presigned-url/CHANGELOG.md index 6f143784e12..743183c8df6 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/internal/presigned-url/CHANGELOG.md +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/internal/presigned-url/CHANGELOG.md @@ -1,3 +1,34 @@ +# v1.13.16 (2025-12-08) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.13.15 (2025-12-02) + +* **Dependency Update**: Updated to the latest SDK module versions +* **Dependency Update**: Upgrade to smithy-go v1.24.0. Notably this version of the library reduces the allocation footprint of the middleware system. We observe a ~10% reduction in allocations per SDK call with this change. + +# v1.13.14 (2025-11-19.2) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.13.13 (2025-11-04) + +* **Dependency Update**: Updated to the latest SDK module versions +* **Dependency Update**: Upgrade to smithy-go v1.23.2 which should convey some passive reduction of overall allocations, especially when not using the metrics system. + +# v1.13.12 (2025-10-30) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.13.11 (2025-10-23) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.13.10 (2025-10-16) + +* **Dependency Update**: Bump minimum Go version to 1.23. +* **Dependency Update**: Updated to the latest SDK module versions + # v1.13.9 (2025-09-26) * **Dependency Update**: Updated to the latest SDK module versions diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/internal/presigned-url/go_module_metadata.go b/vendor/github.com/aws/aws-sdk-go-v2/service/internal/presigned-url/go_module_metadata.go index bc347369d8b..a8a2e692bfc 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/internal/presigned-url/go_module_metadata.go +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/internal/presigned-url/go_module_metadata.go @@ -3,4 +3,4 @@ package presignedurl // goModuleVersion is the tagged release for this module -const goModuleVersion = "1.13.9" +const goModuleVersion = "1.13.16" diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/signin/CHANGELOG.md b/vendor/github.com/aws/aws-sdk-go-v2/service/signin/CHANGELOG.md new file mode 100644 index 00000000000..4d6c08996e5 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/signin/CHANGELOG.md @@ -0,0 +1,22 @@ +# v1.0.4 (2025-12-08) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.0.3 (2025-12-02) + +* **Dependency Update**: Updated to the latest SDK module versions +* **Dependency Update**: Upgrade to smithy-go v1.24.0. Notably this version of the library reduces the allocation footprint of the middleware system. We observe a ~10% reduction in allocations per SDK call with this change. + +# v1.0.2 (2025-11-25) + +* **Bug Fix**: Add error check for endpoint param binding during auth scheme resolution to fix panic reported in #3234 + +# v1.0.1 (2025-11-19.2) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.0.0 (2025-11-19) + +* **Release**: New AWS service client module +* **Feature**: AWS Sign-In manages authentication for AWS services. This service provides secure authentication flows for accessing AWS resources from the console and developer tools. This release adds the CreateOAuth2Token API, which can be used to fetch OAuth2 access tokens and refresh tokens from Sign-In. + diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/signin/LICENSE.txt b/vendor/github.com/aws/aws-sdk-go-v2/service/signin/LICENSE.txt new file mode 100644 index 00000000000..d6456956733 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/signin/LICENSE.txt @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/signin/api_client.go b/vendor/github.com/aws/aws-sdk-go-v2/service/signin/api_client.go new file mode 100644 index 00000000000..d2db11d2aa1 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/signin/api_client.go @@ -0,0 +1,949 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package signin + +import ( + "context" + "errors" + "fmt" + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/aws/defaults" + awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" + "github.com/aws/aws-sdk-go-v2/aws/retry" + "github.com/aws/aws-sdk-go-v2/aws/signer/v4" + awshttp "github.com/aws/aws-sdk-go-v2/aws/transport/http" + internalauth "github.com/aws/aws-sdk-go-v2/internal/auth" + internalauthsmithy "github.com/aws/aws-sdk-go-v2/internal/auth/smithy" + internalConfig "github.com/aws/aws-sdk-go-v2/internal/configsources" + internalmiddleware "github.com/aws/aws-sdk-go-v2/internal/middleware" + smithy "github.com/aws/smithy-go" + smithyauth "github.com/aws/smithy-go/auth" + smithydocument "github.com/aws/smithy-go/document" + "github.com/aws/smithy-go/logging" + "github.com/aws/smithy-go/metrics" + "github.com/aws/smithy-go/middleware" + "github.com/aws/smithy-go/tracing" + smithyhttp "github.com/aws/smithy-go/transport/http" + "net" + "net/http" + "sync/atomic" + "time" +) + +const ServiceID = "Signin" +const ServiceAPIVersion = "2023-01-01" + +type operationMetrics struct { + Duration metrics.Float64Histogram + SerializeDuration metrics.Float64Histogram + ResolveIdentityDuration metrics.Float64Histogram + ResolveEndpointDuration metrics.Float64Histogram + SignRequestDuration metrics.Float64Histogram + DeserializeDuration metrics.Float64Histogram +} + +func (m *operationMetrics) histogramFor(name string) metrics.Float64Histogram { + switch name { + case "client.call.duration": + return m.Duration + case "client.call.serialization_duration": + return m.SerializeDuration + case "client.call.resolve_identity_duration": + return m.ResolveIdentityDuration + case "client.call.resolve_endpoint_duration": + return m.ResolveEndpointDuration + case "client.call.signing_duration": + return m.SignRequestDuration + case "client.call.deserialization_duration": + return m.DeserializeDuration + default: + panic("unrecognized operation metric") + } +} + +func timeOperationMetric[T any]( + ctx context.Context, metric string, fn func() (T, error), + opts ...metrics.RecordMetricOption, +) (T, error) { + mm := getOperationMetrics(ctx) + if mm == nil { // not using the metrics system + return fn() + } + + instr := mm.histogramFor(metric) + opts = append([]metrics.RecordMetricOption{withOperationMetadata(ctx)}, opts...) + + start := time.Now() + v, err := fn() + end := time.Now() + + elapsed := end.Sub(start) + instr.Record(ctx, float64(elapsed)/1e9, opts...) + return v, err +} + +func startMetricTimer(ctx context.Context, metric string, opts ...metrics.RecordMetricOption) func() { + mm := getOperationMetrics(ctx) + if mm == nil { // not using the metrics system + return func() {} + } + + instr := mm.histogramFor(metric) + opts = append([]metrics.RecordMetricOption{withOperationMetadata(ctx)}, opts...) + + var ended bool + start := time.Now() + return func() { + if ended { + return + } + ended = true + + end := time.Now() + + elapsed := end.Sub(start) + instr.Record(ctx, float64(elapsed)/1e9, opts...) + } +} + +func withOperationMetadata(ctx context.Context) metrics.RecordMetricOption { + return func(o *metrics.RecordMetricOptions) { + o.Properties.Set("rpc.service", middleware.GetServiceID(ctx)) + o.Properties.Set("rpc.method", middleware.GetOperationName(ctx)) + } +} + +type operationMetricsKey struct{} + +func withOperationMetrics(parent context.Context, mp metrics.MeterProvider) (context.Context, error) { + if _, ok := mp.(metrics.NopMeterProvider); ok { + // not using the metrics system - setting up the metrics context is a memory-intensive operation + // so we should skip it in this case + return parent, nil + } + + meter := mp.Meter("github.com/aws/aws-sdk-go-v2/service/signin") + om := &operationMetrics{} + + var err error + + om.Duration, err = operationMetricTimer(meter, "client.call.duration", + "Overall call duration (including retries and time to send or receive request and response body)") + if err != nil { + return nil, err + } + om.SerializeDuration, err = operationMetricTimer(meter, "client.call.serialization_duration", + "The time it takes to serialize a message body") + if err != nil { + return nil, err + } + om.ResolveIdentityDuration, err = operationMetricTimer(meter, "client.call.auth.resolve_identity_duration", + "The time taken to acquire an identity (AWS credentials, bearer token, etc) from an Identity Provider") + if err != nil { + return nil, err + } + om.ResolveEndpointDuration, err = operationMetricTimer(meter, "client.call.resolve_endpoint_duration", + "The time it takes to resolve an endpoint (endpoint resolver, not DNS) for the request") + if err != nil { + return nil, err + } + om.SignRequestDuration, err = operationMetricTimer(meter, "client.call.auth.signing_duration", + "The time it takes to sign a request") + if err != nil { + return nil, err + } + om.DeserializeDuration, err = operationMetricTimer(meter, "client.call.deserialization_duration", + "The time it takes to deserialize a message body") + if err != nil { + return nil, err + } + + return context.WithValue(parent, operationMetricsKey{}, om), nil +} + +func operationMetricTimer(m metrics.Meter, name, desc string) (metrics.Float64Histogram, error) { + return m.Float64Histogram(name, func(o *metrics.InstrumentOptions) { + o.UnitLabel = "s" + o.Description = desc + }) +} + +func getOperationMetrics(ctx context.Context) *operationMetrics { + if v := ctx.Value(operationMetricsKey{}); v != nil { + return v.(*operationMetrics) + } + return nil +} + +func operationTracer(p tracing.TracerProvider) tracing.Tracer { + return p.Tracer("github.com/aws/aws-sdk-go-v2/service/signin") +} + +// Client provides the API client to make operations call for AWS Sign-In Service. +type Client struct { + options Options + + // Difference between the time reported by the server and the client + timeOffset *atomic.Int64 +} + +// New returns an initialized Client based on the functional options. Provide +// additional functional options to further configure the behavior of the client, +// such as changing the client's endpoint or adding custom middleware behavior. +func New(options Options, optFns ...func(*Options)) *Client { + options = options.Copy() + + resolveDefaultLogger(&options) + + setResolvedDefaultsMode(&options) + + resolveRetryer(&options) + + resolveHTTPClient(&options) + + resolveHTTPSignerV4(&options) + + resolveEndpointResolverV2(&options) + + resolveTracerProvider(&options) + + resolveMeterProvider(&options) + + resolveAuthSchemeResolver(&options) + + for _, fn := range optFns { + fn(&options) + } + + finalizeRetryMaxAttempts(&options) + + ignoreAnonymousAuth(&options) + + wrapWithAnonymousAuth(&options) + + resolveAuthSchemes(&options) + + client := &Client{ + options: options, + } + + initializeTimeOffsetResolver(client) + + return client +} + +// Options returns a copy of the client configuration. +// +// Callers SHOULD NOT perform mutations on any inner structures within client +// config. Config overrides should instead be made on a per-operation basis through +// functional options. +func (c *Client) Options() Options { + return c.options.Copy() +} + +func (c *Client) invokeOperation( + ctx context.Context, opID string, params interface{}, optFns []func(*Options), stackFns ...func(*middleware.Stack, Options) error, +) ( + result interface{}, metadata middleware.Metadata, err error, +) { + ctx = middleware.ClearStackValues(ctx) + ctx = middleware.WithServiceID(ctx, ServiceID) + ctx = middleware.WithOperationName(ctx, opID) + + stack := middleware.NewStack(opID, smithyhttp.NewStackRequest) + options := c.options.Copy() + + for _, fn := range optFns { + fn(&options) + } + + finalizeOperationRetryMaxAttempts(&options, *c) + + finalizeClientEndpointResolverOptions(&options) + + for _, fn := range stackFns { + if err := fn(stack, options); err != nil { + return nil, metadata, err + } + } + + for _, fn := range options.APIOptions { + if err := fn(stack); err != nil { + return nil, metadata, err + } + } + + ctx, err = withOperationMetrics(ctx, options.MeterProvider) + if err != nil { + return nil, metadata, err + } + + tracer := operationTracer(options.TracerProvider) + spanName := fmt.Sprintf("%s.%s", ServiceID, opID) + + ctx = tracing.WithOperationTracer(ctx, tracer) + + ctx, span := tracer.StartSpan(ctx, spanName, func(o *tracing.SpanOptions) { + o.Kind = tracing.SpanKindClient + o.Properties.Set("rpc.system", "aws-api") + o.Properties.Set("rpc.method", opID) + o.Properties.Set("rpc.service", ServiceID) + }) + endTimer := startMetricTimer(ctx, "client.call.duration") + defer endTimer() + defer span.End() + + handler := smithyhttp.NewClientHandlerWithOptions(options.HTTPClient, func(o *smithyhttp.ClientHandler) { + o.Meter = options.MeterProvider.Meter("github.com/aws/aws-sdk-go-v2/service/signin") + }) + decorated := middleware.DecorateHandler(handler, stack) + result, metadata, err = decorated.Handle(ctx, params) + if err != nil { + span.SetProperty("exception.type", fmt.Sprintf("%T", err)) + span.SetProperty("exception.message", err.Error()) + + var aerr smithy.APIError + if errors.As(err, &aerr) { + span.SetProperty("api.error_code", aerr.ErrorCode()) + span.SetProperty("api.error_message", aerr.ErrorMessage()) + span.SetProperty("api.error_fault", aerr.ErrorFault().String()) + } + + err = &smithy.OperationError{ + ServiceID: ServiceID, + OperationName: opID, + Err: err, + } + } + + span.SetProperty("error", err != nil) + if err == nil { + span.SetStatus(tracing.SpanStatusOK) + } else { + span.SetStatus(tracing.SpanStatusError) + } + + return result, metadata, err +} + +type operationInputKey struct{} + +func setOperationInput(ctx context.Context, input interface{}) context.Context { + return middleware.WithStackValue(ctx, operationInputKey{}, input) +} + +func getOperationInput(ctx context.Context) interface{} { + return middleware.GetStackValue(ctx, operationInputKey{}) +} + +type setOperationInputMiddleware struct { +} + +func (*setOperationInputMiddleware) ID() string { + return "setOperationInput" +} + +func (m *setOperationInputMiddleware) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( + out middleware.SerializeOutput, metadata middleware.Metadata, err error, +) { + ctx = setOperationInput(ctx, in.Parameters) + return next.HandleSerialize(ctx, in) +} + +func addProtocolFinalizerMiddlewares(stack *middleware.Stack, options Options, operation string) error { + if err := stack.Finalize.Add(&resolveAuthSchemeMiddleware{operation: operation, options: options}, middleware.Before); err != nil { + return fmt.Errorf("add ResolveAuthScheme: %w", err) + } + if err := stack.Finalize.Insert(&getIdentityMiddleware{options: options}, "ResolveAuthScheme", middleware.After); err != nil { + return fmt.Errorf("add GetIdentity: %v", err) + } + if err := stack.Finalize.Insert(&resolveEndpointV2Middleware{options: options}, "GetIdentity", middleware.After); err != nil { + return fmt.Errorf("add ResolveEndpointV2: %v", err) + } + if err := stack.Finalize.Insert(&signRequestMiddleware{options: options}, "ResolveEndpointV2", middleware.After); err != nil { + return fmt.Errorf("add Signing: %w", err) + } + return nil +} +func resolveAuthSchemeResolver(options *Options) { + if options.AuthSchemeResolver == nil { + options.AuthSchemeResolver = &defaultAuthSchemeResolver{} + } +} + +func resolveAuthSchemes(options *Options) { + if options.AuthSchemes == nil { + options.AuthSchemes = []smithyhttp.AuthScheme{ + internalauth.NewHTTPAuthScheme("aws.auth#sigv4", &internalauthsmithy.V4SignerAdapter{ + Signer: options.HTTPSignerV4, + Logger: options.Logger, + LogSigning: options.ClientLogMode.IsSigning(), + }), + } + } +} + +type noSmithyDocumentSerde = smithydocument.NoSerde + +type legacyEndpointContextSetter struct { + LegacyResolver EndpointResolver +} + +func (*legacyEndpointContextSetter) ID() string { + return "legacyEndpointContextSetter" +} + +func (m *legacyEndpointContextSetter) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( + out middleware.InitializeOutput, metadata middleware.Metadata, err error, +) { + if m.LegacyResolver != nil { + ctx = awsmiddleware.SetRequiresLegacyEndpoints(ctx, true) + } + + return next.HandleInitialize(ctx, in) + +} +func addlegacyEndpointContextSetter(stack *middleware.Stack, o Options) error { + return stack.Initialize.Add(&legacyEndpointContextSetter{ + LegacyResolver: o.EndpointResolver, + }, middleware.Before) +} + +func resolveDefaultLogger(o *Options) { + if o.Logger != nil { + return + } + o.Logger = logging.Nop{} +} + +func addSetLoggerMiddleware(stack *middleware.Stack, o Options) error { + return middleware.AddSetLoggerMiddleware(stack, o.Logger) +} + +func setResolvedDefaultsMode(o *Options) { + if len(o.resolvedDefaultsMode) > 0 { + return + } + + var mode aws.DefaultsMode + mode.SetFromString(string(o.DefaultsMode)) + + if mode == aws.DefaultsModeAuto { + mode = defaults.ResolveDefaultsModeAuto(o.Region, o.RuntimeEnvironment) + } + + o.resolvedDefaultsMode = mode +} + +// NewFromConfig returns a new client from the provided config. +func NewFromConfig(cfg aws.Config, optFns ...func(*Options)) *Client { + opts := Options{ + Region: cfg.Region, + DefaultsMode: cfg.DefaultsMode, + RuntimeEnvironment: cfg.RuntimeEnvironment, + HTTPClient: cfg.HTTPClient, + Credentials: cfg.Credentials, + APIOptions: cfg.APIOptions, + Logger: cfg.Logger, + ClientLogMode: cfg.ClientLogMode, + AppID: cfg.AppID, + AuthSchemePreference: cfg.AuthSchemePreference, + } + resolveAWSRetryerProvider(cfg, &opts) + resolveAWSRetryMaxAttempts(cfg, &opts) + resolveAWSRetryMode(cfg, &opts) + resolveAWSEndpointResolver(cfg, &opts) + resolveInterceptors(cfg, &opts) + resolveUseDualStackEndpoint(cfg, &opts) + resolveUseFIPSEndpoint(cfg, &opts) + resolveBaseEndpoint(cfg, &opts) + return New(opts, func(o *Options) { + for _, opt := range cfg.ServiceOptions { + opt(ServiceID, o) + } + for _, opt := range optFns { + opt(o) + } + }) +} + +func resolveHTTPClient(o *Options) { + var buildable *awshttp.BuildableClient + + if o.HTTPClient != nil { + var ok bool + buildable, ok = o.HTTPClient.(*awshttp.BuildableClient) + if !ok { + return + } + } else { + buildable = awshttp.NewBuildableClient() + } + + modeConfig, err := defaults.GetModeConfiguration(o.resolvedDefaultsMode) + if err == nil { + buildable = buildable.WithDialerOptions(func(dialer *net.Dialer) { + if dialerTimeout, ok := modeConfig.GetConnectTimeout(); ok { + dialer.Timeout = dialerTimeout + } + }) + + buildable = buildable.WithTransportOptions(func(transport *http.Transport) { + if tlsHandshakeTimeout, ok := modeConfig.GetTLSNegotiationTimeout(); ok { + transport.TLSHandshakeTimeout = tlsHandshakeTimeout + } + }) + } + + o.HTTPClient = buildable +} + +func resolveRetryer(o *Options) { + if o.Retryer != nil { + return + } + + if len(o.RetryMode) == 0 { + modeConfig, err := defaults.GetModeConfiguration(o.resolvedDefaultsMode) + if err == nil { + o.RetryMode = modeConfig.RetryMode + } + } + if len(o.RetryMode) == 0 { + o.RetryMode = aws.RetryModeStandard + } + + var standardOptions []func(*retry.StandardOptions) + if v := o.RetryMaxAttempts; v != 0 { + standardOptions = append(standardOptions, func(so *retry.StandardOptions) { + so.MaxAttempts = v + }) + } + + switch o.RetryMode { + case aws.RetryModeAdaptive: + var adaptiveOptions []func(*retry.AdaptiveModeOptions) + if len(standardOptions) != 0 { + adaptiveOptions = append(adaptiveOptions, func(ao *retry.AdaptiveModeOptions) { + ao.StandardOptions = append(ao.StandardOptions, standardOptions...) + }) + } + o.Retryer = retry.NewAdaptiveMode(adaptiveOptions...) + + default: + o.Retryer = retry.NewStandard(standardOptions...) + } +} + +func resolveAWSRetryerProvider(cfg aws.Config, o *Options) { + if cfg.Retryer == nil { + return + } + o.Retryer = cfg.Retryer() +} + +func resolveAWSRetryMode(cfg aws.Config, o *Options) { + if len(cfg.RetryMode) == 0 { + return + } + o.RetryMode = cfg.RetryMode +} +func resolveAWSRetryMaxAttempts(cfg aws.Config, o *Options) { + if cfg.RetryMaxAttempts == 0 { + return + } + o.RetryMaxAttempts = cfg.RetryMaxAttempts +} + +func finalizeRetryMaxAttempts(o *Options) { + if o.RetryMaxAttempts == 0 { + return + } + + o.Retryer = retry.AddWithMaxAttempts(o.Retryer, o.RetryMaxAttempts) +} + +func finalizeOperationRetryMaxAttempts(o *Options, client Client) { + if v := o.RetryMaxAttempts; v == 0 || v == client.options.RetryMaxAttempts { + return + } + + o.Retryer = retry.AddWithMaxAttempts(o.Retryer, o.RetryMaxAttempts) +} + +func resolveAWSEndpointResolver(cfg aws.Config, o *Options) { + if cfg.EndpointResolver == nil && cfg.EndpointResolverWithOptions == nil { + return + } + o.EndpointResolver = withEndpointResolver(cfg.EndpointResolver, cfg.EndpointResolverWithOptions) +} + +func resolveInterceptors(cfg aws.Config, o *Options) { + o.Interceptors = cfg.Interceptors.Copy() +} + +func addClientUserAgent(stack *middleware.Stack, options Options) error { + ua, err := getOrAddRequestUserAgent(stack) + if err != nil { + return err + } + + ua.AddSDKAgentKeyValue(awsmiddleware.APIMetadata, "signin", goModuleVersion) + if len(options.AppID) > 0 { + ua.AddSDKAgentKey(awsmiddleware.ApplicationIdentifier, options.AppID) + } + + return nil +} + +func getOrAddRequestUserAgent(stack *middleware.Stack) (*awsmiddleware.RequestUserAgent, error) { + id := (*awsmiddleware.RequestUserAgent)(nil).ID() + mw, ok := stack.Build.Get(id) + if !ok { + mw = awsmiddleware.NewRequestUserAgent() + if err := stack.Build.Add(mw, middleware.After); err != nil { + return nil, err + } + } + + ua, ok := mw.(*awsmiddleware.RequestUserAgent) + if !ok { + return nil, fmt.Errorf("%T for %s middleware did not match expected type", mw, id) + } + + return ua, nil +} + +type HTTPSignerV4 interface { + SignHTTP(ctx context.Context, credentials aws.Credentials, r *http.Request, payloadHash string, service string, region string, signingTime time.Time, optFns ...func(*v4.SignerOptions)) error +} + +func resolveHTTPSignerV4(o *Options) { + if o.HTTPSignerV4 != nil { + return + } + o.HTTPSignerV4 = newDefaultV4Signer(*o) +} + +func newDefaultV4Signer(o Options) *v4.Signer { + return v4.NewSigner(func(so *v4.SignerOptions) { + so.Logger = o.Logger + so.LogSigning = o.ClientLogMode.IsSigning() + }) +} + +func addClientRequestID(stack *middleware.Stack) error { + return stack.Build.Add(&awsmiddleware.ClientRequestID{}, middleware.After) +} + +func addComputeContentLength(stack *middleware.Stack) error { + return stack.Build.Add(&smithyhttp.ComputeContentLength{}, middleware.After) +} + +func addRawResponseToMetadata(stack *middleware.Stack) error { + return stack.Deserialize.Add(&awsmiddleware.AddRawResponse{}, middleware.Before) +} + +func addRecordResponseTiming(stack *middleware.Stack) error { + return stack.Deserialize.Add(&awsmiddleware.RecordResponseTiming{}, middleware.After) +} + +func addSpanRetryLoop(stack *middleware.Stack, options Options) error { + return stack.Finalize.Insert(&spanRetryLoop{options: options}, "Retry", middleware.Before) +} + +type spanRetryLoop struct { + options Options +} + +func (*spanRetryLoop) ID() string { + return "spanRetryLoop" +} + +func (m *spanRetryLoop) HandleFinalize( + ctx context.Context, in middleware.FinalizeInput, next middleware.FinalizeHandler, +) ( + middleware.FinalizeOutput, middleware.Metadata, error, +) { + tracer := operationTracer(m.options.TracerProvider) + ctx, span := tracer.StartSpan(ctx, "RetryLoop") + defer span.End() + + return next.HandleFinalize(ctx, in) +} +func addStreamingEventsPayload(stack *middleware.Stack) error { + return stack.Finalize.Add(&v4.StreamingEventsPayload{}, middleware.Before) +} + +func addUnsignedPayload(stack *middleware.Stack) error { + return stack.Finalize.Insert(&v4.UnsignedPayload{}, "ResolveEndpointV2", middleware.After) +} + +func addComputePayloadSHA256(stack *middleware.Stack) error { + return stack.Finalize.Insert(&v4.ComputePayloadSHA256{}, "ResolveEndpointV2", middleware.After) +} + +func addContentSHA256Header(stack *middleware.Stack) error { + return stack.Finalize.Insert(&v4.ContentSHA256Header{}, (*v4.ComputePayloadSHA256)(nil).ID(), middleware.After) +} + +func addIsWaiterUserAgent(o *Options) { + o.APIOptions = append(o.APIOptions, func(stack *middleware.Stack) error { + ua, err := getOrAddRequestUserAgent(stack) + if err != nil { + return err + } + + ua.AddUserAgentFeature(awsmiddleware.UserAgentFeatureWaiter) + return nil + }) +} + +func addIsPaginatorUserAgent(o *Options) { + o.APIOptions = append(o.APIOptions, func(stack *middleware.Stack) error { + ua, err := getOrAddRequestUserAgent(stack) + if err != nil { + return err + } + + ua.AddUserAgentFeature(awsmiddleware.UserAgentFeaturePaginator) + return nil + }) +} + +func addRetry(stack *middleware.Stack, o Options) error { + attempt := retry.NewAttemptMiddleware(o.Retryer, smithyhttp.RequestCloner, func(m *retry.Attempt) { + m.LogAttempts = o.ClientLogMode.IsRetries() + m.OperationMeter = o.MeterProvider.Meter("github.com/aws/aws-sdk-go-v2/service/signin") + }) + if err := stack.Finalize.Insert(attempt, "ResolveAuthScheme", middleware.Before); err != nil { + return err + } + if err := stack.Finalize.Insert(&retry.MetricsHeader{}, attempt.ID(), middleware.After); err != nil { + return err + } + return nil +} + +// resolves dual-stack endpoint configuration +func resolveUseDualStackEndpoint(cfg aws.Config, o *Options) error { + if len(cfg.ConfigSources) == 0 { + return nil + } + value, found, err := internalConfig.ResolveUseDualStackEndpoint(context.Background(), cfg.ConfigSources) + if err != nil { + return err + } + if found { + o.EndpointOptions.UseDualStackEndpoint = value + } + return nil +} + +// resolves FIPS endpoint configuration +func resolveUseFIPSEndpoint(cfg aws.Config, o *Options) error { + if len(cfg.ConfigSources) == 0 { + return nil + } + value, found, err := internalConfig.ResolveUseFIPSEndpoint(context.Background(), cfg.ConfigSources) + if err != nil { + return err + } + if found { + o.EndpointOptions.UseFIPSEndpoint = value + } + return nil +} + +func resolveAccountID(identity smithyauth.Identity, mode aws.AccountIDEndpointMode) *string { + if mode == aws.AccountIDEndpointModeDisabled { + return nil + } + + if ca, ok := identity.(*internalauthsmithy.CredentialsAdapter); ok && ca.Credentials.AccountID != "" { + return aws.String(ca.Credentials.AccountID) + } + + return nil +} + +func addTimeOffsetBuild(stack *middleware.Stack, c *Client) error { + mw := internalmiddleware.AddTimeOffsetMiddleware{Offset: c.timeOffset} + if err := stack.Build.Add(&mw, middleware.After); err != nil { + return err + } + return stack.Deserialize.Insert(&mw, "RecordResponseTiming", middleware.Before) +} +func initializeTimeOffsetResolver(c *Client) { + c.timeOffset = new(atomic.Int64) +} + +func addUserAgentRetryMode(stack *middleware.Stack, options Options) error { + ua, err := getOrAddRequestUserAgent(stack) + if err != nil { + return err + } + + switch options.Retryer.(type) { + case *retry.Standard: + ua.AddUserAgentFeature(awsmiddleware.UserAgentFeatureRetryModeStandard) + case *retry.AdaptiveMode: + ua.AddUserAgentFeature(awsmiddleware.UserAgentFeatureRetryModeAdaptive) + } + return nil +} + +type setCredentialSourceMiddleware struct { + ua *awsmiddleware.RequestUserAgent + options Options +} + +func (m setCredentialSourceMiddleware) ID() string { return "SetCredentialSourceMiddleware" } + +func (m setCredentialSourceMiddleware) HandleBuild(ctx context.Context, in middleware.BuildInput, next middleware.BuildHandler) ( + out middleware.BuildOutput, metadata middleware.Metadata, err error, +) { + asProviderSource, ok := m.options.Credentials.(aws.CredentialProviderSource) + if !ok { + return next.HandleBuild(ctx, in) + } + providerSources := asProviderSource.ProviderSources() + for _, source := range providerSources { + m.ua.AddCredentialsSource(source) + } + return next.HandleBuild(ctx, in) +} + +func addCredentialSource(stack *middleware.Stack, options Options) error { + ua, err := getOrAddRequestUserAgent(stack) + if err != nil { + return err + } + + mw := setCredentialSourceMiddleware{ua: ua, options: options} + return stack.Build.Insert(&mw, "UserAgent", middleware.Before) +} + +func resolveTracerProvider(options *Options) { + if options.TracerProvider == nil { + options.TracerProvider = &tracing.NopTracerProvider{} + } +} + +func resolveMeterProvider(options *Options) { + if options.MeterProvider == nil { + options.MeterProvider = metrics.NopMeterProvider{} + } +} + +func addRecursionDetection(stack *middleware.Stack) error { + return stack.Build.Add(&awsmiddleware.RecursionDetection{}, middleware.After) +} + +func addRequestIDRetrieverMiddleware(stack *middleware.Stack) error { + return stack.Deserialize.Insert(&awsmiddleware.RequestIDRetriever{}, "OperationDeserializer", middleware.Before) + +} + +func addResponseErrorMiddleware(stack *middleware.Stack) error { + return stack.Deserialize.Insert(&awshttp.ResponseErrorWrapper{}, "RequestIDRetriever", middleware.Before) + +} + +func addRequestResponseLogging(stack *middleware.Stack, o Options) error { + return stack.Deserialize.Add(&smithyhttp.RequestResponseLogger{ + LogRequest: o.ClientLogMode.IsRequest(), + LogRequestWithBody: o.ClientLogMode.IsRequestWithBody(), + LogResponse: o.ClientLogMode.IsResponse(), + LogResponseWithBody: o.ClientLogMode.IsResponseWithBody(), + }, middleware.After) +} + +type disableHTTPSMiddleware struct { + DisableHTTPS bool +} + +func (*disableHTTPSMiddleware) ID() string { + return "disableHTTPS" +} + +func (m *disableHTTPSMiddleware) HandleFinalize(ctx context.Context, in middleware.FinalizeInput, next middleware.FinalizeHandler) ( + out middleware.FinalizeOutput, metadata middleware.Metadata, err error, +) { + req, ok := in.Request.(*smithyhttp.Request) + if !ok { + return out, metadata, fmt.Errorf("unknown transport type %T", in.Request) + } + + if m.DisableHTTPS && !smithyhttp.GetHostnameImmutable(ctx) { + req.URL.Scheme = "http" + } + + return next.HandleFinalize(ctx, in) +} + +func addDisableHTTPSMiddleware(stack *middleware.Stack, o Options) error { + return stack.Finalize.Insert(&disableHTTPSMiddleware{ + DisableHTTPS: o.EndpointOptions.DisableHTTPS, + }, "ResolveEndpointV2", middleware.After) +} + +func addInterceptBeforeRetryLoop(stack *middleware.Stack, opts Options) error { + return stack.Finalize.Insert(&smithyhttp.InterceptBeforeRetryLoop{ + Interceptors: opts.Interceptors.BeforeRetryLoop, + }, "Retry", middleware.Before) +} + +func addInterceptAttempt(stack *middleware.Stack, opts Options) error { + return stack.Finalize.Insert(&smithyhttp.InterceptAttempt{ + BeforeAttempt: opts.Interceptors.BeforeAttempt, + AfterAttempt: opts.Interceptors.AfterAttempt, + }, "Retry", middleware.After) +} + +func addInterceptors(stack *middleware.Stack, opts Options) error { + // middlewares are expensive, don't add all of these interceptor ones unless the caller + // actually has at least one interceptor configured + // + // at the moment it's all-or-nothing because some of the middlewares here are responsible for + // setting fields in the interceptor context for future ones + if len(opts.Interceptors.BeforeExecution) == 0 && + len(opts.Interceptors.BeforeSerialization) == 0 && len(opts.Interceptors.AfterSerialization) == 0 && + len(opts.Interceptors.BeforeRetryLoop) == 0 && + len(opts.Interceptors.BeforeAttempt) == 0 && + len(opts.Interceptors.BeforeSigning) == 0 && len(opts.Interceptors.AfterSigning) == 0 && + len(opts.Interceptors.BeforeTransmit) == 0 && len(opts.Interceptors.AfterTransmit) == 0 && + len(opts.Interceptors.BeforeDeserialization) == 0 && len(opts.Interceptors.AfterDeserialization) == 0 && + len(opts.Interceptors.AfterAttempt) == 0 && len(opts.Interceptors.AfterExecution) == 0 { + return nil + } + + return errors.Join( + stack.Initialize.Add(&smithyhttp.InterceptExecution{ + BeforeExecution: opts.Interceptors.BeforeExecution, + AfterExecution: opts.Interceptors.AfterExecution, + }, middleware.Before), + stack.Serialize.Insert(&smithyhttp.InterceptBeforeSerialization{ + Interceptors: opts.Interceptors.BeforeSerialization, + }, "OperationSerializer", middleware.Before), + stack.Serialize.Insert(&smithyhttp.InterceptAfterSerialization{ + Interceptors: opts.Interceptors.AfterSerialization, + }, "OperationSerializer", middleware.After), + stack.Finalize.Insert(&smithyhttp.InterceptBeforeSigning{ + Interceptors: opts.Interceptors.BeforeSigning, + }, "Signing", middleware.Before), + stack.Finalize.Insert(&smithyhttp.InterceptAfterSigning{ + Interceptors: opts.Interceptors.AfterSigning, + }, "Signing", middleware.After), + stack.Deserialize.Add(&smithyhttp.InterceptTransmit{ + BeforeTransmit: opts.Interceptors.BeforeTransmit, + AfterTransmit: opts.Interceptors.AfterTransmit, + }, middleware.After), + stack.Deserialize.Insert(&smithyhttp.InterceptBeforeDeserialization{ + Interceptors: opts.Interceptors.BeforeDeserialization, + }, "OperationDeserializer", middleware.After), // (deserialize stack is called in reverse) + stack.Deserialize.Insert(&smithyhttp.InterceptAfterDeserialization{ + Interceptors: opts.Interceptors.AfterDeserialization, + }, "OperationDeserializer", middleware.Before), + ) +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/signin/api_op_CreateOAuth2Token.go b/vendor/github.com/aws/aws-sdk-go-v2/service/signin/api_op_CreateOAuth2Token.go new file mode 100644 index 00000000000..54ba42422d0 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/signin/api_op_CreateOAuth2Token.go @@ -0,0 +1,209 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package signin + +import ( + "context" + "fmt" + awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" + "github.com/aws/aws-sdk-go-v2/service/signin/types" + "github.com/aws/smithy-go/middleware" + smithyhttp "github.com/aws/smithy-go/transport/http" +) + +// CreateOAuth2Token API +// +// Path: /v1/token Request Method: POST Content-Type: application/json or +// application/x-www-form-urlencoded +// +// This API implements OAuth 2.0 flows for AWS Sign-In CLI clients, supporting +// both: +// +// - Authorization code redemption (grant_type=authorization_code) - NOT +// idempotent +// - Token refresh (grant_type=refresh_token) - Idempotent within token validity +// window +// +// The operation behavior is determined by the grant_type parameter in the request +// body: +// +// Authorization Code Flow (NOT Idempotent): +// +// - JSON or form-encoded body with client_id, grant_type=authorization_code, +// code, redirect_uri, code_verifier +// - Returns access_token, token_type, expires_in, refresh_token, and id_token +// - Each authorization code can only be used ONCE for security (prevents replay +// attacks) +// +// Token Refresh Flow (Idempotent): +// +// - JSON or form-encoded body with client_id, grant_type=refresh_token, +// refresh_token +// - Returns access_token, token_type, expires_in, and refresh_token (no +// id_token) +// - Multiple calls with same refresh_token return consistent results within +// validity window +// +// Authentication and authorization: +// +// - Confidential clients: sigv4 signing required with signin:ExchangeToken +// permissions +// - CLI clients (public): authn/authz skipped based on client_id & grant_type +// +// Note: This operation cannot be marked as @idempotent because it handles both +// idempotent (token refresh) and non-idempotent (auth code redemption) flows in a +// single endpoint. +func (c *Client) CreateOAuth2Token(ctx context.Context, params *CreateOAuth2TokenInput, optFns ...func(*Options)) (*CreateOAuth2TokenOutput, error) { + if params == nil { + params = &CreateOAuth2TokenInput{} + } + + result, metadata, err := c.invokeOperation(ctx, "CreateOAuth2Token", params, optFns, c.addOperationCreateOAuth2TokenMiddlewares) + if err != nil { + return nil, err + } + + out := result.(*CreateOAuth2TokenOutput) + out.ResultMetadata = metadata + return out, nil +} + +// Input structure for CreateOAuth2Token operation +// +// Contains flattened token operation inputs for both authorization code and +// refresh token flows. The operation type is determined by the grant_type +// parameter in the request body. +type CreateOAuth2TokenInput struct { + + // Flattened token operation inputs The specific operation is determined by + // grant_type in the request body + // + // This member is required. + TokenInput *types.CreateOAuth2TokenRequestBody + + noSmithyDocumentSerde +} + +// Output structure for CreateOAuth2Token operation +// +// Contains flattened token operation outputs for both authorization code and +// refresh token flows. The response content depends on the grant_type from the +// original request. +type CreateOAuth2TokenOutput struct { + + // Flattened token operation outputs The specific response fields depend on the + // grant_type used in the request + // + // This member is required. + TokenOutput *types.CreateOAuth2TokenResponseBody + + // Metadata pertaining to the operation's result. + ResultMetadata middleware.Metadata + + noSmithyDocumentSerde +} + +func (c *Client) addOperationCreateOAuth2TokenMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } + err = stack.Serialize.Add(&awsRestjson1_serializeOpCreateOAuth2Token{}, middleware.After) + if err != nil { + return err + } + err = stack.Deserialize.Add(&awsRestjson1_deserializeOpCreateOAuth2Token{}, middleware.After) + if err != nil { + return err + } + if err := addProtocolFinalizerMiddlewares(stack, options, "CreateOAuth2Token"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + + if err = addlegacyEndpointContextSetter(stack, options); err != nil { + return err + } + if err = addSetLoggerMiddleware(stack, options); err != nil { + return err + } + if err = addClientRequestID(stack); err != nil { + return err + } + if err = addComputeContentLength(stack); err != nil { + return err + } + if err = addResolveEndpointMiddleware(stack, options); err != nil { + return err + } + if err = addRetry(stack, options); err != nil { + return err + } + if err = addRawResponseToMetadata(stack); err != nil { + return err + } + if err = addRecordResponseTiming(stack); err != nil { + return err + } + if err = addSpanRetryLoop(stack, options); err != nil { + return err + } + if err = addClientUserAgent(stack, options); err != nil { + return err + } + if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { + return err + } + if err = addCredentialSource(stack, options); err != nil { + return err + } + if err = addOpCreateOAuth2TokenValidationMiddleware(stack); err != nil { + return err + } + if err = stack.Initialize.Add(newServiceMetadataMiddleware_opCreateOAuth2Token(options.Region), middleware.Before); err != nil { + return err + } + if err = addRecursionDetection(stack); err != nil { + return err + } + if err = addRequestIDRetrieverMiddleware(stack); err != nil { + return err + } + if err = addResponseErrorMiddleware(stack); err != nil { + return err + } + if err = addRequestResponseLogging(stack, options); err != nil { + return err + } + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addInterceptBeforeRetryLoop(stack, options); err != nil { + return err + } + if err = addInterceptAttempt(stack, options); err != nil { + return err + } + if err = addInterceptors(stack, options); err != nil { + return err + } + return nil +} + +func newServiceMetadataMiddleware_opCreateOAuth2Token(region string) *awsmiddleware.RegisterServiceMetadata { + return &awsmiddleware.RegisterServiceMetadata{ + Region: region, + ServiceID: ServiceID, + OperationName: "CreateOAuth2Token", + } +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/signin/auth.go b/vendor/github.com/aws/aws-sdk-go-v2/service/signin/auth.go new file mode 100644 index 00000000000..cf6b3650410 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/signin/auth.go @@ -0,0 +1,351 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package signin + +import ( + "context" + "fmt" + awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" + smithy "github.com/aws/smithy-go" + smithyauth "github.com/aws/smithy-go/auth" + "github.com/aws/smithy-go/metrics" + "github.com/aws/smithy-go/middleware" + "github.com/aws/smithy-go/tracing" + smithyhttp "github.com/aws/smithy-go/transport/http" + "slices" + "strings" +) + +func bindAuthParamsRegion(_ interface{}, params *AuthResolverParameters, _ interface{}, options Options) error { + params.Region = options.Region + return nil +} + +type setLegacyContextSigningOptionsMiddleware struct { +} + +func (*setLegacyContextSigningOptionsMiddleware) ID() string { + return "setLegacyContextSigningOptions" +} + +func (m *setLegacyContextSigningOptionsMiddleware) HandleFinalize(ctx context.Context, in middleware.FinalizeInput, next middleware.FinalizeHandler) ( + out middleware.FinalizeOutput, metadata middleware.Metadata, err error, +) { + rscheme := getResolvedAuthScheme(ctx) + schemeID := rscheme.Scheme.SchemeID() + + if sn := awsmiddleware.GetSigningName(ctx); sn != "" { + if schemeID == "aws.auth#sigv4" { + smithyhttp.SetSigV4SigningName(&rscheme.SignerProperties, sn) + } else if schemeID == "aws.auth#sigv4a" { + smithyhttp.SetSigV4ASigningName(&rscheme.SignerProperties, sn) + } + } + + if sr := awsmiddleware.GetSigningRegion(ctx); sr != "" { + if schemeID == "aws.auth#sigv4" { + smithyhttp.SetSigV4SigningRegion(&rscheme.SignerProperties, sr) + } else if schemeID == "aws.auth#sigv4a" { + smithyhttp.SetSigV4ASigningRegions(&rscheme.SignerProperties, []string{sr}) + } + } + + return next.HandleFinalize(ctx, in) +} + +func addSetLegacyContextSigningOptionsMiddleware(stack *middleware.Stack) error { + return stack.Finalize.Insert(&setLegacyContextSigningOptionsMiddleware{}, "Signing", middleware.Before) +} + +type withAnonymous struct { + resolver AuthSchemeResolver +} + +var _ AuthSchemeResolver = (*withAnonymous)(nil) + +func (v *withAnonymous) ResolveAuthSchemes(ctx context.Context, params *AuthResolverParameters) ([]*smithyauth.Option, error) { + opts, err := v.resolver.ResolveAuthSchemes(ctx, params) + if err != nil { + return nil, err + } + + opts = append(opts, &smithyauth.Option{ + SchemeID: smithyauth.SchemeIDAnonymous, + }) + return opts, nil +} + +func wrapWithAnonymousAuth(options *Options) { + if _, ok := options.AuthSchemeResolver.(*defaultAuthSchemeResolver); !ok { + return + } + + options.AuthSchemeResolver = &withAnonymous{ + resolver: options.AuthSchemeResolver, + } +} + +// AuthResolverParameters contains the set of inputs necessary for auth scheme +// resolution. +type AuthResolverParameters struct { + // The name of the operation being invoked. + Operation string + + // The region in which the operation is being invoked. + Region string +} + +func bindAuthResolverParams(ctx context.Context, operation string, input interface{}, options Options) (*AuthResolverParameters, error) { + params := &AuthResolverParameters{ + Operation: operation, + } + + if err := bindAuthParamsRegion(ctx, params, input, options); err != nil { + return nil, err + } + + return params, nil +} + +// AuthSchemeResolver returns a set of possible authentication options for an +// operation. +type AuthSchemeResolver interface { + ResolveAuthSchemes(context.Context, *AuthResolverParameters) ([]*smithyauth.Option, error) +} + +type defaultAuthSchemeResolver struct{} + +var _ AuthSchemeResolver = (*defaultAuthSchemeResolver)(nil) + +func (*defaultAuthSchemeResolver) ResolveAuthSchemes(ctx context.Context, params *AuthResolverParameters) ([]*smithyauth.Option, error) { + if overrides, ok := operationAuthOptions[params.Operation]; ok { + return overrides(params), nil + } + return serviceAuthOptions(params), nil +} + +var operationAuthOptions = map[string]func(*AuthResolverParameters) []*smithyauth.Option{ + "CreateOAuth2Token": func(params *AuthResolverParameters) []*smithyauth.Option { + return []*smithyauth.Option{ + {SchemeID: smithyauth.SchemeIDAnonymous}, + } + }, +} + +func serviceAuthOptions(params *AuthResolverParameters) []*smithyauth.Option { + return []*smithyauth.Option{ + { + SchemeID: smithyauth.SchemeIDSigV4, + SignerProperties: func() smithy.Properties { + var props smithy.Properties + smithyhttp.SetSigV4SigningName(&props, "signin") + smithyhttp.SetSigV4SigningRegion(&props, params.Region) + return props + }(), + }, + } +} + +type resolveAuthSchemeMiddleware struct { + operation string + options Options +} + +func (*resolveAuthSchemeMiddleware) ID() string { + return "ResolveAuthScheme" +} + +func (m *resolveAuthSchemeMiddleware) HandleFinalize(ctx context.Context, in middleware.FinalizeInput, next middleware.FinalizeHandler) ( + out middleware.FinalizeOutput, metadata middleware.Metadata, err error, +) { + _, span := tracing.StartSpan(ctx, "ResolveAuthScheme") + defer span.End() + + params, err := bindAuthResolverParams(ctx, m.operation, getOperationInput(ctx), m.options) + if err != nil { + return out, metadata, fmt.Errorf("bind auth scheme params: %w", err) + } + options, err := m.options.AuthSchemeResolver.ResolveAuthSchemes(ctx, params) + if err != nil { + return out, metadata, fmt.Errorf("resolve auth scheme: %w", err) + } + + scheme, ok := m.selectScheme(options) + if !ok { + return out, metadata, fmt.Errorf("could not select an auth scheme") + } + + ctx = setResolvedAuthScheme(ctx, scheme) + + span.SetProperty("auth.scheme_id", scheme.Scheme.SchemeID()) + span.End() + return next.HandleFinalize(ctx, in) +} + +func (m *resolveAuthSchemeMiddleware) selectScheme(options []*smithyauth.Option) (*resolvedAuthScheme, bool) { + sorted := sortAuthOptions(options, m.options.AuthSchemePreference) + for _, option := range sorted { + if option.SchemeID == smithyauth.SchemeIDAnonymous { + return newResolvedAuthScheme(smithyhttp.NewAnonymousScheme(), option), true + } + + for _, scheme := range m.options.AuthSchemes { + if scheme.SchemeID() != option.SchemeID { + continue + } + + if scheme.IdentityResolver(m.options) != nil { + return newResolvedAuthScheme(scheme, option), true + } + } + } + + return nil, false +} + +func sortAuthOptions(options []*smithyauth.Option, preferred []string) []*smithyauth.Option { + byPriority := make([]*smithyauth.Option, 0, len(options)) + for _, prefName := range preferred { + for _, option := range options { + optName := option.SchemeID + if parts := strings.Split(option.SchemeID, "#"); len(parts) == 2 { + optName = parts[1] + } + if prefName == optName { + byPriority = append(byPriority, option) + } + } + } + for _, option := range options { + if !slices.ContainsFunc(byPriority, func(o *smithyauth.Option) bool { + return o.SchemeID == option.SchemeID + }) { + byPriority = append(byPriority, option) + } + } + return byPriority +} + +type resolvedAuthSchemeKey struct{} + +type resolvedAuthScheme struct { + Scheme smithyhttp.AuthScheme + IdentityProperties smithy.Properties + SignerProperties smithy.Properties +} + +func newResolvedAuthScheme(scheme smithyhttp.AuthScheme, option *smithyauth.Option) *resolvedAuthScheme { + return &resolvedAuthScheme{ + Scheme: scheme, + IdentityProperties: option.IdentityProperties, + SignerProperties: option.SignerProperties, + } +} + +func setResolvedAuthScheme(ctx context.Context, scheme *resolvedAuthScheme) context.Context { + return middleware.WithStackValue(ctx, resolvedAuthSchemeKey{}, scheme) +} + +func getResolvedAuthScheme(ctx context.Context) *resolvedAuthScheme { + v, _ := middleware.GetStackValue(ctx, resolvedAuthSchemeKey{}).(*resolvedAuthScheme) + return v +} + +type getIdentityMiddleware struct { + options Options +} + +func (*getIdentityMiddleware) ID() string { + return "GetIdentity" +} + +func (m *getIdentityMiddleware) HandleFinalize(ctx context.Context, in middleware.FinalizeInput, next middleware.FinalizeHandler) ( + out middleware.FinalizeOutput, metadata middleware.Metadata, err error, +) { + innerCtx, span := tracing.StartSpan(ctx, "GetIdentity") + defer span.End() + + rscheme := getResolvedAuthScheme(innerCtx) + if rscheme == nil { + return out, metadata, fmt.Errorf("no resolved auth scheme") + } + + resolver := rscheme.Scheme.IdentityResolver(m.options) + if resolver == nil { + return out, metadata, fmt.Errorf("no identity resolver") + } + + identity, err := timeOperationMetric(ctx, "client.call.resolve_identity_duration", + func() (smithyauth.Identity, error) { + return resolver.GetIdentity(innerCtx, rscheme.IdentityProperties) + }, + func(o *metrics.RecordMetricOptions) { + o.Properties.Set("auth.scheme_id", rscheme.Scheme.SchemeID()) + }) + if err != nil { + return out, metadata, fmt.Errorf("get identity: %w", err) + } + + ctx = setIdentity(ctx, identity) + + span.End() + return next.HandleFinalize(ctx, in) +} + +type identityKey struct{} + +func setIdentity(ctx context.Context, identity smithyauth.Identity) context.Context { + return middleware.WithStackValue(ctx, identityKey{}, identity) +} + +func getIdentity(ctx context.Context) smithyauth.Identity { + v, _ := middleware.GetStackValue(ctx, identityKey{}).(smithyauth.Identity) + return v +} + +type signRequestMiddleware struct { + options Options +} + +func (*signRequestMiddleware) ID() string { + return "Signing" +} + +func (m *signRequestMiddleware) HandleFinalize(ctx context.Context, in middleware.FinalizeInput, next middleware.FinalizeHandler) ( + out middleware.FinalizeOutput, metadata middleware.Metadata, err error, +) { + _, span := tracing.StartSpan(ctx, "SignRequest") + defer span.End() + + req, ok := in.Request.(*smithyhttp.Request) + if !ok { + return out, metadata, fmt.Errorf("unexpected transport type %T", in.Request) + } + + rscheme := getResolvedAuthScheme(ctx) + if rscheme == nil { + return out, metadata, fmt.Errorf("no resolved auth scheme") + } + + identity := getIdentity(ctx) + if identity == nil { + return out, metadata, fmt.Errorf("no identity") + } + + signer := rscheme.Scheme.Signer() + if signer == nil { + return out, metadata, fmt.Errorf("no signer") + } + + _, err = timeOperationMetric(ctx, "client.call.signing_duration", func() (any, error) { + return nil, signer.SignRequest(ctx, req, identity, rscheme.SignerProperties) + }, func(o *metrics.RecordMetricOptions) { + o.Properties.Set("auth.scheme_id", rscheme.Scheme.SchemeID()) + }) + if err != nil { + return out, metadata, fmt.Errorf("sign request: %w", err) + } + + span.End() + return next.HandleFinalize(ctx, in) +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/signin/deserializers.go b/vendor/github.com/aws/aws-sdk-go-v2/service/signin/deserializers.go new file mode 100644 index 00000000000..b74b612e6b0 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/signin/deserializers.go @@ -0,0 +1,655 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package signin + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "github.com/aws/aws-sdk-go-v2/aws/protocol/restjson" + "github.com/aws/aws-sdk-go-v2/service/signin/types" + smithy "github.com/aws/smithy-go" + smithyio "github.com/aws/smithy-go/io" + "github.com/aws/smithy-go/middleware" + "github.com/aws/smithy-go/ptr" + "github.com/aws/smithy-go/tracing" + smithyhttp "github.com/aws/smithy-go/transport/http" + "io" + "strings" +) + +type awsRestjson1_deserializeOpCreateOAuth2Token struct { +} + +func (*awsRestjson1_deserializeOpCreateOAuth2Token) ID() string { + return "OperationDeserializer" +} + +func (m *awsRestjson1_deserializeOpCreateOAuth2Token) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( + out middleware.DeserializeOutput, metadata middleware.Metadata, err error, +) { + out, metadata, err = next.HandleDeserialize(ctx, in) + if err != nil { + return out, metadata, err + } + + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() + response, ok := out.RawResponse.(*smithyhttp.Response) + if !ok { + return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} + } + + if response.StatusCode < 200 || response.StatusCode >= 300 { + return out, metadata, awsRestjson1_deserializeOpErrorCreateOAuth2Token(response, &metadata) + } + output := &CreateOAuth2TokenOutput{} + out.Result = output + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(response.Body, ringBuffer) + + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + err = awsRestjson1_deserializeDocumentCreateOAuth2TokenResponseBody(&output.TokenOutput, shape) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + return out, metadata, &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body with invalid JSON, %w", err), + Snapshot: snapshot.Bytes(), + } + } + + span.End() + return out, metadata, err +} + +func awsRestjson1_deserializeOpErrorCreateOAuth2Token(response *smithyhttp.Response, metadata *middleware.Metadata) error { + var errorBuffer bytes.Buffer + if _, err := io.Copy(&errorBuffer, response.Body); err != nil { + return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} + } + errorBody := bytes.NewReader(errorBuffer.Bytes()) + + errorCode := "UnknownError" + errorMessage := errorCode + + headerCode := response.Header.Get("X-Amzn-ErrorType") + if len(headerCode) != 0 { + errorCode = restjson.SanitizeErrorCode(headerCode) + } + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + jsonCode, message, err := restjson.GetErrorInfo(decoder) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + if len(headerCode) == 0 && len(jsonCode) != 0 { + errorCode = restjson.SanitizeErrorCode(jsonCode) + } + if len(message) != 0 { + errorMessage = message + } + + switch { + case strings.EqualFold("AccessDeniedException", errorCode): + return awsRestjson1_deserializeErrorAccessDeniedException(response, errorBody) + + case strings.EqualFold("InternalServerException", errorCode): + return awsRestjson1_deserializeErrorInternalServerException(response, errorBody) + + case strings.EqualFold("TooManyRequestsError", errorCode): + return awsRestjson1_deserializeErrorTooManyRequestsError(response, errorBody) + + case strings.EqualFold("ValidationException", errorCode): + return awsRestjson1_deserializeErrorValidationException(response, errorBody) + + default: + genericError := &smithy.GenericAPIError{ + Code: errorCode, + Message: errorMessage, + } + return genericError + + } +} + +func awsRestjson1_deserializeOpDocumentCreateOAuth2TokenOutput(v **CreateOAuth2TokenOutput, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *CreateOAuth2TokenOutput + if *v == nil { + sv = &CreateOAuth2TokenOutput{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "tokenOutput": + if err := awsRestjson1_deserializeDocumentCreateOAuth2TokenResponseBody(&sv.TokenOutput, value); err != nil { + return err + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsRestjson1_deserializeErrorAccessDeniedException(response *smithyhttp.Response, errorBody *bytes.Reader) error { + output := &types.AccessDeniedException{} + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + err := awsRestjson1_deserializeDocumentAccessDeniedException(&output, shape) + + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + + return output +} + +func awsRestjson1_deserializeErrorInternalServerException(response *smithyhttp.Response, errorBody *bytes.Reader) error { + output := &types.InternalServerException{} + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + err := awsRestjson1_deserializeDocumentInternalServerException(&output, shape) + + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + + return output +} + +func awsRestjson1_deserializeErrorTooManyRequestsError(response *smithyhttp.Response, errorBody *bytes.Reader) error { + output := &types.TooManyRequestsError{} + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + err := awsRestjson1_deserializeDocumentTooManyRequestsError(&output, shape) + + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + + return output +} + +func awsRestjson1_deserializeErrorValidationException(response *smithyhttp.Response, errorBody *bytes.Reader) error { + output := &types.ValidationException{} + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + + body := io.TeeReader(errorBody, ringBuffer) + decoder := json.NewDecoder(body) + decoder.UseNumber() + var shape interface{} + if err := decoder.Decode(&shape); err != nil && err != io.EOF { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + err := awsRestjson1_deserializeDocumentValidationException(&output, shape) + + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return err + } + + errorBody.Seek(0, io.SeekStart) + + return output +} + +func awsRestjson1_deserializeDocumentAccessDeniedException(v **types.AccessDeniedException, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.AccessDeniedException + if *v == nil { + sv = &types.AccessDeniedException{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "error": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected OAuth2ErrorCode to be of type string, got %T instead", value) + } + sv.Error_ = types.OAuth2ErrorCode(jtv) + } + + case "message", "Message": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected String to be of type string, got %T instead", value) + } + sv.Message = ptr.String(jtv) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsRestjson1_deserializeDocumentAccessToken(v **types.AccessToken, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.AccessToken + if *v == nil { + sv = &types.AccessToken{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "accessKeyId": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected String to be of type string, got %T instead", value) + } + sv.AccessKeyId = ptr.String(jtv) + } + + case "secretAccessKey": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected String to be of type string, got %T instead", value) + } + sv.SecretAccessKey = ptr.String(jtv) + } + + case "sessionToken": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected String to be of type string, got %T instead", value) + } + sv.SessionToken = ptr.String(jtv) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsRestjson1_deserializeDocumentCreateOAuth2TokenResponseBody(v **types.CreateOAuth2TokenResponseBody, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.CreateOAuth2TokenResponseBody + if *v == nil { + sv = &types.CreateOAuth2TokenResponseBody{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "accessToken": + if err := awsRestjson1_deserializeDocumentAccessToken(&sv.AccessToken, value); err != nil { + return err + } + + case "expiresIn": + if value != nil { + jtv, ok := value.(json.Number) + if !ok { + return fmt.Errorf("expected ExpiresIn to be json.Number, got %T instead", value) + } + i64, err := jtv.Int64() + if err != nil { + return err + } + sv.ExpiresIn = ptr.Int32(int32(i64)) + } + + case "idToken": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected IdToken to be of type string, got %T instead", value) + } + sv.IdToken = ptr.String(jtv) + } + + case "refreshToken": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected RefreshToken to be of type string, got %T instead", value) + } + sv.RefreshToken = ptr.String(jtv) + } + + case "tokenType": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected TokenType to be of type string, got %T instead", value) + } + sv.TokenType = ptr.String(jtv) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsRestjson1_deserializeDocumentInternalServerException(v **types.InternalServerException, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.InternalServerException + if *v == nil { + sv = &types.InternalServerException{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "error": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected OAuth2ErrorCode to be of type string, got %T instead", value) + } + sv.Error_ = types.OAuth2ErrorCode(jtv) + } + + case "message", "Message": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected String to be of type string, got %T instead", value) + } + sv.Message = ptr.String(jtv) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsRestjson1_deserializeDocumentTooManyRequestsError(v **types.TooManyRequestsError, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.TooManyRequestsError + if *v == nil { + sv = &types.TooManyRequestsError{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "error": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected OAuth2ErrorCode to be of type string, got %T instead", value) + } + sv.Error_ = types.OAuth2ErrorCode(jtv) + } + + case "message", "Message": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected String to be of type string, got %T instead", value) + } + sv.Message = ptr.String(jtv) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} + +func awsRestjson1_deserializeDocumentValidationException(v **types.ValidationException, value interface{}) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + if value == nil { + return nil + } + + shape, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected JSON type %v", value) + } + + var sv *types.ValidationException + if *v == nil { + sv = &types.ValidationException{} + } else { + sv = *v + } + + for key, value := range shape { + switch key { + case "error": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected OAuth2ErrorCode to be of type string, got %T instead", value) + } + sv.Error_ = types.OAuth2ErrorCode(jtv) + } + + case "message", "Message": + if value != nil { + jtv, ok := value.(string) + if !ok { + return fmt.Errorf("expected String to be of type string, got %T instead", value) + } + sv.Message = ptr.String(jtv) + } + + default: + _, _ = key, value + + } + } + *v = sv + return nil +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/signin/doc.go b/vendor/github.com/aws/aws-sdk-go-v2/service/signin/doc.go new file mode 100644 index 00000000000..dc1a8b62f09 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/signin/doc.go @@ -0,0 +1,9 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +// Package signin provides the API client, operations, and parameter types for AWS +// Sign-In Service. +// +// AWS Sign-In manages authentication for AWS services. This service provides +// secure authentication flows for accessing AWS resources from the console and +// developer tools. +package signin diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/signin/endpoints.go b/vendor/github.com/aws/aws-sdk-go-v2/service/signin/endpoints.go new file mode 100644 index 00000000000..db2e6a62a38 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/signin/endpoints.go @@ -0,0 +1,624 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package signin + +import ( + "context" + "errors" + "fmt" + "github.com/aws/aws-sdk-go-v2/aws" + awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" + internalConfig "github.com/aws/aws-sdk-go-v2/internal/configsources" + "github.com/aws/aws-sdk-go-v2/internal/endpoints" + "github.com/aws/aws-sdk-go-v2/internal/endpoints/awsrulesfn" + internalendpoints "github.com/aws/aws-sdk-go-v2/service/signin/internal/endpoints" + smithyauth "github.com/aws/smithy-go/auth" + smithyendpoints "github.com/aws/smithy-go/endpoints" + "github.com/aws/smithy-go/endpoints/private/rulesfn" + "github.com/aws/smithy-go/middleware" + "github.com/aws/smithy-go/ptr" + "github.com/aws/smithy-go/tracing" + smithyhttp "github.com/aws/smithy-go/transport/http" + "net/http" + "net/url" + "os" + "strings" +) + +// EndpointResolverOptions is the service endpoint resolver options +type EndpointResolverOptions = internalendpoints.Options + +// EndpointResolver interface for resolving service endpoints. +type EndpointResolver interface { + ResolveEndpoint(region string, options EndpointResolverOptions) (aws.Endpoint, error) +} + +var _ EndpointResolver = &internalendpoints.Resolver{} + +// NewDefaultEndpointResolver constructs a new service endpoint resolver +func NewDefaultEndpointResolver() *internalendpoints.Resolver { + return internalendpoints.New() +} + +// EndpointResolverFunc is a helper utility that wraps a function so it satisfies +// the EndpointResolver interface. This is useful when you want to add additional +// endpoint resolving logic, or stub out specific endpoints with custom values. +type EndpointResolverFunc func(region string, options EndpointResolverOptions) (aws.Endpoint, error) + +func (fn EndpointResolverFunc) ResolveEndpoint(region string, options EndpointResolverOptions) (endpoint aws.Endpoint, err error) { + return fn(region, options) +} + +// EndpointResolverFromURL returns an EndpointResolver configured using the +// provided endpoint url. By default, the resolved endpoint resolver uses the +// client region as signing region, and the endpoint source is set to +// EndpointSourceCustom.You can provide functional options to configure endpoint +// values for the resolved endpoint. +func EndpointResolverFromURL(url string, optFns ...func(*aws.Endpoint)) EndpointResolver { + e := aws.Endpoint{URL: url, Source: aws.EndpointSourceCustom} + for _, fn := range optFns { + fn(&e) + } + + return EndpointResolverFunc( + func(region string, options EndpointResolverOptions) (aws.Endpoint, error) { + if len(e.SigningRegion) == 0 { + e.SigningRegion = region + } + return e, nil + }, + ) +} + +type ResolveEndpoint struct { + Resolver EndpointResolver + Options EndpointResolverOptions +} + +func (*ResolveEndpoint) ID() string { + return "ResolveEndpoint" +} + +func (m *ResolveEndpoint) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( + out middleware.SerializeOutput, metadata middleware.Metadata, err error, +) { + if !awsmiddleware.GetRequiresLegacyEndpoints(ctx) { + return next.HandleSerialize(ctx, in) + } + + req, ok := in.Request.(*smithyhttp.Request) + if !ok { + return out, metadata, fmt.Errorf("unknown transport type %T", in.Request) + } + + if m.Resolver == nil { + return out, metadata, fmt.Errorf("expected endpoint resolver to not be nil") + } + + eo := m.Options + eo.Logger = middleware.GetLogger(ctx) + + var endpoint aws.Endpoint + endpoint, err = m.Resolver.ResolveEndpoint(awsmiddleware.GetRegion(ctx), eo) + if err != nil { + nf := (&aws.EndpointNotFoundError{}) + if errors.As(err, &nf) { + ctx = awsmiddleware.SetRequiresLegacyEndpoints(ctx, false) + return next.HandleSerialize(ctx, in) + } + return out, metadata, fmt.Errorf("failed to resolve service endpoint, %w", err) + } + + req.URL, err = url.Parse(endpoint.URL) + if err != nil { + return out, metadata, fmt.Errorf("failed to parse endpoint URL: %w", err) + } + + if len(awsmiddleware.GetSigningName(ctx)) == 0 { + signingName := endpoint.SigningName + if len(signingName) == 0 { + signingName = "signin" + } + ctx = awsmiddleware.SetSigningName(ctx, signingName) + } + ctx = awsmiddleware.SetEndpointSource(ctx, endpoint.Source) + ctx = smithyhttp.SetHostnameImmutable(ctx, endpoint.HostnameImmutable) + ctx = awsmiddleware.SetSigningRegion(ctx, endpoint.SigningRegion) + ctx = awsmiddleware.SetPartitionID(ctx, endpoint.PartitionID) + return next.HandleSerialize(ctx, in) +} +func addResolveEndpointMiddleware(stack *middleware.Stack, o Options) error { + return stack.Serialize.Insert(&ResolveEndpoint{ + Resolver: o.EndpointResolver, + Options: o.EndpointOptions, + }, "OperationSerializer", middleware.Before) +} + +func removeResolveEndpointMiddleware(stack *middleware.Stack) error { + _, err := stack.Serialize.Remove((&ResolveEndpoint{}).ID()) + return err +} + +type wrappedEndpointResolver struct { + awsResolver aws.EndpointResolverWithOptions +} + +func (w *wrappedEndpointResolver) ResolveEndpoint(region string, options EndpointResolverOptions) (endpoint aws.Endpoint, err error) { + return w.awsResolver.ResolveEndpoint(ServiceID, region, options) +} + +type awsEndpointResolverAdaptor func(service, region string) (aws.Endpoint, error) + +func (a awsEndpointResolverAdaptor) ResolveEndpoint(service, region string, options ...interface{}) (aws.Endpoint, error) { + return a(service, region) +} + +var _ aws.EndpointResolverWithOptions = awsEndpointResolverAdaptor(nil) + +// withEndpointResolver returns an aws.EndpointResolverWithOptions that first delegates endpoint resolution to the awsResolver. +// If awsResolver returns aws.EndpointNotFoundError error, the v1 resolver middleware will swallow the error, +// and set an appropriate context flag such that fallback will occur when EndpointResolverV2 is invoked +// via its middleware. +// +// If another error (besides aws.EndpointNotFoundError) is returned, then that error will be propagated. +func withEndpointResolver(awsResolver aws.EndpointResolver, awsResolverWithOptions aws.EndpointResolverWithOptions) EndpointResolver { + var resolver aws.EndpointResolverWithOptions + + if awsResolverWithOptions != nil { + resolver = awsResolverWithOptions + } else if awsResolver != nil { + resolver = awsEndpointResolverAdaptor(awsResolver.ResolveEndpoint) + } + + return &wrappedEndpointResolver{ + awsResolver: resolver, + } +} + +func finalizeClientEndpointResolverOptions(options *Options) { + options.EndpointOptions.LogDeprecated = options.ClientLogMode.IsDeprecatedUsage() + + if len(options.EndpointOptions.ResolvedRegion) == 0 { + const fipsInfix = "-fips-" + const fipsPrefix = "fips-" + const fipsSuffix = "-fips" + + if strings.Contains(options.Region, fipsInfix) || + strings.Contains(options.Region, fipsPrefix) || + strings.Contains(options.Region, fipsSuffix) { + options.EndpointOptions.ResolvedRegion = strings.ReplaceAll(strings.ReplaceAll(strings.ReplaceAll( + options.Region, fipsInfix, "-"), fipsPrefix, ""), fipsSuffix, "") + options.EndpointOptions.UseFIPSEndpoint = aws.FIPSEndpointStateEnabled + } + } + +} + +func resolveEndpointResolverV2(options *Options) { + if options.EndpointResolverV2 == nil { + options.EndpointResolverV2 = NewDefaultEndpointResolverV2() + } +} + +func resolveBaseEndpoint(cfg aws.Config, o *Options) { + if cfg.BaseEndpoint != nil { + o.BaseEndpoint = cfg.BaseEndpoint + } + + _, g := os.LookupEnv("AWS_ENDPOINT_URL") + _, s := os.LookupEnv("AWS_ENDPOINT_URL_SIGNIN") + + if g && !s { + return + } + + value, found, err := internalConfig.ResolveServiceBaseEndpoint(context.Background(), "Signin", cfg.ConfigSources) + if found && err == nil { + o.BaseEndpoint = &value + } +} + +func bindRegion(region string) (*string, error) { + if region == "" { + return nil, nil + } + if !rulesfn.IsValidHostLabel(region, true) { + return nil, fmt.Errorf("invalid input region %s", region) + } + + return aws.String(endpoints.MapFIPSRegion(region)), nil +} + +// EndpointParameters provides the parameters that influence how endpoints are +// resolved. +type EndpointParameters struct { + // When true, use the dual-stack endpoint. If the configured endpoint does not + // support dual-stack, dispatching the request MAY return an error. + // + // Defaults to + // false if no value is provided. + // + // AWS::UseDualStack + UseDualStack *bool + + // When true, send this request to the FIPS-compliant regional endpoint. If the + // configured endpoint does not have a FIPS compliant endpoint, dispatching the + // request will return an error. + // + // Defaults to false if no value is + // provided. + // + // AWS::UseFIPS + UseFIPS *bool + + // Override the endpoint used to send this request + // + // Parameter is + // required. + // + // SDK::Endpoint + Endpoint *string + + // The AWS region used to dispatch the request. + // + // Parameter is + // required. + // + // AWS::Region + Region *string +} + +// ValidateRequired validates required parameters are set. +func (p EndpointParameters) ValidateRequired() error { + if p.UseDualStack == nil { + return fmt.Errorf("parameter UseDualStack is required") + } + + if p.UseFIPS == nil { + return fmt.Errorf("parameter UseFIPS is required") + } + + return nil +} + +// WithDefaults returns a shallow copy of EndpointParameterswith default values +// applied to members where applicable. +func (p EndpointParameters) WithDefaults() EndpointParameters { + if p.UseDualStack == nil { + p.UseDualStack = ptr.Bool(false) + } + + if p.UseFIPS == nil { + p.UseFIPS = ptr.Bool(false) + } + return p +} + +type stringSlice []string + +func (s stringSlice) Get(i int) *string { + if i < 0 || i >= len(s) { + return nil + } + + v := s[i] + return &v +} + +// EndpointResolverV2 provides the interface for resolving service endpoints. +type EndpointResolverV2 interface { + // ResolveEndpoint attempts to resolve the endpoint with the provided options, + // returning the endpoint if found. Otherwise an error is returned. + ResolveEndpoint(ctx context.Context, params EndpointParameters) ( + smithyendpoints.Endpoint, error, + ) +} + +// resolver provides the implementation for resolving endpoints. +type resolver struct{} + +func NewDefaultEndpointResolverV2() EndpointResolverV2 { + return &resolver{} +} + +// ResolveEndpoint attempts to resolve the endpoint with the provided options, +// returning the endpoint if found. Otherwise an error is returned. +func (r *resolver) ResolveEndpoint( + ctx context.Context, params EndpointParameters, +) ( + endpoint smithyendpoints.Endpoint, err error, +) { + params = params.WithDefaults() + if err = params.ValidateRequired(); err != nil { + return endpoint, fmt.Errorf("endpoint parameters are not valid, %w", err) + } + _UseDualStack := *params.UseDualStack + _ = _UseDualStack + _UseFIPS := *params.UseFIPS + _ = _UseFIPS + + if exprVal := params.Endpoint; exprVal != nil { + _Endpoint := *exprVal + _ = _Endpoint + if _UseFIPS == true { + return endpoint, fmt.Errorf("endpoint rule error, %s", "Invalid Configuration: FIPS and custom endpoint are not supported") + } + if _UseDualStack == true { + return endpoint, fmt.Errorf("endpoint rule error, %s", "Invalid Configuration: Dualstack and custom endpoint are not supported") + } + uriString := _Endpoint + + uri, err := url.Parse(uriString) + if err != nil { + return endpoint, fmt.Errorf("Failed to parse uri: %s", uriString) + } + + return smithyendpoints.Endpoint{ + URI: *uri, + Headers: http.Header{}, + }, nil + } + if exprVal := params.Region; exprVal != nil { + _Region := *exprVal + _ = _Region + if exprVal := awsrulesfn.GetPartition(_Region); exprVal != nil { + _PartitionResult := *exprVal + _ = _PartitionResult + if _PartitionResult.Name == "aws" { + if _UseFIPS == false { + if _UseDualStack == false { + uriString := func() string { + var out strings.Builder + out.WriteString("https://") + out.WriteString(_Region) + out.WriteString(".signin.aws.amazon.com") + return out.String() + }() + + uri, err := url.Parse(uriString) + if err != nil { + return endpoint, fmt.Errorf("Failed to parse uri: %s", uriString) + } + + return smithyendpoints.Endpoint{ + URI: *uri, + Headers: http.Header{}, + }, nil + } + } + } + if _PartitionResult.Name == "aws-cn" { + if _UseFIPS == false { + if _UseDualStack == false { + uriString := func() string { + var out strings.Builder + out.WriteString("https://") + out.WriteString(_Region) + out.WriteString(".signin.amazonaws.cn") + return out.String() + }() + + uri, err := url.Parse(uriString) + if err != nil { + return endpoint, fmt.Errorf("Failed to parse uri: %s", uriString) + } + + return smithyendpoints.Endpoint{ + URI: *uri, + Headers: http.Header{}, + }, nil + } + } + } + if _PartitionResult.Name == "aws-us-gov" { + if _UseFIPS == false { + if _UseDualStack == false { + uriString := func() string { + var out strings.Builder + out.WriteString("https://") + out.WriteString(_Region) + out.WriteString(".signin.amazonaws-us-gov.com") + return out.String() + }() + + uri, err := url.Parse(uriString) + if err != nil { + return endpoint, fmt.Errorf("Failed to parse uri: %s", uriString) + } + + return smithyendpoints.Endpoint{ + URI: *uri, + Headers: http.Header{}, + }, nil + } + } + } + if _UseFIPS == true { + if _UseDualStack == true { + if true == _PartitionResult.SupportsFIPS { + if true == _PartitionResult.SupportsDualStack { + uriString := func() string { + var out strings.Builder + out.WriteString("https://signin-fips.") + out.WriteString(_Region) + out.WriteString(".") + out.WriteString(_PartitionResult.DualStackDnsSuffix) + return out.String() + }() + + uri, err := url.Parse(uriString) + if err != nil { + return endpoint, fmt.Errorf("Failed to parse uri: %s", uriString) + } + + return smithyendpoints.Endpoint{ + URI: *uri, + Headers: http.Header{}, + }, nil + } + } + return endpoint, fmt.Errorf("endpoint rule error, %s", "FIPS and DualStack are enabled, but this partition does not support one or both") + } + } + if _UseFIPS == true { + if _UseDualStack == false { + if _PartitionResult.SupportsFIPS == true { + uriString := func() string { + var out strings.Builder + out.WriteString("https://signin-fips.") + out.WriteString(_Region) + out.WriteString(".") + out.WriteString(_PartitionResult.DnsSuffix) + return out.String() + }() + + uri, err := url.Parse(uriString) + if err != nil { + return endpoint, fmt.Errorf("Failed to parse uri: %s", uriString) + } + + return smithyendpoints.Endpoint{ + URI: *uri, + Headers: http.Header{}, + }, nil + } + return endpoint, fmt.Errorf("endpoint rule error, %s", "FIPS is enabled but this partition does not support FIPS") + } + } + if _UseFIPS == false { + if _UseDualStack == true { + if true == _PartitionResult.SupportsDualStack { + uriString := func() string { + var out strings.Builder + out.WriteString("https://signin.") + out.WriteString(_Region) + out.WriteString(".") + out.WriteString(_PartitionResult.DualStackDnsSuffix) + return out.String() + }() + + uri, err := url.Parse(uriString) + if err != nil { + return endpoint, fmt.Errorf("Failed to parse uri: %s", uriString) + } + + return smithyendpoints.Endpoint{ + URI: *uri, + Headers: http.Header{}, + }, nil + } + return endpoint, fmt.Errorf("endpoint rule error, %s", "DualStack is enabled but this partition does not support DualStack") + } + } + uriString := func() string { + var out strings.Builder + out.WriteString("https://signin.") + out.WriteString(_Region) + out.WriteString(".") + out.WriteString(_PartitionResult.DnsSuffix) + return out.String() + }() + + uri, err := url.Parse(uriString) + if err != nil { + return endpoint, fmt.Errorf("Failed to parse uri: %s", uriString) + } + + return smithyendpoints.Endpoint{ + URI: *uri, + Headers: http.Header{}, + }, nil + } + return endpoint, fmt.Errorf("Endpoint resolution failed. Invalid operation or environment input.") + } + return endpoint, fmt.Errorf("endpoint rule error, %s", "Invalid Configuration: Missing Region") +} + +type endpointParamsBinder interface { + bindEndpointParams(*EndpointParameters) +} + +func bindEndpointParams(ctx context.Context, input interface{}, options Options) (*EndpointParameters, error) { + params := &EndpointParameters{} + + params.UseDualStack = aws.Bool(options.EndpointOptions.UseDualStackEndpoint == aws.DualStackEndpointStateEnabled) + params.UseFIPS = aws.Bool(options.EndpointOptions.UseFIPSEndpoint == aws.FIPSEndpointStateEnabled) + params.Endpoint = options.BaseEndpoint + region, err := bindRegion(options.Region) + if err != nil { + return nil, err + } + params.Region = region + + if b, ok := input.(endpointParamsBinder); ok { + b.bindEndpointParams(params) + } + + return params, nil +} + +type resolveEndpointV2Middleware struct { + options Options +} + +func (*resolveEndpointV2Middleware) ID() string { + return "ResolveEndpointV2" +} + +func (m *resolveEndpointV2Middleware) HandleFinalize(ctx context.Context, in middleware.FinalizeInput, next middleware.FinalizeHandler) ( + out middleware.FinalizeOutput, metadata middleware.Metadata, err error, +) { + _, span := tracing.StartSpan(ctx, "ResolveEndpoint") + defer span.End() + + if awsmiddleware.GetRequiresLegacyEndpoints(ctx) { + return next.HandleFinalize(ctx, in) + } + + req, ok := in.Request.(*smithyhttp.Request) + if !ok { + return out, metadata, fmt.Errorf("unknown transport type %T", in.Request) + } + + if m.options.EndpointResolverV2 == nil { + return out, metadata, fmt.Errorf("expected endpoint resolver to not be nil") + } + + params, err := bindEndpointParams(ctx, getOperationInput(ctx), m.options) + if err != nil { + return out, metadata, fmt.Errorf("failed to bind endpoint params, %w", err) + } + endpt, err := timeOperationMetric(ctx, "client.call.resolve_endpoint_duration", + func() (smithyendpoints.Endpoint, error) { + return m.options.EndpointResolverV2.ResolveEndpoint(ctx, *params) + }) + if err != nil { + return out, metadata, fmt.Errorf("failed to resolve service endpoint, %w", err) + } + + span.SetProperty("client.call.resolved_endpoint", endpt.URI.String()) + + if endpt.URI.RawPath == "" && req.URL.RawPath != "" { + endpt.URI.RawPath = endpt.URI.Path + } + req.URL.Scheme = endpt.URI.Scheme + req.URL.Host = endpt.URI.Host + req.URL.Path = smithyhttp.JoinPath(endpt.URI.Path, req.URL.Path) + req.URL.RawPath = smithyhttp.JoinPath(endpt.URI.RawPath, req.URL.RawPath) + for k := range endpt.Headers { + req.Header.Set(k, endpt.Headers.Get(k)) + } + + rscheme := getResolvedAuthScheme(ctx) + if rscheme == nil { + return out, metadata, fmt.Errorf("no resolved auth scheme") + } + + opts, _ := smithyauth.GetAuthOptions(&endpt.Properties) + for _, o := range opts { + rscheme.SignerProperties.SetAll(&o.SignerProperties) + } + + span.End() + return next.HandleFinalize(ctx, in) +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/signin/generated.json b/vendor/github.com/aws/aws-sdk-go-v2/service/signin/generated.json new file mode 100644 index 00000000000..8014c56167c --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/signin/generated.json @@ -0,0 +1,34 @@ +{ + "dependencies": { + "github.com/aws/aws-sdk-go-v2": "v1.4.0", + "github.com/aws/aws-sdk-go-v2/internal/configsources": "v0.0.0-00010101000000-000000000000", + "github.com/aws/aws-sdk-go-v2/internal/endpoints/v2": "v2.0.0-00010101000000-000000000000", + "github.com/aws/smithy-go": "v1.4.0" + }, + "files": [ + "api_client.go", + "api_client_test.go", + "api_op_CreateOAuth2Token.go", + "auth.go", + "deserializers.go", + "doc.go", + "endpoints.go", + "endpoints_config_test.go", + "endpoints_test.go", + "generated.json", + "internal/endpoints/endpoints.go", + "internal/endpoints/endpoints_test.go", + "options.go", + "protocol_test.go", + "serializers.go", + "snapshot_test.go", + "sra_operation_order_test.go", + "types/enums.go", + "types/errors.go", + "types/types.go", + "validators.go" + ], + "go": "1.23", + "module": "github.com/aws/aws-sdk-go-v2/service/signin", + "unstable": false +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/signin/go_module_metadata.go b/vendor/github.com/aws/aws-sdk-go-v2/service/signin/go_module_metadata.go new file mode 100644 index 00000000000..2424c057e8e --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/signin/go_module_metadata.go @@ -0,0 +1,6 @@ +// Code generated by internal/repotools/cmd/updatemodulemeta DO NOT EDIT. + +package signin + +// goModuleVersion is the tagged release for this module +const goModuleVersion = "1.0.4" diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/signin/internal/endpoints/endpoints.go b/vendor/github.com/aws/aws-sdk-go-v2/service/signin/internal/endpoints/endpoints.go new file mode 100644 index 00000000000..cfb2efea8a3 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/signin/internal/endpoints/endpoints.go @@ -0,0 +1,333 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package endpoints + +import ( + "github.com/aws/aws-sdk-go-v2/aws" + endpoints "github.com/aws/aws-sdk-go-v2/internal/endpoints/v2" + "github.com/aws/smithy-go/logging" + "regexp" +) + +// Options is the endpoint resolver configuration options +type Options struct { + // Logger is a logging implementation that log events should be sent to. + Logger logging.Logger + + // LogDeprecated indicates that deprecated endpoints should be logged to the + // provided logger. + LogDeprecated bool + + // ResolvedRegion is used to override the region to be resolved, rather then the + // using the value passed to the ResolveEndpoint method. This value is used by the + // SDK to translate regions like fips-us-east-1 or us-east-1-fips to an alternative + // name. You must not set this value directly in your application. + ResolvedRegion string + + // DisableHTTPS informs the resolver to return an endpoint that does not use the + // HTTPS scheme. + DisableHTTPS bool + + // UseDualStackEndpoint specifies the resolver must resolve a dual-stack endpoint. + UseDualStackEndpoint aws.DualStackEndpointState + + // UseFIPSEndpoint specifies the resolver must resolve a FIPS endpoint. + UseFIPSEndpoint aws.FIPSEndpointState +} + +func (o Options) GetResolvedRegion() string { + return o.ResolvedRegion +} + +func (o Options) GetDisableHTTPS() bool { + return o.DisableHTTPS +} + +func (o Options) GetUseDualStackEndpoint() aws.DualStackEndpointState { + return o.UseDualStackEndpoint +} + +func (o Options) GetUseFIPSEndpoint() aws.FIPSEndpointState { + return o.UseFIPSEndpoint +} + +func transformToSharedOptions(options Options) endpoints.Options { + return endpoints.Options{ + Logger: options.Logger, + LogDeprecated: options.LogDeprecated, + ResolvedRegion: options.ResolvedRegion, + DisableHTTPS: options.DisableHTTPS, + UseDualStackEndpoint: options.UseDualStackEndpoint, + UseFIPSEndpoint: options.UseFIPSEndpoint, + } +} + +// Resolver Signin endpoint resolver +type Resolver struct { + partitions endpoints.Partitions +} + +// ResolveEndpoint resolves the service endpoint for the given region and options +func (r *Resolver) ResolveEndpoint(region string, options Options) (endpoint aws.Endpoint, err error) { + if len(region) == 0 { + return endpoint, &aws.MissingRegionError{} + } + + opt := transformToSharedOptions(options) + return r.partitions.ResolveEndpoint(region, opt) +} + +// New returns a new Resolver +func New() *Resolver { + return &Resolver{ + partitions: defaultPartitions, + } +} + +var partitionRegexp = struct { + Aws *regexp.Regexp + AwsCn *regexp.Regexp + AwsEusc *regexp.Regexp + AwsIso *regexp.Regexp + AwsIsoB *regexp.Regexp + AwsIsoE *regexp.Regexp + AwsIsoF *regexp.Regexp + AwsUsGov *regexp.Regexp +}{ + + Aws: regexp.MustCompile("^(us|eu|ap|sa|ca|me|af|il|mx)\\-\\w+\\-\\d+$"), + AwsCn: regexp.MustCompile("^cn\\-\\w+\\-\\d+$"), + AwsEusc: regexp.MustCompile("^eusc\\-(de)\\-\\w+\\-\\d+$"), + AwsIso: regexp.MustCompile("^us\\-iso\\-\\w+\\-\\d+$"), + AwsIsoB: regexp.MustCompile("^us\\-isob\\-\\w+\\-\\d+$"), + AwsIsoE: regexp.MustCompile("^eu\\-isoe\\-\\w+\\-\\d+$"), + AwsIsoF: regexp.MustCompile("^us\\-isof\\-\\w+\\-\\d+$"), + AwsUsGov: regexp.MustCompile("^us\\-gov\\-\\w+\\-\\d+$"), +} + +var defaultPartitions = endpoints.Partitions{ + { + ID: "aws", + Defaults: map[endpoints.DefaultKey]endpoints.Endpoint{ + { + Variant: endpoints.DualStackVariant, + }: { + Hostname: "signin.{region}.api.aws", + Protocols: []string{"https"}, + SignatureVersions: []string{"v4"}, + }, + { + Variant: endpoints.FIPSVariant, + }: { + Hostname: "signin-fips.{region}.amazonaws.com", + Protocols: []string{"https"}, + SignatureVersions: []string{"v4"}, + }, + { + Variant: endpoints.FIPSVariant | endpoints.DualStackVariant, + }: { + Hostname: "signin-fips.{region}.api.aws", + Protocols: []string{"https"}, + SignatureVersions: []string{"v4"}, + }, + { + Variant: 0, + }: { + Hostname: "signin.{region}.amazonaws.com", + Protocols: []string{"https"}, + SignatureVersions: []string{"v4"}, + }, + }, + RegionRegex: partitionRegexp.Aws, + IsRegionalized: true, + }, + { + ID: "aws-cn", + Defaults: map[endpoints.DefaultKey]endpoints.Endpoint{ + { + Variant: endpoints.DualStackVariant, + }: { + Hostname: "signin.{region}.api.amazonwebservices.com.cn", + Protocols: []string{"https"}, + SignatureVersions: []string{"v4"}, + }, + { + Variant: endpoints.FIPSVariant, + }: { + Hostname: "signin-fips.{region}.amazonaws.com.cn", + Protocols: []string{"https"}, + SignatureVersions: []string{"v4"}, + }, + { + Variant: endpoints.FIPSVariant | endpoints.DualStackVariant, + }: { + Hostname: "signin-fips.{region}.api.amazonwebservices.com.cn", + Protocols: []string{"https"}, + SignatureVersions: []string{"v4"}, + }, + { + Variant: 0, + }: { + Hostname: "signin.{region}.amazonaws.com.cn", + Protocols: []string{"https"}, + SignatureVersions: []string{"v4"}, + }, + }, + RegionRegex: partitionRegexp.AwsCn, + IsRegionalized: true, + }, + { + ID: "aws-eusc", + Defaults: map[endpoints.DefaultKey]endpoints.Endpoint{ + { + Variant: endpoints.DualStackVariant, + }: { + Hostname: "signin.{region}.api.amazonwebservices.eu", + Protocols: []string{"https"}, + SignatureVersions: []string{"v4"}, + }, + { + Variant: endpoints.FIPSVariant, + }: { + Hostname: "signin-fips.{region}.amazonaws.eu", + Protocols: []string{"https"}, + SignatureVersions: []string{"v4"}, + }, + { + Variant: endpoints.FIPSVariant | endpoints.DualStackVariant, + }: { + Hostname: "signin-fips.{region}.api.amazonwebservices.eu", + Protocols: []string{"https"}, + SignatureVersions: []string{"v4"}, + }, + { + Variant: 0, + }: { + Hostname: "signin.{region}.amazonaws.eu", + Protocols: []string{"https"}, + SignatureVersions: []string{"v4"}, + }, + }, + RegionRegex: partitionRegexp.AwsEusc, + IsRegionalized: true, + }, + { + ID: "aws-iso", + Defaults: map[endpoints.DefaultKey]endpoints.Endpoint{ + { + Variant: endpoints.FIPSVariant, + }: { + Hostname: "signin-fips.{region}.c2s.ic.gov", + Protocols: []string{"https"}, + SignatureVersions: []string{"v4"}, + }, + { + Variant: 0, + }: { + Hostname: "signin.{region}.c2s.ic.gov", + Protocols: []string{"https"}, + SignatureVersions: []string{"v4"}, + }, + }, + RegionRegex: partitionRegexp.AwsIso, + IsRegionalized: true, + }, + { + ID: "aws-iso-b", + Defaults: map[endpoints.DefaultKey]endpoints.Endpoint{ + { + Variant: endpoints.FIPSVariant, + }: { + Hostname: "signin-fips.{region}.sc2s.sgov.gov", + Protocols: []string{"https"}, + SignatureVersions: []string{"v4"}, + }, + { + Variant: 0, + }: { + Hostname: "signin.{region}.sc2s.sgov.gov", + Protocols: []string{"https"}, + SignatureVersions: []string{"v4"}, + }, + }, + RegionRegex: partitionRegexp.AwsIsoB, + IsRegionalized: true, + }, + { + ID: "aws-iso-e", + Defaults: map[endpoints.DefaultKey]endpoints.Endpoint{ + { + Variant: endpoints.FIPSVariant, + }: { + Hostname: "signin-fips.{region}.cloud.adc-e.uk", + Protocols: []string{"https"}, + SignatureVersions: []string{"v4"}, + }, + { + Variant: 0, + }: { + Hostname: "signin.{region}.cloud.adc-e.uk", + Protocols: []string{"https"}, + SignatureVersions: []string{"v4"}, + }, + }, + RegionRegex: partitionRegexp.AwsIsoE, + IsRegionalized: true, + }, + { + ID: "aws-iso-f", + Defaults: map[endpoints.DefaultKey]endpoints.Endpoint{ + { + Variant: endpoints.FIPSVariant, + }: { + Hostname: "signin-fips.{region}.csp.hci.ic.gov", + Protocols: []string{"https"}, + SignatureVersions: []string{"v4"}, + }, + { + Variant: 0, + }: { + Hostname: "signin.{region}.csp.hci.ic.gov", + Protocols: []string{"https"}, + SignatureVersions: []string{"v4"}, + }, + }, + RegionRegex: partitionRegexp.AwsIsoF, + IsRegionalized: true, + }, + { + ID: "aws-us-gov", + Defaults: map[endpoints.DefaultKey]endpoints.Endpoint{ + { + Variant: endpoints.DualStackVariant, + }: { + Hostname: "signin.{region}.api.aws", + Protocols: []string{"https"}, + SignatureVersions: []string{"v4"}, + }, + { + Variant: endpoints.FIPSVariant, + }: { + Hostname: "signin-fips.{region}.amazonaws.com", + Protocols: []string{"https"}, + SignatureVersions: []string{"v4"}, + }, + { + Variant: endpoints.FIPSVariant | endpoints.DualStackVariant, + }: { + Hostname: "signin-fips.{region}.api.aws", + Protocols: []string{"https"}, + SignatureVersions: []string{"v4"}, + }, + { + Variant: 0, + }: { + Hostname: "signin.{region}.amazonaws.com", + Protocols: []string{"https"}, + SignatureVersions: []string{"v4"}, + }, + }, + RegionRegex: partitionRegexp.AwsUsGov, + IsRegionalized: true, + }, +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/signin/options.go b/vendor/github.com/aws/aws-sdk-go-v2/service/signin/options.go new file mode 100644 index 00000000000..3262aa58224 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/signin/options.go @@ -0,0 +1,239 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package signin + +import ( + "context" + "github.com/aws/aws-sdk-go-v2/aws" + awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" + internalauthsmithy "github.com/aws/aws-sdk-go-v2/internal/auth/smithy" + smithyauth "github.com/aws/smithy-go/auth" + "github.com/aws/smithy-go/logging" + "github.com/aws/smithy-go/metrics" + "github.com/aws/smithy-go/middleware" + "github.com/aws/smithy-go/tracing" + smithyhttp "github.com/aws/smithy-go/transport/http" + "net/http" +) + +type HTTPClient interface { + Do(*http.Request) (*http.Response, error) +} + +type Options struct { + // Set of options to modify how an operation is invoked. These apply to all + // operations invoked for this client. Use functional options on operation call to + // modify this list for per operation behavior. + APIOptions []func(*middleware.Stack) error + + // The optional application specific identifier appended to the User-Agent header. + AppID string + + // This endpoint will be given as input to an EndpointResolverV2. It is used for + // providing a custom base endpoint that is subject to modifications by the + // processing EndpointResolverV2. + BaseEndpoint *string + + // Configures the events that will be sent to the configured logger. + ClientLogMode aws.ClientLogMode + + // The credentials object to use when signing requests. + Credentials aws.CredentialsProvider + + // The configuration DefaultsMode that the SDK should use when constructing the + // clients initial default settings. + DefaultsMode aws.DefaultsMode + + // The endpoint options to be used when attempting to resolve an endpoint. + EndpointOptions EndpointResolverOptions + + // The service endpoint resolver. + // + // Deprecated: Deprecated: EndpointResolver and WithEndpointResolver. Providing a + // value for this field will likely prevent you from using any endpoint-related + // service features released after the introduction of EndpointResolverV2 and + // BaseEndpoint. + // + // To migrate an EndpointResolver implementation that uses a custom endpoint, set + // the client option BaseEndpoint instead. + EndpointResolver EndpointResolver + + // Resolves the endpoint used for a particular service operation. This should be + // used over the deprecated EndpointResolver. + EndpointResolverV2 EndpointResolverV2 + + // Signature Version 4 (SigV4) Signer + HTTPSignerV4 HTTPSignerV4 + + // The logger writer interface to write logging messages to. + Logger logging.Logger + + // The client meter provider. + MeterProvider metrics.MeterProvider + + // The region to send requests to. (Required) + Region string + + // RetryMaxAttempts specifies the maximum number attempts an API client will call + // an operation that fails with a retryable error. A value of 0 is ignored, and + // will not be used to configure the API client created default retryer, or modify + // per operation call's retry max attempts. + // + // If specified in an operation call's functional options with a value that is + // different than the constructed client's Options, the Client's Retryer will be + // wrapped to use the operation's specific RetryMaxAttempts value. + RetryMaxAttempts int + + // RetryMode specifies the retry mode the API client will be created with, if + // Retryer option is not also specified. + // + // When creating a new API Clients this member will only be used if the Retryer + // Options member is nil. This value will be ignored if Retryer is not nil. + // + // Currently does not support per operation call overrides, may in the future. + RetryMode aws.RetryMode + + // Retryer guides how HTTP requests should be retried in case of recoverable + // failures. When nil the API client will use a default retryer. The kind of + // default retry created by the API client can be changed with the RetryMode + // option. + Retryer aws.Retryer + + // The RuntimeEnvironment configuration, only populated if the DefaultsMode is set + // to DefaultsModeAuto and is initialized using config.LoadDefaultConfig . You + // should not populate this structure programmatically, or rely on the values here + // within your applications. + RuntimeEnvironment aws.RuntimeEnvironment + + // The client tracer provider. + TracerProvider tracing.TracerProvider + + // The initial DefaultsMode used when the client options were constructed. If the + // DefaultsMode was set to aws.DefaultsModeAuto this will store what the resolved + // value was at that point in time. + // + // Currently does not support per operation call overrides, may in the future. + resolvedDefaultsMode aws.DefaultsMode + + // The HTTP client to invoke API calls with. Defaults to client's default HTTP + // implementation if nil. + HTTPClient HTTPClient + + // Client registry of operation interceptors. + Interceptors smithyhttp.InterceptorRegistry + + // The auth scheme resolver which determines how to authenticate for each + // operation. + AuthSchemeResolver AuthSchemeResolver + + // The list of auth schemes supported by the client. + AuthSchemes []smithyhttp.AuthScheme + + // Priority list of preferred auth scheme names (e.g. sigv4a). + AuthSchemePreference []string +} + +// Copy creates a clone where the APIOptions list is deep copied. +func (o Options) Copy() Options { + to := o + to.APIOptions = make([]func(*middleware.Stack) error, len(o.APIOptions)) + copy(to.APIOptions, o.APIOptions) + to.Interceptors = o.Interceptors.Copy() + + return to +} + +func (o Options) GetIdentityResolver(schemeID string) smithyauth.IdentityResolver { + if schemeID == "aws.auth#sigv4" { + return getSigV4IdentityResolver(o) + } + if schemeID == "smithy.api#noAuth" { + return &smithyauth.AnonymousIdentityResolver{} + } + return nil +} + +// WithAPIOptions returns a functional option for setting the Client's APIOptions +// option. +func WithAPIOptions(optFns ...func(*middleware.Stack) error) func(*Options) { + return func(o *Options) { + o.APIOptions = append(o.APIOptions, optFns...) + } +} + +// Deprecated: EndpointResolver and WithEndpointResolver. Providing a value for +// this field will likely prevent you from using any endpoint-related service +// features released after the introduction of EndpointResolverV2 and BaseEndpoint. +// +// To migrate an EndpointResolver implementation that uses a custom endpoint, set +// the client option BaseEndpoint instead. +func WithEndpointResolver(v EndpointResolver) func(*Options) { + return func(o *Options) { + o.EndpointResolver = v + } +} + +// WithEndpointResolverV2 returns a functional option for setting the Client's +// EndpointResolverV2 option. +func WithEndpointResolverV2(v EndpointResolverV2) func(*Options) { + return func(o *Options) { + o.EndpointResolverV2 = v + } +} + +func getSigV4IdentityResolver(o Options) smithyauth.IdentityResolver { + if o.Credentials != nil { + return &internalauthsmithy.CredentialsProviderAdapter{Provider: o.Credentials} + } + return nil +} + +// WithSigV4SigningName applies an override to the authentication workflow to +// use the given signing name for SigV4-authenticated operations. +// +// This is an advanced setting. The value here is FINAL, taking precedence over +// the resolved signing name from both auth scheme resolution and endpoint +// resolution. +func WithSigV4SigningName(name string) func(*Options) { + fn := func(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( + out middleware.InitializeOutput, metadata middleware.Metadata, err error, + ) { + return next.HandleInitialize(awsmiddleware.SetSigningName(ctx, name), in) + } + return func(o *Options) { + o.APIOptions = append(o.APIOptions, func(s *middleware.Stack) error { + return s.Initialize.Add( + middleware.InitializeMiddlewareFunc("withSigV4SigningName", fn), + middleware.Before, + ) + }) + } +} + +// WithSigV4SigningRegion applies an override to the authentication workflow to +// use the given signing region for SigV4-authenticated operations. +// +// This is an advanced setting. The value here is FINAL, taking precedence over +// the resolved signing region from both auth scheme resolution and endpoint +// resolution. +func WithSigV4SigningRegion(region string) func(*Options) { + fn := func(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( + out middleware.InitializeOutput, metadata middleware.Metadata, err error, + ) { + return next.HandleInitialize(awsmiddleware.SetSigningRegion(ctx, region), in) + } + return func(o *Options) { + o.APIOptions = append(o.APIOptions, func(s *middleware.Stack) error { + return s.Initialize.Add( + middleware.InitializeMiddlewareFunc("withSigV4SigningRegion", fn), + middleware.Before, + ) + }) + } +} + +func ignoreAnonymousAuth(options *Options) { + if aws.IsCredentialsProvider(options.Credentials, (*aws.AnonymousCredentials)(nil)) { + options.Credentials = nil + } +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/signin/serializers.go b/vendor/github.com/aws/aws-sdk-go-v2/service/signin/serializers.go new file mode 100644 index 00000000000..958240275e3 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/signin/serializers.go @@ -0,0 +1,135 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package signin + +import ( + "bytes" + "context" + "fmt" + "github.com/aws/aws-sdk-go-v2/service/signin/types" + smithy "github.com/aws/smithy-go" + "github.com/aws/smithy-go/encoding/httpbinding" + smithyjson "github.com/aws/smithy-go/encoding/json" + "github.com/aws/smithy-go/middleware" + "github.com/aws/smithy-go/tracing" + smithyhttp "github.com/aws/smithy-go/transport/http" +) + +type awsRestjson1_serializeOpCreateOAuth2Token struct { +} + +func (*awsRestjson1_serializeOpCreateOAuth2Token) ID() string { + return "OperationSerializer" +} + +func (m *awsRestjson1_serializeOpCreateOAuth2Token) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( + out middleware.SerializeOutput, metadata middleware.Metadata, err error, +) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() + request, ok := in.Request.(*smithyhttp.Request) + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} + } + + input, ok := in.Parameters.(*CreateOAuth2TokenInput) + _ = input + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown input parameters type %T", in.Parameters)} + } + + opPath, opQuery := httpbinding.SplitURI("/v1/token") + request.URL.Path = smithyhttp.JoinPath(request.URL.Path, opPath) + request.URL.RawQuery = smithyhttp.JoinRawQuery(request.URL.RawQuery, opQuery) + request.Method = "POST" + var restEncoder *httpbinding.Encoder + if request.URL.RawPath == "" { + restEncoder, err = httpbinding.NewEncoder(request.URL.Path, request.URL.RawQuery, request.Header) + } else { + request.URL.RawPath = smithyhttp.JoinPath(request.URL.RawPath, opPath) + restEncoder, err = httpbinding.NewEncoderWithRawPath(request.URL.Path, request.URL.RawPath, request.URL.RawQuery, request.Header) + } + + if err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if !restEncoder.HasHeader("Content-Type") { + ctx = smithyhttp.SetIsContentTypeDefaultValue(ctx, true) + restEncoder.SetHeader("Content-Type").String("application/json") + } + + if input.TokenInput != nil { + jsonEncoder := smithyjson.NewEncoder() + if err := awsRestjson1_serializeDocumentCreateOAuth2TokenRequestBody(input.TokenInput, jsonEncoder.Value); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + payload := bytes.NewReader(jsonEncoder.Bytes()) + if request, err = request.SetStream(payload); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + } else { + jsonEncoder := smithyjson.NewEncoder() + jsonEncoder.Value.Object().Close() + payload := bytes.NewReader(jsonEncoder.Bytes()) + if request, err = request.SetStream(payload); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + } + + if request.Request, err = restEncoder.Encode(request.Request); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + in.Request = request + + endTimer() + span.End() + return next.HandleSerialize(ctx, in) +} +func awsRestjson1_serializeOpHttpBindingsCreateOAuth2TokenInput(v *CreateOAuth2TokenInput, encoder *httpbinding.Encoder) error { + if v == nil { + return fmt.Errorf("unsupported serialization of nil %T", v) + } + + return nil +} + +func awsRestjson1_serializeDocumentCreateOAuth2TokenRequestBody(v *types.CreateOAuth2TokenRequestBody, value smithyjson.Value) error { + object := value.Object() + defer object.Close() + + if v.ClientId != nil { + ok := object.Key("clientId") + ok.String(*v.ClientId) + } + + if v.Code != nil { + ok := object.Key("code") + ok.String(*v.Code) + } + + if v.CodeVerifier != nil { + ok := object.Key("codeVerifier") + ok.String(*v.CodeVerifier) + } + + if v.GrantType != nil { + ok := object.Key("grantType") + ok.String(*v.GrantType) + } + + if v.RedirectUri != nil { + ok := object.Key("redirectUri") + ok.String(*v.RedirectUri) + } + + if v.RefreshToken != nil { + ok := object.Key("refreshToken") + ok.String(*v.RefreshToken) + } + + return nil +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/signin/types/enums.go b/vendor/github.com/aws/aws-sdk-go-v2/service/signin/types/enums.go new file mode 100644 index 00000000000..ecfabb81f74 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/signin/types/enums.go @@ -0,0 +1,37 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package types + +type OAuth2ErrorCode string + +// Enum values for OAuth2ErrorCode +const ( + // Token has expired and needs to be refreshed + OAuth2ErrorCodeTokenExpired OAuth2ErrorCode = "TOKEN_EXPIRED" + // User credentials have been changed + OAuth2ErrorCodeUserCredentialsChanged OAuth2ErrorCode = "USER_CREDENTIALS_CHANGED" + // Insufficient permissions to perform this operation + OAuth2ErrorCodeInsufficientPermissions OAuth2ErrorCode = "INSUFFICIENT_PERMISSIONS" + // Authorization code has expired + OAuth2ErrorCodeAuthcodeExpired OAuth2ErrorCode = "AUTHCODE_EXPIRED" + // Internal server error occurred + OAuth2ErrorCodeServerError OAuth2ErrorCode = "server_error" + // The request is missing a required parameter, includes an invalid parameter + // value, or is otherwise malformed + OAuth2ErrorCodeInvalidRequest OAuth2ErrorCode = "INVALID_REQUEST" +) + +// Values returns all known values for OAuth2ErrorCode. Note that this can be +// expanded in the future, and so it is only as up to date as the client. +// +// The ordering of this slice is not guaranteed to be stable across updates. +func (OAuth2ErrorCode) Values() []OAuth2ErrorCode { + return []OAuth2ErrorCode{ + "TOKEN_EXPIRED", + "USER_CREDENTIALS_CHANGED", + "INSUFFICIENT_PERMISSIONS", + "AUTHCODE_EXPIRED", + "server_error", + "INVALID_REQUEST", + } +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/signin/types/errors.go b/vendor/github.com/aws/aws-sdk-go-v2/service/signin/types/errors.go new file mode 100644 index 00000000000..ca4928a86c8 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/signin/types/errors.go @@ -0,0 +1,151 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package types + +import ( + "fmt" + smithy "github.com/aws/smithy-go" +) + +// Error thrown for access denied scenarios with flexible HTTP status mapping +// +// Runtime HTTP Status Code Mapping: +// +// - HTTP 401 (Unauthorized): TOKEN_EXPIRED, AUTHCODE_EXPIRED +// - HTTP 403 (Forbidden): USER_CREDENTIALS_CHANGED, INSUFFICIENT_PERMISSIONS +// +// The specific HTTP status code is determined at runtime based on the error enum +// value. Consumers should use the error field to determine the specific access +// denial reason. +type AccessDeniedException struct { + Message *string + + ErrorCodeOverride *string + + Error_ OAuth2ErrorCode + + noSmithyDocumentSerde +} + +func (e *AccessDeniedException) Error() string { + return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) +} +func (e *AccessDeniedException) ErrorMessage() string { + if e.Message == nil { + return "" + } + return *e.Message +} +func (e *AccessDeniedException) ErrorCode() string { + if e == nil || e.ErrorCodeOverride == nil { + return "AccessDeniedException" + } + return *e.ErrorCodeOverride +} +func (e *AccessDeniedException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } + +// Error thrown when an internal server error occurs +// +// HTTP Status Code: 500 Internal Server Error +// +// Used for unexpected server-side errors that prevent request processing. +type InternalServerException struct { + Message *string + + ErrorCodeOverride *string + + Error_ OAuth2ErrorCode + + noSmithyDocumentSerde +} + +func (e *InternalServerException) Error() string { + return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) +} +func (e *InternalServerException) ErrorMessage() string { + if e.Message == nil { + return "" + } + return *e.Message +} +func (e *InternalServerException) ErrorCode() string { + if e == nil || e.ErrorCodeOverride == nil { + return "InternalServerException" + } + return *e.ErrorCodeOverride +} +func (e *InternalServerException) ErrorFault() smithy.ErrorFault { return smithy.FaultServer } + +// Error thrown when rate limit is exceeded +// +// HTTP Status Code: 429 Too Many Requests +// +// Possible OAuth2ErrorCode values: +// +// - INVALID_REQUEST: Rate limiting, too many requests, abuse prevention +// +// Possible causes: +// +// - Too many token requests from the same client +// - Rate limiting based on client_id or IP address +// - Abuse prevention mechanisms triggered +// - Service protection against excessive token generation +type TooManyRequestsError struct { + Message *string + + ErrorCodeOverride *string + + Error_ OAuth2ErrorCode + + noSmithyDocumentSerde +} + +func (e *TooManyRequestsError) Error() string { + return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) +} +func (e *TooManyRequestsError) ErrorMessage() string { + if e.Message == nil { + return "" + } + return *e.Message +} +func (e *TooManyRequestsError) ErrorCode() string { + if e == nil || e.ErrorCodeOverride == nil { + return "TooManyRequestsError" + } + return *e.ErrorCodeOverride +} +func (e *TooManyRequestsError) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } + +// Error thrown when request validation fails +// +// HTTP Status Code: 400 Bad Request +// +// Used for request validation errors such as malformed parameters, missing +// required fields, or invalid parameter values. +type ValidationException struct { + Message *string + + ErrorCodeOverride *string + + Error_ OAuth2ErrorCode + + noSmithyDocumentSerde +} + +func (e *ValidationException) Error() string { + return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) +} +func (e *ValidationException) ErrorMessage() string { + if e.Message == nil { + return "" + } + return *e.Message +} +func (e *ValidationException) ErrorCode() string { + if e == nil || e.ErrorCodeOverride == nil { + return "ValidationException" + } + return *e.ErrorCodeOverride +} +func (e *ValidationException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/signin/types/types.go b/vendor/github.com/aws/aws-sdk-go-v2/service/signin/types/types.go new file mode 100644 index 00000000000..98afa20bfcb --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/signin/types/types.go @@ -0,0 +1,115 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package types + +import ( + smithydocument "github.com/aws/smithy-go/document" +) + +// AWS credentials structure containing temporary access credentials +// +// The scoped-down, 15 minute duration AWS credentials. Scoping down will be based +// on CLI policy (CLI team needs to create it). Similar to cloud shell +// implementation. +type AccessToken struct { + + // AWS access key ID for temporary credentials + // + // This member is required. + AccessKeyId *string + + // AWS secret access key for temporary credentials + // + // This member is required. + SecretAccessKey *string + + // AWS session token for temporary credentials + // + // This member is required. + SessionToken *string + + noSmithyDocumentSerde +} + +// Request body payload for CreateOAuth2Token operation +// +// The operation type is determined by the grant_type parameter: +// +// - grant_type=authorization_code: Requires code, redirect_uri, code_verifier +// - grant_type=refresh_token: Requires refresh_token +type CreateOAuth2TokenRequestBody struct { + + // The client identifier (ARN) used during Sign-In onboarding Required for both + // authorization code and refresh token flows + // + // This member is required. + ClientId *string + + // OAuth 2.0 grant type - determines which flow is used Must be + // "authorization_code" or "refresh_token" + // + // This member is required. + GrantType *string + + // The authorization code received from /v1/authorize Required only when + // grant_type=authorization_code + Code *string + + // PKCE code verifier to prove possession of the original code challenge Required + // only when grant_type=authorization_code + CodeVerifier *string + + // The redirect URI that must match the original authorization request Required + // only when grant_type=authorization_code + RedirectUri *string + + // The refresh token returned from auth_code redemption Required only when + // grant_type=refresh_token + RefreshToken *string + + noSmithyDocumentSerde +} + +// Response body payload for CreateOAuth2Token operation +// +// The response content depends on the grant_type from the request: +// +// - grant_type=authorization_code: Returns all fields including refresh_token +// and id_token +// - grant_type=refresh_token: Returns access_token, token_type, expires_in, +// refresh_token (no id_token) +type CreateOAuth2TokenResponseBody struct { + + // Scoped-down AWS credentials (15 minute duration) Present for both authorization + // code redemption and token refresh + // + // This member is required. + AccessToken *AccessToken + + // Time to expiry in seconds (maximum 900) Present for both authorization code + // redemption and token refresh + // + // This member is required. + ExpiresIn *int32 + + // Encrypted refresh token with cnf.jkt (SHA-256 thumbprint of presented jwk) + // Always present in responses (required for both flows) + // + // This member is required. + RefreshToken *string + + // Token type indicating this is AWS SigV4 credentials Value is "aws_sigv4" for + // both flows + // + // This member is required. + TokenType *string + + // ID token containing user identity information Present only in authorization + // code redemption response (grant_type=authorization_code) Not included in token + // refresh responses + IdToken *string + + noSmithyDocumentSerde +} + +type noSmithyDocumentSerde = smithydocument.NoSerde diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/signin/validators.go b/vendor/github.com/aws/aws-sdk-go-v2/service/signin/validators.go new file mode 100644 index 00000000000..f07252341ad --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/signin/validators.go @@ -0,0 +1,72 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package signin + +import ( + "context" + "fmt" + "github.com/aws/aws-sdk-go-v2/service/signin/types" + smithy "github.com/aws/smithy-go" + "github.com/aws/smithy-go/middleware" +) + +type validateOpCreateOAuth2Token struct { +} + +func (*validateOpCreateOAuth2Token) ID() string { + return "OperationInputValidation" +} + +func (m *validateOpCreateOAuth2Token) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( + out middleware.InitializeOutput, metadata middleware.Metadata, err error, +) { + input, ok := in.Parameters.(*CreateOAuth2TokenInput) + if !ok { + return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) + } + if err := validateOpCreateOAuth2TokenInput(input); err != nil { + return out, metadata, err + } + return next.HandleInitialize(ctx, in) +} + +func addOpCreateOAuth2TokenValidationMiddleware(stack *middleware.Stack) error { + return stack.Initialize.Add(&validateOpCreateOAuth2Token{}, middleware.After) +} + +func validateCreateOAuth2TokenRequestBody(v *types.CreateOAuth2TokenRequestBody) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "CreateOAuth2TokenRequestBody"} + if v.ClientId == nil { + invalidParams.Add(smithy.NewErrParamRequired("ClientId")) + } + if v.GrantType == nil { + invalidParams.Add(smithy.NewErrParamRequired("GrantType")) + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + +func validateOpCreateOAuth2TokenInput(v *CreateOAuth2TokenInput) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "CreateOAuth2TokenInput"} + if v.TokenInput == nil { + invalidParams.Add(smithy.NewErrParamRequired("TokenInput")) + } else if v.TokenInput != nil { + if err := validateCreateOAuth2TokenRequestBody(v.TokenInput); err != nil { + invalidParams.AddNested("TokenInput", err.(smithy.InvalidParamsError)) + } + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/sso/CHANGELOG.md b/vendor/github.com/aws/aws-sdk-go-v2/service/sso/CHANGELOG.md index 4c5e39d8739..f73d6253edd 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/sso/CHANGELOG.md +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/sso/CHANGELOG.md @@ -1,3 +1,53 @@ +# v1.30.8 (2025-12-16) + +* No change notes available for this release. + +# v1.30.7 (2025-12-08) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.30.6 (2025-12-02) + +* **Dependency Update**: Updated to the latest SDK module versions +* **Dependency Update**: Upgrade to smithy-go v1.24.0. Notably this version of the library reduces the allocation footprint of the middleware system. We observe a ~10% reduction in allocations per SDK call with this change. + +# v1.30.5 (2025-11-25) + +* **Bug Fix**: Add error check for endpoint param binding during auth scheme resolution to fix panic reported in #3234 + +# v1.30.4 (2025-11-19.2) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.30.3 (2025-11-12) + +* **Bug Fix**: Further reduce allocation overhead when the metrics system isn't in-use. +* **Bug Fix**: Reduce allocation overhead when the client doesn't have any HTTP interceptors configured. +* **Bug Fix**: Remove blank trace spans towards the beginning of the request that added no additional information. This conveys a slight reduction in overall allocations. + +# v1.30.2 (2025-11-11) + +* **Bug Fix**: Return validation error if input region is not a valid host label. + +# v1.30.1 (2025-11-04) + +* **Dependency Update**: Updated to the latest SDK module versions +* **Dependency Update**: Upgrade to smithy-go v1.23.2 which should convey some passive reduction of overall allocations, especially when not using the metrics system. + +# v1.30.0 (2025-10-30) + +* **Feature**: Update endpoint ruleset parameters casing +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.29.8 (2025-10-23) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.29.7 (2025-10-16) + +* **Dependency Update**: Bump minimum Go version to 1.23. +* **Dependency Update**: Updated to the latest SDK module versions + # v1.29.6 (2025-09-29) * No change notes available for this release. diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/sso/api_client.go b/vendor/github.com/aws/aws-sdk-go-v2/service/sso/api_client.go index 2c498e4689a..8e5a2e77f87 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/sso/api_client.go +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/sso/api_client.go @@ -65,7 +65,12 @@ func timeOperationMetric[T any]( ctx context.Context, metric string, fn func() (T, error), opts ...metrics.RecordMetricOption, ) (T, error) { - instr := getOperationMetrics(ctx).histogramFor(metric) + mm := getOperationMetrics(ctx) + if mm == nil { // not using the metrics system + return fn() + } + + instr := mm.histogramFor(metric) opts = append([]metrics.RecordMetricOption{withOperationMetadata(ctx)}, opts...) start := time.Now() @@ -78,7 +83,12 @@ func timeOperationMetric[T any]( } func startMetricTimer(ctx context.Context, metric string, opts ...metrics.RecordMetricOption) func() { - instr := getOperationMetrics(ctx).histogramFor(metric) + mm := getOperationMetrics(ctx) + if mm == nil { // not using the metrics system + return func() {} + } + + instr := mm.histogramFor(metric) opts = append([]metrics.RecordMetricOption{withOperationMetadata(ctx)}, opts...) var ended bool @@ -106,6 +116,12 @@ func withOperationMetadata(ctx context.Context) metrics.RecordMetricOption { type operationMetricsKey struct{} func withOperationMetrics(parent context.Context, mp metrics.MeterProvider) (context.Context, error) { + if _, ok := mp.(metrics.NopMeterProvider); ok { + // not using the metrics system - setting up the metrics context is a memory-intensive operation + // so we should skip it in this case + return parent, nil + } + meter := mp.Meter("github.com/aws/aws-sdk-go-v2/service/sso") om := &operationMetrics{} @@ -153,7 +169,10 @@ func operationMetricTimer(m metrics.Meter, name, desc string) (metrics.Float64Hi } func getOperationMetrics(ctx context.Context) *operationMetrics { - return ctx.Value(operationMetricsKey{}).(*operationMetrics) + if v := ctx.Value(operationMetricsKey{}); v != nil { + return v.(*operationMetrics) + } + return nil } func operationTracer(p tracing.TracerProvider) tracing.Tracer { @@ -882,138 +901,49 @@ func addInterceptAttempt(stack *middleware.Stack, opts Options) error { }, "Retry", middleware.After) } -func addInterceptExecution(stack *middleware.Stack, opts Options) error { - return stack.Initialize.Add(&smithyhttp.InterceptExecution{ - BeforeExecution: opts.Interceptors.BeforeExecution, - AfterExecution: opts.Interceptors.AfterExecution, - }, middleware.Before) -} - -func addInterceptBeforeSerialization(stack *middleware.Stack, opts Options) error { - return stack.Serialize.Insert(&smithyhttp.InterceptBeforeSerialization{ - Interceptors: opts.Interceptors.BeforeSerialization, - }, "OperationSerializer", middleware.Before) -} - -func addInterceptAfterSerialization(stack *middleware.Stack, opts Options) error { - return stack.Serialize.Insert(&smithyhttp.InterceptAfterSerialization{ - Interceptors: opts.Interceptors.AfterSerialization, - }, "OperationSerializer", middleware.After) -} - -func addInterceptBeforeSigning(stack *middleware.Stack, opts Options) error { - return stack.Finalize.Insert(&smithyhttp.InterceptBeforeSigning{ - Interceptors: opts.Interceptors.BeforeSigning, - }, "Signing", middleware.Before) -} - -func addInterceptAfterSigning(stack *middleware.Stack, opts Options) error { - return stack.Finalize.Insert(&smithyhttp.InterceptAfterSigning{ - Interceptors: opts.Interceptors.AfterSigning, - }, "Signing", middleware.After) -} - -func addInterceptTransmit(stack *middleware.Stack, opts Options) error { - return stack.Deserialize.Add(&smithyhttp.InterceptTransmit{ - BeforeTransmit: opts.Interceptors.BeforeTransmit, - AfterTransmit: opts.Interceptors.AfterTransmit, - }, middleware.After) -} - -func addInterceptBeforeDeserialization(stack *middleware.Stack, opts Options) error { - return stack.Deserialize.Insert(&smithyhttp.InterceptBeforeDeserialization{ - Interceptors: opts.Interceptors.BeforeDeserialization, - }, "OperationDeserializer", middleware.After) // (deserialize stack is called in reverse) -} - -func addInterceptAfterDeserialization(stack *middleware.Stack, opts Options) error { - return stack.Deserialize.Insert(&smithyhttp.InterceptAfterDeserialization{ - Interceptors: opts.Interceptors.AfterDeserialization, - }, "OperationDeserializer", middleware.Before) -} - -type spanInitializeStart struct { -} - -func (*spanInitializeStart) ID() string { - return "spanInitializeStart" -} - -func (m *spanInitializeStart) HandleInitialize( - ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler, -) ( - middleware.InitializeOutput, middleware.Metadata, error, -) { - ctx, _ = tracing.StartSpan(ctx, "Initialize") - - return next.HandleInitialize(ctx, in) -} - -type spanInitializeEnd struct { -} - -func (*spanInitializeEnd) ID() string { - return "spanInitializeEnd" -} - -func (m *spanInitializeEnd) HandleInitialize( - ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler, -) ( - middleware.InitializeOutput, middleware.Metadata, error, -) { - ctx, span := tracing.PopSpan(ctx) - span.End() - - return next.HandleInitialize(ctx, in) -} - -type spanBuildRequestStart struct { -} - -func (*spanBuildRequestStart) ID() string { - return "spanBuildRequestStart" -} - -func (m *spanBuildRequestStart) HandleSerialize( - ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler, -) ( - middleware.SerializeOutput, middleware.Metadata, error, -) { - ctx, _ = tracing.StartSpan(ctx, "BuildRequest") - - return next.HandleSerialize(ctx, in) -} - -type spanBuildRequestEnd struct { -} - -func (*spanBuildRequestEnd) ID() string { - return "spanBuildRequestEnd" -} - -func (m *spanBuildRequestEnd) HandleBuild( - ctx context.Context, in middleware.BuildInput, next middleware.BuildHandler, -) ( - middleware.BuildOutput, middleware.Metadata, error, -) { - ctx, span := tracing.PopSpan(ctx) - span.End() - - return next.HandleBuild(ctx, in) -} - -func addSpanInitializeStart(stack *middleware.Stack) error { - return stack.Initialize.Add(&spanInitializeStart{}, middleware.Before) -} - -func addSpanInitializeEnd(stack *middleware.Stack) error { - return stack.Initialize.Add(&spanInitializeEnd{}, middleware.After) -} - -func addSpanBuildRequestStart(stack *middleware.Stack) error { - return stack.Serialize.Add(&spanBuildRequestStart{}, middleware.Before) -} +func addInterceptors(stack *middleware.Stack, opts Options) error { + // middlewares are expensive, don't add all of these interceptor ones unless the caller + // actually has at least one interceptor configured + // + // at the moment it's all-or-nothing because some of the middlewares here are responsible for + // setting fields in the interceptor context for future ones + if len(opts.Interceptors.BeforeExecution) == 0 && + len(opts.Interceptors.BeforeSerialization) == 0 && len(opts.Interceptors.AfterSerialization) == 0 && + len(opts.Interceptors.BeforeRetryLoop) == 0 && + len(opts.Interceptors.BeforeAttempt) == 0 && + len(opts.Interceptors.BeforeSigning) == 0 && len(opts.Interceptors.AfterSigning) == 0 && + len(opts.Interceptors.BeforeTransmit) == 0 && len(opts.Interceptors.AfterTransmit) == 0 && + len(opts.Interceptors.BeforeDeserialization) == 0 && len(opts.Interceptors.AfterDeserialization) == 0 && + len(opts.Interceptors.AfterAttempt) == 0 && len(opts.Interceptors.AfterExecution) == 0 { + return nil + } -func addSpanBuildRequestEnd(stack *middleware.Stack) error { - return stack.Build.Add(&spanBuildRequestEnd{}, middleware.After) + return errors.Join( + stack.Initialize.Add(&smithyhttp.InterceptExecution{ + BeforeExecution: opts.Interceptors.BeforeExecution, + AfterExecution: opts.Interceptors.AfterExecution, + }, middleware.Before), + stack.Serialize.Insert(&smithyhttp.InterceptBeforeSerialization{ + Interceptors: opts.Interceptors.BeforeSerialization, + }, "OperationSerializer", middleware.Before), + stack.Serialize.Insert(&smithyhttp.InterceptAfterSerialization{ + Interceptors: opts.Interceptors.AfterSerialization, + }, "OperationSerializer", middleware.After), + stack.Finalize.Insert(&smithyhttp.InterceptBeforeSigning{ + Interceptors: opts.Interceptors.BeforeSigning, + }, "Signing", middleware.Before), + stack.Finalize.Insert(&smithyhttp.InterceptAfterSigning{ + Interceptors: opts.Interceptors.AfterSigning, + }, "Signing", middleware.After), + stack.Deserialize.Add(&smithyhttp.InterceptTransmit{ + BeforeTransmit: opts.Interceptors.BeforeTransmit, + AfterTransmit: opts.Interceptors.AfterTransmit, + }, middleware.After), + stack.Deserialize.Insert(&smithyhttp.InterceptBeforeDeserialization{ + Interceptors: opts.Interceptors.BeforeDeserialization, + }, "OperationDeserializer", middleware.After), // (deserialize stack is called in reverse) + stack.Deserialize.Insert(&smithyhttp.InterceptAfterDeserialization{ + Interceptors: opts.Interceptors.AfterDeserialization, + }, "OperationDeserializer", middleware.Before), + ) } diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/sso/api_op_GetRoleCredentials.go b/vendor/github.com/aws/aws-sdk-go-v2/service/sso/api_op_GetRoleCredentials.go index df5dc1674f3..c0b961fcf18 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/sso/api_op_GetRoleCredentials.go +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/sso/api_op_GetRoleCredentials.go @@ -153,40 +153,7 @@ func (c *Client) addOperationGetRoleCredentialsMiddlewares(stack *middleware.Sta if err = addInterceptAttempt(stack, options); err != nil { return err } - if err = addInterceptExecution(stack, options); err != nil { - return err - } - if err = addInterceptBeforeSerialization(stack, options); err != nil { - return err - } - if err = addInterceptAfterSerialization(stack, options); err != nil { - return err - } - if err = addInterceptBeforeSigning(stack, options); err != nil { - return err - } - if err = addInterceptAfterSigning(stack, options); err != nil { - return err - } - if err = addInterceptTransmit(stack, options); err != nil { - return err - } - if err = addInterceptBeforeDeserialization(stack, options); err != nil { - return err - } - if err = addInterceptAfterDeserialization(stack, options); err != nil { - return err - } - if err = addSpanInitializeStart(stack); err != nil { - return err - } - if err = addSpanInitializeEnd(stack); err != nil { - return err - } - if err = addSpanBuildRequestStart(stack); err != nil { - return err - } - if err = addSpanBuildRequestEnd(stack); err != nil { + if err = addInterceptors(stack, options); err != nil { return err } return nil diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/sso/api_op_ListAccountRoles.go b/vendor/github.com/aws/aws-sdk-go-v2/service/sso/api_op_ListAccountRoles.go index 2a3b2ad9021..f5ca09ac7d8 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/sso/api_op_ListAccountRoles.go +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/sso/api_op_ListAccountRoles.go @@ -158,40 +158,7 @@ func (c *Client) addOperationListAccountRolesMiddlewares(stack *middleware.Stack if err = addInterceptAttempt(stack, options); err != nil { return err } - if err = addInterceptExecution(stack, options); err != nil { - return err - } - if err = addInterceptBeforeSerialization(stack, options); err != nil { - return err - } - if err = addInterceptAfterSerialization(stack, options); err != nil { - return err - } - if err = addInterceptBeforeSigning(stack, options); err != nil { - return err - } - if err = addInterceptAfterSigning(stack, options); err != nil { - return err - } - if err = addInterceptTransmit(stack, options); err != nil { - return err - } - if err = addInterceptBeforeDeserialization(stack, options); err != nil { - return err - } - if err = addInterceptAfterDeserialization(stack, options); err != nil { - return err - } - if err = addSpanInitializeStart(stack); err != nil { - return err - } - if err = addSpanInitializeEnd(stack); err != nil { - return err - } - if err = addSpanBuildRequestStart(stack); err != nil { - return err - } - if err = addSpanBuildRequestEnd(stack); err != nil { + if err = addInterceptors(stack, options); err != nil { return err } return nil diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/sso/api_op_ListAccounts.go b/vendor/github.com/aws/aws-sdk-go-v2/service/sso/api_op_ListAccounts.go index f6114a7c105..54511d34a6e 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/sso/api_op_ListAccounts.go +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/sso/api_op_ListAccounts.go @@ -157,40 +157,7 @@ func (c *Client) addOperationListAccountsMiddlewares(stack *middleware.Stack, op if err = addInterceptAttempt(stack, options); err != nil { return err } - if err = addInterceptExecution(stack, options); err != nil { - return err - } - if err = addInterceptBeforeSerialization(stack, options); err != nil { - return err - } - if err = addInterceptAfterSerialization(stack, options); err != nil { - return err - } - if err = addInterceptBeforeSigning(stack, options); err != nil { - return err - } - if err = addInterceptAfterSigning(stack, options); err != nil { - return err - } - if err = addInterceptTransmit(stack, options); err != nil { - return err - } - if err = addInterceptBeforeDeserialization(stack, options); err != nil { - return err - } - if err = addInterceptAfterDeserialization(stack, options); err != nil { - return err - } - if err = addSpanInitializeStart(stack); err != nil { - return err - } - if err = addSpanInitializeEnd(stack); err != nil { - return err - } - if err = addSpanBuildRequestStart(stack); err != nil { - return err - } - if err = addSpanBuildRequestEnd(stack); err != nil { + if err = addInterceptors(stack, options); err != nil { return err } return nil diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/sso/api_op_Logout.go b/vendor/github.com/aws/aws-sdk-go-v2/service/sso/api_op_Logout.go index 2c7f181c344..a21116e96c1 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/sso/api_op_Logout.go +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/sso/api_op_Logout.go @@ -152,40 +152,7 @@ func (c *Client) addOperationLogoutMiddlewares(stack *middleware.Stack, options if err = addInterceptAttempt(stack, options); err != nil { return err } - if err = addInterceptExecution(stack, options); err != nil { - return err - } - if err = addInterceptBeforeSerialization(stack, options); err != nil { - return err - } - if err = addInterceptAfterSerialization(stack, options); err != nil { - return err - } - if err = addInterceptBeforeSigning(stack, options); err != nil { - return err - } - if err = addInterceptAfterSigning(stack, options); err != nil { - return err - } - if err = addInterceptTransmit(stack, options); err != nil { - return err - } - if err = addInterceptBeforeDeserialization(stack, options); err != nil { - return err - } - if err = addInterceptAfterDeserialization(stack, options); err != nil { - return err - } - if err = addSpanInitializeStart(stack); err != nil { - return err - } - if err = addSpanInitializeEnd(stack); err != nil { - return err - } - if err = addSpanBuildRequestStart(stack); err != nil { - return err - } - if err = addSpanBuildRequestEnd(stack); err != nil { + if err = addInterceptors(stack, options); err != nil { return err } return nil diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/sso/auth.go b/vendor/github.com/aws/aws-sdk-go-v2/service/sso/auth.go index 708e53c5ad5..c658615fdec 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/sso/auth.go +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/sso/auth.go @@ -16,8 +16,9 @@ import ( "strings" ) -func bindAuthParamsRegion(_ interface{}, params *AuthResolverParameters, _ interface{}, options Options) { +func bindAuthParamsRegion(_ interface{}, params *AuthResolverParameters, _ interface{}, options Options) error { params.Region = options.Region + return nil } type setLegacyContextSigningOptionsMiddleware struct { @@ -94,14 +95,16 @@ type AuthResolverParameters struct { Region string } -func bindAuthResolverParams(ctx context.Context, operation string, input interface{}, options Options) *AuthResolverParameters { +func bindAuthResolverParams(ctx context.Context, operation string, input interface{}, options Options) (*AuthResolverParameters, error) { params := &AuthResolverParameters{ Operation: operation, } - bindAuthParamsRegion(ctx, params, input, options) + if err := bindAuthParamsRegion(ctx, params, input, options); err != nil { + return nil, err + } - return params + return params, nil } // AuthSchemeResolver returns a set of possible authentication options for an @@ -176,7 +179,10 @@ func (m *resolveAuthSchemeMiddleware) HandleFinalize(ctx context.Context, in mid _, span := tracing.StartSpan(ctx, "ResolveAuthScheme") defer span.End() - params := bindAuthResolverParams(ctx, m.operation, getOperationInput(ctx), m.options) + params, err := bindAuthResolverParams(ctx, m.operation, getOperationInput(ctx), m.options) + if err != nil { + return out, metadata, fmt.Errorf("bind auth scheme params: %w", err) + } options, err := m.options.AuthSchemeResolver.ResolveAuthSchemes(ctx, params) if err != nil { return out, metadata, fmt.Errorf("resolve auth scheme: %w", err) diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/sso/endpoints.go b/vendor/github.com/aws/aws-sdk-go-v2/service/sso/endpoints.go index 2b22ab779c2..551f05974e8 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/sso/endpoints.go +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/sso/endpoints.go @@ -14,6 +14,7 @@ import ( internalendpoints "github.com/aws/aws-sdk-go-v2/service/sso/internal/endpoints" smithyauth "github.com/aws/smithy-go/auth" smithyendpoints "github.com/aws/smithy-go/endpoints" + "github.com/aws/smithy-go/endpoints/private/rulesfn" "github.com/aws/smithy-go/middleware" "github.com/aws/smithy-go/ptr" "github.com/aws/smithy-go/tracing" @@ -217,11 +218,15 @@ func resolveBaseEndpoint(cfg aws.Config, o *Options) { } } -func bindRegion(region string) *string { +func bindRegion(region string) (*string, error) { if region == "" { - return nil + return nil, nil + } + if !rulesfn.IsValidHostLabel(region, true) { + return nil, fmt.Errorf("invalid input region %s", region) } - return aws.String(endpoints.MapFIPSRegion(region)) + + return aws.String(endpoints.MapFIPSRegion(region)), nil } // EndpointParameters provides the parameters that influence how endpoints are @@ -479,10 +484,15 @@ type endpointParamsBinder interface { bindEndpointParams(*EndpointParameters) } -func bindEndpointParams(ctx context.Context, input interface{}, options Options) *EndpointParameters { +func bindEndpointParams(ctx context.Context, input interface{}, options Options) (*EndpointParameters, error) { params := &EndpointParameters{} - params.Region = bindRegion(options.Region) + region, err := bindRegion(options.Region) + if err != nil { + return nil, err + } + params.Region = region + params.UseDualStack = aws.Bool(options.EndpointOptions.UseDualStackEndpoint == aws.DualStackEndpointStateEnabled) params.UseFIPS = aws.Bool(options.EndpointOptions.UseFIPSEndpoint == aws.FIPSEndpointStateEnabled) params.Endpoint = options.BaseEndpoint @@ -491,7 +501,7 @@ func bindEndpointParams(ctx context.Context, input interface{}, options Options) b.bindEndpointParams(params) } - return params + return params, nil } type resolveEndpointV2Middleware struct { @@ -521,7 +531,10 @@ func (m *resolveEndpointV2Middleware) HandleFinalize(ctx context.Context, in mid return out, metadata, fmt.Errorf("expected endpoint resolver to not be nil") } - params := bindEndpointParams(ctx, getOperationInput(ctx), m.options) + params, err := bindEndpointParams(ctx, getOperationInput(ctx), m.options) + if err != nil { + return out, metadata, fmt.Errorf("failed to bind endpoint params, %w", err) + } endpt, err := timeOperationMetric(ctx, "client.call.resolve_endpoint_duration", func() (smithyendpoints.Endpoint, error) { return m.options.EndpointResolverV2.ResolveEndpoint(ctx, *params) diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/sso/generated.json b/vendor/github.com/aws/aws-sdk-go-v2/service/sso/generated.json index 1a88fe4df8e..1499c0a9591 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/sso/generated.json +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/sso/generated.json @@ -30,7 +30,7 @@ "types/types.go", "validators.go" ], - "go": "1.22", + "go": "1.23", "module": "github.com/aws/aws-sdk-go-v2/service/sso", "unstable": false } diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/sso/go_module_metadata.go b/vendor/github.com/aws/aws-sdk-go-v2/service/sso/go_module_metadata.go index 3628768ce40..5d9e65e303f 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/sso/go_module_metadata.go +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/sso/go_module_metadata.go @@ -3,4 +3,4 @@ package sso // goModuleVersion is the tagged release for this module -const goModuleVersion = "1.29.6" +const goModuleVersion = "1.30.8" diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/sso/internal/endpoints/endpoints.go b/vendor/github.com/aws/aws-sdk-go-v2/service/sso/internal/endpoints/endpoints.go index 8bb8730be07..182423b4e6c 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/sso/internal/endpoints/endpoints.go +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/sso/internal/endpoints/endpoints.go @@ -157,6 +157,9 @@ var defaultPartitions = endpoints.Partitions{ Region: "ap-east-1", }, }, + endpoints.EndpointKey{ + Region: "ap-east-2", + }: endpoints.Endpoint{}, endpoints.EndpointKey{ Region: "ap-northeast-1", }: endpoints.Endpoint{ @@ -445,6 +448,13 @@ var defaultPartitions = endpoints.Partitions{ { ID: "aws-eusc", Defaults: map[endpoints.DefaultKey]endpoints.Endpoint{ + { + Variant: endpoints.DualStackVariant, + }: { + Hostname: "portal.sso.{region}.api.amazonwebservices.eu", + Protocols: []string{"https"}, + SignatureVersions: []string{"v4"}, + }, { Variant: endpoints.FIPSVariant, }: { @@ -452,6 +462,13 @@ var defaultPartitions = endpoints.Partitions{ Protocols: []string{"https"}, SignatureVersions: []string{"v4"}, }, + { + Variant: endpoints.FIPSVariant | endpoints.DualStackVariant, + }: { + Hostname: "portal.sso-fips.{region}.api.amazonwebservices.eu", + Protocols: []string{"https"}, + SignatureVersions: []string{"v4"}, + }, { Variant: 0, }: { diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssooidc/CHANGELOG.md b/vendor/github.com/aws/aws-sdk-go-v2/service/ssooidc/CHANGELOG.md index dc5e399a88b..0ac3f8cc4c9 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssooidc/CHANGELOG.md +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/ssooidc/CHANGELOG.md @@ -1,3 +1,52 @@ +# v1.35.12 (2025-12-08) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.35.11 (2025-12-02) + +* **Dependency Update**: Updated to the latest SDK module versions +* **Dependency Update**: Upgrade to smithy-go v1.24.0. Notably this version of the library reduces the allocation footprint of the middleware system. We observe a ~10% reduction in allocations per SDK call with this change. + +# v1.35.10 (2025-11-25) + +* **Bug Fix**: Add error check for endpoint param binding during auth scheme resolution to fix panic reported in #3234 + +# v1.35.9 (2025-11-21) + +* No change notes available for this release. + +# v1.35.8 (2025-11-19.2) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.35.7 (2025-11-12) + +* **Bug Fix**: Further reduce allocation overhead when the metrics system isn't in-use. +* **Bug Fix**: Reduce allocation overhead when the client doesn't have any HTTP interceptors configured. +* **Bug Fix**: Remove blank trace spans towards the beginning of the request that added no additional information. This conveys a slight reduction in overall allocations. + +# v1.35.6 (2025-11-11) + +* **Bug Fix**: Return validation error if input region is not a valid host label. + +# v1.35.5 (2025-11-04) + +* **Dependency Update**: Updated to the latest SDK module versions +* **Dependency Update**: Upgrade to smithy-go v1.23.2 which should convey some passive reduction of overall allocations, especially when not using the metrics system. + +# v1.35.4 (2025-10-30) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.35.3 (2025-10-23) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.35.2 (2025-10-16) + +* **Dependency Update**: Bump minimum Go version to 1.23. +* **Dependency Update**: Updated to the latest SDK module versions + # v1.35.1 (2025-09-26) * **Dependency Update**: Updated to the latest SDK module versions diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssooidc/api_client.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssooidc/api_client.go index 12ad2f5d9d5..8e8508fa349 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssooidc/api_client.go +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/ssooidc/api_client.go @@ -65,7 +65,12 @@ func timeOperationMetric[T any]( ctx context.Context, metric string, fn func() (T, error), opts ...metrics.RecordMetricOption, ) (T, error) { - instr := getOperationMetrics(ctx).histogramFor(metric) + mm := getOperationMetrics(ctx) + if mm == nil { // not using the metrics system + return fn() + } + + instr := mm.histogramFor(metric) opts = append([]metrics.RecordMetricOption{withOperationMetadata(ctx)}, opts...) start := time.Now() @@ -78,7 +83,12 @@ func timeOperationMetric[T any]( } func startMetricTimer(ctx context.Context, metric string, opts ...metrics.RecordMetricOption) func() { - instr := getOperationMetrics(ctx).histogramFor(metric) + mm := getOperationMetrics(ctx) + if mm == nil { // not using the metrics system + return func() {} + } + + instr := mm.histogramFor(metric) opts = append([]metrics.RecordMetricOption{withOperationMetadata(ctx)}, opts...) var ended bool @@ -106,6 +116,12 @@ func withOperationMetadata(ctx context.Context) metrics.RecordMetricOption { type operationMetricsKey struct{} func withOperationMetrics(parent context.Context, mp metrics.MeterProvider) (context.Context, error) { + if _, ok := mp.(metrics.NopMeterProvider); ok { + // not using the metrics system - setting up the metrics context is a memory-intensive operation + // so we should skip it in this case + return parent, nil + } + meter := mp.Meter("github.com/aws/aws-sdk-go-v2/service/ssooidc") om := &operationMetrics{} @@ -153,7 +169,10 @@ func operationMetricTimer(m metrics.Meter, name, desc string) (metrics.Float64Hi } func getOperationMetrics(ctx context.Context) *operationMetrics { - return ctx.Value(operationMetricsKey{}).(*operationMetrics) + if v := ctx.Value(operationMetricsKey{}); v != nil { + return v.(*operationMetrics) + } + return nil } func operationTracer(p tracing.TracerProvider) tracing.Tracer { @@ -882,138 +901,49 @@ func addInterceptAttempt(stack *middleware.Stack, opts Options) error { }, "Retry", middleware.After) } -func addInterceptExecution(stack *middleware.Stack, opts Options) error { - return stack.Initialize.Add(&smithyhttp.InterceptExecution{ - BeforeExecution: opts.Interceptors.BeforeExecution, - AfterExecution: opts.Interceptors.AfterExecution, - }, middleware.Before) -} - -func addInterceptBeforeSerialization(stack *middleware.Stack, opts Options) error { - return stack.Serialize.Insert(&smithyhttp.InterceptBeforeSerialization{ - Interceptors: opts.Interceptors.BeforeSerialization, - }, "OperationSerializer", middleware.Before) -} - -func addInterceptAfterSerialization(stack *middleware.Stack, opts Options) error { - return stack.Serialize.Insert(&smithyhttp.InterceptAfterSerialization{ - Interceptors: opts.Interceptors.AfterSerialization, - }, "OperationSerializer", middleware.After) -} - -func addInterceptBeforeSigning(stack *middleware.Stack, opts Options) error { - return stack.Finalize.Insert(&smithyhttp.InterceptBeforeSigning{ - Interceptors: opts.Interceptors.BeforeSigning, - }, "Signing", middleware.Before) -} - -func addInterceptAfterSigning(stack *middleware.Stack, opts Options) error { - return stack.Finalize.Insert(&smithyhttp.InterceptAfterSigning{ - Interceptors: opts.Interceptors.AfterSigning, - }, "Signing", middleware.After) -} - -func addInterceptTransmit(stack *middleware.Stack, opts Options) error { - return stack.Deserialize.Add(&smithyhttp.InterceptTransmit{ - BeforeTransmit: opts.Interceptors.BeforeTransmit, - AfterTransmit: opts.Interceptors.AfterTransmit, - }, middleware.After) -} - -func addInterceptBeforeDeserialization(stack *middleware.Stack, opts Options) error { - return stack.Deserialize.Insert(&smithyhttp.InterceptBeforeDeserialization{ - Interceptors: opts.Interceptors.BeforeDeserialization, - }, "OperationDeserializer", middleware.After) // (deserialize stack is called in reverse) -} - -func addInterceptAfterDeserialization(stack *middleware.Stack, opts Options) error { - return stack.Deserialize.Insert(&smithyhttp.InterceptAfterDeserialization{ - Interceptors: opts.Interceptors.AfterDeserialization, - }, "OperationDeserializer", middleware.Before) -} - -type spanInitializeStart struct { -} - -func (*spanInitializeStart) ID() string { - return "spanInitializeStart" -} - -func (m *spanInitializeStart) HandleInitialize( - ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler, -) ( - middleware.InitializeOutput, middleware.Metadata, error, -) { - ctx, _ = tracing.StartSpan(ctx, "Initialize") - - return next.HandleInitialize(ctx, in) -} - -type spanInitializeEnd struct { -} - -func (*spanInitializeEnd) ID() string { - return "spanInitializeEnd" -} - -func (m *spanInitializeEnd) HandleInitialize( - ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler, -) ( - middleware.InitializeOutput, middleware.Metadata, error, -) { - ctx, span := tracing.PopSpan(ctx) - span.End() - - return next.HandleInitialize(ctx, in) -} - -type spanBuildRequestStart struct { -} - -func (*spanBuildRequestStart) ID() string { - return "spanBuildRequestStart" -} - -func (m *spanBuildRequestStart) HandleSerialize( - ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler, -) ( - middleware.SerializeOutput, middleware.Metadata, error, -) { - ctx, _ = tracing.StartSpan(ctx, "BuildRequest") - - return next.HandleSerialize(ctx, in) -} - -type spanBuildRequestEnd struct { -} - -func (*spanBuildRequestEnd) ID() string { - return "spanBuildRequestEnd" -} - -func (m *spanBuildRequestEnd) HandleBuild( - ctx context.Context, in middleware.BuildInput, next middleware.BuildHandler, -) ( - middleware.BuildOutput, middleware.Metadata, error, -) { - ctx, span := tracing.PopSpan(ctx) - span.End() - - return next.HandleBuild(ctx, in) -} - -func addSpanInitializeStart(stack *middleware.Stack) error { - return stack.Initialize.Add(&spanInitializeStart{}, middleware.Before) -} - -func addSpanInitializeEnd(stack *middleware.Stack) error { - return stack.Initialize.Add(&spanInitializeEnd{}, middleware.After) -} - -func addSpanBuildRequestStart(stack *middleware.Stack) error { - return stack.Serialize.Add(&spanBuildRequestStart{}, middleware.Before) -} +func addInterceptors(stack *middleware.Stack, opts Options) error { + // middlewares are expensive, don't add all of these interceptor ones unless the caller + // actually has at least one interceptor configured + // + // at the moment it's all-or-nothing because some of the middlewares here are responsible for + // setting fields in the interceptor context for future ones + if len(opts.Interceptors.BeforeExecution) == 0 && + len(opts.Interceptors.BeforeSerialization) == 0 && len(opts.Interceptors.AfterSerialization) == 0 && + len(opts.Interceptors.BeforeRetryLoop) == 0 && + len(opts.Interceptors.BeforeAttempt) == 0 && + len(opts.Interceptors.BeforeSigning) == 0 && len(opts.Interceptors.AfterSigning) == 0 && + len(opts.Interceptors.BeforeTransmit) == 0 && len(opts.Interceptors.AfterTransmit) == 0 && + len(opts.Interceptors.BeforeDeserialization) == 0 && len(opts.Interceptors.AfterDeserialization) == 0 && + len(opts.Interceptors.AfterAttempt) == 0 && len(opts.Interceptors.AfterExecution) == 0 { + return nil + } -func addSpanBuildRequestEnd(stack *middleware.Stack) error { - return stack.Build.Add(&spanBuildRequestEnd{}, middleware.After) + return errors.Join( + stack.Initialize.Add(&smithyhttp.InterceptExecution{ + BeforeExecution: opts.Interceptors.BeforeExecution, + AfterExecution: opts.Interceptors.AfterExecution, + }, middleware.Before), + stack.Serialize.Insert(&smithyhttp.InterceptBeforeSerialization{ + Interceptors: opts.Interceptors.BeforeSerialization, + }, "OperationSerializer", middleware.Before), + stack.Serialize.Insert(&smithyhttp.InterceptAfterSerialization{ + Interceptors: opts.Interceptors.AfterSerialization, + }, "OperationSerializer", middleware.After), + stack.Finalize.Insert(&smithyhttp.InterceptBeforeSigning{ + Interceptors: opts.Interceptors.BeforeSigning, + }, "Signing", middleware.Before), + stack.Finalize.Insert(&smithyhttp.InterceptAfterSigning{ + Interceptors: opts.Interceptors.AfterSigning, + }, "Signing", middleware.After), + stack.Deserialize.Add(&smithyhttp.InterceptTransmit{ + BeforeTransmit: opts.Interceptors.BeforeTransmit, + AfterTransmit: opts.Interceptors.AfterTransmit, + }, middleware.After), + stack.Deserialize.Insert(&smithyhttp.InterceptBeforeDeserialization{ + Interceptors: opts.Interceptors.BeforeDeserialization, + }, "OperationDeserializer", middleware.After), // (deserialize stack is called in reverse) + stack.Deserialize.Insert(&smithyhttp.InterceptAfterDeserialization{ + Interceptors: opts.Interceptors.AfterDeserialization, + }, "OperationDeserializer", middleware.Before), + ) } diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssooidc/api_op_CreateToken.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssooidc/api_op_CreateToken.go index 681eb4087c5..3f622dbcb95 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssooidc/api_op_CreateToken.go +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/ssooidc/api_op_CreateToken.go @@ -223,40 +223,7 @@ func (c *Client) addOperationCreateTokenMiddlewares(stack *middleware.Stack, opt if err = addInterceptAttempt(stack, options); err != nil { return err } - if err = addInterceptExecution(stack, options); err != nil { - return err - } - if err = addInterceptBeforeSerialization(stack, options); err != nil { - return err - } - if err = addInterceptAfterSerialization(stack, options); err != nil { - return err - } - if err = addInterceptBeforeSigning(stack, options); err != nil { - return err - } - if err = addInterceptAfterSigning(stack, options); err != nil { - return err - } - if err = addInterceptTransmit(stack, options); err != nil { - return err - } - if err = addInterceptBeforeDeserialization(stack, options); err != nil { - return err - } - if err = addInterceptAfterDeserialization(stack, options); err != nil { - return err - } - if err = addSpanInitializeStart(stack); err != nil { - return err - } - if err = addSpanInitializeEnd(stack); err != nil { - return err - } - if err = addSpanBuildRequestStart(stack); err != nil { - return err - } - if err = addSpanBuildRequestEnd(stack); err != nil { + if err = addInterceptors(stack, options); err != nil { return err } return nil diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssooidc/api_op_CreateTokenWithIAM.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssooidc/api_op_CreateTokenWithIAM.go index d7a27da5953..24cb2fac8db 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssooidc/api_op_CreateTokenWithIAM.go +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/ssooidc/api_op_CreateTokenWithIAM.go @@ -270,40 +270,7 @@ func (c *Client) addOperationCreateTokenWithIAMMiddlewares(stack *middleware.Sta if err = addInterceptAttempt(stack, options); err != nil { return err } - if err = addInterceptExecution(stack, options); err != nil { - return err - } - if err = addInterceptBeforeSerialization(stack, options); err != nil { - return err - } - if err = addInterceptAfterSerialization(stack, options); err != nil { - return err - } - if err = addInterceptBeforeSigning(stack, options); err != nil { - return err - } - if err = addInterceptAfterSigning(stack, options); err != nil { - return err - } - if err = addInterceptTransmit(stack, options); err != nil { - return err - } - if err = addInterceptBeforeDeserialization(stack, options); err != nil { - return err - } - if err = addInterceptAfterDeserialization(stack, options); err != nil { - return err - } - if err = addSpanInitializeStart(stack); err != nil { - return err - } - if err = addSpanInitializeEnd(stack); err != nil { - return err - } - if err = addSpanBuildRequestStart(stack); err != nil { - return err - } - if err = addSpanBuildRequestEnd(stack); err != nil { + if err = addInterceptors(stack, options); err != nil { return err } return nil diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssooidc/api_op_RegisterClient.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssooidc/api_op_RegisterClient.go index 8d50092fb15..14472ee3be6 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssooidc/api_op_RegisterClient.go +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/ssooidc/api_op_RegisterClient.go @@ -194,40 +194,7 @@ func (c *Client) addOperationRegisterClientMiddlewares(stack *middleware.Stack, if err = addInterceptAttempt(stack, options); err != nil { return err } - if err = addInterceptExecution(stack, options); err != nil { - return err - } - if err = addInterceptBeforeSerialization(stack, options); err != nil { - return err - } - if err = addInterceptAfterSerialization(stack, options); err != nil { - return err - } - if err = addInterceptBeforeSigning(stack, options); err != nil { - return err - } - if err = addInterceptAfterSigning(stack, options); err != nil { - return err - } - if err = addInterceptTransmit(stack, options); err != nil { - return err - } - if err = addInterceptBeforeDeserialization(stack, options); err != nil { - return err - } - if err = addInterceptAfterDeserialization(stack, options); err != nil { - return err - } - if err = addSpanInitializeStart(stack); err != nil { - return err - } - if err = addSpanInitializeEnd(stack); err != nil { - return err - } - if err = addSpanBuildRequestStart(stack); err != nil { - return err - } - if err = addSpanBuildRequestEnd(stack); err != nil { + if err = addInterceptors(stack, options); err != nil { return err } return nil diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssooidc/api_op_StartDeviceAuthorization.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssooidc/api_op_StartDeviceAuthorization.go index 7242ac82b68..92a6854a776 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssooidc/api_op_StartDeviceAuthorization.go +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/ssooidc/api_op_StartDeviceAuthorization.go @@ -176,40 +176,7 @@ func (c *Client) addOperationStartDeviceAuthorizationMiddlewares(stack *middlewa if err = addInterceptAttempt(stack, options); err != nil { return err } - if err = addInterceptExecution(stack, options); err != nil { - return err - } - if err = addInterceptBeforeSerialization(stack, options); err != nil { - return err - } - if err = addInterceptAfterSerialization(stack, options); err != nil { - return err - } - if err = addInterceptBeforeSigning(stack, options); err != nil { - return err - } - if err = addInterceptAfterSigning(stack, options); err != nil { - return err - } - if err = addInterceptTransmit(stack, options); err != nil { - return err - } - if err = addInterceptBeforeDeserialization(stack, options); err != nil { - return err - } - if err = addInterceptAfterDeserialization(stack, options); err != nil { - return err - } - if err = addSpanInitializeStart(stack); err != nil { - return err - } - if err = addSpanInitializeEnd(stack); err != nil { - return err - } - if err = addSpanBuildRequestStart(stack); err != nil { - return err - } - if err = addSpanBuildRequestEnd(stack); err != nil { + if err = addInterceptors(stack, options); err != nil { return err } return nil diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssooidc/auth.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssooidc/auth.go index 89b01c629dd..5f253df305e 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssooidc/auth.go +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/ssooidc/auth.go @@ -16,8 +16,9 @@ import ( "strings" ) -func bindAuthParamsRegion(_ interface{}, params *AuthResolverParameters, _ interface{}, options Options) { +func bindAuthParamsRegion(_ interface{}, params *AuthResolverParameters, _ interface{}, options Options) error { params.Region = options.Region + return nil } type setLegacyContextSigningOptionsMiddleware struct { @@ -94,14 +95,16 @@ type AuthResolverParameters struct { Region string } -func bindAuthResolverParams(ctx context.Context, operation string, input interface{}, options Options) *AuthResolverParameters { +func bindAuthResolverParams(ctx context.Context, operation string, input interface{}, options Options) (*AuthResolverParameters, error) { params := &AuthResolverParameters{ Operation: operation, } - bindAuthParamsRegion(ctx, params, input, options) + if err := bindAuthParamsRegion(ctx, params, input, options); err != nil { + return nil, err + } - return params + return params, nil } // AuthSchemeResolver returns a set of possible authentication options for an @@ -170,7 +173,10 @@ func (m *resolveAuthSchemeMiddleware) HandleFinalize(ctx context.Context, in mid _, span := tracing.StartSpan(ctx, "ResolveAuthScheme") defer span.End() - params := bindAuthResolverParams(ctx, m.operation, getOperationInput(ctx), m.options) + params, err := bindAuthResolverParams(ctx, m.operation, getOperationInput(ctx), m.options) + if err != nil { + return out, metadata, fmt.Errorf("bind auth scheme params: %w", err) + } options, err := m.options.AuthSchemeResolver.ResolveAuthSchemes(ctx, params) if err != nil { return out, metadata, fmt.Errorf("resolve auth scheme: %w", err) diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssooidc/endpoints.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssooidc/endpoints.go index 1e001f7a9e8..884983eb4d0 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssooidc/endpoints.go +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/ssooidc/endpoints.go @@ -14,6 +14,7 @@ import ( internalendpoints "github.com/aws/aws-sdk-go-v2/service/ssooidc/internal/endpoints" smithyauth "github.com/aws/smithy-go/auth" smithyendpoints "github.com/aws/smithy-go/endpoints" + "github.com/aws/smithy-go/endpoints/private/rulesfn" "github.com/aws/smithy-go/middleware" "github.com/aws/smithy-go/ptr" "github.com/aws/smithy-go/tracing" @@ -217,11 +218,15 @@ func resolveBaseEndpoint(cfg aws.Config, o *Options) { } } -func bindRegion(region string) *string { +func bindRegion(region string) (*string, error) { if region == "" { - return nil + return nil, nil + } + if !rulesfn.IsValidHostLabel(region, true) { + return nil, fmt.Errorf("invalid input region %s", region) } - return aws.String(endpoints.MapFIPSRegion(region)) + + return aws.String(endpoints.MapFIPSRegion(region)), nil } // EndpointParameters provides the parameters that influence how endpoints are @@ -479,10 +484,15 @@ type endpointParamsBinder interface { bindEndpointParams(*EndpointParameters) } -func bindEndpointParams(ctx context.Context, input interface{}, options Options) *EndpointParameters { +func bindEndpointParams(ctx context.Context, input interface{}, options Options) (*EndpointParameters, error) { params := &EndpointParameters{} - params.Region = bindRegion(options.Region) + region, err := bindRegion(options.Region) + if err != nil { + return nil, err + } + params.Region = region + params.UseDualStack = aws.Bool(options.EndpointOptions.UseDualStackEndpoint == aws.DualStackEndpointStateEnabled) params.UseFIPS = aws.Bool(options.EndpointOptions.UseFIPSEndpoint == aws.FIPSEndpointStateEnabled) params.Endpoint = options.BaseEndpoint @@ -491,7 +501,7 @@ func bindEndpointParams(ctx context.Context, input interface{}, options Options) b.bindEndpointParams(params) } - return params + return params, nil } type resolveEndpointV2Middleware struct { @@ -521,7 +531,10 @@ func (m *resolveEndpointV2Middleware) HandleFinalize(ctx context.Context, in mid return out, metadata, fmt.Errorf("expected endpoint resolver to not be nil") } - params := bindEndpointParams(ctx, getOperationInput(ctx), m.options) + params, err := bindEndpointParams(ctx, getOperationInput(ctx), m.options) + if err != nil { + return out, metadata, fmt.Errorf("failed to bind endpoint params, %w", err) + } endpt, err := timeOperationMetric(ctx, "client.call.resolve_endpoint_duration", func() (smithyendpoints.Endpoint, error) { return m.options.EndpointResolverV2.ResolveEndpoint(ctx, *params) diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssooidc/generated.json b/vendor/github.com/aws/aws-sdk-go-v2/service/ssooidc/generated.json index f3b0b242acc..ee79b48eaa5 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssooidc/generated.json +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/ssooidc/generated.json @@ -31,7 +31,7 @@ "types/types.go", "validators.go" ], - "go": "1.22", + "go": "1.23", "module": "github.com/aws/aws-sdk-go-v2/service/ssooidc", "unstable": false } diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssooidc/go_module_metadata.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssooidc/go_module_metadata.go index 765f6371dae..13996510020 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssooidc/go_module_metadata.go +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/ssooidc/go_module_metadata.go @@ -3,4 +3,4 @@ package ssooidc // goModuleVersion is the tagged release for this module -const goModuleVersion = "1.35.1" +const goModuleVersion = "1.35.12" diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssooidc/internal/endpoints/endpoints.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssooidc/internal/endpoints/endpoints.go index f15c1a3ff52..2088fc7fb22 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssooidc/internal/endpoints/endpoints.go +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/ssooidc/internal/endpoints/endpoints.go @@ -157,6 +157,9 @@ var defaultPartitions = endpoints.Partitions{ Region: "ap-east-1", }, }, + endpoints.EndpointKey{ + Region: "ap-east-2", + }: endpoints.Endpoint{}, endpoints.EndpointKey{ Region: "ap-northeast-1", }: endpoints.Endpoint{ @@ -445,6 +448,13 @@ var defaultPartitions = endpoints.Partitions{ { ID: "aws-eusc", Defaults: map[endpoints.DefaultKey]endpoints.Endpoint{ + { + Variant: endpoints.DualStackVariant, + }: { + Hostname: "oidc.{region}.api.amazonwebservices.eu", + Protocols: []string{"https"}, + SignatureVersions: []string{"v4"}, + }, { Variant: endpoints.FIPSVariant, }: { @@ -452,6 +462,13 @@ var defaultPartitions = endpoints.Partitions{ Protocols: []string{"https"}, SignatureVersions: []string{"v4"}, }, + { + Variant: endpoints.FIPSVariant | endpoints.DualStackVariant, + }: { + Hostname: "oidc-fips.{region}.api.amazonwebservices.eu", + Protocols: []string{"https"}, + SignatureVersions: []string{"v4"}, + }, { Variant: 0, }: { diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/sts/CHANGELOG.md b/vendor/github.com/aws/aws-sdk-go-v2/service/sts/CHANGELOG.md index 77183922d3c..42c252ba1fa 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/sts/CHANGELOG.md +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/sts/CHANGELOG.md @@ -1,3 +1,65 @@ +# v1.41.5 (2025-12-09) + +* No change notes available for this release. + +# v1.41.4 (2025-12-08) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.41.3 (2025-12-02) + +* **Dependency Update**: Updated to the latest SDK module versions +* **Dependency Update**: Upgrade to smithy-go v1.24.0. Notably this version of the library reduces the allocation footprint of the middleware system. We observe a ~10% reduction in allocations per SDK call with this change. + +# v1.41.2 (2025-11-25) + +* **Bug Fix**: Add error check for endpoint param binding during auth scheme resolution to fix panic reported in #3234 + +# v1.41.1 (2025-11-19.2) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.41.0 (2025-11-19) + +* **Feature**: IAM now supports outbound identity federation via the STS GetWebIdentityToken API, enabling AWS workloads to securely authenticate with external services using short-lived JSON Web Tokens. + +# v1.40.2 (2025-11-12) + +* **Bug Fix**: Further reduce allocation overhead when the metrics system isn't in-use. +* **Bug Fix**: Reduce allocation overhead when the client doesn't have any HTTP interceptors configured. +* **Bug Fix**: Remove blank trace spans towards the beginning of the request that added no additional information. This conveys a slight reduction in overall allocations. + +# v1.40.1 (2025-11-11) + +* **Bug Fix**: Return validation error if input region is not a valid host label. + +# v1.40.0 (2025-11-10) + +* **Feature**: Added GetDelegatedAccessToken API, which is not available for general use at this time. + +# v1.39.1 (2025-11-04) + +* **Dependency Update**: Updated to the latest SDK module versions +* **Dependency Update**: Upgrade to smithy-go v1.23.2 which should convey some passive reduction of overall allocations, especially when not using the metrics system. + +# v1.39.0 (2025-10-30) + +* **Feature**: Update endpoint ruleset parameters casing +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.38.9 (2025-10-23) + +* **Dependency Update**: Updated to the latest SDK module versions + +# v1.38.8 (2025-10-22) + +* No change notes available for this release. + +# v1.38.7 (2025-10-16) + +* **Dependency Update**: Bump minimum Go version to 1.23. +* **Dependency Update**: Updated to the latest SDK module versions + # v1.38.6 (2025-09-26) * **Dependency Update**: Updated to the latest SDK module versions diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/sts/api_client.go b/vendor/github.com/aws/aws-sdk-go-v2/service/sts/api_client.go index 6658babc95f..70228d0dfa7 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/sts/api_client.go +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/sts/api_client.go @@ -68,7 +68,12 @@ func timeOperationMetric[T any]( ctx context.Context, metric string, fn func() (T, error), opts ...metrics.RecordMetricOption, ) (T, error) { - instr := getOperationMetrics(ctx).histogramFor(metric) + mm := getOperationMetrics(ctx) + if mm == nil { // not using the metrics system + return fn() + } + + instr := mm.histogramFor(metric) opts = append([]metrics.RecordMetricOption{withOperationMetadata(ctx)}, opts...) start := time.Now() @@ -81,7 +86,12 @@ func timeOperationMetric[T any]( } func startMetricTimer(ctx context.Context, metric string, opts ...metrics.RecordMetricOption) func() { - instr := getOperationMetrics(ctx).histogramFor(metric) + mm := getOperationMetrics(ctx) + if mm == nil { // not using the metrics system + return func() {} + } + + instr := mm.histogramFor(metric) opts = append([]metrics.RecordMetricOption{withOperationMetadata(ctx)}, opts...) var ended bool @@ -109,6 +119,12 @@ func withOperationMetadata(ctx context.Context) metrics.RecordMetricOption { type operationMetricsKey struct{} func withOperationMetrics(parent context.Context, mp metrics.MeterProvider) (context.Context, error) { + if _, ok := mp.(metrics.NopMeterProvider); ok { + // not using the metrics system - setting up the metrics context is a memory-intensive operation + // so we should skip it in this case + return parent, nil + } + meter := mp.Meter("github.com/aws/aws-sdk-go-v2/service/sts") om := &operationMetrics{} @@ -156,7 +172,10 @@ func operationMetricTimer(m metrics.Meter, name, desc string) (metrics.Float64Hi } func getOperationMetrics(ctx context.Context) *operationMetrics { - return ctx.Value(operationMetricsKey{}).(*operationMetrics) + if v := ctx.Value(operationMetricsKey{}); v != nil { + return v.(*operationMetrics) + } + return nil } func operationTracer(p tracing.TracerProvider) tracing.Tracer { @@ -1034,138 +1053,49 @@ func addInterceptAttempt(stack *middleware.Stack, opts Options) error { }, "Retry", middleware.After) } -func addInterceptExecution(stack *middleware.Stack, opts Options) error { - return stack.Initialize.Add(&smithyhttp.InterceptExecution{ - BeforeExecution: opts.Interceptors.BeforeExecution, - AfterExecution: opts.Interceptors.AfterExecution, - }, middleware.Before) -} - -func addInterceptBeforeSerialization(stack *middleware.Stack, opts Options) error { - return stack.Serialize.Insert(&smithyhttp.InterceptBeforeSerialization{ - Interceptors: opts.Interceptors.BeforeSerialization, - }, "OperationSerializer", middleware.Before) -} - -func addInterceptAfterSerialization(stack *middleware.Stack, opts Options) error { - return stack.Serialize.Insert(&smithyhttp.InterceptAfterSerialization{ - Interceptors: opts.Interceptors.AfterSerialization, - }, "OperationSerializer", middleware.After) -} - -func addInterceptBeforeSigning(stack *middleware.Stack, opts Options) error { - return stack.Finalize.Insert(&smithyhttp.InterceptBeforeSigning{ - Interceptors: opts.Interceptors.BeforeSigning, - }, "Signing", middleware.Before) -} - -func addInterceptAfterSigning(stack *middleware.Stack, opts Options) error { - return stack.Finalize.Insert(&smithyhttp.InterceptAfterSigning{ - Interceptors: opts.Interceptors.AfterSigning, - }, "Signing", middleware.After) -} - -func addInterceptTransmit(stack *middleware.Stack, opts Options) error { - return stack.Deserialize.Add(&smithyhttp.InterceptTransmit{ - BeforeTransmit: opts.Interceptors.BeforeTransmit, - AfterTransmit: opts.Interceptors.AfterTransmit, - }, middleware.After) -} - -func addInterceptBeforeDeserialization(stack *middleware.Stack, opts Options) error { - return stack.Deserialize.Insert(&smithyhttp.InterceptBeforeDeserialization{ - Interceptors: opts.Interceptors.BeforeDeserialization, - }, "OperationDeserializer", middleware.After) // (deserialize stack is called in reverse) -} - -func addInterceptAfterDeserialization(stack *middleware.Stack, opts Options) error { - return stack.Deserialize.Insert(&smithyhttp.InterceptAfterDeserialization{ - Interceptors: opts.Interceptors.AfterDeserialization, - }, "OperationDeserializer", middleware.Before) -} - -type spanInitializeStart struct { -} - -func (*spanInitializeStart) ID() string { - return "spanInitializeStart" -} - -func (m *spanInitializeStart) HandleInitialize( - ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler, -) ( - middleware.InitializeOutput, middleware.Metadata, error, -) { - ctx, _ = tracing.StartSpan(ctx, "Initialize") - - return next.HandleInitialize(ctx, in) -} - -type spanInitializeEnd struct { -} - -func (*spanInitializeEnd) ID() string { - return "spanInitializeEnd" -} - -func (m *spanInitializeEnd) HandleInitialize( - ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler, -) ( - middleware.InitializeOutput, middleware.Metadata, error, -) { - ctx, span := tracing.PopSpan(ctx) - span.End() - - return next.HandleInitialize(ctx, in) -} - -type spanBuildRequestStart struct { -} - -func (*spanBuildRequestStart) ID() string { - return "spanBuildRequestStart" -} - -func (m *spanBuildRequestStart) HandleSerialize( - ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler, -) ( - middleware.SerializeOutput, middleware.Metadata, error, -) { - ctx, _ = tracing.StartSpan(ctx, "BuildRequest") - - return next.HandleSerialize(ctx, in) -} - -type spanBuildRequestEnd struct { -} - -func (*spanBuildRequestEnd) ID() string { - return "spanBuildRequestEnd" -} - -func (m *spanBuildRequestEnd) HandleBuild( - ctx context.Context, in middleware.BuildInput, next middleware.BuildHandler, -) ( - middleware.BuildOutput, middleware.Metadata, error, -) { - ctx, span := tracing.PopSpan(ctx) - span.End() - - return next.HandleBuild(ctx, in) -} - -func addSpanInitializeStart(stack *middleware.Stack) error { - return stack.Initialize.Add(&spanInitializeStart{}, middleware.Before) -} - -func addSpanInitializeEnd(stack *middleware.Stack) error { - return stack.Initialize.Add(&spanInitializeEnd{}, middleware.After) -} - -func addSpanBuildRequestStart(stack *middleware.Stack) error { - return stack.Serialize.Add(&spanBuildRequestStart{}, middleware.Before) -} +func addInterceptors(stack *middleware.Stack, opts Options) error { + // middlewares are expensive, don't add all of these interceptor ones unless the caller + // actually has at least one interceptor configured + // + // at the moment it's all-or-nothing because some of the middlewares here are responsible for + // setting fields in the interceptor context for future ones + if len(opts.Interceptors.BeforeExecution) == 0 && + len(opts.Interceptors.BeforeSerialization) == 0 && len(opts.Interceptors.AfterSerialization) == 0 && + len(opts.Interceptors.BeforeRetryLoop) == 0 && + len(opts.Interceptors.BeforeAttempt) == 0 && + len(opts.Interceptors.BeforeSigning) == 0 && len(opts.Interceptors.AfterSigning) == 0 && + len(opts.Interceptors.BeforeTransmit) == 0 && len(opts.Interceptors.AfterTransmit) == 0 && + len(opts.Interceptors.BeforeDeserialization) == 0 && len(opts.Interceptors.AfterDeserialization) == 0 && + len(opts.Interceptors.AfterAttempt) == 0 && len(opts.Interceptors.AfterExecution) == 0 { + return nil + } -func addSpanBuildRequestEnd(stack *middleware.Stack) error { - return stack.Build.Add(&spanBuildRequestEnd{}, middleware.After) + return errors.Join( + stack.Initialize.Add(&smithyhttp.InterceptExecution{ + BeforeExecution: opts.Interceptors.BeforeExecution, + AfterExecution: opts.Interceptors.AfterExecution, + }, middleware.Before), + stack.Serialize.Insert(&smithyhttp.InterceptBeforeSerialization{ + Interceptors: opts.Interceptors.BeforeSerialization, + }, "OperationSerializer", middleware.Before), + stack.Serialize.Insert(&smithyhttp.InterceptAfterSerialization{ + Interceptors: opts.Interceptors.AfterSerialization, + }, "OperationSerializer", middleware.After), + stack.Finalize.Insert(&smithyhttp.InterceptBeforeSigning{ + Interceptors: opts.Interceptors.BeforeSigning, + }, "Signing", middleware.Before), + stack.Finalize.Insert(&smithyhttp.InterceptAfterSigning{ + Interceptors: opts.Interceptors.AfterSigning, + }, "Signing", middleware.After), + stack.Deserialize.Add(&smithyhttp.InterceptTransmit{ + BeforeTransmit: opts.Interceptors.BeforeTransmit, + AfterTransmit: opts.Interceptors.AfterTransmit, + }, middleware.After), + stack.Deserialize.Insert(&smithyhttp.InterceptBeforeDeserialization{ + Interceptors: opts.Interceptors.BeforeDeserialization, + }, "OperationDeserializer", middleware.After), // (deserialize stack is called in reverse) + stack.Deserialize.Insert(&smithyhttp.InterceptAfterDeserialization{ + Interceptors: opts.Interceptors.AfterDeserialization, + }, "OperationDeserializer", middleware.Before), + ) } diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/sts/api_op_AssumeRole.go b/vendor/github.com/aws/aws-sdk-go-v2/service/sts/api_op_AssumeRole.go index f3a93418fa0..0ddd3623ae5 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/sts/api_op_AssumeRole.go +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/sts/api_op_AssumeRole.go @@ -147,7 +147,7 @@ type AssumeRoleInput struct { // // The regex used to validate this parameter is a string of characters consisting // of upper- and lower-case alphanumeric characters with no spaces. You can also - // include underscores or any of the following characters: =,.@- + // include underscores or any of the following characters: +=,.@- // // [CloudTrail logs]: https://docs.aws.amazon.com/IAM/latest/UserGuide/cloudtrail-integration.html#cloudtrail-integration_signin-tempcreds // [sts:RoleSessionName]: https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_iam-condition-keys.html#ck_rolesessionname @@ -196,7 +196,7 @@ type AssumeRoleInput struct { // // The regex used to validate this parameter is a string of characters consisting // of upper- and lower-case alphanumeric characters with no spaces. You can also - // include underscores or any of the following characters: =,.@:/- + // include underscores or any of the following characters: +=,.@:\/- // // [How to Use an External ID When Granting Access to Your Amazon Web Services Resources to a Third Party]: https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_create_for-user_externalid.html ExternalId *string @@ -279,7 +279,7 @@ type AssumeRoleInput struct { // // The regex used to validate this parameter is a string of characters consisting // of upper- and lower-case alphanumeric characters with no spaces. You can also - // include underscores or any of the following characters: =,.@- + // include underscores or any of the following characters: +=/:,.@- SerialNumber *string // The source identity specified by the principal that is calling the AssumeRole @@ -508,40 +508,7 @@ func (c *Client) addOperationAssumeRoleMiddlewares(stack *middleware.Stack, opti if err = addInterceptAttempt(stack, options); err != nil { return err } - if err = addInterceptExecution(stack, options); err != nil { - return err - } - if err = addInterceptBeforeSerialization(stack, options); err != nil { - return err - } - if err = addInterceptAfterSerialization(stack, options); err != nil { - return err - } - if err = addInterceptBeforeSigning(stack, options); err != nil { - return err - } - if err = addInterceptAfterSigning(stack, options); err != nil { - return err - } - if err = addInterceptTransmit(stack, options); err != nil { - return err - } - if err = addInterceptBeforeDeserialization(stack, options); err != nil { - return err - } - if err = addInterceptAfterDeserialization(stack, options); err != nil { - return err - } - if err = addSpanInitializeStart(stack); err != nil { - return err - } - if err = addSpanInitializeEnd(stack); err != nil { - return err - } - if err = addSpanBuildRequestStart(stack); err != nil { - return err - } - if err = addSpanBuildRequestEnd(stack); err != nil { + if err = addInterceptors(stack, options); err != nil { return err } return nil diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/sts/api_op_AssumeRoleWithSAML.go b/vendor/github.com/aws/aws-sdk-go-v2/service/sts/api_op_AssumeRoleWithSAML.go index 9dcceec12a2..15f1dd91d29 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/sts/api_op_AssumeRoleWithSAML.go +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/sts/api_op_AssumeRoleWithSAML.go @@ -23,6 +23,9 @@ import ( // these temporary security credentials to sign calls to Amazon Web Services // services. // +// AssumeRoleWithSAML will not work on IAM Identity Center managed roles. These +// roles' names start with AWSReservedSSO_ . +// // # Session Duration // // By default, the temporary security credentials created by AssumeRoleWithSAML @@ -440,40 +443,7 @@ func (c *Client) addOperationAssumeRoleWithSAMLMiddlewares(stack *middleware.Sta if err = addInterceptAttempt(stack, options); err != nil { return err } - if err = addInterceptExecution(stack, options); err != nil { - return err - } - if err = addInterceptBeforeSerialization(stack, options); err != nil { - return err - } - if err = addInterceptAfterSerialization(stack, options); err != nil { - return err - } - if err = addInterceptBeforeSigning(stack, options); err != nil { - return err - } - if err = addInterceptAfterSigning(stack, options); err != nil { - return err - } - if err = addInterceptTransmit(stack, options); err != nil { - return err - } - if err = addInterceptBeforeDeserialization(stack, options); err != nil { - return err - } - if err = addInterceptAfterDeserialization(stack, options); err != nil { - return err - } - if err = addSpanInitializeStart(stack); err != nil { - return err - } - if err = addSpanInitializeEnd(stack); err != nil { - return err - } - if err = addSpanBuildRequestStart(stack); err != nil { - return err - } - if err = addSpanBuildRequestEnd(stack); err != nil { + if err = addInterceptors(stack, options); err != nil { return err } return nil diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/sts/api_op_AssumeRoleWithWebIdentity.go b/vendor/github.com/aws/aws-sdk-go-v2/service/sts/api_op_AssumeRoleWithWebIdentity.go index 5975a0cdee8..7006eb3b7fb 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/sts/api_op_AssumeRoleWithWebIdentity.go +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/sts/api_op_AssumeRoleWithWebIdentity.go @@ -75,7 +75,7 @@ import ( // // (Optional) You can configure your IdP to pass attributes into your web identity // token as session tags. Each session tag consists of a key name and an associated -// value. For more information about session tags, see [Passing Session Tags in STS]in the IAM User Guide. +// value. For more information about session tags, see [Passing session tags using AssumeRoleWithWebIdentity]in the IAM User Guide. // // You can pass up to 50 session tags. The plaintext session tag keys can’t exceed // 128 characters and the values can’t exceed 256 characters. For these and @@ -123,6 +123,7 @@ import ( // providers to get and use temporary security credentials. // // [Amazon Web Services SDK for iOS Developer Guide]: http://aws.amazon.com/sdkforios/ +// [Passing session tags using AssumeRoleWithWebIdentity]: https://docs.aws.amazon.com/IAM/latest/UserGuide/id_session-tags.html#id_session-tags_adding-assume-role-idp // [Amazon Web Services SDK for Android Developer Guide]: http://aws.amazon.com/sdkforandroid/ // [IAM and STS Character Limits]: https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_iam-limits.html#reference_iam-limits-entity-length // [session policies]: https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html#policies_session @@ -135,7 +136,6 @@ import ( // [Using IAM Roles]: https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use.html // [Session Policies]: https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html#policies_session // [Amazon Cognito federated identities]: https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-identity.html -// [Passing Session Tags in STS]: https://docs.aws.amazon.com/IAM/latest/UserGuide/id_session-tags.html // [Chaining Roles with Session Tags]: https://docs.aws.amazon.com/IAM/latest/UserGuide/id_session-tags.html#id_session-tags_role-chaining // [Update the maximum session duration for a role]: https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_update-role-settings.html#id_roles_update-session-duration // [Using Web Identity Federation API Operations for Mobile Apps]: https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_oidc_manual.html @@ -460,40 +460,7 @@ func (c *Client) addOperationAssumeRoleWithWebIdentityMiddlewares(stack *middlew if err = addInterceptAttempt(stack, options); err != nil { return err } - if err = addInterceptExecution(stack, options); err != nil { - return err - } - if err = addInterceptBeforeSerialization(stack, options); err != nil { - return err - } - if err = addInterceptAfterSerialization(stack, options); err != nil { - return err - } - if err = addInterceptBeforeSigning(stack, options); err != nil { - return err - } - if err = addInterceptAfterSigning(stack, options); err != nil { - return err - } - if err = addInterceptTransmit(stack, options); err != nil { - return err - } - if err = addInterceptBeforeDeserialization(stack, options); err != nil { - return err - } - if err = addInterceptAfterDeserialization(stack, options); err != nil { - return err - } - if err = addSpanInitializeStart(stack); err != nil { - return err - } - if err = addSpanInitializeEnd(stack); err != nil { - return err - } - if err = addSpanBuildRequestStart(stack); err != nil { - return err - } - if err = addSpanBuildRequestEnd(stack); err != nil { + if err = addInterceptors(stack, options); err != nil { return err } return nil diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/sts/api_op_AssumeRoot.go b/vendor/github.com/aws/aws-sdk-go-v2/service/sts/api_op_AssumeRoot.go index 571f06728a5..009c4055838 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/sts/api_op_AssumeRoot.go +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/sts/api_op_AssumeRoot.go @@ -12,7 +12,9 @@ import ( ) // Returns a set of short term credentials you can use to perform privileged tasks -// on a member account in your organization. +// on a member account in your organization. You must use credentials from an +// Organizations management account or a delegated administrator account for IAM to +// call AssumeRoot . You cannot use root user credentials to make this call. // // Before you can launch a privileged session, you must have centralized root // access in your organization. For steps to enable this feature, see [Centralize root access for member accounts]in the IAM @@ -24,8 +26,16 @@ import ( // You can track AssumeRoot in CloudTrail logs to determine what actions were // performed in a session. For more information, see [Track privileged tasks in CloudTrail]in the IAM User Guide. // +// When granting access to privileged tasks you should only grant the necessary +// permissions required to perform that task. For more information, see [Security best practices in IAM]. In +// addition, you can use [service control policies](SCPs) to manage and limit permissions in your +// organization. See [General examples]in the Organizations User Guide for more information on SCPs. +// // [Endpoints]: https://docs.aws.amazon.com/STS/latest/APIReference/welcome.html#sts-endpoints +// [Security best practices in IAM]: https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html // [Track privileged tasks in CloudTrail]: https://docs.aws.amazon.com/IAM/latest/UserGuide/cloudtrail-track-privileged-tasks.html +// [General examples]: https://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_policies_scps_examples_general.html +// [service control policies]: https://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_policies_scps.html // [Centralize root access for member accounts]: https://docs.aws.amazon.com/IAM/latest/UserGuide/id_root-enable-root-access.html func (c *Client) AssumeRoot(ctx context.Context, params *AssumeRootInput, optFns ...func(*Options)) (*AssumeRootOutput, error) { if params == nil { @@ -50,8 +60,10 @@ type AssumeRootInput struct { TargetPrincipal *string // The identity based policy that scopes the session to the privileged tasks that - // can be performed. You can use one of following Amazon Web Services managed - // policies to scope root session actions. + // can be performed. You must + // + // use one of following Amazon Web Services managed policies to scope root session + // actions: // // [IAMAuditRootUserCredentials] // @@ -205,40 +217,7 @@ func (c *Client) addOperationAssumeRootMiddlewares(stack *middleware.Stack, opti if err = addInterceptAttempt(stack, options); err != nil { return err } - if err = addInterceptExecution(stack, options); err != nil { - return err - } - if err = addInterceptBeforeSerialization(stack, options); err != nil { - return err - } - if err = addInterceptAfterSerialization(stack, options); err != nil { - return err - } - if err = addInterceptBeforeSigning(stack, options); err != nil { - return err - } - if err = addInterceptAfterSigning(stack, options); err != nil { - return err - } - if err = addInterceptTransmit(stack, options); err != nil { - return err - } - if err = addInterceptBeforeDeserialization(stack, options); err != nil { - return err - } - if err = addInterceptAfterDeserialization(stack, options); err != nil { - return err - } - if err = addSpanInitializeStart(stack); err != nil { - return err - } - if err = addSpanInitializeEnd(stack); err != nil { - return err - } - if err = addSpanBuildRequestStart(stack); err != nil { - return err - } - if err = addSpanBuildRequestEnd(stack); err != nil { + if err = addInterceptors(stack, options); err != nil { return err } return nil diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/sts/api_op_DecodeAuthorizationMessage.go b/vendor/github.com/aws/aws-sdk-go-v2/service/sts/api_op_DecodeAuthorizationMessage.go index 786bac89b8a..b00b0c4096c 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/sts/api_op_DecodeAuthorizationMessage.go +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/sts/api_op_DecodeAuthorizationMessage.go @@ -177,40 +177,7 @@ func (c *Client) addOperationDecodeAuthorizationMessageMiddlewares(stack *middle if err = addInterceptAttempt(stack, options); err != nil { return err } - if err = addInterceptExecution(stack, options); err != nil { - return err - } - if err = addInterceptBeforeSerialization(stack, options); err != nil { - return err - } - if err = addInterceptAfterSerialization(stack, options); err != nil { - return err - } - if err = addInterceptBeforeSigning(stack, options); err != nil { - return err - } - if err = addInterceptAfterSigning(stack, options); err != nil { - return err - } - if err = addInterceptTransmit(stack, options); err != nil { - return err - } - if err = addInterceptBeforeDeserialization(stack, options); err != nil { - return err - } - if err = addInterceptAfterDeserialization(stack, options); err != nil { - return err - } - if err = addSpanInitializeStart(stack); err != nil { - return err - } - if err = addSpanInitializeEnd(stack); err != nil { - return err - } - if err = addSpanBuildRequestStart(stack); err != nil { - return err - } - if err = addSpanBuildRequestEnd(stack); err != nil { + if err = addInterceptors(stack, options); err != nil { return err } return nil diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/sts/api_op_GetAccessKeyInfo.go b/vendor/github.com/aws/aws-sdk-go-v2/service/sts/api_op_GetAccessKeyInfo.go index 6c1f878981c..887bb081f3b 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/sts/api_op_GetAccessKeyInfo.go +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/sts/api_op_GetAccessKeyInfo.go @@ -168,40 +168,7 @@ func (c *Client) addOperationGetAccessKeyInfoMiddlewares(stack *middleware.Stack if err = addInterceptAttempt(stack, options); err != nil { return err } - if err = addInterceptExecution(stack, options); err != nil { - return err - } - if err = addInterceptBeforeSerialization(stack, options); err != nil { - return err - } - if err = addInterceptAfterSerialization(stack, options); err != nil { - return err - } - if err = addInterceptBeforeSigning(stack, options); err != nil { - return err - } - if err = addInterceptAfterSigning(stack, options); err != nil { - return err - } - if err = addInterceptTransmit(stack, options); err != nil { - return err - } - if err = addInterceptBeforeDeserialization(stack, options); err != nil { - return err - } - if err = addInterceptAfterDeserialization(stack, options); err != nil { - return err - } - if err = addSpanInitializeStart(stack); err != nil { - return err - } - if err = addSpanInitializeEnd(stack); err != nil { - return err - } - if err = addSpanBuildRequestStart(stack); err != nil { - return err - } - if err = addSpanBuildRequestEnd(stack); err != nil { + if err = addInterceptors(stack, options); err != nil { return err } return nil diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/sts/api_op_GetCallerIdentity.go b/vendor/github.com/aws/aws-sdk-go-v2/service/sts/api_op_GetCallerIdentity.go index 7d0653398b3..2c8d8867013 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/sts/api_op_GetCallerIdentity.go +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/sts/api_op_GetCallerIdentity.go @@ -156,40 +156,7 @@ func (c *Client) addOperationGetCallerIdentityMiddlewares(stack *middleware.Stac if err = addInterceptAttempt(stack, options); err != nil { return err } - if err = addInterceptExecution(stack, options); err != nil { - return err - } - if err = addInterceptBeforeSerialization(stack, options); err != nil { - return err - } - if err = addInterceptAfterSerialization(stack, options); err != nil { - return err - } - if err = addInterceptBeforeSigning(stack, options); err != nil { - return err - } - if err = addInterceptAfterSigning(stack, options); err != nil { - return err - } - if err = addInterceptTransmit(stack, options); err != nil { - return err - } - if err = addInterceptBeforeDeserialization(stack, options); err != nil { - return err - } - if err = addInterceptAfterDeserialization(stack, options); err != nil { - return err - } - if err = addSpanInitializeStart(stack); err != nil { - return err - } - if err = addSpanInitializeEnd(stack); err != nil { - return err - } - if err = addSpanBuildRequestStart(stack); err != nil { - return err - } - if err = addSpanBuildRequestEnd(stack); err != nil { + if err = addInterceptors(stack, options); err != nil { return err } return nil diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/sts/api_op_GetDelegatedAccessToken.go b/vendor/github.com/aws/aws-sdk-go-v2/service/sts/api_op_GetDelegatedAccessToken.go new file mode 100644 index 00000000000..092ec13e3a3 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/sts/api_op_GetDelegatedAccessToken.go @@ -0,0 +1,172 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package sts + +import ( + "context" + "fmt" + awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" + "github.com/aws/aws-sdk-go-v2/service/sts/types" + "github.com/aws/smithy-go/middleware" + smithyhttp "github.com/aws/smithy-go/transport/http" +) + +// Exchanges a trade-in token for temporary Amazon Web Services credentials with +// the permissions associated with the assumed principal. This operation allows you +// to obtain credentials for a specific principal based on a trade-in token, +// enabling delegation of access to Amazon Web Services resources. +func (c *Client) GetDelegatedAccessToken(ctx context.Context, params *GetDelegatedAccessTokenInput, optFns ...func(*Options)) (*GetDelegatedAccessTokenOutput, error) { + if params == nil { + params = &GetDelegatedAccessTokenInput{} + } + + result, metadata, err := c.invokeOperation(ctx, "GetDelegatedAccessToken", params, optFns, c.addOperationGetDelegatedAccessTokenMiddlewares) + if err != nil { + return nil, err + } + + out := result.(*GetDelegatedAccessTokenOutput) + out.ResultMetadata = metadata + return out, nil +} + +type GetDelegatedAccessTokenInput struct { + + // The token to exchange for temporary Amazon Web Services credentials. This token + // must be valid and unexpired at the time of the request. + // + // This member is required. + TradeInToken *string + + noSmithyDocumentSerde +} + +type GetDelegatedAccessTokenOutput struct { + + // The Amazon Resource Name (ARN) of the principal that was assumed when obtaining + // the delegated access token. This ARN identifies the IAM entity whose permissions + // are granted by the temporary credentials. + AssumedPrincipal *string + + // Amazon Web Services credentials for API authentication. + Credentials *types.Credentials + + // The percentage of the maximum policy size that is used by the session policy. + // The policy size is calculated as the sum of all the session policies and + // permission boundaries attached to the session. If the packed size exceeds 100%, + // the request fails. + PackedPolicySize *int32 + + // Metadata pertaining to the operation's result. + ResultMetadata middleware.Metadata + + noSmithyDocumentSerde +} + +func (c *Client) addOperationGetDelegatedAccessTokenMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } + err = stack.Serialize.Add(&awsAwsquery_serializeOpGetDelegatedAccessToken{}, middleware.After) + if err != nil { + return err + } + err = stack.Deserialize.Add(&awsAwsquery_deserializeOpGetDelegatedAccessToken{}, middleware.After) + if err != nil { + return err + } + if err := addProtocolFinalizerMiddlewares(stack, options, "GetDelegatedAccessToken"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + + if err = addlegacyEndpointContextSetter(stack, options); err != nil { + return err + } + if err = addSetLoggerMiddleware(stack, options); err != nil { + return err + } + if err = addClientRequestID(stack); err != nil { + return err + } + if err = addComputeContentLength(stack); err != nil { + return err + } + if err = addResolveEndpointMiddleware(stack, options); err != nil { + return err + } + if err = addComputePayloadSHA256(stack); err != nil { + return err + } + if err = addRetry(stack, options); err != nil { + return err + } + if err = addRawResponseToMetadata(stack); err != nil { + return err + } + if err = addRecordResponseTiming(stack); err != nil { + return err + } + if err = addSpanRetryLoop(stack, options); err != nil { + return err + } + if err = addClientUserAgent(stack, options); err != nil { + return err + } + if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { + return err + } + if err = addCredentialSource(stack, options); err != nil { + return err + } + if err = addOpGetDelegatedAccessTokenValidationMiddleware(stack); err != nil { + return err + } + if err = stack.Initialize.Add(newServiceMetadataMiddleware_opGetDelegatedAccessToken(options.Region), middleware.Before); err != nil { + return err + } + if err = addRecursionDetection(stack); err != nil { + return err + } + if err = addRequestIDRetrieverMiddleware(stack); err != nil { + return err + } + if err = addResponseErrorMiddleware(stack); err != nil { + return err + } + if err = addRequestResponseLogging(stack, options); err != nil { + return err + } + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addInterceptBeforeRetryLoop(stack, options); err != nil { + return err + } + if err = addInterceptAttempt(stack, options); err != nil { + return err + } + if err = addInterceptors(stack, options); err != nil { + return err + } + return nil +} + +func newServiceMetadataMiddleware_opGetDelegatedAccessToken(region string) *awsmiddleware.RegisterServiceMetadata { + return &awsmiddleware.RegisterServiceMetadata{ + Region: region, + ServiceID: ServiceID, + OperationName: "GetDelegatedAccessToken", + } +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/sts/api_op_GetFederationToken.go b/vendor/github.com/aws/aws-sdk-go-v2/service/sts/api_op_GetFederationToken.go index 1c2f28e519c..e0fc9a54848 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/sts/api_op_GetFederationToken.go +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/sts/api_op_GetFederationToken.go @@ -381,40 +381,7 @@ func (c *Client) addOperationGetFederationTokenMiddlewares(stack *middleware.Sta if err = addInterceptAttempt(stack, options); err != nil { return err } - if err = addInterceptExecution(stack, options); err != nil { - return err - } - if err = addInterceptBeforeSerialization(stack, options); err != nil { - return err - } - if err = addInterceptAfterSerialization(stack, options); err != nil { - return err - } - if err = addInterceptBeforeSigning(stack, options); err != nil { - return err - } - if err = addInterceptAfterSigning(stack, options); err != nil { - return err - } - if err = addInterceptTransmit(stack, options); err != nil { - return err - } - if err = addInterceptBeforeDeserialization(stack, options); err != nil { - return err - } - if err = addInterceptAfterDeserialization(stack, options); err != nil { - return err - } - if err = addSpanInitializeStart(stack); err != nil { - return err - } - if err = addSpanInitializeEnd(stack); err != nil { - return err - } - if err = addSpanBuildRequestStart(stack); err != nil { - return err - } - if err = addSpanBuildRequestEnd(stack); err != nil { + if err = addInterceptors(stack, options); err != nil { return err } return nil diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/sts/api_op_GetSessionToken.go b/vendor/github.com/aws/aws-sdk-go-v2/service/sts/api_op_GetSessionToken.go index 25604699009..2f931f4446d 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/sts/api_op_GetSessionToken.go +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/sts/api_op_GetSessionToken.go @@ -227,40 +227,7 @@ func (c *Client) addOperationGetSessionTokenMiddlewares(stack *middleware.Stack, if err = addInterceptAttempt(stack, options); err != nil { return err } - if err = addInterceptExecution(stack, options); err != nil { - return err - } - if err = addInterceptBeforeSerialization(stack, options); err != nil { - return err - } - if err = addInterceptAfterSerialization(stack, options); err != nil { - return err - } - if err = addInterceptBeforeSigning(stack, options); err != nil { - return err - } - if err = addInterceptAfterSigning(stack, options); err != nil { - return err - } - if err = addInterceptTransmit(stack, options); err != nil { - return err - } - if err = addInterceptBeforeDeserialization(stack, options); err != nil { - return err - } - if err = addInterceptAfterDeserialization(stack, options); err != nil { - return err - } - if err = addSpanInitializeStart(stack); err != nil { - return err - } - if err = addSpanInitializeEnd(stack); err != nil { - return err - } - if err = addSpanBuildRequestStart(stack); err != nil { - return err - } - if err = addSpanBuildRequestEnd(stack); err != nil { + if err = addInterceptors(stack, options); err != nil { return err } return nil diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/sts/api_op_GetWebIdentityToken.go b/vendor/github.com/aws/aws-sdk-go-v2/service/sts/api_op_GetWebIdentityToken.go new file mode 100644 index 00000000000..306ee43b1e2 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/sts/api_op_GetWebIdentityToken.go @@ -0,0 +1,195 @@ +// Code generated by smithy-go-codegen DO NOT EDIT. + +package sts + +import ( + "context" + "fmt" + awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" + "github.com/aws/aws-sdk-go-v2/service/sts/types" + "github.com/aws/smithy-go/middleware" + smithyhttp "github.com/aws/smithy-go/transport/http" + "time" +) + +// Returns a signed JSON Web Token (JWT) that represents the calling Amazon Web +// Services identity. The returned JWT can be used to authenticate with external +// services that support OIDC discovery. The token is signed by Amazon Web Services +// STS and can be publicly verified using the verification keys published at the +// issuer's JWKS endpoint. +func (c *Client) GetWebIdentityToken(ctx context.Context, params *GetWebIdentityTokenInput, optFns ...func(*Options)) (*GetWebIdentityTokenOutput, error) { + if params == nil { + params = &GetWebIdentityTokenInput{} + } + + result, metadata, err := c.invokeOperation(ctx, "GetWebIdentityToken", params, optFns, c.addOperationGetWebIdentityTokenMiddlewares) + if err != nil { + return nil, err + } + + out := result.(*GetWebIdentityTokenOutput) + out.ResultMetadata = metadata + return out, nil +} + +type GetWebIdentityTokenInput struct { + + // The intended recipient of the web identity token. This value populates the aud + // claim in the JWT and should identify the service or application that will + // validate and use the token. The external service should verify this claim to + // ensure the token was intended for their use. + // + // This member is required. + Audience []string + + // The cryptographic algorithm to use for signing the JSON Web Token (JWT). Valid + // values are RS256 (RSA with SHA-256) and ES384 (ECDSA using P-384 curve with + // SHA-384). + // + // This member is required. + SigningAlgorithm *string + + // The duration, in seconds, for which the JSON Web Token (JWT) will remain valid. + // The value can range from 60 seconds (1 minute) to 3600 seconds (1 hour). If not + // specified, the default duration is 300 seconds (5 minutes). The token is + // designed to be short-lived and should be used for proof of identity, then + // exchanged for credentials or short-lived tokens in the external service. + DurationSeconds *int32 + + // An optional list of tags to include in the JSON Web Token (JWT). These tags are + // added as custom claims to the JWT and can be used by the downstream service for + // authorization decisions. + Tags []types.Tag + + noSmithyDocumentSerde +} + +type GetWebIdentityTokenOutput struct { + + // The date and time when the web identity token expires, in UTC. The expiration + // is determined by adding the DurationSeconds value to the time the token was + // issued. After this time, the token should no longer be considered valid. + Expiration *time.Time + + // A signed JSON Web Token (JWT) that represents the caller's Amazon Web Services + // identity. The token contains standard JWT claims such as subject, audience, + // expiration time, and additional identity attributes added by STS as custom + // claims. You can also add your own custom claims to the token by passing tags as + // request parameters to the GetWebIdentityToken API. The token is signed using + // the specified signing algorithm and can be verified using the verification keys + // available at the issuer's JWKS endpoint. + WebIdentityToken *string + + // Metadata pertaining to the operation's result. + ResultMetadata middleware.Metadata + + noSmithyDocumentSerde +} + +func (c *Client) addOperationGetWebIdentityTokenMiddlewares(stack *middleware.Stack, options Options) (err error) { + if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { + return err + } + err = stack.Serialize.Add(&awsAwsquery_serializeOpGetWebIdentityToken{}, middleware.After) + if err != nil { + return err + } + err = stack.Deserialize.Add(&awsAwsquery_deserializeOpGetWebIdentityToken{}, middleware.After) + if err != nil { + return err + } + if err := addProtocolFinalizerMiddlewares(stack, options, "GetWebIdentityToken"); err != nil { + return fmt.Errorf("add protocol finalizers: %v", err) + } + + if err = addlegacyEndpointContextSetter(stack, options); err != nil { + return err + } + if err = addSetLoggerMiddleware(stack, options); err != nil { + return err + } + if err = addClientRequestID(stack); err != nil { + return err + } + if err = addComputeContentLength(stack); err != nil { + return err + } + if err = addResolveEndpointMiddleware(stack, options); err != nil { + return err + } + if err = addComputePayloadSHA256(stack); err != nil { + return err + } + if err = addRetry(stack, options); err != nil { + return err + } + if err = addRawResponseToMetadata(stack); err != nil { + return err + } + if err = addRecordResponseTiming(stack); err != nil { + return err + } + if err = addSpanRetryLoop(stack, options); err != nil { + return err + } + if err = addClientUserAgent(stack, options); err != nil { + return err + } + if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { + return err + } + if err = addSetLegacyContextSigningOptionsMiddleware(stack); err != nil { + return err + } + if err = addTimeOffsetBuild(stack, c); err != nil { + return err + } + if err = addUserAgentRetryMode(stack, options); err != nil { + return err + } + if err = addCredentialSource(stack, options); err != nil { + return err + } + if err = addOpGetWebIdentityTokenValidationMiddleware(stack); err != nil { + return err + } + if err = stack.Initialize.Add(newServiceMetadataMiddleware_opGetWebIdentityToken(options.Region), middleware.Before); err != nil { + return err + } + if err = addRecursionDetection(stack); err != nil { + return err + } + if err = addRequestIDRetrieverMiddleware(stack); err != nil { + return err + } + if err = addResponseErrorMiddleware(stack); err != nil { + return err + } + if err = addRequestResponseLogging(stack, options); err != nil { + return err + } + if err = addDisableHTTPSMiddleware(stack, options); err != nil { + return err + } + if err = addInterceptBeforeRetryLoop(stack, options); err != nil { + return err + } + if err = addInterceptAttempt(stack, options); err != nil { + return err + } + if err = addInterceptors(stack, options); err != nil { + return err + } + return nil +} + +func newServiceMetadataMiddleware_opGetWebIdentityToken(region string) *awsmiddleware.RegisterServiceMetadata { + return &awsmiddleware.RegisterServiceMetadata{ + Region: region, + ServiceID: ServiceID, + OperationName: "GetWebIdentityToken", + } +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/sts/auth.go b/vendor/github.com/aws/aws-sdk-go-v2/service/sts/auth.go index 2a81b3fb19d..4db5a51f938 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/sts/auth.go +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/sts/auth.go @@ -16,8 +16,9 @@ import ( "strings" ) -func bindAuthParamsRegion(_ interface{}, params *AuthResolverParameters, _ interface{}, options Options) { +func bindAuthParamsRegion(_ interface{}, params *AuthResolverParameters, _ interface{}, options Options) error { params.Region = options.Region + return nil } type setLegacyContextSigningOptionsMiddleware struct { @@ -94,14 +95,16 @@ type AuthResolverParameters struct { Region string } -func bindAuthResolverParams(ctx context.Context, operation string, input interface{}, options Options) *AuthResolverParameters { +func bindAuthResolverParams(ctx context.Context, operation string, input interface{}, options Options) (*AuthResolverParameters, error) { params := &AuthResolverParameters{ Operation: operation, } - bindAuthParamsRegion(ctx, params, input, options) + if err := bindAuthParamsRegion(ctx, params, input, options); err != nil { + return nil, err + } - return params + return params, nil } // AuthSchemeResolver returns a set of possible authentication options for an @@ -164,7 +167,10 @@ func (m *resolveAuthSchemeMiddleware) HandleFinalize(ctx context.Context, in mid _, span := tracing.StartSpan(ctx, "ResolveAuthScheme") defer span.End() - params := bindAuthResolverParams(ctx, m.operation, getOperationInput(ctx), m.options) + params, err := bindAuthResolverParams(ctx, m.operation, getOperationInput(ctx), m.options) + if err != nil { + return out, metadata, fmt.Errorf("bind auth scheme params: %w", err) + } options, err := m.options.AuthSchemeResolver.ResolveAuthSchemes(ctx, params) if err != nil { return out, metadata, fmt.Errorf("resolve auth scheme: %w", err) diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/sts/deserializers.go b/vendor/github.com/aws/aws-sdk-go-v2/service/sts/deserializers.go index a1ac917ec6a..8c1ce351616 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/sts/deserializers.go +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/sts/deserializers.go @@ -846,6 +846,124 @@ func awsAwsquery_deserializeOpErrorGetCallerIdentity(response *smithyhttp.Respon } } +type awsAwsquery_deserializeOpGetDelegatedAccessToken struct { +} + +func (*awsAwsquery_deserializeOpGetDelegatedAccessToken) ID() string { + return "OperationDeserializer" +} + +func (m *awsAwsquery_deserializeOpGetDelegatedAccessToken) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( + out middleware.DeserializeOutput, metadata middleware.Metadata, err error, +) { + out, metadata, err = next.HandleDeserialize(ctx, in) + if err != nil { + return out, metadata, err + } + + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() + response, ok := out.RawResponse.(*smithyhttp.Response) + if !ok { + return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} + } + + if response.StatusCode < 200 || response.StatusCode >= 300 { + return out, metadata, awsAwsquery_deserializeOpErrorGetDelegatedAccessToken(response, &metadata) + } + output := &GetDelegatedAccessTokenOutput{} + out.Result = output + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + body := io.TeeReader(response.Body, ringBuffer) + rootDecoder := xml.NewDecoder(body) + t, err := smithyxml.FetchRootElement(rootDecoder) + if err == io.EOF { + return out, metadata, nil + } + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + return out, metadata, &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + } + + decoder := smithyxml.WrapNodeDecoder(rootDecoder, t) + t, err = decoder.GetElement("GetDelegatedAccessTokenResult") + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + decoder = smithyxml.WrapNodeDecoder(decoder.Decoder, t) + err = awsAwsquery_deserializeOpDocumentGetDelegatedAccessTokenOutput(&output, decoder) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + return out, metadata, err +} + +func awsAwsquery_deserializeOpErrorGetDelegatedAccessToken(response *smithyhttp.Response, metadata *middleware.Metadata) error { + var errorBuffer bytes.Buffer + if _, err := io.Copy(&errorBuffer, response.Body); err != nil { + return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} + } + errorBody := bytes.NewReader(errorBuffer.Bytes()) + + errorCode := "UnknownError" + errorMessage := errorCode + + errorComponents, err := awsxml.GetErrorResponseComponents(errorBody, false) + if err != nil { + return err + } + if reqID := errorComponents.RequestID; len(reqID) != 0 { + awsmiddleware.SetRequestIDMetadata(metadata, reqID) + } + if len(errorComponents.Code) != 0 { + errorCode = errorComponents.Code + } + if len(errorComponents.Message) != 0 { + errorMessage = errorComponents.Message + } + errorBody.Seek(0, io.SeekStart) + switch { + case strings.EqualFold("ExpiredTradeInTokenException", errorCode): + return awsAwsquery_deserializeErrorExpiredTradeInTokenException(response, errorBody) + + case strings.EqualFold("PackedPolicyTooLarge", errorCode): + return awsAwsquery_deserializeErrorPackedPolicyTooLargeException(response, errorBody) + + case strings.EqualFold("RegionDisabledException", errorCode): + return awsAwsquery_deserializeErrorRegionDisabledException(response, errorBody) + + default: + genericError := &smithy.GenericAPIError{ + Code: errorCode, + Message: errorMessage, + } + return genericError + + } +} + type awsAwsquery_deserializeOpGetFederationToken struct { } @@ -1076,6 +1194,124 @@ func awsAwsquery_deserializeOpErrorGetSessionToken(response *smithyhttp.Response } } +type awsAwsquery_deserializeOpGetWebIdentityToken struct { +} + +func (*awsAwsquery_deserializeOpGetWebIdentityToken) ID() string { + return "OperationDeserializer" +} + +func (m *awsAwsquery_deserializeOpGetWebIdentityToken) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) ( + out middleware.DeserializeOutput, metadata middleware.Metadata, err error, +) { + out, metadata, err = next.HandleDeserialize(ctx, in) + if err != nil { + return out, metadata, err + } + + _, span := tracing.StartSpan(ctx, "OperationDeserializer") + endTimer := startMetricTimer(ctx, "client.call.deserialization_duration") + defer endTimer() + defer span.End() + response, ok := out.RawResponse.(*smithyhttp.Response) + if !ok { + return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} + } + + if response.StatusCode < 200 || response.StatusCode >= 300 { + return out, metadata, awsAwsquery_deserializeOpErrorGetWebIdentityToken(response, &metadata) + } + output := &GetWebIdentityTokenOutput{} + out.Result = output + + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + body := io.TeeReader(response.Body, ringBuffer) + rootDecoder := xml.NewDecoder(body) + t, err := smithyxml.FetchRootElement(rootDecoder) + if err == io.EOF { + return out, metadata, nil + } + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + return out, metadata, &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + } + + decoder := smithyxml.WrapNodeDecoder(rootDecoder, t) + t, err = decoder.GetElement("GetWebIdentityTokenResult") + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + decoder = smithyxml.WrapNodeDecoder(decoder.Decoder, t) + err = awsAwsquery_deserializeOpDocumentGetWebIdentityTokenOutput(&output, decoder) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + err = &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + return out, metadata, err + } + + return out, metadata, err +} + +func awsAwsquery_deserializeOpErrorGetWebIdentityToken(response *smithyhttp.Response, metadata *middleware.Metadata) error { + var errorBuffer bytes.Buffer + if _, err := io.Copy(&errorBuffer, response.Body); err != nil { + return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)} + } + errorBody := bytes.NewReader(errorBuffer.Bytes()) + + errorCode := "UnknownError" + errorMessage := errorCode + + errorComponents, err := awsxml.GetErrorResponseComponents(errorBody, false) + if err != nil { + return err + } + if reqID := errorComponents.RequestID; len(reqID) != 0 { + awsmiddleware.SetRequestIDMetadata(metadata, reqID) + } + if len(errorComponents.Code) != 0 { + errorCode = errorComponents.Code + } + if len(errorComponents.Message) != 0 { + errorMessage = errorComponents.Message + } + errorBody.Seek(0, io.SeekStart) + switch { + case strings.EqualFold("JWTPayloadSizeExceededException", errorCode): + return awsAwsquery_deserializeErrorJWTPayloadSizeExceededException(response, errorBody) + + case strings.EqualFold("OutboundWebIdentityFederationDisabledException", errorCode): + return awsAwsquery_deserializeErrorOutboundWebIdentityFederationDisabledException(response, errorBody) + + case strings.EqualFold("SessionDurationEscalationException", errorCode): + return awsAwsquery_deserializeErrorSessionDurationEscalationException(response, errorBody) + + default: + genericError := &smithy.GenericAPIError{ + Code: errorCode, + Message: errorMessage, + } + return genericError + + } +} + func awsAwsquery_deserializeErrorExpiredTokenException(response *smithyhttp.Response, errorBody *bytes.Reader) error { output := &types.ExpiredTokenException{} var buff [1024]byte @@ -1120,8 +1356,8 @@ func awsAwsquery_deserializeErrorExpiredTokenException(response *smithyhttp.Resp return output } -func awsAwsquery_deserializeErrorIDPCommunicationErrorException(response *smithyhttp.Response, errorBody *bytes.Reader) error { - output := &types.IDPCommunicationErrorException{} +func awsAwsquery_deserializeErrorExpiredTradeInTokenException(response *smithyhttp.Response, errorBody *bytes.Reader) error { + output := &types.ExpiredTradeInTokenException{} var buff [1024]byte ringBuffer := smithyio.NewRingBuffer(buff[:]) body := io.TeeReader(errorBody, ringBuffer) @@ -1151,7 +1387,7 @@ func awsAwsquery_deserializeErrorIDPCommunicationErrorException(response *smithy } decoder = smithyxml.WrapNodeDecoder(decoder.Decoder, t) - err = awsAwsquery_deserializeDocumentIDPCommunicationErrorException(&output, decoder) + err = awsAwsquery_deserializeDocumentExpiredTradeInTokenException(&output, decoder) if err != nil { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) @@ -1164,8 +1400,8 @@ func awsAwsquery_deserializeErrorIDPCommunicationErrorException(response *smithy return output } -func awsAwsquery_deserializeErrorIDPRejectedClaimException(response *smithyhttp.Response, errorBody *bytes.Reader) error { - output := &types.IDPRejectedClaimException{} +func awsAwsquery_deserializeErrorIDPCommunicationErrorException(response *smithyhttp.Response, errorBody *bytes.Reader) error { + output := &types.IDPCommunicationErrorException{} var buff [1024]byte ringBuffer := smithyio.NewRingBuffer(buff[:]) body := io.TeeReader(errorBody, ringBuffer) @@ -1195,7 +1431,7 @@ func awsAwsquery_deserializeErrorIDPRejectedClaimException(response *smithyhttp. } decoder = smithyxml.WrapNodeDecoder(decoder.Decoder, t) - err = awsAwsquery_deserializeDocumentIDPRejectedClaimException(&output, decoder) + err = awsAwsquery_deserializeDocumentIDPCommunicationErrorException(&output, decoder) if err != nil { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) @@ -1208,8 +1444,8 @@ func awsAwsquery_deserializeErrorIDPRejectedClaimException(response *smithyhttp. return output } -func awsAwsquery_deserializeErrorInvalidAuthorizationMessageException(response *smithyhttp.Response, errorBody *bytes.Reader) error { - output := &types.InvalidAuthorizationMessageException{} +func awsAwsquery_deserializeErrorIDPRejectedClaimException(response *smithyhttp.Response, errorBody *bytes.Reader) error { + output := &types.IDPRejectedClaimException{} var buff [1024]byte ringBuffer := smithyio.NewRingBuffer(buff[:]) body := io.TeeReader(errorBody, ringBuffer) @@ -1239,7 +1475,7 @@ func awsAwsquery_deserializeErrorInvalidAuthorizationMessageException(response * } decoder = smithyxml.WrapNodeDecoder(decoder.Decoder, t) - err = awsAwsquery_deserializeDocumentInvalidAuthorizationMessageException(&output, decoder) + err = awsAwsquery_deserializeDocumentIDPRejectedClaimException(&output, decoder) if err != nil { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) @@ -1252,8 +1488,8 @@ func awsAwsquery_deserializeErrorInvalidAuthorizationMessageException(response * return output } -func awsAwsquery_deserializeErrorInvalidIdentityTokenException(response *smithyhttp.Response, errorBody *bytes.Reader) error { - output := &types.InvalidIdentityTokenException{} +func awsAwsquery_deserializeErrorInvalidAuthorizationMessageException(response *smithyhttp.Response, errorBody *bytes.Reader) error { + output := &types.InvalidAuthorizationMessageException{} var buff [1024]byte ringBuffer := smithyio.NewRingBuffer(buff[:]) body := io.TeeReader(errorBody, ringBuffer) @@ -1283,7 +1519,7 @@ func awsAwsquery_deserializeErrorInvalidIdentityTokenException(response *smithyh } decoder = smithyxml.WrapNodeDecoder(decoder.Decoder, t) - err = awsAwsquery_deserializeDocumentInvalidIdentityTokenException(&output, decoder) + err = awsAwsquery_deserializeDocumentInvalidAuthorizationMessageException(&output, decoder) if err != nil { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) @@ -1296,8 +1532,8 @@ func awsAwsquery_deserializeErrorInvalidIdentityTokenException(response *smithyh return output } -func awsAwsquery_deserializeErrorMalformedPolicyDocumentException(response *smithyhttp.Response, errorBody *bytes.Reader) error { - output := &types.MalformedPolicyDocumentException{} +func awsAwsquery_deserializeErrorInvalidIdentityTokenException(response *smithyhttp.Response, errorBody *bytes.Reader) error { + output := &types.InvalidIdentityTokenException{} var buff [1024]byte ringBuffer := smithyio.NewRingBuffer(buff[:]) body := io.TeeReader(errorBody, ringBuffer) @@ -1327,7 +1563,7 @@ func awsAwsquery_deserializeErrorMalformedPolicyDocumentException(response *smit } decoder = smithyxml.WrapNodeDecoder(decoder.Decoder, t) - err = awsAwsquery_deserializeDocumentMalformedPolicyDocumentException(&output, decoder) + err = awsAwsquery_deserializeDocumentInvalidIdentityTokenException(&output, decoder) if err != nil { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) @@ -1340,8 +1576,8 @@ func awsAwsquery_deserializeErrorMalformedPolicyDocumentException(response *smit return output } -func awsAwsquery_deserializeErrorPackedPolicyTooLargeException(response *smithyhttp.Response, errorBody *bytes.Reader) error { - output := &types.PackedPolicyTooLargeException{} +func awsAwsquery_deserializeErrorJWTPayloadSizeExceededException(response *smithyhttp.Response, errorBody *bytes.Reader) error { + output := &types.JWTPayloadSizeExceededException{} var buff [1024]byte ringBuffer := smithyio.NewRingBuffer(buff[:]) body := io.TeeReader(errorBody, ringBuffer) @@ -1371,7 +1607,7 @@ func awsAwsquery_deserializeErrorPackedPolicyTooLargeException(response *smithyh } decoder = smithyxml.WrapNodeDecoder(decoder.Decoder, t) - err = awsAwsquery_deserializeDocumentPackedPolicyTooLargeException(&output, decoder) + err = awsAwsquery_deserializeDocumentJWTPayloadSizeExceededException(&output, decoder) if err != nil { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) @@ -1384,8 +1620,8 @@ func awsAwsquery_deserializeErrorPackedPolicyTooLargeException(response *smithyh return output } -func awsAwsquery_deserializeErrorRegionDisabledException(response *smithyhttp.Response, errorBody *bytes.Reader) error { - output := &types.RegionDisabledException{} +func awsAwsquery_deserializeErrorMalformedPolicyDocumentException(response *smithyhttp.Response, errorBody *bytes.Reader) error { + output := &types.MalformedPolicyDocumentException{} var buff [1024]byte ringBuffer := smithyio.NewRingBuffer(buff[:]) body := io.TeeReader(errorBody, ringBuffer) @@ -1415,7 +1651,7 @@ func awsAwsquery_deserializeErrorRegionDisabledException(response *smithyhttp.Re } decoder = smithyxml.WrapNodeDecoder(decoder.Decoder, t) - err = awsAwsquery_deserializeDocumentRegionDisabledException(&output, decoder) + err = awsAwsquery_deserializeDocumentMalformedPolicyDocumentException(&output, decoder) if err != nil { var snapshot bytes.Buffer io.Copy(&snapshot, ringBuffer) @@ -1428,13 +1664,441 @@ func awsAwsquery_deserializeErrorRegionDisabledException(response *smithyhttp.Re return output } -func awsAwsquery_deserializeDocumentAssumedRoleUser(v **types.AssumedRoleUser, decoder smithyxml.NodeDecoder) error { +func awsAwsquery_deserializeErrorOutboundWebIdentityFederationDisabledException(response *smithyhttp.Response, errorBody *bytes.Reader) error { + output := &types.OutboundWebIdentityFederationDisabledException{} + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + body := io.TeeReader(errorBody, ringBuffer) + rootDecoder := xml.NewDecoder(body) + t, err := smithyxml.FetchRootElement(rootDecoder) + if err == io.EOF { + return output + } + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + return &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + } + + decoder := smithyxml.WrapNodeDecoder(rootDecoder, t) + t, err = decoder.GetElement("Error") + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + return &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + } + + decoder = smithyxml.WrapNodeDecoder(decoder.Decoder, t) + err = awsAwsquery_deserializeDocumentOutboundWebIdentityFederationDisabledException(&output, decoder) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + return &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + } + + return output +} + +func awsAwsquery_deserializeErrorPackedPolicyTooLargeException(response *smithyhttp.Response, errorBody *bytes.Reader) error { + output := &types.PackedPolicyTooLargeException{} + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + body := io.TeeReader(errorBody, ringBuffer) + rootDecoder := xml.NewDecoder(body) + t, err := smithyxml.FetchRootElement(rootDecoder) + if err == io.EOF { + return output + } + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + return &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + } + + decoder := smithyxml.WrapNodeDecoder(rootDecoder, t) + t, err = decoder.GetElement("Error") + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + return &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + } + + decoder = smithyxml.WrapNodeDecoder(decoder.Decoder, t) + err = awsAwsquery_deserializeDocumentPackedPolicyTooLargeException(&output, decoder) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + return &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + } + + return output +} + +func awsAwsquery_deserializeErrorRegionDisabledException(response *smithyhttp.Response, errorBody *bytes.Reader) error { + output := &types.RegionDisabledException{} + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + body := io.TeeReader(errorBody, ringBuffer) + rootDecoder := xml.NewDecoder(body) + t, err := smithyxml.FetchRootElement(rootDecoder) + if err == io.EOF { + return output + } + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + return &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + } + + decoder := smithyxml.WrapNodeDecoder(rootDecoder, t) + t, err = decoder.GetElement("Error") + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + return &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + } + + decoder = smithyxml.WrapNodeDecoder(decoder.Decoder, t) + err = awsAwsquery_deserializeDocumentRegionDisabledException(&output, decoder) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + return &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + } + + return output +} + +func awsAwsquery_deserializeErrorSessionDurationEscalationException(response *smithyhttp.Response, errorBody *bytes.Reader) error { + output := &types.SessionDurationEscalationException{} + var buff [1024]byte + ringBuffer := smithyio.NewRingBuffer(buff[:]) + body := io.TeeReader(errorBody, ringBuffer) + rootDecoder := xml.NewDecoder(body) + t, err := smithyxml.FetchRootElement(rootDecoder) + if err == io.EOF { + return output + } + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + return &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + } + + decoder := smithyxml.WrapNodeDecoder(rootDecoder, t) + t, err = decoder.GetElement("Error") + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + return &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + } + + decoder = smithyxml.WrapNodeDecoder(decoder.Decoder, t) + err = awsAwsquery_deserializeDocumentSessionDurationEscalationException(&output, decoder) + if err != nil { + var snapshot bytes.Buffer + io.Copy(&snapshot, ringBuffer) + return &smithy.DeserializationError{ + Err: fmt.Errorf("failed to decode response body, %w", err), + Snapshot: snapshot.Bytes(), + } + } + + return output +} + +func awsAwsquery_deserializeDocumentAssumedRoleUser(v **types.AssumedRoleUser, decoder smithyxml.NodeDecoder) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + var sv *types.AssumedRoleUser + if *v == nil { + sv = &types.AssumedRoleUser{} + } else { + sv = *v + } + + for { + t, done, err := decoder.Token() + if err != nil { + return err + } + if done { + break + } + originalDecoder := decoder + decoder = smithyxml.WrapNodeDecoder(originalDecoder.Decoder, t) + switch { + case strings.EqualFold("Arn", t.Name.Local): + val, err := decoder.Value() + if err != nil { + return err + } + if val == nil { + break + } + { + xtv := string(val) + sv.Arn = ptr.String(xtv) + } + + case strings.EqualFold("AssumedRoleId", t.Name.Local): + val, err := decoder.Value() + if err != nil { + return err + } + if val == nil { + break + } + { + xtv := string(val) + sv.AssumedRoleId = ptr.String(xtv) + } + + default: + // Do nothing and ignore the unexpected tag element + err = decoder.Decoder.Skip() + if err != nil { + return err + } + + } + decoder = originalDecoder + } + *v = sv + return nil +} + +func awsAwsquery_deserializeDocumentCredentials(v **types.Credentials, decoder smithyxml.NodeDecoder) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + var sv *types.Credentials + if *v == nil { + sv = &types.Credentials{} + } else { + sv = *v + } + + for { + t, done, err := decoder.Token() + if err != nil { + return err + } + if done { + break + } + originalDecoder := decoder + decoder = smithyxml.WrapNodeDecoder(originalDecoder.Decoder, t) + switch { + case strings.EqualFold("AccessKeyId", t.Name.Local): + val, err := decoder.Value() + if err != nil { + return err + } + if val == nil { + break + } + { + xtv := string(val) + sv.AccessKeyId = ptr.String(xtv) + } + + case strings.EqualFold("Expiration", t.Name.Local): + val, err := decoder.Value() + if err != nil { + return err + } + if val == nil { + break + } + { + xtv := string(val) + t, err := smithytime.ParseDateTime(xtv) + if err != nil { + return err + } + sv.Expiration = ptr.Time(t) + } + + case strings.EqualFold("SecretAccessKey", t.Name.Local): + val, err := decoder.Value() + if err != nil { + return err + } + if val == nil { + break + } + { + xtv := string(val) + sv.SecretAccessKey = ptr.String(xtv) + } + + case strings.EqualFold("SessionToken", t.Name.Local): + val, err := decoder.Value() + if err != nil { + return err + } + if val == nil { + break + } + { + xtv := string(val) + sv.SessionToken = ptr.String(xtv) + } + + default: + // Do nothing and ignore the unexpected tag element + err = decoder.Decoder.Skip() + if err != nil { + return err + } + + } + decoder = originalDecoder + } + *v = sv + return nil +} + +func awsAwsquery_deserializeDocumentExpiredTokenException(v **types.ExpiredTokenException, decoder smithyxml.NodeDecoder) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + var sv *types.ExpiredTokenException + if *v == nil { + sv = &types.ExpiredTokenException{} + } else { + sv = *v + } + + for { + t, done, err := decoder.Token() + if err != nil { + return err + } + if done { + break + } + originalDecoder := decoder + decoder = smithyxml.WrapNodeDecoder(originalDecoder.Decoder, t) + switch { + case strings.EqualFold("message", t.Name.Local): + val, err := decoder.Value() + if err != nil { + return err + } + if val == nil { + break + } + { + xtv := string(val) + sv.Message = ptr.String(xtv) + } + + default: + // Do nothing and ignore the unexpected tag element + err = decoder.Decoder.Skip() + if err != nil { + return err + } + + } + decoder = originalDecoder + } + *v = sv + return nil +} + +func awsAwsquery_deserializeDocumentExpiredTradeInTokenException(v **types.ExpiredTradeInTokenException, decoder smithyxml.NodeDecoder) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + var sv *types.ExpiredTradeInTokenException + if *v == nil { + sv = &types.ExpiredTradeInTokenException{} + } else { + sv = *v + } + + for { + t, done, err := decoder.Token() + if err != nil { + return err + } + if done { + break + } + originalDecoder := decoder + decoder = smithyxml.WrapNodeDecoder(originalDecoder.Decoder, t) + switch { + case strings.EqualFold("message", t.Name.Local): + val, err := decoder.Value() + if err != nil { + return err + } + if val == nil { + break + } + { + xtv := string(val) + sv.Message = ptr.String(xtv) + } + + default: + // Do nothing and ignore the unexpected tag element + err = decoder.Decoder.Skip() + if err != nil { + return err + } + + } + decoder = originalDecoder + } + *v = sv + return nil +} + +func awsAwsquery_deserializeDocumentFederatedUser(v **types.FederatedUser, decoder smithyxml.NodeDecoder) error { if v == nil { return fmt.Errorf("unexpected nil of type %T", v) } - var sv *types.AssumedRoleUser + var sv *types.FederatedUser if *v == nil { - sv = &types.AssumedRoleUser{} + sv = &types.FederatedUser{} } else { sv = *v } @@ -1463,7 +2127,7 @@ func awsAwsquery_deserializeDocumentAssumedRoleUser(v **types.AssumedRoleUser, d sv.Arn = ptr.String(xtv) } - case strings.EqualFold("AssumedRoleId", t.Name.Local): + case strings.EqualFold("FederatedUserId", t.Name.Local): val, err := decoder.Value() if err != nil { return err @@ -1473,7 +2137,7 @@ func awsAwsquery_deserializeDocumentAssumedRoleUser(v **types.AssumedRoleUser, d } { xtv := string(val) - sv.AssumedRoleId = ptr.String(xtv) + sv.FederatedUserId = ptr.String(xtv) } default: @@ -1490,13 +2154,13 @@ func awsAwsquery_deserializeDocumentAssumedRoleUser(v **types.AssumedRoleUser, d return nil } -func awsAwsquery_deserializeDocumentCredentials(v **types.Credentials, decoder smithyxml.NodeDecoder) error { +func awsAwsquery_deserializeDocumentIDPCommunicationErrorException(v **types.IDPCommunicationErrorException, decoder smithyxml.NodeDecoder) error { if v == nil { return fmt.Errorf("unexpected nil of type %T", v) } - var sv *types.Credentials + var sv *types.IDPCommunicationErrorException if *v == nil { - sv = &types.Credentials{} + sv = &types.IDPCommunicationErrorException{} } else { sv = *v } @@ -1512,50 +2176,7 @@ func awsAwsquery_deserializeDocumentCredentials(v **types.Credentials, decoder s originalDecoder := decoder decoder = smithyxml.WrapNodeDecoder(originalDecoder.Decoder, t) switch { - case strings.EqualFold("AccessKeyId", t.Name.Local): - val, err := decoder.Value() - if err != nil { - return err - } - if val == nil { - break - } - { - xtv := string(val) - sv.AccessKeyId = ptr.String(xtv) - } - - case strings.EqualFold("Expiration", t.Name.Local): - val, err := decoder.Value() - if err != nil { - return err - } - if val == nil { - break - } - { - xtv := string(val) - t, err := smithytime.ParseDateTime(xtv) - if err != nil { - return err - } - sv.Expiration = ptr.Time(t) - } - - case strings.EqualFold("SecretAccessKey", t.Name.Local): - val, err := decoder.Value() - if err != nil { - return err - } - if val == nil { - break - } - { - xtv := string(val) - sv.SecretAccessKey = ptr.String(xtv) - } - - case strings.EqualFold("SessionToken", t.Name.Local): + case strings.EqualFold("message", t.Name.Local): val, err := decoder.Value() if err != nil { return err @@ -1565,7 +2186,7 @@ func awsAwsquery_deserializeDocumentCredentials(v **types.Credentials, decoder s } { xtv := string(val) - sv.SessionToken = ptr.String(xtv) + sv.Message = ptr.String(xtv) } default: @@ -1582,13 +2203,13 @@ func awsAwsquery_deserializeDocumentCredentials(v **types.Credentials, decoder s return nil } -func awsAwsquery_deserializeDocumentExpiredTokenException(v **types.ExpiredTokenException, decoder smithyxml.NodeDecoder) error { +func awsAwsquery_deserializeDocumentIDPRejectedClaimException(v **types.IDPRejectedClaimException, decoder smithyxml.NodeDecoder) error { if v == nil { return fmt.Errorf("unexpected nil of type %T", v) } - var sv *types.ExpiredTokenException + var sv *types.IDPRejectedClaimException if *v == nil { - sv = &types.ExpiredTokenException{} + sv = &types.IDPRejectedClaimException{} } else { sv = *v } @@ -1631,13 +2252,13 @@ func awsAwsquery_deserializeDocumentExpiredTokenException(v **types.ExpiredToken return nil } -func awsAwsquery_deserializeDocumentFederatedUser(v **types.FederatedUser, decoder smithyxml.NodeDecoder) error { +func awsAwsquery_deserializeDocumentInvalidAuthorizationMessageException(v **types.InvalidAuthorizationMessageException, decoder smithyxml.NodeDecoder) error { if v == nil { return fmt.Errorf("unexpected nil of type %T", v) } - var sv *types.FederatedUser + var sv *types.InvalidAuthorizationMessageException if *v == nil { - sv = &types.FederatedUser{} + sv = &types.InvalidAuthorizationMessageException{} } else { sv = *v } @@ -1653,20 +2274,7 @@ func awsAwsquery_deserializeDocumentFederatedUser(v **types.FederatedUser, decod originalDecoder := decoder decoder = smithyxml.WrapNodeDecoder(originalDecoder.Decoder, t) switch { - case strings.EqualFold("Arn", t.Name.Local): - val, err := decoder.Value() - if err != nil { - return err - } - if val == nil { - break - } - { - xtv := string(val) - sv.Arn = ptr.String(xtv) - } - - case strings.EqualFold("FederatedUserId", t.Name.Local): + case strings.EqualFold("message", t.Name.Local): val, err := decoder.Value() if err != nil { return err @@ -1676,7 +2284,7 @@ func awsAwsquery_deserializeDocumentFederatedUser(v **types.FederatedUser, decod } { xtv := string(val) - sv.FederatedUserId = ptr.String(xtv) + sv.Message = ptr.String(xtv) } default: @@ -1693,13 +2301,13 @@ func awsAwsquery_deserializeDocumentFederatedUser(v **types.FederatedUser, decod return nil } -func awsAwsquery_deserializeDocumentIDPCommunicationErrorException(v **types.IDPCommunicationErrorException, decoder smithyxml.NodeDecoder) error { +func awsAwsquery_deserializeDocumentInvalidIdentityTokenException(v **types.InvalidIdentityTokenException, decoder smithyxml.NodeDecoder) error { if v == nil { return fmt.Errorf("unexpected nil of type %T", v) } - var sv *types.IDPCommunicationErrorException + var sv *types.InvalidIdentityTokenException if *v == nil { - sv = &types.IDPCommunicationErrorException{} + sv = &types.InvalidIdentityTokenException{} } else { sv = *v } @@ -1742,13 +2350,13 @@ func awsAwsquery_deserializeDocumentIDPCommunicationErrorException(v **types.IDP return nil } -func awsAwsquery_deserializeDocumentIDPRejectedClaimException(v **types.IDPRejectedClaimException, decoder smithyxml.NodeDecoder) error { +func awsAwsquery_deserializeDocumentJWTPayloadSizeExceededException(v **types.JWTPayloadSizeExceededException, decoder smithyxml.NodeDecoder) error { if v == nil { return fmt.Errorf("unexpected nil of type %T", v) } - var sv *types.IDPRejectedClaimException + var sv *types.JWTPayloadSizeExceededException if *v == nil { - sv = &types.IDPRejectedClaimException{} + sv = &types.JWTPayloadSizeExceededException{} } else { sv = *v } @@ -1791,13 +2399,13 @@ func awsAwsquery_deserializeDocumentIDPRejectedClaimException(v **types.IDPRejec return nil } -func awsAwsquery_deserializeDocumentInvalidAuthorizationMessageException(v **types.InvalidAuthorizationMessageException, decoder smithyxml.NodeDecoder) error { +func awsAwsquery_deserializeDocumentMalformedPolicyDocumentException(v **types.MalformedPolicyDocumentException, decoder smithyxml.NodeDecoder) error { if v == nil { return fmt.Errorf("unexpected nil of type %T", v) } - var sv *types.InvalidAuthorizationMessageException + var sv *types.MalformedPolicyDocumentException if *v == nil { - sv = &types.InvalidAuthorizationMessageException{} + sv = &types.MalformedPolicyDocumentException{} } else { sv = *v } @@ -1840,13 +2448,13 @@ func awsAwsquery_deserializeDocumentInvalidAuthorizationMessageException(v **typ return nil } -func awsAwsquery_deserializeDocumentInvalidIdentityTokenException(v **types.InvalidIdentityTokenException, decoder smithyxml.NodeDecoder) error { +func awsAwsquery_deserializeDocumentOutboundWebIdentityFederationDisabledException(v **types.OutboundWebIdentityFederationDisabledException, decoder smithyxml.NodeDecoder) error { if v == nil { return fmt.Errorf("unexpected nil of type %T", v) } - var sv *types.InvalidIdentityTokenException + var sv *types.OutboundWebIdentityFederationDisabledException if *v == nil { - sv = &types.InvalidIdentityTokenException{} + sv = &types.OutboundWebIdentityFederationDisabledException{} } else { sv = *v } @@ -1889,13 +2497,13 @@ func awsAwsquery_deserializeDocumentInvalidIdentityTokenException(v **types.Inva return nil } -func awsAwsquery_deserializeDocumentMalformedPolicyDocumentException(v **types.MalformedPolicyDocumentException, decoder smithyxml.NodeDecoder) error { +func awsAwsquery_deserializeDocumentPackedPolicyTooLargeException(v **types.PackedPolicyTooLargeException, decoder smithyxml.NodeDecoder) error { if v == nil { return fmt.Errorf("unexpected nil of type %T", v) } - var sv *types.MalformedPolicyDocumentException + var sv *types.PackedPolicyTooLargeException if *v == nil { - sv = &types.MalformedPolicyDocumentException{} + sv = &types.PackedPolicyTooLargeException{} } else { sv = *v } @@ -1938,13 +2546,13 @@ func awsAwsquery_deserializeDocumentMalformedPolicyDocumentException(v **types.M return nil } -func awsAwsquery_deserializeDocumentPackedPolicyTooLargeException(v **types.PackedPolicyTooLargeException, decoder smithyxml.NodeDecoder) error { +func awsAwsquery_deserializeDocumentRegionDisabledException(v **types.RegionDisabledException, decoder smithyxml.NodeDecoder) error { if v == nil { return fmt.Errorf("unexpected nil of type %T", v) } - var sv *types.PackedPolicyTooLargeException + var sv *types.RegionDisabledException if *v == nil { - sv = &types.PackedPolicyTooLargeException{} + sv = &types.RegionDisabledException{} } else { sv = *v } @@ -1987,13 +2595,13 @@ func awsAwsquery_deserializeDocumentPackedPolicyTooLargeException(v **types.Pack return nil } -func awsAwsquery_deserializeDocumentRegionDisabledException(v **types.RegionDisabledException, decoder smithyxml.NodeDecoder) error { +func awsAwsquery_deserializeDocumentSessionDurationEscalationException(v **types.SessionDurationEscalationException, decoder smithyxml.NodeDecoder) error { if v == nil { return fmt.Errorf("unexpected nil of type %T", v) } - var sv *types.RegionDisabledException + var sv *types.SessionDurationEscalationException if *v == nil { - sv = &types.RegionDisabledException{} + sv = &types.SessionDurationEscalationException{} } else { sv = *v } @@ -2602,6 +3210,78 @@ func awsAwsquery_deserializeOpDocumentGetCallerIdentityOutput(v **GetCallerIdent return nil } +func awsAwsquery_deserializeOpDocumentGetDelegatedAccessTokenOutput(v **GetDelegatedAccessTokenOutput, decoder smithyxml.NodeDecoder) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + var sv *GetDelegatedAccessTokenOutput + if *v == nil { + sv = &GetDelegatedAccessTokenOutput{} + } else { + sv = *v + } + + for { + t, done, err := decoder.Token() + if err != nil { + return err + } + if done { + break + } + originalDecoder := decoder + decoder = smithyxml.WrapNodeDecoder(originalDecoder.Decoder, t) + switch { + case strings.EqualFold("AssumedPrincipal", t.Name.Local): + val, err := decoder.Value() + if err != nil { + return err + } + if val == nil { + break + } + { + xtv := string(val) + sv.AssumedPrincipal = ptr.String(xtv) + } + + case strings.EqualFold("Credentials", t.Name.Local): + nodeDecoder := smithyxml.WrapNodeDecoder(decoder.Decoder, t) + if err := awsAwsquery_deserializeDocumentCredentials(&sv.Credentials, nodeDecoder); err != nil { + return err + } + + case strings.EqualFold("PackedPolicySize", t.Name.Local): + val, err := decoder.Value() + if err != nil { + return err + } + if val == nil { + break + } + { + xtv := string(val) + i64, err := strconv.ParseInt(xtv, 10, 64) + if err != nil { + return err + } + sv.PackedPolicySize = ptr.Int32(int32(i64)) + } + + default: + // Do nothing and ignore the unexpected tag element + err = decoder.Decoder.Skip() + if err != nil { + return err + } + + } + decoder = originalDecoder + } + *v = sv + return nil +} + func awsAwsquery_deserializeOpDocumentGetFederationTokenOutput(v **GetFederationTokenOutput, decoder smithyxml.NodeDecoder) error { if v == nil { return fmt.Errorf("unexpected nil of type %T", v) @@ -2708,3 +3388,69 @@ func awsAwsquery_deserializeOpDocumentGetSessionTokenOutput(v **GetSessionTokenO *v = sv return nil } + +func awsAwsquery_deserializeOpDocumentGetWebIdentityTokenOutput(v **GetWebIdentityTokenOutput, decoder smithyxml.NodeDecoder) error { + if v == nil { + return fmt.Errorf("unexpected nil of type %T", v) + } + var sv *GetWebIdentityTokenOutput + if *v == nil { + sv = &GetWebIdentityTokenOutput{} + } else { + sv = *v + } + + for { + t, done, err := decoder.Token() + if err != nil { + return err + } + if done { + break + } + originalDecoder := decoder + decoder = smithyxml.WrapNodeDecoder(originalDecoder.Decoder, t) + switch { + case strings.EqualFold("Expiration", t.Name.Local): + val, err := decoder.Value() + if err != nil { + return err + } + if val == nil { + break + } + { + xtv := string(val) + t, err := smithytime.ParseDateTime(xtv) + if err != nil { + return err + } + sv.Expiration = ptr.Time(t) + } + + case strings.EqualFold("WebIdentityToken", t.Name.Local): + val, err := decoder.Value() + if err != nil { + return err + } + if val == nil { + break + } + { + xtv := string(val) + sv.WebIdentityToken = ptr.String(xtv) + } + + default: + // Do nothing and ignore the unexpected tag element + err = decoder.Decoder.Skip() + if err != nil { + return err + } + + } + decoder = originalDecoder + } + *v = sv + return nil +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/sts/endpoints.go b/vendor/github.com/aws/aws-sdk-go-v2/service/sts/endpoints.go index 945682e1a50..c8f9526c78a 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/sts/endpoints.go +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/sts/endpoints.go @@ -15,6 +15,7 @@ import ( smithy "github.com/aws/smithy-go" smithyauth "github.com/aws/smithy-go/auth" smithyendpoints "github.com/aws/smithy-go/endpoints" + "github.com/aws/smithy-go/endpoints/private/rulesfn" "github.com/aws/smithy-go/middleware" "github.com/aws/smithy-go/ptr" "github.com/aws/smithy-go/tracing" @@ -218,11 +219,15 @@ func resolveBaseEndpoint(cfg aws.Config, o *Options) { } } -func bindRegion(region string) *string { +func bindRegion(region string) (*string, error) { if region == "" { - return nil + return nil, nil + } + if !rulesfn.IsValidHostLabel(region, true) { + return nil, fmt.Errorf("invalid input region %s", region) } - return aws.String(endpoints.MapFIPSRegion(region)) + + return aws.String(endpoints.MapFIPSRegion(region)), nil } // EndpointParameters provides the parameters that influence how endpoints are @@ -1060,10 +1065,15 @@ type endpointParamsBinder interface { bindEndpointParams(*EndpointParameters) } -func bindEndpointParams(ctx context.Context, input interface{}, options Options) *EndpointParameters { +func bindEndpointParams(ctx context.Context, input interface{}, options Options) (*EndpointParameters, error) { params := &EndpointParameters{} - params.Region = bindRegion(options.Region) + region, err := bindRegion(options.Region) + if err != nil { + return nil, err + } + params.Region = region + params.UseDualStack = aws.Bool(options.EndpointOptions.UseDualStackEndpoint == aws.DualStackEndpointStateEnabled) params.UseFIPS = aws.Bool(options.EndpointOptions.UseFIPSEndpoint == aws.FIPSEndpointStateEnabled) params.Endpoint = options.BaseEndpoint @@ -1072,7 +1082,7 @@ func bindEndpointParams(ctx context.Context, input interface{}, options Options) b.bindEndpointParams(params) } - return params + return params, nil } type resolveEndpointV2Middleware struct { @@ -1102,7 +1112,10 @@ func (m *resolveEndpointV2Middleware) HandleFinalize(ctx context.Context, in mid return out, metadata, fmt.Errorf("expected endpoint resolver to not be nil") } - params := bindEndpointParams(ctx, getOperationInput(ctx), m.options) + params, err := bindEndpointParams(ctx, getOperationInput(ctx), m.options) + if err != nil { + return out, metadata, fmt.Errorf("failed to bind endpoint params, %w", err) + } endpt, err := timeOperationMetric(ctx, "client.call.resolve_endpoint_duration", func() (smithyendpoints.Endpoint, error) { return m.options.EndpointResolverV2.ResolveEndpoint(ctx, *params) diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/sts/generated.json b/vendor/github.com/aws/aws-sdk-go-v2/service/sts/generated.json index 86bb3b79be4..e61823ea016 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/sts/generated.json +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/sts/generated.json @@ -17,8 +17,10 @@ "api_op_DecodeAuthorizationMessage.go", "api_op_GetAccessKeyInfo.go", "api_op_GetCallerIdentity.go", + "api_op_GetDelegatedAccessToken.go", "api_op_GetFederationToken.go", "api_op_GetSessionToken.go", + "api_op_GetWebIdentityToken.go", "auth.go", "deserializers.go", "doc.go", @@ -37,7 +39,7 @@ "types/types.go", "validators.go" ], - "go": "1.22", + "go": "1.23", "module": "github.com/aws/aws-sdk-go-v2/service/sts", "unstable": false } diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/sts/go_module_metadata.go b/vendor/github.com/aws/aws-sdk-go-v2/service/sts/go_module_metadata.go index dd0eacf56c2..c081cdeb307 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/sts/go_module_metadata.go +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/sts/go_module_metadata.go @@ -3,4 +3,4 @@ package sts // goModuleVersion is the tagged release for this module -const goModuleVersion = "1.38.6" +const goModuleVersion = "1.41.5" diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/sts/internal/endpoints/endpoints.go b/vendor/github.com/aws/aws-sdk-go-v2/service/sts/internal/endpoints/endpoints.go index 1dc87dd6bf1..be72d93dccd 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/sts/internal/endpoints/endpoints.go +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/sts/internal/endpoints/endpoints.go @@ -359,6 +359,13 @@ var defaultPartitions = endpoints.Partitions{ { ID: "aws-eusc", Defaults: map[endpoints.DefaultKey]endpoints.Endpoint{ + { + Variant: endpoints.DualStackVariant, + }: { + Hostname: "sts.{region}.api.amazonwebservices.eu", + Protocols: []string{"https"}, + SignatureVersions: []string{"v4"}, + }, { Variant: endpoints.FIPSVariant, }: { @@ -366,6 +373,13 @@ var defaultPartitions = endpoints.Partitions{ Protocols: []string{"https"}, SignatureVersions: []string{"v4"}, }, + { + Variant: endpoints.FIPSVariant | endpoints.DualStackVariant, + }: { + Hostname: "sts-fips.{region}.api.amazonwebservices.eu", + Protocols: []string{"https"}, + SignatureVersions: []string{"v4"}, + }, { Variant: 0, }: { @@ -376,6 +390,11 @@ var defaultPartitions = endpoints.Partitions{ }, RegionRegex: partitionRegexp.AwsEusc, IsRegionalized: true, + Endpoints: endpoints.Endpoints{ + endpoints.EndpointKey{ + Region: "eusc-de-east-1", + }: endpoints.Endpoint{}, + }, }, { ID: "aws-iso", @@ -430,6 +449,9 @@ var defaultPartitions = endpoints.Partitions{ endpoints.EndpointKey{ Region: "us-isob-east-1", }: endpoints.Endpoint{}, + endpoints.EndpointKey{ + Region: "us-isob-west-1", + }: endpoints.Endpoint{}, }, }, { diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/sts/serializers.go b/vendor/github.com/aws/aws-sdk-go-v2/service/sts/serializers.go index 96b222136bf..5e227387827 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/sts/serializers.go +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/sts/serializers.go @@ -502,6 +502,76 @@ func (m *awsAwsquery_serializeOpGetCallerIdentity) HandleSerialize(ctx context.C return next.HandleSerialize(ctx, in) } +type awsAwsquery_serializeOpGetDelegatedAccessToken struct { +} + +func (*awsAwsquery_serializeOpGetDelegatedAccessToken) ID() string { + return "OperationSerializer" +} + +func (m *awsAwsquery_serializeOpGetDelegatedAccessToken) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( + out middleware.SerializeOutput, metadata middleware.Metadata, err error, +) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() + request, ok := in.Request.(*smithyhttp.Request) + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} + } + + input, ok := in.Parameters.(*GetDelegatedAccessTokenInput) + _ = input + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown input parameters type %T", in.Parameters)} + } + + operationPath := "/" + if len(request.Request.URL.Path) == 0 { + request.Request.URL.Path = operationPath + } else { + request.Request.URL.Path = path.Join(request.Request.URL.Path, operationPath) + if request.Request.URL.Path != "/" && operationPath[len(operationPath)-1] == '/' { + request.Request.URL.Path += "/" + } + } + request.Request.Method = "POST" + httpBindingEncoder, err := httpbinding.NewEncoder(request.URL.Path, request.URL.RawQuery, request.Header) + if err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + httpBindingEncoder.SetHeader("Content-Type").String("application/x-www-form-urlencoded") + + bodyWriter := bytes.NewBuffer(nil) + bodyEncoder := query.NewEncoder(bodyWriter) + body := bodyEncoder.Object() + body.Key("Action").String("GetDelegatedAccessToken") + body.Key("Version").String("2011-06-15") + + if err := awsAwsquery_serializeOpDocumentGetDelegatedAccessTokenInput(input, bodyEncoder.Value); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + err = bodyEncoder.Encode() + if err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request, err = request.SetStream(bytes.NewReader(bodyWriter.Bytes())); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request.Request, err = httpBindingEncoder.Encode(request.Request); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + in.Request = request + + endTimer() + span.End() + return next.HandleSerialize(ctx, in) +} + type awsAwsquery_serializeOpGetFederationToken struct { } @@ -641,6 +711,76 @@ func (m *awsAwsquery_serializeOpGetSessionToken) HandleSerialize(ctx context.Con span.End() return next.HandleSerialize(ctx, in) } + +type awsAwsquery_serializeOpGetWebIdentityToken struct { +} + +func (*awsAwsquery_serializeOpGetWebIdentityToken) ID() string { + return "OperationSerializer" +} + +func (m *awsAwsquery_serializeOpGetWebIdentityToken) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( + out middleware.SerializeOutput, metadata middleware.Metadata, err error, +) { + _, span := tracing.StartSpan(ctx, "OperationSerializer") + endTimer := startMetricTimer(ctx, "client.call.serialization_duration") + defer endTimer() + defer span.End() + request, ok := in.Request.(*smithyhttp.Request) + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown transport type %T", in.Request)} + } + + input, ok := in.Parameters.(*GetWebIdentityTokenInput) + _ = input + if !ok { + return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown input parameters type %T", in.Parameters)} + } + + operationPath := "/" + if len(request.Request.URL.Path) == 0 { + request.Request.URL.Path = operationPath + } else { + request.Request.URL.Path = path.Join(request.Request.URL.Path, operationPath) + if request.Request.URL.Path != "/" && operationPath[len(operationPath)-1] == '/' { + request.Request.URL.Path += "/" + } + } + request.Request.Method = "POST" + httpBindingEncoder, err := httpbinding.NewEncoder(request.URL.Path, request.URL.RawQuery, request.Header) + if err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + httpBindingEncoder.SetHeader("Content-Type").String("application/x-www-form-urlencoded") + + bodyWriter := bytes.NewBuffer(nil) + bodyEncoder := query.NewEncoder(bodyWriter) + body := bodyEncoder.Object() + body.Key("Action").String("GetWebIdentityToken") + body.Key("Version").String("2011-06-15") + + if err := awsAwsquery_serializeOpDocumentGetWebIdentityTokenInput(input, bodyEncoder.Value); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + err = bodyEncoder.Encode() + if err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request, err = request.SetStream(bytes.NewReader(bodyWriter.Bytes())); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + + if request.Request, err = httpBindingEncoder.Encode(request.Request); err != nil { + return out, metadata, &smithy.SerializationError{Err: err} + } + in.Request = request + + endTimer() + span.End() + return next.HandleSerialize(ctx, in) +} func awsAwsquery_serializeDocumentPolicyDescriptorListType(v []types.PolicyDescriptorType, value query.Value) error { array := value.Array("member") @@ -733,6 +873,16 @@ func awsAwsquery_serializeDocumentTagListType(v []types.Tag, value query.Value) return nil } +func awsAwsquery_serializeDocumentWebIdentityTokenAudienceListType(v []string, value query.Value) error { + array := value.Array("member") + + for i := range v { + av := array.Value() + av.String(v[i]) + } + return nil +} + func awsAwsquery_serializeOpDocumentAssumeRoleInput(v *AssumeRoleInput, value query.Value) error { object := value.Object() _ = object @@ -946,6 +1096,18 @@ func awsAwsquery_serializeOpDocumentGetCallerIdentityInput(v *GetCallerIdentityI return nil } +func awsAwsquery_serializeOpDocumentGetDelegatedAccessTokenInput(v *GetDelegatedAccessTokenInput, value query.Value) error { + object := value.Object() + _ = object + + if v.TradeInToken != nil { + objectKey := object.Key("TradeInToken") + objectKey.String(*v.TradeInToken) + } + + return nil +} + func awsAwsquery_serializeOpDocumentGetFederationTokenInput(v *GetFederationTokenInput, value query.Value) error { object := value.Object() _ = object @@ -1003,3 +1165,34 @@ func awsAwsquery_serializeOpDocumentGetSessionTokenInput(v *GetSessionTokenInput return nil } + +func awsAwsquery_serializeOpDocumentGetWebIdentityTokenInput(v *GetWebIdentityTokenInput, value query.Value) error { + object := value.Object() + _ = object + + if v.Audience != nil { + objectKey := object.Key("Audience") + if err := awsAwsquery_serializeDocumentWebIdentityTokenAudienceListType(v.Audience, objectKey); err != nil { + return err + } + } + + if v.DurationSeconds != nil { + objectKey := object.Key("DurationSeconds") + objectKey.Integer(*v.DurationSeconds) + } + + if v.SigningAlgorithm != nil { + objectKey := object.Key("SigningAlgorithm") + objectKey.String(*v.SigningAlgorithm) + } + + if v.Tags != nil { + objectKey := object.Key("Tags") + if err := awsAwsquery_serializeDocumentTagListType(v.Tags, objectKey); err != nil { + return err + } + } + + return nil +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/sts/types/errors.go b/vendor/github.com/aws/aws-sdk-go-v2/service/sts/types/errors.go index 041629bba2c..70d99a220b8 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/sts/types/errors.go +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/sts/types/errors.go @@ -34,6 +34,33 @@ func (e *ExpiredTokenException) ErrorCode() string { } func (e *ExpiredTokenException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } +// The trade-in token provided in the request has expired and can no longer be +// exchanged for credentials. Request a new token and retry the operation. +type ExpiredTradeInTokenException struct { + Message *string + + ErrorCodeOverride *string + + noSmithyDocumentSerde +} + +func (e *ExpiredTradeInTokenException) Error() string { + return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) +} +func (e *ExpiredTradeInTokenException) ErrorMessage() string { + if e.Message == nil { + return "" + } + return *e.Message +} +func (e *ExpiredTradeInTokenException) ErrorCode() string { + if e == nil || e.ErrorCodeOverride == nil { + return "ExpiredTradeInTokenException" + } + return *e.ErrorCodeOverride +} +func (e *ExpiredTradeInTokenException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } + // The request could not be fulfilled because the identity provider (IDP) that was // asked to verify the incoming identity token could not be reached. This is often // a transient error caused by network conditions. Retry the request a limited @@ -152,6 +179,34 @@ func (e *InvalidIdentityTokenException) ErrorCode() string { } func (e *InvalidIdentityTokenException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } +// The requested token payload size exceeds the maximum allowed size. Reduce the +// number of request tags included in the GetWebIdentityToken API call to reduce +// the token payload size. +type JWTPayloadSizeExceededException struct { + Message *string + + ErrorCodeOverride *string + + noSmithyDocumentSerde +} + +func (e *JWTPayloadSizeExceededException) Error() string { + return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) +} +func (e *JWTPayloadSizeExceededException) ErrorMessage() string { + if e.Message == nil { + return "" + } + return *e.Message +} +func (e *JWTPayloadSizeExceededException) ErrorCode() string { + if e == nil || e.ErrorCodeOverride == nil { + return "JWTPayloadSizeExceededException" + } + return *e.ErrorCodeOverride +} +func (e *JWTPayloadSizeExceededException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } + // The request was rejected because the policy document was malformed. The error // message describes the specific error. type MalformedPolicyDocumentException struct { @@ -179,6 +234,36 @@ func (e *MalformedPolicyDocumentException) ErrorCode() string { } func (e *MalformedPolicyDocumentException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } +// The outbound web identity federation feature is not enabled for this account. +// To use this feature, you must first enable it through the Amazon Web Services +// Management Console or API. +type OutboundWebIdentityFederationDisabledException struct { + Message *string + + ErrorCodeOverride *string + + noSmithyDocumentSerde +} + +func (e *OutboundWebIdentityFederationDisabledException) Error() string { + return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) +} +func (e *OutboundWebIdentityFederationDisabledException) ErrorMessage() string { + if e.Message == nil { + return "" + } + return *e.Message +} +func (e *OutboundWebIdentityFederationDisabledException) ErrorCode() string { + if e == nil || e.ErrorCodeOverride == nil { + return "OutboundWebIdentityFederationDisabledException" + } + return *e.ErrorCodeOverride +} +func (e *OutboundWebIdentityFederationDisabledException) ErrorFault() smithy.ErrorFault { + return smithy.FaultClient +} + // The request was rejected because the total packed size of the session policies // and session tags combined was too large. An Amazon Web Services conversion // compresses the session policy document, session policy ARNs, and session tags @@ -221,7 +306,7 @@ func (e *PackedPolicyTooLargeException) ErrorFault() smithy.ErrorFault { return // console to activate STS in that region. For more information, see [Activating and Deactivating STS in an Amazon Web Services Region]in the IAM // User Guide. // -// [Activating and Deactivating STS in an Amazon Web Services Region]: https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_enable-regions.html +// [Activating and Deactivating STS in an Amazon Web Services Region]: https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_enable-regions.html#sts-regions-activate-deactivate type RegionDisabledException struct { Message *string @@ -246,3 +331,33 @@ func (e *RegionDisabledException) ErrorCode() string { return *e.ErrorCodeOverride } func (e *RegionDisabledException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } + +// The requested token duration would extend the session beyond its original +// expiration time. You cannot use this operation to extend the lifetime of a +// session beyond what was granted when the session was originally created. +type SessionDurationEscalationException struct { + Message *string + + ErrorCodeOverride *string + + noSmithyDocumentSerde +} + +func (e *SessionDurationEscalationException) Error() string { + return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) +} +func (e *SessionDurationEscalationException) ErrorMessage() string { + if e.Message == nil { + return "" + } + return *e.Message +} +func (e *SessionDurationEscalationException) ErrorCode() string { + if e == nil || e.ErrorCodeOverride == nil { + return "SessionDurationEscalationException" + } + return *e.ErrorCodeOverride +} +func (e *SessionDurationEscalationException) ErrorFault() smithy.ErrorFault { + return smithy.FaultClient +} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/sts/validators.go b/vendor/github.com/aws/aws-sdk-go-v2/service/sts/validators.go index 1026e22118d..4d37dd22a1d 100644 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/sts/validators.go +++ b/vendor/github.com/aws/aws-sdk-go-v2/service/sts/validators.go @@ -130,6 +130,26 @@ func (m *validateOpGetAccessKeyInfo) HandleInitialize(ctx context.Context, in mi return next.HandleInitialize(ctx, in) } +type validateOpGetDelegatedAccessToken struct { +} + +func (*validateOpGetDelegatedAccessToken) ID() string { + return "OperationInputValidation" +} + +func (m *validateOpGetDelegatedAccessToken) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( + out middleware.InitializeOutput, metadata middleware.Metadata, err error, +) { + input, ok := in.Parameters.(*GetDelegatedAccessTokenInput) + if !ok { + return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) + } + if err := validateOpGetDelegatedAccessTokenInput(input); err != nil { + return out, metadata, err + } + return next.HandleInitialize(ctx, in) +} + type validateOpGetFederationToken struct { } @@ -150,6 +170,26 @@ func (m *validateOpGetFederationToken) HandleInitialize(ctx context.Context, in return next.HandleInitialize(ctx, in) } +type validateOpGetWebIdentityToken struct { +} + +func (*validateOpGetWebIdentityToken) ID() string { + return "OperationInputValidation" +} + +func (m *validateOpGetWebIdentityToken) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( + out middleware.InitializeOutput, metadata middleware.Metadata, err error, +) { + input, ok := in.Parameters.(*GetWebIdentityTokenInput) + if !ok { + return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) + } + if err := validateOpGetWebIdentityTokenInput(input); err != nil { + return out, metadata, err + } + return next.HandleInitialize(ctx, in) +} + func addOpAssumeRoleValidationMiddleware(stack *middleware.Stack) error { return stack.Initialize.Add(&validateOpAssumeRole{}, middleware.After) } @@ -174,10 +214,18 @@ func addOpGetAccessKeyInfoValidationMiddleware(stack *middleware.Stack) error { return stack.Initialize.Add(&validateOpGetAccessKeyInfo{}, middleware.After) } +func addOpGetDelegatedAccessTokenValidationMiddleware(stack *middleware.Stack) error { + return stack.Initialize.Add(&validateOpGetDelegatedAccessToken{}, middleware.After) +} + func addOpGetFederationTokenValidationMiddleware(stack *middleware.Stack) error { return stack.Initialize.Add(&validateOpGetFederationToken{}, middleware.After) } +func addOpGetWebIdentityTokenValidationMiddleware(stack *middleware.Stack) error { + return stack.Initialize.Add(&validateOpGetWebIdentityToken{}, middleware.After) +} + func validateTag(v *types.Tag) error { if v == nil { return nil @@ -326,6 +374,21 @@ func validateOpGetAccessKeyInfoInput(v *GetAccessKeyInfoInput) error { } } +func validateOpGetDelegatedAccessTokenInput(v *GetDelegatedAccessTokenInput) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "GetDelegatedAccessTokenInput"} + if v.TradeInToken == nil { + invalidParams.Add(smithy.NewErrParamRequired("TradeInToken")) + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} + func validateOpGetFederationTokenInput(v *GetFederationTokenInput) error { if v == nil { return nil @@ -345,3 +408,26 @@ func validateOpGetFederationTokenInput(v *GetFederationTokenInput) error { return nil } } + +func validateOpGetWebIdentityTokenInput(v *GetWebIdentityTokenInput) error { + if v == nil { + return nil + } + invalidParams := smithy.InvalidParamsError{Context: "GetWebIdentityTokenInput"} + if v.Audience == nil { + invalidParams.Add(smithy.NewErrParamRequired("Audience")) + } + if v.SigningAlgorithm == nil { + invalidParams.Add(smithy.NewErrParamRequired("SigningAlgorithm")) + } + if v.Tags != nil { + if err := validateTagListType(v.Tags); err != nil { + invalidParams.AddNested("Tags", err.(smithy.InvalidParamsError)) + } + } + if invalidParams.Len() > 0 { + return invalidParams + } else { + return nil + } +} diff --git a/vendor/github.com/aws/smithy-go/CHANGELOG.md b/vendor/github.com/aws/smithy-go/CHANGELOG.md index 8b6ab295004..80af245f087 100644 --- a/vendor/github.com/aws/smithy-go/CHANGELOG.md +++ b/vendor/github.com/aws/smithy-go/CHANGELOG.md @@ -1,3 +1,34 @@ +# Release (2025-12-01) + +## General Highlights +* **Dependency Update**: Updated to the latest SDK module versions + +## Module Highlights +* `github.com/aws/smithy-go`: v1.24.0 + * **Feature**: Improve allocation footprint of the middleware stack. This should convey a ~10% reduction in allocations per SDK request. + +# Release (2025-11-03) + +## General Highlights +* **Dependency Update**: Updated to the latest SDK module versions + +## Module Highlights +* `github.com/aws/smithy-go`: v1.23.2 + * **Bug Fix**: Adjust the initial sizes of each middleware phase to avoid some unnecessary reallocation. + * **Bug Fix**: Avoid unnecessary allocation overhead from the metrics system when not in use. + +# Release (2025-10-15) + +## General Highlights +* **Dependency Update**: Bump minimum go version to 1.23. +* **Dependency Update**: Updated to the latest SDK module versions + +# Release (2025-09-18) + +## Module Highlights +* `github.com/aws/smithy-go/aws-http-auth`: [v1.1.0](aws-http-auth/CHANGELOG.md#v110-2025-09-18) + * **Feature**: Added support for SIG4/SIGV4A querystring authentication. + # Release (2025-08-27) ## General Highlights diff --git a/vendor/github.com/aws/smithy-go/Makefile b/vendor/github.com/aws/smithy-go/Makefile index 34b17ab2fe0..a12b124d505 100644 --- a/vendor/github.com/aws/smithy-go/Makefile +++ b/vendor/github.com/aws/smithy-go/Makefile @@ -13,6 +13,7 @@ REPOTOOLS_CMD_GENERATE_CHANGELOG = ${REPOTOOLS_MODULE}/cmd/generatechangelog@${R REPOTOOLS_CMD_CHANGELOG = ${REPOTOOLS_MODULE}/cmd/changelog@${REPOTOOLS_VERSION} REPOTOOLS_CMD_TAG_RELEASE = ${REPOTOOLS_MODULE}/cmd/tagrelease@${REPOTOOLS_VERSION} REPOTOOLS_CMD_MODULE_VERSION = ${REPOTOOLS_MODULE}/cmd/moduleversion@${REPOTOOLS_VERSION} +REPOTOOLS_CMD_EACHMODULE = ${REPOTOOLS_MODULE}/cmd/eachmodule@${REPOTOOLS_VERSION} UNIT_TEST_TAGS= BUILD_TAGS= @@ -55,8 +56,11 @@ ensure-gradle-up: verify: vet -vet: - go vet ${BUILD_TAGS} --all ./... +vet: vet-modules-. + +vet-modules-%: + go run ${REPOTOOLS_CMD_EACHMODULE} -p $(subst vet-modules-,,$@) \ + "go vet ${BUILD_TAGS} --all ./..." cover: go test ${BUILD_TAGS} -coverprofile c.out ./... @@ -66,21 +70,22 @@ cover: ################ # Unit Testing # ################ -.PHONY: unit unit-race unit-test unit-race-test +.PHONY: test unit unit-race + +test: unit-race + +unit: verify unit-modules-. -unit: verify - go test ${BUILD_TAGS} ${RUN_NONE} ./... && \ - go test -timeout=1m ${UNIT_TEST_TAGS} ./... +unit-modules-%: + go run ${REPOTOOLS_CMD_EACHMODULE} -p $(subst unit-modules-,,$@) \ + "go test -timeout=1m ${UNIT_TEST_TAGS} ./..." -unit-race: verify - go test ${BUILD_TAGS} ${RUN_NONE} ./... && \ - go test -timeout=1m ${UNIT_TEST_TAGS} -race -cpu=4 ./... +unit-race: verify unit-race-modules-. -unit-test: verify - go test -timeout=1m ${UNIT_TEST_TAGS} ./... +unit-race-modules-%: + go run ${REPOTOOLS_CMD_EACHMODULE} -p $(subst unit-race-modules-,,$@) \ + "go test -timeout=1m ${UNIT_TEST_TAGS} -race -cpu=4 ./..." -unit-race-test: verify - go test -timeout=1m ${UNIT_TEST_TAGS} -race -cpu=4 ./... ##################### # Release Process # diff --git a/vendor/github.com/aws/smithy-go/README.md b/vendor/github.com/aws/smithy-go/README.md index 77a74ae0c2c..ddce37b99ef 100644 --- a/vendor/github.com/aws/smithy-go/README.md +++ b/vendor/github.com/aws/smithy-go/README.md @@ -4,7 +4,7 @@ [Smithy](https://smithy.io/) code generators for Go and the accompanying smithy-go runtime. -The smithy-go runtime requires a minimum version of Go 1.22. +The smithy-go runtime requires a minimum version of Go 1.23. **WARNING: All interfaces are subject to change.** @@ -80,7 +80,7 @@ example created from `smithy init`: "service": "example.weather#Weather", "module": "github.com/example/weather", "generateGoMod": true, - "goDirective": "1.22" + "goDirective": "1.23" } } } diff --git a/vendor/github.com/aws/smithy-go/endpoints/private/rulesfn/doc.go b/vendor/github.com/aws/smithy-go/endpoints/private/rulesfn/doc.go new file mode 100644 index 00000000000..e24e190dca7 --- /dev/null +++ b/vendor/github.com/aws/smithy-go/endpoints/private/rulesfn/doc.go @@ -0,0 +1,4 @@ +// Package rulesfn provides endpoint rule functions for evaluating endpoint +// resolution rules. + +package rulesfn diff --git a/vendor/github.com/aws/smithy-go/endpoints/private/rulesfn/strings.go b/vendor/github.com/aws/smithy-go/endpoints/private/rulesfn/strings.go new file mode 100644 index 00000000000..5cf4a7b02d7 --- /dev/null +++ b/vendor/github.com/aws/smithy-go/endpoints/private/rulesfn/strings.go @@ -0,0 +1,25 @@ +package rulesfn + +// Substring returns the substring of the input provided. If the start or stop +// indexes are not valid for the input nil will be returned. If errors occur +// they will be added to the provided [ErrorCollector]. +func SubString(input string, start, stop int, reverse bool) *string { + if start < 0 || stop < 1 || start >= stop || len(input) < stop { + return nil + } + + for _, r := range input { + if r > 127 { + return nil + } + } + + if !reverse { + v := input[start:stop] + return &v + } + + rStart := len(input) - stop + rStop := len(input) - start + return SubString(input, rStart, rStop, false) +} diff --git a/vendor/github.com/aws/smithy-go/endpoints/private/rulesfn/uri.go b/vendor/github.com/aws/smithy-go/endpoints/private/rulesfn/uri.go new file mode 100644 index 00000000000..0c11541276b --- /dev/null +++ b/vendor/github.com/aws/smithy-go/endpoints/private/rulesfn/uri.go @@ -0,0 +1,130 @@ +package rulesfn + +import ( + "fmt" + "net" + "net/url" + "strings" + + smithyhttp "github.com/aws/smithy-go/transport/http" +) + +// IsValidHostLabel returns if the input is a single valid [RFC 1123] host +// label. If allowSubDomains is true, will allow validation to include nested +// host labels. Returns false if the input is not a valid host label. If errors +// occur they will be added to the provided [ErrorCollector]. +// +// [RFC 1123]: https://www.ietf.org/rfc/rfc1123.txt +func IsValidHostLabel(input string, allowSubDomains bool) bool { + var labels []string + if allowSubDomains { + labels = strings.Split(input, ".") + } else { + labels = []string{input} + } + + for _, label := range labels { + if !smithyhttp.ValidHostLabel(label) { + return false + } + } + + return true +} + +// ParseURL returns a [URL] if the provided string could be parsed. Returns nil +// if the string could not be parsed. Any parsing error will be added to the +// [ErrorCollector]. +// +// If the input URL string contains an IP6 address with a zone index. The +// returned [builtin.URL.Authority] value will contain the percent escaped (%) +// zone index separator. +func ParseURL(input string) *URL { + u, err := url.Parse(input) + if err != nil { + return nil + } + + if u.RawQuery != "" { + return nil + } + + if u.Scheme != "http" && u.Scheme != "https" { + return nil + } + + normalizedPath := u.Path + if !strings.HasPrefix(normalizedPath, "/") { + normalizedPath = "/" + normalizedPath + } + if !strings.HasSuffix(normalizedPath, "/") { + normalizedPath = normalizedPath + "/" + } + + // IP6 hosts may have zone indexes that need to be escaped to be valid in a + // URI. The Go URL parser will unescape the `%25` into `%`. This needs to + // be reverted since the returned URL will be used in string builders. + authority := strings.ReplaceAll(u.Host, "%", "%25") + + return &URL{ + Scheme: u.Scheme, + Authority: authority, + Path: u.Path, + NormalizedPath: normalizedPath, + IsIp: net.ParseIP(hostnameWithoutZone(u)) != nil, + } +} + +// URL provides the structure describing the parts of a parsed URL returned by +// [ParseURL]. +type URL struct { + Scheme string // https://www.rfc-editor.org/rfc/rfc3986#section-3.1 + Authority string // https://www.rfc-editor.org/rfc/rfc3986#section-3.2 + Path string // https://www.rfc-editor.org/rfc/rfc3986#section-3.3 + NormalizedPath string // https://www.rfc-editor.org/rfc/rfc3986#section-6.2.3 + IsIp bool +} + +// URIEncode returns an percent-encoded [RFC3986 section 2.1] version of the +// input string. +// +// [RFC3986 section 2.1]: https://www.rfc-editor.org/rfc/rfc3986#section-2.1 +func URIEncode(input string) string { + var output strings.Builder + for _, c := range []byte(input) { + if validPercentEncodedChar(c) { + output.WriteByte(c) + continue + } + + fmt.Fprintf(&output, "%%%X", c) + } + + return output.String() +} + +func validPercentEncodedChar(c byte) bool { + return (c >= 'a' && c <= 'z') || + (c >= 'A' && c <= 'Z') || + (c >= '0' && c <= '9') || + c == '-' || c == '_' || c == '.' || c == '~' +} + +// hostname implements u.Hostname() but strips the ipv6 zone ID (if present) +// such that net.ParseIP can still recognize IPv6 addresses with zone IDs. +// +// FUTURE(10/2023): netip.ParseAddr handles this natively but we can't take +// that package as a dependency yet due to our min go version (1.15, netip +// starts in 1.18). When we align with go runtime deprecation policy in +// 10/2023, we can remove this. +func hostnameWithoutZone(u *url.URL) string { + full := u.Hostname() + + // this more or less mimics the internals of net/ (see unexported + // splitHostZone in that source) but throws the zone away because we don't + // need it + if i := strings.LastIndex(full, "%"); i > -1 { + return full[:i] + } + return full +} diff --git a/vendor/github.com/aws/smithy-go/go_module_metadata.go b/vendor/github.com/aws/smithy-go/go_module_metadata.go index 945db0af309..b6c4c2f51cf 100644 --- a/vendor/github.com/aws/smithy-go/go_module_metadata.go +++ b/vendor/github.com/aws/smithy-go/go_module_metadata.go @@ -3,4 +3,4 @@ package smithy // goModuleVersion is the tagged release for this module -const goModuleVersion = "1.23.0" +const goModuleVersion = "1.24.0" diff --git a/vendor/github.com/aws/smithy-go/metrics/nop.go b/vendor/github.com/aws/smithy-go/metrics/nop.go index fb374e1fb85..444126df5a0 100644 --- a/vendor/github.com/aws/smithy-go/metrics/nop.go +++ b/vendor/github.com/aws/smithy-go/metrics/nop.go @@ -9,54 +9,82 @@ var _ MeterProvider = (*NopMeterProvider)(nil) // Meter returns a meter which creates no-op instruments. func (NopMeterProvider) Meter(string, ...MeterOption) Meter { - return nopMeter{} + return NopMeter{} } -type nopMeter struct{} +// NopMeter creates no-op instruments. +type NopMeter struct{} -var _ Meter = (*nopMeter)(nil) +var _ Meter = (*NopMeter)(nil) -func (nopMeter) Int64Counter(string, ...InstrumentOption) (Int64Counter, error) { - return nopInstrument[int64]{}, nil +// Int64Counter creates a no-op instrument. +func (NopMeter) Int64Counter(string, ...InstrumentOption) (Int64Counter, error) { + return nopInstrumentInt64, nil } -func (nopMeter) Int64UpDownCounter(string, ...InstrumentOption) (Int64UpDownCounter, error) { - return nopInstrument[int64]{}, nil + +// Int64UpDownCounter creates a no-op instrument. +func (NopMeter) Int64UpDownCounter(string, ...InstrumentOption) (Int64UpDownCounter, error) { + return nopInstrumentInt64, nil } -func (nopMeter) Int64Gauge(string, ...InstrumentOption) (Int64Gauge, error) { - return nopInstrument[int64]{}, nil + +// Int64Gauge creates a no-op instrument. +func (NopMeter) Int64Gauge(string, ...InstrumentOption) (Int64Gauge, error) { + return nopInstrumentInt64, nil } -func (nopMeter) Int64Histogram(string, ...InstrumentOption) (Int64Histogram, error) { - return nopInstrument[int64]{}, nil + +// Int64Histogram creates a no-op instrument. +func (NopMeter) Int64Histogram(string, ...InstrumentOption) (Int64Histogram, error) { + return nopInstrumentInt64, nil } -func (nopMeter) Int64AsyncCounter(string, Int64Callback, ...InstrumentOption) (AsyncInstrument, error) { - return nopInstrument[int64]{}, nil + +// Int64AsyncCounter creates a no-op instrument. +func (NopMeter) Int64AsyncCounter(string, Int64Callback, ...InstrumentOption) (AsyncInstrument, error) { + return nopInstrumentInt64, nil } -func (nopMeter) Int64AsyncUpDownCounter(string, Int64Callback, ...InstrumentOption) (AsyncInstrument, error) { - return nopInstrument[int64]{}, nil + +// Int64AsyncUpDownCounter creates a no-op instrument. +func (NopMeter) Int64AsyncUpDownCounter(string, Int64Callback, ...InstrumentOption) (AsyncInstrument, error) { + return nopInstrumentInt64, nil } -func (nopMeter) Int64AsyncGauge(string, Int64Callback, ...InstrumentOption) (AsyncInstrument, error) { - return nopInstrument[int64]{}, nil + +// Int64AsyncGauge creates a no-op instrument. +func (NopMeter) Int64AsyncGauge(string, Int64Callback, ...InstrumentOption) (AsyncInstrument, error) { + return nopInstrumentInt64, nil } -func (nopMeter) Float64Counter(string, ...InstrumentOption) (Float64Counter, error) { - return nopInstrument[float64]{}, nil + +// Float64Counter creates a no-op instrument. +func (NopMeter) Float64Counter(string, ...InstrumentOption) (Float64Counter, error) { + return nopInstrumentFloat64, nil } -func (nopMeter) Float64UpDownCounter(string, ...InstrumentOption) (Float64UpDownCounter, error) { - return nopInstrument[float64]{}, nil + +// Float64UpDownCounter creates a no-op instrument. +func (NopMeter) Float64UpDownCounter(string, ...InstrumentOption) (Float64UpDownCounter, error) { + return nopInstrumentFloat64, nil } -func (nopMeter) Float64Gauge(string, ...InstrumentOption) (Float64Gauge, error) { - return nopInstrument[float64]{}, nil + +// Float64Gauge creates a no-op instrument. +func (NopMeter) Float64Gauge(string, ...InstrumentOption) (Float64Gauge, error) { + return nopInstrumentFloat64, nil } -func (nopMeter) Float64Histogram(string, ...InstrumentOption) (Float64Histogram, error) { - return nopInstrument[float64]{}, nil + +// Float64Histogram creates a no-op instrument. +func (NopMeter) Float64Histogram(string, ...InstrumentOption) (Float64Histogram, error) { + return nopInstrumentFloat64, nil } -func (nopMeter) Float64AsyncCounter(string, Float64Callback, ...InstrumentOption) (AsyncInstrument, error) { - return nopInstrument[float64]{}, nil + +// Float64AsyncCounter creates a no-op instrument. +func (NopMeter) Float64AsyncCounter(string, Float64Callback, ...InstrumentOption) (AsyncInstrument, error) { + return nopInstrumentFloat64, nil } -func (nopMeter) Float64AsyncUpDownCounter(string, Float64Callback, ...InstrumentOption) (AsyncInstrument, error) { - return nopInstrument[float64]{}, nil + +// Float64AsyncUpDownCounter creates a no-op instrument. +func (NopMeter) Float64AsyncUpDownCounter(string, Float64Callback, ...InstrumentOption) (AsyncInstrument, error) { + return nopInstrumentFloat64, nil } -func (nopMeter) Float64AsyncGauge(string, Float64Callback, ...InstrumentOption) (AsyncInstrument, error) { - return nopInstrument[float64]{}, nil + +// Float64AsyncGauge creates a no-op instrument. +func (NopMeter) Float64AsyncGauge(string, Float64Callback, ...InstrumentOption) (AsyncInstrument, error) { + return nopInstrumentFloat64, nil } type nopInstrument[N any] struct{} @@ -65,3 +93,6 @@ func (nopInstrument[N]) Add(context.Context, N, ...RecordMetricOption) {} func (nopInstrument[N]) Sample(context.Context, N, ...RecordMetricOption) {} func (nopInstrument[N]) Record(context.Context, N, ...RecordMetricOption) {} func (nopInstrument[_]) Stop() {} + +var nopInstrumentInt64 = nopInstrument[int64]{} +var nopInstrumentFloat64 = nopInstrument[float64]{} diff --git a/vendor/github.com/aws/smithy-go/middleware/ordered_group.go b/vendor/github.com/aws/smithy-go/middleware/ordered_group.go index 4b195308c59..daf90136e96 100644 --- a/vendor/github.com/aws/smithy-go/middleware/ordered_group.go +++ b/vendor/github.com/aws/smithy-go/middleware/ordered_group.go @@ -23,12 +23,14 @@ type orderedIDs struct { items map[string]ider } -const baseOrderedItems = 5 +// selected based on the general upper bound of # of middlewares in each step +// in the downstream aws-sdk-go-v2 +const baseOrderedItems = 8 -func newOrderedIDs() *orderedIDs { +func newOrderedIDs(cap int) *orderedIDs { return &orderedIDs{ - order: newRelativeOrder(), - items: make(map[string]ider, baseOrderedItems), + order: newRelativeOrder(cap), + items: make(map[string]ider, cap), } } @@ -141,9 +143,9 @@ type relativeOrder struct { order []string } -func newRelativeOrder() *relativeOrder { +func newRelativeOrder(cap int) *relativeOrder { return &relativeOrder{ - order: make([]string, 0, baseOrderedItems), + order: make([]string, 0, cap), } } diff --git a/vendor/github.com/aws/smithy-go/middleware/step_build.go b/vendor/github.com/aws/smithy-go/middleware/step_build.go index 7e1d94caeef..db8c26715cb 100644 --- a/vendor/github.com/aws/smithy-go/middleware/step_build.go +++ b/vendor/github.com/aws/smithy-go/middleware/step_build.go @@ -1,7 +1,9 @@ +// Code generated by smithy-go/middleware/generate.go DO NOT EDIT. package middleware import ( "context" + "fmt" ) // BuildInput provides the input parameters for the BuildMiddleware to consume. @@ -25,14 +27,14 @@ type BuildHandler interface { } // BuildMiddleware provides the interface for middleware specific to the -// serialize step. Delegates to the next BuildHandler for further +// build step. Delegates to the next BuildHandler for further // processing. type BuildMiddleware interface { - // Unique ID for the middleware in theBuildStep. The step does not allow - // duplicate IDs. + // ID returns a unique ID for the middleware in the BuildStep. The step does not + // allow duplicate IDs. ID() string - // Invokes the middleware behavior which must delegate to the next handler + // HandleBuild invokes the middleware behavior which must delegate to the next handler // for the middleware chain to continue. The method must return a result or // error to its caller. HandleBuild(ctx context.Context, in BuildInput, next BuildHandler) ( @@ -54,7 +56,9 @@ type buildMiddlewareFunc struct { id string // Middleware function to be called. - fn func(context.Context, BuildInput, BuildHandler) (BuildOutput, Metadata, error) + fn func(context.Context, BuildInput, BuildHandler) ( + BuildOutput, Metadata, error, + ) } // ID returns the unique ID for the middleware. @@ -69,23 +73,22 @@ func (s buildMiddlewareFunc) HandleBuild(ctx context.Context, in BuildInput, nex var _ BuildMiddleware = (buildMiddlewareFunc{}) -// BuildStep provides the ordered grouping of BuildMiddleware to be invoked on -// a handler. +// BuildStep provides the ordered grouping of BuildMiddleware to be +// invoked on a handler. type BuildStep struct { - ids *orderedIDs + head *decoratedBuildHandler + tail *decoratedBuildHandler } -// NewBuildStep returns a BuildStep ready to have middleware for -// initialization added to it. +// NewBuildStep returns an BuildStep ready to have middleware for +// build added to it. func NewBuildStep() *BuildStep { - return &BuildStep{ - ids: newOrderedIDs(), - } + return &BuildStep{} } var _ Middleware = (*BuildStep)(nil) -// ID returns the unique name of the step as a middleware. +// ID returns the unique ID of the step as a middleware. func (s *BuildStep) ID() string { return "Build stack step" } @@ -97,77 +100,161 @@ func (s *BuildStep) ID() string { func (s *BuildStep) HandleMiddleware(ctx context.Context, in interface{}, next Handler) ( out interface{}, metadata Metadata, err error, ) { - order := s.ids.GetOrder() - - var h BuildHandler = buildWrapHandler{Next: next} - for i := len(order) - 1; i >= 0; i-- { - h = decoratedBuildHandler{ - Next: h, - With: order[i].(BuildMiddleware), - } - } - sIn := BuildInput{ Request: in, } - res, metadata, err := h.HandleBuild(ctx, sIn) + wh := &buildWrapHandler{next} + if s.head == nil { + res, metadata, err := wh.HandleBuild(ctx, sIn) + return res.Result, metadata, err + } + + s.tail.Next = wh + res, metadata, err := s.head.HandleBuild(ctx, sIn) return res.Result, metadata, err } // Get retrieves the middleware identified by id. If the middleware is not present, returns false. func (s *BuildStep) Get(id string) (BuildMiddleware, bool) { - get, ok := s.ids.Get(id) - if !ok { + found, _ := s.get(id) + if found == nil { return nil, false } - return get.(BuildMiddleware), ok + + return found.With, true } // Add injects the middleware to the relative position of the middleware group. -// Returns an error if the middleware already exists. +// +// Add never returns an error. It used to for duplicate phases but this +// behavior has since been removed as part of a performance optimization. The +// return value from Add can be ignored. func (s *BuildStep) Add(m BuildMiddleware, pos RelativePosition) error { - return s.ids.Add(m, pos) + if s.head == nil { + s.head = &decoratedBuildHandler{nil, m} + s.tail = s.head + return nil + } + + if pos == Before { + s.head = &decoratedBuildHandler{s.head, m} + } else { + tail := &decoratedBuildHandler{nil, m} + s.tail.Next = tail + s.tail = tail + } + + return nil } -// Insert injects the middleware relative to an existing middleware id. -// Returns an error if the original middleware does not exist, or the middleware +// Insert injects the middleware relative to an existing middleware ID. +// Returns error if the original middleware does not exist, or the middleware // being added already exists. func (s *BuildStep) Insert(m BuildMiddleware, relativeTo string, pos RelativePosition) error { - return s.ids.Insert(m, relativeTo, pos) + found, prev := s.get(relativeTo) + if found == nil { + return fmt.Errorf("not found: %s", m.ID()) + } + + if pos == Before { + if prev == nil { // at the front + s.head = &decoratedBuildHandler{s.head, m} + } else { // somewhere in the middle + prev.Next = &decoratedBuildHandler{found, m} + } + } else { + if found.Next == nil { // at the end + tail := &decoratedBuildHandler{nil, m} + s.tail.Next = tail + s.tail = tail + } else { // somewhere in the middle + found.Next = &decoratedBuildHandler{found.Next, m} + } + } + + return nil } // Swap removes the middleware by id, replacing it with the new middleware. -// Returns the middleware removed, or an error if the middleware to be removed +// Returns the middleware removed, or error if the middleware to be removed // doesn't exist. func (s *BuildStep) Swap(id string, m BuildMiddleware) (BuildMiddleware, error) { - removed, err := s.ids.Swap(id, m) - if err != nil { - return nil, err + found, _ := s.get(id) + if found == nil { + return nil, fmt.Errorf("not found: %s", m.ID()) } - return removed.(BuildMiddleware), nil + swapped := found.With + found.With = m + return swapped, nil } // Remove removes the middleware by id. Returns error if the middleware // doesn't exist. func (s *BuildStep) Remove(id string) (BuildMiddleware, error) { - removed, err := s.ids.Remove(id) - if err != nil { - return nil, err + found, prev := s.get(id) + if found == nil { + return nil, fmt.Errorf("not found: %s", id) } - return removed.(BuildMiddleware), nil + if s.head == s.tail { // it's the only one + s.head = nil + s.tail = nil + } else if found == s.head { // at the front + s.head = s.head.Next.(*decoratedBuildHandler) + } else if found == s.tail { // at the end + prev.Next = nil + s.tail = prev + } else { + prev.Next = found.Next // somewhere in the middle + } + + return found.With, nil } // List returns a list of the middleware in the step. func (s *BuildStep) List() []string { - return s.ids.List() + var ids []string + for h := s.head; h != nil; { + ids = append(ids, h.With.ID()) + if h.Next == nil { + break + } + + // once executed, tail.Next of the list will be set to an + // *buildWrapHandler, make sure to check for that + if hnext, ok := h.Next.(*decoratedBuildHandler); ok { + h = hnext + } else { + break + } + } + return ids } // Clear removes all middleware in the step. func (s *BuildStep) Clear() { - s.ids.Clear() + s.head = nil + s.tail = nil +} + +func (s *BuildStep) get(id string) (found, prev *decoratedBuildHandler) { + for h := s.head; h != nil; { + if h.With.ID() == id { + found = h + return + } + prev = h + if h.Next == nil { + return + } + + // once executed, tail.Next of the list will be set to an + // *buildWrapHandler + h, _ = h.Next.(*decoratedBuildHandler) + } + return } type buildWrapHandler struct { @@ -176,7 +263,7 @@ type buildWrapHandler struct { var _ BuildHandler = (*buildWrapHandler)(nil) -// Implements BuildHandler, converts types and delegates to underlying +// HandleBuild implements BuildHandler, converts types and delegates to underlying // generic handler. func (w buildWrapHandler) HandleBuild(ctx context.Context, in BuildInput) ( out BuildOutput, metadata Metadata, err error, @@ -200,12 +287,12 @@ func (h decoratedBuildHandler) HandleBuild(ctx context.Context, in BuildInput) ( return h.With.HandleBuild(ctx, in, h.Next) } -// BuildHandlerFunc provides a wrapper around a function to be used as a build middleware handler. +// BuildHandlerFunc provides a wrapper around a function to be used as buildMiddleware. type BuildHandlerFunc func(context.Context, BuildInput) (BuildOutput, Metadata, error) -// HandleBuild invokes the wrapped function with the provided arguments. -func (b BuildHandlerFunc) HandleBuild(ctx context.Context, in BuildInput) (BuildOutput, Metadata, error) { - return b(ctx, in) +// HandleBuild calls the wrapped function with the provided arguments. +func (f BuildHandlerFunc) HandleBuild(ctx context.Context, in BuildInput) (BuildOutput, Metadata, error) { + return f(ctx, in) } var _ BuildHandler = BuildHandlerFunc(nil) diff --git a/vendor/github.com/aws/smithy-go/middleware/step_deserialize.go b/vendor/github.com/aws/smithy-go/middleware/step_deserialize.go index 44860721571..1f337f2dbc9 100644 --- a/vendor/github.com/aws/smithy-go/middleware/step_deserialize.go +++ b/vendor/github.com/aws/smithy-go/middleware/step_deserialize.go @@ -1,7 +1,9 @@ +// Code generated by smithy-go/middleware/generate.go DO NOT EDIT. package middleware import ( "context" + "fmt" ) // DeserializeInput provides the input parameters for the DeserializeInput to @@ -11,10 +13,7 @@ type DeserializeInput struct { Request interface{} } -// DeserializeOutput provides the result returned by the next -// DeserializeHandler. The DeserializeMiddleware should deserialize the -// RawResponse into a Result that can be consumed by middleware higher up in -// the stack. +// DeserializeOutput provides the result returned by the next DeserializeHandler. type DeserializeOutput struct { RawResponse interface{} Result interface{} @@ -29,7 +28,7 @@ type DeserializeHandler interface { } // DeserializeMiddleware provides the interface for middleware specific to the -// serialize step. Delegates to the next DeserializeHandler for further +// deserialize step. Delegates to the next DeserializeHandler for further // processing. type DeserializeMiddleware interface { // ID returns a unique ID for the middleware in the DeserializeStep. The step does not @@ -44,8 +43,8 @@ type DeserializeMiddleware interface { ) } -// DeserializeMiddlewareFunc returns a DeserializeMiddleware with the unique ID -// provided, and the func to be invoked. +// DeserializeMiddlewareFunc returns a DeserializeMiddleware with the unique ID provided, +// and the func to be invoked. func DeserializeMiddlewareFunc(id string, fn func(context.Context, DeserializeInput, DeserializeHandler) (DeserializeOutput, Metadata, error)) DeserializeMiddleware { return deserializeMiddlewareFunc{ id: id, @@ -78,15 +77,14 @@ var _ DeserializeMiddleware = (deserializeMiddlewareFunc{}) // DeserializeStep provides the ordered grouping of DeserializeMiddleware to be // invoked on a handler. type DeserializeStep struct { - ids *orderedIDs + head *decoratedDeserializeHandler + tail *decoratedDeserializeHandler } -// NewDeserializeStep returns a DeserializeStep ready to have middleware for -// initialization added to it. +// NewDeserializeStep returns an DeserializeStep ready to have middleware for +// deserialize added to it. func NewDeserializeStep() *DeserializeStep { - return &DeserializeStep{ - ids: newOrderedIDs(), - } + return &DeserializeStep{} } var _ Middleware = (*DeserializeStep)(nil) @@ -103,77 +101,161 @@ func (s *DeserializeStep) ID() string { func (s *DeserializeStep) HandleMiddleware(ctx context.Context, in interface{}, next Handler) ( out interface{}, metadata Metadata, err error, ) { - order := s.ids.GetOrder() - - var h DeserializeHandler = deserializeWrapHandler{Next: next} - for i := len(order) - 1; i >= 0; i-- { - h = decoratedDeserializeHandler{ - Next: h, - With: order[i].(DeserializeMiddleware), - } - } - sIn := DeserializeInput{ Request: in, } - res, metadata, err := h.HandleDeserialize(ctx, sIn) + wh := &deserializeWrapHandler{next} + if s.head == nil { + res, metadata, err := wh.HandleDeserialize(ctx, sIn) + return res.Result, metadata, err + } + + s.tail.Next = wh + res, metadata, err := s.head.HandleDeserialize(ctx, sIn) return res.Result, metadata, err } // Get retrieves the middleware identified by id. If the middleware is not present, returns false. func (s *DeserializeStep) Get(id string) (DeserializeMiddleware, bool) { - get, ok := s.ids.Get(id) - if !ok { + found, _ := s.get(id) + if found == nil { return nil, false } - return get.(DeserializeMiddleware), ok + + return found.With, true } // Add injects the middleware to the relative position of the middleware group. -// Returns an error if the middleware already exists. +// +// Add never returns an error. It used to for duplicate phases but this +// behavior has since been removed as part of a performance optimization. The +// return value from Add can be ignored. func (s *DeserializeStep) Add(m DeserializeMiddleware, pos RelativePosition) error { - return s.ids.Add(m, pos) + if s.head == nil { + s.head = &decoratedDeserializeHandler{nil, m} + s.tail = s.head + return nil + } + + if pos == Before { + s.head = &decoratedDeserializeHandler{s.head, m} + } else { + tail := &decoratedDeserializeHandler{nil, m} + s.tail.Next = tail + s.tail = tail + } + + return nil } // Insert injects the middleware relative to an existing middleware ID. // Returns error if the original middleware does not exist, or the middleware // being added already exists. func (s *DeserializeStep) Insert(m DeserializeMiddleware, relativeTo string, pos RelativePosition) error { - return s.ids.Insert(m, relativeTo, pos) + found, prev := s.get(relativeTo) + if found == nil { + return fmt.Errorf("not found: %s", m.ID()) + } + + if pos == Before { + if prev == nil { // at the front + s.head = &decoratedDeserializeHandler{s.head, m} + } else { // somewhere in the middle + prev.Next = &decoratedDeserializeHandler{found, m} + } + } else { + if found.Next == nil { // at the end + tail := &decoratedDeserializeHandler{nil, m} + s.tail.Next = tail + s.tail = tail + } else { // somewhere in the middle + found.Next = &decoratedDeserializeHandler{found.Next, m} + } + } + + return nil } // Swap removes the middleware by id, replacing it with the new middleware. // Returns the middleware removed, or error if the middleware to be removed // doesn't exist. func (s *DeserializeStep) Swap(id string, m DeserializeMiddleware) (DeserializeMiddleware, error) { - removed, err := s.ids.Swap(id, m) - if err != nil { - return nil, err + found, _ := s.get(id) + if found == nil { + return nil, fmt.Errorf("not found: %s", m.ID()) } - return removed.(DeserializeMiddleware), nil + swapped := found.With + found.With = m + return swapped, nil } // Remove removes the middleware by id. Returns error if the middleware // doesn't exist. func (s *DeserializeStep) Remove(id string) (DeserializeMiddleware, error) { - removed, err := s.ids.Remove(id) - if err != nil { - return nil, err + found, prev := s.get(id) + if found == nil { + return nil, fmt.Errorf("not found: %s", id) + } + + if s.head == s.tail { // it's the only one + s.head = nil + s.tail = nil + } else if found == s.head { // at the front + s.head = s.head.Next.(*decoratedDeserializeHandler) + } else if found == s.tail { // at the end + prev.Next = nil + s.tail = prev + } else { + prev.Next = found.Next // somewhere in the middle } - return removed.(DeserializeMiddleware), nil + return found.With, nil } // List returns a list of the middleware in the step. func (s *DeserializeStep) List() []string { - return s.ids.List() + var ids []string + for h := s.head; h != nil; { + ids = append(ids, h.With.ID()) + if h.Next == nil { + break + } + + // once executed, tail.Next of the list will be set to an + // *deserializeWrapHandler, make sure to check for that + if hnext, ok := h.Next.(*decoratedDeserializeHandler); ok { + h = hnext + } else { + break + } + } + return ids } // Clear removes all middleware in the step. func (s *DeserializeStep) Clear() { - s.ids.Clear() + s.head = nil + s.tail = nil +} + +func (s *DeserializeStep) get(id string) (found, prev *decoratedDeserializeHandler) { + for h := s.head; h != nil; { + if h.With.ID() == id { + found = h + return + } + prev = h + if h.Next == nil { + return + } + + // once executed, tail.Next of the list will be set to an + // *deserializeWrapHandler + h, _ = h.Next.(*decoratedDeserializeHandler) + } + return } type deserializeWrapHandler struct { @@ -187,9 +269,10 @@ var _ DeserializeHandler = (*deserializeWrapHandler)(nil) func (w deserializeWrapHandler) HandleDeserialize(ctx context.Context, in DeserializeInput) ( out DeserializeOutput, metadata Metadata, err error, ) { - resp, metadata, err := w.Next.Handle(ctx, in.Request) + res, metadata, err := w.Next.Handle(ctx, in.Request) return DeserializeOutput{ - RawResponse: resp, + RawResponse: res, + Result: nil, }, metadata, err } @@ -206,12 +289,12 @@ func (h decoratedDeserializeHandler) HandleDeserialize(ctx context.Context, in D return h.With.HandleDeserialize(ctx, in, h.Next) } -// DeserializeHandlerFunc provides a wrapper around a function to be used as a deserialize middleware handler. +// DeserializeHandlerFunc provides a wrapper around a function to be used as deserializeMiddleware. type DeserializeHandlerFunc func(context.Context, DeserializeInput) (DeserializeOutput, Metadata, error) -// HandleDeserialize invokes the wrapped function with the given arguments. -func (d DeserializeHandlerFunc) HandleDeserialize(ctx context.Context, in DeserializeInput) (DeserializeOutput, Metadata, error) { - return d(ctx, in) +// HandleDeserialize calls the wrapped function with the provided arguments. +func (f DeserializeHandlerFunc) HandleDeserialize(ctx context.Context, in DeserializeInput) (DeserializeOutput, Metadata, error) { + return f(ctx, in) } var _ DeserializeHandler = DeserializeHandlerFunc(nil) diff --git a/vendor/github.com/aws/smithy-go/middleware/step_finalize.go b/vendor/github.com/aws/smithy-go/middleware/step_finalize.go index 065e3885de9..1a0ad9fb88b 100644 --- a/vendor/github.com/aws/smithy-go/middleware/step_finalize.go +++ b/vendor/github.com/aws/smithy-go/middleware/step_finalize.go @@ -1,6 +1,10 @@ +// Code generated by smithy-go/middleware/generate.go DO NOT EDIT. package middleware -import "context" +import ( + "context" + "fmt" +) // FinalizeInput provides the input parameters for the FinalizeMiddleware to // consume. FinalizeMiddleware may modify the Request value before forwarding @@ -23,7 +27,7 @@ type FinalizeHandler interface { } // FinalizeMiddleware provides the interface for middleware specific to the -// serialize step. Delegates to the next FinalizeHandler for further +// finalize step. Delegates to the next FinalizeHandler for further // processing. type FinalizeMiddleware interface { // ID returns a unique ID for the middleware in the FinalizeStep. The step does not @@ -38,8 +42,8 @@ type FinalizeMiddleware interface { ) } -// FinalizeMiddlewareFunc returns a FinalizeMiddleware with the unique ID -// provided, and the func to be invoked. +// FinalizeMiddlewareFunc returns a FinalizeMiddleware with the unique ID provided, +// and the func to be invoked. func FinalizeMiddlewareFunc(id string, fn func(context.Context, FinalizeInput, FinalizeHandler) (FinalizeOutput, Metadata, error)) FinalizeMiddleware { return finalizeMiddlewareFunc{ id: id, @@ -72,20 +76,19 @@ var _ FinalizeMiddleware = (finalizeMiddlewareFunc{}) // FinalizeStep provides the ordered grouping of FinalizeMiddleware to be // invoked on a handler. type FinalizeStep struct { - ids *orderedIDs + head *decoratedFinalizeHandler + tail *decoratedFinalizeHandler } -// NewFinalizeStep returns a FinalizeStep ready to have middleware for -// initialization added to it. +// NewFinalizeStep returns an FinalizeStep ready to have middleware for +// finalize added to it. func NewFinalizeStep() *FinalizeStep { - return &FinalizeStep{ - ids: newOrderedIDs(), - } + return &FinalizeStep{} } var _ Middleware = (*FinalizeStep)(nil) -// ID returns the unique id of the step as a middleware. +// ID returns the unique ID of the step as a middleware. func (s *FinalizeStep) ID() string { return "Finalize stack step" } @@ -97,77 +100,161 @@ func (s *FinalizeStep) ID() string { func (s *FinalizeStep) HandleMiddleware(ctx context.Context, in interface{}, next Handler) ( out interface{}, metadata Metadata, err error, ) { - order := s.ids.GetOrder() - - var h FinalizeHandler = finalizeWrapHandler{Next: next} - for i := len(order) - 1; i >= 0; i-- { - h = decoratedFinalizeHandler{ - Next: h, - With: order[i].(FinalizeMiddleware), - } - } - sIn := FinalizeInput{ Request: in, } - res, metadata, err := h.HandleFinalize(ctx, sIn) + wh := &finalizeWrapHandler{next} + if s.head == nil { + res, metadata, err := wh.HandleFinalize(ctx, sIn) + return res.Result, metadata, err + } + + s.tail.Next = wh + res, metadata, err := s.head.HandleFinalize(ctx, sIn) return res.Result, metadata, err } // Get retrieves the middleware identified by id. If the middleware is not present, returns false. func (s *FinalizeStep) Get(id string) (FinalizeMiddleware, bool) { - get, ok := s.ids.Get(id) - if !ok { + found, _ := s.get(id) + if found == nil { return nil, false } - return get.(FinalizeMiddleware), ok + + return found.With, true } // Add injects the middleware to the relative position of the middleware group. -// Returns an error if the middleware already exists. +// +// Add never returns an error. It used to for duplicate phases but this +// behavior has since been removed as part of a performance optimization. The +// return value from Add can be ignored. func (s *FinalizeStep) Add(m FinalizeMiddleware, pos RelativePosition) error { - return s.ids.Add(m, pos) + if s.head == nil { + s.head = &decoratedFinalizeHandler{nil, m} + s.tail = s.head + return nil + } + + if pos == Before { + s.head = &decoratedFinalizeHandler{s.head, m} + } else { + tail := &decoratedFinalizeHandler{nil, m} + s.tail.Next = tail + s.tail = tail + } + + return nil } // Insert injects the middleware relative to an existing middleware ID. // Returns error if the original middleware does not exist, or the middleware // being added already exists. func (s *FinalizeStep) Insert(m FinalizeMiddleware, relativeTo string, pos RelativePosition) error { - return s.ids.Insert(m, relativeTo, pos) + found, prev := s.get(relativeTo) + if found == nil { + return fmt.Errorf("not found: %s", m.ID()) + } + + if pos == Before { + if prev == nil { // at the front + s.head = &decoratedFinalizeHandler{s.head, m} + } else { // somewhere in the middle + prev.Next = &decoratedFinalizeHandler{found, m} + } + } else { + if found.Next == nil { // at the end + tail := &decoratedFinalizeHandler{nil, m} + s.tail.Next = tail + s.tail = tail + } else { // somewhere in the middle + found.Next = &decoratedFinalizeHandler{found.Next, m} + } + } + + return nil } // Swap removes the middleware by id, replacing it with the new middleware. // Returns the middleware removed, or error if the middleware to be removed // doesn't exist. func (s *FinalizeStep) Swap(id string, m FinalizeMiddleware) (FinalizeMiddleware, error) { - removed, err := s.ids.Swap(id, m) - if err != nil { - return nil, err + found, _ := s.get(id) + if found == nil { + return nil, fmt.Errorf("not found: %s", m.ID()) } - return removed.(FinalizeMiddleware), nil + swapped := found.With + found.With = m + return swapped, nil } // Remove removes the middleware by id. Returns error if the middleware // doesn't exist. func (s *FinalizeStep) Remove(id string) (FinalizeMiddleware, error) { - removed, err := s.ids.Remove(id) - if err != nil { - return nil, err + found, prev := s.get(id) + if found == nil { + return nil, fmt.Errorf("not found: %s", id) + } + + if s.head == s.tail { // it's the only one + s.head = nil + s.tail = nil + } else if found == s.head { // at the front + s.head = s.head.Next.(*decoratedFinalizeHandler) + } else if found == s.tail { // at the end + prev.Next = nil + s.tail = prev + } else { + prev.Next = found.Next // somewhere in the middle } - return removed.(FinalizeMiddleware), nil + return found.With, nil } // List returns a list of the middleware in the step. func (s *FinalizeStep) List() []string { - return s.ids.List() + var ids []string + for h := s.head; h != nil; { + ids = append(ids, h.With.ID()) + if h.Next == nil { + break + } + + // once executed, tail.Next of the list will be set to an + // *finalizeWrapHandler, make sure to check for that + if hnext, ok := h.Next.(*decoratedFinalizeHandler); ok { + h = hnext + } else { + break + } + } + return ids } // Clear removes all middleware in the step. func (s *FinalizeStep) Clear() { - s.ids.Clear() + s.head = nil + s.tail = nil +} + +func (s *FinalizeStep) get(id string) (found, prev *decoratedFinalizeHandler) { + for h := s.head; h != nil; { + if h.With.ID() == id { + found = h + return + } + prev = h + if h.Next == nil { + return + } + + // once executed, tail.Next of the list will be set to an + // *finalizeWrapHandler + h, _ = h.Next.(*decoratedFinalizeHandler) + } + return } type finalizeWrapHandler struct { @@ -200,10 +287,10 @@ func (h decoratedFinalizeHandler) HandleFinalize(ctx context.Context, in Finaliz return h.With.HandleFinalize(ctx, in, h.Next) } -// FinalizeHandlerFunc provides a wrapper around a function to be used as a finalize middleware handler. +// FinalizeHandlerFunc provides a wrapper around a function to be used as finalizeMiddleware. type FinalizeHandlerFunc func(context.Context, FinalizeInput) (FinalizeOutput, Metadata, error) -// HandleFinalize invokes the wrapped function with the given arguments. +// HandleFinalize calls the wrapped function with the provided arguments. func (f FinalizeHandlerFunc) HandleFinalize(ctx context.Context, in FinalizeInput) (FinalizeOutput, Metadata, error) { return f(ctx, in) } diff --git a/vendor/github.com/aws/smithy-go/middleware/step_initialize.go b/vendor/github.com/aws/smithy-go/middleware/step_initialize.go index fe359144d24..446f3b7bb9c 100644 --- a/vendor/github.com/aws/smithy-go/middleware/step_initialize.go +++ b/vendor/github.com/aws/smithy-go/middleware/step_initialize.go @@ -1,10 +1,15 @@ +// Code generated by smithy-go/middleware/generate.go DO NOT EDIT. package middleware -import "context" +import ( + "context" + "fmt" +) // InitializeInput wraps the input parameters for the InitializeMiddlewares to // consume. InitializeMiddleware may modify the parameter value before // forwarding it along to the next InitializeHandler. + type InitializeInput struct { Parameters interface{} } @@ -72,15 +77,14 @@ var _ InitializeMiddleware = (initializeMiddlewareFunc{}) // InitializeStep provides the ordered grouping of InitializeMiddleware to be // invoked on a handler. type InitializeStep struct { - ids *orderedIDs + head *decoratedInitializeHandler + tail *decoratedInitializeHandler } // NewInitializeStep returns an InitializeStep ready to have middleware for -// initialization added to it. +// initialize added to it. func NewInitializeStep() *InitializeStep { - return &InitializeStep{ - ids: newOrderedIDs(), - } + return &InitializeStep{} } var _ Middleware = (*InitializeStep)(nil) @@ -97,77 +101,161 @@ func (s *InitializeStep) ID() string { func (s *InitializeStep) HandleMiddleware(ctx context.Context, in interface{}, next Handler) ( out interface{}, metadata Metadata, err error, ) { - order := s.ids.GetOrder() - - var h InitializeHandler = initializeWrapHandler{Next: next} - for i := len(order) - 1; i >= 0; i-- { - h = decoratedInitializeHandler{ - Next: h, - With: order[i].(InitializeMiddleware), - } - } - sIn := InitializeInput{ Parameters: in, } - res, metadata, err := h.HandleInitialize(ctx, sIn) + wh := &initializeWrapHandler{next} + if s.head == nil { + res, metadata, err := wh.HandleInitialize(ctx, sIn) + return res.Result, metadata, err + } + + s.tail.Next = wh + res, metadata, err := s.head.HandleInitialize(ctx, sIn) return res.Result, metadata, err } // Get retrieves the middleware identified by id. If the middleware is not present, returns false. func (s *InitializeStep) Get(id string) (InitializeMiddleware, bool) { - get, ok := s.ids.Get(id) - if !ok { + found, _ := s.get(id) + if found == nil { return nil, false } - return get.(InitializeMiddleware), ok + + return found.With, true } // Add injects the middleware to the relative position of the middleware group. -// Returns an error if the middleware already exists. +// +// Add never returns an error. It used to for duplicate phases but this +// behavior has since been removed as part of a performance optimization. The +// return value from Add can be ignored. func (s *InitializeStep) Add(m InitializeMiddleware, pos RelativePosition) error { - return s.ids.Add(m, pos) + if s.head == nil { + s.head = &decoratedInitializeHandler{nil, m} + s.tail = s.head + return nil + } + + if pos == Before { + s.head = &decoratedInitializeHandler{s.head, m} + } else { + tail := &decoratedInitializeHandler{nil, m} + s.tail.Next = tail + s.tail = tail + } + + return nil } // Insert injects the middleware relative to an existing middleware ID. // Returns error if the original middleware does not exist, or the middleware // being added already exists. func (s *InitializeStep) Insert(m InitializeMiddleware, relativeTo string, pos RelativePosition) error { - return s.ids.Insert(m, relativeTo, pos) + found, prev := s.get(relativeTo) + if found == nil { + return fmt.Errorf("not found: %s", m.ID()) + } + + if pos == Before { + if prev == nil { // at the front + s.head = &decoratedInitializeHandler{s.head, m} + } else { // somewhere in the middle + prev.Next = &decoratedInitializeHandler{found, m} + } + } else { + if found.Next == nil { // at the end + tail := &decoratedInitializeHandler{nil, m} + s.tail.Next = tail + s.tail = tail + } else { // somewhere in the middle + found.Next = &decoratedInitializeHandler{found.Next, m} + } + } + + return nil } // Swap removes the middleware by id, replacing it with the new middleware. // Returns the middleware removed, or error if the middleware to be removed // doesn't exist. func (s *InitializeStep) Swap(id string, m InitializeMiddleware) (InitializeMiddleware, error) { - removed, err := s.ids.Swap(id, m) - if err != nil { - return nil, err + found, _ := s.get(id) + if found == nil { + return nil, fmt.Errorf("not found: %s", m.ID()) } - return removed.(InitializeMiddleware), nil + swapped := found.With + found.With = m + return swapped, nil } // Remove removes the middleware by id. Returns error if the middleware // doesn't exist. func (s *InitializeStep) Remove(id string) (InitializeMiddleware, error) { - removed, err := s.ids.Remove(id) - if err != nil { - return nil, err + found, prev := s.get(id) + if found == nil { + return nil, fmt.Errorf("not found: %s", id) } - return removed.(InitializeMiddleware), nil + if s.head == s.tail { // it's the only one + s.head = nil + s.tail = nil + } else if found == s.head { // at the front + s.head = s.head.Next.(*decoratedInitializeHandler) + } else if found == s.tail { // at the end + prev.Next = nil + s.tail = prev + } else { + prev.Next = found.Next // somewhere in the middle + } + + return found.With, nil } // List returns a list of the middleware in the step. func (s *InitializeStep) List() []string { - return s.ids.List() + var ids []string + for h := s.head; h != nil; { + ids = append(ids, h.With.ID()) + if h.Next == nil { + break + } + + // once executed, tail.Next of the list will be set to an + // *initializeWrapHandler, make sure to check for that + if hnext, ok := h.Next.(*decoratedInitializeHandler); ok { + h = hnext + } else { + break + } + } + return ids } // Clear removes all middleware in the step. func (s *InitializeStep) Clear() { - s.ids.Clear() + s.head = nil + s.tail = nil +} + +func (s *InitializeStep) get(id string) (found, prev *decoratedInitializeHandler) { + for h := s.head; h != nil; { + if h.With.ID() == id { + found = h + return + } + prev = h + if h.Next == nil { + return + } + + // once executed, tail.Next of the list will be set to an + // *initializeWrapHandler + h, _ = h.Next.(*decoratedInitializeHandler) + } + return } type initializeWrapHandler struct { @@ -200,12 +288,12 @@ func (h decoratedInitializeHandler) HandleInitialize(ctx context.Context, in Ini return h.With.HandleInitialize(ctx, in, h.Next) } -// InitializeHandlerFunc provides a wrapper around a function to be used as an initialize middleware handler. +// InitializeHandlerFunc provides a wrapper around a function to be used as initializeMiddleware. type InitializeHandlerFunc func(context.Context, InitializeInput) (InitializeOutput, Metadata, error) // HandleInitialize calls the wrapped function with the provided arguments. -func (i InitializeHandlerFunc) HandleInitialize(ctx context.Context, in InitializeInput) (InitializeOutput, Metadata, error) { - return i(ctx, in) +func (f InitializeHandlerFunc) HandleInitialize(ctx context.Context, in InitializeInput) (InitializeOutput, Metadata, error) { + return f(ctx, in) } var _ InitializeHandler = InitializeHandlerFunc(nil) diff --git a/vendor/github.com/aws/smithy-go/middleware/step_serialize.go b/vendor/github.com/aws/smithy-go/middleware/step_serialize.go index 114bafcedea..942ebb4f3e7 100644 --- a/vendor/github.com/aws/smithy-go/middleware/step_serialize.go +++ b/vendor/github.com/aws/smithy-go/middleware/step_serialize.go @@ -1,6 +1,10 @@ +// Code generated by smithy-go/middleware/generate.go DO NOT EDIT. package middleware -import "context" +import ( + "context" + "fmt" +) // SerializeInput provides the input parameters for the SerializeMiddleware to // consume. SerializeMiddleware may modify the Request value before forwarding @@ -41,8 +45,8 @@ type SerializeMiddleware interface { ) } -// SerializeMiddlewareFunc returns a SerializeMiddleware with the unique ID -// provided, and the func to be invoked. +// SerializeMiddlewareFunc returns a SerializeMiddleware with the unique ID provided, +// and the func to be invoked. func SerializeMiddlewareFunc(id string, fn func(context.Context, SerializeInput, SerializeHandler) (SerializeOutput, Metadata, error)) SerializeMiddleware { return serializeMiddlewareFunc{ id: id, @@ -75,17 +79,15 @@ var _ SerializeMiddleware = (serializeMiddlewareFunc{}) // SerializeStep provides the ordered grouping of SerializeMiddleware to be // invoked on a handler. type SerializeStep struct { + head *decoratedSerializeHandler + tail *decoratedSerializeHandler newRequest func() interface{} - ids *orderedIDs } -// NewSerializeStep returns a SerializeStep ready to have middleware for -// initialization added to it. The newRequest func parameter is used to -// initialize the transport specific request for the stack SerializeStep to -// serialize the input parameters into. +// NewSerializeStep returns an SerializeStep ready to have middleware for +// serialize added to it. func NewSerializeStep(newRequest func() interface{}) *SerializeStep { return &SerializeStep{ - ids: newOrderedIDs(), newRequest: newRequest, } } @@ -104,78 +106,162 @@ func (s *SerializeStep) ID() string { func (s *SerializeStep) HandleMiddleware(ctx context.Context, in interface{}, next Handler) ( out interface{}, metadata Metadata, err error, ) { - order := s.ids.GetOrder() - - var h SerializeHandler = serializeWrapHandler{Next: next} - for i := len(order) - 1; i >= 0; i-- { - h = decoratedSerializeHandler{ - Next: h, - With: order[i].(SerializeMiddleware), - } - } - sIn := SerializeInput{ Parameters: in, Request: s.newRequest(), } - res, metadata, err := h.HandleSerialize(ctx, sIn) + wh := &serializeWrapHandler{next} + if s.head == nil { + res, metadata, err := wh.HandleSerialize(ctx, sIn) + return res.Result, metadata, err + } + + s.tail.Next = wh + res, metadata, err := s.head.HandleSerialize(ctx, sIn) return res.Result, metadata, err } // Get retrieves the middleware identified by id. If the middleware is not present, returns false. func (s *SerializeStep) Get(id string) (SerializeMiddleware, bool) { - get, ok := s.ids.Get(id) - if !ok { + found, _ := s.get(id) + if found == nil { return nil, false } - return get.(SerializeMiddleware), ok + + return found.With, true } // Add injects the middleware to the relative position of the middleware group. -// Returns an error if the middleware already exists. +// +// Add never returns an error. It used to for duplicate phases but this +// behavior has since been removed as part of a performance optimization. The +// return value from Add can be ignored. func (s *SerializeStep) Add(m SerializeMiddleware, pos RelativePosition) error { - return s.ids.Add(m, pos) + if s.head == nil { + s.head = &decoratedSerializeHandler{nil, m} + s.tail = s.head + return nil + } + + if pos == Before { + s.head = &decoratedSerializeHandler{s.head, m} + } else { + tail := &decoratedSerializeHandler{nil, m} + s.tail.Next = tail + s.tail = tail + } + + return nil } // Insert injects the middleware relative to an existing middleware ID. // Returns error if the original middleware does not exist, or the middleware // being added already exists. func (s *SerializeStep) Insert(m SerializeMiddleware, relativeTo string, pos RelativePosition) error { - return s.ids.Insert(m, relativeTo, pos) + found, prev := s.get(relativeTo) + if found == nil { + return fmt.Errorf("not found: %s", m.ID()) + } + + if pos == Before { + if prev == nil { // at the front + s.head = &decoratedSerializeHandler{s.head, m} + } else { // somewhere in the middle + prev.Next = &decoratedSerializeHandler{found, m} + } + } else { + if found.Next == nil { // at the end + tail := &decoratedSerializeHandler{nil, m} + s.tail.Next = tail + s.tail = tail + } else { // somewhere in the middle + found.Next = &decoratedSerializeHandler{found.Next, m} + } + } + + return nil } // Swap removes the middleware by id, replacing it with the new middleware. // Returns the middleware removed, or error if the middleware to be removed // doesn't exist. func (s *SerializeStep) Swap(id string, m SerializeMiddleware) (SerializeMiddleware, error) { - removed, err := s.ids.Swap(id, m) - if err != nil { - return nil, err + found, _ := s.get(id) + if found == nil { + return nil, fmt.Errorf("not found: %s", m.ID()) } - return removed.(SerializeMiddleware), nil + swapped := found.With + found.With = m + return swapped, nil } // Remove removes the middleware by id. Returns error if the middleware // doesn't exist. func (s *SerializeStep) Remove(id string) (SerializeMiddleware, error) { - removed, err := s.ids.Remove(id) - if err != nil { - return nil, err + found, prev := s.get(id) + if found == nil { + return nil, fmt.Errorf("not found: %s", id) + } + + if s.head == s.tail { // it's the only one + s.head = nil + s.tail = nil + } else if found == s.head { // at the front + s.head = s.head.Next.(*decoratedSerializeHandler) + } else if found == s.tail { // at the end + prev.Next = nil + s.tail = prev + } else { + prev.Next = found.Next // somewhere in the middle } - return removed.(SerializeMiddleware), nil + return found.With, nil } // List returns a list of the middleware in the step. func (s *SerializeStep) List() []string { - return s.ids.List() + var ids []string + for h := s.head; h != nil; { + ids = append(ids, h.With.ID()) + if h.Next == nil { + break + } + + // once executed, tail.Next of the list will be set to an + // *serializeWrapHandler, make sure to check for that + if hnext, ok := h.Next.(*decoratedSerializeHandler); ok { + h = hnext + } else { + break + } + } + return ids } // Clear removes all middleware in the step. func (s *SerializeStep) Clear() { - s.ids.Clear() + s.head = nil + s.tail = nil +} + +func (s *SerializeStep) get(id string) (found, prev *decoratedSerializeHandler) { + for h := s.head; h != nil; { + if h.With.ID() == id { + found = h + return + } + prev = h + if h.Next == nil { + return + } + + // once executed, tail.Next of the list will be set to an + // *serializeWrapHandler + h, _ = h.Next.(*decoratedSerializeHandler) + } + return } type serializeWrapHandler struct { @@ -184,7 +270,7 @@ type serializeWrapHandler struct { var _ SerializeHandler = (*serializeWrapHandler)(nil) -// Implements SerializeHandler, converts types and delegates to underlying +// HandleSerialize implements SerializeHandler, converts types and delegates to underlying // generic handler. func (w serializeWrapHandler) HandleSerialize(ctx context.Context, in SerializeInput) ( out SerializeOutput, metadata Metadata, err error, @@ -208,12 +294,12 @@ func (h decoratedSerializeHandler) HandleSerialize(ctx context.Context, in Seria return h.With.HandleSerialize(ctx, in, h.Next) } -// SerializeHandlerFunc provides a wrapper around a function to be used as a serialize middleware handler. +// SerializeHandlerFunc provides a wrapper around a function to be used as serializeMiddleware. type SerializeHandlerFunc func(context.Context, SerializeInput) (SerializeOutput, Metadata, error) // HandleSerialize calls the wrapped function with the provided arguments. -func (s SerializeHandlerFunc) HandleSerialize(ctx context.Context, in SerializeInput) (SerializeOutput, Metadata, error) { - return s(ctx, in) +func (f SerializeHandlerFunc) HandleSerialize(ctx context.Context, in SerializeInput) (SerializeOutput, Metadata, error) { + return f(ctx, in) } var _ SerializeHandler = SerializeHandlerFunc(nil) diff --git a/vendor/github.com/aws/smithy-go/transport/http/metrics.go b/vendor/github.com/aws/smithy-go/transport/http/metrics.go index d1beaa595d9..b4cd4a47e36 100644 --- a/vendor/github.com/aws/smithy-go/transport/http/metrics.go +++ b/vendor/github.com/aws/smithy-go/transport/http/metrics.go @@ -17,6 +17,12 @@ var now = time.Now func withMetrics(parent context.Context, client ClientDo, meter metrics.Meter) ( context.Context, ClientDo, error, ) { + // WithClientTrace is an expensive operation - avoid calling it if we're + // not actually using a metrics sink. + if _, ok := meter.(metrics.NopMeter); ok { + return parent, client, nil + } + hm, err := newHTTPMetrics(meter) if err != nil { return nil, nil, err diff --git a/vendor/github.com/go-openapi/analysis/.golangci.yml b/vendor/github.com/go-openapi/analysis/.golangci.yml index 5609b4fea9c..06190ac055f 100644 --- a/vendor/github.com/go-openapi/analysis/.golangci.yml +++ b/vendor/github.com/go-openapi/analysis/.golangci.yml @@ -16,7 +16,7 @@ linters: - godox - gosmopolitan - inamedparam - #- intrange # disabled while < go1.22 + - intrange - ireturn - lll - musttag diff --git a/vendor/github.com/go-openapi/analysis/analyzer.go b/vendor/github.com/go-openapi/analysis/analyzer.go index 3e57de88701..4870ad07beb 100644 --- a/vendor/github.com/go-openapi/analysis/analyzer.go +++ b/vendor/github.com/go-openapi/analysis/analyzer.go @@ -1,21 +1,11 @@ -// Copyright 2015 go-swagger maintainers -// -// 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. +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 package analysis import ( "fmt" + "maps" slashpath "path" "strconv" "strings" @@ -111,33 +101,33 @@ func (p *patternAnalysis) addSchemaPattern(key, pattern string) { } type enumAnalysis struct { - parameters map[string][]interface{} - headers map[string][]interface{} - items map[string][]interface{} - schemas map[string][]interface{} - allEnums map[string][]interface{} + parameters map[string][]any + headers map[string][]any + items map[string][]any + schemas map[string][]any + allEnums map[string][]any } -func (p *enumAnalysis) addEnum(key string, enum []interface{}) { +func (p *enumAnalysis) addEnum(key string, enum []any) { p.allEnums["#"+key] = enum } -func (p *enumAnalysis) addParameterEnum(key string, enum []interface{}) { +func (p *enumAnalysis) addParameterEnum(key string, enum []any) { p.parameters["#"+key] = enum p.addEnum(key, enum) } -func (p *enumAnalysis) addHeaderEnum(key string, enum []interface{}) { +func (p *enumAnalysis) addHeaderEnum(key string, enum []any) { p.headers["#"+key] = enum p.addEnum(key, enum) } -func (p *enumAnalysis) addItemsEnum(key string, enum []interface{}) { +func (p *enumAnalysis) addItemsEnum(key string, enum []any) { p.items["#"+key] = enum p.addEnum(key, enum) } -func (p *enumAnalysis) addSchemaEnum(key string, enum []interface{}) { +func (p *enumAnalysis) addSchemaEnum(key string, enum []any) { p.schemas["#"+key] = enum p.addEnum(key, enum) } @@ -633,31 +623,31 @@ func (s *Spec) AllPatterns() map[string]string { // ParameterEnums returns all the enums found in parameters // the map is cloned to avoid accidental changes -func (s *Spec) ParameterEnums() map[string][]interface{} { +func (s *Spec) ParameterEnums() map[string][]any { return cloneEnumMap(s.enums.parameters) } // HeaderEnums returns all the enums found in response headers // the map is cloned to avoid accidental changes -func (s *Spec) HeaderEnums() map[string][]interface{} { +func (s *Spec) HeaderEnums() map[string][]any { return cloneEnumMap(s.enums.headers) } // ItemsEnums returns all the enums found in simple array items // the map is cloned to avoid accidental changes -func (s *Spec) ItemsEnums() map[string][]interface{} { +func (s *Spec) ItemsEnums() map[string][]any { return cloneEnumMap(s.enums.items) } // SchemaEnums returns all the enums found in schemas // the map is cloned to avoid accidental changes -func (s *Spec) SchemaEnums() map[string][]interface{} { +func (s *Spec) SchemaEnums() map[string][]any { return cloneEnumMap(s.enums.schemas) } // AllEnums returns all the enums found in the spec // the map is cloned to avoid accidental changes -func (s *Spec) AllEnums() map[string][]interface{} { +func (s *Spec) AllEnums() map[string][]any { return cloneEnumMap(s.enums.allEnums) } @@ -733,11 +723,11 @@ func (s *Spec) reset() { s.patterns.items = make(map[string]string, allocLargeMap) s.patterns.schemas = make(map[string]string, allocLargeMap) s.patterns.allPatterns = make(map[string]string, allocLargeMap) - s.enums.parameters = make(map[string][]interface{}, allocLargeMap) - s.enums.headers = make(map[string][]interface{}, allocLargeMap) - s.enums.items = make(map[string][]interface{}, allocLargeMap) - s.enums.schemas = make(map[string][]interface{}, allocLargeMap) - s.enums.allEnums = make(map[string][]interface{}, allocLargeMap) + s.enums.parameters = make(map[string][]any, allocLargeMap) + s.enums.headers = make(map[string][]any, allocLargeMap) + s.enums.items = make(map[string][]any, allocLargeMap) + s.enums.schemas = make(map[string][]any, allocLargeMap) + s.enums.allEnums = make(map[string][]any, allocLargeMap) } func (s *Spec) reload() { @@ -1051,18 +1041,14 @@ func (s *Spec) analyzeSchema(name string, schema *spec.Schema, prefix string) { func cloneStringMap(source map[string]string) map[string]string { res := make(map[string]string, len(source)) - for k, v := range source { - res[k] = v - } + maps.Copy(res, source) return res } -func cloneEnumMap(source map[string][]interface{}) map[string][]interface{} { - res := make(map[string][]interface{}, len(source)) - for k, v := range source { - res[k] = v - } +func cloneEnumMap(source map[string][]any) map[string][]any { + res := make(map[string][]any, len(source)) + maps.Copy(res, source) return res } diff --git a/vendor/github.com/go-openapi/analysis/debug.go b/vendor/github.com/go-openapi/analysis/debug.go index 33c15704ecb..d490eab6063 100644 --- a/vendor/github.com/go-openapi/analysis/debug.go +++ b/vendor/github.com/go-openapi/analysis/debug.go @@ -1,16 +1,5 @@ -// Copyright 2015 go-swagger maintainers -// -// 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. +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 package analysis diff --git a/vendor/github.com/go-openapi/analysis/doc.go b/vendor/github.com/go-openapi/analysis/doc.go index e8d9f9b1312..9d41371a9f0 100644 --- a/vendor/github.com/go-openapi/analysis/doc.go +++ b/vendor/github.com/go-openapi/analysis/doc.go @@ -1,16 +1,5 @@ -// Copyright 2015 go-swagger maintainers -// -// 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. +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 /* Package analysis provides methods to work with a Swagger specification document from diff --git a/vendor/github.com/go-openapi/analysis/errors.go b/vendor/github.com/go-openapi/analysis/errors.go index 98133e7af06..540e159a23c 100644 --- a/vendor/github.com/go-openapi/analysis/errors.go +++ b/vendor/github.com/go-openapi/analysis/errors.go @@ -1,3 +1,6 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + package analysis import ( diff --git a/vendor/github.com/go-openapi/analysis/fixer.go b/vendor/github.com/go-openapi/analysis/fixer.go index 8bac3a4d19b..74becbbe496 100644 --- a/vendor/github.com/go-openapi/analysis/fixer.go +++ b/vendor/github.com/go-openapi/analysis/fixer.go @@ -1,16 +1,5 @@ -// Copyright 2015 go-swagger maintainers -// -// 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. +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 package analysis diff --git a/vendor/github.com/go-openapi/analysis/flatten.go b/vendor/github.com/go-openapi/analysis/flatten.go index 7042bb5adaf..1c7a49c034f 100644 --- a/vendor/github.com/go-openapi/analysis/flatten.go +++ b/vendor/github.com/go-openapi/analysis/flatten.go @@ -1,22 +1,12 @@ -// Copyright 2015 go-swagger maintainers -// -// 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. +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 package analysis import ( "log" "path" + "slices" "sort" "strings" @@ -541,14 +531,7 @@ func updateRefParents(allRefs map[string]spec.Ref, r *newRef) { continue } - found := false - for _, p := range r.parents { - if p == k { - found = true - - break - } - } + found := slices.Contains(r.parents, k) if !found { r.parents = append(r.parents, k) } diff --git a/vendor/github.com/go-openapi/analysis/flatten_name.go b/vendor/github.com/go-openapi/analysis/flatten_name.go index 44ffe4226f2..475b33c4136 100644 --- a/vendor/github.com/go-openapi/analysis/flatten_name.go +++ b/vendor/github.com/go-openapi/analysis/flatten_name.go @@ -1,3 +1,6 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + package analysis import ( diff --git a/vendor/github.com/go-openapi/analysis/flatten_options.go b/vendor/github.com/go-openapi/analysis/flatten_options.go index c943fe1e84a..d8fc25cf586 100644 --- a/vendor/github.com/go-openapi/analysis/flatten_options.go +++ b/vendor/github.com/go-openapi/analysis/flatten_options.go @@ -1,3 +1,6 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + package analysis import ( diff --git a/vendor/github.com/go-openapi/analysis/internal/debug/debug.go b/vendor/github.com/go-openapi/analysis/internal/debug/debug.go index 39f55a97bfd..03e0d32e9ea 100644 --- a/vendor/github.com/go-openapi/analysis/internal/debug/debug.go +++ b/vendor/github.com/go-openapi/analysis/internal/debug/debug.go @@ -1,16 +1,5 @@ -// Copyright 2015 go-swagger maintainers -// -// 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. +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 package debug @@ -27,15 +16,15 @@ var ( ) // GetLogger provides a prefix debug logger -func GetLogger(prefix string, debug bool) func(string, ...interface{}) { +func GetLogger(prefix string, debug bool) func(string, ...any) { if debug { logger := log.New(output, prefix+":", log.LstdFlags) - return func(msg string, args ...interface{}) { + return func(msg string, args ...any) { _, file1, pos1, _ := runtime.Caller(1) logger.Printf("%s:%d: %s", filepath.Base(file1), pos1, fmt.Sprintf(msg, args...)) } } - return func(_ string, _ ...interface{}) {} + return func(_ string, _ ...any) {} } diff --git a/vendor/github.com/go-openapi/analysis/internal/flatten/normalize/normalize.go b/vendor/github.com/go-openapi/analysis/internal/flatten/normalize/normalize.go index 8c9df0580da..320a50bff85 100644 --- a/vendor/github.com/go-openapi/analysis/internal/flatten/normalize/normalize.go +++ b/vendor/github.com/go-openapi/analysis/internal/flatten/normalize/normalize.go @@ -1,3 +1,6 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + package normalize import ( diff --git a/vendor/github.com/go-openapi/analysis/internal/flatten/operations/operations.go b/vendor/github.com/go-openapi/analysis/internal/flatten/operations/operations.go index a1911b07674..940c46a9256 100644 --- a/vendor/github.com/go-openapi/analysis/internal/flatten/operations/operations.go +++ b/vendor/github.com/go-openapi/analysis/internal/flatten/operations/operations.go @@ -1,3 +1,6 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + package operations import ( diff --git a/vendor/github.com/go-openapi/analysis/internal/flatten/replace/errors.go b/vendor/github.com/go-openapi/analysis/internal/flatten/replace/errors.go index 60c3aa044af..d7c28b88571 100644 --- a/vendor/github.com/go-openapi/analysis/internal/flatten/replace/errors.go +++ b/vendor/github.com/go-openapi/analysis/internal/flatten/replace/errors.go @@ -1,3 +1,6 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + package replace import ( diff --git a/vendor/github.com/go-openapi/analysis/internal/flatten/replace/replace.go b/vendor/github.com/go-openapi/analysis/internal/flatten/replace/replace.go index f30a22ae2f2..61c13f7ebaa 100644 --- a/vendor/github.com/go-openapi/analysis/internal/flatten/replace/replace.go +++ b/vendor/github.com/go-openapi/analysis/internal/flatten/replace/replace.go @@ -1,3 +1,6 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + package replace import ( @@ -45,7 +48,7 @@ func RewriteSchemaToRef(sp *spec.Swagger, key string, ref spec.Ref) error { if refable.Schema != nil { refable.Schema = &spec.Schema{SchemaProps: spec.SchemaProps{Ref: ref}} } - case map[string]interface{}: // this happens e.g. if a schema points to an extension unmarshaled as map[string]interface{} + case map[string]any: // this happens e.g. if a schema points to an extension unmarshaled as map[string]interface{} return rewriteParentRef(sp, key, ref) default: return ErrNoSchemaWithRef(key, value) @@ -127,7 +130,7 @@ func rewriteParentRef(sp *spec.Swagger, key string, ref spec.Ref) error { case spec.SchemaProperties: container[entry] = spec.Schema{SchemaProps: spec.SchemaProps{Ref: ref}} - case *interface{}: + case *any: *container = spec.Schema{SchemaProps: spec.SchemaProps{Ref: ref}} // NOTE: can't have case *spec.SchemaOrBool = parent in this case is *Schema @@ -140,7 +143,7 @@ func rewriteParentRef(sp *spec.Swagger, key string, ref spec.Ref) error { } // getPointerFromKey retrieves the content of the JSON pointer "key" -func getPointerFromKey(sp interface{}, key string) (string, interface{}, error) { +func getPointerFromKey(sp any, key string) (string, any, error) { switch sp.(type) { case *spec.Schema: case *spec.Swagger: @@ -168,7 +171,7 @@ func getPointerFromKey(sp interface{}, key string) (string, interface{}, error) } // getParentFromKey retrieves the container of the JSON pointer "key" -func getParentFromKey(sp interface{}, key string) (string, string, interface{}, error) { +func getParentFromKey(sp any, key string) (string, string, any, error) { switch sp.(type) { case *spec.Schema: case *spec.Swagger: @@ -194,7 +197,7 @@ func getParentFromKey(sp interface{}, key string) (string, string, interface{}, } // UpdateRef replaces a ref by another one -func UpdateRef(sp interface{}, key string, ref spec.Ref) error { +func UpdateRef(sp any, key string, ref spec.Ref) error { switch sp.(type) { case *spec.Schema: case *spec.Swagger: diff --git a/vendor/github.com/go-openapi/analysis/internal/flatten/schutils/flatten_schema.go b/vendor/github.com/go-openapi/analysis/internal/flatten/schutils/flatten_schema.go index fa7f6bf34e3..7e9fb9f0a5f 100644 --- a/vendor/github.com/go-openapi/analysis/internal/flatten/schutils/flatten_schema.go +++ b/vendor/github.com/go-openapi/analysis/internal/flatten/schutils/flatten_schema.go @@ -1,3 +1,6 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + // Package schutils provides tools to save or clone a schema // when flattening a spec. package schutils diff --git a/vendor/github.com/go-openapi/analysis/internal/flatten/sortref/keys.go b/vendor/github.com/go-openapi/analysis/internal/flatten/sortref/keys.go index cbe16f65247..a5db0249ecc 100644 --- a/vendor/github.com/go-openapi/analysis/internal/flatten/sortref/keys.go +++ b/vendor/github.com/go-openapi/analysis/internal/flatten/sortref/keys.go @@ -1,3 +1,6 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + package sortref import ( @@ -60,7 +63,7 @@ func (k Keys) Less(i, j int) bool { // KeyParts construct a SplitKey with all its /-separated segments decomposed. It is sortable. func KeyParts(key string) SplitKey { var res []string - for _, part := range strings.Split(key[1:], "/") { + for part := range strings.SplitSeq(key[1:], "/") { if part != "" { res = append(res, jsonpointer.Unescape(part)) } diff --git a/vendor/github.com/go-openapi/analysis/internal/flatten/sortref/sort_ref.go b/vendor/github.com/go-openapi/analysis/internal/flatten/sortref/sort_ref.go index 73243df87f0..ceac7137728 100644 --- a/vendor/github.com/go-openapi/analysis/internal/flatten/sortref/sort_ref.go +++ b/vendor/github.com/go-openapi/analysis/internal/flatten/sortref/sort_ref.go @@ -1,3 +1,6 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + package sortref import ( @@ -30,7 +33,7 @@ func (i *mapIterator) Key() string { return i.mapIter.Key().String() } -func mustMapIterator(anyMap interface{}) *mapIterator { +func mustMapIterator(anyMap any) *mapIterator { val := reflect.ValueOf(anyMap) return &mapIterator{mapIter: val.MapRange(), len: val.Len()} @@ -40,7 +43,7 @@ func mustMapIterator(anyMap interface{}) *mapIterator { // (shared params, op param, statuscode response, default response, definitions) // sort groups internally by number of parts in the key and lexical names // flatten groups into a single list of keys -func DepthFirst(in interface{}) []string { +func DepthFirst(in any) []string { iterator := mustMapIterator(in) sorted := make([]string, 0, iterator.Len()) grouped := make(map[string]Keys, iterator.Len()) diff --git a/vendor/github.com/go-openapi/analysis/mixin.go b/vendor/github.com/go-openapi/analysis/mixin.go index b0b41dba644..cc5c392334b 100644 --- a/vendor/github.com/go-openapi/analysis/mixin.go +++ b/vendor/github.com/go-openapi/analysis/mixin.go @@ -1,22 +1,12 @@ -// Copyright 2015 go-swagger maintainers -// -// 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. +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 package analysis import ( "fmt" "reflect" + "slices" "github.com/go-openapi/spec" ) @@ -248,14 +238,7 @@ func mergeResponses(primary *spec.Swagger, m *spec.Swagger) (skipped []string) { func mergeConsumes(primary *spec.Swagger, m *spec.Swagger) []string { for _, v := range m.Consumes { - found := false - for _, vv := range primary.Consumes { - if v == vv { - found = true - - break - } - } + found := slices.Contains(primary.Consumes, v) if found { // no warning here: we just skip it @@ -269,14 +252,7 @@ func mergeConsumes(primary *spec.Swagger, m *spec.Swagger) []string { func mergeProduces(primary *spec.Swagger, m *spec.Swagger) []string { for _, v := range m.Produces { - found := false - for _, vv := range primary.Produces { - if v == vv { - found = true - - break - } - } + found := slices.Contains(primary.Produces, v) if found { // no warning here: we just skip it @@ -317,14 +293,7 @@ func mergeTags(primary *spec.Swagger, m *spec.Swagger) (skipped []string) { func mergeSchemes(primary *spec.Swagger, m *spec.Swagger) []string { for _, v := range m.Schemes { - found := false - for _, vv := range primary.Schemes { - if v == vv { - found = true - - break - } - } + found := slices.Contains(primary.Schemes, v) if found { // no warning here: we just skip it diff --git a/vendor/github.com/go-openapi/analysis/schema.go b/vendor/github.com/go-openapi/analysis/schema.go index baeb784e730..039dac15661 100644 --- a/vendor/github.com/go-openapi/analysis/schema.go +++ b/vendor/github.com/go-openapi/analysis/schema.go @@ -1,3 +1,6 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + package analysis import ( @@ -8,7 +11,7 @@ import ( // SchemaOpts configures the schema analyzer type SchemaOpts struct { Schema *spec.Schema - Root interface{} + Root any BasePath string _ struct{} } @@ -52,7 +55,7 @@ func Schema(opts SchemaOpts) (*AnalyzedSchema, error) { // AnalyzedSchema indicates what the schema represents type AnalyzedSchema struct { schema *spec.Schema - root interface{} + root any basePath string hasProps bool diff --git a/vendor/github.com/go-openapi/errors/README.md b/vendor/github.com/go-openapi/errors/README.md index 6d57ea55c7c..d7e3a18bcf5 100644 --- a/vendor/github.com/go-openapi/errors/README.md +++ b/vendor/github.com/go-openapi/errors/README.md @@ -6,3 +6,7 @@ [![Go Report Card](https://goreportcard.com/badge/github.com/go-openapi/errors)](https://goreportcard.com/report/github.com/go-openapi/errors) Shared errors and error interface used throughout the various libraries found in the go-openapi toolkit. + +## Licensing + +This library ships under the [SPDX-License-Identifier: Apache-2.0](./LICENSE). diff --git a/vendor/github.com/go-openapi/errors/api.go b/vendor/github.com/go-openapi/errors/api.go index 52d45777280..d39233bafe4 100644 --- a/vendor/github.com/go-openapi/errors/api.go +++ b/vendor/github.com/go-openapi/errors/api.go @@ -1,16 +1,5 @@ -// Copyright 2015 go-swagger maintainers -// -// 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. +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 package errors @@ -46,14 +35,14 @@ func (a *apiError) Code() int32 { // MarshalJSON implements the JSON encoding interface func (a apiError) MarshalJSON() ([]byte, error) { - return json.Marshal(map[string]interface{}{ + return json.Marshal(map[string]any{ "code": a.code, "message": a.message, }) } // New creates a new API error with a code and a message -func New(code int32, message string, args ...interface{}) Error { +func New(code int32, message string, args ...any) Error { if len(args) > 0 { return &apiError{ code: code, @@ -67,7 +56,7 @@ func New(code int32, message string, args ...interface{}) Error { } // NotFound creates a new not found error -func NotFound(message string, args ...interface{}) Error { +func NotFound(message string, args ...any) Error { if message == "" { message = "Not found" } @@ -97,7 +86,7 @@ func (m *MethodNotAllowedError) Code() int32 { // MarshalJSON implements the JSON encoding interface func (m MethodNotAllowedError) MarshalJSON() ([]byte, error) { - return json.Marshal(map[string]interface{}{ + return json.Marshal(map[string]any{ "code": m.code, "message": m.message, "allowed": m.Allowed, diff --git a/vendor/github.com/go-openapi/errors/auth.go b/vendor/github.com/go-openapi/errors/auth.go index 0545b501bd7..08de582e5db 100644 --- a/vendor/github.com/go-openapi/errors/auth.go +++ b/vendor/github.com/go-openapi/errors/auth.go @@ -1,16 +1,5 @@ -// Copyright 2015 go-swagger maintainers -// -// 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. +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 package errors diff --git a/vendor/github.com/go-openapi/errors/doc.go b/vendor/github.com/go-openapi/errors/doc.go index af01190ce61..b4627f30f4c 100644 --- a/vendor/github.com/go-openapi/errors/doc.go +++ b/vendor/github.com/go-openapi/errors/doc.go @@ -1,16 +1,5 @@ -// Copyright 2015 go-swagger maintainers -// -// 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. +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 /* Package errors provides an Error interface and several concrete types diff --git a/vendor/github.com/go-openapi/errors/headers.go b/vendor/github.com/go-openapi/errors/headers.go index 6ea1151f415..2d837c34ac4 100644 --- a/vendor/github.com/go-openapi/errors/headers.go +++ b/vendor/github.com/go-openapi/errors/headers.go @@ -1,16 +1,5 @@ -// Copyright 2015 go-swagger maintainers -// -// 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. +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 package errors @@ -25,9 +14,9 @@ type Validation struct { //nolint: errname code int32 Name string In string - Value interface{} + Value any message string - Values []interface{} + Values []any } func (e *Validation) Error() string { @@ -41,7 +30,7 @@ func (e *Validation) Code() int32 { // MarshalJSON implements the JSON encoding interface func (e Validation) MarshalJSON() ([]byte, error) { - return json.Marshal(map[string]interface{}{ + return json.Marshal(map[string]any{ "code": e.code, "message": e.message, "in": e.In, @@ -72,7 +61,7 @@ const ( // InvalidContentType error for an invalid content type func InvalidContentType(value string, allowed []string) *Validation { - values := make([]interface{}, 0, len(allowed)) + values := make([]any, 0, len(allowed)) for _, v := range allowed { values = append(values, v) } @@ -88,7 +77,7 @@ func InvalidContentType(value string, allowed []string) *Validation { // InvalidResponseFormat error for an unacceptable response format request func InvalidResponseFormat(value string, allowed []string) *Validation { - values := make([]interface{}, 0, len(allowed)) + values := make([]any, 0, len(allowed)) for _, v := range allowed { values = append(values, v) } diff --git a/vendor/github.com/go-openapi/errors/middleware.go b/vendor/github.com/go-openapi/errors/middleware.go index 1b9f3a93016..c434e59a6fa 100644 --- a/vendor/github.com/go-openapi/errors/middleware.go +++ b/vendor/github.com/go-openapi/errors/middleware.go @@ -1,16 +1,5 @@ -// Copyright 2015 go-swagger maintainers -// -// 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. +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 package errors diff --git a/vendor/github.com/go-openapi/errors/parsing.go b/vendor/github.com/go-openapi/errors/parsing.go index 34930c087a7..ea2a7c60377 100644 --- a/vendor/github.com/go-openapi/errors/parsing.go +++ b/vendor/github.com/go-openapi/errors/parsing.go @@ -1,16 +1,5 @@ -// Copyright 2015 go-swagger maintainers -// -// 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. +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 package errors @@ -63,7 +52,7 @@ func (e ParseError) MarshalJSON() ([]byte, error) { if e.Reason != nil { reason = e.Reason.Error() } - return json.Marshal(map[string]interface{}{ + return json.Marshal(map[string]any{ "code": e.code, "message": e.message, "in": e.In, diff --git a/vendor/github.com/go-openapi/errors/schema.go b/vendor/github.com/go-openapi/errors/schema.go index 8f3239dfd9b..e59ca4f863f 100644 --- a/vendor/github.com/go-openapi/errors/schema.go +++ b/vendor/github.com/go-openapi/errors/schema.go @@ -1,16 +1,5 @@ -// Copyright 2015 go-swagger maintainers -// -// 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. +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 package errors @@ -130,7 +119,7 @@ func (c *CompositeError) Unwrap() []error { // MarshalJSON implements the JSON encoding interface func (c CompositeError) MarshalJSON() ([]byte, error) { - return json.Marshal(map[string]interface{}{ + return json.Marshal(map[string]any{ "code": c.code, "message": c.message, "errors": c.Errors, @@ -254,7 +243,7 @@ func InvalidTypeName(typeName string) *Validation { } // InvalidType creates an error for when the type is invalid -func InvalidType(name, in, typeName string, value interface{}) *Validation { +func InvalidType(name, in, typeName string, value any) *Validation { var message string if in != "" { @@ -302,7 +291,7 @@ func DuplicateItems(name, in string) *Validation { } // TooManyItems error for when an array contains too many items -func TooManyItems(name, in string, maximum int64, value interface{}) *Validation { +func TooManyItems(name, in string, maximum int64, value any) *Validation { msg := fmt.Sprintf(maximumItemsFail, name, in, maximum) if in == "" { msg = fmt.Sprintf(maximumItemsFailNoIn, name, maximum) @@ -318,7 +307,7 @@ func TooManyItems(name, in string, maximum int64, value interface{}) *Validation } // TooFewItems error for when an array contains too few items -func TooFewItems(name, in string, minimum int64, value interface{}) *Validation { +func TooFewItems(name, in string, minimum int64, value any) *Validation { msg := fmt.Sprintf(minItemsFail, name, in, minimum) if in == "" { msg = fmt.Sprintf(minItemsFailNoIn, name, minimum) @@ -333,7 +322,7 @@ func TooFewItems(name, in string, minimum int64, value interface{}) *Validation } // ExceedsMaximumInt error for when maximumimum validation fails -func ExceedsMaximumInt(name, in string, maximum int64, exclusive bool, value interface{}) *Validation { +func ExceedsMaximumInt(name, in string, maximum int64, exclusive bool, value any) *Validation { var message string if in == "" { m := maximumIncFailNoIn @@ -358,7 +347,7 @@ func ExceedsMaximumInt(name, in string, maximum int64, exclusive bool, value int } // ExceedsMaximumUint error for when maximumimum validation fails -func ExceedsMaximumUint(name, in string, maximum uint64, exclusive bool, value interface{}) *Validation { +func ExceedsMaximumUint(name, in string, maximum uint64, exclusive bool, value any) *Validation { var message string if in == "" { m := maximumIncFailNoIn @@ -383,7 +372,7 @@ func ExceedsMaximumUint(name, in string, maximum uint64, exclusive bool, value i } // ExceedsMaximum error for when maximumimum validation fails -func ExceedsMaximum(name, in string, maximum float64, exclusive bool, value interface{}) *Validation { +func ExceedsMaximum(name, in string, maximum float64, exclusive bool, value any) *Validation { var message string if in == "" { m := maximumIncFailNoIn @@ -408,7 +397,7 @@ func ExceedsMaximum(name, in string, maximum float64, exclusive bool, value inte } // ExceedsMinimumInt error for when minimum validation fails -func ExceedsMinimumInt(name, in string, minimum int64, exclusive bool, value interface{}) *Validation { +func ExceedsMinimumInt(name, in string, minimum int64, exclusive bool, value any) *Validation { var message string if in == "" { m := minIncFailNoIn @@ -433,7 +422,7 @@ func ExceedsMinimumInt(name, in string, minimum int64, exclusive bool, value int } // ExceedsMinimumUint error for when minimum validation fails -func ExceedsMinimumUint(name, in string, minimum uint64, exclusive bool, value interface{}) *Validation { +func ExceedsMinimumUint(name, in string, minimum uint64, exclusive bool, value any) *Validation { var message string if in == "" { m := minIncFailNoIn @@ -458,7 +447,7 @@ func ExceedsMinimumUint(name, in string, minimum uint64, exclusive bool, value i } // ExceedsMinimum error for when minimum validation fails -func ExceedsMinimum(name, in string, minimum float64, exclusive bool, value interface{}) *Validation { +func ExceedsMinimum(name, in string, minimum float64, exclusive bool, value any) *Validation { var message string if in == "" { m := minIncFailNoIn @@ -483,7 +472,7 @@ func ExceedsMinimum(name, in string, minimum float64, exclusive bool, value inte } // NotMultipleOf error for when multiple of validation fails -func NotMultipleOf(name, in string, multiple, value interface{}) *Validation { +func NotMultipleOf(name, in string, multiple, value any) *Validation { var msg string if in == "" { msg = fmt.Sprintf(multipleOfFailNoIn, name, multiple) @@ -500,7 +489,7 @@ func NotMultipleOf(name, in string, multiple, value interface{}) *Validation { } // EnumFail error for when an enum validation fails -func EnumFail(name, in string, value interface{}, values []interface{}) *Validation { +func EnumFail(name, in string, value any, values []any) *Validation { var msg string if in == "" { msg = fmt.Sprintf(enumFailNoIn, name, values) @@ -519,7 +508,7 @@ func EnumFail(name, in string, value interface{}, values []interface{}) *Validat } // Required error for when a value is missing -func Required(name, in string, value interface{}) *Validation { +func Required(name, in string, value any) *Validation { var msg string if in == "" { msg = fmt.Sprintf(requiredFailNoIn, name) @@ -536,7 +525,7 @@ func Required(name, in string, value interface{}) *Validation { } // ReadOnly error for when a value is present in request -func ReadOnly(name, in string, value interface{}) *Validation { +func ReadOnly(name, in string, value any) *Validation { var msg string if in == "" { msg = fmt.Sprintf(readOnlyFailNoIn, name) @@ -553,7 +542,7 @@ func ReadOnly(name, in string, value interface{}) *Validation { } // TooLong error for when a string is too long -func TooLong(name, in string, maximum int64, value interface{}) *Validation { +func TooLong(name, in string, maximum int64, value any) *Validation { var msg string if in == "" { msg = fmt.Sprintf(tooLongMessageNoIn, name, maximum) @@ -570,7 +559,7 @@ func TooLong(name, in string, maximum int64, value interface{}) *Validation { } // TooShort error for when a string is too short -func TooShort(name, in string, minimum int64, value interface{}) *Validation { +func TooShort(name, in string, minimum int64, value any) *Validation { var msg string if in == "" { msg = fmt.Sprintf(tooShortMessageNoIn, name, minimum) @@ -589,7 +578,7 @@ func TooShort(name, in string, minimum int64, value interface{}) *Validation { // FailedPattern error for when a string fails a regex pattern match // the pattern that is returned is the ECMA syntax version of the pattern not the golang version. -func FailedPattern(name, in, pattern string, value interface{}) *Validation { +func FailedPattern(name, in, pattern string, value any) *Validation { var msg string if in == "" { msg = fmt.Sprintf(patternFailNoIn, name, pattern) @@ -608,7 +597,7 @@ func FailedPattern(name, in, pattern string, value interface{}) *Validation { // MultipleOfMustBePositive error for when a // multipleOf factor is negative -func MultipleOfMustBePositive(name, in string, factor interface{}) *Validation { +func MultipleOfMustBePositive(name, in string, factor any) *Validation { return &Validation{ code: MultipleOfMustBePositiveCode, Name: name, diff --git a/vendor/github.com/go-openapi/jsonreference/NOTICE b/vendor/github.com/go-openapi/jsonreference/NOTICE new file mode 100644 index 00000000000..f9ad7e0f7a0 --- /dev/null +++ b/vendor/github.com/go-openapi/jsonreference/NOTICE @@ -0,0 +1,36 @@ +Copyright 2015-2025 go-swagger maintainers + +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +This software library, github.com/go-openapi/jsonpointer, includes software developed +by the go-swagger and go-openapi maintainers ("go-swagger maintainers"). + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this software except in compliance with the License. +You may obtain a copy of the License at + +This software is copied from, derived from, and inspired by other original software products. +It ships with copies of other software which license terms are recalled below. + +The original sofware was authored on 25-02-2013 by sigu-399 (https://github.com/sigu-399, sigu.399@gmail.com). + +github.com/sigh-399/jsonpointer +=========================== + +// SPDX-FileCopyrightText: Copyright 2013 sigu-399 ( https://github.com/sigu-399 ) +// SPDX-License-Identifier: Apache-2.0 + +Copyright 2013 sigu-399 ( https://github.com/sigu-399 ) + +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/github.com/go-openapi/jsonreference/README.md b/vendor/github.com/go-openapi/jsonreference/README.md index c7fc2049c1d..2274a4b78fc 100644 --- a/vendor/github.com/go-openapi/jsonreference/README.md +++ b/vendor/github.com/go-openapi/jsonreference/README.md @@ -17,3 +17,10 @@ Feature complete. Stable API * http://tools.ietf.org/html/draft-ietf-appsawg-json-pointer-07 * http://tools.ietf.org/html/draft-pbryan-zyp-json-ref-03 + +## Licensing + +This library ships under the [SPDX-License-Identifier: Apache-2.0](./LICENSE). + +See the license [NOTICE](./NOTICE), which recalls the licensing terms of all the pieces of software +on top of which it has been built. diff --git a/vendor/github.com/go-openapi/jsonreference/internal/normalize_url.go b/vendor/github.com/go-openapi/jsonreference/internal/normalize_url.go index f0610cf1e57..ca79391dcf3 100644 --- a/vendor/github.com/go-openapi/jsonreference/internal/normalize_url.go +++ b/vendor/github.com/go-openapi/jsonreference/internal/normalize_url.go @@ -1,3 +1,6 @@ +// SPDX-FileCopyrightText: Copyright (c) 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + package internal import ( diff --git a/vendor/github.com/go-openapi/jsonreference/reference.go b/vendor/github.com/go-openapi/jsonreference/reference.go index 6a1fed5dfe7..33d4798cad3 100644 --- a/vendor/github.com/go-openapi/jsonreference/reference.go +++ b/vendor/github.com/go-openapi/jsonreference/reference.go @@ -1,27 +1,5 @@ -// Copyright 2013 sigu-399 ( https://github.com/sigu-399 ) -// -// 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. - -// author sigu-399 -// author-github https://github.com/sigu-399 -// author-mail sigu.399@gmail.com -// -// repository-name jsonreference -// repository-desc An implementation of JSON Reference - Go language -// -// description Main and unique file. -// -// created 26-02-2013 +// SPDX-FileCopyrightText: Copyright (c) 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 package jsonreference diff --git a/vendor/github.com/go-openapi/loads/.golangci.yml b/vendor/github.com/go-openapi/loads/.golangci.yml index 7cea1af8b52..1ad5adf47e6 100644 --- a/vendor/github.com/go-openapi/loads/.golangci.yml +++ b/vendor/github.com/go-openapi/loads/.golangci.yml @@ -16,7 +16,7 @@ linters: - godox - gosmopolitan - inamedparam - #- intrange # disabled while < go1.22 + - intrange - ireturn - lll - musttag diff --git a/vendor/github.com/go-openapi/loads/README.md b/vendor/github.com/go-openapi/loads/README.md index 6164ebe40a3..1f0174f2d91 100644 --- a/vendor/github.com/go-openapi/loads/README.md +++ b/vendor/github.com/go-openapi/loads/README.md @@ -26,3 +26,7 @@ Primary usage: ``` See also the provided [examples](https://pkg.go.dev/github.com/go-openapi/loads#pkg-examples). + +## Licensing + +This library ships under the [SPDX-License-Identifier: Apache-2.0](./LICENSE). diff --git a/vendor/github.com/go-openapi/loads/doc.go b/vendor/github.com/go-openapi/loads/doc.go index 1ca47bcfb0d..7981e70e9f1 100644 --- a/vendor/github.com/go-openapi/loads/doc.go +++ b/vendor/github.com/go-openapi/loads/doc.go @@ -1,16 +1,5 @@ -// Copyright 2015 go-swagger maintainers -// -// 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. +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 // Package loads provides document loading methods for swagger (OAI v2) API specifications. // diff --git a/vendor/github.com/go-openapi/loads/errors.go b/vendor/github.com/go-openapi/loads/errors.go index 132a702e938..8f2d602f5cc 100644 --- a/vendor/github.com/go-openapi/loads/errors.go +++ b/vendor/github.com/go-openapi/loads/errors.go @@ -1,3 +1,6 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + package loads type loaderError string diff --git a/vendor/github.com/go-openapi/loads/loaders.go b/vendor/github.com/go-openapi/loads/loaders.go index 646d35af393..25b157302e4 100644 --- a/vendor/github.com/go-openapi/loads/loaders.go +++ b/vendor/github.com/go-openapi/loads/loaders.go @@ -1,3 +1,6 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + package loads import ( diff --git a/vendor/github.com/go-openapi/loads/options.go b/vendor/github.com/go-openapi/loads/options.go index 3b055319b3d..adb5e6d15b0 100644 --- a/vendor/github.com/go-openapi/loads/options.go +++ b/vendor/github.com/go-openapi/loads/options.go @@ -1,3 +1,6 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + package loads import "github.com/go-openapi/swag/loading" diff --git a/vendor/github.com/go-openapi/loads/spec.go b/vendor/github.com/go-openapi/loads/spec.go index 838231a580e..213c40c657a 100644 --- a/vendor/github.com/go-openapi/loads/spec.go +++ b/vendor/github.com/go-openapi/loads/spec.go @@ -1,16 +1,5 @@ -// Copyright 2015 go-swagger maintainers -// -// 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. +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 package loads diff --git a/vendor/github.com/go-openapi/runtime/.golangci.yml b/vendor/github.com/go-openapi/runtime/.golangci.yml index 5a0faa2e5f6..0087ed31130 100644 --- a/vendor/github.com/go-openapi/runtime/.golangci.yml +++ b/vendor/github.com/go-openapi/runtime/.golangci.yml @@ -18,7 +18,6 @@ linters: - gomoddirectives # moved to mono-repo, multi-modules, so replace directives are needed - gosmopolitan - inamedparam - #- intrange # disabled while < go1.22 - ireturn - lll - musttag diff --git a/vendor/github.com/go-openapi/runtime/README.md b/vendor/github.com/go-openapi/runtime/README.md index 16a151234f4..9e15b1adb5b 100644 --- a/vendor/github.com/go-openapi/runtime/README.md +++ b/vendor/github.com/go-openapi/runtime/README.md @@ -11,7 +11,7 @@ The runtime component for use in code generation or as untyped usage. ## Release notes -### v0.29.0 [draft, unpublished] +### v0.29.0 **New with this release**: @@ -37,3 +37,7 @@ Moving forward, we want to : independently from the main package (to avoid breaking changes, the existing API will remain maintained, but evolve at a slower pace than opentelemetry). * [ ] fix a few known issues with some file upload requests (e.g. #286) + +## Licensing + +This library ships under the [SPDX-License-Identifier: Apache-2.0](./LICENSE). diff --git a/vendor/github.com/go-openapi/runtime/bytestream.go b/vendor/github.com/go-openapi/runtime/bytestream.go index 98e961878d9..eb649742e8e 100644 --- a/vendor/github.com/go-openapi/runtime/bytestream.go +++ b/vendor/github.com/go-openapi/runtime/bytestream.go @@ -1,16 +1,5 @@ -// Copyright 2015 go-swagger maintainers -// -// 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. +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 package runtime @@ -54,7 +43,7 @@ func ByteStreamConsumer(opts ...byteStreamOpt) Consumer { opt(&vals) } - return ConsumerFunc(func(reader io.Reader, data interface{}) error { + return ConsumerFunc(func(reader io.Reader, data any) error { if reader == nil { return errors.New("ByteStreamConsumer requires a reader") // early exit } @@ -148,7 +137,7 @@ func ByteStreamProducer(opts ...byteStreamOpt) Producer { opt(&vals) } - return ProducerFunc(func(writer io.Writer, data interface{}) error { + return ProducerFunc(func(writer io.Writer, data any) error { if writer == nil { return errors.New("ByteStreamProducer requires a writer") // early exit } diff --git a/vendor/github.com/go-openapi/runtime/client/auth_info.go b/vendor/github.com/go-openapi/runtime/client/auth_info.go index 4f26e92347a..a98690c4d60 100644 --- a/vendor/github.com/go-openapi/runtime/client/auth_info.go +++ b/vendor/github.com/go-openapi/runtime/client/auth_info.go @@ -1,16 +1,5 @@ -// Copyright 2015 go-swagger maintainers -// -// 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. +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 package client diff --git a/vendor/github.com/go-openapi/runtime/client/keepalive.go b/vendor/github.com/go-openapi/runtime/client/keepalive.go index 7dd6b51c4df..831d23b511d 100644 --- a/vendor/github.com/go-openapi/runtime/client/keepalive.go +++ b/vendor/github.com/go-openapi/runtime/client/keepalive.go @@ -1,3 +1,6 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + package client import ( diff --git a/vendor/github.com/go-openapi/runtime/client/opentelemetry.go b/vendor/github.com/go-openapi/runtime/client/opentelemetry.go index db246fc686e..e77941293f9 100644 --- a/vendor/github.com/go-openapi/runtime/client/opentelemetry.go +++ b/vendor/github.com/go-openapi/runtime/client/opentelemetry.go @@ -1,3 +1,6 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + package client import ( @@ -108,7 +111,7 @@ func newOpenTelemetryTransport(transport runtime.ClientTransport, host string, o return tr } -func (t *openTelemetryTransport) Submit(op *runtime.ClientOperation) (interface{}, error) { +func (t *openTelemetryTransport) Submit(op *runtime.ClientOperation) (any, error) { if op.Context == nil { return t.transport.Submit(op) } @@ -128,7 +131,7 @@ func (t *openTelemetryTransport) Submit(op *runtime.ClientOperation) (interface{ return params.WriteToRequest(req, reg) }) - op.Reader = runtime.ClientResponseReaderFunc(func(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + op.Reader = runtime.ClientResponseReaderFunc(func(response runtime.ClientResponse, consumer runtime.Consumer) (any, error) { if span != nil { statusCode := response.Code() // NOTE: this is replaced by semconv.HTTPResponseStatusCode in semconv v1.21 diff --git a/vendor/github.com/go-openapi/runtime/client/request.go b/vendor/github.com/go-openapi/runtime/client/request.go index 8f8bab03439..6d9b25912ec 100644 --- a/vendor/github.com/go-openapi/runtime/client/request.go +++ b/vendor/github.com/go-openapi/runtime/client/request.go @@ -1,16 +1,5 @@ -// Copyright 2015 go-swagger maintainers -// -// 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. +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 package client diff --git a/vendor/github.com/go-openapi/runtime/client/response.go b/vendor/github.com/go-openapi/runtime/client/response.go index 0bbd388bc8b..59abc3b549a 100644 --- a/vendor/github.com/go-openapi/runtime/client/response.go +++ b/vendor/github.com/go-openapi/runtime/client/response.go @@ -1,16 +1,5 @@ -// Copyright 2015 go-swagger maintainers -// -// 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. +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 package client diff --git a/vendor/github.com/go-openapi/runtime/client/runtime.go b/vendor/github.com/go-openapi/runtime/client/runtime.go index 8dc50c15e36..203c74e49db 100644 --- a/vendor/github.com/go-openapi/runtime/client/runtime.go +++ b/vendor/github.com/go-openapi/runtime/client/runtime.go @@ -1,16 +1,5 @@ -// Copyright 2015 go-swagger maintainers -// -// 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. +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 package client @@ -363,7 +352,7 @@ func (r *Runtime) CreateHttpRequest(operation *runtime.ClientOperation) (req *ht // Submit a request and when there is a body on success it will turn that into the result // all other things are turned into an api error for swagger which retains the status code -func (r *Runtime) Submit(operation *runtime.ClientOperation) (interface{}, error) { +func (r *Runtime) Submit(operation *runtime.ClientOperation) (any, error) { _, readResponse, _ := operation.Params, operation.Reader, operation.AuthInfo request, req, err := r.createHttpRequest(operation) diff --git a/vendor/github.com/go-openapi/runtime/client_auth_info.go b/vendor/github.com/go-openapi/runtime/client_auth_info.go index c6c97d9a7c3..581e64451a2 100644 --- a/vendor/github.com/go-openapi/runtime/client_auth_info.go +++ b/vendor/github.com/go-openapi/runtime/client_auth_info.go @@ -1,16 +1,5 @@ -// Copyright 2015 go-swagger maintainers -// -// 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. +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 package runtime diff --git a/vendor/github.com/go-openapi/runtime/client_operation.go b/vendor/github.com/go-openapi/runtime/client_operation.go index 5a5d63563ad..b0bb0977db5 100644 --- a/vendor/github.com/go-openapi/runtime/client_operation.go +++ b/vendor/github.com/go-openapi/runtime/client_operation.go @@ -1,16 +1,5 @@ -// Copyright 2015 go-swagger maintainers -// -// 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. +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 package runtime @@ -37,5 +26,5 @@ type ClientOperation struct { // A ClientTransport implementor knows how to submit Request objects to some destination type ClientTransport interface { // Submit(string, RequestWriter, ResponseReader, AuthInfoWriter) (interface{}, error) - Submit(*ClientOperation) (interface{}, error) + Submit(*ClientOperation) (any, error) } diff --git a/vendor/github.com/go-openapi/runtime/client_request.go b/vendor/github.com/go-openapi/runtime/client_request.go index 4ebb2deabe9..6e335b36f32 100644 --- a/vendor/github.com/go-openapi/runtime/client_request.go +++ b/vendor/github.com/go-openapi/runtime/client_request.go @@ -1,16 +1,5 @@ -// Copyright 2015 go-swagger maintainers -// -// 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. +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 package runtime @@ -53,7 +42,7 @@ type ClientRequest interface { //nolint:interfacebloat // a swagger-capable requ SetFileParam(string, ...NamedReadCloser) error - SetBodyParam(interface{}) error + SetBodyParam(any) error SetTimeout(time.Duration) error @@ -63,7 +52,7 @@ type ClientRequest interface { //nolint:interfacebloat // a swagger-capable requ GetBody() []byte - GetBodyParam() interface{} + GetBodyParam() any GetFileParam() map[string][]NamedReadCloser } @@ -103,7 +92,7 @@ func (n *namedReadCloser) Name() string { type TestClientRequest struct { Headers http.Header - Body interface{} + Body any } func (t *TestClientRequest) SetHeaderParam(name string, values ...string) error { @@ -122,7 +111,7 @@ func (t *TestClientRequest) SetPathParam(_ string, _ string) error { return nil func (t *TestClientRequest) SetFileParam(_ string, _ ...NamedReadCloser) error { return nil } -func (t *TestClientRequest) SetBodyParam(body interface{}) error { +func (t *TestClientRequest) SetBodyParam(body any) error { t.Body = body return nil } @@ -139,7 +128,7 @@ func (t *TestClientRequest) GetPath() string { return "" } func (t *TestClientRequest) GetBody() []byte { return nil } -func (t *TestClientRequest) GetBodyParam() interface{} { +func (t *TestClientRequest) GetBodyParam() any { return t.Body } diff --git a/vendor/github.com/go-openapi/runtime/client_response.go b/vendor/github.com/go-openapi/runtime/client_response.go index b9929946d80..f2cf942ab36 100644 --- a/vendor/github.com/go-openapi/runtime/client_response.go +++ b/vendor/github.com/go-openapi/runtime/client_response.go @@ -1,16 +1,5 @@ -// Copyright 2015 go-swagger maintainers -// -// 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. +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 package runtime @@ -18,6 +7,7 @@ import ( "encoding/json" "fmt" "io" + "strings" ) // A ClientResponse represents a client response. @@ -32,28 +22,28 @@ type ClientResponse interface { } // A ClientResponseReaderFunc turns a function into a ClientResponseReader interface implementation -type ClientResponseReaderFunc func(ClientResponse, Consumer) (interface{}, error) +type ClientResponseReaderFunc func(ClientResponse, Consumer) (any, error) // ReadResponse reads the response -func (read ClientResponseReaderFunc) ReadResponse(resp ClientResponse, consumer Consumer) (interface{}, error) { +func (read ClientResponseReaderFunc) ReadResponse(resp ClientResponse, consumer Consumer) (any, error) { return read(resp, consumer) } // A ClientResponseReader is an interface for things want to read a response. // An application of this is to create structs from response values type ClientResponseReader interface { - ReadResponse(ClientResponse, Consumer) (interface{}, error) + ReadResponse(ClientResponse, Consumer) (any, error) } // APIError wraps an error model and captures the status code type APIError struct { OperationName string - Response interface{} + Response any Code int } // NewAPIError creates a new API error -func NewAPIError(opName string, payload interface{}, code int) *APIError { +func NewAPIError(opName string, payload any, code int) *APIError { return &APIError{ OperationName: opName, Response: payload, @@ -61,13 +51,17 @@ func NewAPIError(opName string, payload interface{}, code int) *APIError { } } +// sanitizer ensures that single quotes are escaped +var sanitizer = strings.NewReplacer(`\`, `\\`, `'`, `\'`) + func (o *APIError) Error() string { var resp []byte if err, ok := o.Response.(error); ok { - resp = []byte("'" + err.Error() + "'") + resp = []byte("'" + sanitizer.Replace(err.Error()) + "'") } else { resp, _ = json.Marshal(o.Response) } + return fmt.Sprintf("%s (status %d): %s", o.OperationName, o.Code, resp) } diff --git a/vendor/github.com/go-openapi/runtime/constants.go b/vendor/github.com/go-openapi/runtime/constants.go index 515969242ca..62ae9eec0cf 100644 --- a/vendor/github.com/go-openapi/runtime/constants.go +++ b/vendor/github.com/go-openapi/runtime/constants.go @@ -1,16 +1,5 @@ -// Copyright 2015 go-swagger maintainers -// -// 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. +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 package runtime diff --git a/vendor/github.com/go-openapi/runtime/csv.go b/vendor/github.com/go-openapi/runtime/csv.go index c9597bcd6e0..567e3d9db24 100644 --- a/vendor/github.com/go-openapi/runtime/csv.go +++ b/vendor/github.com/go-openapi/runtime/csv.go @@ -1,16 +1,5 @@ -// Copyright 2015 go-swagger maintainers -// -// 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. +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 package runtime @@ -48,7 +37,7 @@ import ( func CSVConsumer(opts ...CSVOpt) Consumer { o := csvOptsWithDefaults(opts) - return ConsumerFunc(func(reader io.Reader, data interface{}) error { + return ConsumerFunc(func(reader io.Reader, data any) error { if reader == nil { return errors.New("CSVConsumer requires a reader") } @@ -181,7 +170,7 @@ func CSVConsumer(opts ...CSVOpt) Consumer { func CSVProducer(opts ...CSVOpt) Producer { o := csvOptsWithDefaults(opts) - return ProducerFunc(func(writer io.Writer, data interface{}) error { + return ProducerFunc(func(writer io.Writer, data any) error { if writer == nil { return errors.New("CSVProducer requires a writer") } diff --git a/vendor/github.com/go-openapi/runtime/csv_options.go b/vendor/github.com/go-openapi/runtime/csv_options.go index 89665788242..4cc04390010 100644 --- a/vendor/github.com/go-openapi/runtime/csv_options.go +++ b/vendor/github.com/go-openapi/runtime/csv_options.go @@ -1,3 +1,6 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + package runtime import ( diff --git a/vendor/github.com/go-openapi/runtime/discard.go b/vendor/github.com/go-openapi/runtime/discard.go index 0d390cfd64c..b05678becd9 100644 --- a/vendor/github.com/go-openapi/runtime/discard.go +++ b/vendor/github.com/go-openapi/runtime/discard.go @@ -1,9 +1,12 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + package runtime import "io" // DiscardConsumer does absolutely nothing, it's a black hole. -var DiscardConsumer = ConsumerFunc(func(_ io.Reader, _ interface{}) error { return nil }) +var DiscardConsumer = ConsumerFunc(func(_ io.Reader, _ any) error { return nil }) // DiscardProducer does absolutely nothing, it's a black hole. -var DiscardProducer = ProducerFunc(func(_ io.Writer, _ interface{}) error { return nil }) +var DiscardProducer = ProducerFunc(func(_ io.Writer, _ any) error { return nil }) diff --git a/vendor/github.com/go-openapi/runtime/file.go b/vendor/github.com/go-openapi/runtime/file.go index 1bc6aabf705..2a85379a748 100644 --- a/vendor/github.com/go-openapi/runtime/file.go +++ b/vendor/github.com/go-openapi/runtime/file.go @@ -1,16 +1,5 @@ -// Copyright 2015 go-swagger maintainers -// -// 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. +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 package runtime diff --git a/vendor/github.com/go-openapi/runtime/go.work.sum b/vendor/github.com/go-openapi/runtime/go.work.sum index a60668ab8a0..b0c2c9a63de 100644 --- a/vendor/github.com/go-openapi/runtime/go.work.sum +++ b/vendor/github.com/go-openapi/runtime/go.work.sum @@ -43,15 +43,18 @@ golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5y golang.org/x/crypto v0.17.0/go.mod h1:gCAAfMLgwOJRpTjQ2zCCt2OcSfYMTeZVSRtQlPC7Nq4= golang.org/x/crypto v0.26.0/go.mod h1:GY7jblb9wI+FOo5y8/S2oY4zWP07AkOJ4+jxCqdqn54= golang.org/x/crypto v0.42.0/go.mod h1:4+rDnOTJhQCx2q7/j6rAN5XDw8kPjeaXEUR2eL94ix8= +golang.org/x/crypto v0.43.0/go.mod h1:BFbav4mRNlXJL4wNeejLpWxB7wMbc79PdRGhWKncxR0= golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= golang.org/x/mod v0.18.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c= golang.org/x/mod v0.21.0/go.mod h1:6SkKJ3Xj0I0BrPOZoBy3bdMptDDU9oJrpohJ3eWZ1fY= golang.org/x/mod v0.27.0/go.mod h1:rWI627Fq0DEoudcK+MBkNkCe0EetEaDSwJJkCcjpazc= +golang.org/x/mod v0.28.0/go.mod h1:yfB/L0NOf/kmEbXjzCPOx1iK1fRutOydrCMsqRhEBxI= golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= golang.org/x/net v0.26.0/go.mod h1:5YKkiSynbBIh3p6iOc/vibscux0x38BZDkn8sCUPxHE= golang.org/x/net v0.43.0/go.mod h1:vhO1fvI4dGsIjh73sWfUVjj3N7CA9WkKJNQm2svM6Jg= +golang.org/x/net v0.45.0/go.mod h1:ECOoLqd5U3Lhyeyo/QDCEVQ4sNgYsqvCZ722XogGieY= golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.8.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= @@ -70,6 +73,7 @@ golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9sn golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= golang.org/x/term v0.23.0/go.mod h1:DgV24QBUrK6jhZXl+20l6UWznPlwAHm1Q1mGHtydmSk= golang.org/x/term v0.35.0/go.mod h1:TPGtkTLesOwf2DE8CgVYiZinHAOuy5AYUYT1lENIZnA= +golang.org/x/term v0.36.0/go.mod h1:Qu394IJq6V6dCBRgwqshf3mPF85AqzYEzofzRdZkWss= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= @@ -83,6 +87,7 @@ golang.org/x/tools v0.22.0/go.mod h1:aCwcsjqvq7Yqt6TNyX7QMU2enbQ/Gt0bo6krSeEri+c golang.org/x/tools v0.26.0/go.mod h1:TPVVj70c7JJ3WCazhD8OdXcZg/og+b9+tH/KxylGwH0= golang.org/x/tools v0.35.0/go.mod h1:NKdj5HkL/73byiZSJjqJgKn3ep7KjFkBOkR/Hps3VPw= golang.org/x/tools v0.36.0/go.mod h1:WBDiHKJK8YgLHlcQPYQzNCkUxUypCaa5ZegCVutKm+s= +golang.org/x/tools v0.37.0/go.mod h1:MBN5QPQtLMHVdvsbtarmTNukZDdgwdwlO5qGacAzF0w= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= diff --git a/vendor/github.com/go-openapi/runtime/headers.go b/vendor/github.com/go-openapi/runtime/headers.go index 4d111db4fec..510e396ca73 100644 --- a/vendor/github.com/go-openapi/runtime/headers.go +++ b/vendor/github.com/go-openapi/runtime/headers.go @@ -1,16 +1,5 @@ -// Copyright 2015 go-swagger maintainers -// -// 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. +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 package runtime diff --git a/vendor/github.com/go-openapi/runtime/interfaces.go b/vendor/github.com/go-openapi/runtime/interfaces.go index e3341286834..90046bf367e 100644 --- a/vendor/github.com/go-openapi/runtime/interfaces.go +++ b/vendor/github.com/go-openapi/runtime/interfaces.go @@ -1,16 +1,5 @@ -// Copyright 2015 go-swagger maintainers -// -// 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. +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 package runtime @@ -23,23 +12,23 @@ import ( ) // OperationHandlerFunc an adapter for a function to the OperationHandler interface -type OperationHandlerFunc func(interface{}) (interface{}, error) +type OperationHandlerFunc func(any) (any, error) // Handle implements the operation handler interface -func (s OperationHandlerFunc) Handle(data interface{}) (interface{}, error) { +func (s OperationHandlerFunc) Handle(data any) (any, error) { return s(data) } // OperationHandler a handler for a swagger operation type OperationHandler interface { - Handle(interface{}) (interface{}, error) + Handle(any) (any, error) } // ConsumerFunc represents a function that can be used as a consumer -type ConsumerFunc func(io.Reader, interface{}) error +type ConsumerFunc func(io.Reader, any) error // Consume consumes the reader into the data parameter -func (fn ConsumerFunc) Consume(reader io.Reader, data interface{}) error { +func (fn ConsumerFunc) Consume(reader io.Reader, data any) error { return fn(reader, data) } @@ -47,14 +36,14 @@ func (fn ConsumerFunc) Consume(reader io.Reader, data interface{}) error { // data provided by the request body type Consumer interface { // Consume performs the binding of request values - Consume(io.Reader, interface{}) error + Consume(io.Reader, any) error } // ProducerFunc represents a function that can be used as a producer -type ProducerFunc func(io.Writer, interface{}) error +type ProducerFunc func(io.Writer, any) error // Produce produces the response for the provided data -func (f ProducerFunc) Produce(writer io.Writer, data interface{}) error { +func (f ProducerFunc) Produce(writer io.Writer, data any) error { return f(writer, data) } @@ -62,14 +51,14 @@ func (f ProducerFunc) Produce(writer io.Writer, data interface{}) error { // HTTP response type Producer interface { // Produce writes to the http response - Produce(io.Writer, interface{}) error + Produce(io.Writer, any) error } // AuthenticatorFunc turns a function into an authenticator -type AuthenticatorFunc func(interface{}) (bool, interface{}, error) +type AuthenticatorFunc func(any) (bool, any, error) // Authenticate authenticates the request with the provided data -func (f AuthenticatorFunc) Authenticate(params interface{}) (bool, interface{}, error) { +func (f AuthenticatorFunc) Authenticate(params any) (bool, any, error) { return f(params) } @@ -77,14 +66,14 @@ func (f AuthenticatorFunc) Authenticate(params interface{}) (bool, interface{}, // implementations of Authenticator know how to authenticate the // request data and translate that into a valid principal object or an error type Authenticator interface { - Authenticate(interface{}) (bool, interface{}, error) + Authenticate(any) (bool, any, error) } // AuthorizerFunc turns a function into an authorizer -type AuthorizerFunc func(*http.Request, interface{}) error +type AuthorizerFunc func(*http.Request, any) error // Authorize authorizes the processing of the request for the principal -func (f AuthorizerFunc) Authorize(r *http.Request, principal interface{}) error { +func (f AuthorizerFunc) Authorize(r *http.Request, principal any) error { return f(r, principal) } @@ -92,7 +81,7 @@ func (f AuthorizerFunc) Authorize(r *http.Request, principal interface{}) error // implementations of Authorizer know how to authorize the principal object // using the request data and returns error if unauthorized type Authorizer interface { - Authorize(*http.Request, interface{}) error + Authorize(*http.Request, any) error } // Validatable types implementing this interface allow customizing their validation diff --git a/vendor/github.com/go-openapi/runtime/json.go b/vendor/github.com/go-openapi/runtime/json.go index 5a690559cc5..8f93eebfaa2 100644 --- a/vendor/github.com/go-openapi/runtime/json.go +++ b/vendor/github.com/go-openapi/runtime/json.go @@ -1,16 +1,5 @@ -// Copyright 2015 go-swagger maintainers -// -// 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. +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 package runtime @@ -21,7 +10,7 @@ import ( // JSONConsumer creates a new JSON consumer func JSONConsumer() Consumer { - return ConsumerFunc(func(reader io.Reader, data interface{}) error { + return ConsumerFunc(func(reader io.Reader, data any) error { dec := json.NewDecoder(reader) dec.UseNumber() // preserve number formats return dec.Decode(data) @@ -30,7 +19,7 @@ func JSONConsumer() Consumer { // JSONProducer creates a new JSON producer func JSONProducer() Producer { - return ProducerFunc(func(writer io.Writer, data interface{}) error { + return ProducerFunc(func(writer io.Writer, data any) error { enc := json.NewEncoder(writer) enc.SetEscapeHTML(false) return enc.Encode(data) diff --git a/vendor/github.com/go-openapi/runtime/logger/logger.go b/vendor/github.com/go-openapi/runtime/logger/logger.go index 6f4debcc145..45484deb593 100644 --- a/vendor/github.com/go-openapi/runtime/logger/logger.go +++ b/vendor/github.com/go-openapi/runtime/logger/logger.go @@ -1,10 +1,13 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + package logger import "os" type Logger interface { - Printf(format string, args ...interface{}) - Debugf(format string, args ...interface{}) + Printf(format string, args ...any) + Debugf(format string, args ...any) } func DebugEnabled() bool { diff --git a/vendor/github.com/go-openapi/runtime/logger/standard.go b/vendor/github.com/go-openapi/runtime/logger/standard.go index 30035a77770..48ba27f4a3d 100644 --- a/vendor/github.com/go-openapi/runtime/logger/standard.go +++ b/vendor/github.com/go-openapi/runtime/logger/standard.go @@ -1,3 +1,6 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + package logger import ( @@ -9,14 +12,14 @@ var _ Logger = StandardLogger{} type StandardLogger struct{} -func (StandardLogger) Printf(format string, args ...interface{}) { +func (StandardLogger) Printf(format string, args ...any) { if len(format) == 0 || format[len(format)-1] != '\n' { format += "\n" } fmt.Fprintf(os.Stderr, format, args...) } -func (StandardLogger) Debugf(format string, args ...interface{}) { +func (StandardLogger) Debugf(format string, args ...any) { if len(format) == 0 || format[len(format)-1] != '\n' { format += "\n" } diff --git a/vendor/github.com/go-openapi/runtime/middleware/context.go b/vendor/github.com/go-openapi/runtime/middleware/context.go index f2cade3ca0a..bb00b93b89b 100644 --- a/vendor/github.com/go-openapi/runtime/middleware/context.go +++ b/vendor/github.com/go-openapi/runtime/middleware/context.go @@ -1,16 +1,5 @@ -// Copyright 2015 go-swagger maintainers -// -// 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. +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 package middleware @@ -126,7 +115,7 @@ func newRoutableUntypedAPI(spec *loads.Document, api *untyped.API, context *Cont } // bind and validate the request using reflection - var bound interface{} + var bound any var validation error bound, r, validation = context.BindAndValidate(r, route) if validation != nil { @@ -287,7 +276,7 @@ func MatchedRouteFrom(req *http.Request) *MatchedRoute { } // SecurityPrincipalFrom request context value. -func SecurityPrincipalFrom(req *http.Request) interface{} { +func SecurityPrincipalFrom(req *http.Request) any { return req.Context().Value(ctxSecurityPrincipal) } @@ -466,7 +455,7 @@ func (c *Context) ResetAuth(request *http.Request) *http.Request { // Returns the principal object and a shallow copy of the request when its // context doesn't contain the principal, otherwise the same request or an error // (the last) if one of the authenticators returns one or an Unauthenticated error -func (c *Context) Authorize(request *http.Request, route *MatchedRoute) (interface{}, *http.Request, error) { +func (c *Context) Authorize(request *http.Request, route *MatchedRoute) (any, *http.Request, error) { if route == nil || !route.HasAuth() { return nil, nil, nil } @@ -504,7 +493,7 @@ func (c *Context) Authorize(request *http.Request, route *MatchedRoute) (interfa // Returns the validation map and a shallow copy of the request when its context // doesn't contain the validation, otherwise it returns the same request or an // CompositeValidationError error -func (c *Context) BindAndValidate(request *http.Request, matched *MatchedRoute) (interface{}, *http.Request, error) { +func (c *Context) BindAndValidate(request *http.Request, matched *MatchedRoute) (any, *http.Request, error) { var rCtx = request.Context() if v, ok := rCtx.Value(ctxBoundParams).(*validation); ok { @@ -530,7 +519,7 @@ func (c *Context) NotFound(rw http.ResponseWriter, r *http.Request) { } // Respond renders the response after doing some content negotiation -func (c *Context) Respond(rw http.ResponseWriter, r *http.Request, produces []string, route *MatchedRoute, data interface{}) { +func (c *Context) Respond(rw http.ResponseWriter, r *http.Request, produces []string, route *MatchedRoute, data any) { c.debugLogf("responding to %s %s with produces: %v", r.Method, r.URL.Path, produces) offers := []string{} for _, mt := range produces { diff --git a/vendor/github.com/go-openapi/runtime/middleware/denco/router.go b/vendor/github.com/go-openapi/runtime/middleware/denco/router.go index 21808ede332..b371a2cf84e 100644 --- a/vendor/github.com/go-openapi/runtime/middleware/denco/router.go +++ b/vendor/github.com/go-openapi/runtime/middleware/denco/router.go @@ -1,3 +1,6 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + // Package denco provides fast URL router. package denco @@ -36,14 +39,14 @@ type Router struct { // By default, SizeHint will be determined from given records to Build. SizeHint int - static map[string]interface{} + static map[string]any } // New returns a new Router. func New() *Router { return &Router{ SizeHint: -1, - static: make(map[string]interface{}), + static: make(map[string]any), param: newDoubleArray(), } } @@ -51,7 +54,7 @@ func New() *Router { // Lookup returns data and path parameters that associated with path. // params is a slice of the Param that arranged in the order in which parameters appeared. // e.g. when built routing path is "/path/to/:id/:name" and given path is "/path/to/1/alice". params order is [{"id": "1"}, {"name": "alice"}], not [{"name": "alice"}, {"id": "1"}]. -func (rt *Router) Lookup(path string) (data interface{}, params Params, found bool) { +func (rt *Router) Lookup(path string) (data any, params Params, found bool) { if data, found = rt.static[path]; found { return data, nil, true } @@ -348,7 +351,7 @@ func (da *doubleArray) arrange(records []*record, idx, depth int, usedBase map[i // node represents a node of Double-Array. type node struct { - data interface{} + data any // Names of path parameters. paramNames []string @@ -422,11 +425,11 @@ type Record struct { Key string // Result value for Key. - Value interface{} + Value any } // NewRecord returns a new Record. -func NewRecord(key string, value interface{}) Record { +func NewRecord(key string, value any) Record { return Record{ Key: key, Value: value, diff --git a/vendor/github.com/go-openapi/runtime/middleware/denco/server.go b/vendor/github.com/go-openapi/runtime/middleware/denco/server.go index 0886713c181..8f04d93dba9 100644 --- a/vendor/github.com/go-openapi/runtime/middleware/denco/server.go +++ b/vendor/github.com/go-openapi/runtime/middleware/denco/server.go @@ -1,3 +1,6 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + package denco import ( diff --git a/vendor/github.com/go-openapi/runtime/middleware/denco/util.go b/vendor/github.com/go-openapi/runtime/middleware/denco/util.go index edc1f6ab80a..f002bc4693f 100644 --- a/vendor/github.com/go-openapi/runtime/middleware/denco/util.go +++ b/vendor/github.com/go-openapi/runtime/middleware/denco/util.go @@ -1,3 +1,6 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + package denco // NextSeparator returns an index of next separator in path. diff --git a/vendor/github.com/go-openapi/runtime/middleware/doc.go b/vendor/github.com/go-openapi/runtime/middleware/doc.go index 836a98850d7..04b83223638 100644 --- a/vendor/github.com/go-openapi/runtime/middleware/doc.go +++ b/vendor/github.com/go-openapi/runtime/middleware/doc.go @@ -1,16 +1,5 @@ -// Copyright 2015 go-swagger maintainers -// -// 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. +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 /* Package middleware provides the library with helper functions for serving swagger APIs. diff --git a/vendor/github.com/go-openapi/runtime/middleware/header/header.go b/vendor/github.com/go-openapi/runtime/middleware/header/header.go index 13d7dc31203..6ce870d8936 100644 --- a/vendor/github.com/go-openapi/runtime/middleware/header/header.go +++ b/vendor/github.com/go-openapi/runtime/middleware/header/header.go @@ -1,3 +1,6 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + // Copyright 2013 The Go Authors. All rights reserved. // // Use of this source code is governed by a BSD-style @@ -10,6 +13,7 @@ package header import ( + "maps" "net/http" "strings" "time" @@ -65,9 +69,7 @@ func init() { // Copy returns a shallow copy of the header. func Copy(header http.Header) http.Header { h := make(http.Header) - for k, vs := range header { - h[k] = vs - } + maps.Copy(h, header) return h } diff --git a/vendor/github.com/go-openapi/runtime/middleware/negotiate.go b/vendor/github.com/go-openapi/runtime/middleware/negotiate.go index d25d58cf3a3..cb0a85283c1 100644 --- a/vendor/github.com/go-openapi/runtime/middleware/negotiate.go +++ b/vendor/github.com/go-openapi/runtime/middleware/negotiate.go @@ -1,3 +1,6 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + // Copyright 2013 The Go Authors. All rights reserved. // // Use of this source code is governed by a BSD-style diff --git a/vendor/github.com/go-openapi/runtime/middleware/not_implemented.go b/vendor/github.com/go-openapi/runtime/middleware/not_implemented.go index bc6942a0f1b..2e63780c70b 100644 --- a/vendor/github.com/go-openapi/runtime/middleware/not_implemented.go +++ b/vendor/github.com/go-openapi/runtime/middleware/not_implemented.go @@ -1,16 +1,5 @@ -// Copyright 2015 go-swagger maintainers -// -// 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. +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 package middleware @@ -22,7 +11,7 @@ import ( type errorResp struct { code int - response interface{} + response any headers http.Header } @@ -49,7 +38,7 @@ func NotImplemented(message string) Responder { // Error creates a generic responder for returning errors, the data will be serialized // with the matching producer for the request -func Error(code int, data interface{}, headers ...http.Header) Responder { +func Error(code int, data any, headers ...http.Header) Responder { var hdr http.Header for _, h := range headers { for k, v := range h { diff --git a/vendor/github.com/go-openapi/runtime/middleware/operation.go b/vendor/github.com/go-openapi/runtime/middleware/operation.go index 1175a63cf29..2a7ab1fadaf 100644 --- a/vendor/github.com/go-openapi/runtime/middleware/operation.go +++ b/vendor/github.com/go-openapi/runtime/middleware/operation.go @@ -1,16 +1,5 @@ -// Copyright 2015 go-swagger maintainers -// -// 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. +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 package middleware diff --git a/vendor/github.com/go-openapi/runtime/middleware/parameter.go b/vendor/github.com/go-openapi/runtime/middleware/parameter.go index 5301b4c3340..7d630d6cce6 100644 --- a/vendor/github.com/go-openapi/runtime/middleware/parameter.go +++ b/vendor/github.com/go-openapi/runtime/middleware/parameter.go @@ -1,16 +1,5 @@ -// Copyright 2015 go-swagger maintainers -// -// 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. +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 package middleware @@ -192,34 +181,34 @@ func (p *untypedParamBinder) Bind(request *http.Request, routeParams RouteParams func (p *untypedParamBinder) typeForSchema(tpe, format string, items *spec.Items) reflect.Type { switch tpe { case "boolean": - return reflect.TypeOf(true) + return reflect.TypeFor[bool]() case typeString: if tt, ok := p.formats.GetType(format); ok { return tt } - return reflect.TypeOf("") + return reflect.TypeFor[string]() case "integer": switch format { case "int8": - return reflect.TypeOf(int8(0)) + return reflect.TypeFor[int8]() case "int16": - return reflect.TypeOf(int16(0)) + return reflect.TypeFor[int16]() case "int32": - return reflect.TypeOf(int32(0)) + return reflect.TypeFor[int32]() case "int64": - return reflect.TypeOf(int64(0)) + return reflect.TypeFor[int64]() default: - return reflect.TypeOf(int64(0)) + return reflect.TypeFor[int64]() } case "number": switch format { case "float": - return reflect.TypeOf(float32(0)) + return reflect.TypeFor[float32]() case "double": - return reflect.TypeOf(float64(0)) + return reflect.TypeFor[float64]() } case typeArray: @@ -233,10 +222,10 @@ func (p *untypedParamBinder) typeForSchema(tpe, format string, items *spec.Items return reflect.MakeSlice(reflect.SliceOf(itemsType), 0, 0).Type() case "file": - return reflect.TypeOf(&runtime.File{}).Elem() + return reflect.TypeFor[runtime.File]() case "object": - return reflect.TypeOf(map[string]interface{}{}) + return reflect.TypeFor[map[string]any]() } return nil } @@ -279,7 +268,7 @@ func (p *untypedParamBinder) bindValue(data []string, hasKey bool, target reflec return p.setFieldValue(target, p.parameter.Default, d, hasKey) } -func (p *untypedParamBinder) setFieldValue(target reflect.Value, defaultValue interface{}, data string, hasKey bool) error { //nolint:gocyclo +func (p *untypedParamBinder) setFieldValue(target reflect.Value, defaultValue any, data string, hasKey bool) error { //nolint:gocyclo tpe := p.parameter.Type if p.parameter.Format != "" { tpe = p.parameter.Format @@ -341,7 +330,7 @@ func (p *untypedParamBinder) setFieldValue(target reflect.Value, defaultValue in case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: if data == "" { if target.CanSet() { - rd := defVal.Convert(reflect.TypeOf(int64(0))) + rd := defVal.Convert(reflect.TypeFor[int64]()) target.SetInt(rd.Int()) } return nil @@ -360,7 +349,7 @@ func (p *untypedParamBinder) setFieldValue(target reflect.Value, defaultValue in case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: if data == "" { if target.CanSet() { - rd := defVal.Convert(reflect.TypeOf(uint64(0))) + rd := defVal.Convert(reflect.TypeFor[uint64]()) target.SetUint(rd.Uint()) } return nil @@ -379,7 +368,7 @@ func (p *untypedParamBinder) setFieldValue(target reflect.Value, defaultValue in case reflect.Float32, reflect.Float64: if data == "" { if target.CanSet() { - rd := defVal.Convert(reflect.TypeOf(float64(0))) + rd := defVal.Convert(reflect.TypeFor[float64]()) target.SetFloat(rd.Float()) } return nil @@ -426,7 +415,7 @@ func (p *untypedParamBinder) setFieldValue(target reflect.Value, defaultValue in return nil } -func (p *untypedParamBinder) tryUnmarshaler(target reflect.Value, defaultValue interface{}, data string) (bool, error) { +func (p *untypedParamBinder) tryUnmarshaler(target reflect.Value, defaultValue any, data string) (bool, error) { if !target.CanSet() { return false, nil } @@ -458,7 +447,7 @@ func (p *untypedParamBinder) readFormattedSliceFieldValue(data string, target re return stringutils.SplitByFormat(data, p.parameter.CollectionFormat), false, nil } -func (p *untypedParamBinder) setSliceFieldValue(target reflect.Value, defaultValue interface{}, data []string, hasKey bool) error { +func (p *untypedParamBinder) setSliceFieldValue(target reflect.Value, defaultValue any, data []string, hasKey bool) error { sz := len(data) if (!hasKey || (!p.parameter.AllowEmptyValue && (sz == 0 || (sz == 1 && data[0] == "")))) && p.parameter.Required && defaultValue == nil { return errors.Required(p.Name, p.parameter.In, data) diff --git a/vendor/github.com/go-openapi/runtime/middleware/rapidoc.go b/vendor/github.com/go-openapi/runtime/middleware/rapidoc.go index ef75e7441fc..6039a26f33e 100644 --- a/vendor/github.com/go-openapi/runtime/middleware/rapidoc.go +++ b/vendor/github.com/go-openapi/runtime/middleware/rapidoc.go @@ -1,3 +1,6 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + package middleware import ( diff --git a/vendor/github.com/go-openapi/runtime/middleware/redoc.go b/vendor/github.com/go-openapi/runtime/middleware/redoc.go index b96b01e7f3f..cbaec73c438 100644 --- a/vendor/github.com/go-openapi/runtime/middleware/redoc.go +++ b/vendor/github.com/go-openapi/runtime/middleware/redoc.go @@ -1,3 +1,6 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + package middleware import ( diff --git a/vendor/github.com/go-openapi/runtime/middleware/request.go b/vendor/github.com/go-openapi/runtime/middleware/request.go index 577e4a0f107..52facfefcd2 100644 --- a/vendor/github.com/go-openapi/runtime/middleware/request.go +++ b/vendor/github.com/go-openapi/runtime/middleware/request.go @@ -1,16 +1,5 @@ -// Copyright 2015 go-swagger maintainers -// -// 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. +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 package middleware @@ -50,7 +39,7 @@ func NewUntypedRequestBinder(parameters map[string]spec.Parameter, spec *spec.Sw } // Bind perform the databinding and validation -func (o *UntypedRequestBinder) Bind(request *http.Request, routeParams RouteParams, consumer runtime.Consumer, data interface{}) error { +func (o *UntypedRequestBinder) Bind(request *http.Request, routeParams RouteParams, consumer runtime.Consumer, data any) error { val := reflect.Indirect(reflect.ValueOf(data)) isMap := val.Kind() == reflect.Map var result []error @@ -68,9 +57,9 @@ func (o *UntypedRequestBinder) Bind(request *http.Request, routeParams RoutePara tpe := binder.Type() if tpe == nil { if param.Schema.Type.Contains(typeArray) { - tpe = reflect.TypeOf([]interface{}{}) + tpe = reflect.TypeFor[[]any]() } else { - tpe = reflect.TypeOf(map[string]interface{}{}) + tpe = reflect.TypeFor[map[string]any]() } } target = reflect.Indirect(reflect.New(tpe)) diff --git a/vendor/github.com/go-openapi/runtime/middleware/router.go b/vendor/github.com/go-openapi/runtime/middleware/router.go index 0f9317903c7..16816580da8 100644 --- a/vendor/github.com/go-openapi/runtime/middleware/router.go +++ b/vendor/github.com/go-openapi/runtime/middleware/router.go @@ -1,16 +1,5 @@ -// Copyright 2015 go-swagger maintainers -// -// 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. +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 package middleware @@ -208,13 +197,13 @@ func (ra *RouteAuthenticator) CommonScopes() []string { } // Authenticate Authenticator interface implementation -func (ra *RouteAuthenticator) Authenticate(req *http.Request, route *MatchedRoute) (bool, interface{}, error) { +func (ra *RouteAuthenticator) Authenticate(req *http.Request, route *MatchedRoute) (bool, any, error) { if ra.allowAnonymous { route.Authenticator = ra return true, nil, nil } // iterate in proper order - var lastResult interface{} + var lastResult any for _, scheme := range ra.Schemes { if authenticator, ok := ra.Authenticator[scheme]; ok { applies, princ, err := authenticator.Authenticate(&security.ScopedAuthRequest{ @@ -287,7 +276,7 @@ func (ras RouteAuthenticators) AllowsAnonymous() bool { } // Authenticate method implemention so this collection can be used as authenticator -func (ras RouteAuthenticators) Authenticate(req *http.Request, route *MatchedRoute) (bool, interface{}, error) { +func (ras RouteAuthenticators) Authenticate(req *http.Request, route *MatchedRoute) (bool, any, error) { var lastError error var allowsAnon bool var anonAuth RouteAuthenticator diff --git a/vendor/github.com/go-openapi/runtime/middleware/security.go b/vendor/github.com/go-openapi/runtime/middleware/security.go index 2b061caefcb..37ecfa6fd4e 100644 --- a/vendor/github.com/go-openapi/runtime/middleware/security.go +++ b/vendor/github.com/go-openapi/runtime/middleware/security.go @@ -1,16 +1,5 @@ -// Copyright 2015 go-swagger maintainers -// -// 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. +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 package middleware diff --git a/vendor/github.com/go-openapi/runtime/middleware/spec.go b/vendor/github.com/go-openapi/runtime/middleware/spec.go index 87e17e34249..9cc9940aaa5 100644 --- a/vendor/github.com/go-openapi/runtime/middleware/spec.go +++ b/vendor/github.com/go-openapi/runtime/middleware/spec.go @@ -1,16 +1,5 @@ -// Copyright 2015 go-swagger maintainers -// -// 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. +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 package middleware diff --git a/vendor/github.com/go-openapi/runtime/middleware/swaggerui.go b/vendor/github.com/go-openapi/runtime/middleware/swaggerui.go index ec3c10cbafa..b25a3a2cff7 100644 --- a/vendor/github.com/go-openapi/runtime/middleware/swaggerui.go +++ b/vendor/github.com/go-openapi/runtime/middleware/swaggerui.go @@ -1,3 +1,6 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + package middleware import ( diff --git a/vendor/github.com/go-openapi/runtime/middleware/swaggerui_oauth2.go b/vendor/github.com/go-openapi/runtime/middleware/swaggerui_oauth2.go index e81212f71c8..879bdbaadea 100644 --- a/vendor/github.com/go-openapi/runtime/middleware/swaggerui_oauth2.go +++ b/vendor/github.com/go-openapi/runtime/middleware/swaggerui_oauth2.go @@ -1,3 +1,6 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + package middleware import ( diff --git a/vendor/github.com/go-openapi/runtime/middleware/ui_options.go b/vendor/github.com/go-openapi/runtime/middleware/ui_options.go index 7a5fb16f633..cf2f673d3cb 100644 --- a/vendor/github.com/go-openapi/runtime/middleware/ui_options.go +++ b/vendor/github.com/go-openapi/runtime/middleware/ui_options.go @@ -1,3 +1,6 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + package middleware import ( @@ -39,7 +42,7 @@ type uiOptions struct { // toCommonUIOptions converts any UI option type to retain the common options. // // This uses gob encoding/decoding to convert common fields from one struct to another. -func toCommonUIOptions(opts interface{}) uiOptions { +func toCommonUIOptions(opts any) uiOptions { var buf bytes.Buffer enc := gob.NewEncoder(&buf) dec := gob.NewDecoder(&buf) diff --git a/vendor/github.com/go-openapi/runtime/middleware/untyped/api.go b/vendor/github.com/go-openapi/runtime/middleware/untyped/api.go index a98d6690a4f..774da0ba0c8 100644 --- a/vendor/github.com/go-openapi/runtime/middleware/untyped/api.go +++ b/vendor/github.com/go-openapi/runtime/middleware/untyped/api.go @@ -1,16 +1,5 @@ -// Copyright 2015 go-swagger maintainers -// -// 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. +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 package untyped diff --git a/vendor/github.com/go-openapi/runtime/middleware/validation.go b/vendor/github.com/go-openapi/runtime/middleware/validation.go index 3879d754ee7..ed026d626ba 100644 --- a/vendor/github.com/go-openapi/runtime/middleware/validation.go +++ b/vendor/github.com/go-openapi/runtime/middleware/validation.go @@ -1,16 +1,5 @@ -// Copyright 2015 go-swagger maintainers -// -// 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. +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 package middleware diff --git a/vendor/github.com/go-openapi/runtime/request.go b/vendor/github.com/go-openapi/runtime/request.go index 203dab2f1d0..aab7b8c055a 100644 --- a/vendor/github.com/go-openapi/runtime/request.go +++ b/vendor/github.com/go-openapi/runtime/request.go @@ -1,16 +1,5 @@ -// Copyright 2015 go-swagger maintainers -// -// 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. +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 package runtime diff --git a/vendor/github.com/go-openapi/runtime/security/authenticator.go b/vendor/github.com/go-openapi/runtime/security/authenticator.go index def3746e20c..b5b7904dc1e 100644 --- a/vendor/github.com/go-openapi/runtime/security/authenticator.go +++ b/vendor/github.com/go-openapi/runtime/security/authenticator.go @@ -1,16 +1,5 @@ -// Copyright 2015 go-swagger maintainers -// -// 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. +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 package security @@ -31,8 +20,8 @@ const ( ) // HttpAuthenticator is a function that authenticates a HTTP request -func HttpAuthenticator(handler func(*http.Request) (bool, interface{}, error)) runtime.Authenticator { //nolint:revive - return runtime.AuthenticatorFunc(func(params interface{}) (bool, interface{}, error) { +func HttpAuthenticator(handler func(*http.Request) (bool, any, error)) runtime.Authenticator { //nolint:revive + return runtime.AuthenticatorFunc(func(params any) (bool, any, error) { if request, ok := params.(*http.Request); ok { return handler(request) } @@ -44,8 +33,8 @@ func HttpAuthenticator(handler func(*http.Request) (bool, interface{}, error)) r } // ScopedAuthenticator is a function that authenticates a HTTP request against a list of valid scopes -func ScopedAuthenticator(handler func(*ScopedAuthRequest) (bool, interface{}, error)) runtime.Authenticator { - return runtime.AuthenticatorFunc(func(params interface{}) (bool, interface{}, error) { +func ScopedAuthenticator(handler func(*ScopedAuthRequest) (bool, any, error)) runtime.Authenticator { + return runtime.AuthenticatorFunc(func(params any) (bool, any, error) { if request, ok := params.(*ScopedAuthRequest); ok { return handler(request) } @@ -54,22 +43,22 @@ func ScopedAuthenticator(handler func(*ScopedAuthRequest) (bool, interface{}, er } // UserPassAuthentication authentication function -type UserPassAuthentication func(string, string) (interface{}, error) +type UserPassAuthentication func(string, string) (any, error) // UserPassAuthenticationCtx authentication function with context.Context -type UserPassAuthenticationCtx func(context.Context, string, string) (context.Context, interface{}, error) +type UserPassAuthenticationCtx func(context.Context, string, string) (context.Context, any, error) // TokenAuthentication authentication function -type TokenAuthentication func(string) (interface{}, error) +type TokenAuthentication func(string) (any, error) // TokenAuthenticationCtx authentication function with context.Context -type TokenAuthenticationCtx func(context.Context, string) (context.Context, interface{}, error) +type TokenAuthenticationCtx func(context.Context, string) (context.Context, any, error) // ScopedTokenAuthentication authentication function -type ScopedTokenAuthentication func(string, []string) (interface{}, error) +type ScopedTokenAuthentication func(string, []string) (any, error) // ScopedTokenAuthenticationCtx authentication function with context.Context -type ScopedTokenAuthenticationCtx func(context.Context, string, []string) (context.Context, interface{}, error) +type ScopedTokenAuthenticationCtx func(context.Context, string, []string) (context.Context, any, error) var DefaultRealmName = "API" @@ -115,7 +104,7 @@ func BasicAuthRealm(realm string, authenticate UserPassAuthentication) runtime.A realm = DefaultRealmName } - return HttpAuthenticator(func(r *http.Request) (bool, interface{}, error) { + return HttpAuthenticator(func(r *http.Request) (bool, any, error) { if usr, pass, ok := r.BasicAuth(); ok { p, err := authenticate(usr, pass) if err != nil { @@ -139,7 +128,7 @@ func BasicAuthRealmCtx(realm string, authenticate UserPassAuthenticationCtx) run realm = DefaultRealmName } - return HttpAuthenticator(func(r *http.Request) (bool, interface{}, error) { + return HttpAuthenticator(func(r *http.Request) (bool, any, error) { if usr, pass, ok := r.BasicAuth(); ok { ctx, p, err := authenticate(r.Context(), usr, pass) if err != nil { @@ -170,7 +159,7 @@ func APIKeyAuth(name, in string, authenticate TokenAuthentication) runtime.Authe getToken = func(r *http.Request) string { return r.URL.Query().Get(name) } } - return HttpAuthenticator(func(r *http.Request) (bool, interface{}, error) { + return HttpAuthenticator(func(r *http.Request) (bool, any, error) { token := getToken(r) if token == "" { return false, nil, nil @@ -198,7 +187,7 @@ func APIKeyAuthCtx(name, in string, authenticate TokenAuthenticationCtx) runtime getToken = func(r *http.Request) string { return r.URL.Query().Get(name) } } - return HttpAuthenticator(func(r *http.Request) (bool, interface{}, error) { + return HttpAuthenticator(func(r *http.Request) (bool, any, error) { token := getToken(r) if token == "" { return false, nil, nil @@ -219,11 +208,11 @@ type ScopedAuthRequest struct { // BearerAuth for use with oauth2 flows func BearerAuth(name string, authenticate ScopedTokenAuthentication) runtime.Authenticator { const prefix = "Bearer " - return ScopedAuthenticator(func(r *ScopedAuthRequest) (bool, interface{}, error) { + return ScopedAuthenticator(func(r *ScopedAuthRequest) (bool, any, error) { var token string hdr := r.Request.Header.Get(runtime.HeaderAuthorization) - if strings.HasPrefix(hdr, prefix) { - token = strings.TrimPrefix(hdr, prefix) + if after, ok := strings.CutPrefix(hdr, prefix); ok { + token = after } if token == "" { qs := r.Request.URL.Query() @@ -249,11 +238,11 @@ func BearerAuth(name string, authenticate ScopedTokenAuthentication) runtime.Aut // BearerAuthCtx for use with oauth2 flows with support for context.Context. func BearerAuthCtx(name string, authenticate ScopedTokenAuthenticationCtx) runtime.Authenticator { const prefix = "Bearer " - return ScopedAuthenticator(func(r *ScopedAuthRequest) (bool, interface{}, error) { + return ScopedAuthenticator(func(r *ScopedAuthRequest) (bool, any, error) { var token string hdr := r.Request.Header.Get(runtime.HeaderAuthorization) - if strings.HasPrefix(hdr, prefix) { - token = strings.TrimPrefix(hdr, prefix) + if after, ok := strings.CutPrefix(hdr, prefix); ok { + token = after } if token == "" { qs := r.Request.URL.Query() diff --git a/vendor/github.com/go-openapi/runtime/security/authorizer.go b/vendor/github.com/go-openapi/runtime/security/authorizer.go index 00c1a4d6a4c..69bd497a3c2 100644 --- a/vendor/github.com/go-openapi/runtime/security/authorizer.go +++ b/vendor/github.com/go-openapi/runtime/security/authorizer.go @@ -1,16 +1,5 @@ -// Copyright 2015 go-swagger maintainers -// -// 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. +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 package security @@ -23,5 +12,5 @@ import ( // Authorized provides a default implementation of the Authorizer interface where all // requests are authorized (successful) func Authorized() runtime.Authorizer { - return runtime.AuthorizerFunc(func(_ *http.Request, _ interface{}) error { return nil }) + return runtime.AuthorizerFunc(func(_ *http.Request, _ any) error { return nil }) } diff --git a/vendor/github.com/go-openapi/runtime/statuses.go b/vendor/github.com/go-openapi/runtime/statuses.go index 3b011a0bff1..7e10a5a56c2 100644 --- a/vendor/github.com/go-openapi/runtime/statuses.go +++ b/vendor/github.com/go-openapi/runtime/statuses.go @@ -1,16 +1,5 @@ -// Copyright 2015 go-swagger maintainers -// -// 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. +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 package runtime diff --git a/vendor/github.com/go-openapi/runtime/text.go b/vendor/github.com/go-openapi/runtime/text.go index d8dee9410cb..2b8e4ac09d0 100644 --- a/vendor/github.com/go-openapi/runtime/text.go +++ b/vendor/github.com/go-openapi/runtime/text.go @@ -1,16 +1,5 @@ -// Copyright 2015 go-swagger maintainers -// -// 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. +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 package runtime @@ -27,7 +16,7 @@ import ( // TextConsumer creates a new text consumer func TextConsumer() Consumer { - return ConsumerFunc(func(reader io.Reader, data interface{}) error { + return ConsumerFunc(func(reader io.Reader, data any) error { if reader == nil { return errors.New("TextConsumer requires a reader") // early exit } @@ -69,7 +58,7 @@ func TextConsumer() Consumer { // TextProducer creates a new text producer func TextProducer() Producer { - return ProducerFunc(func(writer io.Writer, data interface{}) error { + return ProducerFunc(func(writer io.Writer, data any) error { if writer == nil { return errors.New("TextProducer requires a writer") // early exit } diff --git a/vendor/github.com/go-openapi/runtime/values.go b/vendor/github.com/go-openapi/runtime/values.go index 11f5732af4e..19894e78451 100644 --- a/vendor/github.com/go-openapi/runtime/values.go +++ b/vendor/github.com/go-openapi/runtime/values.go @@ -1,3 +1,6 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + package runtime // Values typically represent parameters on a http request. diff --git a/vendor/github.com/go-openapi/runtime/xml.go b/vendor/github.com/go-openapi/runtime/xml.go index 821c7393dfb..5060b5c8e91 100644 --- a/vendor/github.com/go-openapi/runtime/xml.go +++ b/vendor/github.com/go-openapi/runtime/xml.go @@ -1,16 +1,5 @@ -// Copyright 2015 go-swagger maintainers -// -// 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. +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 package runtime @@ -21,7 +10,7 @@ import ( // XMLConsumer creates a new XML consumer func XMLConsumer() Consumer { - return ConsumerFunc(func(reader io.Reader, data interface{}) error { + return ConsumerFunc(func(reader io.Reader, data any) error { dec := xml.NewDecoder(reader) return dec.Decode(data) }) @@ -29,7 +18,7 @@ func XMLConsumer() Consumer { // XMLProducer creates a new XML producer func XMLProducer() Producer { - return ProducerFunc(func(writer io.Writer, data interface{}) error { + return ProducerFunc(func(writer io.Writer, data any) error { enc := xml.NewEncoder(writer) return enc.Encode(data) }) diff --git a/vendor/github.com/go-openapi/runtime/yamlpc/yaml.go b/vendor/github.com/go-openapi/runtime/yamlpc/yaml.go index 467408c4f66..ca63430e0b7 100644 --- a/vendor/github.com/go-openapi/runtime/yamlpc/yaml.go +++ b/vendor/github.com/go-openapi/runtime/yamlpc/yaml.go @@ -1,16 +1,5 @@ -// Copyright 2015 go-swagger maintainers -// -// 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. +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 package yamlpc diff --git a/vendor/github.com/go-openapi/spec/.golangci.yml b/vendor/github.com/go-openapi/spec/.golangci.yml index 7cea1af8b52..1ad5adf47e6 100644 --- a/vendor/github.com/go-openapi/spec/.golangci.yml +++ b/vendor/github.com/go-openapi/spec/.golangci.yml @@ -16,7 +16,7 @@ linters: - godox - gosmopolitan - inamedparam - #- intrange # disabled while < go1.22 + - intrange - ireturn - lll - musttag diff --git a/vendor/github.com/go-openapi/spec/README.md b/vendor/github.com/go-openapi/spec/README.md index 7fd2810c698..3203bd2556d 100644 --- a/vendor/github.com/go-openapi/spec/README.md +++ b/vendor/github.com/go-openapi/spec/README.md @@ -7,6 +7,10 @@ The object model for OpenAPI specification documents. +## Licensing + +This library ships under the [SPDX-License-Identifier: Apache-2.0](./LICENSE). + ### FAQ * What does this do? diff --git a/vendor/github.com/go-openapi/spec/cache.go b/vendor/github.com/go-openapi/spec/cache.go index 122993b44b4..10fba77a839 100644 --- a/vendor/github.com/go-openapi/spec/cache.go +++ b/vendor/github.com/go-openapi/spec/cache.go @@ -1,40 +1,28 @@ -// Copyright 2015 go-swagger maintainers -// -// 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. +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 package spec import ( + "maps" "sync" ) // ResolutionCache a cache for resolving urls type ResolutionCache interface { - Get(string) (interface{}, bool) - Set(string, interface{}) + Get(string) (any, bool) + Set(string, any) } type simpleCache struct { lock sync.RWMutex - store map[string]interface{} + store map[string]any } func (s *simpleCache) ShallowClone() ResolutionCache { - store := make(map[string]interface{}, len(s.store)) + store := make(map[string]any, len(s.store)) s.lock.RLock() - for k, v := range s.store { - store[k] = v - } + maps.Copy(store, s.store) s.lock.RUnlock() return &simpleCache{ @@ -43,7 +31,7 @@ func (s *simpleCache) ShallowClone() ResolutionCache { } // Get retrieves a cached URI -func (s *simpleCache) Get(uri string) (interface{}, bool) { +func (s *simpleCache) Get(uri string) (any, bool) { s.lock.RLock() v, ok := s.store[uri] @@ -52,7 +40,7 @@ func (s *simpleCache) Get(uri string) (interface{}, bool) { } // Set caches a URI -func (s *simpleCache) Set(uri string, data interface{}) { +func (s *simpleCache) Set(uri string, data any) { s.lock.Lock() s.store[uri] = data s.lock.Unlock() @@ -80,7 +68,7 @@ func initResolutionCache() { } func defaultResolutionCache() *simpleCache { - return &simpleCache{store: map[string]interface{}{ + return &simpleCache{store: map[string]any{ "http://swagger.io/v2/schema.json": MustLoadSwagger20Schema(), "http://json-schema.org/draft-04/schema": MustLoadJSONSchemaDraft04(), }} diff --git a/vendor/github.com/go-openapi/spec/contact_info.go b/vendor/github.com/go-openapi/spec/contact_info.go index 3eaa41e4aab..fafe639b45d 100644 --- a/vendor/github.com/go-openapi/spec/contact_info.go +++ b/vendor/github.com/go-openapi/spec/contact_info.go @@ -1,16 +1,5 @@ -// Copyright 2015 go-swagger maintainers -// -// 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. +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 package spec diff --git a/vendor/github.com/go-openapi/spec/debug.go b/vendor/github.com/go-openapi/spec/debug.go index fc889f6d0b0..f4316c26333 100644 --- a/vendor/github.com/go-openapi/spec/debug.go +++ b/vendor/github.com/go-openapi/spec/debug.go @@ -1,16 +1,5 @@ -// Copyright 2015 go-swagger maintainers -// -// 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. +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 package spec @@ -40,7 +29,7 @@ func debugOptions() { specLogger = log.New(os.Stdout, "spec:", log.LstdFlags) } -func debugLog(msg string, args ...interface{}) { +func debugLog(msg string, args ...any) { // A private, trivial trace logger, based on go-openapi/spec/expander.go:debugLog() if Debug { _, file1, pos1, _ := runtime.Caller(1) diff --git a/vendor/github.com/go-openapi/spec/embed.go b/vendor/github.com/go-openapi/spec/embed.go index 1f4284750ab..0d0b69996cc 100644 --- a/vendor/github.com/go-openapi/spec/embed.go +++ b/vendor/github.com/go-openapi/spec/embed.go @@ -1,3 +1,6 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + package spec import ( diff --git a/vendor/github.com/go-openapi/spec/errors.go b/vendor/github.com/go-openapi/spec/errors.go index 718b4aecc32..e39ab8bf71e 100644 --- a/vendor/github.com/go-openapi/spec/errors.go +++ b/vendor/github.com/go-openapi/spec/errors.go @@ -1,3 +1,6 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + package spec import "errors" diff --git a/vendor/github.com/go-openapi/spec/expander.go b/vendor/github.com/go-openapi/spec/expander.go index df936b312e7..cc4bd1cba1b 100644 --- a/vendor/github.com/go-openapi/spec/expander.go +++ b/vendor/github.com/go-openapi/spec/expander.go @@ -1,16 +1,5 @@ -// Copyright 2015 go-swagger maintainers -// -// 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. +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 package spec @@ -104,7 +93,7 @@ const rootBase = ".root" // baseForRoot loads in the cache the root document and produces a fake ".root" base path entry // for further $ref resolution -func baseForRoot(root interface{}, cache ResolutionCache) string { +func baseForRoot(root any, cache ResolutionCache) string { // cache the root document to resolve $ref's normalizedBase := normalizeBase(rootBase) @@ -116,7 +105,7 @@ func baseForRoot(root interface{}, cache ResolutionCache) string { return normalizedBase } - root = map[string]interface{}{} + root = map[string]any{} } cache.Set(normalizedBase, root) @@ -132,7 +121,7 @@ func baseForRoot(root interface{}, cache ResolutionCache) string { // (use ExpandSchemaWithBasePath to resolve external references). // // Setting the cache is optional and this parameter may safely be left to nil. -func ExpandSchema(schema *Schema, root interface{}, cache ResolutionCache) error { +func ExpandSchema(schema *Schema, root any, cache ResolutionCache) error { cache = cacheOrDefault(cache) if root == nil { root = schema @@ -463,7 +452,7 @@ func expandOperation(op *Operation, resolver *schemaLoader, basePath string) err // (use ExpandResponse to resolve external references). // // Setting the cache is optional and this parameter may safely be left to nil. -func ExpandResponseWithRoot(response *Response, root interface{}, cache ResolutionCache) error { +func ExpandResponseWithRoot(response *Response, root any, cache ResolutionCache) error { cache = cacheOrDefault(cache) opts := &ExpandOptions{ RelativeBase: baseForRoot(root, cache), @@ -489,7 +478,7 @@ func ExpandResponse(response *Response, basePath string) error { // // Notice that it is impossible to reference a json schema in a different document other than root // (use ExpandParameter to resolve external references). -func ExpandParameterWithRoot(parameter *Parameter, root interface{}, cache ResolutionCache) error { +func ExpandParameterWithRoot(parameter *Parameter, root any, cache ResolutionCache) error { cache = cacheOrDefault(cache) opts := &ExpandOptions{ @@ -512,7 +501,7 @@ func ExpandParameter(parameter *Parameter, basePath string) error { return expandParameterOrResponse(parameter, resolver, opts.RelativeBase) } -func getRefAndSchema(input interface{}) (*Ref, *Schema, error) { +func getRefAndSchema(input any) (*Ref, *Schema, error) { var ( ref *Ref sch *Schema @@ -538,7 +527,7 @@ func getRefAndSchema(input interface{}) (*Ref, *Schema, error) { return ref, sch, nil } -func expandParameterOrResponse(input interface{}, resolver *schemaLoader, basePath string) error { +func expandParameterOrResponse(input any, resolver *schemaLoader, basePath string) error { ref, sch, err := getRefAndSchema(input) if err != nil { return err diff --git a/vendor/github.com/go-openapi/spec/external_docs.go b/vendor/github.com/go-openapi/spec/external_docs.go index 88add91b2b8..17b8efbf100 100644 --- a/vendor/github.com/go-openapi/spec/external_docs.go +++ b/vendor/github.com/go-openapi/spec/external_docs.go @@ -1,16 +1,5 @@ -// Copyright 2015 go-swagger maintainers -// -// 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. +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 package spec diff --git a/vendor/github.com/go-openapi/spec/header.go b/vendor/github.com/go-openapi/spec/header.go index 55c415e6c24..ab251ef7659 100644 --- a/vendor/github.com/go-openapi/spec/header.go +++ b/vendor/github.com/go-openapi/spec/header.go @@ -1,16 +1,5 @@ -// Copyright 2015 go-swagger maintainers -// -// 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. +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 package spec @@ -68,7 +57,7 @@ func (h *Header) CollectionOf(items *Items, format string) *Header { } // WithDefault sets the default value on this item -func (h *Header) WithDefault(defaultValue interface{}) *Header { +func (h *Header) WithDefault(defaultValue any) *Header { h.Default = defaultValue return h } @@ -112,8 +101,8 @@ func (h *Header) WithMinimum(minimum float64, exclusive bool) *Header { } // WithEnum sets a the enum values (replace) -func (h *Header) WithEnum(values ...interface{}) *Header { - h.Enum = append([]interface{}{}, values...) +func (h *Header) WithEnum(values ...any) *Header { + h.Enum = append([]any{}, values...) return h } @@ -179,7 +168,7 @@ func (h *Header) UnmarshalJSON(data []byte) error { } // JSONLookup look up a value by the json property name -func (h Header) JSONLookup(token string) (interface{}, error) { +func (h Header) JSONLookup(token string) (any, error) { if ex, ok := h.Extensions[token]; ok { return &ex, nil } diff --git a/vendor/github.com/go-openapi/spec/info.go b/vendor/github.com/go-openapi/spec/info.go index 695cd9a2818..9401065bbde 100644 --- a/vendor/github.com/go-openapi/spec/info.go +++ b/vendor/github.com/go-openapi/spec/info.go @@ -1,16 +1,5 @@ -// Copyright 2015 go-swagger maintainers -// -// 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. +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 package spec @@ -24,10 +13,10 @@ import ( ) // Extensions vendor specific extensions -type Extensions map[string]interface{} +type Extensions map[string]any // Add adds a value to these extensions -func (e Extensions) Add(key string, value interface{}) { +func (e Extensions) Add(key string, value any) { realKey := strings.ToLower(key) e[realKey] = value } @@ -71,7 +60,7 @@ func (e Extensions) GetBool(key string) (bool, bool) { // GetStringSlice gets a string value from the extensions func (e Extensions) GetStringSlice(key string) ([]string, bool) { if v, ok := e[strings.ToLower(key)]; ok { - arr, isSlice := v.([]interface{}) + arr, isSlice := v.([]any) if !isSlice { return nil, false } @@ -94,19 +83,19 @@ type VendorExtensible struct { } // AddExtension adds an extension to this extensible object -func (v *VendorExtensible) AddExtension(key string, value interface{}) { +func (v *VendorExtensible) AddExtension(key string, value any) { if value == nil { return } if v.Extensions == nil { - v.Extensions = make(map[string]interface{}) + v.Extensions = make(map[string]any) } v.Extensions.Add(key, value) } // MarshalJSON marshals the extensions to json func (v VendorExtensible) MarshalJSON() ([]byte, error) { - toser := make(map[string]interface{}) + toser := make(map[string]any) for k, v := range v.Extensions { lk := strings.ToLower(k) if strings.HasPrefix(lk, "x-") { @@ -118,7 +107,7 @@ func (v VendorExtensible) MarshalJSON() ([]byte, error) { // UnmarshalJSON for this extensible object func (v *VendorExtensible) UnmarshalJSON(data []byte) error { - var d map[string]interface{} + var d map[string]any if err := json.Unmarshal(data, &d); err != nil { return err } @@ -126,7 +115,7 @@ func (v *VendorExtensible) UnmarshalJSON(data []byte) error { lk := strings.ToLower(k) if strings.HasPrefix(lk, "x-") { if v.Extensions == nil { - v.Extensions = map[string]interface{}{} + v.Extensions = map[string]any{} } v.Extensions[k] = vv } @@ -154,7 +143,7 @@ type Info struct { } // JSONLookup look up a value by the json property name -func (i Info) JSONLookup(token string) (interface{}, error) { +func (i Info) JSONLookup(token string) (any, error) { if ex, ok := i.Extensions[token]; ok { return &ex, nil } diff --git a/vendor/github.com/go-openapi/spec/items.go b/vendor/github.com/go-openapi/spec/items.go index 0224673c547..d30ca3569b1 100644 --- a/vendor/github.com/go-openapi/spec/items.go +++ b/vendor/github.com/go-openapi/spec/items.go @@ -1,16 +1,5 @@ -// Copyright 2015 go-swagger maintainers -// -// 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. +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 package spec @@ -28,13 +17,13 @@ const ( // SimpleSchema describe swagger simple schemas for parameters and headers type SimpleSchema struct { - Type string `json:"type,omitempty"` - Nullable bool `json:"nullable,omitempty"` - Format string `json:"format,omitempty"` - Items *Items `json:"items,omitempty"` - CollectionFormat string `json:"collectionFormat,omitempty"` - Default interface{} `json:"default,omitempty"` - Example interface{} `json:"example,omitempty"` + Type string `json:"type,omitempty"` + Nullable bool `json:"nullable,omitempty"` + Format string `json:"format,omitempty"` + Items *Items `json:"items,omitempty"` + CollectionFormat string `json:"collectionFormat,omitempty"` + Default any `json:"default,omitempty"` + Example any `json:"example,omitempty"` } // TypeName return the type (or format) of a simple schema @@ -91,7 +80,7 @@ func (i *Items) CollectionOf(items *Items, format string) *Items { } // WithDefault sets the default value on this item -func (i *Items) WithDefault(defaultValue interface{}) *Items { +func (i *Items) WithDefault(defaultValue any) *Items { i.Default = defaultValue return i } @@ -135,8 +124,8 @@ func (i *Items) WithMinimum(minimum float64, exclusive bool) *Items { } // WithEnum sets a the enum values (replace) -func (i *Items) WithEnum(values ...interface{}) *Items { - i.Enum = append([]interface{}{}, values...) +func (i *Items) WithEnum(values ...any) *Items { + i.Enum = append([]any{}, values...) return i } @@ -217,7 +206,7 @@ func (i Items) MarshalJSON() ([]byte, error) { } // JSONLookup look up a value by the json property name -func (i Items) JSONLookup(token string) (interface{}, error) { +func (i Items) JSONLookup(token string) (any, error) { if token == jsonRef { return &i.Ref, nil } diff --git a/vendor/github.com/go-openapi/spec/license.go b/vendor/github.com/go-openapi/spec/license.go index 09f54fea08a..286b237e2bf 100644 --- a/vendor/github.com/go-openapi/spec/license.go +++ b/vendor/github.com/go-openapi/spec/license.go @@ -1,16 +1,5 @@ -// Copyright 2015 go-swagger maintainers -// -// 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. +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 package spec diff --git a/vendor/github.com/go-openapi/spec/normalizer.go b/vendor/github.com/go-openapi/spec/normalizer.go index e8b60099457..c3ea810aaf3 100644 --- a/vendor/github.com/go-openapi/spec/normalizer.go +++ b/vendor/github.com/go-openapi/spec/normalizer.go @@ -1,16 +1,5 @@ -// Copyright 2015 go-swagger maintainers -// -// 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. +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 package spec @@ -129,8 +118,8 @@ func rebase(ref *Ref, v *url.URL, notEqual bool) (Ref, bool) { newBase.Fragment = u.Fragment - if strings.HasPrefix(u.Path, docPath) { - newBase.Path = strings.TrimPrefix(u.Path, docPath) + if after, ok := strings.CutPrefix(u.Path, docPath); ok { + newBase.Path = after } else { newBase.Path = strings.TrimPrefix(u.Path, v.Path) } diff --git a/vendor/github.com/go-openapi/spec/normalizer_nonwindows.go b/vendor/github.com/go-openapi/spec/normalizer_nonwindows.go index f19f1a8fb65..0d55632349f 100644 --- a/vendor/github.com/go-openapi/spec/normalizer_nonwindows.go +++ b/vendor/github.com/go-openapi/spec/normalizer_nonwindows.go @@ -1,19 +1,7 @@ //go:build !windows -// +build !windows -// Copyright 2015 go-swagger maintainers -// -// 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. +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 package spec diff --git a/vendor/github.com/go-openapi/spec/normalizer_windows.go b/vendor/github.com/go-openapi/spec/normalizer_windows.go index a66c532dbc6..61515c9a163 100644 --- a/vendor/github.com/go-openapi/spec/normalizer_windows.go +++ b/vendor/github.com/go-openapi/spec/normalizer_windows.go @@ -1,18 +1,7 @@ // -build windows -// Copyright 2015 go-swagger maintainers -// -// 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. +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 package spec diff --git a/vendor/github.com/go-openapi/spec/operation.go b/vendor/github.com/go-openapi/spec/operation.go index 98262192aee..bbf8c757372 100644 --- a/vendor/github.com/go-openapi/spec/operation.go +++ b/vendor/github.com/go-openapi/spec/operation.go @@ -1,16 +1,5 @@ -// Copyright 2015 go-swagger maintainers -// -// 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. +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 package spec diff --git a/vendor/github.com/go-openapi/spec/parameter.go b/vendor/github.com/go-openapi/spec/parameter.go index 1dd831149a2..b94b7682ac8 100644 --- a/vendor/github.com/go-openapi/spec/parameter.go +++ b/vendor/github.com/go-openapi/spec/parameter.go @@ -1,16 +1,5 @@ -// Copyright 2015 go-swagger maintainers -// -// 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. +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 package spec @@ -116,7 +105,7 @@ type Parameter struct { } // JSONLookup look up a value by the json property name -func (p Parameter) JSONLookup(token string) (interface{}, error) { +func (p Parameter) JSONLookup(token string) (any, error) { if ex, ok := p.Extensions[token]; ok { return &ex, nil } @@ -176,7 +165,7 @@ func (p *Parameter) CollectionOf(items *Items, format string) *Parameter { } // WithDefault sets the default value on this parameter -func (p *Parameter) WithDefault(defaultValue interface{}) *Parameter { +func (p *Parameter) WithDefault(defaultValue any) *Parameter { p.AsOptional() // with default implies optional p.Default = defaultValue return p @@ -248,8 +237,8 @@ func (p *Parameter) WithMinimum(minimum float64, exclusive bool) *Parameter { } // WithEnum sets a the enum values (replace) -func (p *Parameter) WithEnum(values ...interface{}) *Parameter { - p.Enum = append([]interface{}{}, values...) +func (p *Parameter) WithEnum(values ...any) *Parameter { + p.Enum = append([]any{}, values...) return p } diff --git a/vendor/github.com/go-openapi/spec/path_item.go b/vendor/github.com/go-openapi/spec/path_item.go index e51b81007d8..c692b89e46c 100644 --- a/vendor/github.com/go-openapi/spec/path_item.go +++ b/vendor/github.com/go-openapi/spec/path_item.go @@ -1,16 +1,5 @@ -// Copyright 2015 go-swagger maintainers -// -// 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. +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 package spec @@ -46,7 +35,7 @@ type PathItem struct { } // JSONLookup look up a value by the json property name -func (p PathItem) JSONLookup(token string) (interface{}, error) { +func (p PathItem) JSONLookup(token string) (any, error) { if ex, ok := p.Extensions[token]; ok { return &ex, nil } diff --git a/vendor/github.com/go-openapi/spec/paths.go b/vendor/github.com/go-openapi/spec/paths.go index b95eadc9509..b9e42184b19 100644 --- a/vendor/github.com/go-openapi/spec/paths.go +++ b/vendor/github.com/go-openapi/spec/paths.go @@ -1,16 +1,5 @@ -// Copyright 2015 go-swagger maintainers -// -// 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. +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 package spec diff --git a/vendor/github.com/go-openapi/spec/properties.go b/vendor/github.com/go-openapi/spec/properties.go index ada68dd0c12..4142308dd39 100644 --- a/vendor/github.com/go-openapi/spec/properties.go +++ b/vendor/github.com/go-openapi/spec/properties.go @@ -1,3 +1,6 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + package spec import ( diff --git a/vendor/github.com/go-openapi/spec/ref.go b/vendor/github.com/go-openapi/spec/ref.go index 87b8b3a8acd..c9279262942 100644 --- a/vendor/github.com/go-openapi/spec/ref.go +++ b/vendor/github.com/go-openapi/spec/ref.go @@ -1,16 +1,5 @@ -// Copyright 2015 go-swagger maintainers -// -// 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. +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 package spec diff --git a/vendor/github.com/go-openapi/spec/resolver.go b/vendor/github.com/go-openapi/spec/resolver.go index dd577b03a79..b82c1821332 100644 --- a/vendor/github.com/go-openapi/spec/resolver.go +++ b/vendor/github.com/go-openapi/spec/resolver.go @@ -1,3 +1,6 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + package spec import ( @@ -6,7 +9,7 @@ import ( "github.com/go-openapi/swag/jsonutils" ) -func resolveAnyWithBase(root interface{}, ref *Ref, result interface{}, options *ExpandOptions) error { +func resolveAnyWithBase(root any, ref *Ref, result any, options *ExpandOptions) error { options = optionsOrDefault(options) resolver := defaultSchemaLoader(root, options, nil, nil) @@ -18,7 +21,7 @@ func resolveAnyWithBase(root interface{}, ref *Ref, result interface{}, options } // ResolveRefWithBase resolves a reference against a context root with preservation of base path -func ResolveRefWithBase(root interface{}, ref *Ref, options *ExpandOptions) (*Schema, error) { +func ResolveRefWithBase(root any, ref *Ref, options *ExpandOptions) (*Schema, error) { result := new(Schema) if err := resolveAnyWithBase(root, ref, result, options); err != nil { @@ -32,7 +35,7 @@ func ResolveRefWithBase(root interface{}, ref *Ref, options *ExpandOptions) (*Sc // ref is guaranteed to be in root (no need to go to external files) // // ResolveRef is ONLY called from the code generation module -func ResolveRef(root interface{}, ref *Ref) (*Schema, error) { +func ResolveRef(root any, ref *Ref) (*Schema, error) { res, _, err := ref.GetPointer().Get(root) if err != nil { return nil, err @@ -43,7 +46,7 @@ func ResolveRef(root interface{}, ref *Ref) (*Schema, error) { return &sch, nil case *Schema: return sch, nil - case map[string]interface{}: + case map[string]any: newSch := new(Schema) if err = jsonutils.FromDynamicJSON(sch, newSch); err != nil { return nil, err @@ -55,7 +58,7 @@ func ResolveRef(root interface{}, ref *Ref) (*Schema, error) { } // ResolveParameterWithBase resolves a parameter reference against a context root and base path -func ResolveParameterWithBase(root interface{}, ref Ref, options *ExpandOptions) (*Parameter, error) { +func ResolveParameterWithBase(root any, ref Ref, options *ExpandOptions) (*Parameter, error) { result := new(Parameter) if err := resolveAnyWithBase(root, &ref, result, options); err != nil { @@ -66,12 +69,12 @@ func ResolveParameterWithBase(root interface{}, ref Ref, options *ExpandOptions) } // ResolveParameter resolves a parameter reference against a context root -func ResolveParameter(root interface{}, ref Ref) (*Parameter, error) { +func ResolveParameter(root any, ref Ref) (*Parameter, error) { return ResolveParameterWithBase(root, ref, nil) } // ResolveResponseWithBase resolves response a reference against a context root and base path -func ResolveResponseWithBase(root interface{}, ref Ref, options *ExpandOptions) (*Response, error) { +func ResolveResponseWithBase(root any, ref Ref, options *ExpandOptions) (*Response, error) { result := new(Response) err := resolveAnyWithBase(root, &ref, result, options) @@ -83,12 +86,12 @@ func ResolveResponseWithBase(root interface{}, ref Ref, options *ExpandOptions) } // ResolveResponse resolves response a reference against a context root -func ResolveResponse(root interface{}, ref Ref) (*Response, error) { +func ResolveResponse(root any, ref Ref) (*Response, error) { return ResolveResponseWithBase(root, ref, nil) } // ResolvePathItemWithBase resolves response a path item against a context root and base path -func ResolvePathItemWithBase(root interface{}, ref Ref, options *ExpandOptions) (*PathItem, error) { +func ResolvePathItemWithBase(root any, ref Ref, options *ExpandOptions) (*PathItem, error) { result := new(PathItem) if err := resolveAnyWithBase(root, &ref, result, options); err != nil { @@ -101,7 +104,7 @@ func ResolvePathItemWithBase(root interface{}, ref Ref, options *ExpandOptions) // ResolvePathItem resolves response a path item against a context root and base path // // Deprecated: use ResolvePathItemWithBase instead -func ResolvePathItem(root interface{}, ref Ref, options *ExpandOptions) (*PathItem, error) { +func ResolvePathItem(root any, ref Ref, options *ExpandOptions) (*PathItem, error) { return ResolvePathItemWithBase(root, ref, options) } @@ -109,7 +112,7 @@ func ResolvePathItem(root interface{}, ref Ref, options *ExpandOptions) (*PathIt // // NOTE: stricly speaking, this construct is not supported by Swagger 2.0. // Similarly, $ref are forbidden in response headers. -func ResolveItemsWithBase(root interface{}, ref Ref, options *ExpandOptions) (*Items, error) { +func ResolveItemsWithBase(root any, ref Ref, options *ExpandOptions) (*Items, error) { result := new(Items) if err := resolveAnyWithBase(root, &ref, result, options); err != nil { @@ -122,6 +125,6 @@ func ResolveItemsWithBase(root interface{}, ref Ref, options *ExpandOptions) (*I // ResolveItems resolves parameter items reference against a context root and base path. // // Deprecated: use ResolveItemsWithBase instead -func ResolveItems(root interface{}, ref Ref, options *ExpandOptions) (*Items, error) { +func ResolveItems(root any, ref Ref, options *ExpandOptions) (*Items, error) { return ResolveItemsWithBase(root, ref, options) } diff --git a/vendor/github.com/go-openapi/spec/response.go b/vendor/github.com/go-openapi/spec/response.go index edb60a500e6..e5a7e5c40d4 100644 --- a/vendor/github.com/go-openapi/spec/response.go +++ b/vendor/github.com/go-openapi/spec/response.go @@ -1,16 +1,5 @@ -// Copyright 2015 go-swagger maintainers -// -// 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. +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 package spec @@ -23,10 +12,10 @@ import ( // ResponseProps properties specific to a response type ResponseProps struct { - Description string `json:"description"` - Schema *Schema `json:"schema,omitempty"` - Headers map[string]Header `json:"headers,omitempty"` - Examples map[string]interface{} `json:"examples,omitempty"` + Description string `json:"description"` + Schema *Schema `json:"schema,omitempty"` + Headers map[string]Header `json:"headers,omitempty"` + Examples map[string]any `json:"examples,omitempty"` } // Response describes a single response from an API Operation. @@ -51,7 +40,7 @@ func ResponseRef(url string) *Response { } // JSONLookup look up a value by the json property name -func (r Response) JSONLookup(token string) (interface{}, error) { +func (r Response) JSONLookup(token string) (any, error) { if ex, ok := r.Extensions[token]; ok { return &ex, nil } @@ -86,10 +75,10 @@ func (r Response) MarshalJSON() ([]byte, error) { } else { // when there is $ref inside the schema, description should be omitempty-ied b1, err = json.Marshal(struct { - Description string `json:"description,omitempty"` - Schema *Schema `json:"schema,omitempty"` - Headers map[string]Header `json:"headers,omitempty"` - Examples map[string]interface{} `json:"examples,omitempty"` + Description string `json:"description,omitempty"` + Schema *Schema `json:"schema,omitempty"` + Headers map[string]Header `json:"headers,omitempty"` + Examples map[string]any `json:"examples,omitempty"` }{ Description: r.Description, Schema: r.Schema, @@ -143,9 +132,9 @@ func (r *Response) RemoveHeader(name string) *Response { } // AddExample adds an example to this response -func (r *Response) AddExample(mediaType string, example interface{}) *Response { +func (r *Response) AddExample(mediaType string, example any) *Response { if r.Examples == nil { - r.Examples = make(map[string]interface{}) + r.Examples = make(map[string]any) } r.Examples[mediaType] = example return r diff --git a/vendor/github.com/go-openapi/spec/responses.go b/vendor/github.com/go-openapi/spec/responses.go index 337c6b1bda0..733a1315d02 100644 --- a/vendor/github.com/go-openapi/spec/responses.go +++ b/vendor/github.com/go-openapi/spec/responses.go @@ -1,16 +1,5 @@ -// Copyright 2015 go-swagger maintainers -// -// 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. +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 package spec @@ -43,7 +32,7 @@ type Responses struct { } // JSONLookup implements an interface to customize json pointer lookup -func (r Responses) JSONLookup(token string) (interface{}, error) { +func (r Responses) JSONLookup(token string) (any, error) { if token == "default" { return r.Default, nil } diff --git a/vendor/github.com/go-openapi/spec/schema.go b/vendor/github.com/go-openapi/spec/schema.go index 0a49f2d49bf..6623728a41a 100644 --- a/vendor/github.com/go-openapi/spec/schema.go +++ b/vendor/github.com/go-openapi/spec/schema.go @@ -1,16 +1,5 @@ -// Copyright 2015 go-swagger maintainers -// -// 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. +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 package spec diff --git a/vendor/github.com/go-openapi/spec/schema_loader.go b/vendor/github.com/go-openapi/spec/schema_loader.go index 328e5b83a80..8d4a9853256 100644 --- a/vendor/github.com/go-openapi/spec/schema_loader.go +++ b/vendor/github.com/go-openapi/spec/schema_loader.go @@ -1,16 +1,5 @@ -// Copyright 2015 go-swagger maintainers -// -// 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. +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 package spec diff --git a/vendor/github.com/go-openapi/spec/security_scheme.go b/vendor/github.com/go-openapi/spec/security_scheme.go index 2dfe934f7e2..46a4a7e2f9f 100644 --- a/vendor/github.com/go-openapi/spec/security_scheme.go +++ b/vendor/github.com/go-openapi/spec/security_scheme.go @@ -1,16 +1,5 @@ -// Copyright 2015 go-swagger maintainers -// -// 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. +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 package spec @@ -109,7 +98,7 @@ type SecurityScheme struct { } // JSONLookup implements an interface to customize json pointer lookup -func (s SecurityScheme) JSONLookup(token string) (interface{}, error) { +func (s SecurityScheme) JSONLookup(token string) (any, error) { if ex, ok := s.Extensions[token]; ok { return &ex, nil } diff --git a/vendor/github.com/go-openapi/spec/spec.go b/vendor/github.com/go-openapi/spec/spec.go index 876aa12759d..05c3fc775cf 100644 --- a/vendor/github.com/go-openapi/spec/spec.go +++ b/vendor/github.com/go-openapi/spec/spec.go @@ -1,16 +1,5 @@ -// Copyright 2015 go-swagger maintainers -// -// 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. +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 package spec diff --git a/vendor/github.com/go-openapi/spec/swagger.go b/vendor/github.com/go-openapi/spec/swagger.go index 0e73759d48b..f7cd0f608c2 100644 --- a/vendor/github.com/go-openapi/spec/swagger.go +++ b/vendor/github.com/go-openapi/spec/swagger.go @@ -1,16 +1,5 @@ -// Copyright 2015 go-swagger maintainers -// -// 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. +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 package spec @@ -19,6 +8,7 @@ import ( "encoding/gob" "encoding/json" "fmt" + "slices" "strconv" "github.com/go-openapi/jsonpointer" @@ -36,7 +26,7 @@ type Swagger struct { } // JSONLookup look up a value by the json property name -func (s Swagger) JSONLookup(token string) (interface{}, error) { +func (s Swagger) JSONLookup(token string) (any, error) { if ex, ok := s.Extensions[token]; ok { return &ex, nil } @@ -227,7 +217,7 @@ type SchemaOrBool struct { } // JSONLookup implements an interface to customize json pointer lookup -func (s SchemaOrBool) JSONLookup(token string) (interface{}, error) { +func (s SchemaOrBool) JSONLookup(token string) (any, error) { if token == "allows" { return s.Allows, nil } @@ -274,7 +264,7 @@ type SchemaOrStringArray struct { } // JSONLookup implements an interface to customize json pointer lookup -func (s SchemaOrStringArray) JSONLookup(token string) (interface{}, error) { +func (s SchemaOrStringArray) JSONLookup(token string) (any, error) { r, _, err := jsonpointer.GetForToken(s.Schema, token) return r, err } @@ -333,16 +323,11 @@ type StringOrArray []string // Contains returns true when the value is contained in the slice func (s StringOrArray) Contains(value string) bool { - for _, str := range s { - if str == value { - return true - } - } - return false + return slices.Contains(s, value) } // JSONLookup implements an interface to customize json pointer lookup -func (s SchemaOrArray) JSONLookup(token string) (interface{}, error) { +func (s SchemaOrArray) JSONLookup(token string) (any, error) { if _, err := strconv.Atoi(token); err == nil { r, _, err := jsonpointer.GetForToken(s.Schemas, token) return r, err @@ -367,7 +352,7 @@ func (s *StringOrArray) UnmarshalJSON(data []byte) error { return nil } - var single interface{} + var single any if err := json.Unmarshal(data, &single); err != nil { return err } diff --git a/vendor/github.com/go-openapi/spec/tag.go b/vendor/github.com/go-openapi/spec/tag.go index baf1f3d1755..ae98fd985fb 100644 --- a/vendor/github.com/go-openapi/spec/tag.go +++ b/vendor/github.com/go-openapi/spec/tag.go @@ -1,16 +1,5 @@ -// Copyright 2015 go-swagger maintainers -// -// 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. +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 package spec @@ -44,7 +33,7 @@ func NewTag(name, description string, externalDocs *ExternalDocumentation) Tag { } // JSONLookup implements an interface to customize json pointer lookup -func (t Tag) JSONLookup(token string) (interface{}, error) { +func (t Tag) JSONLookup(token string) (any, error) { if ex, ok := t.Extensions[token]; ok { return &ex, nil } diff --git a/vendor/github.com/go-openapi/spec/url_go19.go b/vendor/github.com/go-openapi/spec/url_go19.go index 5bdfe40bcc1..8d0c81acd68 100644 --- a/vendor/github.com/go-openapi/spec/url_go19.go +++ b/vendor/github.com/go-openapi/spec/url_go19.go @@ -1,3 +1,6 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + package spec import "net/url" diff --git a/vendor/github.com/go-openapi/spec/validations.go b/vendor/github.com/go-openapi/spec/validations.go index ae80a5dfd5e..4f70e301732 100644 --- a/vendor/github.com/go-openapi/spec/validations.go +++ b/vendor/github.com/go-openapi/spec/validations.go @@ -1,19 +1,22 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + package spec // CommonValidations describe common JSON-schema validations type CommonValidations struct { - Maximum *float64 `json:"maximum,omitempty"` - ExclusiveMaximum bool `json:"exclusiveMaximum,omitempty"` - Minimum *float64 `json:"minimum,omitempty"` - ExclusiveMinimum bool `json:"exclusiveMinimum,omitempty"` - MaxLength *int64 `json:"maxLength,omitempty"` - MinLength *int64 `json:"minLength,omitempty"` - Pattern string `json:"pattern,omitempty"` - MaxItems *int64 `json:"maxItems,omitempty"` - MinItems *int64 `json:"minItems,omitempty"` - UniqueItems bool `json:"uniqueItems,omitempty"` - MultipleOf *float64 `json:"multipleOf,omitempty"` - Enum []interface{} `json:"enum,omitempty"` + Maximum *float64 `json:"maximum,omitempty"` + ExclusiveMaximum bool `json:"exclusiveMaximum,omitempty"` + Minimum *float64 `json:"minimum,omitempty"` + ExclusiveMinimum bool `json:"exclusiveMinimum,omitempty"` + MaxLength *int64 `json:"maxLength,omitempty"` + MinLength *int64 `json:"minLength,omitempty"` + Pattern string `json:"pattern,omitempty"` + MaxItems *int64 `json:"maxItems,omitempty"` + MinItems *int64 `json:"minItems,omitempty"` + UniqueItems bool `json:"uniqueItems,omitempty"` + MultipleOf *float64 `json:"multipleOf,omitempty"` + Enum []any `json:"enum,omitempty"` } // SetValidations defines all validations for a simple schema. @@ -37,12 +40,12 @@ func (v *CommonValidations) SetValidations(val SchemaValidations) { type clearedValidation struct { Validation string - Value interface{} + Value any } type clearedValidations []clearedValidation -func (c clearedValidations) apply(cbs []func(string, interface{})) { +func (c clearedValidations) apply(cbs []func(string, any)) { for _, cb := range cbs { for _, cleared := range c { cb(cleared.Validation, cleared.Value) @@ -53,7 +56,7 @@ func (c clearedValidations) apply(cbs []func(string, interface{})) { // ClearNumberValidations clears all number validations. // // Some callbacks may be set by the caller to capture changed values. -func (v *CommonValidations) ClearNumberValidations(cbs ...func(string, interface{})) { +func (v *CommonValidations) ClearNumberValidations(cbs ...func(string, any)) { const maxNumberValidations = 5 done := make(clearedValidations, 0, maxNumberValidations) defer func() { @@ -85,7 +88,7 @@ func (v *CommonValidations) ClearNumberValidations(cbs ...func(string, interface // ClearStringValidations clears all string validations. // // Some callbacks may be set by the caller to capture changed values. -func (v *CommonValidations) ClearStringValidations(cbs ...func(string, interface{})) { +func (v *CommonValidations) ClearStringValidations(cbs ...func(string, any)) { const maxStringValidations = 3 done := make(clearedValidations, 0, maxStringValidations) defer func() { @@ -109,7 +112,7 @@ func (v *CommonValidations) ClearStringValidations(cbs ...func(string, interface // ClearArrayValidations clears all array validations. // // Some callbacks may be set by the caller to capture changed values. -func (v *CommonValidations) ClearArrayValidations(cbs ...func(string, interface{})) { +func (v *CommonValidations) ClearArrayValidations(cbs ...func(string, any)) { const maxArrayValidations = 3 done := make(clearedValidations, 0, maxArrayValidations) defer func() { @@ -197,7 +200,7 @@ func (v SchemaValidations) Validations() SchemaValidations { // ClearObjectValidations returns a clone of the validations with all object validations cleared. // // Some callbacks may be set by the caller to capture changed values. -func (v *SchemaValidations) ClearObjectValidations(cbs ...func(string, interface{})) { +func (v *SchemaValidations) ClearObjectValidations(cbs ...func(string, any)) { const maxObjectValidations = 3 done := make(clearedValidations, 0, maxObjectValidations) defer func() { diff --git a/vendor/github.com/go-openapi/spec/xml_object.go b/vendor/github.com/go-openapi/spec/xml_object.go index 945a46703d5..bf2f8f18b24 100644 --- a/vendor/github.com/go-openapi/spec/xml_object.go +++ b/vendor/github.com/go-openapi/spec/xml_object.go @@ -1,16 +1,5 @@ -// Copyright 2015 go-swagger maintainers -// -// 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. +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 package spec diff --git a/vendor/github.com/go-openapi/strfmt/.golangci.yml b/vendor/github.com/go-openapi/strfmt/.golangci.yml index 7cea1af8b52..1ad5adf47e6 100644 --- a/vendor/github.com/go-openapi/strfmt/.golangci.yml +++ b/vendor/github.com/go-openapi/strfmt/.golangci.yml @@ -16,7 +16,7 @@ linters: - godox - gosmopolitan - inamedparam - #- intrange # disabled while < go1.22 + - intrange - ireturn - lll - musttag diff --git a/vendor/github.com/go-openapi/strfmt/README.md b/vendor/github.com/go-openapi/strfmt/README.md index f6b39c6c56c..de5afe13760 100644 --- a/vendor/github.com/go-openapi/strfmt/README.md +++ b/vendor/github.com/go-openapi/strfmt/README.md @@ -35,7 +35,7 @@ It also provides convenient extensions to go-openapi users. - mac (e.g "01:02:03:04:05:06") - rgbcolor (e.g. "rgb(100,100,100)") - ssn - - uuid, uuid3, uuid4, uuid5 + - uuid, uuid3, uuid4, uuid5, uuid7 - cidr (e.g. "192.0.2.1/24", "2001:db8:a0b:12f0::1/32") - ulid (e.g. "00000PP9HGSBSSDZ1JTEXBJ0PW", [spec](https://github.com/ulid/spec)) @@ -81,7 +81,12 @@ List of defined types: - SSN - URI - UUID -- UUID3 -- UUID4 -- UUID5 +- [UUID3](https://www.rfc-editor.org/rfc/rfc9562.html#name-uuid-version-3) +- [UUID4](https://www.rfc-editor.org/rfc/rfc9562.html#name-uuid-version-4) +- [UUID5](https://www.rfc-editor.org/rfc/rfc9562.html#name-uuid-version-5) +- [UUID7](https://www.rfc-editor.org/rfc/rfc9562.html#name-uuid-version-7) - [ULID](https://github.com/ulid/spec) + +## Licensing + +This library ships under the [SPDX-License-Identifier: Apache-2.0](./LICENSE). diff --git a/vendor/github.com/go-openapi/strfmt/bson.go b/vendor/github.com/go-openapi/strfmt/bson.go index 78d6e073587..0eec8f6432c 100644 --- a/vendor/github.com/go-openapi/strfmt/bson.go +++ b/vendor/github.com/go-openapi/strfmt/bson.go @@ -1,16 +1,5 @@ -// Copyright 2015 go-swagger maintainers -// -// 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. +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 package strfmt @@ -18,9 +7,6 @@ import ( "database/sql/driver" "fmt" - "go.mongodb.org/mongo-driver/bson" - - "go.mongodb.org/mongo-driver/bson/bsontype" bsonprim "go.mongodb.org/mongo-driver/bson/primitive" ) @@ -75,7 +61,7 @@ func (id *ObjectId) UnmarshalText(data []byte) error { // validation is performe } // Scan read a value from a database driver -func (id *ObjectId) Scan(raw interface{}) error { +func (id *ObjectId) Scan(raw any) error { var data []byte switch v := raw.(type) { case []byte: @@ -113,42 +99,6 @@ func (id *ObjectId) UnmarshalJSON(data []byte) error { return nil } -// MarshalBSON renders the object id as a BSON document -func (id ObjectId) MarshalBSON() ([]byte, error) { - return bson.Marshal(bson.M{"data": bsonprim.ObjectID(id)}) -} - -// UnmarshalBSON reads the objectId from a BSON document -func (id *ObjectId) UnmarshalBSON(data []byte) error { - var obj struct { - Data bsonprim.ObjectID - } - if err := bson.Unmarshal(data, &obj); err != nil { - return err - } - *id = ObjectId(obj.Data) - return nil -} - -// MarshalBSONValue is an interface implemented by types that can marshal themselves -// into a BSON document represented as bytes. The bytes returned must be a valid -// BSON document if the error is nil. -func (id ObjectId) MarshalBSONValue() (bsontype.Type, []byte, error) { - oid := bsonprim.ObjectID(id) - return bson.TypeObjectID, oid[:], nil -} - -// UnmarshalBSONValue is an interface implemented by types that can unmarshal a -// BSON value representation of themselves. The BSON bytes and type can be -// assumed to be valid. UnmarshalBSONValue must copy the BSON value bytes if it -// wishes to retain the data after returning. -func (id *ObjectId) UnmarshalBSONValue(_ bsontype.Type, data []byte) error { - var oid bsonprim.ObjectID - copy(oid[:], data) - *id = ObjectId(oid) - return nil -} - // DeepCopyInto copies the receiver and writes its value into out. func (id *ObjectId) DeepCopyInto(out *ObjectId) { *out = *id diff --git a/vendor/github.com/go-openapi/strfmt/date.go b/vendor/github.com/go-openapi/strfmt/date.go index a8f52ff354d..8aa17b8ea55 100644 --- a/vendor/github.com/go-openapi/strfmt/date.go +++ b/vendor/github.com/go-openapi/strfmt/date.go @@ -1,16 +1,5 @@ -// Copyright 2015 go-swagger maintainers -// -// 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. +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 package strfmt @@ -19,8 +8,6 @@ import ( "encoding/json" "fmt" "time" - - "go.mongodb.org/mongo-driver/bson" ) func init() { @@ -70,7 +57,7 @@ func (d Date) MarshalText() ([]byte, error) { } // Scan scans a Date value from database driver type. -func (d *Date) Scan(raw interface{}) error { +func (d *Date) Scan(raw any) error { switch v := raw.(type) { case []byte: return d.UnmarshalText(v) @@ -114,28 +101,6 @@ func (d *Date) UnmarshalJSON(data []byte) error { return nil } -func (d Date) MarshalBSON() ([]byte, error) { - return bson.Marshal(bson.M{"data": d.String()}) -} - -func (d *Date) UnmarshalBSON(data []byte) error { - var m bson.M - if err := bson.Unmarshal(data, &m); err != nil { - return err - } - - if data, ok := m["data"].(string); ok { - rd, err := time.ParseInLocation(RFC3339FullDate, data, DefaultTimeLocation) - if err != nil { - return err - } - *d = Date(rd) - return nil - } - - return fmt.Errorf("couldn't unmarshal bson bytes value as Date: %w", ErrFormat) -} - // DeepCopyInto copies the receiver and writes its value into out. func (d *Date) DeepCopyInto(out *Date) { *out = *d diff --git a/vendor/github.com/go-openapi/strfmt/default.go b/vendor/github.com/go-openapi/strfmt/default.go index 02e11122937..8a80cfbdb8a 100644 --- a/vendor/github.com/go-openapi/strfmt/default.go +++ b/vendor/github.com/go-openapi/strfmt/default.go @@ -1,16 +1,5 @@ -// Copyright 2015 go-swagger maintainers -// -// 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. +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 package strfmt @@ -19,14 +8,15 @@ import ( "encoding/base64" "encoding/json" "fmt" + "net" "net/mail" "net/netip" + "net/url" + "regexp" "strconv" "strings" - "github.com/asaskevich/govalidator" "github.com/google/uuid" - "go.mongodb.org/mongo-driver/bson" "golang.org/x/net/idna" ) @@ -60,10 +50,33 @@ const ( // // Deprecated: strfmt no longer uses regular expressions to validate UUIDs. UUID5Pattern = `(?i)(^[0-9a-f]{8}-[0-9a-f]{4}-5[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$)|(^[0-9a-f]{12}5[0-9a-f]{3}[89ab][0-9a-f]{15}$)` + + isbn10Pattern string = "^(?:[0-9]{9}X|[0-9]{10})$" + isbn13Pattern string = "^(?:[0-9]{13})$" + usCardPattern string = "^(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|(222[1-9]|22[3-9][0-9]|2[3-6][0-9]{2}|27[01][0-9]|2720)[0-9]{12}|6(?:011|5[0-9][0-9])[0-9]{12}|3[47][0-9]{13}|3(?:0[0-5]|[68][0-9])[0-9]{11}|(?:2131|1800|35\\d{3})\\d{11}|6[27][0-9]{14})$" + ssnPattern string = `^\d{3}[- ]?\d{2}[- ]?\d{4}$` + hexColorPattern string = "^#?([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$" + rgbColorPattern string = "^rgb\\(\\s*(0|[1-9]\\d?|1\\d\\d?|2[0-4]\\d|25[0-5])\\s*,\\s*(0|[1-9]\\d?|1\\d\\d?|2[0-4]\\d|25[0-5])\\s*,\\s*(0|[1-9]\\d?|1\\d\\d?|2[0-4]\\d|25[0-5])\\s*\\)$" +) + +const ( + isbnVersion10 = 10 + isbnVersion13 = 13 + decimalBase = 10 ) -var idnaHostChecker = idna.New( - idna.ValidateForRegistration(), // shorthand for [idna.StrictDomainName], [idna.ValidateLabels], [idna.VerifyDNSLength], [idna.BidiRule] +var ( + idnaHostChecker = idna.New( + idna.ValidateForRegistration(), // shorthand for [idna.StrictDomainName], [idna.ValidateLabels], [idna.VerifyDNSLength], [idna.BidiRule] + ) + + whiteSpacesAndMinus = regexp.MustCompile(`[\s-]+`) + rxISBN10 = regexp.MustCompile(isbn10Pattern) + rxISBN13 = regexp.MustCompile(isbn13Pattern) + rxCreditCard = regexp.MustCompile(usCardPattern) + rxSSN = regexp.MustCompile(ssnPattern) + rxHexcolor = regexp.MustCompile(hexColorPattern) + rxRGBcolor = regexp.MustCompile(rgbColorPattern) ) // IsHostname returns true when the string is a valid hostname. @@ -322,6 +335,7 @@ const ( uuidV3 = 3 uuidV4 = 4 uuidV5 = 5 + uuidV7 = 7 ) // IsUUID3 returns true is the string matches a UUID v3, upper case is allowed @@ -342,6 +356,12 @@ func IsUUID5(str string) bool { return err == nil && id.Version() == uuid.Version(uuidV5) } +// IsUUID7 returns true is the string matches a UUID v7, upper case is allowed +func IsUUID7(str string) bool { + id, err := uuid.Parse(str) + return err == nil && id.Version() == uuid.Version(uuidV7) +} + // IsEmail validates an email address. func IsEmail(str string) bool { addr, e := mail.ParseAddress(str) @@ -370,8 +390,9 @@ func init() { // - uuid3 // - uuid4 // - uuid5 + // - uuid7 u := URI("") - Default.Add("uri", &u, govalidator.IsRequestURI) + Default.Add("uri", &u, isRequestURI) eml := Email("") Default.Add("email", &eml, IsEmail) @@ -380,16 +401,16 @@ func init() { Default.Add("hostname", &hn, IsHostname) ip4 := IPv4("") - Default.Add("ipv4", &ip4, govalidator.IsIPv4) + Default.Add("ipv4", &ip4, isIPv4) ip6 := IPv6("") - Default.Add("ipv6", &ip6, govalidator.IsIPv6) + Default.Add("ipv6", &ip6, isIPv6) cidr := CIDR("") - Default.Add("cidr", &cidr, govalidator.IsCIDR) + Default.Add("cidr", &cidr, isCIDR) mac := MAC("") - Default.Add("mac", &mac, govalidator.IsMAC) + Default.Add("mac", &mac, isMAC) uid := UUID("") Default.Add("uuid", &uid, IsUUID) @@ -403,29 +424,32 @@ func init() { uid5 := UUID5("") Default.Add("uuid5", &uid5, IsUUID5) + uid7 := UUID7("") + Default.Add("uuid7", &uid7, IsUUID7) + isbn := ISBN("") - Default.Add("isbn", &isbn, func(str string) bool { return govalidator.IsISBN10(str) || govalidator.IsISBN13(str) }) + Default.Add("isbn", &isbn, func(str string) bool { return isISBN10(str) || isISBN13(str) }) isbn10 := ISBN10("") - Default.Add("isbn10", &isbn10, govalidator.IsISBN10) + Default.Add("isbn10", &isbn10, isISBN10) isbn13 := ISBN13("") - Default.Add("isbn13", &isbn13, govalidator.IsISBN13) + Default.Add("isbn13", &isbn13, isISBN13) cc := CreditCard("") - Default.Add("creditcard", &cc, govalidator.IsCreditCard) + Default.Add("creditcard", &cc, isCreditCard) ssn := SSN("") - Default.Add("ssn", &ssn, govalidator.IsSSN) + Default.Add("ssn", &ssn, isSSN) hc := HexColor("") - Default.Add("hexcolor", &hc, govalidator.IsHexcolor) + Default.Add("hexcolor", &hc, isHexcolor) rc := RGBColor("") - Default.Add("rgbcolor", &rc, govalidator.IsRGBcolor) + Default.Add("rgbcolor", &rc, isRGBcolor) b64 := Base64([]byte(nil)) - Default.Add("byte", &b64, govalidator.IsBase64) + Default.Add("byte", &b64, isBase64) pw := Password("") Default.Add("password", &pw, func(_ string) bool { return true }) @@ -460,7 +484,7 @@ func (b *Base64) UnmarshalText(data []byte) error { // validation is performed l } // Scan read a value from a database driver -func (b *Base64) Scan(raw interface{}) error { +func (b *Base64) Scan(raw any) error { switch v := raw.(type) { case []byte: dbuf := make([]byte, base64.StdEncoding.DecodedLen(len(v))) @@ -510,29 +534,6 @@ func (b *Base64) UnmarshalJSON(data []byte) error { return nil } -// MarshalBSON document from this value -func (b Base64) MarshalBSON() ([]byte, error) { - return bson.Marshal(bson.M{"data": b.String()}) -} - -// UnmarshalBSON document into this value -func (b *Base64) UnmarshalBSON(data []byte) error { - var m bson.M - if err := bson.Unmarshal(data, &m); err != nil { - return err - } - - if bd, ok := m["data"].(string); ok { - vb, err := base64.StdEncoding.DecodeString(bd) - if err != nil { - return err - } - *b = Base64(vb) - return nil - } - return fmt.Errorf("couldn't unmarshal bson bytes as base64: %w", ErrFormat) -} - // DeepCopyInto copies the receiver and writes its value into out. func (b *Base64) DeepCopyInto(out *Base64) { *out = *b @@ -565,7 +566,7 @@ func (u *URI) UnmarshalText(data []byte) error { // validation is performed late } // Scan read a value from a database driver -func (u *URI) Scan(raw interface{}) error { +func (u *URI) Scan(raw any) error { switch v := raw.(type) { case []byte: *u = URI(string(v)) @@ -602,25 +603,6 @@ func (u *URI) UnmarshalJSON(data []byte) error { return nil } -// MarshalBSON document from this value -func (u URI) MarshalBSON() ([]byte, error) { - return bson.Marshal(bson.M{"data": u.String()}) -} - -// UnmarshalBSON document into this value -func (u *URI) UnmarshalBSON(data []byte) error { - var m bson.M - if err := bson.Unmarshal(data, &m); err != nil { - return err - } - - if ud, ok := m["data"].(string); ok { - *u = URI(ud) - return nil - } - return fmt.Errorf("couldn't unmarshal bson bytes as uri: %w", ErrFormat) -} - // DeepCopyInto copies the receiver and writes its value into out. func (u *URI) DeepCopyInto(out *URI) { *out = *u @@ -653,7 +635,7 @@ func (e *Email) UnmarshalText(data []byte) error { // validation is performed la } // Scan read a value from a database driver -func (e *Email) Scan(raw interface{}) error { +func (e *Email) Scan(raw any) error { switch v := raw.(type) { case []byte: *e = Email(string(v)) @@ -690,25 +672,6 @@ func (e *Email) UnmarshalJSON(data []byte) error { return nil } -// MarshalBSON document from this value -func (e Email) MarshalBSON() ([]byte, error) { - return bson.Marshal(bson.M{"data": e.String()}) -} - -// UnmarshalBSON document into this value -func (e *Email) UnmarshalBSON(data []byte) error { - var m bson.M - if err := bson.Unmarshal(data, &m); err != nil { - return err - } - - if ud, ok := m["data"].(string); ok { - *e = Email(ud) - return nil - } - return fmt.Errorf("couldn't unmarshal bson bytes as email: %w", ErrFormat) -} - // DeepCopyInto copies the receiver and writes its value into out. func (e *Email) DeepCopyInto(out *Email) { *out = *e @@ -741,7 +704,7 @@ func (h *Hostname) UnmarshalText(data []byte) error { // validation is performed } // Scan read a value from a database driver -func (h *Hostname) Scan(raw interface{}) error { +func (h *Hostname) Scan(raw any) error { switch v := raw.(type) { case []byte: *h = Hostname(string(v)) @@ -778,25 +741,6 @@ func (h *Hostname) UnmarshalJSON(data []byte) error { return nil } -// MarshalBSON document from this value -func (h Hostname) MarshalBSON() ([]byte, error) { - return bson.Marshal(bson.M{"data": h.String()}) -} - -// UnmarshalBSON document into this value -func (h *Hostname) UnmarshalBSON(data []byte) error { - var m bson.M - if err := bson.Unmarshal(data, &m); err != nil { - return err - } - - if ud, ok := m["data"].(string); ok { - *h = Hostname(ud) - return nil - } - return fmt.Errorf("couldn't unmarshal bson bytes as hostname: %w", ErrFormat) -} - // DeepCopyInto copies the receiver and writes its value into out. func (h *Hostname) DeepCopyInto(out *Hostname) { *out = *h @@ -829,7 +773,7 @@ func (u *IPv4) UnmarshalText(data []byte) error { // validation is performed lat } // Scan read a value from a database driver -func (u *IPv4) Scan(raw interface{}) error { +func (u *IPv4) Scan(raw any) error { switch v := raw.(type) { case []byte: *u = IPv4(string(v)) @@ -866,25 +810,6 @@ func (u *IPv4) UnmarshalJSON(data []byte) error { return nil } -// MarshalBSON document from this value -func (u IPv4) MarshalBSON() ([]byte, error) { - return bson.Marshal(bson.M{"data": u.String()}) -} - -// UnmarshalBSON document into this value -func (u *IPv4) UnmarshalBSON(data []byte) error { - var m bson.M - if err := bson.Unmarshal(data, &m); err != nil { - return err - } - - if ud, ok := m["data"].(string); ok { - *u = IPv4(ud) - return nil - } - return fmt.Errorf("couldn't unmarshal bson bytes as ipv4: %w", ErrFormat) -} - // DeepCopyInto copies the receiver and writes its value into out. func (u *IPv4) DeepCopyInto(out *IPv4) { *out = *u @@ -917,7 +842,7 @@ func (u *IPv6) UnmarshalText(data []byte) error { // validation is performed lat } // Scan read a value from a database driver -func (u *IPv6) Scan(raw interface{}) error { +func (u *IPv6) Scan(raw any) error { switch v := raw.(type) { case []byte: *u = IPv6(string(v)) @@ -954,25 +879,6 @@ func (u *IPv6) UnmarshalJSON(data []byte) error { return nil } -// MarshalBSON document from this value -func (u IPv6) MarshalBSON() ([]byte, error) { - return bson.Marshal(bson.M{"data": u.String()}) -} - -// UnmarshalBSON document into this value -func (u *IPv6) UnmarshalBSON(data []byte) error { - var m bson.M - if err := bson.Unmarshal(data, &m); err != nil { - return err - } - - if ud, ok := m["data"].(string); ok { - *u = IPv6(ud) - return nil - } - return fmt.Errorf("couldn't unmarshal bson bytes as ipv6: %w", ErrFormat) -} - // DeepCopyInto copies the receiver and writes its value into out. func (u *IPv6) DeepCopyInto(out *IPv6) { *out = *u @@ -1005,7 +911,7 @@ func (u *CIDR) UnmarshalText(data []byte) error { // validation is performed lat } // Scan read a value from a database driver -func (u *CIDR) Scan(raw interface{}) error { +func (u *CIDR) Scan(raw any) error { switch v := raw.(type) { case []byte: *u = CIDR(string(v)) @@ -1042,25 +948,6 @@ func (u *CIDR) UnmarshalJSON(data []byte) error { return nil } -// MarshalBSON document from this value -func (u CIDR) MarshalBSON() ([]byte, error) { - return bson.Marshal(bson.M{"data": u.String()}) -} - -// UnmarshalBSON document into this value -func (u *CIDR) UnmarshalBSON(data []byte) error { - var m bson.M - if err := bson.Unmarshal(data, &m); err != nil { - return err - } - - if ud, ok := m["data"].(string); ok { - *u = CIDR(ud) - return nil - } - return fmt.Errorf("couldn't unmarshal bson bytes as CIDR: %w", ErrFormat) -} - // DeepCopyInto copies the receiver and writes its value into out. func (u *CIDR) DeepCopyInto(out *CIDR) { *out = *u @@ -1093,7 +980,7 @@ func (u *MAC) UnmarshalText(data []byte) error { // validation is performed late } // Scan read a value from a database driver -func (u *MAC) Scan(raw interface{}) error { +func (u *MAC) Scan(raw any) error { switch v := raw.(type) { case []byte: *u = MAC(string(v)) @@ -1130,25 +1017,6 @@ func (u *MAC) UnmarshalJSON(data []byte) error { return nil } -// MarshalBSON document from this value -func (u MAC) MarshalBSON() ([]byte, error) { - return bson.Marshal(bson.M{"data": u.String()}) -} - -// UnmarshalBSON document into this value -func (u *MAC) UnmarshalBSON(data []byte) error { - var m bson.M - if err := bson.Unmarshal(data, &m); err != nil { - return err - } - - if ud, ok := m["data"].(string); ok { - *u = MAC(ud) - return nil - } - return fmt.Errorf("couldn't unmarshal bson bytes as MAC: %w", ErrFormat) -} - // DeepCopyInto copies the receiver and writes its value into out. func (u *MAC) DeepCopyInto(out *MAC) { *out = *u @@ -1181,7 +1049,7 @@ func (u *UUID) UnmarshalText(data []byte) error { // validation is performed lat } // Scan read a value from a database driver -func (u *UUID) Scan(raw interface{}) error { +func (u *UUID) Scan(raw any) error { switch v := raw.(type) { case []byte: *u = UUID(string(v)) @@ -1221,25 +1089,6 @@ func (u *UUID) UnmarshalJSON(data []byte) error { return nil } -// MarshalBSON document from this value -func (u UUID) MarshalBSON() ([]byte, error) { - return bson.Marshal(bson.M{"data": u.String()}) -} - -// UnmarshalBSON document into this value -func (u *UUID) UnmarshalBSON(data []byte) error { - var m bson.M - if err := bson.Unmarshal(data, &m); err != nil { - return err - } - - if ud, ok := m["data"].(string); ok { - *u = UUID(ud) - return nil - } - return fmt.Errorf("couldn't unmarshal bson bytes as UUID: %w", ErrFormat) -} - // DeepCopyInto copies the receiver and writes its value into out. func (u *UUID) DeepCopyInto(out *UUID) { *out = *u @@ -1272,7 +1121,7 @@ func (u *UUID3) UnmarshalText(data []byte) error { // validation is performed la } // Scan read a value from a database driver -func (u *UUID3) Scan(raw interface{}) error { +func (u *UUID3) Scan(raw any) error { switch v := raw.(type) { case []byte: *u = UUID3(string(v)) @@ -1312,25 +1161,6 @@ func (u *UUID3) UnmarshalJSON(data []byte) error { return nil } -// MarshalBSON document from this value -func (u UUID3) MarshalBSON() ([]byte, error) { - return bson.Marshal(bson.M{"data": u.String()}) -} - -// UnmarshalBSON document into this value -func (u *UUID3) UnmarshalBSON(data []byte) error { - var m bson.M - if err := bson.Unmarshal(data, &m); err != nil { - return err - } - - if ud, ok := m["data"].(string); ok { - *u = UUID3(ud) - return nil - } - return fmt.Errorf("couldn't unmarshal bson bytes as UUID3: %w", ErrFormat) -} - // DeepCopyInto copies the receiver and writes its value into out. func (u *UUID3) DeepCopyInto(out *UUID3) { *out = *u @@ -1363,7 +1193,7 @@ func (u *UUID4) UnmarshalText(data []byte) error { // validation is performed la } // Scan read a value from a database driver -func (u *UUID4) Scan(raw interface{}) error { +func (u *UUID4) Scan(raw any) error { switch v := raw.(type) { case []byte: *u = UUID4(string(v)) @@ -1403,25 +1233,6 @@ func (u *UUID4) UnmarshalJSON(data []byte) error { return nil } -// MarshalBSON document from this value -func (u UUID4) MarshalBSON() ([]byte, error) { - return bson.Marshal(bson.M{"data": u.String()}) -} - -// UnmarshalBSON document into this value -func (u *UUID4) UnmarshalBSON(data []byte) error { - var m bson.M - if err := bson.Unmarshal(data, &m); err != nil { - return err - } - - if ud, ok := m["data"].(string); ok { - *u = UUID4(ud) - return nil - } - return fmt.Errorf("couldn't unmarshal bson bytes as UUID4: %w", ErrFormat) -} - // DeepCopyInto copies the receiver and writes its value into out. func (u *UUID4) DeepCopyInto(out *UUID4) { *out = *u @@ -1454,7 +1265,7 @@ func (u *UUID5) UnmarshalText(data []byte) error { // validation is performed la } // Scan read a value from a database driver -func (u *UUID5) Scan(raw interface{}) error { +func (u *UUID5) Scan(raw any) error { switch v := raw.(type) { case []byte: *u = UUID5(string(v)) @@ -1494,36 +1305,89 @@ func (u *UUID5) UnmarshalJSON(data []byte) error { return nil } -// MarshalBSON document from this value -func (u UUID5) MarshalBSON() ([]byte, error) { - return bson.Marshal(bson.M{"data": u.String()}) +// DeepCopyInto copies the receiver and writes its value into out. +func (u *UUID5) DeepCopyInto(out *UUID5) { + *out = *u } -// UnmarshalBSON document into this value -func (u *UUID5) UnmarshalBSON(data []byte) error { - var m bson.M - if err := bson.Unmarshal(data, &m); err != nil { - return err +// DeepCopy copies the receiver into a new UUID5. +func (u *UUID5) DeepCopy() *UUID5 { + if u == nil { + return nil } + out := new(UUID5) + u.DeepCopyInto(out) + return out +} - if ud, ok := m["data"].(string); ok { - *u = UUID5(ud) +// UUID7 represents a uuid7 string format +// +// swagger:strfmt uuid7 +type UUID7 string + +// MarshalText turns this instance into text +func (u UUID7) MarshalText() ([]byte, error) { + return []byte(string(u)), nil +} + +// UnmarshalText hydrates this instance from text +func (u *UUID7) UnmarshalText(data []byte) error { // validation is performed later on + *u = UUID7(string(data)) + return nil +} + +// Scan read a value from a database driver +func (u *UUID7) Scan(raw any) error { + switch v := raw.(type) { + case []byte: + *u = UUID7(string(v)) + case string: + *u = UUID7(v) + default: + return fmt.Errorf("cannot sql.Scan() strfmt.UUID7 from: %#v: %w", v, ErrFormat) + } + + return nil +} + +// Value converts a value to a database driver value +func (u UUID7) Value() (driver.Value, error) { + return driver.Value(string(u)), nil +} + +func (u UUID7) String() string { + return string(u) +} + +// MarshalJSON returns the UUID as JSON +func (u UUID7) MarshalJSON() ([]byte, error) { + return json.Marshal(string(u)) +} + +// UnmarshalJSON sets the UUID from JSON +func (u *UUID7) UnmarshalJSON(data []byte) error { + if string(data) == jsonNull { return nil } - return fmt.Errorf("couldn't unmarshal bson bytes as UUID5: %w", ErrFormat) + var ustr string + if err := json.Unmarshal(data, &ustr); err != nil { + return err + } + *u = UUID7(ustr) + return nil } // DeepCopyInto copies the receiver and writes its value into out. -func (u *UUID5) DeepCopyInto(out *UUID5) { +func (u *UUID7) DeepCopyInto(out *UUID7) { *out = *u } -// DeepCopy copies the receiver into a new UUID5. -func (u *UUID5) DeepCopy() *UUID5 { +// DeepCopy copies the receiver into a new UUID7. +func (u *UUID7) DeepCopy() *UUID7 { if u == nil { return nil } - out := new(UUID5) + out := new(UUID7) u.DeepCopyInto(out) return out } @@ -1545,7 +1409,7 @@ func (u *ISBN) UnmarshalText(data []byte) error { // validation is performed lat } // Scan read a value from a database driver -func (u *ISBN) Scan(raw interface{}) error { +func (u *ISBN) Scan(raw any) error { switch v := raw.(type) { case []byte: *u = ISBN(string(v)) @@ -1585,25 +1449,6 @@ func (u *ISBN) UnmarshalJSON(data []byte) error { return nil } -// MarshalBSON document from this value -func (u ISBN) MarshalBSON() ([]byte, error) { - return bson.Marshal(bson.M{"data": u.String()}) -} - -// UnmarshalBSON document into this value -func (u *ISBN) UnmarshalBSON(data []byte) error { - var m bson.M - if err := bson.Unmarshal(data, &m); err != nil { - return err - } - - if ud, ok := m["data"].(string); ok { - *u = ISBN(ud) - return nil - } - return fmt.Errorf("couldn't unmarshal bson bytes as ISBN: %w", ErrFormat) -} - // DeepCopyInto copies the receiver and writes its value into out. func (u *ISBN) DeepCopyInto(out *ISBN) { *out = *u @@ -1636,7 +1481,7 @@ func (u *ISBN10) UnmarshalText(data []byte) error { // validation is performed l } // Scan read a value from a database driver -func (u *ISBN10) Scan(raw interface{}) error { +func (u *ISBN10) Scan(raw any) error { switch v := raw.(type) { case []byte: *u = ISBN10(string(v)) @@ -1676,25 +1521,6 @@ func (u *ISBN10) UnmarshalJSON(data []byte) error { return nil } -// MarshalBSON document from this value -func (u ISBN10) MarshalBSON() ([]byte, error) { - return bson.Marshal(bson.M{"data": u.String()}) -} - -// UnmarshalBSON document into this value -func (u *ISBN10) UnmarshalBSON(data []byte) error { - var m bson.M - if err := bson.Unmarshal(data, &m); err != nil { - return err - } - - if ud, ok := m["data"].(string); ok { - *u = ISBN10(ud) - return nil - } - return fmt.Errorf("couldn't unmarshal bson bytes as ISBN10: %w", ErrFormat) -} - // DeepCopyInto copies the receiver and writes its value into out. func (u *ISBN10) DeepCopyInto(out *ISBN10) { *out = *u @@ -1727,7 +1553,7 @@ func (u *ISBN13) UnmarshalText(data []byte) error { // validation is performed l } // Scan read a value from a database driver -func (u *ISBN13) Scan(raw interface{}) error { +func (u *ISBN13) Scan(raw any) error { switch v := raw.(type) { case []byte: *u = ISBN13(string(v)) @@ -1767,25 +1593,6 @@ func (u *ISBN13) UnmarshalJSON(data []byte) error { return nil } -// MarshalBSON document from this value -func (u ISBN13) MarshalBSON() ([]byte, error) { - return bson.Marshal(bson.M{"data": u.String()}) -} - -// UnmarshalBSON document into this value -func (u *ISBN13) UnmarshalBSON(data []byte) error { - var m bson.M - if err := bson.Unmarshal(data, &m); err != nil { - return err - } - - if ud, ok := m["data"].(string); ok { - *u = ISBN13(ud) - return nil - } - return fmt.Errorf("couldn't unmarshal bson bytes as ISBN13: %w", ErrFormat) -} - // DeepCopyInto copies the receiver and writes its value into out. func (u *ISBN13) DeepCopyInto(out *ISBN13) { *out = *u @@ -1818,7 +1625,7 @@ func (u *CreditCard) UnmarshalText(data []byte) error { // validation is perform } // Scan read a value from a database driver -func (u *CreditCard) Scan(raw interface{}) error { +func (u *CreditCard) Scan(raw any) error { switch v := raw.(type) { case []byte: *u = CreditCard(string(v)) @@ -1858,25 +1665,6 @@ func (u *CreditCard) UnmarshalJSON(data []byte) error { return nil } -// MarshalBSON document from this value -func (u CreditCard) MarshalBSON() ([]byte, error) { - return bson.Marshal(bson.M{"data": u.String()}) -} - -// UnmarshalBSON document into this value -func (u *CreditCard) UnmarshalBSON(data []byte) error { - var m bson.M - if err := bson.Unmarshal(data, &m); err != nil { - return err - } - - if ud, ok := m["data"].(string); ok { - *u = CreditCard(ud) - return nil - } - return fmt.Errorf("couldn't unmarshal bson bytes as CreditCard: %w", ErrFormat) -} - // DeepCopyInto copies the receiver and writes its value into out. func (u *CreditCard) DeepCopyInto(out *CreditCard) { *out = *u @@ -1909,7 +1697,7 @@ func (u *SSN) UnmarshalText(data []byte) error { // validation is performed late } // Scan read a value from a database driver -func (u *SSN) Scan(raw interface{}) error { +func (u *SSN) Scan(raw any) error { switch v := raw.(type) { case []byte: *u = SSN(string(v)) @@ -1949,25 +1737,6 @@ func (u *SSN) UnmarshalJSON(data []byte) error { return nil } -// MarshalBSON document from this value -func (u SSN) MarshalBSON() ([]byte, error) { - return bson.Marshal(bson.M{"data": u.String()}) -} - -// UnmarshalBSON document into this value -func (u *SSN) UnmarshalBSON(data []byte) error { - var m bson.M - if err := bson.Unmarshal(data, &m); err != nil { - return err - } - - if ud, ok := m["data"].(string); ok { - *u = SSN(ud) - return nil - } - return fmt.Errorf("couldn't unmarshal bson bytes as SSN: %w", ErrFormat) -} - // DeepCopyInto copies the receiver and writes its value into out. func (u *SSN) DeepCopyInto(out *SSN) { *out = *u @@ -2000,7 +1769,7 @@ func (h *HexColor) UnmarshalText(data []byte) error { // validation is performed } // Scan read a value from a database driver -func (h *HexColor) Scan(raw interface{}) error { +func (h *HexColor) Scan(raw any) error { switch v := raw.(type) { case []byte: *h = HexColor(string(v)) @@ -2040,25 +1809,6 @@ func (h *HexColor) UnmarshalJSON(data []byte) error { return nil } -// MarshalBSON document from this value -func (h HexColor) MarshalBSON() ([]byte, error) { - return bson.Marshal(bson.M{"data": h.String()}) -} - -// UnmarshalBSON document into this value -func (h *HexColor) UnmarshalBSON(data []byte) error { - var m bson.M - if err := bson.Unmarshal(data, &m); err != nil { - return err - } - - if ud, ok := m["data"].(string); ok { - *h = HexColor(ud) - return nil - } - return fmt.Errorf("couldn't unmarshal bson bytes as HexColor: %w", ErrFormat) -} - // DeepCopyInto copies the receiver and writes its value into out. func (h *HexColor) DeepCopyInto(out *HexColor) { *out = *h @@ -2091,7 +1841,7 @@ func (r *RGBColor) UnmarshalText(data []byte) error { // validation is performed } // Scan read a value from a database driver -func (r *RGBColor) Scan(raw interface{}) error { +func (r *RGBColor) Scan(raw any) error { switch v := raw.(type) { case []byte: *r = RGBColor(string(v)) @@ -2131,25 +1881,6 @@ func (r *RGBColor) UnmarshalJSON(data []byte) error { return nil } -// MarshalBSON document from this value -func (r RGBColor) MarshalBSON() ([]byte, error) { - return bson.Marshal(bson.M{"data": r.String()}) -} - -// UnmarshalBSON document into this value -func (r *RGBColor) UnmarshalBSON(data []byte) error { - var m bson.M - if err := bson.Unmarshal(data, &m); err != nil { - return err - } - - if ud, ok := m["data"].(string); ok { - *r = RGBColor(ud) - return nil - } - return fmt.Errorf("couldn't unmarshal bson bytes as RGBColor: %w", ErrFormat) -} - // DeepCopyInto copies the receiver and writes its value into out. func (r *RGBColor) DeepCopyInto(out *RGBColor) { *out = *r @@ -2183,7 +1914,7 @@ func (r *Password) UnmarshalText(data []byte) error { // validation is performed } // Scan read a value from a database driver -func (r *Password) Scan(raw interface{}) error { +func (r *Password) Scan(raw any) error { switch v := raw.(type) { case []byte: *r = Password(string(v)) @@ -2223,25 +1954,6 @@ func (r *Password) UnmarshalJSON(data []byte) error { return nil } -// MarshalBSON document from this value -func (r Password) MarshalBSON() ([]byte, error) { - return bson.Marshal(bson.M{"data": r.String()}) -} - -// UnmarshalBSON document into this value -func (r *Password) UnmarshalBSON(data []byte) error { - var m bson.M - if err := bson.Unmarshal(data, &m); err != nil { - return err - } - - if ud, ok := m["data"].(string); ok { - *r = Password(ud) - return nil - } - return fmt.Errorf("couldn't unmarshal bson bytes as Password: %w", ErrFormat) -} - // DeepCopyInto copies the receiver and writes its value into out. func (r *Password) DeepCopyInto(out *Password) { *out = *r @@ -2256,3 +1968,143 @@ func (r *Password) DeepCopy() *Password { r.DeepCopyInto(out) return out } + +func isRequestURI(rawurl string) bool { + _, err := url.ParseRequestURI(rawurl) + return err == nil +} + +// isIPv4 checks if the string is an IP version 4. +func isIPv4(str string) bool { + ip := net.ParseIP(str) + return ip != nil && strings.Contains(str, ".") +} + +// isIPv6 checks if the string is an IP version 6. +func isIPv6(str string) bool { + ip := net.ParseIP(str) + return ip != nil && strings.Contains(str, ":") +} + +// isCIDR checks if the string is an valid CIDR notiation (IPV4 & IPV6) +func isCIDR(str string) bool { + _, _, err := net.ParseCIDR(str) + return err == nil +} + +// isMAC checks if a string is valid MAC address. +// Possible MAC formats: +// 01:23:45:67:89:ab +// 01:23:45:67:89:ab:cd:ef +// 01-23-45-67-89-ab +// 01-23-45-67-89-ab-cd-ef +// 0123.4567.89ab +// 0123.4567.89ab.cdef +func isMAC(str string) bool { + _, err := net.ParseMAC(str) + return err == nil +} + +// isISBN checks if the string is an ISBN (version 10 or 13). +// If version value is not equal to 10 or 13, it will be checks both variants. +func isISBN(str string, version int) bool { + sanitized := whiteSpacesAndMinus.ReplaceAllString(str, "") + var checksum int32 + var i int32 + + switch version { + case isbnVersion10: + if !rxISBN10.MatchString(sanitized) { + return false + } + for i = range isbnVersion10 - 1 { + checksum += (i + 1) * int32(sanitized[i]-'0') + } + if sanitized[isbnVersion10-1] == 'X' { + checksum += isbnVersion10 * isbnVersion10 + } else { + checksum += isbnVersion10 * int32(sanitized[isbnVersion10-1]-'0') + } + if checksum%(isbnVersion10+1) == 0 { + return true + } + return false + case isbnVersion13: + if !rxISBN13.MatchString(sanitized) { + return false + } + factor := []int32{1, 3} + for i = range isbnVersion13 - 1 { + checksum += factor[i%2] * int32(sanitized[i]-'0') + } + return (int32(sanitized[isbnVersion13-1]-'0'))-((decimalBase-(checksum%decimalBase))%decimalBase) == 0 + default: + return isISBN(str, isbnVersion10) || isISBN(str, isbnVersion13) + } +} + +// isISBN10 checks if the string is an ISBN version 10. +func isISBN10(str string) bool { + return isISBN(str, isbnVersion10) +} + +// isISBN13 checks if the string is an ISBN version 13. +func isISBN13(str string) bool { + return isISBN(str, isbnVersion13) +} + +// isCreditCard checks if the string is a credit card. +func isCreditCard(str string) bool { + sanitized := whiteSpacesAndMinus.ReplaceAllString(str, "") + if !rxCreditCard.MatchString(sanitized) { + return false + } + + number, err := strconv.ParseInt(sanitized, 0, 64) + if err != nil { + return false + } + number, lastDigit := number/decimalBase, number%decimalBase + + var sum int64 + for i := 0; number > 0; i++ { + digit := number % decimalBase + + if i%2 == 0 { + digit *= 2 + if digit > decimalBase-1 { + digit -= decimalBase - 1 + } + } + + sum += digit + number /= decimalBase + } + + return (sum+lastDigit)%decimalBase == 0 +} + +// isSSN will validate the given string as a U.S. Social Security Number +func isSSN(str string) bool { + if str == "" || len(str) != 11 { + return false + } + return rxSSN.MatchString(str) +} + +// isHexcolor checks if the string is a hexadecimal color. +func isHexcolor(str string) bool { + return rxHexcolor.MatchString(str) +} + +// isRGBcolor checks if the string is a valid RGB color in form rgb(RRR, GGG, BBB). +func isRGBcolor(str string) bool { + return rxRGBcolor.MatchString(str) +} + +// isBase64 checks if a string is base64 encoded. +func isBase64(str string) bool { + _, err := base64.StdEncoding.DecodeString(str) + + return err == nil +} diff --git a/vendor/github.com/go-openapi/strfmt/doc.go b/vendor/github.com/go-openapi/strfmt/doc.go index 41aebe6d51a..5825b72108e 100644 --- a/vendor/github.com/go-openapi/strfmt/doc.go +++ b/vendor/github.com/go-openapi/strfmt/doc.go @@ -1,16 +1,5 @@ -// Copyright 2015 go-swagger maintainers -// -// 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. +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 // Package strfmt contains custom string formats // diff --git a/vendor/github.com/go-openapi/strfmt/duration.go b/vendor/github.com/go-openapi/strfmt/duration.go index 749c4b561c2..908c1b02f3c 100644 --- a/vendor/github.com/go-openapi/strfmt/duration.go +++ b/vendor/github.com/go-openapi/strfmt/duration.go @@ -1,16 +1,5 @@ -// Copyright 2015 go-swagger maintainers -// -// 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. +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 package strfmt @@ -23,8 +12,6 @@ import ( "strconv" "strings" "time" - - "go.mongodb.org/mongo-driver/bson" ) func init() { @@ -154,7 +141,7 @@ func ParseDuration(cand string) (time.Duration, error) { } // Scan reads a Duration value from database driver type. -func (d *Duration) Scan(raw interface{}) error { +func (d *Duration) Scan(raw any) error { switch v := raw.(type) { // TODO: case []byte: // ? case int64: @@ -203,28 +190,6 @@ func (d *Duration) UnmarshalJSON(data []byte) error { return nil } -func (d Duration) MarshalBSON() ([]byte, error) { - return bson.Marshal(bson.M{"data": d.String()}) -} - -func (d *Duration) UnmarshalBSON(data []byte) error { - var m bson.M - if err := bson.Unmarshal(data, &m); err != nil { - return err - } - - if data, ok := m["data"].(string); ok { - rd, err := ParseDuration(data) - if err != nil { - return err - } - *d = Duration(rd) - return nil - } - - return fmt.Errorf("couldn't unmarshal bson bytes value as Date: %w", ErrFormat) -} - // DeepCopyInto copies the receiver and writes its value into out. func (d *Duration) DeepCopyInto(out *Duration) { *out = *d diff --git a/vendor/github.com/go-openapi/strfmt/errors.go b/vendor/github.com/go-openapi/strfmt/errors.go index 9a9240363de..9faa37cf2e5 100644 --- a/vendor/github.com/go-openapi/strfmt/errors.go +++ b/vendor/github.com/go-openapi/strfmt/errors.go @@ -1,3 +1,6 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + package strfmt type strfmtError string diff --git a/vendor/github.com/go-openapi/strfmt/format.go b/vendor/github.com/go-openapi/strfmt/format.go index 73f83af9c92..d9d9e04c208 100644 --- a/vendor/github.com/go-openapi/strfmt/format.go +++ b/vendor/github.com/go-openapi/strfmt/format.go @@ -1,16 +1,5 @@ -// Copyright 2015 go-swagger maintainers -// -// 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. +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 package strfmt @@ -18,6 +7,7 @@ import ( "encoding" "fmt" "reflect" + "slices" "strings" "sync" "time" @@ -32,27 +22,6 @@ var Default = NewSeededFormats(nil, nil) // Validator represents a validator for a string format. type Validator func(string) bool -// Format represents a string format. -// -// All implementations of Format provide a string representation and text -// marshaling/unmarshaling interface to be used by encoders (e.g. encoding/json). -type Format interface { - String() string - encoding.TextMarshaler - encoding.TextUnmarshaler -} - -// Registry is a registry of string formats, with a validation method. -type Registry interface { - Add(string, Format, Validator) bool - DelByName(string) bool - GetType(string) (reflect.Type, bool) - ContainsName(string) bool - Validates(string, string) bool - Parse(string, string) (any, error) - MapStructureHookFunc() mapstructure.DecodeHookFunc -} - // NewFormats creates a new formats registry seeded with the values from the default func NewFormats() Registry { //nolint:forcetypeassert @@ -64,10 +33,9 @@ func NewSeededFormats(seeds []knownFormat, normalizer NameNormalizer) Registry { if normalizer == nil { normalizer = DefaultNameNormalizer } - // copy here, don't modify original - d := append([]knownFormat(nil), seeds...) + // copy here, don't modify the original return &defaultFormats{ - data: d, + data: slices.Clone(seeds), normalizeName: normalizer, } } @@ -139,6 +107,8 @@ func (f *defaultFormats) MapStructureHookFunc() mapstructure.DecodeHookFunc { return UUID4(data), nil case "uuid5": return UUID5(data), nil + case "uuid7": + return UUID7(data), nil case "hostname": return Hostname(data), nil case "ipv4": diff --git a/vendor/github.com/go-openapi/strfmt/ifaces.go b/vendor/github.com/go-openapi/strfmt/ifaces.go new file mode 100644 index 00000000000..1b9e72c64eb --- /dev/null +++ b/vendor/github.com/go-openapi/strfmt/ifaces.go @@ -0,0 +1,32 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +package strfmt + +import ( + "encoding" + "reflect" + + "github.com/go-viper/mapstructure/v2" +) + +// Format represents a string format. +// +// All implementations of Format provide a string representation and text +// marshaling/unmarshaling interface to be used by encoders (e.g. encoding/json). +type Format interface { + String() string + encoding.TextMarshaler + encoding.TextUnmarshaler +} + +// Registry is a registry of string formats, with a validation method. +type Registry interface { + Add(string, Format, Validator) bool + DelByName(string) bool + GetType(string) (reflect.Type, bool) + ContainsName(string) bool + Validates(string, string) bool + Parse(string, string) (any, error) + MapStructureHookFunc() mapstructure.DecodeHookFunc +} diff --git a/vendor/github.com/go-openapi/strfmt/mongo.go b/vendor/github.com/go-openapi/strfmt/mongo.go new file mode 100644 index 00000000000..641fed9b1a6 --- /dev/null +++ b/vendor/github.com/go-openapi/strfmt/mongo.go @@ -0,0 +1,646 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +package strfmt + +import ( + "encoding/base64" + "encoding/binary" + "fmt" + "time" + + "github.com/oklog/ulid" + "go.mongodb.org/mongo-driver/bson" + "go.mongodb.org/mongo-driver/bson/bsontype" + bsonprim "go.mongodb.org/mongo-driver/bson/primitive" +) + +var ( + _ bson.Marshaler = Date{} + _ bson.Unmarshaler = &Date{} + _ bson.Marshaler = Base64{} + _ bson.Unmarshaler = &Base64{} + _ bson.Marshaler = Duration(0) + _ bson.Unmarshaler = (*Duration)(nil) + _ bson.Marshaler = DateTime{} + _ bson.Unmarshaler = &DateTime{} + _ bson.Marshaler = ULID{} + _ bson.Unmarshaler = &ULID{} + _ bson.Marshaler = URI("") + _ bson.Unmarshaler = (*URI)(nil) + _ bson.Marshaler = Email("") + _ bson.Unmarshaler = (*Email)(nil) + _ bson.Marshaler = Hostname("") + _ bson.Unmarshaler = (*Hostname)(nil) + _ bson.Marshaler = IPv4("") + _ bson.Unmarshaler = (*IPv4)(nil) + _ bson.Marshaler = IPv6("") + _ bson.Unmarshaler = (*IPv6)(nil) + _ bson.Marshaler = CIDR("") + _ bson.Unmarshaler = (*CIDR)(nil) + _ bson.Marshaler = MAC("") + _ bson.Unmarshaler = (*MAC)(nil) + _ bson.Marshaler = Password("") + _ bson.Unmarshaler = (*Password)(nil) + _ bson.Marshaler = UUID("") + _ bson.Unmarshaler = (*UUID)(nil) + _ bson.Marshaler = UUID3("") + _ bson.Unmarshaler = (*UUID3)(nil) + _ bson.Marshaler = UUID4("") + _ bson.Unmarshaler = (*UUID4)(nil) + _ bson.Marshaler = UUID5("") + _ bson.Unmarshaler = (*UUID5)(nil) + _ bson.Marshaler = UUID7("") + _ bson.Unmarshaler = (*UUID7)(nil) + _ bson.Marshaler = ISBN("") + _ bson.Unmarshaler = (*ISBN)(nil) + _ bson.Marshaler = ISBN10("") + _ bson.Unmarshaler = (*ISBN10)(nil) + _ bson.Marshaler = ISBN13("") + _ bson.Unmarshaler = (*ISBN13)(nil) + _ bson.Marshaler = CreditCard("") + _ bson.Unmarshaler = (*CreditCard)(nil) + _ bson.Marshaler = SSN("") + _ bson.Unmarshaler = (*SSN)(nil) + _ bson.Marshaler = HexColor("") + _ bson.Unmarshaler = (*HexColor)(nil) + _ bson.Marshaler = RGBColor("") + _ bson.Unmarshaler = (*RGBColor)(nil) + _ bson.Marshaler = ObjectId{} + _ bson.Unmarshaler = &ObjectId{} + + _ bson.ValueMarshaler = DateTime{} + _ bson.ValueUnmarshaler = &DateTime{} + _ bson.ValueMarshaler = ObjectId{} + _ bson.ValueUnmarshaler = &ObjectId{} +) + +const ( + millisec = 1000 + microsec = 1_000_000 + bsonDateTimeSize = 8 +) + +func (d Date) MarshalBSON() ([]byte, error) { + return bson.Marshal(bson.M{"data": d.String()}) +} + +func (d *Date) UnmarshalBSON(data []byte) error { + var m bson.M + if err := bson.Unmarshal(data, &m); err != nil { + return err + } + + if data, ok := m["data"].(string); ok { + rd, err := time.ParseInLocation(RFC3339FullDate, data, DefaultTimeLocation) + if err != nil { + return err + } + *d = Date(rd) + return nil + } + + return fmt.Errorf("couldn't unmarshal bson bytes value as Date: %w", ErrFormat) +} + +// MarshalBSON document from this value +func (b Base64) MarshalBSON() ([]byte, error) { + return bson.Marshal(bson.M{"data": b.String()}) +} + +// UnmarshalBSON document into this value +func (b *Base64) UnmarshalBSON(data []byte) error { + var m bson.M + if err := bson.Unmarshal(data, &m); err != nil { + return err + } + + if bd, ok := m["data"].(string); ok { + vb, err := base64.StdEncoding.DecodeString(bd) + if err != nil { + return err + } + *b = Base64(vb) + return nil + } + return fmt.Errorf("couldn't unmarshal bson bytes as base64: %w", ErrFormat) +} + +func (d Duration) MarshalBSON() ([]byte, error) { + return bson.Marshal(bson.M{"data": d.String()}) +} + +func (d *Duration) UnmarshalBSON(data []byte) error { + var m bson.M + if err := bson.Unmarshal(data, &m); err != nil { + return err + } + + if data, ok := m["data"].(string); ok { + rd, err := ParseDuration(data) + if err != nil { + return err + } + *d = Duration(rd) + return nil + } + + return fmt.Errorf("couldn't unmarshal bson bytes value as Date: %w", ErrFormat) +} + +// MarshalBSON renders the DateTime as a BSON document +func (t DateTime) MarshalBSON() ([]byte, error) { + return bson.Marshal(bson.M{"data": t}) +} + +// UnmarshalBSON reads the DateTime from a BSON document +func (t *DateTime) UnmarshalBSON(data []byte) error { + var obj struct { + Data DateTime + } + + if err := bson.Unmarshal(data, &obj); err != nil { + return err + } + + *t = obj.Data + + return nil +} + +// MarshalBSONValue is an interface implemented by types that can marshal themselves +// into a BSON document represented as bytes. The bytes returned must be a valid +// BSON document if the error is nil. +// +// Marshals a DateTime as a bson.TypeDateTime, an int64 representing +// milliseconds since epoch. +func (t DateTime) MarshalBSONValue() (bsontype.Type, []byte, error) { + // UnixNano cannot be used directly, the result of calling UnixNano on the zero + // Time is undefined. Thats why we use time.Nanosecond() instead. + + tNorm := NormalizeTimeForMarshal(time.Time(t)) + i64 := tNorm.Unix()*millisec + int64(tNorm.Nanosecond())/microsec + buf := make([]byte, bsonDateTimeSize) + binary.LittleEndian.PutUint64(buf, uint64(i64)) //nolint:gosec // it's okay to handle negative int64 this way + + return bson.TypeDateTime, buf, nil +} + +// UnmarshalBSONValue is an interface implemented by types that can unmarshal a +// BSON value representation of themselves. The BSON bytes and type can be +// assumed to be valid. UnmarshalBSONValue must copy the BSON value bytes if it +// wishes to retain the data after returning. +func (t *DateTime) UnmarshalBSONValue(tpe bsontype.Type, data []byte) error { + if tpe == bson.TypeNull { + *t = DateTime{} + return nil + } + + if len(data) != bsonDateTimeSize { + return fmt.Errorf("bson date field length not exactly %d bytes: %w", bsonDateTimeSize, ErrFormat) + } + + i64 := int64(binary.LittleEndian.Uint64(data)) //nolint:gosec // it's okay if we overflow and get a negative datetime + *t = DateTime(time.Unix(i64/millisec, i64%millisec*microsec)) + + return nil +} + +// MarshalBSON document from this value +func (u ULID) MarshalBSON() ([]byte, error) { + return bson.Marshal(bson.M{"data": u.String()}) +} + +// UnmarshalBSON document into this value +func (u *ULID) UnmarshalBSON(data []byte) error { + var m bson.M + if err := bson.Unmarshal(data, &m); err != nil { + return err + } + + if ud, ok := m["data"].(string); ok { + id, err := ulid.ParseStrict(ud) + if err != nil { + return fmt.Errorf("couldn't parse bson bytes as ULID: %w: %w", err, ErrFormat) + } + u.ULID = id + return nil + } + return fmt.Errorf("couldn't unmarshal bson bytes as ULID: %w", ErrFormat) +} + +// MarshalBSON document from this value +func (u URI) MarshalBSON() ([]byte, error) { + return bson.Marshal(bson.M{"data": u.String()}) +} + +// UnmarshalBSON document into this value +func (u *URI) UnmarshalBSON(data []byte) error { + var m bson.M + if err := bson.Unmarshal(data, &m); err != nil { + return err + } + + if ud, ok := m["data"].(string); ok { + *u = URI(ud) + return nil + } + return fmt.Errorf("couldn't unmarshal bson bytes as uri: %w", ErrFormat) +} + +// MarshalBSON document from this value +func (e Email) MarshalBSON() ([]byte, error) { + return bson.Marshal(bson.M{"data": e.String()}) +} + +// UnmarshalBSON document into this value +func (e *Email) UnmarshalBSON(data []byte) error { + var m bson.M + if err := bson.Unmarshal(data, &m); err != nil { + return err + } + + if ud, ok := m["data"].(string); ok { + *e = Email(ud) + return nil + } + return fmt.Errorf("couldn't unmarshal bson bytes as email: %w", ErrFormat) +} + +// MarshalBSON document from this value +func (h Hostname) MarshalBSON() ([]byte, error) { + return bson.Marshal(bson.M{"data": h.String()}) +} + +// UnmarshalBSON document into this value +func (h *Hostname) UnmarshalBSON(data []byte) error { + var m bson.M + if err := bson.Unmarshal(data, &m); err != nil { + return err + } + + if ud, ok := m["data"].(string); ok { + *h = Hostname(ud) + return nil + } + return fmt.Errorf("couldn't unmarshal bson bytes as hostname: %w", ErrFormat) +} + +// MarshalBSON document from this value +func (u IPv4) MarshalBSON() ([]byte, error) { + return bson.Marshal(bson.M{"data": u.String()}) +} + +// UnmarshalBSON document into this value +func (u *IPv4) UnmarshalBSON(data []byte) error { + var m bson.M + if err := bson.Unmarshal(data, &m); err != nil { + return err + } + + if ud, ok := m["data"].(string); ok { + *u = IPv4(ud) + return nil + } + return fmt.Errorf("couldn't unmarshal bson bytes as ipv4: %w", ErrFormat) +} + +// MarshalBSON document from this value +func (u IPv6) MarshalBSON() ([]byte, error) { + return bson.Marshal(bson.M{"data": u.String()}) +} + +// UnmarshalBSON document into this value +func (u *IPv6) UnmarshalBSON(data []byte) error { + var m bson.M + if err := bson.Unmarshal(data, &m); err != nil { + return err + } + + if ud, ok := m["data"].(string); ok { + *u = IPv6(ud) + return nil + } + return fmt.Errorf("couldn't unmarshal bson bytes as ipv6: %w", ErrFormat) +} + +// MarshalBSON document from this value +func (u CIDR) MarshalBSON() ([]byte, error) { + return bson.Marshal(bson.M{"data": u.String()}) +} + +// UnmarshalBSON document into this value +func (u *CIDR) UnmarshalBSON(data []byte) error { + var m bson.M + if err := bson.Unmarshal(data, &m); err != nil { + return err + } + + if ud, ok := m["data"].(string); ok { + *u = CIDR(ud) + return nil + } + return fmt.Errorf("couldn't unmarshal bson bytes as CIDR: %w", ErrFormat) +} + +// MarshalBSON document from this value +func (u MAC) MarshalBSON() ([]byte, error) { + return bson.Marshal(bson.M{"data": u.String()}) +} + +// UnmarshalBSON document into this value +func (u *MAC) UnmarshalBSON(data []byte) error { + var m bson.M + if err := bson.Unmarshal(data, &m); err != nil { + return err + } + + if ud, ok := m["data"].(string); ok { + *u = MAC(ud) + return nil + } + return fmt.Errorf("couldn't unmarshal bson bytes as MAC: %w", ErrFormat) +} + +// MarshalBSON document from this value +func (r Password) MarshalBSON() ([]byte, error) { + return bson.Marshal(bson.M{"data": r.String()}) +} + +// UnmarshalBSON document into this value +func (r *Password) UnmarshalBSON(data []byte) error { + var m bson.M + if err := bson.Unmarshal(data, &m); err != nil { + return err + } + + if ud, ok := m["data"].(string); ok { + *r = Password(ud) + return nil + } + return fmt.Errorf("couldn't unmarshal bson bytes as Password: %w", ErrFormat) +} + +// MarshalBSON document from this value +func (u UUID) MarshalBSON() ([]byte, error) { + return bson.Marshal(bson.M{"data": u.String()}) +} + +// UnmarshalBSON document into this value +func (u *UUID) UnmarshalBSON(data []byte) error { + var m bson.M + if err := bson.Unmarshal(data, &m); err != nil { + return err + } + + if ud, ok := m["data"].(string); ok { + *u = UUID(ud) + return nil + } + return fmt.Errorf("couldn't unmarshal bson bytes as UUID: %w", ErrFormat) +} + +// MarshalBSON document from this value +func (u UUID3) MarshalBSON() ([]byte, error) { + return bson.Marshal(bson.M{"data": u.String()}) +} + +// UnmarshalBSON document into this value +func (u *UUID3) UnmarshalBSON(data []byte) error { + var m bson.M + if err := bson.Unmarshal(data, &m); err != nil { + return err + } + + if ud, ok := m["data"].(string); ok { + *u = UUID3(ud) + return nil + } + return fmt.Errorf("couldn't unmarshal bson bytes as UUID3: %w", ErrFormat) +} + +// MarshalBSON document from this value +func (u UUID4) MarshalBSON() ([]byte, error) { + return bson.Marshal(bson.M{"data": u.String()}) +} + +// UnmarshalBSON document into this value +func (u *UUID4) UnmarshalBSON(data []byte) error { + var m bson.M + if err := bson.Unmarshal(data, &m); err != nil { + return err + } + + if ud, ok := m["data"].(string); ok { + *u = UUID4(ud) + return nil + } + return fmt.Errorf("couldn't unmarshal bson bytes as UUID4: %w", ErrFormat) +} + +// MarshalBSON document from this value +func (u UUID5) MarshalBSON() ([]byte, error) { + return bson.Marshal(bson.M{"data": u.String()}) +} + +// UnmarshalBSON document into this value +func (u *UUID5) UnmarshalBSON(data []byte) error { + var m bson.M + if err := bson.Unmarshal(data, &m); err != nil { + return err + } + + if ud, ok := m["data"].(string); ok { + *u = UUID5(ud) + return nil + } + return fmt.Errorf("couldn't unmarshal bson bytes as UUID5: %w", ErrFormat) +} + +// MarshalBSON document from this value +func (u UUID7) MarshalBSON() ([]byte, error) { + return bson.Marshal(bson.M{"data": u.String()}) +} + +// UnmarshalBSON document into this value +func (u *UUID7) UnmarshalBSON(data []byte) error { + var m bson.M + if err := bson.Unmarshal(data, &m); err != nil { + return err + } + + if ud, ok := m["data"].(string); ok { + *u = UUID7(ud) + return nil + } + return fmt.Errorf("couldn't unmarshal bson bytes as UUID7: %w", ErrFormat) +} + +// MarshalBSON document from this value +func (u ISBN) MarshalBSON() ([]byte, error) { + return bson.Marshal(bson.M{"data": u.String()}) +} + +// UnmarshalBSON document into this value +func (u *ISBN) UnmarshalBSON(data []byte) error { + var m bson.M + if err := bson.Unmarshal(data, &m); err != nil { + return err + } + + if ud, ok := m["data"].(string); ok { + *u = ISBN(ud) + return nil + } + return fmt.Errorf("couldn't unmarshal bson bytes as ISBN: %w", ErrFormat) +} + +// MarshalBSON document from this value +func (u ISBN10) MarshalBSON() ([]byte, error) { + return bson.Marshal(bson.M{"data": u.String()}) +} + +// UnmarshalBSON document into this value +func (u *ISBN10) UnmarshalBSON(data []byte) error { + var m bson.M + if err := bson.Unmarshal(data, &m); err != nil { + return err + } + + if ud, ok := m["data"].(string); ok { + *u = ISBN10(ud) + return nil + } + return fmt.Errorf("couldn't unmarshal bson bytes as ISBN10: %w", ErrFormat) +} + +// MarshalBSON document from this value +func (u ISBN13) MarshalBSON() ([]byte, error) { + return bson.Marshal(bson.M{"data": u.String()}) +} + +// UnmarshalBSON document into this value +func (u *ISBN13) UnmarshalBSON(data []byte) error { + var m bson.M + if err := bson.Unmarshal(data, &m); err != nil { + return err + } + + if ud, ok := m["data"].(string); ok { + *u = ISBN13(ud) + return nil + } + return fmt.Errorf("couldn't unmarshal bson bytes as ISBN13: %w", ErrFormat) +} + +// MarshalBSON document from this value +func (u CreditCard) MarshalBSON() ([]byte, error) { + return bson.Marshal(bson.M{"data": u.String()}) +} + +// UnmarshalBSON document into this value +func (u *CreditCard) UnmarshalBSON(data []byte) error { + var m bson.M + if err := bson.Unmarshal(data, &m); err != nil { + return err + } + + if ud, ok := m["data"].(string); ok { + *u = CreditCard(ud) + return nil + } + return fmt.Errorf("couldn't unmarshal bson bytes as CreditCard: %w", ErrFormat) +} + +// MarshalBSON document from this value +func (u SSN) MarshalBSON() ([]byte, error) { + return bson.Marshal(bson.M{"data": u.String()}) +} + +// UnmarshalBSON document into this value +func (u *SSN) UnmarshalBSON(data []byte) error { + var m bson.M + if err := bson.Unmarshal(data, &m); err != nil { + return err + } + + if ud, ok := m["data"].(string); ok { + *u = SSN(ud) + return nil + } + return fmt.Errorf("couldn't unmarshal bson bytes as SSN: %w", ErrFormat) +} + +// MarshalBSON document from this value +func (h HexColor) MarshalBSON() ([]byte, error) { + return bson.Marshal(bson.M{"data": h.String()}) +} + +// UnmarshalBSON document into this value +func (h *HexColor) UnmarshalBSON(data []byte) error { + var m bson.M + if err := bson.Unmarshal(data, &m); err != nil { + return err + } + + if ud, ok := m["data"].(string); ok { + *h = HexColor(ud) + return nil + } + return fmt.Errorf("couldn't unmarshal bson bytes as HexColor: %w", ErrFormat) +} + +// MarshalBSON document from this value +func (r RGBColor) MarshalBSON() ([]byte, error) { + return bson.Marshal(bson.M{"data": r.String()}) +} + +// UnmarshalBSON document into this value +func (r *RGBColor) UnmarshalBSON(data []byte) error { + var m bson.M + if err := bson.Unmarshal(data, &m); err != nil { + return err + } + + if ud, ok := m["data"].(string); ok { + *r = RGBColor(ud) + return nil + } + return fmt.Errorf("couldn't unmarshal bson bytes as RGBColor: %w", ErrFormat) +} + +// MarshalBSON renders the object id as a BSON document +func (id ObjectId) MarshalBSON() ([]byte, error) { + return bson.Marshal(bson.M{"data": bsonprim.ObjectID(id)}) +} + +// UnmarshalBSON reads the objectId from a BSON document +func (id *ObjectId) UnmarshalBSON(data []byte) error { + var obj struct { + Data bsonprim.ObjectID + } + if err := bson.Unmarshal(data, &obj); err != nil { + return err + } + *id = ObjectId(obj.Data) + return nil +} + +// MarshalBSONValue is an interface implemented by types that can marshal themselves +// into a BSON document represented as bytes. The bytes returned must be a valid +// BSON document if the error is nil. +func (id ObjectId) MarshalBSONValue() (bsontype.Type, []byte, error) { + oid := bsonprim.ObjectID(id) + return bson.TypeObjectID, oid[:], nil +} + +// UnmarshalBSONValue is an interface implemented by types that can unmarshal a +// BSON value representation of themselves. The BSON bytes and type can be +// assumed to be valid. UnmarshalBSONValue must copy the BSON value bytes if it +// wishes to retain the data after returning. +func (id *ObjectId) UnmarshalBSONValue(_ bsontype.Type, data []byte) error { + var oid bsonprim.ObjectID + copy(oid[:], data) + *id = ObjectId(oid) + return nil +} diff --git a/vendor/github.com/go-openapi/strfmt/time.go b/vendor/github.com/go-openapi/strfmt/time.go index 84e2412b937..8085aaf6965 100644 --- a/vendor/github.com/go-openapi/strfmt/time.go +++ b/vendor/github.com/go-openapi/strfmt/time.go @@ -1,31 +1,15 @@ -// Copyright 2015 go-swagger maintainers -// -// 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. +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 package strfmt import ( "database/sql/driver" - "encoding/binary" "encoding/json" "fmt" "regexp" "strings" "time" - - "go.mongodb.org/mongo-driver/bson" - - "go.mongodb.org/mongo-driver/bson/bsontype" ) var ( @@ -178,7 +162,7 @@ func (t *DateTime) UnmarshalText(text []byte) error { } // Scan scans a DateTime value from database driver type. -func (t *DateTime) Scan(raw interface{}) error { +func (t *DateTime) Scan(raw any) error { // TODO: case int64: and case float64: ? switch v := raw.(type) { case []byte: @@ -224,69 +208,6 @@ func (t *DateTime) UnmarshalJSON(data []byte) error { return nil } -// MarshalBSON renders the DateTime as a BSON document -func (t DateTime) MarshalBSON() ([]byte, error) { - return bson.Marshal(bson.M{"data": t}) -} - -// UnmarshalBSON reads the DateTime from a BSON document -func (t *DateTime) UnmarshalBSON(data []byte) error { - var obj struct { - Data DateTime - } - - if err := bson.Unmarshal(data, &obj); err != nil { - return err - } - - *t = obj.Data - - return nil -} - -const bsonDateLength = 8 - -// MarshalBSONValue is an interface implemented by types that can marshal themselves -// into a BSON document represented as bytes. The bytes returned must be a valid -// BSON document if the error is nil. -// -// Marshals a DateTime as a bsontype.DateTime, an int64 representing -// milliseconds since epoch. -func (t DateTime) MarshalBSONValue() (bsontype.Type, []byte, error) { - // UnixNano cannot be used directly, the result of calling UnixNano on the zero - // Time is undefined. That's why we use time.Nanosecond() instead. - tNorm := NormalizeTimeForMarshal(time.Time(t)) - i64 := tNorm.UnixMilli() - - buf := make([]byte, bsonDateLength) - // int64 -> uint64 conversion is safe here - binary.LittleEndian.PutUint64(buf, uint64(i64)) //nolint:gosec - - return bson.TypeDateTime, buf, nil -} - -// UnmarshalBSONValue is an interface implemented by types that can unmarshal a -// BSON value representation of themselves. The BSON bytes and type can be -// assumed to be valid. UnmarshalBSONValue must copy the BSON value bytes if it -// wishes to retain the data after returning. -func (t *DateTime) UnmarshalBSONValue(tpe bsontype.Type, data []byte) error { - if tpe == bson.TypeNull { - *t = DateTime{} - return nil - } - - if len(data) != bsonDateLength { - return fmt.Errorf("bson date field length not exactly 8 bytes: %w", ErrFormat) - } - - // it's ok to get negative values after conversion - i64 := int64(binary.LittleEndian.Uint64(data)) //nolint:gosec - // TODO: Use bsonprim.DateTime.Time() method - *t = DateTime(time.UnixMilli(i64)) - - return nil -} - // DeepCopyInto copies the receiver and writes its value into out. func (t *DateTime) DeepCopyInto(out *DateTime) { *out = *t diff --git a/vendor/github.com/go-openapi/strfmt/ulid.go b/vendor/github.com/go-openapi/strfmt/ulid.go index 434eb01baa5..85c5b53e6c7 100644 --- a/vendor/github.com/go-openapi/strfmt/ulid.go +++ b/vendor/github.com/go-openapi/strfmt/ulid.go @@ -1,3 +1,6 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + package strfmt import ( @@ -9,7 +12,6 @@ import ( "sync" "github.com/oklog/ulid" - "go.mongodb.org/mongo-driver/bson" ) // ULID represents a ulid string format @@ -28,12 +30,12 @@ type ULID struct { var ( ulidEntropyPool = sync.Pool{ - New: func() interface{} { + New: func() any { return cryptorand.Reader }, } - ULIDScanDefaultFunc = func(raw interface{}) (ULID, error) { + ULIDScanDefaultFunc = func(raw any) (ULID, error) { u := NewULIDZero() switch x := raw.(type) { case nil: @@ -111,7 +113,7 @@ func NewULID() (ULID, error) { } // GetULID returns underlying instance of ULID -func (u *ULID) GetULID() interface{} { +func (u *ULID) GetULID() any { return u.ULID } @@ -126,7 +128,7 @@ func (u *ULID) UnmarshalText(data []byte) error { // validation is performed lat } // Scan reads a value from a database driver -func (u *ULID) Scan(raw interface{}) error { +func (u *ULID) Scan(raw any) error { ul, err := ULIDScanOverrideFunc(raw) if err == nil { *u = ul @@ -165,29 +167,6 @@ func (u *ULID) UnmarshalJSON(data []byte) error { return nil } -// MarshalBSON document from this value -func (u ULID) MarshalBSON() ([]byte, error) { - return bson.Marshal(bson.M{"data": u.String()}) -} - -// UnmarshalBSON document into this value -func (u *ULID) UnmarshalBSON(data []byte) error { - var m bson.M - if err := bson.Unmarshal(data, &m); err != nil { - return err - } - - if ud, ok := m["data"].(string); ok { - id, err := ulid.ParseStrict(ud) - if err != nil { - return fmt.Errorf("couldn't parse bson bytes as ULID: %w: %w", err, ErrFormat) - } - u.ULID = id - return nil - } - return fmt.Errorf("couldn't unmarshal bson bytes as ULID: %w", ErrFormat) -} - // DeepCopyInto copies the receiver and writes its value into out. func (u *ULID) DeepCopyInto(out *ULID) { *out = *u diff --git a/vendor/github.com/go-openapi/swag/.golangci.yml b/vendor/github.com/go-openapi/swag/.golangci.yml index 4129e7e57ee..126264a6b89 100644 --- a/vendor/github.com/go-openapi/swag/.golangci.yml +++ b/vendor/github.com/go-openapi/swag/.golangci.yml @@ -21,6 +21,7 @@ linters: - ireturn - lll - musttag + - modernize - nestif - nlreturn - nonamedreturns diff --git a/vendor/github.com/go-openapi/swag/README.md b/vendor/github.com/go-openapi/swag/README.md index 786b92fd3a2..371fd55fdc3 100644 --- a/vendor/github.com/go-openapi/swag/README.md +++ b/vendor/github.com/go-openapi/swag/README.md @@ -18,6 +18,7 @@ You may also use it standalone for your projects. * [Contents](#contents) * [Dependencies](#dependencies) * [Release Notes](#release-notes) +* [Licensing](#licensing) * [Note to contributors](#note-to-contributors) * [TODOs, suggestions and plans](#todos-suggestions-and-plans) @@ -62,6 +63,42 @@ dependencies outside of the standard library. ## Release notes +### v0.25.4 + +** mangling** + +Bug fix + +* [x] mangler may panic with pluralized overlapping initialisms + +Tests + +* [x] introduced fuzz tests + +### v0.25.3 + +** mangling** + +Bug fix + +* [x] mangler may panic with pluralized initialisms + +### v0.25.2 + +Minor changes due to internal maintenance that don't affect the behavior of the library. + +* [x] removed indirect test dependencies by switching all tests to `go-openapi/testify`, + a fork of `stretch/testify` with zero-dependencies. +* [x] improvements to CI to catch test reports. +* [x] modernized licensing annotations in source code, using the more compact SPDX annotations + rather than the full license terms. +* [x] simplified a bit JSON & YAML testing by using newly available assertions +* started the journey to an OpenSSF score card badge: + * [x] explicited permissions in CI workflows + * [x] published security policy + * pinned dependencies to github actions + * introduced fuzzing in tests + ### v0.25.1 * fixes a data race that could occur when using the standard library implementation of a JSON ordered map @@ -74,7 +111,7 @@ dependencies outside of the standard library. * removes the dependency to `mailru/easyjson` by default (#68) * functionality remains the same, but performance may somewhat degrade for applications that relied on `easyjson` - * users of the JSON or YAML utilities who want to use `easyjson` as their prefered JSON serializer library + * users of the JSON or YAML utilities who want to use `easyjson` as their preferred JSON serializer library will be able to do so by registering this the corresponding JSON adapter at runtime. See below. * ordered keys in JSON and YAML objects: this feature used to rely solely on `easyjson`. With this release, an implementation relying on the standard `encoding/json` is provided. @@ -96,10 +133,13 @@ Moving forward, we want to : The following would maintain how JSON utilities proposed by `swag` used work, up to `v0.24.1`. ```go - import "github.com/go-openapi/swag/jsonutils/adapters/easyjson/json" + import ( + "github.com/go-openapi/swag/jsonutils/adapters" + easyjson "github.com/go-openapi/swag/jsonutils/adapters/easyjson/json" + ) func init() { - json.Register() + easyjson.Register(adapters.Registry) } ``` @@ -107,6 +147,9 @@ Subsequent calls to `jsonutils.ReadJSON()` or `jsonutils.WriteJSON()` will switc whenever the passed data structures implement the `easyjson.Unmarshaler` or `easyjson.Marshaler` respectively, or fallback to the standard library. +For more details, you may also look at our +[integration tests](jsonutils/adapters/testintegration/integration_suite_test.go#29). + ### v0.24.0 With this release, we have largely modernized the API of `swag`: @@ -133,6 +176,10 @@ With this release, we have largely modernized the API of `swag`: --- +## Licensing + +This library ships under the [SPDX-License-Identifier: Apache-2.0](./LICENSE). + ## Note to contributors A mono-repo structure comes with some unavoidable extra pains... diff --git a/vendor/github.com/go-openapi/swag/SECURITY.md b/vendor/github.com/go-openapi/swag/SECURITY.md new file mode 100644 index 00000000000..72296a83135 --- /dev/null +++ b/vendor/github.com/go-openapi/swag/SECURITY.md @@ -0,0 +1,19 @@ +# Security Policy + +This policy outlines the commitment and practices of the go-openapi maintainers regarding security. + +## Supported Versions + +| Version | Supported | +| ------- | ------------------ | +| 0.25.x | :white_check_mark: | + +## Reporting a vulnerability + +If you become aware of a security vulnerability that affects the current repository, +please report it privately to the maintainers. + +Please follow the instructions provided by github to +[Privately report a security vulnerability](https://docs.github.com/en/code-security/security-advisories/guidance-on-reporting-and-writing-information-about-vulnerabilities/privately-reporting-a-security-vulnerability#privately-reporting-a-security-vulnerability). + +TL;DR: on Github, navigate to the project's "Security" tab then click on "Report a vulnerability". diff --git a/vendor/github.com/go-openapi/swag/TODO.md b/vendor/github.com/go-openapi/swag/TODO.md deleted file mode 100644 index 129888038b2..00000000000 --- a/vendor/github.com/go-openapi/swag/TODO.md +++ /dev/null @@ -1 +0,0 @@ -fix data race https://github.com/go-openapi/swag/actions/runs/17989156861/job/51174860188 diff --git a/vendor/github.com/go-openapi/swag/cmdutils/cmd_utils.go b/vendor/github.com/go-openapi/swag/cmdutils/cmd_utils.go index bc01ec2bb94..6c7bbb26f03 100644 --- a/vendor/github.com/go-openapi/swag/cmdutils/cmd_utils.go +++ b/vendor/github.com/go-openapi/swag/cmdutils/cmd_utils.go @@ -1,16 +1,5 @@ -// Copyright 2015 go-swagger maintainers -// -// 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. +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 package cmdutils @@ -20,5 +9,5 @@ package cmdutils type CommandLineOptionsGroup struct { ShortDescription string LongDescription string - Options interface{} + Options any } diff --git a/vendor/github.com/go-openapi/swag/cmdutils/doc.go b/vendor/github.com/go-openapi/swag/cmdutils/doc.go index 63ac1d17eef..31f2c37538a 100644 --- a/vendor/github.com/go-openapi/swag/cmdutils/doc.go +++ b/vendor/github.com/go-openapi/swag/cmdutils/doc.go @@ -1,16 +1,5 @@ -// Copyright 2015 go-swagger maintainers -// -// 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. +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 // Package cmdutils brings helpers for CLIs produced by go-openapi package cmdutils diff --git a/vendor/github.com/go-openapi/swag/cmdutils_iface.go b/vendor/github.com/go-openapi/swag/cmdutils_iface.go index 1eaf36f157b..bd0c1fc1280 100644 --- a/vendor/github.com/go-openapi/swag/cmdutils_iface.go +++ b/vendor/github.com/go-openapi/swag/cmdutils_iface.go @@ -1,16 +1,5 @@ -// Copyright 2015 go-swagger maintainers -// -// 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. +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 package swag diff --git a/vendor/github.com/go-openapi/swag/conv/convert.go b/vendor/github.com/go-openapi/swag/conv/convert.go index b9b8698543a..f205c391345 100644 --- a/vendor/github.com/go-openapi/swag/conv/convert.go +++ b/vendor/github.com/go-openapi/swag/conv/convert.go @@ -1,16 +1,5 @@ -// Copyright 2015 go-swagger maintainers -// -// 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. +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 package conv diff --git a/vendor/github.com/go-openapi/swag/conv/convert_types.go b/vendor/github.com/go-openapi/swag/conv/convert_types.go index 423e8663f8e..cf4c6495ebc 100644 --- a/vendor/github.com/go-openapi/swag/conv/convert_types.go +++ b/vendor/github.com/go-openapi/swag/conv/convert_types.go @@ -1,20 +1,13 @@ -// Copyright 2015 go-swagger maintainers -// -// 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. +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 package conv -// The original version of this file, eons ago, was taken from the aws go sdk +// Unlicensed credits (idea, concept) +// +// The idea to convert values to pointers and the other way around, was inspired, eons ago, by the aws go sdk. +// +// Nowadays, all sensible API sdk's expose a similar functionality. // Pointer returns a pointer to the value passed in. func Pointer[T any](v T) *T { diff --git a/vendor/github.com/go-openapi/swag/conv/doc.go b/vendor/github.com/go-openapi/swag/conv/doc.go index b02711f422c..1bd6ead6e2d 100644 --- a/vendor/github.com/go-openapi/swag/conv/doc.go +++ b/vendor/github.com/go-openapi/swag/conv/doc.go @@ -1,16 +1,5 @@ -// Copyright 2015 go-swagger maintainers -// -// 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. +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 // Package conv exposes utilities to convert types. // diff --git a/vendor/github.com/go-openapi/swag/conv/format.go b/vendor/github.com/go-openapi/swag/conv/format.go index db7562a4a34..5b87b8e146b 100644 --- a/vendor/github.com/go-openapi/swag/conv/format.go +++ b/vendor/github.com/go-openapi/swag/conv/format.go @@ -1,16 +1,5 @@ -// Copyright 2015 go-swagger maintainers -// -// 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. +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 package conv diff --git a/vendor/github.com/go-openapi/swag/conv/sizeof.go b/vendor/github.com/go-openapi/swag/conv/sizeof.go index 646f8be9aa3..49434655738 100644 --- a/vendor/github.com/go-openapi/swag/conv/sizeof.go +++ b/vendor/github.com/go-openapi/swag/conv/sizeof.go @@ -1,3 +1,6 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + package conv import "unsafe" diff --git a/vendor/github.com/go-openapi/swag/conv/type_constraints.go b/vendor/github.com/go-openapi/swag/conv/type_constraints.go index 3c61498361c..81135e827e5 100644 --- a/vendor/github.com/go-openapi/swag/conv/type_constraints.go +++ b/vendor/github.com/go-openapi/swag/conv/type_constraints.go @@ -1,16 +1,5 @@ -// Copyright 2015 go-swagger maintainers -// -// 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. +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 package conv diff --git a/vendor/github.com/go-openapi/swag/conv_iface.go b/vendor/github.com/go-openapi/swag/conv_iface.go index 9991acb6510..eea7b2e56e3 100644 --- a/vendor/github.com/go-openapi/swag/conv_iface.go +++ b/vendor/github.com/go-openapi/swag/conv_iface.go @@ -1,16 +1,5 @@ -// Copyright 2015 go-swagger maintainers -// -// 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. +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 package swag diff --git a/vendor/github.com/go-openapi/swag/doc.go b/vendor/github.com/go-openapi/swag/doc.go index a079fe81066..b54b57478af 100644 --- a/vendor/github.com/go-openapi/swag/doc.go +++ b/vendor/github.com/go-openapi/swag/doc.go @@ -1,16 +1,5 @@ -// Copyright 2015 go-swagger maintainers -// -// 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. +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 // Package swag contains a bunch of helper functions for go-openapi and go-swagger projects. // diff --git a/vendor/github.com/go-openapi/swag/fileutils/doc.go b/vendor/github.com/go-openapi/swag/fileutils/doc.go index 4b48e71960e..859a200d841 100644 --- a/vendor/github.com/go-openapi/swag/fileutils/doc.go +++ b/vendor/github.com/go-openapi/swag/fileutils/doc.go @@ -1,16 +1,5 @@ -// Copyright 2015 go-swagger maintainers -// -// 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. +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 // Package fileutils exposes utilities to deal with files and paths. // diff --git a/vendor/github.com/go-openapi/swag/fileutils/file.go b/vendor/github.com/go-openapi/swag/fileutils/file.go index b17eaba58fb..5ad4cfaeafa 100644 --- a/vendor/github.com/go-openapi/swag/fileutils/file.go +++ b/vendor/github.com/go-openapi/swag/fileutils/file.go @@ -1,16 +1,5 @@ -// Copyright 2015 go-swagger maintainers -// -// 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. +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 package fileutils diff --git a/vendor/github.com/go-openapi/swag/fileutils/path.go b/vendor/github.com/go-openapi/swag/fileutils/path.go index 0de77e12d48..dd09f690bf8 100644 --- a/vendor/github.com/go-openapi/swag/fileutils/path.go +++ b/vendor/github.com/go-openapi/swag/fileutils/path.go @@ -1,16 +1,5 @@ -// Copyright 2015 go-swagger maintainers -// -// 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. +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 package fileutils diff --git a/vendor/github.com/go-openapi/swag/fileutils_iface.go b/vendor/github.com/go-openapi/swag/fileutils_iface.go index 0c639e8c16a..f3e79a0e4bc 100644 --- a/vendor/github.com/go-openapi/swag/fileutils_iface.go +++ b/vendor/github.com/go-openapi/swag/fileutils_iface.go @@ -1,16 +1,5 @@ -// Copyright 2015 go-swagger maintainers -// -// 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. +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 package swag diff --git a/vendor/github.com/go-openapi/swag/go.work.sum b/vendor/github.com/go-openapi/swag/go.work.sum index bee4481a708..c1308cafa67 100644 --- a/vendor/github.com/go-openapi/swag/go.work.sum +++ b/vendor/github.com/go-openapi/swag/go.work.sum @@ -1,4 +1,7 @@ -github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA= -github.com/stretchr/testify v1.11.0/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= -go.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc= -go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg= +github.com/go-openapi/testify/v2 v2.0.1/go.mod h1:HCPmvFFnheKK2BuwSA0TbbdxJ3I16pjwMkYkP4Ywn54= +golang.org/x/mod v0.21.0 h1:vvrHzRwRfVKSiLrG+d4FMl/Qi4ukBCE6kZlTUkDYRT0= +golang.org/x/mod v0.21.0/go.mod h1:6SkKJ3Xj0I0BrPOZoBy3bdMptDDU9oJrpohJ3eWZ1fY= +golang.org/x/sys v0.26.0 h1:KHjCJyddX0LoSTb3J+vWpupP9p0oznkqVk/IfjymZbo= +golang.org/x/sys v0.26.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= +golang.org/x/tools v0.26.0 h1:v/60pFQmzmT9ExmjDv2gGIfi3OqfKoEP6I5+umXlbnQ= +golang.org/x/tools v0.26.0/go.mod h1:TPVVj70c7JJ3WCazhD8OdXcZg/og+b9+tH/KxylGwH0= diff --git a/vendor/github.com/go-openapi/swag/jsonname/doc.go b/vendor/github.com/go-openapi/swag/jsonname/doc.go index b2e0c80fc3a..79232eaca47 100644 --- a/vendor/github.com/go-openapi/swag/jsonname/doc.go +++ b/vendor/github.com/go-openapi/swag/jsonname/doc.go @@ -1,16 +1,5 @@ -// Copyright 2015 go-swagger maintainers -// -// 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. +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 // Package jsonname is a provider of json property names from go properties. package jsonname diff --git a/vendor/github.com/go-openapi/swag/jsonname/name_provider.go b/vendor/github.com/go-openapi/swag/jsonname/name_provider.go index e87aac2f78b..8eaf1bece8d 100644 --- a/vendor/github.com/go-openapi/swag/jsonname/name_provider.go +++ b/vendor/github.com/go-openapi/swag/jsonname/name_provider.go @@ -1,16 +1,5 @@ -// Copyright 2015 go-swagger maintainers -// -// 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. +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 package jsonname @@ -90,7 +79,7 @@ func newNameIndex(tpe reflect.Type) nameIndex { } // GetJSONNames gets all the json property names for a type -func (n *NameProvider) GetJSONNames(subject interface{}) []string { +func (n *NameProvider) GetJSONNames(subject any) []string { n.lock.Lock() defer n.lock.Unlock() tpe := reflect.Indirect(reflect.ValueOf(subject)).Type() @@ -107,7 +96,7 @@ func (n *NameProvider) GetJSONNames(subject interface{}) []string { } // GetJSONName gets the json name for a go property name -func (n *NameProvider) GetJSONName(subject interface{}, name string) (string, bool) { +func (n *NameProvider) GetJSONName(subject any, name string) (string, bool) { tpe := reflect.Indirect(reflect.ValueOf(subject)).Type() return n.GetJSONNameForType(tpe, name) } @@ -125,7 +114,7 @@ func (n *NameProvider) GetJSONNameForType(tpe reflect.Type, name string) (string } // GetGoName gets the go name for a json property name -func (n *NameProvider) GetGoName(subject interface{}, name string) (string, bool) { +func (n *NameProvider) GetGoName(subject any, name string) (string, bool) { tpe := reflect.Indirect(reflect.ValueOf(subject)).Type() return n.GetGoNameForType(tpe, name) } diff --git a/vendor/github.com/go-openapi/swag/jsonname_iface.go b/vendor/github.com/go-openapi/swag/jsonname_iface.go index 555369d75a0..303a007f6f4 100644 --- a/vendor/github.com/go-openapi/swag/jsonname_iface.go +++ b/vendor/github.com/go-openapi/swag/jsonname_iface.go @@ -1,16 +1,5 @@ -// Copyright 2015 go-swagger maintainers -// -// 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. +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 package swag diff --git a/vendor/github.com/go-openapi/swag/jsonutils/README.md b/vendor/github.com/go-openapi/swag/jsonutils/README.md index c8d0cab67b6..d745cdb466e 100644 --- a/vendor/github.com/go-openapi/swag/jsonutils/README.md +++ b/vendor/github.com/go-openapi/swag/jsonutils/README.md @@ -78,7 +78,7 @@ Each adapter is an independent go module. Hence you'll pick its dependencies onl At this moment we provide: * `stdlib`: JSON adapter based on the standard library -* `easyjson`: JSON adapter based on the `github.com/mailru/easyyjson` +* `easyjson`: JSON adapter based on the `github.com/mailru/easyjson` The adapters provide the basic `Marshal` and `Unmarshal` capabilities, plus an implementation of the `MapSlice` pattern. diff --git a/vendor/github.com/go-openapi/swag/jsonutils/adapters/doc.go b/vendor/github.com/go-openapi/swag/jsonutils/adapters/doc.go index dbb38c2f0cf..76d3898fca5 100644 --- a/vendor/github.com/go-openapi/swag/jsonutils/adapters/doc.go +++ b/vendor/github.com/go-openapi/swag/jsonutils/adapters/doc.go @@ -1,16 +1,5 @@ -// Copyright 2015 go-swagger maintainers -// -// 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. +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 // Package adapters exposes a registry of adapters to multiple // JSON serialization libraries. diff --git a/vendor/github.com/go-openapi/swag/jsonutils/adapters/ifaces/doc.go b/vendor/github.com/go-openapi/swag/jsonutils/adapters/ifaces/doc.go index 49649859af6..1fd43a1fad5 100644 --- a/vendor/github.com/go-openapi/swag/jsonutils/adapters/ifaces/doc.go +++ b/vendor/github.com/go-openapi/swag/jsonutils/adapters/ifaces/doc.go @@ -1,2 +1,5 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + // Package ifaces exposes all interfaces to work with adapters. package ifaces diff --git a/vendor/github.com/go-openapi/swag/jsonutils/adapters/ifaces/ifaces.go b/vendor/github.com/go-openapi/swag/jsonutils/adapters/ifaces/ifaces.go index 4927d872dab..7805e5e5e39 100644 --- a/vendor/github.com/go-openapi/swag/jsonutils/adapters/ifaces/ifaces.go +++ b/vendor/github.com/go-openapi/swag/jsonutils/adapters/ifaces/ifaces.go @@ -1,3 +1,6 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + package ifaces import ( diff --git a/vendor/github.com/go-openapi/swag/jsonutils/adapters/ifaces/registry_iface.go b/vendor/github.com/go-openapi/swag/jsonutils/adapters/ifaces/registry_iface.go index d1fe6a0adb6..2d6c69f4e60 100644 --- a/vendor/github.com/go-openapi/swag/jsonutils/adapters/ifaces/registry_iface.go +++ b/vendor/github.com/go-openapi/swag/jsonutils/adapters/ifaces/registry_iface.go @@ -1,3 +1,6 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + package ifaces import ( diff --git a/vendor/github.com/go-openapi/swag/jsonutils/adapters/registry.go b/vendor/github.com/go-openapi/swag/jsonutils/adapters/registry.go index b34a2305181..3062acaff26 100644 --- a/vendor/github.com/go-openapi/swag/jsonutils/adapters/registry.go +++ b/vendor/github.com/go-openapi/swag/jsonutils/adapters/registry.go @@ -1,16 +1,5 @@ -// Copyright 2015 go-swagger maintainers -// -// 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. +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 package adapters diff --git a/vendor/github.com/go-openapi/swag/jsonutils/adapters/stdlib/json/adapter.go b/vendor/github.com/go-openapi/swag/jsonutils/adapters/stdlib/json/adapter.go index 4df831b62dd..0213ff5c29f 100644 --- a/vendor/github.com/go-openapi/swag/jsonutils/adapters/stdlib/json/adapter.go +++ b/vendor/github.com/go-openapi/swag/jsonutils/adapters/stdlib/json/adapter.go @@ -1,16 +1,5 @@ -// Copyright 2015 go-swagger maintainers -// -// 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. +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 package json diff --git a/vendor/github.com/go-openapi/swag/jsonutils/adapters/stdlib/json/doc.go b/vendor/github.com/go-openapi/swag/jsonutils/adapters/stdlib/json/doc.go index 2ff6b212fc8..5ea1b440425 100644 --- a/vendor/github.com/go-openapi/swag/jsonutils/adapters/stdlib/json/doc.go +++ b/vendor/github.com/go-openapi/swag/jsonutils/adapters/stdlib/json/doc.go @@ -1,16 +1,5 @@ -// Copyright 2015 go-swagger maintainers -// -// 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. +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 // Package json implements an [ifaces.Adapter] using the standard library. package json diff --git a/vendor/github.com/go-openapi/swag/jsonutils/adapters/stdlib/json/lexer.go b/vendor/github.com/go-openapi/swag/jsonutils/adapters/stdlib/json/lexer.go index 6d919199d03..b5aa1c7972e 100644 --- a/vendor/github.com/go-openapi/swag/jsonutils/adapters/stdlib/json/lexer.go +++ b/vendor/github.com/go-openapi/swag/jsonutils/adapters/stdlib/json/lexer.go @@ -1,16 +1,5 @@ -// Copyright 2015 go-swagger maintainers -// -// 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. +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 package json diff --git a/vendor/github.com/go-openapi/swag/jsonutils/adapters/stdlib/json/ordered_map.go b/vendor/github.com/go-openapi/swag/jsonutils/adapters/stdlib/json/ordered_map.go index 18e6294e50e..54deef406f3 100644 --- a/vendor/github.com/go-openapi/swag/jsonutils/adapters/stdlib/json/ordered_map.go +++ b/vendor/github.com/go-openapi/swag/jsonutils/adapters/stdlib/json/ordered_map.go @@ -1,16 +1,5 @@ -// Copyright 2015 go-swagger maintainers -// -// 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. +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 package json diff --git a/vendor/github.com/go-openapi/swag/jsonutils/adapters/stdlib/json/pool.go b/vendor/github.com/go-openapi/swag/jsonutils/adapters/stdlib/json/pool.go index 0f51d3a20cd..709b97c3046 100644 --- a/vendor/github.com/go-openapi/swag/jsonutils/adapters/stdlib/json/pool.go +++ b/vendor/github.com/go-openapi/swag/jsonutils/adapters/stdlib/json/pool.go @@ -1,16 +1,5 @@ -// Copyright 2015 go-swagger maintainers -// -// 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. +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 package json diff --git a/vendor/github.com/go-openapi/swag/jsonutils/adapters/stdlib/json/register.go b/vendor/github.com/go-openapi/swag/jsonutils/adapters/stdlib/json/register.go index 18bbc377450..fc8818694ea 100644 --- a/vendor/github.com/go-openapi/swag/jsonutils/adapters/stdlib/json/register.go +++ b/vendor/github.com/go-openapi/swag/jsonutils/adapters/stdlib/json/register.go @@ -1,16 +1,5 @@ -// Copyright 2015 go-swagger maintainers -// -// 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. +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 package json diff --git a/vendor/github.com/go-openapi/swag/jsonutils/adapters/stdlib/json/writer.go b/vendor/github.com/go-openapi/swag/jsonutils/adapters/stdlib/json/writer.go index 38e9b6e034a..dc2325c1a30 100644 --- a/vendor/github.com/go-openapi/swag/jsonutils/adapters/stdlib/json/writer.go +++ b/vendor/github.com/go-openapi/swag/jsonutils/adapters/stdlib/json/writer.go @@ -1,16 +1,5 @@ -// Copyright 2015 go-swagger maintainers -// -// 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. +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 package json diff --git a/vendor/github.com/go-openapi/swag/jsonutils/concat.go b/vendor/github.com/go-openapi/swag/jsonutils/concat.go index 049d4698bf8..2068503af05 100644 --- a/vendor/github.com/go-openapi/swag/jsonutils/concat.go +++ b/vendor/github.com/go-openapi/swag/jsonutils/concat.go @@ -1,16 +1,5 @@ -// Copyright 2015 go-swagger maintainers -// -// 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. +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 package jsonutils @@ -34,7 +23,7 @@ func init() { // ConcatJSON concatenates multiple json objects or arrays efficiently. // -// Note that [ConcatJSON] performs a very simmple (and fast) concatenation +// Note that [ConcatJSON] performs a very simple (and fast) concatenation // operation: it does not attempt to merge objects. func ConcatJSON(blobs ...[]byte) []byte { if len(blobs) == 0 { diff --git a/vendor/github.com/go-openapi/swag/jsonutils/doc.go b/vendor/github.com/go-openapi/swag/jsonutils/doc.go index 495ef834134..3926cc58d1b 100644 --- a/vendor/github.com/go-openapi/swag/jsonutils/doc.go +++ b/vendor/github.com/go-openapi/swag/jsonutils/doc.go @@ -1,16 +1,5 @@ -// Copyright 2015 go-swagger maintainers -// -// 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. +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 // Package jsonutils provides helpers to work with JSON. // diff --git a/vendor/github.com/go-openapi/swag/jsonutils/json.go b/vendor/github.com/go-openapi/swag/jsonutils/json.go index a33b89bd4d9..40753ce03fd 100644 --- a/vendor/github.com/go-openapi/swag/jsonutils/json.go +++ b/vendor/github.com/go-openapi/swag/jsonutils/json.go @@ -1,16 +1,5 @@ -// Copyright 2015 go-swagger maintainers -// -// 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. +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 package jsonutils diff --git a/vendor/github.com/go-openapi/swag/jsonutils/ordered_map.go b/vendor/github.com/go-openapi/swag/jsonutils/ordered_map.go index 931ce2559d8..38dd3e24442 100644 --- a/vendor/github.com/go-openapi/swag/jsonutils/ordered_map.go +++ b/vendor/github.com/go-openapi/swag/jsonutils/ordered_map.go @@ -1,16 +1,5 @@ -// Copyright 2015 go-swagger maintainers -// -// 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. +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 package jsonutils diff --git a/vendor/github.com/go-openapi/swag/jsonutils_iface.go b/vendor/github.com/go-openapi/swag/jsonutils_iface.go index 63e23f0b69d..7bd4105fa51 100644 --- a/vendor/github.com/go-openapi/swag/jsonutils_iface.go +++ b/vendor/github.com/go-openapi/swag/jsonutils_iface.go @@ -1,16 +1,5 @@ -// Copyright 2015 go-swagger maintainers -// -// 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. +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 package swag @@ -33,17 +22,17 @@ type JSONMapItem = jsonutils.JSONMapItem // WriteJSON writes json data. // // Deprecated: use [jsonutils.WriteJSON] instead. -func WriteJSON(data interface{}) ([]byte, error) { return jsonutils.WriteJSON(data) } +func WriteJSON(data any) ([]byte, error) { return jsonutils.WriteJSON(data) } // ReadJSON reads json data. // // Deprecated: use [jsonutils.ReadJSON] instead. -func ReadJSON(data []byte, value interface{}) error { return jsonutils.ReadJSON(data, value) } +func ReadJSON(data []byte, value any) error { return jsonutils.ReadJSON(data, value) } // DynamicJSONToStruct converts an untyped JSON structure into a target data type. // // Deprecated: use [jsonutils.FromDynamicJSON] instead. -func DynamicJSONToStruct(data interface{}, target interface{}) error { +func DynamicJSONToStruct(data any, target any) error { return jsonutils.FromDynamicJSON(data, target) } @@ -57,8 +46,8 @@ func ConcatJSON(blobs ...[]byte) []byte { return jsonutils.ConcatJSON(blobs...) // It is the same as [FromDynamicJSON], but doesn't check for errors. // // Deprecated: this function is a misnomer and is unsafe. Use [jsonutils.FromDynamicJSON] instead. -func ToDynamicJSON(value interface{}) interface{} { - var res interface{} +func ToDynamicJSON(value any) any { + var res any if err := FromDynamicJSON(value, &res); err != nil { log.Println(err) } @@ -68,9 +57,9 @@ func ToDynamicJSON(value interface{}) interface{} { // FromDynamicJSON turns a go value into a properly JSON typed structure. // -// "Dynamic JSON" refers to what you get when unmarshaling JSON into an untyped interface{}, -// i.e. objects are represented by map[string]interface{}, arrays by []interface{}, and all -// scalar values are interface{}. +// "Dynamic JSON" refers to what you get when unmarshaling JSON into an untyped any, +// i.e. objects are represented by map[string]any, arrays by []any, and all +// scalar values are any. // // Deprecated: use [jsonutils.FromDynamicJSON] instead. -func FromDynamicJSON(data, target interface{}) error { return jsonutils.FromDynamicJSON(data, target) } +func FromDynamicJSON(data, target any) error { return jsonutils.FromDynamicJSON(data, target) } diff --git a/vendor/github.com/go-openapi/swag/loading/doc.go b/vendor/github.com/go-openapi/swag/loading/doc.go index 62585615e1e..8cf7bcb8b9d 100644 --- a/vendor/github.com/go-openapi/swag/loading/doc.go +++ b/vendor/github.com/go-openapi/swag/loading/doc.go @@ -1,16 +1,5 @@ -// Copyright 2015 go-swagger maintainers -// -// 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. +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 // Package loading provides tools to load a file from http or from a local file system. package loading diff --git a/vendor/github.com/go-openapi/swag/loading/errors.go b/vendor/github.com/go-openapi/swag/loading/errors.go index ca45732a7a6..b3964289c74 100644 --- a/vendor/github.com/go-openapi/swag/loading/errors.go +++ b/vendor/github.com/go-openapi/swag/loading/errors.go @@ -1,16 +1,5 @@ -// Copyright 2015 go-swagger maintainers -// -// 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. +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 package loading diff --git a/vendor/github.com/go-openapi/swag/loading/json.go b/vendor/github.com/go-openapi/swag/loading/json.go index aadf9991357..59db12f5cfd 100644 --- a/vendor/github.com/go-openapi/swag/loading/json.go +++ b/vendor/github.com/go-openapi/swag/loading/json.go @@ -1,3 +1,6 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + package loading import ( diff --git a/vendor/github.com/go-openapi/swag/loading/loading.go b/vendor/github.com/go-openapi/swag/loading/loading.go index bd955535f71..269fb74d167 100644 --- a/vendor/github.com/go-openapi/swag/loading/loading.go +++ b/vendor/github.com/go-openapi/swag/loading/loading.go @@ -1,16 +1,5 @@ -// Copyright 2015 go-swagger maintainers -// -// 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. +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 package loading diff --git a/vendor/github.com/go-openapi/swag/loading/options.go b/vendor/github.com/go-openapi/swag/loading/options.go index a51329e938b..6674ac69e62 100644 --- a/vendor/github.com/go-openapi/swag/loading/options.go +++ b/vendor/github.com/go-openapi/swag/loading/options.go @@ -1,16 +1,5 @@ -// Copyright 2015 go-swagger maintainers -// -// 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. +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 package loading @@ -81,7 +70,7 @@ func WithCustomHeaders(headers map[string]string) Option { } } -// WithHTTClient overrides the default HTTP client used to fetch a remote file. +// WithHTTPClient overrides the default HTTP client used to fetch a remote file. // // By default, [http.DefaultClient] is used. func WithHTTPClient(client *http.Client) Option { @@ -90,7 +79,7 @@ func WithHTTPClient(client *http.Client) Option { } } -// WithFileFS sets a file system for the local file loader. +// WithFS sets a file system for the local file loader. // // If the provided file system is a [fs.ReadFileFS], the ReadFile function is used. // Otherwise, ReadFile is wrapped using [fs.ReadFile]. diff --git a/vendor/github.com/go-openapi/swag/loading/yaml.go b/vendor/github.com/go-openapi/swag/loading/yaml.go index 40bd2a769f9..3ebb53668c4 100644 --- a/vendor/github.com/go-openapi/swag/loading/yaml.go +++ b/vendor/github.com/go-openapi/swag/loading/yaml.go @@ -1,16 +1,5 @@ -// Copyright 2015 go-swagger maintainers -// -// 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. +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 package loading @@ -38,7 +27,7 @@ func YAMLDoc(path string, opts ...Option) (json.RawMessage, error) { } // YAMLData loads a yaml document from either http or a file. -func YAMLData(path string, opts ...Option) (interface{}, error) { +func YAMLData(path string, opts ...Option) (any, error) { data, err := LoadFromFileOrHTTP(path, opts...) if err != nil { return nil, err diff --git a/vendor/github.com/go-openapi/swag/loading_iface.go b/vendor/github.com/go-openapi/swag/loading_iface.go index 38d825bc5ea..27ec3fb8c37 100644 --- a/vendor/github.com/go-openapi/swag/loading_iface.go +++ b/vendor/github.com/go-openapi/swag/loading_iface.go @@ -1,16 +1,5 @@ -// Copyright 2015 go-swagger maintainers -// -// 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. +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 package swag @@ -84,7 +73,7 @@ func YAMLDoc(path string) (json.RawMessage, error) { // YAMLData loads a yaml document from either http or a file. // // Deprecated: use [loading.YAMLData] instead. -func YAMLData(path string) (interface{}, error) { +func YAMLData(path string) (any, error) { return loading.YAMLData(path) } diff --git a/vendor/github.com/go-openapi/swag/mangling/doc.go b/vendor/github.com/go-openapi/swag/mangling/doc.go index dbe806828c3..ce0d8904857 100644 --- a/vendor/github.com/go-openapi/swag/mangling/doc.go +++ b/vendor/github.com/go-openapi/swag/mangling/doc.go @@ -1,16 +1,5 @@ -// Copyright 2015 go-swagger maintainers -// -// 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. +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 // Package mangling provides name mangling capabilities. // diff --git a/vendor/github.com/go-openapi/swag/mangling/initialism_index.go b/vendor/github.com/go-openapi/swag/mangling/initialism_index.go index cf0786f812c..e5b70c14938 100644 --- a/vendor/github.com/go-openapi/swag/mangling/initialism_index.go +++ b/vendor/github.com/go-openapi/swag/mangling/initialism_index.go @@ -1,16 +1,5 @@ -// Copyright 2015 go-swagger maintainers -// -// 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. +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 package mangling @@ -190,6 +179,19 @@ const ( simplePlural ) +func (f pluralForm) String() string { + switch f { + case notPlural: + return "notPlural" + case invariantPlural: + return "invariantPlural" + case simplePlural: + return "simplePlural" + default: + return "" + } +} + // pluralForm indicates how we want to pluralize a given initialism. // // Besides configured invariant forms (like HTTP and HTTPS), diff --git a/vendor/github.com/go-openapi/swag/mangling/name_lexem.go b/vendor/github.com/go-openapi/swag/mangling/name_lexem.go index 02004b4f3ab..bc837e3b9f5 100644 --- a/vendor/github.com/go-openapi/swag/mangling/name_lexem.go +++ b/vendor/github.com/go-openapi/swag/mangling/name_lexem.go @@ -1,16 +1,5 @@ -// Copyright 2015 go-swagger maintainers -// -// 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. +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 package mangling diff --git a/vendor/github.com/go-openapi/swag/mangling/name_mangler.go b/vendor/github.com/go-openapi/swag/mangling/name_mangler.go index 94ae555a7b6..da685681d08 100644 --- a/vendor/github.com/go-openapi/swag/mangling/name_mangler.go +++ b/vendor/github.com/go-openapi/swag/mangling/name_mangler.go @@ -1,16 +1,5 @@ -// Copyright 2015 go-swagger maintainers -// -// 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. +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 package mangling diff --git a/vendor/github.com/go-openapi/swag/mangling/options.go b/vendor/github.com/go-openapi/swag/mangling/options.go index 66ad2e46c78..3c92b2f18bf 100644 --- a/vendor/github.com/go-openapi/swag/mangling/options.go +++ b/vendor/github.com/go-openapi/swag/mangling/options.go @@ -1,16 +1,5 @@ -// Copyright 2015 go-swagger maintainers -// -// 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. +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 package mangling diff --git a/vendor/github.com/go-openapi/swag/mangling/pools.go b/vendor/github.com/go-openapi/swag/mangling/pools.go index d85b4038776..f8104351445 100644 --- a/vendor/github.com/go-openapi/swag/mangling/pools.go +++ b/vendor/github.com/go-openapi/swag/mangling/pools.go @@ -1,16 +1,5 @@ -// Copyright 2015 go-swagger maintainers -// -// 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. +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 package mangling diff --git a/vendor/github.com/go-openapi/swag/mangling/split.go b/vendor/github.com/go-openapi/swag/mangling/split.go index 40e4a2e0e1d..ed12ea25674 100644 --- a/vendor/github.com/go-openapi/swag/mangling/split.go +++ b/vendor/github.com/go-openapi/swag/mangling/split.go @@ -1,20 +1,10 @@ -// Copyright 2015 go-swagger maintainers -// -// 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. +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 package mangling import ( + "fmt" "unicode" ) @@ -47,6 +37,13 @@ type ( initialismMatches []initialismMatch ) +// String representation of a match, e.g. for debugging. +func (m initialismMatch) String() string { + return fmt.Sprintf("{body: %s (%d), start: %d, end; %d, complete: %t, hasPlural: %v}", + string(m.body), len(m.body), m.start, m.end, m.complete, m.hasPlural, + ) +} + func (m initialismMatch) isZero() bool { return m.start == 0 && m.end == 0 } @@ -83,116 +80,148 @@ func (s splitter) split(name string) *[]nameLexem { } func (s splitter) gatherInitialismMatches(nameRunes []rune) *initialismMatches { - var matches *initialismMatches + matches := poolOfMatches.BorrowMatches() + const minLenInitialism = 1 + if len(nameRunes) < minLenInitialism+1 { + // can't match initialism with 0 or 1 rune + return matches + } + + // first iteration + s.findMatches(matches, nameRunes, nameRunes[0], 0) - for currentRunePosition, currentRune := range nameRunes { - // recycle these allocations as we loop over runes + for i, currentRune := range nameRunes[1:] { + currentRunePosition := i + 1 + // recycle allocations as we loop over runes // with such recycling, only 2 slices should be allocated per call // instead of o(n). + // + // BorrowMatches always yields slices with zero length (with some capacity) newMatches := poolOfMatches.BorrowMatches() // check current initialism matches - if matches != nil { // skip first iteration - for _, match := range *matches { - if keepCompleteMatch := match.complete; keepCompleteMatch { - *newMatches = append(*newMatches, match) - - // the match is complete: keep it then move on to next rune - continue - } + for _, match := range *matches { + if keepCompleteMatch := match.complete; keepCompleteMatch { + // the match is already complete: keep it then move on to the next match + *newMatches = append(*newMatches, match) + continue + } - currentMatchRune := match.body[currentRunePosition-match.start] - if currentMatchRune != currentRune { - // failed match, move on to next rune - continue - } + if currentRunePosition-match.start == len(match.body) { + // unmatched: skip + continue + } - // try to complete ongoing match - if currentRunePosition-match.start == len(match.body)-1 { - // we are close; the next step is to check the symbol ahead - // if it is a lowercase letter, then it is not the end of match - // but the beginning of the next word. - // - // NOTE(fredbi): this heuristic sometimes leads to counterintuitive splits and - // perhaps (not sure yet) we should check against case _alternance_. - // - // Example: - // - // In the current version, in the sentence "IDS initialism", "ID" is recognized as an initialism, - // leading to a split like "id_s_initialism" (or IDSInitialism), - // whereas in the sentence "IDx initialism", it is not and produces something like - // "i_d_x_initialism" (or IDxInitialism). The generated file name is not great. - // - // Both go identifiers are tolerated by linters. - // - // Notice that the slightly different input "IDs initialism" is correctly detected - // as a pluralized initialism and produces something like "ids_initialism" (or IDsInitialism). - - if currentRunePosition < len(nameRunes)-1 { - nextRune := nameRunes[currentRunePosition+1] - - // recognize a plural form for this initialism (only simple pluralization is supported) - if nextRune == 's' && match.hasPlural == simplePlural { - // detected a pluralized initialism - match.body = append(match.body, nextRune) - currentRunePosition++ - if currentRunePosition < len(nameRunes)-1 { - nextRune = nameRunes[currentRunePosition+1] - if newWord := unicode.IsLower(nextRune); newWord { - // it is the start of a new word. - // Match is only partial and the initialism is not recognized : move on - continue - } - } + // 1. by construction of the matches, we can't have currentRunePosition - match.start < 0 + // because matches have been computed with their start <= currentRunePosition in the previous + // iterations. + // 2. by construction of the matches, we can't have currentRunePosition - match.start >= len(match.body) - // this is a pluralized match: keep it - match.complete = true - match.hasPlural = simplePlural - match.end = currentRunePosition - *newMatches = append(*newMatches, match) + currentMatchRune := match.body[currentRunePosition-match.start] + if currentMatchRune != currentRune { + // failed match, discard it then move on to the next match + continue + } - // match is complete: keep it then move on to next rune - continue + // try to complete the current match + if currentRunePosition-match.start == len(match.body)-1 { + // we are close: the next step is to check the symbol ahead + // if it is a lowercase letter, then it is not the end of match + // but the beginning of the next word. + // + // NOTE(fredbi): this heuristic sometimes leads to counterintuitive splits and + // perhaps (not sure yet) we should check against case _alternance_. + // + // Example: + // + // In the current version, in the sentence "IDS initialism", "ID" is recognized as an initialism, + // leading to a split like "id_s_initialism" (or IDSInitialism), + // whereas in the sentence "IDx initialism", it is not and produces something like + // "i_d_x_initialism" (or IDxInitialism). The generated file name is not great. + // + // Both go identifiers are tolerated by linters. + // + // Notice that the slightly different input "IDs initialism" is correctly detected + // as a pluralized initialism and produces something like "ids_initialism" (or IDsInitialism). + + if currentRunePosition < len(nameRunes)-1 { // when before the last rune + nextRune := nameRunes[currentRunePosition+1] + + // recognize a plural form for this initialism (only simple english pluralization is supported). + if nextRune == 's' && match.hasPlural == simplePlural { + // detected a pluralized initialism + match.body = append(match.body, nextRune) + lookAhead := currentRunePosition + 1 + if lookAhead < len(nameRunes)-1 { + nextRune = nameRunes[lookAhead+1] + if newWord := unicode.IsLower(nextRune); newWord { + // it is the start of a new word. + // Match is only partial and the initialism is not recognized: + // move on to the next match, but do not advance the rune position + continue + } } - if newWord := unicode.IsLower(nextRune); newWord { - // it is the start of a new word - // Match is only partial and the initialism is not recognized : move on - continue - } + // this is a pluralized match: keep it + currentRunePosition++ + match.complete = true + match.hasPlural = simplePlural + match.end = currentRunePosition + *newMatches = append(*newMatches, match) + + // match is complete: keep it then move on to the next match + continue } - match.complete = true - match.end = currentRunePosition + // other cases + // example: invariant plural such as "TLS" + if newWord := unicode.IsLower(nextRune); newWord { + // it is the start of a new word + // Match is only partial and the initialism is not recognized : move on + continue + } } - // append the ongoing matching attempt (not necessarily complete) - *newMatches = append(*newMatches, match) + match.complete = true + match.end = currentRunePosition } - } - // check for new initialism matches - for i, r := range s.initialismsRunes { - if r[0] == currentRune { - *newMatches = append(*newMatches, initialismMatch{ - start: currentRunePosition, - body: r, - complete: false, - hasPlural: s.initialismsPluralForm[i], - }) - } + // append the ongoing matching attempt: it is not necessarily complete, but was successful so far. + // Let's see if it still matches on the next rune. + *newMatches = append(*newMatches, match) } - if matches != nil { - poolOfMatches.RedeemMatches(matches) - } + s.findMatches(newMatches, nameRunes, currentRune, currentRunePosition) + + poolOfMatches.RedeemMatches(matches) matches = newMatches } - // up to the caller to redeem this last slice + // it is up to the caller to redeem this last slice return matches } +func (s splitter) findMatches(newMatches *initialismMatches, nameRunes []rune, currentRune rune, currentRunePosition int) { + // check for new initialism matches, based on the first character + for i, r := range s.initialismsRunes { + if r[0] != currentRune { + continue + } + + if currentRunePosition+len(r) > len(nameRunes) { + continue // not eligible: would spilll over the initial string + } + + // possible matches: all initialisms starting with the current rune and that can fit the given string (nameRunes) + *newMatches = append(*newMatches, initialismMatch{ + start: currentRunePosition, + body: r, + complete: false, + hasPlural: s.initialismsPluralForm[i], + }) + } +} + func (s splitter) mapMatchesToNameLexems(nameRunes []rune, matches *initialismMatches) *[]nameLexem { nameLexems := poolOfLexems.BorrowLexems() diff --git a/vendor/github.com/go-openapi/swag/mangling/string_bytes.go b/vendor/github.com/go-openapi/swag/mangling/string_bytes.go index 06351434d38..28daaf72b1a 100644 --- a/vendor/github.com/go-openapi/swag/mangling/string_bytes.go +++ b/vendor/github.com/go-openapi/swag/mangling/string_bytes.go @@ -1,16 +1,5 @@ -// Copyright 2015 go-swagger maintainers -// -// 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. +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 package mangling diff --git a/vendor/github.com/go-openapi/swag/mangling/util.go b/vendor/github.com/go-openapi/swag/mangling/util.go index c289dc6bddb..0636417e360 100644 --- a/vendor/github.com/go-openapi/swag/mangling/util.go +++ b/vendor/github.com/go-openapi/swag/mangling/util.go @@ -1,16 +1,5 @@ -// Copyright 2015 go-swagger maintainers -// -// 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. +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 package mangling diff --git a/vendor/github.com/go-openapi/swag/mangling_iface.go b/vendor/github.com/go-openapi/swag/mangling_iface.go index 2d0d07ddb62..98b9a999293 100644 --- a/vendor/github.com/go-openapi/swag/mangling_iface.go +++ b/vendor/github.com/go-openapi/swag/mangling_iface.go @@ -1,16 +1,5 @@ -// Copyright 2015 go-swagger maintainers -// -// 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. +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 package swag diff --git a/vendor/github.com/go-openapi/swag/netutils/doc.go b/vendor/github.com/go-openapi/swag/netutils/doc.go index ed6d8a022b8..74282f8e51c 100644 --- a/vendor/github.com/go-openapi/swag/netutils/doc.go +++ b/vendor/github.com/go-openapi/swag/netutils/doc.go @@ -1,16 +1,5 @@ -// Copyright 2015 go-swagger maintainers -// -// 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. +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 // Package netutils provides helpers for network-related tasks. package netutils diff --git a/vendor/github.com/go-openapi/swag/netutils/net.go b/vendor/github.com/go-openapi/swag/netutils/net.go index 3d0182fc5a1..82a1544af7b 100644 --- a/vendor/github.com/go-openapi/swag/netutils/net.go +++ b/vendor/github.com/go-openapi/swag/netutils/net.go @@ -1,16 +1,5 @@ -// Copyright 2015 go-swagger maintainers -// -// 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. +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 package netutils diff --git a/vendor/github.com/go-openapi/swag/netutils_iface.go b/vendor/github.com/go-openapi/swag/netutils_iface.go index 537314e3645..d658de25b3f 100644 --- a/vendor/github.com/go-openapi/swag/netutils_iface.go +++ b/vendor/github.com/go-openapi/swag/netutils_iface.go @@ -1,16 +1,5 @@ -// Copyright 2015 go-swagger maintainers -// -// 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. +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 package swag diff --git a/vendor/github.com/go-openapi/swag/stringutils/collection_formats.go b/vendor/github.com/go-openapi/swag/stringutils/collection_formats.go index 1ff96dcbd81..28056ad25c3 100644 --- a/vendor/github.com/go-openapi/swag/stringutils/collection_formats.go +++ b/vendor/github.com/go-openapi/swag/stringutils/collection_formats.go @@ -1,16 +1,5 @@ -// Copyright 2015 go-swagger maintainers -// -// 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. +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 package stringutils diff --git a/vendor/github.com/go-openapi/swag/stringutils/doc.go b/vendor/github.com/go-openapi/swag/stringutils/doc.go index b5d18e517d2..c6d17a1160b 100644 --- a/vendor/github.com/go-openapi/swag/stringutils/doc.go +++ b/vendor/github.com/go-openapi/swag/stringutils/doc.go @@ -1,16 +1,5 @@ -// Copyright 2015 go-swagger maintainers -// -// 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. +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 // Package stringutils exposes helpers to search and process strings. package stringutils diff --git a/vendor/github.com/go-openapi/swag/stringutils/strings.go b/vendor/github.com/go-openapi/swag/stringutils/strings.go index 086592317f8..cd792b7d083 100644 --- a/vendor/github.com/go-openapi/swag/stringutils/strings.go +++ b/vendor/github.com/go-openapi/swag/stringutils/strings.go @@ -1,16 +1,5 @@ -// Copyright 2015 go-swagger maintainers -// -// 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. +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 package stringutils diff --git a/vendor/github.com/go-openapi/swag/stringutils_iface.go b/vendor/github.com/go-openapi/swag/stringutils_iface.go index 00d7e021251..dbfa4848430 100644 --- a/vendor/github.com/go-openapi/swag/stringutils_iface.go +++ b/vendor/github.com/go-openapi/swag/stringutils_iface.go @@ -1,16 +1,5 @@ -// Copyright 2015 go-swagger maintainers -// -// 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. +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 package swag diff --git a/vendor/github.com/go-openapi/swag/typeutils/doc.go b/vendor/github.com/go-openapi/swag/typeutils/doc.go index 67e49d12ec5..66bed20dff0 100644 --- a/vendor/github.com/go-openapi/swag/typeutils/doc.go +++ b/vendor/github.com/go-openapi/swag/typeutils/doc.go @@ -1,16 +1,5 @@ -// Copyright 2015 go-swagger maintainers -// -// 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. +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 // Package typeutils exposes utilities to inspect generic types. package typeutils diff --git a/vendor/github.com/go-openapi/swag/typeutils/types.go b/vendor/github.com/go-openapi/swag/typeutils/types.go index f0ddd3cd3df..55487a673c4 100644 --- a/vendor/github.com/go-openapi/swag/typeutils/types.go +++ b/vendor/github.com/go-openapi/swag/typeutils/types.go @@ -1,16 +1,5 @@ -// Copyright 2015 go-swagger maintainers -// -// 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. +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 package typeutils diff --git a/vendor/github.com/go-openapi/swag/typeutils_iface.go b/vendor/github.com/go-openapi/swag/typeutils_iface.go index b104a8040aa..b63813ea408 100644 --- a/vendor/github.com/go-openapi/swag/typeutils_iface.go +++ b/vendor/github.com/go-openapi/swag/typeutils_iface.go @@ -1,16 +1,5 @@ -// Copyright 2015 go-swagger maintainers -// -// 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. +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 package swag @@ -20,4 +9,4 @@ import "github.com/go-openapi/swag/typeutils" // This allows for safer checking of interface values. // // Deprecated: use [typeutils.IsZero] instead. -func IsZero(data interface{}) bool { return typeutils.IsZero(data) } +func IsZero(data any) bool { return typeutils.IsZero(data) } diff --git a/vendor/github.com/go-openapi/swag/yamlutils/doc.go b/vendor/github.com/go-openapi/swag/yamlutils/doc.go index 4aeadc22480..7bb92a82f1b 100644 --- a/vendor/github.com/go-openapi/swag/yamlutils/doc.go +++ b/vendor/github.com/go-openapi/swag/yamlutils/doc.go @@ -1,16 +1,5 @@ -// Copyright 2015 go-swagger maintainers -// -// 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. +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 // Package yamlutils provides utilities to work with YAML documents. // diff --git a/vendor/github.com/go-openapi/swag/yamlutils/errors.go b/vendor/github.com/go-openapi/swag/yamlutils/errors.go index 014f227d965..e87bc5e8beb 100644 --- a/vendor/github.com/go-openapi/swag/yamlutils/errors.go +++ b/vendor/github.com/go-openapi/swag/yamlutils/errors.go @@ -1,16 +1,5 @@ -// Copyright 2015 go-swagger maintainers -// -// 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. +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 package yamlutils diff --git a/vendor/github.com/go-openapi/swag/yamlutils/ordered_map.go b/vendor/github.com/go-openapi/swag/yamlutils/ordered_map.go index af1d7bb518a..3daf68dbba0 100644 --- a/vendor/github.com/go-openapi/swag/yamlutils/ordered_map.go +++ b/vendor/github.com/go-openapi/swag/yamlutils/ordered_map.go @@ -1,3 +1,6 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + package yamlutils import ( diff --git a/vendor/github.com/go-openapi/swag/yamlutils/yaml.go b/vendor/github.com/go-openapi/swag/yamlutils/yaml.go index 67fba8fd7c8..e3aff3c2fde 100644 --- a/vendor/github.com/go-openapi/swag/yamlutils/yaml.go +++ b/vendor/github.com/go-openapi/swag/yamlutils/yaml.go @@ -1,16 +1,5 @@ -// Copyright 2015 go-swagger maintainers -// -// 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. +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 package yamlutils diff --git a/vendor/github.com/go-openapi/swag/yamlutils_iface.go b/vendor/github.com/go-openapi/swag/yamlutils_iface.go index 49e646486e3..57767efc567 100644 --- a/vendor/github.com/go-openapi/swag/yamlutils_iface.go +++ b/vendor/github.com/go-openapi/swag/yamlutils_iface.go @@ -1,16 +1,5 @@ -// Copyright 2015 go-swagger maintainers -// -// 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. +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 package swag @@ -23,9 +12,9 @@ import ( // YAMLToJSON converts YAML unmarshaled data into json compatible data // // Deprecated: use [yamlutils.YAMLToJSON] instead. -func YAMLToJSON(data interface{}) (json.RawMessage, error) { return yamlutils.YAMLToJSON(data) } +func YAMLToJSON(data any) (json.RawMessage, error) { return yamlutils.YAMLToJSON(data) } // BytesToYAMLDoc converts a byte slice into a YAML document // // Deprecated: use [yamlutils.BytesToYAMLDoc] instead. -func BytesToYAMLDoc(data []byte) (interface{}, error) { return yamlutils.BytesToYAMLDoc(data) } +func BytesToYAMLDoc(data []byte) (any, error) { return yamlutils.BytesToYAMLDoc(data) } diff --git a/vendor/github.com/go-openapi/validate/.golangci.yml b/vendor/github.com/go-openapi/validate/.golangci.yml index 43e2576479a..10c513342fc 100644 --- a/vendor/github.com/go-openapi/validate/.golangci.yml +++ b/vendor/github.com/go-openapi/validate/.golangci.yml @@ -17,7 +17,7 @@ linters: - gomoddirectives - gosmopolitan - inamedparam - #- intrange # disabled while < go1.22 + - intrange - ireturn - lll - musttag diff --git a/vendor/github.com/go-openapi/validate/README.md b/vendor/github.com/go-openapi/validate/README.md index e8e1bb218d9..73d87ce4f01 100644 --- a/vendor/github.com/go-openapi/validate/README.md +++ b/vendor/github.com/go-openapi/validate/README.md @@ -24,6 +24,10 @@ Reference can be found here: https://github.com/OAI/OpenAPI-Specification/blob/m [Documentation](https://pkg.go.dev/github.com/go-openapi/validate) +## Licensing + +This library ships under the [SPDX-License-Identifier: Apache-2.0](./LICENSE). + ## FAQ * Does this library support OpenAPI 3? diff --git a/vendor/github.com/go-openapi/validate/context.go b/vendor/github.com/go-openapi/validate/context.go index d54791c9d05..b4587dcd560 100644 --- a/vendor/github.com/go-openapi/validate/context.go +++ b/vendor/github.com/go-openapi/validate/context.go @@ -1,3 +1,6 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + package validate import ( diff --git a/vendor/github.com/go-openapi/validate/debug.go b/vendor/github.com/go-openapi/validate/debug.go index 8815fd93597..79145a4495d 100644 --- a/vendor/github.com/go-openapi/validate/debug.go +++ b/vendor/github.com/go-openapi/validate/debug.go @@ -1,16 +1,5 @@ -// Copyright 2015 go-swagger maintainers -// -// 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. +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 package validate @@ -38,7 +27,7 @@ func debugOptions() { validateLogger = log.New(os.Stdout, "validate:", log.LstdFlags) } -func debugLog(msg string, args ...interface{}) { +func debugLog(msg string, args ...any) { // A private, trivial trace logger, based on go-openapi/spec/expander.go:debugLog() if Debug { _, file1, pos1, _ := runtime.Caller(1) diff --git a/vendor/github.com/go-openapi/validate/default_validator.go b/vendor/github.com/go-openapi/validate/default_validator.go index e82bb30178e..79a431677e4 100644 --- a/vendor/github.com/go-openapi/validate/default_validator.go +++ b/vendor/github.com/go-openapi/validate/default_validator.go @@ -1,16 +1,5 @@ -// Copyright 2015 go-swagger maintainers -// -// 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. +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 package validate diff --git a/vendor/github.com/go-openapi/validate/doc.go b/vendor/github.com/go-openapi/validate/doc.go index d2b901eab9a..a99893e1a38 100644 --- a/vendor/github.com/go-openapi/validate/doc.go +++ b/vendor/github.com/go-openapi/validate/doc.go @@ -1,16 +1,5 @@ -// Copyright 2015 go-swagger maintainers -// -// 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. +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 /* Package validate provides methods to validate a swagger specification, diff --git a/vendor/github.com/go-openapi/validate/example_validator.go b/vendor/github.com/go-openapi/validate/example_validator.go index 0663b21dc5e..e4ef52c6dc1 100644 --- a/vendor/github.com/go-openapi/validate/example_validator.go +++ b/vendor/github.com/go-openapi/validate/example_validator.go @@ -1,16 +1,5 @@ -// Copyright 2015 go-swagger maintainers -// -// 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. +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 package validate diff --git a/vendor/github.com/go-openapi/validate/formats.go b/vendor/github.com/go-openapi/validate/formats.go index f4e35521306..85ee6349418 100644 --- a/vendor/github.com/go-openapi/validate/formats.go +++ b/vendor/github.com/go-openapi/validate/formats.go @@ -1,16 +1,5 @@ -// Copyright 2015 go-swagger maintainers -// -// 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. +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 package validate @@ -54,7 +43,7 @@ func (f *formatValidator) SetPath(path string) { f.Path = path } -func (f *formatValidator) Applies(source interface{}, kind reflect.Kind) bool { +func (f *formatValidator) Applies(source any, kind reflect.Kind) bool { if source == nil || f.KnownFormats == nil { return false } @@ -73,7 +62,7 @@ func (f *formatValidator) Applies(source interface{}, kind reflect.Kind) bool { } } -func (f *formatValidator) Validate(val interface{}) *Result { +func (f *formatValidator) Validate(val any) *Result { if f.Options.recycleValidators { defer func() { f.redeem() diff --git a/vendor/github.com/go-openapi/validate/helpers.go b/vendor/github.com/go-openapi/validate/helpers.go index 16840da6331..49b130473a9 100644 --- a/vendor/github.com/go-openapi/validate/helpers.go +++ b/vendor/github.com/go-openapi/validate/helpers.go @@ -1,16 +1,5 @@ -// Copyright 2015 go-swagger maintainers -// -// 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. +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 package validate @@ -139,7 +128,7 @@ func (h *pathHelper) stripParametersInPath(path string) string { rexParsePathParam := mustCompileRegexp(`{[^{}]+?}`) strippedSegments := []string{} - for _, segment := range strings.Split(path, "/") { + for segment := range strings.SplitSeq(path, "/") { strippedSegments = append(strippedSegments, rexParsePathParam.ReplaceAllString(segment, "X")) } return strings.Join(strippedSegments, "/") @@ -149,7 +138,7 @@ func (h *pathHelper) extractPathParams(path string) (params []string) { // Extracts all params from a path, with surrounding "{}" rexParsePathParam := mustCompileRegexp(`{[^{}]+?}`) - for _, segment := range strings.Split(path, "/") { + for segment := range strings.SplitSeq(path, "/") { for _, v := range rexParsePathParam.FindAllStringSubmatch(segment, -1) { params = append(params, v...) } @@ -161,7 +150,7 @@ type valueHelper struct { // A collection of unexported helpers for value validation } -func (h *valueHelper) asInt64(val interface{}) int64 { +func (h *valueHelper) asInt64(val any) int64 { // Number conversion function for int64, without error checking // (implements an implicit type upgrade). v := reflect.ValueOf(val) @@ -178,7 +167,7 @@ func (h *valueHelper) asInt64(val interface{}) int64 { } } -func (h *valueHelper) asUint64(val interface{}) uint64 { +func (h *valueHelper) asUint64(val any) uint64 { // Number conversion function for uint64, without error checking // (implements an implicit type upgrade). v := reflect.ValueOf(val) @@ -196,7 +185,7 @@ func (h *valueHelper) asUint64(val interface{}) uint64 { } // Same for unsigned floats -func (h *valueHelper) asFloat64(val interface{}) float64 { +func (h *valueHelper) asFloat64(val any) float64 { // Number conversion function for float64, without error checking // (implements an implicit type upgrade). v := reflect.ValueOf(val) diff --git a/vendor/github.com/go-openapi/validate/object_validator.go b/vendor/github.com/go-openapi/validate/object_validator.go index 76301d0e887..cf98ed377d5 100644 --- a/vendor/github.com/go-openapi/validate/object_validator.go +++ b/vendor/github.com/go-openapi/validate/object_validator.go @@ -1,16 +1,5 @@ -// Copyright 2015 go-swagger maintainers -// -// 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. +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 package validate diff --git a/vendor/github.com/go-openapi/validate/options.go b/vendor/github.com/go-openapi/validate/options.go index cfe9b0660f6..f5e7f7131c7 100644 --- a/vendor/github.com/go-openapi/validate/options.go +++ b/vendor/github.com/go-openapi/validate/options.go @@ -1,16 +1,5 @@ -// Copyright 2015 go-swagger maintainers -// -// 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. +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 package validate diff --git a/vendor/github.com/go-openapi/validate/pools.go b/vendor/github.com/go-openapi/validate/pools.go index 3ddce4dcc2b..1e734be493b 100644 --- a/vendor/github.com/go-openapi/validate/pools.go +++ b/vendor/github.com/go-openapi/validate/pools.go @@ -1,3 +1,6 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + //go:build !validatedebug package validate diff --git a/vendor/github.com/go-openapi/validate/pools_debug.go b/vendor/github.com/go-openapi/validate/pools_debug.go index 12949f02a7e..d123ed4093f 100644 --- a/vendor/github.com/go-openapi/validate/pools_debug.go +++ b/vendor/github.com/go-openapi/validate/pools_debug.go @@ -1,3 +1,6 @@ +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + //go:build validatedebug package validate diff --git a/vendor/github.com/go-openapi/validate/result.go b/vendor/github.com/go-openapi/validate/result.go index 1955cff7837..69219e99823 100644 --- a/vendor/github.com/go-openapi/validate/result.go +++ b/vendor/github.com/go-openapi/validate/result.go @@ -1,16 +1,5 @@ -// Copyright 2015 go-swagger maintainers -// -// 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. +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 package validate diff --git a/vendor/github.com/go-openapi/validate/rexp.go b/vendor/github.com/go-openapi/validate/rexp.go index 76de03e1f41..795f148d0cf 100644 --- a/vendor/github.com/go-openapi/validate/rexp.go +++ b/vendor/github.com/go-openapi/validate/rexp.go @@ -1,20 +1,10 @@ -// Copyright 2015 go-swagger maintainers -// -// 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. +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 package validate import ( + "maps" re "regexp" "sync" "sync/atomic" @@ -62,9 +52,7 @@ func cacheRegexp(r *re.Regexp) { r.String(): r, } - for k, v := range cache { - newCache[k] = v - } + maps.Copy(newCache, cache) reDict.Store(newCache) } diff --git a/vendor/github.com/go-openapi/validate/schema.go b/vendor/github.com/go-openapi/validate/schema.go index 8c48899b0b1..375a98765d7 100644 --- a/vendor/github.com/go-openapi/validate/schema.go +++ b/vendor/github.com/go-openapi/validate/schema.go @@ -1,16 +1,5 @@ -// Copyright 2015 go-swagger maintainers -// -// 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. +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 package validate @@ -30,7 +19,7 @@ type SchemaValidator struct { in string Schema *spec.Schema validators [8]valueValidator - Root interface{} + Root any KnownFormats strfmt.Registry Options *SchemaValidatorOptions } @@ -38,7 +27,7 @@ type SchemaValidator struct { // AgainstSchema validates the specified data against the provided schema, using a registry of supported formats. // // When no pre-parsed *spec.Schema structure is provided, it uses a JSON schema as default. See example. -func AgainstSchema(schema *spec.Schema, data interface{}, formats strfmt.Registry, options ...Option) error { +func AgainstSchema(schema *spec.Schema, data any, formats strfmt.Registry, options ...Option) error { res := NewSchemaValidator(schema, nil, "", formats, append(options, WithRecycleValidators(true), withRecycleResults(true))..., ).Validate(data) @@ -56,7 +45,7 @@ func AgainstSchema(schema *spec.Schema, data interface{}, formats strfmt.Registr // NewSchemaValidator creates a new schema validator. // // Panics if the provided schema is invalid. -func NewSchemaValidator(schema *spec.Schema, rootSchema interface{}, root string, formats strfmt.Registry, options ...Option) *SchemaValidator { +func NewSchemaValidator(schema *spec.Schema, rootSchema any, root string, formats strfmt.Registry, options ...Option) *SchemaValidator { opts := new(SchemaValidatorOptions) for _, o := range options { o(opts) @@ -65,7 +54,7 @@ func NewSchemaValidator(schema *spec.Schema, rootSchema interface{}, root string return newSchemaValidator(schema, rootSchema, root, formats, opts) } -func newSchemaValidator(schema *spec.Schema, rootSchema interface{}, root string, formats strfmt.Registry, opts *SchemaValidatorOptions) *SchemaValidator { +func newSchemaValidator(schema *spec.Schema, rootSchema any, root string, formats strfmt.Registry, opts *SchemaValidatorOptions) *SchemaValidator { if schema == nil { return nil } @@ -120,13 +109,13 @@ func (s *SchemaValidator) SetPath(path string) { } // Applies returns true when this schema validator applies -func (s *SchemaValidator) Applies(source interface{}, _ reflect.Kind) bool { +func (s *SchemaValidator) Applies(source any, _ reflect.Kind) bool { _, ok := source.(*spec.Schema) return ok } // Validate validates the data against the schema -func (s *SchemaValidator) Validate(data interface{}) *Result { +func (s *SchemaValidator) Validate(data any) *Result { if s == nil { return emptyResult } diff --git a/vendor/github.com/go-openapi/validate/schema_messages.go b/vendor/github.com/go-openapi/validate/schema_messages.go index 786e2e3554e..e8c7c48ad7f 100644 --- a/vendor/github.com/go-openapi/validate/schema_messages.go +++ b/vendor/github.com/go-openapi/validate/schema_messages.go @@ -1,16 +1,5 @@ -// Copyright 2015 go-swagger maintainers -// -// 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. +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 package validate diff --git a/vendor/github.com/go-openapi/validate/schema_option.go b/vendor/github.com/go-openapi/validate/schema_option.go index 65eeebeaab3..d9fd21a75a1 100644 --- a/vendor/github.com/go-openapi/validate/schema_option.go +++ b/vendor/github.com/go-openapi/validate/schema_option.go @@ -1,16 +1,5 @@ -// Copyright 2015 go-swagger maintainers -// -// 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. +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 package validate diff --git a/vendor/github.com/go-openapi/validate/schema_props.go b/vendor/github.com/go-openapi/validate/schema_props.go index b8bdee82c58..485f536adc3 100644 --- a/vendor/github.com/go-openapi/validate/schema_props.go +++ b/vendor/github.com/go-openapi/validate/schema_props.go @@ -1,16 +1,5 @@ -// Copyright 2015 go-swagger maintainers -// -// 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. +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 package validate @@ -34,7 +23,7 @@ type schemaPropsValidator struct { allOfValidators []*SchemaValidator oneOfValidators []*SchemaValidator notValidator *SchemaValidator - Root interface{} + Root any KnownFormats strfmt.Registry Options *SchemaValidatorOptions } @@ -44,7 +33,7 @@ func (s *schemaPropsValidator) SetPath(path string) { } func newSchemaPropsValidator( - path string, in string, allOf, oneOf, anyOf []spec.Schema, not *spec.Schema, deps spec.Dependencies, root interface{}, formats strfmt.Registry, + path string, in string, allOf, oneOf, anyOf []spec.Schema, not *spec.Schema, deps spec.Dependencies, root any, formats strfmt.Registry, opts *SchemaValidatorOptions) *schemaPropsValidator { if opts == nil { opts = new(SchemaValidatorOptions) @@ -93,12 +82,12 @@ func newSchemaPropsValidator( return s } -func (s *schemaPropsValidator) Applies(source interface{}, _ reflect.Kind) bool { +func (s *schemaPropsValidator) Applies(source any, _ reflect.Kind) bool { _, isSchema := source.(*spec.Schema) return isSchema } -func (s *schemaPropsValidator) Validate(data interface{}) *Result { +func (s *schemaPropsValidator) Validate(data any) *Result { var mainResult *Result if s.Options.recycleResult { mainResult = pools.poolOfResults.BorrowResult() @@ -150,7 +139,7 @@ func (s *schemaPropsValidator) Validate(data interface{}) *Result { return mainResult.Merge(keepResultAllOf, keepResultOneOf, keepResultAnyOf) } -func (s *schemaPropsValidator) validateAnyOf(data interface{}, mainResult, keepResultAnyOf *Result) { +func (s *schemaPropsValidator) validateAnyOf(data any, mainResult, keepResultAnyOf *Result) { // Validates at least one in anyOf schemas var bestFailures *Result @@ -192,7 +181,7 @@ func (s *schemaPropsValidator) validateAnyOf(data interface{}, mainResult, keepR mainResult.Merge(bestFailures) } -func (s *schemaPropsValidator) validateOneOf(data interface{}, mainResult, keepResultOneOf *Result) { +func (s *schemaPropsValidator) validateOneOf(data any, mainResult, keepResultOneOf *Result) { // Validates exactly one in oneOf schemas var ( firstSuccess, bestFailures *Result @@ -251,7 +240,7 @@ func (s *schemaPropsValidator) validateOneOf(data interface{}, mainResult, keepR } } -func (s *schemaPropsValidator) validateAllOf(data interface{}, mainResult, keepResultAllOf *Result) { +func (s *schemaPropsValidator) validateAllOf(data any, mainResult, keepResultAllOf *Result) { // Validates all of allOf schemas var validated int @@ -277,7 +266,7 @@ func (s *schemaPropsValidator) validateAllOf(data interface{}, mainResult, keepR } } -func (s *schemaPropsValidator) validateNot(data interface{}, mainResult *Result) { +func (s *schemaPropsValidator) validateNot(data any, mainResult *Result) { result := s.notValidator.Validate(data) if s.Options.recycleValidators { s.notValidator = nil @@ -291,8 +280,8 @@ func (s *schemaPropsValidator) validateNot(data interface{}, mainResult *Result) } } -func (s *schemaPropsValidator) validateDependencies(data interface{}, mainResult *Result) { - val := data.(map[string]interface{}) +func (s *schemaPropsValidator) validateDependencies(data any, mainResult *Result) { + val := data.(map[string]any) for key := range val { dep, ok := s.Dependencies[key] if !ok { diff --git a/vendor/github.com/go-openapi/validate/slice_validator.go b/vendor/github.com/go-openapi/validate/slice_validator.go index 7b0dede290d..4a5a2089687 100644 --- a/vendor/github.com/go-openapi/validate/slice_validator.go +++ b/vendor/github.com/go-openapi/validate/slice_validator.go @@ -1,16 +1,5 @@ -// Copyright 2015 go-swagger maintainers -// -// 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. +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 package validate @@ -30,7 +19,7 @@ type schemaSliceValidator struct { UniqueItems bool AdditionalItems *spec.SchemaOrBool Items *spec.SchemaOrArray - Root interface{} + Root any KnownFormats strfmt.Registry Options *SchemaValidatorOptions } @@ -38,7 +27,7 @@ type schemaSliceValidator struct { func newSliceValidator(path, in string, maxItems, minItems *int64, uniqueItems bool, additionalItems *spec.SchemaOrBool, items *spec.SchemaOrArray, - root interface{}, formats strfmt.Registry, opts *SchemaValidatorOptions) *schemaSliceValidator { + root any, formats strfmt.Registry, opts *SchemaValidatorOptions) *schemaSliceValidator { if opts == nil { opts = new(SchemaValidatorOptions) } @@ -68,13 +57,13 @@ func (s *schemaSliceValidator) SetPath(path string) { s.Path = path } -func (s *schemaSliceValidator) Applies(source interface{}, kind reflect.Kind) bool { +func (s *schemaSliceValidator) Applies(source any, kind reflect.Kind) bool { _, ok := source.(*spec.Schema) r := ok && kind == reflect.Slice return r } -func (s *schemaSliceValidator) Validate(data interface{}) *Result { +func (s *schemaSliceValidator) Validate(data any) *Result { if s.Options.recycleValidators { defer func() { s.redeem() diff --git a/vendor/github.com/go-openapi/validate/spec.go b/vendor/github.com/go-openapi/validate/spec.go index aef0cc36eca..8616a861f28 100644 --- a/vendor/github.com/go-openapi/validate/spec.go +++ b/vendor/github.com/go-openapi/validate/spec.go @@ -1,16 +1,5 @@ -// Copyright 2015 go-swagger maintainers -// -// 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. +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 package validate @@ -19,6 +8,7 @@ import ( "encoding/gob" "encoding/json" "fmt" + "slices" "sort" "strings" @@ -458,11 +448,8 @@ func (s *SpecValidator) validatePathParamPresence(path string, fromPath, fromOpe for _, p := range fromOperation { var matched bool - for _, r := range fromPath { - if "{"+p+"}" == r { - matched = true - break - } + if slices.Contains(fromPath, "{"+p+"}") { + matched = true } if !matched { res.AddErrors(pathParamNotInPathMsg(path, p)) diff --git a/vendor/github.com/go-openapi/validate/spec_messages.go b/vendor/github.com/go-openapi/validate/spec_messages.go index 8da22cfb853..9b079af647a 100644 --- a/vendor/github.com/go-openapi/validate/spec_messages.go +++ b/vendor/github.com/go-openapi/validate/spec_messages.go @@ -1,16 +1,5 @@ -// Copyright 2015 go-swagger maintainers -// -// 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. +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 package validate @@ -217,10 +206,10 @@ func emptyPathParameterMsg(path string) errors.Error { func nonUniqueOperationIDMsg(path string, i int) errors.Error { return errors.New(errors.CompositeErrorCode, NonUniqueOperationIDError, path, i) } -func circularAncestryDefinitionMsg(path string, args interface{}) errors.Error { +func circularAncestryDefinitionMsg(path string, args any) errors.Error { return errors.New(errors.CompositeErrorCode, CircularAncestryDefinitionError, path, args) } -func duplicatePropertiesMsg(path string, args interface{}) errors.Error { +func duplicatePropertiesMsg(path string, args any) errors.Error { return errors.New(errors.CompositeErrorCode, DuplicatePropertiesError, path, args) } func pathParamNotInPathMsg(path, param string) errors.Error { @@ -262,7 +251,7 @@ func pathParamRequiredMsg(operation, param string) errors.Error { func bothFormDataAndBodyMsg(operation string) errors.Error { return errors.New(errors.CompositeErrorCode, BothFormDataAndBodyError, operation) } -func multipleBodyParamMsg(operation string, args interface{}) errors.Error { +func multipleBodyParamMsg(operation string, args any) errors.Error { return errors.New(errors.CompositeErrorCode, MultipleBodyParamError, operation, args) } func pathParamNotUniqueMsg(path, param, arg string) errors.Error { @@ -304,7 +293,7 @@ func defaultValueHeaderDoesNotValidateMsg(operation, header, path string) errors func defaultValueHeaderItemsDoesNotValidateMsg(operation, header, path string) errors.Error { return errors.New(errors.CompositeErrorCode, DefaultValueHeaderItemsDoesNotValidateError, operation, header, path) } -func invalidPatternInHeaderMsg(operation, header, path, pattern string, args interface{}) errors.Error { +func invalidPatternInHeaderMsg(operation, header, path, pattern string, args any) errors.Error { return errors.New(errors.CompositeErrorCode, InvalidPatternInHeaderError, operation, header, path, pattern, args) } func invalidPatternInMsg(path, in, pattern string) errors.Error { diff --git a/vendor/github.com/go-openapi/validate/type.go b/vendor/github.com/go-openapi/validate/type.go index 91ae3413cd0..9b9ab8d917d 100644 --- a/vendor/github.com/go-openapi/validate/type.go +++ b/vendor/github.com/go-openapi/validate/type.go @@ -1,16 +1,5 @@ -// Copyright 2015 go-swagger maintainers -// -// 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. +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 package validate @@ -60,7 +49,7 @@ func (t *typeValidator) SetPath(path string) { t.Path = path } -func (t *typeValidator) Applies(source interface{}, _ reflect.Kind) bool { +func (t *typeValidator) Applies(source any, _ reflect.Kind) bool { // typeValidator applies to Schema, Parameter and Header objects switch source.(type) { case *spec.Schema: @@ -73,7 +62,7 @@ func (t *typeValidator) Applies(source interface{}, _ reflect.Kind) bool { return (len(t.Type) > 0 || t.Format != "") } -func (t *typeValidator) Validate(data interface{}) *Result { +func (t *typeValidator) Validate(data any) *Result { if t.Options.recycleValidators { defer func() { t.redeem() @@ -120,7 +109,7 @@ func (t *typeValidator) Validate(data interface{}) *Result { return emptyResult } -func (t *typeValidator) schemaInfoForType(data interface{}) (string, string) { +func (t *typeValidator) schemaInfoForType(data any) (string, string) { // internal type to JSON type with swagger 2.0 format (with go-openapi/strfmt extensions), // see https://github.com/go-openapi/strfmt/blob/master/README.md // TODO: this switch really is some sort of reverse lookup for formats. It should be provided by strfmt. diff --git a/vendor/github.com/go-openapi/validate/validator.go b/vendor/github.com/go-openapi/validate/validator.go index b76b8636141..289a847fc7b 100644 --- a/vendor/github.com/go-openapi/validate/validator.go +++ b/vendor/github.com/go-openapi/validate/validator.go @@ -1,16 +1,5 @@ -// Copyright 2015 go-swagger maintainers -// -// 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. +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 package validate @@ -25,18 +14,18 @@ import ( // An EntityValidator is an interface for things that can validate entities type EntityValidator interface { - Validate(interface{}) *Result + Validate(any) *Result } type valueValidator interface { SetPath(path string) - Applies(interface{}, reflect.Kind) bool - Validate(interface{}) *Result + Applies(any, reflect.Kind) bool + Validate(any) *Result } type itemsValidator struct { items *spec.Items - root interface{} + root any path string in string validators [6]valueValidator @@ -44,7 +33,7 @@ type itemsValidator struct { Options *SchemaValidatorOptions } -func newItemsValidator(path, in string, items *spec.Items, root interface{}, formats strfmt.Registry, opts *SchemaValidatorOptions) *itemsValidator { +func newItemsValidator(path, in string, items *spec.Items, root any, formats strfmt.Registry, opts *SchemaValidatorOptions) *itemsValidator { if opts == nil { opts = new(SchemaValidatorOptions) } @@ -73,7 +62,7 @@ func newItemsValidator(path, in string, items *spec.Items, root interface{}, for return iv } -func (i *itemsValidator) Validate(index int, data interface{}) *Result { +func (i *itemsValidator) Validate(index int, data any) *Result { if i.Options.recycleValidators { defer func() { i.redeemChildren() @@ -226,12 +215,12 @@ func (i *itemsValidator) redeemChildren() { type basicCommonValidator struct { Path string In string - Default interface{} - Enum []interface{} + Default any + Enum []any Options *SchemaValidatorOptions } -func newBasicCommonValidator(path, in string, def interface{}, enum []interface{}, opts *SchemaValidatorOptions) *basicCommonValidator { +func newBasicCommonValidator(path, in string, def any, enum []any, opts *SchemaValidatorOptions) *basicCommonValidator { if opts == nil { opts = new(SchemaValidatorOptions) } @@ -256,7 +245,7 @@ func (b *basicCommonValidator) SetPath(path string) { b.Path = path } -func (b *basicCommonValidator) Applies(source interface{}, _ reflect.Kind) bool { +func (b *basicCommonValidator) Applies(source any, _ reflect.Kind) bool { switch source.(type) { case *spec.Parameter, *spec.Schema, *spec.Header: return true @@ -265,7 +254,7 @@ func (b *basicCommonValidator) Applies(source interface{}, _ reflect.Kind) bool } } -func (b *basicCommonValidator) Validate(data interface{}) (res *Result) { +func (b *basicCommonValidator) Validate(data any) (res *Result) { if b.Options.recycleValidators { defer func() { b.redeem() @@ -352,7 +341,7 @@ func newHeaderValidator(name string, header *spec.Header, formats strfmt.Registr } // Validate the value of the header against its schema -func (p *HeaderValidator) Validate(data interface{}) *Result { +func (p *HeaderValidator) Validate(data any) *Result { if p.Options.recycleValidators { defer func() { p.redeemChildren() @@ -543,7 +532,7 @@ func newParamValidator(param *spec.Parameter, formats strfmt.Registry, opts *Sch } // Validate the data against the description of the parameter -func (p *ParamValidator) Validate(data interface{}) *Result { +func (p *ParamValidator) Validate(data any) *Result { if data == nil { return nil } @@ -685,20 +674,20 @@ func (p *ParamValidator) redeemChildren() { type basicSliceValidator struct { Path string In string - Default interface{} + Default any MaxItems *int64 MinItems *int64 UniqueItems bool Items *spec.Items - Source interface{} + Source any KnownFormats strfmt.Registry Options *SchemaValidatorOptions } func newBasicSliceValidator( path, in string, - def interface{}, maxItems, minItems *int64, uniqueItems bool, items *spec.Items, - source interface{}, formats strfmt.Registry, + def any, maxItems, minItems *int64, uniqueItems bool, items *spec.Items, + source any, formats strfmt.Registry, opts *SchemaValidatorOptions) *basicSliceValidator { if opts == nil { opts = new(SchemaValidatorOptions) @@ -729,7 +718,7 @@ func (s *basicSliceValidator) SetPath(path string) { s.Path = path } -func (s *basicSliceValidator) Applies(source interface{}, kind reflect.Kind) bool { +func (s *basicSliceValidator) Applies(source any, kind reflect.Kind) bool { switch source.(type) { case *spec.Parameter, *spec.Items, *spec.Header: return kind == reflect.Slice @@ -738,7 +727,7 @@ func (s *basicSliceValidator) Applies(source interface{}, kind reflect.Kind) boo } } -func (s *basicSliceValidator) Validate(data interface{}) *Result { +func (s *basicSliceValidator) Validate(data any) *Result { if s.Options.recycleValidators { defer func() { s.redeem() @@ -792,7 +781,7 @@ func (s *basicSliceValidator) redeem() { type numberValidator struct { Path string In string - Default interface{} + Default any MultipleOf *float64 Maximum *float64 ExclusiveMaximum bool @@ -805,7 +794,7 @@ type numberValidator struct { } func newNumberValidator( - path, in string, def interface{}, + path, in string, def any, multipleOf, maximum *float64, exclusiveMaximum bool, minimum *float64, exclusiveMinimum bool, typ, format string, opts *SchemaValidatorOptions) *numberValidator { @@ -839,7 +828,7 @@ func (n *numberValidator) SetPath(path string) { n.Path = path } -func (n *numberValidator) Applies(source interface{}, kind reflect.Kind) bool { +func (n *numberValidator) Applies(source any, kind reflect.Kind) bool { switch source.(type) { case *spec.Parameter, *spec.Schema, *spec.Items, *spec.Header: isInt := kind >= reflect.Int && kind <= reflect.Uint64 @@ -871,7 +860,7 @@ func (n *numberValidator) Applies(source interface{}, kind reflect.Kind) bool { // TODO: consider replacing boundary check errors by simple warnings. // // TODO: default boundaries with MAX_SAFE_INTEGER are not checked (specific to json.Number?) -func (n *numberValidator) Validate(val interface{}) *Result { +func (n *numberValidator) Validate(val any) *Result { if n.Options.recycleValidators { defer func() { n.redeem() @@ -958,7 +947,7 @@ func (n *numberValidator) redeem() { type stringValidator struct { Path string In string - Default interface{} + Default any Required bool AllowEmptyValue bool MaxLength *int64 @@ -969,7 +958,7 @@ type stringValidator struct { func newStringValidator( path, in string, - def interface{}, required, allowEmpty bool, maxLength, minLength *int64, pattern string, + def any, required, allowEmpty bool, maxLength, minLength *int64, pattern string, opts *SchemaValidatorOptions) *stringValidator { if opts == nil { opts = new(SchemaValidatorOptions) @@ -999,7 +988,7 @@ func (s *stringValidator) SetPath(path string) { s.Path = path } -func (s *stringValidator) Applies(source interface{}, kind reflect.Kind) bool { +func (s *stringValidator) Applies(source any, kind reflect.Kind) bool { switch source.(type) { case *spec.Parameter, *spec.Schema, *spec.Items, *spec.Header: return kind == reflect.String @@ -1008,7 +997,7 @@ func (s *stringValidator) Applies(source interface{}, kind reflect.Kind) bool { } } -func (s *stringValidator) Validate(val interface{}) *Result { +func (s *stringValidator) Validate(val any) *Result { if s.Options.recycleValidators { defer func() { s.redeem() diff --git a/vendor/github.com/go-openapi/validate/values.go b/vendor/github.com/go-openapi/validate/values.go index 1bfa6f3c8cf..e7dd5c8d3ab 100644 --- a/vendor/github.com/go-openapi/validate/values.go +++ b/vendor/github.com/go-openapi/validate/values.go @@ -1,16 +1,5 @@ -// Copyright 2015 go-swagger maintainers -// -// 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. +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 package validate diff --git a/vendor/github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1/alertmanager_types.go b/vendor/github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1/alertmanager_types.go index 29de7972872..9254d1a4b03 100644 --- a/vendor/github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1/alertmanager_types.go +++ b/vendor/github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1/alertmanager_types.go @@ -198,9 +198,10 @@ type AlertmanagerSpec struct { // paused if set to true all actions on the underlying managed objects are not // going to be performed, except for delete actions. // +optional - Paused bool `json:"paused,omitempty"` + Paused bool `json:"paused,omitempty"` // nolint:kubeapilinter // nodeSelector defines which Nodes the Pods are scheduled on. // +optional + //nolint:kubeapilinter // standard Kubernetes node selector format NodeSelector map[string]string `json:"nodeSelector,omitempty"` // resources defines the resource requests and limits of the Pods. // +optional @@ -228,7 +229,7 @@ type AlertmanagerSpec struct { DNSConfig *PodDNSConfig `json:"dnsConfig,omitempty"` // enableServiceLinks defines whether information about services should be injected into pod's environment variables // +optional - EnableServiceLinks *bool `json:"enableServiceLinks,omitempty"` + EnableServiceLinks *bool `json:"enableServiceLinks,omitempty"` // nolint:kubeapilinter // serviceName defines the service name used by the underlying StatefulSet(s) as the governing service. // If defined, the Service must be created before the Alertmanager resource in the same namespace and it must define a selector that matches the pod labels. // If empty, the operator will create and manage a headless service named `alertmanager-operated` for Alertmanager resources. @@ -245,7 +246,30 @@ type AlertmanagerSpec struct { // does not bind against the Pod IP. Note this is only for the Alertmanager // UI, not the gossip communication. // +optional - ListenLocal bool `json:"listenLocal,omitempty"` + ListenLocal bool `json:"listenLocal,omitempty"` // nolint:kubeapilinter + + // podManagementPolicy defines the policy for creating/deleting pods when + // scaling up and down. + // + // Unlike the default StatefulSet behavior, the default policy is + // `Parallel` to avoid manual intervention in case a pod gets stuck during + // a rollout. + // + // Note that updating this value implies the recreation of the StatefulSet + // which incurs a service outage. + // + // +optional + PodManagementPolicy *PodManagementPolicyType `json:"podManagementPolicy,omitempty"` + + // updateStrategy indicates the strategy that will be employed to update + // Pods in the StatefulSet when a revision is made to statefulset's Pod + // Template. + // + // The default strategy is RollingUpdate. + // + // +optional + UpdateStrategy *StatefulSetUpdateStrategy `json:"updateStrategy,omitempty"` + // containers allows injecting additional containers. This is meant to // allow adding an authentication proxy to an Alertmanager pod. // Containers described here modify an operator generated container if they @@ -299,7 +323,7 @@ type AlertmanagerSpec struct { // forceEnableClusterMode ensures Alertmanager does not deactivate the cluster mode when running with a single replica. // Use case is e.g. spanning an Alertmanager cluster across Kubernetes clusters with a single replica in each. // +optional - ForceEnableClusterMode bool `json:"forceEnableClusterMode,omitempty"` + ForceEnableClusterMode bool `json:"forceEnableClusterMode,omitempty"` // nolint:kubeapilinter // alertmanagerConfigSelector defines the selector to be used for to merge and configure Alertmanager with. // +optional AlertmanagerConfigSelector *metav1.LabelSelector `json:"alertmanagerConfigSelector,omitempty"` @@ -313,11 +337,19 @@ type AlertmanagerSpec struct { // +optional AlertmanagerConfigMatcherStrategy AlertmanagerConfigMatcherStrategy `json:"alertmanagerConfigMatcherStrategy,omitempty"` - // minReadySeconds defines the minimum number of seconds for which a newly created pod should be ready - // without any of its container crashing for it to be considered available. + // minReadySeconds defines the minimum number of seconds for which a newly + // created pod should be ready without any of its container crashing for it + // to be considered available. // // If unset, pods will be considered available as soon as they are ready. // + // When the Alertmanager version is greater than or equal to v0.30.0, the + // duration is also used to delay the first flush of the aggregation + // groups. This delay helps ensuring that all alerts have been resent by + // the Prometheus instances to Alertmanager after a roll-out. It is + // possible to override this behavior passing a custom value via + // `.spec.additionalArgs`. + // // +kubebuilder:validation:Minimum:=0 // +optional MinReadySeconds *int32 `json:"minReadySeconds,omitempty"` @@ -332,6 +364,7 @@ type AlertmanagerSpec struct { // limits defines the limits command line flags when starting Alertmanager. // +optional Limits *AlertmanagerLimitsSpec `json:"limits,omitempty"` + // clusterTLS defines the mutual TLS configuration for the Alertmanager cluster's gossip protocol. // // It requires Alertmanager >= 0.24.0. @@ -349,7 +382,7 @@ type AlertmanagerSpec struct { // automountServiceAccountToken defines whether a service account token should be automatically mounted in the pod. // If the service account has `automountServiceAccountToken: true`, set the field to `false` to opt out of automounting API credentials. // +optional - AutomountServiceAccountToken *bool `json:"automountServiceAccountToken,omitempty"` + AutomountServiceAccountToken *bool `json:"automountServiceAccountToken,omitempty"` // nolint:kubeapilinter // enableFeatures defines the Alertmanager's feature flags. By default, no features are enabled. // Enabling features which are disabled by default is entirely outside the // scope of what the maintainers will support and by doing so, you accept @@ -385,7 +418,7 @@ type AlertmanagerSpec struct { // Starting Kubernetes 1.33, the feature is enabled by default. // // +optional - HostUsers *bool `json:"hostUsers,omitempty"` + HostUsers *bool `json:"hostUsers,omitempty"` // nolint:kubeapilinter } type AlertmanagerConfigMatcherStrategy struct { @@ -452,7 +485,7 @@ type AlertmanagerGlobalConfig struct { // httpConfig defines the default HTTP configuration. // +optional - HTTPConfig *HTTPConfig `json:"httpConfig,omitempty"` + HTTPConfigWithProxy *HTTPConfigWithProxy `json:"httpConfig,omitempty"` // slackApiUrl defines the default Slack API URL. // +optional @@ -486,7 +519,7 @@ type AlertmanagerGlobalConfig struct { // +optional RocketChatConfig *GlobalRocketChatConfig `json:"rocketChat,omitempty"` - // webex defines the default configuration for Jira. + // webex defines the default configuration for Webex. // +optional WebexConfig *GlobalWebexConfig `json:"webex,omitempty"` @@ -503,7 +536,7 @@ type AlertmanagerStatus struct { // paused defines whether any actions on the underlying managed objects are // being performed. Only delete actions will be performed. // +optional - Paused bool `json:"paused"` + Paused bool `json:"paused"` // nolint:kubeapilinter // replicas defines the total number of non-terminated pods targeted by this Alertmanager // object (their labels match the selector). // +optional @@ -607,7 +640,7 @@ type GlobalSMTPConfig struct { // requireTLS defines the default SMTP TLS requirement. // Note that Go does not support unencrypted connections to remote SMTP endpoints. // +optional - RequireTLS *bool `json:"requireTLS,omitempty"` + RequireTLS *bool `json:"requireTLS,omitempty"` // nolint:kubeapilinter // tlsConfig defines the default TLS configuration for SMTP receivers // +optional diff --git a/vendor/github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1/http_config.go b/vendor/github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1/http_config.go index 3d7a0b82300..1590d23e097 100644 --- a/vendor/github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1/http_config.go +++ b/vendor/github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1/http_config.go @@ -21,8 +21,49 @@ import ( v1 "k8s.io/api/core/v1" ) -// HTTPConfig defines the configuration for the HTTP client. -type HTTPConfig struct { +// HTTPConfigWithProxyAndTLSFiles defines the configuration for the HTTP client +// with proxy configuration and TLS configuration. It is used for +// ServiceMonitor endpoints. +type HTTPConfigWithProxyAndTLSFiles struct { + HTTPConfigWithTLSFiles `json:",inline"` + ProxyConfig `json:",inline"` +} + +// Validate semantically validates the given TLSConfig. +func (c *HTTPConfigWithProxyAndTLSFiles) Validate() error { + if err := c.HTTPConfigWithTLSFiles.Validate(); err != nil { + return err + } + + if err := c.ProxyConfig.Validate(); err != nil { + return err + } + + return nil +} + +// HTTPConfigWithProxy defines the configuration for the HTTP client with proxy +// configuration. It is used for PodMonitor endpoints and Probes. +type HTTPConfigWithProxy struct { + HTTPConfig `json:",inline"` + ProxyConfig `json:",inline"` +} + +// Validate semantically validates the given HTTPConfigWithProxy. +func (hc *HTTPConfigWithProxy) Validate() error { + if hc == nil { + return nil + } + + if err := hc.HTTPConfig.Validate(); err != nil { + return err + } + + return hc.ProxyConfig.Validate() +} + +// HTTPConfigWithoutTLS defines the configuration for the HTTP client. +type HTTPConfigWithoutTLS struct { // authorization configures the Authorization header credentials used by // the client. // @@ -60,27 +101,20 @@ type HTTPConfig struct { // Deprecated: use `authorization` instead. BearerTokenSecret *v1.SecretKeySelector `json:"bearerTokenSecret,omitempty"` - // tlsConfig defines the TLS configuration used by the client. - // - // +optional - TLSConfig *SafeTLSConfig `json:"tlsConfig,omitempty"` - - ProxyConfig `json:",inline"` - // followRedirects defines whether the client should follow HTTP 3xx // redirects. // // +optional - FollowRedirects *bool `json:"followRedirects,omitempty"` + FollowRedirects *bool `json:"followRedirects,omitempty"` // nolint:kubeapilinter // enableHttp2 can be used to disable HTTP2. // // +optional - EnableHTTP2 *bool `json:"enableHttp2,omitempty"` + EnableHTTP2 *bool `json:"enableHttp2,omitempty"` // nolint:kubeapilinter } -// Validate semantically validates the given HTTPConfig. -func (hc *HTTPConfig) Validate() error { +// Validate semantically validates the given HTTPConfigWithoutTLS. +func (hc *HTTPConfigWithoutTLS) Validate() error { if hc == nil { return nil } @@ -118,13 +152,56 @@ func (hc *HTTPConfig) Validate() error { return fmt.Errorf("oauth2: %w", err) } + return nil +} + +// HTTPConfig defines the HTTP configuration + TLS configuration (only from +// secret/configmap references). +type HTTPConfig struct { + HTTPConfigWithoutTLS `json:",inline"` + + // tlsConfig defines the TLS configuration used by the client. + // + // +optional + TLSConfig *SafeTLSConfig `json:"tlsConfig,omitempty"` +} + +// Validate semantically validates the given HTTPConfig. +func (hc *HTTPConfig) Validate() error { + if hc == nil { + return nil + } + + if err := hc.HTTPConfigWithoutTLS.Validate(); err != nil { + return err + } if err := hc.TLSConfig.Validate(); err != nil { return fmt.Errorf("tlsConfig: %w", err) } - if err := hc.ProxyConfig.Validate(); err != nil { + return nil +} + +// HTTPConfigWithTLSFiles defines HTTP configuration + TLS configuration +// (from secret/configmap references as well as files). +type HTTPConfigWithTLSFiles struct { + HTTPConfigWithoutTLS `json:",inline"` + + // tlsConfig defines TLS configuration used by the client. + // + // +optional + TLSConfig *TLSConfig `json:"tlsConfig,omitempty"` +} + +// Validate semantically validates the given HTTPConfigWithTLSFiles. +func (c *HTTPConfigWithTLSFiles) Validate() error { + if err := c.HTTPConfigWithoutTLS.Validate(); err != nil { return err } + if err := c.TLSConfig.Validate(); err != nil { + return fmt.Errorf("tlsConfig: %w", err) + } + return nil } diff --git a/vendor/github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1/podmonitor_types.go b/vendor/github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1/podmonitor_types.go index 8f439fd11cb..d7da9bdcaa2 100644 --- a/vendor/github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1/podmonitor_types.go +++ b/vendor/github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1/podmonitor_types.go @@ -267,6 +267,7 @@ type PodMetricsEndpoint struct { // params define optional HTTP URL parameters. // +optional + //nolint:kubeapilinter Params map[string][]string `json:"params,omitempty"` // interval at which Prometheus scrapes the metrics from the target. @@ -286,13 +287,13 @@ type PodMetricsEndpoint struct { // honorLabels when true preserves the metric's labels when they collide // with the target's labels. // +optional - HonorLabels bool `json:"honorLabels,omitempty"` + HonorLabels bool `json:"honorLabels,omitempty"` // nolint:kubeapilinter // honorTimestamps defines whether Prometheus preserves the timestamps // when exposed by the target. // // +optional - HonorTimestamps *bool `json:"honorTimestamps,omitempty"` + HonorTimestamps *bool `json:"honorTimestamps,omitempty"` // nolint:kubeapilinter // trackTimestampsStaleness defines whether Prometheus tracks staleness of // the metrics that have an explicit timestamp present in scraped data. @@ -301,7 +302,7 @@ type PodMetricsEndpoint struct { // It requires Prometheus >= v2.48.0. // // +optional - TrackTimestampsStaleness *bool `json:"trackTimestampsStaleness,omitempty"` + TrackTimestampsStaleness *bool `json:"trackTimestampsStaleness,omitempty"` // nolint:kubeapilinter // metricRelabelings defines the relabeling rules to apply to the // samples before ingestion. @@ -329,7 +330,7 @@ type PodMetricsEndpoint struct { // More info: https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle/#pod-phase // // +optional - FilterRunning *bool `json:"filterRunning,omitempty"` + FilterRunning *bool `json:"filterRunning,omitempty"` // nolint:kubeapilinter - HTTPConfig `json:",inline"` + HTTPConfigWithProxy `json:",inline"` } diff --git a/vendor/github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1/probe_types.go b/vendor/github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1/probe_types.go index 34218f4ca58..dc7ad44ee99 100644 --- a/vendor/github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1/probe_types.go +++ b/vendor/github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1/probe_types.go @@ -17,7 +17,6 @@ package v1 import ( "errors" - v1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" ) @@ -75,10 +74,12 @@ type ProbeSpec struct { // jobName assigned to scraped metrics by default. // +optional JobName string `json:"jobName,omitempty"` + // prober defines the specification for the prober to use for probing targets. // The prober.URL parameter is required. Targets cannot be probed if left empty. // +optional ProberSpec ProberSpec `json:"prober,omitempty"` + // module to use for probing specifying how to probe the target. // Example module configuring in the blackbox exporter: // https://github.com/prometheus/blackbox_exporter/blob/master/example.yml @@ -96,21 +97,7 @@ type ProbeSpec struct { // The value cannot be greater than the scrape interval otherwise the operator will reject the resource. // +optional ScrapeTimeout Duration `json:"scrapeTimeout,omitempty"` - // tlsConfig defines the TLS configuration to use when scraping the endpoint. - // +optional - TLSConfig *SafeTLSConfig `json:"tlsConfig,omitempty"` - // bearerTokenSecret defines the secret to mount to read bearer token for scraping targets. The secret - // needs to be in the same namespace as the probe and accessible by - // the Prometheus Operator. - // +optional - BearerTokenSecret v1.SecretKeySelector `json:"bearerTokenSecret,omitempty"` - // basicAuth allow an endpoint to authenticate over basic authentication. - // More info: https://prometheus.io/docs/operating/configuration/#endpoint - // +optional - BasicAuth *BasicAuth `json:"basicAuth,omitempty"` - // oauth2 for the URL. Only valid in Prometheus versions 2.27.0 and newer. - // +optional - OAuth2 *OAuth2 `json:"oauth2,omitempty"` + // metricRelabelings defines the RelabelConfig to apply to samples before ingestion. // +optional MetricRelabelConfigs []RelabelConfig `json:"metricRelabelings,omitempty"` @@ -133,19 +120,23 @@ type ProbeSpec struct { // +listType=set // +optional ScrapeProtocols []ScrapeProtocol `json:"scrapeProtocols,omitempty"` + // fallbackScrapeProtocol defines the protocol to use if a scrape returns blank, unparseable, or otherwise invalid Content-Type. // // It requires Prometheus >= v3.0.0. // +optional FallbackScrapeProtocol *ScrapeProtocol `json:"fallbackScrapeProtocol,omitempty"` + // labelLimit defines the per-scrape limit on number of labels that will be accepted for a sample. // Only valid in Prometheus versions 2.27.0 and newer. // +optional LabelLimit *uint64 `json:"labelLimit,omitempty"` + // labelNameLengthLimit defines the per-scrape limit on length of labels name that will be accepted for a sample. // Only valid in Prometheus versions 2.27.0 and newer. // +optional LabelNameLengthLimit *uint64 `json:"labelNameLengthLimit,omitempty"` + // labelValueLengthLimit defines the per-scrape limit on length of labels value that will be accepted for a sample. // Only valid in Prometheus versions 2.27.0 and newer. // +optional @@ -153,6 +144,7 @@ type ProbeSpec struct { // +optional NativeHistogramConfig `json:",inline"` + // keepDroppedTargets defines the per-scrape limit on the number of targets dropped by relabeling // that will be kept in memory. 0 means no limit. // @@ -174,6 +166,8 @@ type ProbeSpec struct { // +listType=map // +listMapKey=name Params []ProbeParam `json:"params,omitempty"` + + HTTPConfig `json:",inline"` } // ProbeParam defines specification of extra parameters for a Probe. @@ -225,6 +219,7 @@ type ProbeTargetStaticConfig struct { Targets []string `json:"static,omitempty"` // labels defines all labels assigned to all metrics scraped from the targets. // +optional + //nolint:kubeapilinter Labels map[string]string `json:"labels,omitempty"` // relabelingConfigs defines relabelings to be apply to the label set of the targets before it gets // scraped. diff --git a/vendor/github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1/prometheus_types.go b/vendor/github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1/prometheus_types.go index 2122906ac9f..812f6efbc80 100644 --- a/vendor/github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1/prometheus_types.go +++ b/vendor/github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1/prometheus_types.go @@ -21,7 +21,6 @@ import ( appsv1 "k8s.io/api/apps/v1" v1 "k8s.io/api/core/v1" - "k8s.io/apimachinery/pkg/api/resource" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime/schema" @@ -222,7 +221,7 @@ type CommonPrometheusFields struct { // paused defines when a Prometheus deployment is paused, no actions except for deletion // will be performed on the underlying objects. // +optional - Paused bool `json:"paused,omitempty"` + Paused bool `json:"paused,omitempty"` // nolint:kubeapilinter // image defines the container image name for Prometheus. If specified, it takes precedence // over the `spec.baseImage`, `spec.tag` and `spec.sha` fields. @@ -337,6 +336,7 @@ type CommonPrometheusFields struct { // Labels defined by `spec.replicaExternalLabelName` and // `spec.prometheusExternalLabelName` take precedence over this list. // +optional + //nolint:kubeapilinter ExternalLabels map[string]string `json:"externalLabels,omitempty"` // enableRemoteWriteReceiver defines the Prometheus to be used as a receiver for the Prometheus remote @@ -350,7 +350,7 @@ type CommonPrometheusFields struct { // // It requires Prometheus >= v2.33.0. // +optional - EnableRemoteWriteReceiver bool `json:"enableRemoteWriteReceiver,omitempty"` + EnableRemoteWriteReceiver bool `json:"enableRemoteWriteReceiver,omitempty"` // nolint:kubeapilinter // enableOTLPReceiver defines the Prometheus to be used as a receiver for the OTLP Metrics protocol. // @@ -358,7 +358,7 @@ type CommonPrometheusFields struct { // // It requires Prometheus >= v2.47.0. // +optional - EnableOTLPReceiver *bool `json:"enableOTLPReceiver,omitempty"` + EnableOTLPReceiver *bool `json:"enableOTLPReceiver,omitempty"` // nolint:kubeapilinter // remoteWriteReceiverMessageVersions list of the protobuf message versions to accept when receiving the // remote writes. @@ -430,6 +430,7 @@ type CommonPrometheusFields struct { // nodeSelector defines on which Nodes the Pods are scheduled. // +optional + //nolint:kubeapilinter NodeSelector map[string]string `json:"nodeSelector,omitempty"` // serviceAccountName is the name of the ServiceAccount to use to run the @@ -443,7 +444,7 @@ type CommonPrometheusFields struct { // **Warning:** be aware that by default, Prometheus requires the service account token for Kubernetes service discovery. // It is possible to use strategic merge patch to project the service account token into the 'prometheus' container. // +optional - AutomountServiceAccountToken *bool `json:"automountServiceAccountToken,omitempty"` + AutomountServiceAccountToken *bool `json:"automountServiceAccountToken,omitempty"` // nolint:kubeapilinter // secrets defines a list of Secrets in the same namespace as the Prometheus // object, which shall be mounted into the Prometheus Pods. @@ -497,11 +498,33 @@ type CommonPrometheusFields struct { // instead of the Pod IP's address. // // +optional - ListenLocal bool `json:"listenLocal,omitempty"` + ListenLocal bool `json:"listenLocal,omitempty"` // nolint:kubeapilinter + + // podManagementPolicy defines the policy for creating/deleting pods when + // scaling up and down. + // + // Unlike the default StatefulSet behavior, the default policy is + // `Parallel` to avoid manual intervention in case a pod gets stuck during + // a rollout. + // + // Note that updating this value implies the recreation of the StatefulSet + // which incurs a service outage. + // + // +optional + PodManagementPolicy *PodManagementPolicyType `json:"podManagementPolicy,omitempty"` + + // updateStrategy indicates the strategy that will be employed to update + // Pods in the StatefulSet when a revision is made to statefulset's Pod + // Template. + // + // The default strategy is RollingUpdate. + // + // +optional + UpdateStrategy *StatefulSetUpdateStrategy `json:"updateStrategy,omitempty"` // enableServiceLinks defines whether information about services should be injected into pod's environment variables // +optional - EnableServiceLinks *bool `json:"enableServiceLinks,omitempty"` + EnableServiceLinks *bool `json:"enableServiceLinks,omitempty"` // nolint:kubeapilinter // containers allows injecting additional containers or modifying operator // generated containers. This can be used to allow adding an authentication @@ -588,19 +611,19 @@ type CommonPrometheusFields struct { // In practice,`OverrideHonorLabels:true` enforces `honorLabels:false` // for all ServiceMonitor, PodMonitor and ScrapeConfig objects. // +optional - OverrideHonorLabels bool `json:"overrideHonorLabels,omitempty"` + OverrideHonorLabels bool `json:"overrideHonorLabels,omitempty"` // nolint:kubeapilinter // overrideHonorTimestamps when true, Prometheus ignores the timestamps for all the targets created // from service and pod monitors. // Otherwise the HonorTimestamps field of the service or pod monitor applies. // +optional - OverrideHonorTimestamps bool `json:"overrideHonorTimestamps,omitempty"` + OverrideHonorTimestamps bool `json:"overrideHonorTimestamps,omitempty"` // nolint:kubeapilinter // ignoreNamespaceSelectors when true, `spec.namespaceSelector` from all PodMonitor, ServiceMonitor // and Probe objects will be ignored. They will only discover targets // within the namespace of the PodMonitor, ServiceMonitor and Probe // object. // +optional - IgnoreNamespaceSelectors bool `json:"ignoreNamespaceSelectors,omitempty"` + IgnoreNamespaceSelectors bool `json:"ignoreNamespaceSelectors,omitempty"` // nolint:kubeapilinter // enforcedNamespaceLabel when not empty, a label will be added to: // @@ -755,7 +778,13 @@ type CommonPrometheusFields struct { // It requires Prometheus >= v3.4.0. // // +optional - ConvertClassicHistogramsToNHCB *bool `json:"convertClassicHistogramsToNHCB,omitempty"` + ConvertClassicHistogramsToNHCB *bool `json:"convertClassicHistogramsToNHCB,omitempty"` // nolint:kubeapilinter + + // scrapeNativeHistograms defines whether to enable scraping of native histograms. + // It requires Prometheus >= v3.8.0. + // + // +optional + ScrapeNativeHistograms *bool `json:"scrapeNativeHistograms,omitempty"` // nolint:kubeapilinter // scrapeClassicHistograms defines whether to scrape a classic histogram that is also exposed as a native histogram. // @@ -764,7 +793,7 @@ type CommonPrometheusFields struct { // It requires Prometheus >= v3.5.0. // // +optional - ScrapeClassicHistograms *bool `json:"scrapeClassicHistograms,omitempty"` + ScrapeClassicHistograms *bool `json:"scrapeClassicHistograms,omitempty"` // nolint:kubeapilinter // minReadySeconds defines the minimum number of seconds for which a newly created Pod should be ready // without any of its container crashing for it to be considered available. @@ -804,7 +833,7 @@ type CommonPrometheusFields struct { // Requires Prometheus v2.11.0 and above. // // +optional - WALCompression *bool `json:"walCompression,omitempty"` + WALCompression *bool `json:"walCompression,omitempty"` // nolint:kubeapilinter // excludedFromEnforcement defines the list of references to PodMonitor, ServiceMonitor, Probe and PrometheusRule objects // to be excluded from enforcing a namespace label of origin. @@ -824,7 +853,7 @@ type CommonPrometheusFields struct { // to a different value). // // +optional - HostNetwork bool `json:"hostNetwork,omitempty"` + HostNetwork bool `json:"hostNetwork,omitempty"` // nolint:kubeapilinter // podTargetLabels are appended to the `spec.podTargetLabels` field of all // PodMonitor and ServiceMonitor objects. @@ -838,7 +867,7 @@ type CommonPrometheusFields struct { // in a breaking way. // // +optional - TracingConfig *PrometheusTracingConfig `json:"tracingConfig,omitempty"` + TracingConfig *TracingConfig `json:"tracingConfig,omitempty"` // bodySizeLimit defines per-scrape on response body size. // Only valid in Prometheus versions 2.45.0 and newer. // @@ -981,7 +1010,7 @@ type CommonPrometheusFields struct { // Starting Kubernetes 1.33, the feature is enabled by default. // // +optional - HostUsers *bool `json:"hostUsers,omitempty"` + HostUsers *bool `json:"hostUsers,omitempty"` // nolint:kubeapilinter } // Specifies the validation scheme for metric and label names. @@ -1162,7 +1191,7 @@ type PrometheusSpec struct { // When `spec.thanos.objectStorageConfig` or `spec.objectStorageConfigFile` are defined, the operator automatically // disables block compaction to avoid race conditions during block uploads (as the Thanos documentation recommends). // +optional - DisableCompaction bool `json:"disableCompaction,omitempty"` + DisableCompaction bool `json:"disableCompaction,omitempty"` // nolint:kubeapilinter // rules defines the configuration of the Prometheus rules' engine. // +optional @@ -1252,7 +1281,7 @@ type PrometheusSpec struct { // // Deprecated: this flag has no effect for Prometheus >= 2.39.0 where overlapping blocks are enabled by default. // +optional - AllowOverlappingBlocks bool `json:"allowOverlappingBlocks,omitempty"` + AllowOverlappingBlocks bool `json:"allowOverlappingBlocks,omitempty"` // nolint:kubeapilinter // exemplars related settings that are runtime reloadable. // It requires to enable the `exemplar-storage` feature flag to be effective. @@ -1280,7 +1309,7 @@ type PrometheusSpec struct { // For more information: // https://prometheus.io/docs/prometheus/latest/querying/api/#tsdb-admin-apis // +optional - EnableAdminAPI bool `json:"enableAdminAPI,omitempty"` + EnableAdminAPI bool `json:"enableAdminAPI,omitempty"` // nolint:kubeapilinter } type WhenScaledRetentionType string @@ -1311,43 +1340,6 @@ type ShardRetentionPolicy struct { Retain *RetainConfig `json:"retain,omitempty"` } -type PrometheusTracingConfig struct { - // clientType defines the client used to export the traces. Supported values are `http` or `grpc`. - // +kubebuilder:validation:Enum=http;grpc - // +optional - ClientType *string `json:"clientType"` - - // endpoint to send the traces to. Should be provided in format :. - // +kubebuilder:validation:MinLength:=1 - // +required - Endpoint string `json:"endpoint"` - - // samplingFraction defines the probability a given trace will be sampled. Must be a float from 0 through 1. - // +optional - SamplingFraction *resource.Quantity `json:"samplingFraction"` - - // insecure if disabled, the client will use a secure connection. - // +optional - Insecure *bool `json:"insecure"` - - // headers defines the key-value pairs to be used as headers associated with gRPC or HTTP requests. - // +optional - Headers map[string]string `json:"headers"` - - // compression key for supported compression types. The only supported value is `gzip`. - // +kubebuilder:validation:Enum=gzip - // +optional - Compression *string `json:"compression"` - - // timeout defines the maximum time the exporter will wait for each batch export. - // +optional - Timeout *Duration `json:"timeout"` - - // tlsConfig to use when sending traces. - // +optional - TLSConfig *TLSConfig `json:"tlsConfig"` -} - // PrometheusStatus is the most recent observed status of the Prometheus cluster. // More info: // https://github.com/kubernetes/community/blob/master/contributors/devel/sig-architecture/api-conventions.md#spec-and-status @@ -1356,7 +1348,7 @@ type PrometheusStatus struct { // paused defines whether any actions on the underlying managed objects are // being performed. Only delete actions will be performed. // +optional - Paused bool `json:"paused"` + Paused bool `json:"paused"` // nolint:kubeapilinter // replicas defines the total number of non-terminated pods targeted by this Prometheus deployment // (their labels match the selector). // +optional @@ -1410,7 +1402,7 @@ type AlertingSpec struct { type StorageSpec struct { // disableMountSubPath deprecated: subPath usage will be removed in a future release. // +optional - DisableMountSubPath bool `json:"disableMountSubPath,omitempty"` + DisableMountSubPath bool `json:"disableMountSubPath,omitempty"` // nolint:kubeapilinter // emptyDir to be used by the StatefulSet. // If specified, it takes precedence over `ephemeral` and `volumeClaimTemplate`. // More info: https://kubernetes.io/docs/concepts/storage/volumes/#emptydir @@ -1522,21 +1514,21 @@ type ThanosSpec struct { // listenLocal is deprecated: use `grpcListenLocal` and `httpListenLocal` instead. // +optional - ListenLocal bool `json:"listenLocal,omitempty"` + ListenLocal bool `json:"listenLocal,omitempty"` // nolint:kubeapilinter // grpcListenLocal defines when true, the Thanos sidecar listens on the loopback interface instead // of the Pod IP's address for the gRPC endpoints. // // It has no effect if `listenLocal` is true. // +optional - GRPCListenLocal bool `json:"grpcListenLocal,omitempty"` + GRPCListenLocal bool `json:"grpcListenLocal,omitempty"` // nolint:kubeapilinter // httpListenLocal when true, the Thanos sidecar listens on the loopback interface instead // of the Pod IP's address for the HTTP endpoints. // // It has no effect if `listenLocal` is true. // +optional - HTTPListenLocal bool `json:"httpListenLocal,omitempty"` + HTTPListenLocal bool `json:"httpListenLocal,omitempty"` // nolint:kubeapilinter // tracingConfig defines the tracing configuration for the Thanos sidecar. // @@ -1663,7 +1655,7 @@ type RemoteWriteSpec struct { // It requires Prometheus >= v2.27.0 or Thanos >= v0.24.0. // // +optional - SendExemplars *bool `json:"sendExemplars,omitempty"` + SendExemplars *bool `json:"sendExemplars,omitempty"` // nolint:kubeapilinter // sendNativeHistograms enables sending of native histograms, also known as sparse histograms // over remote write. @@ -1671,7 +1663,7 @@ type RemoteWriteSpec struct { // It requires Prometheus >= v2.40.0 or Thanos >= v0.30.0. // // +optional - SendNativeHistograms *bool `json:"sendNativeHistograms,omitempty"` + SendNativeHistograms *bool `json:"sendNativeHistograms,omitempty"` // nolint:kubeapilinter // remoteTimeout defines the timeout for requests to the remote write endpoint. // +optional @@ -1683,6 +1675,7 @@ type RemoteWriteSpec struct { // It requires Prometheus >= v2.25.0 or Thanos >= v0.24.0. // // +optional + //nolint:kubeapilinter Headers map[string]string `json:"headers,omitempty"` // writeRelabelConfigs defines the list of remote write relabel configurations. @@ -1757,7 +1750,7 @@ type RemoteWriteSpec struct { // It requires Prometheus >= v2.26.0 or Thanos >= v0.24.0. // // +optional - FollowRedirects *bool `json:"followRedirects,omitempty"` + FollowRedirects *bool `json:"followRedirects,omitempty"` // nolint:kubeapilinter // queueConfig allows tuning of the remote write queue parameters. // +optional @@ -1773,7 +1766,7 @@ type RemoteWriteSpec struct { // enableHTTP2 defines whether to enable HTTP2. // +optional - EnableHttp2 *bool `json:"enableHTTP2,omitempty"` + EnableHttp2 *bool `json:"enableHTTP2,omitempty"` // nolint:kubeapilinter // roundRobinDNS controls the DNS resolution behavior for remote-write connections. // When enabled: @@ -1791,7 +1784,7 @@ type RemoteWriteSpec struct { // It requires Prometheus >= v3.1.0 or Thanos >= v0.38.0. // // +optional - RoundRobinDNS *bool `json:"roundRobinDNS,omitempty"` + RoundRobinDNS *bool `json:"roundRobinDNS,omitempty"` // nolint:kubeapilinter } // +kubebuilder:validation:Enum=V1.0;V2.0 @@ -1838,7 +1831,7 @@ type QueueConfig struct { // This is an *experimental feature*, it may change in any upcoming release // in a breaking way. // +optional - RetryOnRateLimit bool `json:"retryOnRateLimit,omitempty"` + RetryOnRateLimit bool `json:"retryOnRateLimit,omitempty"` // nolint:kubeapilinter // sampleAgeLimit drops samples older than the limit. // It requires Prometheus >= v2.50.0 or Thanos >= v0.32.0. // @@ -1871,7 +1864,7 @@ type Sigv4 struct { // It requires Prometheus >= v2.54.0. // // +optional - UseFIPSSTSEndpoint *bool `json:"useFIPSSTSEndpoint,omitempty"` + UseFIPSSTSEndpoint *bool `json:"useFIPSSTSEndpoint,omitempty"` // nolint:kubeapilinter } // AzureAD defines the configuration for remote write's azuread parameters. @@ -1882,11 +1875,11 @@ type AzureAD struct { // +optional Cloud *string `json:"cloud,omitempty"` // managedIdentity defines the Azure User-assigned Managed identity. - // Cannot be set at the same time as `oauth` or `sdk`. + // Cannot be set at the same time as `oauth`, `sdk` or `workloadIdentity`. // +optional ManagedIdentity *ManagedIdentity `json:"managedIdentity,omitempty"` // oauth defines the oauth config that is being used to authenticate. - // Cannot be set at the same time as `managedIdentity` or `sdk`. + // Cannot be set at the same time as `managedIdentity`, `sdk` or `workloadIdentity`. // // It requires Prometheus >= v2.48.0 or Thanos >= v0.31.0. // @@ -1894,11 +1887,22 @@ type AzureAD struct { OAuth *AzureOAuth `json:"oauth,omitempty"` // sdk defines the Azure SDK config that is being used to authenticate. // See https://learn.microsoft.com/en-us/azure/developer/go/azure-sdk-authentication - // Cannot be set at the same time as `oauth` or `managedIdentity`. + // Cannot be set at the same time as `oauth`, `managedIdentity` or `workloadIdentity`. // // It requires Prometheus >= v2.52.0 or Thanos >= v0.36.0. // +optional SDK *AzureSDK `json:"sdk,omitempty"` + // workloadIdentity defines the Azure Workload Identity authentication. + // Cannot be set at the same time as `oauth`, `managedIdentity`, or `sdk`. + // + // It requires Prometheus >= 3.7.0. Currently not supported by Thanos. + // +optional + WorkloadIdentity *AzureWorkloadIdentity `json:"workloadIdentity,omitempty"` + // scope is the custom OAuth 2.0 scope to request when acquiring tokens. + // It requires Prometheus >= 3.9.0. Currently not supported by Thanos. + // +kubebuilder:validation:Pattern=`^[\w\s:/.\\-]+$` + // +optional + Scope *string `json:"scope,omitempty"` } // AzureOAuth defines the Azure OAuth settings. @@ -1938,6 +1942,19 @@ type AzureSDK struct { TenantID *string `json:"tenantId,omitempty"` } +// AzureWorkloadIdentity defines the Azure Workload Identity authentication configuration. +type AzureWorkloadIdentity struct { + // clientId is the clientID of the Azure Active Directory application. + // +kubebuilder:validation:MinLength=1 + // +required + ClientID string `json:"clientId"` + + // tenantId is the tenant ID of the Azure Active Directory application. + // +kubebuilder:validation:MinLength=1 + // +required + TenantID string `json:"tenantId"` +} + // RemoteReadSpec defines the configuration for Prometheus to read back samples // from a remote endpoint. // +k8s:openapi-gen=true @@ -1958,6 +1975,7 @@ type RemoteReadSpec struct { // requiredMatchers defines an optional list of equality matchers which have to be present // in a selector to query the remote read endpoint. // +optional + //nolint:kubeapilinter RequiredMatchers map[string]string `json:"requiredMatchers,omitempty"` // remoteTimeout defines the timeout for requests to the remote read endpoint. @@ -1968,12 +1986,13 @@ type RemoteReadSpec struct { // Be aware that headers that are set by Prometheus itself can't be overwritten. // Only valid in Prometheus versions 2.26.0 and newer. // +optional + //nolint:kubeapilinter Headers map[string]string `json:"headers,omitempty"` // readRecent defines whether reads should be made for queries for time ranges that // the local storage should have complete data for. // +optional - ReadRecent bool `json:"readRecent,omitempty"` + ReadRecent bool `json:"readRecent,omitempty"` // nolint:kubeapilinter // oauth2 configuration for the URL. // @@ -2023,14 +2042,14 @@ type RemoteReadSpec struct { // It requires Prometheus >= v2.26.0. // // +optional - FollowRedirects *bool `json:"followRedirects,omitempty"` + FollowRedirects *bool `json:"followRedirects,omitempty"` // nolint:kubeapilinter // filterExternalLabels defines whether to use the external labels as selectors for the remote read endpoint. // // It requires Prometheus >= v2.34.0. // // +optional - FilterExternalLabels *bool `json:"filterExternalLabels,omitempty"` + FilterExternalLabels *bool `json:"filterExternalLabels,omitempty"` // nolint:kubeapilinter } // RelabelConfig allows dynamic rewriting of the label set for targets, alerts, @@ -2240,7 +2259,7 @@ type AlertmanagerEndpoints struct { // enableHttp2 defines whether to enable HTTP2. // // +optional - EnableHttp2 *bool `json:"enableHttp2,omitempty"` + EnableHttp2 *bool `json:"enableHttp2,omitempty"` // nolint:kubeapilinter // relabelings defines the relabel configuration applied to the discovered Alertmanagers. // @@ -2290,7 +2309,7 @@ type MetadataConfig struct { // send defines whether metric metadata is sent to the remote storage or not. // // +optional - Send bool `json:"send,omitempty"` + Send bool `json:"send,omitempty"` // nolint:kubeapilinter // sendInterval defines how frequently metric metadata is sent to the remote storage. // @@ -2429,7 +2448,7 @@ type ScrapeClass struct { // Only one scrape class can be set as the default. // // +optional - Default *bool `json:"default,omitempty"` + Default *bool `json:"default,omitempty"` // nolint:kubeapilinter // fallbackScrapeProtocol defines the protocol to use if a scrape returns blank, unparseable, or otherwise invalid Content-Type. // It will only apply if the scrape resource doesn't specify any FallbackScrapeProtocol @@ -2510,7 +2529,7 @@ type OTLPConfig struct { // Cannot be true when `promoteResourceAttributes` is defined. // It requires Prometheus >= v3.5.0. // +optional - PromoteAllResourceAttributes *bool `json:"promoteAllResourceAttributes,omitempty"` + PromoteAllResourceAttributes *bool `json:"promoteAllResourceAttributes,omitempty"` // nolint:kubeapilinter // ignoreResourceAttributes defines the list of OpenTelemetry resource attributes to ignore when `promoteAllResourceAttributes` is true. // @@ -2542,18 +2561,18 @@ type OTLPConfig struct { // // It requires Prometheus >= v3.1.0. // +optional - KeepIdentifyingResourceAttributes *bool `json:"keepIdentifyingResourceAttributes,omitempty"` + KeepIdentifyingResourceAttributes *bool `json:"keepIdentifyingResourceAttributes,omitempty"` // nolint:kubeapilinter // convertHistogramsToNHCB defines optional translation of OTLP explicit bucket histograms into native histograms with custom buckets. // It requires Prometheus >= v3.4.0. // +optional - ConvertHistogramsToNHCB *bool `json:"convertHistogramsToNHCB,omitempty"` + ConvertHistogramsToNHCB *bool `json:"convertHistogramsToNHCB,omitempty"` // nolint:kubeapilinter // promoteScopeMetadata controls whether to promote OpenTelemetry scope metadata (i.e. name, version, schema URL, and attributes) to metric labels. // As per the OpenTelemetry specification, the aforementioned scope metadata should be identifying, i.e. made into metric labels. // It requires Prometheus >= v3.6.0. // +optional - PromoteScopeMetadata *bool `json:"promoteScopeMetadata,omitempty"` + PromoteScopeMetadata *bool `json:"promoteScopeMetadata,omitempty"` // nolint:kubeapilinter } // Validate semantically validates the given OTLPConfig section. diff --git a/vendor/github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1/prometheusrule_types.go b/vendor/github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1/prometheusrule_types.go index 576f8d38925..439b57c53f6 100644 --- a/vendor/github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1/prometheusrule_types.go +++ b/vendor/github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1/prometheusrule_types.go @@ -88,6 +88,7 @@ type RuleGroup struct { // It requires Prometheus >= 3.0.0. // The field is ignored for Thanos Ruler. // +optional + //nolint:kubeapilinter Labels map[string]string `json:"labels,omitempty"` // interval defines how often rules in the group are evaluated. // +optional @@ -141,10 +142,12 @@ type Rule struct { KeepFiringFor *NonEmptyDuration `json:"keep_firing_for,omitempty"` // labels defines labels to add or overwrite. // +optional + //nolint:kubeapilinter Labels map[string]string `json:"labels,omitempty"` // annotations defines annotations to add to each alert. // Only valid for alerting rules. // +optional + //nolint:kubeapilinter Annotations map[string]string `json:"annotations,omitempty"` } diff --git a/vendor/github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1/thanos_types.go b/vendor/github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1/thanos_types.go index 434664c23bb..49dd72f0bd5 100644 --- a/vendor/github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1/thanos_types.go +++ b/vendor/github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1/thanos_types.go @@ -111,7 +111,7 @@ type ThanosRulerSpec struct { // paused defines when a ThanosRuler deployment is paused, no actions except for deletion // will be performed on the underlying objects. // +optional - Paused bool `json:"paused,omitempty"` + Paused bool `json:"paused,omitempty"` // nolint:kubeapilinter // replicas defines the number of thanos ruler instances to deploy. // +optional @@ -119,6 +119,7 @@ type ThanosRulerSpec struct { // nodeSelector defines which Nodes the Pods are scheduled on. // +optional + //nolint:kubeapilinter NodeSelector map[string]string `json:"nodeSelector,omitempty"` // resources defines the resource requirements for single Pods. @@ -154,7 +155,7 @@ type ThanosRulerSpec struct { // enableServiceLinks defines whether information about services should be injected into pod's environment variables // +optional - EnableServiceLinks *bool `json:"enableServiceLinks,omitempty"` + EnableServiceLinks *bool `json:"enableServiceLinks,omitempty"` // nolint:kubeapilinter // priorityClassName defines the priority class assigned to the Pods // +optional @@ -210,7 +211,29 @@ type ThanosRulerSpec struct { // listenLocal defines the Thanos ruler listen on loopback, so that it // does not bind against the Pod IP. // +optional - ListenLocal bool `json:"listenLocal,omitempty"` + ListenLocal bool `json:"listenLocal,omitempty"` // nolint:kubeapilinter + + // podManagementPolicy defines the policy for creating/deleting pods when + // scaling up and down. + // + // Unlike the default StatefulSet behavior, the default policy is + // `Parallel` to avoid manual intervention in case a pod gets stuck during + // a rollout. + // + // Note that updating this value implies the recreation of the StatefulSet + // which incurs a service outage. + // + // +optional + PodManagementPolicy *PodManagementPolicyType `json:"podManagementPolicy,omitempty"` + + // updateStrategy indicates the strategy that will be employed to update + // Pods in the StatefulSet when a revision is made to statefulset's Pod + // Template. + // + // The default strategy is RollingUpdate. + // + // +optional + UpdateStrategy *StatefulSetUpdateStrategy `json:"updateStrategy,omitempty"` // queryEndpoints defines the list of Thanos Query endpoints from which to query metrics. // @@ -395,6 +418,7 @@ type ThanosRulerSpec struct { // label with the value of the pod's name. // // +optional + //nolint:kubeapilinter Labels map[string]string `json:"labels,omitempty"` // alertDropLabels defines the label names which should be dropped in Thanos Ruler @@ -523,7 +547,7 @@ type ThanosRulerSpec struct { // Starting Kubernetes 1.33, the feature is enabled by default. // // +optional - HostUsers *bool `json:"hostUsers,omitempty"` + HostUsers *bool `json:"hostUsers,omitempty"` // nolint:kubeapilinter } // ThanosRulerWebSpec defines the configuration of the ThanosRuler web server. @@ -541,7 +565,7 @@ type ThanosRulerStatus struct { // paused defines whether any actions on the underlying managed objects are // being performed. Only delete actions will be performed. // +optional - Paused bool `json:"paused"` + Paused bool `json:"paused"` // nolint:kubeapilinter // replicas defines the total number of non-terminated pods targeted by this ThanosRuler deployment // (their labels match the selector). // +optional diff --git a/vendor/github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1/tls_types.go b/vendor/github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1/tls_types.go new file mode 100644 index 00000000000..51e6835279f --- /dev/null +++ b/vendor/github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1/tls_types.go @@ -0,0 +1,173 @@ +// Copyright 2025 The prometheus-operator Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package v1 + +import ( + "fmt" + "reflect" + "strings" + + v1 "k8s.io/api/core/v1" +) + +// +kubebuilder:validation:Enum=TLS10;TLS11;TLS12;TLS13 +type TLSVersion string + +const ( + TLSVersion10 TLSVersion = "TLS10" + TLSVersion11 TLSVersion = "TLS11" + TLSVersion12 TLSVersion = "TLS12" + TLSVersion13 TLSVersion = "TLS13" +) + +// TLSConfig defines full TLS configuration. +type TLSConfig struct { + SafeTLSConfig `json:",inline"` + TLSFilesConfig `json:",inline"` +} + +// Validate semantically validates the given TLSConfig. +func (c *TLSConfig) Validate() error { + if c == nil { + return nil + } + + if !reflect.ValueOf(c.CA).IsZero() { + if c.CAFile != "" { + return fmt.Errorf("cannot specify both 'caFile' and 'ca'") + } + + if err := c.CA.Validate(); err != nil { + return fmt.Errorf("ca: %w", err) + } + } + + hasCert := !reflect.ValueOf(c.Cert).IsZero() + if hasCert { + if c.CertFile != "" { + return fmt.Errorf("cannot specify both 'certFile' and 'cert'") + } + + if err := c.Cert.Validate(); err != nil { + return fmt.Errorf("cert: %w", err) + } + } + + if c.KeyFile != "" && c.KeySecret != nil { + return fmt.Errorf("cannot specify both 'keyFile' and 'keySecret'") + } + + hasCert = hasCert || c.CertFile != "" + hasKey := c.KeyFile != "" || c.KeySecret != nil + + if hasCert && !hasKey { + return fmt.Errorf("cannot specify client cert without client key") + } + + if hasKey && !hasCert { + return fmt.Errorf("cannot specify client key without client cert") + } + + if c.MaxVersion != nil && c.MinVersion != nil && strings.Compare(string(*c.MaxVersion), string(*c.MinVersion)) == -1 { + return fmt.Errorf("'maxVersion' must greater than or equal to 'minVersion'") + } + + return nil +} + +// SafeTLSConfig defines safe TLS configurations. +// +k8s:openapi-gen=true +type SafeTLSConfig struct { + // ca defines the Certificate authority used when verifying server certificates. + // +optional + CA SecretOrConfigMap `json:"ca,omitempty"` + + // cert defines the Client certificate to present when doing client-authentication. + // +optional + Cert SecretOrConfigMap `json:"cert,omitempty"` + + // keySecret defines the Secret containing the client key file for the targets. + // +optional + KeySecret *v1.SecretKeySelector `json:"keySecret,omitempty"` + + // serverName is used to verify the hostname for the targets. + // +optional + ServerName *string `json:"serverName,omitempty"` + + // insecureSkipVerify defines how to disable target certificate validation. + // +optional + InsecureSkipVerify *bool `json:"insecureSkipVerify,omitempty"` // nolint:kubeapilinter + + // minVersion defines the minimum acceptable TLS version. + // + // It requires Prometheus >= v2.35.0 or Thanos >= v0.28.0. + // +optional + MinVersion *TLSVersion `json:"minVersion,omitempty"` + + // maxVersion defines the maximum acceptable TLS version. + // + // It requires Prometheus >= v2.41.0 or Thanos >= v0.31.0. + // +optional + MaxVersion *TLSVersion `json:"maxVersion,omitempty"` +} + +// Validate semantically validates the given SafeTLSConfig. +func (c *SafeTLSConfig) Validate() error { + if c == nil { + return nil + } + + if c.CA != (SecretOrConfigMap{}) { + if err := c.CA.Validate(); err != nil { + return fmt.Errorf("ca %s: %w", c.CA.String(), err) + } + } + + if c.Cert != (SecretOrConfigMap{}) { + if err := c.Cert.Validate(); err != nil { + return fmt.Errorf("cert %s: %w", c.Cert.String(), err) + } + } + + if c.Cert != (SecretOrConfigMap{}) && c.KeySecret == nil { + return fmt.Errorf("client cert specified without client key") + } + + if c.KeySecret != nil && c.Cert == (SecretOrConfigMap{}) { + return fmt.Errorf("client key specified without client cert") + } + + if c.MaxVersion != nil && c.MinVersion != nil && strings.Compare(string(*c.MaxVersion), string(*c.MinVersion)) == -1 { + return fmt.Errorf("maxVersion must more than or equal to minVersion") + } + + return nil +} + +// TLSFilesConfig extends the TLS configuration with file parameters. +// +k8s:openapi-gen=true +type TLSFilesConfig struct { + // caFile defines the path to the CA cert in the Prometheus container to use for the targets. + // +optional + CAFile string `json:"caFile,omitempty"` + // certFile defines the path to the client cert file in the Prometheus container for the targets. + // +optional + CertFile string `json:"certFile,omitempty"` + // keyFile defines the path to the client key file in the Prometheus container for the targets. + // +optional + KeyFile string `json:"keyFile,omitempty"` +} + +// diff --git a/vendor/github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1/types.go b/vendor/github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1/types.go index bddbed14bb6..2f1cd1f1e6e 100644 --- a/vendor/github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1/types.go +++ b/vendor/github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1/types.go @@ -109,14 +109,14 @@ type ProxyConfig struct { // // It requires Prometheus >= v2.43.0, Alertmanager >= v0.25.0 or Thanos >= v0.32.0. // +optional - ProxyFromEnvironment *bool `json:"proxyFromEnvironment,omitempty"` + ProxyFromEnvironment *bool `json:"proxyFromEnvironment,omitempty"` // nolint:kubeapilinter // proxyConnectHeader optionally specifies headers to send to // proxies during CONNECT requests. // // It requires Prometheus >= v2.43.0, Alertmanager >= v0.25.0 or Thanos >= v0.32.0. // +optional // +mapType:=atomic - ProxyConnectHeader map[string][]v1.SecretKeySelector `json:"proxyConnectHeader,omitempty"` + ProxyConnectHeader map[string][]v1.SecretKeySelector `json:"proxyConnectHeader,omitempty"` //nolint:kubeapilinter } // Validate semantically validates the given ProxyConfig. @@ -227,7 +227,7 @@ type ArbitraryFSAccessThroughSMsConfig struct { // Setting this to true enhances security by preventing potential credential theft attacks. // // +optional - Deny bool `json:"deny,omitempty"` + Deny bool `json:"deny,omitempty"` // nolint:kubeapilinter } // Condition represents the state of the resources associated with the @@ -330,6 +330,7 @@ type EmbeddedObjectMetadata struct { // and services. // More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/labels/ // +optional + //nolint:kubeapilinter Labels map[string]string `json:"labels,omitempty" protobuf:"bytes,11,rep,name=labels"` // annotations defines an unstructured key value map stored with a resource that may be @@ -337,6 +338,7 @@ type EmbeddedObjectMetadata struct { // queryable and should be preserved when modifying objects. // More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/annotations/ // +optional + //nolint:kubeapilinter Annotations map[string]string `json:"annotations,omitempty" protobuf:"bytes,12,rep,name=annotations"` } @@ -358,7 +360,7 @@ type WebHTTPConfig struct { // When TLSConfig is not configured, HTTP/2 will be disabled. // Whenever the value of the field changes, a rolling update will be triggered. // +optional - HTTP2 *bool `json:"http2,omitempty"` + HTTP2 *bool `json:"http2,omitempty"` // nolint:kubeapilinter // headers defines a list of headers that can be added to HTTP responses. // +optional Headers *WebHTTPHeaders `json:"headers,omitempty"` @@ -483,7 +485,7 @@ type WebTLSConfig struct { // the order of elements in cipherSuites, is used. // // +optional - PreferServerCipherSuites *bool `json:"preferServerCipherSuites,omitempty"` + PreferServerCipherSuites *bool `json:"preferServerCipherSuites,omitempty"` // nolint:kubeapilinter // curvePreferences defines elliptic curves that will be used in an ECDHE handshake, in preference // order. @@ -572,6 +574,7 @@ type Endpoint struct { // params define optional HTTP URL parameters. // +optional + //nolint:kubeapilinter Params map[string][]string `json:"params,omitempty"` // interval at which Prometheus scrapes the metrics from the target. @@ -588,44 +591,16 @@ type Endpoint struct { // +optional ScrapeTimeout Duration `json:"scrapeTimeout,omitempty"` - // tlsConfig defines the TLS configuration to use when scraping the target. - // - // +optional - TLSConfig *TLSConfig `json:"tlsConfig,omitempty"` - - // bearerTokenFile defines the file to read bearer token for scraping the target. - // - // Deprecated: use `authorization` instead. - // +optional - BearerTokenFile string `json:"bearerTokenFile,omitempty"` - - // bearerTokenSecret defines a key of a Secret containing the bearer - // token for scraping targets. The secret needs to be in the same namespace - // as the ServiceMonitor object and readable by the Prometheus Operator. - // - // +optional - // - // Deprecated: use `authorization` instead. - BearerTokenSecret *v1.SecretKeySelector `json:"bearerTokenSecret,omitempty"` - - // authorization configures the Authorization header credentials to use when - // scraping the target. - // - // Cannot be set at the same time as `basicAuth`, or `oauth2`. - // - // +optional - Authorization *SafeAuthorization `json:"authorization,omitempty"` - // honorLabels defines when true the metric's labels when they collide // with the target's labels. // +optional - HonorLabels bool `json:"honorLabels,omitempty"` + HonorLabels bool `json:"honorLabels,omitempty"` // nolint:kubeapilinter // honorTimestamps defines whether Prometheus preserves the timestamps // when exposed by the target. // // +optional - HonorTimestamps *bool `json:"honorTimestamps,omitempty"` + HonorTimestamps *bool `json:"honorTimestamps,omitempty"` // nolint:kubeapilinter // trackTimestampsStaleness defines whether Prometheus tracks staleness of // the metrics that have an explicit timestamp present in scraped data. @@ -634,24 +609,7 @@ type Endpoint struct { // It requires Prometheus >= v2.48.0. // // +optional - TrackTimestampsStaleness *bool `json:"trackTimestampsStaleness,omitempty"` - - // basicAuth defines the Basic Authentication credentials to use when - // scraping the target. - // - // Cannot be set at the same time as `authorization`, or `oauth2`. - // - // +optional - BasicAuth *BasicAuth `json:"basicAuth,omitempty"` - - // oauth2 defines the OAuth2 settings to use when scraping the target. - // - // It requires Prometheus >= 2.27.0. - // - // Cannot be set at the same time as `authorization`, or `basicAuth`. - // - // +optional - OAuth2 *OAuth2 `json:"oauth2,omitempty"` + TrackTimestampsStaleness *bool `json:"trackTimestampsStaleness,omitempty"` // nolint:kubeapilinter // metricRelabelings defines the relabeling rules to apply to the // samples before ingestion. @@ -671,20 +629,6 @@ type Endpoint struct { // +optional RelabelConfigs []RelabelConfig `json:"relabelings,omitempty"` - // +optional - ProxyConfig `json:",inline"` - - // followRedirects defines whether the scrape requests should follow HTTP - // 3xx redirects. - // - // +optional - FollowRedirects *bool `json:"followRedirects,omitempty"` - - // enableHttp2 can be used to disable HTTP2 when scraping the target. - // - // +optional - EnableHttp2 *bool `json:"enableHttp2,omitempty"` - // filterRunning when true, the pods which are not running (e.g. either in Failed or // Succeeded state) are dropped during the target discovery. // @@ -693,7 +637,15 @@ type Endpoint struct { // More info: https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle/#pod-phase // // +optional - FilterRunning *bool `json:"filterRunning,omitempty"` + FilterRunning *bool `json:"filterRunning,omitempty"` // nolint:kubeapilinter + + // bearerTokenFile defines the file to read bearer token for scraping the target. + // + // Deprecated: use `authorization` instead. + // +optional + BearerTokenFile string `json:"bearerTokenFile,omitempty"` + + HTTPConfigWithProxyAndTLSFiles `json:",inline"` } type AttachMetadata struct { @@ -704,7 +656,7 @@ type AttachMetadata struct { // permissions on the `Nodes` objects. // // +optional - Node *bool `json:"node,omitempty"` + Node *bool `json:"node,omitempty"` // nolint:kubeapilinter } // OAuth2 configures OAuth2 settings. @@ -736,6 +688,7 @@ type OAuth2 struct { // URL. // // +optional + //nolint:kubeapilinter EndpointParams map[string]string `json:"endpointParams,omitempty"` // tlsConfig defines the TLS configuration to use when connecting to the OAuth2 server. @@ -828,147 +781,6 @@ func (c *SecretOrConfigMap) String() string { return "" } -// +kubebuilder:validation:Enum=TLS10;TLS11;TLS12;TLS13 -type TLSVersion string - -const ( - TLSVersion10 TLSVersion = "TLS10" - TLSVersion11 TLSVersion = "TLS11" - TLSVersion12 TLSVersion = "TLS12" - TLSVersion13 TLSVersion = "TLS13" -) - -// SafeTLSConfig specifies safe TLS configuration parameters. -// +k8s:openapi-gen=true -type SafeTLSConfig struct { - // ca defines the Certificate authority used when verifying server certificates. - // +optional - CA SecretOrConfigMap `json:"ca,omitempty"` - - // cert defines the Client certificate to present when doing client-authentication. - // +optional - Cert SecretOrConfigMap `json:"cert,omitempty"` - - // keySecret defines the Secret containing the client key file for the targets. - // +optional - KeySecret *v1.SecretKeySelector `json:"keySecret,omitempty"` - - // serverName is used to verify the hostname for the targets. - // +optional - ServerName *string `json:"serverName,omitempty"` - - // insecureSkipVerify defines how to disable target certificate validation. - // +optional - InsecureSkipVerify *bool `json:"insecureSkipVerify,omitempty"` - - // minVersion defines the minimum acceptable TLS version. - // - // It requires Prometheus >= v2.35.0 or Thanos >= v0.28.0. - // +optional - MinVersion *TLSVersion `json:"minVersion,omitempty"` - - // maxVersion defines the maximum acceptable TLS version. - // - // It requires Prometheus >= v2.41.0 or Thanos >= v0.31.0. - // +optional - MaxVersion *TLSVersion `json:"maxVersion,omitempty"` -} - -// Validate semantically validates the given SafeTLSConfig. -func (c *SafeTLSConfig) Validate() error { - if c == nil { - return nil - } - - if c.CA != (SecretOrConfigMap{}) { - if err := c.CA.Validate(); err != nil { - return fmt.Errorf("ca %s: %w", c.CA.String(), err) - } - } - - if c.Cert != (SecretOrConfigMap{}) { - if err := c.Cert.Validate(); err != nil { - return fmt.Errorf("cert %s: %w", c.Cert.String(), err) - } - } - - if c.Cert != (SecretOrConfigMap{}) && c.KeySecret == nil { - return fmt.Errorf("client cert specified without client key") - } - - if c.KeySecret != nil && c.Cert == (SecretOrConfigMap{}) { - return fmt.Errorf("client key specified without client cert") - } - - if c.MaxVersion != nil && c.MinVersion != nil && strings.Compare(string(*c.MaxVersion), string(*c.MinVersion)) == -1 { - return fmt.Errorf("maxVersion must more than or equal to minVersion") - } - - return nil -} - -// TLSConfig extends the safe TLS configuration with file parameters. -// +k8s:openapi-gen=true -type TLSConfig struct { - // +optional - SafeTLSConfig `json:",inline"` - // caFile defines the path to the CA cert in the Prometheus container to use for the targets. - // +optional - CAFile string `json:"caFile,omitempty"` - // certFile defines the path to the client cert file in the Prometheus container for the targets. - // +optional - CertFile string `json:"certFile,omitempty"` - // keyFile defines the path to the client key file in the Prometheus container for the targets. - // +optional - KeyFile string `json:"keyFile,omitempty"` -} - -// Validate semantically validates the given TLSConfig. -func (c *TLSConfig) Validate() error { - if c == nil { - return nil - } - - if c.CA != (SecretOrConfigMap{}) { - if c.CAFile != "" { - return fmt.Errorf("cannot specify both caFile and ca") - } - if err := c.CA.Validate(); err != nil { - return fmt.Errorf("SecretOrConfigMap ca: %w", err) - } - } - - if c.Cert != (SecretOrConfigMap{}) { - if c.CertFile != "" { - return fmt.Errorf("cannot specify both certFile and cert") - } - if err := c.Cert.Validate(); err != nil { - return fmt.Errorf("SecretOrConfigMap cert: %w", err) - } - } - - if c.KeyFile != "" && c.KeySecret != nil { - return fmt.Errorf("cannot specify both keyFile and keySecret") - } - - hasCert := c.CertFile != "" || c.Cert != (SecretOrConfigMap{}) - hasKey := c.KeyFile != "" || c.KeySecret != nil - - if hasCert && !hasKey { - return fmt.Errorf("cannot specify client cert without client key") - } - - if hasKey && !hasCert { - return fmt.Errorf("cannot specify client key without client cert") - } - - if c.MaxVersion != nil && c.MinVersion != nil && strings.Compare(string(*c.MaxVersion), string(*c.MinVersion)) == -1 { - return fmt.Errorf("maxVersion must more than or equal to minVersion") - } - - return nil -} - // NamespaceSelector is a selector for selecting either all namespaces or a // list of namespaces. // If `any` is true, it takes precedence over `matchNames`. @@ -979,7 +791,7 @@ type NamespaceSelector struct { // any defines the boolean describing whether all namespaces are selected in contrast to a // list restricting them. // +optional - Any bool `json:"any,omitempty"` + Any bool `json:"any,omitempty"` // nolint:kubeapilinter // matchNames defines the list of namespace names to select from. // +optional MatchNames []string `json:"matchNames,omitempty"` @@ -1014,13 +826,19 @@ const ( // NativeHistogramConfig extends the native histogram configuration settings. // +k8s:openapi-gen=true type NativeHistogramConfig struct { + // scrapeNativeHistograms defines whether to enable scraping of native histograms. + // It requires Prometheus >= v3.8.0. + // + // +optional + ScrapeNativeHistograms *bool `json:"scrapeNativeHistograms,omitempty"` // nolint:kubeapilinter + // scrapeClassicHistograms defines whether to scrape a classic histogram that is also exposed as a native histogram. // It requires Prometheus >= v2.45.0. // // Notice: `scrapeClassicHistograms` corresponds to the `always_scrape_classic_histograms` field in the Prometheus configuration. // // +optional - ScrapeClassicHistograms *bool `json:"scrapeClassicHistograms,omitempty"` + ScrapeClassicHistograms *bool `json:"scrapeClassicHistograms,omitempty"` // nolint:kubeapilinter // nativeHistogramBucketLimit defines ff there are more than this many buckets in a native histogram, // buckets will be merged to stay within the limit. @@ -1040,7 +858,7 @@ type NativeHistogramConfig struct { // It requires Prometheus >= v3.0.0. // // +optional - ConvertClassicHistogramsToNHCB *bool `json:"convertClassicHistogramsToNHCB,omitempty"` + ConvertClassicHistogramsToNHCB *bool `json:"convertClassicHistogramsToNHCB,omitempty"` // nolint:kubeapilinter } // +kubebuilder:validation:Enum=RelabelConfig;RoleSelector @@ -1140,3 +958,135 @@ const ( SchemeHTTP Scheme = "HTTP" SchemeHTTPS Scheme = "HTTPS" ) + +// +kubebuilder:validation:Enum=OrderedReady;Parallel +type PodManagementPolicyType string + +const ( + // OrderedReadyPodManagement will create pods in strictly increasing order on + // scale up and strictly decreasing order on scale down, progressing only when + // the previous pod is ready or terminated. At most one pod will be changed + // at any time. + OrderedReadyPodManagement PodManagementPolicyType = "OrderedReady" + // ParallelPodManagement will create and delete pods as soon as the stateful set + // replica count is changed, and will not wait for pods to be ready or complete + // termination. + ParallelPodManagement PodManagementPolicyType = "Parallel" +) + +// StatefulSetUpdateStrategy indicates the strategy used when updating the +// StatefulSet. It includes any additional parameters necessary to perform the +// update for the indicated strategy. +// +// +kubebuilder:validation:XValidation:rule="!(self.type != 'RollingUpdate' && has(self.rollingUpdate))",message="rollingUpdate requires type to be RollingUpdate" +type StatefulSetUpdateStrategy struct { + // type indicates the type of the StatefulSetUpdateStrategy. + // + // Default is RollingUpdate. + // + // +required + Type StatefulSetUpdateStrategyType `json:"type"` + + // rollingUpdate is used to communicate parameters when type is RollingUpdate. + // + // +optional + RollingUpdate *RollingUpdateStatefulSetStrategy `json:"rollingUpdate,omitempty"` +} + +// RollingUpdateStatefulSetStrategy is used to communicate parameter for the RollingUpdate strategy. +type RollingUpdateStatefulSetStrategy struct { + // maxUnavailable is the maximum number of pods that can be unavailable + // during the update. The value can be an absolute number (ex: 5) or a + // percentage of desired pods (ex: 10%). Absolute number is calculated from + // percentage by rounding up. This can not be 0. Defaults to 1. This field + // is alpha-level and is only honored by servers that enable the + // MaxUnavailableStatefulSet feature. The field applies to all pods in the + // range 0 to Replicas-1. That means if there is any unavailable pod in + // the range 0 to Replicas-1, it will be counted towards MaxUnavailable. + // + // +kubebuilder:validation:XIntOrString + // +optional + MaxUnavailable *intstr.IntOrString `json:"maxUnavailable,omitempty" protobuf:"varint,2,opt,name=maxUnavailable"` +} + +// StatefulSetUpdateStrategyType is a string enumeration type that enumerates +// all possible update strategies for the StatefulSet pods. +// +// +kubebuilder:validation:Enum=OnDelete;RollingUpdate +type StatefulSetUpdateStrategyType string + +const ( + // RollingUpdateStatefulSetStrategyType indicates that update will be + // applied to all Pods in the StatefulSet with respect to the StatefulSet + // ordering constraints. When a scale operation is performed with this + // strategy, new Pods will be created from the specification version indicated + // by the StatefulSet's updateRevision. + RollingUpdateStatefulSetStrategyType StatefulSetUpdateStrategyType = "RollingUpdate" + + // OnDeleteStatefulSetStrategyType triggers the legacy behavior. Version + // tracking and ordered rolling restarts are disabled. Pods are recreated + // from the StatefulSetSpec when they are manually deleted. When a scale + // operation is performed with this strategy, new Pods will be created from + // the the specification version indicated by the StatefulSet's + // currentRevision. + OnDeleteStatefulSetStrategyType StatefulSetUpdateStrategyType = "OnDelete" +) + +type TracingConfig struct { + // clientType defines the client used to export the traces. Supported values are `HTTP` and `GRPC`. + // +kubebuilder:validation:Enum=http;grpc;HTTP;GRPC + // +optional + ClientType *string `json:"clientType",omitempty` + + // endpoint to send the traces to. Should be provided in format :. + // +kubebuilder:validation:MinLength:=1 + // +required + Endpoint string `json:"endpoint"` + + // samplingFraction defines the probability a given trace will be sampled. Must be a float from 0 through 1. + // +optional + SamplingFraction *resource.Quantity `json:"samplingFraction",omitempty` + + // insecure if disabled, the client will use a secure connection. + // +optional + Insecure *bool `json:"insecure",omitempty` // nolint:kubeapilinter + + // headers defines the key-value pairs to be used as headers associated with gRPC or HTTP requests. + // +optional + Headers map[string]string `json:"headers"` + + // compression key for supported compression types. The only supported value is `Gzip`. + // +kubebuilder:validation:Enum=gzip;Gzip + // +optional + Compression *string `json:"compression",omitempty` + + // timeout defines the maximum time the exporter will wait for each batch export. + // +optional + Timeout *Duration `json:"timeout",omitempty` + + // tlsConfig to use when sending traces. + // +optional + TLSConfig *TLSConfig `json:"tlsConfig",omitempty` +} + +// Validate semantically validates the given TracingConfig. +func (tc *TracingConfig) Validate() error { + if tc == nil { + return nil + } + + if err := tc.TLSConfig.Validate(); err != nil { + return err + } + + if tc.SamplingFraction != nil { + min, _ := resource.ParseQuantity("0") + max, _ := resource.ParseQuantity("1") + + if tc.SamplingFraction.Cmp(min) < 0 || tc.SamplingFraction.Cmp(max) > 0 { + return fmt.Errorf("`samplingFraction` must be between 0 and 1") + } + } + + return nil +} diff --git a/vendor/github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1/zz_generated.deepcopy.go b/vendor/github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1/zz_generated.deepcopy.go index 03b17df8bcb..73314958dc9 100644 --- a/vendor/github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1/zz_generated.deepcopy.go +++ b/vendor/github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1/zz_generated.deepcopy.go @@ -228,9 +228,9 @@ func (in *AlertmanagerGlobalConfig) DeepCopyInto(out *AlertmanagerGlobalConfig) *out = new(GlobalSMTPConfig) (*in).DeepCopyInto(*out) } - if in.HTTPConfig != nil { - in, out := &in.HTTPConfig, &out.HTTPConfig - *out = new(HTTPConfig) + if in.HTTPConfigWithProxy != nil { + in, out := &in.HTTPConfigWithProxy, &out.HTTPConfigWithProxy + *out = new(HTTPConfigWithProxy) (*in).DeepCopyInto(*out) } if in.SlackAPIURL != nil { @@ -453,6 +453,16 @@ func (in *AlertmanagerSpec) DeepCopyInto(out *AlertmanagerSpec) { *out = new(string) **out = **in } + if in.PodManagementPolicy != nil { + in, out := &in.PodManagementPolicy, &out.PodManagementPolicy + *out = new(PodManagementPolicyType) + **out = **in + } + if in.UpdateStrategy != nil { + in, out := &in.UpdateStrategy, &out.UpdateStrategy + *out = new(StatefulSetUpdateStrategy) + (*in).DeepCopyInto(*out) + } if in.Containers != nil { in, out := &in.Containers, &out.Containers *out = make([]corev1.Container, len(*in)) @@ -694,6 +704,16 @@ func (in *AzureAD) DeepCopyInto(out *AzureAD) { *out = new(AzureSDK) (*in).DeepCopyInto(*out) } + if in.WorkloadIdentity != nil { + in, out := &in.WorkloadIdentity, &out.WorkloadIdentity + *out = new(AzureWorkloadIdentity) + **out = **in + } + if in.Scope != nil { + in, out := &in.Scope, &out.Scope + *out = new(string) + **out = **in + } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new AzureAD. @@ -742,6 +762,21 @@ func (in *AzureSDK) DeepCopy() *AzureSDK { return out } +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *AzureWorkloadIdentity) DeepCopyInto(out *AzureWorkloadIdentity) { + *out = *in +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new AzureWorkloadIdentity. +func (in *AzureWorkloadIdentity) DeepCopy() *AzureWorkloadIdentity { + if in == nil { + return nil + } + out := new(AzureWorkloadIdentity) + in.DeepCopyInto(out) + return out +} + // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *BasicAuth) DeepCopyInto(out *BasicAuth) { *out = *in @@ -979,6 +1014,16 @@ func (in *CommonPrometheusFields) DeepCopyInto(out *CommonPrometheusFields) { *out = new(PodDNSConfig) (*in).DeepCopyInto(*out) } + if in.PodManagementPolicy != nil { + in, out := &in.PodManagementPolicy, &out.PodManagementPolicy + *out = new(PodManagementPolicyType) + **out = **in + } + if in.UpdateStrategy != nil { + in, out := &in.UpdateStrategy, &out.UpdateStrategy + *out = new(StatefulSetUpdateStrategy) + (*in).DeepCopyInto(*out) + } if in.EnableServiceLinks != nil { in, out := &in.EnableServiceLinks, &out.EnableServiceLinks *out = new(bool) @@ -1054,6 +1099,11 @@ func (in *CommonPrometheusFields) DeepCopyInto(out *CommonPrometheusFields) { *out = new(bool) **out = **in } + if in.ScrapeNativeHistograms != nil { + in, out := &in.ScrapeNativeHistograms, &out.ScrapeNativeHistograms + *out = new(bool) + **out = **in + } if in.ScrapeClassicHistograms != nil { in, out := &in.ScrapeClassicHistograms, &out.ScrapeClassicHistograms *out = new(bool) @@ -1093,7 +1143,7 @@ func (in *CommonPrometheusFields) DeepCopyInto(out *CommonPrometheusFields) { } if in.TracingConfig != nil { in, out := &in.TracingConfig, &out.TracingConfig - *out = new(PrometheusTracingConfig) + *out = new(TracingConfig) (*in).DeepCopyInto(*out) } if in.BodySizeLimit != nil { @@ -1366,21 +1416,6 @@ func (in *Endpoint) DeepCopyInto(out *Endpoint) { (*out)[key] = outVal } } - if in.TLSConfig != nil { - in, out := &in.TLSConfig, &out.TLSConfig - *out = new(TLSConfig) - (*in).DeepCopyInto(*out) - } - if in.BearerTokenSecret != nil { - in, out := &in.BearerTokenSecret, &out.BearerTokenSecret - *out = new(corev1.SecretKeySelector) - (*in).DeepCopyInto(*out) - } - if in.Authorization != nil { - in, out := &in.Authorization, &out.Authorization - *out = new(SafeAuthorization) - (*in).DeepCopyInto(*out) - } if in.HonorTimestamps != nil { in, out := &in.HonorTimestamps, &out.HonorTimestamps *out = new(bool) @@ -1391,16 +1426,6 @@ func (in *Endpoint) DeepCopyInto(out *Endpoint) { *out = new(bool) **out = **in } - if in.BasicAuth != nil { - in, out := &in.BasicAuth, &out.BasicAuth - *out = new(BasicAuth) - (*in).DeepCopyInto(*out) - } - if in.OAuth2 != nil { - in, out := &in.OAuth2, &out.OAuth2 - *out = new(OAuth2) - (*in).DeepCopyInto(*out) - } if in.MetricRelabelConfigs != nil { in, out := &in.MetricRelabelConfigs, &out.MetricRelabelConfigs *out = make([]RelabelConfig, len(*in)) @@ -1415,22 +1440,12 @@ func (in *Endpoint) DeepCopyInto(out *Endpoint) { (*in)[i].DeepCopyInto(&(*out)[i]) } } - in.ProxyConfig.DeepCopyInto(&out.ProxyConfig) - if in.FollowRedirects != nil { - in, out := &in.FollowRedirects, &out.FollowRedirects - *out = new(bool) - **out = **in - } - if in.EnableHttp2 != nil { - in, out := &in.EnableHttp2, &out.EnableHttp2 - *out = new(bool) - **out = **in - } if in.FilterRunning != nil { in, out := &in.FilterRunning, &out.FilterRunning *out = new(bool) **out = **in } + in.HTTPConfigWithProxyAndTLSFiles.DeepCopyInto(&out.HTTPConfigWithProxyAndTLSFiles) } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Endpoint. @@ -1670,6 +1685,82 @@ func (in *GlobalWebexConfig) DeepCopy() *GlobalWebexConfig { // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *HTTPConfig) DeepCopyInto(out *HTTPConfig) { + *out = *in + in.HTTPConfigWithoutTLS.DeepCopyInto(&out.HTTPConfigWithoutTLS) + if in.TLSConfig != nil { + in, out := &in.TLSConfig, &out.TLSConfig + *out = new(SafeTLSConfig) + (*in).DeepCopyInto(*out) + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new HTTPConfig. +func (in *HTTPConfig) DeepCopy() *HTTPConfig { + if in == nil { + return nil + } + out := new(HTTPConfig) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *HTTPConfigWithProxy) DeepCopyInto(out *HTTPConfigWithProxy) { + *out = *in + in.HTTPConfig.DeepCopyInto(&out.HTTPConfig) + in.ProxyConfig.DeepCopyInto(&out.ProxyConfig) +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new HTTPConfigWithProxy. +func (in *HTTPConfigWithProxy) DeepCopy() *HTTPConfigWithProxy { + if in == nil { + return nil + } + out := new(HTTPConfigWithProxy) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *HTTPConfigWithProxyAndTLSFiles) DeepCopyInto(out *HTTPConfigWithProxyAndTLSFiles) { + *out = *in + in.HTTPConfigWithTLSFiles.DeepCopyInto(&out.HTTPConfigWithTLSFiles) + in.ProxyConfig.DeepCopyInto(&out.ProxyConfig) +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new HTTPConfigWithProxyAndTLSFiles. +func (in *HTTPConfigWithProxyAndTLSFiles) DeepCopy() *HTTPConfigWithProxyAndTLSFiles { + if in == nil { + return nil + } + out := new(HTTPConfigWithProxyAndTLSFiles) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *HTTPConfigWithTLSFiles) DeepCopyInto(out *HTTPConfigWithTLSFiles) { + *out = *in + in.HTTPConfigWithoutTLS.DeepCopyInto(&out.HTTPConfigWithoutTLS) + if in.TLSConfig != nil { + in, out := &in.TLSConfig, &out.TLSConfig + *out = new(TLSConfig) + (*in).DeepCopyInto(*out) + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new HTTPConfigWithTLSFiles. +func (in *HTTPConfigWithTLSFiles) DeepCopy() *HTTPConfigWithTLSFiles { + if in == nil { + return nil + } + out := new(HTTPConfigWithTLSFiles) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *HTTPConfigWithoutTLS) DeepCopyInto(out *HTTPConfigWithoutTLS) { *out = *in if in.Authorization != nil { in, out := &in.Authorization, &out.Authorization @@ -1691,12 +1782,6 @@ func (in *HTTPConfig) DeepCopyInto(out *HTTPConfig) { *out = new(corev1.SecretKeySelector) (*in).DeepCopyInto(*out) } - if in.TLSConfig != nil { - in, out := &in.TLSConfig, &out.TLSConfig - *out = new(SafeTLSConfig) - (*in).DeepCopyInto(*out) - } - in.ProxyConfig.DeepCopyInto(&out.ProxyConfig) if in.FollowRedirects != nil { in, out := &in.FollowRedirects, &out.FollowRedirects *out = new(bool) @@ -1709,12 +1794,12 @@ func (in *HTTPConfig) DeepCopyInto(out *HTTPConfig) { } } -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new HTTPConfig. -func (in *HTTPConfig) DeepCopy() *HTTPConfig { +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new HTTPConfigWithoutTLS. +func (in *HTTPConfigWithoutTLS) DeepCopy() *HTTPConfigWithoutTLS { if in == nil { return nil } - out := new(HTTPConfig) + out := new(HTTPConfigWithoutTLS) in.DeepCopyInto(out) return out } @@ -1817,6 +1902,11 @@ func (in *NamespaceSelector) DeepCopy() *NamespaceSelector { // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *NativeHistogramConfig) DeepCopyInto(out *NativeHistogramConfig) { *out = *in + if in.ScrapeNativeHistograms != nil { + in, out := &in.ScrapeNativeHistograms, &out.ScrapeNativeHistograms + *out = new(bool) + **out = **in + } if in.ScrapeClassicHistograms != nil { in, out := &in.ScrapeClassicHistograms, &out.ScrapeClassicHistograms *out = new(bool) @@ -2069,7 +2159,7 @@ func (in *PodMetricsEndpoint) DeepCopyInto(out *PodMetricsEndpoint) { *out = new(bool) **out = **in } - in.HTTPConfig.DeepCopyInto(&out.HTTPConfig) + in.HTTPConfigWithProxy.DeepCopyInto(&out.HTTPConfigWithProxy) } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PodMetricsEndpoint. @@ -2283,22 +2373,6 @@ func (in *ProbeSpec) DeepCopyInto(out *ProbeSpec) { *out = *in in.ProberSpec.DeepCopyInto(&out.ProberSpec) in.Targets.DeepCopyInto(&out.Targets) - if in.TLSConfig != nil { - in, out := &in.TLSConfig, &out.TLSConfig - *out = new(SafeTLSConfig) - (*in).DeepCopyInto(*out) - } - in.BearerTokenSecret.DeepCopyInto(&out.BearerTokenSecret) - if in.BasicAuth != nil { - in, out := &in.BasicAuth, &out.BasicAuth - *out = new(BasicAuth) - (*in).DeepCopyInto(*out) - } - if in.OAuth2 != nil { - in, out := &in.OAuth2, &out.OAuth2 - *out = new(OAuth2) - (*in).DeepCopyInto(*out) - } if in.MetricRelabelConfigs != nil { in, out := &in.MetricRelabelConfigs, &out.MetricRelabelConfigs *out = make([]RelabelConfig, len(*in)) @@ -2364,6 +2438,7 @@ func (in *ProbeSpec) DeepCopyInto(out *ProbeSpec) { (*in)[i].DeepCopyInto(&(*out)[i]) } } + in.HTTPConfig.DeepCopyInto(&out.HTTPConfig) } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ProbeSpec. @@ -2709,58 +2784,6 @@ func (in *PrometheusStatus) DeepCopy() *PrometheusStatus { return out } -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *PrometheusTracingConfig) DeepCopyInto(out *PrometheusTracingConfig) { - *out = *in - if in.ClientType != nil { - in, out := &in.ClientType, &out.ClientType - *out = new(string) - **out = **in - } - if in.SamplingFraction != nil { - in, out := &in.SamplingFraction, &out.SamplingFraction - x := (*in).DeepCopy() - *out = &x - } - if in.Insecure != nil { - in, out := &in.Insecure, &out.Insecure - *out = new(bool) - **out = **in - } - if in.Headers != nil { - in, out := &in.Headers, &out.Headers - *out = make(map[string]string, len(*in)) - for key, val := range *in { - (*out)[key] = val - } - } - if in.Compression != nil { - in, out := &in.Compression, &out.Compression - *out = new(string) - **out = **in - } - if in.Timeout != nil { - in, out := &in.Timeout, &out.Timeout - *out = new(Duration) - **out = **in - } - if in.TLSConfig != nil { - in, out := &in.TLSConfig, &out.TLSConfig - *out = new(TLSConfig) - (*in).DeepCopyInto(*out) - } -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PrometheusTracingConfig. -func (in *PrometheusTracingConfig) DeepCopy() *PrometheusTracingConfig { - if in == nil { - return nil - } - out := new(PrometheusTracingConfig) - in.DeepCopyInto(out) - return out -} - // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *PrometheusWebSpec) DeepCopyInto(out *PrometheusWebSpec) { *out = *in @@ -3125,6 +3148,26 @@ func (in *RetainConfig) DeepCopy() *RetainConfig { return out } +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *RollingUpdateStatefulSetStrategy) DeepCopyInto(out *RollingUpdateStatefulSetStrategy) { + *out = *in + if in.MaxUnavailable != nil { + in, out := &in.MaxUnavailable, &out.MaxUnavailable + *out = new(intstr.IntOrString) + **out = **in + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new RollingUpdateStatefulSetStrategy. +func (in *RollingUpdateStatefulSetStrategy) DeepCopy() *RollingUpdateStatefulSetStrategy { + if in == nil { + return nil + } + out := new(RollingUpdateStatefulSetStrategy) + in.DeepCopyInto(out) + return out +} + // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *Rule) DeepCopyInto(out *Rule) { *out = *in @@ -3614,6 +3657,26 @@ func (in *Sigv4) DeepCopy() *Sigv4 { return out } +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *StatefulSetUpdateStrategy) DeepCopyInto(out *StatefulSetUpdateStrategy) { + *out = *in + if in.RollingUpdate != nil { + in, out := &in.RollingUpdate, &out.RollingUpdate + *out = new(RollingUpdateStatefulSetStrategy) + (*in).DeepCopyInto(*out) + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new StatefulSetUpdateStrategy. +func (in *StatefulSetUpdateStrategy) DeepCopy() *StatefulSetUpdateStrategy { + if in == nil { + return nil + } + out := new(StatefulSetUpdateStrategy) + in.DeepCopyInto(out) + return out +} + // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *StorageSpec) DeepCopyInto(out *StorageSpec) { *out = *in @@ -3644,6 +3707,7 @@ func (in *StorageSpec) DeepCopy() *StorageSpec { func (in *TLSConfig) DeepCopyInto(out *TLSConfig) { *out = *in in.SafeTLSConfig.DeepCopyInto(&out.SafeTLSConfig) + out.TLSFilesConfig = in.TLSFilesConfig } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new TLSConfig. @@ -3656,6 +3720,21 @@ func (in *TLSConfig) DeepCopy() *TLSConfig { return out } +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *TLSFilesConfig) DeepCopyInto(out *TLSFilesConfig) { + *out = *in +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new TLSFilesConfig. +func (in *TLSFilesConfig) DeepCopy() *TLSFilesConfig { + if in == nil { + return nil + } + out := new(TLSFilesConfig) + in.DeepCopyInto(out) + return out +} + // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *TSDBSpec) DeepCopyInto(out *TSDBSpec) { *out = *in @@ -3823,6 +3902,16 @@ func (in *ThanosRulerSpec) DeepCopyInto(out *ThanosRulerSpec) { *out = new(string) **out = **in } + if in.PodManagementPolicy != nil { + in, out := &in.PodManagementPolicy, &out.PodManagementPolicy + *out = new(PodManagementPolicyType) + **out = **in + } + if in.UpdateStrategy != nil { + in, out := &in.UpdateStrategy, &out.UpdateStrategy + *out = new(StatefulSetUpdateStrategy) + (*in).DeepCopyInto(*out) + } if in.QueryEndpoints != nil { in, out := &in.QueryEndpoints, &out.QueryEndpoints *out = make([]string, len(*in)) @@ -4122,6 +4211,58 @@ func (in *TopologySpreadConstraint) DeepCopy() *TopologySpreadConstraint { return out } +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *TracingConfig) DeepCopyInto(out *TracingConfig) { + *out = *in + if in.ClientType != nil { + in, out := &in.ClientType, &out.ClientType + *out = new(string) + **out = **in + } + if in.SamplingFraction != nil { + in, out := &in.SamplingFraction, &out.SamplingFraction + x := (*in).DeepCopy() + *out = &x + } + if in.Insecure != nil { + in, out := &in.Insecure, &out.Insecure + *out = new(bool) + **out = **in + } + if in.Headers != nil { + in, out := &in.Headers, &out.Headers + *out = make(map[string]string, len(*in)) + for key, val := range *in { + (*out)[key] = val + } + } + if in.Compression != nil { + in, out := &in.Compression, &out.Compression + *out = new(string) + **out = **in + } + if in.Timeout != nil { + in, out := &in.Timeout, &out.Timeout + *out = new(Duration) + **out = **in + } + if in.TLSConfig != nil { + in, out := &in.TLSConfig, &out.TLSConfig + *out = new(TLSConfig) + (*in).DeepCopyInto(*out) + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new TracingConfig. +func (in *TracingConfig) DeepCopy() *TracingConfig { + if in == nil { + return nil + } + out := new(TracingConfig) + in.DeepCopyInto(out) + return out +} + // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *WebConfigFileFields) DeepCopyInto(out *WebConfigFileFields) { *out = *in diff --git a/vendor/github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1alpha1/alertmanager_config_types.go b/vendor/github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1alpha1/alertmanager_config_types.go index e17e7fc02d9..4b0512c8bd1 100644 --- a/vendor/github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1alpha1/alertmanager_config_types.go +++ b/vendor/github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1alpha1/alertmanager_config_types.go @@ -29,6 +29,7 @@ import ( apiextensionsv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" + "k8s.io/utils/ptr" ) const ( @@ -43,6 +44,7 @@ const ( // +k8s:openapi-gen=true // +kubebuilder:resource:categories="prometheus-operator",shortName="amcfg" // +kubebuilder:storageversion +// +kubebuilder:subresource:status // AlertmanagerConfig configures the Prometheus Alertmanager, // specifying how alerts should be grouped, inhibited and notified to external systems. @@ -55,6 +57,14 @@ type AlertmanagerConfig struct { // spec defines the specification of AlertmanagerConfigSpec // +required Spec AlertmanagerConfigSpec `json:"spec"` + // status defines the status subresource. It is under active development and is updated only when the + // "StatusForConfigurationResources" feature gate is enabled. + // + // Most recent observed status of the ServiceMonitor. Read-only. + // More info: + // https://github.com/kubernetes/community/blob/master/contributors/devel/sig-architecture/api-conventions.md#spec-and-status + // +optional + Status monitoringv1.ConfigResourceStatus `json:"status,omitempty,omitzero"` } // AlertmanagerConfigList is a list of AlertmanagerConfig. @@ -81,13 +91,17 @@ type AlertmanagerConfigSpec struct { // +optional Route *Route `json:"route"` // receivers defines the list of receivers. + // +listType=map + // +listMapKey=name // +optional Receivers []Receiver `json:"receivers"` // inhibitRules defines the list of inhibition rules. The rules will only apply to alerts matching // the resource's namespace. + // +listType=atomic // +optional InhibitRules []InhibitRule `json:"inhibitRules,omitempty"` // muteTimeIntervals defines the list of MuteTimeInterval specifying when the routes should be muted. + // +listType=atomic // +optional MuteTimeIntervals []MuteTimeInterval `json:"muteTimeIntervals,omitempty"` } @@ -101,6 +115,7 @@ type Route struct { // groupBy defines the list of labels to group by. // Labels must not be repeated (unique list). // Special label "..." (aggregate by all possible labels), if provided, must be the only element in the list. + // +listType=set // +optional GroupBy []string `json:"groupBy,omitempty"` // groupWait defines how long to wait before sending the initial notification. @@ -122,14 +137,16 @@ type Route struct { // level route, the operator removes any existing equality and regexp // matcher on the `namespace` label and adds a `namespace: ` matcher. + // +listType=atomic // +optional Matchers []Matcher `json:"matchers,omitempty"` // continue defines the boolean indicating whether an alert should continue matching subsequent // sibling nodes. It will always be overridden to true for the first-level // route by the Prometheus operator. // +optional - Continue bool `json:"continue,omitempty"` + Continue bool `json:"continue,omitempty"` // nolint:kubeapilinter // routes defines the child routes. + // +listType=atomic // +optional Routes []apiextensionsv1.JSON `json:"routes,omitempty"` // Note: this comment applies to the field definition above but appears @@ -141,9 +158,11 @@ type Route struct { // JSON representation. // muteTimeIntervals is a list of MuteTimeInterval names that will mute this route when matched, + // +listType=set // +optional MuteTimeIntervals []string `json:"muteTimeIntervals,omitempty"` // activeTimeIntervals is a list of MuteTimeInterval names when this route should be active. + // +listType=set // +optional ActiveTimeIntervals []string `json:"activeTimeIntervals,omitempty"` } @@ -170,51 +189,66 @@ type Receiver struct { // +required Name string `json:"name"` // opsgenieConfigs defines the list of OpsGenie configurations. + // +listType=atomic // +optional OpsGenieConfigs []OpsGenieConfig `json:"opsgenieConfigs,omitempty"` // pagerdutyConfigs defines the List of PagerDuty configurations. + // +listType=atomic // +optional PagerDutyConfigs []PagerDutyConfig `json:"pagerdutyConfigs,omitempty"` // discordConfigs defines the list of Slack configurations. + // +listType=atomic // +optional DiscordConfigs []DiscordConfig `json:"discordConfigs,omitempty"` // slackConfigs defines the list of Slack configurations. + // +listType=atomic // +optional SlackConfigs []SlackConfig `json:"slackConfigs,omitempty"` // webhookConfigs defines the List of webhook configurations. + // +listType=atomic // +optional WebhookConfigs []WebhookConfig `json:"webhookConfigs,omitempty"` // wechatConfigs defines the list of WeChat configurations. + // +listType=atomic // +optional WeChatConfigs []WeChatConfig `json:"wechatConfigs,omitempty"` // emailConfigs defines the list of Email configurations. + // +listType=atomic // +optional EmailConfigs []EmailConfig `json:"emailConfigs,omitempty"` // victoropsConfigs defines the list of VictorOps configurations. + // +listType=atomic // +optional VictorOpsConfigs []VictorOpsConfig `json:"victoropsConfigs,omitempty"` // pushoverConfigs defines the list of Pushover configurations. + // +listType=atomic // +optional PushoverConfigs []PushoverConfig `json:"pushoverConfigs,omitempty"` // snsConfigs defines the list of SNS configurations + // +listType=atomic // +optional SNSConfigs []SNSConfig `json:"snsConfigs,omitempty"` // telegramConfigs defines the list of Telegram configurations. + // +listType=atomic // +optional TelegramConfigs []TelegramConfig `json:"telegramConfigs,omitempty"` // webexConfigs defines the list of Webex configurations. + // +listType=atomic // +optional WebexConfigs []WebexConfig `json:"webexConfigs,omitempty"` // msteamsConfigs defines the list of MSTeams configurations. // It requires Alertmanager >= 0.26.0. + // +listType=atomic // +optional MSTeamsConfigs []MSTeamsConfig `json:"msteamsConfigs,omitempty"` // msteamsv2Configs defines the list of MSTeamsV2 configurations. // It requires Alertmanager >= 0.28.0. + // +listType=atomic // +optional MSTeamsV2Configs []MSTeamsV2Config `json:"msteamsv2Configs,omitempty"` // rocketchatConfigs defines the list of RocketChat configurations. // It requires Alertmanager >= 0.28.0. + // +listType=atomic // +optional RocketChatConfigs []RocketChatConfig `json:"rocketchatConfigs,omitempty"` } @@ -224,7 +258,7 @@ type Receiver struct { type PagerDutyConfig struct { // sendResolved defines whether or not to notify about resolved alerts. // +optional - SendResolved *bool `json:"sendResolved,omitempty"` + SendResolved *bool `json:"sendResolved,omitempty"` // nolint:kubeapilinter // routingKey defines the secret's key that contains the PagerDuty integration key (when using // Events API v2). Either this field or `serviceKey` needs to be defined. // The secret needs to be in the same namespace as the AlertmanagerConfig @@ -240,66 +274,83 @@ type PagerDutyConfig struct { ServiceKey *v1.SecretKeySelector `json:"serviceKey,omitempty"` // url defines the URL to send requests to. // +optional - URL string `json:"url,omitempty"` + URL *URL `json:"url,omitempty"` // client defines the client identification. + // +kubebuilder:validation:MinLength=1 // +optional - Client string `json:"client,omitempty"` + Client *string `json:"client,omitempty"` // clientURL defines the backlink to the sender of notification. // +optional - ClientURL string `json:"clientURL,omitempty"` + ClientURL *URL `json:"clientURL,omitempty"` // description of the incident. + // +kubebuilder:validation:MinLength=1 // +optional - Description string `json:"description,omitempty"` + Description *string `json:"description,omitempty"` // severity of the incident. + // +kubebuilder:validation:MinLength=1 // +optional - Severity string `json:"severity,omitempty"` + Severity *string `json:"severity,omitempty"` // class defines the class/type of the event. + // +kubebuilder:validation:MinLength=1 // +optional - Class string `json:"class,omitempty"` + Class *string `json:"class,omitempty"` // group defines a cluster or grouping of sources. + // +kubebuilder:validation:MinLength=1 // +optional - Group string `json:"group,omitempty"` + Group *string `json:"group,omitempty"` // component defines the part or component of the affected system that is broken. + // +kubebuilder:validation:MinLength=1 // +optional - Component string `json:"component,omitempty"` + Component *string `json:"component,omitempty"` // details defines the arbitrary key/value pairs that provide further detail about the incident. + // +listType=atomic // +optional Details []KeyValue `json:"details,omitempty"` // pagerDutyImageConfigs defines a list of image details to attach that provide further detail about an incident. + // +listType=atomic // +optional PagerDutyImageConfigs []PagerDutyImageConfig `json:"pagerDutyImageConfigs,omitempty"` // pagerDutyLinkConfigs defines a list of link details to attach that provide further detail about an incident. + // +listType=atomic // +optional PagerDutyLinkConfigs []PagerDutyLinkConfig `json:"pagerDutyLinkConfigs,omitempty"` // httpConfig defines the HTTP client configuration. // +optional HTTPConfig *HTTPConfig `json:"httpConfig,omitempty"` // source defines the unique location of the affected system. + // +kubebuilder:validation:MinLength=1 + // +optional + Source *string `json:"source,omitempty"` + // timeout is the maximum time allowed to invoke the pagerduty + // It requires Alertmanager >= v0.30.0. // +optional - Source *string `yaml:"source,omitempty" json:"source,omitempty"` + Timeout *monitoringv1.Duration `json:"timeout,omitempty"` } // PagerDutyImageConfig attaches images to an incident type PagerDutyImageConfig struct { // src of the image being attached to the incident + // +kubebuilder:validation:MinLength=1 // +optional - Src string `json:"src,omitempty"` + Src *string `json:"src,omitempty"` // href defines the optional URL; makes the image a clickable link. // +optional - Href string `json:"href,omitempty"` + Href *URL `json:"href,omitempty"` // alt is the optional alternative text for the image. + // +kubebuilder:validation:MinLength=1 // +optional - Alt string `json:"alt,omitempty"` + Alt *string `json:"alt,omitempty"` } // PagerDutyLinkConfig attaches text links to an incident type PagerDutyLinkConfig struct { // href defines the URL of the link to be attached // +optional - Href string `json:"href,omitempty"` + Href *URL `json:"href,omitempty"` // alt defines the text that describes the purpose of the link, and can be used as the link's text. + // +kubebuilder:validation:MinLength=1 // +optional - Text string `json:"alt,omitempty"` + Text *string `json:"alt,omitempty"` } // DiscordConfig configures notifications via Discord. @@ -307,7 +358,7 @@ type PagerDutyLinkConfig struct { type DiscordConfig struct { // sendResolved defines whether or not to notify about resolved alerts. // +optional - SendResolved *bool `json:"sendResolved,omitempty"` + SendResolved *bool `json:"sendResolved,omitempty"` // nolint:kubeapilinter // apiURL defines the secret's key that contains the Discord webhook URL. // The secret needs to be in the same namespace as the AlertmanagerConfig // object and accessible by the Prometheus Operator. @@ -340,77 +391,99 @@ type DiscordConfig struct { type SlackConfig struct { // sendResolved defines whether or not to notify about resolved alerts. // +optional - SendResolved *bool `json:"sendResolved,omitempty"` + SendResolved *bool `json:"sendResolved,omitempty"` // nolint:kubeapilinter // apiURL defines the secret's key that contains the Slack webhook URL. // The secret needs to be in the same namespace as the AlertmanagerConfig // object and accessible by the Prometheus Operator. // +optional APIURL *v1.SecretKeySelector `json:"apiURL,omitempty"` // channel defines the channel or user to send notifications to. + // +kubebuilder:validation:MinLength=1 // +optional - Channel string `json:"channel,omitempty"` + Channel *string `json:"channel,omitempty"` // username defines the slack bot user name. + // +kubebuilder:validation:MinLength=1 // +optional - Username string `json:"username,omitempty"` + Username *string `json:"username,omitempty"` // color defines the color of the left border of the Slack message attachment. // Can be a hex color code (e.g., "#ff0000") or a predefined color name. + // +kubebuilder:validation:MinLength=1 // +optional - Color string `json:"color,omitempty"` + Color *string `json:"color,omitempty"` // title defines the title text displayed in the Slack message attachment. + // +kubebuilder:validation:MinLength=1 // +optional - Title string `json:"title,omitempty"` + Title *string `json:"title,omitempty"` // titleLink defines the URL that the title will link to when clicked. // +optional - TitleLink string `json:"titleLink,omitempty"` + TitleLink *URL `json:"titleLink,omitempty"` // pretext defines optional text that appears above the message attachment block. + // +kubebuilder:validation:MinLength=1 // +optional - Pretext string `json:"pretext,omitempty"` + Pretext *string `json:"pretext,omitempty"` // text defines the main text content of the Slack message attachment. + // +kubebuilder:validation:MinLength=1 // +optional - Text string `json:"text,omitempty"` + Text *string `json:"text,omitempty"` // fields defines a list of Slack fields that are sent with each notification. + // +kubebuilder:validation:MinItems=1 + // +listType=atomic // +optional Fields []SlackField `json:"fields,omitempty"` // shortFields determines whether fields are displayed in a compact format. // When true, fields are shown side by side when possible. // +optional - ShortFields bool `json:"shortFields,omitempty"` + ShortFields *bool `json:"shortFields,omitempty"` // nolint:kubeapilinter // footer defines small text displayed at the bottom of the message attachment. + // +kubebuilder:validation:MinLength=1 // +optional - Footer string `json:"footer,omitempty"` + Footer *string `json:"footer,omitempty"` // fallback defines a plain-text summary of the attachment for clients that don't support attachments. + // +kubebuilder:validation:MinLength=1 // +optional - Fallback string `json:"fallback,omitempty"` + Fallback *string `json:"fallback,omitempty"` // callbackId defines an identifier for the message used in interactive components. + // +kubebuilder:validation:MinLength=1 // +optional - CallbackID string `json:"callbackId,omitempty"` + CallbackID *string `json:"callbackId,omitempty"` // iconEmoji defines the emoji to use as the bot's avatar (e.g., ":ghost:"). + // +kubebuilder:validation:MinLength=1 // +optional - IconEmoji string `json:"iconEmoji,omitempty"` + IconEmoji *string `json:"iconEmoji,omitempty"` // iconURL defines the URL to an image to use as the bot's avatar. // +optional - IconURL string `json:"iconURL,omitempty"` + IconURL *URL `json:"iconURL,omitempty"` // imageURL defines the URL to an image file that will be displayed inside the message attachment. // +optional - ImageURL string `json:"imageURL,omitempty"` + ImageURL *URL `json:"imageURL,omitempty"` // thumbURL defines the URL to an image file that will be displayed as a thumbnail // on the right side of the message attachment. // +optional - ThumbURL string `json:"thumbURL,omitempty"` + ThumbURL *URL `json:"thumbURL,omitempty"` // linkNames enables automatic linking of channel names and usernames in the message. // When true, @channel and @username will be converted to clickable links. // +optional - LinkNames bool `json:"linkNames,omitempty"` + LinkNames *bool `json:"linkNames,omitempty"` // nolint:kubeapilinter // mrkdwnIn defines which fields should be parsed as Slack markdown. // Valid values include "pretext", "text", and "fields". + // +listType=atomic + // +kubebuilder:validation:MinItems=1 + // +kubebuilder:validation:items:MinLength=1 // +optional MrkdwnIn []string `json:"mrkdwnIn,omitempty"` // actions defines a list of Slack actions that are sent with each notification. + // +kubebuilder:validation:MinItems=1 + // +listType=atomic // +optional Actions []SlackAction `json:"actions,omitempty"` // httpConfig defines the HTTP client configuration. // +optional HTTPConfig *HTTPConfig `json:"httpConfig,omitempty"` + // timeout defines the maximum time to wait for a webhook request to complete, + // before failing the request and allowing it to be retried. + // It requires Alertmanager >= v0.30.0. + // +optional + Timeout *monitoringv1.Duration `json:"timeout,omitempty"` } // Validate ensures SlackConfig is valid. @@ -448,19 +521,22 @@ type SlackAction struct { // url defines the URL to open when the action is triggered. // Only applicable for button-type actions. When set, clicking the button opens this URL. // +optional - URL string `json:"url,omitempty"` + URL *URL `json:"url,omitempty"` // style defines the visual appearance of the action element. // Valid values include "default", "primary" (green), and "danger" (red). + // +kubebuilder:validation:MinLength=1 // +optional - Style string `json:"style,omitempty"` + Style *string `json:"style,omitempty"` // name defines a unique identifier for the action within the message. // This value is sent back to your application when the action is triggered. + // +kubebuilder:validation:MinLength=1 // +optional - Name string `json:"name,omitempty"` + Name *string `json:"name,omitempty"` // value defines the payload sent when the action is triggered. // This data is included in the callback sent to your application. + // +kubebuilder:validation:MinLength=1 // +optional - Value string `json:"value,omitempty"` + Value *string `json:"value,omitempty"` // confirm defines an optional confirmation dialog that appears before the action is executed. // When set, users must confirm their intent before the action proceeds. // +optional @@ -477,7 +553,7 @@ func (sa *SlackAction) Validate() error { return errors.New("missing text in Slack action configuration") } - if sa.URL == "" && sa.Name == "" { + if ptr.Deref(sa.URL, "") == "" && ptr.Deref(sa.Name, "") == "" { return errors.New("missing name or url in Slack action configuration") } @@ -503,16 +579,19 @@ type SlackConfirmationField struct { Text string `json:"text"` // title defines the title text displayed at the top of the confirmation dialog. // When not specified, a default title will be used. + // +kubebuilder:validation:MinLength=1 // +optional - Title string `json:"title,omitempty"` + Title *string `json:"title,omitempty"` // okText defines the label for the confirmation button in the dialog. // When not specified, defaults to "Okay". This button proceeds with the action. + // +kubebuilder:validation:MinLength=1 // +optional - OkText string `json:"okText,omitempty"` + OkText *string `json:"okText,omitempty"` // dismissText defines the label for the cancel button in the dialog. // When not specified, defaults to "Cancel". This button cancels the action. + // +kubebuilder:validation:MinLength=1 // +optional - DismissText string `json:"dismissText,omitempty"` + DismissText *string `json:"dismissText,omitempty"` } // Validate ensures SlackConfirmationField is valid. @@ -542,7 +621,7 @@ type SlackField struct { // When true, Slack may display this field side by side with other short fields. // When false or not specified, the field takes the full width of the message. // +optional - Short *bool `json:"short,omitempty"` + Short *bool `json:"short,omitempty"` // nolint:kubeapilinter } // Validate ensures SlackField is valid @@ -563,11 +642,11 @@ func (sf *SlackField) Validate() error { type WebhookConfig struct { // sendResolved defines whether or not to notify about resolved alerts. // +optional - SendResolved *bool `json:"sendResolved,omitempty"` + SendResolved *bool `json:"sendResolved,omitempty"` // nolint:kubeapilinter // url defines the URL to send HTTP POST requests to. // urlSecret takes precedence over url. One of urlSecret and url should be defined. // +optional - URL *string `json:"url,omitempty"` + URL *URL `json:"url,omitempty"` // urlSecret defines the secret's key that contains the webhook URL to send HTTP requests to. // urlSecret takes precedence over url. One of urlSecret and url should be defined. // The secret needs to be in the same namespace as the AlertmanagerConfig @@ -594,7 +673,7 @@ type WebhookConfig struct { type OpsGenieConfig struct { // sendResolved defines whether or not to notify about resolved alerts. // +optional - SendResolved *bool `json:"sendResolved,omitempty"` + SendResolved *bool `json:"sendResolved,omitempty"` // nolint:kubeapilinter // apiKey defines the secret's key that contains the OpsGenie API key. // The secret needs to be in the same namespace as the AlertmanagerConfig // object and accessible by the Prometheus Operator. @@ -603,7 +682,7 @@ type OpsGenieConfig struct { // apiURL defines the URL to send OpsGenie API requests to. // When not specified, defaults to the standard OpsGenie API endpoint. // +optional - APIURL string `json:"apiURL,omitempty"` + APIURL *URL `json:"apiURL,omitempty"` // message defines the alert text limited to 130 characters. // This appears as the main alert title in OpsGenie. // +optional @@ -631,13 +710,15 @@ type OpsGenieConfig struct { // updateAlerts defines Whether to update message and description of the alert in OpsGenie if it already exists // By default, the alert is never updated in OpsGenie, the new message only appears in activity log. // +optional - UpdateAlerts *bool `json:"updateAlerts,omitempty"` + UpdateAlerts *bool `json:"updateAlerts,omitempty"` // nolint:kubeapilinter // details defines a set of arbitrary key/value pairs that provide further detail about the incident. // These appear as additional fields in the OpsGenie alert. + // +listType=atomic // +optional Details []KeyValue `json:"details,omitempty"` // responders defines the list of responders responsible for notifications. // These determine who gets notified when the alert is created. + // +listType=atomic // +optional Responders []OpsGenieConfigResponder `json:"responders,omitempty"` // httpConfig defines the HTTP client configuration for OpsGenie API requests. @@ -748,12 +829,12 @@ type HTTPConfig struct { // followRedirects specifies whether the client should follow HTTP 3xx redirects. // When true, the client will automatically follow redirect responses. // +optional - FollowRedirects *bool `json:"followRedirects,omitempty"` + FollowRedirects *bool `json:"followRedirects,omitempty"` // nolint:kubeapilinter // enableHttp2 can be used to disable HTTP2. // // +optional - EnableHTTP2 *bool `json:"enableHttp2,omitempty"` + EnableHTTP2 *bool `json:"enableHttp2,omitempty"` // nolint:kubeapilinter } // WebexConfig configures notification via Cisco Webex @@ -761,7 +842,7 @@ type HTTPConfig struct { type WebexConfig struct { // sendResolved defines whether or not to notify about resolved alerts. // +optional - SendResolved *bool `json:"sendResolved,omitempty"` + SendResolved *bool `json:"sendResolved,omitempty"` // nolint:kubeapilinter // apiURL defines the Webex Teams API URL i.e. https://webexapis.com/v1/messages // +optional @@ -786,7 +867,7 @@ type WebexConfig struct { type WeChatConfig struct { // sendResolved defines whether or not to notify about resolved alerts. // +optional - SendResolved *bool `json:"sendResolved,omitempty"` + SendResolved *bool `json:"sendResolved,omitempty"` // nolint:kubeapilinter // apiSecret defines the secret's key that contains the WeChat API key. // The secret needs to be in the same namespace as the AlertmanagerConfig // object and accessible by the Prometheus Operator. @@ -795,7 +876,7 @@ type WeChatConfig struct { // apiURL defines the WeChat API URL. // When not specified, defaults to the standard WeChat Work API endpoint. // +optional - APIURL string `json:"apiURL,omitempty"` + APIURL *URL `json:"apiURL,omitempty"` // corpID defines the corp id for authentication. // This is the unique identifier for your WeChat Work organization. // +optional @@ -833,7 +914,7 @@ type WeChatConfig struct { type EmailConfig struct { // sendResolved defines whether or not to notify about resolved alerts. // +optional - SendResolved *bool `json:"sendResolved,omitempty"` + SendResolved *bool `json:"sendResolved,omitempty"` // nolint:kubeapilinter // to defines the email address to send notifications to. // This is the recipient address for alert notifications. // +optional @@ -871,6 +952,7 @@ type EmailConfig struct { AuthIdentity string `json:"authIdentity,omitempty"` // headers defines additional email header key/value pairs. // These override any headers previously set by the notification implementation. + // +listType=atomic // +optional Headers []KeyValue `json:"headers,omitempty"` // html defines the HTML body of the email notification. @@ -884,7 +966,7 @@ type EmailConfig struct { // requireTLS defines the SMTP TLS requirement. // Note that Go does not support unencrypted connections to remote SMTP endpoints. // +optional - RequireTLS *bool `json:"requireTLS,omitempty"` + RequireTLS *bool `json:"requireTLS,omitempty"` // nolint:kubeapilinter // tlsConfig defines the TLS configuration for SMTP connections. // This includes settings for certificates, CA validation, and TLS protocol options. // +optional @@ -896,7 +978,7 @@ type EmailConfig struct { type VictorOpsConfig struct { // sendResolved defines whether or not to notify about resolved alerts. // +optional - SendResolved *bool `json:"sendResolved,omitempty"` + SendResolved *bool `json:"sendResolved,omitempty"` // nolint:kubeapilinter // apiKey defines the secret's key that contains the API key to use when talking to the VictorOps API. // The secret needs to be in the same namespace as the AlertmanagerConfig // object and accessible by the Prometheus Operator. @@ -905,29 +987,35 @@ type VictorOpsConfig struct { // apiUrl defines the VictorOps API URL. // When not specified, defaults to the standard VictorOps API endpoint. // +optional - APIURL string `json:"apiUrl,omitempty"` + APIURL *URL `json:"apiUrl,omitempty"` // routingKey defines a key used to map the alert to a team. // This determines which VictorOps team will receive the alert notification. - // +optional + // +kubebuilder:validation:MinLength=1 + // +required RoutingKey string `json:"routingKey"` // messageType describes the behavior of the alert. // Valid values are "CRITICAL", "WARNING", and "INFO". + // +kubebuilder:validation:MinLength=1 // +optional - MessageType string `json:"messageType,omitempty"` + MessageType *string `json:"messageType,omitempty"` // entityDisplayName contains a summary of the alerted problem. // This appears as the main title or identifier for the incident. + // +kubebuilder:validation:MinLength=1 // +optional - EntityDisplayName string `json:"entityDisplayName,omitempty"` + EntityDisplayName *string `json:"entityDisplayName,omitempty"` // stateMessage contains a long explanation of the alerted problem. // This provides detailed context about the incident. + // +kubebuilder:validation:MinLength=1 // +optional - StateMessage string `json:"stateMessage,omitempty"` + StateMessage *string `json:"stateMessage,omitempty"` // monitoringTool defines the monitoring tool the state message is from. // This helps identify the source system that generated the alert. + // +kubebuilder:validation:MinLength=1 // +optional - MonitoringTool string `json:"monitoringTool,omitempty"` + MonitoringTool *string `json:"monitoringTool,omitempty"` // customFields defines additional custom fields for notification. // These provide extra metadata that will be included with the VictorOps incident. + // +listType=atomic // +optional CustomFields []KeyValue `json:"customFields,omitempty"` // httpConfig defines the HTTP client's configuration for VictorOps API requests. @@ -940,7 +1028,7 @@ type VictorOpsConfig struct { type PushoverConfig struct { // sendResolved defines whether or not to notify about resolved alerts. // +optional - SendResolved *bool `json:"sendResolved,omitempty"` + SendResolved *bool `json:"sendResolved,omitempty"` // nolint:kubeapilinter // userKey defines the secret's key that contains the recipient user's user key. // The secret needs to be in the same namespace as the AlertmanagerConfig // object and accessible by the Prometheus Operator. @@ -950,6 +1038,7 @@ type PushoverConfig struct { // userKeyFile defines the user key file that contains the recipient user's user key. // Either `userKey` or `userKeyFile` is required. // It requires Alertmanager >= v0.26.0. + // +kubebuilder:validation:MinLength=1 // +optional UserKeyFile *string `json:"userKeyFile,omitempty"` // token defines the secret's key that contains the registered application's API token. @@ -963,58 +1052,66 @@ type PushoverConfig struct { // See https://pushover.net/apps for application registration. // Either `token` or `tokenFile` is required. // It requires Alertmanager >= v0.26.0. + // +kubebuilder:validation:MinLength=1 // +optional TokenFile *string `json:"tokenFile,omitempty"` // title defines the notification title displayed in the Pushover message. // This appears as the bold header text in the notification. + // +kubebuilder:validation:MinLength=1 // +optional - Title string `json:"title,omitempty"` + Title *string `json:"title,omitempty"` // message defines the notification message content. // This is the main body text of the Pushover notification. + // +kubebuilder:validation:MinLength=1 // +optional - Message string `json:"message,omitempty"` + Message *string `json:"message,omitempty"` // url defines a supplementary URL shown alongside the message. // This creates a clickable link within the Pushover notification. // +optional - URL string `json:"url,omitempty"` + URL *URL `json:"url,omitempty"` // urlTitle defines a title for the supplementary URL. // If not specified, the raw URL is shown instead. + // +kubebuilder:validation:MinLength=1 // +optional - URLTitle string `json:"urlTitle,omitempty"` + URLTitle *string `json:"urlTitle,omitempty"` // ttl defines the time to live for the alert notification. // This determines how long the notification remains active before expiring. // +optional TTL *monitoringv1.Duration `json:"ttl,omitempty"` // device defines the name of a specific device to send the notification to. // If not specified, the notification is sent to all user's devices. + // +kubebuilder:validation:MinLength=1 // +optional Device *string `json:"device,omitempty"` // sound defines the name of one of the sounds supported by device clients. // This overrides the user's default sound choice for this notification. + // +kubebuilder:validation:MinLength=1 // +optional - Sound string `json:"sound,omitempty"` + Sound *string `json:"sound,omitempty"` // priority defines the notification priority level. // See https://pushover.net/api#priority for valid values and behavior. + // +kubebuilder:validation:MinLength=1 // +optional - Priority string `json:"priority,omitempty"` + Priority *string `json:"priority,omitempty"` // retry defines how often the Pushover servers will send the same notification to the user. // Must be at least 30 seconds. Only applies to priority 2 notifications. // +kubebuilder:validation:Pattern=`^(([0-9]+)y)?(([0-9]+)w)?(([0-9]+)d)?(([0-9]+)h)?(([0-9]+)m)?(([0-9]+)s)?(([0-9]+)ms)?$` // +optional - Retry string `json:"retry,omitempty"` + Retry *string `json:"retry,omitempty"` // expire defines how long your notification will continue to be retried for, // unless the user acknowledges the notification. Only applies to priority 2 notifications. // +kubebuilder:validation:Pattern=`^(([0-9]+)y)?(([0-9]+)w)?(([0-9]+)d)?(([0-9]+)h)?(([0-9]+)m)?(([0-9]+)s)?(([0-9]+)ms)?$` // +optional - Expire string `json:"expire,omitempty"` + Expire *string `json:"expire,omitempty"` // html defines whether notification message is HTML or plain text. // When true, the message can include HTML formatting tags. + // html and monospace formatting are mutually exclusive. // +optional - HTML *bool `json:"html,omitempty"` + HTML *bool `json:"html,omitempty"` //nolint:kubeapilinter // monospace optional HTML/monospace formatting for the message, see https://pushover.net/api#html // html and monospace formatting are mutually exclusive. // +optional - Monospace *bool `json:"monospace,omitempty"` + Monospace *bool `json:"monospace,omitempty"` //nolint:kubeapilinter // httpConfig defines the HTTP client configuration for Pushover API requests. // +optional HTTPConfig *HTTPConfig `json:"httpConfig,omitempty"` @@ -1025,7 +1122,7 @@ type PushoverConfig struct { type SNSConfig struct { // sendResolved defines whether or not to notify about resolved alerts. // +optional - SendResolved *bool `json:"sendResolved,omitempty"` + SendResolved *bool `json:"sendResolved,omitempty"` // nolint:kubeapilinter // apiURL defines the SNS API URL, e.g. https://sns.us-east-2.amazonaws.com. // If not specified, the SNS API URL from the SNS SDK will be used. // +optional @@ -1057,6 +1154,7 @@ type SNSConfig struct { // attributes defines SNS message attributes as key-value pairs. // These provide additional metadata that can be used for message filtering and routing. // +optional + //nolint:kubeapilinter Attributes map[string]string `json:"attributes,omitempty"` // httpConfig defines the HTTP client configuration for SNS API requests. // +optional @@ -1068,11 +1166,11 @@ type SNSConfig struct { type TelegramConfig struct { // sendResolved defines whether or not to notify about resolved alerts. // +optional - SendResolved *bool `json:"sendResolved,omitempty"` + SendResolved *bool `json:"sendResolved,omitempty"` // nolint:kubeapilinter // apiURL defines the Telegram API URL, e.g. https://api.telegram.org. // If not specified, the default Telegram API URL will be used. // +optional - APIURL string `json:"apiURL,omitempty"` + APIURL *URL `json:"apiURL,omitempty"` // botToken defines the Telegram bot token. It is mutually exclusive with `botTokenFile`. // The secret needs to be in the same namespace as the AlertmanagerConfig // object and accessible by the Prometheus Operator. @@ -1101,7 +1199,7 @@ type TelegramConfig struct { // disableNotifications controls whether Telegram notifications are sent silently. // When true, users will receive the message without notification sounds. // +optional - DisableNotifications *bool `json:"disableNotifications,omitempty"` + DisableNotifications *bool `json:"disableNotifications,omitempty"` // nolint:kubeapilinter // parseMode defines the parse mode for telegram message formatting. // Valid values are "MarkdownV2", "Markdown", and "HTML". // This determines how text formatting is interpreted in the message. @@ -1118,7 +1216,7 @@ type TelegramConfig struct { type MSTeamsConfig struct { // sendResolved defines whether or not to notify about resolved alerts. // +optional - SendResolved *bool `json:"sendResolved,omitempty"` + SendResolved *bool `json:"sendResolved,omitempty"` // nolint:kubeapilinter // webhookUrl defines the MSTeams webhook URL for sending notifications. // This is the incoming webhook URL configured in your Teams channel. // +required @@ -1147,7 +1245,7 @@ type MSTeamsConfig struct { type MSTeamsV2Config struct { // sendResolved defines whether or not to notify about resolved alerts. // +optional - SendResolved *bool `json:"sendResolved,omitempty"` + SendResolved *bool `json:"sendResolved,omitempty"` // nolint:kubeapilinter // webhookURL defines the MSTeams incoming webhook URL for adaptive card notifications. // This webhook must support the newer adaptive cards format required by Teams flows. // +optional @@ -1172,7 +1270,7 @@ type MSTeamsV2Config struct { type RocketChatConfig struct { // sendResolved defines whether or not to notify about resolved alerts. // +optional - SendResolved *bool `json:"sendResolved,omitempty"` + SendResolved *bool `json:"sendResolved,omitempty"` // nolint:kubeapilinter // apiURL defines the API URL for RocketChat. // Defaults to https://open.rocket.chat/ if not specified. // +optional @@ -1221,13 +1319,14 @@ type RocketChatConfig struct { TitleLink *string `json:"titleLink,omitempty"` // fields defines additional fields for the message attachment. // These appear as structured key-value pairs within the message. + // +listType=atomic // +kubebuilder:validation:MinItems=1 // +optional Fields []RocketChatFieldConfig `json:"fields,omitempty"` // shortFields defines whether to use short fields in the message layout. // When true, fields may be displayed side by side to save space. // +optional - ShortFields *bool `json:"shortFields,omitempty"` + ShortFields *bool `json:"shortFields,omitempty"` // nolint:kubeapilinter // imageURL defines the image URL to display within the message. // This embeds an image directly in the message attachment. // +optional @@ -1239,9 +1338,10 @@ type RocketChatConfig struct { // linkNames defines whether to enable automatic linking of usernames and channels. // When true, @username and #channel references become clickable links. // +optional - LinkNames *bool `json:"linkNames,omitempty"` + LinkNames *bool `json:"linkNames,omitempty"` // nolint:kubeapilinter // actions defines interactive actions to include in the message. // These appear as buttons that users can click to trigger responses. + // +listType=atomic // +kubebuilder:validation:MinItems=1 // +optional Actions []RocketChatActionConfig `json:"actions,omitempty"` @@ -1265,7 +1365,7 @@ type RocketChatFieldConfig struct { // short defines whether this field should be a short field. // When true, the field may be displayed inline with other short fields to save space. // +optional - Short *bool `json:"short,omitempty"` + Short *bool `json:"short,omitempty"` // nolint:kubeapilinter } // RocketChatActionConfig defines actions for RocketChat messages. @@ -1293,15 +1393,18 @@ type InhibitRule struct { // targetMatch defines matchers that have to be fulfilled in the alerts to be muted. // The operator enforces that the alert matches the resource's namespace. // When these conditions are met, matching alerts will be inhibited (silenced). + // +listType=atomic // +optional TargetMatch []Matcher `json:"targetMatch,omitempty"` // sourceMatch defines matchers for which one or more alerts have to exist for the inhibition // to take effect. The operator enforces that the alert matches the resource's namespace. // These are the "trigger" alerts that cause other alerts to be inhibited. + // +listType=atomic // +optional SourceMatch []Matcher `json:"sourceMatch,omitempty"` // equal defines labels that must have an equal value in the source and target alert // for the inhibition to take effect. This ensures related alerts are properly grouped. + // +listType=atomic // +optional Equal []string `json:"equal,omitempty"` } @@ -1339,7 +1442,7 @@ type Matcher struct { // regex defines whether to match on equality (false) or regular-expression (true). // Deprecated: for AlertManager >= v0.22.0, `matchType` should be used instead. // +optional - Regex bool `json:"regex,omitempty"` + Regex bool `json:"regex,omitempty"` // nolint:kubeapilinter } // String returns Matcher as a string @@ -1420,6 +1523,7 @@ type MuteTimeInterval struct { // +required Name string `json:"name,omitempty"` // timeIntervals defines a list of TimeInterval + // +listType=atomic // +optional TimeIntervals []TimeInterval `json:"timeIntervals,omitempty"` } @@ -1427,18 +1531,23 @@ type MuteTimeInterval struct { // TimeInterval describes intervals of time type TimeInterval struct { // times defines a list of TimeRange + // +listType=atomic // +optional Times []TimeRange `json:"times,omitempty"` // weekdays defines a list of WeekdayRange + // +listType=atomic // +optional Weekdays []WeekdayRange `json:"weekdays,omitempty"` // daysOfMonth defines a list of DayOfMonthRange + // +listType=atomic // +optional DaysOfMonth []DayOfMonthRange `json:"daysOfMonth,omitempty"` // months defines a list of MonthRange + // +listType=atomic // +optional Months []MonthRange `json:"months,omitempty"` // years defines a list of YearRange + // +listType=atomic // +optional Years []YearRange `json:"years,omitempty"` } diff --git a/vendor/github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1alpha1/prometheusagent_types.go b/vendor/github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1alpha1/prometheusagent_types.go index 5172a5ce8e8..e9dfdad6959 100644 --- a/vendor/github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1alpha1/prometheusagent_types.go +++ b/vendor/github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1alpha1/prometheusagent_types.go @@ -103,6 +103,11 @@ func (l *PrometheusAgentList) DeepCopyObject() runtime.Object { // +kubebuilder:validation:XValidation:rule="!(has(self.mode) && self.mode == 'DaemonSet' && has(self.persistentVolumeClaimRetentionPolicy))",message="persistentVolumeClaimRetentionPolicy cannot be set when mode is DaemonSet" // +kubebuilder:validation:XValidation:rule="!(has(self.mode) && self.mode == 'DaemonSet' && has(self.scrapeConfigSelector))",message="scrapeConfigSelector cannot be set when mode is DaemonSet" // +kubebuilder:validation:XValidation:rule="!(has(self.mode) && self.mode == 'DaemonSet' && has(self.probeSelector))",message="probeSelector cannot be set when mode is DaemonSet" +// +kubebuilder:validation:XValidation:rule="!(has(self.mode) && self.mode == 'DaemonSet' && has(self.scrapeConfigNamespaceSelector))",message="scrapeConfigNamespaceSelector cannot be set when mode is DaemonSet" +// +kubebuilder:validation:XValidation:rule="!(has(self.mode) && self.mode == 'DaemonSet' && has(self.probeNamespaceSelector))",message="probeNamespaceSelector cannot be set when mode is DaemonSet" +// +kubebuilder:validation:XValidation:rule="!(has(self.mode) && self.mode == 'DaemonSet' && has(self.serviceMonitorSelector))",message="serviceMonitorSelector cannot be set when mode is DaemonSet" +// +kubebuilder:validation:XValidation:rule="!(has(self.mode) && self.mode == 'DaemonSet' && has(self.serviceMonitorNamespaceSelector))",message="serviceMonitorNamespaceSelector cannot be set when mode is DaemonSet" +// +kubebuilder:validation:XValidation:rule="!(has(self.mode) && self.mode == 'DaemonSet' && has(self.additionalScrapeConfigs))",message="additionalScrapeConfigs cannot be set when mode is DaemonSet" type PrometheusAgentSpec struct { // mode defines how the Prometheus operator deploys the PrometheusAgent pod(s). // diff --git a/vendor/github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1alpha1/scrapeconfig_types.go b/vendor/github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1alpha1/scrapeconfig_types.go index 828a05abcce..972ac16dedc 100644 --- a/vendor/github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1alpha1/scrapeconfig_types.go +++ b/vendor/github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1alpha1/scrapeconfig_types.go @@ -40,7 +40,7 @@ type SDFile string type NamespaceDiscovery struct { // ownNamespace includes the namespace in which the Prometheus pod runs to the list of watched namespaces. // +optional - IncludeOwnNamespace *bool `json:"ownNamespace,omitempty"` + IncludeOwnNamespace *bool `json:"ownNamespace,omitempty"` // nolint:kubeapilinter // names defines a list of namespaces where to watch for resources. // If empty and `ownNamespace` isn't true, Prometheus watches for resources in all namespaces. // +listType=set @@ -55,7 +55,7 @@ type AttachMetadata struct { // Only valid for Pod, Endpoint and Endpointslice roles. // // +optional - Node *bool `json:"node,omitempty"` + Node *bool `json:"node,omitempty"` // nolint:kubeapilinter } // Filter name and value pairs to limit the discovery process to a subset of available resources. @@ -279,21 +279,22 @@ type ScrapeConfigSpec struct { // honorTimestamps defines whether Prometheus preserves the timestamps // when exposed by the target. // +optional - HonorTimestamps *bool `json:"honorTimestamps,omitempty"` + HonorTimestamps *bool `json:"honorTimestamps,omitempty"` // nolint:kubeapilinter // trackTimestampsStaleness defines whether Prometheus tracks staleness of // the metrics that have an explicit timestamp present in scraped data. // Has no effect if `honorTimestamps` is false. // It requires Prometheus >= v2.48.0. // // +optional - TrackTimestampsStaleness *bool `json:"trackTimestampsStaleness,omitempty"` + TrackTimestampsStaleness *bool `json:"trackTimestampsStaleness,omitempty"` // nolint:kubeapilinter // honorLabels defines when true the metric's labels when they collide // with the target's labels. // +optional - HonorLabels *bool `json:"honorLabels,omitempty"` + HonorLabels *bool `json:"honorLabels,omitempty"` // nolint:kubeapilinter // params defines optional HTTP URL parameters // +mapType:=atomic // +optional + //nolint:kubeapilinter Params map[string][]string `json:"params,omitempty"` // scheme defines the protocol scheme used for requests. // +optional @@ -304,10 +305,10 @@ type ScrapeConfigSpec struct { // // If unset, Prometheus uses true by default. // +optional - EnableCompression *bool `json:"enableCompression,omitempty"` + EnableCompression *bool `json:"enableCompression,omitempty"` // nolint:kubeapilinter // enableHTTP2 defines whether to enable HTTP2. // +optional - EnableHTTP2 *bool `json:"enableHTTP2,omitempty"` + EnableHTTP2 *bool `json:"enableHTTP2,omitempty"` // nolint:kubeapilinter // basicAuth defines information to use on every scrape request. // +optional BasicAuth *v1.BasicAuth `json:"basicAuth,omitempty"` @@ -384,6 +385,7 @@ type StaticConfig struct { // labels defines labels assigned to all metrics scraped from the targets. // +mapType:=atomic // +optional + //nolint:kubeapilinter Labels map[string]string `json:"labels,omitempty"` } @@ -437,10 +439,10 @@ type HTTPSDConfig struct { TLSConfig *v1.SafeTLSConfig `json:"tlsConfig,omitempty"` // followRedirects defines whether HTTP requests follow HTTP 3xx redirects. // +optional - FollowRedirects *bool `json:"followRedirects,omitempty"` + FollowRedirects *bool `json:"followRedirects,omitempty"` // nolint:kubeapilinter // enableHTTP2 defines whether to enable HTTP2. // +optional - EnableHTTP2 *bool `json:"enableHTTP2,omitempty"` + EnableHTTP2 *bool `json:"enableHTTP2,omitempty"` // nolint:kubeapilinter } // KubernetesSDConfig allows retrieving scrape targets from Kubernetes' REST API. @@ -488,10 +490,10 @@ type KubernetesSDConfig struct { v1.ProxyConfig `json:",inline"` // followRedirects defines whether HTTP requests follow HTTP 3xx redirects. // +optional - FollowRedirects *bool `json:"followRedirects,omitempty"` + FollowRedirects *bool `json:"followRedirects,omitempty"` // nolint:kubeapilinter // enableHTTP2 defines whether to enable HTTP2. // +optional - EnableHTTP2 *bool `json:"enableHTTP2,omitempty"` + EnableHTTP2 *bool `json:"enableHTTP2,omitempty"` // nolint:kubeapilinter // tlsConfig defines the TLS configuration to connect to the Kubernetes API. // +optional TLSConfig *v1.SafeTLSConfig `json:"tlsConfig,omitempty"` @@ -549,6 +551,7 @@ type ConsulSDConfig struct { // Starting with Consul 1.14, it is recommended to use `filter` with the `NodeMeta` selector instead. // +mapType:=atomic // +optional + //nolint:kubeapilinter NodeMeta map[string]string `json:"nodeMeta,omitempty"` // filter defines the filter expression used to filter the catalog results. // See https://www.consul.io/api-docs/catalog#list-services @@ -559,7 +562,7 @@ type ConsulSDConfig struct { // allowStale Consul results (see https://www.consul.io/api/features/consistency.html). Will reduce load on Consul. // If unset, Prometheus uses its default value. // +optional - AllowStale *bool `json:"allowStale,omitempty"` + AllowStale *bool `json:"allowStale,omitempty"` // nolint:kubeapilinter // refreshInterval defines the time after which the provided names are refreshed. // If not set, Prometheus uses its default value. // +optional @@ -580,10 +583,10 @@ type ConsulSDConfig struct { v1.ProxyConfig `json:",inline"` // followRedirects defines whether HTTP requests follow HTTP 3xx redirects. // +optional - FollowRedirects *bool `json:"followRedirects,omitempty"` + FollowRedirects *bool `json:"followRedirects,omitempty"` // nolint:kubeapilinter // enableHTTP2 defines whether to enable HTTP2. // +optional - EnableHttp2 *bool `json:"enableHTTP2,omitempty"` + EnableHttp2 *bool `json:"enableHTTP2,omitempty"` // nolint:kubeapilinter // tlsConfig defines the TLS configuration to connect to the Consul API. // +optional TLSConfig *v1.SafeTLSConfig `json:"tlsConfig,omitempty"` @@ -679,11 +682,11 @@ type EC2SDConfig struct { // followRedirects defines whether HTTP requests follow HTTP 3xx redirects. // It requires Prometheus >= v2.41.0 // +optional - FollowRedirects *bool `json:"followRedirects,omitempty"` + FollowRedirects *bool `json:"followRedirects,omitempty"` // nolint:kubeapilinter // enableHTTP2 defines whether to enable HTTP2. // It requires Prometheus >= v2.41.0 // +optional - EnableHTTP2 *bool `json:"enableHTTP2,omitempty"` + EnableHTTP2 *bool `json:"enableHTTP2,omitempty"` // nolint:kubeapilinter } // +kubebuilder:validation:Enum=OAuth;ManagedIdentity;SDK @@ -756,10 +759,10 @@ type AzureSDConfig struct { v1.ProxyConfig `json:",inline"` // followRedirects defines whether HTTP requests follow HTTP 3xx redirects. // +optional - FollowRedirects *bool `json:"followRedirects,omitempty"` + FollowRedirects *bool `json:"followRedirects,omitempty"` // nolint:kubeapilinter // enableHTTP2 defines whether to enable HTTP2. // +optional - EnableHTTP2 *bool `json:"enableHTTP2,omitempty"` + EnableHTTP2 *bool `json:"enableHTTP2,omitempty"` // nolint:kubeapilinter // tlsConfig defies the TLS configuration applying to the target HTTP endpoint. // +optional TLSConfig *v1.SafeTLSConfig `json:"tlsConfig,omitempty"` @@ -890,7 +893,7 @@ type OpenStackSDConfig struct { // allTenants defines whether the service discovery should list all instances for all projects. // It is only relevant for the 'instance' role and usually requires admin permissions. // +optional - AllTenants *bool `json:"allTenants,omitempty"` + AllTenants *bool `json:"allTenants,omitempty"` // nolint:kubeapilinter // refreshInterval defines the time after which the provided names are refreshed. // If not set, Prometheus uses its default value. // +optional @@ -927,10 +930,10 @@ type DigitalOceanSDConfig struct { v1.ProxyConfig `json:",inline"` // followRedirects defines whether HTTP requests follow HTTP 3xx redirects. // +optional - FollowRedirects *bool `json:"followRedirects,omitempty"` + FollowRedirects *bool `json:"followRedirects,omitempty"` // nolint:kubeapilinter // enableHTTP2 defines whether to enable HTTP2. // +optional - EnableHTTP2 *bool `json:"enableHTTP2,omitempty"` + EnableHTTP2 *bool `json:"enableHTTP2,omitempty"` // nolint:kubeapilinter // tlsConfig defines the TLS configuration to connect to the Consul API. // +optional TLSConfig *v1.SafeTLSConfig `json:"tlsConfig,omitempty"` @@ -982,10 +985,10 @@ type KumaSDConfig struct { OAuth2 *v1.OAuth2 `json:"oauth2,omitempty"` // followRedirects defines whether HTTP requests follow HTTP 3xx redirects. // +optional - FollowRedirects *bool `json:"followRedirects,omitempty"` + FollowRedirects *bool `json:"followRedirects,omitempty"` // nolint:kubeapilinter // enableHTTP2 defines whether to enable HTTP2. // +optional - EnableHTTP2 *bool `json:"enableHTTP2,omitempty"` + EnableHTTP2 *bool `json:"enableHTTP2,omitempty"` // nolint:kubeapilinter } // Eureka SD configurations allow retrieving scrape targets using the Eureka REST API. @@ -1016,10 +1019,10 @@ type EurekaSDConfig struct { v1.ProxyConfig `json:",inline"` // followRedirects defines whether HTTP requests follow HTTP 3xx redirects. // +optional - FollowRedirects *bool `json:"followRedirects,omitempty"` + FollowRedirects *bool `json:"followRedirects,omitempty"` // nolint:kubeapilinter // enableHTTP2 defines whether to enable HTTP2. // +optional - EnableHTTP2 *bool `json:"enableHTTP2,omitempty"` + EnableHTTP2 *bool `json:"enableHTTP2,omitempty"` // nolint:kubeapilinter // refreshInterval defines the time after which the provided names are refreshed. // If not set, Prometheus uses its default value. // +optional @@ -1056,7 +1059,7 @@ type DockerSDConfig struct { // It requires Prometheus >= v2.54.1. // // +optional - MatchFirstNetwork *bool `json:"matchFirstNetwork,omitempty"` + MatchFirstNetwork *bool `json:"matchFirstNetwork,omitempty"` // nolint:kubeapilinter // filters defines filters to limit the discovery process to a subset of the available resources. // +optional Filters Filters `json:"filters,omitempty"` @@ -1076,10 +1079,10 @@ type DockerSDConfig struct { OAuth2 *v1.OAuth2 `json:"oauth2,omitempty"` // followRedirects defines whether HTTP requests follow HTTP 3xx redirects. // +optional - FollowRedirects *bool `json:"followRedirects,omitempty"` + FollowRedirects *bool `json:"followRedirects,omitempty"` // nolint:kubeapilinter // enableHTTP2 defines whether to enable HTTP2. // +optional - EnableHTTP2 *bool `json:"enableHTTP2,omitempty"` + EnableHTTP2 *bool `json:"enableHTTP2,omitempty"` // nolint:kubeapilinter } // HetznerSDConfig allow retrieving scrape targets from Hetzner Cloud API and Robot API. @@ -1106,10 +1109,10 @@ type HetznerSDConfig struct { v1.ProxyConfig `json:",inline"` // followRedirects defines whether HTTP requests follow HTTP 3xx redirects. // +optional - FollowRedirects *bool `json:"followRedirects,omitempty"` + FollowRedirects *bool `json:"followRedirects,omitempty"` // nolint:kubeapilinter // enableHTTP2 defines whether to enable HTTP2. // +optional - EnableHTTP2 *bool `json:"enableHTTP2,omitempty"` + EnableHTTP2 *bool `json:"enableHTTP2,omitempty"` // nolint:kubeapilinter // tlsConfig defines the TLS configuration to connect to the Consul API. // +optional TLSConfig *v1.SafeTLSConfig `json:"tlsConfig,omitempty"` @@ -1136,7 +1139,7 @@ type NomadSDConfig struct { // allowStale defines the information to access the Nomad API. It is to be defined // as the Nomad documentation requires. // +optional - AllowStale *bool `json:"allowStale,omitempty"` + AllowStale *bool `json:"allowStale,omitempty"` // nolint:kubeapilinter // namespace defines the Nomad namespace to query for service discovery. // When specified, only resources within this namespace will be discovered. // +optional @@ -1176,10 +1179,10 @@ type NomadSDConfig struct { v1.ProxyConfig `json:",inline"` // followRedirects defines whether HTTP requests follow HTTP 3xx redirects. // +optional - FollowRedirects *bool `json:"followRedirects,omitempty"` + FollowRedirects *bool `json:"followRedirects,omitempty"` // nolint:kubeapilinter // enableHTTP2 defines whether to enable HTTP2. // +optional - EnableHTTP2 *bool `json:"enableHTTP2,omitempty"` + EnableHTTP2 *bool `json:"enableHTTP2,omitempty"` // nolint:kubeapilinter } // Service of the targets to retrieve. Must be `VPS` or `DedicatedServer`. @@ -1270,10 +1273,10 @@ type DockerSwarmSDConfig struct { TLSConfig *v1.SafeTLSConfig `json:"tlsConfig,omitempty"` // followRedirects defines whether HTTP requests follow HTTP 3xx redirects. // +optional - FollowRedirects *bool `json:"followRedirects,omitempty"` + FollowRedirects *bool `json:"followRedirects,omitempty"` // nolint:kubeapilinter // enableHTTP2 defines whether to enable HTTP2. // +optional - EnableHTTP2 *bool `json:"enableHTTP2,omitempty"` + EnableHTTP2 *bool `json:"enableHTTP2,omitempty"` // nolint:kubeapilinter } // LinodeSDConfig configurations allow retrieving scrape targets from Linode's Linode APIv4. @@ -1308,13 +1311,13 @@ type LinodeSDConfig struct { v1.ProxyConfig `json:",inline"` // followRedirects defines whether HTTP requests follow HTTP 3xx redirects. // +optional - FollowRedirects *bool `json:"followRedirects,omitempty"` + FollowRedirects *bool `json:"followRedirects,omitempty"` // nolint:kubeapilinter // tlsConfig defines the TLS configuration to connect to the Consul API. // +optional TLSConfig *v1.SafeTLSConfig `json:"tlsConfig,omitempty"` // enableHTTP2 defines whether to enable HTTP2. // +optional - EnableHTTP2 *bool `json:"enableHTTP2,omitempty"` + EnableHTTP2 *bool `json:"enableHTTP2,omitempty"` // nolint:kubeapilinter } // PuppetDBSDConfig configurations allow retrieving scrape targets from PuppetDB resources. @@ -1334,7 +1337,7 @@ type PuppetDBSDConfig struct { // Note: Enabling this exposes parameters in the Prometheus UI and API. Make sure // that you don't have secrets exposed as parameters if you enable this. // +optional - IncludeParameters *bool `json:"includeParameters,omitempty"` + IncludeParameters *bool `json:"includeParameters,omitempty"` // nolint:kubeapilinter // refreshInterval defines the time after which the provided names are refreshed. // If not set, Prometheus uses its default value. // +optional @@ -1362,10 +1365,10 @@ type PuppetDBSDConfig struct { TLSConfig *v1.SafeTLSConfig `json:"tlsConfig,omitempty"` // followRedirects defines whether HTTP requests follow HTTP 3xx redirects. // +optional - FollowRedirects *bool `json:"followRedirects,omitempty"` + FollowRedirects *bool `json:"followRedirects,omitempty"` // nolint:kubeapilinter // enableHTTP2 defines whether to enable HTTP2. // +optional - EnableHTTP2 *bool `json:"enableHTTP2,omitempty"` + EnableHTTP2 *bool `json:"enableHTTP2,omitempty"` // nolint:kubeapilinter } // LightSailSDConfig configurations allow retrieving scrape targets from AWS Lightsail instances. @@ -1416,10 +1419,10 @@ type LightSailSDConfig struct { TLSConfig *v1.SafeTLSConfig `json:"tlsConfig,omitempty"` // followRedirects defines whether HTTP requests follow HTTP 3xx redirects. // +optional - FollowRedirects *bool `json:"followRedirects,omitempty"` + FollowRedirects *bool `json:"followRedirects,omitempty"` // nolint:kubeapilinter // enableHTTP2 defines whether to enable HTTP2. // +optional - EnableHTTP2 *bool `json:"enableHTTP2,omitempty"` + EnableHTTP2 *bool `json:"enableHTTP2,omitempty"` // nolint:kubeapilinter } // Role of the targets to retrieve. Must be `Instance` or `Baremetal`. @@ -1480,10 +1483,10 @@ type ScalewaySDConfig struct { v1.ProxyConfig `json:",inline"` // followRedirects defines whether HTTP requests follow HTTP 3xx redirects. // +optional - FollowRedirects *bool `json:"followRedirects,omitempty"` + FollowRedirects *bool `json:"followRedirects,omitempty"` // nolint:kubeapilinter // enableHTTP2 defines whether to enable HTTP2. // +optional - EnableHTTP2 *bool `json:"enableHTTP2,omitempty"` + EnableHTTP2 *bool `json:"enableHTTP2,omitempty"` // nolint:kubeapilinter // tlsConfig defines the TLS configuration to connect to the Consul API. // +optional TLSConfig *v1.SafeTLSConfig `json:"tlsConfig,omitempty"` @@ -1515,10 +1518,10 @@ type IonosSDConfig struct { TLSConfig *v1.SafeTLSConfig `json:"tlsConfig,omitempty"` // followRedirects defines whether HTTP requests follow HTTP 3xx redirects. // +optional - FollowRedirects *bool `json:"followRedirects,omitempty"` + FollowRedirects *bool `json:"followRedirects,omitempty"` // nolint:kubeapilinter // enableHTTP2 defines whether to enable HTTP2. // +optional - EnableHTTP2 *bool `json:"enableHTTP2,omitempty"` + EnableHTTP2 *bool `json:"enableHTTP2,omitempty"` // nolint:kubeapilinter // oauth2 defines the configuration to use on every scrape request. // +optional OAuth2 *v1.OAuth2 `json:"oauth2,omitempty"` diff --git a/vendor/github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1alpha1/zz_generated.deepcopy.go b/vendor/github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1alpha1/zz_generated.deepcopy.go index f703c33a7ad..a83ae23b42b 100644 --- a/vendor/github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1alpha1/zz_generated.deepcopy.go +++ b/vendor/github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1alpha1/zz_generated.deepcopy.go @@ -30,6 +30,7 @@ func (in *AlertmanagerConfig) DeepCopyInto(out *AlertmanagerConfig) { out.TypeMeta = in.TypeMeta in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) in.Spec.DeepCopyInto(&out.Spec) + in.Status.DeepCopyInto(&out.Status) } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new AlertmanagerConfig. @@ -1794,6 +1795,11 @@ func (in *OpsGenieConfig) DeepCopyInto(out *OpsGenieConfig) { *out = new(corev1.SecretKeySelector) (*in).DeepCopyInto(*out) } + if in.APIURL != nil { + in, out := &in.APIURL, &out.APIURL + *out = new(URL) + **out = **in + } if in.UpdateAlerts != nil { in, out := &in.UpdateAlerts, &out.UpdateAlerts *out = new(bool) @@ -1859,6 +1865,46 @@ func (in *PagerDutyConfig) DeepCopyInto(out *PagerDutyConfig) { *out = new(corev1.SecretKeySelector) (*in).DeepCopyInto(*out) } + if in.URL != nil { + in, out := &in.URL, &out.URL + *out = new(URL) + **out = **in + } + if in.Client != nil { + in, out := &in.Client, &out.Client + *out = new(string) + **out = **in + } + if in.ClientURL != nil { + in, out := &in.ClientURL, &out.ClientURL + *out = new(URL) + **out = **in + } + if in.Description != nil { + in, out := &in.Description, &out.Description + *out = new(string) + **out = **in + } + if in.Severity != nil { + in, out := &in.Severity, &out.Severity + *out = new(string) + **out = **in + } + if in.Class != nil { + in, out := &in.Class, &out.Class + *out = new(string) + **out = **in + } + if in.Group != nil { + in, out := &in.Group, &out.Group + *out = new(string) + **out = **in + } + if in.Component != nil { + in, out := &in.Component, &out.Component + *out = new(string) + **out = **in + } if in.Details != nil { in, out := &in.Details, &out.Details *out = make([]KeyValue, len(*in)) @@ -1867,12 +1913,16 @@ func (in *PagerDutyConfig) DeepCopyInto(out *PagerDutyConfig) { if in.PagerDutyImageConfigs != nil { in, out := &in.PagerDutyImageConfigs, &out.PagerDutyImageConfigs *out = make([]PagerDutyImageConfig, len(*in)) - copy(*out, *in) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } } if in.PagerDutyLinkConfigs != nil { in, out := &in.PagerDutyLinkConfigs, &out.PagerDutyLinkConfigs *out = make([]PagerDutyLinkConfig, len(*in)) - copy(*out, *in) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } } if in.HTTPConfig != nil { in, out := &in.HTTPConfig, &out.HTTPConfig @@ -1884,6 +1934,11 @@ func (in *PagerDutyConfig) DeepCopyInto(out *PagerDutyConfig) { *out = new(string) **out = **in } + if in.Timeout != nil { + in, out := &in.Timeout, &out.Timeout + *out = new(monitoringv1.Duration) + **out = **in + } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PagerDutyConfig. @@ -1899,6 +1954,21 @@ func (in *PagerDutyConfig) DeepCopy() *PagerDutyConfig { // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *PagerDutyImageConfig) DeepCopyInto(out *PagerDutyImageConfig) { *out = *in + if in.Src != nil { + in, out := &in.Src, &out.Src + *out = new(string) + **out = **in + } + if in.Href != nil { + in, out := &in.Href, &out.Href + *out = new(URL) + **out = **in + } + if in.Alt != nil { + in, out := &in.Alt, &out.Alt + *out = new(string) + **out = **in + } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PagerDutyImageConfig. @@ -1914,6 +1984,16 @@ func (in *PagerDutyImageConfig) DeepCopy() *PagerDutyImageConfig { // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *PagerDutyLinkConfig) DeepCopyInto(out *PagerDutyLinkConfig) { *out = *in + if in.Href != nil { + in, out := &in.Href, &out.Href + *out = new(URL) + **out = **in + } + if in.Text != nil { + in, out := &in.Text, &out.Text + *out = new(string) + **out = **in + } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PagerDutyLinkConfig. @@ -2079,6 +2159,26 @@ func (in *PushoverConfig) DeepCopyInto(out *PushoverConfig) { *out = new(string) **out = **in } + if in.Title != nil { + in, out := &in.Title, &out.Title + *out = new(string) + **out = **in + } + if in.Message != nil { + in, out := &in.Message, &out.Message + *out = new(string) + **out = **in + } + if in.URL != nil { + in, out := &in.URL, &out.URL + *out = new(URL) + **out = **in + } + if in.URLTitle != nil { + in, out := &in.URLTitle, &out.URLTitle + *out = new(string) + **out = **in + } if in.TTL != nil { in, out := &in.TTL, &out.TTL *out = new(monitoringv1.Duration) @@ -2089,6 +2189,26 @@ func (in *PushoverConfig) DeepCopyInto(out *PushoverConfig) { *out = new(string) **out = **in } + if in.Sound != nil { + in, out := &in.Sound, &out.Sound + *out = new(string) + **out = **in + } + if in.Priority != nil { + in, out := &in.Priority, &out.Priority + *out = new(string) + **out = **in + } + if in.Retry != nil { + in, out := &in.Retry, &out.Retry + *out = new(string) + **out = **in + } + if in.Expire != nil { + in, out := &in.Expire, &out.Expire + *out = new(string) + **out = **in + } if in.HTML != nil { in, out := &in.HTML, &out.HTML *out = new(bool) @@ -2917,10 +3037,30 @@ func (in *ScrapeConfigSpec) DeepCopy() *ScrapeConfigSpec { // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *SlackAction) DeepCopyInto(out *SlackAction) { *out = *in + if in.URL != nil { + in, out := &in.URL, &out.URL + *out = new(URL) + **out = **in + } + if in.Style != nil { + in, out := &in.Style, &out.Style + *out = new(string) + **out = **in + } + if in.Name != nil { + in, out := &in.Name, &out.Name + *out = new(string) + **out = **in + } + if in.Value != nil { + in, out := &in.Value, &out.Value + *out = new(string) + **out = **in + } if in.ConfirmField != nil { in, out := &in.ConfirmField, &out.ConfirmField *out = new(SlackConfirmationField) - **out = **in + (*in).DeepCopyInto(*out) } } @@ -2947,6 +3087,41 @@ func (in *SlackConfig) DeepCopyInto(out *SlackConfig) { *out = new(corev1.SecretKeySelector) (*in).DeepCopyInto(*out) } + if in.Channel != nil { + in, out := &in.Channel, &out.Channel + *out = new(string) + **out = **in + } + if in.Username != nil { + in, out := &in.Username, &out.Username + *out = new(string) + **out = **in + } + if in.Color != nil { + in, out := &in.Color, &out.Color + *out = new(string) + **out = **in + } + if in.Title != nil { + in, out := &in.Title, &out.Title + *out = new(string) + **out = **in + } + if in.TitleLink != nil { + in, out := &in.TitleLink, &out.TitleLink + *out = new(URL) + **out = **in + } + if in.Pretext != nil { + in, out := &in.Pretext, &out.Pretext + *out = new(string) + **out = **in + } + if in.Text != nil { + in, out := &in.Text, &out.Text + *out = new(string) + **out = **in + } if in.Fields != nil { in, out := &in.Fields, &out.Fields *out = make([]SlackField, len(*in)) @@ -2954,6 +3129,51 @@ func (in *SlackConfig) DeepCopyInto(out *SlackConfig) { (*in)[i].DeepCopyInto(&(*out)[i]) } } + if in.ShortFields != nil { + in, out := &in.ShortFields, &out.ShortFields + *out = new(bool) + **out = **in + } + if in.Footer != nil { + in, out := &in.Footer, &out.Footer + *out = new(string) + **out = **in + } + if in.Fallback != nil { + in, out := &in.Fallback, &out.Fallback + *out = new(string) + **out = **in + } + if in.CallbackID != nil { + in, out := &in.CallbackID, &out.CallbackID + *out = new(string) + **out = **in + } + if in.IconEmoji != nil { + in, out := &in.IconEmoji, &out.IconEmoji + *out = new(string) + **out = **in + } + if in.IconURL != nil { + in, out := &in.IconURL, &out.IconURL + *out = new(URL) + **out = **in + } + if in.ImageURL != nil { + in, out := &in.ImageURL, &out.ImageURL + *out = new(URL) + **out = **in + } + if in.ThumbURL != nil { + in, out := &in.ThumbURL, &out.ThumbURL + *out = new(URL) + **out = **in + } + if in.LinkNames != nil { + in, out := &in.LinkNames, &out.LinkNames + *out = new(bool) + **out = **in + } if in.MrkdwnIn != nil { in, out := &in.MrkdwnIn, &out.MrkdwnIn *out = make([]string, len(*in)) @@ -2971,6 +3191,11 @@ func (in *SlackConfig) DeepCopyInto(out *SlackConfig) { *out = new(HTTPConfig) (*in).DeepCopyInto(*out) } + if in.Timeout != nil { + in, out := &in.Timeout, &out.Timeout + *out = new(monitoringv1.Duration) + **out = **in + } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new SlackConfig. @@ -2986,6 +3211,21 @@ func (in *SlackConfig) DeepCopy() *SlackConfig { // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *SlackConfirmationField) DeepCopyInto(out *SlackConfirmationField) { *out = *in + if in.Title != nil { + in, out := &in.Title, &out.Title + *out = new(string) + **out = **in + } + if in.OkText != nil { + in, out := &in.OkText, &out.OkText + *out = new(string) + **out = **in + } + if in.DismissText != nil { + in, out := &in.DismissText, &out.DismissText + *out = new(string) + **out = **in + } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new SlackConfirmationField. @@ -3053,6 +3293,11 @@ func (in *TelegramConfig) DeepCopyInto(out *TelegramConfig) { *out = new(bool) **out = **in } + if in.APIURL != nil { + in, out := &in.APIURL, &out.APIURL + *out = new(URL) + **out = **in + } if in.BotToken != nil { in, out := &in.BotToken, &out.BotToken *out = new(corev1.SecretKeySelector) @@ -3158,6 +3403,31 @@ func (in *VictorOpsConfig) DeepCopyInto(out *VictorOpsConfig) { *out = new(corev1.SecretKeySelector) (*in).DeepCopyInto(*out) } + if in.APIURL != nil { + in, out := &in.APIURL, &out.APIURL + *out = new(URL) + **out = **in + } + if in.MessageType != nil { + in, out := &in.MessageType, &out.MessageType + *out = new(string) + **out = **in + } + if in.EntityDisplayName != nil { + in, out := &in.EntityDisplayName, &out.EntityDisplayName + *out = new(string) + **out = **in + } + if in.StateMessage != nil { + in, out := &in.StateMessage, &out.StateMessage + *out = new(string) + **out = **in + } + if in.MonitoringTool != nil { + in, out := &in.MonitoringTool, &out.MonitoringTool + *out = new(string) + **out = **in + } if in.CustomFields != nil { in, out := &in.CustomFields, &out.CustomFields *out = make([]KeyValue, len(*in)) @@ -3193,6 +3463,11 @@ func (in *WeChatConfig) DeepCopyInto(out *WeChatConfig) { *out = new(corev1.SecretKeySelector) (*in).DeepCopyInto(*out) } + if in.APIURL != nil { + in, out := &in.APIURL, &out.APIURL + *out = new(URL) + **out = **in + } if in.HTTPConfig != nil { in, out := &in.HTTPConfig, &out.HTTPConfig *out = new(HTTPConfig) @@ -3255,7 +3530,7 @@ func (in *WebhookConfig) DeepCopyInto(out *WebhookConfig) { } if in.URL != nil { in, out := &in.URL, &out.URL - *out = new(string) + *out = new(URL) **out = **in } if in.URLSecret != nil { diff --git a/vendor/github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1beta1/alertmanager_config_types.go b/vendor/github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1beta1/alertmanager_config_types.go index 38b4ec820ed..f43068e4281 100644 --- a/vendor/github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1beta1/alertmanager_config_types.go +++ b/vendor/github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1beta1/alertmanager_config_types.go @@ -29,6 +29,7 @@ import ( apiextensionsv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" + "k8s.io/utils/ptr" ) const ( @@ -42,6 +43,7 @@ const ( // +genclient // +k8s:openapi-gen=true // +kubebuilder:resource:categories="prometheus-operator",shortName="amcfg" +// +kubebuilder:subresource:status // The `AlertmanagerConfig` custom resource definition (CRD) defines how `Alertmanager` objects process Prometheus alerts. It allows to specify alert grouping and routing, notification receivers and inhibition rules. // @@ -55,6 +57,14 @@ type AlertmanagerConfig struct { // spec defines the specification of AlertmanagerConfigSpec // +required Spec AlertmanagerConfigSpec `json:"spec"` + // status defines the status subresource. It is under active development and is updated only when the + // "StatusForConfigurationResources" feature gate is enabled. + // + // Most recent observed status of the ServiceMonitor. Read-only. + // More info: + // https://github.com/kubernetes/community/blob/master/contributors/devel/sig-architecture/api-conventions.md#spec-and-status + // +optional + Status monitoringv1.ConfigResourceStatus `json:"status,omitempty,omitzero"` } // AlertmanagerConfigList is a list of AlertmanagerConfig. @@ -125,7 +135,7 @@ type Route struct { // sibling nodes. It will always be overridden to true for the first-level // route by the Prometheus operator. // +optional - Continue bool `json:"continue,omitempty"` + Continue bool `json:"continue,omitempty"` // nolint:kubeapilinter // routes defines the child routes. // +optional Routes []apiextensionsv1.JSON `json:"routes,omitempty"` @@ -221,7 +231,7 @@ type Receiver struct { type PagerDutyConfig struct { // sendResolved defines whether or not to notify about resolved alerts. // +optional - SendResolved *bool `json:"sendResolved,omitempty"` + SendResolved *bool `json:"sendResolved,omitempty"` // nolint:kubeapilinter // routingKey defines the secret's key that contains the PagerDuty integration key (when using // Events API v2). Either this field or `serviceKey` needs to be defined. // The secret needs to be in the same namespace as the AlertmanagerConfig @@ -237,66 +247,83 @@ type PagerDutyConfig struct { ServiceKey *SecretKeySelector `json:"serviceKey,omitempty"` // url defines the URL to send requests to. // +optional - URL string `json:"url,omitempty"` + URL *URL `json:"url,omitempty"` // client defines the client identification. + // +kubebuilder:validation:MinLength=1 // +optional - Client string `json:"client,omitempty"` + Client *string `json:"client,omitempty"` // clientURL defines the backlink to the sender of notification. // +optional - ClientURL string `json:"clientURL,omitempty"` + ClientURL *URL `json:"clientURL,omitempty"` // description of the incident. + // +kubebuilder:validation:MinLength=1 // +optional - Description string `json:"description,omitempty"` + Description *string `json:"description,omitempty"` // severity of the incident. + // +kubebuilder:validation:MinLength=1 // +optional - Severity string `json:"severity,omitempty"` + Severity *string `json:"severity,omitempty"` // class defines the class/type of the event. + // +kubebuilder:validation:MinLength=1 // +optional - Class string `json:"class,omitempty"` + Class *string `json:"class,omitempty"` // group defines a cluster or grouping of sources. + // +kubebuilder:validation:MinLength=1 // +optional - Group string `json:"group,omitempty"` + Group *string `json:"group,omitempty"` // component defines the part or component of the affected system that is broken. + // +kubebuilder:validation:MinLength=1 // +optional - Component string `json:"component,omitempty"` + Component *string `json:"component,omitempty"` // details defines the arbitrary key/value pairs that provide further detail about the incident. + // +listType=atomic // +optional Details []KeyValue `json:"details,omitempty"` // pagerDutyImageConfigs defines a list of image details to attach that provide further detail about an incident. + // +listType=atomic // +optional PagerDutyImageConfigs []PagerDutyImageConfig `json:"pagerDutyImageConfigs,omitempty"` // pagerDutyLinkConfigs defines a list of link details to attach that provide further detail about an incident. + // +listType=atomic // +optional PagerDutyLinkConfigs []PagerDutyLinkConfig `json:"pagerDutyLinkConfigs,omitempty"` // httpConfig defines the HTTP client configuration. // +optional HTTPConfig *HTTPConfig `json:"httpConfig,omitempty"` // source defines the unique location of the affected system. + // +kubebuilder:validation:MinLength=1 + // +optional + Source *string `json:"source,omitempty"` + // timeout is the maximum time allowed to invoke the pagerduty + // It requires Alertmanager >= v0.30.0. // +optional - Source *string `yaml:"source,omitempty" json:"source,omitempty"` + Timeout *monitoringv1.Duration `json:"timeout,omitempty"` } // PagerDutyImageConfig attaches images to an incident type PagerDutyImageConfig struct { // src of the image being attached to the incident + // +kubebuilder:validation:MinLength=1 // +optional - Src string `json:"src,omitempty"` + Src *string `json:"src,omitempty"` // href defines the optional URL; makes the image a clickable link. // +optional - Href string `json:"href,omitempty"` + Href *URL `json:"href,omitempty"` // alt is the optional alternative text for the image. + // +kubebuilder:validation:MinLength=1 // +optional - Alt string `json:"alt,omitempty"` + Alt *string `json:"alt,omitempty"` } // PagerDutyLinkConfig attaches text links to an incident type PagerDutyLinkConfig struct { // href defines the URL of the link to be attached // +optional - Href string `json:"href,omitempty"` + Href *URL `json:"href,omitempty"` // alt defines the text that describes the purpose of the link, and can be used as the link's text. + // +kubebuilder:validation:MinLength=1 // +optional - Text string `json:"alt,omitempty"` + Text *string `json:"alt,omitempty"` } // DiscordConfig configures notifications via Discord. @@ -304,7 +331,7 @@ type PagerDutyLinkConfig struct { type DiscordConfig struct { // sendResolved defines whether or not to notify about resolved alerts. // +optional - SendResolved *bool `json:"sendResolved,omitempty"` + SendResolved *bool `json:"sendResolved,omitempty"` // nolint:kubeapilinter // apiURL defines the secret's key that contains the Discord webhook URL. // The secret needs to be in the same namespace as the AlertmanagerConfig // object and accessible by the Prometheus Operator. @@ -337,77 +364,99 @@ type DiscordConfig struct { type SlackConfig struct { // sendResolved defines whether or not to notify about resolved alerts. // +optional - SendResolved *bool `json:"sendResolved,omitempty"` + SendResolved *bool `json:"sendResolved,omitempty"` // nolint:kubeapilinter // apiURL defines the secret's key that contains the Slack webhook URL. // The secret needs to be in the same namespace as the AlertmanagerConfig // object and accessible by the Prometheus Operator. // +optional APIURL *SecretKeySelector `json:"apiURL,omitempty"` // channel defines the channel or user to send notifications to. + // +kubebuilder:validation:MinLength=1 // +optional - Channel string `json:"channel,omitempty"` + Channel *string `json:"channel,omitempty"` // username defines the slack bot user name. + // +kubebuilder:validation:MinLength=1 // +optional - Username string `json:"username,omitempty"` + Username *string `json:"username,omitempty"` // color defines the color of the left border of the Slack message attachment. // Can be a hex color code (e.g., "#ff0000") or a predefined color name. + // +kubebuilder:validation:MinLength=1 // +optional - Color string `json:"color,omitempty"` + Color *string `json:"color,omitempty"` // title defines the title text displayed in the Slack message attachment. + // +kubebuilder:validation:MinLength=1 // +optional - Title string `json:"title,omitempty"` + Title *string `json:"title,omitempty"` // titleLink defines the URL that the title will link to when clicked. // +optional - TitleLink string `json:"titleLink,omitempty"` + TitleLink *URL `json:"titleLink,omitempty"` // pretext defines optional text that appears above the message attachment block. + // +kubebuilder:validation:MinLength=1 // +optional - Pretext string `json:"pretext,omitempty"` + Pretext *string `json:"pretext,omitempty"` // text defines the main text content of the Slack message attachment. + // +kubebuilder:validation:MinLength=1 // +optional - Text string `json:"text,omitempty"` + Text *string `json:"text,omitempty"` // fields defines a list of Slack fields that are sent with each notification. + // +kubebuilder:validation:MinItems=1 + // +listType=atomic // +optional Fields []SlackField `json:"fields,omitempty"` // shortFields determines whether fields are displayed in a compact format. // When true, fields are shown side by side when possible. // +optional - ShortFields bool `json:"shortFields,omitempty"` + ShortFields *bool `json:"shortFields,omitempty"` // nolint:kubeapilinter // footer defines small text displayed at the bottom of the message attachment. + // +kubebuilder:validation:MinLength=1 // +optional - Footer string `json:"footer,omitempty"` + Footer *string `json:"footer,omitempty"` // fallback defines a plain-text summary of the attachment for clients that don't support attachments. + // +kubebuilder:validation:MinLength=1 // +optional - Fallback string `json:"fallback,omitempty"` + Fallback *string `json:"fallback,omitempty"` // callbackId defines an identifier for the message used in interactive components. + // +kubebuilder:validation:MinLength=1 // +optional - CallbackID string `json:"callbackId,omitempty"` + CallbackID *string `json:"callbackId,omitempty"` // iconEmoji defines the emoji to use as the bot's avatar (e.g., ":ghost:"). + // +kubebuilder:validation:MinLength=1 // +optional - IconEmoji string `json:"iconEmoji,omitempty"` + IconEmoji *string `json:"iconEmoji,omitempty"` // iconURL defines the URL to an image to use as the bot's avatar. // +optional - IconURL string `json:"iconURL,omitempty"` + IconURL *URL `json:"iconURL,omitempty"` // imageURL defines the URL to an image file that will be displayed inside the message attachment. // +optional - ImageURL string `json:"imageURL,omitempty"` + ImageURL *URL `json:"imageURL,omitempty"` // thumbURL defines the URL to an image file that will be displayed as a thumbnail // on the right side of the message attachment. // +optional - ThumbURL string `json:"thumbURL,omitempty"` + ThumbURL *URL `json:"thumbURL,omitempty"` // linkNames enables automatic linking of channel names and usernames in the message. // When true, @channel and @username will be converted to clickable links. // +optional - LinkNames bool `json:"linkNames,omitempty"` + LinkNames *bool `json:"linkNames,omitempty"` // nolint:kubeapilinter // mrkdwnIn defines which fields should be parsed as Slack markdown. // Valid values include "pretext", "text", and "fields". + // +listType=atomic + // +kubebuilder:validation:MinItems=1 + // +kubebuilder:validation:items:MinLength=1 // +optional MrkdwnIn []string `json:"mrkdwnIn,omitempty"` // actions defines a list of Slack actions that are sent with each notification. + // +kubebuilder:validation:MinItems=1 + // +listType=atomic // +optional Actions []SlackAction `json:"actions,omitempty"` // httpConfig defines the HTTP client configuration. // +optional HTTPConfig *HTTPConfig `json:"httpConfig,omitempty"` + // timeout defines the maximum time to wait for a webhook request to complete, + // before failing the request and allowing it to be retried. + // It requires Alertmanager >= v0.30.0. + // +optional + Timeout *monitoringv1.Duration `json:"timeout,omitempty"` } // Validate ensures SlackConfig is valid. @@ -445,19 +494,22 @@ type SlackAction struct { // url defines the URL to open when the action is triggered. // Only applicable for button-type actions. When set, clicking the button opens this URL. // +optional - URL string `json:"url,omitempty"` + URL *URL `json:"url,omitempty"` // style defines the visual appearance of the action element. // Valid values include "default", "primary" (green), and "danger" (red). + // +kubebuilder:validation:MinLength=1 // +optional - Style string `json:"style,omitempty"` + Style *string `json:"style,omitempty"` // name defines a unique identifier for the action within the message. // This value is sent back to your application when the action is triggered. + // +kubebuilder:validation:MinLength=1 // +optional - Name string `json:"name,omitempty"` + Name *string `json:"name,omitempty"` // value defines the payload sent when the action is triggered. // This data is included in the callback sent to your application. + // +kubebuilder:validation:MinLength=1 // +optional - Value string `json:"value,omitempty"` + Value *string `json:"value,omitempty"` // confirm defines an optional confirmation dialog that appears before the action is executed. // When set, users must confirm their intent before the action proceeds. // +optional @@ -474,7 +526,7 @@ func (sa *SlackAction) Validate() error { return errors.New("missing text in Slack action configuration") } - if sa.URL == "" && sa.Name == "" { + if ptr.Deref(sa.URL, "") == "" && ptr.Deref(sa.Name, "") == "" { return errors.New("missing name or url in Slack action configuration") } @@ -500,16 +552,19 @@ type SlackConfirmationField struct { Text string `json:"text"` // title defines the title text displayed at the top of the confirmation dialog. // When not specified, a default title will be used. + // +kubebuilder:validation:MinLength=1 // +optional - Title string `json:"title,omitempty"` + Title *string `json:"title,omitempty"` // okText defines the label for the confirmation button in the dialog. // When not specified, defaults to "Okay". This button proceeds with the action. + // +kubebuilder:validation:MinLength=1 // +optional - OkText string `json:"okText,omitempty"` + OkText *string `json:"okText,omitempty"` // dismissText defines the label for the cancel button in the dialog. // When not specified, defaults to "Cancel". This button cancels the action. + // +kubebuilder:validation:MinLength=1 // +optional - DismissText string `json:"dismissText,omitempty"` + DismissText *string `json:"dismissText,omitempty"` } // Validate ensures SlackConfirmationField is valid. @@ -539,7 +594,7 @@ type SlackField struct { // When true, Slack may display this field side by side with other short fields. // When false or not specified, the field takes the full width of the message. // +optional - Short *bool `json:"short,omitempty"` + Short *bool `json:"short,omitempty"` // nolint:kubeapilinter } // Validate ensures SlackField is valid @@ -560,11 +615,11 @@ func (sf *SlackField) Validate() error { type WebhookConfig struct { // sendResolved defines whether or not to notify about resolved alerts. // +optional - SendResolved *bool `json:"sendResolved,omitempty"` + SendResolved *bool `json:"sendResolved,omitempty"` // nolint:kubeapilinter // url defines the URL to send HTTP POST requests to. // urlSecret takes precedence over url. One of urlSecret and url should be defined. // +optional - URL *string `json:"url,omitempty"` + URL *URL `json:"url,omitempty"` // urlSecret defines the secret's key that contains the webhook URL to send HTTP requests to. // urlSecret takes precedence over url. One of urlSecret and url should be defined. // The secret needs to be in the same namespace as the AlertmanagerConfig @@ -591,7 +646,7 @@ type WebhookConfig struct { type OpsGenieConfig struct { // sendResolved defines whether or not to notify about resolved alerts. // +optional - SendResolved *bool `json:"sendResolved,omitempty"` + SendResolved *bool `json:"sendResolved,omitempty"` // nolint:kubeapilinter // apiKey defines the secret's key that contains the OpsGenie API key. // The secret needs to be in the same namespace as the AlertmanagerConfig // object and accessible by the Prometheus Operator. @@ -600,7 +655,7 @@ type OpsGenieConfig struct { // apiURL defines the URL to send OpsGenie API requests to. // When not specified, defaults to the standard OpsGenie API endpoint. // +optional - APIURL string `json:"apiURL,omitempty"` + APIURL *URL `json:"apiURL,omitempty"` // message defines the alert text limited to 130 characters. // This appears as the main alert title in OpsGenie. // +optional @@ -742,12 +797,12 @@ type HTTPConfig struct { // followRedirects defines whether HTTP requests follow HTTP 3xx redirects. // When true, the client will automatically follow redirect responses. // +optional - FollowRedirects *bool `json:"followRedirects,omitempty"` + FollowRedirects *bool `json:"followRedirects,omitempty"` // nolint:kubeapilinter // enableHttp2 can be used to disable HTTP2. // // +optional - EnableHTTP2 *bool `json:"enableHttp2,omitempty"` + EnableHTTP2 *bool `json:"enableHttp2,omitempty"` // nolint:kubeapilinter } // WebexConfig configures notification via Cisco Webex @@ -755,7 +810,7 @@ type HTTPConfig struct { type WebexConfig struct { // sendResolved defines whether or not to notify about resolved alerts. // +optional - SendResolved *bool `json:"sendResolved,omitempty"` + SendResolved *bool `json:"sendResolved,omitempty"` // nolint:kubeapilinter // apiURL defines the Webex Teams API URL i.e. https://webexapis.com/v1/messages // +optional @@ -781,7 +836,7 @@ type WebexConfig struct { type WeChatConfig struct { // sendResolved defines whether or not to notify about resolved alerts. // +optional - SendResolved *bool `json:"sendResolved,omitempty"` + SendResolved *bool `json:"sendResolved,omitempty"` // nolint:kubeapilinter // apiSecret defines the secret's key that contains the WeChat API key. // The secret needs to be in the same namespace as the AlertmanagerConfig // object and accessible by the Prometheus Operator. @@ -790,7 +845,7 @@ type WeChatConfig struct { // apiURL defines the WeChat API URL. // When not specified, defaults to the standard WeChat Work API endpoint. // +optional - APIURL string `json:"apiURL,omitempty"` + APIURL *URL `json:"apiURL,omitempty"` // corpID defines the corp id for authentication. // This is the unique identifier for your WeChat Work organization. // +optional @@ -828,7 +883,7 @@ type WeChatConfig struct { type EmailConfig struct { // sendResolved defines whether or not to notify about resolved alerts. // +optional - SendResolved *bool `json:"sendResolved,omitempty"` + SendResolved *bool `json:"sendResolved,omitempty"` // nolint:kubeapilinter // to defines the email address to send notifications to. // This is the recipient address for alert notifications. // +optional @@ -879,7 +934,7 @@ type EmailConfig struct { // requireTLS defines the SMTP TLS requirement. // Note that Go does not support unencrypted connections to remote SMTP endpoints. // +optional - RequireTLS *bool `json:"requireTLS,omitempty"` + RequireTLS *bool `json:"requireTLS,omitempty"` // nolint:kubeapilinter // tlsConfig defines the TLS configuration for SMTP connections. // This includes settings for certificates, CA validation, and TLS protocol options. // +optional @@ -891,7 +946,7 @@ type EmailConfig struct { type VictorOpsConfig struct { // sendResolved defines whether or not to notify about resolved alerts. // +optional - SendResolved *bool `json:"sendResolved,omitempty"` + SendResolved *bool `json:"sendResolved,omitempty"` // nolint:kubeapilinter // apiKey defines the secret's key that contains the API key to use when talking to the VictorOps API. // The secret needs to be in the same namespace as the AlertmanagerConfig // object and accessible by the Prometheus Operator. @@ -900,29 +955,35 @@ type VictorOpsConfig struct { // apiUrl defines the VictorOps API URL. // When not specified, defaults to the standard VictorOps API endpoint. // +optional - APIURL string `json:"apiUrl,omitempty"` + APIURL *URL `json:"apiUrl,omitempty"` // routingKey defines a key used to map the alert to a team. // This determines which VictorOps team will receive the alert notification. - // +optional + // +kubebuilder:validation:MinLength=1 + // +required RoutingKey string `json:"routingKey"` // messageType describes the behavior of the alert. // Valid values are "CRITICAL", "WARNING", and "INFO". + // +kubebuilder:validation:MinLength=1 // +optional - MessageType string `json:"messageType,omitempty"` + MessageType *string `json:"messageType,omitempty"` // entityDisplayName contains a summary of the alerted problem. // This appears as the main title or identifier for the incident. + // +kubebuilder:validation:MinLength=1 // +optional - EntityDisplayName string `json:"entityDisplayName,omitempty"` + EntityDisplayName *string `json:"entityDisplayName,omitempty"` // stateMessage contains a long explanation of the alerted problem. // This provides detailed context about the incident. + // +kubebuilder:validation:MinLength=1 // +optional - StateMessage string `json:"stateMessage,omitempty"` + StateMessage *string `json:"stateMessage,omitempty"` // monitoringTool defines the monitoring tool the state message is from. // This helps identify the source system that generated the alert. + // +kubebuilder:validation:MinLength=1 // +optional - MonitoringTool string `json:"monitoringTool,omitempty"` + MonitoringTool *string `json:"monitoringTool,omitempty"` // customFields defines additional custom fields for notification. // These provide extra metadata that will be included with the VictorOps incident. + // +listType=atomic // +optional CustomFields []KeyValue `json:"customFields,omitempty"` // httpConfig defines the HTTP client's configuration for VictorOps API requests. @@ -935,7 +996,7 @@ type VictorOpsConfig struct { type PushoverConfig struct { // sendResolved defines whether or not to notify about resolved alerts. // +optional - SendResolved *bool `json:"sendResolved,omitempty"` + SendResolved *bool `json:"sendResolved,omitempty"` // nolint:kubeapilinter // userKey defines the secret's key that contains the recipient user's user key. // The secret needs to be in the same namespace as the AlertmanagerConfig // object and accessible by the Prometheus Operator. @@ -962,54 +1023,61 @@ type PushoverConfig struct { TokenFile *string `json:"tokenFile,omitempty"` // title defines the notification title displayed in the Pushover message. // This appears as the bold header text in the notification. + // +kubebuilder:validation:MinLength=1 // +optional - Title string `json:"title,omitempty"` + Title *string `json:"title,omitempty"` // message defines the notification message content. // This is the main body text of the Pushover notification. + // +kubebuilder:validation:MinLength=1 // +optional - Message string `json:"message,omitempty"` + Message *string `json:"message,omitempty"` // url defines a supplementary URL shown alongside the message. // This creates a clickable link within the Pushover notification. // +optional - URL string `json:"url,omitempty"` + URL *URL `json:"url,omitempty"` // urlTitle defines a title for the supplementary URL. // If not specified, the raw URL is shown instead. + // +kubebuilder:validation:MinLength=1 // +optional - URLTitle string `json:"urlTitle,omitempty"` + URLTitle *string `json:"urlTitle,omitempty"` // ttl defines the time to live for the alert notification. // This determines how long the notification remains active before expiring. // +optional TTL *monitoringv1.Duration `json:"ttl,omitempty"` // device defines the name of a specific device to send the notification to. // If not specified, the notification is sent to all user's devices. + // +kubebuilder:validation:MinLength=1 // +optional Device *string `json:"device,omitempty"` // sound defines the name of one of the sounds supported by device clients. // This overrides the user's default sound choice for this notification. + // +kubebuilder:validation:MinLength=1 // +optional - Sound string `json:"sound,omitempty"` + Sound *string `json:"sound,omitempty"` // priority defines the notification priority level. // See https://pushover.net/api#priority for valid values and behavior. + // +kubebuilder:validation:MinLength=1 // +optional - Priority string `json:"priority,omitempty"` + Priority *string `json:"priority,omitempty"` // retry defines how often the Pushover servers will send the same notification to the user. // Must be at least 30 seconds. Only applies to priority 2 notifications. // +kubebuilder:validation:Pattern=`^(([0-9]+)y)?(([0-9]+)w)?(([0-9]+)d)?(([0-9]+)h)?(([0-9]+)m)?(([0-9]+)s)?(([0-9]+)ms)?$` // +optional - Retry string `json:"retry,omitempty"` + Retry *string `json:"retry,omitempty"` // expire defines how long your notification will continue to be retried for, // unless the user acknowledges the notification. Only applies to priority 2 notifications. // +kubebuilder:validation:Pattern=`^(([0-9]+)y)?(([0-9]+)w)?(([0-9]+)d)?(([0-9]+)h)?(([0-9]+)m)?(([0-9]+)s)?(([0-9]+)ms)?$` // +optional - Expire string `json:"expire,omitempty"` + Expire *string `json:"expire,omitempty"` // html defines whether notification message is HTML or plain text. // When true, the message can include HTML formatting tags. + // html and monospace formatting are mutually exclusive. // +optional - HTML *bool `json:"html,omitempty"` + HTML *bool `json:"html,omitempty"` //nolint:kubeapilinter // monospace optional HTML/monospace formatting for the message, see https://pushover.net/api#html // html and monospace formatting are mutually exclusive. // +optional - Monospace *bool `json:"monospace,omitempty"` + Monospace *bool `json:"monospace,omitempty"` //nolint:kubeapilinter // httpConfig defines the HTTP client configuration for Pushover API requests. // +optional HTTPConfig *HTTPConfig `json:"httpConfig,omitempty"` @@ -1020,7 +1088,7 @@ type PushoverConfig struct { type SNSConfig struct { // sendResolved defines whether or not to notify about resolved alerts. // +optional - SendResolved *bool `json:"sendResolved,omitempty"` + SendResolved *bool `json:"sendResolved,omitempty"` // nolint:kubeapilinter // apiURL defines the SNS API URL, e.g. https://sns.us-east-2.amazonaws.com. // If not specified, the SNS API URL from the SNS SDK will be used. // +optional @@ -1052,6 +1120,7 @@ type SNSConfig struct { // attributes defines SNS message attributes as key-value pairs. // These provide additional metadata that can be used for message filtering and routing. // +optional + //nolint:kubeapilinter Attributes map[string]string `json:"attributes,omitempty"` // httpConfig defines the HTTP client configuration for SNS API requests. // +optional @@ -1063,11 +1132,11 @@ type SNSConfig struct { type TelegramConfig struct { // sendResolved defines whether or not to notify about resolved alerts. // +optional - SendResolved *bool `json:"sendResolved,omitempty"` + SendResolved *bool `json:"sendResolved,omitempty"` // nolint:kubeapilinter // apiURL defines the Telegram API URL, e.g. https://api.telegram.org. // If not specified, the default Telegram API URL will be used. // +optional - APIURL string `json:"apiURL,omitempty"` + APIURL *URL `json:"apiURL,omitempty"` // botToken defines the Telegram bot token. It is mutually exclusive with `botTokenFile`. // The secret needs to be in the same namespace as the AlertmanagerConfig // object and accessible by the Prometheus Operator. @@ -1096,7 +1165,7 @@ type TelegramConfig struct { // disableNotifications controls whether Telegram notifications are sent silently. // When true, users will receive the message without notification sounds. // +optional - DisableNotifications *bool `json:"disableNotifications,omitempty"` + DisableNotifications *bool `json:"disableNotifications,omitempty"` // nolint:kubeapilinter // parseMode defines the parse mode for telegram message formatting. // Valid values are "MarkdownV2", "Markdown", and "HTML". // This determines how text formatting is interpreted in the message. @@ -1113,7 +1182,7 @@ type TelegramConfig struct { type MSTeamsConfig struct { // sendResolved defines whether or not to notify about resolved alerts. // +optional - SendResolved *bool `json:"sendResolved,omitempty"` + SendResolved *bool `json:"sendResolved,omitempty"` // nolint:kubeapilinter // webhookUrl defines the MSTeams webhook URL for sending notifications. // This is the incoming webhook URL configured in your Teams channel. // +required @@ -1142,7 +1211,7 @@ type MSTeamsConfig struct { type MSTeamsV2Config struct { // sendResolved defines whether or not to notify about resolved alerts. // +optional - SendResolved *bool `json:"sendResolved,omitempty"` + SendResolved *bool `json:"sendResolved,omitempty"` // nolint:kubeapilinter // webhookURL defines the MSTeams incoming webhook URL for adaptive card notifications. // This webhook must support the newer adaptive cards format required by Teams flows. // +optional @@ -1167,7 +1236,7 @@ type MSTeamsV2Config struct { type RocketChatConfig struct { // sendResolved defines whether or not to notify about resolved alerts. // +optional - SendResolved *bool `json:"sendResolved,omitempty"` + SendResolved *bool `json:"sendResolved,omitempty"` // nolint:kubeapilinter // apiURL defines the API URL for RocketChat. // Defaults to https://open.rocket.chat/ if not specified. // +optional @@ -1222,7 +1291,7 @@ type RocketChatConfig struct { // shortFields defines whether to use short fields in the message layout. // When true, fields may be displayed side by side to save space. // +optional - ShortFields *bool `json:"shortFields,omitempty"` + ShortFields *bool `json:"shortFields,omitempty"` // nolint:kubeapilinter // imageURL defines the image URL to display within the message. // This embeds an image directly in the message attachment. // +optional @@ -1234,7 +1303,7 @@ type RocketChatConfig struct { // linkNames defines whether to enable automatic linking of usernames and channels. // When true, @username and #channel references become clickable links. // +optional - LinkNames *bool `json:"linkNames,omitempty"` + LinkNames *bool `json:"linkNames,omitempty"` // nolint:kubeapilinter // actions defines interactive actions to include in the message. // These appear as buttons that users can click to trigger responses. // +kubebuilder:validation:MinItems=1 @@ -1260,7 +1329,7 @@ type RocketChatFieldConfig struct { // short defines whether this field should be a short field. // When true, the field may be displayed inline with other short fields to save space. // +optional - Short *bool `json:"short,omitempty"` + Short *bool `json:"short,omitempty"` // nolint:kubeapilinter } // RocketChatActionConfig defines actions for RocketChat messages. diff --git a/vendor/github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1beta1/conversion_from.go b/vendor/github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1beta1/conversion_from.go index 8d2241b16a0..714dde3943f 100644 --- a/vendor/github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1beta1/conversion_from.go +++ b/vendor/github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1beta1/conversion_from.go @@ -198,7 +198,7 @@ func convertOpsGenieConfigFrom(in v1alpha1.OpsGenieConfig) OpsGenieConfig { return OpsGenieConfig{ SendResolved: in.SendResolved, APIKey: convertSecretKeySelectorFrom(in.APIKey), - APIURL: in.APIURL, + APIURL: (*URL)(in.APIURL), Message: in.Message, Description: in.Description, Source: in.Source, @@ -219,7 +219,7 @@ func convertPagerDutyImageConfigsFrom(in []v1alpha1.PagerDutyImageConfig) []Page for i := range in { out[i] = PagerDutyImageConfig{ Src: in[i].Src, - Href: in[i].Href, + Href: (*URL)(in[i].Href), Alt: in[i].Alt, } } @@ -232,7 +232,7 @@ func convertPagerDutyLinkConfigsFrom(in []v1alpha1.PagerDutyLinkConfig) []PagerD for i := range in { out[i] = PagerDutyLinkConfig{ - Href: in[i].Href, + Href: (*URL)(in[i].Href), Text: in[i].Text, } } @@ -245,9 +245,9 @@ func convertPagerDutyConfigFrom(in v1alpha1.PagerDutyConfig) PagerDutyConfig { SendResolved: in.SendResolved, RoutingKey: convertSecretKeySelectorFrom(in.RoutingKey), ServiceKey: convertSecretKeySelectorFrom(in.ServiceKey), - URL: in.URL, + URL: (*URL)(in.URL), Client: in.Client, - ClientURL: in.ClientURL, + ClientURL: (*URL)(in.ClientURL), Description: in.Description, Severity: in.Severity, Class: in.Class, @@ -258,6 +258,7 @@ func convertPagerDutyConfigFrom(in v1alpha1.PagerDutyConfig) PagerDutyConfig { PagerDutyLinkConfigs: convertPagerDutyLinkConfigsFrom(in.PagerDutyLinkConfigs), HTTPConfig: convertHTTPConfigFrom(in.HTTPConfig), Source: in.Source, + Timeout: in.Timeout, } } @@ -348,7 +349,7 @@ func convertSlackActionsFrom(in []v1alpha1.SlackAction) []SlackAction { out[i] = SlackAction{ Type: in[i].Type, Text: in[i].Text, - URL: in[i].URL, + URL: (*URL)(in[i].URL), Style: in[i].Style, Name: in[i].Name, Value: in[i].Value, @@ -374,7 +375,7 @@ func convertSlackConfigFrom(in v1alpha1.SlackConfig) SlackConfig { Username: in.Username, Color: in.Color, Title: in.Title, - TitleLink: in.TitleLink, + TitleLink: (*URL)(in.TitleLink), Pretext: in.Pretext, Text: in.Text, Fields: convertSlackFieldsFrom(in.Fields), @@ -383,13 +384,14 @@ func convertSlackConfigFrom(in v1alpha1.SlackConfig) SlackConfig { Fallback: in.Fallback, CallbackID: in.CallbackID, IconEmoji: in.IconEmoji, - IconURL: in.IconURL, - ImageURL: in.ImageURL, - ThumbURL: in.ThumbURL, + IconURL: (*URL)(in.IconURL), + ImageURL: (*URL)(in.ImageURL), + ThumbURL: (*URL)(in.ThumbURL), LinkNames: in.LinkNames, MrkdwnIn: in.MrkdwnIn, Actions: convertSlackActionsFrom(in.Actions), HTTPConfig: convertHTTPConfigFrom(in.HTTPConfig), + Timeout: in.Timeout, } } @@ -406,7 +408,7 @@ func convertWebexConfigFrom(in v1alpha1.WebexConfig) WebexConfig { func convertWebhookConfigFrom(in v1alpha1.WebhookConfig) WebhookConfig { return WebhookConfig{ SendResolved: in.SendResolved, - URL: in.URL, + URL: (*URL)(in.URL), URLSecret: convertSecretKeySelectorFrom(in.URLSecret), HTTPConfig: convertHTTPConfigFrom(in.HTTPConfig), MaxAlerts: in.MaxAlerts, @@ -418,7 +420,7 @@ func convertWeChatConfigFrom(in v1alpha1.WeChatConfig) WeChatConfig { return WeChatConfig{ SendResolved: in.SendResolved, APISecret: convertSecretKeySelectorFrom(in.APISecret), - APIURL: in.APIURL, + APIURL: (*URL)(in.APIURL), CorpID: in.CorpID, AgentID: in.AgentID, ToUser: in.ToUser, @@ -453,7 +455,7 @@ func convertVictorOpsConfigFrom(in v1alpha1.VictorOpsConfig) VictorOpsConfig { return VictorOpsConfig{ SendResolved: in.SendResolved, APIKey: convertSecretKeySelectorFrom(in.APIKey), - APIURL: in.APIURL, + APIURL: (*URL)(in.APIURL), RoutingKey: in.RoutingKey, MessageType: in.MessageType, EntityDisplayName: in.EntityDisplayName, @@ -473,7 +475,7 @@ func convertPushoverConfigFrom(in v1alpha1.PushoverConfig) PushoverConfig { TokenFile: in.TokenFile, Title: in.Title, Message: in.Message, - URL: in.URL, + URL: (*URL)(in.URL), URLTitle: in.URLTitle, Device: in.Device, Sound: in.Sound, @@ -504,7 +506,7 @@ func convertSNSConfigFrom(in v1alpha1.SNSConfig) SNSConfig { func convertTelegramConfigFrom(in v1alpha1.TelegramConfig) TelegramConfig { return TelegramConfig{ SendResolved: in.SendResolved, - APIURL: in.APIURL, + APIURL: (*URL)(in.APIURL), BotToken: convertSecretKeySelectorFrom(in.BotToken), BotTokenFile: in.BotTokenFile, ChatID: in.ChatID, diff --git a/vendor/github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1beta1/conversion_to.go b/vendor/github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1beta1/conversion_to.go index 2a9d2afe484..931b5373b9e 100644 --- a/vendor/github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1beta1/conversion_to.go +++ b/vendor/github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1beta1/conversion_to.go @@ -194,7 +194,7 @@ func convertOpsGenieConfigTo(in OpsGenieConfig) v1alpha1.OpsGenieConfig { return v1alpha1.OpsGenieConfig{ SendResolved: in.SendResolved, APIKey: convertSecretKeySelectorTo(in.APIKey), - APIURL: in.APIURL, + APIURL: (*v1alpha1.URL)(in.APIURL), Message: in.Message, Description: in.Description, Source: in.Source, @@ -215,7 +215,7 @@ func convertPagerDutyImageConfigsTo(in []PagerDutyImageConfig) []v1alpha1.PagerD for i := range in { out[i] = v1alpha1.PagerDutyImageConfig{ Src: in[i].Src, - Href: in[i].Href, + Href: (*v1alpha1.URL)(in[i].Href), Alt: in[i].Alt, } } @@ -228,7 +228,7 @@ func convertPagerDutyLinkConfigsTo(in []PagerDutyLinkConfig) []v1alpha1.PagerDut for i := range in { out[i] = v1alpha1.PagerDutyLinkConfig{ - Href: in[i].Href, + Href: (*v1alpha1.URL)(in[i].Href), Text: in[i].Text, } } @@ -241,9 +241,9 @@ func convertPagerDutyConfigTo(in PagerDutyConfig) v1alpha1.PagerDutyConfig { SendResolved: in.SendResolved, RoutingKey: convertSecretKeySelectorTo(in.RoutingKey), ServiceKey: convertSecretKeySelectorTo(in.ServiceKey), - URL: in.URL, + URL: (*v1alpha1.URL)(in.URL), Client: in.Client, - ClientURL: in.ClientURL, + ClientURL: (*v1alpha1.URL)(in.ClientURL), Description: in.Description, Severity: in.Severity, Class: in.Class, @@ -254,6 +254,7 @@ func convertPagerDutyConfigTo(in PagerDutyConfig) v1alpha1.PagerDutyConfig { PagerDutyLinkConfigs: convertPagerDutyLinkConfigsTo(in.PagerDutyLinkConfigs), HTTPConfig: convertHTTPConfigTo(in.HTTPConfig), Source: in.Source, + Timeout: in.Timeout, } } @@ -344,7 +345,7 @@ func convertSlackActionsTo(in []SlackAction) []v1alpha1.SlackAction { out[i] = v1alpha1.SlackAction{ Type: in[i].Type, Text: in[i].Text, - URL: in[i].URL, + URL: (*v1alpha1.URL)(in[i].URL), Style: in[i].Style, Name: in[i].Name, Value: in[i].Value, @@ -370,7 +371,7 @@ func convertSlackConfigTo(in SlackConfig) v1alpha1.SlackConfig { Username: in.Username, Color: in.Color, Title: in.Title, - TitleLink: in.TitleLink, + TitleLink: (*v1alpha1.URL)(in.TitleLink), Pretext: in.Pretext, Text: in.Text, Fields: convertSlackFieldsTo(in.Fields), @@ -379,13 +380,14 @@ func convertSlackConfigTo(in SlackConfig) v1alpha1.SlackConfig { Fallback: in.Fallback, CallbackID: in.CallbackID, IconEmoji: in.IconEmoji, - IconURL: in.IconURL, - ImageURL: in.ImageURL, - ThumbURL: in.ThumbURL, + IconURL: (*v1alpha1.URL)(in.IconURL), + ImageURL: (*v1alpha1.URL)(in.ImageURL), + ThumbURL: (*v1alpha1.URL)(in.ThumbURL), LinkNames: in.LinkNames, MrkdwnIn: in.MrkdwnIn, Actions: convertSlackActionsTo(in.Actions), HTTPConfig: convertHTTPConfigTo(in.HTTPConfig), + Timeout: in.Timeout, } } @@ -402,7 +404,7 @@ func convertWebexConfigTo(in WebexConfig) v1alpha1.WebexConfig { func convertWebhookConfigTo(in WebhookConfig) v1alpha1.WebhookConfig { return v1alpha1.WebhookConfig{ SendResolved: in.SendResolved, - URL: in.URL, + URL: (*v1alpha1.URL)(in.URL), URLSecret: convertSecretKeySelectorTo(in.URLSecret), HTTPConfig: convertHTTPConfigTo(in.HTTPConfig), MaxAlerts: in.MaxAlerts, @@ -414,7 +416,7 @@ func convertWeChatConfigTo(in WeChatConfig) v1alpha1.WeChatConfig { return v1alpha1.WeChatConfig{ SendResolved: in.SendResolved, APISecret: convertSecretKeySelectorTo(in.APISecret), - APIURL: in.APIURL, + APIURL: (*v1alpha1.URL)(in.APIURL), CorpID: in.CorpID, AgentID: in.AgentID, ToUser: in.ToUser, @@ -449,7 +451,7 @@ func convertVictorOpsConfigTo(in VictorOpsConfig) v1alpha1.VictorOpsConfig { return v1alpha1.VictorOpsConfig{ SendResolved: in.SendResolved, APIKey: convertSecretKeySelectorTo(in.APIKey), - APIURL: in.APIURL, + APIURL: (*v1alpha1.URL)(in.APIURL), RoutingKey: in.RoutingKey, MessageType: in.MessageType, EntityDisplayName: in.EntityDisplayName, @@ -469,7 +471,7 @@ func convertPushoverConfigTo(in PushoverConfig) v1alpha1.PushoverConfig { TokenFile: in.TokenFile, Title: in.Title, Message: in.Message, - URL: in.URL, + URL: (*v1alpha1.URL)(in.URL), URLTitle: in.URLTitle, Device: in.Device, Sound: in.Sound, @@ -500,7 +502,7 @@ func convertSNSConfigTo(in SNSConfig) v1alpha1.SNSConfig { func convertTelegramConfigTo(in TelegramConfig) v1alpha1.TelegramConfig { return v1alpha1.TelegramConfig{ SendResolved: in.SendResolved, - APIURL: in.APIURL, + APIURL: (*v1alpha1.URL)(in.APIURL), BotToken: convertSecretKeySelectorTo(in.BotToken), BotTokenFile: in.BotTokenFile, ChatID: in.ChatID, diff --git a/vendor/github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1beta1/zz_generated.deepcopy.go b/vendor/github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1beta1/zz_generated.deepcopy.go index 2b7c061ff6b..fbb8f218333 100644 --- a/vendor/github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1beta1/zz_generated.deepcopy.go +++ b/vendor/github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1beta1/zz_generated.deepcopy.go @@ -30,6 +30,7 @@ func (in *AlertmanagerConfig) DeepCopyInto(out *AlertmanagerConfig) { out.TypeMeta = in.TypeMeta in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) in.Spec.DeepCopyInto(&out.Spec) + in.Status.DeepCopyInto(&out.Status) } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new AlertmanagerConfig. @@ -438,6 +439,11 @@ func (in *OpsGenieConfig) DeepCopyInto(out *OpsGenieConfig) { *out = new(SecretKeySelector) **out = **in } + if in.APIURL != nil { + in, out := &in.APIURL, &out.APIURL + *out = new(URL) + **out = **in + } if in.Details != nil { in, out := &in.Details, &out.Details *out = make([]KeyValue, len(*in)) @@ -498,6 +504,46 @@ func (in *PagerDutyConfig) DeepCopyInto(out *PagerDutyConfig) { *out = new(SecretKeySelector) **out = **in } + if in.URL != nil { + in, out := &in.URL, &out.URL + *out = new(URL) + **out = **in + } + if in.Client != nil { + in, out := &in.Client, &out.Client + *out = new(string) + **out = **in + } + if in.ClientURL != nil { + in, out := &in.ClientURL, &out.ClientURL + *out = new(URL) + **out = **in + } + if in.Description != nil { + in, out := &in.Description, &out.Description + *out = new(string) + **out = **in + } + if in.Severity != nil { + in, out := &in.Severity, &out.Severity + *out = new(string) + **out = **in + } + if in.Class != nil { + in, out := &in.Class, &out.Class + *out = new(string) + **out = **in + } + if in.Group != nil { + in, out := &in.Group, &out.Group + *out = new(string) + **out = **in + } + if in.Component != nil { + in, out := &in.Component, &out.Component + *out = new(string) + **out = **in + } if in.Details != nil { in, out := &in.Details, &out.Details *out = make([]KeyValue, len(*in)) @@ -506,12 +552,16 @@ func (in *PagerDutyConfig) DeepCopyInto(out *PagerDutyConfig) { if in.PagerDutyImageConfigs != nil { in, out := &in.PagerDutyImageConfigs, &out.PagerDutyImageConfigs *out = make([]PagerDutyImageConfig, len(*in)) - copy(*out, *in) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } } if in.PagerDutyLinkConfigs != nil { in, out := &in.PagerDutyLinkConfigs, &out.PagerDutyLinkConfigs *out = make([]PagerDutyLinkConfig, len(*in)) - copy(*out, *in) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } } if in.HTTPConfig != nil { in, out := &in.HTTPConfig, &out.HTTPConfig @@ -523,6 +573,11 @@ func (in *PagerDutyConfig) DeepCopyInto(out *PagerDutyConfig) { *out = new(string) **out = **in } + if in.Timeout != nil { + in, out := &in.Timeout, &out.Timeout + *out = new(monitoringv1.Duration) + **out = **in + } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PagerDutyConfig. @@ -538,6 +593,21 @@ func (in *PagerDutyConfig) DeepCopy() *PagerDutyConfig { // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *PagerDutyImageConfig) DeepCopyInto(out *PagerDutyImageConfig) { *out = *in + if in.Src != nil { + in, out := &in.Src, &out.Src + *out = new(string) + **out = **in + } + if in.Href != nil { + in, out := &in.Href, &out.Href + *out = new(URL) + **out = **in + } + if in.Alt != nil { + in, out := &in.Alt, &out.Alt + *out = new(string) + **out = **in + } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PagerDutyImageConfig. @@ -553,6 +623,16 @@ func (in *PagerDutyImageConfig) DeepCopy() *PagerDutyImageConfig { // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *PagerDutyLinkConfig) DeepCopyInto(out *PagerDutyLinkConfig) { *out = *in + if in.Href != nil { + in, out := &in.Href, &out.Href + *out = new(URL) + **out = **in + } + if in.Text != nil { + in, out := &in.Text, &out.Text + *out = new(string) + **out = **in + } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PagerDutyLinkConfig. @@ -593,6 +673,26 @@ func (in *PushoverConfig) DeepCopyInto(out *PushoverConfig) { *out = new(string) **out = **in } + if in.Title != nil { + in, out := &in.Title, &out.Title + *out = new(string) + **out = **in + } + if in.Message != nil { + in, out := &in.Message, &out.Message + *out = new(string) + **out = **in + } + if in.URL != nil { + in, out := &in.URL, &out.URL + *out = new(URL) + **out = **in + } + if in.URLTitle != nil { + in, out := &in.URLTitle, &out.URLTitle + *out = new(string) + **out = **in + } if in.TTL != nil { in, out := &in.TTL, &out.TTL *out = new(monitoringv1.Duration) @@ -603,6 +703,26 @@ func (in *PushoverConfig) DeepCopyInto(out *PushoverConfig) { *out = new(string) **out = **in } + if in.Sound != nil { + in, out := &in.Sound, &out.Sound + *out = new(string) + **out = **in + } + if in.Priority != nil { + in, out := &in.Priority, &out.Priority + *out = new(string) + **out = **in + } + if in.Retry != nil { + in, out := &in.Retry, &out.Retry + *out = new(string) + **out = **in + } + if in.Expire != nil { + in, out := &in.Expire, &out.Expire + *out = new(string) + **out = **in + } if in.HTML != nil { in, out := &in.HTML, &out.HTML *out = new(bool) @@ -1008,10 +1128,30 @@ func (in *SecretKeySelector) DeepCopy() *SecretKeySelector { // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *SlackAction) DeepCopyInto(out *SlackAction) { *out = *in + if in.URL != nil { + in, out := &in.URL, &out.URL + *out = new(URL) + **out = **in + } + if in.Style != nil { + in, out := &in.Style, &out.Style + *out = new(string) + **out = **in + } + if in.Name != nil { + in, out := &in.Name, &out.Name + *out = new(string) + **out = **in + } + if in.Value != nil { + in, out := &in.Value, &out.Value + *out = new(string) + **out = **in + } if in.ConfirmField != nil { in, out := &in.ConfirmField, &out.ConfirmField *out = new(SlackConfirmationField) - **out = **in + (*in).DeepCopyInto(*out) } } @@ -1038,6 +1178,41 @@ func (in *SlackConfig) DeepCopyInto(out *SlackConfig) { *out = new(SecretKeySelector) **out = **in } + if in.Channel != nil { + in, out := &in.Channel, &out.Channel + *out = new(string) + **out = **in + } + if in.Username != nil { + in, out := &in.Username, &out.Username + *out = new(string) + **out = **in + } + if in.Color != nil { + in, out := &in.Color, &out.Color + *out = new(string) + **out = **in + } + if in.Title != nil { + in, out := &in.Title, &out.Title + *out = new(string) + **out = **in + } + if in.TitleLink != nil { + in, out := &in.TitleLink, &out.TitleLink + *out = new(URL) + **out = **in + } + if in.Pretext != nil { + in, out := &in.Pretext, &out.Pretext + *out = new(string) + **out = **in + } + if in.Text != nil { + in, out := &in.Text, &out.Text + *out = new(string) + **out = **in + } if in.Fields != nil { in, out := &in.Fields, &out.Fields *out = make([]SlackField, len(*in)) @@ -1045,6 +1220,51 @@ func (in *SlackConfig) DeepCopyInto(out *SlackConfig) { (*in)[i].DeepCopyInto(&(*out)[i]) } } + if in.ShortFields != nil { + in, out := &in.ShortFields, &out.ShortFields + *out = new(bool) + **out = **in + } + if in.Footer != nil { + in, out := &in.Footer, &out.Footer + *out = new(string) + **out = **in + } + if in.Fallback != nil { + in, out := &in.Fallback, &out.Fallback + *out = new(string) + **out = **in + } + if in.CallbackID != nil { + in, out := &in.CallbackID, &out.CallbackID + *out = new(string) + **out = **in + } + if in.IconEmoji != nil { + in, out := &in.IconEmoji, &out.IconEmoji + *out = new(string) + **out = **in + } + if in.IconURL != nil { + in, out := &in.IconURL, &out.IconURL + *out = new(URL) + **out = **in + } + if in.ImageURL != nil { + in, out := &in.ImageURL, &out.ImageURL + *out = new(URL) + **out = **in + } + if in.ThumbURL != nil { + in, out := &in.ThumbURL, &out.ThumbURL + *out = new(URL) + **out = **in + } + if in.LinkNames != nil { + in, out := &in.LinkNames, &out.LinkNames + *out = new(bool) + **out = **in + } if in.MrkdwnIn != nil { in, out := &in.MrkdwnIn, &out.MrkdwnIn *out = make([]string, len(*in)) @@ -1062,6 +1282,11 @@ func (in *SlackConfig) DeepCopyInto(out *SlackConfig) { *out = new(HTTPConfig) (*in).DeepCopyInto(*out) } + if in.Timeout != nil { + in, out := &in.Timeout, &out.Timeout + *out = new(monitoringv1.Duration) + **out = **in + } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new SlackConfig. @@ -1077,6 +1302,21 @@ func (in *SlackConfig) DeepCopy() *SlackConfig { // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *SlackConfirmationField) DeepCopyInto(out *SlackConfirmationField) { *out = *in + if in.Title != nil { + in, out := &in.Title, &out.Title + *out = new(string) + **out = **in + } + if in.OkText != nil { + in, out := &in.OkText, &out.OkText + *out = new(string) + **out = **in + } + if in.DismissText != nil { + in, out := &in.DismissText, &out.DismissText + *out = new(string) + **out = **in + } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new SlackConfirmationField. @@ -1117,6 +1357,11 @@ func (in *TelegramConfig) DeepCopyInto(out *TelegramConfig) { *out = new(bool) **out = **in } + if in.APIURL != nil { + in, out := &in.APIURL, &out.APIURL + *out = new(URL) + **out = **in + } if in.BotToken != nil { in, out := &in.BotToken, &out.BotToken *out = new(SecretKeySelector) @@ -1244,6 +1489,31 @@ func (in *VictorOpsConfig) DeepCopyInto(out *VictorOpsConfig) { *out = new(SecretKeySelector) **out = **in } + if in.APIURL != nil { + in, out := &in.APIURL, &out.APIURL + *out = new(URL) + **out = **in + } + if in.MessageType != nil { + in, out := &in.MessageType, &out.MessageType + *out = new(string) + **out = **in + } + if in.EntityDisplayName != nil { + in, out := &in.EntityDisplayName, &out.EntityDisplayName + *out = new(string) + **out = **in + } + if in.StateMessage != nil { + in, out := &in.StateMessage, &out.StateMessage + *out = new(string) + **out = **in + } + if in.MonitoringTool != nil { + in, out := &in.MonitoringTool, &out.MonitoringTool + *out = new(string) + **out = **in + } if in.CustomFields != nil { in, out := &in.CustomFields, &out.CustomFields *out = make([]KeyValue, len(*in)) @@ -1279,6 +1549,11 @@ func (in *WeChatConfig) DeepCopyInto(out *WeChatConfig) { *out = new(SecretKeySelector) **out = **in } + if in.APIURL != nil { + in, out := &in.APIURL, &out.APIURL + *out = new(URL) + **out = **in + } if in.HTTPConfig != nil { in, out := &in.HTTPConfig, &out.HTTPConfig *out = new(HTTPConfig) @@ -1341,7 +1616,7 @@ func (in *WebhookConfig) DeepCopyInto(out *WebhookConfig) { } if in.URL != nil { in, out := &in.URL, &out.URL - *out = new(string) + *out = new(URL) **out = **in } if in.URLSecret != nil { diff --git a/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1/alertmanagerglobalconfig.go b/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1/alertmanagerglobalconfig.go index a9cd77c60a9..47a3582cfa2 100644 --- a/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1/alertmanagerglobalconfig.go +++ b/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1/alertmanagerglobalconfig.go @@ -24,19 +24,19 @@ import ( // AlertmanagerGlobalConfigApplyConfiguration represents a declarative configuration of the AlertmanagerGlobalConfig type for use // with apply. type AlertmanagerGlobalConfigApplyConfiguration struct { - SMTPConfig *GlobalSMTPConfigApplyConfiguration `json:"smtp,omitempty"` - ResolveTimeout *monitoringv1.Duration `json:"resolveTimeout,omitempty"` - HTTPConfig *HTTPConfigApplyConfiguration `json:"httpConfig,omitempty"` - SlackAPIURL *corev1.SecretKeySelector `json:"slackApiUrl,omitempty"` - OpsGenieAPIURL *corev1.SecretKeySelector `json:"opsGenieApiUrl,omitempty"` - OpsGenieAPIKey *corev1.SecretKeySelector `json:"opsGenieApiKey,omitempty"` - PagerdutyURL *monitoringv1.URL `json:"pagerdutyUrl,omitempty"` - TelegramConfig *GlobalTelegramConfigApplyConfiguration `json:"telegram,omitempty"` - JiraConfig *GlobalJiraConfigApplyConfiguration `json:"jira,omitempty"` - VictorOpsConfig *GlobalVictorOpsConfigApplyConfiguration `json:"victorops,omitempty"` - RocketChatConfig *GlobalRocketChatConfigApplyConfiguration `json:"rocketChat,omitempty"` - WebexConfig *GlobalWebexConfigApplyConfiguration `json:"webex,omitempty"` - WeChatConfig *GlobalWeChatConfigApplyConfiguration `json:"wechat,omitempty"` + SMTPConfig *GlobalSMTPConfigApplyConfiguration `json:"smtp,omitempty"` + ResolveTimeout *monitoringv1.Duration `json:"resolveTimeout,omitempty"` + HTTPConfigWithProxy *HTTPConfigWithProxyApplyConfiguration `json:"httpConfig,omitempty"` + SlackAPIURL *corev1.SecretKeySelector `json:"slackApiUrl,omitempty"` + OpsGenieAPIURL *corev1.SecretKeySelector `json:"opsGenieApiUrl,omitempty"` + OpsGenieAPIKey *corev1.SecretKeySelector `json:"opsGenieApiKey,omitempty"` + PagerdutyURL *monitoringv1.URL `json:"pagerdutyUrl,omitempty"` + TelegramConfig *GlobalTelegramConfigApplyConfiguration `json:"telegram,omitempty"` + JiraConfig *GlobalJiraConfigApplyConfiguration `json:"jira,omitempty"` + VictorOpsConfig *GlobalVictorOpsConfigApplyConfiguration `json:"victorops,omitempty"` + RocketChatConfig *GlobalRocketChatConfigApplyConfiguration `json:"rocketChat,omitempty"` + WebexConfig *GlobalWebexConfigApplyConfiguration `json:"webex,omitempty"` + WeChatConfig *GlobalWeChatConfigApplyConfiguration `json:"wechat,omitempty"` } // AlertmanagerGlobalConfigApplyConfiguration constructs a declarative configuration of the AlertmanagerGlobalConfig type for use with @@ -61,11 +61,11 @@ func (b *AlertmanagerGlobalConfigApplyConfiguration) WithResolveTimeout(value mo return b } -// WithHTTPConfig sets the HTTPConfig field in the declarative configuration to the given value +// WithHTTPConfigWithProxy sets the HTTPConfigWithProxy field in the declarative configuration to the given value // and returns the receiver, so that objects can be built by chaining "With" function invocations. -// If called multiple times, the HTTPConfig field is set to the value of the last call. -func (b *AlertmanagerGlobalConfigApplyConfiguration) WithHTTPConfig(value *HTTPConfigApplyConfiguration) *AlertmanagerGlobalConfigApplyConfiguration { - b.HTTPConfig = value +// If called multiple times, the HTTPConfigWithProxy field is set to the value of the last call. +func (b *AlertmanagerGlobalConfigApplyConfiguration) WithHTTPConfigWithProxy(value *HTTPConfigWithProxyApplyConfiguration) *AlertmanagerGlobalConfigApplyConfiguration { + b.HTTPConfigWithProxy = value return b } diff --git a/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1/alertmanagerspec.go b/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1/alertmanagerspec.go index ef35441316d..89f7e447387 100644 --- a/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1/alertmanagerspec.go +++ b/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1/alertmanagerspec.go @@ -60,6 +60,8 @@ type AlertmanagerSpecApplyConfiguration struct { ServiceName *string `json:"serviceName,omitempty"` ServiceAccountName *string `json:"serviceAccountName,omitempty"` ListenLocal *bool `json:"listenLocal,omitempty"` + PodManagementPolicy *monitoringv1.PodManagementPolicyType `json:"podManagementPolicy,omitempty"` + UpdateStrategy *StatefulSetUpdateStrategyApplyConfiguration `json:"updateStrategy,omitempty"` Containers []corev1.Container `json:"containers,omitempty"` InitContainers []corev1.Container `json:"initContainers,omitempty"` PriorityClassName *string `json:"priorityClassName,omitempty"` @@ -385,6 +387,22 @@ func (b *AlertmanagerSpecApplyConfiguration) WithListenLocal(value bool) *Alertm return b } +// WithPodManagementPolicy sets the PodManagementPolicy field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the PodManagementPolicy field is set to the value of the last call. +func (b *AlertmanagerSpecApplyConfiguration) WithPodManagementPolicy(value monitoringv1.PodManagementPolicyType) *AlertmanagerSpecApplyConfiguration { + b.PodManagementPolicy = &value + return b +} + +// WithUpdateStrategy sets the UpdateStrategy field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the UpdateStrategy field is set to the value of the last call. +func (b *AlertmanagerSpecApplyConfiguration) WithUpdateStrategy(value *StatefulSetUpdateStrategyApplyConfiguration) *AlertmanagerSpecApplyConfiguration { + b.UpdateStrategy = value + return b +} + // WithContainers adds the given value to the Containers field in the declarative configuration // and returns the receiver, so that objects can be build by chaining "With" function invocations. // If called multiple times, values provided by each call will be appended to the Containers field. diff --git a/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1/azuread.go b/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1/azuread.go index 758881efe3b..22e0b20ef85 100644 --- a/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1/azuread.go +++ b/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1/azuread.go @@ -19,10 +19,12 @@ package v1 // AzureADApplyConfiguration represents a declarative configuration of the AzureAD type for use // with apply. type AzureADApplyConfiguration struct { - Cloud *string `json:"cloud,omitempty"` - ManagedIdentity *ManagedIdentityApplyConfiguration `json:"managedIdentity,omitempty"` - OAuth *AzureOAuthApplyConfiguration `json:"oauth,omitempty"` - SDK *AzureSDKApplyConfiguration `json:"sdk,omitempty"` + Cloud *string `json:"cloud,omitempty"` + ManagedIdentity *ManagedIdentityApplyConfiguration `json:"managedIdentity,omitempty"` + OAuth *AzureOAuthApplyConfiguration `json:"oauth,omitempty"` + SDK *AzureSDKApplyConfiguration `json:"sdk,omitempty"` + WorkloadIdentity *AzureWorkloadIdentityApplyConfiguration `json:"workloadIdentity,omitempty"` + Scope *string `json:"scope,omitempty"` } // AzureADApplyConfiguration constructs a declarative configuration of the AzureAD type for use with @@ -62,3 +64,19 @@ func (b *AzureADApplyConfiguration) WithSDK(value *AzureSDKApplyConfiguration) * b.SDK = value return b } + +// WithWorkloadIdentity sets the WorkloadIdentity field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the WorkloadIdentity field is set to the value of the last call. +func (b *AzureADApplyConfiguration) WithWorkloadIdentity(value *AzureWorkloadIdentityApplyConfiguration) *AzureADApplyConfiguration { + b.WorkloadIdentity = value + return b +} + +// WithScope sets the Scope field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the Scope field is set to the value of the last call. +func (b *AzureADApplyConfiguration) WithScope(value string) *AzureADApplyConfiguration { + b.Scope = &value + return b +} diff --git a/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1/azureworkloadidentity.go b/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1/azureworkloadidentity.go new file mode 100644 index 00000000000..0db86616bf3 --- /dev/null +++ b/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1/azureworkloadidentity.go @@ -0,0 +1,46 @@ +// Copyright The prometheus-operator Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// Code generated by applyconfiguration-gen. DO NOT EDIT. + +package v1 + +// AzureWorkloadIdentityApplyConfiguration represents a declarative configuration of the AzureWorkloadIdentity type for use +// with apply. +type AzureWorkloadIdentityApplyConfiguration struct { + ClientID *string `json:"clientId,omitempty"` + TenantID *string `json:"tenantId,omitempty"` +} + +// AzureWorkloadIdentityApplyConfiguration constructs a declarative configuration of the AzureWorkloadIdentity type for use with +// apply. +func AzureWorkloadIdentity() *AzureWorkloadIdentityApplyConfiguration { + return &AzureWorkloadIdentityApplyConfiguration{} +} + +// WithClientID sets the ClientID field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the ClientID field is set to the value of the last call. +func (b *AzureWorkloadIdentityApplyConfiguration) WithClientID(value string) *AzureWorkloadIdentityApplyConfiguration { + b.ClientID = &value + return b +} + +// WithTenantID sets the TenantID field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the TenantID field is set to the value of the last call. +func (b *AzureWorkloadIdentityApplyConfiguration) WithTenantID(value string) *AzureWorkloadIdentityApplyConfiguration { + b.TenantID = &value + return b +} diff --git a/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1/commonprometheusfields.go b/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1/commonprometheusfields.go index a476b86e73d..07d2e308979 100644 --- a/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1/commonprometheusfields.go +++ b/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1/commonprometheusfields.go @@ -76,6 +76,8 @@ type CommonPrometheusFieldsApplyConfiguration struct { DNSPolicy *monitoringv1.DNSPolicy `json:"dnsPolicy,omitempty"` DNSConfig *PodDNSConfigApplyConfiguration `json:"dnsConfig,omitempty"` ListenLocal *bool `json:"listenLocal,omitempty"` + PodManagementPolicy *monitoringv1.PodManagementPolicyType `json:"podManagementPolicy,omitempty"` + UpdateStrategy *StatefulSetUpdateStrategyApplyConfiguration `json:"updateStrategy,omitempty"` EnableServiceLinks *bool `json:"enableServiceLinks,omitempty"` Containers []corev1.Container `json:"containers,omitempty"` InitContainers []corev1.Container `json:"initContainers,omitempty"` @@ -98,6 +100,7 @@ type CommonPrometheusFieldsApplyConfiguration struct { NameValidationScheme *monitoringv1.NameValidationSchemeOptions `json:"nameValidationScheme,omitempty"` NameEscapingScheme *monitoringv1.NameEscapingSchemeOptions `json:"nameEscapingScheme,omitempty"` ConvertClassicHistogramsToNHCB *bool `json:"convertClassicHistogramsToNHCB,omitempty"` + ScrapeNativeHistograms *bool `json:"scrapeNativeHistograms,omitempty"` ScrapeClassicHistograms *bool `json:"scrapeClassicHistograms,omitempty"` MinReadySeconds *int32 `json:"minReadySeconds,omitempty"` HostAliases []HostAliasApplyConfiguration `json:"hostAliases,omitempty"` @@ -106,7 +109,7 @@ type CommonPrometheusFieldsApplyConfiguration struct { ExcludedFromEnforcement []ObjectReferenceApplyConfiguration `json:"excludedFromEnforcement,omitempty"` HostNetwork *bool `json:"hostNetwork,omitempty"` PodTargetLabels []string `json:"podTargetLabels,omitempty"` - TracingConfig *PrometheusTracingConfigApplyConfiguration `json:"tracingConfig,omitempty"` + TracingConfig *TracingConfigApplyConfiguration `json:"tracingConfig,omitempty"` BodySizeLimit *monitoringv1.ByteSize `json:"bodySizeLimit,omitempty"` SampleLimit *uint64 `json:"sampleLimit,omitempty"` TargetLimit *uint64 `json:"targetLimit,omitempty"` @@ -572,6 +575,22 @@ func (b *CommonPrometheusFieldsApplyConfiguration) WithListenLocal(value bool) * return b } +// WithPodManagementPolicy sets the PodManagementPolicy field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the PodManagementPolicy field is set to the value of the last call. +func (b *CommonPrometheusFieldsApplyConfiguration) WithPodManagementPolicy(value monitoringv1.PodManagementPolicyType) *CommonPrometheusFieldsApplyConfiguration { + b.PodManagementPolicy = &value + return b +} + +// WithUpdateStrategy sets the UpdateStrategy field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the UpdateStrategy field is set to the value of the last call. +func (b *CommonPrometheusFieldsApplyConfiguration) WithUpdateStrategy(value *StatefulSetUpdateStrategyApplyConfiguration) *CommonPrometheusFieldsApplyConfiguration { + b.UpdateStrategy = value + return b +} + // WithEnableServiceLinks sets the EnableServiceLinks field in the declarative configuration to the given value // and returns the receiver, so that objects can be built by chaining "With" function invocations. // If called multiple times, the EnableServiceLinks field is set to the value of the last call. @@ -752,6 +771,14 @@ func (b *CommonPrometheusFieldsApplyConfiguration) WithConvertClassicHistogramsT return b } +// WithScrapeNativeHistograms sets the ScrapeNativeHistograms field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the ScrapeNativeHistograms field is set to the value of the last call. +func (b *CommonPrometheusFieldsApplyConfiguration) WithScrapeNativeHistograms(value bool) *CommonPrometheusFieldsApplyConfiguration { + b.ScrapeNativeHistograms = &value + return b +} + // WithScrapeClassicHistograms sets the ScrapeClassicHistograms field in the declarative configuration to the given value // and returns the receiver, so that objects can be built by chaining "With" function invocations. // If called multiple times, the ScrapeClassicHistograms field is set to the value of the last call. @@ -836,7 +863,7 @@ func (b *CommonPrometheusFieldsApplyConfiguration) WithPodTargetLabels(values .. // WithTracingConfig sets the TracingConfig field in the declarative configuration to the given value // and returns the receiver, so that objects can be built by chaining "With" function invocations. // If called multiple times, the TracingConfig field is set to the value of the last call. -func (b *CommonPrometheusFieldsApplyConfiguration) WithTracingConfig(value *PrometheusTracingConfigApplyConfiguration) *CommonPrometheusFieldsApplyConfiguration { +func (b *CommonPrometheusFieldsApplyConfiguration) WithTracingConfig(value *TracingConfigApplyConfiguration) *CommonPrometheusFieldsApplyConfiguration { b.TracingConfig = value return b } diff --git a/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1/endpoint.go b/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1/endpoint.go index 84ff92f6b71..0deb3e8d17d 100644 --- a/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1/endpoint.go +++ b/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1/endpoint.go @@ -25,28 +25,21 @@ import ( // EndpointApplyConfiguration represents a declarative configuration of the Endpoint type for use // with apply. type EndpointApplyConfiguration struct { - Port *string `json:"port,omitempty"` - TargetPort *intstr.IntOrString `json:"targetPort,omitempty"` - Path *string `json:"path,omitempty"` - Scheme *monitoringv1.Scheme `json:"scheme,omitempty"` - Params map[string][]string `json:"params,omitempty"` - Interval *monitoringv1.Duration `json:"interval,omitempty"` - ScrapeTimeout *monitoringv1.Duration `json:"scrapeTimeout,omitempty"` - TLSConfig *TLSConfigApplyConfiguration `json:"tlsConfig,omitempty"` - BearerTokenFile *string `json:"bearerTokenFile,omitempty"` - BearerTokenSecret *corev1.SecretKeySelector `json:"bearerTokenSecret,omitempty"` - Authorization *SafeAuthorizationApplyConfiguration `json:"authorization,omitempty"` - HonorLabels *bool `json:"honorLabels,omitempty"` - HonorTimestamps *bool `json:"honorTimestamps,omitempty"` - TrackTimestampsStaleness *bool `json:"trackTimestampsStaleness,omitempty"` - BasicAuth *BasicAuthApplyConfiguration `json:"basicAuth,omitempty"` - OAuth2 *OAuth2ApplyConfiguration `json:"oauth2,omitempty"` - MetricRelabelConfigs []RelabelConfigApplyConfiguration `json:"metricRelabelings,omitempty"` - RelabelConfigs []RelabelConfigApplyConfiguration `json:"relabelings,omitempty"` - ProxyConfigApplyConfiguration `json:",inline"` - FollowRedirects *bool `json:"followRedirects,omitempty"` - EnableHttp2 *bool `json:"enableHttp2,omitempty"` - FilterRunning *bool `json:"filterRunning,omitempty"` + Port *string `json:"port,omitempty"` + TargetPort *intstr.IntOrString `json:"targetPort,omitempty"` + Path *string `json:"path,omitempty"` + Scheme *monitoringv1.Scheme `json:"scheme,omitempty"` + Params map[string][]string `json:"params,omitempty"` + Interval *monitoringv1.Duration `json:"interval,omitempty"` + ScrapeTimeout *monitoringv1.Duration `json:"scrapeTimeout,omitempty"` + HonorLabels *bool `json:"honorLabels,omitempty"` + HonorTimestamps *bool `json:"honorTimestamps,omitempty"` + TrackTimestampsStaleness *bool `json:"trackTimestampsStaleness,omitempty"` + MetricRelabelConfigs []RelabelConfigApplyConfiguration `json:"metricRelabelings,omitempty"` + RelabelConfigs []RelabelConfigApplyConfiguration `json:"relabelings,omitempty"` + FilterRunning *bool `json:"filterRunning,omitempty"` + BearerTokenFile *string `json:"bearerTokenFile,omitempty"` + HTTPConfigWithProxyAndTLSFilesApplyConfiguration `json:",inline"` } // EndpointApplyConfiguration constructs a declarative configuration of the Endpoint type for use with @@ -117,38 +110,6 @@ func (b *EndpointApplyConfiguration) WithScrapeTimeout(value monitoringv1.Durati return b } -// WithTLSConfig sets the TLSConfig field in the declarative configuration to the given value -// and returns the receiver, so that objects can be built by chaining "With" function invocations. -// If called multiple times, the TLSConfig field is set to the value of the last call. -func (b *EndpointApplyConfiguration) WithTLSConfig(value *TLSConfigApplyConfiguration) *EndpointApplyConfiguration { - b.TLSConfig = value - return b -} - -// WithBearerTokenFile sets the BearerTokenFile field in the declarative configuration to the given value -// and returns the receiver, so that objects can be built by chaining "With" function invocations. -// If called multiple times, the BearerTokenFile field is set to the value of the last call. -func (b *EndpointApplyConfiguration) WithBearerTokenFile(value string) *EndpointApplyConfiguration { - b.BearerTokenFile = &value - return b -} - -// WithBearerTokenSecret sets the BearerTokenSecret field in the declarative configuration to the given value -// and returns the receiver, so that objects can be built by chaining "With" function invocations. -// If called multiple times, the BearerTokenSecret field is set to the value of the last call. -func (b *EndpointApplyConfiguration) WithBearerTokenSecret(value corev1.SecretKeySelector) *EndpointApplyConfiguration { - b.BearerTokenSecret = &value - return b -} - -// WithAuthorization sets the Authorization field in the declarative configuration to the given value -// and returns the receiver, so that objects can be built by chaining "With" function invocations. -// If called multiple times, the Authorization field is set to the value of the last call. -func (b *EndpointApplyConfiguration) WithAuthorization(value *SafeAuthorizationApplyConfiguration) *EndpointApplyConfiguration { - b.Authorization = value - return b -} - // WithHonorLabels sets the HonorLabels field in the declarative configuration to the given value // and returns the receiver, so that objects can be built by chaining "With" function invocations. // If called multiple times, the HonorLabels field is set to the value of the last call. @@ -173,22 +134,6 @@ func (b *EndpointApplyConfiguration) WithTrackTimestampsStaleness(value bool) *E return b } -// WithBasicAuth sets the BasicAuth field in the declarative configuration to the given value -// and returns the receiver, so that objects can be built by chaining "With" function invocations. -// If called multiple times, the BasicAuth field is set to the value of the last call. -func (b *EndpointApplyConfiguration) WithBasicAuth(value *BasicAuthApplyConfiguration) *EndpointApplyConfiguration { - b.BasicAuth = value - return b -} - -// WithOAuth2 sets the OAuth2 field in the declarative configuration to the given value -// and returns the receiver, so that objects can be built by chaining "With" function invocations. -// If called multiple times, the OAuth2 field is set to the value of the last call. -func (b *EndpointApplyConfiguration) WithOAuth2(value *OAuth2ApplyConfiguration) *EndpointApplyConfiguration { - b.OAuth2 = value - return b -} - // WithMetricRelabelConfigs adds the given value to the MetricRelabelConfigs field in the declarative configuration // and returns the receiver, so that objects can be build by chaining "With" function invocations. // If called multiple times, values provided by each call will be appended to the MetricRelabelConfigs field. @@ -215,6 +160,78 @@ func (b *EndpointApplyConfiguration) WithRelabelConfigs(values ...*RelabelConfig return b } +// WithFilterRunning sets the FilterRunning field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the FilterRunning field is set to the value of the last call. +func (b *EndpointApplyConfiguration) WithFilterRunning(value bool) *EndpointApplyConfiguration { + b.FilterRunning = &value + return b +} + +// WithBearerTokenFile sets the BearerTokenFile field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the BearerTokenFile field is set to the value of the last call. +func (b *EndpointApplyConfiguration) WithBearerTokenFile(value string) *EndpointApplyConfiguration { + b.BearerTokenFile = &value + return b +} + +// WithAuthorization sets the Authorization field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the Authorization field is set to the value of the last call. +func (b *EndpointApplyConfiguration) WithAuthorization(value *SafeAuthorizationApplyConfiguration) *EndpointApplyConfiguration { + b.HTTPConfigWithoutTLSApplyConfiguration.Authorization = value + return b +} + +// WithBasicAuth sets the BasicAuth field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the BasicAuth field is set to the value of the last call. +func (b *EndpointApplyConfiguration) WithBasicAuth(value *BasicAuthApplyConfiguration) *EndpointApplyConfiguration { + b.HTTPConfigWithoutTLSApplyConfiguration.BasicAuth = value + return b +} + +// WithOAuth2 sets the OAuth2 field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the OAuth2 field is set to the value of the last call. +func (b *EndpointApplyConfiguration) WithOAuth2(value *OAuth2ApplyConfiguration) *EndpointApplyConfiguration { + b.HTTPConfigWithoutTLSApplyConfiguration.OAuth2 = value + return b +} + +// WithBearerTokenSecret sets the BearerTokenSecret field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the BearerTokenSecret field is set to the value of the last call. +func (b *EndpointApplyConfiguration) WithBearerTokenSecret(value corev1.SecretKeySelector) *EndpointApplyConfiguration { + b.HTTPConfigWithoutTLSApplyConfiguration.BearerTokenSecret = &value + return b +} + +// WithFollowRedirects sets the FollowRedirects field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the FollowRedirects field is set to the value of the last call. +func (b *EndpointApplyConfiguration) WithFollowRedirects(value bool) *EndpointApplyConfiguration { + b.HTTPConfigWithoutTLSApplyConfiguration.FollowRedirects = &value + return b +} + +// WithEnableHTTP2 sets the EnableHTTP2 field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the EnableHTTP2 field is set to the value of the last call. +func (b *EndpointApplyConfiguration) WithEnableHTTP2(value bool) *EndpointApplyConfiguration { + b.HTTPConfigWithoutTLSApplyConfiguration.EnableHTTP2 = &value + return b +} + +// WithTLSConfig sets the TLSConfig field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the TLSConfig field is set to the value of the last call. +func (b *EndpointApplyConfiguration) WithTLSConfig(value *TLSConfigApplyConfiguration) *EndpointApplyConfiguration { + b.HTTPConfigWithTLSFilesApplyConfiguration.TLSConfig = value + return b +} + // WithProxyURL sets the ProxyURL field in the declarative configuration to the given value // and returns the receiver, so that objects can be built by chaining "With" function invocations. // If called multiple times, the ProxyURL field is set to the value of the last call. @@ -252,27 +269,3 @@ func (b *EndpointApplyConfiguration) WithProxyConnectHeader(entries map[string][ } return b } - -// WithFollowRedirects sets the FollowRedirects field in the declarative configuration to the given value -// and returns the receiver, so that objects can be built by chaining "With" function invocations. -// If called multiple times, the FollowRedirects field is set to the value of the last call. -func (b *EndpointApplyConfiguration) WithFollowRedirects(value bool) *EndpointApplyConfiguration { - b.FollowRedirects = &value - return b -} - -// WithEnableHttp2 sets the EnableHttp2 field in the declarative configuration to the given value -// and returns the receiver, so that objects can be built by chaining "With" function invocations. -// If called multiple times, the EnableHttp2 field is set to the value of the last call. -func (b *EndpointApplyConfiguration) WithEnableHttp2(value bool) *EndpointApplyConfiguration { - b.EnableHttp2 = &value - return b -} - -// WithFilterRunning sets the FilterRunning field in the declarative configuration to the given value -// and returns the receiver, so that objects can be built by chaining "With" function invocations. -// If called multiple times, the FilterRunning field is set to the value of the last call. -func (b *EndpointApplyConfiguration) WithFilterRunning(value bool) *EndpointApplyConfiguration { - b.FilterRunning = &value - return b -} diff --git a/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1/httpconfig.go b/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1/httpconfig.go index 3e724da1b6f..b2eddc0eca3 100644 --- a/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1/httpconfig.go +++ b/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1/httpconfig.go @@ -23,14 +23,8 @@ import ( // HTTPConfigApplyConfiguration represents a declarative configuration of the HTTPConfig type for use // with apply. type HTTPConfigApplyConfiguration struct { - Authorization *SafeAuthorizationApplyConfiguration `json:"authorization,omitempty"` - BasicAuth *BasicAuthApplyConfiguration `json:"basicAuth,omitempty"` - OAuth2 *OAuth2ApplyConfiguration `json:"oauth2,omitempty"` - BearerTokenSecret *corev1.SecretKeySelector `json:"bearerTokenSecret,omitempty"` - TLSConfig *SafeTLSConfigApplyConfiguration `json:"tlsConfig,omitempty"` - ProxyConfigApplyConfiguration `json:",inline"` - FollowRedirects *bool `json:"followRedirects,omitempty"` - EnableHTTP2 *bool `json:"enableHttp2,omitempty"` + HTTPConfigWithoutTLSApplyConfiguration `json:",inline"` + TLSConfig *SafeTLSConfigApplyConfiguration `json:"tlsConfig,omitempty"` } // HTTPConfigApplyConfiguration constructs a declarative configuration of the HTTPConfig type for use with @@ -43,7 +37,7 @@ func HTTPConfig() *HTTPConfigApplyConfiguration { // and returns the receiver, so that objects can be built by chaining "With" function invocations. // If called multiple times, the Authorization field is set to the value of the last call. func (b *HTTPConfigApplyConfiguration) WithAuthorization(value *SafeAuthorizationApplyConfiguration) *HTTPConfigApplyConfiguration { - b.Authorization = value + b.HTTPConfigWithoutTLSApplyConfiguration.Authorization = value return b } @@ -51,7 +45,7 @@ func (b *HTTPConfigApplyConfiguration) WithAuthorization(value *SafeAuthorizatio // and returns the receiver, so that objects can be built by chaining "With" function invocations. // If called multiple times, the BasicAuth field is set to the value of the last call. func (b *HTTPConfigApplyConfiguration) WithBasicAuth(value *BasicAuthApplyConfiguration) *HTTPConfigApplyConfiguration { - b.BasicAuth = value + b.HTTPConfigWithoutTLSApplyConfiguration.BasicAuth = value return b } @@ -59,7 +53,7 @@ func (b *HTTPConfigApplyConfiguration) WithBasicAuth(value *BasicAuthApplyConfig // and returns the receiver, so that objects can be built by chaining "With" function invocations. // If called multiple times, the OAuth2 field is set to the value of the last call. func (b *HTTPConfigApplyConfiguration) WithOAuth2(value *OAuth2ApplyConfiguration) *HTTPConfigApplyConfiguration { - b.OAuth2 = value + b.HTTPConfigWithoutTLSApplyConfiguration.OAuth2 = value return b } @@ -67,53 +61,7 @@ func (b *HTTPConfigApplyConfiguration) WithOAuth2(value *OAuth2ApplyConfiguratio // and returns the receiver, so that objects can be built by chaining "With" function invocations. // If called multiple times, the BearerTokenSecret field is set to the value of the last call. func (b *HTTPConfigApplyConfiguration) WithBearerTokenSecret(value corev1.SecretKeySelector) *HTTPConfigApplyConfiguration { - b.BearerTokenSecret = &value - return b -} - -// WithTLSConfig sets the TLSConfig field in the declarative configuration to the given value -// and returns the receiver, so that objects can be built by chaining "With" function invocations. -// If called multiple times, the TLSConfig field is set to the value of the last call. -func (b *HTTPConfigApplyConfiguration) WithTLSConfig(value *SafeTLSConfigApplyConfiguration) *HTTPConfigApplyConfiguration { - b.TLSConfig = value - return b -} - -// WithProxyURL sets the ProxyURL field in the declarative configuration to the given value -// and returns the receiver, so that objects can be built by chaining "With" function invocations. -// If called multiple times, the ProxyURL field is set to the value of the last call. -func (b *HTTPConfigApplyConfiguration) WithProxyURL(value string) *HTTPConfigApplyConfiguration { - b.ProxyConfigApplyConfiguration.ProxyURL = &value - return b -} - -// WithNoProxy sets the NoProxy field in the declarative configuration to the given value -// and returns the receiver, so that objects can be built by chaining "With" function invocations. -// If called multiple times, the NoProxy field is set to the value of the last call. -func (b *HTTPConfigApplyConfiguration) WithNoProxy(value string) *HTTPConfigApplyConfiguration { - b.ProxyConfigApplyConfiguration.NoProxy = &value - return b -} - -// WithProxyFromEnvironment sets the ProxyFromEnvironment field in the declarative configuration to the given value -// and returns the receiver, so that objects can be built by chaining "With" function invocations. -// If called multiple times, the ProxyFromEnvironment field is set to the value of the last call. -func (b *HTTPConfigApplyConfiguration) WithProxyFromEnvironment(value bool) *HTTPConfigApplyConfiguration { - b.ProxyConfigApplyConfiguration.ProxyFromEnvironment = &value - return b -} - -// WithProxyConnectHeader puts the entries into the ProxyConnectHeader field in the declarative configuration -// and returns the receiver, so that objects can be build by chaining "With" function invocations. -// If called multiple times, the entries provided by each call will be put on the ProxyConnectHeader field, -// overwriting an existing map entries in ProxyConnectHeader field with the same key. -func (b *HTTPConfigApplyConfiguration) WithProxyConnectHeader(entries map[string][]corev1.SecretKeySelector) *HTTPConfigApplyConfiguration { - if b.ProxyConfigApplyConfiguration.ProxyConnectHeader == nil && len(entries) > 0 { - b.ProxyConfigApplyConfiguration.ProxyConnectHeader = make(map[string][]corev1.SecretKeySelector, len(entries)) - } - for k, v := range entries { - b.ProxyConfigApplyConfiguration.ProxyConnectHeader[k] = v - } + b.HTTPConfigWithoutTLSApplyConfiguration.BearerTokenSecret = &value return b } @@ -121,7 +69,7 @@ func (b *HTTPConfigApplyConfiguration) WithProxyConnectHeader(entries map[string // and returns the receiver, so that objects can be built by chaining "With" function invocations. // If called multiple times, the FollowRedirects field is set to the value of the last call. func (b *HTTPConfigApplyConfiguration) WithFollowRedirects(value bool) *HTTPConfigApplyConfiguration { - b.FollowRedirects = &value + b.HTTPConfigWithoutTLSApplyConfiguration.FollowRedirects = &value return b } @@ -129,6 +77,14 @@ func (b *HTTPConfigApplyConfiguration) WithFollowRedirects(value bool) *HTTPConf // and returns the receiver, so that objects can be built by chaining "With" function invocations. // If called multiple times, the EnableHTTP2 field is set to the value of the last call. func (b *HTTPConfigApplyConfiguration) WithEnableHTTP2(value bool) *HTTPConfigApplyConfiguration { - b.EnableHTTP2 = &value + b.HTTPConfigWithoutTLSApplyConfiguration.EnableHTTP2 = &value + return b +} + +// WithTLSConfig sets the TLSConfig field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the TLSConfig field is set to the value of the last call. +func (b *HTTPConfigApplyConfiguration) WithTLSConfig(value *SafeTLSConfigApplyConfiguration) *HTTPConfigApplyConfiguration { + b.TLSConfig = value return b } diff --git a/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1/httpconfigwithouttls.go b/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1/httpconfigwithouttls.go new file mode 100644 index 00000000000..2c4e7835e56 --- /dev/null +++ b/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1/httpconfigwithouttls.go @@ -0,0 +1,86 @@ +// Copyright The prometheus-operator Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// Code generated by applyconfiguration-gen. DO NOT EDIT. + +package v1 + +import ( + corev1 "k8s.io/api/core/v1" +) + +// HTTPConfigWithoutTLSApplyConfiguration represents a declarative configuration of the HTTPConfigWithoutTLS type for use +// with apply. +type HTTPConfigWithoutTLSApplyConfiguration struct { + Authorization *SafeAuthorizationApplyConfiguration `json:"authorization,omitempty"` + BasicAuth *BasicAuthApplyConfiguration `json:"basicAuth,omitempty"` + OAuth2 *OAuth2ApplyConfiguration `json:"oauth2,omitempty"` + BearerTokenSecret *corev1.SecretKeySelector `json:"bearerTokenSecret,omitempty"` + FollowRedirects *bool `json:"followRedirects,omitempty"` + EnableHTTP2 *bool `json:"enableHttp2,omitempty"` +} + +// HTTPConfigWithoutTLSApplyConfiguration constructs a declarative configuration of the HTTPConfigWithoutTLS type for use with +// apply. +func HTTPConfigWithoutTLS() *HTTPConfigWithoutTLSApplyConfiguration { + return &HTTPConfigWithoutTLSApplyConfiguration{} +} + +// WithAuthorization sets the Authorization field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the Authorization field is set to the value of the last call. +func (b *HTTPConfigWithoutTLSApplyConfiguration) WithAuthorization(value *SafeAuthorizationApplyConfiguration) *HTTPConfigWithoutTLSApplyConfiguration { + b.Authorization = value + return b +} + +// WithBasicAuth sets the BasicAuth field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the BasicAuth field is set to the value of the last call. +func (b *HTTPConfigWithoutTLSApplyConfiguration) WithBasicAuth(value *BasicAuthApplyConfiguration) *HTTPConfigWithoutTLSApplyConfiguration { + b.BasicAuth = value + return b +} + +// WithOAuth2 sets the OAuth2 field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the OAuth2 field is set to the value of the last call. +func (b *HTTPConfigWithoutTLSApplyConfiguration) WithOAuth2(value *OAuth2ApplyConfiguration) *HTTPConfigWithoutTLSApplyConfiguration { + b.OAuth2 = value + return b +} + +// WithBearerTokenSecret sets the BearerTokenSecret field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the BearerTokenSecret field is set to the value of the last call. +func (b *HTTPConfigWithoutTLSApplyConfiguration) WithBearerTokenSecret(value corev1.SecretKeySelector) *HTTPConfigWithoutTLSApplyConfiguration { + b.BearerTokenSecret = &value + return b +} + +// WithFollowRedirects sets the FollowRedirects field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the FollowRedirects field is set to the value of the last call. +func (b *HTTPConfigWithoutTLSApplyConfiguration) WithFollowRedirects(value bool) *HTTPConfigWithoutTLSApplyConfiguration { + b.FollowRedirects = &value + return b +} + +// WithEnableHTTP2 sets the EnableHTTP2 field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the EnableHTTP2 field is set to the value of the last call. +func (b *HTTPConfigWithoutTLSApplyConfiguration) WithEnableHTTP2(value bool) *HTTPConfigWithoutTLSApplyConfiguration { + b.EnableHTTP2 = &value + return b +} diff --git a/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1/httpconfigwithproxy.go b/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1/httpconfigwithproxy.go new file mode 100644 index 00000000000..9e4666d233a --- /dev/null +++ b/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1/httpconfigwithproxy.go @@ -0,0 +1,128 @@ +// Copyright The prometheus-operator Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// Code generated by applyconfiguration-gen. DO NOT EDIT. + +package v1 + +import ( + corev1 "k8s.io/api/core/v1" +) + +// HTTPConfigWithProxyApplyConfiguration represents a declarative configuration of the HTTPConfigWithProxy type for use +// with apply. +type HTTPConfigWithProxyApplyConfiguration struct { + HTTPConfigApplyConfiguration `json:",inline"` + ProxyConfigApplyConfiguration `json:",inline"` +} + +// HTTPConfigWithProxyApplyConfiguration constructs a declarative configuration of the HTTPConfigWithProxy type for use with +// apply. +func HTTPConfigWithProxy() *HTTPConfigWithProxyApplyConfiguration { + return &HTTPConfigWithProxyApplyConfiguration{} +} + +// WithAuthorization sets the Authorization field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the Authorization field is set to the value of the last call. +func (b *HTTPConfigWithProxyApplyConfiguration) WithAuthorization(value *SafeAuthorizationApplyConfiguration) *HTTPConfigWithProxyApplyConfiguration { + b.HTTPConfigWithoutTLSApplyConfiguration.Authorization = value + return b +} + +// WithBasicAuth sets the BasicAuth field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the BasicAuth field is set to the value of the last call. +func (b *HTTPConfigWithProxyApplyConfiguration) WithBasicAuth(value *BasicAuthApplyConfiguration) *HTTPConfigWithProxyApplyConfiguration { + b.HTTPConfigWithoutTLSApplyConfiguration.BasicAuth = value + return b +} + +// WithOAuth2 sets the OAuth2 field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the OAuth2 field is set to the value of the last call. +func (b *HTTPConfigWithProxyApplyConfiguration) WithOAuth2(value *OAuth2ApplyConfiguration) *HTTPConfigWithProxyApplyConfiguration { + b.HTTPConfigWithoutTLSApplyConfiguration.OAuth2 = value + return b +} + +// WithBearerTokenSecret sets the BearerTokenSecret field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the BearerTokenSecret field is set to the value of the last call. +func (b *HTTPConfigWithProxyApplyConfiguration) WithBearerTokenSecret(value corev1.SecretKeySelector) *HTTPConfigWithProxyApplyConfiguration { + b.HTTPConfigWithoutTLSApplyConfiguration.BearerTokenSecret = &value + return b +} + +// WithFollowRedirects sets the FollowRedirects field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the FollowRedirects field is set to the value of the last call. +func (b *HTTPConfigWithProxyApplyConfiguration) WithFollowRedirects(value bool) *HTTPConfigWithProxyApplyConfiguration { + b.HTTPConfigWithoutTLSApplyConfiguration.FollowRedirects = &value + return b +} + +// WithEnableHTTP2 sets the EnableHTTP2 field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the EnableHTTP2 field is set to the value of the last call. +func (b *HTTPConfigWithProxyApplyConfiguration) WithEnableHTTP2(value bool) *HTTPConfigWithProxyApplyConfiguration { + b.HTTPConfigWithoutTLSApplyConfiguration.EnableHTTP2 = &value + return b +} + +// WithTLSConfig sets the TLSConfig field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the TLSConfig field is set to the value of the last call. +func (b *HTTPConfigWithProxyApplyConfiguration) WithTLSConfig(value *SafeTLSConfigApplyConfiguration) *HTTPConfigWithProxyApplyConfiguration { + b.HTTPConfigApplyConfiguration.TLSConfig = value + return b +} + +// WithProxyURL sets the ProxyURL field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the ProxyURL field is set to the value of the last call. +func (b *HTTPConfigWithProxyApplyConfiguration) WithProxyURL(value string) *HTTPConfigWithProxyApplyConfiguration { + b.ProxyConfigApplyConfiguration.ProxyURL = &value + return b +} + +// WithNoProxy sets the NoProxy field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the NoProxy field is set to the value of the last call. +func (b *HTTPConfigWithProxyApplyConfiguration) WithNoProxy(value string) *HTTPConfigWithProxyApplyConfiguration { + b.ProxyConfigApplyConfiguration.NoProxy = &value + return b +} + +// WithProxyFromEnvironment sets the ProxyFromEnvironment field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the ProxyFromEnvironment field is set to the value of the last call. +func (b *HTTPConfigWithProxyApplyConfiguration) WithProxyFromEnvironment(value bool) *HTTPConfigWithProxyApplyConfiguration { + b.ProxyConfigApplyConfiguration.ProxyFromEnvironment = &value + return b +} + +// WithProxyConnectHeader puts the entries into the ProxyConnectHeader field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, the entries provided by each call will be put on the ProxyConnectHeader field, +// overwriting an existing map entries in ProxyConnectHeader field with the same key. +func (b *HTTPConfigWithProxyApplyConfiguration) WithProxyConnectHeader(entries map[string][]corev1.SecretKeySelector) *HTTPConfigWithProxyApplyConfiguration { + if b.ProxyConfigApplyConfiguration.ProxyConnectHeader == nil && len(entries) > 0 { + b.ProxyConfigApplyConfiguration.ProxyConnectHeader = make(map[string][]corev1.SecretKeySelector, len(entries)) + } + for k, v := range entries { + b.ProxyConfigApplyConfiguration.ProxyConnectHeader[k] = v + } + return b +} diff --git a/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1/httpconfigwithproxyandtlsfiles.go b/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1/httpconfigwithproxyandtlsfiles.go new file mode 100644 index 00000000000..eae11b14c7d --- /dev/null +++ b/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1/httpconfigwithproxyandtlsfiles.go @@ -0,0 +1,128 @@ +// Copyright The prometheus-operator Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// Code generated by applyconfiguration-gen. DO NOT EDIT. + +package v1 + +import ( + corev1 "k8s.io/api/core/v1" +) + +// HTTPConfigWithProxyAndTLSFilesApplyConfiguration represents a declarative configuration of the HTTPConfigWithProxyAndTLSFiles type for use +// with apply. +type HTTPConfigWithProxyAndTLSFilesApplyConfiguration struct { + HTTPConfigWithTLSFilesApplyConfiguration `json:",inline"` + ProxyConfigApplyConfiguration `json:",inline"` +} + +// HTTPConfigWithProxyAndTLSFilesApplyConfiguration constructs a declarative configuration of the HTTPConfigWithProxyAndTLSFiles type for use with +// apply. +func HTTPConfigWithProxyAndTLSFiles() *HTTPConfigWithProxyAndTLSFilesApplyConfiguration { + return &HTTPConfigWithProxyAndTLSFilesApplyConfiguration{} +} + +// WithAuthorization sets the Authorization field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the Authorization field is set to the value of the last call. +func (b *HTTPConfigWithProxyAndTLSFilesApplyConfiguration) WithAuthorization(value *SafeAuthorizationApplyConfiguration) *HTTPConfigWithProxyAndTLSFilesApplyConfiguration { + b.HTTPConfigWithoutTLSApplyConfiguration.Authorization = value + return b +} + +// WithBasicAuth sets the BasicAuth field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the BasicAuth field is set to the value of the last call. +func (b *HTTPConfigWithProxyAndTLSFilesApplyConfiguration) WithBasicAuth(value *BasicAuthApplyConfiguration) *HTTPConfigWithProxyAndTLSFilesApplyConfiguration { + b.HTTPConfigWithoutTLSApplyConfiguration.BasicAuth = value + return b +} + +// WithOAuth2 sets the OAuth2 field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the OAuth2 field is set to the value of the last call. +func (b *HTTPConfigWithProxyAndTLSFilesApplyConfiguration) WithOAuth2(value *OAuth2ApplyConfiguration) *HTTPConfigWithProxyAndTLSFilesApplyConfiguration { + b.HTTPConfigWithoutTLSApplyConfiguration.OAuth2 = value + return b +} + +// WithBearerTokenSecret sets the BearerTokenSecret field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the BearerTokenSecret field is set to the value of the last call. +func (b *HTTPConfigWithProxyAndTLSFilesApplyConfiguration) WithBearerTokenSecret(value corev1.SecretKeySelector) *HTTPConfigWithProxyAndTLSFilesApplyConfiguration { + b.HTTPConfigWithoutTLSApplyConfiguration.BearerTokenSecret = &value + return b +} + +// WithFollowRedirects sets the FollowRedirects field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the FollowRedirects field is set to the value of the last call. +func (b *HTTPConfigWithProxyAndTLSFilesApplyConfiguration) WithFollowRedirects(value bool) *HTTPConfigWithProxyAndTLSFilesApplyConfiguration { + b.HTTPConfigWithoutTLSApplyConfiguration.FollowRedirects = &value + return b +} + +// WithEnableHTTP2 sets the EnableHTTP2 field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the EnableHTTP2 field is set to the value of the last call. +func (b *HTTPConfigWithProxyAndTLSFilesApplyConfiguration) WithEnableHTTP2(value bool) *HTTPConfigWithProxyAndTLSFilesApplyConfiguration { + b.HTTPConfigWithoutTLSApplyConfiguration.EnableHTTP2 = &value + return b +} + +// WithTLSConfig sets the TLSConfig field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the TLSConfig field is set to the value of the last call. +func (b *HTTPConfigWithProxyAndTLSFilesApplyConfiguration) WithTLSConfig(value *TLSConfigApplyConfiguration) *HTTPConfigWithProxyAndTLSFilesApplyConfiguration { + b.HTTPConfigWithTLSFilesApplyConfiguration.TLSConfig = value + return b +} + +// WithProxyURL sets the ProxyURL field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the ProxyURL field is set to the value of the last call. +func (b *HTTPConfigWithProxyAndTLSFilesApplyConfiguration) WithProxyURL(value string) *HTTPConfigWithProxyAndTLSFilesApplyConfiguration { + b.ProxyConfigApplyConfiguration.ProxyURL = &value + return b +} + +// WithNoProxy sets the NoProxy field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the NoProxy field is set to the value of the last call. +func (b *HTTPConfigWithProxyAndTLSFilesApplyConfiguration) WithNoProxy(value string) *HTTPConfigWithProxyAndTLSFilesApplyConfiguration { + b.ProxyConfigApplyConfiguration.NoProxy = &value + return b +} + +// WithProxyFromEnvironment sets the ProxyFromEnvironment field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the ProxyFromEnvironment field is set to the value of the last call. +func (b *HTTPConfigWithProxyAndTLSFilesApplyConfiguration) WithProxyFromEnvironment(value bool) *HTTPConfigWithProxyAndTLSFilesApplyConfiguration { + b.ProxyConfigApplyConfiguration.ProxyFromEnvironment = &value + return b +} + +// WithProxyConnectHeader puts the entries into the ProxyConnectHeader field in the declarative configuration +// and returns the receiver, so that objects can be build by chaining "With" function invocations. +// If called multiple times, the entries provided by each call will be put on the ProxyConnectHeader field, +// overwriting an existing map entries in ProxyConnectHeader field with the same key. +func (b *HTTPConfigWithProxyAndTLSFilesApplyConfiguration) WithProxyConnectHeader(entries map[string][]corev1.SecretKeySelector) *HTTPConfigWithProxyAndTLSFilesApplyConfiguration { + if b.ProxyConfigApplyConfiguration.ProxyConnectHeader == nil && len(entries) > 0 { + b.ProxyConfigApplyConfiguration.ProxyConnectHeader = make(map[string][]corev1.SecretKeySelector, len(entries)) + } + for k, v := range entries { + b.ProxyConfigApplyConfiguration.ProxyConnectHeader[k] = v + } + return b +} diff --git a/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1/httpconfigwithtlsfiles.go b/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1/httpconfigwithtlsfiles.go new file mode 100644 index 00000000000..fba1aab365b --- /dev/null +++ b/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1/httpconfigwithtlsfiles.go @@ -0,0 +1,90 @@ +// Copyright The prometheus-operator Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// Code generated by applyconfiguration-gen. DO NOT EDIT. + +package v1 + +import ( + corev1 "k8s.io/api/core/v1" +) + +// HTTPConfigWithTLSFilesApplyConfiguration represents a declarative configuration of the HTTPConfigWithTLSFiles type for use +// with apply. +type HTTPConfigWithTLSFilesApplyConfiguration struct { + HTTPConfigWithoutTLSApplyConfiguration `json:",inline"` + TLSConfig *TLSConfigApplyConfiguration `json:"tlsConfig,omitempty"` +} + +// HTTPConfigWithTLSFilesApplyConfiguration constructs a declarative configuration of the HTTPConfigWithTLSFiles type for use with +// apply. +func HTTPConfigWithTLSFiles() *HTTPConfigWithTLSFilesApplyConfiguration { + return &HTTPConfigWithTLSFilesApplyConfiguration{} +} + +// WithAuthorization sets the Authorization field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the Authorization field is set to the value of the last call. +func (b *HTTPConfigWithTLSFilesApplyConfiguration) WithAuthorization(value *SafeAuthorizationApplyConfiguration) *HTTPConfigWithTLSFilesApplyConfiguration { + b.HTTPConfigWithoutTLSApplyConfiguration.Authorization = value + return b +} + +// WithBasicAuth sets the BasicAuth field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the BasicAuth field is set to the value of the last call. +func (b *HTTPConfigWithTLSFilesApplyConfiguration) WithBasicAuth(value *BasicAuthApplyConfiguration) *HTTPConfigWithTLSFilesApplyConfiguration { + b.HTTPConfigWithoutTLSApplyConfiguration.BasicAuth = value + return b +} + +// WithOAuth2 sets the OAuth2 field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the OAuth2 field is set to the value of the last call. +func (b *HTTPConfigWithTLSFilesApplyConfiguration) WithOAuth2(value *OAuth2ApplyConfiguration) *HTTPConfigWithTLSFilesApplyConfiguration { + b.HTTPConfigWithoutTLSApplyConfiguration.OAuth2 = value + return b +} + +// WithBearerTokenSecret sets the BearerTokenSecret field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the BearerTokenSecret field is set to the value of the last call. +func (b *HTTPConfigWithTLSFilesApplyConfiguration) WithBearerTokenSecret(value corev1.SecretKeySelector) *HTTPConfigWithTLSFilesApplyConfiguration { + b.HTTPConfigWithoutTLSApplyConfiguration.BearerTokenSecret = &value + return b +} + +// WithFollowRedirects sets the FollowRedirects field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the FollowRedirects field is set to the value of the last call. +func (b *HTTPConfigWithTLSFilesApplyConfiguration) WithFollowRedirects(value bool) *HTTPConfigWithTLSFilesApplyConfiguration { + b.HTTPConfigWithoutTLSApplyConfiguration.FollowRedirects = &value + return b +} + +// WithEnableHTTP2 sets the EnableHTTP2 field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the EnableHTTP2 field is set to the value of the last call. +func (b *HTTPConfigWithTLSFilesApplyConfiguration) WithEnableHTTP2(value bool) *HTTPConfigWithTLSFilesApplyConfiguration { + b.HTTPConfigWithoutTLSApplyConfiguration.EnableHTTP2 = &value + return b +} + +// WithTLSConfig sets the TLSConfig field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the TLSConfig field is set to the value of the last call. +func (b *HTTPConfigWithTLSFilesApplyConfiguration) WithTLSConfig(value *TLSConfigApplyConfiguration) *HTTPConfigWithTLSFilesApplyConfiguration { + b.TLSConfig = value + return b +} diff --git a/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1/nativehistogramconfig.go b/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1/nativehistogramconfig.go index 8ca307498f3..a6831e87799 100644 --- a/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1/nativehistogramconfig.go +++ b/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1/nativehistogramconfig.go @@ -23,6 +23,7 @@ import ( // NativeHistogramConfigApplyConfiguration represents a declarative configuration of the NativeHistogramConfig type for use // with apply. type NativeHistogramConfigApplyConfiguration struct { + ScrapeNativeHistograms *bool `json:"scrapeNativeHistograms,omitempty"` ScrapeClassicHistograms *bool `json:"scrapeClassicHistograms,omitempty"` NativeHistogramBucketLimit *uint64 `json:"nativeHistogramBucketLimit,omitempty"` NativeHistogramMinBucketFactor *resource.Quantity `json:"nativeHistogramMinBucketFactor,omitempty"` @@ -35,6 +36,14 @@ func NativeHistogramConfig() *NativeHistogramConfigApplyConfiguration { return &NativeHistogramConfigApplyConfiguration{} } +// WithScrapeNativeHistograms sets the ScrapeNativeHistograms field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the ScrapeNativeHistograms field is set to the value of the last call. +func (b *NativeHistogramConfigApplyConfiguration) WithScrapeNativeHistograms(value bool) *NativeHistogramConfigApplyConfiguration { + b.ScrapeNativeHistograms = &value + return b +} + // WithScrapeClassicHistograms sets the ScrapeClassicHistograms field in the declarative configuration to the given value // and returns the receiver, so that objects can be built by chaining "With" function invocations. // If called multiple times, the ScrapeClassicHistograms field is set to the value of the last call. diff --git a/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1/podmetricsendpoint.go b/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1/podmetricsendpoint.go index 263727a3868..2d0a81428bc 100644 --- a/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1/podmetricsendpoint.go +++ b/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1/podmetricsendpoint.go @@ -25,21 +25,21 @@ import ( // PodMetricsEndpointApplyConfiguration represents a declarative configuration of the PodMetricsEndpoint type for use // with apply. type PodMetricsEndpointApplyConfiguration struct { - Port *string `json:"port,omitempty"` - PortNumber *int32 `json:"portNumber,omitempty"` - TargetPort *intstr.IntOrString `json:"targetPort,omitempty"` - Path *string `json:"path,omitempty"` - Scheme *monitoringv1.Scheme `json:"scheme,omitempty"` - Params map[string][]string `json:"params,omitempty"` - Interval *monitoringv1.Duration `json:"interval,omitempty"` - ScrapeTimeout *monitoringv1.Duration `json:"scrapeTimeout,omitempty"` - HonorLabels *bool `json:"honorLabels,omitempty"` - HonorTimestamps *bool `json:"honorTimestamps,omitempty"` - TrackTimestampsStaleness *bool `json:"trackTimestampsStaleness,omitempty"` - MetricRelabelConfigs []RelabelConfigApplyConfiguration `json:"metricRelabelings,omitempty"` - RelabelConfigs []RelabelConfigApplyConfiguration `json:"relabelings,omitempty"` - FilterRunning *bool `json:"filterRunning,omitempty"` - HTTPConfigApplyConfiguration `json:",inline"` + Port *string `json:"port,omitempty"` + PortNumber *int32 `json:"portNumber,omitempty"` + TargetPort *intstr.IntOrString `json:"targetPort,omitempty"` + Path *string `json:"path,omitempty"` + Scheme *monitoringv1.Scheme `json:"scheme,omitempty"` + Params map[string][]string `json:"params,omitempty"` + Interval *monitoringv1.Duration `json:"interval,omitempty"` + ScrapeTimeout *monitoringv1.Duration `json:"scrapeTimeout,omitempty"` + HonorLabels *bool `json:"honorLabels,omitempty"` + HonorTimestamps *bool `json:"honorTimestamps,omitempty"` + TrackTimestampsStaleness *bool `json:"trackTimestampsStaleness,omitempty"` + MetricRelabelConfigs []RelabelConfigApplyConfiguration `json:"metricRelabelings,omitempty"` + RelabelConfigs []RelabelConfigApplyConfiguration `json:"relabelings,omitempty"` + FilterRunning *bool `json:"filterRunning,omitempty"` + HTTPConfigWithProxyApplyConfiguration `json:",inline"` } // PodMetricsEndpointApplyConfiguration constructs a declarative configuration of the PodMetricsEndpoint type for use with @@ -180,7 +180,7 @@ func (b *PodMetricsEndpointApplyConfiguration) WithFilterRunning(value bool) *Po // and returns the receiver, so that objects can be built by chaining "With" function invocations. // If called multiple times, the Authorization field is set to the value of the last call. func (b *PodMetricsEndpointApplyConfiguration) WithAuthorization(value *SafeAuthorizationApplyConfiguration) *PodMetricsEndpointApplyConfiguration { - b.HTTPConfigApplyConfiguration.Authorization = value + b.HTTPConfigWithoutTLSApplyConfiguration.Authorization = value return b } @@ -188,7 +188,7 @@ func (b *PodMetricsEndpointApplyConfiguration) WithAuthorization(value *SafeAuth // and returns the receiver, so that objects can be built by chaining "With" function invocations. // If called multiple times, the BasicAuth field is set to the value of the last call. func (b *PodMetricsEndpointApplyConfiguration) WithBasicAuth(value *BasicAuthApplyConfiguration) *PodMetricsEndpointApplyConfiguration { - b.HTTPConfigApplyConfiguration.BasicAuth = value + b.HTTPConfigWithoutTLSApplyConfiguration.BasicAuth = value return b } @@ -196,7 +196,7 @@ func (b *PodMetricsEndpointApplyConfiguration) WithBasicAuth(value *BasicAuthApp // and returns the receiver, so that objects can be built by chaining "With" function invocations. // If called multiple times, the OAuth2 field is set to the value of the last call. func (b *PodMetricsEndpointApplyConfiguration) WithOAuth2(value *OAuth2ApplyConfiguration) *PodMetricsEndpointApplyConfiguration { - b.HTTPConfigApplyConfiguration.OAuth2 = value + b.HTTPConfigWithoutTLSApplyConfiguration.OAuth2 = value return b } @@ -204,7 +204,23 @@ func (b *PodMetricsEndpointApplyConfiguration) WithOAuth2(value *OAuth2ApplyConf // and returns the receiver, so that objects can be built by chaining "With" function invocations. // If called multiple times, the BearerTokenSecret field is set to the value of the last call. func (b *PodMetricsEndpointApplyConfiguration) WithBearerTokenSecret(value corev1.SecretKeySelector) *PodMetricsEndpointApplyConfiguration { - b.HTTPConfigApplyConfiguration.BearerTokenSecret = &value + b.HTTPConfigWithoutTLSApplyConfiguration.BearerTokenSecret = &value + return b +} + +// WithFollowRedirects sets the FollowRedirects field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the FollowRedirects field is set to the value of the last call. +func (b *PodMetricsEndpointApplyConfiguration) WithFollowRedirects(value bool) *PodMetricsEndpointApplyConfiguration { + b.HTTPConfigWithoutTLSApplyConfiguration.FollowRedirects = &value + return b +} + +// WithEnableHTTP2 sets the EnableHTTP2 field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the EnableHTTP2 field is set to the value of the last call. +func (b *PodMetricsEndpointApplyConfiguration) WithEnableHTTP2(value bool) *PodMetricsEndpointApplyConfiguration { + b.HTTPConfigWithoutTLSApplyConfiguration.EnableHTTP2 = &value return b } @@ -253,19 +269,3 @@ func (b *PodMetricsEndpointApplyConfiguration) WithProxyConnectHeader(entries ma } return b } - -// WithFollowRedirects sets the FollowRedirects field in the declarative configuration to the given value -// and returns the receiver, so that objects can be built by chaining "With" function invocations. -// If called multiple times, the FollowRedirects field is set to the value of the last call. -func (b *PodMetricsEndpointApplyConfiguration) WithFollowRedirects(value bool) *PodMetricsEndpointApplyConfiguration { - b.HTTPConfigApplyConfiguration.FollowRedirects = &value - return b -} - -// WithEnableHTTP2 sets the EnableHTTP2 field in the declarative configuration to the given value -// and returns the receiver, so that objects can be built by chaining "With" function invocations. -// If called multiple times, the EnableHTTP2 field is set to the value of the last call. -func (b *PodMetricsEndpointApplyConfiguration) WithEnableHTTP2(value bool) *PodMetricsEndpointApplyConfiguration { - b.HTTPConfigApplyConfiguration.EnableHTTP2 = &value - return b -} diff --git a/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1/podmonitorspec.go b/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1/podmonitorspec.go index a7477e029d0..3daf46fc261 100644 --- a/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1/podmonitorspec.go +++ b/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1/podmonitorspec.go @@ -164,6 +164,14 @@ func (b *PodMonitorSpecApplyConfiguration) WithLabelValueLengthLimit(value uint6 return b } +// WithScrapeNativeHistograms sets the ScrapeNativeHistograms field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the ScrapeNativeHistograms field is set to the value of the last call. +func (b *PodMonitorSpecApplyConfiguration) WithScrapeNativeHistograms(value bool) *PodMonitorSpecApplyConfiguration { + b.NativeHistogramConfigApplyConfiguration.ScrapeNativeHistograms = &value + return b +} + // WithScrapeClassicHistograms sets the ScrapeClassicHistograms field in the declarative configuration to the given value // and returns the receiver, so that objects can be built by chaining "With" function invocations. // If called multiple times, the ScrapeClassicHistograms field is set to the value of the last call. diff --git a/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1/probespec.go b/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1/probespec.go index 68fc056d2a6..6be60f3a137 100644 --- a/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1/probespec.go +++ b/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1/probespec.go @@ -31,10 +31,6 @@ type ProbeSpecApplyConfiguration struct { Targets *ProbeTargetsApplyConfiguration `json:"targets,omitempty"` Interval *monitoringv1.Duration `json:"interval,omitempty"` ScrapeTimeout *monitoringv1.Duration `json:"scrapeTimeout,omitempty"` - TLSConfig *SafeTLSConfigApplyConfiguration `json:"tlsConfig,omitempty"` - BearerTokenSecret *corev1.SecretKeySelector `json:"bearerTokenSecret,omitempty"` - BasicAuth *BasicAuthApplyConfiguration `json:"basicAuth,omitempty"` - OAuth2 *OAuth2ApplyConfiguration `json:"oauth2,omitempty"` MetricRelabelConfigs []RelabelConfigApplyConfiguration `json:"metricRelabelings,omitempty"` Authorization *SafeAuthorizationApplyConfiguration `json:"authorization,omitempty"` SampleLimit *uint64 `json:"sampleLimit,omitempty"` @@ -48,6 +44,7 @@ type ProbeSpecApplyConfiguration struct { KeepDroppedTargets *uint64 `json:"keepDroppedTargets,omitempty"` ScrapeClassName *string `json:"scrapeClass,omitempty"` Params []ProbeParamApplyConfiguration `json:"params,omitempty"` + HTTPConfigApplyConfiguration `json:",inline"` } // ProbeSpecApplyConfiguration constructs a declarative configuration of the ProbeSpec type for use with @@ -104,38 +101,6 @@ func (b *ProbeSpecApplyConfiguration) WithScrapeTimeout(value monitoringv1.Durat return b } -// WithTLSConfig sets the TLSConfig field in the declarative configuration to the given value -// and returns the receiver, so that objects can be built by chaining "With" function invocations. -// If called multiple times, the TLSConfig field is set to the value of the last call. -func (b *ProbeSpecApplyConfiguration) WithTLSConfig(value *SafeTLSConfigApplyConfiguration) *ProbeSpecApplyConfiguration { - b.TLSConfig = value - return b -} - -// WithBearerTokenSecret sets the BearerTokenSecret field in the declarative configuration to the given value -// and returns the receiver, so that objects can be built by chaining "With" function invocations. -// If called multiple times, the BearerTokenSecret field is set to the value of the last call. -func (b *ProbeSpecApplyConfiguration) WithBearerTokenSecret(value corev1.SecretKeySelector) *ProbeSpecApplyConfiguration { - b.BearerTokenSecret = &value - return b -} - -// WithBasicAuth sets the BasicAuth field in the declarative configuration to the given value -// and returns the receiver, so that objects can be built by chaining "With" function invocations. -// If called multiple times, the BasicAuth field is set to the value of the last call. -func (b *ProbeSpecApplyConfiguration) WithBasicAuth(value *BasicAuthApplyConfiguration) *ProbeSpecApplyConfiguration { - b.BasicAuth = value - return b -} - -// WithOAuth2 sets the OAuth2 field in the declarative configuration to the given value -// and returns the receiver, so that objects can be built by chaining "With" function invocations. -// If called multiple times, the OAuth2 field is set to the value of the last call. -func (b *ProbeSpecApplyConfiguration) WithOAuth2(value *OAuth2ApplyConfiguration) *ProbeSpecApplyConfiguration { - b.OAuth2 = value - return b -} - // WithMetricRelabelConfigs adds the given value to the MetricRelabelConfigs field in the declarative configuration // and returns the receiver, so that objects can be build by chaining "With" function invocations. // If called multiple times, values provided by each call will be appended to the MetricRelabelConfigs field. @@ -215,6 +180,14 @@ func (b *ProbeSpecApplyConfiguration) WithLabelValueLengthLimit(value uint64) *P return b } +// WithScrapeNativeHistograms sets the ScrapeNativeHistograms field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the ScrapeNativeHistograms field is set to the value of the last call. +func (b *ProbeSpecApplyConfiguration) WithScrapeNativeHistograms(value bool) *ProbeSpecApplyConfiguration { + b.NativeHistogramConfigApplyConfiguration.ScrapeNativeHistograms = &value + return b +} + // WithScrapeClassicHistograms sets the ScrapeClassicHistograms field in the declarative configuration to the given value // and returns the receiver, so that objects can be built by chaining "With" function invocations. // If called multiple times, the ScrapeClassicHistograms field is set to the value of the last call. @@ -275,3 +248,51 @@ func (b *ProbeSpecApplyConfiguration) WithParams(values ...*ProbeParamApplyConfi } return b } + +// WithBasicAuth sets the BasicAuth field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the BasicAuth field is set to the value of the last call. +func (b *ProbeSpecApplyConfiguration) WithBasicAuth(value *BasicAuthApplyConfiguration) *ProbeSpecApplyConfiguration { + b.HTTPConfigWithoutTLSApplyConfiguration.BasicAuth = value + return b +} + +// WithOAuth2 sets the OAuth2 field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the OAuth2 field is set to the value of the last call. +func (b *ProbeSpecApplyConfiguration) WithOAuth2(value *OAuth2ApplyConfiguration) *ProbeSpecApplyConfiguration { + b.HTTPConfigWithoutTLSApplyConfiguration.OAuth2 = value + return b +} + +// WithBearerTokenSecret sets the BearerTokenSecret field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the BearerTokenSecret field is set to the value of the last call. +func (b *ProbeSpecApplyConfiguration) WithBearerTokenSecret(value corev1.SecretKeySelector) *ProbeSpecApplyConfiguration { + b.HTTPConfigWithoutTLSApplyConfiguration.BearerTokenSecret = &value + return b +} + +// WithFollowRedirects sets the FollowRedirects field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the FollowRedirects field is set to the value of the last call. +func (b *ProbeSpecApplyConfiguration) WithFollowRedirects(value bool) *ProbeSpecApplyConfiguration { + b.HTTPConfigWithoutTLSApplyConfiguration.FollowRedirects = &value + return b +} + +// WithEnableHTTP2 sets the EnableHTTP2 field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the EnableHTTP2 field is set to the value of the last call. +func (b *ProbeSpecApplyConfiguration) WithEnableHTTP2(value bool) *ProbeSpecApplyConfiguration { + b.HTTPConfigWithoutTLSApplyConfiguration.EnableHTTP2 = &value + return b +} + +// WithTLSConfig sets the TLSConfig field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the TLSConfig field is set to the value of the last call. +func (b *ProbeSpecApplyConfiguration) WithTLSConfig(value *SafeTLSConfigApplyConfiguration) *ProbeSpecApplyConfiguration { + b.HTTPConfigApplyConfiguration.TLSConfig = value + return b +} diff --git a/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1/prometheusspec.go b/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1/prometheusspec.go index a8f878e0ec8..9c6b6c6b2a7 100644 --- a/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1/prometheusspec.go +++ b/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1/prometheusspec.go @@ -498,6 +498,22 @@ func (b *PrometheusSpecApplyConfiguration) WithListenLocal(value bool) *Promethe return b } +// WithPodManagementPolicy sets the PodManagementPolicy field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the PodManagementPolicy field is set to the value of the last call. +func (b *PrometheusSpecApplyConfiguration) WithPodManagementPolicy(value monitoringv1.PodManagementPolicyType) *PrometheusSpecApplyConfiguration { + b.CommonPrometheusFieldsApplyConfiguration.PodManagementPolicy = &value + return b +} + +// WithUpdateStrategy sets the UpdateStrategy field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the UpdateStrategy field is set to the value of the last call. +func (b *PrometheusSpecApplyConfiguration) WithUpdateStrategy(value *StatefulSetUpdateStrategyApplyConfiguration) *PrometheusSpecApplyConfiguration { + b.CommonPrometheusFieldsApplyConfiguration.UpdateStrategy = value + return b +} + // WithEnableServiceLinks sets the EnableServiceLinks field in the declarative configuration to the given value // and returns the receiver, so that objects can be built by chaining "With" function invocations. // If called multiple times, the EnableServiceLinks field is set to the value of the last call. @@ -678,6 +694,14 @@ func (b *PrometheusSpecApplyConfiguration) WithConvertClassicHistogramsToNHCB(va return b } +// WithScrapeNativeHistograms sets the ScrapeNativeHistograms field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the ScrapeNativeHistograms field is set to the value of the last call. +func (b *PrometheusSpecApplyConfiguration) WithScrapeNativeHistograms(value bool) *PrometheusSpecApplyConfiguration { + b.CommonPrometheusFieldsApplyConfiguration.ScrapeNativeHistograms = &value + return b +} + // WithScrapeClassicHistograms sets the ScrapeClassicHistograms field in the declarative configuration to the given value // and returns the receiver, so that objects can be built by chaining "With" function invocations. // If called multiple times, the ScrapeClassicHistograms field is set to the value of the last call. @@ -762,7 +786,7 @@ func (b *PrometheusSpecApplyConfiguration) WithPodTargetLabels(values ...string) // WithTracingConfig sets the TracingConfig field in the declarative configuration to the given value // and returns the receiver, so that objects can be built by chaining "With" function invocations. // If called multiple times, the TracingConfig field is set to the value of the last call. -func (b *PrometheusSpecApplyConfiguration) WithTracingConfig(value *PrometheusTracingConfigApplyConfiguration) *PrometheusSpecApplyConfiguration { +func (b *PrometheusSpecApplyConfiguration) WithTracingConfig(value *TracingConfigApplyConfiguration) *PrometheusSpecApplyConfiguration { b.CommonPrometheusFieldsApplyConfiguration.TracingConfig = value return b } diff --git a/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1/rollingupdatestatefulsetstrategy.go b/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1/rollingupdatestatefulsetstrategy.go new file mode 100644 index 00000000000..5c09187f4ac --- /dev/null +++ b/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1/rollingupdatestatefulsetstrategy.go @@ -0,0 +1,41 @@ +// Copyright The prometheus-operator Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// Code generated by applyconfiguration-gen. DO NOT EDIT. + +package v1 + +import ( + intstr "k8s.io/apimachinery/pkg/util/intstr" +) + +// RollingUpdateStatefulSetStrategyApplyConfiguration represents a declarative configuration of the RollingUpdateStatefulSetStrategy type for use +// with apply. +type RollingUpdateStatefulSetStrategyApplyConfiguration struct { + MaxUnavailable *intstr.IntOrString `json:"maxUnavailable,omitempty"` +} + +// RollingUpdateStatefulSetStrategyApplyConfiguration constructs a declarative configuration of the RollingUpdateStatefulSetStrategy type for use with +// apply. +func RollingUpdateStatefulSetStrategy() *RollingUpdateStatefulSetStrategyApplyConfiguration { + return &RollingUpdateStatefulSetStrategyApplyConfiguration{} +} + +// WithMaxUnavailable sets the MaxUnavailable field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the MaxUnavailable field is set to the value of the last call. +func (b *RollingUpdateStatefulSetStrategyApplyConfiguration) WithMaxUnavailable(value intstr.IntOrString) *RollingUpdateStatefulSetStrategyApplyConfiguration { + b.MaxUnavailable = &value + return b +} diff --git a/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1/servicemonitorspec.go b/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1/servicemonitorspec.go index 2800a7e0502..b0b7887644d 100644 --- a/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1/servicemonitorspec.go +++ b/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1/servicemonitorspec.go @@ -176,6 +176,14 @@ func (b *ServiceMonitorSpecApplyConfiguration) WithLabelValueLengthLimit(value u return b } +// WithScrapeNativeHistograms sets the ScrapeNativeHistograms field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the ScrapeNativeHistograms field is set to the value of the last call. +func (b *ServiceMonitorSpecApplyConfiguration) WithScrapeNativeHistograms(value bool) *ServiceMonitorSpecApplyConfiguration { + b.NativeHistogramConfigApplyConfiguration.ScrapeNativeHistograms = &value + return b +} + // WithScrapeClassicHistograms sets the ScrapeClassicHistograms field in the declarative configuration to the given value // and returns the receiver, so that objects can be built by chaining "With" function invocations. // If called multiple times, the ScrapeClassicHistograms field is set to the value of the last call. diff --git a/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1/statefulsetupdatestrategy.go b/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1/statefulsetupdatestrategy.go new file mode 100644 index 00000000000..f5e00d979cb --- /dev/null +++ b/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1/statefulsetupdatestrategy.go @@ -0,0 +1,50 @@ +// Copyright The prometheus-operator Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// Code generated by applyconfiguration-gen. DO NOT EDIT. + +package v1 + +import ( + monitoringv1 "github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1" +) + +// StatefulSetUpdateStrategyApplyConfiguration represents a declarative configuration of the StatefulSetUpdateStrategy type for use +// with apply. +type StatefulSetUpdateStrategyApplyConfiguration struct { + Type *monitoringv1.StatefulSetUpdateStrategyType `json:"type,omitempty"` + RollingUpdate *RollingUpdateStatefulSetStrategyApplyConfiguration `json:"rollingUpdate,omitempty"` +} + +// StatefulSetUpdateStrategyApplyConfiguration constructs a declarative configuration of the StatefulSetUpdateStrategy type for use with +// apply. +func StatefulSetUpdateStrategy() *StatefulSetUpdateStrategyApplyConfiguration { + return &StatefulSetUpdateStrategyApplyConfiguration{} +} + +// WithType sets the Type field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the Type field is set to the value of the last call. +func (b *StatefulSetUpdateStrategyApplyConfiguration) WithType(value monitoringv1.StatefulSetUpdateStrategyType) *StatefulSetUpdateStrategyApplyConfiguration { + b.Type = &value + return b +} + +// WithRollingUpdate sets the RollingUpdate field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the RollingUpdate field is set to the value of the last call. +func (b *StatefulSetUpdateStrategyApplyConfiguration) WithRollingUpdate(value *RollingUpdateStatefulSetStrategyApplyConfiguration) *StatefulSetUpdateStrategyApplyConfiguration { + b.RollingUpdate = value + return b +} diff --git a/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1/thanosrulerspec.go b/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1/thanosrulerspec.go index 461086e213d..f0608d96ceb 100644 --- a/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1/thanosrulerspec.go +++ b/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1/thanosrulerspec.go @@ -50,6 +50,8 @@ type ThanosRulerSpecApplyConfiguration struct { ObjectStorageConfig *corev1.SecretKeySelector `json:"objectStorageConfig,omitempty"` ObjectStorageConfigFile *string `json:"objectStorageConfigFile,omitempty"` ListenLocal *bool `json:"listenLocal,omitempty"` + PodManagementPolicy *monitoringv1.PodManagementPolicyType `json:"podManagementPolicy,omitempty"` + UpdateStrategy *StatefulSetUpdateStrategyApplyConfiguration `json:"updateStrategy,omitempty"` QueryEndpoints []string `json:"queryEndpoints,omitempty"` QueryConfig *corev1.SecretKeySelector `json:"queryConfig,omitempty"` AlertManagersURL []string `json:"alertmanagersUrl,omitempty"` @@ -313,6 +315,22 @@ func (b *ThanosRulerSpecApplyConfiguration) WithListenLocal(value bool) *ThanosR return b } +// WithPodManagementPolicy sets the PodManagementPolicy field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the PodManagementPolicy field is set to the value of the last call. +func (b *ThanosRulerSpecApplyConfiguration) WithPodManagementPolicy(value monitoringv1.PodManagementPolicyType) *ThanosRulerSpecApplyConfiguration { + b.PodManagementPolicy = &value + return b +} + +// WithUpdateStrategy sets the UpdateStrategy field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the UpdateStrategy field is set to the value of the last call. +func (b *ThanosRulerSpecApplyConfiguration) WithUpdateStrategy(value *StatefulSetUpdateStrategyApplyConfiguration) *ThanosRulerSpecApplyConfiguration { + b.UpdateStrategy = value + return b +} + // WithQueryEndpoints adds the given value to the QueryEndpoints field in the declarative configuration // and returns the receiver, so that objects can be build by chaining "With" function invocations. // If called multiple times, values provided by each call will be appended to the QueryEndpoints field. diff --git a/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1/tlsconfig.go b/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1/tlsconfig.go index fe1b8bfc500..d18d96de216 100644 --- a/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1/tlsconfig.go +++ b/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1/tlsconfig.go @@ -24,10 +24,8 @@ import ( // TLSConfigApplyConfiguration represents a declarative configuration of the TLSConfig type for use // with apply. type TLSConfigApplyConfiguration struct { - SafeTLSConfigApplyConfiguration `json:",inline"` - CAFile *string `json:"caFile,omitempty"` - CertFile *string `json:"certFile,omitempty"` - KeyFile *string `json:"keyFile,omitempty"` + SafeTLSConfigApplyConfiguration `json:",inline"` + TLSFilesConfigApplyConfiguration `json:",inline"` } // TLSConfigApplyConfiguration constructs a declarative configuration of the TLSConfig type for use with @@ -96,7 +94,7 @@ func (b *TLSConfigApplyConfiguration) WithMaxVersion(value monitoringv1.TLSVersi // and returns the receiver, so that objects can be built by chaining "With" function invocations. // If called multiple times, the CAFile field is set to the value of the last call. func (b *TLSConfigApplyConfiguration) WithCAFile(value string) *TLSConfigApplyConfiguration { - b.CAFile = &value + b.TLSFilesConfigApplyConfiguration.CAFile = &value return b } @@ -104,7 +102,7 @@ func (b *TLSConfigApplyConfiguration) WithCAFile(value string) *TLSConfigApplyCo // and returns the receiver, so that objects can be built by chaining "With" function invocations. // If called multiple times, the CertFile field is set to the value of the last call. func (b *TLSConfigApplyConfiguration) WithCertFile(value string) *TLSConfigApplyConfiguration { - b.CertFile = &value + b.TLSFilesConfigApplyConfiguration.CertFile = &value return b } @@ -112,6 +110,6 @@ func (b *TLSConfigApplyConfiguration) WithCertFile(value string) *TLSConfigApply // and returns the receiver, so that objects can be built by chaining "With" function invocations. // If called multiple times, the KeyFile field is set to the value of the last call. func (b *TLSConfigApplyConfiguration) WithKeyFile(value string) *TLSConfigApplyConfiguration { - b.KeyFile = &value + b.TLSFilesConfigApplyConfiguration.KeyFile = &value return b } diff --git a/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1/tlsfilesconfig.go b/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1/tlsfilesconfig.go new file mode 100644 index 00000000000..24581704955 --- /dev/null +++ b/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1/tlsfilesconfig.go @@ -0,0 +1,55 @@ +// Copyright The prometheus-operator Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// Code generated by applyconfiguration-gen. DO NOT EDIT. + +package v1 + +// TLSFilesConfigApplyConfiguration represents a declarative configuration of the TLSFilesConfig type for use +// with apply. +type TLSFilesConfigApplyConfiguration struct { + CAFile *string `json:"caFile,omitempty"` + CertFile *string `json:"certFile,omitempty"` + KeyFile *string `json:"keyFile,omitempty"` +} + +// TLSFilesConfigApplyConfiguration constructs a declarative configuration of the TLSFilesConfig type for use with +// apply. +func TLSFilesConfig() *TLSFilesConfigApplyConfiguration { + return &TLSFilesConfigApplyConfiguration{} +} + +// WithCAFile sets the CAFile field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the CAFile field is set to the value of the last call. +func (b *TLSFilesConfigApplyConfiguration) WithCAFile(value string) *TLSFilesConfigApplyConfiguration { + b.CAFile = &value + return b +} + +// WithCertFile sets the CertFile field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the CertFile field is set to the value of the last call. +func (b *TLSFilesConfigApplyConfiguration) WithCertFile(value string) *TLSFilesConfigApplyConfiguration { + b.CertFile = &value + return b +} + +// WithKeyFile sets the KeyFile field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the KeyFile field is set to the value of the last call. +func (b *TLSFilesConfigApplyConfiguration) WithKeyFile(value string) *TLSFilesConfigApplyConfiguration { + b.KeyFile = &value + return b +} diff --git a/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1/prometheustracingconfig.go b/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1/tracingconfig.go similarity index 73% rename from vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1/prometheustracingconfig.go rename to vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1/tracingconfig.go index c461a133240..a75c8f18848 100644 --- a/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1/prometheustracingconfig.go +++ b/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1/tracingconfig.go @@ -21,9 +21,9 @@ import ( resource "k8s.io/apimachinery/pkg/api/resource" ) -// PrometheusTracingConfigApplyConfiguration represents a declarative configuration of the PrometheusTracingConfig type for use +// TracingConfigApplyConfiguration represents a declarative configuration of the TracingConfig type for use // with apply. -type PrometheusTracingConfigApplyConfiguration struct { +type TracingConfigApplyConfiguration struct { ClientType *string `json:"clientType,omitempty"` Endpoint *string `json:"endpoint,omitempty"` SamplingFraction *resource.Quantity `json:"samplingFraction,omitempty"` @@ -34,16 +34,16 @@ type PrometheusTracingConfigApplyConfiguration struct { TLSConfig *TLSConfigApplyConfiguration `json:"tlsConfig,omitempty"` } -// PrometheusTracingConfigApplyConfiguration constructs a declarative configuration of the PrometheusTracingConfig type for use with +// TracingConfigApplyConfiguration constructs a declarative configuration of the TracingConfig type for use with // apply. -func PrometheusTracingConfig() *PrometheusTracingConfigApplyConfiguration { - return &PrometheusTracingConfigApplyConfiguration{} +func TracingConfig() *TracingConfigApplyConfiguration { + return &TracingConfigApplyConfiguration{} } // WithClientType sets the ClientType field in the declarative configuration to the given value // and returns the receiver, so that objects can be built by chaining "With" function invocations. // If called multiple times, the ClientType field is set to the value of the last call. -func (b *PrometheusTracingConfigApplyConfiguration) WithClientType(value string) *PrometheusTracingConfigApplyConfiguration { +func (b *TracingConfigApplyConfiguration) WithClientType(value string) *TracingConfigApplyConfiguration { b.ClientType = &value return b } @@ -51,7 +51,7 @@ func (b *PrometheusTracingConfigApplyConfiguration) WithClientType(value string) // WithEndpoint sets the Endpoint field in the declarative configuration to the given value // and returns the receiver, so that objects can be built by chaining "With" function invocations. // If called multiple times, the Endpoint field is set to the value of the last call. -func (b *PrometheusTracingConfigApplyConfiguration) WithEndpoint(value string) *PrometheusTracingConfigApplyConfiguration { +func (b *TracingConfigApplyConfiguration) WithEndpoint(value string) *TracingConfigApplyConfiguration { b.Endpoint = &value return b } @@ -59,7 +59,7 @@ func (b *PrometheusTracingConfigApplyConfiguration) WithEndpoint(value string) * // WithSamplingFraction sets the SamplingFraction field in the declarative configuration to the given value // and returns the receiver, so that objects can be built by chaining "With" function invocations. // If called multiple times, the SamplingFraction field is set to the value of the last call. -func (b *PrometheusTracingConfigApplyConfiguration) WithSamplingFraction(value resource.Quantity) *PrometheusTracingConfigApplyConfiguration { +func (b *TracingConfigApplyConfiguration) WithSamplingFraction(value resource.Quantity) *TracingConfigApplyConfiguration { b.SamplingFraction = &value return b } @@ -67,7 +67,7 @@ func (b *PrometheusTracingConfigApplyConfiguration) WithSamplingFraction(value r // WithInsecure sets the Insecure field in the declarative configuration to the given value // and returns the receiver, so that objects can be built by chaining "With" function invocations. // If called multiple times, the Insecure field is set to the value of the last call. -func (b *PrometheusTracingConfigApplyConfiguration) WithInsecure(value bool) *PrometheusTracingConfigApplyConfiguration { +func (b *TracingConfigApplyConfiguration) WithInsecure(value bool) *TracingConfigApplyConfiguration { b.Insecure = &value return b } @@ -76,7 +76,7 @@ func (b *PrometheusTracingConfigApplyConfiguration) WithInsecure(value bool) *Pr // and returns the receiver, so that objects can be build by chaining "With" function invocations. // If called multiple times, the entries provided by each call will be put on the Headers field, // overwriting an existing map entries in Headers field with the same key. -func (b *PrometheusTracingConfigApplyConfiguration) WithHeaders(entries map[string]string) *PrometheusTracingConfigApplyConfiguration { +func (b *TracingConfigApplyConfiguration) WithHeaders(entries map[string]string) *TracingConfigApplyConfiguration { if b.Headers == nil && len(entries) > 0 { b.Headers = make(map[string]string, len(entries)) } @@ -89,7 +89,7 @@ func (b *PrometheusTracingConfigApplyConfiguration) WithHeaders(entries map[stri // WithCompression sets the Compression field in the declarative configuration to the given value // and returns the receiver, so that objects can be built by chaining "With" function invocations. // If called multiple times, the Compression field is set to the value of the last call. -func (b *PrometheusTracingConfigApplyConfiguration) WithCompression(value string) *PrometheusTracingConfigApplyConfiguration { +func (b *TracingConfigApplyConfiguration) WithCompression(value string) *TracingConfigApplyConfiguration { b.Compression = &value return b } @@ -97,7 +97,7 @@ func (b *PrometheusTracingConfigApplyConfiguration) WithCompression(value string // WithTimeout sets the Timeout field in the declarative configuration to the given value // and returns the receiver, so that objects can be built by chaining "With" function invocations. // If called multiple times, the Timeout field is set to the value of the last call. -func (b *PrometheusTracingConfigApplyConfiguration) WithTimeout(value monitoringv1.Duration) *PrometheusTracingConfigApplyConfiguration { +func (b *TracingConfigApplyConfiguration) WithTimeout(value monitoringv1.Duration) *TracingConfigApplyConfiguration { b.Timeout = &value return b } @@ -105,7 +105,7 @@ func (b *PrometheusTracingConfigApplyConfiguration) WithTimeout(value monitoring // WithTLSConfig sets the TLSConfig field in the declarative configuration to the given value // and returns the receiver, so that objects can be built by chaining "With" function invocations. // If called multiple times, the TLSConfig field is set to the value of the last call. -func (b *PrometheusTracingConfigApplyConfiguration) WithTLSConfig(value *TLSConfigApplyConfiguration) *PrometheusTracingConfigApplyConfiguration { +func (b *TracingConfigApplyConfiguration) WithTLSConfig(value *TLSConfigApplyConfiguration) *TracingConfigApplyConfiguration { b.TLSConfig = value return b } diff --git a/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1alpha1/alertmanagerconfig.go b/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1alpha1/alertmanagerconfig.go index dd7e9dfbed8..157a4f25ec0 100644 --- a/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1alpha1/alertmanagerconfig.go +++ b/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1alpha1/alertmanagerconfig.go @@ -17,6 +17,7 @@ package v1alpha1 import ( + monitoringv1 "github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" types "k8s.io/apimachinery/pkg/types" v1 "k8s.io/client-go/applyconfigurations/meta/v1" @@ -27,7 +28,8 @@ import ( type AlertmanagerConfigApplyConfiguration struct { v1.TypeMetaApplyConfiguration `json:",inline"` *v1.ObjectMetaApplyConfiguration `json:"metadata,omitempty"` - Spec *AlertmanagerConfigSpecApplyConfiguration `json:"spec,omitempty"` + Spec *AlertmanagerConfigSpecApplyConfiguration `json:"spec,omitempty"` + Status *monitoringv1.ConfigResourceStatusApplyConfiguration `json:"status,omitempty"` } // AlertmanagerConfig constructs a declarative configuration of the AlertmanagerConfig type for use with @@ -208,6 +210,14 @@ func (b *AlertmanagerConfigApplyConfiguration) WithSpec(value *AlertmanagerConfi return b } +// WithStatus sets the Status field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the Status field is set to the value of the last call. +func (b *AlertmanagerConfigApplyConfiguration) WithStatus(value *monitoringv1.ConfigResourceStatusApplyConfiguration) *AlertmanagerConfigApplyConfiguration { + b.Status = value + return b +} + // GetKind retrieves the value of the Kind field in the declarative configuration. func (b *AlertmanagerConfigApplyConfiguration) GetKind() *string { return b.TypeMetaApplyConfiguration.Kind diff --git a/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1alpha1/opsgenieconfig.go b/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1alpha1/opsgenieconfig.go index d8bbd7d8810..2ddb9b240b6 100644 --- a/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1alpha1/opsgenieconfig.go +++ b/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1alpha1/opsgenieconfig.go @@ -17,6 +17,7 @@ package v1alpha1 import ( + monitoringv1alpha1 "github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1alpha1" v1 "k8s.io/api/core/v1" ) @@ -25,7 +26,7 @@ import ( type OpsGenieConfigApplyConfiguration struct { SendResolved *bool `json:"sendResolved,omitempty"` APIKey *v1.SecretKeySelector `json:"apiKey,omitempty"` - APIURL *string `json:"apiURL,omitempty"` + APIURL *monitoringv1alpha1.URL `json:"apiURL,omitempty"` Message *string `json:"message,omitempty"` Description *string `json:"description,omitempty"` Source *string `json:"source,omitempty"` @@ -65,7 +66,7 @@ func (b *OpsGenieConfigApplyConfiguration) WithAPIKey(value v1.SecretKeySelector // WithAPIURL sets the APIURL field in the declarative configuration to the given value // and returns the receiver, so that objects can be built by chaining "With" function invocations. // If called multiple times, the APIURL field is set to the value of the last call. -func (b *OpsGenieConfigApplyConfiguration) WithAPIURL(value string) *OpsGenieConfigApplyConfiguration { +func (b *OpsGenieConfigApplyConfiguration) WithAPIURL(value monitoringv1alpha1.URL) *OpsGenieConfigApplyConfiguration { b.APIURL = &value return b } diff --git a/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1alpha1/pagerdutyconfig.go b/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1alpha1/pagerdutyconfig.go index b33e6802d91..36229445469 100644 --- a/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1alpha1/pagerdutyconfig.go +++ b/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1alpha1/pagerdutyconfig.go @@ -17,6 +17,8 @@ package v1alpha1 import ( + monitoringv1 "github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1" + monitoringv1alpha1 "github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1alpha1" v1 "k8s.io/api/core/v1" ) @@ -26,9 +28,9 @@ type PagerDutyConfigApplyConfiguration struct { SendResolved *bool `json:"sendResolved,omitempty"` RoutingKey *v1.SecretKeySelector `json:"routingKey,omitempty"` ServiceKey *v1.SecretKeySelector `json:"serviceKey,omitempty"` - URL *string `json:"url,omitempty"` + URL *monitoringv1alpha1.URL `json:"url,omitempty"` Client *string `json:"client,omitempty"` - ClientURL *string `json:"clientURL,omitempty"` + ClientURL *monitoringv1alpha1.URL `json:"clientURL,omitempty"` Description *string `json:"description,omitempty"` Severity *string `json:"severity,omitempty"` Class *string `json:"class,omitempty"` @@ -39,6 +41,7 @@ type PagerDutyConfigApplyConfiguration struct { PagerDutyLinkConfigs []PagerDutyLinkConfigApplyConfiguration `json:"pagerDutyLinkConfigs,omitempty"` HTTPConfig *HTTPConfigApplyConfiguration `json:"httpConfig,omitempty"` Source *string `json:"source,omitempty"` + Timeout *monitoringv1.Duration `json:"timeout,omitempty"` } // PagerDutyConfigApplyConfiguration constructs a declarative configuration of the PagerDutyConfig type for use with @@ -74,7 +77,7 @@ func (b *PagerDutyConfigApplyConfiguration) WithServiceKey(value v1.SecretKeySel // WithURL sets the URL field in the declarative configuration to the given value // and returns the receiver, so that objects can be built by chaining "With" function invocations. // If called multiple times, the URL field is set to the value of the last call. -func (b *PagerDutyConfigApplyConfiguration) WithURL(value string) *PagerDutyConfigApplyConfiguration { +func (b *PagerDutyConfigApplyConfiguration) WithURL(value monitoringv1alpha1.URL) *PagerDutyConfigApplyConfiguration { b.URL = &value return b } @@ -90,7 +93,7 @@ func (b *PagerDutyConfigApplyConfiguration) WithClient(value string) *PagerDutyC // WithClientURL sets the ClientURL field in the declarative configuration to the given value // and returns the receiver, so that objects can be built by chaining "With" function invocations. // If called multiple times, the ClientURL field is set to the value of the last call. -func (b *PagerDutyConfigApplyConfiguration) WithClientURL(value string) *PagerDutyConfigApplyConfiguration { +func (b *PagerDutyConfigApplyConfiguration) WithClientURL(value monitoringv1alpha1.URL) *PagerDutyConfigApplyConfiguration { b.ClientURL = &value return b } @@ -189,3 +192,11 @@ func (b *PagerDutyConfigApplyConfiguration) WithSource(value string) *PagerDutyC b.Source = &value return b } + +// WithTimeout sets the Timeout field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the Timeout field is set to the value of the last call. +func (b *PagerDutyConfigApplyConfiguration) WithTimeout(value monitoringv1.Duration) *PagerDutyConfigApplyConfiguration { + b.Timeout = &value + return b +} diff --git a/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1alpha1/pagerdutyimageconfig.go b/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1alpha1/pagerdutyimageconfig.go index a0759824b88..d4325e80a72 100644 --- a/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1alpha1/pagerdutyimageconfig.go +++ b/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1alpha1/pagerdutyimageconfig.go @@ -16,12 +16,16 @@ package v1alpha1 +import ( + monitoringv1alpha1 "github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1alpha1" +) + // PagerDutyImageConfigApplyConfiguration represents a declarative configuration of the PagerDutyImageConfig type for use // with apply. type PagerDutyImageConfigApplyConfiguration struct { - Src *string `json:"src,omitempty"` - Href *string `json:"href,omitempty"` - Alt *string `json:"alt,omitempty"` + Src *string `json:"src,omitempty"` + Href *monitoringv1alpha1.URL `json:"href,omitempty"` + Alt *string `json:"alt,omitempty"` } // PagerDutyImageConfigApplyConfiguration constructs a declarative configuration of the PagerDutyImageConfig type for use with @@ -41,7 +45,7 @@ func (b *PagerDutyImageConfigApplyConfiguration) WithSrc(value string) *PagerDut // WithHref sets the Href field in the declarative configuration to the given value // and returns the receiver, so that objects can be built by chaining "With" function invocations. // If called multiple times, the Href field is set to the value of the last call. -func (b *PagerDutyImageConfigApplyConfiguration) WithHref(value string) *PagerDutyImageConfigApplyConfiguration { +func (b *PagerDutyImageConfigApplyConfiguration) WithHref(value monitoringv1alpha1.URL) *PagerDutyImageConfigApplyConfiguration { b.Href = &value return b } diff --git a/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1alpha1/pagerdutylinkconfig.go b/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1alpha1/pagerdutylinkconfig.go index 418c322ac38..7693d89aade 100644 --- a/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1alpha1/pagerdutylinkconfig.go +++ b/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1alpha1/pagerdutylinkconfig.go @@ -16,11 +16,15 @@ package v1alpha1 +import ( + monitoringv1alpha1 "github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1alpha1" +) + // PagerDutyLinkConfigApplyConfiguration represents a declarative configuration of the PagerDutyLinkConfig type for use // with apply. type PagerDutyLinkConfigApplyConfiguration struct { - Href *string `json:"href,omitempty"` - Text *string `json:"alt,omitempty"` + Href *monitoringv1alpha1.URL `json:"href,omitempty"` + Text *string `json:"alt,omitempty"` } // PagerDutyLinkConfigApplyConfiguration constructs a declarative configuration of the PagerDutyLinkConfig type for use with @@ -32,7 +36,7 @@ func PagerDutyLinkConfig() *PagerDutyLinkConfigApplyConfiguration { // WithHref sets the Href field in the declarative configuration to the given value // and returns the receiver, so that objects can be built by chaining "With" function invocations. // If called multiple times, the Href field is set to the value of the last call. -func (b *PagerDutyLinkConfigApplyConfiguration) WithHref(value string) *PagerDutyLinkConfigApplyConfiguration { +func (b *PagerDutyLinkConfigApplyConfiguration) WithHref(value monitoringv1alpha1.URL) *PagerDutyLinkConfigApplyConfiguration { b.Href = &value return b } diff --git a/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1alpha1/prometheusagentspec.go b/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1alpha1/prometheusagentspec.go index 7255e57c114..347ef88661b 100644 --- a/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1alpha1/prometheusagentspec.go +++ b/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1alpha1/prometheusagentspec.go @@ -486,6 +486,22 @@ func (b *PrometheusAgentSpecApplyConfiguration) WithListenLocal(value bool) *Pro return b } +// WithPodManagementPolicy sets the PodManagementPolicy field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the PodManagementPolicy field is set to the value of the last call. +func (b *PrometheusAgentSpecApplyConfiguration) WithPodManagementPolicy(value monitoringv1.PodManagementPolicyType) *PrometheusAgentSpecApplyConfiguration { + b.CommonPrometheusFieldsApplyConfiguration.PodManagementPolicy = &value + return b +} + +// WithUpdateStrategy sets the UpdateStrategy field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the UpdateStrategy field is set to the value of the last call. +func (b *PrometheusAgentSpecApplyConfiguration) WithUpdateStrategy(value *v1.StatefulSetUpdateStrategyApplyConfiguration) *PrometheusAgentSpecApplyConfiguration { + b.CommonPrometheusFieldsApplyConfiguration.UpdateStrategy = value + return b +} + // WithEnableServiceLinks sets the EnableServiceLinks field in the declarative configuration to the given value // and returns the receiver, so that objects can be built by chaining "With" function invocations. // If called multiple times, the EnableServiceLinks field is set to the value of the last call. @@ -666,6 +682,14 @@ func (b *PrometheusAgentSpecApplyConfiguration) WithConvertClassicHistogramsToNH return b } +// WithScrapeNativeHistograms sets the ScrapeNativeHistograms field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the ScrapeNativeHistograms field is set to the value of the last call. +func (b *PrometheusAgentSpecApplyConfiguration) WithScrapeNativeHistograms(value bool) *PrometheusAgentSpecApplyConfiguration { + b.CommonPrometheusFieldsApplyConfiguration.ScrapeNativeHistograms = &value + return b +} + // WithScrapeClassicHistograms sets the ScrapeClassicHistograms field in the declarative configuration to the given value // and returns the receiver, so that objects can be built by chaining "With" function invocations. // If called multiple times, the ScrapeClassicHistograms field is set to the value of the last call. @@ -750,7 +774,7 @@ func (b *PrometheusAgentSpecApplyConfiguration) WithPodTargetLabels(values ...st // WithTracingConfig sets the TracingConfig field in the declarative configuration to the given value // and returns the receiver, so that objects can be built by chaining "With" function invocations. // If called multiple times, the TracingConfig field is set to the value of the last call. -func (b *PrometheusAgentSpecApplyConfiguration) WithTracingConfig(value *v1.PrometheusTracingConfigApplyConfiguration) *PrometheusAgentSpecApplyConfiguration { +func (b *PrometheusAgentSpecApplyConfiguration) WithTracingConfig(value *v1.TracingConfigApplyConfiguration) *PrometheusAgentSpecApplyConfiguration { b.CommonPrometheusFieldsApplyConfiguration.TracingConfig = value return b } diff --git a/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1alpha1/pushoverconfig.go b/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1alpha1/pushoverconfig.go index c51188be5cb..da1f1c17230 100644 --- a/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1alpha1/pushoverconfig.go +++ b/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1alpha1/pushoverconfig.go @@ -18,6 +18,7 @@ package v1alpha1 import ( monitoringv1 "github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1" + monitoringv1alpha1 "github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1alpha1" v1 "k8s.io/api/core/v1" ) @@ -31,7 +32,7 @@ type PushoverConfigApplyConfiguration struct { TokenFile *string `json:"tokenFile,omitempty"` Title *string `json:"title,omitempty"` Message *string `json:"message,omitempty"` - URL *string `json:"url,omitempty"` + URL *monitoringv1alpha1.URL `json:"url,omitempty"` URLTitle *string `json:"urlTitle,omitempty"` TTL *monitoringv1.Duration `json:"ttl,omitempty"` Device *string `json:"device,omitempty"` @@ -109,7 +110,7 @@ func (b *PushoverConfigApplyConfiguration) WithMessage(value string) *PushoverCo // WithURL sets the URL field in the declarative configuration to the given value // and returns the receiver, so that objects can be built by chaining "With" function invocations. // If called multiple times, the URL field is set to the value of the last call. -func (b *PushoverConfigApplyConfiguration) WithURL(value string) *PushoverConfigApplyConfiguration { +func (b *PushoverConfigApplyConfiguration) WithURL(value monitoringv1alpha1.URL) *PushoverConfigApplyConfiguration { b.URL = &value return b } diff --git a/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1alpha1/scrapeconfigspec.go b/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1alpha1/scrapeconfigspec.go index 8f8078f0ae2..8e212b53691 100644 --- a/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1alpha1/scrapeconfigspec.go +++ b/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1alpha1/scrapeconfigspec.go @@ -583,6 +583,14 @@ func (b *ScrapeConfigSpecApplyConfiguration) WithLabelValueLengthLimit(value uin return b } +// WithScrapeNativeHistograms sets the ScrapeNativeHistograms field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the ScrapeNativeHistograms field is set to the value of the last call. +func (b *ScrapeConfigSpecApplyConfiguration) WithScrapeNativeHistograms(value bool) *ScrapeConfigSpecApplyConfiguration { + b.NativeHistogramConfigApplyConfiguration.ScrapeNativeHistograms = &value + return b +} + // WithScrapeClassicHistograms sets the ScrapeClassicHistograms field in the declarative configuration to the given value // and returns the receiver, so that objects can be built by chaining "With" function invocations. // If called multiple times, the ScrapeClassicHistograms field is set to the value of the last call. diff --git a/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1alpha1/slackaction.go b/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1alpha1/slackaction.go index 39878c54a6b..5837e098789 100644 --- a/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1alpha1/slackaction.go +++ b/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1alpha1/slackaction.go @@ -16,12 +16,16 @@ package v1alpha1 +import ( + monitoringv1alpha1 "github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1alpha1" +) + // SlackActionApplyConfiguration represents a declarative configuration of the SlackAction type for use // with apply. type SlackActionApplyConfiguration struct { Type *string `json:"type,omitempty"` Text *string `json:"text,omitempty"` - URL *string `json:"url,omitempty"` + URL *monitoringv1alpha1.URL `json:"url,omitempty"` Style *string `json:"style,omitempty"` Name *string `json:"name,omitempty"` Value *string `json:"value,omitempty"` @@ -53,7 +57,7 @@ func (b *SlackActionApplyConfiguration) WithText(value string) *SlackActionApply // WithURL sets the URL field in the declarative configuration to the given value // and returns the receiver, so that objects can be built by chaining "With" function invocations. // If called multiple times, the URL field is set to the value of the last call. -func (b *SlackActionApplyConfiguration) WithURL(value string) *SlackActionApplyConfiguration { +func (b *SlackActionApplyConfiguration) WithURL(value monitoringv1alpha1.URL) *SlackActionApplyConfiguration { b.URL = &value return b } diff --git a/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1alpha1/slackconfig.go b/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1alpha1/slackconfig.go index d0c9904f15a..0b07c752ed1 100644 --- a/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1alpha1/slackconfig.go +++ b/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1alpha1/slackconfig.go @@ -17,6 +17,8 @@ package v1alpha1 import ( + monitoringv1 "github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1" + monitoringv1alpha1 "github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1alpha1" v1 "k8s.io/api/core/v1" ) @@ -29,7 +31,7 @@ type SlackConfigApplyConfiguration struct { Username *string `json:"username,omitempty"` Color *string `json:"color,omitempty"` Title *string `json:"title,omitempty"` - TitleLink *string `json:"titleLink,omitempty"` + TitleLink *monitoringv1alpha1.URL `json:"titleLink,omitempty"` Pretext *string `json:"pretext,omitempty"` Text *string `json:"text,omitempty"` Fields []SlackFieldApplyConfiguration `json:"fields,omitempty"` @@ -38,13 +40,14 @@ type SlackConfigApplyConfiguration struct { Fallback *string `json:"fallback,omitempty"` CallbackID *string `json:"callbackId,omitempty"` IconEmoji *string `json:"iconEmoji,omitempty"` - IconURL *string `json:"iconURL,omitempty"` - ImageURL *string `json:"imageURL,omitempty"` - ThumbURL *string `json:"thumbURL,omitempty"` + IconURL *monitoringv1alpha1.URL `json:"iconURL,omitempty"` + ImageURL *monitoringv1alpha1.URL `json:"imageURL,omitempty"` + ThumbURL *monitoringv1alpha1.URL `json:"thumbURL,omitempty"` LinkNames *bool `json:"linkNames,omitempty"` MrkdwnIn []string `json:"mrkdwnIn,omitempty"` Actions []SlackActionApplyConfiguration `json:"actions,omitempty"` HTTPConfig *HTTPConfigApplyConfiguration `json:"httpConfig,omitempty"` + Timeout *monitoringv1.Duration `json:"timeout,omitempty"` } // SlackConfigApplyConfiguration constructs a declarative configuration of the SlackConfig type for use with @@ -104,7 +107,7 @@ func (b *SlackConfigApplyConfiguration) WithTitle(value string) *SlackConfigAppl // WithTitleLink sets the TitleLink field in the declarative configuration to the given value // and returns the receiver, so that objects can be built by chaining "With" function invocations. // If called multiple times, the TitleLink field is set to the value of the last call. -func (b *SlackConfigApplyConfiguration) WithTitleLink(value string) *SlackConfigApplyConfiguration { +func (b *SlackConfigApplyConfiguration) WithTitleLink(value monitoringv1alpha1.URL) *SlackConfigApplyConfiguration { b.TitleLink = &value return b } @@ -181,7 +184,7 @@ func (b *SlackConfigApplyConfiguration) WithIconEmoji(value string) *SlackConfig // WithIconURL sets the IconURL field in the declarative configuration to the given value // and returns the receiver, so that objects can be built by chaining "With" function invocations. // If called multiple times, the IconURL field is set to the value of the last call. -func (b *SlackConfigApplyConfiguration) WithIconURL(value string) *SlackConfigApplyConfiguration { +func (b *SlackConfigApplyConfiguration) WithIconURL(value monitoringv1alpha1.URL) *SlackConfigApplyConfiguration { b.IconURL = &value return b } @@ -189,7 +192,7 @@ func (b *SlackConfigApplyConfiguration) WithIconURL(value string) *SlackConfigAp // WithImageURL sets the ImageURL field in the declarative configuration to the given value // and returns the receiver, so that objects can be built by chaining "With" function invocations. // If called multiple times, the ImageURL field is set to the value of the last call. -func (b *SlackConfigApplyConfiguration) WithImageURL(value string) *SlackConfigApplyConfiguration { +func (b *SlackConfigApplyConfiguration) WithImageURL(value monitoringv1alpha1.URL) *SlackConfigApplyConfiguration { b.ImageURL = &value return b } @@ -197,7 +200,7 @@ func (b *SlackConfigApplyConfiguration) WithImageURL(value string) *SlackConfigA // WithThumbURL sets the ThumbURL field in the declarative configuration to the given value // and returns the receiver, so that objects can be built by chaining "With" function invocations. // If called multiple times, the ThumbURL field is set to the value of the last call. -func (b *SlackConfigApplyConfiguration) WithThumbURL(value string) *SlackConfigApplyConfiguration { +func (b *SlackConfigApplyConfiguration) WithThumbURL(value monitoringv1alpha1.URL) *SlackConfigApplyConfiguration { b.ThumbURL = &value return b } @@ -240,3 +243,11 @@ func (b *SlackConfigApplyConfiguration) WithHTTPConfig(value *HTTPConfigApplyCon b.HTTPConfig = value return b } + +// WithTimeout sets the Timeout field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the Timeout field is set to the value of the last call. +func (b *SlackConfigApplyConfiguration) WithTimeout(value monitoringv1.Duration) *SlackConfigApplyConfiguration { + b.Timeout = &value + return b +} diff --git a/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1alpha1/telegramconfig.go b/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1alpha1/telegramconfig.go index 37cb9107425..34ad12e97ad 100644 --- a/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1alpha1/telegramconfig.go +++ b/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1alpha1/telegramconfig.go @@ -17,6 +17,7 @@ package v1alpha1 import ( + monitoringv1alpha1 "github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1alpha1" v1 "k8s.io/api/core/v1" ) @@ -24,7 +25,7 @@ import ( // with apply. type TelegramConfigApplyConfiguration struct { SendResolved *bool `json:"sendResolved,omitempty"` - APIURL *string `json:"apiURL,omitempty"` + APIURL *monitoringv1alpha1.URL `json:"apiURL,omitempty"` BotToken *v1.SecretKeySelector `json:"botToken,omitempty"` BotTokenFile *string `json:"botTokenFile,omitempty"` ChatID *int64 `json:"chatID,omitempty"` @@ -52,7 +53,7 @@ func (b *TelegramConfigApplyConfiguration) WithSendResolved(value bool) *Telegra // WithAPIURL sets the APIURL field in the declarative configuration to the given value // and returns the receiver, so that objects can be built by chaining "With" function invocations. // If called multiple times, the APIURL field is set to the value of the last call. -func (b *TelegramConfigApplyConfiguration) WithAPIURL(value string) *TelegramConfigApplyConfiguration { +func (b *TelegramConfigApplyConfiguration) WithAPIURL(value monitoringv1alpha1.URL) *TelegramConfigApplyConfiguration { b.APIURL = &value return b } diff --git a/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1alpha1/victoropsconfig.go b/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1alpha1/victoropsconfig.go index b1632d5f4ff..bbd54cb314f 100644 --- a/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1alpha1/victoropsconfig.go +++ b/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1alpha1/victoropsconfig.go @@ -17,6 +17,7 @@ package v1alpha1 import ( + monitoringv1alpha1 "github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1alpha1" v1 "k8s.io/api/core/v1" ) @@ -25,7 +26,7 @@ import ( type VictorOpsConfigApplyConfiguration struct { SendResolved *bool `json:"sendResolved,omitempty"` APIKey *v1.SecretKeySelector `json:"apiKey,omitempty"` - APIURL *string `json:"apiUrl,omitempty"` + APIURL *monitoringv1alpha1.URL `json:"apiUrl,omitempty"` RoutingKey *string `json:"routingKey,omitempty"` MessageType *string `json:"messageType,omitempty"` EntityDisplayName *string `json:"entityDisplayName,omitempty"` @@ -60,7 +61,7 @@ func (b *VictorOpsConfigApplyConfiguration) WithAPIKey(value v1.SecretKeySelecto // WithAPIURL sets the APIURL field in the declarative configuration to the given value // and returns the receiver, so that objects can be built by chaining "With" function invocations. // If called multiple times, the APIURL field is set to the value of the last call. -func (b *VictorOpsConfigApplyConfiguration) WithAPIURL(value string) *VictorOpsConfigApplyConfiguration { +func (b *VictorOpsConfigApplyConfiguration) WithAPIURL(value monitoringv1alpha1.URL) *VictorOpsConfigApplyConfiguration { b.APIURL = &value return b } diff --git a/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1alpha1/webhookconfig.go b/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1alpha1/webhookconfig.go index 214064e981c..d7190b51008 100644 --- a/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1alpha1/webhookconfig.go +++ b/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1alpha1/webhookconfig.go @@ -18,6 +18,7 @@ package v1alpha1 import ( monitoringv1 "github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1" + monitoringv1alpha1 "github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1alpha1" v1 "k8s.io/api/core/v1" ) @@ -25,7 +26,7 @@ import ( // with apply. type WebhookConfigApplyConfiguration struct { SendResolved *bool `json:"sendResolved,omitempty"` - URL *string `json:"url,omitempty"` + URL *monitoringv1alpha1.URL `json:"url,omitempty"` URLSecret *v1.SecretKeySelector `json:"urlSecret,omitempty"` HTTPConfig *HTTPConfigApplyConfiguration `json:"httpConfig,omitempty"` MaxAlerts *int32 `json:"maxAlerts,omitempty"` @@ -49,7 +50,7 @@ func (b *WebhookConfigApplyConfiguration) WithSendResolved(value bool) *WebhookC // WithURL sets the URL field in the declarative configuration to the given value // and returns the receiver, so that objects can be built by chaining "With" function invocations. // If called multiple times, the URL field is set to the value of the last call. -func (b *WebhookConfigApplyConfiguration) WithURL(value string) *WebhookConfigApplyConfiguration { +func (b *WebhookConfigApplyConfiguration) WithURL(value monitoringv1alpha1.URL) *WebhookConfigApplyConfiguration { b.URL = &value return b } diff --git a/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1alpha1/wechatconfig.go b/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1alpha1/wechatconfig.go index de747f63391..3f3b134af72 100644 --- a/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1alpha1/wechatconfig.go +++ b/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1alpha1/wechatconfig.go @@ -17,6 +17,7 @@ package v1alpha1 import ( + monitoringv1alpha1 "github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1alpha1" v1 "k8s.io/api/core/v1" ) @@ -25,7 +26,7 @@ import ( type WeChatConfigApplyConfiguration struct { SendResolved *bool `json:"sendResolved,omitempty"` APISecret *v1.SecretKeySelector `json:"apiSecret,omitempty"` - APIURL *string `json:"apiURL,omitempty"` + APIURL *monitoringv1alpha1.URL `json:"apiURL,omitempty"` CorpID *string `json:"corpID,omitempty"` AgentID *string `json:"agentID,omitempty"` ToUser *string `json:"toUser,omitempty"` @@ -61,7 +62,7 @@ func (b *WeChatConfigApplyConfiguration) WithAPISecret(value v1.SecretKeySelecto // WithAPIURL sets the APIURL field in the declarative configuration to the given value // and returns the receiver, so that objects can be built by chaining "With" function invocations. // If called multiple times, the APIURL field is set to the value of the last call. -func (b *WeChatConfigApplyConfiguration) WithAPIURL(value string) *WeChatConfigApplyConfiguration { +func (b *WeChatConfigApplyConfiguration) WithAPIURL(value monitoringv1alpha1.URL) *WeChatConfigApplyConfiguration { b.APIURL = &value return b } diff --git a/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1beta1/alertmanagerconfig.go b/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1beta1/alertmanagerconfig.go index 2d95b225a07..0c8972507d7 100644 --- a/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1beta1/alertmanagerconfig.go +++ b/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1beta1/alertmanagerconfig.go @@ -17,6 +17,7 @@ package v1beta1 import ( + monitoringv1 "github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" types "k8s.io/apimachinery/pkg/types" v1 "k8s.io/client-go/applyconfigurations/meta/v1" @@ -27,7 +28,8 @@ import ( type AlertmanagerConfigApplyConfiguration struct { v1.TypeMetaApplyConfiguration `json:",inline"` *v1.ObjectMetaApplyConfiguration `json:"metadata,omitempty"` - Spec *AlertmanagerConfigSpecApplyConfiguration `json:"spec,omitempty"` + Spec *AlertmanagerConfigSpecApplyConfiguration `json:"spec,omitempty"` + Status *monitoringv1.ConfigResourceStatusApplyConfiguration `json:"status,omitempty"` } // AlertmanagerConfig constructs a declarative configuration of the AlertmanagerConfig type for use with @@ -208,6 +210,14 @@ func (b *AlertmanagerConfigApplyConfiguration) WithSpec(value *AlertmanagerConfi return b } +// WithStatus sets the Status field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the Status field is set to the value of the last call. +func (b *AlertmanagerConfigApplyConfiguration) WithStatus(value *monitoringv1.ConfigResourceStatusApplyConfiguration) *AlertmanagerConfigApplyConfiguration { + b.Status = value + return b +} + // GetKind retrieves the value of the Kind field in the declarative configuration. func (b *AlertmanagerConfigApplyConfiguration) GetKind() *string { return b.TypeMetaApplyConfiguration.Kind diff --git a/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1beta1/opsgenieconfig.go b/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1beta1/opsgenieconfig.go index 9fafd3b4658..aa811b8d47b 100644 --- a/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1beta1/opsgenieconfig.go +++ b/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1beta1/opsgenieconfig.go @@ -16,12 +16,16 @@ package v1beta1 +import ( + monitoringv1beta1 "github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1beta1" +) + // OpsGenieConfigApplyConfiguration represents a declarative configuration of the OpsGenieConfig type for use // with apply. type OpsGenieConfigApplyConfiguration struct { SendResolved *bool `json:"sendResolved,omitempty"` APIKey *SecretKeySelectorApplyConfiguration `json:"apiKey,omitempty"` - APIURL *string `json:"apiURL,omitempty"` + APIURL *monitoringv1beta1.URL `json:"apiURL,omitempty"` Message *string `json:"message,omitempty"` Description *string `json:"description,omitempty"` Source *string `json:"source,omitempty"` @@ -60,7 +64,7 @@ func (b *OpsGenieConfigApplyConfiguration) WithAPIKey(value *SecretKeySelectorAp // WithAPIURL sets the APIURL field in the declarative configuration to the given value // and returns the receiver, so that objects can be built by chaining "With" function invocations. // If called multiple times, the APIURL field is set to the value of the last call. -func (b *OpsGenieConfigApplyConfiguration) WithAPIURL(value string) *OpsGenieConfigApplyConfiguration { +func (b *OpsGenieConfigApplyConfiguration) WithAPIURL(value monitoringv1beta1.URL) *OpsGenieConfigApplyConfiguration { b.APIURL = &value return b } diff --git a/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1beta1/pagerdutyconfig.go b/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1beta1/pagerdutyconfig.go index 653e53ebbf4..8978e021a70 100644 --- a/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1beta1/pagerdutyconfig.go +++ b/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1beta1/pagerdutyconfig.go @@ -16,15 +16,20 @@ package v1beta1 +import ( + v1 "github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1" + monitoringv1beta1 "github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1beta1" +) + // PagerDutyConfigApplyConfiguration represents a declarative configuration of the PagerDutyConfig type for use // with apply. type PagerDutyConfigApplyConfiguration struct { SendResolved *bool `json:"sendResolved,omitempty"` RoutingKey *SecretKeySelectorApplyConfiguration `json:"routingKey,omitempty"` ServiceKey *SecretKeySelectorApplyConfiguration `json:"serviceKey,omitempty"` - URL *string `json:"url,omitempty"` + URL *monitoringv1beta1.URL `json:"url,omitempty"` Client *string `json:"client,omitempty"` - ClientURL *string `json:"clientURL,omitempty"` + ClientURL *monitoringv1beta1.URL `json:"clientURL,omitempty"` Description *string `json:"description,omitempty"` Severity *string `json:"severity,omitempty"` Class *string `json:"class,omitempty"` @@ -35,6 +40,7 @@ type PagerDutyConfigApplyConfiguration struct { PagerDutyLinkConfigs []PagerDutyLinkConfigApplyConfiguration `json:"pagerDutyLinkConfigs,omitempty"` HTTPConfig *HTTPConfigApplyConfiguration `json:"httpConfig,omitempty"` Source *string `json:"source,omitempty"` + Timeout *v1.Duration `json:"timeout,omitempty"` } // PagerDutyConfigApplyConfiguration constructs a declarative configuration of the PagerDutyConfig type for use with @@ -70,7 +76,7 @@ func (b *PagerDutyConfigApplyConfiguration) WithServiceKey(value *SecretKeySelec // WithURL sets the URL field in the declarative configuration to the given value // and returns the receiver, so that objects can be built by chaining "With" function invocations. // If called multiple times, the URL field is set to the value of the last call. -func (b *PagerDutyConfigApplyConfiguration) WithURL(value string) *PagerDutyConfigApplyConfiguration { +func (b *PagerDutyConfigApplyConfiguration) WithURL(value monitoringv1beta1.URL) *PagerDutyConfigApplyConfiguration { b.URL = &value return b } @@ -86,7 +92,7 @@ func (b *PagerDutyConfigApplyConfiguration) WithClient(value string) *PagerDutyC // WithClientURL sets the ClientURL field in the declarative configuration to the given value // and returns the receiver, so that objects can be built by chaining "With" function invocations. // If called multiple times, the ClientURL field is set to the value of the last call. -func (b *PagerDutyConfigApplyConfiguration) WithClientURL(value string) *PagerDutyConfigApplyConfiguration { +func (b *PagerDutyConfigApplyConfiguration) WithClientURL(value monitoringv1beta1.URL) *PagerDutyConfigApplyConfiguration { b.ClientURL = &value return b } @@ -185,3 +191,11 @@ func (b *PagerDutyConfigApplyConfiguration) WithSource(value string) *PagerDutyC b.Source = &value return b } + +// WithTimeout sets the Timeout field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the Timeout field is set to the value of the last call. +func (b *PagerDutyConfigApplyConfiguration) WithTimeout(value v1.Duration) *PagerDutyConfigApplyConfiguration { + b.Timeout = &value + return b +} diff --git a/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1beta1/pagerdutyimageconfig.go b/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1beta1/pagerdutyimageconfig.go index d49bc2442cd..62602cef883 100644 --- a/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1beta1/pagerdutyimageconfig.go +++ b/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1beta1/pagerdutyimageconfig.go @@ -16,12 +16,16 @@ package v1beta1 +import ( + monitoringv1beta1 "github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1beta1" +) + // PagerDutyImageConfigApplyConfiguration represents a declarative configuration of the PagerDutyImageConfig type for use // with apply. type PagerDutyImageConfigApplyConfiguration struct { - Src *string `json:"src,omitempty"` - Href *string `json:"href,omitempty"` - Alt *string `json:"alt,omitempty"` + Src *string `json:"src,omitempty"` + Href *monitoringv1beta1.URL `json:"href,omitempty"` + Alt *string `json:"alt,omitempty"` } // PagerDutyImageConfigApplyConfiguration constructs a declarative configuration of the PagerDutyImageConfig type for use with @@ -41,7 +45,7 @@ func (b *PagerDutyImageConfigApplyConfiguration) WithSrc(value string) *PagerDut // WithHref sets the Href field in the declarative configuration to the given value // and returns the receiver, so that objects can be built by chaining "With" function invocations. // If called multiple times, the Href field is set to the value of the last call. -func (b *PagerDutyImageConfigApplyConfiguration) WithHref(value string) *PagerDutyImageConfigApplyConfiguration { +func (b *PagerDutyImageConfigApplyConfiguration) WithHref(value monitoringv1beta1.URL) *PagerDutyImageConfigApplyConfiguration { b.Href = &value return b } diff --git a/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1beta1/pagerdutylinkconfig.go b/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1beta1/pagerdutylinkconfig.go index b4f12a652b4..50eb84b78c4 100644 --- a/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1beta1/pagerdutylinkconfig.go +++ b/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1beta1/pagerdutylinkconfig.go @@ -16,11 +16,15 @@ package v1beta1 +import ( + monitoringv1beta1 "github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1beta1" +) + // PagerDutyLinkConfigApplyConfiguration represents a declarative configuration of the PagerDutyLinkConfig type for use // with apply. type PagerDutyLinkConfigApplyConfiguration struct { - Href *string `json:"href,omitempty"` - Text *string `json:"alt,omitempty"` + Href *monitoringv1beta1.URL `json:"href,omitempty"` + Text *string `json:"alt,omitempty"` } // PagerDutyLinkConfigApplyConfiguration constructs a declarative configuration of the PagerDutyLinkConfig type for use with @@ -32,7 +36,7 @@ func PagerDutyLinkConfig() *PagerDutyLinkConfigApplyConfiguration { // WithHref sets the Href field in the declarative configuration to the given value // and returns the receiver, so that objects can be built by chaining "With" function invocations. // If called multiple times, the Href field is set to the value of the last call. -func (b *PagerDutyLinkConfigApplyConfiguration) WithHref(value string) *PagerDutyLinkConfigApplyConfiguration { +func (b *PagerDutyLinkConfigApplyConfiguration) WithHref(value monitoringv1beta1.URL) *PagerDutyLinkConfigApplyConfiguration { b.Href = &value return b } diff --git a/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1beta1/pushoverconfig.go b/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1beta1/pushoverconfig.go index ac15ac00604..910b6a07054 100644 --- a/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1beta1/pushoverconfig.go +++ b/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1beta1/pushoverconfig.go @@ -18,6 +18,7 @@ package v1beta1 import ( v1 "github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1" + monitoringv1beta1 "github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1beta1" ) // PushoverConfigApplyConfiguration represents a declarative configuration of the PushoverConfig type for use @@ -30,7 +31,7 @@ type PushoverConfigApplyConfiguration struct { TokenFile *string `json:"tokenFile,omitempty"` Title *string `json:"title,omitempty"` Message *string `json:"message,omitempty"` - URL *string `json:"url,omitempty"` + URL *monitoringv1beta1.URL `json:"url,omitempty"` URLTitle *string `json:"urlTitle,omitempty"` TTL *v1.Duration `json:"ttl,omitempty"` Device *string `json:"device,omitempty"` @@ -108,7 +109,7 @@ func (b *PushoverConfigApplyConfiguration) WithMessage(value string) *PushoverCo // WithURL sets the URL field in the declarative configuration to the given value // and returns the receiver, so that objects can be built by chaining "With" function invocations. // If called multiple times, the URL field is set to the value of the last call. -func (b *PushoverConfigApplyConfiguration) WithURL(value string) *PushoverConfigApplyConfiguration { +func (b *PushoverConfigApplyConfiguration) WithURL(value monitoringv1beta1.URL) *PushoverConfigApplyConfiguration { b.URL = &value return b } diff --git a/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1beta1/slackaction.go b/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1beta1/slackaction.go index 45511920100..a4f936f3553 100644 --- a/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1beta1/slackaction.go +++ b/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1beta1/slackaction.go @@ -16,12 +16,16 @@ package v1beta1 +import ( + monitoringv1beta1 "github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1beta1" +) + // SlackActionApplyConfiguration represents a declarative configuration of the SlackAction type for use // with apply. type SlackActionApplyConfiguration struct { Type *string `json:"type,omitempty"` Text *string `json:"text,omitempty"` - URL *string `json:"url,omitempty"` + URL *monitoringv1beta1.URL `json:"url,omitempty"` Style *string `json:"style,omitempty"` Name *string `json:"name,omitempty"` Value *string `json:"value,omitempty"` @@ -53,7 +57,7 @@ func (b *SlackActionApplyConfiguration) WithText(value string) *SlackActionApply // WithURL sets the URL field in the declarative configuration to the given value // and returns the receiver, so that objects can be built by chaining "With" function invocations. // If called multiple times, the URL field is set to the value of the last call. -func (b *SlackActionApplyConfiguration) WithURL(value string) *SlackActionApplyConfiguration { +func (b *SlackActionApplyConfiguration) WithURL(value monitoringv1beta1.URL) *SlackActionApplyConfiguration { b.URL = &value return b } diff --git a/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1beta1/slackconfig.go b/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1beta1/slackconfig.go index 4c86d5287d3..69e888942b0 100644 --- a/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1beta1/slackconfig.go +++ b/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1beta1/slackconfig.go @@ -16,6 +16,11 @@ package v1beta1 +import ( + v1 "github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1" + monitoringv1beta1 "github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1beta1" +) + // SlackConfigApplyConfiguration represents a declarative configuration of the SlackConfig type for use // with apply. type SlackConfigApplyConfiguration struct { @@ -25,7 +30,7 @@ type SlackConfigApplyConfiguration struct { Username *string `json:"username,omitempty"` Color *string `json:"color,omitempty"` Title *string `json:"title,omitempty"` - TitleLink *string `json:"titleLink,omitempty"` + TitleLink *monitoringv1beta1.URL `json:"titleLink,omitempty"` Pretext *string `json:"pretext,omitempty"` Text *string `json:"text,omitempty"` Fields []SlackFieldApplyConfiguration `json:"fields,omitempty"` @@ -34,13 +39,14 @@ type SlackConfigApplyConfiguration struct { Fallback *string `json:"fallback,omitempty"` CallbackID *string `json:"callbackId,omitempty"` IconEmoji *string `json:"iconEmoji,omitempty"` - IconURL *string `json:"iconURL,omitempty"` - ImageURL *string `json:"imageURL,omitempty"` - ThumbURL *string `json:"thumbURL,omitempty"` + IconURL *monitoringv1beta1.URL `json:"iconURL,omitempty"` + ImageURL *monitoringv1beta1.URL `json:"imageURL,omitempty"` + ThumbURL *monitoringv1beta1.URL `json:"thumbURL,omitempty"` LinkNames *bool `json:"linkNames,omitempty"` MrkdwnIn []string `json:"mrkdwnIn,omitempty"` Actions []SlackActionApplyConfiguration `json:"actions,omitempty"` HTTPConfig *HTTPConfigApplyConfiguration `json:"httpConfig,omitempty"` + Timeout *v1.Duration `json:"timeout,omitempty"` } // SlackConfigApplyConfiguration constructs a declarative configuration of the SlackConfig type for use with @@ -100,7 +106,7 @@ func (b *SlackConfigApplyConfiguration) WithTitle(value string) *SlackConfigAppl // WithTitleLink sets the TitleLink field in the declarative configuration to the given value // and returns the receiver, so that objects can be built by chaining "With" function invocations. // If called multiple times, the TitleLink field is set to the value of the last call. -func (b *SlackConfigApplyConfiguration) WithTitleLink(value string) *SlackConfigApplyConfiguration { +func (b *SlackConfigApplyConfiguration) WithTitleLink(value monitoringv1beta1.URL) *SlackConfigApplyConfiguration { b.TitleLink = &value return b } @@ -177,7 +183,7 @@ func (b *SlackConfigApplyConfiguration) WithIconEmoji(value string) *SlackConfig // WithIconURL sets the IconURL field in the declarative configuration to the given value // and returns the receiver, so that objects can be built by chaining "With" function invocations. // If called multiple times, the IconURL field is set to the value of the last call. -func (b *SlackConfigApplyConfiguration) WithIconURL(value string) *SlackConfigApplyConfiguration { +func (b *SlackConfigApplyConfiguration) WithIconURL(value monitoringv1beta1.URL) *SlackConfigApplyConfiguration { b.IconURL = &value return b } @@ -185,7 +191,7 @@ func (b *SlackConfigApplyConfiguration) WithIconURL(value string) *SlackConfigAp // WithImageURL sets the ImageURL field in the declarative configuration to the given value // and returns the receiver, so that objects can be built by chaining "With" function invocations. // If called multiple times, the ImageURL field is set to the value of the last call. -func (b *SlackConfigApplyConfiguration) WithImageURL(value string) *SlackConfigApplyConfiguration { +func (b *SlackConfigApplyConfiguration) WithImageURL(value monitoringv1beta1.URL) *SlackConfigApplyConfiguration { b.ImageURL = &value return b } @@ -193,7 +199,7 @@ func (b *SlackConfigApplyConfiguration) WithImageURL(value string) *SlackConfigA // WithThumbURL sets the ThumbURL field in the declarative configuration to the given value // and returns the receiver, so that objects can be built by chaining "With" function invocations. // If called multiple times, the ThumbURL field is set to the value of the last call. -func (b *SlackConfigApplyConfiguration) WithThumbURL(value string) *SlackConfigApplyConfiguration { +func (b *SlackConfigApplyConfiguration) WithThumbURL(value monitoringv1beta1.URL) *SlackConfigApplyConfiguration { b.ThumbURL = &value return b } @@ -236,3 +242,11 @@ func (b *SlackConfigApplyConfiguration) WithHTTPConfig(value *HTTPConfigApplyCon b.HTTPConfig = value return b } + +// WithTimeout sets the Timeout field in the declarative configuration to the given value +// and returns the receiver, so that objects can be built by chaining "With" function invocations. +// If called multiple times, the Timeout field is set to the value of the last call. +func (b *SlackConfigApplyConfiguration) WithTimeout(value v1.Duration) *SlackConfigApplyConfiguration { + b.Timeout = &value + return b +} diff --git a/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1beta1/telegramconfig.go b/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1beta1/telegramconfig.go index 1c8ea3fddab..474e462ec75 100644 --- a/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1beta1/telegramconfig.go +++ b/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1beta1/telegramconfig.go @@ -16,11 +16,15 @@ package v1beta1 +import ( + monitoringv1beta1 "github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1beta1" +) + // TelegramConfigApplyConfiguration represents a declarative configuration of the TelegramConfig type for use // with apply. type TelegramConfigApplyConfiguration struct { SendResolved *bool `json:"sendResolved,omitempty"` - APIURL *string `json:"apiURL,omitempty"` + APIURL *monitoringv1beta1.URL `json:"apiURL,omitempty"` BotToken *SecretKeySelectorApplyConfiguration `json:"botToken,omitempty"` BotTokenFile *string `json:"botTokenFile,omitempty"` ChatID *int64 `json:"chatID,omitempty"` @@ -48,7 +52,7 @@ func (b *TelegramConfigApplyConfiguration) WithSendResolved(value bool) *Telegra // WithAPIURL sets the APIURL field in the declarative configuration to the given value // and returns the receiver, so that objects can be built by chaining "With" function invocations. // If called multiple times, the APIURL field is set to the value of the last call. -func (b *TelegramConfigApplyConfiguration) WithAPIURL(value string) *TelegramConfigApplyConfiguration { +func (b *TelegramConfigApplyConfiguration) WithAPIURL(value monitoringv1beta1.URL) *TelegramConfigApplyConfiguration { b.APIURL = &value return b } diff --git a/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1beta1/victoropsconfig.go b/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1beta1/victoropsconfig.go index ffd1be84957..0286668ed20 100644 --- a/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1beta1/victoropsconfig.go +++ b/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1beta1/victoropsconfig.go @@ -16,12 +16,16 @@ package v1beta1 +import ( + monitoringv1beta1 "github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1beta1" +) + // VictorOpsConfigApplyConfiguration represents a declarative configuration of the VictorOpsConfig type for use // with apply. type VictorOpsConfigApplyConfiguration struct { SendResolved *bool `json:"sendResolved,omitempty"` APIKey *SecretKeySelectorApplyConfiguration `json:"apiKey,omitempty"` - APIURL *string `json:"apiUrl,omitempty"` + APIURL *monitoringv1beta1.URL `json:"apiUrl,omitempty"` RoutingKey *string `json:"routingKey,omitempty"` MessageType *string `json:"messageType,omitempty"` EntityDisplayName *string `json:"entityDisplayName,omitempty"` @@ -56,7 +60,7 @@ func (b *VictorOpsConfigApplyConfiguration) WithAPIKey(value *SecretKeySelectorA // WithAPIURL sets the APIURL field in the declarative configuration to the given value // and returns the receiver, so that objects can be built by chaining "With" function invocations. // If called multiple times, the APIURL field is set to the value of the last call. -func (b *VictorOpsConfigApplyConfiguration) WithAPIURL(value string) *VictorOpsConfigApplyConfiguration { +func (b *VictorOpsConfigApplyConfiguration) WithAPIURL(value monitoringv1beta1.URL) *VictorOpsConfigApplyConfiguration { b.APIURL = &value return b } diff --git a/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1beta1/webhookconfig.go b/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1beta1/webhookconfig.go index 61a59b26132..be6879ed6db 100644 --- a/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1beta1/webhookconfig.go +++ b/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1beta1/webhookconfig.go @@ -18,13 +18,14 @@ package v1beta1 import ( v1 "github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1" + monitoringv1beta1 "github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1beta1" ) // WebhookConfigApplyConfiguration represents a declarative configuration of the WebhookConfig type for use // with apply. type WebhookConfigApplyConfiguration struct { SendResolved *bool `json:"sendResolved,omitempty"` - URL *string `json:"url,omitempty"` + URL *monitoringv1beta1.URL `json:"url,omitempty"` URLSecret *SecretKeySelectorApplyConfiguration `json:"urlSecret,omitempty"` HTTPConfig *HTTPConfigApplyConfiguration `json:"httpConfig,omitempty"` MaxAlerts *int32 `json:"maxAlerts,omitempty"` @@ -48,7 +49,7 @@ func (b *WebhookConfigApplyConfiguration) WithSendResolved(value bool) *WebhookC // WithURL sets the URL field in the declarative configuration to the given value // and returns the receiver, so that objects can be built by chaining "With" function invocations. // If called multiple times, the URL field is set to the value of the last call. -func (b *WebhookConfigApplyConfiguration) WithURL(value string) *WebhookConfigApplyConfiguration { +func (b *WebhookConfigApplyConfiguration) WithURL(value monitoringv1beta1.URL) *WebhookConfigApplyConfiguration { b.URL = &value return b } diff --git a/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1beta1/wechatconfig.go b/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1beta1/wechatconfig.go index 8ce8441b918..92af08e3180 100644 --- a/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1beta1/wechatconfig.go +++ b/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/monitoring/v1beta1/wechatconfig.go @@ -16,12 +16,16 @@ package v1beta1 +import ( + monitoringv1beta1 "github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1beta1" +) + // WeChatConfigApplyConfiguration represents a declarative configuration of the WeChatConfig type for use // with apply. type WeChatConfigApplyConfiguration struct { SendResolved *bool `json:"sendResolved,omitempty"` APISecret *SecretKeySelectorApplyConfiguration `json:"apiSecret,omitempty"` - APIURL *string `json:"apiURL,omitempty"` + APIURL *monitoringv1beta1.URL `json:"apiURL,omitempty"` CorpID *string `json:"corpID,omitempty"` AgentID *string `json:"agentID,omitempty"` ToUser *string `json:"toUser,omitempty"` @@ -57,7 +61,7 @@ func (b *WeChatConfigApplyConfiguration) WithAPISecret(value *SecretKeySelectorA // WithAPIURL sets the APIURL field in the declarative configuration to the given value // and returns the receiver, so that objects can be built by chaining "With" function invocations. // If called multiple times, the APIURL field is set to the value of the last call. -func (b *WeChatConfigApplyConfiguration) WithAPIURL(value string) *WeChatConfigApplyConfiguration { +func (b *WeChatConfigApplyConfiguration) WithAPIURL(value monitoringv1beta1.URL) *WeChatConfigApplyConfiguration { b.APIURL = &value return b } diff --git a/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/utils.go b/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/utils.go index f0002d79779..eb697c40e7f 100644 --- a/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/utils.go +++ b/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/utils.go @@ -70,6 +70,8 @@ func ForKind(kind schema.GroupVersionKind) interface{} { return &monitoringv1.AzureOAuthApplyConfiguration{} case v1.SchemeGroupVersion.WithKind("AzureSDK"): return &monitoringv1.AzureSDKApplyConfiguration{} + case v1.SchemeGroupVersion.WithKind("AzureWorkloadIdentity"): + return &monitoringv1.AzureWorkloadIdentityApplyConfiguration{} case v1.SchemeGroupVersion.WithKind("BasicAuth"): return &monitoringv1.BasicAuthApplyConfiguration{} case v1.SchemeGroupVersion.WithKind("ClusterTLSConfig"): @@ -112,6 +114,14 @@ func ForKind(kind schema.GroupVersionKind) interface{} { return &monitoringv1.HostPortApplyConfiguration{} case v1.SchemeGroupVersion.WithKind("HTTPConfig"): return &monitoringv1.HTTPConfigApplyConfiguration{} + case v1.SchemeGroupVersion.WithKind("HTTPConfigWithoutTLS"): + return &monitoringv1.HTTPConfigWithoutTLSApplyConfiguration{} + case v1.SchemeGroupVersion.WithKind("HTTPConfigWithProxy"): + return &monitoringv1.HTTPConfigWithProxyApplyConfiguration{} + case v1.SchemeGroupVersion.WithKind("HTTPConfigWithProxyAndTLSFiles"): + return &monitoringv1.HTTPConfigWithProxyAndTLSFilesApplyConfiguration{} + case v1.SchemeGroupVersion.WithKind("HTTPConfigWithTLSFiles"): + return &monitoringv1.HTTPConfigWithTLSFilesApplyConfiguration{} case v1.SchemeGroupVersion.WithKind("ManagedIdentity"): return &monitoringv1.ManagedIdentityApplyConfiguration{} case v1.SchemeGroupVersion.WithKind("MetadataConfig"): @@ -162,8 +172,6 @@ func ForKind(kind schema.GroupVersionKind) interface{} { return &monitoringv1.PrometheusSpecApplyConfiguration{} case v1.SchemeGroupVersion.WithKind("PrometheusStatus"): return &monitoringv1.PrometheusStatusApplyConfiguration{} - case v1.SchemeGroupVersion.WithKind("PrometheusTracingConfig"): - return &monitoringv1.PrometheusTracingConfigApplyConfiguration{} case v1.SchemeGroupVersion.WithKind("PrometheusWebSpec"): return &monitoringv1.PrometheusWebSpecApplyConfiguration{} case v1.SchemeGroupVersion.WithKind("ProxyConfig"): @@ -180,6 +188,8 @@ func ForKind(kind schema.GroupVersionKind) interface{} { return &monitoringv1.RemoteWriteSpecApplyConfiguration{} case v1.SchemeGroupVersion.WithKind("RetainConfig"): return &monitoringv1.RetainConfigApplyConfiguration{} + case v1.SchemeGroupVersion.WithKind("RollingUpdateStatefulSetStrategy"): + return &monitoringv1.RollingUpdateStatefulSetStrategyApplyConfiguration{} case v1.SchemeGroupVersion.WithKind("Rule"): return &monitoringv1.RuleApplyConfiguration{} case v1.SchemeGroupVersion.WithKind("RuleGroup"): @@ -208,6 +218,8 @@ func ForKind(kind schema.GroupVersionKind) interface{} { return &monitoringv1.ShardStatusApplyConfiguration{} case v1.SchemeGroupVersion.WithKind("Sigv4"): return &monitoringv1.Sigv4ApplyConfiguration{} + case v1.SchemeGroupVersion.WithKind("StatefulSetUpdateStrategy"): + return &monitoringv1.StatefulSetUpdateStrategyApplyConfiguration{} case v1.SchemeGroupVersion.WithKind("StorageSpec"): return &monitoringv1.StorageSpecApplyConfiguration{} case v1.SchemeGroupVersion.WithKind("ThanosRuler"): @@ -222,8 +234,12 @@ func ForKind(kind schema.GroupVersionKind) interface{} { return &monitoringv1.ThanosSpecApplyConfiguration{} case v1.SchemeGroupVersion.WithKind("TLSConfig"): return &monitoringv1.TLSConfigApplyConfiguration{} + case v1.SchemeGroupVersion.WithKind("TLSFilesConfig"): + return &monitoringv1.TLSFilesConfigApplyConfiguration{} case v1.SchemeGroupVersion.WithKind("TopologySpreadConstraint"): return &monitoringv1.TopologySpreadConstraintApplyConfiguration{} + case v1.SchemeGroupVersion.WithKind("TracingConfig"): + return &monitoringv1.TracingConfigApplyConfiguration{} case v1.SchemeGroupVersion.WithKind("TSDBSpec"): return &monitoringv1.TSDBSpecApplyConfiguration{} case v1.SchemeGroupVersion.WithKind("WebConfigFileFields"): diff --git a/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/versioned/typed/monitoring/v1alpha1/alertmanagerconfig.go b/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/versioned/typed/monitoring/v1alpha1/alertmanagerconfig.go index d9ca01a91c0..bfc032ed528 100644 --- a/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/versioned/typed/monitoring/v1alpha1/alertmanagerconfig.go +++ b/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/versioned/typed/monitoring/v1alpha1/alertmanagerconfig.go @@ -38,6 +38,8 @@ type AlertmanagerConfigsGetter interface { type AlertmanagerConfigInterface interface { Create(ctx context.Context, alertmanagerConfig *monitoringv1alpha1.AlertmanagerConfig, opts v1.CreateOptions) (*monitoringv1alpha1.AlertmanagerConfig, error) Update(ctx context.Context, alertmanagerConfig *monitoringv1alpha1.AlertmanagerConfig, opts v1.UpdateOptions) (*monitoringv1alpha1.AlertmanagerConfig, error) + // Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus(). + UpdateStatus(ctx context.Context, alertmanagerConfig *monitoringv1alpha1.AlertmanagerConfig, opts v1.UpdateOptions) (*monitoringv1alpha1.AlertmanagerConfig, error) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error Get(ctx context.Context, name string, opts v1.GetOptions) (*monitoringv1alpha1.AlertmanagerConfig, error) @@ -45,6 +47,8 @@ type AlertmanagerConfigInterface interface { Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *monitoringv1alpha1.AlertmanagerConfig, err error) Apply(ctx context.Context, alertmanagerConfig *applyconfigurationmonitoringv1alpha1.AlertmanagerConfigApplyConfiguration, opts v1.ApplyOptions) (result *monitoringv1alpha1.AlertmanagerConfig, err error) + // Add a +genclient:noStatus comment above the type to avoid generating ApplyStatus(). + ApplyStatus(ctx context.Context, alertmanagerConfig *applyconfigurationmonitoringv1alpha1.AlertmanagerConfigApplyConfiguration, opts v1.ApplyOptions) (result *monitoringv1alpha1.AlertmanagerConfig, err error) AlertmanagerConfigExpansion } diff --git a/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/versioned/typed/monitoring/v1beta1/alertmanagerconfig.go b/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/versioned/typed/monitoring/v1beta1/alertmanagerconfig.go index 3c8bf2da37d..1e14605efc1 100644 --- a/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/versioned/typed/monitoring/v1beta1/alertmanagerconfig.go +++ b/vendor/github.com/prometheus-operator/prometheus-operator/pkg/client/versioned/typed/monitoring/v1beta1/alertmanagerconfig.go @@ -38,6 +38,8 @@ type AlertmanagerConfigsGetter interface { type AlertmanagerConfigInterface interface { Create(ctx context.Context, alertmanagerConfig *monitoringv1beta1.AlertmanagerConfig, opts v1.CreateOptions) (*monitoringv1beta1.AlertmanagerConfig, error) Update(ctx context.Context, alertmanagerConfig *monitoringv1beta1.AlertmanagerConfig, opts v1.UpdateOptions) (*monitoringv1beta1.AlertmanagerConfig, error) + // Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus(). + UpdateStatus(ctx context.Context, alertmanagerConfig *monitoringv1beta1.AlertmanagerConfig, opts v1.UpdateOptions) (*monitoringv1beta1.AlertmanagerConfig, error) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error Get(ctx context.Context, name string, opts v1.GetOptions) (*monitoringv1beta1.AlertmanagerConfig, error) @@ -45,6 +47,8 @@ type AlertmanagerConfigInterface interface { Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *monitoringv1beta1.AlertmanagerConfig, err error) Apply(ctx context.Context, alertmanagerConfig *applyconfigurationmonitoringv1beta1.AlertmanagerConfigApplyConfiguration, opts v1.ApplyOptions) (result *monitoringv1beta1.AlertmanagerConfig, err error) + // Add a +genclient:noStatus comment above the type to avoid generating ApplyStatus(). + ApplyStatus(ctx context.Context, alertmanagerConfig *applyconfigurationmonitoringv1beta1.AlertmanagerConfigApplyConfiguration, opts v1.ApplyOptions) (result *monitoringv1beta1.AlertmanagerConfig, err error) AlertmanagerConfigExpansion } diff --git a/vendor/github.com/prometheus/alertmanager/api/v2/client/alert/get_alerts_parameters.go b/vendor/github.com/prometheus/alertmanager/api/v2/client/alert/get_alerts_parameters.go index 89ff1880eeb..b5fdac356f0 100644 --- a/vendor/github.com/prometheus/alertmanager/api/v2/client/alert/get_alerts_parameters.go +++ b/vendor/github.com/prometheus/alertmanager/api/v2/client/alert/get_alerts_parameters.go @@ -86,7 +86,7 @@ type GetAlertsParams struct { /* Filter. - A list of matchers to filter alerts by + A matcher expression to filter alerts. For example `alertname="MyAlert"`. It can be repeated to apply multiple matchers. */ Filter []string diff --git a/vendor/github.com/prometheus/alertmanager/api/v2/client/alertgroup/get_alert_groups_parameters.go b/vendor/github.com/prometheus/alertmanager/api/v2/client/alertgroup/get_alert_groups_parameters.go index 81020fcf679..1c96b29cfa4 100644 --- a/vendor/github.com/prometheus/alertmanager/api/v2/client/alertgroup/get_alert_groups_parameters.go +++ b/vendor/github.com/prometheus/alertmanager/api/v2/client/alertgroup/get_alert_groups_parameters.go @@ -86,7 +86,7 @@ type GetAlertGroupsParams struct { /* Filter. - A list of matchers to filter alerts by + A matcher expression to filter alert groups. For example `alertname="MyAlert"`. It can be repeated to apply multiple matchers. */ Filter []string diff --git a/vendor/github.com/prometheus/alertmanager/api/v2/client/silence/get_silences_parameters.go b/vendor/github.com/prometheus/alertmanager/api/v2/client/silence/get_silences_parameters.go index d964efefa26..8e02101200c 100644 --- a/vendor/github.com/prometheus/alertmanager/api/v2/client/silence/get_silences_parameters.go +++ b/vendor/github.com/prometheus/alertmanager/api/v2/client/silence/get_silences_parameters.go @@ -78,7 +78,7 @@ type GetSilencesParams struct { /* Filter. - A list of matchers to filter silences by + A matcher expression to filter silences. For example `alertname="MyAlert"`. It can be repeated to apply multiple matchers. */ Filter []string diff --git a/vendor/github.com/prometheus/alertmanager/config/config.go b/vendor/github.com/prometheus/alertmanager/config/config.go index 09cd7138705..4f8d803e63c 100644 --- a/vendor/github.com/prometheus/alertmanager/config/config.go +++ b/vendor/github.com/prometheus/alertmanager/config/config.go @@ -1,4 +1,4 @@ -// Copyright 2015 Prometheus Team +// Copyright The Prometheus Authors // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at @@ -298,6 +298,9 @@ func resolveFilepaths(baseDir string, cfg *Config) { for _, cfg := range receiver.RocketchatConfigs { cfg.HTTPConfig.SetDirectory(baseDir) } + for _, cfg := range receiver.MattermostConfigs { + cfg.HTTPConfig.SetDirectory(baseDir) + } } } @@ -348,6 +351,8 @@ type Config struct { MuteTimeIntervals []MuteTimeInterval `yaml:"mute_time_intervals,omitempty" json:"mute_time_intervals,omitempty"` TimeIntervals []TimeInterval `yaml:"time_intervals,omitempty" json:"time_intervals,omitempty"` + TracingConfig TracingConfig `yaml:"tracing,omitempty" json:"tracing,omitempty"` + // original is the input from which the config was parsed. original string } @@ -377,10 +382,23 @@ func (c *Config) UnmarshalYAML(unmarshal func(any) error) error { *c.Global = DefaultGlobalConfig() } + if c.Global.SlackAppToken != "" && len(c.Global.SlackAppTokenFile) > 0 { + return errors.New("at most one of slack_app_token & slack_app_token_file must be configured") + } + if c.Global.SlackAPIURL != nil && len(c.Global.SlackAPIURLFile) > 0 { return errors.New("at most one of slack_api_url & slack_api_url_file must be configured") } + if (c.Global.SlackAppToken != "" || len(c.Global.SlackAppTokenFile) > 0) && (c.Global.SlackAPIURL != nil || len(c.Global.SlackAPIURLFile) > 0) { + // Support transition from workaround suggested in https://github.com/prometheus/alertmanager/issues/2513, + // where users might set `slack_api_url` at the top level and then have `http_config` with individual + // bearer tokens in the receivers. + if c.Global.SlackAPIURL.String() != c.Global.SlackAppURL.String() { + return errors.New("at most one of slack_app_token/slack_app_token_file & slack_api_url/slack_api_url_file must be configured") + } + } + if c.Global.OpsGenieAPIKey != "" && len(c.Global.OpsGenieAPIKeyFile) > 0 { return errors.New("at most one of opsgenie_api_key & opsgenie_api_key_file must be configured") } @@ -450,16 +468,40 @@ func (c *Config) UnmarshalYAML(unmarshal func(any) error) error { } } for _, sc := range rcv.SlackConfigs { - if sc.HTTPConfig == nil { - sc.HTTPConfig = c.Global.HTTPConfig + if sc.AppURL == nil { + if c.Global.SlackAppURL == nil { + return errors.New("no global Slack App URL set") + } + sc.AppURL = c.Global.SlackAppURL + } + // we only want to set the app token from global if there's no local authorization or webhook url + if sc.AppToken == "" && len(sc.AppTokenFile) == 0 && (sc.HTTPConfig == nil || sc.HTTPConfig.Authorization == nil) && sc.APIURL == nil { + sc.AppToken = c.Global.SlackAppToken + sc.AppTokenFile = c.Global.SlackAppTokenFile } if sc.APIURL == nil && len(sc.APIURLFile) == 0 { - if c.Global.SlackAPIURL == nil && len(c.Global.SlackAPIURLFile) == 0 { - return errors.New("no global Slack API URL set either inline or in a file") - } sc.APIURL = c.Global.SlackAPIURL sc.APIURLFile = c.Global.SlackAPIURLFile } + if sc.APIURL == nil && len(sc.APIURLFile) == 0 && sc.AppToken == "" && len(sc.AppTokenFile) == 0 { + return errors.New("no Slack API URL nor App token set either inline or in a file") + } + if sc.HTTPConfig == nil { + // we don't want to change the global http config when setting the receiver's http config, do we do a copy + httpconfig := *c.Global.HTTPConfig + sc.HTTPConfig = &httpconfig + } + if sc.AppToken != "" || len(sc.AppTokenFile) != 0 { + if sc.HTTPConfig.Authorization != nil { + return errors.New("http authorization can't be set when using Slack App tokens") + } + sc.HTTPConfig.Authorization = &commoncfg.Authorization{ + Type: "Bearer", + Credentials: commoncfg.Secret(sc.AppToken), + CredentialsFile: sc.AppTokenFile, + } + sc.APIURL = (*SecretURL)(sc.AppURL) + } } for _, poc := range rcv.PushoverConfigs { if poc.HTTPConfig == nil { @@ -637,6 +679,11 @@ func (c *Config) UnmarshalYAML(unmarshal func(any) error) error { rocketchat.TokenFile = c.Global.RocketchatTokenFile } } + for _, mattermost := range rcv.MattermostConfigs { + if mattermost.HTTPConfig == nil { + mattermost.HTTPConfig = c.Global.HTTPConfig + } + } names[rcv.Name] = struct{}{} } @@ -741,6 +788,7 @@ func DefaultGlobalConfig() GlobalConfig { TelegramAPIUrl: mustParseURL("https://api.telegram.org"), WebexAPIURL: mustParseURL("https://webexapis.com/v1/messages"), RocketchatAPIURL: mustParseURL("https://open.rocket.chat/"), + SlackAppURL: mustParseURL("https://slack.com/api/chat.postMessage"), } } @@ -855,6 +903,9 @@ type GlobalConfig struct { SMTPTLSConfig *commoncfg.TLSConfig `yaml:"smtp_tls_config,omitempty" json:"smtp_tls_config,omitempty"` SlackAPIURL *SecretURL `yaml:"slack_api_url,omitempty" json:"slack_api_url,omitempty"` SlackAPIURLFile string `yaml:"slack_api_url_file,omitempty" json:"slack_api_url_file,omitempty"` + SlackAppToken Secret `yaml:"slack_app_token,omitempty" json:"slack_app_token,omitempty"` + SlackAppTokenFile string `yaml:"slack_app_token_file,omitempty" json:"slack_app_token_file,omitempty"` + SlackAppURL *URL `yaml:"slack_app_url,omitempty" json:"slack_app_url,omitempty"` PagerdutyURL *URL `yaml:"pagerduty_url,omitempty" json:"pagerduty_url,omitempty"` OpsGenieAPIURL *URL `yaml:"opsgenie_api_url,omitempty" json:"opsgenie_api_url,omitempty"` OpsGenieAPIKey Secret `yaml:"opsgenie_api_key,omitempty" json:"opsgenie_api_key,omitempty"` @@ -955,6 +1006,8 @@ func (r *Route) UnmarshalYAML(unmarshal func(any) error) error { // target labels if an alert matching the source labels exists. // Both alerts have to have a set of labels being equal. type InhibitRule struct { + // Name is an optional name for the inhibition rule. + Name string `yaml:"name,omitempty" json:"name,omitempty"` // SourceMatch defines a set of labels that have to equal the given // value for source alerts. Deprecated. Remove before v1.0 release. SourceMatch map[string]string `yaml:"source_match,omitempty" json:"source_match,omitempty"` @@ -1027,6 +1080,7 @@ type Receiver struct { MSTeamsV2Configs []*MSTeamsV2Config `yaml:"msteamsv2_configs,omitempty" json:"msteamsv2_configs,omitempty"` JiraConfigs []*JiraConfig `yaml:"jira_configs,omitempty" json:"jira_configs,omitempty"` RocketchatConfigs []*RocketchatConfig `yaml:"rocketchat_configs,omitempty" json:"rocketchat_configs,omitempty"` + MattermostConfigs []*MattermostConfig `yaml:"mattermost_configs,omitempty" json:"mattermost_configs,omitempty"` } // UnmarshalYAML implements the yaml.Unmarshaler interface for Receiver. diff --git a/vendor/github.com/prometheus/alertmanager/config/coordinator.go b/vendor/github.com/prometheus/alertmanager/config/coordinator.go index 68d1f0307ac..e9f3e21d8f4 100644 --- a/vendor/github.com/prometheus/alertmanager/config/coordinator.go +++ b/vendor/github.com/prometheus/alertmanager/config/coordinator.go @@ -20,6 +20,7 @@ import ( "sync" "github.com/prometheus/client_golang/prometheus" + "github.com/prometheus/client_golang/prometheus/promauto" ) // Coordinator coordinates Alertmanager configurations beyond the lifetime of a @@ -53,21 +54,19 @@ func NewCoordinator(configFilePath string, r prometheus.Registerer, l *slog.Logg } func (c *Coordinator) registerMetrics(r prometheus.Registerer) { - configHash := prometheus.NewGauge(prometheus.GaugeOpts{ + configHash := promauto.With(r).NewGauge(prometheus.GaugeOpts{ Name: "alertmanager_config_hash", Help: "Hash of the currently loaded alertmanager configuration. Note that this is not a cryptographically strong hash.", }) - configSuccess := prometheus.NewGauge(prometheus.GaugeOpts{ + configSuccess := promauto.With(r).NewGauge(prometheus.GaugeOpts{ Name: "alertmanager_config_last_reload_successful", Help: "Whether the last configuration reload attempt was successful.", }) - configSuccessTime := prometheus.NewGauge(prometheus.GaugeOpts{ + configSuccessTime := promauto.With(r).NewGauge(prometheus.GaugeOpts{ Name: "alertmanager_config_last_reload_success_timestamp_seconds", Help: "Timestamp of the last successful configuration reload.", }) - r.MustRegister(configHash, configSuccess, configSuccessTime) - c.configHashMetric = configHash c.configSuccessMetric = configSuccess c.configSuccessTimeMetric = configSuccessTime diff --git a/vendor/github.com/prometheus/alertmanager/config/notifiers.go b/vendor/github.com/prometheus/alertmanager/config/notifiers.go index e8b7dcf28cb..bf7be0b28a5 100644 --- a/vendor/github.com/prometheus/alertmanager/config/notifiers.go +++ b/vendor/github.com/prometheus/alertmanager/config/notifiers.go @@ -72,9 +72,9 @@ var ( DefaultEmailSubject = `{{ template "email.default.subject" . }}` // DefaultPagerdutyDetails defines the default values for PagerDuty details. - DefaultPagerdutyDetails = map[string]string{ - "firing": `{{ template "pagerduty.default.instances" .Alerts.Firing }}`, - "resolved": `{{ template "pagerduty.default.instances" .Alerts.Resolved }}`, + DefaultPagerdutyDetails = map[string]any{ + "firing": `{{ .Alerts.Firing | toJson }}`, + "resolved": `{{ .Alerts.Resolved | toJson }}`, "num_firing": `{{ .Alerts.Firing | len }}`, "num_resolved": `{{ .Alerts.Resolved | len }}`, } @@ -206,10 +206,21 @@ var ( NotifierConfig: NotifierConfig{ VSendResolved: true, }, - APIType: "auto", - Summary: `{{ template "jira.default.summary" . }}`, - Description: `{{ template "jira.default.description" . }}`, - Priority: `{{ template "jira.default.priority" . }}`, + APIType: "auto", + Summary: JiraFieldConfig{ + Template: `{{ template "jira.default.summary" . }}`, + }, + Description: JiraFieldConfig{ + Template: `{{ template "jira.default.description" . }}`, + }, + Priority: `{{ template "jira.default.priority" . }}`, + } + + DefaultMattermostConfig = MattermostConfig{ + NotifierConfig: NotifierConfig{ + VSendResolved: true, + }, + Text: `{{ template "mattermost.default.text" . }}`, } ) @@ -304,6 +315,13 @@ type EmailConfig struct { Text string `yaml:"text,omitempty" json:"text,omitempty"` RequireTLS *bool `yaml:"require_tls,omitempty" json:"require_tls,omitempty"` TLSConfig *commoncfg.TLSConfig `yaml:"tls_config,omitempty" json:"tls_config,omitempty"` + Threading ThreadingConfig `yaml:"threading,omitempty" json:"threading,omitempty"` +} + +// ThreadingConfig configures mail threading. +type ThreadingConfig struct { + Enabled bool `yaml:"enabled,omitempty" json:"enabled,omitempty"` + ThreadByDate string `yaml:"thread_by_date,omitempty" json:"thread_by_date,omitempty"` } // UnmarshalYAML implements the yaml.Unmarshaler interface. @@ -327,6 +345,15 @@ func (c *EmailConfig) UnmarshalYAML(unmarshal func(any) error) error { } c.Headers = normalizedHeaders + if c.Threading.Enabled { + if _, ok := normalizedHeaders["References"]; ok { + return errors.New("conflicting configuration: threading.enabled conflicts with custom References header") + } + if _, ok := normalizedHeaders["In-Reply-To"]; ok { + return errors.New("conflicting configuration: threading.enabled conflicts with custom In-Reply-To header") + } + } + return nil } @@ -336,22 +363,25 @@ type PagerdutyConfig struct { HTTPConfig *commoncfg.HTTPClientConfig `yaml:"http_config,omitempty" json:"http_config,omitempty"` - ServiceKey Secret `yaml:"service_key,omitempty" json:"service_key,omitempty"` - ServiceKeyFile string `yaml:"service_key_file,omitempty" json:"service_key_file,omitempty"` - RoutingKey Secret `yaml:"routing_key,omitempty" json:"routing_key,omitempty"` - RoutingKeyFile string `yaml:"routing_key_file,omitempty" json:"routing_key_file,omitempty"` - URL *URL `yaml:"url,omitempty" json:"url,omitempty"` - Client string `yaml:"client,omitempty" json:"client,omitempty"` - ClientURL string `yaml:"client_url,omitempty" json:"client_url,omitempty"` - Description string `yaml:"description,omitempty" json:"description,omitempty"` - Details map[string]string `yaml:"details,omitempty" json:"details,omitempty"` - Images []PagerdutyImage `yaml:"images,omitempty" json:"images,omitempty"` - Links []PagerdutyLink `yaml:"links,omitempty" json:"links,omitempty"` - Source string `yaml:"source,omitempty" json:"source,omitempty"` - Severity string `yaml:"severity,omitempty" json:"severity,omitempty"` - Class string `yaml:"class,omitempty" json:"class,omitempty"` - Component string `yaml:"component,omitempty" json:"component,omitempty"` - Group string `yaml:"group,omitempty" json:"group,omitempty"` + ServiceKey Secret `yaml:"service_key,omitempty" json:"service_key,omitempty"` + ServiceKeyFile string `yaml:"service_key_file,omitempty" json:"service_key_file,omitempty"` + RoutingKey Secret `yaml:"routing_key,omitempty" json:"routing_key,omitempty"` + RoutingKeyFile string `yaml:"routing_key_file,omitempty" json:"routing_key_file,omitempty"` + URL *URL `yaml:"url,omitempty" json:"url,omitempty"` + Client string `yaml:"client,omitempty" json:"client,omitempty"` + ClientURL string `yaml:"client_url,omitempty" json:"client_url,omitempty"` + Description string `yaml:"description,omitempty" json:"description,omitempty"` + Details map[string]any `yaml:"details,omitempty" json:"details,omitempty"` + Images []PagerdutyImage `yaml:"images,omitempty" json:"images,omitempty"` + Links []PagerdutyLink `yaml:"links,omitempty" json:"links,omitempty"` + Source string `yaml:"source,omitempty" json:"source,omitempty"` + Severity string `yaml:"severity,omitempty" json:"severity,omitempty"` + Class string `yaml:"class,omitempty" json:"class,omitempty"` + Component string `yaml:"component,omitempty" json:"component,omitempty"` + Group string `yaml:"group,omitempty" json:"group,omitempty"` + // Timeout is the maximum time allowed to invoke the pagerduty. Setting this to 0 + // does not impose a timeout. + Timeout time.Duration `yaml:"timeout" json:"timeout"` } // PagerdutyLink is a link. @@ -384,7 +414,7 @@ func (c *PagerdutyConfig) UnmarshalYAML(unmarshal func(any) error) error { return errors.New("at most one of service_key & service_key_file must be configured") } if c.Details == nil { - c.Details = make(map[string]string) + c.Details = make(map[string]any) } if c.Source == "" { c.Source = c.Client @@ -488,8 +518,11 @@ type SlackConfig struct { HTTPConfig *commoncfg.HTTPClientConfig `yaml:"http_config,omitempty" json:"http_config,omitempty"` - APIURL *SecretURL `yaml:"api_url,omitempty" json:"api_url,omitempty"` - APIURLFile string `yaml:"api_url_file,omitempty" json:"api_url_file,omitempty"` + APIURL *SecretURL `yaml:"api_url,omitempty" json:"api_url,omitempty"` + APIURLFile string `yaml:"api_url_file,omitempty" json:"api_url_file,omitempty"` + AppToken Secret `yaml:"app_token,omitempty" json:"app_token,omitempty"` + AppTokenFile string `yaml:"app_token_file,omitempty" json:"app_token_file,omitempty"` + AppURL *URL `yaml:"app_url,omitempty" json:"app_url,omitempty"` // Slack channel override, (like #other-channel or @username). Channel string `yaml:"channel,omitempty" json:"channel,omitempty"` @@ -512,6 +545,9 @@ type SlackConfig struct { LinkNames bool `yaml:"link_names" json:"link_names,omitempty"` MrkdwnIn []string `yaml:"mrkdwn_in,omitempty" json:"mrkdwn_in,omitempty"` Actions []*SlackAction `yaml:"actions,omitempty" json:"actions,omitempty"` + // Timeout is the maximum time allowed to invoke the slack. Setting this to 0 + // does not impose a timeout. + Timeout time.Duration `yaml:"timeout" json:"timeout"` } // UnmarshalYAML implements the yaml.Unmarshaler interface. @@ -525,6 +561,12 @@ func (c *SlackConfig) UnmarshalYAML(unmarshal func(any) error) error { if c.APIURL != nil && len(c.APIURLFile) > 0 { return errors.New("at most one of api_url & api_url_file must be configured") } + if c.AppToken != "" && len(c.AppTokenFile) > 0 { + return errors.New("at most one of app_token & app_token_file must be configured") + } + if (c.APIURL != nil || len(c.APIURLFile) > 0) && (c.AppToken != "" || len(c.AppTokenFile) > 0) { + return errors.New("at most one of api_url/api_url_file & app_token/app_token_file must be configured") + } return nil } @@ -556,7 +598,7 @@ type IncidentioConfig struct { } // UnmarshalYAML implements the yaml.Unmarshaler interface. -func (c *IncidentioConfig) UnmarshalYAML(unmarshal func(interface{}) error) error { +func (c *IncidentioConfig) UnmarshalYAML(unmarshal func(any) error) error { *c = DefaultIncidentioConfig type plain IncidentioConfig if err := unmarshal((*plain)(c)); err != nil { @@ -956,6 +998,13 @@ func (c *MSTeamsV2Config) UnmarshalYAML(unmarshal func(any) error) error { return nil } +type JiraFieldConfig struct { + // Template is the template string used to render the field. + Template string `yaml:"template,omitempty" json:"template,omitempty"` + // EnableUpdate indicates whether this field should be omitted when updating an existing issue. + EnableUpdate *bool `yaml:"enable_update,omitempty" json:"enable_update,omitempty"` +} + type JiraConfig struct { NotifierConfig `yaml:",inline" json:",inline"` HTTPConfig *commoncfg.HTTPClientConfig `yaml:"http_config,omitempty" json:"http_config,omitempty"` @@ -963,12 +1012,12 @@ type JiraConfig struct { APIURL *URL `yaml:"api_url,omitempty" json:"api_url,omitempty"` APIType string `yaml:"api_type,omitempty" json:"api_type,omitempty"` - Project string `yaml:"project,omitempty" json:"project,omitempty"` - Summary string `yaml:"summary,omitempty" json:"summary,omitempty"` - Description string `yaml:"description,omitempty" json:"description,omitempty"` - Labels []string `yaml:"labels,omitempty" json:"labels,omitempty"` - Priority string `yaml:"priority,omitempty" json:"priority,omitempty"` - IssueType string `yaml:"issue_type,omitempty" json:"issue_type,omitempty"` + Project string `yaml:"project,omitempty" json:"project,omitempty"` + Summary JiraFieldConfig `yaml:"summary,omitempty" json:"summary,omitempty"` + Description JiraFieldConfig `yaml:"description,omitempty" json:"description,omitempty"` + Labels []string `yaml:"labels,omitempty" json:"labels,omitempty"` + Priority string `yaml:"priority,omitempty" json:"priority,omitempty"` + IssueType string `yaml:"issue_type,omitempty" json:"issue_type,omitempty"` ReopenTransition string `yaml:"reopen_transition,omitempty" json:"reopen_transition,omitempty"` ResolveTransition string `yaml:"resolve_transition,omitempty" json:"resolve_transition,omitempty"` @@ -978,6 +1027,28 @@ type JiraConfig struct { Fields map[string]any `yaml:"fields,omitempty" json:"custom_fields,omitempty"` } +func (f *JiraFieldConfig) EnableUpdateValue() bool { + if f.EnableUpdate == nil { + return true + } + return *f.EnableUpdate +} + +// Supports both the legacy string and the new object form. +func (f *JiraFieldConfig) UnmarshalYAML(unmarshal func(any) error) error { + // Try simple string first (backward compatibility). + var s string + if err := unmarshal(&s); err == nil { + f.Template = s + // DisableUpdate stays false by default. + return nil + } + + // Fallback to full object form. + type plain JiraFieldConfig + return unmarshal((*plain)(f)) +} + func (c *JiraConfig) UnmarshalYAML(unmarshal func(any) error) error { *c = DefaultJiraConfig type plain JiraConfig @@ -1066,3 +1137,98 @@ func (c *RocketchatConfig) UnmarshalYAML(unmarshal func(any) error) error { } return nil } + +// MattermostPriority defines the priority for a mattermost notification. +type MattermostPriority struct { + Priority string `yaml:"priority,omitempty" json:"priority,omitempty"` + RequestedAck bool `yaml:"requested_ack,omitempty" json:"requested_ack,omitempty"` + PersistentNotifications bool `yaml:"persistent_notifications,omitempty" json:"persistent_notifications,omitempty"` +} + +// MattermostProps defines additional properties for a mattermost notification. +// Only 'card' property takes effect now. +type MattermostProps struct { + Card string `yaml:"card,omitempty" json:"card,omitempty"` +} + +// MattermostField configures a single Mattermost field for Slack compatibility. +// See https://developers.mattermost.com/integrate/reference/message-attachments/#fields for more information. +type MattermostField struct { + Title string `yaml:"title,omitempty" json:"title,omitempty"` + Value string `yaml:"value,omitempty" json:"value,omitempty"` + Short *bool `yaml:"short,omitempty" json:"short,omitempty"` +} + +// UnmarshalYAML implements the yaml.Unmarshaler interface for MattermostField. +func (c *MattermostField) UnmarshalYAML(unmarshal func(any) error) error { + type plain MattermostField + if err := unmarshal((*plain)(c)); err != nil { + return err + } + if c.Title == "" { + return errors.New("missing title in Mattermost field configuration") + } + if c.Value == "" { + return errors.New("missing value in Mattermost field configuration") + } + return nil +} + +// MattermostAttachment defines an attachment for a Mattermost notification. +// See https://developers.mattermost.com/integrate/reference/message-attachments/#fields for more information. +type MattermostAttachment struct { + Fallback string `yaml:"fallback,omitempty" json:"fallback,omitempty"` + Color string `yaml:"color,omitempty" json:"color,omitempty"` + Pretext string `yaml:"pretext,omitempty" json:"pretext,omitempty"` + Text string `yaml:"text,omitempty" json:"text,omitempty"` + AuthorName string `yaml:"author_name,omitempty" json:"author_name,omitempty"` + AuthorLink string `yaml:"author_link,omitempty" json:"author_link,omitempty"` + AuthorIcon string `yaml:"author_icon,omitempty" json:"author_icon,omitempty"` + Title string `yaml:"title,omitempty" json:"title,omitempty"` + TitleLink string `yaml:"title_link,omitempty" json:"title_link,omitempty"` + Fields []*MattermostField `yaml:"fields,omitempty" json:"fields,omitempty"` + ThumbURL string `yaml:"thumb_url,omitempty" json:"thumb_url,omitempty"` + Footer string `yaml:"footer,omitempty" json:"footer,omitempty"` + FooterIcon string `yaml:"footer_icon,omitempty" json:"footer_icon,omitempty"` + ImageURL string `yaml:"image_url,omitempty" json:"image_url,omitempty"` +} + +// MattermostConfig configures notifications via Mattermost. +// See https://developers.mattermost.com/integrate/webhooks/incoming/ for more information. +type MattermostConfig struct { + NotifierConfig `yaml:",inline" json:",inline"` + + HTTPConfig *commoncfg.HTTPClientConfig `yaml:"http_config,omitempty" json:"http_config,omitempty"` + WebhookURL *SecretURL `yaml:"webhook_url,omitempty" json:"webhook_url,omitempty"` + WebhookURLFile string `yaml:"webhook_url_file,omitempty" json:"webhook_url_file,omitempty"` + + Channel string `yaml:"channel,omitempty" json:"channel,omitempty"` + Username string `yaml:"username,omitempty" json:"username,omitempty"` + + Text string `yaml:"text,omitempty" json:"text,omitempty"` + IconURL string `yaml:"icon_url,omitempty" json:"icon_url,omitempty"` + IconEmoji string `yaml:"icon_emoji,omitempty" json:"icon_emoji,omitempty"` + Attachments []*MattermostAttachment `yaml:"attachments,omitempty" json:"attachments,omitempty"` + Type string `yaml:"type,omitempty" json:"type,omitempty"` + Props *MattermostProps `yaml:"props,omitempty" json:"props,omitempty"` + Priority *MattermostPriority `yaml:"priority,omitempty" json:"priority,omitempty"` +} + +// UnmarshalYAML implements the yaml.Unmarshaler interface. +func (c *MattermostConfig) UnmarshalYAML(unmarshal func(any) error) error { + *c = DefaultMattermostConfig + type plain MattermostConfig + if err := unmarshal((*plain)(c)); err != nil { + return err + } + + if c.WebhookURL == nil && c.WebhookURLFile == "" { + return errors.New("one of webhook_url or webhook_url_file must be configured") + } + + if c.WebhookURL != nil && len(c.WebhookURLFile) > 0 { + return errors.New("at most one of webhook_url & webhook_url_file must be configured") + } + + return nil +} diff --git a/vendor/github.com/prometheus/alertmanager/config/tracing.go b/vendor/github.com/prometheus/alertmanager/config/tracing.go new file mode 100644 index 00000000000..b88d926070f --- /dev/null +++ b/vendor/github.com/prometheus/alertmanager/config/tracing.go @@ -0,0 +1,92 @@ +// Copyright The Prometheus Authors +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package config + +import ( + "errors" + "fmt" + + commoncfg "github.com/prometheus/common/config" + "github.com/prometheus/common/model" +) + +// TODO: probably move these into prometheus/common since they're copied from +// prometheus/prometheus? + +type TracingClientType string + +const ( + TracingClientHTTP TracingClientType = "http" + TracingClientGRPC TracingClientType = "grpc" + + GzipCompression = "gzip" +) + +// UnmarshalYAML implements the yaml.Unmarshaler interface. +func (t *TracingClientType) UnmarshalYAML(unmarshal func(any) error) error { + *t = TracingClientType("") + type plain TracingClientType + if err := unmarshal((*plain)(t)); err != nil { + return err + } + + switch *t { + case TracingClientHTTP, TracingClientGRPC: + return nil + default: + return fmt.Errorf("expected tracing client type to be to be %s or %s, but got %s", + TracingClientHTTP, TracingClientGRPC, *t, + ) + } +} + +// TracingConfig configures the tracing options. +type TracingConfig struct { + ClientType TracingClientType `yaml:"client_type,omitempty"` + Endpoint string `yaml:"endpoint,omitempty"` + SamplingFraction float64 `yaml:"sampling_fraction,omitempty"` + Insecure bool `yaml:"insecure,omitempty"` + TLSConfig *commoncfg.TLSConfig `yaml:"tls_config,omitempty"` + Headers *commoncfg.Headers `yaml:"headers,omitempty"` + Compression string `yaml:"compression,omitempty"` + Timeout model.Duration `yaml:"timeout,omitempty"` +} + +// SetDirectory joins any relative file paths with dir. +func (t *TracingConfig) SetDirectory(dir string) { + t.TLSConfig.SetDirectory(dir) + t.Headers.SetDirectory(dir) +} + +// UnmarshalYAML implements the yaml.Unmarshaler interface. +func (t *TracingConfig) UnmarshalYAML(unmarshal func(any) error) error { + *t = TracingConfig{ + ClientType: TracingClientGRPC, + } + type plain TracingConfig + if err := unmarshal((*plain)(t)); err != nil { + return err + } + + if t.Endpoint == "" { + return errors.New("tracing endpoint must be set") + } + + if t.Compression != "" && t.Compression != GzipCompression { + return fmt.Errorf("invalid compression type %s provided, valid options: %s", + t.Compression, GzipCompression) + } + + return nil +} diff --git a/vendor/github.com/prometheus/alertmanager/featurecontrol/featurecontrol.go b/vendor/github.com/prometheus/alertmanager/featurecontrol/featurecontrol.go index d6da3ac88f2..b4b7cf4735c 100644 --- a/vendor/github.com/prometheus/alertmanager/featurecontrol/featurecontrol.go +++ b/vendor/github.com/prometheus/alertmanager/featurecontrol/featurecontrol.go @@ -113,7 +113,7 @@ func NewFlags(logger *slog.Logger, features string) (Flagger, error) { return NoopFlags{}, nil } - for _, feature := range strings.Split(features, ",") { + for feature := range strings.SplitSeq(features, ",") { switch feature { case FeatureReceiverNameInMetrics: opts = append(opts, enableReceiverNameInMetrics()) diff --git a/vendor/github.com/prometheus/alertmanager/matcher/parse/token.go b/vendor/github.com/prometheus/alertmanager/matcher/parse/token.go index 96baeeef43b..3e73fb8536a 100644 --- a/vendor/github.com/prometheus/alertmanager/matcher/parse/token.go +++ b/vendor/github.com/prometheus/alertmanager/matcher/parse/token.go @@ -16,6 +16,7 @@ package parse import ( "errors" "fmt" + "slices" "strconv" "unicode/utf8" ) @@ -73,12 +74,7 @@ func (t token) isEOF() bool { // isOneOf returns true if the token is one of the specified kinds. func (t token) isOneOf(kinds ...tokenKind) bool { - for _, k := range kinds { - if k == t.kind { - return true - } - } - return false + return slices.Contains(kinds, t.kind) } // unquote the value in token. If unquoted returns it unmodified. diff --git a/vendor/github.com/prometheus/alertmanager/pkg/labels/parse.go b/vendor/github.com/prometheus/alertmanager/pkg/labels/parse.go index f84b29e84b1..13360174c90 100644 --- a/vendor/github.com/prometheus/alertmanager/pkg/labels/parse.go +++ b/vendor/github.com/prometheus/alertmanager/pkg/labels/parse.go @@ -127,8 +127,8 @@ func ParseMatcher(s string) (_ *Matcher, err error) { expectTrailingQuote bool ) - if strings.HasPrefix(rawValue, "\"") { - rawValue = strings.TrimPrefix(rawValue, "\"") + if after, ok := strings.CutPrefix(rawValue, "\""); ok { + rawValue = after expectTrailingQuote = true } diff --git a/vendor/github.com/prometheus/common/config/http_config.go b/vendor/github.com/prometheus/common/config/http_config.go index bc906bc6599..55cc5b0770c 100644 --- a/vendor/github.com/prometheus/common/config/http_config.go +++ b/vendor/github.com/prometheus/common/config/http_config.go @@ -136,7 +136,7 @@ func (tv *TLSVersion) String() string { // BasicAuth contains basic HTTP authentication credentials. type BasicAuth struct { - Username string `yaml:"username" json:"username"` + Username string `yaml:"username,omitempty" json:"username,omitempty"` UsernameFile string `yaml:"username_file,omitempty" json:"username_file,omitempty"` // UsernameRef is the name of the secret within the secret manager to use as the username. UsernameRef string `yaml:"username_ref,omitempty" json:"username_ref,omitempty"` @@ -238,22 +238,22 @@ func (u URL) MarshalJSON() ([]byte, error) { // OAuth2 is the oauth2 client configuration. type OAuth2 struct { - ClientID string `yaml:"client_id" json:"client_id"` - ClientSecret Secret `yaml:"client_secret" json:"client_secret"` - ClientSecretFile string `yaml:"client_secret_file" json:"client_secret_file"` + ClientID string `yaml:"client_id,omitempty" json:"client_id,omitempty"` + ClientSecret Secret `yaml:"client_secret,omitempty" json:"client_secret,omitempty"` + ClientSecretFile string `yaml:"client_secret_file,omitempty" json:"client_secret_file,omitempty"` // ClientSecretRef is the name of the secret within the secret manager to use as the client // secret. - ClientSecretRef string `yaml:"client_secret_ref" json:"client_secret_ref"` - ClientCertificateKeyID string `yaml:"client_certificate_key_id" json:"client_certificate_key_id"` - ClientCertificateKey Secret `yaml:"client_certificate_key" json:"client_certificate_key"` - ClientCertificateKeyFile string `yaml:"client_certificate_key_file" json:"client_certificate_key_file"` + ClientSecretRef string `yaml:"client_secret_ref,omitempty" json:"client_secret_ref,omitempty"` + ClientCertificateKeyID string `yaml:"client_certificate_key_id,omitempty" json:"client_certificate_key_id,omitempty"` + ClientCertificateKey Secret `yaml:"client_certificate_key,omitempty" json:"client_certificate_key,omitempty"` + ClientCertificateKeyFile string `yaml:"client_certificate_key_file,omitempty" json:"client_certificate_key_file,omitempty"` // ClientCertificateKeyRef is the name of the secret within the secret manager to use as the client // secret. - ClientCertificateKeyRef string `yaml:"client_certificate_key_ref" json:"client_certificate_key_ref"` + ClientCertificateKeyRef string `yaml:"client_certificate_key_ref,omitempty" json:"client_certificate_key_ref,omitempty"` // GrantType is the OAuth2 grant type to use. It can be one of // "client_credentials" or "urn:ietf:params:oauth:grant-type:jwt-bearer" (RFC 7523). // Default value is "client_credentials" - GrantType string `yaml:"grant_type" json:"grant_type"` + GrantType string `yaml:"grant_type,omitempty" json:"grant_type,omitempty"` // SignatureAlgorithm is the RSA algorithm used to sign JWT token. Only used if // GrantType is set to "urn:ietf:params:oauth:grant-type:jwt-bearer". // Default value is RS256 and valid values RS256, RS384, RS512 @@ -271,7 +271,7 @@ type OAuth2 struct { // GrantType is set to "urn:ietf:params:oauth:grant-type:jwt-bearer". Claims map[string]interface{} `yaml:"claims,omitempty" json:"claims,omitempty"` Scopes []string `yaml:"scopes,omitempty" json:"scopes,omitempty"` - TokenURL string `yaml:"token_url" json:"token_url"` + TokenURL string `yaml:"token_url,omitempty" json:"token_url,omitempty"` EndpointParams map[string]string `yaml:"endpoint_params,omitempty" json:"endpoint_params,omitempty"` TLSConfig TLSConfig `yaml:"tls_config,omitempty"` ProxyConfig `yaml:",inline"` diff --git a/vendor/github.com/prometheus/common/expfmt/expfmt.go b/vendor/github.com/prometheus/common/expfmt/expfmt.go index c34c7de432b..4e4c13e724c 100644 --- a/vendor/github.com/prometheus/common/expfmt/expfmt.go +++ b/vendor/github.com/prometheus/common/expfmt/expfmt.go @@ -45,6 +45,7 @@ const ( // The Content-Type values for the different wire protocols. Do not do direct // comparisons to these constants, instead use the comparison functions. + // // Deprecated: Use expfmt.NewFormat(expfmt.TypeUnknown) instead. FmtUnknown Format = `` // Deprecated: Use expfmt.NewFormat(expfmt.TypeTextPlain) instead. diff --git a/vendor/github.com/prometheus/common/expfmt/fuzz.go b/vendor/github.com/prometheus/common/expfmt/fuzz.go index 0290f6abc40..872c0c15b40 100644 --- a/vendor/github.com/prometheus/common/expfmt/fuzz.go +++ b/vendor/github.com/prometheus/common/expfmt/fuzz.go @@ -13,7 +13,6 @@ // Build only when actually fuzzing //go:build gofuzz -// +build gofuzz package expfmt diff --git a/vendor/github.com/prometheus/prometheus/NOTICE b/vendor/github.com/prometheus/prometheus/NOTICE index 8605c258e32..b2fcf4deb4c 100644 --- a/vendor/github.com/prometheus/prometheus/NOTICE +++ b/vendor/github.com/prometheus/prometheus/NOTICE @@ -101,6 +101,11 @@ https://github.com/microsoft/vscode-codicons Copyright (c) Microsoft Corporation and other contributors See https://github.com/microsoft/vscode-codicons/blob/main/LICENSE for license details. +Mantine UI +https://github.com/mantinedev/mantine +Copyright (c) 2021 Vitaly Rtishchev +See https://github.com/mantinedev/mantine/blob/master/LICENSE for license details. + We also use code from a large number of npm packages. For details, see: - https://github.com/prometheus/prometheus/blob/main/web/ui/react-app/package.json - https://github.com/prometheus/prometheus/blob/main/web/ui/react-app/package-lock.json diff --git a/vendor/github.com/prometheus/prometheus/model/histogram/convert.go b/vendor/github.com/prometheus/prometheus/model/histogram/convert.go new file mode 100644 index 00000000000..218fbe197e9 --- /dev/null +++ b/vendor/github.com/prometheus/prometheus/model/histogram/convert.go @@ -0,0 +1,145 @@ +// Copyright The Prometheus Authors +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package histogram + +import ( + "errors" + "fmt" + "math" + + "github.com/prometheus/common/model" + + "github.com/prometheus/prometheus/model/labels" +) + +// ConvertNHCBToClassic converts Native Histogram Custom Buckets (NHCB) to classic histogram series. +// This conversion is needed in various scenarios where users need to get NHCB back to classic histogram format, +// such as Remote Write v1 for external system compatibility and migration use cases. +// +// When calling this function, caller must ensure that provided nhcb is valid NHCB histogram. +func ConvertNHCBToClassic(nhcb any, lset labels.Labels, lsetBuilder *labels.Builder, emitSeriesFn func(labels labels.Labels, value float64) error) error { + baseName := lset.Get(model.MetricNameLabel) + if baseName == "" { + return errors.New("metric name label '__name__' is missing") + } + + // We preserve original labels and restore them after conversion. + // This is to ensure that no modifications are made to the original labels + // that the queue_manager relies on. + oldLabels := lsetBuilder.Labels() + defer lsetBuilder.Reset(oldLabels) + + var ( + customValues []float64 + positiveBuckets []float64 + count, sum float64 + idx int // This index is to track buckets in Classic Histogram + currIdx int // This index is to track buckets in Native Histogram + ) + + switch h := nhcb.(type) { + case *Histogram: + if !IsCustomBucketsSchema(h.Schema) { + return errors.New("unsupported histogram schema, not a NHCB") + } + + // Validate the histogram before conversion. + // The caller must ensure that the provided histogram is valid NHCB. + if h.Validate() != nil { + return errors.New(h.Validate().Error()) + } + + customValues = h.CustomValues + positiveBuckets = make([]float64, len(customValues)+1) + + // Histograms are in delta format so we first bring them to absolute format. + acc := int64(0) + for _, s := range h.PositiveSpans { + for i := 0; i < int(s.Offset); i++ { + positiveBuckets[idx] = float64(acc) + idx++ + } + for i := 0; i < int(s.Length); i++ { + acc += h.PositiveBuckets[currIdx] + positiveBuckets[idx] = float64(acc) + idx++ + currIdx++ + } + } + count = float64(h.Count) + sum = h.Sum + case *FloatHistogram: + if !IsCustomBucketsSchema(h.Schema) { + return errors.New("unsupported histogram schema, not a NHCB") + } + + // Validate the histogram before conversion. + // The caller must ensure that the provided histogram is valid NHCB. + if h.Validate() != nil { + return errors.New(h.Validate().Error()) + } + customValues = h.CustomValues + positiveBuckets = make([]float64, len(customValues)+1) + + for _, span := range h.PositiveSpans { + // Since Float Histogram is already in absolute format we should + // keep the sparse buckets empty so we jump and go to next filled + // bucket index. + idx += int(span.Offset) + for i := 0; i < int(span.Length); i++ { + positiveBuckets[idx] = h.PositiveBuckets[currIdx] + idx++ + currIdx++ + } + } + count = h.Count + sum = h.Sum + default: + return fmt.Errorf("unsupported histogram type: %T", h) + } + + currCount := float64(0) + for i, val := range customValues { + currCount += positiveBuckets[i] + lsetBuilder.Reset(lset) + lsetBuilder.Set(model.MetricNameLabel, baseName+"_bucket") + lsetBuilder.Set(model.BucketLabel, labels.FormatOpenMetricsFloat(val)) + if err := emitSeriesFn(lsetBuilder.Labels(), currCount); err != nil { + return err + } + } + + currCount += positiveBuckets[len(positiveBuckets)-1] + + lsetBuilder.Reset(lset) + lsetBuilder.Set(model.MetricNameLabel, baseName+"_bucket") + lsetBuilder.Set(model.BucketLabel, labels.FormatOpenMetricsFloat(math.Inf(1))) + if err := emitSeriesFn(lsetBuilder.Labels(), currCount); err != nil { + return err + } + + lsetBuilder.Reset(lset) + lsetBuilder.Set(model.MetricNameLabel, baseName+"_count") + if err := emitSeriesFn(lsetBuilder.Labels(), count); err != nil { + return err + } + + lsetBuilder.Reset(lset) + lsetBuilder.Set(model.MetricNameLabel, baseName+"_sum") + if err := emitSeriesFn(lsetBuilder.Labels(), sum); err != nil { + return err + } + + return nil +} diff --git a/vendor/github.com/prometheus/prometheus/model/histogram/float_histogram.go b/vendor/github.com/prometheus/prometheus/model/histogram/float_histogram.go index 0f89ec38fa2..91fcac1cfbf 100644 --- a/vendor/github.com/prometheus/prometheus/model/histogram/float_histogram.go +++ b/vendor/github.com/prometheus/prometheus/model/histogram/float_histogram.go @@ -164,8 +164,8 @@ func (h *FloatHistogram) CopyToSchema(targetSchema int32) *FloatHistogram { Sum: h.Sum, } - c.PositiveSpans, c.PositiveBuckets = reduceResolution(h.PositiveSpans, h.PositiveBuckets, h.Schema, targetSchema, false, false) - c.NegativeSpans, c.NegativeBuckets = reduceResolution(h.NegativeSpans, h.NegativeBuckets, h.Schema, targetSchema, false, false) + c.PositiveSpans, c.PositiveBuckets = mustReduceResolution(h.PositiveSpans, h.PositiveBuckets, h.Schema, targetSchema, false, false) + c.NegativeSpans, c.NegativeBuckets = mustReduceResolution(h.NegativeSpans, h.NegativeBuckets, h.Schema, targetSchema, false, false) return &c } @@ -283,7 +283,8 @@ func (h *FloatHistogram) ZeroBucket() Bucket[float64] { // bucket counts including the zero bucket and the count and the sum of // observations. The bucket layout stays the same. This method changes the // receiving histogram directly (rather than acting on a copy). It returns a -// pointer to the receiving histogram for convenience. +// pointer to the receiving histogram for convenience. If factor is negative, +// the counter reset hint is set to GaugeType. func (h *FloatHistogram) Mul(factor float64) *FloatHistogram { h.ZeroCount *= factor h.Count *= factor @@ -301,7 +302,8 @@ func (h *FloatHistogram) Mul(factor float64) *FloatHistogram { } // Div works like Mul but divides instead of multiplies. -// When dividing by 0, everything will be set to Inf. +// When dividing by 0, everything will be set to Inf. If scalar is negative, +// the counter reset hint is set to GaugeType. func (h *FloatHistogram) Div(scalar float64) *FloatHistogram { h.ZeroCount /= scalar h.Count /= scalar @@ -341,39 +343,15 @@ func (h *FloatHistogram) Div(scalar float64) *FloatHistogram { // is returned as true. A counter reset conflict occurs iff one of two histograms indicate // a counter reset (CounterReset) while the other indicates no reset (NotCounterReset). // +// In case of mismatched NHCB bounds, they will be reconciled to the intersection of +// both histograms, and nhcbBoundsReconciled will be returned as true. +// // This method returns a pointer to the receiving histogram for convenience. -func (h *FloatHistogram) Add(other *FloatHistogram) (res *FloatHistogram, counterResetCollision bool, err error) { - if h.UsesCustomBuckets() != other.UsesCustomBuckets() { - return nil, false, ErrHistogramsIncompatibleSchema - } - if h.UsesCustomBuckets() && !FloatBucketsMatch(h.CustomValues, other.CustomValues) { - return nil, false, ErrHistogramsIncompatibleBounds - } - - switch { - case other.CounterResetHint == h.CounterResetHint: - // Adding apples to apples, all good. No need to change anything. - case h.CounterResetHint == GaugeType: - // Adding something else to a gauge. That's probably OK. Outcome is a gauge. - // Nothing to do since the receiver is already marked as gauge. - case other.CounterResetHint == GaugeType: - // Similar to before, but this time the receiver is "something else" and we have to change it to gauge. - h.CounterResetHint = GaugeType - case h.CounterResetHint == UnknownCounterReset: - // With the receiver's CounterResetHint being "unknown", this could still be legitimate - // if the caller knows what they are doing. Outcome is then again "unknown". - // No need to do anything since the receiver's CounterResetHint is already "unknown". - case other.CounterResetHint == UnknownCounterReset: - // Similar to before, but now we have to set the receiver's CounterResetHint to "unknown". - h.CounterResetHint = UnknownCounterReset - default: - // All other cases shouldn't actually happen. - // They are a direct collision of CounterReset and NotCounterReset. - // Conservatively set the CounterResetHint to "unknown" and issue a warning. - h.CounterResetHint = UnknownCounterReset - counterResetCollision = true +func (h *FloatHistogram) Add(other *FloatHistogram) (res *FloatHistogram, counterResetCollision, nhcbBoundsReconciled bool, err error) { + if err := h.checkSchemaAndBounds(other); err != nil { + return nil, false, false, err } - + counterResetCollision = h.adjustCounterReset(other) if !h.UsesCustomBuckets() { otherZeroCount := h.reconcileZeroBuckets(other) h.ZeroCount += otherZeroCount @@ -389,8 +367,21 @@ func (h *FloatHistogram) Add(other *FloatHistogram) (res *FloatHistogram, counte ) if h.UsesCustomBuckets() { - h.PositiveSpans, h.PositiveBuckets = addBuckets(h.Schema, h.ZeroThreshold, false, hPositiveSpans, hPositiveBuckets, otherPositiveSpans, otherPositiveBuckets) - return h, counterResetCollision, nil + if CustomBucketBoundsMatch(h.CustomValues, other.CustomValues) { + h.PositiveSpans, h.PositiveBuckets = addBuckets(h.Schema, h.ZeroThreshold, false, hPositiveSpans, hPositiveBuckets, otherPositiveSpans, otherPositiveBuckets) + } else { + nhcbBoundsReconciled = true + intersectedBounds := intersectCustomBucketBounds(h.CustomValues, other.CustomValues) + + // Add with mapping - maps both histograms to intersected layout. + h.PositiveSpans, h.PositiveBuckets = addCustomBucketsWithMismatches( + false, + hPositiveSpans, hPositiveBuckets, h.CustomValues, + otherPositiveSpans, otherPositiveBuckets, other.CustomValues, + intersectedBounds) + h.CustomValues = intersectedBounds + } + return h, counterResetCollision, nhcbBoundsReconciled, nil } var ( @@ -402,34 +393,31 @@ func (h *FloatHistogram) Add(other *FloatHistogram) (res *FloatHistogram, counte switch { case other.Schema < h.Schema: - hPositiveSpans, hPositiveBuckets = reduceResolution(hPositiveSpans, hPositiveBuckets, h.Schema, other.Schema, false, true) - hNegativeSpans, hNegativeBuckets = reduceResolution(hNegativeSpans, hNegativeBuckets, h.Schema, other.Schema, false, true) + hPositiveSpans, hPositiveBuckets = mustReduceResolution(hPositiveSpans, hPositiveBuckets, h.Schema, other.Schema, false, true) + hNegativeSpans, hNegativeBuckets = mustReduceResolution(hNegativeSpans, hNegativeBuckets, h.Schema, other.Schema, false, true) h.Schema = other.Schema case other.Schema > h.Schema: - otherPositiveSpans, otherPositiveBuckets = reduceResolution(otherPositiveSpans, otherPositiveBuckets, other.Schema, h.Schema, false, false) - otherNegativeSpans, otherNegativeBuckets = reduceResolution(otherNegativeSpans, otherNegativeBuckets, other.Schema, h.Schema, false, false) + otherPositiveSpans, otherPositiveBuckets = mustReduceResolution(otherPositiveSpans, otherPositiveBuckets, other.Schema, h.Schema, false, false) + otherNegativeSpans, otherNegativeBuckets = mustReduceResolution(otherNegativeSpans, otherNegativeBuckets, other.Schema, h.Schema, false, false) } h.PositiveSpans, h.PositiveBuckets = addBuckets(h.Schema, h.ZeroThreshold, false, hPositiveSpans, hPositiveBuckets, otherPositiveSpans, otherPositiveBuckets) h.NegativeSpans, h.NegativeBuckets = addBuckets(h.Schema, h.ZeroThreshold, false, hNegativeSpans, hNegativeBuckets, otherNegativeSpans, otherNegativeBuckets) - return h, counterResetCollision, nil + return h, counterResetCollision, nhcbBoundsReconciled, nil } -// Sub works like Add but subtracts the other histogram. -func (h *FloatHistogram) Sub(other *FloatHistogram) (res *FloatHistogram, counterResetCollision bool, err error) { - if h.UsesCustomBuckets() != other.UsesCustomBuckets() { - return nil, false, ErrHistogramsIncompatibleSchema - } - if h.UsesCustomBuckets() && !FloatBucketsMatch(h.CustomValues, other.CustomValues) { - return nil, false, ErrHistogramsIncompatibleBounds +// Sub works like Add but subtracts the other histogram. It uses the same logic +// to adjust the counter reset hint. This is useful where this method is used +// for incremental mean calculation. However, if it is used for the actual "-" +// operator in PromQL, the counter reset needs to be set to GaugeType after +// calling this method. +func (h *FloatHistogram) Sub(other *FloatHistogram) (res *FloatHistogram, counterResetCollision, nhcbBoundsReconciled bool, err error) { + if err := h.checkSchemaAndBounds(other); err != nil { + return nil, false, false, err } - - counterResetCollision = hasCounterResetCollision(h, other) - - h.CounterResetHint = GaugeType - + counterResetCollision = h.adjustCounterReset(other) if !h.UsesCustomBuckets() { otherZeroCount := h.reconcileZeroBuckets(other) h.ZeroCount -= otherZeroCount @@ -445,8 +433,21 @@ func (h *FloatHistogram) Sub(other *FloatHistogram) (res *FloatHistogram, counte ) if h.UsesCustomBuckets() { - h.PositiveSpans, h.PositiveBuckets = addBuckets(h.Schema, h.ZeroThreshold, true, hPositiveSpans, hPositiveBuckets, otherPositiveSpans, otherPositiveBuckets) - return h, counterResetCollision, nil + if CustomBucketBoundsMatch(h.CustomValues, other.CustomValues) { + h.PositiveSpans, h.PositiveBuckets = addBuckets(h.Schema, h.ZeroThreshold, true, hPositiveSpans, hPositiveBuckets, otherPositiveSpans, otherPositiveBuckets) + } else { + nhcbBoundsReconciled = true + intersectedBounds := intersectCustomBucketBounds(h.CustomValues, other.CustomValues) + + // Subtract with mapping - maps both histograms to intersected layout. + h.PositiveSpans, h.PositiveBuckets = addCustomBucketsWithMismatches( + true, + hPositiveSpans, hPositiveBuckets, h.CustomValues, + otherPositiveSpans, otherPositiveBuckets, other.CustomValues, + intersectedBounds) + h.CustomValues = intersectedBounds + } + return h, counterResetCollision, nhcbBoundsReconciled, nil } var ( @@ -458,25 +459,18 @@ func (h *FloatHistogram) Sub(other *FloatHistogram) (res *FloatHistogram, counte switch { case other.Schema < h.Schema: - hPositiveSpans, hPositiveBuckets = reduceResolution(hPositiveSpans, hPositiveBuckets, h.Schema, other.Schema, false, true) - hNegativeSpans, hNegativeBuckets = reduceResolution(hNegativeSpans, hNegativeBuckets, h.Schema, other.Schema, false, true) + hPositiveSpans, hPositiveBuckets = mustReduceResolution(hPositiveSpans, hPositiveBuckets, h.Schema, other.Schema, false, true) + hNegativeSpans, hNegativeBuckets = mustReduceResolution(hNegativeSpans, hNegativeBuckets, h.Schema, other.Schema, false, true) h.Schema = other.Schema case other.Schema > h.Schema: - otherPositiveSpans, otherPositiveBuckets = reduceResolution(otherPositiveSpans, otherPositiveBuckets, other.Schema, h.Schema, false, false) - otherNegativeSpans, otherNegativeBuckets = reduceResolution(otherNegativeSpans, otherNegativeBuckets, other.Schema, h.Schema, false, false) + otherPositiveSpans, otherPositiveBuckets = mustReduceResolution(otherPositiveSpans, otherPositiveBuckets, other.Schema, h.Schema, false, false) + otherNegativeSpans, otherNegativeBuckets = mustReduceResolution(otherNegativeSpans, otherNegativeBuckets, other.Schema, h.Schema, false, false) } h.PositiveSpans, h.PositiveBuckets = addBuckets(h.Schema, h.ZeroThreshold, true, hPositiveSpans, hPositiveBuckets, otherPositiveSpans, otherPositiveBuckets) h.NegativeSpans, h.NegativeBuckets = addBuckets(h.Schema, h.ZeroThreshold, true, hNegativeSpans, hNegativeBuckets, otherNegativeSpans, otherNegativeBuckets) - return h, counterResetCollision, nil -} - -// hasCounterResetCollision returns true iff one of two histogram indicates -// a counter reset (CounterReset) while the other indicates no reset (NotCounterReset). -func hasCounterResetCollision(a, b *FloatHistogram) bool { - return a.CounterResetHint == CounterReset && b.CounterResetHint == NotCounterReset || - a.CounterResetHint == NotCounterReset && b.CounterResetHint == CounterReset + return h, counterResetCollision, nhcbBoundsReconciled, nil } // Equals returns true if the given float histogram matches exactly. @@ -500,7 +494,7 @@ func (h *FloatHistogram) Equals(h2 *FloatHistogram) bool { } if h.UsesCustomBuckets() { - if !FloatBucketsMatch(h.CustomValues, h2.CustomValues) { + if !CustomBucketBoundsMatch(h.CustomValues, h2.CustomValues) { return false } } @@ -513,14 +507,14 @@ func (h *FloatHistogram) Equals(h2 *FloatHistogram) bool { if !spansMatch(h.NegativeSpans, h2.NegativeSpans) { return false } - if !FloatBucketsMatch(h.NegativeBuckets, h2.NegativeBuckets) { + if !floatBucketsMatch(h.NegativeBuckets, h2.NegativeBuckets) { return false } if !spansMatch(h.PositiveSpans, h2.PositiveSpans) { return false } - if !FloatBucketsMatch(h.PositiveBuckets, h2.PositiveBuckets) { + if !floatBucketsMatch(h.PositiveBuckets, h2.PositiveBuckets) { return false } @@ -639,11 +633,17 @@ func (h *FloatHistogram) DetectReset(previous *FloatHistogram) bool { if h.Count < previous.Count { return true } - if h.UsesCustomBuckets() != previous.UsesCustomBuckets() || (h.UsesCustomBuckets() && !FloatBucketsMatch(h.CustomValues, previous.CustomValues)) { - // Mark that something has changed or that the application has been restarted. However, this does - // not matter so much since the change in schema will be handled directly in the chunks and PromQL - // functions. - return true + if h.UsesCustomBuckets() { + if !previous.UsesCustomBuckets() { + // Mark that something has changed or that the application has been restarted. However, this does + // not matter so much since the change in schema will be handled directly in the chunks and PromQL + // functions. + return true + } + if !CustomBucketBoundsMatch(h.CustomValues, previous.CustomValues) { + // Custom bounds don't match - check if any reconciled bucket value has decreased. + return h.detectResetWithMismatchedCustomBounds(previous, h.CustomValues, previous.CustomValues) + } } if h.Schema > previous.Schema { return true @@ -826,12 +826,18 @@ func (h *FloatHistogram) Validate() error { if err != nil { return fmt.Errorf("negative side: %w", err) } + if h.ZeroCount < 0 { + return fmt.Errorf("zero bucket has observation count of %v: %w", h.ZeroCount, ErrHistogramNegativeBucketCount) + } if h.CustomValues != nil { return ErrHistogramExpSchemaCustomBounds } default: return InvalidSchemaError(h.Schema) } + if h.Count < 0 { + return fmt.Errorf("observation count is %v: %w", h.Count, ErrHistogramNegativeCount) + } err := checkHistogramBuckets(h.PositiveBuckets, &pCount, false) if err != nil { return fmt.Errorf("positive side: %w", err) @@ -1044,16 +1050,21 @@ func (i *floatBucketIterator) Next() bool { if i.spansIdx >= len(i.spans) { return false } + span := i.spans[i.spansIdx] if i.schema == i.targetSchema { // Fast path for the common case. - span := i.spans[i.spansIdx] if i.bucketsIdx == 0 { // Seed origIdx for the first bucket. i.currIdx = span.Offset } else { i.currIdx++ } + if i.bucketsIdx >= len(i.buckets) { + // This protects against index out of range panic, which + // can only happen with an invalid histogram. + return false + } for i.idxInSpan >= span.Length { // We have exhausted the current span and have to find a new @@ -1074,7 +1085,6 @@ func (i *floatBucketIterator) Next() bool { // Copy all of these into local variables so that we can forward to the // next bucket and then roll back if needed. origIdx, spansIdx, idxInSpan := i.origIdx, i.spansIdx, i.idxInSpan - span := i.spans[spansIdx] firstPass := true i.currCount = 0 @@ -1086,6 +1096,14 @@ func (i *floatBucketIterator) Next() bool { } else { origIdx++ } + if i.bucketsIdx >= len(i.buckets) { + // This protects against index out of range panic, which + // can only happen with an invalid histogram. + if firstPass { + return false + } + break mergeLoop + } for idxInSpan >= span.Length { // We have exhausted the current span and have to find a new // one. We even handle pathologic spans of length 0 here. @@ -1146,6 +1164,11 @@ func (i *reverseFloatBucketIterator) Next() bool { // We have exhausted the current span and have to find a new // one. We'll even handle pathologic spans of length 0. i.spansIdx-- + if i.spansIdx < 0 { + // This protects against index out of range panic, which + // can only happen with an invalid histogram. + return false + } i.idxInSpan = int32(i.spans[i.spansIdx].Length) - 1 i.currIdx -= i.spans[i.spansIdx+1].Offset } @@ -1346,7 +1369,9 @@ func addBuckets( return spansA, bucketsA } -func FloatBucketsMatch(b1, b2 []float64) bool { +// floatBucketsMatch compares bucket values of two float histograms using binary float comparison +// and returns true if all values match. +func floatBucketsMatch(b1, b2 []float64) bool { if len(b1) != len(b2) { return false } @@ -1358,24 +1383,279 @@ func FloatBucketsMatch(b1, b2 []float64) bool { return true } +// detectResetWithMismatchedCustomBounds checks if any bucket count has decreased when +// comparing NHCBs with mismatched custom bounds. It maps both histograms +// to the intersected bounds on-the-fly and compares values without allocating +// arrays for all mapped buckets. +// Will panic if called with histograms that are not NHCB. +func (h *FloatHistogram) detectResetWithMismatchedCustomBounds( + previous *FloatHistogram, currBounds, prevBounds []float64, +) bool { + if h.Schema != CustomBucketsSchema || previous.Schema != CustomBucketsSchema { + panic("detectResetWithMismatchedCustomBounds called with non-NHCB schema") + } + currIt := h.floatBucketIterator(true, 0, CustomBucketsSchema) + prevIt := previous.floatBucketIterator(true, 0, CustomBucketsSchema) + + rollupSumForBound := func(iter *floatBucketIterator, iterStarted bool, iterBucket Bucket[float64], bound float64) (float64, Bucket[float64], bool) { + if !iterStarted { + if !iter.Next() { + return 0, Bucket[float64]{}, false + } + iterBucket = iter.At() + } + var sum float64 + for iterBucket.Upper <= bound { + sum += iterBucket.Count + if !iter.Next() { + return sum, Bucket[float64]{}, false + } + iterBucket = iter.At() + } + return sum, iterBucket, true + } + + var ( + currBoundIdx, prevBoundIdx = 0, 0 + currBucket, prevBucket Bucket[float64] + currIterStarted, currHasMore bool + prevIterStarted, prevHasMore bool + ) + + for currBoundIdx <= len(currBounds) && prevBoundIdx <= len(prevBounds) { + currBound := math.Inf(1) + if currBoundIdx < len(currBounds) { + currBound = currBounds[currBoundIdx] + } + prevBound := math.Inf(1) + if prevBoundIdx < len(prevBounds) { + prevBound = prevBounds[prevBoundIdx] + } + + switch { + case currBound == prevBound: + // Check matching bound, rolling up lesser buckets that have not been accounter for yet. + currRollupSum := 0.0 + if !currIterStarted || currHasMore { + currRollupSum, currBucket, currHasMore = rollupSumForBound(&currIt, currIterStarted, currBucket, currBound) + currIterStarted = true + } + + prevRollupSum := 0.0 + if !prevIterStarted || prevHasMore { + prevRollupSum, prevBucket, prevHasMore = rollupSumForBound(&prevIt, prevIterStarted, prevBucket, currBound) + prevIterStarted = true + } + + if currRollupSum < prevRollupSum { + return true + } + + currBoundIdx++ + prevBoundIdx++ + case currBound < prevBound: + currBoundIdx++ + default: + prevBoundIdx++ + } + } + + return false +} + +// intersectCustomBucketBounds returns the intersection of two custom bucket boundary sets. +func intersectCustomBucketBounds(boundsA, boundsB []float64) []float64 { + if len(boundsA) == 0 || len(boundsB) == 0 { + return nil + } + + var ( + result []float64 + i, j = 0, 0 + ) + + for i < len(boundsA) && j < len(boundsB) { + switch { + case boundsA[i] == boundsB[j]: + if result == nil { + // Allocate a new slice because FloatHistogram.CustomValues has to be immutable. + result = make([]float64, 0, min(len(boundsA), len(boundsB))) + } + result = append(result, boundsA[i]) + i++ + j++ + case boundsA[i] < boundsB[j]: + i++ + default: + j++ + } + } + + return result +} + +// addCustomBucketsWithMismatches handles adding/subtracting custom bucket histograms +// with mismatched bucket layouts by mapping both to an intersected layout. +func addCustomBucketsWithMismatches( + negative bool, + spansA []Span, bucketsA, boundsA []float64, + spansB []Span, bucketsB, boundsB []float64, + intersectedBounds []float64, +) ([]Span, []float64) { + targetBuckets := make([]float64, len(intersectedBounds)+1) + + mapBuckets := func(spans []Span, buckets, bounds []float64, negative bool) { + srcIdx := 0 + bucketIdx := 0 + intersectIdx := 0 + + for _, span := range spans { + srcIdx += int(span.Offset) + for range span.Length { + if bucketIdx < len(buckets) { + value := buckets[bucketIdx] + + // Find target bucket index. + targetIdx := len(targetBuckets) - 1 // Default to +Inf bucket. + if srcIdx < len(bounds) { + srcBound := bounds[srcIdx] + // Since both arrays are sorted, we can continue from where we left off. + for intersectIdx < len(intersectedBounds) { + if intersectedBounds[intersectIdx] >= srcBound { + targetIdx = intersectIdx + break + } + intersectIdx++ + } + } + + if negative { + targetBuckets[targetIdx] -= value + } else { + targetBuckets[targetIdx] += value + } + } + srcIdx++ + bucketIdx++ + } + } + } + + // Map both histograms to the intersected layout. + mapBuckets(spansA, bucketsA, boundsA, false) + mapBuckets(spansB, bucketsB, boundsB, negative) + + // Build spans and buckets, excluding zero-valued buckets from the final result. + destSpans := spansA[:0] // Reuse spansA capacity for destSpans since we don't need it anymore. + destBuckets := targetBuckets[:0] // Reuse targetBuckets capacity for destBuckets since it's guaranteed to be large enough. + lastIdx := int32(-1) + + for i, count := range targetBuckets { + if count == 0 { + continue + } + + destBuckets = append(destBuckets, count) + idx := int32(i) + + if len(destSpans) > 0 && idx == lastIdx+1 { + // Consecutive bucket, extend the last span. + destSpans[len(destSpans)-1].Length++ + } else { + // New span needed. + // TODO: optimize away small gaps. + offset := idx + if len(destSpans) > 0 { + // Convert to relative offset from the end of the last span. + prevEnd := lastIdx + offset = idx - prevEnd - 1 + } + destSpans = append(destSpans, Span{ + Offset: offset, + Length: 1, + }) + } + lastIdx = idx + } + + return destSpans, destBuckets +} + // ReduceResolution reduces the float histogram's spans, buckets into target schema. -// The target schema must be smaller than the current float histogram's schema. -// This will panic if the histogram has custom buckets or if the target schema is -// a custom buckets schema. -func (h *FloatHistogram) ReduceResolution(targetSchema int32) *FloatHistogram { +// An error is returned in the following cases: +// - The target schema is not smaller than the current histogram's schema. +// - The histogram has custom buckets. +// - The target schema is a custom buckets schema. +// - Any spans have an invalid offset. +// - The spans are inconsistent with the number of buckets. +func (h *FloatHistogram) ReduceResolution(targetSchema int32) error { + // Note that the follow three returns are not returning a + // histogram.Error because they are programming errors. if h.UsesCustomBuckets() { - panic("cannot reduce resolution when there are custom buckets") + return errors.New("cannot reduce resolution when there are custom buckets") } if IsCustomBucketsSchema(targetSchema) { - panic("cannot reduce resolution to custom buckets schema") + return errors.New("cannot reduce resolution to custom buckets schema") } if targetSchema >= h.Schema { - panic(fmt.Errorf("cannot reduce resolution from schema %d to %d", h.Schema, targetSchema)) + return fmt.Errorf("cannot reduce resolution from schema %d to %d", h.Schema, targetSchema) } - h.PositiveSpans, h.PositiveBuckets = reduceResolution(h.PositiveSpans, h.PositiveBuckets, h.Schema, targetSchema, false, true) - h.NegativeSpans, h.NegativeBuckets = reduceResolution(h.NegativeSpans, h.NegativeBuckets, h.Schema, targetSchema, false, true) + var err error + + if h.PositiveSpans, h.PositiveBuckets, err = reduceResolution( + h.PositiveSpans, h.PositiveBuckets, h.Schema, targetSchema, false, true, + ); err != nil { + return err + } + if h.NegativeSpans, h.NegativeBuckets, err = reduceResolution( + h.NegativeSpans, h.NegativeBuckets, h.Schema, targetSchema, false, true, + ); err != nil { + return err + } h.Schema = targetSchema - return h + return nil +} + +// checkSchemaAndBounds checks if two histograms are compatible because they +// both use a standard exponential schema or because they both are NHCBs. +func (h *FloatHistogram) checkSchemaAndBounds(other *FloatHistogram) error { + if h.UsesCustomBuckets() != other.UsesCustomBuckets() { + return ErrHistogramsIncompatibleSchema + } + return nil +} + +// adjustCounterReset is used for addition and subtraction. Those operation are +// usually only performed between gauge histograms, but if one or both are +// counters, we try to at least set the counter reset hint to something +// meaningful (see code comments below). The return counterResetCollision is +// true if one histogram has a counter reset hint of CounterReset and the other +// NotCounterReset. All other combinations are not considered a collision. +func (h *FloatHistogram) adjustCounterReset(other *FloatHistogram) (counterResetCollision bool) { + switch { + case other.CounterResetHint == h.CounterResetHint: + // Adding apples to apples, all good. No need to change anything. + case h.CounterResetHint == GaugeType: + // Adding something else to a gauge. That's probably OK. Outcome is a gauge. + // Nothing to do since the receiver is already marked as gauge. + case other.CounterResetHint == GaugeType: + // Similar to before, but this time the receiver is "something else" and we have to change it to gauge. + h.CounterResetHint = GaugeType + case h.CounterResetHint == UnknownCounterReset: + // With the receiver's CounterResetHint being "unknown", this could still be legitimate + // if the caller knows what they are doing. Outcome is then again "unknown". + // No need to do anything since the receiver's CounterResetHint is already "unknown". + case other.CounterResetHint == UnknownCounterReset: + // Similar to before, but now we have to set the receiver's CounterResetHint to "unknown". + h.CounterResetHint = UnknownCounterReset + default: + // All other cases shouldn't actually happen. + // They are a direct collision of CounterReset and NotCounterReset. + // Conservatively set the CounterResetHint to "unknown" and issue a warning. + h.CounterResetHint = UnknownCounterReset + return true + } + return false } diff --git a/vendor/github.com/prometheus/prometheus/model/histogram/generic.go b/vendor/github.com/prometheus/prometheus/model/histogram/generic.go index bc4c69d40c1..649db769c7e 100644 --- a/vendor/github.com/prometheus/prometheus/model/histogram/generic.go +++ b/vendor/github.com/prometheus/prometheus/model/histogram/generic.go @@ -28,32 +28,41 @@ const ( CustomBucketsSchema int32 = -53 ) +type Error struct { + error +} + +func (e Error) Unwrap() error { + return e.error +} + var ( - ErrHistogramCountNotBigEnough = errors.New("histogram's observation count should be at least the number of observations found in the buckets") - ErrHistogramCountMismatch = errors.New("histogram's observation count should equal the number of observations found in the buckets (in absence of NaN)") - ErrHistogramNegativeBucketCount = errors.New("histogram has a bucket whose observation count is negative") - ErrHistogramSpanNegativeOffset = errors.New("histogram has a span whose offset is negative") - ErrHistogramSpansBucketsMismatch = errors.New("histogram spans specify different number of buckets than provided") - ErrHistogramCustomBucketsMismatch = errors.New("histogram custom bounds are too few") - ErrHistogramCustomBucketsInvalid = errors.New("histogram custom bounds must be in strictly increasing order") - ErrHistogramCustomBucketsInfinite = errors.New("histogram custom bounds must be finite") - ErrHistogramsIncompatibleSchema = errors.New("cannot apply this operation on histograms with a mix of exponential and custom bucket schemas") - ErrHistogramsIncompatibleBounds = errors.New("cannot apply this operation on custom buckets histograms with different custom bounds") - ErrHistogramCustomBucketsZeroCount = errors.New("custom buckets: must have zero count of 0") - ErrHistogramCustomBucketsZeroThresh = errors.New("custom buckets: must have zero threshold of 0") - ErrHistogramCustomBucketsNegSpans = errors.New("custom buckets: must not have negative spans") - ErrHistogramCustomBucketsNegBuckets = errors.New("custom buckets: must not have negative buckets") - ErrHistogramExpSchemaCustomBounds = errors.New("histogram with exponential schema must not have custom bounds") - ErrHistogramsInvalidSchema = fmt.Errorf("histogram has an invalid schema, which must be between %d and %d for exponential buckets, or %d for custom buckets", ExponentialSchemaMin, ExponentialSchemaMax, CustomBucketsSchema) - ErrHistogramsUnknownSchema = fmt.Errorf("histogram has an unknown schema, which must be between %d and %d for exponential buckets, or %d for custom buckets", ExponentialSchemaMinReserved, ExponentialSchemaMaxReserved, CustomBucketsSchema) + ErrHistogramCountNotBigEnough = Error{error: errors.New("histogram's observation count should be at least the number of observations found in the buckets")} + ErrHistogramCountMismatch = Error{error: errors.New("histogram's observation count should equal the number of observations found in the buckets (in absence of NaN)")} + ErrHistogramNegativeCount = Error{error: errors.New("histogram's observation count is negative")} + ErrHistogramNegativeBucketCount = Error{error: errors.New("histogram has a bucket whose observation count is negative")} + ErrHistogramSpanNegativeOffset = Error{error: errors.New("histogram has a span whose offset is negative")} + ErrHistogramSpansBucketsMismatch = Error{error: errors.New("histogram spans specify different number of buckets than provided")} + ErrHistogramCustomBucketsMismatch = Error{error: errors.New("histogram custom bounds are too few")} + ErrHistogramCustomBucketsInvalid = Error{error: errors.New("histogram custom bounds must be in strictly increasing order")} + ErrHistogramCustomBucketsInfinite = Error{error: errors.New("histogram custom bounds must be finite")} + ErrHistogramCustomBucketsNaN = Error{error: errors.New("histogram custom bounds must not be NaN")} + ErrHistogramsIncompatibleSchema = Error{error: errors.New("cannot apply this operation on histograms with a mix of exponential and custom bucket schemas")} + ErrHistogramCustomBucketsZeroCount = Error{error: errors.New("custom buckets: must have zero count of 0")} + ErrHistogramCustomBucketsZeroThresh = Error{error: errors.New("custom buckets: must have zero threshold of 0")} + ErrHistogramCustomBucketsNegSpans = Error{error: errors.New("custom buckets: must not have negative spans")} + ErrHistogramCustomBucketsNegBuckets = Error{error: errors.New("custom buckets: must not have negative buckets")} + ErrHistogramExpSchemaCustomBounds = Error{error: errors.New("histogram with exponential schema must not have custom bounds")} + ErrHistogramsInvalidSchema = Error{error: fmt.Errorf("histogram has an invalid schema, which must be between %d and %d for exponential buckets, or %d for custom buckets", ExponentialSchemaMin, ExponentialSchemaMax, CustomBucketsSchema)} + ErrHistogramsUnknownSchema = Error{error: fmt.Errorf("histogram has an unknown schema, which must be between %d and %d for exponential buckets, or %d for custom buckets", ExponentialSchemaMinReserved, ExponentialSchemaMaxReserved, CustomBucketsSchema)} ) func InvalidSchemaError(s int32) error { - return fmt.Errorf("%w, got schema %d", ErrHistogramsInvalidSchema, s) + return Error{error: fmt.Errorf("%w, got schema %d", ErrHistogramsInvalidSchema, s)} } func UnknownSchemaError(s int32) error { - return fmt.Errorf("%w, got schema %d", ErrHistogramsUnknownSchema, s) + return Error{error: fmt.Errorf("%w, got schema %d", ErrHistogramsUnknownSchema, s)} } func IsCustomBucketsSchema(s int32) bool { @@ -78,6 +87,20 @@ func IsKnownSchema(s int32) bool { return IsCustomBucketsSchema(s) || IsExponentialSchemaReserved(s) } +// CustomBucketBoundsMatch compares histogram custom bucket bounds (CustomValues) +// and returns true if all values match. +func CustomBucketBoundsMatch(c1, c2 []float64) bool { + if len(c1) != len(c2) { + return false + } + for i, c := range c1 { + if c != c2[i] { + return false + } + } + return true +} + // BucketCount is a type constraint for the count in a bucket, which can be // float64 (for type FloatHistogram) or uint64 (for type Histogram). type BucketCount interface { @@ -452,8 +475,11 @@ func checkHistogramBuckets[BC BucketCount, IBC InternalBucketCount](buckets []IB func checkHistogramCustomBounds(bounds []float64, spans []Span, numBuckets int) error { prev := math.Inf(-1) - for _, curr := range bounds { - if curr <= prev { + for i, curr := range bounds { + if math.IsNaN(curr) { + return ErrHistogramCustomBucketsNaN + } + if i > 0 && curr <= prev { return fmt.Errorf("previous bound is %f and current is %f: %w", prev, curr, ErrHistogramCustomBucketsInvalid) } prev = curr @@ -712,6 +738,8 @@ var exponentialBounds = [][]float64{ // deltas. Set it to false if the buckets contain absolute counts. // Set inplace to true to reuse input slices and avoid allocations (otherwise // new slices will be allocated for result). +// The functions returns an error if there are too many or too few buckets for the spans +// or if any span except the first has a negative offset. func reduceResolution[IBC InternalBucketCount]( originSpans []Span, originBuckets []IBC, @@ -719,7 +747,7 @@ func reduceResolution[IBC InternalBucketCount]( targetSchema int32, deltaBuckets bool, inplace bool, -) ([]Span, []IBC) { +) ([]Span, []IBC, error) { var ( targetSpans []Span // The spans in the target schema. targetBuckets []IBC // The bucket counts in the target schema. @@ -738,10 +766,18 @@ func reduceResolution[IBC InternalBucketCount]( targetBuckets = originBuckets[:0] } - for _, span := range originSpans { + for n, span := range originSpans { + if n > 0 && span.Offset < 0 { + return nil, nil, fmt.Errorf("span number %d with offset %d: %w", n+1, span.Offset, ErrHistogramSpanNegativeOffset) + } // Determine the index of the first bucket in this span. bucketIdx += span.Offset for j := 0; j < int(span.Length); j++ { + // Protect against too few buckets in the origin. + if bucketCountIdx >= len(originBuckets) { + return nil, nil, fmt.Errorf("have %d buckets but spans need more: %w", len(originBuckets), ErrHistogramSpansBucketsMismatch) + } + // Determine the index of the bucket in the target schema from the index in the original schema. targetBucketIdx = targetIdx(bucketIdx, originSchema, targetSchema) @@ -800,12 +836,33 @@ func reduceResolution[IBC InternalBucketCount]( targetBuckets = append(targetBuckets, originBuckets[bucketCountIdx]) } } - bucketIdx++ bucketCountIdx++ } } + if bucketCountIdx != len(originBuckets) { + return nil, nil, fmt.Errorf("spans need %d buckets, have %d buckets: %w", bucketCountIdx, len(originBuckets), ErrHistogramSpansBucketsMismatch) + } + return targetSpans, targetBuckets, nil +} +// mustReduceResolution works like reduceResolution, but panics instead of +// returning an error. Use mustReduceResolution if you are sure that the spans +// and buckets are valid. +func mustReduceResolution[IBC InternalBucketCount]( + originSpans []Span, + originBuckets []IBC, + originSchema, + targetSchema int32, + deltaBuckets bool, + inplace bool, +) ([]Span, []IBC) { + targetSpans, targetBuckets, err := reduceResolution( + originSpans, originBuckets, originSchema, targetSchema, deltaBuckets, inplace, + ) + if err != nil { + panic(err) + } return targetSpans, targetBuckets } diff --git a/vendor/github.com/prometheus/prometheus/model/histogram/histogram.go b/vendor/github.com/prometheus/prometheus/model/histogram/histogram.go index 35c97971552..5fc68ef9d02 100644 --- a/vendor/github.com/prometheus/prometheus/model/histogram/histogram.go +++ b/vendor/github.com/prometheus/prometheus/model/histogram/histogram.go @@ -14,6 +14,7 @@ package histogram import ( + "errors" "fmt" "math" "slices" @@ -255,7 +256,7 @@ func (h *Histogram) Equals(h2 *Histogram) bool { } if h.UsesCustomBuckets() { - if !FloatBucketsMatch(h.CustomValues, h2.CustomValues) { + if !CustomBucketBoundsMatch(h.CustomValues, h2.CustomValues) { return false } } @@ -515,6 +516,11 @@ func (r *regularBucketIterator) Next() bool { r.currIdx += span.Offset } + // This protects against index out of range panic, which + // can only happen with an invalid histogram. + if r.bucketsIdx >= len(r.buckets) { + return false + } r.currCount += r.buckets[r.bucketsIdx] r.idxInSpan++ r.bucketsIdx++ @@ -576,6 +582,11 @@ func (c *cumulativeBucketIterator) Next() bool { c.initialized = true } + // This protects against index out of range panic, which + // can only happen with an invalid histogram. + if c.posBucketsIdx >= len(c.h.PositiveBuckets) { + return false + } c.currCount += c.h.PositiveBuckets[c.posBucketsIdx] c.currCumulativeCount += uint64(c.currCount) c.currUpper = getBound(c.currIdx, c.h.Schema, c.h.CustomValues) @@ -607,26 +618,37 @@ func (c *cumulativeBucketIterator) At() Bucket[uint64] { } // ReduceResolution reduces the histogram's spans, buckets into target schema. -// The target schema must be smaller than the current histogram's schema. -// This will panic if the histogram has custom buckets or if the target schema is -// a custom buckets schema. -func (h *Histogram) ReduceResolution(targetSchema int32) *Histogram { +// An error is returned in the following cases: +// - The target schema is not smaller than the current histogram's schema. +// - The histogram has custom buckets. +// - The target schema is a custom buckets schema. +// - Any spans have an invalid offset. +// - The spans are inconsistent with the number of buckets. +func (h *Histogram) ReduceResolution(targetSchema int32) error { + // Note that the follow three returns are not returning a + // histogram.Error because they are programming errors. if h.UsesCustomBuckets() { - panic("cannot reduce resolution when there are custom buckets") + return errors.New("cannot reduce resolution when there are custom buckets") } if IsCustomBucketsSchema(targetSchema) { - panic("cannot reduce resolution to custom buckets schema") + return errors.New("cannot reduce resolution to custom buckets schema") } if targetSchema >= h.Schema { - panic(fmt.Errorf("cannot reduce resolution from schema %d to %d", h.Schema, targetSchema)) + return fmt.Errorf("cannot reduce resolution from schema %d to %d", h.Schema, targetSchema) } - h.PositiveSpans, h.PositiveBuckets = reduceResolution( + var err error + + if h.PositiveSpans, h.PositiveBuckets, err = reduceResolution( h.PositiveSpans, h.PositiveBuckets, h.Schema, targetSchema, true, true, - ) - h.NegativeSpans, h.NegativeBuckets = reduceResolution( + ); err != nil { + return err + } + if h.NegativeSpans, h.NegativeBuckets, err = reduceResolution( h.NegativeSpans, h.NegativeBuckets, h.Schema, targetSchema, true, true, - ) + ); err != nil { + return err + } h.Schema = targetSchema - return h + return nil } diff --git a/vendor/github.com/prometheus/prometheus/model/labels/float.go b/vendor/github.com/prometheus/prometheus/model/labels/float.go new file mode 100644 index 00000000000..c526a5b2a6a --- /dev/null +++ b/vendor/github.com/prometheus/prometheus/model/labels/float.go @@ -0,0 +1,60 @@ +// Copyright The Prometheus Authors +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package labels + +import ( + "bytes" + "math" + "strconv" + "sync" +) + +// floatFormatBufPool is exclusively used in FormatOpenMetricsFloat. +var floatFormatBufPool = sync.Pool{ + New: func() any { + // To contain at most 17 digits and additional syntax for a float64. + b := make([]byte, 0, 24) + return &b + }, +} + +// FormatOpenMetricsFloat works like the usual Go string formatting of a float +// but appends ".0" if the resulting number would otherwise contain neither a +// "." nor an "e". +func FormatOpenMetricsFloat(f float64) string { + // A few common cases hardcoded. + switch { + case f == 1: + return "1.0" + case f == 0: + return "0.0" + case f == -1: + return "-1.0" + case math.IsNaN(f): + return "NaN" + case math.IsInf(f, +1): + return "+Inf" + case math.IsInf(f, -1): + return "-Inf" + } + bp := floatFormatBufPool.Get().(*[]byte) + defer floatFormatBufPool.Put(bp) + + *bp = strconv.AppendFloat((*bp)[:0], f, 'g', -1, 64) + if bytes.ContainsAny(*bp, "e.") { + return string(*bp) + } + *bp = append(*bp, '.', '0') + return string(*bp) +} diff --git a/vendor/github.com/prometheus/prometheus/model/labels/labels_common.go b/vendor/github.com/prometheus/prometheus/model/labels/labels_common.go index e27da94a477..ab82ae6a8fc 100644 --- a/vendor/github.com/prometheus/prometheus/model/labels/labels_common.go +++ b/vendor/github.com/prometheus/prometheus/model/labels/labels_common.go @@ -25,7 +25,10 @@ import ( const ( // MetricName is a special label name that represent a metric name. - // Deprecated: Use schema.Metadata structure and its methods. + // + // Deprecated: Instead, consider using schema.Metadata structure and its methods for consistent metadata behaviour with the newly added __type__ and __unit__ labels. Alternatively use github.com/prometheus/common/model.MetricNameLabel for the direct replacement. + // + // labels package is providing label transport, agnostic to semantic meaning of each label. MetricName = "__name__" AlertName = "alertname" diff --git a/vendor/github.com/prometheus/prometheus/model/labels/labels_dedupelabels.go b/vendor/github.com/prometheus/prometheus/model/labels/labels_dedupelabels.go index 0b28e3398b9..4518482c968 100644 --- a/vendor/github.com/prometheus/prometheus/model/labels/labels_dedupelabels.go +++ b/vendor/github.com/prometheus/prometheus/model/labels/labels_dedupelabels.go @@ -24,6 +24,9 @@ import ( "github.com/cespare/xxhash/v2" ) +// ImplementationName is the name of the labels implementation. +const ImplementationName = "dedupelabels" + // Labels is implemented by a SymbolTable and string holding name/value // pairs encoded as indexes into the table in varint encoding. // Names are in alphabetical order. @@ -562,6 +565,7 @@ func (Labels) ReleaseStrings(func(string)) { } // DropMetricName returns Labels with the "__name__" removed. +// // Deprecated: Use DropReserved instead. func (ls Labels) DropMetricName() Labels { return ls.DropReserved(func(n string) bool { return n == MetricName }) @@ -775,6 +779,14 @@ func (b *ScratchBuilder) SetSymbolTable(s *SymbolTable) { b.syms = s } +// SetUnsafeAdd allows turning on/off the assumptions that added strings are unsafe +// for reuse. ScratchBuilder implementations that do reuse strings, must clone +// the strings. +// +// DedupeLabels implementation copies any new strings to the symbolTable when +// Labels() is called, so this operation is noop. +func (ScratchBuilder) SetUnsafeAdd(bool) {} + func (b *ScratchBuilder) Reset() { b.add = b.add[:0] b.output = EmptyLabels() @@ -782,16 +794,11 @@ func (b *ScratchBuilder) Reset() { // Add a name/value pair. // Note if you Add the same name twice you will get a duplicate label, which is invalid. +// The values must remain live until Labels() is called. func (b *ScratchBuilder) Add(name, value string) { b.add = append(b.add, Label{Name: name, Value: value}) } -// UnsafeAddBytes adds a name/value pair, using []byte instead of string to reduce memory allocations. -// The values must remain live until Labels() is called. -func (b *ScratchBuilder) UnsafeAddBytes(name, value []byte) { - b.add = append(b.add, Label{Name: yoloString(name), Value: yoloString(value)}) -} - // Sort the labels added so far by name. func (b *ScratchBuilder) Sort() { slices.SortFunc(b.add, func(a, b Label) int { return strings.Compare(a.Name, b.Name) }) diff --git a/vendor/github.com/prometheus/prometheus/model/labels/labels_slicelabels.go b/vendor/github.com/prometheus/prometheus/model/labels/labels_slicelabels.go index 3b09c706161..71dbcd00449 100644 --- a/vendor/github.com/prometheus/prometheus/model/labels/labels_slicelabels.go +++ b/vendor/github.com/prometheus/prometheus/model/labels/labels_slicelabels.go @@ -19,11 +19,15 @@ import ( "bytes" "slices" "strings" + "unique" "unsafe" "github.com/cespare/xxhash/v2" ) +// ImplementationName is the name of the labels implementation. +const ImplementationName = "slicelabels" + // Labels is a sorted set of labels. Order has to be guaranteed upon // instantiation. type Labels []Label @@ -296,12 +300,9 @@ func FromStrings(ss ...string) Labels { // Compare compares the two label sets. // The result will be 0 if a==b, <0 if a < b, and >0 if a > b. func Compare(a, b Labels) int { - l := len(a) - if len(b) < l { - l = len(b) - } + l := min(len(b), len(a)) - for i := 0; i < l; i++ { + for i := range l { if a[i].Name != b[i].Name { if a[i].Name < b[i].Name { return -1 @@ -348,6 +349,7 @@ func (ls Labels) Validate(f func(l Label) error) error { } // DropMetricName returns Labels with the "__name__" removed. +// // Deprecated: Use DropReserved instead. func (ls Labels) DropMetricName() Labels { return ls.DropReserved(func(n string) bool { return n == MetricName }) @@ -417,10 +419,7 @@ func (b *Builder) Labels() Labels { return b.base } - expectedSize := len(b.base) + len(b.add) - len(b.del) - if expectedSize < 1 { - expectedSize = 1 - } + expectedSize := max(len(b.base)+len(b.add)-len(b.del), 1) res := make(Labels, 0, expectedSize) for _, l := range b.base { if slices.Contains(b.del, l.Name) || contains(b.add, l.Name) { @@ -437,7 +436,8 @@ func (b *Builder) Labels() Labels { // ScratchBuilder allows efficient construction of a Labels from scratch. type ScratchBuilder struct { - add Labels + add Labels + unsafeAdd bool } // SymbolTable is no-op, just for api parity with dedupelabels. @@ -466,23 +466,32 @@ func (*ScratchBuilder) SetSymbolTable(*SymbolTable) { // no-op } +// SetUnsafeAdd allows turning on/off the assumptions that added strings are unsafe +// for reuse. ScratchBuilder implementations that do reuse strings, must clone +// the strings. +// +// SliceLabels will clone all added strings when this option is true. +func (b *ScratchBuilder) SetUnsafeAdd(unsafeAdd bool) { + b.unsafeAdd = unsafeAdd +} + func (b *ScratchBuilder) Reset() { b.add = b.add[:0] } // Add a name/value pair. // Note if you Add the same name twice you will get a duplicate label, which is invalid. +// If SetUnsafeAdd was set to false, the values must remain live until Labels() is called. func (b *ScratchBuilder) Add(name, value string) { + if b.unsafeAdd { + // Underlying label structure for slicelabels shares memory, so we need to + // copy it if the input is unsafe. + name = unique.Make(name).Value() + value = unique.Make(value).Value() + } b.add = append(b.add, Label{Name: name, Value: value}) } -// UnsafeAddBytes adds a name/value pair, using []byte instead of string. -// The default version of this function is unsafe, hence the name. -// This version is safe - it copies the strings immediately - but we keep the same name so everything compiles. -func (b *ScratchBuilder) UnsafeAddBytes(name, value []byte) { - b.add = append(b.add, Label{Name: string(name), Value: string(value)}) -} - // Sort the labels added so far by name. func (b *ScratchBuilder) Sort() { slices.SortFunc(b.add, func(a, b Label) int { return strings.Compare(a.Name, b.Name) }) diff --git a/vendor/github.com/prometheus/prometheus/model/labels/labels_stringlabels.go b/vendor/github.com/prometheus/prometheus/model/labels/labels_stringlabels.go index 8743c0149a8..1460e7db932 100644 --- a/vendor/github.com/prometheus/prometheus/model/labels/labels_stringlabels.go +++ b/vendor/github.com/prometheus/prometheus/model/labels/labels_stringlabels.go @@ -23,6 +23,9 @@ import ( "github.com/cespare/xxhash/v2" ) +// ImplementationName is the name of the labels implementation. +const ImplementationName = "stringlabels" + // Labels is implemented by a single flat string holding name/value pairs. // Each name and value is preceded by its length, encoded as a single byte // for size 0-254, or the following 3 bytes little-endian, if the first byte is 255. @@ -421,6 +424,7 @@ func (ls Labels) Validate(f func(l Label) error) error { } // DropMetricName returns Labels with the "__name__" removed. +// // Deprecated: Use DropReserved instead. func (ls Labels) DropMetricName() Labels { return ls.DropReserved(func(n string) bool { return n == MetricName }) @@ -614,16 +618,11 @@ func (b *ScratchBuilder) Reset() { // Add a name/value pair. // Note if you Add the same name twice you will get a duplicate label, which is invalid. +// The values must remain live until Labels() is called. func (b *ScratchBuilder) Add(name, value string) { b.add = append(b.add, Label{Name: name, Value: value}) } -// UnsafeAddBytes adds a name/value pair using []byte instead of string to reduce memory allocations. -// The values must remain live until Labels() is called. -func (b *ScratchBuilder) UnsafeAddBytes(name, value []byte) { - b.add = append(b.add, Label{Name: yoloString(name), Value: yoloString(value)}) -} - // Sort the labels added so far by name. func (b *ScratchBuilder) Sort() { slices.SortFunc(b.add, func(a, b Label) int { return strings.Compare(a.Name, b.Name) }) @@ -680,6 +679,13 @@ func (*ScratchBuilder) SetSymbolTable(*SymbolTable) { // no-op } +// SetUnsafeAdd allows turning on/off the assumptions that added strings are unsafe +// for reuse. ScratchBuilder implementations that do reuse strings, must clone +// the strings. +// +// StringLabels implementation copies all strings when Labels() is called, so this operation is noop. +func (ScratchBuilder) SetUnsafeAdd(bool) {} + // SizeOfLabels returns the approximate space required for n copies of a label. func SizeOfLabels(name, value string, n uint64) uint64 { return uint64(labelSize(&Label{Name: name, Value: value})) * n diff --git a/vendor/github.com/prometheus/prometheus/model/labels/regexp.go b/vendor/github.com/prometheus/prometheus/model/labels/regexp.go index 6838e094f1a..47b50e703a5 100644 --- a/vendor/github.com/prometheus/prometheus/model/labels/regexp.go +++ b/vendor/github.com/prometheus/prometheus/model/labels/regexp.go @@ -67,8 +67,6 @@ func NewFastRegexMatcher(v string) (*FastRegexMatcher, error) { if err != nil { return nil, err } - // Simplify the syntax tree to run faster. - parsed = parsed.Simplify() m.re, err = regexp.Compile("^(?s:" + parsed.String() + ")$") if err != nil { return nil, err @@ -372,7 +370,7 @@ func optimizeConcatRegex(r *syntax.Regexp) (prefix, suffix string, contains []st } if len(sub) == 0 { - return + return prefix, suffix, contains } // Given Prometheus regex matchers are always anchored to the begin/end @@ -393,7 +391,7 @@ func optimizeConcatRegex(r *syntax.Regexp) (prefix, suffix string, contains []st } } - return + return prefix, suffix, contains } // StringMatcher is a matcher that matches a string in place of a regular expression. diff --git a/vendor/github.com/prometheus/prometheus/model/labels/test_utils.go b/vendor/github.com/prometheus/prometheus/model/labels/test_utils.go index d060def4811..66020799e9a 100644 --- a/vendor/github.com/prometheus/prometheus/model/labels/test_utils.go +++ b/vendor/github.com/prometheus/prometheus/model/labels/test_utils.go @@ -62,8 +62,7 @@ func ReadLabels(fn string, n int) ([]Labels, error) { r := strings.NewReplacer("\"", "", "{", "", "}", "") s := r.Replace(scanner.Text()) - labelChunks := strings.Split(s, ",") - for _, labelChunk := range labelChunks { + for labelChunk := range strings.SplitSeq(s, ",") { split := strings.Split(labelChunk, ":") b.Add(split[0], split[1]) } diff --git a/vendor/github.com/prometheus/prometheus/model/metadata/metadata.go b/vendor/github.com/prometheus/prometheus/model/metadata/metadata.go index 1b7e63e0f35..d2a91bb5603 100644 --- a/vendor/github.com/prometheus/prometheus/model/metadata/metadata.go +++ b/vendor/github.com/prometheus/prometheus/model/metadata/metadata.go @@ -1,4 +1,4 @@ -// Copyright 2022 The Prometheus Authors +// Copyright The Prometheus Authors // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at @@ -13,7 +13,11 @@ package metadata -import "github.com/prometheus/common/model" +import ( + "strings" + + "github.com/prometheus/common/model" +) // Metadata stores a series' metadata information. type Metadata struct { @@ -21,3 +25,21 @@ type Metadata struct { Unit string `json:"unit"` Help string `json:"help"` } + +// IsEmpty returns true if metadata structure is empty, including unknown type case. +func (m Metadata) IsEmpty() bool { + return (m.Type == "" || m.Type == model.MetricTypeUnknown) && m.Unit == "" && m.Help == "" +} + +// Equals returns true if m is semantically the same as other metadata. +func (m Metadata) Equals(other Metadata) bool { + if strings.Compare(m.Unit, other.Unit) != 0 || strings.Compare(m.Help, other.Help) != 0 { + return false + } + + // Unknown means the same as empty string. + if m.Type == "" || m.Type == model.MetricTypeUnknown { + return other.Type == "" || other.Type == model.MetricTypeUnknown + } + return m.Type == other.Type +} diff --git a/vendor/github.com/prometheus/prometheus/model/relabel/relabel.go b/vendor/github.com/prometheus/prometheus/model/relabel/relabel.go index c15049b2b0a..f7085037fdb 100644 --- a/vendor/github.com/prometheus/prometheus/model/relabel/relabel.go +++ b/vendor/github.com/prometheus/prometheus/model/relabel/relabel.go @@ -86,7 +86,7 @@ func (a *Action) UnmarshalYAML(unmarshal func(any) error) error { type Config struct { // A list of labels from which values are taken and concatenated // with the configured separator in order. - SourceLabels model.LabelNames `yaml:"source_labels,flow,omitempty" json:"sourceLabels,omitempty"` + SourceLabels model.LabelNames `yaml:"source_labels,flow,omitempty" json:"source_labels,omitempty"` // Separator is the string between concatenated values from the source labels. Separator string `yaml:"separator,omitempty" json:"separator,omitempty"` // Regex against which the concatenation is matched. @@ -95,7 +95,7 @@ type Config struct { Modulus uint64 `yaml:"modulus,omitempty" json:"modulus,omitempty"` // TargetLabel is the label to which the resulting string is written in a replacement. // Regexp interpolation is allowed for the replace action. - TargetLabel string `yaml:"target_label,omitempty" json:"targetLabel,omitempty"` + TargetLabel string `yaml:"target_label,omitempty" json:"target_label,omitempty"` // Replacement is the regex replacement pattern to be used. Replacement string `yaml:"replacement,omitempty" json:"replacement,omitempty"` // Action is the action to be performed for the relabeling. diff --git a/vendor/github.com/prometheus/prometheus/model/rulefmt/rulefmt.go b/vendor/github.com/prometheus/prometheus/model/rulefmt/rulefmt.go index 68681d6ac05..83203ba7691 100644 --- a/vendor/github.com/prometheus/prometheus/model/rulefmt/rulefmt.go +++ b/vendor/github.com/prometheus/prometheus/model/rulefmt/rulefmt.go @@ -100,7 +100,7 @@ type ruleGroups struct { func (g *RuleGroups) Validate(node ruleGroups, nameValidationScheme model.ValidationScheme) (errs []error) { if err := namevalidationutil.CheckNameValidationScheme(nameValidationScheme); err != nil { errs = append(errs, err) - return + return errs } set := map[string]struct{}{} @@ -286,7 +286,7 @@ func (r *Rule) Validate(node RuleNode, nameValidationScheme model.ValidationSche nodes = append(nodes, WrappedError{err: err}) } - return + return nodes } // testTemplateParsing checks if the templates used in labels and annotations diff --git a/vendor/github.com/prometheus/prometheus/model/textparse/interface.go b/vendor/github.com/prometheus/prometheus/model/textparse/interface.go index d4749c3da6b..bbc52290ade 100644 --- a/vendor/github.com/prometheus/prometheus/model/textparse/interface.go +++ b/vendor/github.com/prometheus/prometheus/model/textparse/interface.go @@ -29,7 +29,7 @@ import ( type Parser interface { // Series returns the bytes of a series with a simple float64 as a // value, the timestamp if set, and the value of the current sample. - // TODO(bwplotka): Similar to CreatedTimestamp, have ts == 0 meaning no timestamp provided. + // TODO(bwplotka): Similar to StartTimestamp, have ts == 0 meaning no timestamp provided. // We already accepted in many places (PRW, proto parsing histograms) that 0 timestamp is not a // a valid timestamp. If needed it can be represented as 0+1ms. Series() ([]byte, *int64, float64) @@ -38,7 +38,7 @@ type Parser interface { // value, the timestamp if set, and the histogram in the current sample. // Depending on the parsed input, the function returns an (integer) Histogram // or a FloatHistogram, with the respective other return value being nil. - // TODO(bwplotka): Similar to CreatedTimestamp, have ts == 0 meaning no timestamp provided. + // TODO(bwplotka): Similar to StartTimestamp, have ts == 0 meaning no timestamp provided. // We already accepted in many places (PRW, proto parsing histograms) that 0 timestamp is not a // a valid timestamp. If needed it can be represented as 0+1ms. Histogram() ([]byte, *int64, *histogram.Histogram, *histogram.FloatHistogram) @@ -76,10 +76,10 @@ type Parser interface { // retrieved (including the case where no exemplars exist at all). Exemplar(l *exemplar.Exemplar) bool - // CreatedTimestamp returns the created timestamp (in milliseconds) for the + // StartTimestamp returns the created timestamp (in milliseconds) for the // current sample. It returns 0 if it is unknown e.g. if it wasn't set or // if the scrape protocol or metric type does not support created timestamps. - CreatedTimestamp() int64 + StartTimestamp() int64 // Next advances the parser to the next sample. // It returns (EntryInvalid, io.EOF) if no samples were read. @@ -127,6 +127,17 @@ type ParserOptions struct { // in the parsed metrics. EnableTypeAndUnitLabels bool + // IgnoreNativeHistograms causes the parser to completely ignore all + // parts of native histograms, but to keep the ability to convert + // classic histograms to NHCB. This has the implication that even a + // histogram that has some native parts but not a single classic bucket + // will be parsed as a classic histogram (with only the +Inf bucket and + // count and sum). Setting this also allows converting a classic + // histogram that already has a native representation to an NHCB. This + // option has no effect on parsers for formats that do not support + // native histograms. + IgnoreNativeHistograms bool + // ConvertClassicHistogramsToNHCB enables conversion of classic histograms // to native histogram custom buckets (NHCB) format. ConvertClassicHistogramsToNHCB bool @@ -135,9 +146,9 @@ type ParserOptions struct { // that is also present as a native histogram. (Proto parsing only). KeepClassicOnClassicAndNativeHistograms bool - // OpenMetricsSkipCTSeries determines whether to skip `_created` timestamp series + // OpenMetricsSkipSTSeries determines whether to skip `_created` timestamp series // during (OpenMetrics parsing only). - OpenMetricsSkipCTSeries bool + OpenMetricsSkipSTSeries bool // FallbackContentType specifies the fallback content type to use when the provided // Content-Type header cannot be parsed or is not supported. @@ -164,11 +175,18 @@ func New(b []byte, contentType string, st *labels.SymbolTable, opts ParserOption switch mediaType { case "application/openmetrics-text": baseParser = NewOpenMetricsParser(b, st, func(o *openMetricsParserOptions) { - o.skipCTSeries = opts.OpenMetricsSkipCTSeries + o.skipSTSeries = opts.OpenMetricsSkipSTSeries o.enableTypeAndUnitLabels = opts.EnableTypeAndUnitLabels }) case "application/vnd.google.protobuf": - return NewProtobufParser(b, opts.KeepClassicOnClassicAndNativeHistograms, opts.ConvertClassicHistogramsToNHCB, opts.EnableTypeAndUnitLabels, st), err + return NewProtobufParser( + b, + opts.IgnoreNativeHistograms, + opts.KeepClassicOnClassicAndNativeHistograms, + opts.ConvertClassicHistogramsToNHCB, + opts.EnableTypeAndUnitLabels, + st, + ), err case "text/plain": baseParser = NewPromParser(b, st, opts.EnableTypeAndUnitLabels) default: diff --git a/vendor/github.com/prometheus/prometheus/model/textparse/nhcbparse.go b/vendor/github.com/prometheus/prometheus/model/textparse/nhcbparse.go index d820a0f8b13..79441e1f754 100644 --- a/vendor/github.com/prometheus/prometheus/model/textparse/nhcbparse.go +++ b/vendor/github.com/prometheus/prometheus/model/textparse/nhcbparse.go @@ -83,7 +83,7 @@ type NHCBParser struct { fhNHCB *histogram.FloatHistogram lsetNHCB labels.Labels exemplars []exemplar.Exemplar - ctNHCB int64 + stNHCB int64 metricStringNHCB string // Collates values from the classic histogram series to build @@ -92,7 +92,7 @@ type NHCBParser struct { tempNHCB convertnhcb.TempHistogram tempExemplars []exemplar.Exemplar tempExemplarCount int - tempCT int64 + tempST int64 // Remembers the last base histogram metric name (assuming it's // a classic histogram) so we can tell if the next float series @@ -159,16 +159,16 @@ func (p *NHCBParser) Exemplar(ex *exemplar.Exemplar) bool { return p.parser.Exemplar(ex) } -func (p *NHCBParser) CreatedTimestamp() int64 { +func (p *NHCBParser) StartTimestamp() int64 { switch p.state { case stateStart, stateInhibiting: if p.entry == EntrySeries || p.entry == EntryHistogram { - return p.parser.CreatedTimestamp() + return p.parser.StartTimestamp() } case stateCollecting: - return p.tempCT + return p.tempST case stateEmitting: - return p.ctNHCB + return p.stNHCB } return 0 } @@ -318,7 +318,7 @@ func (p *NHCBParser) handleClassicHistogramSeries(lset labels.Labels) bool { func (p *NHCBParser) processClassicHistogramSeries(lset labels.Labels, name string, updateHist func(*convertnhcb.TempHistogram)) { if p.state != stateCollecting { p.storeClassicLabels(name) - p.tempCT = p.parser.CreatedTimestamp() + p.tempST = p.parser.StartTimestamp() p.state = stateCollecting p.tempLsetNHCB = convertnhcb.GetHistogramMetricBase(lset, name) } @@ -352,7 +352,7 @@ func (p *NHCBParser) swapExemplars() { } // processNHCB converts the collated classic histogram series to NHCB and caches the info -// to be returned to callers. Retruns true if the conversion was successful. +// to be returned to callers. Returns true if the conversion was successful. func (p *NHCBParser) processNHCB() bool { if p.state != stateCollecting { return false @@ -373,7 +373,7 @@ func (p *NHCBParser) processNHCB() bool { p.fhNHCB = fh } - lblsWithMetricName := p.tempLsetNHCB.DropMetricName() + lblsWithMetricName := p.tempLsetNHCB.DropReserved(func(n string) bool { return n == labels.MetricName }) // Ensure we return `metric` instead of `metric{}` for name only // series, for consistency with wrapped parsers. if lblsWithMetricName.IsEmpty() { @@ -385,13 +385,13 @@ func (p *NHCBParser) processNHCB() bool { p.bytesNHCB = []byte(p.metricStringNHCB) p.lsetNHCB = p.tempLsetNHCB p.swapExemplars() - p.ctNHCB = p.tempCT + p.stNHCB = p.tempST p.state = stateEmitting } else { p.state = stateStart } p.tempNHCB.Reset() p.tempExemplarCount = 0 - p.tempCT = 0 + p.tempST = 0 return err == nil } diff --git a/vendor/github.com/prometheus/prometheus/model/textparse/openmetricslex.l.go b/vendor/github.com/prometheus/prometheus/model/textparse/openmetricslex.l.go index c0b2fcdb4d8..a99bb9df8ee 100644 --- a/vendor/github.com/prometheus/prometheus/model/textparse/openmetricslex.l.go +++ b/vendor/github.com/prometheus/prometheus/model/textparse/openmetricslex.l.go @@ -74,10 +74,10 @@ yystart1: yystate2: c = l.next() - switch { + switch c { default: goto yyabort - case c == ' ': + case ' ': goto yystate3 } @@ -101,43 +101,43 @@ yystate5: yystate6: c = l.next() yystart6: - switch { + switch c { default: goto yyabort - case c == 'E': + case 'E': goto yystate7 - case c == 'H': + case 'H': goto yystate11 - case c == 'T': + case 'T': goto yystate16 - case c == 'U': + case 'U': goto yystate21 } yystate7: c = l.next() - switch { + switch c { default: goto yyabort - case c == 'O': + case 'O': goto yystate8 } yystate8: c = l.next() - switch { + switch c { default: goto yyabort - case c == 'F': + case 'F': goto yystate9 } yystate9: c = l.next() - switch { + switch c { default: goto yyrule5 - case c == '\n': + case '\n': goto yystate10 } @@ -147,37 +147,37 @@ yystate10: yystate11: c = l.next() - switch { + switch c { default: goto yyabort - case c == 'E': + case 'E': goto yystate12 } yystate12: c = l.next() - switch { + switch c { default: goto yyabort - case c == 'L': + case 'L': goto yystate13 } yystate13: c = l.next() - switch { + switch c { default: goto yyabort - case c == 'P': + case 'P': goto yystate14 } yystate14: c = l.next() - switch { + switch c { default: goto yyabort - case c == ' ': + case ' ': goto yystate15 } @@ -187,37 +187,37 @@ yystate15: yystate16: c = l.next() - switch { + switch c { default: goto yyabort - case c == 'Y': + case 'Y': goto yystate17 } yystate17: c = l.next() - switch { + switch c { default: goto yyabort - case c == 'P': + case 'P': goto yystate18 } yystate18: c = l.next() - switch { + switch c { default: goto yyabort - case c == 'E': + case 'E': goto yystate19 } yystate19: c = l.next() - switch { + switch c { default: goto yyabort - case c == ' ': + case ' ': goto yystate20 } @@ -227,37 +227,37 @@ yystate20: yystate21: c = l.next() - switch { + switch c { default: goto yyabort - case c == 'N': + case 'N': goto yystate22 } yystate22: c = l.next() - switch { + switch c { default: goto yyabort - case c == 'I': + case 'I': goto yystate23 } yystate23: c = l.next() - switch { + switch c { default: goto yyabort - case c == 'T': + case 'T': goto yystate24 } yystate24: c = l.next() - switch { + switch c { default: goto yyabort - case c == ' ': + case ' ': goto yystate25 } @@ -315,10 +315,10 @@ yystate30: yystate31: c = l.next() yystart31: - switch { + switch c { default: goto yyabort - case c == ' ': + case ' ': goto yystate32 } @@ -405,10 +405,10 @@ yystate41: yystate42: c = l.next() yystart42: - switch { + switch c { default: goto yyabort - case c == '"': + case '"': goto yystate43 } @@ -441,12 +441,12 @@ yystate45: yystate46: c = l.next() yystart46: - switch { + switch c { default: goto yyabort - case c == ' ': + case ' ': goto yystate47 - case c == '{': + case '{': goto yystate49 } @@ -475,12 +475,12 @@ yystate49: yystate50: c = l.next() yystart50: - switch { + switch c { default: goto yyabort - case c == ' ': + case ' ': goto yystate52 - case c == '\n': + case '\n': goto yystate51 } @@ -521,10 +521,10 @@ yystate54: yystate55: c = l.next() - switch { + switch c { default: goto yyabort - case c == '{': + case '{': goto yystate56 } @@ -600,12 +600,12 @@ yystate64: yystate65: c = l.next() yystart65: - switch { + switch c { default: goto yyabort - case c == ' ': + case ' ': goto yystate66 - case c == '"': + case '"': goto yystate68 } @@ -656,12 +656,12 @@ yystate70: yystate71: c = l.next() yystart71: - switch { + switch c { default: goto yyabort - case c == ' ': + case ' ': goto yystate73 - case c == '\n': + case '\n': goto yystate72 } @@ -696,61 +696,61 @@ yyrule2: // HELP{S} { l.state = sMeta1 return tHelp - goto yystate0 + } yyrule3: // TYPE{S} { l.state = sMeta1 return tType - goto yystate0 + } yyrule4: // UNIT{S} { l.state = sMeta1 return tUnit - goto yystate0 + } yyrule5: // "EOF"\n? { l.state = sInit return tEOFWord - goto yystate0 + } yyrule6: // \"(\\.|[^\\"])*\" { l.state = sMeta2 return tMName - goto yystate0 + } yyrule7: // {M}({M}|{D})* { l.state = sMeta2 return tMName - goto yystate0 + } yyrule8: // {S}{C}*\n { l.state = sInit return tText - goto yystate0 + } yyrule9: // {M}({M}|{D})* { l.state = sValue return tMName - goto yystate0 + } yyrule10: // \{ { l.state = sLabels return tBraceOpen - goto yystate0 + } yyrule11: // \{ { l.state = sLabels return tBraceOpen - goto yystate0 + } yyrule12: // {L}({L}|{D})* { @@ -760,19 +760,19 @@ yyrule13: // \"(\\.|[^\\"])*\" { l.state = sLabels return tQString - goto yystate0 + } yyrule14: // \} { l.state = sValue return tBraceClose - goto yystate0 + } yyrule15: // = { l.state = sLValue return tEqual - goto yystate0 + } yyrule16: // , { @@ -782,13 +782,13 @@ yyrule17: // \"(\\.|[^\\"\n])*\" { l.state = sLabels return tLValue - goto yystate0 + } yyrule18: // {S}[^ \n]+ { l.state = sTimestamp return tValue - goto yystate0 + } yyrule19: // {S}[^ \n]+ { @@ -798,13 +798,13 @@ yyrule20: // \n { l.state = sInit return tLinebreak - goto yystate0 + } yyrule21: // {S}#{S}\{ { l.state = sExemplar return tComment - goto yystate0 + } yyrule22: // {L}({L}|{D})* { @@ -814,25 +814,25 @@ yyrule23: // \"(\\.|[^\\"\n])*\" { l.state = sExemplar return tQString - goto yystate0 + } yyrule24: // \} { l.state = sEValue return tBraceClose - goto yystate0 + } yyrule25: // = { l.state = sEValue return tEqual - goto yystate0 + } yyrule26: // \"(\\.|[^\\"\n])*\" { l.state = sExemplar return tLValue - goto yystate0 + } yyrule27: // , { @@ -842,7 +842,7 @@ yyrule28: // {S}[^ \n]+ { l.state = sETimestamp return tValue - goto yystate0 + } yyrule29: // {S}[^ \n]+ { @@ -852,7 +852,7 @@ yyrule30: // \n if true { // avoid go vet determining the below panic will not be reached l.state = sInit return tLinebreak - goto yystate0 + } panic("unreachable") diff --git a/vendor/github.com/prometheus/prometheus/model/textparse/openmetricsparse.go b/vendor/github.com/prometheus/prometheus/model/textparse/openmetricsparse.go index 4e592167f3d..207ceb45737 100644 --- a/vendor/github.com/prometheus/prometheus/model/textparse/openmetricsparse.go +++ b/vendor/github.com/prometheus/prometheus/model/textparse/openmetricsparse.go @@ -103,34 +103,34 @@ type OpenMetricsParser struct { hasExemplarTs bool // Created timestamp parsing state. - ct int64 - ctHashSet uint64 + st int64 + stHashSet uint64 // ignoreExemplar instructs the parser to not overwrite exemplars (to keep them while peeking ahead). ignoreExemplar bool // visitedMFName is the metric family name of the last visited metric when peeking ahead - // for _created series during the execution of the CreatedTimestamp method. + // for _created series during the execution of the StartTimestamp method. visitedMFName []byte - skipCTSeries bool + skipSTSeries bool enableTypeAndUnitLabels bool } type openMetricsParserOptions struct { - skipCTSeries bool + skipSTSeries bool enableTypeAndUnitLabels bool } type OpenMetricsOption func(*openMetricsParserOptions) -// WithOMParserCTSeriesSkipped turns off exposing _created lines +// WithOMParserSTSeriesSkipped turns off exposing _created lines // as series, which makes those only used for parsing created timestamp -// for `CreatedTimestamp` method purposes. +// for `StartTimestamp` method purposes. // // It's recommended to use this option to avoid using _created lines for other // purposes than created timestamp, but leave false by default for the // best-effort compatibility. -func WithOMParserCTSeriesSkipped() OpenMetricsOption { +func WithOMParserSTSeriesSkipped() OpenMetricsOption { return func(o *openMetricsParserOptions) { - o.skipCTSeries = true + o.skipSTSeries = true } } @@ -142,7 +142,7 @@ func WithOMParserTypeAndUnitLabels() OpenMetricsOption { } } -// NewOpenMetricsParser returns a new parser for the byte slice with option to skip CT series parsing. +// NewOpenMetricsParser returns a new parser for the byte slice with option to skip ST series parsing. func NewOpenMetricsParser(b []byte, st *labels.SymbolTable, opts ...OpenMetricsOption) Parser { options := &openMetricsParserOptions{} @@ -153,7 +153,7 @@ func NewOpenMetricsParser(b []byte, st *labels.SymbolTable, opts ...OpenMetricsO parser := &OpenMetricsParser{ l: &openMetricsLexer{b: b}, builder: labels.NewScratchBuilderWithSymbolTable(st, 16), - skipCTSeries: options.skipCTSeries, + skipSTSeries: options.skipSTSeries, enableTypeAndUnitLabels: options.enableTypeAndUnitLabels, } @@ -285,12 +285,12 @@ func (p *OpenMetricsParser) Exemplar(e *exemplar.Exemplar) bool { return true } -// CreatedTimestamp returns the created timestamp for a current Metric if exists or nil. +// StartTimestamp returns the created timestamp for a current Metric if exists or nil. // NOTE(Maniktherana): Might use additional CPU/mem resources due to deep copy of parser required for peeking given 1.0 OM specification on _created series. -func (p *OpenMetricsParser) CreatedTimestamp() int64 { - if !typeRequiresCT(p.mtype) { - // Not a CT supported metric type, fast path. - p.ctHashSet = 0 // Use ctHashSet as a single way of telling "empty cache" +func (p *OpenMetricsParser) StartTimestamp() int64 { + if !typeRequiresST(p.mtype) { + // Not a ST supported metric type, fast path. + p.stHashSet = 0 // Use stHashSet as a single way of telling "empty cache" return 0 } @@ -307,8 +307,8 @@ func (p *OpenMetricsParser) CreatedTimestamp() int64 { currHash := p.seriesHash(&buf, currName) // Check cache, perhaps we fetched something already. - if currHash == p.ctHashSet && p.ct > 0 { - return p.ct + if currHash == p.stHashSet && p.st > 0 { + return p.st } // Create a new lexer and other core state details to reset the parser once this function is done executing. @@ -322,7 +322,7 @@ func (p *OpenMetricsParser) CreatedTimestamp() int64 { resetStart := p.start resetMType := p.mtype - p.skipCTSeries = false + p.skipSTSeries = false p.ignoreExemplar = true defer func() { p.l = resetLexer @@ -334,38 +334,38 @@ func (p *OpenMetricsParser) CreatedTimestamp() int64 { for { eType, err := p.Next() if err != nil { - // This means p.Next() will give error too later on, so def no CT line found. - // This might result in partial scrape with wrong/missing CT, but only + // This means p.Next() will give error too later on, so def no ST line found. + // This might result in partial scrape with wrong/missing ST, but only // spec improvement would help. - // TODO: Make sure OM 1.1/2.0 pass CT via metadata or exemplar-like to avoid this. - p.resetCTParseValues() + // TODO: Make sure OM 1.1/2.0 pass ST via metadata or exemplar-like to avoid this. + p.resetSTParseValues() return 0 } if eType != EntrySeries { - // Assume we hit different family, no CT line found. - p.resetCTParseValues() + // Assume we hit different family, no ST line found. + p.resetSTParseValues() return 0 } peekedName := p.series[p.offsets[0]-p.start : p.offsets[1]-p.start] if len(peekedName) < 8 || string(peekedName[len(peekedName)-8:]) != "_created" { - // Not a CT line, search more. + // Not a ST line, search more. continue } // Remove _created suffix. peekedHash := p.seriesHash(&buf, peekedName[:len(peekedName)-8]) if peekedHash != currHash { - // Found CT line for a different series, for our series no CT. - p.resetCTParseValues() + // Found ST line for a different series, for our series no ST. + p.resetSTParseValues() return 0 } // All timestamps in OpenMetrics are Unix Epoch in seconds. Convert to milliseconds. // https://github.com/prometheus/OpenMetrics/blob/v1.0.0/specification/OpenMetrics.md#timestamps - ct := int64(p.val * 1000.0) - p.setCTParseValues(ct, currHash, currName, true) - return ct + st := int64(p.val * 1000.0) + p.setSTParseValues(st, currHash, currName, true) + return st } } @@ -404,23 +404,23 @@ func (p *OpenMetricsParser) seriesHash(offsetsArr *[]byte, metricFamilyName []by return hashedOffsets } -// setCTParseValues sets the parser to the state after CreatedTimestamp method was called and CT was found. -// This is useful to prevent re-parsing the same series again and early return the CT value. -func (p *OpenMetricsParser) setCTParseValues(ct int64, ctHashSet uint64, mfName []byte, skipCTSeries bool) { - p.ct = ct - p.ctHashSet = ctHashSet +// setSTParseValues sets the parser to the state after StartTimestamp method was called and ST was found. +// This is useful to prevent re-parsing the same series again and early return the ST value. +func (p *OpenMetricsParser) setSTParseValues(st int64, stHashSet uint64, mfName []byte, skipSTSeries bool) { + p.st = st + p.stHashSet = stHashSet p.visitedMFName = mfName - p.skipCTSeries = skipCTSeries // Do we need to set it? + p.skipSTSeries = skipSTSeries // Do we need to set it? } -// resetCTParseValues resets the parser to the state before CreatedTimestamp method was called. -func (p *OpenMetricsParser) resetCTParseValues() { - p.ctHashSet = 0 - p.skipCTSeries = true +// resetSTParseValues resets the parser to the state before StartTimestamp method was called. +func (p *OpenMetricsParser) resetSTParseValues() { + p.stHashSet = 0 + p.skipSTSeries = true } -// typeRequiresCT returns true if the metric type requires a _created timestamp. -func typeRequiresCT(t model.MetricType) bool { +// typeRequiresST returns true if the metric type requires a _created timestamp. +func typeRequiresST(t model.MetricType) bool { switch t { case model.MetricTypeCounter, model.MetricTypeSummary, model.MetricTypeHistogram: return true @@ -544,7 +544,7 @@ func (p *OpenMetricsParser) Next() (Entry, error) { if err := p.parseSeriesEndOfLine(p.nextToken()); err != nil { return EntryInvalid, err } - if p.skipCTSeries && p.isCreatedSeries() { + if p.skipSTSeries && p.isCreatedSeries() { return p.Next() } return EntrySeries, nil @@ -565,7 +565,7 @@ func (p *OpenMetricsParser) Next() (Entry, error) { if err := p.parseSeriesEndOfLine(t2); err != nil { return EntryInvalid, err } - if p.skipCTSeries && p.isCreatedSeries() { + if p.skipSTSeries && p.isCreatedSeries() { return p.Next() } return EntrySeries, nil @@ -697,7 +697,7 @@ func (p *OpenMetricsParser) parseLVals(offsets []int, isExemplar bool) ([]int, e func (p *OpenMetricsParser) isCreatedSeries() bool { metricName := p.series[p.offsets[0]-p.start : p.offsets[1]-p.start] // check length so the metric is longer than len("_created") - if typeRequiresCT(p.mtype) && len(metricName) >= 8 && string(metricName[len(metricName)-8:]) == "_created" { + if typeRequiresST(p.mtype) && len(metricName) >= 8 && string(metricName[len(metricName)-8:]) == "_created" { return true } return false @@ -773,7 +773,7 @@ func normalizeFloatsInLabelValues(t model.MetricType, l, v string) string { if (t == model.MetricTypeSummary && l == model.QuantileLabel) || (t == model.MetricTypeHistogram && l == model.BucketLabel) { f, err := strconv.ParseFloat(v, 64) if err == nil { - return formatOpenMetricsFloat(f) + return labels.FormatOpenMetricsFloat(f) } } return v diff --git a/vendor/github.com/prometheus/prometheus/model/textparse/promlex.l.go b/vendor/github.com/prometheus/prometheus/model/textparse/promlex.l.go index a083e5549b6..9ff5d6c9f86 100644 --- a/vendor/github.com/prometheus/prometheus/model/textparse/promlex.l.go +++ b/vendor/github.com/prometheus/prometheus/model/textparse/promlex.l.go @@ -92,10 +92,10 @@ yystate2: yystate3: c = l.next() - switch { + switch c { default: goto yyrule3 - case c == '\t' || c == ' ': + case '\t', ' ': goto yystate3 } @@ -105,19 +105,19 @@ yystate4: yystate5: c = l.next() - switch { + switch c { default: goto yyrule5 - case c == '\t' || c == ' ': + case '\t', ' ': goto yystate6 } yystate6: c = l.next() - switch { + switch c { default: goto yyrule4 - case c == '\t' || c == ' ': + case '\t', ' ': goto yystate6 } @@ -137,104 +137,104 @@ yystate8: yystate9: c = l.next() yystart9: - switch { + switch c { default: goto yyabort - case c == 'H': + case 'H': goto yystate10 - case c == 'T': + case 'T': goto yystate15 - case c == '\t' || c == ' ': + case '\t', ' ': goto yystate3 } yystate10: c = l.next() - switch { + switch c { default: goto yyabort - case c == 'E': + case 'E': goto yystate11 } yystate11: c = l.next() - switch { + switch c { default: goto yyabort - case c == 'L': + case 'L': goto yystate12 } yystate12: c = l.next() - switch { + switch c { default: goto yyabort - case c == 'P': + case 'P': goto yystate13 } yystate13: c = l.next() - switch { + switch c { default: goto yyabort - case c == '\t' || c == ' ': + case '\t', ' ': goto yystate14 } yystate14: c = l.next() - switch { + switch c { default: goto yyrule6 - case c == '\t' || c == ' ': + case '\t', ' ': goto yystate14 } yystate15: c = l.next() - switch { + switch c { default: goto yyabort - case c == 'Y': + case 'Y': goto yystate16 } yystate16: c = l.next() - switch { + switch c { default: goto yyabort - case c == 'P': + case 'P': goto yystate17 } yystate17: c = l.next() - switch { + switch c { default: goto yyabort - case c == 'E': + case 'E': goto yystate18 } yystate18: c = l.next() - switch { + switch c { default: goto yyabort - case c == '\t' || c == ' ': + case '\t', ' ': goto yystate19 } yystate19: c = l.next() - switch { + switch c { default: goto yyrule7 - case c == '\t' || c == ' ': + case '\t', ' ': goto yystate19 } @@ -389,12 +389,12 @@ yystate35: yystate36: c = l.next() yystart36: - switch { + switch c { default: goto yyabort - case c == '"': + case '"': goto yystate37 - case c == '\t' || c == ' ': + case '\t', ' ': goto yystate3 } @@ -486,7 +486,7 @@ yyrule2: // \n { l.state = sInit return tLinebreak - goto yystate0 + } yyrule3: // [ \t]+ { @@ -505,49 +505,49 @@ yyrule6: // HELP[\t ]+ { l.state = sMeta1 return tHelp - goto yystate0 + } yyrule7: // TYPE[\t ]+ { l.state = sMeta1 return tType - goto yystate0 + } yyrule8: // \"(\\.|[^\\"])*\" { l.state = sMeta2 return tMName - goto yystate0 + } yyrule9: // {M}({M}|{D})* { l.state = sMeta2 return tMName - goto yystate0 + } yyrule10: // {C}* { l.state = sInit return tText - goto yystate0 + } yyrule11: // {M}({M}|{D})* { l.state = sValue return tMName - goto yystate0 + } yyrule12: // \{ { l.state = sLabels return tBraceOpen - goto yystate0 + } yyrule13: // \{ { l.state = sLabels return tBraceOpen - goto yystate0 + } yyrule14: // {L}({L}|{D})* { @@ -557,19 +557,19 @@ yyrule15: // \"(\\.|[^\\"])*\" { l.state = sLabels return tQString - goto yystate0 + } yyrule16: // \} { l.state = sValue return tBraceClose - goto yystate0 + } yyrule17: // = { l.state = sLValue return tEqual - goto yystate0 + } yyrule18: // , { @@ -579,13 +579,13 @@ yyrule19: // \"(\\.|[^\\"])*\" { l.state = sLabels return tLValue - goto yystate0 + } yyrule20: // [^{ \t\n]+ { l.state = sTimestamp return tValue - goto yystate0 + } yyrule21: // {D}+ { @@ -595,7 +595,7 @@ yyrule22: // \n if true { // avoid go vet determining the below panic will not be reached l.state = sInit return tLinebreak - goto yystate0 + } panic("unreachable") diff --git a/vendor/github.com/prometheus/prometheus/model/textparse/promparse.go b/vendor/github.com/prometheus/prometheus/model/textparse/promparse.go index 2b4b750b4d7..4a75bcd8d8b 100644 --- a/vendor/github.com/prometheus/prometheus/model/textparse/promparse.go +++ b/vendor/github.com/prometheus/prometheus/model/textparse/promparse.go @@ -274,9 +274,9 @@ func (*PromParser) Exemplar(*exemplar.Exemplar) bool { return false } -// CreatedTimestamp returns 0 as it's not implemented yet. +// StartTimestamp returns 0 as it's not implemented yet. // TODO(bwplotka): https://github.com/prometheus/prometheus/issues/12980 -func (*PromParser) CreatedTimestamp() int64 { +func (*PromParser) StartTimestamp() int64 { return 0 } diff --git a/vendor/github.com/prometheus/prometheus/model/textparse/protobufparse.go b/vendor/github.com/prometheus/prometheus/model/textparse/protobufparse.go index 1b64a4d4903..a48aa4af69a 100644 --- a/vendor/github.com/prometheus/prometheus/model/textparse/protobufparse.go +++ b/vendor/github.com/prometheus/prometheus/model/textparse/protobufparse.go @@ -19,9 +19,6 @@ import ( "fmt" "io" "math" - "strconv" - "strings" - "sync" "unicode/utf8" "github.com/gogo/protobuf/types" @@ -35,15 +32,6 @@ import ( "github.com/prometheus/prometheus/util/convertnhcb" ) -// floatFormatBufPool is exclusively used in formatOpenMetricsFloat. -var floatFormatBufPool = sync.Pool{ - New: func() any { - // To contain at most 17 digits and additional syntax for a float64. - b := make([]byte, 0, 24) - return &b - }, -} - // ProtobufParser parses the old Prometheus protobuf format and present it // as the text-style textparse.Parser interface. // @@ -77,6 +65,8 @@ type ProtobufParser struct { // that we have to decode the next MetricDescriptor. state Entry + // Whether to completely ignore any native parts of histograms. + ignoreNativeHistograms bool // Whether to also parse a classic histogram that is also present as a // native histogram. parseClassicHistograms bool @@ -93,13 +83,20 @@ type ProtobufParser struct { } // NewProtobufParser returns a parser for the payload in the byte slice. -func NewProtobufParser(b []byte, parseClassicHistograms, convertClassicHistogramsToNHCB, enableTypeAndUnitLabels bool, st *labels.SymbolTable) Parser { +func NewProtobufParser( + b []byte, + ignoreNativeHistograms, parseClassicHistograms, convertClassicHistogramsToNHCB, enableTypeAndUnitLabels bool, + st *labels.SymbolTable, +) Parser { + builder := labels.NewScratchBuilderWithSymbolTable(st, 16) + builder.SetUnsafeAdd(true) return &ProtobufParser{ dec: dto.NewMetricStreamingDecoder(b), entryBytes: &bytes.Buffer{}, - builder: labels.NewScratchBuilderWithSymbolTable(st, 16), // TODO(bwplotka): Try base builder. + builder: builder, state: EntryInvalid, + ignoreNativeHistograms: ignoreNativeHistograms, parseClassicHistograms: parseClassicHistograms, enableTypeAndUnitLabels: enableTypeAndUnitLabels, convertClassicHistogramsToNHCB: convertClassicHistogramsToNHCB, @@ -194,7 +191,7 @@ func (p *ProtobufParser) Histogram() ([]byte, *int64, *histogram.Histogram, *his h = p.dec.GetHistogram() ) - if !isNativeHistogram(h) { + if p.ignoreNativeHistograms || !isNativeHistogram(h) { // This only happens if we have a classic histogram and // we converted it to NHCB already in Next. if *ts != 0 { @@ -402,24 +399,24 @@ func (p *ProtobufParser) Exemplar(ex *exemplar.Exemplar) bool { return true } -// CreatedTimestamp returns CT or 0 if CT is not present on counters, summaries or histograms. -func (p *ProtobufParser) CreatedTimestamp() int64 { - var ct *types.Timestamp +// StartTimestamp returns ST or 0 if ST is not present on counters, summaries or histograms. +func (p *ProtobufParser) StartTimestamp() int64 { + var st *types.Timestamp switch p.dec.GetType() { case dto.MetricType_COUNTER: - ct = p.dec.GetCounter().GetCreatedTimestamp() + st = p.dec.GetCounter().GetCreatedTimestamp() case dto.MetricType_SUMMARY: - ct = p.dec.GetSummary().GetCreatedTimestamp() + st = p.dec.GetSummary().GetCreatedTimestamp() case dto.MetricType_HISTOGRAM, dto.MetricType_GAUGE_HISTOGRAM: - ct = p.dec.GetHistogram().GetCreatedTimestamp() + st = p.dec.GetHistogram().GetCreatedTimestamp() default: } - if ct == nil { + if st == nil { return 0 } // Same as the gogo proto types.TimestampFromProto but straight to integer. // and without validation. - return ct.GetSeconds()*1e3 + int64(ct.GetNanos())/1e6 + return st.GetSeconds()*1e3 + int64(st.GetNanos())/1e6 } // Next advances the parser to the next "sample" (emulating the behavior of a @@ -468,16 +465,6 @@ func (p *ProtobufParser) Next() (Entry, error) { default: return EntryInvalid, fmt.Errorf("unknown metric type for metric %q: %s", name, p.dec.GetType()) } - unit := p.dec.GetUnit() - if len(unit) > 0 { - if p.dec.GetType() == dto.MetricType_COUNTER && strings.HasSuffix(name, "_total") { - if !strings.HasSuffix(name[:len(name)-6], unit) || len(name)-6 < len(unit)+1 || name[len(name)-6-len(unit)-1] != '_' { - return EntryInvalid, fmt.Errorf("unit %q not a suffix of counter %q", unit, name) - } - } else if !strings.HasSuffix(name, unit) || len(name) < len(unit)+1 || name[len(name)-len(unit)-1] != '_' { - return EntryInvalid, fmt.Errorf("unit %q not a suffix of metric %q", unit, name) - } - } p.entryBytes.Reset() p.entryBytes.WriteString(name) p.state = EntryHelp @@ -492,7 +479,7 @@ func (p *ProtobufParser) Next() (Entry, error) { case EntryType: t := p.dec.GetType() if t == dto.MetricType_HISTOGRAM || t == dto.MetricType_GAUGE_HISTOGRAM { - if !isNativeHistogram(p.dec.GetHistogram()) { + if p.ignoreNativeHistograms || !isNativeHistogram(p.dec.GetHistogram()) { p.state = EntrySeries p.fieldPos = -3 // We have not returned anything, let p.Next() increment it to -2. return p.Next() @@ -513,7 +500,8 @@ func (p *ProtobufParser) Next() (Entry, error) { t == dto.MetricType_GAUGE_HISTOGRAM { // Non-trivial series (complex metrics, with magic suffixes). - isClassicHistogram := (t == dto.MetricType_HISTOGRAM || t == dto.MetricType_GAUGE_HISTOGRAM) && !isNativeHistogram(p.dec.GetHistogram()) + isClassicHistogram := (t == dto.MetricType_HISTOGRAM || t == dto.MetricType_GAUGE_HISTOGRAM) && + (p.ignoreNativeHistograms || !isNativeHistogram(p.dec.GetHistogram())) skipSeries := p.convertClassicHistogramsToNHCB && isClassicHistogram && !p.parseClassicHistograms // Did we iterate over all the classic representations fields? @@ -589,10 +577,11 @@ func (p *ProtobufParser) Next() (Entry, error) { return EntryInvalid, err } - // If this is a metric family does not contain native - // histograms, it means we are here thanks to NHCB conversion. - // Return to classic histograms for the consistent flow. - if !isNativeHistogram(p.dec.GetHistogram()) { + // If this metric is not a native histograms or we are ignoring + // native histograms, it means we are here thanks to NHCB + // conversion. Return to classic histograms for the consistent + // flow. + if p.ignoreNativeHistograms || !isNativeHistogram(p.dec.GetHistogram()) { return switchToClassic() } @@ -622,10 +611,7 @@ func (p *ProtobufParser) onSeriesOrHistogramUpdate() error { Unit: p.dec.GetUnit(), } m.AddToLabels(&p.builder) - if err := p.dec.Label(schema.IgnoreOverriddenMetadataLabelsScratchBuilder{ - Overwrite: m, - ScratchBuilder: &p.builder, - }); err != nil { + if err := p.dec.Label(m.NewIgnoreOverriddenMetadataLabelScratchBuilder(&p.builder)); err != nil { return err } } else { @@ -690,7 +676,7 @@ func (p *ProtobufParser) getMagicLabel() (bool, string, string) { qq := p.dec.GetSummary().GetQuantile() q := qq[p.fieldPos] p.fieldsDone = p.fieldPos == len(qq)-1 - return true, model.QuantileLabel, formatOpenMetricsFloat(q.GetQuantile()) + return true, model.QuantileLabel, labels.FormatOpenMetricsFloat(q.GetQuantile()) case dto.MetricType_HISTOGRAM, dto.MetricType_GAUGE_HISTOGRAM: bb := p.dec.GetHistogram().GetBucket() if p.fieldPos >= len(bb) { @@ -699,41 +685,11 @@ func (p *ProtobufParser) getMagicLabel() (bool, string, string) { } b := bb[p.fieldPos] p.fieldsDone = math.IsInf(b.GetUpperBound(), +1) - return true, model.BucketLabel, formatOpenMetricsFloat(b.GetUpperBound()) + return true, model.BucketLabel, labels.FormatOpenMetricsFloat(b.GetUpperBound()) } return false, "", "" } -// formatOpenMetricsFloat works like the usual Go string formatting of a float -// but appends ".0" if the resulting number would otherwise contain neither a -// "." nor an "e". -func formatOpenMetricsFloat(f float64) string { - // A few common cases hardcoded. - switch { - case f == 1: - return "1.0" - case f == 0: - return "0.0" - case f == -1: - return "-1.0" - case math.IsNaN(f): - return "NaN" - case math.IsInf(f, +1): - return "+Inf" - case math.IsInf(f, -1): - return "-Inf" - } - bp := floatFormatBufPool.Get().(*[]byte) - defer floatFormatBufPool.Put(bp) - - *bp = strconv.AppendFloat((*bp)[:0], f, 'g', -1, 64) - if bytes.ContainsAny(*bp, "e.") { - return string(*bp) - } - *bp = append(*bp, '.', '0') - return string(*bp) -} - // isNativeHistogram returns false iff the provided histograms has no spans at // all (neither positive nor negative) and a zero threshold of 0 and a zero // count of 0. In principle, this could still be meant to be a native histogram diff --git a/vendor/github.com/prometheus/prometheus/prompb/io/prometheus/client/decoder.go b/vendor/github.com/prometheus/prometheus/prompb/io/prometheus/client/decoder.go index 2f3b1ddee53..6bc9600ab68 100644 --- a/vendor/github.com/prometheus/prometheus/prompb/io/prometheus/client/decoder.go +++ b/vendor/github.com/prometheus/prometheus/prompb/io/prometheus/client/decoder.go @@ -154,17 +154,24 @@ func (*MetricStreamingDecoder) GetLabel() { panic("don't use GetLabel, use Label instead") } -type scratchBuilder interface { +// unsafeLabelAdder adds labels for a single metric. +// The "unsafe" word highlights that some strings must not be retained on a +// caller side. When used with labels.ScratchBuilder ensure it's used +// with SetUnsafeAdd set to true. +type unsafeLabelAdder interface { Add(name, value string) - UnsafeAddBytes(name, value []byte) } -// Label parses labels into labels scratch builder. Metric name is missing +// Label parses labels into unsafeLabelAdder. Metric name is missing // given the protobuf metric model and has to be deduced from the metric family name. -// TODO: The method name intentionally hide MetricStreamingDecoder.Metric.Label +// +// TODO: The Label method name intentionally hide MetricStreamingDecoder.Metric.Label // field to avoid direct use (it's not parsed). In future generator will generate // structs tailored for streaming decoding. -func (m *MetricStreamingDecoder) Label(b scratchBuilder) error { +// +// Unsafe in this context means that bytes and strings are reused across iterations. +// They are live only until the next NextMetric() or NextMetricFamily() call. +func (m *MetricStreamingDecoder) Label(b unsafeLabelAdder) error { for _, l := range m.labels { if err := parseLabel(m.mData[l.start:l.end], b); err != nil { return err @@ -173,11 +180,9 @@ func (m *MetricStreamingDecoder) Label(b scratchBuilder) error { return nil } -// parseLabel is essentially LabelPair.Unmarshal but directly adding into scratch builder -// via UnsafeAddBytes method to reuse strings. -func parseLabel(dAtA []byte, b scratchBuilder) error { - var name, value []byte - var unsafeName string +// parseLabel is essentially LabelPair.Unmarshal but directly adding into unsafeLabelAdder. +func parseLabel(dAtA []byte, b unsafeLabelAdder) error { + var unsafeName, unsafeValue string l := len(dAtA) iNdEx := 0 for iNdEx < l { @@ -236,8 +241,7 @@ func parseLabel(dAtA []byte, b scratchBuilder) error { if postIndex > l { return io.ErrUnexpectedEOF } - name = dAtA[iNdEx:postIndex] - unsafeName = yoloString(name) + unsafeName = yoloString(dAtA[iNdEx:postIndex]) if !model.UTF8Validation.IsValidLabelName(unsafeName) { return fmt.Errorf("invalid label name: %s", unsafeName) } @@ -272,9 +276,9 @@ func parseLabel(dAtA []byte, b scratchBuilder) error { if postIndex > l { return io.ErrUnexpectedEOF } - value = dAtA[iNdEx:postIndex] - if !utf8.ValidString(yoloString(value)) { - return fmt.Errorf("invalid label value: %s", value) + unsafeValue = yoloString(dAtA[iNdEx:postIndex]) + if !utf8.ValidString(unsafeValue) { + return fmt.Errorf("invalid label value: %s", unsafeValue) } iNdEx = postIndex default: @@ -295,7 +299,7 @@ func parseLabel(dAtA []byte, b scratchBuilder) error { if iNdEx > l { return io.ErrUnexpectedEOF } - b.UnsafeAddBytes(name, value) + b.Add(unsafeName, unsafeValue) return nil } diff --git a/vendor/github.com/prometheus/prometheus/prompb/io/prometheus/client/metrics.proto b/vendor/github.com/prometheus/prometheus/prompb/io/prometheus/client/metrics.proto index fe55638bb78..681554a7caf 100644 --- a/vendor/github.com/prometheus/prometheus/prompb/io/prometheus/client/metrics.proto +++ b/vendor/github.com/prometheus/prometheus/prompb/io/prometheus/client/metrics.proto @@ -81,8 +81,7 @@ message Histogram { google.protobuf.Timestamp created_timestamp = 15; - // Everything below here is for native histograms (also known as sparse histograms). - // Native histograms are an experimental feature without stability guarantees. + // Everything below here is for native histograms (formerly known as sparse histograms). // schema defines the bucket schema. Currently, valid numbers are -4 <= n <= 8. // They are all for base-2 bucket schemas, where 1 is a bucket boundary in each case, and diff --git a/vendor/github.com/prometheus/prometheus/promql/engine.go b/vendor/github.com/prometheus/prometheus/promql/engine.go index 31d910da9ac..5a08da121cd 100644 --- a/vendor/github.com/prometheus/prometheus/promql/engine.go +++ b/vendor/github.com/prometheus/prometheus/promql/engine.go @@ -49,6 +49,7 @@ import ( "github.com/prometheus/prometheus/storage" "github.com/prometheus/prometheus/tsdb/chunkenc" "github.com/prometheus/prometheus/util/annotations" + "github.com/prometheus/prometheus/util/features" "github.com/prometheus/prometheus/util/logging" "github.com/prometheus/prometheus/util/stats" "github.com/prometheus/prometheus/util/zeropool" @@ -76,15 +77,19 @@ const ( ) type engineMetrics struct { - currentQueries prometheus.Gauge - maxConcurrentQueries prometheus.Gauge - queryLogEnabled prometheus.Gauge - queryLogFailures prometheus.Counter - queryQueueTime prometheus.Observer - queryPrepareTime prometheus.Observer - queryInnerEval prometheus.Observer - queryResultSort prometheus.Observer - querySamples prometheus.Counter + currentQueries prometheus.Gauge + maxConcurrentQueries prometheus.Gauge + queryLogEnabled prometheus.Gauge + queryLogFailures prometheus.Counter + queryQueueTime prometheus.Observer + queryQueueTimeHistogram prometheus.Observer + queryPrepareTime prometheus.Observer + queryPrepareTimeHistogram prometheus.Observer + queryInnerEval prometheus.Observer + queryInnerEvalHistogram prometheus.Observer + queryResultSort prometheus.Observer + queryResultSortHistogram prometheus.Observer + querySamples prometheus.Counter } type ( @@ -326,6 +331,9 @@ type EngineOpts struct { EnableDelayedNameRemoval bool // EnableTypeAndUnitLabels will allow PromQL Engine to make decisions based on the type and unit labels. EnableTypeAndUnitLabels bool + + // FeatureRegistry is the registry for tracking enabled/disabled features. + FeatureRegistry features.Collector } // Engine handles the lifetime of queries from beginning to end. @@ -363,6 +371,19 @@ func NewEngine(opts EngineOpts) *Engine { []string{"slice"}, ) + queryResultHistogram := prometheus.NewHistogramVec(prometheus.HistogramOpts{ + Namespace: namespace, + Subsystem: subsystem, + Name: "query_duration_histogram_seconds", + Help: "The duration of various parts of PromQL query execution.", + Buckets: []float64{.01, .1, 1, 10}, + NativeHistogramBucketFactor: 1.1, + NativeHistogramMaxBucketNumber: 100, + NativeHistogramMinResetDuration: 1 * time.Hour, + }, + []string{"slice"}, + ) + metrics := &engineMetrics{ currentQueries: prometheus.NewGauge(prometheus.GaugeOpts{ Namespace: namespace, @@ -394,10 +415,14 @@ func NewEngine(opts EngineOpts) *Engine { Name: "query_samples_total", Help: "The total number of samples loaded by all queries.", }), - queryQueueTime: queryResultSummary.WithLabelValues("queue_time"), - queryPrepareTime: queryResultSummary.WithLabelValues("prepare_time"), - queryInnerEval: queryResultSummary.WithLabelValues("inner_eval"), - queryResultSort: queryResultSummary.WithLabelValues("result_sort"), + queryQueueTime: queryResultSummary.WithLabelValues("queue_time"), + queryQueueTimeHistogram: queryResultHistogram.WithLabelValues("queue_time"), + queryPrepareTime: queryResultSummary.WithLabelValues("prepare_time"), + queryPrepareTimeHistogram: queryResultHistogram.WithLabelValues("prepare_time"), + queryInnerEval: queryResultSummary.WithLabelValues("inner_eval"), + queryInnerEvalHistogram: queryResultHistogram.WithLabelValues("inner_eval"), + queryResultSort: queryResultSummary.WithLabelValues("result_sort"), + queryResultSortHistogram: queryResultHistogram.WithLabelValues("result_sort"), } if t := opts.ActiveQueryTracker; t != nil { @@ -421,9 +446,22 @@ func NewEngine(opts EngineOpts) *Engine { metrics.queryLogFailures, metrics.querySamples, queryResultSummary, + queryResultHistogram, ) } + if r := opts.FeatureRegistry; r != nil { + r.Set(features.PromQL, "at_modifier", opts.EnableAtModifier) + r.Set(features.PromQL, "negative_offset", opts.EnableNegativeOffset) + r.Set(features.PromQL, "per_step_stats", opts.EnablePerStepStats) + r.Set(features.PromQL, "delayed_name_removal", opts.EnableDelayedNameRemoval) + r.Set(features.PromQL, "type_and_unit_labels", opts.EnableTypeAndUnitLabels) + r.Enable(features.PromQL, "per_query_lookback_delta") + r.Enable(features.PromQL, "subqueries") + + parser.RegisterFeatures(r) + } + return &Engine{ timeout: opts.Timeout, logger: opts.Logger, @@ -701,7 +739,7 @@ func (ng *Engine) queueActive(ctx context.Context, q *query) (func(), error) { if ng.activeQueryTracker == nil { return func() {}, nil } - queueSpanTimer, _ := q.stats.GetSpanTimer(ctx, stats.ExecQueueTime, ng.metrics.queryQueueTime) + queueSpanTimer, _ := q.stats.GetSpanTimer(ctx, stats.ExecQueueTime, ng.metrics.queryQueueTime, ng.metrics.queryQueueTimeHistogram) queryIndex, err := ng.activeQueryTracker.Insert(ctx, q.q) queueSpanTimer.Finish() return func() { ng.activeQueryTracker.Delete(queryIndex) }, err @@ -717,7 +755,7 @@ func durationMilliseconds(d time.Duration) int64 { // execEvalStmt evaluates the expression of an evaluation statement for the given time range. func (ng *Engine) execEvalStmt(ctx context.Context, query *query, s *parser.EvalStmt) (parser.Value, annotations.Annotations, error) { - prepareSpanTimer, ctxPrepare := query.stats.GetSpanTimer(ctx, stats.QueryPreparationTime, ng.metrics.queryPrepareTime) + prepareSpanTimer, ctxPrepare := query.stats.GetSpanTimer(ctx, stats.QueryPreparationTime, ng.metrics.queryPrepareTime, ng.metrics.queryPrepareTimeHistogram) mint, maxt := FindMinMaxTime(s) querier, err := query.queryable.Querier(mint, maxt) if err != nil { @@ -732,7 +770,7 @@ func (ng *Engine) execEvalStmt(ctx context.Context, query *query, s *parser.Eval // Modify the offset of vector and matrix selectors for the @ modifier // w.r.t. the start time since only 1 evaluation will be done on them. setOffsetForAtModifier(timeMilliseconds(s.Start), s.Expr) - evalSpanTimer, ctxInnerEval := query.stats.GetSpanTimer(ctx, stats.InnerEvalTime, ng.metrics.queryInnerEval) + evalSpanTimer, ctxInnerEval := query.stats.GetSpanTimer(ctx, stats.InnerEvalTime, ng.metrics.queryInnerEval, ng.metrics.queryInnerEvalHistogram) // Instant evaluation. This is executed as a range evaluation with one step. if s.Start.Equal(s.End) && s.Interval == 0 { start := timeMilliseconds(s.Start) @@ -835,7 +873,7 @@ func (ng *Engine) execEvalStmt(ctx context.Context, query *query, s *parser.Eval } func (ng *Engine) sortMatrixResult(ctx context.Context, query *query, mat Matrix) { - sortSpanTimer, _ := query.stats.GetSpanTimer(ctx, stats.ResultSortTime, ng.metrics.queryResultSort) + sortSpanTimer, _ := query.stats.GetSpanTimer(ctx, stats.ResultSortTime, ng.metrics.queryResultSort, ng.metrics.queryResultSortHistogram) sort.Sort(mat) sortSpanTimer.Finish() } @@ -1137,15 +1175,20 @@ func (ev *evaluator) Eval(ctx context.Context, expr parser.Expr) (v parser.Value v, ws = ev.eval(ctx, expr) if ev.enableDelayedNameRemoval { - ev.cleanupMetricLabels(v) + v = ev.cleanupMetricLabels(v) } return v, ws, nil } // EvalSeriesHelper stores extra information about a series. type EvalSeriesHelper struct { - // Used to map left-hand to right-hand in binary operations. - signature string + // Ordinal number of join signature, used to map left-hand to right-hand in + // binary operations. For example given the following series, if + // the join signature is job, instance then: + // metric{job="a", instance="1", other="x"} -> sigOrdinal 0 + // metric{job="a", instance="1", other="y"} -> sigOrdinal 0 + // metric{job="a", instance="2", other="x"} -> sigOrdinal 1 + sigOrdinal int } // EvalNodeHelper stores extra information and caches for evaluating a single node across steps. @@ -1165,9 +1208,13 @@ type EvalNodeHelper struct { lblResultBuf []byte // For binary vector matching. - rightSigs map[string]Sample - matchedSigs map[string]map[uint64]struct{} + rightSigs map[int]Sample + matchedSigs map[int]map[uint64]struct{} resultMetric map[string]labels.Labels + numSigs int + + // For info series matching. + rightStrSigs map[string]Sample // Additional options for the evaluation. enableDelayedNameRemoval bool @@ -1250,13 +1297,14 @@ func (enh *EvalNodeHelper) resetHistograms(inVec Vector, arg parser.Expr) annota // the given funcCall with the values computed for each expression at that // step. The return value is the combination into time series of all the // function call results. -// The prepSeries function (if provided) can be used to prepare the helper +// The matching (if provided) can be used to prepare the helper // for each series, then passed to each call funcCall. -func (ev *evaluator) rangeEval(ctx context.Context, prepSeries func(labels.Labels, *EvalSeriesHelper), funcCall func([]Vector, Matrix, [][]EvalSeriesHelper, *EvalNodeHelper) (Vector, annotations.Annotations), exprs ...parser.Expr) (Matrix, annotations.Annotations) { +func (ev *evaluator) rangeEval(ctx context.Context, matching *parser.VectorMatching, funcCall func([]Vector, Matrix, [][]EvalSeriesHelper, *EvalNodeHelper) (Vector, annotations.Annotations), exprs ...parser.Expr) (Matrix, annotations.Annotations) { numSteps := int((ev.endTimestamp-ev.startTimestamp)/ev.interval) + 1 matrixes := make([]Matrix, len(exprs)) origMatrixes := make([]Matrix, len(exprs)) originalNumSamples := ev.currentSamples + useSignatures := matching != nil var warnings annotations.Annotations for i, e := range exprs { @@ -1297,18 +1345,46 @@ func (ev *evaluator) rangeEval(ctx context.Context, prepSeries func(labels.Label bufHelpers [][]EvalSeriesHelper // Buffer updated on each step ) - // If the series preparation function is provided, we should run it for - // every single series in the matrix. - if prepSeries != nil { + if useSignatures { + var ( + // Function to compute the join signature for each series. + sigf func(labels.Labels) string + buf = make([]byte, 0, 1024) + names = slices.Clone(matching.MatchingLabels) + ) + if matching.On { + slices.Sort(names) + sigf = func(lset labels.Labels) string { + return string(lset.BytesWithLabels(buf, names...)) + } + } else { // "without" + names = append([]string{labels.MetricName}, names...) + slices.Sort(names) + sigf = func(lset labels.Labels) string { + return string(lset.BytesWithoutLabels(buf, names...)) + } + } + seriesHelpers = make([][]EvalSeriesHelper, len(exprs)) bufHelpers = make([][]EvalSeriesHelper, len(exprs)) + signatureToOrdinal := make(map[string]int) + for i := range exprs { seriesHelpers[i] = make([]EvalSeriesHelper, len(matrixes[i])) bufHelpers[i] = make([]EvalSeriesHelper, len(matrixes[i])) for si, series := range matrixes[i] { - prepSeries(series.Metric, &seriesHelpers[i][si]) + strSig := sigf(series.Metric) + + if sigOrd, ok := signatureToOrdinal[strSig]; ok { + seriesHelpers[i][si] = EvalSeriesHelper{sigOrdinal: sigOrd} + continue + } + + signatureToOrdinal[strSig] = enh.numSigs + seriesHelpers[i][si] = EvalSeriesHelper{sigOrdinal: enh.numSigs} + enh.numSigs++ } } } @@ -1323,12 +1399,12 @@ func (ev *evaluator) rangeEval(ctx context.Context, prepSeries func(labels.Label for i := range exprs { var bh []EvalSeriesHelper var sh []EvalSeriesHelper - if prepSeries != nil { + if useSignatures { bh = bufHelpers[i][:0] sh = seriesHelpers[i] } vectors[i], bh = ev.gatherVector(ts, matrixes[i], vectors[i], bh, sh) - if prepSeries != nil { + if useSignatures { bufHelpers[i] = bh } } @@ -2115,8 +2191,8 @@ func (ev *evaluator) eval(ctx context.Context, expr parser.Expr) (parser.Value, mat[i].Histograms[j].H = mat[i].Histograms[j].H.Copy().Mul(-1) } } - if !ev.enableDelayedNameRemoval && mat.ContainsSameLabelset() { - ev.errorf("vector cannot contain metrics with the same labelset") + if !ev.enableDelayedNameRemoval { + mat = ev.mergeSeriesWithSameLabelset(mat) } } return mat, ws @@ -2129,27 +2205,21 @@ func (ev *evaluator) eval(ctx context.Context, expr parser.Expr) (parser.Value, return append(enh.Out, Sample{F: val}), nil }, e.LHS, e.RHS) case lt == parser.ValueTypeVector && rt == parser.ValueTypeVector: - // Function to compute the join signature for each series. - buf := make([]byte, 0, 1024) - sigf := signatureFunc(e.VectorMatching.On, buf, e.VectorMatching.MatchingLabels...) - initSignatures := func(series labels.Labels, h *EvalSeriesHelper) { - h.signature = sigf(series) - } switch e.Op { case parser.LAND: - return ev.rangeEval(ctx, initSignatures, func(v []Vector, _ Matrix, sh [][]EvalSeriesHelper, enh *EvalNodeHelper) (Vector, annotations.Annotations) { + return ev.rangeEval(ctx, e.VectorMatching, func(v []Vector, _ Matrix, sh [][]EvalSeriesHelper, enh *EvalNodeHelper) (Vector, annotations.Annotations) { return ev.VectorAnd(v[0], v[1], e.VectorMatching, sh[0], sh[1], enh), nil }, e.LHS, e.RHS) case parser.LOR: - return ev.rangeEval(ctx, initSignatures, func(v []Vector, _ Matrix, sh [][]EvalSeriesHelper, enh *EvalNodeHelper) (Vector, annotations.Annotations) { + return ev.rangeEval(ctx, e.VectorMatching, func(v []Vector, _ Matrix, sh [][]EvalSeriesHelper, enh *EvalNodeHelper) (Vector, annotations.Annotations) { return ev.VectorOr(v[0], v[1], e.VectorMatching, sh[0], sh[1], enh), nil }, e.LHS, e.RHS) case parser.LUNLESS: - return ev.rangeEval(ctx, initSignatures, func(v []Vector, _ Matrix, sh [][]EvalSeriesHelper, enh *EvalNodeHelper) (Vector, annotations.Annotations) { + return ev.rangeEval(ctx, e.VectorMatching, func(v []Vector, _ Matrix, sh [][]EvalSeriesHelper, enh *EvalNodeHelper) (Vector, annotations.Annotations) { return ev.VectorUnless(v[0], v[1], e.VectorMatching, sh[0], sh[1], enh), nil }, e.LHS, e.RHS) default: - return ev.rangeEval(ctx, initSignatures, func(v []Vector, _ Matrix, sh [][]EvalSeriesHelper, enh *EvalNodeHelper) (Vector, annotations.Annotations) { + return ev.rangeEval(ctx, e.VectorMatching, func(v []Vector, _ Matrix, sh [][]EvalSeriesHelper, enh *EvalNodeHelper) (Vector, annotations.Annotations) { vec, err := ev.VectorBinop(e.Op, v[0], v[1], e.VectorMatching, e.ReturnBool, sh[0], sh[1], enh, e.PositionRange()) return vec, handleVectorBinopError(err, e) }, e.LHS, e.RHS) @@ -2310,7 +2380,7 @@ func reuseOrGetHPointSlices(prevSS *Series, numSteps int) (r []HPoint) { if prevSS != nil && cap(prevSS.Histograms)-2*len(prevSS.Histograms) > 0 { r = prevSS.Histograms[len(prevSS.Histograms):] prevSS.Histograms = prevSS.Histograms[0:len(prevSS.Histograms):len(prevSS.Histograms)] - return + return r } return getHPointSlice(numSteps) @@ -2322,7 +2392,7 @@ func reuseOrGetFPointSlices(prevSS *Series, numSteps int) (r []FPoint) { if prevSS != nil && cap(prevSS.Floats)-2*len(prevSS.Floats) > 0 { r = prevSS.Floats[len(prevSS.Floats):] prevSS.Floats = prevSS.Floats[0:len(prevSS.Floats):len(prevSS.Floats)] - return + return r } return getFPointSlice(numSteps) @@ -2720,16 +2790,15 @@ func (*evaluator) VectorAnd(lhs, rhs Vector, matching *parser.VectorMatching, lh return nil // Short-circuit: AND with nothing is nothing. } - // The set of signatures for the right-hand side Vector. - rightSigs := map[string]struct{}{} - // Add all rhs samples to a map so we can easily find matches later. + // Ordinals of signatures present on the right-hand side. + rightSigOrdinalsPresent := make([]bool, enh.numSigs) for _, sh := range rhsh { - rightSigs[sh.signature] = struct{}{} + rightSigOrdinalsPresent[sh.sigOrdinal] = true } for i, ls := range lhs { // If there's a matching entry in the right-hand side Vector, add the sample. - if _, ok := rightSigs[lhsh[i].signature]; ok { + if rightSigOrdinalsPresent[lhsh[i].sigOrdinal] { enh.Out = append(enh.Out, ls) } } @@ -2748,15 +2817,15 @@ func (*evaluator) VectorOr(lhs, rhs Vector, matching *parser.VectorMatching, lhs return enh.Out } - leftSigs := map[string]struct{}{} + leftSigOrdinalsPresent := make([]bool, enh.numSigs) // Add everything from the left-hand-side Vector. for i, ls := range lhs { - leftSigs[lhsh[i].signature] = struct{}{} + leftSigOrdinalsPresent[lhsh[i].sigOrdinal] = true enh.Out = append(enh.Out, ls) } // Add all right-hand side elements which have not been added from the left-hand side. for j, rs := range rhs { - if _, ok := leftSigs[rhsh[j].signature]; !ok { + if !leftSigOrdinalsPresent[rhsh[j].sigOrdinal] { enh.Out = append(enh.Out, rs) } } @@ -2774,13 +2843,14 @@ func (*evaluator) VectorUnless(lhs, rhs Vector, matching *parser.VectorMatching, return enh.Out } - rightSigs := map[string]struct{}{} + // Ordinals of signatures present on the right-hand side. + rightSigOrdinalsPresent := make([]bool, enh.numSigs) for _, sh := range rhsh { - rightSigs[sh.signature] = struct{}{} + rightSigOrdinalsPresent[sh.sigOrdinal] = true } for i, ls := range lhs { - if _, ok := rightSigs[lhsh[i].signature]; !ok { + if !rightSigOrdinalsPresent[lhsh[i].sigOrdinal] { enh.Out = append(enh.Out, ls) } } @@ -2804,22 +2874,20 @@ func (ev *evaluator) VectorBinop(op parser.ItemType, lhs, rhs Vector, matching * lhsh, rhsh = rhsh, lhsh } - // All samples from the rhs hashed by the matching label/values. + // All samples from the rhs by their join signature ordinal. if enh.rightSigs == nil { - enh.rightSigs = make(map[string]Sample, len(enh.Out)) + enh.rightSigs = make(map[int]Sample, len(enh.Out)) } else { - for k := range enh.rightSigs { - delete(enh.rightSigs, k) - } + clear(enh.rightSigs) } rightSigs := enh.rightSigs // Add all rhs samples to a map so we can easily find matches later. for i, rs := range rhs { - sig := rhsh[i].signature + sigOrd := rhsh[i].sigOrdinal // The rhs is guaranteed to be the 'one' side. Having multiple samples // with the same signature means that the matching is many-to-many. - if duplSample, found := rightSigs[sig]; found { + if duplSample, found := rightSigs[sigOrd]; found { // oneSide represents which side of the vector represents the 'one' in the many-to-one relationship. oneSide := "right" if matching.Card == parser.CardOneToMany { @@ -2830,17 +2898,15 @@ func (ev *evaluator) VectorBinop(op parser.ItemType, lhs, rhs Vector, matching * ev.errorf("found duplicate series for the match group %s on the %s hand-side of the operation: [%s, %s]"+ ";many-to-many matching not allowed: matching labels must be unique on one side", matchedLabels.String(), oneSide, rs.Metric.String(), duplSample.Metric.String()) } - rightSigs[sig] = rs + rightSigs[sigOrd] = rs } - // Tracks the match-signature. For one-to-one operations the value is nil. For many-to-one - // the value is a set of signatures to detect duplicated result elements. + // Tracks the matching by signature ordinals. For one-to-one operations the value is nil. + // For many-to-one the value is a set of hashes to detect duplicated result elements. if enh.matchedSigs == nil { - enh.matchedSigs = make(map[string]map[uint64]struct{}, len(rightSigs)) + enh.matchedSigs = make(map[int]map[uint64]struct{}, len(rightSigs)) } else { - for k := range enh.matchedSigs { - delete(enh.matchedSigs, k) - } + clear(enh.matchedSigs) } matchedSigs := enh.matchedSigs @@ -2848,9 +2914,9 @@ func (ev *evaluator) VectorBinop(op parser.ItemType, lhs, rhs Vector, matching * // the binary operation. var lastErr error for i, ls := range lhs { - sig := lhsh[i].signature + sigOrd := lhsh[i].sigOrdinal - rs, found := rightSigs[sig] // Look for a match in the rhs Vector. + rs, found := rightSigs[sigOrd] // Look for a match in the rhs Vector. if !found { continue } @@ -2862,32 +2928,33 @@ func (ev *evaluator) VectorBinop(op parser.ItemType, lhs, rhs Vector, matching * fl, fr = fr, fl hl, hr = hr, hl } - floatValue, histogramValue, keep, err := vectorElemBinop(op, fl, fr, hl, hr, pos) + floatValue, histogramValue, keep, info, err := vectorElemBinop(op, fl, fr, hl, hr, pos) if err != nil { lastErr = err continue } - switch { - case returnBool: + if info != nil { + lastErr = info + } + if returnBool { histogramValue = nil if keep { floatValue = 1.0 } else { floatValue = 0.0 } - case !keep: - continue } + metric := resultMetric(ls.Metric, rs.Metric, op, matching, enh) if !ev.enableDelayedNameRemoval && returnBool { metric = metric.DropReserved(schema.IsMetadataLabel) } - insertedSigs, exists := matchedSigs[sig] + insertedSigs, exists := matchedSigs[sigOrd] if matching.Card == parser.CardOneToOne { if exists { ev.errorf("multiple matches for labels: many-to-one matching must be explicit (group_left/group_right)") } - matchedSigs[sig] = nil // Set existence to true. + matchedSigs[sigOrd] = nil // Set existence to true. } else { // In many-to-one matching the grouping labels have to ensure a unique metric // for the result Vector. Check whether those labels have already been added for @@ -2896,13 +2963,17 @@ func (ev *evaluator) VectorBinop(op parser.ItemType, lhs, rhs Vector, matching * if !exists { insertedSigs = map[uint64]struct{}{} - matchedSigs[sig] = insertedSigs + matchedSigs[sigOrd] = insertedSigs } else if _, duplicate := insertedSigs[insertSig]; duplicate { ev.errorf("multiple matches for labels: grouping labels must ensure unique matches") } insertedSigs[insertSig] = struct{}{} } + if !keep && !returnBool { + continue + } + enh.Out = append(enh.Out, Sample{ Metric: metric, F: floatValue, @@ -2913,20 +2984,6 @@ func (ev *evaluator) VectorBinop(op parser.ItemType, lhs, rhs Vector, matching * return enh.Out, lastErr } -func signatureFunc(on bool, b []byte, names ...string) func(labels.Labels) string { - if on { - slices.Sort(names) - return func(lset labels.Labels) string { - return string(lset.BytesWithLabels(b, names...)) - } - } - names = append([]string{labels.MetricName}, names...) - slices.Sort(names) - return func(lset labels.Labels) string { - return string(lset.BytesWithoutLabels(b, names...)) - } -} - // resultMetric returns the metric for the given sample(s) based on the Vector // binary operation and the matching options. func resultMetric(lhs, rhs labels.Labels, op parser.ItemType, matching *parser.VectorMatching, enh *EvalNodeHelper) labels.Labels { @@ -2934,7 +2991,6 @@ func resultMetric(lhs, rhs labels.Labels, op parser.ItemType, matching *parser.V enh.resultMetric = make(map[string]labels.Labels, len(enh.Out)) } - enh.resetBuilder(lhs) buf := bytes.NewBuffer(enh.lblResultBuf[:0]) enh.lblBuf = lhs.Bytes(enh.lblBuf) buf.Write(enh.lblBuf) @@ -2947,6 +3003,7 @@ func resultMetric(lhs, rhs labels.Labels, op parser.ItemType, matching *parser.V } str := string(enh.lblResultBuf) + enh.resetBuilder(lhs) if changesMetricSchema(op) { // Setting empty Metadata causes the deletion of those if they exists. schema.Metadata{}.SetToLabels(enh.lb) @@ -2986,7 +3043,7 @@ func (ev *evaluator) VectorscalarBinop(op parser.ItemType, lhs Vector, rhs Scala lf, rf = rf, lf lh, rh = rh, lh } - float, histogram, keep, err := vectorElemBinop(op, lf, rf, lh, rh, pos) + float, histogram, keep, _, err := vectorElemBinop(op, lf, rf, lh, rh, pos) if err != nil && !errors.Is(err, annotations.PromQLWarning) { lastErr = err continue @@ -3054,89 +3111,97 @@ func scalarBinop(op parser.ItemType, lhs, rhs float64) float64 { } // vectorElemBinop evaluates a binary operation between two Vector elements. -func vectorElemBinop(op parser.ItemType, lhs, rhs float64, hlhs, hrhs *histogram.FloatHistogram, pos posrange.PositionRange) (float64, *histogram.FloatHistogram, bool, error) { - opName := parser.ItemTypeStr[op] +func vectorElemBinop(op parser.ItemType, lhs, rhs float64, hlhs, hrhs *histogram.FloatHistogram, pos posrange.PositionRange) (res float64, resH *histogram.FloatHistogram, keep bool, info, err error) { switch { case hlhs == nil && hrhs == nil: { switch op { case parser.ADD: - return lhs + rhs, nil, true, nil + return lhs + rhs, nil, true, nil, nil case parser.SUB: - return lhs - rhs, nil, true, nil + return lhs - rhs, nil, true, nil, nil case parser.MUL: - return lhs * rhs, nil, true, nil + return lhs * rhs, nil, true, nil, nil case parser.DIV: - return lhs / rhs, nil, true, nil + return lhs / rhs, nil, true, nil, nil case parser.POW: - return math.Pow(lhs, rhs), nil, true, nil + return math.Pow(lhs, rhs), nil, true, nil, nil case parser.MOD: - return math.Mod(lhs, rhs), nil, true, nil + return math.Mod(lhs, rhs), nil, true, nil, nil case parser.EQLC: - return lhs, nil, lhs == rhs, nil + return lhs, nil, lhs == rhs, nil, nil case parser.NEQ: - return lhs, nil, lhs != rhs, nil + return lhs, nil, lhs != rhs, nil, nil case parser.GTR: - return lhs, nil, lhs > rhs, nil + return lhs, nil, lhs > rhs, nil, nil case parser.LSS: - return lhs, nil, lhs < rhs, nil + return lhs, nil, lhs < rhs, nil, nil case parser.GTE: - return lhs, nil, lhs >= rhs, nil + return lhs, nil, lhs >= rhs, nil, nil case parser.LTE: - return lhs, nil, lhs <= rhs, nil + return lhs, nil, lhs <= rhs, nil, nil case parser.ATAN2: - return math.Atan2(lhs, rhs), nil, true, nil + return math.Atan2(lhs, rhs), nil, true, nil, nil } } case hlhs == nil && hrhs != nil: { switch op { case parser.MUL: - return 0, hrhs.Copy().Mul(lhs).Compact(0), true, nil + return 0, hrhs.Copy().Mul(lhs).Compact(0), true, nil, nil case parser.ADD, parser.SUB, parser.DIV, parser.POW, parser.MOD, parser.EQLC, parser.NEQ, parser.GTR, parser.LSS, parser.GTE, parser.LTE, parser.ATAN2: - return 0, nil, false, annotations.NewIncompatibleTypesInBinOpInfo("float", opName, "histogram", pos) + return 0, nil, false, nil, annotations.NewIncompatibleTypesInBinOpInfo("float", parser.ItemTypeStr[op], "histogram", pos) } } case hlhs != nil && hrhs == nil: { switch op { case parser.MUL: - return 0, hlhs.Copy().Mul(rhs).Compact(0), true, nil + return 0, hlhs.Copy().Mul(rhs).Compact(0), true, nil, nil case parser.DIV: - return 0, hlhs.Copy().Div(rhs).Compact(0), true, nil + return 0, hlhs.Copy().Div(rhs).Compact(0), true, nil, nil case parser.ADD, parser.SUB, parser.POW, parser.MOD, parser.EQLC, parser.NEQ, parser.GTR, parser.LSS, parser.GTE, parser.LTE, parser.ATAN2: - return 0, nil, false, annotations.NewIncompatibleTypesInBinOpInfo("histogram", opName, "float", pos) + return 0, nil, false, nil, annotations.NewIncompatibleTypesInBinOpInfo("histogram", parser.ItemTypeStr[op], "float", pos) } } case hlhs != nil && hrhs != nil: { switch op { case parser.ADD: - res, counterResetCollision, err := hlhs.Copy().Add(hrhs) + res, counterResetCollision, nhcbBoundsReconciled, err := hlhs.Copy().Add(hrhs) if err != nil { - return 0, nil, false, err + return 0, nil, false, nil, err } if counterResetCollision { err = annotations.NewHistogramCounterResetCollisionWarning(pos, annotations.HistogramAdd) } - return 0, res.Compact(0), true, err + if nhcbBoundsReconciled { + info = annotations.NewMismatchedCustomBucketsHistogramsInfo(pos, annotations.HistogramAdd) + } + return 0, res.Compact(0), true, info, err case parser.SUB: - res, counterResetCollision, err := hlhs.Copy().Sub(hrhs) + res, counterResetCollision, nhcbBoundsReconciled, err := hlhs.Copy().Sub(hrhs) if err != nil { - return 0, nil, false, err + return 0, nil, false, nil, err } + // The result must be marked as gauge. + res.CounterResetHint = histogram.GaugeType if counterResetCollision { err = annotations.NewHistogramCounterResetCollisionWarning(pos, annotations.HistogramSub) } - return 0, res.Compact(0), true, err + if nhcbBoundsReconciled { + info = annotations.NewMismatchedCustomBucketsHistogramsInfo(pos, annotations.HistogramSub) + } + + return 0, res.Compact(0), true, info, err case parser.EQLC: // This operation expects that both histograms are compacted. - return 0, hlhs, hlhs.Equals(hrhs), nil + return 0, hlhs, hlhs.Equals(hrhs), nil, nil case parser.NEQ: // This operation expects that both histograms are compacted. - return 0, hlhs, !hlhs.Equals(hrhs), nil + return 0, hlhs, !hlhs.Equals(hrhs), nil, nil case parser.MUL, parser.DIV, parser.POW, parser.MOD, parser.GTR, parser.LSS, parser.GTE, parser.LTE, parser.ATAN2: - return 0, nil, false, annotations.NewIncompatibleTypesInBinOpInfo("histogram", opName, "histogram", pos) + return 0, nil, false, nil, annotations.NewIncompatibleTypesInBinOpInfo("histogram", parser.ItemTypeStr[op], "histogram", pos) } } } @@ -3155,9 +3220,12 @@ type groupedAggregation struct { seen bool // Was this output groups seen in the input at this timestamp. hasFloat bool // Has at least 1 float64 sample aggregated. hasHistogram bool // Has at least 1 histogram sample aggregated. - incompatibleHistograms bool // If true, group has seen mixed exponential and custom buckets, or incompatible custom buckets. + incompatibleHistograms bool // If true, group has seen mixed exponential and custom buckets. groupAggrComplete bool // Used by LIMITK to short-cut series loop when we've reached K elem on every group. incrementalMean bool // True after reverting to incremental calculation of the mean value. + counterResetSeen bool // Counter reset hint CounterReset seen. Currently only used for histogram samples. + notCounterResetSeen bool // Counter reset hint NotCounterReset seen. Currently only used for histogram samples. + dropName bool // True if any sample in this group has DropName set. } // aggregation evaluates sum, avg, count, stdvar, stddev or quantile at one timestep on inputMatrix. @@ -3186,6 +3254,7 @@ func (ev *evaluator) aggregation(e *parser.AggregateExpr, q float64, inputMatrix floatMean: f, incompatibleHistograms: false, groupCount: 1, + dropName: inputMatrix[si].DropName, } switch op { case parser.AVG, parser.SUM: @@ -3194,6 +3263,12 @@ func (ev *evaluator) aggregation(e *parser.AggregateExpr, q float64, inputMatrix } else { group.histogramValue = h.Copy() group.hasHistogram = true + switch h.CounterResetHint { + case histogram.CounterReset: + group.counterResetSeen = true + case histogram.NotCounterReset: + group.notCounterResetSeen = true + } } case parser.STDVAR, parser.STDDEV: switch { @@ -3236,18 +3311,28 @@ func (ev *evaluator) aggregation(e *parser.AggregateExpr, q float64, inputMatrix continue } + if inputMatrix[si].DropName { + group.dropName = true + } + switch op { case parser.SUM: if h != nil { group.hasHistogram = true if group.histogramValue != nil { - _, counterResetCollision, err := group.histogramValue.Add(h) + switch h.CounterResetHint { + case histogram.CounterReset: + group.counterResetSeen = true + case histogram.NotCounterReset: + group.notCounterResetSeen = true + } + _, _, nhcbBoundsReconciled, err := group.histogramValue.Add(h) if err != nil { handleAggregationError(err, e, inputMatrix[si].Metric.Get(model.MetricNameLabel), &annos) group.incompatibleHistograms = true } - if counterResetCollision { - annos.Add(annotations.NewHistogramCounterResetCollisionWarning(e.Expr.PositionRange(), annotations.HistogramAgg)) + if nhcbBoundsReconciled { + annos.Add(annotations.NewMismatchedCustomBucketsHistogramsInfo(e.Expr.PositionRange(), annotations.HistogramAgg)) } } // Otherwise the aggregation contained floats @@ -3295,25 +3380,33 @@ func (ev *evaluator) aggregation(e *parser.AggregateExpr, q float64, inputMatrix if h != nil { group.hasHistogram = true if group.histogramValue != nil { + switch h.CounterResetHint { + case histogram.CounterReset: + group.counterResetSeen = true + case histogram.NotCounterReset: + group.notCounterResetSeen = true + } left := h.Copy().Div(group.groupCount) right := group.histogramValue.Copy().Div(group.groupCount) - toAdd, counterResetCollision, err := left.Sub(right) + + toAdd, _, nhcbBoundsReconciled, err := left.Sub(right) if err != nil { handleAggregationError(err, e, inputMatrix[si].Metric.Get(model.MetricNameLabel), &annos) group.incompatibleHistograms = true continue } - if counterResetCollision { - annos.Add(annotations.NewHistogramCounterResetCollisionWarning(e.Expr.PositionRange(), annotations.HistogramAgg)) + if nhcbBoundsReconciled { + annos.Add(annotations.NewMismatchedCustomBucketsHistogramsInfo(e.Expr.PositionRange(), annotations.HistogramAgg)) } - _, counterResetCollision, err = group.histogramValue.Add(toAdd) + + _, _, nhcbBoundsReconciled, err = group.histogramValue.Add(toAdd) if err != nil { handleAggregationError(err, e, inputMatrix[si].Metric.Get(model.MetricNameLabel), &annos) group.incompatibleHistograms = true continue } - if counterResetCollision { - annos.Add(annotations.NewHistogramCounterResetCollisionWarning(e.Expr.PositionRange(), annotations.HistogramAgg)) + if nhcbBoundsReconciled { + annos.Add(annotations.NewMismatchedCustomBucketsHistogramsInfo(e.Expr.PositionRange(), annotations.HistogramAgg)) } } // Otherwise the aggregation contained floats @@ -3446,13 +3539,21 @@ func (ev *evaluator) aggregation(e *parser.AggregateExpr, q float64, inputMatrix default: aggr.floatValue += aggr.floatKahanC } + default: // For other aggregations, we already have the right value. } + // This only is relevant for AVG and SUM with native histograms + // involved, but since those booleans aren't touched in other + // cases, we can just do it here in general. + if aggr.counterResetSeen && aggr.notCounterResetSeen { + annos.Add(annotations.NewHistogramCounterResetCollisionWarning(e.Expr.PositionRange(), annotations.HistogramAgg)) + } + ss := &outputMatrix[ri] addToSeries(ss, enh.Ts, aggr.floatValue, aggr.histogramValue, numSteps) - ss.DropName = inputMatrix[ri].DropName + ss.DropName = aggr.dropName } return annos @@ -3731,7 +3832,7 @@ func (*evaluator) aggregationCountValues(e *parser.AggregateExpr, grouping []str return enh.Out, nil } -func (ev *evaluator) cleanupMetricLabels(v parser.Value) { +func (ev *evaluator) cleanupMetricLabels(v parser.Value) parser.Value { if v.Type() == parser.ValueTypeMatrix { mat := v.(Matrix) for i := range mat { @@ -3739,9 +3840,7 @@ func (ev *evaluator) cleanupMetricLabels(v parser.Value) { mat[i].Metric = mat[i].Metric.DropReserved(schema.IsMetadataLabel) } } - if mat.ContainsSameLabelset() { - ev.errorf("vector cannot contain metrics with the same labelset") - } + return ev.mergeSeriesWithSameLabelset(mat) } else if v.Type() == parser.ValueTypeVector { vec := v.(Vector) for i := range vec { @@ -3752,7 +3851,75 @@ func (ev *evaluator) cleanupMetricLabels(v parser.Value) { if vec.ContainsSameLabelset() { ev.errorf("vector cannot contain metrics with the same labelset") } + return vec + } + return v +} + +// mergeSeriesWithSameLabelset merges series in a matrix that have the same labelset +// after __name__ label removal. This happens when delayed name removal is enabled and +// operations like OR combine series that originally had different names but end up +// with the same labelset after dropping the name. If series with the same labelset +// have overlapping timestamps, an error is returned. +func (ev *evaluator) mergeSeriesWithSameLabelset(mat Matrix) Matrix { + if len(mat) <= 1 { + return mat + } + + // Fast path: check if there are any duplicate labelsets without allocating. + // This is the common case and we want to avoid allocations. + if !mat.ContainsSameLabelset() { + return mat + } + + // Slow path: there are duplicates, so we need to merge series with non-overlapping timestamps. + // Group series by their labelset hash. + seriesByHash := make(map[uint64][]int) + for i := range mat { + hash := mat[i].Metric.Hash() + seriesByHash[hash] = append(seriesByHash[hash], i) + } + + // Merge series with the same labelset. + merged := make(Matrix, 0, len(seriesByHash)) + for _, indices := range seriesByHash { + if len(indices) == 1 { + // No collision, add as-is. + merged = append(merged, mat[indices[0]]) + continue + } + + // Multiple series with the same labelset - merge all samples. + base := mat[indices[0]] + for _, idx := range indices[1:] { + base.Floats = append(base.Floats, mat[idx].Floats...) + base.Histograms = append(base.Histograms, mat[idx].Histograms...) + } + + // Sort merged samples by timestamp. + sort.Slice(base.Floats, func(i, j int) bool { + return base.Floats[i].T < base.Floats[j].T + }) + sort.Slice(base.Histograms, func(i, j int) bool { + return base.Histograms[i].T < base.Histograms[j].T + }) + + // Check for duplicate timestamps in sorted samples. + for i := 1; i < len(base.Floats); i++ { + if base.Floats[i].T == base.Floats[i-1].T { + ev.errorf("vector cannot contain metrics with the same labelset") + } + } + for i := 1; i < len(base.Histograms); i++ { + if base.Histograms[i].T == base.Histograms[i-1].T { + ev.errorf("vector cannot contain metrics with the same labelset") + } + } + + merged = append(merged, base) } + + return merged } func addToSeries(ss *Series, ts int64, f float64, h *histogram.FloatHistogram, numSteps int) { @@ -3788,8 +3955,6 @@ func handleAggregationError(err error, e *parser.AggregateExpr, metricName strin pos := e.Expr.PositionRange() if errors.Is(err, histogram.ErrHistogramsIncompatibleSchema) { annos.Add(annotations.NewMixedExponentialCustomHistogramsWarning(metricName, pos)) - } else if errors.Is(err, histogram.ErrHistogramsIncompatibleBounds) { - annos.Add(annotations.NewIncompatibleCustomBucketsHistogramsWarning(metricName, pos)) } } @@ -3798,13 +3963,13 @@ func handleVectorBinopError(err error, e *parser.BinaryExpr) annotations.Annotat if err == nil { return nil } - op := parser.ItemTypeStr[e.Op] - pos := e.PositionRange() if errors.Is(err, annotations.PromQLInfo) || errors.Is(err, annotations.PromQLWarning) { return annotations.New().Add(err) } // TODO(NeerajGartia21): Test the exact annotation output once the testing framework can do so. - if errors.Is(err, histogram.ErrHistogramsIncompatibleSchema) || errors.Is(err, histogram.ErrHistogramsIncompatibleBounds) { + if errors.Is(err, histogram.ErrHistogramsIncompatibleSchema) { + op := parser.ItemTypeStr[e.Op] + pos := e.PositionRange() return annotations.New().Add(annotations.NewIncompatibleBucketLayoutInBinOpWarning(op, pos)) } return nil @@ -4092,13 +4257,17 @@ func makeInt64Pointer(val int64) *int64 { // RatioSampler allows unit-testing (previously: Randomizer). type RatioSampler interface { - // Return this sample "offset" between [0.0, 1.0] - sampleOffset(ts int64, sample *Sample) float64 - AddRatioSample(r float64, sample *Sample) bool + // SampleOffset returns this sample "offset" between [0.0, 1.0]. + SampleOffset(metric *labels.Labels) float64 + // AddRatioSample reports whether the sampling offset for the given sample falls within the specified ratio limit. + AddRatioSample(ratioLimit float64, sample *Sample) bool + // AddRatioSampleWithOffset reports whether the given sampling offset falls within the specified ratio limit. + AddRatioSampleWithOffset(ratioLimit, sampleOffset float64) bool } // HashRatioSampler uses Hash(labels.String()) / maxUint64 as a "deterministic" // value in [0.0, 1.0]. +// It is a utility used for limit_ratio aggregations. type HashRatioSampler struct{} var ratiosampler RatioSampler = NewHashRatioSampler() @@ -4107,14 +4276,42 @@ func NewHashRatioSampler() *HashRatioSampler { return &HashRatioSampler{} } -func (*HashRatioSampler) sampleOffset(_ int64, sample *Sample) float64 { +// SampleOffset returns a deterministic sampling offset in the range [0, 1) +// derived from the hash of the provided metric labels. +// +// The offset is computed by normalizing the 64-bit hash value of the label set +// to a float64 fraction of math.MaxUint64. This ensures that metrics with the +// same label set always produce the same offset, while different label sets +// produce uniformly distributed offsets suitable for sampling decisions. +func (*HashRatioSampler) SampleOffset(metric *labels.Labels) float64 { const ( float64MaxUint64 = float64(math.MaxUint64) ) - return float64(sample.Metric.Hash()) / float64MaxUint64 + return float64(metric.Hash()) / float64MaxUint64 } +// AddRatioSample returns a bool indicating if the sampling offset for the given sample is +// within the given ratio limit. +// +// See SampleOffset() for further details on the sample offset. +// See AddRatioSampleWithOffset() for further details on the ratioLimit and sampling offset comparison. func (s *HashRatioSampler) AddRatioSample(ratioLimit float64, sample *Sample) bool { + sampleOffset := s.SampleOffset(&sample.Metric) + return s.AddRatioSampleWithOffset(ratioLimit, sampleOffset) +} + +// AddRatioSampleWithOffset reports whether the given sampling offset falls within +// the specified ratio limit. +// +// The ratioLimit must be in the range [-1, 1]. The sampleOffset should be derived +// using SampleOffset(). +// +// When ratioLimit >= 0, the function returns true if sampleOffset < ratioLimit. +// When ratioLimit < 0, the function returns true if sampleOffset >= 1 + ratioLimit. +// +// Note that this method could be moved into AddRatioSample and removed from the Prometheus codebase, +// but it is useful for downstream projects using this code as a library. +func (*HashRatioSampler) AddRatioSampleWithOffset(ratioLimit, sampleOffset float64) bool { // If ratioLimit >= 0: add sample if sampleOffset is lesser than ratioLimit // // 0.0 ratioLimit 1.0 @@ -4135,7 +4332,6 @@ func (s *HashRatioSampler) AddRatioSample(ratioLimit float64, sample *Sample) bo // e.g.: // sampleOffset==0.3 && ratioLimit==-0.6 // 0.3 >= 0.4 ? --> don't add sample - sampleOffset := s.sampleOffset(sample.T, sample) return (ratioLimit >= 0 && sampleOffset < ratioLimit) || (ratioLimit < 0 && sampleOffset >= (1.0+ratioLimit)) } diff --git a/vendor/github.com/prometheus/prometheus/promql/functions.go b/vendor/github.com/prometheus/prometheus/promql/functions.go index 6dfe9611f1f..f844bf5ada5 100644 --- a/vendor/github.com/prometheus/prometheus/promql/functions.go +++ b/vendor/github.com/prometheus/prometheus/promql/functions.go @@ -368,14 +368,15 @@ func histogramRate(points []HPoint, isCounter bool, metricName string, pos posra // This subtraction may deliberately include conflicting counter resets. // Counter resets are treated explicitly in this function, so the // information about conflicting counter resets is ignored here. - _, _, err := h.Sub(prev) + _, _, nhcbBoundsReconciled, err := h.Sub(prev) if err != nil { if errors.Is(err, histogram.ErrHistogramsIncompatibleSchema) { return nil, annotations.New().Add(annotations.NewMixedExponentialCustomHistogramsWarning(metricName, pos)) - } else if errors.Is(err, histogram.ErrHistogramsIncompatibleBounds) { - return nil, annotations.New().Add(annotations.NewIncompatibleCustomBucketsHistogramsWarning(metricName, pos)) } } + if nhcbBoundsReconciled { + annos.Add(annotations.NewMismatchedCustomBucketsHistogramsInfo(pos, annotations.HistogramSub)) + } if isCounter { // Second iteration to deal with counter resets. @@ -383,14 +384,15 @@ func histogramRate(points []HPoint, isCounter bool, metricName string, pos posra curr := currPoint.H if curr.DetectReset(prev) { // Counter reset conflict ignored here for the same reason as above. - _, _, err := h.Add(prev) + _, _, nhcbBoundsReconciled, err := h.Add(prev) if err != nil { if errors.Is(err, histogram.ErrHistogramsIncompatibleSchema) { return nil, annotations.New().Add(annotations.NewMixedExponentialCustomHistogramsWarning(metricName, pos)) - } else if errors.Is(err, histogram.ErrHistogramsIncompatibleBounds) { - return nil, annotations.New().Add(annotations.NewIncompatibleCustomBucketsHistogramsWarning(metricName, pos)) } } + if nhcbBoundsReconciled { + annos.Add(annotations.NewMismatchedCustomBucketsHistogramsInfo(pos, annotations.HistogramAdd)) + } } prev = curr } @@ -398,6 +400,7 @@ func histogramRate(points []HPoint, isCounter bool, metricName string, pos posra annos.Add(annotations.NewNativeHistogramNotGaugeWarning(metricName, pos)) } + h.CounterResetHint = histogram.GaugeType return h.Compact(0), annos } @@ -508,11 +511,12 @@ func instantValue(vals Matrix, args parser.Expressions, out Vector, isRate bool) // counter resets. Counter resets are treated explicitly // in this function, so the information about // conflicting counter resets is ignored here. - _, _, err := resultSample.H.Sub(ss[0].H) + _, _, nhcbBoundsReconciled, err := resultSample.H.Sub(ss[0].H) if errors.Is(err, histogram.ErrHistogramsIncompatibleSchema) { return out, annos.Add(annotations.NewMixedExponentialCustomHistogramsWarning(metricName, args.PositionRange())) - } else if errors.Is(err, histogram.ErrHistogramsIncompatibleBounds) { - return out, annos.Add(annotations.NewIncompatibleCustomBucketsHistogramsWarning(metricName, args.PositionRange())) + } + if nhcbBoundsReconciled { + annos.Add(annotations.NewMismatchedCustomBucketsHistogramsInfo(args.PositionRange(), annotations.HistogramSub)) } } resultSample.H.CounterResetHint = histogram.GaugeType @@ -820,24 +824,48 @@ func funcAvgOverTime(_ []Vector, matrixVal Matrix, args parser.Expressions, enh // The passed values only contain histograms. var annos annotations.Annotations vec, err := aggrHistOverTime(matrixVal, enh, func(s Series) (*histogram.FloatHistogram, error) { + var counterResetSeen, notCounterResetSeen, nhcbBoundsReconciledSeen bool + + trackCounterReset := func(h *histogram.FloatHistogram) { + switch h.CounterResetHint { + case histogram.CounterReset: + counterResetSeen = true + case histogram.NotCounterReset: + notCounterResetSeen = true + } + } + + defer func() { + if counterResetSeen && notCounterResetSeen { + annos.Add(annotations.NewHistogramCounterResetCollisionWarning(args[0].PositionRange(), annotations.HistogramAgg)) + } + if nhcbBoundsReconciledSeen { + annos.Add(annotations.NewMismatchedCustomBucketsHistogramsInfo(args[0].PositionRange(), annotations.HistogramAgg)) + } + }() + mean := s.Histograms[0].H.Copy() + trackCounterReset(mean) for i, h := range s.Histograms[1:] { + trackCounterReset(h.H) count := float64(i + 2) left := h.H.Copy().Div(count) right := mean.Copy().Div(count) - toAdd, counterResetCollision, err := left.Sub(right) + + toAdd, _, nhcbBoundsReconciled, err := left.Sub(right) if err != nil { return mean, err } - if counterResetCollision { - annos.Add(annotations.NewHistogramCounterResetCollisionWarning(args[0].PositionRange(), annotations.HistogramSub)) + if nhcbBoundsReconciled { + nhcbBoundsReconciledSeen = true } - _, counterResetCollision, err = mean.Add(toAdd) + + _, _, nhcbBoundsReconciled, err = mean.Add(toAdd) if err != nil { return mean, err } - if counterResetCollision { - annos.Add(annotations.NewHistogramCounterResetCollisionWarning(args[0].PositionRange(), annotations.HistogramAdd)) + if nhcbBoundsReconciled { + nhcbBoundsReconciledSeen = true } } return mean, nil @@ -846,8 +874,6 @@ func funcAvgOverTime(_ []Vector, matrixVal Matrix, args parser.Expressions, enh metricName := firstSeries.Metric.Get(labels.MetricName) if errors.Is(err, histogram.ErrHistogramsIncompatibleSchema) { return enh.Out, annotations.New().Add(annotations.NewMixedExponentialCustomHistogramsWarning(metricName, args[0].PositionRange())) - } else if errors.Is(err, histogram.ErrHistogramsIncompatibleBounds) { - return enh.Out, annotations.New().Add(annotations.NewIncompatibleCustomBucketsHistogramsWarning(metricName, args[0].PositionRange())) } } return vec, annos @@ -1077,14 +1103,36 @@ func funcSumOverTime(_ []Vector, matrixVal Matrix, args parser.Expressions, enh // The passed values only contain histograms. var annos annotations.Annotations vec, err := aggrHistOverTime(matrixVal, enh, func(s Series) (*histogram.FloatHistogram, error) { + var counterResetSeen, notCounterResetSeen, nhcbBoundsReconciledSeen bool + + trackCounterReset := func(h *histogram.FloatHistogram) { + switch h.CounterResetHint { + case histogram.CounterReset: + counterResetSeen = true + case histogram.NotCounterReset: + notCounterResetSeen = true + } + } + + defer func() { + if counterResetSeen && notCounterResetSeen { + annos.Add(annotations.NewHistogramCounterResetCollisionWarning(args[0].PositionRange(), annotations.HistogramAgg)) + } + if nhcbBoundsReconciledSeen { + annos.Add(annotations.NewMismatchedCustomBucketsHistogramsInfo(args[0].PositionRange(), annotations.HistogramAgg)) + } + }() + sum := s.Histograms[0].H.Copy() + trackCounterReset(sum) for _, h := range s.Histograms[1:] { - _, counterResetCollision, err := sum.Add(h.H) + trackCounterReset(h.H) + _, _, nhcbBoundsReconciled, err := sum.Add(h.H) if err != nil { return sum, err } - if counterResetCollision { - annos.Add(annotations.NewHistogramCounterResetCollisionWarning(args[0].PositionRange(), annotations.HistogramAdd)) + if nhcbBoundsReconciled { + nhcbBoundsReconciledSeen = true } } return sum, nil @@ -1093,8 +1141,6 @@ func funcSumOverTime(_ []Vector, matrixVal Matrix, args parser.Expressions, enh metricName := firstSeries.Metric.Get(labels.MetricName) if errors.Is(err, histogram.ErrHistogramsIncompatibleSchema) { return enh.Out, annotations.New().Add(annotations.NewMixedExponentialCustomHistogramsWarning(metricName, args[0].PositionRange())) - } else if errors.Is(err, histogram.ErrHistogramsIncompatibleBounds) { - return enh.Out, annotations.New().Add(annotations.NewIncompatibleCustomBucketsHistogramsWarning(metricName, args[0].PositionRange())) } } return vec, annos @@ -1481,7 +1527,7 @@ func simpleHistogramFunc(vectorVals []Vector, enh *EvalNodeHelper, f func(h *his for _, el := range vectorVals[0] { if el.H != nil { // Process only histogram samples. if !enh.enableDelayedNameRemoval { - el.Metric = el.Metric.DropMetricName() + el.Metric = el.Metric.DropReserved(func(n string) bool { return n == labels.MetricName }) } enh.Out = append(enh.Out, Sample{ Metric: el.Metric, @@ -1664,15 +1710,19 @@ func funcHistogramQuantile(vectorVals []Vector, _ Matrix, args parser.Expression // pickFirstSampleIndex returns the index of the last sample before // or at the range start, or 0 if none exist before the range start. -// If the vector selector is not anchored, it always returns 0. -func pickFirstSampleIndex(floats []FPoint, args parser.Expressions, enh *EvalNodeHelper) int { +// If the vector selector is not anchored, it always returns 0, true. +// The second return value is false if there are no samples in range (for anchored selectors). +func pickFirstSampleIndex(floats []FPoint, args parser.Expressions, enh *EvalNodeHelper) (int, bool) { ms := args[0].(*parser.MatrixSelector) vs := ms.VectorSelector.(*parser.VectorSelector) if !vs.Anchored { - return 0 + return 0, true } rangeStart := enh.Ts - durationMilliseconds(ms.Range+vs.Offset) - return max(0, sort.Search(len(floats)-1, func(i int) bool { return floats[i].T > rangeStart })-1) + if len(floats) == 0 || floats[len(floats)-1].T <= rangeStart { + return 0, false + } + return max(0, sort.Search(len(floats)-1, func(i int) bool { return floats[i].T > rangeStart })-1), true } // === resets(Matrix parser.ValueTypeMatrix) (Vector, Annotations) === @@ -1685,7 +1735,10 @@ func funcResets(_ []Vector, matrixVal Matrix, args parser.Expressions, enh *Eval } var prevSample, curSample Sample - firstSampleIndex := pickFirstSampleIndex(floats, args, enh) + firstSampleIndex, found := pickFirstSampleIndex(floats, args, enh) + if !found { + return enh.Out, nil + } for iFloat, iHistogram := firstSampleIndex, 0; iFloat < len(floats) || iHistogram < len(histograms); { switch { // Process a float sample if no histogram sample remains or its timestamp is earlier. @@ -1731,7 +1784,10 @@ func funcChanges(_ []Vector, matrixVal Matrix, args parser.Expressions, enh *Eva } var prevSample, curSample Sample - firstSampleIndex := pickFirstSampleIndex(floats, args, enh) + firstSampleIndex, found := pickFirstSampleIndex(floats, args, enh) + if !found { + return enh.Out, nil + } for iFloat, iHistogram := firstSampleIndex, 0; iFloat < len(floats) || iHistogram < len(histograms); { switch { // Process a float sample if no histogram sample remains or its timestamp is earlier. @@ -1803,11 +1859,8 @@ func (ev *evaluator) evalLabelReplace(ctx context.Context, args parser.Expressio } } } - if matrix.ContainsSameLabelset() { - ev.errorf("vector cannot contain metrics with the same labelset") - } - return matrix, ws + return ev.mergeSeriesWithSameLabelset(matrix), ws } // === Vector(s Scalar) (Vector, Annotations) === @@ -1857,11 +1910,8 @@ func (ev *evaluator) evalLabelJoin(ctx context.Context, args parser.Expressions) matrix[i].DropName = el.DropName } } - if matrix.ContainsSameLabelset() { - ev.errorf("vector cannot contain metrics with the same labelset") - } - return matrix, ws + return ev.mergeSeriesWithSameLabelset(matrix), ws } // Common code for date related functions. diff --git a/vendor/github.com/prometheus/prometheus/promql/info.go b/vendor/github.com/prometheus/prometheus/promql/info.go index 318dae399ad..d5ffda6af2b 100644 --- a/vendor/github.com/prometheus/prometheus/promql/info.go +++ b/vendor/github.com/prometheus/prometheus/promql/info.go @@ -55,13 +55,13 @@ func (ev *evaluator) evalInfo(ctx context.Context, args parser.Expressions) (par } // Don't try to enrich info series. - ignoreSeries := map[int]struct{}{} + ignoreSeries := map[uint64]struct{}{} loop: - for i, s := range mat { + for _, s := range mat { name := s.Metric.Get(labels.MetricName) for _, m := range infoNameMatchers { if m.Matches(name) { - ignoreSeries[i] = struct{}{} + ignoreSeries[s.Metric.Hash()] = struct{}{} continue loop } } @@ -121,11 +121,11 @@ func (ev *evaluator) infoSelectHints(expr parser.Expr) storage.SelectHints { // fetchInfoSeries fetches info series given matching identifying labels in mat. // Series in ignoreSeries are not fetched. // dataLabelMatchers may be mutated. -func (ev *evaluator) fetchInfoSeries(ctx context.Context, mat Matrix, ignoreSeries map[int]struct{}, dataLabelMatchers map[string][]*labels.Matcher, selectHints storage.SelectHints) (Matrix, annotations.Annotations, error) { +func (ev *evaluator) fetchInfoSeries(ctx context.Context, mat Matrix, ignoreSeries map[uint64]struct{}, dataLabelMatchers map[string][]*labels.Matcher, selectHints storage.SelectHints) (Matrix, annotations.Annotations, error) { // A map of values for all identifying labels we are interested in. idLblValues := map[string]map[string]struct{}{} - for i, s := range mat { - if _, exists := ignoreSeries[i]; exists { + for _, s := range mat { + if _, exists := ignoreSeries[s.Metric.Hash()]; exists { continue } @@ -197,7 +197,7 @@ func (ev *evaluator) fetchInfoSeries(ctx context.Context, mat Matrix, ignoreSeri } // combineWithInfoSeries combines mat with select data labels from infoMat. -func (ev *evaluator) combineWithInfoSeries(ctx context.Context, mat, infoMat Matrix, ignoreSeries map[int]struct{}, dataLabelMatchers map[string][]*labels.Matcher) (Matrix, annotations.Annotations) { +func (ev *evaluator) combineWithInfoSeries(ctx context.Context, mat, infoMat Matrix, ignoreSeries map[uint64]struct{}, dataLabelMatchers map[string][]*labels.Matcher) (Matrix, annotations.Annotations) { buf := make([]byte, 0, 1024) lb := labels.NewScratchBuilder(0) sigFunction := func(name string) func(labels.Labels) string { @@ -249,13 +249,13 @@ func (ev *evaluator) combineWithInfoSeries(ctx context.Context, mat, infoMat Mat tempNumSamples := ev.currentSamples // For every base series, compute signature per info metric. - baseSigs := make([]map[string]string, 0, len(mat)) + baseSigs := make(map[uint64]map[string]string, len(mat)) for _, s := range mat { sigs := make(map[string]string, len(infoMetrics)) for infoName := range infoMetrics { sigs[infoName] = sigfs[infoName](s.Metric) } - baseSigs = append(baseSigs, sigs) + baseSigs[s.Metric.Hash()] = sigs } infoSigs := make(map[uint64]string, len(infoMat)) @@ -331,16 +331,16 @@ func (ev *evaluator) combineWithInfoSeries(ctx context.Context, mat, infoMat Mat // combineWithInfoVector combines base and info Vectors. // Base series in ignoreSeries are not combined. -func (ev *evaluator) combineWithInfoVector(base, info Vector, ignoreSeries map[int]struct{}, baseSigs []map[string]string, infoSigs map[uint64]string, enh *EvalNodeHelper, dataLabelMatchers map[string][]*labels.Matcher) (Vector, error) { +func (ev *evaluator) combineWithInfoVector(base, info Vector, ignoreSeries map[uint64]struct{}, baseSigs map[uint64]map[string]string, infoSigs map[uint64]string, enh *EvalNodeHelper, dataLabelMatchers map[string][]*labels.Matcher) (Vector, error) { if len(base) == 0 { return nil, nil // Short-circuit: nothing is going to match. } // All samples from the info Vector hashed by the matching label/values. - if enh.rightSigs == nil { - enh.rightSigs = make(map[string]Sample, len(enh.Out)) + if enh.rightStrSigs == nil { + enh.rightStrSigs = make(map[string]Sample, len(enh.Out)) } else { - clear(enh.rightSigs) + clear(enh.rightStrSigs) } for _, s := range info { @@ -351,7 +351,7 @@ func (ev *evaluator) combineWithInfoVector(base, info Vector, ignoreSeries map[i origT := int64(s.F) sig := infoSigs[s.Metric.Hash()] - if existing, exists := enh.rightSigs[sig]; exists { + if existing, exists := enh.rightStrSigs[sig]; exists { // We encode original info sample timestamps via the float value. existingOrigT := int64(existing.F) switch { @@ -359,19 +359,21 @@ func (ev *evaluator) combineWithInfoVector(base, info Vector, ignoreSeries map[i // Keep the other info sample, since it's newer. case existingOrigT < origT: // Keep this info sample, since it's newer. - enh.rightSigs[sig] = s + enh.rightStrSigs[sig] = s default: // The two info samples have the same timestamp - conflict. ev.errorf("found duplicate series for info metric: existing %s @ %d, new %s @ %d", existing.Metric.String(), existingOrigT, s.Metric.String(), origT) } } else { - enh.rightSigs[sig] = s + enh.rightStrSigs[sig] = s } } - for i, bs := range base { - if _, exists := ignoreSeries[i]; exists { + for _, bs := range base { + hash := bs.Metric.Hash() + + if _, exists := ignoreSeries[hash]; exists { // This series should not be enriched with info metric data labels. enh.Out = append(enh.Out, Sample{ Metric: bs.Metric, @@ -386,8 +388,8 @@ func (ev *evaluator) combineWithInfoVector(base, info Vector, ignoreSeries map[i // For every info metric name, try to find an info series with the same signature. seenInfoMetrics := map[string]struct{}{} - for infoName, sig := range baseSigs[i] { - is, exists := enh.rightSigs[sig] + for infoName, sig := range baseSigs[hash] { + is, exists := enh.rightStrSigs[sig] if !exists { continue } diff --git a/vendor/github.com/prometheus/prometheus/promql/parser/features.go b/vendor/github.com/prometheus/prometheus/promql/parser/features.go new file mode 100644 index 00000000000..ec64678237f --- /dev/null +++ b/vendor/github.com/prometheus/prometheus/promql/parser/features.go @@ -0,0 +1,57 @@ +// Copyright The Prometheus Authors +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package parser + +import "github.com/prometheus/prometheus/util/features" + +// RegisterFeatures registers all PromQL features with the feature registry. +// This includes operators (arithmetic and comparison/set), aggregators (standard +// and experimental), and functions. +func RegisterFeatures(r features.Collector) { + // Register core PromQL language keywords. + for keyword, itemType := range key { + if itemType.IsKeyword() { + // Handle experimental keywords separately. + switch keyword { + case "anchored", "smoothed": + r.Set(features.PromQL, keyword, EnableExtendedRangeSelectors) + default: + r.Enable(features.PromQL, keyword) + } + } + } + + // Register operators. + for o := ItemType(operatorsStart + 1); o < operatorsEnd; o++ { + if o.IsOperator() { + r.Set(features.PromQLOperators, o.String(), true) + } + } + + // Register aggregators. + for a := ItemType(aggregatorsStart + 1); a < aggregatorsEnd; a++ { + if a.IsAggregator() { + experimental := a.IsExperimentalAggregator() && !EnableExperimentalFunctions + r.Set(features.PromQLOperators, a.String(), !experimental) + } + } + + // Register functions. + for f, fc := range Functions { + r.Set(features.PromQLFunctions, f, !fc.Experimental || EnableExperimentalFunctions) + } + + // Register experimental parser features. + r.Set(features.PromQL, "duration_expr", ExperimentalDurationExpr) +} diff --git a/vendor/github.com/prometheus/prometheus/promql/parser/lex.go b/vendor/github.com/prometheus/prometheus/promql/parser/lex.go index 949bc453e88..296b91d1aea 100644 --- a/vendor/github.com/prometheus/prometheus/promql/parser/lex.go +++ b/vendor/github.com/prometheus/prometheus/promql/parser/lex.go @@ -199,6 +199,7 @@ var ItemTypeStr = map[ItemType]string{ EQL_REGEX: "=~", NEQ_REGEX: "!~", POW: "^", + AT: "@", } func init() { diff --git a/vendor/github.com/prometheus/prometheus/promql/parser/parse.go b/vendor/github.com/prometheus/prometheus/promql/parser/parse.go index 3a76ddb44d6..bcd511f4670 100644 --- a/vendor/github.com/prometheus/prometheus/promql/parser/parse.go +++ b/vendor/github.com/prometheus/prometheus/promql/parser/parse.go @@ -453,14 +453,14 @@ func (p *parser) newAggregateExpr(op Item, modifier, args Node, overread bool) ( p.addParseErrf(ret.PositionRange(), "no arguments for aggregate expression provided") // Prevents invalid array accesses. - return + return ret } desiredArgs := 1 if ret.Op.IsAggregatorWithParam() { if !EnableExperimentalFunctions && ret.Op.IsExperimentalAggregator() { p.addParseErrf(ret.PositionRange(), "%s() is experimental and must be enabled with --enable-feature=promql-experimental-functions", ret.Op) - return + return ret } desiredArgs = 2 @@ -469,7 +469,7 @@ func (p *parser) newAggregateExpr(op Item, modifier, args Node, overread bool) ( if len(arguments) != desiredArgs { p.addParseErrf(ret.PositionRange(), "wrong number of arguments for aggregate expression provided, expected %d, got %d", desiredArgs, len(arguments)) - return + return ret } ret.Expr = arguments[desiredArgs-1] @@ -497,14 +497,14 @@ func (p *parser) mergeMaps(left, right *map[string]any) (ret *map[string]any) { func (p *parser) histogramsIncreaseSeries(base, inc *histogram.FloatHistogram, times uint64) ([]SequenceValue, error) { return p.histogramsSeries(base, inc, times, func(a, b *histogram.FloatHistogram) (*histogram.FloatHistogram, error) { - res, _, err := a.Add(b) + res, _, _, err := a.Add(b) return res, err }) } func (p *parser) histogramsDecreaseSeries(base, inc *histogram.FloatHistogram, times uint64) ([]SequenceValue, error) { return p.histogramsSeries(base, inc, times, func(a, b *histogram.FloatHistogram) (*histogram.FloatHistogram, error) { - res, _, err := a.Sub(b) + res, _, _, err := a.Sub(b) return res, err }) } @@ -652,7 +652,7 @@ func (p *parser) buildHistogramBucketsAndSpans(desc *map[string]any, bucketsKey, if bucketCount > 0 { spans = []histogram.Span{{Offset: offset, Length: uint32(bucketCount)}} } - return + return buckets, spans } // number parses a number. @@ -730,7 +730,7 @@ func (p *parser) checkAST(node Node) (typ ValueType) { } for r.End = n.RHS.PositionRange().Start - 1; isSpace(rune(p.lex.input[r.End])); r.End-- { } - return + return r } if n.ReturnBool && !n.Op.IsComparisonOperator() { @@ -803,11 +803,14 @@ func (p *parser) checkAST(node Node) (typ ValueType) { p.addParseErrf(node.PositionRange(), "expected type %s in %s, got %s", DocumentedType(ValueTypeVector), fmt.Sprintf("call to function %q", n.Func.Name), DocumentedType(n.Args[1].Type())) } // Check the vector selector in the input doesn't contain a metric name - if n.Args[1].(*VectorSelector).Name != "" { + if vs, ok := n.Args[1].(*VectorSelector); ok && vs.Name != "" { p.addParseErrf(n.Args[1].PositionRange(), "expected label selectors only, got vector selector instead") + } else if ok { + // Set Vector Selector flag to bypass empty matcher check + vs.BypassEmptyMatcherCheck = true + } else { + p.addParseErrf(n.Args[1].PositionRange(), "expected label selectors only") } - // Set Vector Selector flag to bypass empty matcher check - n.Args[1].(*VectorSelector).BypassEmptyMatcherCheck = true } for i, arg := range n.Args { @@ -819,7 +822,9 @@ func (p *parser) checkAST(node Node) (typ ValueType) { } i = len(n.Func.ArgTypes) - 1 } - p.expectType(arg, n.Func.ArgTypes[i], fmt.Sprintf("call to function %q", n.Func.Name)) + if t := p.checkAST(arg); t != n.Func.ArgTypes[i] { + p.addParseErrf(arg.PositionRange(), "expected type %s in call to function %q, got %s", DocumentedType(n.Func.ArgTypes[i]), n.Func.Name, DocumentedType(t)) + } } case *ParenExpr: @@ -877,7 +882,7 @@ func (p *parser) checkAST(node Node) (typ ValueType) { default: p.addParseErrf(n.PositionRange(), "unknown node type: %T", node) } - return + return typ } func (p *parser) unquoteString(s string) string { diff --git a/vendor/github.com/prometheus/prometheus/promql/parser/printer.go b/vendor/github.com/prometheus/prometheus/promql/parser/printer.go index a562b88044d..961167428b0 100644 --- a/vendor/github.com/prometheus/prometheus/promql/parser/printer.go +++ b/vendor/github.com/prometheus/prometheus/promql/parser/printer.go @@ -37,15 +37,16 @@ func tree(node Node, level string) string { } typs := strings.Split(fmt.Sprintf("%T", node), ".")[1] - t := fmt.Sprintf("%s |---- %s :: %s\n", level, typs, node) + var t strings.Builder + t.WriteString(fmt.Sprintf("%s |---- %s :: %s\n", level, typs, node)) level += " · · ·" for e := range ChildrenIter(node) { - t += tree(e, level) + t.WriteString(tree(e, level)) } - return t + return t.String() } func (node *EvalStmt) String() string { @@ -147,12 +148,14 @@ func (node *BinaryExpr) ShortString() string { func (node *BinaryExpr) getMatchingStr() string { matching := "" vm := node.VectorMatching - if vm != nil && (len(vm.MatchingLabels) > 0 || vm.On) { - vmTag := "ignoring" - if vm.On { - vmTag = "on" + if vm != nil { + if len(vm.MatchingLabels) > 0 || vm.On || vm.Card == CardManyToOne || vm.Card == CardOneToMany { + vmTag := "ignoring" + if vm.On { + vmTag = "on" + } + matching = fmt.Sprintf(" %s (%s)", vmTag, strings.Join(vm.MatchingLabels, ", ")) } - matching = fmt.Sprintf(" %s (%s)", vmTag, strings.Join(vm.MatchingLabels, ", ")) if vm.Card == CardManyToOne || vm.Card == CardOneToMany { vmCard := "right" diff --git a/vendor/github.com/prometheus/prometheus/promql/quantile.go b/vendor/github.com/prometheus/prometheus/promql/quantile.go index 14549741078..78df925c519 100644 --- a/vendor/github.com/prometheus/prometheus/promql/quantile.go +++ b/vendor/github.com/prometheus/prometheus/promql/quantile.go @@ -406,6 +406,18 @@ func HistogramFraction(lower, upper float64, h *histogram.FloatHistogram, metric // consistent with the linear interpolation known from classic // histograms. It is also used for the zero bucket. interpolateLinearly := func(v float64) float64 { + // Note: `v` is a finite value. + // For buckets with infinite bounds, we cannot interpolate meaningfully. + // For +Inf upper bound, interpolation returns the cumulative count of the previous bucket + // as the second term in the interpolation formula yields 0 (finite/Inf). + // In other words, no observations from the last bucket are considered in the fraction calculation. + // For -Inf lower bound, however, the second term would be (v-(-Inf))/(upperBound-(-Inf)) = Inf/Inf = NaN. + // To achieve the same effect of no contribution as the +Inf bucket, handle the -Inf case by returning + // the cumulative count at the first bucket (which equals the bucket's count). + // In both cases, we effectively skip interpolation within the infinite-width bucket. + if b.Lower == math.Inf(-1) { + return b.Count + } return rank + b.Count*(v-b.Lower)/(b.Upper-b.Lower) } @@ -531,14 +543,34 @@ func BucketFraction(lower, upper float64, buckets Buckets) float64 { rank, lowerRank, upperRank float64 lowerSet, upperSet bool ) + + // If the upper bound of the first bucket is greater than 0, we assume + // we are dealing with positive buckets only and lowerBound for the + // first bucket is set to 0; otherwise it is set to -Inf. + lowerBound := 0.0 + if buckets[0].UpperBound <= 0 { + lowerBound = math.Inf(-1) + } + for i, b := range buckets { - lowerBound := math.Inf(-1) if i > 0 { lowerBound = buckets[i-1].UpperBound } upperBound := b.UpperBound interpolateLinearly := func(v float64) float64 { + // Note: `v` is a finite value. + // For buckets with infinite bounds, we cannot interpolate meaningfully. + // For +Inf upper bound, interpolation returns the cumulative count of the previous bucket + // as the second term in the interpolation formula yields 0 (finite/Inf). + // In other words, no observations from the last bucket are considered in the fraction calculation. + // For -Inf lower bound, however, the second term would be (v-(-Inf))/(upperBound-(-Inf)) = Inf/Inf = NaN. + // To achieve the same effect of no contribution as the +Inf bucket, handle the -Inf case by returning + // the cumulative count at the first bucket. + // In both cases, we effectively skip interpolation within the infinite-width bucket. + if lowerBound == math.Inf(-1) { + return b.Count + } return rank + (b.Count-rank)*(v-lowerBound)/(upperBound-lowerBound) } diff --git a/vendor/github.com/prometheus/prometheus/schema/labels.go b/vendor/github.com/prometheus/prometheus/schema/labels.go index c68121322b8..05329af7f6a 100644 --- a/vendor/github.com/prometheus/prometheus/schema/labels.go +++ b/vendor/github.com/prometheus/prometheus/schema/labels.go @@ -19,20 +19,10 @@ import ( "github.com/prometheus/prometheus/model/labels" ) -const ( - // Special label names and selectors for schema.Metadata fields. - // They are currently private to ensure __name__, __type__ and __unit__ are used - // together and remain extensible in Prometheus. See NewMetadataFromLabels and Metadata - // methods for the interactions with the labels package structs. - metricName = "__name__" - metricType = "__type__" - metricUnit = "__unit__" -) - // IsMetadataLabel returns true if the given label name is a special // schema Metadata label. func IsMetadataLabel(name string) bool { - return name == metricName || name == metricType || name == metricUnit + return name == model.MetricNameLabel || name == model.MetricTypeLabel || name == model.MetricUnitLabel } // Metadata represents the core metric schema/metadata elements that: @@ -79,13 +69,13 @@ type Metadata struct { // NewMetadataFromLabels returns the schema metadata from the labels. func NewMetadataFromLabels(ls labels.Labels) Metadata { typ := model.MetricTypeUnknown - if got := ls.Get(metricType); got != "" { + if got := ls.Get(model.MetricTypeLabel); got != "" { typ = model.MetricType(got) } return Metadata{ - Name: ls.Get(metricName), + Name: ls.Get(model.MetricNameLabel), Type: typ, - Unit: ls.Get(metricUnit), + Unit: ls.Get(model.MetricUnitLabel), } } @@ -99,11 +89,11 @@ func (m Metadata) IsTypeEmpty() bool { // IsEmptyFor returns true. func (m Metadata) IsEmptyFor(labelName string) bool { switch labelName { - case metricName: + case model.MetricNameLabel: return m.Name == "" - case metricType: + case model.MetricTypeLabel: return m.IsTypeEmpty() - case metricUnit: + case model.MetricUnitLabel: return m.Unit == "" default: return true @@ -114,13 +104,13 @@ func (m Metadata) IsEmptyFor(labelName string) bool { // Empty Metadata fields will be ignored (not added). func (m Metadata) AddToLabels(b *labels.ScratchBuilder) { if m.Name != "" { - b.Add(metricName, m.Name) + b.Add(model.MetricNameLabel, m.Name) } if !m.IsTypeEmpty() { - b.Add(metricType, string(m.Type)) + b.Add(model.MetricTypeLabel, string(m.Type)) } if m.Unit != "" { - b.Add(metricUnit, m.Unit) + b.Add(model.MetricUnitLabel, m.Unit) } } @@ -128,29 +118,33 @@ func (m Metadata) AddToLabels(b *labels.ScratchBuilder) { // It follows the labels.Builder.Set semantics, so empty Metadata fields will // remove the corresponding existing labels if they were previously set. func (m Metadata) SetToLabels(b *labels.Builder) { - b.Set(metricName, m.Name) + b.Set(model.MetricNameLabel, m.Name) if m.Type == model.MetricTypeUnknown { // Unknown equals empty semantically, so remove the label on unknown too as per // method signature comment. - b.Set(metricType, "") + b.Set(model.MetricTypeLabel, "") } else { - b.Set(metricType, string(m.Type)) + b.Set(model.MetricTypeLabel, string(m.Type)) } - b.Set(metricUnit, m.Unit) + b.Set(model.MetricUnitLabel, m.Unit) } -// IgnoreOverriddenMetadataLabelsScratchBuilder is a wrapper over labels scratch builder +// NewIgnoreOverriddenMetadataLabelScratchBuilder creates IgnoreOverriddenMetadataLabelScratchBuilder. +func (m Metadata) NewIgnoreOverriddenMetadataLabelScratchBuilder(b *labels.ScratchBuilder) *IgnoreOverriddenMetadataLabelScratchBuilder { + return &IgnoreOverriddenMetadataLabelScratchBuilder{ScratchBuilder: b, overwrite: m} +} + +// IgnoreOverriddenMetadataLabelScratchBuilder is a wrapper over labels.ScratchBuilder // that ignores label additions that would collide with non-empty Overwrite Metadata fields. -type IgnoreOverriddenMetadataLabelsScratchBuilder struct { +type IgnoreOverriddenMetadataLabelScratchBuilder struct { *labels.ScratchBuilder - - Overwrite Metadata + overwrite Metadata } // Add a name/value pair, unless it would collide with the non-empty Overwrite Metadata // field. Note if you Add the same name twice you will get a duplicate label, which is invalid. -func (b IgnoreOverriddenMetadataLabelsScratchBuilder) Add(name, value string) { - if !b.Overwrite.IsEmptyFor(name) { +func (b IgnoreOverriddenMetadataLabelScratchBuilder) Add(name, value string) { + if !b.overwrite.IsEmptyFor(name) { return } b.ScratchBuilder.Add(name, value) diff --git a/vendor/github.com/prometheus/prometheus/storage/fanout.go b/vendor/github.com/prometheus/prometheus/storage/fanout.go index 4d076788a7c..a699a97b023 100644 --- a/vendor/github.com/prometheus/prometheus/storage/fanout.go +++ b/vendor/github.com/prometheus/prometheus/storage/fanout.go @@ -199,14 +199,14 @@ func (f *fanoutAppender) AppendHistogram(ref SeriesRef, l labels.Labels, t int64 return ref, nil } -func (f *fanoutAppender) AppendHistogramCTZeroSample(ref SeriesRef, l labels.Labels, t, ct int64, h *histogram.Histogram, fh *histogram.FloatHistogram) (SeriesRef, error) { - ref, err := f.primary.AppendHistogramCTZeroSample(ref, l, t, ct, h, fh) +func (f *fanoutAppender) AppendHistogramSTZeroSample(ref SeriesRef, l labels.Labels, t, st int64, h *histogram.Histogram, fh *histogram.FloatHistogram) (SeriesRef, error) { + ref, err := f.primary.AppendHistogramSTZeroSample(ref, l, t, st, h, fh) if err != nil { return ref, err } for _, appender := range f.secondaries { - if _, err := appender.AppendHistogramCTZeroSample(ref, l, t, ct, h, fh); err != nil { + if _, err := appender.AppendHistogramSTZeroSample(ref, l, t, st, h, fh); err != nil { return 0, err } } @@ -227,14 +227,14 @@ func (f *fanoutAppender) UpdateMetadata(ref SeriesRef, l labels.Labels, m metada return ref, nil } -func (f *fanoutAppender) AppendCTZeroSample(ref SeriesRef, l labels.Labels, t, ct int64) (SeriesRef, error) { - ref, err := f.primary.AppendCTZeroSample(ref, l, t, ct) +func (f *fanoutAppender) AppendSTZeroSample(ref SeriesRef, l labels.Labels, t, st int64) (SeriesRef, error) { + ref, err := f.primary.AppendSTZeroSample(ref, l, t, st) if err != nil { return ref, err } for _, appender := range f.secondaries { - if _, err := appender.AppendCTZeroSample(ref, l, t, ct); err != nil { + if _, err := appender.AppendSTZeroSample(ref, l, t, st); err != nil { return 0, err } } @@ -253,7 +253,7 @@ func (f *fanoutAppender) Commit() (err error) { } } } - return + return err } func (f *fanoutAppender) Rollback() (err error) { diff --git a/vendor/github.com/prometheus/prometheus/storage/interface.go b/vendor/github.com/prometheus/prometheus/storage/interface.go index 5684460db0c..ae8bec033e5 100644 --- a/vendor/github.com/prometheus/prometheus/storage/interface.go +++ b/vendor/github.com/prometheus/prometheus/storage/interface.go @@ -44,13 +44,14 @@ var ( ErrExemplarsDisabled = errors.New("exemplar storage is disabled or max exemplars is less than or equal to 0") ErrNativeHistogramsDisabled = errors.New("native histograms are disabled") - // ErrOutOfOrderCT indicates failed append of CT to the storage - // due to CT being older the then newer sample. + // ErrOutOfOrderST indicates failed append of ST to the storage + // due to ST being older the then newer sample. // NOTE(bwplotka): This can be both an instrumentation failure or commonly expected // behaviour, and we currently don't have a way to determine this. As a result // it's recommended to ignore this error for now. - ErrOutOfOrderCT = errors.New("created timestamp out of order, ignoring") - ErrCTNewerThanSample = errors.New("CT is newer or the same as sample's timestamp, ignoring") + // TODO(bwplotka): Remove with appender v1 flow; not used in v2. + ErrOutOfOrderST = errors.New("start timestamp out of order, ignoring") + ErrSTNewerThanSample = errors.New("ST is newer or the same as sample's timestamp, ignoring") ) // SeriesRef is a generic series reference. In prometheus it is either a @@ -58,11 +59,14 @@ var ( // their own reference types. type SeriesRef uint64 -// Appendable allows creating appenders. +// Appendable allows creating Appender. +// +// WARNING: Work AppendableV2 is in progress. Appendable will be removed soon (ETA: Q2 2026). type Appendable interface { - // Appender returns a new appender for the storage. The implementation - // can choose whether or not to use the context, for deadlines or to check - // for errors. + // Appender returns a new appender for the storage. + // + // Implementations CAN choose whether to use the context e.g. for deadlines, + // but it's not mandatory. Appender(ctx context.Context) Appender } @@ -255,7 +259,13 @@ func (f QueryableFunc) Querier(mint, maxt int64) (Querier, error) { return f(mint, maxt) } +// AppendOptions provides options for implementations of the Appender interface. +// +// WARNING: Work AppendableV2 is in progress. Appendable will be removed soon (ETA: Q2 2026). type AppendOptions struct { + // DiscardOutOfOrder tells implementation that this append should not be out + // of order. An OOO append MUST be rejected with storage.ErrOutOfOrderSample + // error. DiscardOutOfOrder bool } @@ -264,9 +274,14 @@ type AppendOptions struct { // // Operations on the Appender interface are not goroutine-safe. // -// The type of samples (float64, histogram, etc) appended for a given series must remain same within an Appender. -// The behaviour is undefined if samples of different types are appended to the same series in a single Commit(). +// The order of samples appended via the Appender is preserved within each series. +// I.e. timestamp order within batch is not validated, samples are not reordered per timestamp or by float/histogram +// type. +// +// WARNING: Work AppendableV2 is in progress. Appendable will be removed soon (ETA: Q2 2026). type Appender interface { + AppenderTransaction + // Append adds a sample pair for the given series. // An optional series reference can be provided to accelerate calls. // A series reference number is returned which can be used to add further @@ -277,16 +292,6 @@ type Appender interface { // If the reference is 0 it must not be used for caching. Append(ref SeriesRef, l labels.Labels, t int64, v float64) (SeriesRef, error) - // Commit submits the collected samples and purges the batch. If Commit - // returns a non-nil error, it also rolls back all modifications made in - // the appender so far, as Rollback would do. In any case, an Appender - // must not be used anymore after Commit has been called. - Commit() error - - // Rollback rolls back all modifications made in the appender so far. - // Appender has to be discarded after rollback. - Rollback() error - // SetOptions configures the appender with specific append options such as // discarding out-of-order samples even if out-of-order is enabled in the TSDB. SetOptions(opts *AppendOptions) @@ -294,14 +299,14 @@ type Appender interface { ExemplarAppender HistogramAppender MetadataUpdater - CreatedTimestampAppender + StartTimestampAppender } // GetRef is an extra interface on Appenders used by downstream projects // (e.g. Cortex) to avoid maintaining a parallel set of references. type GetRef interface { - // Returns reference number that can be used to pass to Appender.Append(), - // and a set of labels that will not cause another copy when passed to Appender.Append(). + // GetRef returns a reference number that can be used to pass to AppenderV2.Append(), + // and a set of labels that will not cause another copy when passed to AppenderV2.Append(). // 0 means the appender does not have a reference to this series. // hash should be a hash of lset. GetRef(lset labels.Labels, hash uint64) (SeriesRef, labels.Labels) @@ -309,6 +314,8 @@ type GetRef interface { // ExemplarAppender provides an interface for adding samples to exemplar storage, which // within Prometheus is in-memory only. +// +// WARNING: Work AppendableV2 is in progress. Appendable will be removed soon (ETA: Q2 2026). type ExemplarAppender interface { // AppendExemplar adds an exemplar for the given series labels. // An optional reference number can be provided to accelerate calls. @@ -325,6 +332,8 @@ type ExemplarAppender interface { } // HistogramAppender provides an interface for appending histograms to the storage. +// +// WARNING: Work AppendableV2 is in progress. Appendable will be removed soon (ETA: Q2 2026). type HistogramAppender interface { // AppendHistogram adds a histogram for the given series labels. An // optional reference number can be provided to accelerate calls. A @@ -338,23 +347,25 @@ type HistogramAppender interface { // pointer. AppendHistogram won't mutate the histogram, but in turn // depends on the caller to not mutate it either. AppendHistogram(ref SeriesRef, l labels.Labels, t int64, h *histogram.Histogram, fh *histogram.FloatHistogram) (SeriesRef, error) - // AppendHistogramCTZeroSample adds synthetic zero sample for the given ct timestamp, + // AppendHistogramSTZeroSample adds synthetic zero sample for the given st timestamp, // which will be associated with given series, labels and the incoming - // sample's t (timestamp). AppendHistogramCTZeroSample returns error if zero sample can't be - // appended, for example when ct is too old, or when it would collide with + // sample's t (timestamp). AppendHistogramSTZeroSample returns error if zero sample can't be + // appended, for example when st is too old, or when it would collide with // incoming sample (sample has priority). // - // AppendHistogramCTZeroSample has to be called before the corresponding histogram AppendHistogram. + // AppendHistogramSTZeroSample has to be called before the corresponding histogram AppendHistogram. // A series reference number is returned which can be used to modify the - // CT for the given series in the same or later transactions. + // ST for the given series in the same or later transactions. // Returned reference numbers are ephemeral and may be rejected in calls - // to AppendHistogramCTZeroSample() at any point. + // to AppendHistogramSTZeroSample() at any point. // // If the reference is 0 it must not be used for caching. - AppendHistogramCTZeroSample(ref SeriesRef, l labels.Labels, t, ct int64, h *histogram.Histogram, fh *histogram.FloatHistogram) (SeriesRef, error) + AppendHistogramSTZeroSample(ref SeriesRef, l labels.Labels, t, st int64, h *histogram.Histogram, fh *histogram.FloatHistogram) (SeriesRef, error) } // MetadataUpdater provides an interface for associating metadata to stored series. +// +// WARNING: Work AppendableV2 is in progress. Appendable will be removed soon (ETA: Q2 2026). type MetadataUpdater interface { // UpdateMetadata updates a metadata entry for the given series and labels. // A series reference number is returned which can be used to modify the @@ -366,22 +377,24 @@ type MetadataUpdater interface { UpdateMetadata(ref SeriesRef, l labels.Labels, m metadata.Metadata) (SeriesRef, error) } -// CreatedTimestampAppender provides an interface for appending CT to storage. -type CreatedTimestampAppender interface { - // AppendCTZeroSample adds synthetic zero sample for the given ct timestamp, +// StartTimestampAppender provides an interface for appending ST to storage. +// +// WARNING: Work AppendableV2 is in progress. Appendable will be removed soon (ETA: Q2 2026). +type StartTimestampAppender interface { + // AppendSTZeroSample adds synthetic zero sample for the given st timestamp, // which will be associated with given series, labels and the incoming - // sample's t (timestamp). AppendCTZeroSample returns error if zero sample can't be - // appended, for example when ct is too old, or when it would collide with + // sample's t (timestamp). AppendSTZeroSample returns error if zero sample can't be + // appended, for example when st is too old, or when it would collide with // incoming sample (sample has priority). // - // AppendCTZeroSample has to be called before the corresponding sample Append. + // AppendSTZeroSample has to be called before the corresponding sample Append. // A series reference number is returned which can be used to modify the - // CT for the given series in the same or later transactions. + // ST for the given series in the same or later transactions. // Returned reference numbers are ephemeral and may be rejected in calls - // to AppendCTZeroSample() at any point. + // to AppendSTZeroSample() at any point. // // If the reference is 0 it must not be used for caching. - AppendCTZeroSample(ref SeriesRef, l labels.Labels, t, ct int64) (SeriesRef, error) + AppendSTZeroSample(ref SeriesRef, l labels.Labels, t, st int64) (SeriesRef, error) } // SeriesSet contains a set of series. @@ -389,10 +402,10 @@ type SeriesSet interface { Next() bool // At returns full series. Returned series should be iterable even after Next is called. At() Series - // The error that iteration as failed with. + // Err returns the error that iteration has failed with. // When an error occurs, set cannot continue to iterate. Err() error - // A collection of warnings for the whole set. + // Warnings returns a collection of warnings for the whole set. // Warnings could be return even iteration has not failed with error. Warnings() annotations.Annotations } diff --git a/vendor/github.com/prometheus/prometheus/storage/interface_append.go b/vendor/github.com/prometheus/prometheus/storage/interface_append.go new file mode 100644 index 00000000000..cc7045dbd58 --- /dev/null +++ b/vendor/github.com/prometheus/prometheus/storage/interface_append.go @@ -0,0 +1,182 @@ +// Copyright The Prometheus Authors +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package storage + +import ( + "context" + "errors" + + "github.com/prometheus/prometheus/model/exemplar" + "github.com/prometheus/prometheus/model/histogram" + "github.com/prometheus/prometheus/model/labels" + "github.com/prometheus/prometheus/model/metadata" +) + +// AppendableV2 allows creating AppenderV2. +type AppendableV2 interface { + // AppenderV2 returns a new appender for the storage. + // + // Implementations CAN choose whether to use the context e.g. for deadlines, + // but it's not mandatory. + AppenderV2(ctx context.Context) AppenderV2 +} + +// AOptions is a shorthand for AppendV2Options. +// NOTE: AppendOption is used already. +type AOptions = AppendV2Options + +// AppendV2Options provides optional, auxiliary data and configuration for AppenderV2.Append. +type AppendV2Options struct { + // MetricFamilyName (optional) provides metric family name for the appended sample's + // series. If the client of the AppenderV2 has this information + // (e.g. from scrape) it's recommended to pass it to the appender. + // + // Provided string bytes are unsafe to reuse, it only lives for the duration of the Append call. + // + // Some implementations use this to avoid slow and prone to error metric family detection for: + // * Metadata per metric family storages (e.g. Prometheus metadata WAL/API/RW1) + // * Strictly complex types storages (e.g. OpenTelemetry Collector). + // + // NOTE(krajorama): Example purpose is highlighted in OTLP ingestion: OTLP calculates the + // metric family name for all metrics and uses it for generating summary, + // histogram series by adding the magic suffixes. The metric family name is + // passed down to the appender in case the storage needs it for metadata updates. + // Known user of this is Mimir that implements /api/v1/metadata and uses + // Remote-Write 1.0 for this. Might be removed later if no longer + // needed by any downstream project. + // NOTE(bwplotka): Long term, once Prometheus uses complex types on storage level + // the MetricFamilyName can be removed as MetricFamilyName will equal to __name__ always. + MetricFamilyName string + + // Metadata (optional) attached to the appended sample. + // Metadata strings are safe for reuse. + // IMPORTANT: Appender v1 was only providing update. This field MUST be + // set (if known) even if it didn't change since the last iteration. + // This moves the responsibility for metadata storage options to TSDB. + Metadata metadata.Metadata + + // Exemplars (optional) attached to the appended sample. + // Exemplar slice MUST be sorted by Exemplar.TS. + // Exemplar slice is unsafe for reuse. + Exemplars []exemplar.Exemplar + + // RejectOutOfOrder tells implementation that this append should not be out + // of order. An OOO append MUST be rejected with storage.ErrOutOfOrderSample + // error. + RejectOutOfOrder bool +} + +// AppendPartialError represents an AppenderV2.Append error that tells +// callers sample was written but some auxiliary optional data (e.g. exemplars) +// was not (or partially written) +// +// It's up to the caller to decide if it's an ignorable error or not, plus +// it allows extra reporting (e.g. for Remote Write 2.0 X-Remote-Write-Written headers). +type AppendPartialError struct { + ExemplarErrors []error +} + +// Error returns combined error string. +func (e *AppendPartialError) Error() string { + errs := errors.Join(e.ExemplarErrors...) + if errs == nil { + return "" + } + return errs.Error() +} + +var _ error = &AppendPartialError{} + +// AppenderV2 provides appends against a storage for all types of samples. +// It must be completed with a call to Commit or Rollback and must not be reused afterwards. +// +// Operations on the AppenderV2 interface are not goroutine-safe. +// +// The order of samples appended via the AppenderV2 is preserved within each series. +// I.e. timestamp order within batch is not validated, samples are not reordered per timestamp or by float/histogram +// type. +type AppenderV2 interface { + AppenderTransaction + + // Append appends a sample and related exemplars, metadata, and start timestamp (st) to the storage. + // + // ref (optional) represents the stable ID for the given series identified by ls (excluding metadata). + // Callers MAY provide the ref to help implementation avoid ls -> ref computation, otherwise ref MUST be 0 (unknown). + // + // ls represents labels for the sample's series. + // + // st (optional) represents sample start timestamp. 0 means unknown. Implementations + // are responsible for any potential ST storage logic (e.g. ST zero injections). + // + // t represents sample timestamp. + // + // v, h, fh represents sample value for each sample type. + // Callers MUST only provide one of the sample types (either v, h or fh). + // Implementations can detect the type of the sample with the following switch: + // + // switch { + // case fh != nil: It's a float histogram append. + // case h != nil: It's a histogram append. + // default: It's a float append. + // } + // TODO(bwplotka): We plan to experiment on using generics for complex sampleType, but do it after we unify interface (derisk) and before we add native summaries. + // + // Implementations MUST attempt to append sample even if metadata, exemplar or (st) start timestamp appends fail. + // Implementations MAY return AppendPartialError as an error. Use errors.As to detect. + // For the successful Append, Implementations MUST return valid SeriesRef that represents ls. + // NOTE(bwplotka): Given OTLP and native histograms and the relaxation of the requirement for + // type and unit suffixes in metric names we start to hit cases of ls being not enough for id + // of the series (metadata matters). Current solution is to enable 'type-and-unit-label' features for those cases, but we may + // start to extend the id with metadata one day. + Append(ref SeriesRef, ls labels.Labels, st, t int64, v float64, h *histogram.Histogram, fh *histogram.FloatHistogram, opts AppendV2Options) (SeriesRef, error) +} + +// AppenderTransaction allows transactional appends. +type AppenderTransaction interface { + // Commit submits the collected samples and purges the batch. If Commit + // returns a non-nil error, it also rolls back all modifications made in + // the appender so far, as Rollback would do. In any case, an Appender + // must not be used anymore after Commit has been called. + Commit() error + + // Rollback rolls back all modifications made in the appender so far. + // Appender has to be discarded after rollback. + Rollback() error +} + +// LimitedAppenderV1 is an Appender that only supports appending float and histogram samples. +// This is to support migration to AppenderV2. +// TODO(bwplotka): Remove once migration to AppenderV2 is fully complete. +type LimitedAppenderV1 interface { + Append(ref SeriesRef, l labels.Labels, t int64, v float64) (SeriesRef, error) + AppendHistogram(ref SeriesRef, l labels.Labels, t int64, h *histogram.Histogram, fh *histogram.FloatHistogram) (SeriesRef, error) +} + +// AppenderV2AsLimitedV1 returns appender that exposes AppenderV2 as LimitedAppenderV1 +// TODO(bwplotka): Remove once migration to AppenderV2 is fully complete. +func AppenderV2AsLimitedV1(app AppenderV2) LimitedAppenderV1 { + return &limitedAppenderV1{AppenderV2: app} +} + +type limitedAppenderV1 struct { + AppenderV2 +} + +func (a *limitedAppenderV1) Append(ref SeriesRef, l labels.Labels, t int64, v float64) (SeriesRef, error) { + return a.AppenderV2.Append(ref, l, 0, t, v, nil, nil, AppendV2Options{}) +} + +func (a *limitedAppenderV1) AppendHistogram(ref SeriesRef, l labels.Labels, t int64, h *histogram.Histogram, fh *histogram.FloatHistogram) (SeriesRef, error) { + return a.AppenderV2.Append(ref, l, 0, t, 0, h, fh, AppendV2Options{}) +} diff --git a/vendor/github.com/prometheus/prometheus/template/template.go b/vendor/github.com/prometheus/prometheus/template/template.go index 295380cc83c..572e8450d35 100644 --- a/vendor/github.com/prometheus/prometheus/template/template.go +++ b/vendor/github.com/prometheus/prometheus/template/template.go @@ -36,6 +36,7 @@ import ( "golang.org/x/text/language" "github.com/prometheus/prometheus/promql" + "github.com/prometheus/prometheus/util/features" "github.com/prometheus/prometheus/util/strutil" ) @@ -288,6 +289,7 @@ func NewTemplateExpander( } return float64(time.Duration(v)) / float64(time.Second), nil }, + "urlQueryEscape": url.QueryEscape, }, options: options, } @@ -412,3 +414,29 @@ func floatToTime(v float64) (*time.Time, error) { t := model.TimeFromUnixNano(int64(timestamp)).Time().UTC() return &t, nil } + +// templateFunctions returns a representative funcMap with all available template functions. +// This is used to discover which functions are available for feature registration. +func templateFunctions() text_template.FuncMap { + // Create a dummy expander to get the function map. + expander := NewTemplateExpander( + context.Background(), + "", + "", + nil, + 0, + nil, + &url.URL{}, + nil, + ) + return expander.funcMap +} + +// RegisterFeatures registers all template functions with the feature registry. +func RegisterFeatures(r features.Collector) { + // Get all function names from the template function map. + funcMap := templateFunctions() + for name := range funcMap { + r.Enable(features.TemplatingFunctions, name) + } +} diff --git a/vendor/github.com/prometheus/prometheus/tsdb/chunkenc/float_histogram.go b/vendor/github.com/prometheus/prometheus/tsdb/chunkenc/float_histogram.go index d80b1d9bcc4..d960e835f25 100644 --- a/vendor/github.com/prometheus/prometheus/tsdb/chunkenc/float_histogram.go +++ b/vendor/github.com/prometheus/prometheus/tsdb/chunkenc/float_histogram.go @@ -230,59 +230,59 @@ func (a *FloatHistogramAppender) appendable(h *histogram.FloatHistogram) ( okToAppend, counterReset bool, ) { if a.NumSamples() > 0 && a.GetCounterResetHeader() == GaugeType { - return + return positiveInserts, negativeInserts, backwardPositiveInserts, backwardNegativeInserts, okToAppend, counterReset } if h.CounterResetHint == histogram.CounterReset { // Always honor the explicit counter reset hint. counterReset = true - return + return positiveInserts, negativeInserts, backwardPositiveInserts, backwardNegativeInserts, okToAppend, counterReset } if value.IsStaleNaN(h.Sum) { // This is a stale sample whose buckets and spans don't matter. okToAppend = true - return + return positiveInserts, negativeInserts, backwardPositiveInserts, backwardNegativeInserts, okToAppend, counterReset } if value.IsStaleNaN(a.sum.value) { // If the last sample was stale, then we can only accept stale // samples in this chunk. - return + return positiveInserts, negativeInserts, backwardPositiveInserts, backwardNegativeInserts, okToAppend, counterReset } if h.Count < a.cnt.value { // There has been a counter reset. counterReset = true - return + return positiveInserts, negativeInserts, backwardPositiveInserts, backwardNegativeInserts, okToAppend, counterReset } if h.Schema != a.schema || h.ZeroThreshold != a.zThreshold { - return + return positiveInserts, negativeInserts, backwardPositiveInserts, backwardNegativeInserts, okToAppend, counterReset } - if histogram.IsCustomBucketsSchema(h.Schema) && !histogram.FloatBucketsMatch(h.CustomValues, a.customValues) { + if histogram.IsCustomBucketsSchema(h.Schema) && !histogram.CustomBucketBoundsMatch(h.CustomValues, a.customValues) { counterReset = true - return + return positiveInserts, negativeInserts, backwardPositiveInserts, backwardNegativeInserts, okToAppend, counterReset } if h.ZeroCount < a.zCnt.value { // There has been a counter reset since ZeroThreshold didn't change. counterReset = true - return + return positiveInserts, negativeInserts, backwardPositiveInserts, backwardNegativeInserts, okToAppend, counterReset } var ok bool positiveInserts, backwardPositiveInserts, ok = expandFloatSpansAndBuckets(a.pSpans, h.PositiveSpans, a.pBuckets, h.PositiveBuckets) if !ok { counterReset = true - return + return positiveInserts, negativeInserts, backwardPositiveInserts, backwardNegativeInserts, okToAppend, counterReset } negativeInserts, backwardNegativeInserts, ok = expandFloatSpansAndBuckets(a.nSpans, h.NegativeSpans, a.nBuckets, h.NegativeBuckets) if !ok { counterReset = true - return + return positiveInserts, negativeInserts, backwardPositiveInserts, backwardNegativeInserts, okToAppend, counterReset } okToAppend = true - return + return positiveInserts, negativeInserts, backwardPositiveInserts, backwardNegativeInserts, okToAppend, counterReset } // expandFloatSpansAndBuckets returns the inserts to expand the bucket spans 'a' so that @@ -478,31 +478,31 @@ func (a *FloatHistogramAppender) appendableGauge(h *histogram.FloatHistogram) ( okToAppend bool, ) { if a.NumSamples() > 0 && a.GetCounterResetHeader() != GaugeType { - return + return positiveInserts, negativeInserts, backwardPositiveInserts, backwardNegativeInserts, positiveSpans, negativeSpans, okToAppend } if value.IsStaleNaN(h.Sum) { // This is a stale sample whose buckets and spans don't matter. okToAppend = true - return + return positiveInserts, negativeInserts, backwardPositiveInserts, backwardNegativeInserts, positiveSpans, negativeSpans, okToAppend } if value.IsStaleNaN(a.sum.value) { // If the last sample was stale, then we can only accept stale // samples in this chunk. - return + return positiveInserts, negativeInserts, backwardPositiveInserts, backwardNegativeInserts, positiveSpans, negativeSpans, okToAppend } if h.Schema != a.schema || h.ZeroThreshold != a.zThreshold { - return + return positiveInserts, negativeInserts, backwardPositiveInserts, backwardNegativeInserts, positiveSpans, negativeSpans, okToAppend } - if histogram.IsCustomBucketsSchema(h.Schema) && !histogram.FloatBucketsMatch(h.CustomValues, a.customValues) { - return + if histogram.IsCustomBucketsSchema(h.Schema) && !histogram.CustomBucketBoundsMatch(h.CustomValues, a.customValues) { + return positiveInserts, negativeInserts, backwardPositiveInserts, backwardNegativeInserts, positiveSpans, negativeSpans, okToAppend } positiveInserts, backwardPositiveInserts, positiveSpans = expandSpansBothWays(a.pSpans, h.PositiveSpans) negativeInserts, backwardNegativeInserts, negativeSpans = expandSpansBothWays(a.nSpans, h.NegativeSpans) okToAppend = true - return + return positiveInserts, negativeInserts, backwardPositiveInserts, backwardNegativeInserts, positiveSpans, negativeSpans, okToAppend } // appendFloatHistogram appends a float histogram to the chunk. The caller must ensure that @@ -884,7 +884,14 @@ func (it *floatHistogramIterator) AtFloatHistogram(fh *histogram.FloatHistogram) // chunk is from a newer Prometheus version that supports higher // resolution. fh = fh.Copy() - fh.ReduceResolution(histogram.ExponentialSchemaMax) + if err := fh.ReduceResolution(histogram.ExponentialSchemaMax); err != nil { + // With the checks above, this can only happen + // with invalid data in a chunk. As this is a + // rare edge case of a rare edge case, we'd + // rather not create all the plumbing to handle + // this error gracefully. + panic(err) + } } return it.t, fh } @@ -915,7 +922,13 @@ func (it *floatHistogramIterator) AtFloatHistogram(fh *histogram.FloatHistogram) // This is a very slow path, but it should only happen if the // chunk is from a newer Prometheus version that supports higher // resolution. - fh.ReduceResolution(histogram.ExponentialSchemaMax) + if err := fh.ReduceResolution(histogram.ExponentialSchemaMax); err != nil { + // With the checks above, this can only happen with + // invalid data in a chunk. As this is a rare edge case + // of a rare edge case, we'd rather not create all the + // plumbing to handle this error gracefully. + panic(err) + } } return it.t, fh diff --git a/vendor/github.com/prometheus/prometheus/tsdb/chunkenc/histogram.go b/vendor/github.com/prometheus/prometheus/tsdb/chunkenc/histogram.go index 9c433fc5e5a..be1c31ae76e 100644 --- a/vendor/github.com/prometheus/prometheus/tsdb/chunkenc/histogram.go +++ b/vendor/github.com/prometheus/prometheus/tsdb/chunkenc/histogram.go @@ -260,29 +260,29 @@ func (a *HistogramAppender) appendable(h *histogram.Histogram) ( ) { counterResetHint = NotCounterReset if a.NumSamples() > 0 && a.GetCounterResetHeader() == GaugeType { - return + return positiveInserts, negativeInserts, backwardPositiveInserts, backwardNegativeInserts, okToAppend, counterResetHint } if h.CounterResetHint == histogram.CounterReset { // Always honor the explicit counter reset hint. counterResetHint = CounterReset - return + return positiveInserts, negativeInserts, backwardPositiveInserts, backwardNegativeInserts, okToAppend, counterResetHint } if value.IsStaleNaN(h.Sum) { // This is a stale sample whose buckets and spans don't matter. okToAppend = true - return + return positiveInserts, negativeInserts, backwardPositiveInserts, backwardNegativeInserts, okToAppend, counterResetHint } if value.IsStaleNaN(a.sum) { // If the last sample was stale, then we can only accept stale // samples in this chunk. counterResetHint = UnknownCounterReset - return + return positiveInserts, negativeInserts, backwardPositiveInserts, backwardNegativeInserts, okToAppend, counterResetHint } if h.Count < a.cnt { // There has been a counter reset. counterResetHint = CounterReset - return + return positiveInserts, negativeInserts, backwardPositiveInserts, backwardNegativeInserts, okToAppend, counterResetHint } if h.Schema != a.schema || h.ZeroThreshold != a.zThreshold { @@ -291,34 +291,34 @@ func (a *HistogramAppender) appendable(h *histogram.Histogram) ( // as long as https://github.com/prometheus/prometheus/issues/15346 is still open. // TODO: consider adding the counter reset detection here once #15346 is fixed. counterResetHint = UnknownCounterReset - return + return positiveInserts, negativeInserts, backwardPositiveInserts, backwardNegativeInserts, okToAppend, counterResetHint } - if histogram.IsCustomBucketsSchema(h.Schema) && !histogram.FloatBucketsMatch(h.CustomValues, a.customValues) { + if histogram.IsCustomBucketsSchema(h.Schema) && !histogram.CustomBucketBoundsMatch(h.CustomValues, a.customValues) { counterResetHint = CounterReset - return + return positiveInserts, negativeInserts, backwardPositiveInserts, backwardNegativeInserts, okToAppend, counterResetHint } if h.ZeroCount < a.zCnt { // There has been a counter reset since ZeroThreshold didn't change. counterResetHint = CounterReset - return + return positiveInserts, negativeInserts, backwardPositiveInserts, backwardNegativeInserts, okToAppend, counterResetHint } var ok bool positiveInserts, backwardPositiveInserts, ok = expandIntSpansAndBuckets(a.pSpans, h.PositiveSpans, a.pBuckets, h.PositiveBuckets) if !ok { counterResetHint = CounterReset - return + return positiveInserts, negativeInserts, backwardPositiveInserts, backwardNegativeInserts, okToAppend, counterResetHint } negativeInserts, backwardNegativeInserts, ok = expandIntSpansAndBuckets(a.nSpans, h.NegativeSpans, a.nBuckets, h.NegativeBuckets) if !ok { counterResetHint = CounterReset - return + return positiveInserts, negativeInserts, backwardPositiveInserts, backwardNegativeInserts, okToAppend, counterResetHint } okToAppend = true - return + return positiveInserts, negativeInserts, backwardPositiveInserts, backwardNegativeInserts, okToAppend, counterResetHint } // expandIntSpansAndBuckets returns the inserts to expand the bucket spans 'a' so that @@ -515,31 +515,31 @@ func (a *HistogramAppender) appendableGauge(h *histogram.Histogram) ( okToAppend bool, ) { if a.NumSamples() > 0 && a.GetCounterResetHeader() != GaugeType { - return + return positiveInserts, negativeInserts, backwardPositiveInserts, backwardNegativeInserts, positiveSpans, negativeSpans, okToAppend } if value.IsStaleNaN(h.Sum) { // This is a stale sample whose buckets and spans don't matter. okToAppend = true - return + return positiveInserts, negativeInserts, backwardPositiveInserts, backwardNegativeInserts, positiveSpans, negativeSpans, okToAppend } if value.IsStaleNaN(a.sum) { // If the last sample was stale, then we can only accept stale // samples in this chunk. - return + return positiveInserts, negativeInserts, backwardPositiveInserts, backwardNegativeInserts, positiveSpans, negativeSpans, okToAppend } if h.Schema != a.schema || h.ZeroThreshold != a.zThreshold { - return + return positiveInserts, negativeInserts, backwardPositiveInserts, backwardNegativeInserts, positiveSpans, negativeSpans, okToAppend } - if histogram.IsCustomBucketsSchema(h.Schema) && !histogram.FloatBucketsMatch(h.CustomValues, a.customValues) { - return + if histogram.IsCustomBucketsSchema(h.Schema) && !histogram.CustomBucketBoundsMatch(h.CustomValues, a.customValues) { + return positiveInserts, negativeInserts, backwardPositiveInserts, backwardNegativeInserts, positiveSpans, negativeSpans, okToAppend } positiveInserts, backwardPositiveInserts, positiveSpans = expandSpansBothWays(a.pSpans, h.PositiveSpans) negativeInserts, backwardNegativeInserts, negativeSpans = expandSpansBothWays(a.nSpans, h.NegativeSpans) okToAppend = true - return + return positiveInserts, negativeInserts, backwardPositiveInserts, backwardNegativeInserts, positiveSpans, negativeSpans, okToAppend } // appendHistogram appends a histogram to the chunk. The caller must ensure that @@ -939,7 +939,14 @@ func (it *histogramIterator) AtHistogram(h *histogram.Histogram) (int64, *histog // chunk is from a newer Prometheus version that supports higher // resolution. h = h.Copy() - h.ReduceResolution(histogram.ExponentialSchemaMax) + if err := h.ReduceResolution(histogram.ExponentialSchemaMax); err != nil { + // With the checks above, this can only happen + // with invalid data in a chunk. As this is a + // rare edge case of a rare edge case, we'd + // rather not create all the plumbing to handle + // this error gracefully. + panic(err) + } } return it.t, h } @@ -970,7 +977,13 @@ func (it *histogramIterator) AtHistogram(h *histogram.Histogram) (int64, *histog // This is a very slow path, but it should only happen if the // chunk is from a newer Prometheus version that supports higher // resolution. - h.ReduceResolution(histogram.ExponentialSchemaMax) + if err := h.ReduceResolution(histogram.ExponentialSchemaMax); err != nil { + // With the checks above, this can only happen with + // invalid data in a chunk. As this is a rare edge case + // of a rare edge case, we'd rather not create all the + // plumbing to handle this error gracefully. + panic(err) + } } return it.t, h @@ -1000,7 +1013,14 @@ func (it *histogramIterator) AtFloatHistogram(fh *histogram.FloatHistogram) (int // chunk is from a newer Prometheus version that supports higher // resolution. fh = fh.Copy() - fh.ReduceResolution(histogram.ExponentialSchemaMax) + if err := fh.ReduceResolution(histogram.ExponentialSchemaMax); err != nil { + // With the checks above, this can only happen + // with invalid data in a chunk. As this is a + // rare edge case of a rare edge case, we'd + // rather not create all the plumbing to handle + // this error gracefully. + panic(err) + } } return it.t, fh } @@ -1039,7 +1059,13 @@ func (it *histogramIterator) AtFloatHistogram(fh *histogram.FloatHistogram) (int // This is a very slow path, but it should only happen if the // chunk is from a newer Prometheus version that supports higher // resolution. - fh.ReduceResolution(histogram.ExponentialSchemaMax) + if err := fh.ReduceResolution(histogram.ExponentialSchemaMax); err != nil { + // With the checks above, this can only happen with + // invalid data in a chunk. As this is a rare edge case + // of a rare edge case, we'd rather not create all the + // plumbing to handle this error gracefully. + panic(err) + } } return it.t, fh diff --git a/vendor/github.com/prometheus/prometheus/tsdb/chunkenc/histogram_meta.go b/vendor/github.com/prometheus/prometheus/tsdb/chunkenc/histogram_meta.go index 5ee783fd683..22bc4a6d3dc 100644 --- a/vendor/github.com/prometheus/prometheus/tsdb/chunkenc/histogram_meta.go +++ b/vendor/github.com/prometheus/prometheus/tsdb/chunkenc/histogram_meta.go @@ -40,33 +40,33 @@ func readHistogramChunkLayout(b *bstreamReader) ( ) { zeroThreshold, err = readZeroThreshold(b) if err != nil { - return + return schema, zeroThreshold, positiveSpans, negativeSpans, customValues, err } v, err := readVarbitInt(b) if err != nil { - return + return schema, zeroThreshold, positiveSpans, negativeSpans, customValues, err } schema = int32(v) positiveSpans, err = readHistogramChunkLayoutSpans(b) if err != nil { - return + return schema, zeroThreshold, positiveSpans, negativeSpans, customValues, err } negativeSpans, err = readHistogramChunkLayoutSpans(b) if err != nil { - return + return schema, zeroThreshold, positiveSpans, negativeSpans, customValues, err } if histogram.IsCustomBucketsSchema(schema) { customValues, err = readHistogramChunkLayoutCustomBounds(b) if err != nil { - return + return schema, zeroThreshold, positiveSpans, negativeSpans, customValues, err } } - return + return schema, zeroThreshold, positiveSpans, negativeSpans, customValues, err } func putHistogramChunkLayoutSpans(b *bstream, spans []histogram.Span) { @@ -550,5 +550,5 @@ func adjustForInserts(spans []histogram.Span, inserts []Insert) (mergedSpans []h addBucket(insertIdx) consumeInsert() } - return + return mergedSpans } diff --git a/vendor/github.com/prometheus/prometheus/tsdb/chunks/chunks.go b/vendor/github.com/prometheus/prometheus/tsdb/chunks/chunks.go index 034106238e3..8b8f5d0f812 100644 --- a/vendor/github.com/prometheus/prometheus/tsdb/chunks/chunks.go +++ b/vendor/github.com/prometheus/prometheus/tsdb/chunks/chunks.go @@ -197,7 +197,7 @@ func ChunkFromSamplesGeneric(s Samples) (Meta, error) { // Used in tests to compare the content of chunks. func ChunkMetasToSamples(chunks []Meta) (result []Sample) { if len(chunks) == 0 { - return + return result } for _, chunk := range chunks { @@ -218,7 +218,7 @@ func ChunkMetasToSamples(chunks []Meta) (result []Sample) { } } } - return + return result } // Iterator iterates over the chunks of a single time series. @@ -408,7 +408,7 @@ func (w *Writer) cut() error { // Uncached IO is implemented using direct I/O for now. wbuf, err = fileutil.NewDirectIOWriter(f, size) } else { - wbuf, err = fileutil.NewBufioWriterWithSeek(f, size) + wbuf, err = fileutil.NewBufioWriterWithSize(f, size) } if err != nil { return err diff --git a/vendor/github.com/prometheus/prometheus/tsdb/chunks/head_chunks.go b/vendor/github.com/prometheus/prometheus/tsdb/chunks/head_chunks.go index 41fce69c723..5e143b8b322 100644 --- a/vendor/github.com/prometheus/prometheus/tsdb/chunks/head_chunks.go +++ b/vendor/github.com/prometheus/prometheus/tsdb/chunks/head_chunks.go @@ -20,6 +20,7 @@ import ( "fmt" "hash" "io" + "math" "os" "path/filepath" "slices" @@ -768,8 +769,25 @@ func (cdm *ChunkDiskMapper) Chunk(ref ChunkDiskMapperRef) (chunkenc.Chunk, error } } + if chkDataLen > uint64(math.MaxInt) { + return nil, &CorruptionErr{ + Dir: cdm.dir.Name(), + FileIndex: sgmIndex, + Err: fmt.Errorf("chunk length %d exceeds supported size", chkDataLen), + } + } + + chkDataLenInt := int(chkDataLen) + if chkDataLenStart > math.MaxInt-n-chkDataLenInt { + return nil, &CorruptionErr{ + Dir: cdm.dir.Name(), + FileIndex: sgmIndex, + Err: fmt.Errorf("chunk data end overflows supported size (start=%d, len=%d, n=%d)", chkDataLenStart, chkDataLenInt, n), + } + } + // Verify the chunk data end. - chkDataEnd := chkDataLenStart + n + int(chkDataLen) + chkDataEnd := chkDataLenStart + n + chkDataLenInt if chkDataEnd > mmapFile.byteSlice.Len() { return nil, &CorruptionErr{ Dir: cdm.dir.Name(), diff --git a/vendor/github.com/prometheus/prometheus/tsdb/fileutil/direct_io_force.go b/vendor/github.com/prometheus/prometheus/tsdb/fileutil/direct_io_force.go index e2f811b9f2a..bb65403911f 100644 --- a/vendor/github.com/prometheus/prometheus/tsdb/fileutil/direct_io_force.go +++ b/vendor/github.com/prometheus/prometheus/tsdb/fileutil/direct_io_force.go @@ -23,6 +23,6 @@ func NewDirectIOWriter(f *os.File, size int) (BufWriter, error) { return newDirectIOWriter(f, size) } -func NewBufioWriterWithSeek(f *os.File, size int) (BufWriter, error) { +func NewBufioWriterWithSize(f *os.File, size int) (BufWriter, error) { return NewDirectIOWriter(f, size) } diff --git a/vendor/github.com/prometheus/prometheus/tsdb/fileutil/direct_io_linux.go b/vendor/github.com/prometheus/prometheus/tsdb/fileutil/direct_io_linux.go index 7406cc1594b..a1d5f9577db 100644 --- a/vendor/github.com/prometheus/prometheus/tsdb/fileutil/direct_io_linux.go +++ b/vendor/github.com/prometheus/prometheus/tsdb/fileutil/direct_io_linux.go @@ -20,7 +20,7 @@ import ( "os" ) -func NewBufioWriterWithSeek(f *os.File, size int) (BufWriter, error) { +func NewBufioWriterWithSize(f *os.File, size int) (BufWriter, error) { return &writer{bufio.NewWriterSize(f, size)}, nil } diff --git a/vendor/github.com/prometheus/prometheus/tsdb/fileutil/direct_io_unsupported.go b/vendor/github.com/prometheus/prometheus/tsdb/fileutil/direct_io_unsupported.go index 3e3555ebf8e..a03782fe428 100644 --- a/vendor/github.com/prometheus/prometheus/tsdb/fileutil/direct_io_unsupported.go +++ b/vendor/github.com/prometheus/prometheus/tsdb/fileutil/direct_io_unsupported.go @@ -20,7 +20,7 @@ import ( "os" ) -func NewBufioWriterWithSeek(f *os.File, size int) (BufWriter, error) { +func NewBufioWriterWithSize(f *os.File, size int) (BufWriter, error) { return &writer{bufio.NewWriterSize(f, size)}, nil } diff --git a/vendor/github.com/prometheus/prometheus/util/annotations/annotations.go b/vendor/github.com/prometheus/prometheus/util/annotations/annotations.go index bbd3b0927fb..817f670b5e8 100644 --- a/vendor/github.com/prometheus/prometheus/util/annotations/annotations.go +++ b/vendor/github.com/prometheus/prometheus/util/annotations/annotations.go @@ -107,7 +107,7 @@ func (a Annotations) AsStrings(query string, maxWarnings, maxInfos int) (warning if infoSkipped > 0 { infos = append(infos, fmt.Sprintf("%d more info annotations omitted", infoSkipped)) } - return + return warnings, infos } // CountWarningsAndInfo counts and returns the number of warnings and infos in the @@ -121,7 +121,7 @@ func (a Annotations) CountWarningsAndInfo() (countWarnings, countInfo int) { countInfo++ } } - return + return countWarnings, countInfo } //nolint:staticcheck,revive // error-naming. @@ -134,16 +134,15 @@ var ( PromQLInfo = errors.New("PromQL info") PromQLWarning = errors.New("PromQL warning") - InvalidRatioWarning = fmt.Errorf("%w: ratio value should be between -1 and 1", PromQLWarning) - InvalidQuantileWarning = fmt.Errorf("%w: quantile value should be between 0 and 1", PromQLWarning) - BadBucketLabelWarning = fmt.Errorf("%w: bucket label %q is missing or has a malformed value", PromQLWarning, model.BucketLabel) - MixedFloatsHistogramsWarning = fmt.Errorf("%w: encountered a mix of histograms and floats for", PromQLWarning) - MixedClassicNativeHistogramsWarning = fmt.Errorf("%w: vector contains a mix of classic and native histograms", PromQLWarning) - NativeHistogramNotCounterWarning = fmt.Errorf("%w: this native histogram metric is not a counter:", PromQLWarning) - NativeHistogramNotGaugeWarning = fmt.Errorf("%w: this native histogram metric is not a gauge:", PromQLWarning) - MixedExponentialCustomHistogramsWarning = fmt.Errorf("%w: vector contains a mix of histograms with exponential and custom buckets schemas for metric name", PromQLWarning) - IncompatibleCustomBucketsHistogramsWarning = fmt.Errorf("%w: vector contains histograms with incompatible custom buckets for metric name", PromQLWarning) - IncompatibleBucketLayoutInBinOpWarning = fmt.Errorf("%w: incompatible bucket layout encountered for binary operator", PromQLWarning) + InvalidRatioWarning = fmt.Errorf("%w: ratio value should be between -1 and 1", PromQLWarning) + InvalidQuantileWarning = fmt.Errorf("%w: quantile value should be between 0 and 1", PromQLWarning) + BadBucketLabelWarning = fmt.Errorf("%w: bucket label %q is missing or has a malformed value", PromQLWarning, model.BucketLabel) + MixedFloatsHistogramsWarning = fmt.Errorf("%w: encountered a mix of histograms and floats for", PromQLWarning) + MixedClassicNativeHistogramsWarning = fmt.Errorf("%w: vector contains a mix of classic and native histograms", PromQLWarning) + NativeHistogramNotCounterWarning = fmt.Errorf("%w: this native histogram metric is not a counter:", PromQLWarning) + NativeHistogramNotGaugeWarning = fmt.Errorf("%w: this native histogram metric is not a gauge:", PromQLWarning) + MixedExponentialCustomHistogramsWarning = fmt.Errorf("%w: vector contains a mix of histograms with exponential and custom buckets schemas for metric name", PromQLWarning) + IncompatibleBucketLayoutInBinOpWarning = fmt.Errorf("%w: incompatible bucket layout encountered for binary operator", PromQLWarning) PossibleNonCounterInfo = fmt.Errorf("%w: metric might not be a counter, name does not end in _total/_sum/_count/_bucket:", PromQLInfo) PossibleNonCounterLabelInfo = fmt.Errorf("%w: metric might not be a counter, __type__ label is not set to %q or %q", PromQLInfo, model.MetricTypeCounter, model.MetricTypeHistogram) @@ -155,6 +154,7 @@ var ( NativeHistogramQuantileNaNSkewInfo = fmt.Errorf("%w: input to histogram_quantile has NaN observations, result is skewed higher", PromQLInfo) NativeHistogramFractionNaNsInfo = fmt.Errorf("%w: input to histogram_fraction has NaN observations, which are excluded from all fractions", PromQLInfo) HistogramCounterResetCollisionWarning = fmt.Errorf("%w: conflicting counter resets during histogram", PromQLWarning) + MismatchedCustomBucketsHistogramsInfo = fmt.Errorf("%w: mismatched custom buckets were reconciled during", PromQLInfo) ) type annoErr struct { @@ -264,15 +264,6 @@ func NewMixedExponentialCustomHistogramsWarning(metricName string, pos posrange. } } -// NewIncompatibleCustomBucketsHistogramsWarning is used when the queried series includes -// custom buckets histograms with incompatible custom bounds. -func NewIncompatibleCustomBucketsHistogramsWarning(metricName string, pos posrange.PositionRange) error { - return annoErr{ - PositionRange: pos, - Err: fmt.Errorf("%w %q", IncompatibleCustomBucketsHistogramsWarning, metricName), - } -} - // NewPossibleNonCounterInfo is used when a named counter metric with only float samples does not // have the suffixes _total, _sum, _count, or _bucket. func NewPossibleNonCounterInfo(metricName string, pos posrange.PositionRange) error { @@ -365,16 +356,29 @@ const ( HistogramAgg HistogramOperation = "aggregation" ) +func (op HistogramOperation) String() string { + switch op { + case HistogramAdd, HistogramSub, HistogramAgg: + return string(op) + default: + return "unknown operation" + } +} + // NewHistogramCounterResetCollisionWarning is used when two counter histograms are added or subtracted where one has // a CounterReset hint and the other has NotCounterReset. func NewHistogramCounterResetCollisionWarning(pos posrange.PositionRange, operation HistogramOperation) error { - switch operation { - case HistogramAdd, HistogramSub, HistogramAgg: - default: - operation = "unknown operation" + return annoErr{ + PositionRange: pos, + Err: fmt.Errorf("%w %s", HistogramCounterResetCollisionWarning, operation.String()), } +} + +// NewMismatchedCustomBucketsHistogramsInfo is used when the queried series includes +// custom buckets histograms with mismatched custom bounds that cause reconciling. +func NewMismatchedCustomBucketsHistogramsInfo(pos posrange.PositionRange, operation HistogramOperation) error { return annoErr{ PositionRange: pos, - Err: fmt.Errorf("%w %s", HistogramCounterResetCollisionWarning, operation), + Err: fmt.Errorf("%w %s", MismatchedCustomBucketsHistogramsInfo, operation.String()), } } diff --git a/vendor/github.com/prometheus/prometheus/util/features/features.go b/vendor/github.com/prometheus/prometheus/util/features/features.go new file mode 100644 index 00000000000..d52384dbd88 --- /dev/null +++ b/vendor/github.com/prometheus/prometheus/util/features/features.go @@ -0,0 +1,127 @@ +// Copyright The Prometheus Authors +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package features + +import ( + "maps" + "sync" +) + +// Category constants define the standard feature flag categories used in Prometheus. +const ( + API = "api" + OTLPReceiver = "otlp_receiver" + Prometheus = "prometheus" + PromQL = "promql" + PromQLFunctions = "promql_functions" + PromQLOperators = "promql_operators" + Rules = "rules" + Scrape = "scrape" + ServiceDiscoveryProviders = "service_discovery_providers" + TemplatingFunctions = "templating_functions" + TSDB = "tsdb" + UI = "ui" +) + +// Collector defines the interface for collecting and managing feature flags. +// It provides methods to enable, disable, and retrieve feature states. +type Collector interface { + // Enable marks a feature as enabled in the registry. + // The category and name should use snake_case naming convention. + Enable(category, name string) + + // Disable marks a feature as disabled in the registry. + // The category and name should use snake_case naming convention. + Disable(category, name string) + + // Set sets a feature to the specified enabled state. + // The category and name should use snake_case naming convention. + Set(category, name string, enabled bool) + + // Get returns a copy of all registered features organized by category. + // Returns a map where the keys are category names and values are maps + // of feature names to their enabled status. + Get() map[string]map[string]bool +} + +// registry is the private implementation of the Collector interface. +// It stores feature information organized by category. +type registry struct { + mu sync.RWMutex + features map[string]map[string]bool +} + +// DefaultRegistry is the package-level registry used by Prometheus. +var DefaultRegistry = NewRegistry() + +// NewRegistry creates a new feature registry. +func NewRegistry() Collector { + return ®istry{ + features: make(map[string]map[string]bool), + } +} + +// Enable marks a feature as enabled in the registry. +func (r *registry) Enable(category, name string) { + r.Set(category, name, true) +} + +// Disable marks a feature as disabled in the registry. +func (r *registry) Disable(category, name string) { + r.Set(category, name, false) +} + +// Set sets a feature to the specified enabled state. +func (r *registry) Set(category, name string, enabled bool) { + r.mu.Lock() + defer r.mu.Unlock() + + if r.features[category] == nil { + r.features[category] = make(map[string]bool) + } + r.features[category][name] = enabled +} + +// Get returns a copy of all registered features organized by category. +func (r *registry) Get() map[string]map[string]bool { + r.mu.RLock() + defer r.mu.RUnlock() + + result := make(map[string]map[string]bool, len(r.features)) + for category, features := range r.features { + result[category] = make(map[string]bool, len(features)) + maps.Copy(result[category], features) + } + return result +} + +// Enable marks a feature as enabled in the default registry. +func Enable(category, name string) { + DefaultRegistry.Enable(category, name) +} + +// Disable marks a feature as disabled in the default registry. +func Disable(category, name string) { + DefaultRegistry.Disable(category, name) +} + +// Set sets a feature to the specified enabled state in the default registry. +func Set(category, name string, enabled bool) { + DefaultRegistry.Set(category, name, enabled) +} + +// Get returns all features from the default registry. +func Get() map[string]map[string]bool { + return DefaultRegistry.Get() +} diff --git a/vendor/github.com/prometheus/prometheus/util/strutil/quote.go b/vendor/github.com/prometheus/prometheus/util/strutil/quote.go index 66d9c88ffce..0a78421fd43 100644 --- a/vendor/github.com/prometheus/prometheus/util/strutil/quote.go +++ b/vendor/github.com/prometheus/prometheus/util/strutil/quote.go @@ -129,7 +129,7 @@ func unquoteChar(s string, quote byte) (value rune, multibyte bool, tail string, switch c := s[0]; { case c == quote && (quote == '\'' || quote == '"'): err = ErrSyntax - return + return value, multibyte, tail, err case c >= utf8.RuneSelf: r, size := utf8.DecodeRuneInString(s) return r, true, s[size:], nil @@ -140,7 +140,7 @@ func unquoteChar(s string, quote byte) (value rune, multibyte bool, tail string, // Hard case: c is backslash. if len(s) <= 1 { err = ErrSyntax - return + return value, multibyte, tail, err } c := s[1] s = s[2:] @@ -173,13 +173,13 @@ func unquoteChar(s string, quote byte) (value rune, multibyte bool, tail string, var v rune if len(s) < n { err = ErrSyntax - return + return value, multibyte, tail, err } for j := 0; j < n; j++ { x, ok := unhex(s[j]) if !ok { err = ErrSyntax - return + return value, multibyte, tail, err } v = v<<4 | x } @@ -191,7 +191,7 @@ func unquoteChar(s string, quote byte) (value rune, multibyte bool, tail string, } if v > utf8.MaxRune { err = ErrSyntax - return + return value, multibyte, tail, err } value = v multibyte = true @@ -199,20 +199,20 @@ func unquoteChar(s string, quote byte) (value rune, multibyte bool, tail string, v := rune(c) - '0' if len(s) < 2 { err = ErrSyntax - return + return value, multibyte, tail, err } for j := range 2 { // One digit already; two more. x := rune(s[j]) - '0' if x < 0 || x > 7 { err = ErrSyntax - return + return value, multibyte, tail, err } v = (v << 3) | x } s = s[2:] if v > 255 { err = ErrSyntax - return + return value, multibyte, tail, err } value = v case '\\': @@ -220,15 +220,15 @@ func unquoteChar(s string, quote byte) (value rune, multibyte bool, tail string, case '\'', '"': if c != quote { err = ErrSyntax - return + return value, multibyte, tail, err } value = rune(c) default: err = ErrSyntax - return + return value, multibyte, tail, err } tail = s - return + return value, multibyte, tail, err } // contains reports whether the string contains the byte c. @@ -251,5 +251,5 @@ func unhex(b byte) (v rune, ok bool) { case 'A' <= c && c <= 'F': return c - 'A' + 10, true } - return + return v, ok } diff --git a/vendor/github.com/prometheus/sigv4/.golangci.yml b/vendor/github.com/prometheus/sigv4/.golangci.yml index 255980fa81b..070f76e9107 100644 --- a/vendor/github.com/prometheus/sigv4/.golangci.yml +++ b/vendor/github.com/prometheus/sigv4/.golangci.yml @@ -2,41 +2,31 @@ version: "2" linters: enable: - errorlint + - gocritic - misspell - revive - testifylint settings: + gocritic: + enable-all: true + disabled-checks: + - whyNoLint revive: rules: - name: unused-parameter severity: warning disabled: true testifylint: - enable: - - bool-compare - - compares - - empty - - error-is-as - - error-nil - - expected-actual - - len - - require-error - - suite-dont-use-pkg - - suite-extra-assert-call + enable-all: true disable: - float-compare - go-require exclusions: - generated: lax presets: - comments - common-false-positives - legacy - std-error-handling - paths: - - third_party$ - - builtin$ - - examples$ issues: max-issues-per-linter: 0 max-same-issues: 0 @@ -48,9 +38,4 @@ formatters: goimports: local-prefixes: - github.com/prometheus/sigv4 - exclusions: - generated: lax - paths: - - third_party$ - - builtin$ - - examples$ + diff --git a/vendor/github.com/prometheus/sigv4/sigv4.go b/vendor/github.com/prometheus/sigv4/sigv4.go index 8ad1a2cbe37..e225ab5ffbf 100644 --- a/vendor/github.com/prometheus/sigv4/sigv4.go +++ b/vendor/github.com/prometheus/sigv4/sigv4.go @@ -119,7 +119,7 @@ func NewSigV4RoundTripper(cfg *SigV4Config, next http.RoundTripper) (http.RoundT return rt, nil } -func (rt *sigV4RoundTripper) newBuf() interface{} { +func (rt *sigV4RoundTripper) newBuf() any { return bytes.NewBuffer(make([]byte, 0, 1024)) } diff --git a/vendor/github.com/prometheus/sigv4/sigv4_config.go b/vendor/github.com/prometheus/sigv4/sigv4_config.go index d4b88f6d236..f756151d61d 100644 --- a/vendor/github.com/prometheus/sigv4/sigv4_config.go +++ b/vendor/github.com/prometheus/sigv4/sigv4_config.go @@ -39,7 +39,7 @@ func (c *SigV4Config) Validate() error { return nil } -func (c *SigV4Config) UnmarshalYAML(unmarshal func(interface{}) error) error { +func (c *SigV4Config) UnmarshalYAML(unmarshal func(any) error) error { type plain SigV4Config *c = SigV4Config{} if err := unmarshal((*plain)(c)); err != nil { diff --git a/vendor/github.com/thanos-io/thanos/pkg/reloader/reloader.go b/vendor/github.com/thanos-io/thanos/pkg/reloader/reloader.go index 77c6b05d700..ad6a912c8dc 100644 --- a/vendor/github.com/thanos-io/thanos/pkg/reloader/reloader.go +++ b/vendor/github.com/thanos-io/thanos/pkg/reloader/reloader.go @@ -316,11 +316,9 @@ func (r *Reloader) Watch(ctx context.Context) error { // Start watching the file-system. var wg sync.WaitGroup - wg.Add(1) - go func() { + wg.Go(func() { r.watcher.run(ctx) - wg.Done() - }() + }) cfgDirsNames := make([]string, 0, len(r.cfgDirs)) for _, cfgDir := range r.cfgDirs { @@ -818,9 +816,7 @@ func (w *watcher) run(ctx context.Context) { notify = make(chan struct{}) ) - wg.Add(1) - go func() { - defer wg.Done() + wg.Go(func() { var ( delayCtx context.Context @@ -864,7 +860,7 @@ func (w *watcher) run(ctx context.Context) { }(delayCtx) } } - }() + }) for { select { diff --git a/vendor/github.com/thanos-io/thanos/pkg/runutil/runutil.go b/vendor/github.com/thanos-io/thanos/pkg/runutil/runutil.go index a455a504b88..e11069352a6 100644 --- a/vendor/github.com/thanos-io/thanos/pkg/runutil/runutil.go +++ b/vendor/github.com/thanos-io/thanos/pkg/runutil/runutil.go @@ -124,7 +124,7 @@ func RetryWithLog(logger log.Logger, interval time.Duration, stopc <-chan struct } // CloseWithLogOnErr is making sure we log every error, even those from best effort tiny closers. -func CloseWithLogOnErr(logger log.Logger, closer io.Closer, format string, a ...interface{}) { +func CloseWithLogOnErr(logger log.Logger, closer io.Closer, format string, a ...any) { err := closer.Close() if err == nil { return @@ -143,7 +143,7 @@ func CloseWithLogOnErr(logger log.Logger, closer io.Closer, format string, a ... } // ExhaustCloseWithLogOnErr closes the io.ReadCloser with a log message on error but exhausts the reader before. -func ExhaustCloseWithLogOnErr(logger log.Logger, r io.ReadCloser, format string, a ...interface{}) { +func ExhaustCloseWithLogOnErr(logger log.Logger, r io.ReadCloser, format string, a ...any) { _, err := io.Copy(io.Discard, r) if err != nil { level.Warn(logger).Log("msg", "failed to exhaust reader, performance may be impeded", "err", err) @@ -153,7 +153,7 @@ func ExhaustCloseWithLogOnErr(logger log.Logger, r io.ReadCloser, format string, } // CloseWithErrCapture closes closer, wraps any error with message from fmt and args, and stores this in err. -func CloseWithErrCapture(err *error, closer io.Closer, format string, a ...interface{}) { +func CloseWithErrCapture(err *error, closer io.Closer, format string, a ...any) { merr := errutil.MultiError{} merr.Add(*err) @@ -163,7 +163,7 @@ func CloseWithErrCapture(err *error, closer io.Closer, format string, a ...inter } // ExhaustCloseWithErrCapture closes the io.ReadCloser with error capture but exhausts the reader before. -func ExhaustCloseWithErrCapture(err *error, r io.ReadCloser, format string, a ...interface{}) { +func ExhaustCloseWithErrCapture(err *error, r io.ReadCloser, format string, a ...any) { _, copyErr := io.Copy(io.Discard, r) CloseWithErrCapture(err, r, format, a...) diff --git a/vendor/go.opentelemetry.io/otel/.codespellignore b/vendor/go.opentelemetry.io/otel/.codespellignore index 2b53a25e1e1..a6d0cbcc9e8 100644 --- a/vendor/go.opentelemetry.io/otel/.codespellignore +++ b/vendor/go.opentelemetry.io/otel/.codespellignore @@ -8,3 +8,4 @@ nam valu thirdparty addOpt +observ diff --git a/vendor/go.opentelemetry.io/otel/.golangci.yml b/vendor/go.opentelemetry.io/otel/.golangci.yml index b01762ffcc7..1b1b2aff9a4 100644 --- a/vendor/go.opentelemetry.io/otel/.golangci.yml +++ b/vendor/go.opentelemetry.io/otel/.golangci.yml @@ -197,6 +197,9 @@ linters: - float-compare - go-require - require-error + usetesting: + context-background: true + context-todo: true exclusions: generated: lax presets: diff --git a/vendor/go.opentelemetry.io/otel/.lycheeignore b/vendor/go.opentelemetry.io/otel/.lycheeignore index 5328505888d..994b677df7f 100644 --- a/vendor/go.opentelemetry.io/otel/.lycheeignore +++ b/vendor/go.opentelemetry.io/otel/.lycheeignore @@ -1,4 +1,5 @@ http://localhost +https://localhost http://jaeger-collector https://github.com/open-telemetry/opentelemetry-go/milestone/ https://github.com/open-telemetry/opentelemetry-go/projects @@ -6,4 +7,7 @@ https://github.com/open-telemetry/opentelemetry-go/projects https?:\/\/github\.com\/open-telemetry\/semantic-conventions\/archive\/refs\/tags\/[^.]+\.zip\[[^]]+] file:///home/runner/work/opentelemetry-go/opentelemetry-go/libraries file:///home/runner/work/opentelemetry-go/opentelemetry-go/manual -http://4.3.2.1:78/user/123 \ No newline at end of file +http://4.3.2.1:78/user/123 +file:///home/runner/work/opentelemetry-go/opentelemetry-go/exporters/otlp/otlptrace/otlptracegrpc/internal/observ/dns:/:4317 +# URL works, but it has blocked link checkers. +https://dl.acm.org/doi/10.1145/198429.198435 diff --git a/vendor/go.opentelemetry.io/otel/CHANGELOG.md b/vendor/go.opentelemetry.io/otel/CHANGELOG.md index f3abcfdc2e3..ecbe0582c48 100644 --- a/vendor/go.opentelemetry.io/otel/CHANGELOG.md +++ b/vendor/go.opentelemetry.io/otel/CHANGELOG.md @@ -11,6 +11,74 @@ This project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.htm +## [1.39.0/0.61.0/0.15.0/0.0.14] 2025-12-05 + +### Added + +- Greatly reduce the cost of recording metrics in `go.opentelemetry.io/otel/sdk/metric` using hashing for map keys. (#7175) +- Add `WithInstrumentationAttributeSet` option to `go.opentelemetry.io/otel/log`, `go.opentelemetry.io/otel/metric`, and `go.opentelemetry.io/otel/trace` packages. + This provides a concurrent-safe and performant alternative to `WithInstrumentationAttributes` by accepting a pre-constructed `attribute.Set`. (#7287) +- Add experimental observability for the Prometheus exporter in `go.opentelemetry.io/otel/exporters/prometheus`. + Check the `go.opentelemetry.io/otel/exporters/prometheus/internal/x` package documentation for more information. (#7345) +- Add experimental observability metrics in `go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploggrpc`. (#7353) +- Add temporality selector functions `DeltaTemporalitySelector`, `CumulativeTemporalitySelector`, `LowMemoryTemporalitySelector` to `go.opentelemetry.io/otel/sdk/metric`. (#7434) +- Add experimental observability metrics for simple log processor in `go.opentelemetry.io/otel/sdk/log`. (#7548) +- Add experimental observability metrics in `go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc`. (#7459) +- Add experimental observability metrics in `go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp`. (#7486) +- Add experimental observability metrics for simple span processor in `go.opentelemetry.io/otel/sdk/trace`. (#7374) +- Add experimental observability metrics in `go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploghttp`. (#7512) +- Add experimental observability metrics for manual reader in `go.opentelemetry.io/otel/sdk/metric`. (#7524) +- Add experimental observability metrics for periodic reader in `go.opentelemetry.io/otel/sdk/metric`. (#7571) +- Support `OTEL_EXPORTER_OTLP_LOGS_INSECURE` and `OTEL_EXPORTER_OTLP_INSECURE` environmental variables in `go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploghttp`. (#7608) +- Add `Enabled` method to the `Processor` interface in `go.opentelemetry.io/otel/sdk/log`. + All `Processor` implementations now include an `Enabled` method. (#7639) +- The `go.opentelemetry.io/otel/semconv/v1.38.0` package. + The package contains semantic conventions from the `v1.38.0` version of the OpenTelemetry Semantic Conventions. + See the [migration documentation](./semconv/v1.38.0/MIGRATION.md) for information on how to upgrade from `go.opentelemetry.io/otel/semconv/v1.37.0.`(#7648) + +### Changed + +- `Distinct` in `go.opentelemetry.io/otel/attribute` is no longer guaranteed to uniquely identify an attribute set. + Collisions between `Distinct` values for different Sets are possible with extremely high cardinality (billions of series per instrument), but are highly unlikely. (#7175) +- `WithInstrumentationAttributes` in `go.opentelemetry.io/otel/trace` synchronously de-duplicates the passed attributes instead of delegating it to the returned `TracerOption`. (#7266) +- `WithInstrumentationAttributes` in `go.opentelemetry.io/otel/meter` synchronously de-duplicates the passed attributes instead of delegating it to the returned `MeterOption`. (#7266) +- `WithInstrumentationAttributes` in `go.opentelemetry.io/otel/log` synchronously de-duplicates the passed attributes instead of delegating it to the returned `LoggerOption`. (#7266) +- Rename the `OTEL_GO_X_SELF_OBSERVABILITY` environment variable to `OTEL_GO_X_OBSERVABILITY` in `go.opentelemetry.io/otel/sdk/trace`, `go.opentelemetry.io/otel/sdk/log`, and `go.opentelemetry.io/otel/exporters/stdout/stdouttrace`. (#7302) +- Improve performance of histogram `Record` in `go.opentelemetry.io/otel/sdk/metric` when min and max are disabled using `NoMinMax`. (#7306) +- Improve error handling for dropped data during translation by using `prometheus.NewInvalidMetric` in `go.opentelemetry.io/otel/exporters/prometheus`. + ⚠️ **Breaking Change:** Previously, these cases were only logged and scrapes succeeded. + Now, when translation would drop data (e.g., invalid label/value), the exporter emits a `NewInvalidMetric`, and Prometheus scrapes **fail with HTTP 500** by default. + To preserve the prior behavior (scrapes succeed while errors are logged), configure your Prometheus HTTP handler with: `promhttp.HandlerOpts{ ErrorHandling: promhttp.ContinueOnError }`. (#7363) +- Replace fnv hash with xxhash in `go.opentelemetry.io/otel/attribute` for better performance. (#7371) +- The default `TranslationStrategy` in `go.opentelemetry.io/exporters/prometheus` is changed from `otlptranslator.NoUTF8EscapingWithSuffixes` to `otlptranslator.UnderscoreEscapingWithSuffixes`. (#7421) +- Improve performance of concurrent measurements in `go.opentelemetry.io/otel/sdk/metric`. (#7427) +- Include W3C TraceFlags (bits 0–7) in the OTLP `Span.Flags` field in `go.opentelemetry.io/exporters/otlp/otlptrace/otlptracehttp` and `go.opentelemetry.io/exporters/otlp/otlptrace/otlptracegrpc`. (#7438) +- The `ErrorType` function in `go.opentelemetry.io/otel/semconv/v1.37.0` now handles custom error types. + If an error implements an `ErrorType() string` method, the return value of that method will be used as the error type. (#7442) + +### Fixed + +- Fix `WithInstrumentationAttributes` options in `go.opentelemetry.io/otel/trace`, `go.opentelemetry.io/otel/metric`, and `go.opentelemetry.io/otel/log` to properly merge attributes when passed multiple times instead of replacing them. + Attributes with duplicate keys will use the last value passed. (#7300) +- The equality of `attribute.Set` when using the `Equal` method is not affected by the user overriding the empty set pointed to by `attribute.EmptySet` in `go.opentelemetry.io/otel/attribute`. (#7357) +- Return partial OTLP export errors to the caller in `go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploggrpc`. (#7372) +- Return partial OTLP export errors to the caller in `go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploghttp`. (#7372) +- Return partial OTLP export errors to the caller in `go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetricgrpc`. (#7372) +- Return partial OTLP export errors to the caller in `go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetrichttp`. (#7372) +- Return partial OTLP export errors to the caller in `go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc`. (#7372) +- Return partial OTLP export errors to the caller in `go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp`. (#7372) +- Fix `AddAttributes`, `SetAttributes`, `SetBody` on `Record` in `go.opentelemetry.io/otel/sdk/log` to not mutate input. (#7403) +- Do not double record measurements of `RecordSet` methods in `go.opentelemetry.io/otel/semconv/v1.37.0`. (#7655) +- Do not double record measurements of `RecordSet` methods in `go.opentelemetry.io/otel/semconv/v1.36.0`. (#7656) + +### Removed + +- Drop support for [Go 1.23]. (#7274) +- Remove the `FilterProcessor` interface in `go.opentelemetry.io/otel/sdk/log`. + The `Enabled` method has been added to the `Processor` interface instead. + All `Processor` implementations must now implement the `Enabled` method. + Custom processors that do not filter records can implement `Enabled` to return `true`. (#7639) + ## [1.38.0/0.60.0/0.14.0/0.0.13] 2025-08-29 This release is the last to support [Go 1.23]. @@ -3430,8 +3498,10 @@ It contains api and sdk for trace and meter. - CircleCI build CI manifest files. - CODEOWNERS file to track owners of this project. -[Unreleased]: https://github.com/open-telemetry/opentelemetry-go/compare/v1.38.0...HEAD +[Unreleased]: https://github.com/open-telemetry/opentelemetry-go/compare/v1.39.0...HEAD +[1.39.0/0.61.0/0.15.0/0.0.14]: https://github.com/open-telemetry/opentelemetry-go/releases/tag/v1.39.0 [1.38.0/0.60.0/0.14.0/0.0.13]: https://github.com/open-telemetry/opentelemetry-go/releases/tag/v1.38.0 +[0.59.1]: https://github.com/open-telemetry/opentelemetry-go/releases/tag/exporters/prometheus/v0.59.1 [1.37.0/0.59.0/0.13.0]: https://github.com/open-telemetry/opentelemetry-go/releases/tag/v1.37.0 [0.12.2]: https://github.com/open-telemetry/opentelemetry-go/releases/tag/log/v0.12.2 [0.12.1]: https://github.com/open-telemetry/opentelemetry-go/releases/tag/log/v0.12.1 diff --git a/vendor/go.opentelemetry.io/otel/CONTRIBUTING.md b/vendor/go.opentelemetry.io/otel/CONTRIBUTING.md index 0b3ae855c19..ff5e1f76ecd 100644 --- a/vendor/go.opentelemetry.io/otel/CONTRIBUTING.md +++ b/vendor/go.opentelemetry.io/otel/CONTRIBUTING.md @@ -54,8 +54,8 @@ go get -d go.opentelemetry.io/otel (This may print some warning about "build constraints exclude all Go files", just ignore it.) -This will put the project in `${GOPATH}/src/go.opentelemetry.io/otel`. You -can alternatively use `git` directly with: +This will put the project in `${GOPATH}/src/go.opentelemetry.io/otel`. +Alternatively, you can use `git` directly with: ```sh git clone https://github.com/open-telemetry/opentelemetry-go @@ -65,8 +65,7 @@ git clone https://github.com/open-telemetry/opentelemetry-go that name is a kind of a redirector to GitHub that `go get` can understand, but `git` does not.) -This would put the project in the `opentelemetry-go` directory in -current working directory. +This will add the project as `opentelemetry-go` within the current directory. Enter the newly created directory and add your fork as a new remote: @@ -109,7 +108,7 @@ A PR is considered **ready to merge** when: This is not enforced through automation, but needs to be validated by the maintainer merging. - * At least one of the qualified approvals need to be from an + * At least one of the qualified approvals needs to be from an [Approver]/[Maintainer] affiliated with a different company than the author of the PR. * PRs introducing changes that have already been discussed and consensus @@ -166,11 +165,11 @@ guidelines](https://opentelemetry.io/docs/specs/otel/library-guidelines). ### Focus on Capabilities, Not Structure Compliance OpenTelemetry is an evolving specification, one where the desires and -use cases are clear, but the method to satisfy those uses cases are +use cases are clear, but the methods to satisfy those use cases are not. As such, Contributions should provide functionality and behavior that -conforms to the specification, but the interface and structure is +conforms to the specification, but the interface and structure are flexible. It is preferable to have contributions follow the idioms of the @@ -217,7 +216,7 @@ about dependency compatibility. This project does not partition dependencies based on the environment (i.e. `development`, `staging`, `production`). -Only the dependencies explicitly included in the released modules have be +Only the dependencies explicitly included in the released modules have been tested and verified to work with the released code. No other guarantee is made about the compatibility of other dependencies. @@ -635,8 +634,8 @@ is not in their root name. The use of internal packages should be scoped to a single module. A sub-module should never import from a parent internal package. This creates a coupling -between the two modules where a user can upgrade the parent without the child -and if the internal package API has changed it will fail to upgrade[^3]. +between the two modules where a user can upgrade the parent without the child, +and if the internal package API has changed, it will fail to upgrade[^3]. There are two known exceptions to this rule: @@ -657,7 +656,7 @@ this. ### Ignoring context cancellation -OpenTelemetry API implementations need to ignore the cancellation of the context that are +OpenTelemetry API implementations need to ignore the cancellation of the context that is passed when recording a value (e.g. starting a span, recording a measurement, emitting a log). Recording methods should not return an error describing the cancellation state of the context when they complete, nor should they abort any work. @@ -675,6 +674,441 @@ force flushing telemetry, shutting down a signal provider) the context cancellat should be honored. This means all work done on behalf of the user provided context should be canceled. +### Observability + +OpenTelemetry Go SDK components should be instrumented to enable users observability for the health and performance of the telemetry pipeline itself. +This allows operators to understand how well their observability infrastructure is functioning and to identify potential issues before they impact their applications. + +This section outlines the best practices for building instrumentation in OpenTelemetry Go SDK components. + +#### Environment Variable Activation + +Observability features are currently experimental. +They should be disabled by default and activated through the `OTEL_GO_X_OBSERVABILITY` environment variable. +This follows the established experimental feature pattern used throughout the SDK. + +Components should check for this environment variable using a consistent pattern: + +```go +import "go.opentelemetry.io/otel/*/internal/x" + +if x.Observability.Enabled() { + // Initialize observability metrics +} +``` + +**References**: + +- [stdouttrace exporter](./exporters/stdout/stdouttrace/internal/x/x.go) +- [sdk](./sdk/internal/x/x.go) + +#### Encapsulation + +Instrumentation should be encapsulated within a dedicated `struct` (e.g. `instrumentation`). +It should not be mixed into the instrumented component. + +Prefer this: + +```go +type SDKComponent struct { + inst *instrumentation +} + +type instrumentation struct { + inflight otelconv.SDKComponentInflight + exported otelconv.SDKComponentExported +} +``` + +To this: + +```go +// ❌ Avoid this pattern. +type SDKComponent struct { + /* other SDKComponent fields... */ + + inflight otelconv.SDKComponentInflight + exported otelconv.SDKComponentExported +} +``` + +The instrumentation code should not bloat the code being instrumented. +Likely, this means its own file, or its own package if it is complex or reused. + +#### Initialization + +Instrumentation setup should be explicit, side-effect free, and local to the relevant component. +Avoid relying on global or implicit [side effects][side-effect] for initialization. + +Encapsulate setup in constructor functions, ensuring clear ownership and scope: + +```go +import ( + "errors" + + semconv "go.opentelemetry.io/otel/semconv/v1.37.0" + "go.opentelemetry.io/otel/semconv/v1.37.0/otelconv" +) + +type SDKComponent struct { + inst *instrumentation +} + +func NewSDKComponent(config Config) (*SDKComponent, error) { + inst, err := newInstrumentation() + if err != nil { + return nil, err + } + return &SDKComponent{inst: inst}, nil +} + +type instrumentation struct { + inflight otelconv.SDKComponentInflight + exported otelconv.SDKComponentExported +} + +func newInstrumentation() (*instrumentation, error) { + if !x.Observability.Enabled() { + return nil, nil + } + + meter := otel.GetMeterProvider().Meter( + "", + metric.WithInstrumentationVersion(sdk.Version()), + metric.WithSchemaURL(semconv.SchemaURL), + ) + + inst := &instrumentation{} + + var err, e error + inst.inflight, e = otelconv.NewSDKComponentInflight(meter) + err = errors.Join(err, e) + + inst.exported, e = otelconv.NewSDKComponentExported(meter) + err = errors.Join(err, e) + + return inst, err +} +``` + +```go +// ❌ Avoid this pattern. +func (c *Component) initObservability() { + // Initialize observability metrics + if !x.Observability.Enabled() { + return + } + + // Initialize observability metrics + c.inst = &instrumentation{/* ... */} +} +``` + +[side-effect]: https://en.wikipedia.org/wiki/Side_effect_(computer_science) + +#### Performance + +When observability is disabled there should be little to no overhead. + +```go +func (e *Exporter) ExportSpans(ctx context.Context, spans []trace.ReadOnlySpan) error { + if e.inst != nil { + attrs := expensiveOperation() + e.inst.recordSpanInflight(ctx, int64(len(spans)), attrs...) + } + // Export spans... +} +``` + +```go +// ❌ Avoid this pattern. +func (e *Exporter) ExportSpans(ctx context.Context, spans []trace.ReadOnlySpan) error { + attrs := expensiveOperation() + e.inst.recordSpanInflight(ctx, int64(len(spans)), attrs...) + // Export spans... +} + +func (i *instrumentation) recordSpanInflight(ctx context.Context, count int64, attrs ...attribute.KeyValue) { + if i == nil || i.inflight == nil { + return + } + i.inflight.Add(ctx, count, metric.WithAttributes(attrs...)) +} +``` + +When observability is enabled, the instrumentation code paths should be optimized to reduce allocation and computation overhead. + +##### Attribute and Option Allocation Management + +Pool attribute slices and options with [`sync.Pool`] to minimize allocations in measurement calls with dynamic attributes. + +```go +var ( + attrPool = sync.Pool{ + New: func() any { + // Pre-allocate common capacity + knownCap := 8 // Adjust based on expected usage + s := make([]attribute.KeyValue, 0, knownCap) + // Return a pointer to avoid extra allocation on Put(). + return &s + }, + } + + addOptPool = &sync.Pool{ + New: func() any { + const n = 1 // WithAttributeSet + o := make([]metric.AddOption, 0, n) + // Return a pointer to avoid extra allocation on Put(). + return &o + }, + } +) + +func (i *instrumentation) record(ctx context.Context, value int64, baseAttrs ...attribute.KeyValue) { + attrs := attrPool.Get().(*[]attribute.KeyValue) + defer func() { + *attrs = (*attrs)[:0] // Reset. + attrPool.Put(attrs) + }() + + *attrs = append(*attrs, baseAttrs...) + // Add any dynamic attributes. + *attrs = append(*attrs, semconv.OTelComponentName("exporter-1")) + + addOpt := addOptPool.Get().(*[]metric.AddOption) + defer func() { + *addOpt = (*addOpt)[:0] + addOptPool.Put(addOpt) + }() + + set := attribute.NewSet(*attrs...) + *addOpt = append(*addOpt, metric.WithAttributeSet(set)) + + i.counter.Add(ctx, value, *addOpt...) +} +``` + +Pools are most effective when there are many pooled objects of the same sufficiently large size, and the objects are repeatedly used. +This amortizes the cost of allocation and synchronization. +Ideally, the pools should be scoped to be used as widely as possible within the component to maximize this efficiency while still ensuring correctness. + +[`sync.Pool`]: https://pkg.go.dev/sync#Pool + +##### Cache common attribute sets for repeated measurements + +If a static set of attributes are used for measurements and they are known at compile time, pre-compute and cache these attributes. + +```go +type spanLiveSetKey struct { + sampled bool +} + +var spanLiveSetCache = map[spanLiveSetKey]attribute.Set{ + {true}: attribute.NewSet( + otelconv.SDKSpanLive{}.AttrSpanSamplingResult( + otelconv.SpanSamplingResultRecordAndSample, + ), + ), + {false}: attribute.NewSet( + otelconv.SDKSpanLive{}.AttrSpanSamplingResult( + otelconv.SpanSamplingResultRecordOnly, + ), + ), +} + +func spanLiveSet(sampled bool) attribute.Set { + key := spanLiveSetKey{sampled: sampled} + return spanLiveSetCache[key] +} +``` + +##### Benchmarking + +Always provide benchmarks when introducing or refactoring instrumentation. +Demonstrate the impact (allocs/op, B/op, ns/op) in enabled/disabled scenarios: + +```go +func BenchmarkExportSpans(b *testing.B) { + scenarios := []struct { + name string + obsEnabled bool + }{ + {"ObsDisabled", false}, + {"ObsEnabled", true}, + } + + for _, scenario := range scenarios { + b.Run(scenario.name, func(b *testing.B) { + b.Setenv( + "OTEL_GO_X_OBSERVABILITY", + strconv.FormatBool(scenario.obsEnabled), + ) + + exporter := NewExporter() + spans := generateTestSpans(100) + + b.ResetTimer() + b.ReportAllocs() + + for i := 0; i < b.N; i++ { + _ = exporter.ExportSpans(context.Background(), spans) + } + }) + } +} +``` + +#### Error Handling and Robustness + +Errors should be reported back to the caller if possible, and partial failures should be handled as gracefully as possible. + +```go +func newInstrumentation() (*instrumentation, error) { + if !x.Observability.Enabled() { + return nil, nil + } + + m := otel.GetMeterProvider().Meter(/* initialize meter */) + counter, err := otelconv.NewSDKComponentCounter(m) + // Use the partially initialized counter if available. + i := &instrumentation{counter: counter} + // Return any error to the caller. + return i, err +} +``` + +```go +// ❌ Avoid this pattern. +func newInstrumentation() *instrumentation { + if !x.Observability.Enabled() { + return nil, nil + } + + m := otel.GetMeterProvider().Meter(/* initialize meter */) + counter, err := otelconv.NewSDKComponentCounter(m) + if err != nil { + // ❌ Do not dump the error to the OTel Handler. Return it to the + // caller. + otel.Handle(err) + // ❌ Do not return nil if we can still use the partially initialized + // counter. + return nil + } + return &instrumentation{counter: counter} +} +``` + +If the instrumented component cannot report the error to the user, let it report the error to `otel.Handle`. + +#### Context Propagation + +Ensure observability measurements receive the correct context, especially for trace exemplars and distributed context: + +```go +func (e *Exporter) ExportSpans(ctx context.Context, spans []trace.ReadOnlySpan) error { + // Use the provided context for observability measurements + e.inst.recordSpanExportStarted(ctx, len(spans)) + + err := e.doExport(ctx, spans) + + if err != nil { + e.inst.recordSpanExportFailed(ctx, len(spans), err) + } else { + e.inst.recordSpanExportSucceeded(ctx, len(spans)) + } + + return err +} +``` + +```go +// ❌ Avoid this pattern. +func (e *Exporter) ExportSpans(ctx context.Context, spans []trace.ReadOnlySpan) error { + // ❌ Do not break the context propagation. + e.inst.recordSpanExportStarted(context.Background(), len(spans)) + + err := e.doExport(ctx, spans) + + /* ... */ + + return err +} +``` + +#### Semantic Conventions Compliance + +All observability metrics should follow the [OpenTelemetry Semantic Conventions for SDK metrics](https://github.com/open-telemetry/semantic-conventions/blob/1cf2476ae5e518225a766990a28a6d5602bd5a30/docs/otel/sdk-metrics.md). + +Use the metric semantic conventions convenience package [otelconv](./semconv/v1.37.0/otelconv/metric.go). + +##### Component Identification + +Component names and types should follow [semantic convention](https://github.com/open-telemetry/semantic-conventions/blob/1cf2476ae5e518225a766990a28a6d5602bd5a30/docs/registry/attributes/otel.md#otel-component-attributes). + +If a component is not a well-known type specified in the semantic conventions, use the package path scope type as a stable identifier. + +```go +componentType := "go.opentelemetry.io/otel/sdk/trace.Span" +``` + +```go +// ❌ Do not do this. +componentType := "trace-span" +``` + +The component name should be a stable unique identifier for the specific instance of the component. + +Use a global counter to ensure uniqueness if necessary. + +```go +// Unique 0-based ID counter for component instances. +var componentIDCounter atomic.Int64 + +// nextID returns the next unique ID for a component. +func nextID() int64 { + return componentIDCounter.Add(1) - 1 +} + +// componentName returns a unique name for the component instance. +func componentName() attribute.KeyValue { + id := nextID() + name := fmt.Sprintf("%s/%d", componentType, id) + return semconv.OTelComponentName(name) +} +``` + +The component ID will need to be resettable for deterministic testing. +If tests are in a different package than the component being tested (i.e. a `_test` package name), use a generated `counter` internal package to manage the counter. +See [stdouttrace exporter example](./exporters/stdout/stdouttrace/internal/gen.go) for reference. + +#### Testing + +Use deterministic testing with isolated state: + +```go +func TestObservability(t *testing.T) { + // Restore state after test to ensure this does not affect other tests. + prev := otel.GetMeterProvider() + t.Cleanup(func() { otel.SetMeterProvider(prev) }) + + // Isolate the meter provider for deterministic testing + reader := metric.NewManualReader() + meterProvider := metric.NewMeterProvider(metric.WithReader(reader)) + otel.SetMeterProvider(meterProvider) + + // Use t.Setenv to ensure environment variable is restored after test. + t.Setenv("OTEL_GO_X_OBSERVABILITY", "true") + + // Reset component ID counter to ensure deterministic component names. + componentIDCounter.Store(0) + + /* ... test code ... */ +} +``` + +Test order should not affect results. +Ensure that any global state (e.g. component ID counters) is reset between tests. + ## Approvers and Maintainers ### Maintainers @@ -696,7 +1130,6 @@ For more information about the approver role, see the [community repository](htt ### Triagers - [Alex Kats](https://github.com/akats7), Capital One -- [Cheng-Zhen Yang](https://github.com/scorpionknifes), Independent For more information about the triager role, see the [community repository](https://github.com/open-telemetry/community/blob/main/guides/contributor/membership.md#triager). @@ -704,6 +1137,7 @@ For more information about the triager role, see the [community repository](http - [Aaron Clawson](https://github.com/MadVikingGod) - [Anthony Mirabella](https://github.com/Aneurysm9) +- [Cheng-Zhen Yang](https://github.com/scorpionknifes) - [Chester Cheung](https://github.com/hanyuancheung) - [Evan Torrie](https://github.com/evantorrie) - [Gustavo Silva Paiva](https://github.com/paivagustavo) diff --git a/vendor/go.opentelemetry.io/otel/Makefile b/vendor/go.opentelemetry.io/otel/Makefile index bc0f1f92d1f..44870248c32 100644 --- a/vendor/go.opentelemetry.io/otel/Makefile +++ b/vendor/go.opentelemetry.io/otel/Makefile @@ -146,11 +146,12 @@ build-tests/%: # Tests -TEST_TARGETS := test-default test-bench test-short test-verbose test-race test-concurrent-safe +TEST_TARGETS := test-default test-bench test-short test-verbose test-race test-concurrent-safe test-fuzz .PHONY: $(TEST_TARGETS) test test-default test-race: ARGS=-race test-bench: ARGS=-run=xxxxxMatchNothingxxxxx -test.benchtime=1ms -bench=. test-short: ARGS=-short +test-fuzz: ARGS=-fuzztime=10s -fuzz test-verbose: ARGS=-v -race test-concurrent-safe: ARGS=-run=ConcurrentSafe -count=100 -race test-concurrent-safe: TIMEOUT=120 diff --git a/vendor/go.opentelemetry.io/otel/README.md b/vendor/go.opentelemetry.io/otel/README.md index 6b7ab5f2193..c6335954311 100644 --- a/vendor/go.opentelemetry.io/otel/README.md +++ b/vendor/go.opentelemetry.io/otel/README.md @@ -55,25 +55,18 @@ Currently, this project supports the following environments. |----------|------------|--------------| | Ubuntu | 1.25 | amd64 | | Ubuntu | 1.24 | amd64 | -| Ubuntu | 1.23 | amd64 | | Ubuntu | 1.25 | 386 | | Ubuntu | 1.24 | 386 | -| Ubuntu | 1.23 | 386 | | Ubuntu | 1.25 | arm64 | | Ubuntu | 1.24 | arm64 | -| Ubuntu | 1.23 | arm64 | -| macOS 13 | 1.25 | amd64 | -| macOS 13 | 1.24 | amd64 | -| macOS 13 | 1.23 | amd64 | +| macOS | 1.25 | amd64 | +| macOS | 1.24 | amd64 | | macOS | 1.25 | arm64 | | macOS | 1.24 | arm64 | -| macOS | 1.23 | arm64 | | Windows | 1.25 | amd64 | | Windows | 1.24 | amd64 | -| Windows | 1.23 | amd64 | | Windows | 1.25 | 386 | | Windows | 1.24 | 386 | -| Windows | 1.23 | 386 | While this project should work for other systems, no compatibility guarantees are made for those systems currently. diff --git a/vendor/go.opentelemetry.io/otel/RELEASING.md b/vendor/go.opentelemetry.io/otel/RELEASING.md index 1ddcdef0396..861756fd745 100644 --- a/vendor/go.opentelemetry.io/otel/RELEASING.md +++ b/vendor/go.opentelemetry.io/otel/RELEASING.md @@ -24,7 +24,7 @@ Ensure things look correct before submitting a pull request to include the addit ## Breaking changes validation -You can run `make gorelease` that runs [gorelease](https://pkg.go.dev/golang.org/x/exp/cmd/gorelease) to ensure that there are no unwanted changes done in the public API. +You can run `make gorelease` which runs [gorelease](https://pkg.go.dev/golang.org/x/exp/cmd/gorelease) to ensure that there are no unwanted changes made in the public API. You can check/report problems with `gorelease` [here](https://golang.org/issues/26420). @@ -62,7 +62,7 @@ Update go.mod for submodules to depend on the new release which will happen in t ``` 3. Update the [Changelog](./CHANGELOG.md). - - Make sure all relevant changes for this release are included and are in language that non-contributors to the project can understand. + - Make sure all relevant changes for this release are included and are written in language that non-contributors to the project can understand. To verify this, you can look directly at the commits since the ``. ``` @@ -107,34 +107,50 @@ It is critical you make sure the version you push upstream is correct. ... ``` -## Release +## Sign artifacts -Finally create a Release for the new `` on GitHub. -The release body should include all the release notes from the Changelog for this release. +To ensure we comply with CNCF best practices, we need to sign the release artifacts. -### Sign the Release Artifact +Download the `.tar.gz` and `.zip` archives from the [tags page](https://github.com/open-telemetry/opentelemetry-go/tags) for the new release tag. +Both archives need to be signed with your GPG key. -To ensure we comply with CNCF best practices, we need to sign the release artifact. -The tarball attached to the GitHub release needs to be signed with your GPG key. +You can use [this script] to verify the contents of the archives before signing them. -Follow [these steps] to sign the release artifact and upload it to GitHub. -You can use [this script] to verify the contents of the tarball before signing it. +To find your GPG key ID, run: -Be sure to use the correct GPG key when signing the release artifact. +```terminal +gpg --list-secret-keys --keyid-format=long +``` + +The key ID is the 16-character string after `sec rsa4096/` (or similar). + +Set environment variables and sign both artifacts: ```terminal -gpg --local-user --armor --detach-sign opentelemetry-go-.tar.gz +export VERSION="" # e.g., v1.32.0 +export KEY_ID="" + +gpg --local-user $KEY_ID --armor --detach-sign opentelemetry-go-$VERSION.tar.gz +gpg --local-user $KEY_ID --armor --detach-sign opentelemetry-go-$VERSION.zip ``` -You can verify the signature with: +You can verify the signatures with: ```terminal -gpg --verify opentelemetry-go-.tar.gz.asc opentelemetry-go-.tar.gz +gpg --verify opentelemetry-go-$VERSION.tar.gz.asc opentelemetry-go-$VERSION.tar.gz +gpg --verify opentelemetry-go-$VERSION.zip.asc opentelemetry-go-$VERSION.zip ``` -[these steps]: https://wiki.debian.org/Creating%20signed%20GitHub%20releases [this script]: https://github.com/MrAlias/attest-sh +## Release + +Finally create a Release for the new `` on GitHub. +The release body should include all the release notes from the Changelog for this release. + +***IMPORTANT***: GitHub Releases are immutable once created. +You must upload the signed artifacts (`.tar.gz`, `.tar.gz.asc`, `.zip`, and `.zip.asc`) when creating the release, as they cannot be added or modified later. + ## Post-Release ### Contrib Repository @@ -160,14 +176,6 @@ This helps track what changes were included in each release. Once all related issues and PRs have been added to the milestone, close the milestone. -### Demo Repository - -Bump the dependencies in the following Go services: - -- [`accounting`](https://github.com/open-telemetry/opentelemetry-demo/tree/main/src/accounting) -- [`checkoutservice`](https://github.com/open-telemetry/opentelemetry-demo/tree/main/src/checkout) -- [`productcatalogservice`](https://github.com/open-telemetry/opentelemetry-demo/tree/main/src/product-catalog) - ### Close the `Version Release` issue Once the todo list in the `Version Release` issue is complete, close the issue. diff --git a/vendor/go.opentelemetry.io/otel/VERSIONING.md b/vendor/go.opentelemetry.io/otel/VERSIONING.md index b8cb605c166..b27c9e84f51 100644 --- a/vendor/go.opentelemetry.io/otel/VERSIONING.md +++ b/vendor/go.opentelemetry.io/otel/VERSIONING.md @@ -83,7 +83,7 @@ is designed so the following goals can be achieved. in either the module path or the import path. * In addition to public APIs, telemetry produced by stable instrumentation will remain stable and backwards compatible. This is to avoid breaking - alerts and dashboard. + alerts and dashboards. * Modules will be used to encapsulate instrumentation, detectors, exporters, propagators, and any other independent sets of related components. * Experimental modules still under active development will be versioned at diff --git a/vendor/go.opentelemetry.io/otel/attribute/encoder.go b/vendor/go.opentelemetry.io/otel/attribute/encoder.go index 6333d34b310..6cc1a1655cf 100644 --- a/vendor/go.opentelemetry.io/otel/attribute/encoder.go +++ b/vendor/go.opentelemetry.io/otel/attribute/encoder.go @@ -16,7 +16,7 @@ type ( // set into a wire representation. Encoder interface { // Encode returns the serialized encoding of the attribute set using - // its Iterator. This result may be cached by a attribute.Set. + // its Iterator. This result may be cached by an attribute.Set. Encode(iterator Iterator) string // ID returns a value that is unique for each class of attribute diff --git a/vendor/go.opentelemetry.io/otel/attribute/hash.go b/vendor/go.opentelemetry.io/otel/attribute/hash.go new file mode 100644 index 00000000000..6aa69aeaecf --- /dev/null +++ b/vendor/go.opentelemetry.io/otel/attribute/hash.go @@ -0,0 +1,92 @@ +// Copyright The OpenTelemetry Authors +// SPDX-License-Identifier: Apache-2.0 + +package attribute // import "go.opentelemetry.io/otel/attribute" + +import ( + "fmt" + "reflect" + + "go.opentelemetry.io/otel/attribute/internal/xxhash" +) + +// Type identifiers. These identifiers are hashed before the value of the +// corresponding type. This is done to distinguish values that are hashed with +// the same value representation (e.g. `int64(1)` and `true`, []int64{0} and +// int64(0)). +// +// These are all 8 byte length strings converted to a uint64 representation. A +// uint64 is used instead of the string directly as an optimization, it avoids +// the for loop in [xxhash] which adds minor overhead. +const ( + boolID uint64 = 7953749933313450591 // "_boolean" (little endian) + int64ID uint64 = 7592915492740740150 // "64_bit_i" (little endian) + float64ID uint64 = 7376742710626956342 // "64_bit_f" (little endian) + stringID uint64 = 6874584755375207263 // "_string_" (little endian) + boolSliceID uint64 = 6875993255270243167 // "_[]bool_" (little endian) + int64SliceID uint64 = 3762322556277578591 // "_[]int64" (little endian) + float64SliceID uint64 = 7308324551835016539 // "[]double" (little endian) + stringSliceID uint64 = 7453010373645655387 // "[]string" (little endian) +) + +// hashKVs returns a new xxHash64 hash of kvs. +func hashKVs(kvs []KeyValue) uint64 { + h := xxhash.New() + for _, kv := range kvs { + h = hashKV(h, kv) + } + return h.Sum64() +} + +// hashKV returns the xxHash64 hash of kv with h as the base. +func hashKV(h xxhash.Hash, kv KeyValue) xxhash.Hash { + h = h.String(string(kv.Key)) + + switch kv.Value.Type() { + case BOOL: + h = h.Uint64(boolID) + h = h.Uint64(kv.Value.numeric) + case INT64: + h = h.Uint64(int64ID) + h = h.Uint64(kv.Value.numeric) + case FLOAT64: + h = h.Uint64(float64ID) + // Assumes numeric stored with math.Float64bits. + h = h.Uint64(kv.Value.numeric) + case STRING: + h = h.Uint64(stringID) + h = h.String(kv.Value.stringly) + case BOOLSLICE: + h = h.Uint64(boolSliceID) + rv := reflect.ValueOf(kv.Value.slice) + for i := 0; i < rv.Len(); i++ { + h = h.Bool(rv.Index(i).Bool()) + } + case INT64SLICE: + h = h.Uint64(int64SliceID) + rv := reflect.ValueOf(kv.Value.slice) + for i := 0; i < rv.Len(); i++ { + h = h.Int64(rv.Index(i).Int()) + } + case FLOAT64SLICE: + h = h.Uint64(float64SliceID) + rv := reflect.ValueOf(kv.Value.slice) + for i := 0; i < rv.Len(); i++ { + h = h.Float64(rv.Index(i).Float()) + } + case STRINGSLICE: + h = h.Uint64(stringSliceID) + rv := reflect.ValueOf(kv.Value.slice) + for i := 0; i < rv.Len(); i++ { + h = h.String(rv.Index(i).String()) + } + case INVALID: + default: + // Logging is an alternative, but using the internal logger here + // causes an import cycle so it is not done. + v := kv.Value.AsInterface() + msg := fmt.Sprintf("unknown value type: %[1]v (%[1]T)", v) + panic(msg) + } + return h +} diff --git a/vendor/go.opentelemetry.io/otel/attribute/internal/xxhash/xxhash.go b/vendor/go.opentelemetry.io/otel/attribute/internal/xxhash/xxhash.go new file mode 100644 index 00000000000..113a978383b --- /dev/null +++ b/vendor/go.opentelemetry.io/otel/attribute/internal/xxhash/xxhash.go @@ -0,0 +1,64 @@ +// Copyright The OpenTelemetry Authors +// SPDX-License-Identifier: Apache-2.0 + +// Package xxhash provides a wrapper around the xxhash library for attribute hashing. +package xxhash // import "go.opentelemetry.io/otel/attribute/internal/xxhash" + +import ( + "encoding/binary" + "math" + + "github.com/cespare/xxhash/v2" +) + +// Hash wraps xxhash.Digest to provide an API friendly for hashing attribute values. +type Hash struct { + d *xxhash.Digest +} + +// New returns a new initialized xxHash64 hasher. +func New() Hash { + return Hash{d: xxhash.New()} +} + +func (h Hash) Uint64(val uint64) Hash { + var buf [8]byte + binary.LittleEndian.PutUint64(buf[:], val) + // errors from Write are always nil for xxhash + // if it returns an err then panic + _, err := h.d.Write(buf[:]) + if err != nil { + panic("xxhash write of uint64 failed: " + err.Error()) + } + return h +} + +func (h Hash) Bool(val bool) Hash { // nolint:revive // This is a hashing function. + if val { + return h.Uint64(1) + } + return h.Uint64(0) +} + +func (h Hash) Float64(val float64) Hash { + return h.Uint64(math.Float64bits(val)) +} + +func (h Hash) Int64(val int64) Hash { + return h.Uint64(uint64(val)) // nolint:gosec // Overflow doesn't matter since we are hashing. +} + +func (h Hash) String(val string) Hash { + // errors from WriteString are always nil for xxhash + // if it returns an err then panic + _, err := h.d.WriteString(val) + if err != nil { + panic("xxhash write of string failed: " + err.Error()) + } + return h +} + +// Sum64 returns the current hash value. +func (h Hash) Sum64() uint64 { + return h.d.Sum64() +} diff --git a/vendor/go.opentelemetry.io/otel/attribute/set.go b/vendor/go.opentelemetry.io/otel/attribute/set.go index 64735d382ea..911d557ee54 100644 --- a/vendor/go.opentelemetry.io/otel/attribute/set.go +++ b/vendor/go.opentelemetry.io/otel/attribute/set.go @@ -9,6 +9,8 @@ import ( "reflect" "slices" "sort" + + "go.opentelemetry.io/otel/attribute/internal/xxhash" ) type ( @@ -23,19 +25,19 @@ type ( // the Equals method to ensure stable equivalence checking. // // Users should also use the Distinct returned from Equivalent as a map key - // instead of a Set directly. In addition to that type providing guarantees - // on stable equivalence, it may also provide performance improvements. + // instead of a Set directly. Set has relatively poor performance when used + // as a map key compared to Distinct. Set struct { - equivalent Distinct + hash uint64 + data any } - // Distinct is a unique identifier of a Set. + // Distinct is an identifier of a Set which is very likely to be unique. // - // Distinct is designed to ensure equivalence stability: comparisons will - // return the same value across versions. For this reason, Distinct should - // always be used as a map key instead of a Set. + // Distinct should be used as a map key instead of a Set for to provide better + // performance for map operations. Distinct struct { - iface any + hash uint64 } // Sortable implements sort.Interface, used for sorting KeyValue. @@ -46,15 +48,34 @@ type ( Sortable []KeyValue ) +// Compile time check these types remain comparable. +var ( + _ = isComparable(Set{}) + _ = isComparable(Distinct{}) +) + +func isComparable[T comparable](t T) T { return t } + var ( // keyValueType is used in computeDistinctReflect. keyValueType = reflect.TypeOf(KeyValue{}) - // emptySet is returned for empty attribute sets. - emptySet = &Set{ - equivalent: Distinct{ - iface: [0]KeyValue{}, - }, + // emptyHash is the hash of an empty set. + emptyHash = xxhash.New().Sum64() + + // userDefinedEmptySet is an empty set. It was mistakenly exposed to users + // as something they can assign to, so it must remain addressable and + // mutable. + // + // This is kept for backwards compatibility, but should not be used in new code. + userDefinedEmptySet = &Set{ + hash: emptyHash, + data: [0]KeyValue{}, + } + + emptySet = Set{ + hash: emptyHash, + data: [0]KeyValue{}, } ) @@ -62,33 +83,35 @@ var ( // // This is a convenience provided for optimized calling utility. func EmptySet() *Set { - return emptySet -} - -// reflectValue abbreviates reflect.ValueOf(d). -func (d Distinct) reflectValue() reflect.Value { - return reflect.ValueOf(d.iface) + // Continue to return the pointer to the user-defined empty set for + // backwards-compatibility. + // + // New code should not use this, instead use emptySet. + return userDefinedEmptySet } // Valid reports whether this value refers to a valid Set. -func (d Distinct) Valid() bool { - return d.iface != nil +func (d Distinct) Valid() bool { return d.hash != 0 } + +// reflectValue abbreviates reflect.ValueOf(d). +func (l Set) reflectValue() reflect.Value { + return reflect.ValueOf(l.data) } // Len returns the number of attributes in this set. func (l *Set) Len() int { - if l == nil || !l.equivalent.Valid() { + if l == nil || l.hash == 0 { return 0 } - return l.equivalent.reflectValue().Len() + return l.reflectValue().Len() } // Get returns the KeyValue at ordered position idx in this set. func (l *Set) Get(idx int) (KeyValue, bool) { - if l == nil || !l.equivalent.Valid() { + if l == nil || l.hash == 0 { return KeyValue{}, false } - value := l.equivalent.reflectValue() + value := l.reflectValue() if idx >= 0 && idx < value.Len() { // Note: The Go compiler successfully avoids an allocation for @@ -101,10 +124,10 @@ func (l *Set) Get(idx int) (KeyValue, bool) { // Value returns the value of a specified key in this set. func (l *Set) Value(k Key) (Value, bool) { - if l == nil || !l.equivalent.Valid() { + if l == nil || l.hash == 0 { return Value{}, false } - rValue := l.equivalent.reflectValue() + rValue := l.reflectValue() vlen := rValue.Len() idx := sort.Search(vlen, func(idx int) bool { @@ -144,20 +167,29 @@ func (l *Set) ToSlice() []KeyValue { return iter.ToSlice() } -// Equivalent returns a value that may be used as a map key. The Distinct type -// guarantees that the result will equal the equivalent. Distinct value of any +// Equivalent returns a value that may be used as a map key. Equal Distinct +// values are very likely to be equivalent attribute Sets. Distinct value of any // attribute set with the same elements as this, where sets are made unique by // choosing the last value in the input for any given key. func (l *Set) Equivalent() Distinct { - if l == nil || !l.equivalent.Valid() { - return emptySet.equivalent + if l == nil || l.hash == 0 { + return Distinct{hash: emptySet.hash} } - return l.equivalent + return Distinct{hash: l.hash} } // Equals reports whether the argument set is equivalent to this set. func (l *Set) Equals(o *Set) bool { - return l.Equivalent() == o.Equivalent() + if l.Equivalent() != o.Equivalent() { + return false + } + if l == nil || l.hash == 0 { + l = &emptySet + } + if o == nil || o.hash == 0 { + o = &emptySet + } + return l.data == o.data } // Encoded returns the encoded form of this set, according to encoder. @@ -169,12 +201,6 @@ func (l *Set) Encoded(encoder Encoder) string { return encoder.Encode(l.Iter()) } -func empty() Set { - return Set{ - equivalent: emptySet.equivalent, - } -} - // NewSet returns a new Set. See the documentation for // NewSetWithSortableFiltered for more details. // @@ -204,7 +230,7 @@ func NewSetWithSortable(kvs []KeyValue, _ *Sortable) Set { func NewSetWithFiltered(kvs []KeyValue, filter Filter) (Set, []KeyValue) { // Check for empty set. if len(kvs) == 0 { - return empty(), nil + return emptySet, nil } // Stable sort so the following de-duplication can implement @@ -233,10 +259,10 @@ func NewSetWithFiltered(kvs []KeyValue, filter Filter) (Set, []KeyValue) { if filter != nil { if div := filteredToFront(kvs, filter); div != 0 { - return Set{equivalent: computeDistinct(kvs[div:])}, kvs[:div] + return newSet(kvs[div:]), kvs[:div] } } - return Set{equivalent: computeDistinct(kvs)}, nil + return newSet(kvs), nil } // NewSetWithSortableFiltered returns a new Set. @@ -316,7 +342,7 @@ func (l *Set) Filter(re Filter) (Set, []KeyValue) { if first == 0 { // It is safe to assume len(slice) >= 1 given we found at least one // attribute above that needs to be filtered out. - return Set{equivalent: computeDistinct(slice[1:])}, slice[:1] + return newSet(slice[1:]), slice[:1] } // Move the filtered slice[first] to the front (preserving order). @@ -326,25 +352,24 @@ func (l *Set) Filter(re Filter) (Set, []KeyValue) { // Do not re-evaluate re(slice[first+1:]). div := filteredToFront(slice[1:first+1], re) + 1 - return Set{equivalent: computeDistinct(slice[div:])}, slice[:div] + return newSet(slice[div:]), slice[:div] } -// computeDistinct returns a Distinct using either the fixed- or -// reflect-oriented code path, depending on the size of the input. The input -// slice is assumed to already be sorted and de-duplicated. -func computeDistinct(kvs []KeyValue) Distinct { - iface := computeDistinctFixed(kvs) - if iface == nil { - iface = computeDistinctReflect(kvs) +// newSet returns a new set based on the sorted and uniqued kvs. +func newSet(kvs []KeyValue) Set { + s := Set{ + hash: hashKVs(kvs), + data: computeDataFixed(kvs), } - return Distinct{ - iface: iface, + if s.data == nil { + s.data = computeDataReflect(kvs) } + return s } -// computeDistinctFixed computes a Distinct for small slices. It returns nil -// if the input is too large for this code path. -func computeDistinctFixed(kvs []KeyValue) any { +// computeDataFixed computes a Set data for small slices. It returns nil if the +// input is too large for this code path. +func computeDataFixed(kvs []KeyValue) any { switch len(kvs) { case 1: return [1]KeyValue(kvs) @@ -371,9 +396,9 @@ func computeDistinctFixed(kvs []KeyValue) any { } } -// computeDistinctReflect computes a Distinct using reflection, works for any -// size input. -func computeDistinctReflect(kvs []KeyValue) any { +// computeDataReflect computes a Set data using reflection, works for any size +// input. +func computeDataReflect(kvs []KeyValue) any { at := reflect.New(reflect.ArrayOf(len(kvs), keyValueType)).Elem() for i, keyValue := range kvs { *(at.Index(i).Addr().Interface().(*KeyValue)) = keyValue @@ -383,7 +408,7 @@ func computeDistinctReflect(kvs []KeyValue) any { // MarshalJSON returns the JSON encoding of the Set. func (l *Set) MarshalJSON() ([]byte, error) { - return json.Marshal(l.equivalent.iface) + return json.Marshal(l.data) } // MarshalLog is the marshaling function used by the logging system to represent this Set. diff --git a/vendor/go.opentelemetry.io/otel/attribute/type_string.go b/vendor/go.opentelemetry.io/otel/attribute/type_string.go index e584b24776b..24f1fa37dbe 100644 --- a/vendor/go.opentelemetry.io/otel/attribute/type_string.go +++ b/vendor/go.opentelemetry.io/otel/attribute/type_string.go @@ -24,8 +24,9 @@ const _Type_name = "INVALIDBOOLINT64FLOAT64STRINGBOOLSLICEINT64SLICEFLOAT64SLICE var _Type_index = [...]uint8{0, 7, 11, 16, 23, 29, 38, 48, 60, 71} func (i Type) String() string { - if i < 0 || i >= Type(len(_Type_index)-1) { + idx := int(i) - 0 + if i < 0 || idx >= len(_Type_index)-1 { return "Type(" + strconv.FormatInt(int64(i), 10) + ")" } - return _Type_name[_Type_index[i]:_Type_index[i+1]] + return _Type_name[_Type_index[idx]:_Type_index[idx+1]] } diff --git a/vendor/go.opentelemetry.io/otel/baggage/baggage.go b/vendor/go.opentelemetry.io/otel/baggage/baggage.go index f83a448ec61..78e98c4c0f3 100644 --- a/vendor/go.opentelemetry.io/otel/baggage/baggage.go +++ b/vendor/go.opentelemetry.io/otel/baggage/baggage.go @@ -648,7 +648,7 @@ func parsePropertyInternal(s string) (p Property, ok bool) { // If we couldn't find any valid key character, // it means the key is either empty or invalid. if keyStart == keyEnd { - return + return p, ok } // Skip spaces after the key: " key< >= value ". @@ -658,13 +658,13 @@ func parsePropertyInternal(s string) (p Property, ok bool) { // A key can have no value, like: " key ". ok = true p.key = s[keyStart:keyEnd] - return + return p, ok } // If we have not reached the end and we can't find the '=' delimiter, // it means the property is invalid. if s[index] != keyValueDelimiter[0] { - return + return p, ok } // Attempting to parse the value. @@ -690,14 +690,14 @@ func parsePropertyInternal(s string) (p Property, ok bool) { // we have not reached the end, it means the property is // invalid, something like: " key = value value1". if index != len(s) { - return + return p, ok } // Decode a percent-encoded value. rawVal := s[valueStart:valueEnd] unescapeVal, err := url.PathUnescape(rawVal) if err != nil { - return + return p, ok } value := replaceInvalidUTF8Sequences(len(rawVal), unescapeVal) @@ -706,7 +706,7 @@ func parsePropertyInternal(s string) (p Property, ok bool) { p.hasValue = true p.value = value - return + return p, ok } func skipSpace(s string, offset int) int { diff --git a/vendor/go.opentelemetry.io/otel/dependencies.Dockerfile b/vendor/go.opentelemetry.io/otel/dependencies.Dockerfile index a311fbb4835..cadb87cc0ee 100644 --- a/vendor/go.opentelemetry.io/otel/dependencies.Dockerfile +++ b/vendor/go.opentelemetry.io/otel/dependencies.Dockerfile @@ -1,4 +1,4 @@ # This is a renovate-friendly source of Docker images. FROM python:3.13.6-slim-bullseye@sha256:e98b521460ee75bca92175c16247bdf7275637a8faaeb2bcfa19d879ae5c4b9a AS python -FROM otel/weaver:v0.17.1@sha256:32523b5e44fb44418786347e9f7dde187d8797adb6d57a2ee99c245346c3cdfe AS weaver +FROM otel/weaver:v0.19.0@sha256:3d20814cef548f1d31f27f054fb4cd6a05125641a9f7cc29fc7eb234e8052cd9 AS weaver FROM avtodev/markdown-lint:v1@sha256:6aeedc2f49138ce7a1cd0adffc1b1c0321b841dc2102408967d9301c031949ee AS markdown diff --git a/vendor/go.opentelemetry.io/otel/internal/global/meter.go b/vendor/go.opentelemetry.io/otel/internal/global/meter.go index adb37b5b0e7..6db969f73c7 100644 --- a/vendor/go.opentelemetry.io/otel/internal/global/meter.go +++ b/vendor/go.opentelemetry.io/otel/internal/global/meter.go @@ -105,7 +105,7 @@ type delegatedInstrument interface { setDelegate(metric.Meter) } -// instID are the identifying properties of a instrument. +// instID are the identifying properties of an instrument. type instID struct { // name is the name of the stream. name string diff --git a/vendor/go.opentelemetry.io/otel/metric.go b/vendor/go.opentelemetry.io/otel/metric.go index 1e6473b32f3..527d9aec86b 100644 --- a/vendor/go.opentelemetry.io/otel/metric.go +++ b/vendor/go.opentelemetry.io/otel/metric.go @@ -11,7 +11,7 @@ import ( // Meter returns a Meter from the global MeterProvider. The name must be the // name of the library providing instrumentation. This name may be the same as // the instrumented code only if that code provides built-in instrumentation. -// If the name is empty, then a implementation defined default name will be +// If the name is empty, then an implementation defined default name will be // used instead. // // If this is called before a global MeterProvider is registered the returned diff --git a/vendor/go.opentelemetry.io/otel/metric/config.go b/vendor/go.opentelemetry.io/otel/metric/config.go index d9e3b13e4d1..e42dd6e70ab 100644 --- a/vendor/go.opentelemetry.io/otel/metric/config.go +++ b/vendor/go.opentelemetry.io/otel/metric/config.go @@ -3,7 +3,11 @@ package metric // import "go.opentelemetry.io/otel/metric" -import "go.opentelemetry.io/otel/attribute" +import ( + "slices" + + "go.opentelemetry.io/otel/attribute" +) // MeterConfig contains options for Meters. type MeterConfig struct { @@ -62,12 +66,38 @@ func WithInstrumentationVersion(version string) MeterOption { }) } -// WithInstrumentationAttributes sets the instrumentation attributes. +// WithInstrumentationAttributes adds the instrumentation attributes. +// +// This is equivalent to calling [WithInstrumentationAttributeSet] with an +// [attribute.Set] created from a clone of the passed attributes. +// [WithInstrumentationAttributeSet] is recommended for more control. // -// The passed attributes will be de-duplicated. +// If multiple [WithInstrumentationAttributes] or [WithInstrumentationAttributeSet] +// options are passed, the attributes will be merged together in the order +// they are passed. Attributes with duplicate keys will use the last value passed. func WithInstrumentationAttributes(attr ...attribute.KeyValue) MeterOption { + set := attribute.NewSet(slices.Clone(attr)...) + return WithInstrumentationAttributeSet(set) +} + +// WithInstrumentationAttributeSet adds the instrumentation attributes. +// +// If multiple [WithInstrumentationAttributes] or [WithInstrumentationAttributeSet] +// options are passed, the attributes will be merged together in the order +// they are passed. Attributes with duplicate keys will use the last value passed. +func WithInstrumentationAttributeSet(set attribute.Set) MeterOption { + if set.Len() == 0 { + return meterOptionFunc(func(config MeterConfig) MeterConfig { + return config + }) + } + return meterOptionFunc(func(config MeterConfig) MeterConfig { - config.attrs = attribute.NewSet(attr...) + if config.attrs.Len() == 0 { + config.attrs = set + } else { + config.attrs = mergeSets(config.attrs, set) + } return config }) } diff --git a/vendor/go.opentelemetry.io/otel/propagation/trace_context.go b/vendor/go.opentelemetry.io/otel/propagation/trace_context.go index 6692d2665d2..271ab71f1ae 100644 --- a/vendor/go.opentelemetry.io/otel/propagation/trace_context.go +++ b/vendor/go.opentelemetry.io/otel/propagation/trace_context.go @@ -111,7 +111,7 @@ func (TraceContext) extract(carrier TextMapCarrier) trace.SpanContext { } // Clear all flags other than the trace-context supported sampling bit. - scc.TraceFlags = trace.TraceFlags(opts[0]) & trace.FlagsSampled + scc.TraceFlags = trace.TraceFlags(opts[0]) & trace.FlagsSampled // nolint:gosec // slice size already checked. // Ignore the error returned here. Failure to parse tracestate MUST NOT // affect the parsing of traceparent according to the W3C tracecontext diff --git a/vendor/go.opentelemetry.io/otel/semconv/v1.37.0/error_type.go b/vendor/go.opentelemetry.io/otel/semconv/v1.37.0/error_type.go index 666bded4baf..267979c051d 100644 --- a/vendor/go.opentelemetry.io/otel/semconv/v1.37.0/error_type.go +++ b/vendor/go.opentelemetry.io/otel/semconv/v1.37.0/error_type.go @@ -4,28 +4,53 @@ package semconv // import "go.opentelemetry.io/otel/semconv/v1.37.0" import ( - "fmt" "reflect" "go.opentelemetry.io/otel/attribute" ) // ErrorType returns an [attribute.KeyValue] identifying the error type of err. +// +// If err is nil, the returned attribute has the default value +// [ErrorTypeOther]. +// +// If err's type has the method +// +// ErrorType() string +// +// then the returned attribute has the value of err.ErrorType(). Otherwise, the +// returned attribute has a value derived from the concrete type of err. +// +// The key of the returned attribute is [ErrorTypeKey]. func ErrorType(err error) attribute.KeyValue { if err == nil { return ErrorTypeOther } - t := reflect.TypeOf(err) - var value string - if t.PkgPath() == "" && t.Name() == "" { - // Likely a builtin type. - value = t.String() - } else { - value = fmt.Sprintf("%s.%s", t.PkgPath(), t.Name()) + + return ErrorTypeKey.String(errorType(err)) +} + +func errorType(err error) string { + var s string + if et, ok := err.(interface{ ErrorType() string }); ok { + // Prioritize the ErrorType method if available. + s = et.ErrorType() } + if s == "" { + // Fallback to reflection if the ErrorType method is not supported or + // returns an empty value. - if value == "" { - return ErrorTypeOther + t := reflect.TypeOf(err) + pkg, name := t.PkgPath(), t.Name() + if pkg != "" && name != "" { + s = pkg + "." + name + } else { + // The type has no package path or name (predeclared, not-defined, + // or alias for a not-defined type). + // + // This is not guaranteed to be unique, but is a best effort. + s = t.String() + } } - return ErrorTypeKey.String(value) + return s } diff --git a/vendor/go.opentelemetry.io/otel/trace/config.go b/vendor/go.opentelemetry.io/otel/trace/config.go index aea11a2b52c..d9ecef1cad2 100644 --- a/vendor/go.opentelemetry.io/otel/trace/config.go +++ b/vendor/go.opentelemetry.io/otel/trace/config.go @@ -4,6 +4,7 @@ package trace // import "go.opentelemetry.io/otel/trace" import ( + "slices" "time" "go.opentelemetry.io/otel/attribute" @@ -304,12 +305,50 @@ func WithInstrumentationVersion(version string) TracerOption { }) } -// WithInstrumentationAttributes sets the instrumentation attributes. +// mergeSets returns the union of keys between a and b. Any duplicate keys will +// use the value associated with b. +func mergeSets(a, b attribute.Set) attribute.Set { + // NewMergeIterator uses the first value for any duplicates. + iter := attribute.NewMergeIterator(&b, &a) + merged := make([]attribute.KeyValue, 0, a.Len()+b.Len()) + for iter.Next() { + merged = append(merged, iter.Attribute()) + } + return attribute.NewSet(merged...) +} + +// WithInstrumentationAttributes adds the instrumentation attributes. // -// The passed attributes will be de-duplicated. +// This is equivalent to calling [WithInstrumentationAttributeSet] with an +// [attribute.Set] created from a clone of the passed attributes. +// [WithInstrumentationAttributeSet] is recommended for more control. +// +// If multiple [WithInstrumentationAttributes] or [WithInstrumentationAttributeSet] +// options are passed, the attributes will be merged together in the order +// they are passed. Attributes with duplicate keys will use the last value passed. func WithInstrumentationAttributes(attr ...attribute.KeyValue) TracerOption { + set := attribute.NewSet(slices.Clone(attr)...) + return WithInstrumentationAttributeSet(set) +} + +// WithInstrumentationAttributeSet adds the instrumentation attributes. +// +// If multiple [WithInstrumentationAttributes] or [WithInstrumentationAttributeSet] +// options are passed, the attributes will be merged together in the order +// they are passed. Attributes with duplicate keys will use the last value passed. +func WithInstrumentationAttributeSet(set attribute.Set) TracerOption { + if set.Len() == 0 { + return tracerOptionFunc(func(config TracerConfig) TracerConfig { + return config + }) + } + return tracerOptionFunc(func(config TracerConfig) TracerConfig { - config.attrs = attribute.NewSet(attr...) + if config.attrs.Len() == 0 { + config.attrs = set + } else { + config.attrs = mergeSets(config.attrs, set) + } return config }) } diff --git a/vendor/go.opentelemetry.io/otel/trace/span.go b/vendor/go.opentelemetry.io/otel/trace/span.go index d3aa476ee12..d01e7936649 100644 --- a/vendor/go.opentelemetry.io/otel/trace/span.go +++ b/vendor/go.opentelemetry.io/otel/trace/span.go @@ -66,6 +66,10 @@ type Span interface { // SetAttributes sets kv as attributes of the Span. If a key from kv // already exists for an attribute of the Span it will be overwritten with // the value contained in kv. + // + // Note that adding attributes at span creation using [WithAttributes] is preferred + // to calling SetAttribute later, as samplers can only consider information + // already present during span creation. SetAttributes(kv ...attribute.KeyValue) // TracerProvider returns a TracerProvider that can be used to generate diff --git a/vendor/go.opentelemetry.io/otel/version.go b/vendor/go.opentelemetry.io/otel/version.go index bcaa5aa5378..0d5b0291873 100644 --- a/vendor/go.opentelemetry.io/otel/version.go +++ b/vendor/go.opentelemetry.io/otel/version.go @@ -5,5 +5,5 @@ package otel // import "go.opentelemetry.io/otel" // Version is the current release version of OpenTelemetry in use. func Version() string { - return "1.38.0" + return "1.39.0" } diff --git a/vendor/go.opentelemetry.io/otel/versions.yaml b/vendor/go.opentelemetry.io/otel/versions.yaml index 07145e254b5..f4a3893eb5a 100644 --- a/vendor/go.opentelemetry.io/otel/versions.yaml +++ b/vendor/go.opentelemetry.io/otel/versions.yaml @@ -3,7 +3,7 @@ module-sets: stable-v1: - version: v1.38.0 + version: v1.39.0 modules: - go.opentelemetry.io/otel - go.opentelemetry.io/otel/bridge/opencensus @@ -22,11 +22,11 @@ module-sets: - go.opentelemetry.io/otel/sdk/metric - go.opentelemetry.io/otel/trace experimental-metrics: - version: v0.60.0 + version: v0.61.0 modules: - go.opentelemetry.io/otel/exporters/prometheus experimental-logs: - version: v0.14.0 + version: v0.15.0 modules: - go.opentelemetry.io/otel/log - go.opentelemetry.io/otel/log/logtest @@ -36,9 +36,28 @@ module-sets: - go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploghttp - go.opentelemetry.io/otel/exporters/stdout/stdoutlog experimental-schema: - version: v0.0.13 + version: v0.0.14 modules: - go.opentelemetry.io/otel/schema excluded-modules: - go.opentelemetry.io/otel/internal/tools - go.opentelemetry.io/otel/trace/internal/telemetry/test +modules: + go.opentelemetry.io/otel/exporters/stdout/stdouttrace: + version-refs: + - ./internal/version.go + go.opentelemetry.io/otel/exporters/prometheus: + version-refs: + - ./internal/version.go + go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploggrpc: + version-refs: + - ./internal/version.go + go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc: + version-refs: + - ./internal/version.go + go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp: + version-refs: + - ./internal/version.go + go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploghttp: + version-refs: + - ./internal/version.go diff --git a/vendor/golang.org/x/net/http2/transport.go b/vendor/golang.org/x/net/http2/transport.go index 1965913e543..ccb87e6da37 100644 --- a/vendor/golang.org/x/net/http2/transport.go +++ b/vendor/golang.org/x/net/http2/transport.go @@ -376,11 +376,24 @@ type ClientConn struct { // completely unresponsive connection. pendingResets int + // readBeforeStreamID is the smallest stream ID that has not been followed by + // a frame read from the peer. We use this to determine when a request may + // have been sent to a completely unresponsive connection: + // If the request ID is less than readBeforeStreamID, then we have had some + // indication of life on the connection since sending the request. + readBeforeStreamID uint32 + // reqHeaderMu is a 1-element semaphore channel controlling access to sending new requests. // Write to reqHeaderMu to lock it, read from it to unlock. // Lock reqmu BEFORE mu or wmu. reqHeaderMu chan struct{} + // internalStateHook reports state changes back to the net/http.ClientConn. + // Note that this is different from the user state hook registered by + // net/http.ClientConn.SetStateHook: The internal hook calls ClientConn, + // which calls the user hook. + internalStateHook func() + // wmu is held while writing. // Acquire BEFORE mu when holding both, to avoid blocking mu on network writes. // Only acquire both at the same time when changing peer settings. @@ -710,7 +723,7 @@ func canRetryError(err error) bool { func (t *Transport) dialClientConn(ctx context.Context, addr string, singleUse bool) (*ClientConn, error) { if t.transportTestHooks != nil { - return t.newClientConn(nil, singleUse) + return t.newClientConn(nil, singleUse, nil) } host, _, err := net.SplitHostPort(addr) if err != nil { @@ -720,7 +733,7 @@ func (t *Transport) dialClientConn(ctx context.Context, addr string, singleUse b if err != nil { return nil, err } - return t.newClientConn(tconn, singleUse) + return t.newClientConn(tconn, singleUse, nil) } func (t *Transport) newTLSConfig(host string) *tls.Config { @@ -772,10 +785,10 @@ func (t *Transport) expectContinueTimeout() time.Duration { } func (t *Transport) NewClientConn(c net.Conn) (*ClientConn, error) { - return t.newClientConn(c, t.disableKeepAlives()) + return t.newClientConn(c, t.disableKeepAlives(), nil) } -func (t *Transport) newClientConn(c net.Conn, singleUse bool) (*ClientConn, error) { +func (t *Transport) newClientConn(c net.Conn, singleUse bool, internalStateHook func()) (*ClientConn, error) { conf := configFromTransport(t) cc := &ClientConn{ t: t, @@ -797,6 +810,7 @@ func (t *Transport) newClientConn(c net.Conn, singleUse bool) (*ClientConn, erro pings: make(map[[8]byte]chan struct{}), reqHeaderMu: make(chan struct{}, 1), lastActive: time.Now(), + internalStateHook: internalStateHook, } if t.transportTestHooks != nil { t.transportTestHooks.newclientconn(cc) @@ -1037,10 +1051,7 @@ func (cc *ClientConn) idleStateLocked() (st clientConnIdleState) { maxConcurrentOkay = cc.currentRequestCountLocked() < int(cc.maxConcurrentStreams) } - st.canTakeNewRequest = cc.goAway == nil && !cc.closed && !cc.closing && maxConcurrentOkay && - !cc.doNotReuse && - int64(cc.nextStreamID)+2*int64(cc.pendingRequests) < math.MaxInt32 && - !cc.tooIdleLocked() + st.canTakeNewRequest = maxConcurrentOkay && cc.isUsableLocked() // If this connection has never been used for a request and is closed, // then let it take a request (which will fail). @@ -1056,6 +1067,31 @@ func (cc *ClientConn) idleStateLocked() (st clientConnIdleState) { return } +func (cc *ClientConn) isUsableLocked() bool { + return cc.goAway == nil && + !cc.closed && + !cc.closing && + !cc.doNotReuse && + int64(cc.nextStreamID)+2*int64(cc.pendingRequests) < math.MaxInt32 && + !cc.tooIdleLocked() +} + +// canReserveLocked reports whether a net/http.ClientConn can reserve a slot on this conn. +// +// This follows slightly different rules than clientConnIdleState.canTakeNewRequest. +// We only permit reservations up to the conn's concurrency limit. +// This differs from ClientConn.ReserveNewRequest, which permits reservations +// past the limit when StrictMaxConcurrentStreams is set. +func (cc *ClientConn) canReserveLocked() bool { + if cc.currentRequestCountLocked() >= int(cc.maxConcurrentStreams) { + return false + } + if !cc.isUsableLocked() { + return false + } + return true +} + // currentRequestCountLocked reports the number of concurrency slots currently in use, // including active streams, reserved slots, and reset streams waiting for acknowledgement. func (cc *ClientConn) currentRequestCountLocked() int { @@ -1067,6 +1103,14 @@ func (cc *ClientConn) canTakeNewRequestLocked() bool { return st.canTakeNewRequest } +// availableLocked reports the number of concurrency slots available. +func (cc *ClientConn) availableLocked() int { + if !cc.canTakeNewRequestLocked() { + return 0 + } + return max(0, int(cc.maxConcurrentStreams)-cc.currentRequestCountLocked()) +} + // tooIdleLocked reports whether this connection has been been sitting idle // for too much wall time. func (cc *ClientConn) tooIdleLocked() bool { @@ -1091,6 +1135,7 @@ func (cc *ClientConn) closeConn() { t := time.AfterFunc(250*time.Millisecond, cc.forceCloseConn) defer t.Stop() cc.tconn.Close() + cc.maybeCallStateHook() } // A tls.Conn.Close can hang for a long time if the peer is unresponsive. @@ -1616,6 +1661,8 @@ func (cs *clientStream) cleanupWriteRequest(err error) { } bodyClosed := cs.reqBodyClosed closeOnIdle := cc.singleUse || cc.doNotReuse || cc.t.disableKeepAlives() || cc.goAway != nil + // Have we read any frames from the connection since sending this request? + readSinceStream := cc.readBeforeStreamID > cs.ID cc.mu.Unlock() if mustCloseBody { cs.reqBody.Close() @@ -1647,8 +1694,10 @@ func (cs *clientStream) cleanupWriteRequest(err error) { // // This could be due to the server becoming unresponsive. // To avoid sending too many requests on a dead connection, - // we let the request continue to consume a concurrency slot - // until we can confirm the server is still responding. + // if we haven't read any frames from the connection since + // sending this request, we let it continue to consume + // a concurrency slot until we can confirm the server is + // still responding. // We do this by sending a PING frame along with the RST_STREAM // (unless a ping is already in flight). // @@ -1659,7 +1708,7 @@ func (cs *clientStream) cleanupWriteRequest(err error) { // because it's short lived and will probably be closed before // we get the ping response. ping := false - if !closeOnIdle { + if !closeOnIdle && !readSinceStream { cc.mu.Lock() // rstStreamPingsBlocked works around a gRPC behavior: // see comment on the field for details. @@ -1693,6 +1742,7 @@ func (cs *clientStream) cleanupWriteRequest(err error) { } close(cs.donec) + cc.maybeCallStateHook() } // awaitOpenSlotForStreamLocked waits until len(streams) < maxConcurrentStreams. @@ -2745,6 +2795,7 @@ func (rl *clientConnReadLoop) streamByID(id uint32, headerOrData bool) *clientSt // See comment on ClientConn.rstStreamPingsBlocked for details. rl.cc.rstStreamPingsBlocked = false } + rl.cc.readBeforeStreamID = rl.cc.nextStreamID cs := rl.cc.streams[id] if cs != nil && !cs.readAborted { return cs @@ -2795,6 +2846,7 @@ func (rl *clientConnReadLoop) processSettings(f *SettingsFrame) error { func (rl *clientConnReadLoop) processSettingsNoWrite(f *SettingsFrame) error { cc := rl.cc + defer cc.maybeCallStateHook() cc.mu.Lock() defer cc.mu.Unlock() @@ -2975,6 +3027,7 @@ func (cc *ClientConn) Ping(ctx context.Context) error { func (rl *clientConnReadLoop) processPing(f *PingFrame) error { if f.IsAck() { cc := rl.cc + defer cc.maybeCallStateHook() cc.mu.Lock() defer cc.mu.Unlock() // If ack, notify listener if any @@ -3198,9 +3251,13 @@ func registerHTTPSProtocol(t *http.Transport, rt noDialH2RoundTripper) (err erro } // noDialH2RoundTripper is a RoundTripper which only tries to complete the request -// if there's already has a cached connection to the host. +// if there's already a cached connection to the host. // (The field is exported so it can be accessed via reflect from net/http; tested // by TestNoDialH2RoundTripperType) +// +// A noDialH2RoundTripper is registered with http1.Transport.RegisterProtocol, +// and the http1.Transport can use type assertions to call non-RoundTrip methods on it. +// This lets us expose, for example, NewClientConn to net/http. type noDialH2RoundTripper struct{ *Transport } func (rt noDialH2RoundTripper) RoundTrip(req *http.Request) (*http.Response, error) { @@ -3211,6 +3268,85 @@ func (rt noDialH2RoundTripper) RoundTrip(req *http.Request) (*http.Response, err return res, err } +func (rt noDialH2RoundTripper) NewClientConn(conn net.Conn, internalStateHook func()) (http.RoundTripper, error) { + tr := rt.Transport + cc, err := tr.newClientConn(conn, tr.disableKeepAlives(), internalStateHook) + if err != nil { + return nil, err + } + + // RoundTrip should block when the conn is at its concurrency limit, + // not return an error. Setting strictMaxConcurrentStreams enables this. + cc.strictMaxConcurrentStreams = true + + return netHTTPClientConn{cc}, nil +} + +// netHTTPClientConn wraps ClientConn and implements the interface net/http expects from +// the RoundTripper returned by NewClientConn. +type netHTTPClientConn struct { + cc *ClientConn +} + +func (cc netHTTPClientConn) RoundTrip(req *http.Request) (*http.Response, error) { + return cc.cc.RoundTrip(req) +} + +func (cc netHTTPClientConn) Close() error { + return cc.cc.Close() +} + +func (cc netHTTPClientConn) Err() error { + cc.cc.mu.Lock() + defer cc.cc.mu.Unlock() + if cc.cc.closed { + return errors.New("connection closed") + } + return nil +} + +func (cc netHTTPClientConn) Reserve() error { + defer cc.cc.maybeCallStateHook() + cc.cc.mu.Lock() + defer cc.cc.mu.Unlock() + if !cc.cc.canReserveLocked() { + return errors.New("connection is unavailable") + } + cc.cc.streamsReserved++ + return nil +} + +func (cc netHTTPClientConn) Release() { + defer cc.cc.maybeCallStateHook() + cc.cc.mu.Lock() + defer cc.cc.mu.Unlock() + // We don't complain if streamsReserved is 0. + // + // This is consistent with RoundTrip: both Release and RoundTrip will + // consume a reservation iff one exists. + if cc.cc.streamsReserved > 0 { + cc.cc.streamsReserved-- + } +} + +func (cc netHTTPClientConn) Available() int { + cc.cc.mu.Lock() + defer cc.cc.mu.Unlock() + return cc.cc.availableLocked() +} + +func (cc netHTTPClientConn) InFlight() int { + cc.cc.mu.Lock() + defer cc.cc.mu.Unlock() + return cc.cc.currentRequestCountLocked() +} + +func (cc *ClientConn) maybeCallStateHook() { + if cc.internalStateHook != nil { + cc.internalStateHook() + } +} + func (t *Transport) idleConnTimeout() time.Duration { // to keep things backwards compatible, we use non-zero values of // IdleConnTimeout, followed by using the IdleConnTimeout on the underlying diff --git a/vendor/golang.org/x/net/trace/events.go b/vendor/golang.org/x/net/trace/events.go index 3aaffdd1f7a..c2b3c009801 100644 --- a/vendor/golang.org/x/net/trace/events.go +++ b/vendor/golang.org/x/net/trace/events.go @@ -58,8 +58,8 @@ func RenderEvents(w http.ResponseWriter, req *http.Request, sensitive bool) { Buckets: buckets, } - data.Families = make([]string, 0, len(families)) famMu.RLock() + data.Families = make([]string, 0, len(families)) for name := range families { data.Families = append(data.Families, name) } diff --git a/vendor/golang.org/x/oauth2/clientcredentials/clientcredentials.go b/vendor/golang.org/x/oauth2/clientcredentials/clientcredentials.go index e86346e8b6c..3ee122d1e95 100644 --- a/vendor/golang.org/x/oauth2/clientcredentials/clientcredentials.go +++ b/vendor/golang.org/x/oauth2/clientcredentials/clientcredentials.go @@ -3,7 +3,7 @@ // license that can be found in the LICENSE file. // Package clientcredentials implements the OAuth2.0 "client credentials" token flow, -// also known as the "two-legged OAuth 2.0". +// also known as "two-legged OAuth 2.0". // // This should be used when the client is acting on its own behalf or when the client // is the resource owner. It may also be used when requesting access to protected diff --git a/vendor/golang.org/x/oauth2/deviceauth.go b/vendor/golang.org/x/oauth2/deviceauth.go index e99c92f39c7..e783a943748 100644 --- a/vendor/golang.org/x/oauth2/deviceauth.go +++ b/vendor/golang.org/x/oauth2/deviceauth.go @@ -6,6 +6,7 @@ import ( "errors" "fmt" "io" + "mime" "net/http" "net/url" "strings" @@ -116,10 +117,38 @@ func retrieveDeviceAuth(ctx context.Context, c *Config, v url.Values) (*DeviceAu return nil, fmt.Errorf("oauth2: cannot auth device: %v", err) } if code := r.StatusCode; code < 200 || code > 299 { - return nil, &RetrieveError{ + retrieveError := &RetrieveError{ Response: r, Body: body, } + + content, _, _ := mime.ParseMediaType(r.Header.Get("Content-Type")) + switch content { + case "application/x-www-form-urlencoded", "text/plain": + // some endpoints return a query string + vals, err := url.ParseQuery(string(body)) + if err != nil { + return nil, retrieveError + } + retrieveError.ErrorCode = vals.Get("error") + retrieveError.ErrorDescription = vals.Get("error_description") + retrieveError.ErrorURI = vals.Get("error_uri") + default: + var tj struct { + // https://datatracker.ietf.org/doc/html/rfc6749#section-5.2 + ErrorCode string `json:"error"` + ErrorDescription string `json:"error_description"` + ErrorURI string `json:"error_uri"` + } + if json.Unmarshal(body, &tj) != nil { + return nil, retrieveError + } + retrieveError.ErrorCode = tj.ErrorCode + retrieveError.ErrorDescription = tj.ErrorDescription + retrieveError.ErrorURI = tj.ErrorURI + } + + return nil, retrieveError } da := &DeviceAuthResponse{} diff --git a/vendor/golang.org/x/oauth2/oauth2.go b/vendor/golang.org/x/oauth2/oauth2.go index 3e3b6306953..5c527d31fd3 100644 --- a/vendor/golang.org/x/oauth2/oauth2.go +++ b/vendor/golang.org/x/oauth2/oauth2.go @@ -98,7 +98,7 @@ const ( // in the POST body as application/x-www-form-urlencoded parameters. AuthStyleInParams AuthStyle = 1 - // AuthStyleInHeader sends the client_id and client_password + // AuthStyleInHeader sends the client_id and client_secret // using HTTP Basic Authorization. This is an optional style // described in the OAuth2 RFC 6749 section 2.3.1. AuthStyleInHeader AuthStyle = 2 diff --git a/vendor/golang.org/x/oauth2/pkce.go b/vendor/golang.org/x/oauth2/pkce.go index cea8374d51b..f99384f0f5c 100644 --- a/vendor/golang.org/x/oauth2/pkce.go +++ b/vendor/golang.org/x/oauth2/pkce.go @@ -51,7 +51,7 @@ func S256ChallengeFromVerifier(verifier string) string { return base64.RawURLEncoding.EncodeToString(sha[:]) } -// S256ChallengeOption derives a PKCE code challenge derived from verifier with +// S256ChallengeOption derives a PKCE code challenge from the verifier with // method S256. It should be passed to [Config.AuthCodeURL] or [Config.DeviceAuth] // only. func S256ChallengeOption(verifier string) AuthCodeOption { diff --git a/vendor/golang.org/x/oauth2/token.go b/vendor/golang.org/x/oauth2/token.go index 239ec329620..e995eebb5e1 100644 --- a/vendor/golang.org/x/oauth2/token.go +++ b/vendor/golang.org/x/oauth2/token.go @@ -103,7 +103,7 @@ func (t *Token) WithExtra(extra any) *Token { } // Extra returns an extra field. -// Extra fields are key-value pairs returned by the server as a +// Extra fields are key-value pairs returned by the server as // part of the token retrieval response. func (t *Token) Extra(key string) any { if raw, ok := t.raw.(map[string]any); ok { diff --git a/vendor/golang.org/x/oauth2/transport.go b/vendor/golang.org/x/oauth2/transport.go index 8bbebbac9ee..9922ec33164 100644 --- a/vendor/golang.org/x/oauth2/transport.go +++ b/vendor/golang.org/x/oauth2/transport.go @@ -58,7 +58,7 @@ func (t *Transport) RoundTrip(req *http.Request) (*http.Response, error) { var cancelOnce sync.Once // CancelRequest does nothing. It used to be a legacy cancellation mechanism -// but now only it only logs on first use to warn that it's deprecated. +// but now only logs on first use to warn that it's deprecated. // // Deprecated: use contexts for cancellation instead. func (t *Transport) CancelRequest(req *http.Request) { diff --git a/vendor/golang.org/x/sync/errgroup/errgroup.go b/vendor/golang.org/x/sync/errgroup/errgroup.go index 2f45dbc86e5..f69fd754685 100644 --- a/vendor/golang.org/x/sync/errgroup/errgroup.go +++ b/vendor/golang.org/x/sync/errgroup/errgroup.go @@ -144,8 +144,8 @@ func (g *Group) SetLimit(n int) { g.sem = nil return } - if len(g.sem) != 0 { - panic(fmt.Errorf("errgroup: modify limit while %v goroutines in the group are still active", len(g.sem))) + if active := len(g.sem); active != 0 { + panic(fmt.Errorf("errgroup: modify limit while %v goroutines in the group are still active", active)) } g.sem = make(chan token, n) } diff --git a/vendor/golang.org/x/sys/unix/mkerrors.sh b/vendor/golang.org/x/sys/unix/mkerrors.sh index 42517077c43..fd39be4efdc 100644 --- a/vendor/golang.org/x/sys/unix/mkerrors.sh +++ b/vendor/golang.org/x/sys/unix/mkerrors.sh @@ -256,6 +256,7 @@ struct ltchars { #include #include #include +#include #include #include #include @@ -613,7 +614,7 @@ ccflags="$@" $2 !~ /IOC_MAGIC/ && $2 ~ /^[A-Z][A-Z0-9_]+_MAGIC2?$/ || $2 ~ /^(VM|VMADDR)_/ || - $2 ~ /^IOCTL_VM_SOCKETS_/ || + $2 ~ /^(IOCTL_VM_SOCKETS_|IOCTL_MEI_)/ || $2 ~ /^(TASKSTATS|TS)_/ || $2 ~ /^CGROUPSTATS_/ || $2 ~ /^GENL_/ || diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux.go b/vendor/golang.org/x/sys/unix/zerrors_linux.go index d0a75da572c..120a7b35d1d 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux.go @@ -1615,6 +1615,8 @@ const ( IN_OPEN = 0x20 IN_Q_OVERFLOW = 0x4000 IN_UNMOUNT = 0x2000 + IOCTL_MEI_CONNECT_CLIENT = 0xc0104801 + IOCTL_MEI_CONNECT_CLIENT_VTAG = 0xc0144804 IPPROTO_AH = 0x33 IPPROTO_BEETPH = 0x5e IPPROTO_COMP = 0x6c diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_386.go b/vendor/golang.org/x/sys/unix/zerrors_linux_386.go index 1c37f9fbc45..97a61fc5b84 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_386.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_386.go @@ -116,6 +116,8 @@ const ( IEXTEN = 0x8000 IN_CLOEXEC = 0x80000 IN_NONBLOCK = 0x800 + IOCTL_MEI_NOTIFY_GET = 0x80044803 + IOCTL_MEI_NOTIFY_SET = 0x40044802 IOCTL_VM_SOCKETS_GET_LOCAL_CID = 0x7b9 IPV6_FLOWINFO_MASK = 0xffffff0f IPV6_FLOWLABEL_MASK = 0xffff0f00 diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_amd64.go b/vendor/golang.org/x/sys/unix/zerrors_linux_amd64.go index 6f54d34aefc..a0d6d498c4b 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_amd64.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_amd64.go @@ -116,6 +116,8 @@ const ( IEXTEN = 0x8000 IN_CLOEXEC = 0x80000 IN_NONBLOCK = 0x800 + IOCTL_MEI_NOTIFY_GET = 0x80044803 + IOCTL_MEI_NOTIFY_SET = 0x40044802 IOCTL_VM_SOCKETS_GET_LOCAL_CID = 0x7b9 IPV6_FLOWINFO_MASK = 0xffffff0f IPV6_FLOWLABEL_MASK = 0xffff0f00 diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_arm.go b/vendor/golang.org/x/sys/unix/zerrors_linux_arm.go index 783ec5c126f..dd9c903f9ad 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_arm.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_arm.go @@ -115,6 +115,8 @@ const ( IEXTEN = 0x8000 IN_CLOEXEC = 0x80000 IN_NONBLOCK = 0x800 + IOCTL_MEI_NOTIFY_GET = 0x80044803 + IOCTL_MEI_NOTIFY_SET = 0x40044802 IOCTL_VM_SOCKETS_GET_LOCAL_CID = 0x7b9 IPV6_FLOWINFO_MASK = 0xffffff0f IPV6_FLOWLABEL_MASK = 0xffff0f00 diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_arm64.go b/vendor/golang.org/x/sys/unix/zerrors_linux_arm64.go index ca83d3ba162..384c61ca3a8 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_arm64.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_arm64.go @@ -120,6 +120,8 @@ const ( IEXTEN = 0x8000 IN_CLOEXEC = 0x80000 IN_NONBLOCK = 0x800 + IOCTL_MEI_NOTIFY_GET = 0x80044803 + IOCTL_MEI_NOTIFY_SET = 0x40044802 IOCTL_VM_SOCKETS_GET_LOCAL_CID = 0x7b9 IPV6_FLOWINFO_MASK = 0xffffff0f IPV6_FLOWLABEL_MASK = 0xffff0f00 diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_loong64.go b/vendor/golang.org/x/sys/unix/zerrors_linux_loong64.go index 607e611c0cb..6384c9831fc 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_loong64.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_loong64.go @@ -116,6 +116,8 @@ const ( IEXTEN = 0x8000 IN_CLOEXEC = 0x80000 IN_NONBLOCK = 0x800 + IOCTL_MEI_NOTIFY_GET = 0x80044803 + IOCTL_MEI_NOTIFY_SET = 0x40044802 IOCTL_VM_SOCKETS_GET_LOCAL_CID = 0x7b9 IPV6_FLOWINFO_MASK = 0xffffff0f IPV6_FLOWLABEL_MASK = 0xffff0f00 diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_mips.go b/vendor/golang.org/x/sys/unix/zerrors_linux_mips.go index b9cb5bd3c09..553c1c6f15e 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_mips.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_mips.go @@ -115,6 +115,8 @@ const ( IEXTEN = 0x100 IN_CLOEXEC = 0x80000 IN_NONBLOCK = 0x80 + IOCTL_MEI_NOTIFY_GET = 0x40044803 + IOCTL_MEI_NOTIFY_SET = 0x80044802 IOCTL_VM_SOCKETS_GET_LOCAL_CID = 0x200007b9 IPV6_FLOWINFO_MASK = 0xfffffff IPV6_FLOWLABEL_MASK = 0xfffff diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_mips64.go b/vendor/golang.org/x/sys/unix/zerrors_linux_mips64.go index 65b078a6382..b3339f2099a 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_mips64.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_mips64.go @@ -115,6 +115,8 @@ const ( IEXTEN = 0x100 IN_CLOEXEC = 0x80000 IN_NONBLOCK = 0x80 + IOCTL_MEI_NOTIFY_GET = 0x40044803 + IOCTL_MEI_NOTIFY_SET = 0x80044802 IOCTL_VM_SOCKETS_GET_LOCAL_CID = 0x200007b9 IPV6_FLOWINFO_MASK = 0xfffffff IPV6_FLOWLABEL_MASK = 0xfffff diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_mips64le.go b/vendor/golang.org/x/sys/unix/zerrors_linux_mips64le.go index 5298a3033d0..177091d2bc3 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_mips64le.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_mips64le.go @@ -115,6 +115,8 @@ const ( IEXTEN = 0x100 IN_CLOEXEC = 0x80000 IN_NONBLOCK = 0x80 + IOCTL_MEI_NOTIFY_GET = 0x40044803 + IOCTL_MEI_NOTIFY_SET = 0x80044802 IOCTL_VM_SOCKETS_GET_LOCAL_CID = 0x200007b9 IPV6_FLOWINFO_MASK = 0xffffff0f IPV6_FLOWLABEL_MASK = 0xffff0f00 diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_mipsle.go b/vendor/golang.org/x/sys/unix/zerrors_linux_mipsle.go index 7bc557c8761..c5abf156d09 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_mipsle.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_mipsle.go @@ -115,6 +115,8 @@ const ( IEXTEN = 0x100 IN_CLOEXEC = 0x80000 IN_NONBLOCK = 0x80 + IOCTL_MEI_NOTIFY_GET = 0x40044803 + IOCTL_MEI_NOTIFY_SET = 0x80044802 IOCTL_VM_SOCKETS_GET_LOCAL_CID = 0x200007b9 IPV6_FLOWINFO_MASK = 0xffffff0f IPV6_FLOWLABEL_MASK = 0xffff0f00 diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_ppc.go b/vendor/golang.org/x/sys/unix/zerrors_linux_ppc.go index 152399bb04a..f1f3fadf576 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_ppc.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_ppc.go @@ -115,6 +115,8 @@ const ( IEXTEN = 0x400 IN_CLOEXEC = 0x80000 IN_NONBLOCK = 0x800 + IOCTL_MEI_NOTIFY_GET = 0x40044803 + IOCTL_MEI_NOTIFY_SET = 0x80044802 IOCTL_VM_SOCKETS_GET_LOCAL_CID = 0x200007b9 IPV6_FLOWINFO_MASK = 0xfffffff IPV6_FLOWLABEL_MASK = 0xfffff diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_ppc64.go b/vendor/golang.org/x/sys/unix/zerrors_linux_ppc64.go index 1a1ce2409cf..203ad9c54af 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_ppc64.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_ppc64.go @@ -115,6 +115,8 @@ const ( IEXTEN = 0x400 IN_CLOEXEC = 0x80000 IN_NONBLOCK = 0x800 + IOCTL_MEI_NOTIFY_GET = 0x40044803 + IOCTL_MEI_NOTIFY_SET = 0x80044802 IOCTL_VM_SOCKETS_GET_LOCAL_CID = 0x200007b9 IPV6_FLOWINFO_MASK = 0xfffffff IPV6_FLOWLABEL_MASK = 0xfffff diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_ppc64le.go b/vendor/golang.org/x/sys/unix/zerrors_linux_ppc64le.go index 4231a1fb578..4b9abcb21a2 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_ppc64le.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_ppc64le.go @@ -115,6 +115,8 @@ const ( IEXTEN = 0x400 IN_CLOEXEC = 0x80000 IN_NONBLOCK = 0x800 + IOCTL_MEI_NOTIFY_GET = 0x40044803 + IOCTL_MEI_NOTIFY_SET = 0x80044802 IOCTL_VM_SOCKETS_GET_LOCAL_CID = 0x200007b9 IPV6_FLOWINFO_MASK = 0xffffff0f IPV6_FLOWLABEL_MASK = 0xffff0f00 diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_riscv64.go b/vendor/golang.org/x/sys/unix/zerrors_linux_riscv64.go index 21c0e952665..f87983037d9 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_riscv64.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_riscv64.go @@ -115,6 +115,8 @@ const ( IEXTEN = 0x8000 IN_CLOEXEC = 0x80000 IN_NONBLOCK = 0x800 + IOCTL_MEI_NOTIFY_GET = 0x80044803 + IOCTL_MEI_NOTIFY_SET = 0x40044802 IOCTL_VM_SOCKETS_GET_LOCAL_CID = 0x7b9 IPV6_FLOWINFO_MASK = 0xffffff0f IPV6_FLOWLABEL_MASK = 0xffff0f00 diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_s390x.go b/vendor/golang.org/x/sys/unix/zerrors_linux_s390x.go index f00d1cd7cf4..64347eb354c 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_s390x.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_s390x.go @@ -115,6 +115,8 @@ const ( IEXTEN = 0x8000 IN_CLOEXEC = 0x80000 IN_NONBLOCK = 0x800 + IOCTL_MEI_NOTIFY_GET = 0x80044803 + IOCTL_MEI_NOTIFY_SET = 0x40044802 IOCTL_VM_SOCKETS_GET_LOCAL_CID = 0x7b9 IPV6_FLOWINFO_MASK = 0xfffffff IPV6_FLOWLABEL_MASK = 0xfffff diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_sparc64.go b/vendor/golang.org/x/sys/unix/zerrors_linux_sparc64.go index bc8d539e6af..7d71911718f 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_sparc64.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_sparc64.go @@ -119,6 +119,8 @@ const ( IEXTEN = 0x8000 IN_CLOEXEC = 0x400000 IN_NONBLOCK = 0x4000 + IOCTL_MEI_NOTIFY_GET = 0x40044803 + IOCTL_MEI_NOTIFY_SET = 0x80044802 IOCTL_VM_SOCKETS_GET_LOCAL_CID = 0x200007b9 IPV6_FLOWINFO_MASK = 0xfffffff IPV6_FLOWLABEL_MASK = 0xfffff diff --git a/vendor/golang.org/x/sys/unix/ztypes_netbsd_arm.go b/vendor/golang.org/x/sys/unix/ztypes_netbsd_arm.go index 439548ec9ad..50e8e644970 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_netbsd_arm.go +++ b/vendor/golang.org/x/sys/unix/ztypes_netbsd_arm.go @@ -104,7 +104,7 @@ type Statvfs_t struct { Fsid uint32 Namemax uint32 Owner uint32 - Spare [4]uint32 + Spare [4]uint64 Fstypename [32]byte Mntonname [1024]byte Mntfromname [1024]byte diff --git a/vendor/golang.org/x/time/rate/rate.go b/vendor/golang.org/x/time/rate/rate.go index 794b2e32bfa..563270c1549 100644 --- a/vendor/golang.org/x/time/rate/rate.go +++ b/vendor/golang.org/x/time/rate/rate.go @@ -195,7 +195,7 @@ func (r *Reservation) CancelAt(t time.Time) { // update state r.lim.last = t r.lim.tokens = tokens - if r.timeToAct == r.lim.lastEvent { + if r.timeToAct.Equal(r.lim.lastEvent) { prevEvent := r.timeToAct.Add(r.limit.durationFromTokens(float64(-r.tokens))) if !prevEvent.Before(t) { r.lim.lastEvent = prevEvent diff --git a/vendor/google.golang.org/protobuf/internal/encoding/tag/tag.go b/vendor/google.golang.org/protobuf/internal/encoding/tag/tag.go index 669133d04dc..c96e4483460 100644 --- a/vendor/google.golang.org/protobuf/internal/encoding/tag/tag.go +++ b/vendor/google.golang.org/protobuf/internal/encoding/tag/tag.go @@ -32,7 +32,7 @@ var byteType = reflect.TypeOf(byte(0)) func Unmarshal(tag string, goType reflect.Type, evs protoreflect.EnumValueDescriptors) protoreflect.FieldDescriptor { f := new(filedesc.Field) f.L0.ParentFile = filedesc.SurrogateProto2 - f.L1.EditionFeatures = f.L0.ParentFile.L1.EditionFeatures + packed := false for len(tag) > 0 { i := strings.IndexByte(tag, ',') if i < 0 { @@ -108,7 +108,7 @@ func Unmarshal(tag string, goType reflect.Type, evs protoreflect.EnumValueDescri f.L1.StringName.InitJSON(jsonName) } case s == "packed": - f.L1.EditionFeatures.IsPacked = true + packed = true case strings.HasPrefix(s, "def="): // The default tag is special in that everything afterwards is the // default regardless of the presence of commas. @@ -121,6 +121,13 @@ func Unmarshal(tag string, goType reflect.Type, evs protoreflect.EnumValueDescri tag = strings.TrimPrefix(tag[i:], ",") } + // Update EditionFeatures after the loop and after we know whether this is + // a proto2 or proto3 field. + f.L1.EditionFeatures = f.L0.ParentFile.L1.EditionFeatures + if packed { + f.L1.EditionFeatures.IsPacked = true + } + // The generator uses the group message name instead of the field name. // We obtain the real field name by lowercasing the group name. if f.L1.Kind == protoreflect.GroupKind { diff --git a/vendor/google.golang.org/protobuf/internal/encoding/text/decode.go b/vendor/google.golang.org/protobuf/internal/encoding/text/decode.go index 099b2bf451b..9aa7a9bb776 100644 --- a/vendor/google.golang.org/protobuf/internal/encoding/text/decode.go +++ b/vendor/google.golang.org/protobuf/internal/encoding/text/decode.go @@ -424,27 +424,34 @@ func (d *Decoder) parseFieldName() (tok Token, err error) { return Token{}, d.newSyntaxError("invalid field name: %s", errId(d.in)) } -// parseTypeName parses Any type URL or extension field name. The name is -// enclosed in [ and ] characters. The C++ parser does not handle many legal URL -// strings. This implementation is more liberal and allows for the pattern -// ^[-_a-zA-Z0-9]+([./][-_a-zA-Z0-9]+)*`). Whitespaces and comments are allowed -// in between [ ], '.', '/' and the sub names. +// parseTypeName parses an Any type URL or an extension field name. The name is +// enclosed in [ and ] characters. We allow almost arbitrary type URL prefixes, +// closely following the text-format spec [1,2]. We implement "ExtensionName | +// AnyName" as follows (with some exceptions for backwards compatibility): +// +// char = [-_a-zA-Z0-9] +// url_char = char | [.~!$&'()*+,;=] | "%", hex, hex +// +// Ident = char, { char } +// TypeName = Ident, { ".", Ident } ; +// UrlPrefix = url_char, { url_char | "/" } ; +// ExtensionName = "[", TypeName, "]" ; +// AnyName = "[", UrlPrefix, "/", TypeName, "]" ; +// +// Additionally, we allow arbitrary whitespace and comments between [ and ]. +// +// [1] https://protobuf.dev/reference/protobuf/textformat-spec/#characters +// [2] https://protobuf.dev/reference/protobuf/textformat-spec/#field-names func (d *Decoder) parseTypeName() (Token, error) { - startPos := len(d.orig) - len(d.in) // Use alias s to advance first in order to use d.in for error handling. - // Caller already checks for [ as first character. + // Caller already checks for [ as first character (d.in[0] == '['). s := consume(d.in[1:], 0) if len(s) == 0 { return Token{}, ErrUnexpectedEOF } + // Collect everything between [ and ] in name. var name []byte - for len(s) > 0 && isTypeNameChar(s[0]) { - name = append(name, s[0]) - s = s[1:] - } - s = consume(s, 0) - var closed bool for len(s) > 0 && !closed { switch { @@ -452,23 +459,20 @@ func (d *Decoder) parseTypeName() (Token, error) { s = s[1:] closed = true - case s[0] == '/', s[0] == '.': - if len(name) > 0 && (name[len(name)-1] == '/' || name[len(name)-1] == '.') { - return Token{}, d.newSyntaxError("invalid type URL/extension field name: %s", - d.orig[startPos:len(d.orig)-len(s)+1]) - } + case s[0] == '/' || isTypeNameChar(s[0]) || isUrlExtraChar(s[0]): name = append(name, s[0]) - s = s[1:] - s = consume(s, 0) - for len(s) > 0 && isTypeNameChar(s[0]) { - name = append(name, s[0]) - s = s[1:] + s = consume(s[1:], 0) + + // URL percent-encoded chars + case s[0] == '%': + if len(s) < 3 || !isHexChar(s[1]) || !isHexChar(s[2]) { + return Token{}, d.parseTypeNameError(s, 3) } - s = consume(s, 0) + name = append(name, s[0], s[1], s[2]) + s = consume(s[3:], 0) default: - return Token{}, d.newSyntaxError( - "invalid type URL/extension field name: %s", d.orig[startPos:len(d.orig)-len(s)+1]) + return Token{}, d.parseTypeNameError(s, 1) } } @@ -476,15 +480,38 @@ func (d *Decoder) parseTypeName() (Token, error) { return Token{}, ErrUnexpectedEOF } - // First character cannot be '.'. Last character cannot be '.' or '/'. - size := len(name) - if size == 0 || name[0] == '.' || name[size-1] == '.' || name[size-1] == '/' { - return Token{}, d.newSyntaxError("invalid type URL/extension field name: %s", - d.orig[startPos:len(d.orig)-len(s)]) + // Split collected name on last '/' into urlPrefix and typeName (if '/' is + // present). + typeName := name + if i := bytes.LastIndexByte(name, '/'); i != -1 { + urlPrefix := name[:i] + typeName = name[i+1:] + + // urlPrefix may be empty (for backwards compatibility). + // If non-empty, it must not start with '/'. + if len(urlPrefix) > 0 && urlPrefix[0] == '/' { + return Token{}, d.parseTypeNameError(s, 0) + } } + // typeName must not be empty (note: "" splits to [""]) and all identifier + // parts must not be empty. + for _, ident := range bytes.Split(typeName, []byte{'.'}) { + if len(ident) == 0 { + return Token{}, d.parseTypeNameError(s, 0) + } + } + + // typeName must not contain any percent-encoded or special URL chars. + for _, b := range typeName { + if b == '%' || (b != '.' && isUrlExtraChar(b)) { + return Token{}, d.parseTypeNameError(s, 0) + } + } + + startPos := len(d.orig) - len(d.in) + endPos := len(d.orig) - len(s) d.in = s - endPos := len(d.orig) - len(d.in) d.consume(0) return Token{ @@ -496,16 +523,32 @@ func (d *Decoder) parseTypeName() (Token, error) { }, nil } +func (d *Decoder) parseTypeNameError(s []byte, numUnconsumedChars int) error { + return d.newSyntaxError( + "invalid type URL/extension field name: %s", + d.in[:len(d.in)-len(s)+min(numUnconsumedChars, len(s))], + ) +} + +func isHexChar(b byte) bool { + return ('0' <= b && b <= '9') || + ('a' <= b && b <= 'f') || + ('A' <= b && b <= 'F') +} + func isTypeNameChar(b byte) bool { - return (b == '-' || b == '_' || + return b == '-' || b == '_' || ('0' <= b && b <= '9') || ('a' <= b && b <= 'z') || - ('A' <= b && b <= 'Z')) + ('A' <= b && b <= 'Z') } -func isWhiteSpace(b byte) bool { +// isUrlExtraChar complements isTypeNameChar with extra characters that we allow +// in URLs but not in type names. Note that '/' is not included so that it can +// be treated specially. +func isUrlExtraChar(b byte) bool { switch b { - case ' ', '\n', '\r', '\t': + case '.', '~', '!', '$', '&', '(', ')', '*', '+', ',', ';', '=': return true default: return false diff --git a/vendor/google.golang.org/protobuf/internal/filedesc/desc.go b/vendor/google.golang.org/protobuf/internal/filedesc/desc.go index dbcf90b871f..c775e5832f0 100644 --- a/vendor/google.golang.org/protobuf/internal/filedesc/desc.go +++ b/vendor/google.golang.org/protobuf/internal/filedesc/desc.go @@ -32,6 +32,7 @@ const ( EditionProto3 Edition = 999 Edition2023 Edition = 1000 Edition2024 Edition = 1001 + EditionUnstable Edition = 9999 EditionUnsupported Edition = 100000 ) diff --git a/vendor/google.golang.org/protobuf/internal/filedesc/desc_lazy.go b/vendor/google.golang.org/protobuf/internal/filedesc/desc_lazy.go index dd31faaeb0a..78f02b1b495 100644 --- a/vendor/google.golang.org/protobuf/internal/filedesc/desc_lazy.go +++ b/vendor/google.golang.org/protobuf/internal/filedesc/desc_lazy.go @@ -330,7 +330,6 @@ func (md *Message) unmarshalFull(b []byte, sb *strs.Builder) { md.L1.Extensions.List[extensionIdx].unmarshalFull(v, sb) extensionIdx++ case genid.DescriptorProto_Options_field_number: - md.unmarshalOptions(v) rawOptions = appendOptions(rawOptions, v) } default: @@ -356,27 +355,6 @@ func (md *Message) unmarshalFull(b []byte, sb *strs.Builder) { md.L2.Options = md.L0.ParentFile.builder.optionsUnmarshaler(&descopts.Message, rawOptions) } -func (md *Message) unmarshalOptions(b []byte) { - for len(b) > 0 { - num, typ, n := protowire.ConsumeTag(b) - b = b[n:] - switch typ { - case protowire.VarintType: - v, m := protowire.ConsumeVarint(b) - b = b[m:] - switch num { - case genid.MessageOptions_MapEntry_field_number: - md.L1.IsMapEntry = protowire.DecodeBool(v) - case genid.MessageOptions_MessageSetWireFormat_field_number: - md.L1.IsMessageSet = protowire.DecodeBool(v) - } - default: - m := protowire.ConsumeFieldValue(num, typ, b) - b = b[m:] - } - } -} - func unmarshalMessageReservedRange(b []byte) (r [2]protoreflect.FieldNumber) { for len(b) > 0 { num, typ, n := protowire.ConsumeTag(b) diff --git a/vendor/google.golang.org/protobuf/internal/genid/descriptor_gen.go b/vendor/google.golang.org/protobuf/internal/genid/descriptor_gen.go index 950a6a325a4..65aaf4d210a 100644 --- a/vendor/google.golang.org/protobuf/internal/genid/descriptor_gen.go +++ b/vendor/google.golang.org/protobuf/internal/genid/descriptor_gen.go @@ -26,6 +26,7 @@ const ( Edition_EDITION_PROTO3_enum_value = 999 Edition_EDITION_2023_enum_value = 1000 Edition_EDITION_2024_enum_value = 1001 + Edition_EDITION_UNSTABLE_enum_value = 9999 Edition_EDITION_1_TEST_ONLY_enum_value = 1 Edition_EDITION_2_TEST_ONLY_enum_value = 2 Edition_EDITION_99997_TEST_ONLY_enum_value = 99997 diff --git a/vendor/google.golang.org/protobuf/internal/impl/codec_map.go b/vendor/google.golang.org/protobuf/internal/impl/codec_map.go index 229c6980138..4a3bf393ef4 100644 --- a/vendor/google.golang.org/protobuf/internal/impl/codec_map.go +++ b/vendor/google.golang.org/protobuf/internal/impl/codec_map.go @@ -113,6 +113,9 @@ func sizeMap(mapv reflect.Value, mapi *mapInfo, f *coderFieldInfo, opts marshalO } func consumeMap(b []byte, mapv reflect.Value, wtyp protowire.Type, mapi *mapInfo, f *coderFieldInfo, opts unmarshalOptions) (out unmarshalOutput, err error) { + if opts.depth--; opts.depth < 0 { + return out, errRecursionDepth + } if wtyp != protowire.BytesType { return out, errUnknown } @@ -170,6 +173,9 @@ func consumeMap(b []byte, mapv reflect.Value, wtyp protowire.Type, mapi *mapInfo } func consumeMapOfMessage(b []byte, mapv reflect.Value, wtyp protowire.Type, mapi *mapInfo, f *coderFieldInfo, opts unmarshalOptions) (out unmarshalOutput, err error) { + if opts.depth--; opts.depth < 0 { + return out, errRecursionDepth + } if wtyp != protowire.BytesType { return out, errUnknown } diff --git a/vendor/google.golang.org/protobuf/internal/impl/decode.go b/vendor/google.golang.org/protobuf/internal/impl/decode.go index e0dd21fa5f4..1228b5c8c27 100644 --- a/vendor/google.golang.org/protobuf/internal/impl/decode.go +++ b/vendor/google.golang.org/protobuf/internal/impl/decode.go @@ -102,8 +102,7 @@ var errUnknown = errors.New("unknown") func (mi *MessageInfo) unmarshalPointer(b []byte, p pointer, groupTag protowire.Number, opts unmarshalOptions) (out unmarshalOutput, err error) { mi.init() - opts.depth-- - if opts.depth < 0 { + if opts.depth--; opts.depth < 0 { return out, errRecursionDepth } if flags.ProtoLegacy && mi.isMessageSet { diff --git a/vendor/google.golang.org/protobuf/internal/impl/validate.go b/vendor/google.golang.org/protobuf/internal/impl/validate.go index 7b2995dde5e..99a1eb95f7c 100644 --- a/vendor/google.golang.org/protobuf/internal/impl/validate.go +++ b/vendor/google.golang.org/protobuf/internal/impl/validate.go @@ -68,9 +68,13 @@ func Validate(mt protoreflect.MessageType, in protoiface.UnmarshalInput) (out pr if in.Resolver == nil { in.Resolver = protoregistry.GlobalTypes } + if in.Depth == 0 { + in.Depth = protowire.DefaultRecursionLimit + } o, st := mi.validate(in.Buf, 0, unmarshalOptions{ flags: in.Flags, resolver: in.Resolver, + depth: in.Depth, }) if o.initialized { out.Flags |= protoiface.UnmarshalInitialized @@ -257,6 +261,9 @@ func (mi *MessageInfo) validate(b []byte, groupTag protowire.Number, opts unmars states[0].typ = validationTypeGroup states[0].endGroup = groupTag } + if opts.depth--; opts.depth < 0 { + return out, ValidationInvalid + } initialized := true start := len(b) State: @@ -451,6 +458,13 @@ State: mi: vi.mi, tail: b, }) + if vi.typ == validationTypeMessage || + vi.typ == validationTypeGroup || + vi.typ == validationTypeMap { + if opts.depth--; opts.depth < 0 { + return out, ValidationInvalid + } + } b = v continue State case validationTypeRepeatedVarint: @@ -499,6 +513,9 @@ State: mi: vi.mi, endGroup: num, }) + if opts.depth--; opts.depth < 0 { + return out, ValidationInvalid + } continue State case flags.ProtoLegacy && vi.typ == validationTypeMessageSetItem: typeid, v, n, err := messageset.ConsumeFieldValue(b, false) @@ -521,6 +538,13 @@ State: mi: xvi.mi, tail: b[n:], }) + if xvi.typ == validationTypeMessage || + xvi.typ == validationTypeGroup || + xvi.typ == validationTypeMap { + if opts.depth--; opts.depth < 0 { + return out, ValidationInvalid + } + } b = v continue State } @@ -547,12 +571,14 @@ State: switch st.typ { case validationTypeMessage, validationTypeGroup: numRequiredFields = int(st.mi.numRequiredFields) + opts.depth++ case validationTypeMap: // If this is a map field with a message value that contains // required fields, require that the value be present. if st.mi != nil && st.mi.numRequiredFields > 0 { numRequiredFields = 1 } + opts.depth++ } // If there are more than 64 required fields, this check will // always fail and we will report that the message is potentially diff --git a/vendor/google.golang.org/protobuf/internal/version/version.go b/vendor/google.golang.org/protobuf/internal/version/version.go index 77de0f238ce..763fd82841c 100644 --- a/vendor/google.golang.org/protobuf/internal/version/version.go +++ b/vendor/google.golang.org/protobuf/internal/version/version.go @@ -52,7 +52,7 @@ import ( const ( Major = 1 Minor = 36 - Patch = 10 + Patch = 11 PreRelease = "" ) diff --git a/vendor/google.golang.org/protobuf/proto/decode.go b/vendor/google.golang.org/protobuf/proto/decode.go index 4cbf1aeaf79..889d8511d27 100644 --- a/vendor/google.golang.org/protobuf/proto/decode.go +++ b/vendor/google.golang.org/protobuf/proto/decode.go @@ -121,9 +121,8 @@ func (o UnmarshalOptions) unmarshal(b []byte, m protoreflect.Message) (out proto out, err = methods.Unmarshal(in) } else { - o.RecursionLimit-- - if o.RecursionLimit < 0 { - return out, errors.New("exceeded max recursion depth") + if o.RecursionLimit--; o.RecursionLimit < 0 { + return out, errRecursionDepth } err = o.unmarshalMessageSlow(b, m) } @@ -220,6 +219,9 @@ func (o UnmarshalOptions) unmarshalSingular(b []byte, wtyp protowire.Type, m pro } func (o UnmarshalOptions) unmarshalMap(b []byte, wtyp protowire.Type, mapv protoreflect.Map, fd protoreflect.FieldDescriptor) (n int, err error) { + if o.RecursionLimit--; o.RecursionLimit < 0 { + return 0, errRecursionDepth + } if wtyp != protowire.BytesType { return 0, errUnknown } @@ -305,3 +307,5 @@ func (o UnmarshalOptions) unmarshalMap(b []byte, wtyp protowire.Type, mapv proto var errUnknown = errors.New("BUG: internal error (unknown)") var errDecode = errors.New("cannot parse invalid wire-format data") + +var errRecursionDepth = errors.New("exceeded maximum recursion depth") diff --git a/vendor/google.golang.org/protobuf/types/descriptorpb/descriptor.pb.go b/vendor/google.golang.org/protobuf/types/descriptorpb/descriptor.pb.go index 4eacb523c33..0b23faa957c 100644 --- a/vendor/google.golang.org/protobuf/types/descriptorpb/descriptor.pb.go +++ b/vendor/google.golang.org/protobuf/types/descriptorpb/descriptor.pb.go @@ -69,6 +69,8 @@ const ( // comparison. Edition_EDITION_2023 Edition = 1000 Edition_EDITION_2024 Edition = 1001 + // A placeholder edition for developing and testing unscheduled features. + Edition_EDITION_UNSTABLE Edition = 9999 // Placeholder editions for testing feature resolution. These should not be // used or relied on outside of tests. Edition_EDITION_1_TEST_ONLY Edition = 1 @@ -91,6 +93,7 @@ var ( 999: "EDITION_PROTO3", 1000: "EDITION_2023", 1001: "EDITION_2024", + 9999: "EDITION_UNSTABLE", 1: "EDITION_1_TEST_ONLY", 2: "EDITION_2_TEST_ONLY", 99997: "EDITION_99997_TEST_ONLY", @@ -105,6 +108,7 @@ var ( "EDITION_PROTO3": 999, "EDITION_2023": 1000, "EDITION_2024": 1001, + "EDITION_UNSTABLE": 9999, "EDITION_1_TEST_ONLY": 1, "EDITION_2_TEST_ONLY": 2, "EDITION_99997_TEST_ONLY": 99997, @@ -4793,11 +4797,11 @@ const file_google_protobuf_descriptor_proto_rawDesc = "" + "\x18EnumValueDescriptorProto\x12\x12\n" + "\x04name\x18\x01 \x01(\tR\x04name\x12\x16\n" + "\x06number\x18\x02 \x01(\x05R\x06number\x12;\n" + - "\aoptions\x18\x03 \x01(\v2!.google.protobuf.EnumValueOptionsR\aoptions\"\xa7\x01\n" + + "\aoptions\x18\x03 \x01(\v2!.google.protobuf.EnumValueOptionsR\aoptions\"\xb5\x01\n" + "\x16ServiceDescriptorProto\x12\x12\n" + "\x04name\x18\x01 \x01(\tR\x04name\x12>\n" + "\x06method\x18\x02 \x03(\v2&.google.protobuf.MethodDescriptorProtoR\x06method\x129\n" + - "\aoptions\x18\x03 \x01(\v2\x1f.google.protobuf.ServiceOptionsR\aoptions\"\x89\x02\n" + + "\aoptions\x18\x03 \x01(\v2\x1f.google.protobuf.ServiceOptionsR\aoptionsJ\x04\b\x04\x10\x05R\x06stream\"\x89\x02\n" + "\x15MethodDescriptorProto\x12\x12\n" + "\x04name\x18\x01 \x01(\tR\x04name\x12\x1d\n" + "\n" + @@ -5033,14 +5037,15 @@ const file_google_protobuf_descriptor_proto_rawDesc = "" + "\bSemantic\x12\b\n" + "\x04NONE\x10\x00\x12\a\n" + "\x03SET\x10\x01\x12\t\n" + - "\x05ALIAS\x10\x02*\xa7\x02\n" + + "\x05ALIAS\x10\x02*\xbe\x02\n" + "\aEdition\x12\x13\n" + "\x0fEDITION_UNKNOWN\x10\x00\x12\x13\n" + "\x0eEDITION_LEGACY\x10\x84\a\x12\x13\n" + "\x0eEDITION_PROTO2\x10\xe6\a\x12\x13\n" + "\x0eEDITION_PROTO3\x10\xe7\a\x12\x11\n" + "\fEDITION_2023\x10\xe8\a\x12\x11\n" + - "\fEDITION_2024\x10\xe9\a\x12\x17\n" + + "\fEDITION_2024\x10\xe9\a\x12\x15\n" + + "\x10EDITION_UNSTABLE\x10\x8fN\x12\x17\n" + "\x13EDITION_1_TEST_ONLY\x10\x01\x12\x17\n" + "\x13EDITION_2_TEST_ONLY\x10\x02\x12\x1d\n" + "\x17EDITION_99997_TEST_ONLY\x10\x9d\x8d\x06\x12\x1d\n" + diff --git a/vendor/google.golang.org/protobuf/types/known/timestamppb/timestamp.pb.go b/vendor/google.golang.org/protobuf/types/known/timestamppb/timestamp.pb.go index 06d584c14be..484c21fd536 100644 --- a/vendor/google.golang.org/protobuf/types/known/timestamppb/timestamp.pb.go +++ b/vendor/google.golang.org/protobuf/types/known/timestamppb/timestamp.pb.go @@ -172,13 +172,14 @@ import ( // ) to obtain a formatter capable of generating timestamps in this format. type Timestamp struct { state protoimpl.MessageState `protogen:"open.v1"` - // Represents seconds of UTC time since Unix epoch - // 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to - // 9999-12-31T23:59:59Z inclusive. + // Represents seconds of UTC time since Unix epoch 1970-01-01T00:00:00Z. Must + // be between -315576000000 and 315576000000 inclusive (which corresponds to + // 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z). Seconds int64 `protobuf:"varint,1,opt,name=seconds,proto3" json:"seconds,omitempty"` - // Non-negative fractions of a second at nanosecond resolution. Negative - // second values with fractions must still have non-negative nanos values - // that count forward in time. Must be from 0 to 999,999,999 + // Non-negative fractions of a second at nanosecond resolution. This field is + // the nanosecond portion of the duration, not an alternative to seconds. + // Negative second values with fractions must still have non-negative nanos + // values that count forward in time. Must be between 0 and 999,999,999 // inclusive. Nanos int32 `protobuf:"varint,2,opt,name=nanos,proto3" json:"nanos,omitempty"` unknownFields protoimpl.UnknownFields diff --git a/vendor/k8s.io/client-go/tools/cache/controller.go b/vendor/k8s.io/client-go/tools/cache/controller.go index 5f983b6b63a..e07c04e6252 100644 --- a/vendor/k8s.io/client-go/tools/cache/controller.go +++ b/vendor/k8s.io/client-go/tools/cache/controller.go @@ -596,16 +596,7 @@ func newInformer(clientState Store, options InformerOptions) Controller { // KeyLister, that way resync operations will result in the correct set // of update/delete deltas. - var fifo Queue - if clientgofeaturegate.FeatureGates().Enabled(clientgofeaturegate.InOrderInformers) { - fifo = NewRealFIFO(MetaNamespaceKeyFunc, clientState, options.Transform) - } else { - fifo = NewDeltaFIFOWithOptions(DeltaFIFOOptions{ - KnownObjects: clientState, - EmitDeltaTypeReplaced: true, - Transformer: options.Transform, - }) - } + fifo := newQueueFIFO(clientState, options.Transform) cfg := &Config{ Queue: fifo, @@ -623,3 +614,15 @@ func newInformer(clientState Store, options InformerOptions) Controller { } return New(cfg) } + +func newQueueFIFO(clientState Store, transform TransformFunc) Queue { + if clientgofeaturegate.FeatureGates().Enabled(clientgofeaturegate.InOrderInformers) { + return NewRealFIFO(MetaNamespaceKeyFunc, clientState, transform) + } else { + return NewDeltaFIFOWithOptions(DeltaFIFOOptions{ + KnownObjects: clientState, + EmitDeltaTypeReplaced: true, + Transformer: transform, + }) + } +} diff --git a/vendor/k8s.io/client-go/tools/cache/delta_fifo.go b/vendor/k8s.io/client-go/tools/cache/delta_fifo.go index 9d9e238ccce..a0d7a834aa0 100644 --- a/vendor/k8s.io/client-go/tools/cache/delta_fifo.go +++ b/vendor/k8s.io/client-go/tools/cache/delta_fifo.go @@ -270,7 +270,8 @@ func NewDeltaFIFOWithOptions(opts DeltaFIFOOptions) *DeltaFIFO { } var ( - _ = Queue(&DeltaFIFO{}) // DeltaFIFO is a Queue + _ = Queue(&DeltaFIFO{}) // DeltaFIFO is a Queue + _ = TransformingStore(&DeltaFIFO{}) // DeltaFIFO implements TransformingStore to allow memory optimizations ) var ( diff --git a/vendor/k8s.io/client-go/tools/cache/reflector.go b/vendor/k8s.io/client-go/tools/cache/reflector.go index ee9be77278a..6fd43375f60 100644 --- a/vendor/k8s.io/client-go/tools/cache/reflector.go +++ b/vendor/k8s.io/client-go/tools/cache/reflector.go @@ -80,7 +80,7 @@ type ReflectorStore interface { // TransformingStore is an optional interface that can be implemented by the provided store. // If implemented on the provided store reflector will use the same transformer in its internal stores. type TransformingStore interface { - Store + ReflectorStore Transformer() TransformFunc } @@ -726,9 +726,11 @@ func (r *Reflector) watchList(ctx context.Context) (watch.Interface, error) { return false } + var transformer TransformFunc storeOpts := []StoreOption{} if tr, ok := r.store.(TransformingStore); ok && tr.Transformer() != nil { - storeOpts = append(storeOpts, WithTransformer(tr.Transformer())) + transformer = tr.Transformer() + storeOpts = append(storeOpts, WithTransformer(transformer)) } initTrace := trace.New("Reflector WatchList", trace.Field{Key: "name", Value: r.name}) @@ -788,7 +790,7 @@ func (r *Reflector) watchList(ctx context.Context) (watch.Interface, error) { // we utilize the temporaryStore to ensure independence from the current store implementation. // as of today, the store is implemented as a queue and will be drained by the higher-level // component as soon as it finishes replacing the content. - checkWatchListDataConsistencyIfRequested(ctx, r.name, resourceVersion, r.listerWatcher.ListWithContext, temporaryStore.List) + checkWatchListDataConsistencyIfRequested(ctx, r.name, resourceVersion, r.listerWatcher.ListWithContext, transformer, temporaryStore.List) if err := r.store.Replace(temporaryStore.List(), resourceVersion); err != nil { return nil, fmt.Errorf("unable to sync watch-list result: %w", err) diff --git a/vendor/k8s.io/client-go/tools/cache/reflector_data_consistency_detector.go b/vendor/k8s.io/client-go/tools/cache/reflector_data_consistency_detector.go index a7e0d9c4368..4119c78a6c0 100644 --- a/vendor/k8s.io/client-go/tools/cache/reflector_data_consistency_detector.go +++ b/vendor/k8s.io/client-go/tools/cache/reflector_data_consistency_detector.go @@ -33,11 +33,11 @@ import ( // // Note that this function will panic when data inconsistency is detected. // This is intentional because we want to catch it in the CI. -func checkWatchListDataConsistencyIfRequested[T runtime.Object, U any](ctx context.Context, identity string, lastSyncedResourceVersion string, listFn consistencydetector.ListFunc[T], retrieveItemsFn consistencydetector.RetrieveItemsFunc[U]) { +func checkWatchListDataConsistencyIfRequested[T runtime.Object, U any](ctx context.Context, identity string, lastSyncedResourceVersion string, listFn consistencydetector.ListFunc[T], listItemTransformFunc func(interface{}) (interface{}, error), retrieveItemsFn consistencydetector.RetrieveItemsFunc[U]) { if !consistencydetector.IsDataConsistencyDetectionForWatchListEnabled() { return } // for informers we pass an empty ListOptions because // listFn might be wrapped for filtering during informer construction. - consistencydetector.CheckDataConsistency(ctx, identity, lastSyncedResourceVersion, listFn, metav1.ListOptions{}, retrieveItemsFn) + consistencydetector.CheckDataConsistency(ctx, identity, lastSyncedResourceVersion, listFn, listItemTransformFunc, metav1.ListOptions{}, retrieveItemsFn) } diff --git a/vendor/k8s.io/client-go/tools/cache/shared_informer.go b/vendor/k8s.io/client-go/tools/cache/shared_informer.go index 99e5fcd1800..1c12aa2d64a 100644 --- a/vendor/k8s.io/client-go/tools/cache/shared_informer.go +++ b/vendor/k8s.io/client-go/tools/cache/shared_informer.go @@ -539,16 +539,7 @@ func (s *sharedIndexInformer) RunWithContext(ctx context.Context) { s.startedLock.Lock() defer s.startedLock.Unlock() - var fifo Queue - if clientgofeaturegate.FeatureGates().Enabled(clientgofeaturegate.InOrderInformers) { - fifo = NewRealFIFO(MetaNamespaceKeyFunc, s.indexer, s.transform) - } else { - fifo = NewDeltaFIFOWithOptions(DeltaFIFOOptions{ - KnownObjects: s.indexer, - EmitDeltaTypeReplaced: true, - Transformer: s.transform, - }) - } + fifo := newQueueFIFO(s.indexer, s.transform) cfg := &Config{ Queue: fifo, diff --git a/vendor/k8s.io/client-go/tools/cache/the_real_fifo.go b/vendor/k8s.io/client-go/tools/cache/the_real_fifo.go index ef322bea850..b907410dc05 100644 --- a/vendor/k8s.io/client-go/tools/cache/the_real_fifo.go +++ b/vendor/k8s.io/client-go/tools/cache/the_real_fifo.go @@ -61,7 +61,8 @@ type RealFIFO struct { } var ( - _ = Queue(&RealFIFO{}) // RealFIFO is a Queue + _ = Queue(&RealFIFO{}) // RealFIFO is a Queue + _ = TransformingStore(&RealFIFO{}) // RealFIFO implements TransformingStore to allow memory optimizations ) // Close the queue. diff --git a/vendor/k8s.io/client-go/util/consistencydetector/data_consistency_detector.go b/vendor/k8s.io/client-go/util/consistencydetector/data_consistency_detector.go index 06f172d82bf..72c0124a0f1 100644 --- a/vendor/k8s.io/client-go/util/consistencydetector/data_consistency_detector.go +++ b/vendor/k8s.io/client-go/util/consistencydetector/data_consistency_detector.go @@ -45,16 +45,28 @@ func IsDataConsistencyDetectionForWatchListEnabled() bool { return dataConsistencyDetectionForWatchListEnabled } +// SetDataConsistencyDetectionForWatchListEnabledForTest allows to enable/disable data consistency detection for testing purposes. +// It returns a function that restores the original value. +func SetDataConsistencyDetectionForWatchListEnabledForTest(enabled bool) func() { + original := dataConsistencyDetectionForWatchListEnabled + dataConsistencyDetectionForWatchListEnabled = enabled + return func() { + dataConsistencyDetectionForWatchListEnabled = original + } +} + type RetrieveItemsFunc[U any] func() []U type ListFunc[T runtime.Object] func(ctx context.Context, options metav1.ListOptions) (T, error) +type TransformFunc func(interface{}) (interface{}, error) + // CheckDataConsistency exists solely for testing purposes. // we cannot use checkWatchListDataConsistencyIfRequested because // it is guarded by an environmental variable. // we cannot manipulate the environmental variable because // it will affect other tests in this package. -func CheckDataConsistency[T runtime.Object, U any](ctx context.Context, identity string, lastSyncedResourceVersion string, listFn ListFunc[T], listOptions metav1.ListOptions, retrieveItemsFn RetrieveItemsFunc[U]) { +func CheckDataConsistency[T runtime.Object, U any](ctx context.Context, identity string, lastSyncedResourceVersion string, listFn ListFunc[T], listItemTransformFunc TransformFunc, listOptions metav1.ListOptions, retrieveItemsFn RetrieveItemsFunc[U]) { if !canFormAdditionalListCall(lastSyncedResourceVersion, listOptions) { klog.V(4).Infof("data consistency check for %s is enabled but the parameters (RV, ListOptions) doesn't allow for creating a valid LIST request. Skipping the data consistency check.", identity) return @@ -84,6 +96,15 @@ func CheckDataConsistency[T runtime.Object, U any](ctx context.Context, identity if err != nil { panic(err) // this should never happen } + if listItemTransformFunc != nil { + for i := range rawListItems { + obj, err := listItemTransformFunc(rawListItems[i]) + if err != nil { + panic(err) + } + rawListItems[i] = obj.(runtime.Object) + } + } listItems := toMetaObjectSliceOrDie(rawListItems) sort.Sort(byUID(listItems)) diff --git a/vendor/modules.txt b/vendor/modules.txt index d15ceb3004f..ec87eea8dcf 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -10,8 +10,8 @@ github.com/alecthomas/units # github.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2 ## explicit; go 1.13 github.com/asaskevich/govalidator -# github.com/aws/aws-sdk-go-v2 v1.39.2 -## explicit; go 1.22 +# github.com/aws/aws-sdk-go-v2 v1.41.0 +## explicit; go 1.23 github.com/aws/aws-sdk-go-v2/aws github.com/aws/aws-sdk-go-v2/aws/defaults github.com/aws/aws-sdk-go-v2/aws/middleware @@ -36,54 +36,60 @@ github.com/aws/aws-sdk-go-v2/internal/shareddefaults github.com/aws/aws-sdk-go-v2/internal/strings github.com/aws/aws-sdk-go-v2/internal/sync/singleflight github.com/aws/aws-sdk-go-v2/internal/timeconv -# github.com/aws/aws-sdk-go-v2/config v1.31.12 -## explicit; go 1.22 +# github.com/aws/aws-sdk-go-v2/config v1.32.6 +## explicit; go 1.23 github.com/aws/aws-sdk-go-v2/config -# github.com/aws/aws-sdk-go-v2/credentials v1.18.16 -## explicit; go 1.22 +# github.com/aws/aws-sdk-go-v2/credentials v1.19.6 +## explicit; go 1.23 github.com/aws/aws-sdk-go-v2/credentials github.com/aws/aws-sdk-go-v2/credentials/ec2rolecreds github.com/aws/aws-sdk-go-v2/credentials/endpointcreds github.com/aws/aws-sdk-go-v2/credentials/endpointcreds/internal/client +github.com/aws/aws-sdk-go-v2/credentials/logincreds github.com/aws/aws-sdk-go-v2/credentials/processcreds github.com/aws/aws-sdk-go-v2/credentials/ssocreds github.com/aws/aws-sdk-go-v2/credentials/stscreds -# github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.18.9 -## explicit; go 1.22 +# github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.18.16 +## explicit; go 1.23 github.com/aws/aws-sdk-go-v2/feature/ec2/imds github.com/aws/aws-sdk-go-v2/feature/ec2/imds/internal/config -# github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.9 -## explicit; go 1.22 +# github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.16 +## explicit; go 1.23 github.com/aws/aws-sdk-go-v2/internal/configsources -# github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.9 -## explicit; go 1.22 +# github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.16 +## explicit; go 1.23 github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 -# github.com/aws/aws-sdk-go-v2/internal/ini v1.8.3 -## explicit; go 1.22 +# github.com/aws/aws-sdk-go-v2/internal/ini v1.8.4 +## explicit; go 1.23 github.com/aws/aws-sdk-go-v2/internal/ini -# github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.1 -## explicit; go 1.22 +# github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.4 +## explicit; go 1.23 github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding -# github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.9 -## explicit; go 1.22 +# github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.16 +## explicit; go 1.23 github.com/aws/aws-sdk-go-v2/service/internal/presigned-url -# github.com/aws/aws-sdk-go-v2/service/sso v1.29.6 -## explicit; go 1.22 +# github.com/aws/aws-sdk-go-v2/service/signin v1.0.4 +## explicit; go 1.23 +github.com/aws/aws-sdk-go-v2/service/signin +github.com/aws/aws-sdk-go-v2/service/signin/internal/endpoints +github.com/aws/aws-sdk-go-v2/service/signin/types +# github.com/aws/aws-sdk-go-v2/service/sso v1.30.8 +## explicit; go 1.23 github.com/aws/aws-sdk-go-v2/service/sso github.com/aws/aws-sdk-go-v2/service/sso/internal/endpoints github.com/aws/aws-sdk-go-v2/service/sso/types -# github.com/aws/aws-sdk-go-v2/service/ssooidc v1.35.1 -## explicit; go 1.22 +# github.com/aws/aws-sdk-go-v2/service/ssooidc v1.35.12 +## explicit; go 1.23 github.com/aws/aws-sdk-go-v2/service/ssooidc github.com/aws/aws-sdk-go-v2/service/ssooidc/internal/endpoints github.com/aws/aws-sdk-go-v2/service/ssooidc/types -# github.com/aws/aws-sdk-go-v2/service/sts v1.38.6 -## explicit; go 1.22 +# github.com/aws/aws-sdk-go-v2/service/sts v1.41.5 +## explicit; go 1.23 github.com/aws/aws-sdk-go-v2/service/sts github.com/aws/aws-sdk-go-v2/service/sts/internal/endpoints github.com/aws/aws-sdk-go-v2/service/sts/types -# github.com/aws/smithy-go v1.23.0 -## explicit; go 1.22 +# github.com/aws/smithy-go v1.24.0 +## explicit; go 1.23 github.com/aws/smithy-go github.com/aws/smithy-go/auth github.com/aws/smithy-go/auth/bearer @@ -94,6 +100,7 @@ github.com/aws/smithy-go/encoding/httpbinding github.com/aws/smithy-go/encoding/json github.com/aws/smithy-go/encoding/xml github.com/aws/smithy-go/endpoints +github.com/aws/smithy-go/endpoints/private/rulesfn github.com/aws/smithy-go/internal/sync/singleflight github.com/aws/smithy-go/io github.com/aws/smithy-go/logging @@ -165,7 +172,7 @@ github.com/go-logr/logr/funcr # github.com/go-logr/stdr v1.2.2 ## explicit; go 1.16 github.com/go-logr/stdr -# github.com/go-openapi/analysis v0.24.0 +# github.com/go-openapi/analysis v0.24.1 ## explicit; go 1.24.0 github.com/go-openapi/analysis github.com/go-openapi/analysis/internal/debug @@ -174,20 +181,20 @@ github.com/go-openapi/analysis/internal/flatten/operations github.com/go-openapi/analysis/internal/flatten/replace github.com/go-openapi/analysis/internal/flatten/schutils github.com/go-openapi/analysis/internal/flatten/sortref -# github.com/go-openapi/errors v0.22.3 +# github.com/go-openapi/errors v0.22.4 ## explicit; go 1.24.0 github.com/go-openapi/errors # github.com/go-openapi/jsonpointer v0.22.1 ## explicit; go 1.24.0 github.com/go-openapi/jsonpointer -# github.com/go-openapi/jsonreference v0.21.2 +# github.com/go-openapi/jsonreference v0.21.3 ## explicit; go 1.24.0 github.com/go-openapi/jsonreference github.com/go-openapi/jsonreference/internal -# github.com/go-openapi/loads v0.23.1 +# github.com/go-openapi/loads v0.23.2 ## explicit; go 1.24.0 github.com/go-openapi/loads -# github.com/go-openapi/runtime v0.29.0 +# github.com/go-openapi/runtime v0.29.2 ## explicit; go 1.24.0 github.com/go-openapi/runtime github.com/go-openapi/runtime/client @@ -198,52 +205,52 @@ github.com/go-openapi/runtime/middleware/header github.com/go-openapi/runtime/middleware/untyped github.com/go-openapi/runtime/security github.com/go-openapi/runtime/yamlpc -# github.com/go-openapi/spec v0.22.0 +# github.com/go-openapi/spec v0.22.1 ## explicit; go 1.24.0 github.com/go-openapi/spec -# github.com/go-openapi/strfmt v0.24.0 +# github.com/go-openapi/strfmt v0.25.0 ## explicit; go 1.24.0 github.com/go-openapi/strfmt -# github.com/go-openapi/swag v0.25.1 +# github.com/go-openapi/swag v0.25.4 ## explicit; go 1.24.0 github.com/go-openapi/swag -# github.com/go-openapi/swag/cmdutils v0.25.1 +# github.com/go-openapi/swag/cmdutils v0.25.4 ## explicit; go 1.24.0 github.com/go-openapi/swag/cmdutils -# github.com/go-openapi/swag/conv v0.25.1 +# github.com/go-openapi/swag/conv v0.25.4 ## explicit; go 1.24.0 github.com/go-openapi/swag/conv -# github.com/go-openapi/swag/fileutils v0.25.1 +# github.com/go-openapi/swag/fileutils v0.25.4 ## explicit; go 1.24.0 github.com/go-openapi/swag/fileutils -# github.com/go-openapi/swag/jsonname v0.25.1 +# github.com/go-openapi/swag/jsonname v0.25.4 ## explicit; go 1.24.0 github.com/go-openapi/swag/jsonname -# github.com/go-openapi/swag/jsonutils v0.25.1 +# github.com/go-openapi/swag/jsonutils v0.25.4 ## explicit; go 1.24.0 github.com/go-openapi/swag/jsonutils github.com/go-openapi/swag/jsonutils/adapters github.com/go-openapi/swag/jsonutils/adapters/ifaces github.com/go-openapi/swag/jsonutils/adapters/stdlib/json -# github.com/go-openapi/swag/loading v0.25.1 +# github.com/go-openapi/swag/loading v0.25.4 ## explicit; go 1.24.0 github.com/go-openapi/swag/loading -# github.com/go-openapi/swag/mangling v0.25.1 +# github.com/go-openapi/swag/mangling v0.25.4 ## explicit; go 1.24.0 github.com/go-openapi/swag/mangling -# github.com/go-openapi/swag/netutils v0.25.1 +# github.com/go-openapi/swag/netutils v0.25.4 ## explicit; go 1.24.0 github.com/go-openapi/swag/netutils -# github.com/go-openapi/swag/stringutils v0.25.1 +# github.com/go-openapi/swag/stringutils v0.25.4 ## explicit; go 1.24.0 github.com/go-openapi/swag/stringutils -# github.com/go-openapi/swag/typeutils v0.25.1 +# github.com/go-openapi/swag/typeutils v0.25.4 ## explicit; go 1.24.0 github.com/go-openapi/swag/typeutils -# github.com/go-openapi/swag/yamlutils v0.25.1 +# github.com/go-openapi/swag/yamlutils v0.25.4 ## explicit; go 1.24.0 github.com/go-openapi/swag/yamlutils -# github.com/go-openapi/validate v0.25.0 +# github.com/go-openapi/validate v0.25.1 ## explicit; go 1.24.0 github.com/go-openapi/validate # github.com/go-test/deep v1.1.1 @@ -361,13 +368,13 @@ github.com/pmezard/go-difflib/difflib # github.com/prometheus-community/prom-label-proxy v0.12.1 ## explicit; go 1.23.0 github.com/prometheus-community/prom-label-proxy/injectproxy -# github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring v0.87.1 => ./pkg/apis/monitoring +# github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring v0.88.0 => ./pkg/apis/monitoring ## explicit; go 1.24.0 github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1 github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1alpha1 github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1beta1 -# github.com/prometheus-operator/prometheus-operator/pkg/client v0.87.1 => ./pkg/client +# github.com/prometheus-operator/prometheus-operator/pkg/client v0.88.0 => ./pkg/client ## explicit; go 1.24.0 github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration github.com/prometheus-operator/prometheus-operator/pkg/client/applyconfiguration/internal @@ -392,7 +399,7 @@ github.com/prometheus-operator/prometheus-operator/pkg/client/versioned/typed/mo github.com/prometheus-operator/prometheus-operator/pkg/client/versioned/typed/monitoring/v1alpha1/fake github.com/prometheus-operator/prometheus-operator/pkg/client/versioned/typed/monitoring/v1beta1 github.com/prometheus-operator/prometheus-operator/pkg/client/versioned/typed/monitoring/v1beta1/fake -# github.com/prometheus/alertmanager v0.29.0 +# github.com/prometheus/alertmanager v0.30.0 ## explicit; go 1.24.0 github.com/prometheus/alertmanager/api/v2/client github.com/prometheus/alertmanager/api/v2/client/alert @@ -421,7 +428,7 @@ github.com/prometheus/client_golang/prometheus/promhttp/internal # github.com/prometheus/client_model v0.6.2 ## explicit; go 1.22.0 github.com/prometheus/client_model/go -# github.com/prometheus/common v0.67.3 +# github.com/prometheus/common v0.67.5 ## explicit; go 1.24.0 github.com/prometheus/common/config github.com/prometheus/common/expfmt @@ -429,7 +436,7 @@ github.com/prometheus/common/helpers/templates github.com/prometheus/common/model github.com/prometheus/common/promslog github.com/prometheus/common/version -# github.com/prometheus/exporter-toolkit v0.15.0 +# github.com/prometheus/exporter-toolkit v0.15.1 ## explicit; go 1.24.0 github.com/prometheus/exporter-toolkit/web # github.com/prometheus/procfs v0.17.0 @@ -437,8 +444,8 @@ github.com/prometheus/exporter-toolkit/web github.com/prometheus/procfs github.com/prometheus/procfs/internal/fs github.com/prometheus/procfs/internal/util -# github.com/prometheus/prometheus v0.307.3 -## explicit; go 1.24.0 +# github.com/prometheus/prometheus v0.309.1 +## explicit; go 1.24.9 github.com/prometheus/prometheus/model/exemplar github.com/prometheus/prometheus/model/histogram github.com/prometheus/prometheus/model/labels @@ -462,13 +469,14 @@ github.com/prometheus/prometheus/tsdb/fileutil github.com/prometheus/prometheus/util/almost github.com/prometheus/prometheus/util/annotations github.com/prometheus/prometheus/util/convertnhcb +github.com/prometheus/prometheus/util/features github.com/prometheus/prometheus/util/logging github.com/prometheus/prometheus/util/namevalidationutil github.com/prometheus/prometheus/util/stats github.com/prometheus/prometheus/util/strutil github.com/prometheus/prometheus/util/zeropool -# github.com/prometheus/sigv4 v0.2.1 -## explicit; go 1.23.0 +# github.com/prometheus/sigv4 v0.3.0 +## explicit; go 1.24.0 github.com/prometheus/sigv4 # github.com/spf13/cobra v1.10.1 ## explicit; go 1.15 @@ -481,8 +489,8 @@ github.com/spf13/pflag github.com/stretchr/testify/assert github.com/stretchr/testify/assert/yaml github.com/stretchr/testify/require -# github.com/thanos-io/thanos v0.39.2 -## explicit; go 1.24.0 +# github.com/thanos-io/thanos v0.40.1 +## explicit; go 1.25.0 github.com/thanos-io/thanos/pkg/errutil github.com/thanos-io/thanos/pkg/reloader github.com/thanos-io/thanos/pkg/runutil @@ -492,7 +500,7 @@ github.com/x448/float16 # github.com/xhit/go-str2duration/v2 v2.1.0 ## explicit; go 1.13 github.com/xhit/go-str2duration/v2 -# go.mongodb.org/mongo-driver v1.17.4 +# go.mongodb.org/mongo-driver v1.17.6 ## explicit; go 1.18 go.mongodb.org/mongo-driver/bson go.mongodb.org/mongo-driver/bson/bsoncodec @@ -505,23 +513,24 @@ go.mongodb.org/mongo-driver/x/bsonx/bsoncore ## explicit; go 1.24.0 go.opentelemetry.io/auto/sdk go.opentelemetry.io/auto/sdk/internal/telemetry -# go.opentelemetry.io/otel v1.38.0 -## explicit; go 1.23.0 +# go.opentelemetry.io/otel v1.39.0 +## explicit; go 1.24.0 go.opentelemetry.io/otel go.opentelemetry.io/otel/attribute go.opentelemetry.io/otel/attribute/internal +go.opentelemetry.io/otel/attribute/internal/xxhash go.opentelemetry.io/otel/baggage go.opentelemetry.io/otel/codes go.opentelemetry.io/otel/internal/baggage go.opentelemetry.io/otel/internal/global go.opentelemetry.io/otel/propagation go.opentelemetry.io/otel/semconv/v1.37.0 -# go.opentelemetry.io/otel/metric v1.38.0 -## explicit; go 1.23.0 +# go.opentelemetry.io/otel/metric v1.39.0 +## explicit; go 1.24.0 go.opentelemetry.io/otel/metric go.opentelemetry.io/otel/metric/embedded -# go.opentelemetry.io/otel/trace v1.38.0 -## explicit; go 1.23.0 +# go.opentelemetry.io/otel/trace v1.39.0 +## explicit; go 1.24.0 go.opentelemetry.io/otel/trace go.opentelemetry.io/otel/trace/embedded go.opentelemetry.io/otel/trace/internal/telemetry @@ -540,13 +549,13 @@ go.yaml.in/yaml/v2 # go.yaml.in/yaml/v3 v3.0.4 ## explicit; go 1.16 go.yaml.in/yaml/v3 -# golang.org/x/crypto v0.44.0 +# golang.org/x/crypto v0.46.0 ## explicit; go 1.24.0 golang.org/x/crypto/bcrypt golang.org/x/crypto/blowfish # golang.org/x/exp v0.0.0-20251002181428-27f1f14c8bb9 ## explicit; go 1.24.0 -# golang.org/x/net v0.47.0 +# golang.org/x/net v0.48.0 ## explicit; go 1.24.0 golang.org/x/net/bpf golang.org/x/net/html @@ -562,23 +571,23 @@ golang.org/x/net/internal/timeseries golang.org/x/net/proxy golang.org/x/net/trace golang.org/x/net/websocket -# golang.org/x/oauth2 v0.32.0 +# golang.org/x/oauth2 v0.34.0 ## explicit; go 1.24.0 golang.org/x/oauth2 golang.org/x/oauth2/clientcredentials golang.org/x/oauth2/internal -# golang.org/x/sync v0.18.0 +# golang.org/x/sync v0.19.0 ## explicit; go 1.24.0 golang.org/x/sync/errgroup -# golang.org/x/sys v0.38.0 +# golang.org/x/sys v0.39.0 ## explicit; go 1.24.0 golang.org/x/sys/plan9 golang.org/x/sys/unix golang.org/x/sys/windows -# golang.org/x/term v0.37.0 +# golang.org/x/term v0.38.0 ## explicit; go 1.24.0 golang.org/x/term -# golang.org/x/text v0.31.0 +# golang.org/x/text v0.32.0 ## explicit; go 1.24.0 golang.org/x/text/cases golang.org/x/text/internal @@ -590,14 +599,10 @@ golang.org/x/text/secure/bidirule golang.org/x/text/transform golang.org/x/text/unicode/bidi golang.org/x/text/unicode/norm -# golang.org/x/time v0.13.0 +# golang.org/x/time v0.14.0 ## explicit; go 1.24.0 golang.org/x/time/rate -# google.golang.org/genproto/googleapis/rpc v0.0.0-20251006185510-65f7160b3a87 -## explicit; go 1.24.0 -# google.golang.org/grpc v1.76.0 -## explicit; go 1.24.0 -# google.golang.org/protobuf v1.36.10 +# google.golang.org/protobuf v1.36.11 ## explicit; go 1.23 google.golang.org/protobuf/encoding/protodelim google.golang.org/protobuf/encoding/prototext @@ -651,7 +656,7 @@ gotest.tools/v3/internal/assert gotest.tools/v3/internal/difflib gotest.tools/v3/internal/format gotest.tools/v3/internal/source -# k8s.io/api v0.34.2 +# k8s.io/api v0.34.3 ## explicit; go 1.24.0 k8s.io/api/admission/v1 k8s.io/api/admissionregistration/v1 @@ -712,7 +717,7 @@ k8s.io/api/storage/v1 k8s.io/api/storage/v1alpha1 k8s.io/api/storage/v1beta1 k8s.io/api/storagemigration/v1alpha1 -# k8s.io/apiextensions-apiserver v0.34.2 +# k8s.io/apiextensions-apiserver v0.34.3 ## explicit; go 1.24.0 k8s.io/apiextensions-apiserver/pkg/apis/apiextensions k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1 @@ -723,7 +728,7 @@ k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset/scheme k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset/typed/apiextensions/v1 k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset/typed/apiextensions/v1beta1 -# k8s.io/apimachinery v0.34.2 +# k8s.io/apimachinery v0.34.3 ## explicit; go 1.24.0 k8s.io/apimachinery/pkg/api/equality k8s.io/apimachinery/pkg/api/errors @@ -790,11 +795,11 @@ k8s.io/apimachinery/pkg/watch k8s.io/apimachinery/third_party/forked/golang/json k8s.io/apimachinery/third_party/forked/golang/netutil k8s.io/apimachinery/third_party/forked/golang/reflect -# k8s.io/apiserver v0.34.2 +# k8s.io/apiserver v0.34.3 ## explicit; go 1.24.0 k8s.io/apiserver/pkg/server/dynamiccertificates k8s.io/apiserver/pkg/storage/names -# k8s.io/client-go v0.34.2 +# k8s.io/client-go v0.34.3 ## explicit; go 1.24.0 k8s.io/client-go/applyconfigurations k8s.io/client-go/applyconfigurations/admissionregistration/v1 @@ -1137,7 +1142,7 @@ k8s.io/client-go/util/homedir k8s.io/client-go/util/keyutil k8s.io/client-go/util/retry k8s.io/client-go/util/workqueue -# k8s.io/component-base v0.34.2 +# k8s.io/component-base v0.34.3 ## explicit; go 1.24.0 k8s.io/component-base/cli/flag # k8s.io/klog/v2 v2.130.1