From 169071f33a35a5c6d932fdf47b49e6d411fdd389 Mon Sep 17 00:00:00 2001 From: Bella Khizgiyaev Date: Thu, 6 Jun 2024 11:46:11 +0300 Subject: [PATCH 1/7] Add recording rules for forklift metrics Signed-off-by: Bella Khizgiyaev --- pkg/monitoring/rules/BUILD.bazel | 13 +++++ .../rules/recordingrules/BUILD.bazel | 17 +++++++ .../rules/recordingrules/migration.go | 18 +++++++ pkg/monitoring/rules/recordingrules/plan.go | 18 +++++++ .../rules/recordingrules/recording-rules.go | 10 ++++ pkg/monitoring/rules/rules.go | 51 +++++++++++++++++++ 6 files changed, 127 insertions(+) create mode 100644 pkg/monitoring/rules/BUILD.bazel create mode 100644 pkg/monitoring/rules/recordingrules/BUILD.bazel create mode 100644 pkg/monitoring/rules/recordingrules/migration.go create mode 100644 pkg/monitoring/rules/recordingrules/plan.go create mode 100644 pkg/monitoring/rules/recordingrules/recording-rules.go create mode 100644 pkg/monitoring/rules/rules.go diff --git a/pkg/monitoring/rules/BUILD.bazel b/pkg/monitoring/rules/BUILD.bazel new file mode 100644 index 000000000..6e02ab99a --- /dev/null +++ b/pkg/monitoring/rules/BUILD.bazel @@ -0,0 +1,13 @@ +load("@io_bazel_rules_go//go:def.bzl", "go_library") + +go_library( + name = "rules", + srcs = ["rules.go"], + importpath = "github.com/konveyor/forklift-controller/pkg/monitoring/rules", + visibility = ["//visibility:public"], + deps = [ + "//pkg/monitoring/rules/recordingrules", + "@com_github_machadovilaca_operator_observability//pkg/operatorrules:go_default_library", + "@com_github_prometheus_operator_prometheus_operator_pkg_apis_monitoring//v1:go_default_library", + ], +) diff --git a/pkg/monitoring/rules/recordingrules/BUILD.bazel b/pkg/monitoring/rules/recordingrules/BUILD.bazel new file mode 100644 index 000000000..eb0a7cf3f --- /dev/null +++ b/pkg/monitoring/rules/recordingrules/BUILD.bazel @@ -0,0 +1,17 @@ +load("@io_bazel_rules_go//go:def.bzl", "go_library") + +go_library( + name = "recordingrules", + srcs = [ + "migration.go", + "plan.go", + "recording-rules.go", + ], + importpath = "github.com/konveyor/forklift-controller/pkg/monitoring/rules/recordingrules", + visibility = ["//visibility:public"], + deps = [ + "//vendor/k8s.io/apimachinery/pkg/util/intstr", + "@com_github_machadovilaca_operator_observability//pkg/operatormetrics:go_default_library", + "@com_github_machadovilaca_operator_observability//pkg/operatorrules:go_default_library", + ], +) diff --git a/pkg/monitoring/rules/recordingrules/migration.go b/pkg/monitoring/rules/recordingrules/migration.go new file mode 100644 index 000000000..e06a2acd7 --- /dev/null +++ b/pkg/monitoring/rules/recordingrules/migration.go @@ -0,0 +1,18 @@ +package recordingrules + +import ( + "github.com/machadovilaca/operator-observability/pkg/operatormetrics" + "github.com/machadovilaca/operator-observability/pkg/operatorrules" + "k8s.io/apimachinery/pkg/util/intstr" +) + +var migrationsRecordingRules = []operatorrules.RecordingRule{ + { + MetricsOpts: operatormetrics.MetricOpts{ + Name: "mtv_plans_status", + Help: "The number of allocatable nodes in the cluster.", + }, + MetricType: operatormetrics.GaugeType, + Expr: intstr.FromString("count(count (mtv_workload_migrations) by (status))"), + }, +} diff --git a/pkg/monitoring/rules/recordingrules/plan.go b/pkg/monitoring/rules/recordingrules/plan.go new file mode 100644 index 000000000..23e3cc31c --- /dev/null +++ b/pkg/monitoring/rules/recordingrules/plan.go @@ -0,0 +1,18 @@ +package recordingrules + +import ( + "github.com/machadovilaca/operator-observability/pkg/operatormetrics" + "github.com/machadovilaca/operator-observability/pkg/operatorrules" + "k8s.io/apimachinery/pkg/util/intstr" +) + +var plansRecordingRules = []operatorrules.RecordingRule{ + { + MetricsOpts: operatormetrics.MetricOpts{ + Name: "forklift_plans_status", + Help: "The number of succsesfull plans.", + }, + MetricType: operatormetrics.GaugeType, + Expr: intstr.FromString("count(count (forklift_plans_status) by (node))"), + }, +} diff --git a/pkg/monitoring/rules/recordingrules/recording-rules.go b/pkg/monitoring/rules/recordingrules/recording-rules.go new file mode 100644 index 000000000..bf73be3bf --- /dev/null +++ b/pkg/monitoring/rules/recordingrules/recording-rules.go @@ -0,0 +1,10 @@ +package recordingrules + +import "github.com/machadovilaca/operator-observability/pkg/operatorrules" + +func Register(namespace string) error { + return operatorrules.RegisterRecordingRules( + migrationsRecordingRules, + plansRecordingRules, + ) +} diff --git a/pkg/monitoring/rules/rules.go b/pkg/monitoring/rules/rules.go new file mode 100644 index 000000000..d74349884 --- /dev/null +++ b/pkg/monitoring/rules/rules.go @@ -0,0 +1,51 @@ +package rules + +import ( + "github.com/machadovilaca/operator-observability/pkg/operatorrules" + promv1 "github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1" + + "github.com/konveyor/forklift-controller/pkg/monitoring/rules/recordingrules" +) + +const ( + forkliftPrometheusRuleName = "prometheus-forklift-rules" + + prometheusLabelKey = "prometheus.forklift.io" + prometheusLabelValue = "true" + + k8sAppLabelKey = "k8s-app" + forkliftLabelValue = "forklift" +) + +func SetupRules(namespace string) error { + err := recordingrules.Register(namespace) + if err != nil { + return err + } + + return nil +} + +func BuildPrometheusRule(namespace string) (*promv1.PrometheusRule, error) { + rules, err := operatorrules.BuildPrometheusRule( + forkliftPrometheusRuleName, + namespace, + map[string]string{ + prometheusLabelKey: prometheusLabelValue, + k8sAppLabelKey: forkliftLabelValue, + }, + ) + if err != nil { + return nil, err + } + + return rules, nil +} + +func ListRecordingRules() []operatorrules.RecordingRule { + return operatorrules.ListRecordingRules() +} + +func ListAlerts() []promv1.Rule { + return operatorrules.ListAlerts() +} From beb54f1eb4d6dff783f4b725d2faaa2cdc23ec79 Mon Sep 17 00:00:00 2001 From: Bella Khizgiyaev Date: Sun, 9 Jun 2024 15:38:41 +0300 Subject: [PATCH 2/7] Add dependenies for telemetry rules Signed-off-by: Bella Khizgiyaev --- go.mod | 4 +- go.sum | 10 +- pkg/monitoring/rules/BUILD.bazel | 4 +- .../rules/recordingrules/BUILD.bazel | 4 +- .../operator-observability/LICENSE | 201 ++ .../pkg/operatormetrics/BUILD.bazel | 23 + .../pkg/operatormetrics/collector.go | 99 + .../pkg/operatormetrics/counter.go | 36 + .../pkg/operatormetrics/counter_vec.go | 38 + .../pkg/operatormetrics/gauge.go | 36 + .../pkg/operatormetrics/gauge_vec.go | 38 + .../pkg/operatormetrics/histogram.go | 51 + .../pkg/operatormetrics/histogram_vec.go | 42 + .../pkg/operatormetrics/metric.go | 42 + .../pkg/operatormetrics/registry.go | 14 + .../pkg/operatormetrics/summary.go | 51 + .../pkg/operatormetrics/summary_vec.go | 42 + .../pkg/operatormetrics/wrapper_registry.go | 166 + .../pkg/operatorrules/BUILD.bazel | 23 + .../pkg/operatorrules/prometheusrules.go | 76 + .../pkg/operatorrules/rbac.go | 45 + .../pkg/operatorrules/recordingrule.go | 24 + .../pkg/operatorrules/registry.go | 82 + .../pkg/operatorrules/schema.go | 22 + .../pkg/apis/monitoring/BUILD.bazel | 12 + .../pkg/apis/monitoring/LICENSE | 202 ++ .../pkg/apis/monitoring/register.go | 19 + .../pkg/apis/monitoring/resource.go | 60 + .../pkg/apis/monitoring/v1/BUILD.bazel | 30 + .../apis/monitoring/v1/alertmanager_types.go | 442 +++ .../pkg/apis/monitoring/v1/doc.go | 18 + .../apis/monitoring/v1/podmonitor_types.go | 167 + .../pkg/apis/monitoring/v1/probe_types.go | 213 ++ .../apis/monitoring/v1/prometheus_types.go | 1602 +++++++++ .../monitoring/v1/prometheusrule_types.go | 121 + .../pkg/apis/monitoring/v1/register.go | 67 + .../monitoring/v1/servicemonitor_types.go | 111 + .../pkg/apis/monitoring/v1/thanos_types.go | 294 ++ .../pkg/apis/monitoring/v1/types.go | 633 ++++ .../monitoring/v1/zz_generated.deepcopy.go | 3125 +++++++++++++++++ vendor/modules.txt | 10 +- 41 files changed, 8291 insertions(+), 8 deletions(-) create mode 100644 vendor/github.com/machadovilaca/operator-observability/LICENSE create mode 100644 vendor/github.com/machadovilaca/operator-observability/pkg/operatormetrics/BUILD.bazel create mode 100644 vendor/github.com/machadovilaca/operator-observability/pkg/operatormetrics/collector.go create mode 100644 vendor/github.com/machadovilaca/operator-observability/pkg/operatormetrics/counter.go create mode 100644 vendor/github.com/machadovilaca/operator-observability/pkg/operatormetrics/counter_vec.go create mode 100644 vendor/github.com/machadovilaca/operator-observability/pkg/operatormetrics/gauge.go create mode 100644 vendor/github.com/machadovilaca/operator-observability/pkg/operatormetrics/gauge_vec.go create mode 100644 vendor/github.com/machadovilaca/operator-observability/pkg/operatormetrics/histogram.go create mode 100644 vendor/github.com/machadovilaca/operator-observability/pkg/operatormetrics/histogram_vec.go create mode 100644 vendor/github.com/machadovilaca/operator-observability/pkg/operatormetrics/metric.go create mode 100644 vendor/github.com/machadovilaca/operator-observability/pkg/operatormetrics/registry.go create mode 100644 vendor/github.com/machadovilaca/operator-observability/pkg/operatormetrics/summary.go create mode 100644 vendor/github.com/machadovilaca/operator-observability/pkg/operatormetrics/summary_vec.go create mode 100644 vendor/github.com/machadovilaca/operator-observability/pkg/operatormetrics/wrapper_registry.go create mode 100644 vendor/github.com/machadovilaca/operator-observability/pkg/operatorrules/BUILD.bazel create mode 100644 vendor/github.com/machadovilaca/operator-observability/pkg/operatorrules/prometheusrules.go create mode 100644 vendor/github.com/machadovilaca/operator-observability/pkg/operatorrules/rbac.go create mode 100644 vendor/github.com/machadovilaca/operator-observability/pkg/operatorrules/recordingrule.go create mode 100644 vendor/github.com/machadovilaca/operator-observability/pkg/operatorrules/registry.go create mode 100644 vendor/github.com/machadovilaca/operator-observability/pkg/operatorrules/schema.go create mode 100644 vendor/github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/BUILD.bazel create mode 100644 vendor/github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/LICENSE create mode 100644 vendor/github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/register.go create mode 100644 vendor/github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/resource.go create mode 100644 vendor/github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1/BUILD.bazel create mode 100644 vendor/github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1/alertmanager_types.go create mode 100644 vendor/github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1/doc.go create mode 100644 vendor/github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1/podmonitor_types.go create mode 100644 vendor/github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1/probe_types.go create mode 100644 vendor/github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1/prometheus_types.go create mode 100644 vendor/github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1/prometheusrule_types.go create mode 100644 vendor/github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1/register.go create mode 100644 vendor/github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1/servicemonitor_types.go create mode 100644 vendor/github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1/thanos_types.go create mode 100644 vendor/github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1/types.go create mode 100644 vendor/github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1/zz_generated.deepcopy.go diff --git a/go.mod b/go.mod index ada738aae..55ef8f481 100644 --- a/go.mod +++ b/go.mod @@ -12,6 +12,7 @@ require ( github.com/gophercloud/utils v0.0.0-20230418172808-6eab72e966e1 github.com/gorilla/websocket v1.5.1 github.com/k8snetworkplumbingwg/network-attachment-definition-client v1.4.0 + github.com/machadovilaca/operator-observability v0.0.20 github.com/mattn/go-sqlite3 v1.14.18 github.com/onsi/ginkgo v1.16.5 github.com/onsi/ginkgo/v2 v2.13.2 @@ -21,6 +22,7 @@ require ( github.com/ovirt/go-ovirt v0.0.0-20230808190322-9fd1992199b2 github.com/pkg/errors v0.9.1 github.com/pkg/profile v1.7.0 + github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring v0.68.0 github.com/prometheus/client_golang v1.17.0 github.com/prometheus/client_model v0.5.0 github.com/prometheus/common v0.45.0 @@ -49,7 +51,7 @@ require ( github.com/bytedance/sonic v1.9.1 // indirect github.com/cespare/xxhash/v2 v2.2.0 // indirect github.com/chenzhuoyu/base64x v0.0.0-20221115062448-fe3a3abad311 // indirect - github.com/davecgh/go-spew v1.1.1 // indirect + github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect github.com/emicklei/go-restful/v3 v3.11.0 // indirect github.com/evanphx/json-patch v5.6.0+incompatible // indirect github.com/evanphx/json-patch/v5 v5.6.0 // indirect diff --git a/go.sum b/go.sum index 24abff205..c5972e09b 100644 --- a/go.sum +++ b/go.sum @@ -26,8 +26,9 @@ github.com/chzyer/test v0.0.0-20180213035817-a1ea475d72b1/go.mod h1:Q3SI9o4m/ZMn github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw= github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM= +github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/docopt/docopt-go v0.0.0-20180111231733-ee0de3bc6815/go.mod h1:WwZ+bS3ebgob9U8Nd0kOddGdZWjyMGR8Wziv+TBNwSE= github.com/elazarl/goproxy v0.0.0-20180725130230-947c36da3153/go.mod h1:/Zj4wYkgs4iZTTu3o/KG3Itv/qCCa8VVMlb3i9OVuzc= github.com/emicklei/go-restful v0.0.0-20170410110728-ff4f55a20633/go.mod h1:otzb+WCGbkyDHkqmQmT5YD2WR4BBwUdeQoFo8l/7tVs= @@ -181,6 +182,8 @@ github.com/kubev2v/gophercloud v0.0.0-20230629135522-9d701a75c760/go.mod h1:aAVq github.com/leodido/go-urn v1.1.0/go.mod h1:+cyI34gQWZcE1eQU7NVgKkkzdXDQHr1dBMtdAPozLkw= github.com/leodido/go-urn v1.2.4 h1:XlAE/cm/ms7TE/VMVoduSpNBoyc2dOxHs5MZSwAN63Q= github.com/leodido/go-urn v1.2.4/go.mod h1:7ZrI8mTSeBSHl/UaRyKQW1qZeMgak41ANeCNaVckg+4= +github.com/machadovilaca/operator-observability v0.0.20 h1:I9CLKWcaJU9KtPREhUu4yn/CLAZUpxFqEUz/ZVenkAI= +github.com/machadovilaca/operator-observability v0.0.20/go.mod h1:e4Z3VhOXb9InkmSh00JjqBBijE+iD+YMzynBpKB3+gE= github.com/mailru/easyjson v0.0.0-20190614124828-94de47d64c63/go.mod h1:C1wdFJiN94OJF2b5HbByQZoLdCWB1Yqtg26g4irojpc= github.com/mailru/easyjson v0.0.0-20190626092158-b2ccc519800e/go.mod h1:C1wdFJiN94OJF2b5HbByQZoLdCWB1Yqtg26g4irojpc= github.com/mailru/easyjson v0.7.6/go.mod h1:xzfreul335JAWq5oZzymOObrkdz5UnU4kGfJJLY9Nlc= @@ -248,8 +251,11 @@ github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pkg/profile v1.7.0 h1:hnbDkaNWPCLMO9wGLdBFTIZvzDrDfBM2072E1S9gJkA= github.com/pkg/profile v1.7.0/go.mod h1:8Uer0jas47ZQMJ7VD+OHknK4YDY07LPUC6dEvqDjvNo= -github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U= +github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring v0.68.0 h1:yl9ceUSUBo9woQIO+8eoWpcxZkdZgm89g+rVvu37TUw= +github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring v0.68.0/go.mod h1:9Uuu3pEU2jB8PwuqkHvegQ0HV/BlZRJUyfTYAqfdVF8= github.com/prometheus/client_golang v1.17.0 h1:rl2sfwZMtSthVU752MqfjQozy7blglC+1SOtjMAMh+Q= github.com/prometheus/client_golang v1.17.0/go.mod h1:VeL+gMmOAxkS2IqfCq0ZmHSL+LjWfWDUmp1mBz9JgUY= github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= diff --git a/pkg/monitoring/rules/BUILD.bazel b/pkg/monitoring/rules/BUILD.bazel index 6e02ab99a..faf0f77e8 100644 --- a/pkg/monitoring/rules/BUILD.bazel +++ b/pkg/monitoring/rules/BUILD.bazel @@ -7,7 +7,7 @@ go_library( visibility = ["//visibility:public"], deps = [ "//pkg/monitoring/rules/recordingrules", - "@com_github_machadovilaca_operator_observability//pkg/operatorrules:go_default_library", - "@com_github_prometheus_operator_prometheus_operator_pkg_apis_monitoring//v1:go_default_library", + "//vendor/github.com/machadovilaca/operator-observability/pkg/operatorrules", + "//vendor/github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1:monitoring", ], ) diff --git a/pkg/monitoring/rules/recordingrules/BUILD.bazel b/pkg/monitoring/rules/recordingrules/BUILD.bazel index eb0a7cf3f..76a21067c 100644 --- a/pkg/monitoring/rules/recordingrules/BUILD.bazel +++ b/pkg/monitoring/rules/recordingrules/BUILD.bazel @@ -10,8 +10,8 @@ go_library( importpath = "github.com/konveyor/forklift-controller/pkg/monitoring/rules/recordingrules", visibility = ["//visibility:public"], deps = [ + "//vendor/github.com/machadovilaca/operator-observability/pkg/operatormetrics", + "//vendor/github.com/machadovilaca/operator-observability/pkg/operatorrules", "//vendor/k8s.io/apimachinery/pkg/util/intstr", - "@com_github_machadovilaca_operator_observability//pkg/operatormetrics:go_default_library", - "@com_github_machadovilaca_operator_observability//pkg/operatorrules:go_default_library", ], ) diff --git a/vendor/github.com/machadovilaca/operator-observability/LICENSE b/vendor/github.com/machadovilaca/operator-observability/LICENSE new file mode 100644 index 000000000..261eeb9e9 --- /dev/null +++ b/vendor/github.com/machadovilaca/operator-observability/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/vendor/github.com/machadovilaca/operator-observability/pkg/operatormetrics/BUILD.bazel b/vendor/github.com/machadovilaca/operator-observability/pkg/operatormetrics/BUILD.bazel new file mode 100644 index 000000000..260644ea2 --- /dev/null +++ b/vendor/github.com/machadovilaca/operator-observability/pkg/operatormetrics/BUILD.bazel @@ -0,0 +1,23 @@ +load("@io_bazel_rules_go//go:def.bzl", "go_library") + +go_library( + name = "operatormetrics", + srcs = [ + "collector.go", + "counter.go", + "counter_vec.go", + "gauge.go", + "gauge_vec.go", + "histogram.go", + "histogram_vec.go", + "metric.go", + "registry.go", + "summary.go", + "summary_vec.go", + "wrapper_registry.go", + ], + importmap = "github.com/konveyor/forklift-controller/vendor/github.com/machadovilaca/operator-observability/pkg/operatormetrics", + importpath = "github.com/machadovilaca/operator-observability/pkg/operatormetrics", + visibility = ["//visibility:public"], + deps = ["//vendor/github.com/prometheus/client_golang/prometheus"], +) diff --git a/vendor/github.com/machadovilaca/operator-observability/pkg/operatormetrics/collector.go b/vendor/github.com/machadovilaca/operator-observability/pkg/operatormetrics/collector.go new file mode 100644 index 000000000..35015f51a --- /dev/null +++ b/vendor/github.com/machadovilaca/operator-observability/pkg/operatormetrics/collector.go @@ -0,0 +1,99 @@ +package operatormetrics + +import ( + "fmt" + "strings" + + "github.com/prometheus/client_golang/prometheus" +) + +// Collector registers a prometheus.Collector with a set of metrics in the +// Prometheus registry. The metrics are collected by calling the CollectCallback +// function. +type Collector struct { + // Metrics is a list of metrics to be collected by the collector. + Metrics []Metric + + // CollectCallback is a function that returns a list of CollectionResults. + // The CollectionResults are used to populate the metrics in the collector. + CollectCallback func() []CollectorResult +} + +type CollectorResult struct { + Metric Metric + Labels []string + ConstLabels map[string]string + Value float64 +} + +func (c Collector) hash() string { + var sb strings.Builder + + for _, cm := range c.Metrics { + sb.WriteString(cm.GetOpts().Name) + } + + return sb.String() +} + +func (c Collector) Describe(ch chan<- *prometheus.Desc) { + for _, cm := range c.Metrics { + cm.getCollector().Describe(ch) + } +} + +func (c Collector) Collect(ch chan<- prometheus.Metric) { + collectedMetrics := c.CollectCallback() + + for _, cr := range collectedMetrics { + metric, ok := operatorRegistry.registeredCollectorMetrics[cr.Metric.GetOpts().Name] + if !ok { + fmt.Printf("metric %s not found in registry", cr.Metric.GetOpts().Name) + continue + } + + if err := collectValue(ch, metric, cr); err != nil { + fmt.Printf("error collecting metric %s: %v", cr.Metric.GetOpts().Name, err) + } + } +} + +func collectValue(ch chan<- prometheus.Metric, metric Metric, cr CollectorResult) error { + var mType prometheus.ValueType + + switch metric.GetType() { + case CounterType: + mType = prometheus.CounterValue + case GaugeType: + mType = prometheus.GaugeValue + case CounterVecType: + mType = prometheus.CounterValue + case GaugeVecType: + mType = prometheus.GaugeValue + default: + return fmt.Errorf("encountered unsupported type for collector %v", metric.GetType()) + } + + labels := map[string]string{} + for k, v := range cr.ConstLabels { + labels[k] = v + } + for k, v := range metric.GetOpts().ConstLabels { + labels[k] = v + } + + desc := prometheus.NewDesc( + metric.GetOpts().Name, + metric.GetOpts().Help, + metric.GetOpts().labels, + labels, + ) + + cm, err := prometheus.NewConstMetric(desc, mType, cr.Value, cr.Labels...) + if err != nil { + return err + } + ch <- cm + + return nil +} diff --git a/vendor/github.com/machadovilaca/operator-observability/pkg/operatormetrics/counter.go b/vendor/github.com/machadovilaca/operator-observability/pkg/operatormetrics/counter.go new file mode 100644 index 000000000..ddca79de4 --- /dev/null +++ b/vendor/github.com/machadovilaca/operator-observability/pkg/operatormetrics/counter.go @@ -0,0 +1,36 @@ +package operatormetrics + +import "github.com/prometheus/client_golang/prometheus" + +type Counter struct { + prometheus.Counter + + metricOpts MetricOpts +} + +var _ Metric = &Counter{} + +// NewCounter creates a new Counter. The Counter must be registered with the +// Prometheus registry through RegisterMetrics. +func NewCounter(metricOpts MetricOpts) *Counter { + return &Counter{ + Counter: prometheus.NewCounter(prometheus.CounterOpts(convertOpts(metricOpts))), + metricOpts: metricOpts, + } +} + +func (c *Counter) GetOpts() MetricOpts { + return c.metricOpts +} + +func (c *Counter) GetType() MetricType { + return CounterType +} + +func (c *Counter) GetBaseType() MetricType { + return CounterType +} + +func (c *Counter) getCollector() prometheus.Collector { + return c.Counter +} diff --git a/vendor/github.com/machadovilaca/operator-observability/pkg/operatormetrics/counter_vec.go b/vendor/github.com/machadovilaca/operator-observability/pkg/operatormetrics/counter_vec.go new file mode 100644 index 000000000..568ce6c7b --- /dev/null +++ b/vendor/github.com/machadovilaca/operator-observability/pkg/operatormetrics/counter_vec.go @@ -0,0 +1,38 @@ +package operatormetrics + +import "github.com/prometheus/client_golang/prometheus" + +type CounterVec struct { + prometheus.CounterVec + + metricOpts MetricOpts +} + +var _ Metric = &CounterVec{} + +// NewCounterVec creates a new CounterVec. The CounterVec must be registered +// with the Prometheus registry through RegisterMetrics. +func NewCounterVec(metricOpts MetricOpts, labels []string) *CounterVec { + metricOpts.labels = labels + + return &CounterVec{ + CounterVec: *prometheus.NewCounterVec(prometheus.CounterOpts(convertOpts(metricOpts)), labels), + metricOpts: metricOpts, + } +} + +func (c *CounterVec) GetOpts() MetricOpts { + return c.metricOpts +} + +func (c *CounterVec) GetType() MetricType { + return CounterVecType +} + +func (c *CounterVec) GetBaseType() MetricType { + return CounterType +} + +func (c *CounterVec) getCollector() prometheus.Collector { + return c.CounterVec +} diff --git a/vendor/github.com/machadovilaca/operator-observability/pkg/operatormetrics/gauge.go b/vendor/github.com/machadovilaca/operator-observability/pkg/operatormetrics/gauge.go new file mode 100644 index 000000000..de2699b2c --- /dev/null +++ b/vendor/github.com/machadovilaca/operator-observability/pkg/operatormetrics/gauge.go @@ -0,0 +1,36 @@ +package operatormetrics + +import "github.com/prometheus/client_golang/prometheus" + +type Gauge struct { + prometheus.Gauge + + metricOpts MetricOpts +} + +var _ Metric = &Gauge{} + +// NewGauge creates a new Gauge. The Gauge must be registered with the +// Prometheus registry through RegisterMetrics. +func NewGauge(metricOpts MetricOpts) *Gauge { + return &Gauge{ + Gauge: prometheus.NewGauge(prometheus.GaugeOpts(convertOpts(metricOpts))), + metricOpts: metricOpts, + } +} + +func (c *Gauge) GetOpts() MetricOpts { + return c.metricOpts +} + +func (c *Gauge) GetType() MetricType { + return GaugeType +} + +func (c *Gauge) GetBaseType() MetricType { + return GaugeType +} + +func (c *Gauge) getCollector() prometheus.Collector { + return c.Gauge +} diff --git a/vendor/github.com/machadovilaca/operator-observability/pkg/operatormetrics/gauge_vec.go b/vendor/github.com/machadovilaca/operator-observability/pkg/operatormetrics/gauge_vec.go new file mode 100644 index 000000000..c771dece9 --- /dev/null +++ b/vendor/github.com/machadovilaca/operator-observability/pkg/operatormetrics/gauge_vec.go @@ -0,0 +1,38 @@ +package operatormetrics + +import "github.com/prometheus/client_golang/prometheus" + +type GaugeVec struct { + prometheus.GaugeVec + + metricOpts MetricOpts +} + +var _ Metric = &GaugeVec{} + +// NewGaugeVec creates a new GaugeVec. The GaugeVec must be registered +// with the Prometheus registry through RegisterMetrics. +func NewGaugeVec(metricOpts MetricOpts, labels []string) *GaugeVec { + metricOpts.labels = labels + + return &GaugeVec{ + GaugeVec: *prometheus.NewGaugeVec(prometheus.GaugeOpts(convertOpts(metricOpts)), labels), + metricOpts: metricOpts, + } +} + +func (c *GaugeVec) GetOpts() MetricOpts { + return c.metricOpts +} + +func (c *GaugeVec) GetType() MetricType { + return GaugeVecType +} + +func (c *GaugeVec) GetBaseType() MetricType { + return GaugeType +} + +func (c *GaugeVec) getCollector() prometheus.Collector { + return c.GaugeVec +} diff --git a/vendor/github.com/machadovilaca/operator-observability/pkg/operatormetrics/histogram.go b/vendor/github.com/machadovilaca/operator-observability/pkg/operatormetrics/histogram.go new file mode 100644 index 000000000..b764835e2 --- /dev/null +++ b/vendor/github.com/machadovilaca/operator-observability/pkg/operatormetrics/histogram.go @@ -0,0 +1,51 @@ +package operatormetrics + +import ( + "github.com/prometheus/client_golang/prometheus" +) + +type Histogram struct { + prometheus.Histogram + + metricOpts MetricOpts + histogramOpts prometheus.HistogramOpts +} + +var _ Metric = &Histogram{} + +// NewHistogram creates a new Histogram. The Histogram must be registered with the +// Prometheus registry through RegisterMetrics. +func NewHistogram(metricOpts MetricOpts, histogramOpts prometheus.HistogramOpts) *Histogram { + return &Histogram{ + Histogram: prometheus.NewHistogram(makePrometheusHistogramOpts(metricOpts, histogramOpts)), + metricOpts: metricOpts, + histogramOpts: histogramOpts, + } +} + +func makePrometheusHistogramOpts(metricOpts MetricOpts, histogramOpts prometheus.HistogramOpts) prometheus.HistogramOpts { + histogramOpts.Name = metricOpts.Name + histogramOpts.Help = metricOpts.Help + histogramOpts.ConstLabels = metricOpts.ConstLabels + return histogramOpts +} + +func (c *Histogram) GetOpts() MetricOpts { + return c.metricOpts +} + +func (c *Histogram) GetHistogramOpts() prometheus.HistogramOpts { + return c.histogramOpts +} + +func (c *Histogram) GetType() MetricType { + return HistogramType +} + +func (c *Histogram) GetBaseType() MetricType { + return HistogramType +} + +func (c *Histogram) getCollector() prometheus.Collector { + return c.Histogram +} diff --git a/vendor/github.com/machadovilaca/operator-observability/pkg/operatormetrics/histogram_vec.go b/vendor/github.com/machadovilaca/operator-observability/pkg/operatormetrics/histogram_vec.go new file mode 100644 index 000000000..f272495f1 --- /dev/null +++ b/vendor/github.com/machadovilaca/operator-observability/pkg/operatormetrics/histogram_vec.go @@ -0,0 +1,42 @@ +package operatormetrics + +import "github.com/prometheus/client_golang/prometheus" + +type HistogramVec struct { + prometheus.HistogramVec + + metricOpts MetricOpts + histogramOpts prometheus.HistogramOpts +} + +var _ Metric = &HistogramVec{} + +// NewHistogramVec creates a new HistogramVec. The HistogramVec must be +// registered with the Prometheus registry through RegisterMetrics. +func NewHistogramVec(metricOpts MetricOpts, histogramOpts prometheus.HistogramOpts, labels []string) *HistogramVec { + return &HistogramVec{ + HistogramVec: *prometheus.NewHistogramVec(makePrometheusHistogramOpts(metricOpts, histogramOpts), labels), + metricOpts: metricOpts, + histogramOpts: histogramOpts, + } +} + +func (c *HistogramVec) GetOpts() MetricOpts { + return c.metricOpts +} + +func (c *HistogramVec) GetHistogramOpts() prometheus.HistogramOpts { + return c.histogramOpts +} + +func (c *HistogramVec) GetType() MetricType { + return HistogramVecType +} + +func (c *HistogramVec) GetBaseType() MetricType { + return HistogramType +} + +func (c *HistogramVec) getCollector() prometheus.Collector { + return c.HistogramVec +} diff --git a/vendor/github.com/machadovilaca/operator-observability/pkg/operatormetrics/metric.go b/vendor/github.com/machadovilaca/operator-observability/pkg/operatormetrics/metric.go new file mode 100644 index 000000000..108d86bb9 --- /dev/null +++ b/vendor/github.com/machadovilaca/operator-observability/pkg/operatormetrics/metric.go @@ -0,0 +1,42 @@ +package operatormetrics + +import "github.com/prometheus/client_golang/prometheus" + +type MetricOpts struct { + Name string + Help string + ConstLabels map[string]string + ExtraFields map[string]string + + labels []string +} + +type Metric interface { + GetOpts() MetricOpts + GetType() MetricType + GetBaseType() MetricType + + getCollector() prometheus.Collector +} + +type MetricType string + +const ( + CounterType MetricType = "Counter" + GaugeType MetricType = "Gauge" + HistogramType MetricType = "Histogram" + SummaryType MetricType = "Summary" + + CounterVecType MetricType = "CounterVec" + GaugeVecType MetricType = "GaugeVec" + HistogramVecType MetricType = "HistogramVec" + SummaryVecType MetricType = "SummaryVec" +) + +func convertOpts(opts MetricOpts) prometheus.Opts { + return prometheus.Opts{ + Name: opts.Name, + Help: opts.Help, + ConstLabels: opts.ConstLabels, + } +} diff --git a/vendor/github.com/machadovilaca/operator-observability/pkg/operatormetrics/registry.go b/vendor/github.com/machadovilaca/operator-observability/pkg/operatormetrics/registry.go new file mode 100644 index 000000000..b1e803067 --- /dev/null +++ b/vendor/github.com/machadovilaca/operator-observability/pkg/operatormetrics/registry.go @@ -0,0 +1,14 @@ +package operatormetrics + +import ( + "github.com/prometheus/client_golang/prometheus" +) + +type RegistryFunc func(c prometheus.Collector) error +type UnregisterFunc func(c prometheus.Collector) bool + +// Register is the function used to register metrics and collectors by this package. +var Register RegistryFunc = prometheus.Register + +// Unregister is the function used to unregister metrics and collectors by this package. +var Unregister UnregisterFunc = prometheus.Unregister diff --git a/vendor/github.com/machadovilaca/operator-observability/pkg/operatormetrics/summary.go b/vendor/github.com/machadovilaca/operator-observability/pkg/operatormetrics/summary.go new file mode 100644 index 000000000..3bf9d37c8 --- /dev/null +++ b/vendor/github.com/machadovilaca/operator-observability/pkg/operatormetrics/summary.go @@ -0,0 +1,51 @@ +package operatormetrics + +import ( + "github.com/prometheus/client_golang/prometheus" +) + +type Summary struct { + prometheus.Summary + + metricOpts MetricOpts + summaryOpts prometheus.SummaryOpts +} + +var _ Metric = &Summary{} + +// NewSummary creates a new Summary. The Summary must be registered with the +// Prometheus registry through RegisterMetrics. +func NewSummary(metricOpts MetricOpts, summaryOpts prometheus.SummaryOpts) *Summary { + return &Summary{ + Summary: prometheus.NewSummary(makePrometheusSummaryOpts(metricOpts, summaryOpts)), + metricOpts: metricOpts, + summaryOpts: summaryOpts, + } +} + +func makePrometheusSummaryOpts(metricOpts MetricOpts, summaryOpts prometheus.SummaryOpts) prometheus.SummaryOpts { + summaryOpts.Name = metricOpts.Name + summaryOpts.Help = metricOpts.Help + summaryOpts.ConstLabels = metricOpts.ConstLabels + return summaryOpts +} + +func (c *Summary) GetOpts() MetricOpts { + return c.metricOpts +} + +func (c *Summary) GetSummaryOpts() prometheus.SummaryOpts { + return c.summaryOpts +} + +func (c *Summary) GetType() MetricType { + return SummaryType +} + +func (c *Summary) GetBaseType() MetricType { + return SummaryType +} + +func (c *Summary) getCollector() prometheus.Collector { + return c.Summary +} diff --git a/vendor/github.com/machadovilaca/operator-observability/pkg/operatormetrics/summary_vec.go b/vendor/github.com/machadovilaca/operator-observability/pkg/operatormetrics/summary_vec.go new file mode 100644 index 000000000..6ea8bc542 --- /dev/null +++ b/vendor/github.com/machadovilaca/operator-observability/pkg/operatormetrics/summary_vec.go @@ -0,0 +1,42 @@ +package operatormetrics + +import "github.com/prometheus/client_golang/prometheus" + +type SummaryVec struct { + prometheus.SummaryVec + + metricOpts MetricOpts + summaryOpts prometheus.SummaryOpts +} + +var _ Metric = &SummaryVec{} + +// NewSummaryVec creates a new SummaryVec. The SummaryVec must be +// registered with the Prometheus registry through RegisterMetrics. +func NewSummaryVec(metricOpts MetricOpts, summaryOpts prometheus.SummaryOpts, labels []string) *SummaryVec { + return &SummaryVec{ + SummaryVec: *prometheus.NewSummaryVec(makePrometheusSummaryOpts(metricOpts, summaryOpts), labels), + metricOpts: metricOpts, + summaryOpts: summaryOpts, + } +} + +func (c *SummaryVec) GetOpts() MetricOpts { + return c.metricOpts +} + +func (c *SummaryVec) GetSummaryOpts() prometheus.SummaryOpts { + return c.summaryOpts +} + +func (c *SummaryVec) GetType() MetricType { + return SummaryVecType +} + +func (c *SummaryVec) GetBaseType() MetricType { + return SummaryType +} + +func (c *SummaryVec) getCollector() prometheus.Collector { + return c.SummaryVec +} diff --git a/vendor/github.com/machadovilaca/operator-observability/pkg/operatormetrics/wrapper_registry.go b/vendor/github.com/machadovilaca/operator-observability/pkg/operatormetrics/wrapper_registry.go new file mode 100644 index 000000000..8bb2b76e9 --- /dev/null +++ b/vendor/github.com/machadovilaca/operator-observability/pkg/operatormetrics/wrapper_registry.go @@ -0,0 +1,166 @@ +package operatormetrics + +import ( + "cmp" + "fmt" + "slices" +) + +var operatorRegistry = newRegistry() + +type operatorRegisterer struct { + registeredMetrics map[string]Metric + + registeredCollectors map[string]Collector + registeredCollectorMetrics map[string]Metric +} + +func newRegistry() operatorRegisterer { + return operatorRegisterer{ + registeredMetrics: map[string]Metric{}, + registeredCollectors: map[string]Collector{}, + registeredCollectorMetrics: map[string]Metric{}, + } +} + +// RegisterMetrics registers the metrics with the Prometheus registry. +func RegisterMetrics(allMetrics ...[]Metric) error { + for _, metricList := range allMetrics { + for _, metric := range metricList { + if metricExists(metric) { + err := unregisterMetric(metric) + if err != nil { + return err + } + } + + err := registerMetric(metric) + if err != nil { + return err + } + } + } + + return nil +} + +// RegisterCollector registers the collector with the Prometheus registry. +func RegisterCollector(collectors ...Collector) error { + for _, collector := range collectors { + if collectorExists(collector) { + err := unregisterCollector(collector) + if err != nil { + return err + } + } + + err := registerCollector(collector) + if err != nil { + return err + } + } + + return nil +} + +// ListMetrics returns a list of all registered metrics. +func ListMetrics() []Metric { + var result []Metric + + for _, rm := range operatorRegistry.registeredMetrics { + result = append(result, rm) + } + + for _, rc := range operatorRegistry.registeredCollectorMetrics { + result = append(result, rc) + } + + slices.SortFunc(result, func(a, b Metric) int { + return cmp.Compare(a.GetOpts().Name, b.GetOpts().Name) + }) + + return result +} + +// CleanRegistry removes all registered metrics. +func CleanRegistry() error { + for _, metric := range operatorRegistry.registeredMetrics { + err := unregisterMetric(metric) + if err != nil { + return err + } + } + + for _, collector := range operatorRegistry.registeredCollectors { + err := unregisterCollector(collector) + if err != nil { + return err + } + } + + return nil +} + +func metricExists(metric Metric) bool { + _, ok := operatorRegistry.registeredMetrics[metric.GetOpts().Name] + return ok +} + +func unregisterMetric(metric Metric) error { + if succeeded := Unregister(metric.getCollector()); succeeded { + delete(operatorRegistry.registeredMetrics, metric.GetOpts().Name) + return nil + } + + return fmt.Errorf("failed to unregister from Prometheus client metric %s", metric.GetOpts().Name) +} + +func registerMetric(metric Metric) error { + err := Register(metric.getCollector()) + if err != nil { + return err + } + operatorRegistry.registeredMetrics[metric.GetOpts().Name] = metric + + return nil +} + +func collectorExists(collector Collector) bool { + _, ok := operatorRegistry.registeredCollectors[collector.hash()] + return ok +} + +func unregisterCollector(collector Collector) error { + if succeeded := Unregister(collector); succeeded { + delete(operatorRegistry.registeredCollectors, collector.hash()) + for _, metric := range collector.Metrics { + delete(operatorRegistry.registeredCollectorMetrics, metric.GetOpts().Name) + } + return nil + } + + return fmt.Errorf("failed to unregister from Prometheus client collector with metrics: %s", buildCollectorMetricListString(collector)) +} + +func registerCollector(collector Collector) error { + err := Register(collector) + if err != nil { + return err + } + + operatorRegistry.registeredCollectors[collector.hash()] = collector + for _, cm := range collector.Metrics { + operatorRegistry.registeredCollectorMetrics[cm.GetOpts().Name] = cm + } + + return nil +} + +func buildCollectorMetricListString(collector Collector) string { + metricsList := "" + for _, metric := range collector.Metrics { + metricsList += metric.GetOpts().Name + ", " + } + metricsList = metricsList[:len(metricsList)-2] + return metricsList +} diff --git a/vendor/github.com/machadovilaca/operator-observability/pkg/operatorrules/BUILD.bazel b/vendor/github.com/machadovilaca/operator-observability/pkg/operatorrules/BUILD.bazel new file mode 100644 index 000000000..1f4b8a27a --- /dev/null +++ b/vendor/github.com/machadovilaca/operator-observability/pkg/operatorrules/BUILD.bazel @@ -0,0 +1,23 @@ +load("@io_bazel_rules_go//go:def.bzl", "go_library") + +go_library( + name = "operatorrules", + srcs = [ + "prometheusrules.go", + "rbac.go", + "recordingrule.go", + "registry.go", + "schema.go", + ], + importmap = "github.com/konveyor/forklift-controller/vendor/github.com/machadovilaca/operator-observability/pkg/operatorrules", + importpath = "github.com/machadovilaca/operator-observability/pkg/operatorrules", + visibility = ["//visibility:public"], + deps = [ + "//vendor/github.com/machadovilaca/operator-observability/pkg/operatormetrics", + "//vendor/github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1:monitoring", + "//vendor/k8s.io/api/rbac/v1:rbac", + "//vendor/k8s.io/apimachinery/pkg/apis/meta/v1:meta", + "//vendor/k8s.io/apimachinery/pkg/runtime", + "//vendor/k8s.io/apimachinery/pkg/util/intstr", + ], +) diff --git a/vendor/github.com/machadovilaca/operator-observability/pkg/operatorrules/prometheusrules.go b/vendor/github.com/machadovilaca/operator-observability/pkg/operatorrules/prometheusrules.go new file mode 100644 index 000000000..88000e635 --- /dev/null +++ b/vendor/github.com/machadovilaca/operator-observability/pkg/operatorrules/prometheusrules.go @@ -0,0 +1,76 @@ +package operatorrules + +import ( + "cmp" + "fmt" + "slices" + + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + + promv1 "github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1" +) + +// BuildPrometheusRule builds a PrometheusRule object from the registered recording rules and alerts. +func BuildPrometheusRule(name, namespace string, labels map[string]string) (*promv1.PrometheusRule, error) { + spec, err := buildPrometheusRuleSpec() + if err != nil { + return nil, err + } + + return &promv1.PrometheusRule{ + TypeMeta: metav1.TypeMeta{ + APIVersion: promv1.SchemeGroupVersion.String(), + Kind: promv1.PrometheusRuleKind, + }, + ObjectMeta: metav1.ObjectMeta{ + Name: name, + Namespace: namespace, + Labels: labels, + }, + Spec: *spec, + }, nil +} + +func buildPrometheusRuleSpec() (*promv1.PrometheusRuleSpec, error) { + var groups []promv1.RuleGroup + + if len(operatorRegistry.registeredRecordingRules) != 0 { + groups = append(groups, promv1.RuleGroup{ + Name: "recordingRules.rules", + Rules: buildRecordingRulesRules(), + }) + } + + if len(operatorRegistry.registeredAlerts) != 0 { + groups = append(groups, promv1.RuleGroup{ + Name: "alerts.rules", + Rules: ListAlerts(), + }) + } + + if len(groups) == 0 { + return nil, fmt.Errorf("no registered recording rule or alert") + } + + return &promv1.PrometheusRuleSpec{Groups: groups}, nil +} + +func buildRecordingRulesRules() []promv1.Rule { + var rules []promv1.Rule + + for _, recordingRule := range operatorRegistry.registeredRecordingRules { + rules = append(rules, promv1.Rule{ + Record: recordingRule.MetricsOpts.Name, + Expr: recordingRule.Expr, + Labels: recordingRule.MetricsOpts.ConstLabels, + }) + } + + slices.SortFunc(rules, func(a, b promv1.Rule) int { + aKey := a.Record + ":" + a.Expr.String() + bKey := b.Record + ":" + b.Expr.String() + return cmp.Compare(aKey, bKey) + }) + + return rules +} diff --git a/vendor/github.com/machadovilaca/operator-observability/pkg/operatorrules/rbac.go b/vendor/github.com/machadovilaca/operator-observability/pkg/operatorrules/rbac.go new file mode 100644 index 000000000..da582ceec --- /dev/null +++ b/vendor/github.com/machadovilaca/operator-observability/pkg/operatorrules/rbac.go @@ -0,0 +1,45 @@ +package operatorrules + +import ( + rbacv1 "k8s.io/api/rbac/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" +) + +func BuildRoleAndRoleBinding(namePrefix, namespace, promSAName, promSANamespace string, labels map[string]string) (*rbacv1.Role, *rbacv1.RoleBinding) { + r := &rbacv1.Role{ + ObjectMeta: metav1.ObjectMeta{ + Name: namePrefix + "-role", + Namespace: namespace, + Labels: labels, + }, + Rules: []rbacv1.PolicyRule{ + { + APIGroups: []string{""}, + Resources: []string{"services", "endpoints", "pods"}, + Verbs: []string{"get", "list"}, + }, + }, + } + + rb := &rbacv1.RoleBinding{ + ObjectMeta: metav1.ObjectMeta{ + Name: namePrefix + "-rolebinding", + Namespace: namespace, + Labels: labels, + }, + RoleRef: rbacv1.RoleRef{ + Kind: "Role", + Name: namePrefix + "-role", + APIGroup: rbacv1.GroupName, + }, + Subjects: []rbacv1.Subject{ + { + Kind: "ServiceAccount", + Name: promSAName, + Namespace: promSANamespace, + }, + }, + } + + return r, rb +} diff --git a/vendor/github.com/machadovilaca/operator-observability/pkg/operatorrules/recordingrule.go b/vendor/github.com/machadovilaca/operator-observability/pkg/operatorrules/recordingrule.go new file mode 100644 index 000000000..8dfc50c3e --- /dev/null +++ b/vendor/github.com/machadovilaca/operator-observability/pkg/operatorrules/recordingrule.go @@ -0,0 +1,24 @@ +package operatorrules + +import ( + "k8s.io/apimachinery/pkg/util/intstr" + + "github.com/machadovilaca/operator-observability/pkg/operatormetrics" +) + +// RecordingRule is a struct that represents a Prometheus recording rule. +type RecordingRule struct { + MetricsOpts operatormetrics.MetricOpts + MetricType operatormetrics.MetricType + Expr intstr.IntOrString +} + +// GetOpts returns the metric options of the recording rule. +func (c RecordingRule) GetOpts() operatormetrics.MetricOpts { + return c.MetricsOpts +} + +// GetType returns the metric type of the recording rule. +func (c RecordingRule) GetType() operatormetrics.MetricType { + return c.MetricType +} diff --git a/vendor/github.com/machadovilaca/operator-observability/pkg/operatorrules/registry.go b/vendor/github.com/machadovilaca/operator-observability/pkg/operatorrules/registry.go new file mode 100644 index 000000000..fdef00604 --- /dev/null +++ b/vendor/github.com/machadovilaca/operator-observability/pkg/operatorrules/registry.go @@ -0,0 +1,82 @@ +package operatorrules + +import ( + "cmp" + "slices" + + promv1 "github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1" +) + +var operatorRegistry = newRegistry() + +type operatorRegisterer struct { + registeredRecordingRules map[string]RecordingRule + registeredAlerts map[string]promv1.Rule +} + +func newRegistry() operatorRegisterer { + return operatorRegisterer{ + registeredRecordingRules: map[string]RecordingRule{}, + registeredAlerts: map[string]promv1.Rule{}, + } +} + +// RegisterRecordingRules registers the given recording rules. +func RegisterRecordingRules(recordingRules ...[]RecordingRule) error { + for _, recordingRuleList := range recordingRules { + for _, recordingRule := range recordingRuleList { + key := recordingRule.MetricsOpts.Name + ":" + recordingRule.Expr.String() + operatorRegistry.registeredRecordingRules[key] = recordingRule + } + } + + return nil +} + +// RegisterAlerts registers the given alerts. +func RegisterAlerts(alerts ...[]promv1.Rule) error { + for _, alertList := range alerts { + for _, alert := range alertList { + operatorRegistry.registeredAlerts[alert.Alert] = alert + } + } + + return nil +} + +// ListRecordingRules returns the registered recording rules. +func ListRecordingRules() []RecordingRule { + var rules []RecordingRule + for _, rule := range operatorRegistry.registeredRecordingRules { + rules = append(rules, rule) + } + + slices.SortFunc(rules, func(a, b RecordingRule) int { + aKey := a.GetOpts().Name + ":" + a.Expr.String() + bKey := b.GetOpts().Name + ":" + b.Expr.String() + + return cmp.Compare(aKey, bKey) + }) + + return rules +} + +// ListAlerts returns the registered alerts. +func ListAlerts() []promv1.Rule { + var alerts []promv1.Rule + for _, alert := range operatorRegistry.registeredAlerts { + alerts = append(alerts, alert) + } + + slices.SortFunc(alerts, func(a, b promv1.Rule) int { + return cmp.Compare(a.Alert, b.Alert) + }) + + return alerts +} + +// CleanRegistry removes all registered rules and alerts. +func CleanRegistry() error { + operatorRegistry = newRegistry() + return nil +} diff --git a/vendor/github.com/machadovilaca/operator-observability/pkg/operatorrules/schema.go b/vendor/github.com/machadovilaca/operator-observability/pkg/operatorrules/schema.go new file mode 100644 index 000000000..c06a032d7 --- /dev/null +++ b/vendor/github.com/machadovilaca/operator-observability/pkg/operatorrules/schema.go @@ -0,0 +1,22 @@ +package operatorrules + +import ( + rbacv1 "k8s.io/api/rbac/v1" + "k8s.io/apimachinery/pkg/runtime" + + promv1 "github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1" +) + +func AddToScheme(scheme *runtime.Scheme) error { + err := promv1.AddToScheme(scheme) + if err != nil { + return err + } + + err = rbacv1.AddToScheme(scheme) + if err != nil { + return err + } + + return nil +} diff --git a/vendor/github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/BUILD.bazel b/vendor/github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/BUILD.bazel new file mode 100644 index 000000000..f5d480e91 --- /dev/null +++ b/vendor/github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/BUILD.bazel @@ -0,0 +1,12 @@ +load("@io_bazel_rules_go//go:def.bzl", "go_library") + +go_library( + name = "monitoring", + srcs = [ + "register.go", + "resource.go", + ], + importmap = "github.com/konveyor/forklift-controller/vendor/github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring", + importpath = "github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring", + visibility = ["//visibility:public"], +) diff --git a/vendor/github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/LICENSE b/vendor/github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/LICENSE new file mode 100644 index 000000000..e06d20818 --- /dev/null +++ b/vendor/github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/LICENSE @@ -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/prometheus-operator/prometheus-operator/pkg/apis/monitoring/register.go b/vendor/github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/register.go new file mode 100644 index 000000000..a9914fb1a --- /dev/null +++ b/vendor/github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/register.go @@ -0,0 +1,19 @@ +// Copyright 2018 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 monitoring + +const ( + GroupName = "monitoring.coreos.com" +) diff --git a/vendor/github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/resource.go b/vendor/github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/resource.go new file mode 100644 index 000000000..25736ce92 --- /dev/null +++ b/vendor/github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/resource.go @@ -0,0 +1,60 @@ +// Copyright 2018 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 monitoring + +import ( + "fmt" +) + +const ( + PrometheusesKind = "Prometheus" + PrometheusName = "prometheuses" + + AlertmanagersKind = "Alertmanager" + AlertmanagerName = "alertmanagers" + + ServiceMonitorsKind = "ServiceMonitor" + ServiceMonitorName = "servicemonitors" + + PodMonitorsKind = "PodMonitor" + PodMonitorName = "podmonitors" + + PrometheusRuleKind = "PrometheusRule" + PrometheusRuleName = "prometheusrules" + + ProbesKind = "Probe" + ProbeName = "probes" + + ScrapeConfigsKind = "ScrapeConfig" + ScrapeConfigName = "scrapeconfigs" +) + +var resourceToKindMap = map[string]string{ + PrometheusName: PrometheusesKind, + AlertmanagerName: AlertmanagersKind, + ServiceMonitorName: ServiceMonitorsKind, + PodMonitorName: PodMonitorsKind, + PrometheusRuleName: PrometheusRuleKind, + ProbeName: ProbesKind, + ScrapeConfigName: ScrapeConfigsKind, +} + +func ResourceToKind(s string) string { + kind, found := resourceToKindMap[s] + if !found { + panic(fmt.Sprintf("failed to map resource %q to a kind", s)) + } + return kind +} diff --git a/vendor/github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1/BUILD.bazel b/vendor/github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1/BUILD.bazel new file mode 100644 index 000000000..1d695a1ba --- /dev/null +++ b/vendor/github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1/BUILD.bazel @@ -0,0 +1,30 @@ +load("@io_bazel_rules_go//go:def.bzl", "go_library") + +go_library( + name = "monitoring", + srcs = [ + "alertmanager_types.go", + "doc.go", + "podmonitor_types.go", + "probe_types.go", + "prometheus_types.go", + "prometheusrule_types.go", + "register.go", + "servicemonitor_types.go", + "thanos_types.go", + "types.go", + "zz_generated.deepcopy.go", + ], + importmap = "github.com/konveyor/forklift-controller/vendor/github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1", + importpath = "github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1", + visibility = ["//visibility:public"], + deps = [ + "//vendor/github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring", + "//vendor/k8s.io/api/core/v1:core", + "//vendor/k8s.io/apimachinery/pkg/api/resource", + "//vendor/k8s.io/apimachinery/pkg/apis/meta/v1:meta", + "//vendor/k8s.io/apimachinery/pkg/runtime", + "//vendor/k8s.io/apimachinery/pkg/runtime/schema", + "//vendor/k8s.io/apimachinery/pkg/util/intstr", + ], +) 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 new file mode 100644 index 000000000..9bcbf3207 --- /dev/null +++ b/vendor/github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1/alertmanager_types.go @@ -0,0 +1,442 @@ +// Copyright 2018 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 ( + v1 "k8s.io/api/core/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" +) + +const ( + AlertmanagersKind = "Alertmanager" + AlertmanagerName = "alertmanagers" + AlertManagerKindKey = "alertmanager" +) + +// +genclient +// +k8s:openapi-gen=true +// +kubebuilder:resource:categories="prometheus-operator",shortName="am" +// +kubebuilder:printcolumn:name="Version",type="string",JSONPath=".spec.version",description="The version of Alertmanager" +// +kubebuilder:printcolumn:name="Replicas",type="integer",JSONPath=".spec.replicas",description="The number of desired replicas" +// +kubebuilder:printcolumn:name="Ready",type="integer",JSONPath=".status.availableReplicas",description="The number of ready replicas" +// +kubebuilder:printcolumn:name="Reconciled",type="string",JSONPath=".status.conditions[?(@.type == 'Reconciled')].status" +// +kubebuilder:printcolumn:name="Available",type="string",JSONPath=".status.conditions[?(@.type == 'Available')].status" +// +kubebuilder:printcolumn:name="Age",type="date",JSONPath=".metadata.creationTimestamp" +// +kubebuilder:printcolumn:name="Paused",type="boolean",JSONPath=".status.paused",description="Whether the resource reconciliation is paused or not",priority=1 +// +kubebuilder:subresource:status + +// Alertmanager describes an Alertmanager cluster. +type Alertmanager struct { + metav1.TypeMeta `json:",inline"` + metav1.ObjectMeta `json:"metadata,omitempty"` + // Specification of the desired behavior of the Alertmanager cluster. More info: + // https://github.com/kubernetes/community/blob/master/contributors/devel/sig-architecture/api-conventions.md#spec-and-status + Spec AlertmanagerSpec `json:"spec"` + // Most recent observed status of the Alertmanager cluster. Read-only. + // More info: + // https://github.com/kubernetes/community/blob/master/contributors/devel/sig-architecture/api-conventions.md#spec-and-status + Status AlertmanagerStatus `json:"status,omitempty"` +} + +// DeepCopyObject implements the runtime.Object interface. +func (l *Alertmanager) DeepCopyObject() runtime.Object { + return l.DeepCopy() +} + +// AlertmanagerSpec is a specification of the desired behavior of the Alertmanager cluster. More info: +// https://github.com/kubernetes/community/blob/master/contributors/devel/sig-architecture/api-conventions.md#spec-and-status +// +k8s:openapi-gen=true +type AlertmanagerSpec struct { + // PodMetadata configures Labels and Annotations which are propagated to the alertmanager pods. + PodMetadata *EmbeddedObjectMetadata `json:"podMetadata,omitempty"` + // Image if specified has precedence over baseImage, tag and sha + // combinations. Specifying the version is still necessary to ensure the + // Prometheus Operator knows what version of Alertmanager is being + // configured. + Image *string `json:"image,omitempty"` + // Image pull policy for the 'alertmanager', 'init-config-reloader' and 'config-reloader' containers. + // See https://kubernetes.io/docs/concepts/containers/images/#image-pull-policy for more details. + // +kubebuilder:validation:Enum="";Always;Never;IfNotPresent + ImagePullPolicy v1.PullPolicy `json:"imagePullPolicy,omitempty"` + // Version the cluster should be on. + Version string `json:"version,omitempty"` + // Tag of Alertmanager container image to be deployed. Defaults to the value of `version`. + // Version is ignored if Tag is set. + // Deprecated: use 'image' instead. The image tag can be specified + // as part of the image URL. + Tag string `json:"tag,omitempty"` + // SHA of Alertmanager container image to be deployed. Defaults to the value of `version`. + // Similar to a tag, but the SHA explicitly deploys an immutable container image. + // Version and Tag are ignored if SHA is set. + // Deprecated: use 'image' instead. The image digest can be specified + // as part of the image URL. + SHA string `json:"sha,omitempty"` + // Base image that is used to deploy pods, without tag. + // Deprecated: use 'image' instead + BaseImage string `json:"baseImage,omitempty"` + // An optional list of references to secrets in the same namespace + // to use for pulling prometheus and alertmanager images from registries + // see http://kubernetes.io/docs/user-guide/images#specifying-imagepullsecrets-on-a-pod + ImagePullSecrets []v1.LocalObjectReference `json:"imagePullSecrets,omitempty"` + // Secrets is a list of Secrets in the same namespace as the Alertmanager + // object, which shall be mounted into the Alertmanager Pods. + // Each Secret is added to the StatefulSet definition as a volume named `secret-`. + // The Secrets are mounted into `/etc/alertmanager/secrets/` in the 'alertmanager' container. + Secrets []string `json:"secrets,omitempty"` + // ConfigMaps is a list of ConfigMaps in the same namespace as the Alertmanager + // object, which shall be mounted into the Alertmanager Pods. + // Each ConfigMap is added to the StatefulSet definition as a volume named `configmap-`. + // The ConfigMaps are mounted into `/etc/alertmanager/configmaps/` in the 'alertmanager' container. + ConfigMaps []string `json:"configMaps,omitempty"` + // ConfigSecret is the name of a Kubernetes Secret in the same namespace as the + // Alertmanager object, which contains the configuration for this Alertmanager + // instance. If empty, it defaults to `alertmanager-`. + // + // The Alertmanager configuration should be available under the + // `alertmanager.yaml` key. Additional keys from the original secret are + // copied to the generated secret and mounted into the + // `/etc/alertmanager/config` directory in the `alertmanager` container. + // + // If either the secret or the `alertmanager.yaml` key is missing, the + // operator provisions a minimal Alertmanager configuration with one empty + // receiver (effectively dropping alert notifications). + ConfigSecret string `json:"configSecret,omitempty"` + // Log level for Alertmanager to be configured with. + //+kubebuilder:validation:Enum="";debug;info;warn;error + LogLevel string `json:"logLevel,omitempty"` + // Log format for Alertmanager to be configured with. + //+kubebuilder:validation:Enum="";logfmt;json + LogFormat string `json:"logFormat,omitempty"` + // Size is the expected size of the alertmanager cluster. The controller will + // eventually make the size of the running cluster equal to the expected + // size. + Replicas *int32 `json:"replicas,omitempty"` + // Time duration Alertmanager shall retain data for. Default is '120h', + // and must match the regular expression `[0-9]+(ms|s|m|h)` (milliseconds seconds minutes hours). + // +kubebuilder:default:="120h" + Retention GoDuration `json:"retention,omitempty"` + // Storage is the definition of how storage will be used by the Alertmanager + // instances. + Storage *StorageSpec `json:"storage,omitempty"` + // Volumes allows configuration of additional volumes on the output StatefulSet definition. + // Volumes specified will be appended to other volumes that are generated as a result of + // StorageSpec objects. + Volumes []v1.Volume `json:"volumes,omitempty"` + // VolumeMounts allows configuration of additional VolumeMounts on the output StatefulSet definition. + // VolumeMounts specified will be appended to other VolumeMounts in the alertmanager container, + // that are generated as a result of StorageSpec objects. + VolumeMounts []v1.VolumeMount `json:"volumeMounts,omitempty"` + // The external URL the Alertmanager instances will be available under. This is + // necessary to generate correct URLs. This is necessary if Alertmanager is not + // served from root of a DNS name. + ExternalURL string `json:"externalUrl,omitempty"` + // The route prefix Alertmanager registers HTTP handlers for. This is useful, + // if using ExternalURL and a proxy is rewriting HTTP routes of a request, + // and the actual ExternalURL is still true, but the server serves requests + // under a different route prefix. For example for use with `kubectl proxy`. + RoutePrefix string `json:"routePrefix,omitempty"` + // If set to true all actions on the underlying managed objects are not + // goint to be performed, except for delete actions. + Paused bool `json:"paused,omitempty"` + // Define which Nodes the Pods are scheduled on. + NodeSelector map[string]string `json:"nodeSelector,omitempty"` + // Define resources requests and limits for single Pods. + Resources v1.ResourceRequirements `json:"resources,omitempty"` + // If specified, the pod's scheduling constraints. + Affinity *v1.Affinity `json:"affinity,omitempty"` + // If specified, the pod's tolerations. + Tolerations []v1.Toleration `json:"tolerations,omitempty"` + // If specified, the pod's topology spread constraints. + TopologySpreadConstraints []v1.TopologySpreadConstraint `json:"topologySpreadConstraints,omitempty"` + // SecurityContext holds pod-level security attributes and common container settings. + // This defaults to the default PodSecurityContext. + SecurityContext *v1.PodSecurityContext `json:"securityContext,omitempty"` + // ServiceAccountName is the name of the ServiceAccount to use to run the + // Prometheus Pods. + ServiceAccountName string `json:"serviceAccountName,omitempty"` + // ListenLocal makes the Alertmanager server listen on loopback, so that it + // does not bind against the Pod IP. Note this is only for the Alertmanager + // UI, not the gossip communication. + ListenLocal bool `json:"listenLocal,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 + // share the same name and modifications are done via a strategic merge + // patch. The current container names are: `alertmanager` and + // `config-reloader`. Overriding containers is entirely outside the scope + // of what the maintainers will support and by doing so, you accept that + // this behaviour may break at any time without notice. + Containers []v1.Container `json:"containers,omitempty"` + // InitContainers allows adding initContainers to the pod definition. Those can be used to e.g. + // fetch secrets for injection into the Alertmanager configuration from external sources. Any + // errors during the execution of an initContainer will lead to a restart of the Pod. More info: https://kubernetes.io/docs/concepts/workloads/pods/init-containers/ + // InitContainers described here modify an operator + // generated init containers if they share the same name and modifications are + // done via a strategic merge patch. The current init container name is: + // `init-config-reloader`. Overriding init containers is entirely outside the + // scope of what the maintainers will support and by doing so, you accept that + // this behaviour may break at any time without notice. + InitContainers []v1.Container `json:"initContainers,omitempty"` + // Priority class assigned to the Pods + PriorityClassName string `json:"priorityClassName,omitempty"` + // AdditionalPeers allows injecting a set of additional Alertmanagers to peer with to form a highly available cluster. + AdditionalPeers []string `json:"additionalPeers,omitempty"` + // ClusterAdvertiseAddress is the explicit address to advertise in cluster. + // Needs to be provided for non RFC1918 [1] (public) addresses. + // [1] RFC1918: https://tools.ietf.org/html/rfc1918 + ClusterAdvertiseAddress string `json:"clusterAdvertiseAddress,omitempty"` + // Interval between gossip attempts. + ClusterGossipInterval GoDuration `json:"clusterGossipInterval,omitempty"` + // Interval between pushpull attempts. + ClusterPushpullInterval GoDuration `json:"clusterPushpullInterval,omitempty"` + // Timeout for cluster peering. + ClusterPeerTimeout GoDuration `json:"clusterPeerTimeout,omitempty"` + // Port name used for the pods and governing service. + // Defaults to `web`. + // +kubebuilder:default:="web" + PortName string `json:"portName,omitempty"` + // 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. + ForceEnableClusterMode bool `json:"forceEnableClusterMode,omitempty"` + // AlertmanagerConfigs to be selected for to merge and configure Alertmanager with. + AlertmanagerConfigSelector *metav1.LabelSelector `json:"alertmanagerConfigSelector,omitempty"` + // The AlertmanagerConfigMatcherStrategy defines how AlertmanagerConfig objects match the alerts. + // In the future more options may be added. + AlertmanagerConfigMatcherStrategy AlertmanagerConfigMatcherStrategy `json:"alertmanagerConfigMatcherStrategy,omitempty"` + // Namespaces to be selected for AlertmanagerConfig discovery. If nil, only + // check own namespace. + AlertmanagerConfigNamespaceSelector *metav1.LabelSelector `json:"alertmanagerConfigNamespaceSelector,omitempty"` + // 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. + // Defaults to 0 (pod will be considered available as soon as it is ready) + // This is an alpha field from kubernetes 1.22 until 1.24 which requires enabling the StatefulSetMinReadySeconds feature gate. + // +optional + MinReadySeconds *uint32 `json:"minReadySeconds,omitempty"` + // Pods' hostAliases configuration + // +listType=map + // +listMapKey=ip + HostAliases []HostAlias `json:"hostAliases,omitempty"` + // Defines the web command line flags when starting Alertmanager. + Web *AlertmanagerWebSpec `json:"web,omitempty"` + // EXPERIMENTAL: alertmanagerConfiguration specifies the configuration of Alertmanager. + // If defined, it takes precedence over the `configSecret` field. + // This field may change in future releases. + AlertmanagerConfiguration *AlertmanagerConfiguration `json:"alertmanagerConfiguration,omitempty"` + // AutomountServiceAccountToken indicates 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"` +} + +// AlertmanagerConfigMatcherStrategy defines the strategy used by AlertmanagerConfig objects to match alerts. +type AlertmanagerConfigMatcherStrategy struct { + // If set to `OnNamespace`, the operator injects a label matcher matching the namespace of the AlertmanagerConfig object for all its routes and inhibition rules. + // `None` will not add any additional matchers other than the ones specified in the AlertmanagerConfig. + // Default is `OnNamespace`. + // +kubebuilder:validation:Enum="OnNamespace";"None" + // +kubebuilder:default:="OnNamespace" + Type string `json:"type,omitempty"` +} + +// AlertmanagerConfiguration defines the Alertmanager configuration. +// +k8s:openapi-gen=true +type AlertmanagerConfiguration struct { + // The name of the AlertmanagerConfig resource which is used to generate the Alertmanager configuration. + // It must be defined in the same namespace as the Alertmanager object. + // The operator will not enforce a `namespace` label for routes and inhibition rules. + // +kubebuilder:validation:MinLength=1 + Name string `json:"name,omitempty"` + // Defines the global parameters of the Alertmanager configuration. + // +optional + Global *AlertmanagerGlobalConfig `json:"global,omitempty"` + // Custom notification templates. + // +optional + Templates []SecretOrConfigMap `json:"templates,omitempty"` +} + +// AlertmanagerGlobalConfig configures parameters that are valid in all other configuration contexts. +// See https://prometheus.io/docs/alerting/latest/configuration/#configuration-file +type AlertmanagerGlobalConfig struct { + // Configures global SMTP parameters. + // +optional + SMTPConfig *GlobalSMTPConfig `json:"smtp,omitempty"` + + // ResolveTimeout is the default value used by alertmanager if the alert does + // not include EndsAt, after this time passes it can declare the alert as resolved if it has not been updated. + // This has no impact on alerts from Prometheus, as they always include EndsAt. + ResolveTimeout Duration `json:"resolveTimeout,omitempty"` + + // HTTP client configuration. + HTTPConfig *HTTPConfig `json:"httpConfig,omitempty"` + + // The default Slack API URL. + SlackAPIURL *v1.SecretKeySelector `json:"slackApiUrl,omitempty"` + + // The default OpsGenie API URL. + OpsGenieAPIURL *v1.SecretKeySelector `json:"opsGenieApiUrl,omitempty"` + + // The default OpsGenie API Key. + OpsGenieAPIKey *v1.SecretKeySelector `json:"opsGenieApiKey,omitempty"` + + // The default Pagerduty URL. + PagerdutyURL *string `json:"pagerdutyUrl,omitempty"` +} + +// AlertmanagerStatus is the most recent observed status of the Alertmanager cluster. Read-only. +// More info: +// https://github.com/kubernetes/community/blob/master/contributors/devel/sig-architecture/api-conventions.md#spec-and-status +// +k8s:openapi-gen=true +type AlertmanagerStatus struct { + // Represents whether any actions on the underlying managed objects are + // being performed. Only delete actions will be performed. + Paused bool `json:"paused"` + // Total number of non-terminated pods targeted by this Alertmanager + // object (their labels match the selector). + Replicas int32 `json:"replicas"` + // Total number of non-terminated pods targeted by this Alertmanager + // object that have the desired version spec. + UpdatedReplicas int32 `json:"updatedReplicas"` + // Total number of available pods (ready for at least minReadySeconds) + // targeted by this Alertmanager cluster. + AvailableReplicas int32 `json:"availableReplicas"` + // Total number of unavailable pods targeted by this Alertmanager object. + UnavailableReplicas int32 `json:"unavailableReplicas"` + // The current state of the Alertmanager object. + // +listType=map + // +listMapKey=type + // +optional + Conditions []Condition `json:"conditions,omitempty"` +} + +func (a *Alertmanager) ExpectedReplicas() int { + if a.Spec.Replicas == nil { + return 1 + } + return int(*a.Spec.Replicas) +} + +func (a *Alertmanager) SetReplicas(i int) { a.Status.Replicas = int32(i) } +func (a *Alertmanager) SetUpdatedReplicas(i int) { a.Status.UpdatedReplicas = int32(i) } +func (a *Alertmanager) SetAvailableReplicas(i int) { a.Status.AvailableReplicas = int32(i) } +func (a *Alertmanager) SetUnavailableReplicas(i int) { a.Status.UnavailableReplicas = int32(i) } + +// AlertmanagerWebSpec defines the web command line flags when starting Alertmanager. +// +k8s:openapi-gen=true +type AlertmanagerWebSpec struct { + WebConfigFileFields `json:",inline"` + // Maximum number of GET requests processed concurrently. This corresponds to the + // Alertmanager's `--web.get-concurrency` flag. + // +optional + GetConcurrency *uint32 `json:"getConcurrency,omitempty"` + // Timeout for HTTP requests. This corresponds to the Alertmanager's + // `--web.timeout` flag. + // +optional + Timeout *uint32 `json:"timeout,omitempty"` +} + +// GlobalSMTPConfig configures global SMTP parameters. +// See https://prometheus.io/docs/alerting/latest/configuration/#configuration-file +type GlobalSMTPConfig struct { + // The default SMTP From header field. + // +optional + From *string `json:"from,omitempty"` + + // The default SMTP smarthost used for sending emails. + // +optional + SmartHost *HostPort `json:"smartHost,omitempty"` + + // The default hostname to identify to the SMTP server. + // +optional + Hello *string `json:"hello,omitempty"` + + // SMTP Auth using CRAM-MD5, LOGIN and PLAIN. If empty, Alertmanager doesn't authenticate to the SMTP server. + // +optional + AuthUsername *string `json:"authUsername,omitempty"` + + // SMTP Auth using LOGIN and PLAIN. + // +optional + AuthPassword *v1.SecretKeySelector `json:"authPassword,omitempty"` + + // SMTP Auth using PLAIN + // +optional + AuthIdentity *string `json:"authIdentity,omitempty"` + + // SMTP Auth using CRAM-MD5. + // +optional + AuthSecret *v1.SecretKeySelector `json:"authSecret,omitempty"` + + // The default SMTP TLS requirement. + // Note that Go does not support unencrypted connections to remote SMTP endpoints. + // +optional + RequireTLS *bool `json:"requireTLS,omitempty"` +} + +// HostPort represents a "host:port" network address. +type HostPort struct { + // Defines the host's address, it can be a DNS name or a literal IP address. + // +kubebuilder:validation:MinLength=1 + Host string `json:"host"` + // Defines the host's port, it can be a literal port number or a port name. + // +kubebuilder:validation:MinLength=1 + Port string `json:"port"` +} + +// HTTPConfig defines a client HTTP configuration. +// See https://prometheus.io/docs/alerting/latest/configuration/#http_config +type HTTPConfig struct { + // Authorization header configuration for the client. + // This is mutually exclusive with BasicAuth and is only available starting from Alertmanager v0.22+. + // +optional + Authorization *SafeAuthorization `json:"authorization,omitempty"` + // BasicAuth for the client. + // This is mutually exclusive with Authorization. If both are defined, BasicAuth takes precedence. + // +optional + BasicAuth *BasicAuth `json:"basicAuth,omitempty"` + // OAuth2 client credentials used to fetch a token for the targets. + // +optional + OAuth2 *OAuth2 `json:"oauth2,omitempty"` + // The secret's key that contains the bearer token to be used by the client + // for authentication. + // The secret needs to be in the same namespace as the Alertmanager + // object and accessible by the Prometheus Operator. + // +optional + BearerTokenSecret *v1.SecretKeySelector `json:"bearerTokenSecret,omitempty"` + // TLS configuration for the client. + // +optional + TLSConfig *SafeTLSConfig `json:"tlsConfig,omitempty"` + // Optional proxy URL. + // +optional + ProxyURL string `json:"proxyURL,omitempty"` + // FollowRedirects specifies whether the client should follow HTTP 3xx redirects. + // +optional + FollowRedirects *bool `json:"followRedirects,omitempty"` +} + +// AlertmanagerList is a list of Alertmanagers. +// +k8s:openapi-gen=true +type AlertmanagerList struct { + metav1.TypeMeta `json:",inline"` + // Standard list metadata + // More info: https://github.com/kubernetes/community/blob/master/contributors/devel/sig-architecture/api-conventions.md#metadata + metav1.ListMeta `json:"metadata,omitempty"` + // List of Alertmanagers + Items []Alertmanager `json:"items"` +} + +// DeepCopyObject implements the runtime.Object interface. +func (l *AlertmanagerList) DeepCopyObject() runtime.Object { + return l.DeepCopy() +} diff --git a/vendor/github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1/doc.go b/vendor/github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1/doc.go new file mode 100644 index 000000000..64c472527 --- /dev/null +++ b/vendor/github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1/doc.go @@ -0,0 +1,18 @@ +// Copyright 2017 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. + +// +k8s:deepcopy-gen=package +// +groupName=monitoring.coreos.com + +package v1 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 new file mode 100644 index 000000000..ee03102d0 --- /dev/null +++ b/vendor/github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1/podmonitor_types.go @@ -0,0 +1,167 @@ +// Copyright 2018 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 ( + v1 "k8s.io/api/core/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/util/intstr" +) + +const ( + PodMonitorsKind = "PodMonitor" + PodMonitorName = "podmonitors" + PodMonitorKindKey = "podmonitor" +) + +// +genclient +// +k8s:openapi-gen=true +// +kubebuilder:resource:categories="prometheus-operator",shortName="pmon" + +// PodMonitor defines monitoring for a set of pods. +type PodMonitor struct { + metav1.TypeMeta `json:",inline"` + metav1.ObjectMeta `json:"metadata,omitempty"` + // Specification of desired Pod selection for target discovery by Prometheus. + Spec PodMonitorSpec `json:"spec"` +} + +// DeepCopyObject implements the runtime.Object interface. +func (l *PodMonitor) DeepCopyObject() runtime.Object { + return l.DeepCopy() +} + +// PodMonitorSpec contains specification parameters for a PodMonitor. +// +k8s:openapi-gen=true +type PodMonitorSpec struct { + // The label to use to retrieve the job name from. + JobLabel string `json:"jobLabel,omitempty"` + // PodTargetLabels transfers labels on the Kubernetes Pod onto the target. + PodTargetLabels []string `json:"podTargetLabels,omitempty"` + // A list of endpoints allowed as part of this PodMonitor. + PodMetricsEndpoints []PodMetricsEndpoint `json:"podMetricsEndpoints"` + // Selector to select Pod objects. + Selector metav1.LabelSelector `json:"selector"` + // Selector to select which namespaces the Endpoints objects are discovered from. + NamespaceSelector NamespaceSelector `json:"namespaceSelector,omitempty"` + // SampleLimit defines per-scrape limit on number of scraped samples that will be accepted. + SampleLimit *uint64 `json:"sampleLimit,omitempty"` + // TargetLimit defines a limit on the number of scraped targets that will be accepted. + // +optional + TargetLimit *uint64 `json:"targetLimit,omitempty"` + // 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"` + // 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"` + // 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 + LabelValueLengthLimit *uint64 `json:"labelValueLengthLimit,omitempty"` + // Per-scrape limit on the number of targets dropped by relabeling + // that will be kept in memory. 0 means no limit. + // + // It requires Prometheus >= v2.47.0. + // + // +optional + KeepDroppedTargets *uint64 `json:"keepDroppedTargets,omitempty"` + // Attaches node metadata to discovered targets. + // Requires Prometheus v2.35.0 and above. + AttachMetadata *AttachMetadata `json:"attachMetadata,omitempty"` +} + +// PodMonitorList is a list of PodMonitors. +// +k8s:openapi-gen=true +type PodMonitorList struct { + metav1.TypeMeta `json:",inline"` + // Standard list metadata + // More info: https://github.com/kubernetes/community/blob/master/contributors/devel/sig-architecture/api-conventions.md#metadata + metav1.ListMeta `json:"metadata,omitempty"` + // List of PodMonitors + Items []*PodMonitor `json:"items"` +} + +// DeepCopyObject implements the runtime.Object interface. +func (l *PodMonitorList) DeepCopyObject() runtime.Object { + return l.DeepCopy() +} + +// PodMetricsEndpoint defines a scrapeable endpoint of a Kubernetes Pod serving Prometheus metrics. +// +k8s:openapi-gen=true +type PodMetricsEndpoint struct { + // Name of the pod port this endpoint refers to. Mutually exclusive with targetPort. + Port string `json:"port,omitempty"` + // Deprecated: Use 'port' instead. + TargetPort *intstr.IntOrString `json:"targetPort,omitempty"` + // HTTP path to scrape for metrics. + // If empty, Prometheus uses the default value (e.g. `/metrics`). + Path string `json:"path,omitempty"` + // HTTP scheme to use for scraping. + // `http` and `https` are the expected values unless you rewrite the `__scheme__` label via relabeling. + // If empty, Prometheus uses the default value `http`. + // +kubebuilder:validation:Enum=http;https + Scheme string `json:"scheme,omitempty"` + // Optional HTTP URL parameters + Params map[string][]string `json:"params,omitempty"` + // Interval at which metrics should be scraped + // If not specified Prometheus' global scrape interval is used. + Interval Duration `json:"interval,omitempty"` + // Timeout after which the scrape is ended + // If not specified, the Prometheus global scrape interval is used. + ScrapeTimeout Duration `json:"scrapeTimeout,omitempty"` + // TLS configuration to use when scraping the endpoint. + TLSConfig *PodMetricsEndpointTLSConfig `json:"tlsConfig,omitempty"` + // Secret to mount to read bearer token for scraping targets. The secret + // needs to be in the same namespace as the pod monitor and accessible by + // the Prometheus Operator. + BearerTokenSecret v1.SecretKeySelector `json:"bearerTokenSecret,omitempty"` + // HonorLabels chooses the metric's labels on collisions with target labels. + HonorLabels bool `json:"honorLabels,omitempty"` + // HonorTimestamps controls whether Prometheus respects the timestamps present in scraped data. + HonorTimestamps *bool `json:"honorTimestamps,omitempty"` + // BasicAuth allow an endpoint to authenticate over basic authentication. + // More info: https://prometheus.io/docs/operating/configuration/#endpoint + BasicAuth *BasicAuth `json:"basicAuth,omitempty"` + // OAuth2 for the URL. Only valid in Prometheus versions 2.27.0 and newer. + OAuth2 *OAuth2 `json:"oauth2,omitempty"` + // Authorization section for this endpoint + Authorization *SafeAuthorization `json:"authorization,omitempty"` + // MetricRelabelConfigs to apply to samples before ingestion. + MetricRelabelConfigs []*RelabelConfig `json:"metricRelabelings,omitempty"` + // RelabelConfigs to apply to samples before scraping. + // Prometheus 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 + RelabelConfigs []*RelabelConfig `json:"relabelings,omitempty"` + // ProxyURL eg http://proxyserver:2195 Directs scrapes to proxy through this endpoint. + ProxyURL *string `json:"proxyUrl,omitempty"` + // FollowRedirects configures whether scrape requests follow HTTP 3xx redirects. + FollowRedirects *bool `json:"followRedirects,omitempty"` + // Whether to enable HTTP2. + EnableHttp2 *bool `json:"enableHttp2,omitempty"` + // Drop pods that are not running. (Failed, Succeeded). Enabled by default. + // More info: https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle/#pod-phase + FilterRunning *bool `json:"filterRunning,omitempty"` +} + +// PodMetricsEndpointTLSConfig specifies TLS configuration parameters. +// +k8s:openapi-gen=true +type PodMetricsEndpointTLSConfig struct { + SafeTLSConfig `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 new file mode 100644 index 000000000..59b85ae6a --- /dev/null +++ b/vendor/github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1/probe_types.go @@ -0,0 +1,213 @@ +// Copyright 2018 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 ( + v1 "k8s.io/api/core/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" +) + +const ( + ProbesKind = "Probe" + ProbeName = "probes" + ProbeKindKey = "probe" +) + +// +genclient +// +k8s:openapi-gen=true +// +kubebuilder:resource:categories="prometheus-operator",shortName="prb" + +// Probe defines monitoring for a set of static targets or ingresses. +type Probe struct { + metav1.TypeMeta `json:",inline"` + metav1.ObjectMeta `json:"metadata,omitempty"` + // Specification of desired Ingress selection for target discovery by Prometheus. + Spec ProbeSpec `json:"spec"` +} + +// DeepCopyObject implements the runtime.Object interface. +func (l *Probe) DeepCopyObject() runtime.Object { + return l.DeepCopy() +} + +// ProbeSpec contains specification parameters for a Probe. +// +k8s:openapi-gen=true +type ProbeSpec struct { + // The job name assigned to scraped metrics by default. + JobName string `json:"jobName,omitempty"` + // Specification for the prober to use for probing targets. + // The prober.URL parameter is required. Targets cannot be probed if left empty. + ProberSpec ProberSpec `json:"prober,omitempty"` + // The 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 + Module string `json:"module,omitempty"` + // Targets defines a set of static or dynamically discovered targets to probe. + Targets ProbeTargets `json:"targets,omitempty"` + // Interval at which targets are probed using the configured prober. + // If not specified Prometheus' global scrape interval is used. + Interval Duration `json:"interval,omitempty"` + // Timeout for scraping metrics from the Prometheus exporter. + // If not specified, the Prometheus global scrape timeout is used. + ScrapeTimeout Duration `json:"scrapeTimeout,omitempty"` + // TLS configuration to use when scraping the endpoint. + TLSConfig *ProbeTLSConfig `json:"tlsConfig,omitempty"` + // 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 v1.SecretKeySelector `json:"bearerTokenSecret,omitempty"` + // BasicAuth allow an endpoint to authenticate over basic authentication. + // More info: https://prometheus.io/docs/operating/configuration/#endpoint + BasicAuth *BasicAuth `json:"basicAuth,omitempty"` + // OAuth2 for the URL. Only valid in Prometheus versions 2.27.0 and newer. + OAuth2 *OAuth2 `json:"oauth2,omitempty"` + // MetricRelabelConfigs to apply to samples before ingestion. + MetricRelabelConfigs []*RelabelConfig `json:"metricRelabelings,omitempty"` + // Authorization section for this endpoint + Authorization *SafeAuthorization `json:"authorization,omitempty"` + // SampleLimit defines per-scrape limit on number of scraped samples that will be accepted. + // +optional + SampleLimit *uint64 `json:"sampleLimit,omitempty"` + // TargetLimit defines a limit on the number of scraped targets that will be accepted. + // +optional + TargetLimit *uint64 `json:"targetLimit,omitempty"` + // 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"` + // 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"` + // 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 + LabelValueLengthLimit *uint64 `json:"labelValueLengthLimit,omitempty"` + // Per-scrape limit on the number of targets dropped by relabeling + // that will be kept in memory. 0 means no limit. + // + // It requires Prometheus >= v2.47.0. + // + // +optional + KeepDroppedTargets *uint64 `json:"keepDroppedTargets,omitempty"` +} + +// ProbeTargets defines how to discover the probed targets. +// One of the `staticConfig` or `ingress` must be defined. +// If both are defined, `staticConfig` takes precedence. +// +k8s:openapi-gen=true +type ProbeTargets struct { + // staticConfig defines the static list of targets to probe and the + // relabeling configuration. + // If `ingress` is also defined, `staticConfig` takes precedence. + // More info: https://prometheus.io/docs/prometheus/latest/configuration/configuration/#static_config. + StaticConfig *ProbeTargetStaticConfig `json:"staticConfig,omitempty"` + // ingress defines the Ingress objects to probe and the relabeling + // configuration. + // If `staticConfig` is also defined, `staticConfig` takes precedence. + Ingress *ProbeTargetIngress `json:"ingress,omitempty"` +} + +// Validate semantically validates the given ProbeTargets. +func (it *ProbeTargets) Validate() error { + if it.StaticConfig == nil && it.Ingress == nil { + return &ProbeTargetsValidationError{"at least one of .spec.targets.staticConfig and .spec.targets.ingress is required"} + } + + return nil +} + +// ProbeTargetsValidationError is returned by ProbeTargets.Validate() +// on semantically invalid configurations. +// +k8s:openapi-gen=false +type ProbeTargetsValidationError struct { + err string +} + +func (e *ProbeTargetsValidationError) Error() string { + return e.err +} + +// ProbeTargetStaticConfig defines the set of static targets considered for probing. +// +k8s:openapi-gen=true +type ProbeTargetStaticConfig struct { + // The list of hosts to probe. + Targets []string `json:"static,omitempty"` + // Labels assigned to all metrics scraped from the targets. + Labels map[string]string `json:"labels,omitempty"` + // RelabelConfigs to apply to the label set of the targets before it gets + // scraped. + // More info: https://prometheus.io/docs/prometheus/latest/configuration/configuration/#relabel_config + RelabelConfigs []*RelabelConfig `json:"relabelingConfigs,omitempty"` +} + +// ProbeTargetIngress defines the set of Ingress objects considered for probing. +// The operator configures a target for each host/path combination of each ingress object. +// +k8s:openapi-gen=true +type ProbeTargetIngress struct { + // Selector to select the Ingress objects. + Selector metav1.LabelSelector `json:"selector,omitempty"` + // From which namespaces to select Ingress objects. + NamespaceSelector NamespaceSelector `json:"namespaceSelector,omitempty"` + // RelabelConfigs to apply to the label set of the target before it gets + // scraped. + // The original ingress address is available via the + // `__tmp_prometheus_ingress_address` label. It can be used to customize the + // probed URL. + // 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 + RelabelConfigs []*RelabelConfig `json:"relabelingConfigs,omitempty"` +} + +// ProberSpec contains specification parameters for the Prober used for probing. +// +k8s:openapi-gen=true +type ProberSpec struct { + // Mandatory URL of the prober. + URL string `json:"url"` + // HTTP scheme to use for scraping. + // `http` and `https` are the expected values unless you rewrite the `__scheme__` label via relabeling. + // If empty, Prometheus uses the default value `http`. + // +kubebuilder:validation:Enum=http;https + Scheme string `json:"scheme,omitempty"` + // Path to collect metrics from. + // Defaults to `/probe`. + // +kubebuilder:default:="/probe" + Path string `json:"path,omitempty"` + // Optional ProxyURL. + ProxyURL string `json:"proxyUrl,omitempty"` +} + +// ProbeList is a list of Probes. +// +k8s:openapi-gen=true +type ProbeList struct { + metav1.TypeMeta `json:",inline"` + // Standard list metadata + // More info: https://github.com/kubernetes/community/blob/master/contributors/devel/sig-architecture/api-conventions.md#metadata + metav1.ListMeta `json:"metadata,omitempty"` + // List of Probes + Items []*Probe `json:"items"` +} + +// DeepCopyObject implements the runtime.Object interface. +func (l *ProbeList) DeepCopyObject() runtime.Object { + return l.DeepCopy() +} + +// ProbeTLSConfig specifies TLS configuration parameters for the prober. +// +k8s:openapi-gen=true +type ProbeTLSConfig struct { + SafeTLSConfig `json:",inline"` +} 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 new file mode 100644 index 000000000..7dc956109 --- /dev/null +++ b/vendor/github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1/prometheus_types.go @@ -0,0 +1,1602 @@ +// Copyright 2018 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 ( + "strings" + + 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/util/intstr" +) + +const ( + PrometheusesKind = "Prometheus" + PrometheusName = "prometheuses" + PrometheusKindKey = "prometheus" +) + +// PrometheusInterface is used by Prometheus and PrometheusAgent to share common methods, e.g. config generation. +// +k8s:deepcopy-gen=false +type PrometheusInterface interface { + metav1.ObjectMetaAccessor + GetTypeMeta() metav1.TypeMeta + GetCommonPrometheusFields() CommonPrometheusFields + SetCommonPrometheusFields(CommonPrometheusFields) + GetStatus() PrometheusStatus +} + +func (l *Prometheus) GetCommonPrometheusFields() CommonPrometheusFields { + return l.Spec.CommonPrometheusFields +} + +func (l *Prometheus) SetCommonPrometheusFields(f CommonPrometheusFields) { + l.Spec.CommonPrometheusFields = f +} + +func (l *Prometheus) GetTypeMeta() metav1.TypeMeta { + return l.TypeMeta +} + +func (l *Prometheus) GetStatus() PrometheusStatus { + return l.Status +} + +// CommonPrometheusFields are the options available to both the Prometheus server and agent. +// +k8s:deepcopy-gen=true +type CommonPrometheusFields struct { + // PodMetadata configures labels and annotations which are propagated to the Prometheus pods. + PodMetadata *EmbeddedObjectMetadata `json:"podMetadata,omitempty"` + + // ServiceMonitors to be selected for target discovery. An empty label + // selector matches all objects. A null label selector matches no objects. + // + // If `spec.serviceMonitorSelector`, `spec.podMonitorSelector`, `spec.probeSelector` + // and `spec.scrapeConfigSelector` are null, the Prometheus configuration is unmanaged. + // The Prometheus operator will ensure that the Prometheus configuration's + // Secret exists, but it is the responsibility of the user to provide the raw + // gzipped Prometheus configuration under the `prometheus.yaml.gz` key. + // This behavior is *deprecated* and will be removed in the next major version + // of the custom resource definition. It is recommended to use + // `spec.additionalScrapeConfigs` instead. + ServiceMonitorSelector *metav1.LabelSelector `json:"serviceMonitorSelector,omitempty"` + // Namespaces to match for ServicedMonitors discovery. An empty label selector + // matches all namespaces. A null label selector matches the current + // namespace only. + ServiceMonitorNamespaceSelector *metav1.LabelSelector `json:"serviceMonitorNamespaceSelector,omitempty"` + + // *Experimental* PodMonitors to be selected for target discovery. An empty + // label selector matches all objects. A null label selector matches no + // objects. + // + // If `spec.serviceMonitorSelector`, `spec.podMonitorSelector`, `spec.probeSelector` + // and `spec.scrapeConfigSelector` are null, the Prometheus configuration is unmanaged. + // The Prometheus operator will ensure that the Prometheus configuration's + // Secret exists, but it is the responsibility of the user to provide the raw + // gzipped Prometheus configuration under the `prometheus.yaml.gz` key. + // This behavior is *deprecated* and will be removed in the next major version + // of the custom resource definition. It is recommended to use + // `spec.additionalScrapeConfigs` instead. + PodMonitorSelector *metav1.LabelSelector `json:"podMonitorSelector,omitempty"` + // Namespaces to match for PodMonitors discovery. An empty label selector + // matches all namespaces. A null label selector matches the current + // namespace only. + PodMonitorNamespaceSelector *metav1.LabelSelector `json:"podMonitorNamespaceSelector,omitempty"` + + // *Experimental* Probes to be selected for target discovery. An empty + // label selector matches all objects. A null label selector matches no + // objects. + // + // If `spec.serviceMonitorSelector`, `spec.podMonitorSelector`, `spec.probeSelector` + // and `spec.scrapeConfigSelector` are null, the Prometheus configuration is unmanaged. + // The Prometheus operator will ensure that the Prometheus configuration's + // Secret exists, but it is the responsibility of the user to provide the raw + // gzipped Prometheus configuration under the `prometheus.yaml.gz` key. + // This behavior is *deprecated* and will be removed in the next major version + // of the custom resource definition. It is recommended to use + // `spec.additionalScrapeConfigs` instead. + ProbeSelector *metav1.LabelSelector `json:"probeSelector,omitempty"` + // *Experimental* Namespaces to match for Probe discovery. An empty label + // selector matches all namespaces. A null label selector matches the + // current namespace only. + ProbeNamespaceSelector *metav1.LabelSelector `json:"probeNamespaceSelector,omitempty"` + + // *Experimental* ScrapeConfigs to be selected for target discovery. An + // empty label selector matches all objects. A null label selector matches + // no objects. + // + // If `spec.serviceMonitorSelector`, `spec.podMonitorSelector`, `spec.probeSelector` + // and `spec.scrapeConfigSelector` are null, the Prometheus configuration is unmanaged. + // The Prometheus operator will ensure that the Prometheus configuration's + // Secret exists, but it is the responsibility of the user to provide the raw + // gzipped Prometheus configuration under the `prometheus.yaml.gz` key. + // This behavior is *deprecated* and will be removed in the next major version + // of the custom resource definition. It is recommended to use + // `spec.additionalScrapeConfigs` instead. + ScrapeConfigSelector *metav1.LabelSelector `json:"scrapeConfigSelector,omitempty"` + // Namespaces to match for ScrapeConfig discovery. An empty label selector + // matches all namespaces. A null label selector matches the current + // current namespace only. + ScrapeConfigNamespaceSelector *metav1.LabelSelector `json:"scrapeConfigNamespaceSelector,omitempty"` + + // Version of Prometheus being deployed. The operator uses this information + // to generate the Prometheus StatefulSet + configuration files. + // + // If not specified, the operator assumes the latest upstream version of + // Prometheus available at the time when the version of the operator was + // released. + Version string `json:"version,omitempty"` + + // When a Prometheus deployment is paused, no actions except for deletion + // will be performed on the underlying objects. + Paused bool `json:"paused,omitempty"` + + // Container image name for Prometheus. If specified, it takes precedence + // over the `spec.baseImage`, `spec.tag` and `spec.sha` fields. + // + // Specifying `spec.version` is still necessary to ensure the Prometheus + // Operator knows which version of Prometheus is being configured. + // + // If neither `spec.image` nor `spec.baseImage` are defined, the operator + // will use the latest upstream version of Prometheus available at the time + // when the operator was released. + // + // +optional + Image *string `json:"image,omitempty"` + // Image pull policy for the 'prometheus', 'init-config-reloader' and 'config-reloader' containers. + // See https://kubernetes.io/docs/concepts/containers/images/#image-pull-policy for more details. + // +kubebuilder:validation:Enum="";Always;Never;IfNotPresent + ImagePullPolicy v1.PullPolicy `json:"imagePullPolicy,omitempty"` + // An optional list of references to Secrets in the same namespace + // to use for pulling images from registries. + // See http://kubernetes.io/docs/user-guide/images#specifying-imagepullsecrets-on-a-pod + ImagePullSecrets []v1.LocalObjectReference `json:"imagePullSecrets,omitempty"` + + // Number of replicas of each shard to deploy for a Prometheus deployment. + // `spec.replicas` multiplied by `spec.shards` is the total number of Pods + // created. + // + // Default: 1 + // +optional + Replicas *int32 `json:"replicas,omitempty"` + // EXPERIMENTAL: Number of shards to distribute targets onto. `spec.replicas` + // multiplied by `spec.shards` is the total number of Pods created. + // + // Note that scaling down shards will not reshard data onto remaining + // instances, it must be manually moved. Increasing shards will not reshard + // data either but it will continue to be available from the same + // instances. To query globally, use Thanos sidecar and Thanos querier or + // remote write data to a central location. + // + // Sharding is performed on the content of the `__address__` target meta-label + // for PodMonitors and ServiceMonitors and `__param_target__` for Probes. + // + // Default: 1 + // +optional + Shards *int32 `json:"shards,omitempty"` + + // Name of Prometheus external label used to denote the replica name. + // The external label will _not_ be added when the field is set to the + // empty string (`""`). + // + // Default: "prometheus_replica" + // +optional + ReplicaExternalLabelName *string `json:"replicaExternalLabelName,omitempty"` + // Name of Prometheus external label used to denote the Prometheus instance + // name. The external label will _not_ be added when the field is set to + // the empty string (`""`). + // + // Default: "prometheus" + // +optional + PrometheusExternalLabelName *string `json:"prometheusExternalLabelName,omitempty"` + + // Log level for Prometheus and the config-reloader sidecar. + //+kubebuilder:validation:Enum="";debug;info;warn;error + LogLevel string `json:"logLevel,omitempty"` + // Log format for Log level for Prometheus and the config-reloader sidecar. + //+kubebuilder:validation:Enum="";logfmt;json + LogFormat string `json:"logFormat,omitempty"` + + // Interval between consecutive scrapes. + // + // Default: "30s" + // +kubebuilder:default:="30s" + ScrapeInterval Duration `json:"scrapeInterval,omitempty"` + // Number of seconds to wait until a scrape request times out. + ScrapeTimeout Duration `json:"scrapeTimeout,omitempty"` + + // The labels to add to any time series or alerts when communicating with + // external systems (federation, remote storage, Alertmanager). + // Labels defined by `spec.replicaExternalLabelName` and + // `spec.prometheusExternalLabelName` take precedence over this list. + ExternalLabels map[string]string `json:"externalLabels,omitempty"` + + // Enable Prometheus to be used as a receiver for the Prometheus remote + // write protocol. + // + // WARNING: This is not considered an efficient way of ingesting samples. + // Use it with caution for specific low-volume use cases. + // It is not suitable for replacing the ingestion via scraping and turning + // Prometheus into a push-based metrics collection system. + // For more information see https://prometheus.io/docs/prometheus/latest/querying/api/#remote-write-receiver + // + // It requires Prometheus >= v2.33.0. + EnableRemoteWriteReceiver bool `json:"enableRemoteWriteReceiver,omitempty"` + + // Enable access to Prometheus 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 + // that this behaviour may break at any time without notice. + // + // For more information see https://prometheus.io/docs/prometheus/latest/feature_flags/ + EnableFeatures []string `json:"enableFeatures,omitempty"` + + // The external URL under which the Prometheus service is externally + // available. This is necessary to generate correct URLs (for instance if + // Prometheus is accessible behind an Ingress resource). + ExternalURL string `json:"externalUrl,omitempty"` + // The route prefix Prometheus registers HTTP handlers for. + // + // This is useful when using `spec.externalURL`, and a proxy is rewriting + // HTTP routes of a request, and the actual ExternalURL is still true, but + // the server serves requests under a different route prefix. For example + // for use with `kubectl proxy`. + RoutePrefix string `json:"routePrefix,omitempty"` + + // Storage defines the storage used by Prometheus. + Storage *StorageSpec `json:"storage,omitempty"` + + // Volumes allows the configuration of additional volumes on the output + // StatefulSet definition. Volumes specified will be appended to other + // volumes that are generated as a result of StorageSpec objects. + Volumes []v1.Volume `json:"volumes,omitempty"` + // VolumeMounts allows the configuration of additional VolumeMounts. + // + // VolumeMounts will be appended to other VolumeMounts in the 'prometheus' + // container, that are generated as a result of StorageSpec objects. + VolumeMounts []v1.VolumeMount `json:"volumeMounts,omitempty"` + + // Defines the configuration of the Prometheus web server. + Web *PrometheusWebSpec `json:"web,omitempty"` + + // Defines the resources requests and limits of the 'prometheus' container. + Resources v1.ResourceRequirements `json:"resources,omitempty"` + + // Defines on which Nodes the Pods are scheduled. + NodeSelector map[string]string `json:"nodeSelector,omitempty"` + + // ServiceAccountName is the name of the ServiceAccount to use to run the + // Prometheus Pods. + ServiceAccountName string `json:"serviceAccountName,omitempty"` + + // Secrets is a list of Secrets in the same namespace as the Prometheus + // object, which shall be mounted into the Prometheus Pods. + // Each Secret is added to the StatefulSet definition as a volume named `secret-`. + // The Secrets are mounted into /etc/prometheus/secrets/ in the 'prometheus' container. + Secrets []string `json:"secrets,omitempty"` + // ConfigMaps is a list of ConfigMaps in the same namespace as the Prometheus + // object, which shall be mounted into the Prometheus Pods. + // Each ConfigMap is added to the StatefulSet definition as a volume named `configmap-`. + // The ConfigMaps are mounted into /etc/prometheus/configmaps/ in the 'prometheus' container. + ConfigMaps []string `json:"configMaps,omitempty"` + + // Defines the Pods' affinity scheduling rules if specified. + // +optional + Affinity *v1.Affinity `json:"affinity,omitempty"` + // Defines the Pods' tolerations if specified. + // +optional + Tolerations []v1.Toleration `json:"tolerations,omitempty"` + // Defines the pod's topology spread constraints if specified. + //+optional + TopologySpreadConstraints []v1.TopologySpreadConstraint `json:"topologySpreadConstraints,omitempty"` + + // Defines the list of remote write configurations. + // +optional + RemoteWrite []RemoteWriteSpec `json:"remoteWrite,omitempty"` + + // SecurityContext holds pod-level security attributes and common container settings. + // This defaults to the default PodSecurityContext. + // +optional + SecurityContext *v1.PodSecurityContext `json:"securityContext,omitempty"` + + // When true, the Prometheus server listens on the loopback address + // instead of the Pod IP's address. + ListenLocal bool `json:"listenLocal,omitempty"` + + // Containers allows injecting additional containers or modifying operator + // generated containers. This can be used to allow adding an authentication + // proxy to the Pods or to change the behavior of an operator generated + // container. Containers described here modify an operator generated + // container if they share the same name and modifications are done via a + // strategic merge patch. + // + // The names of containers managed by the operator are: + // * `prometheus` + // * `config-reloader` + // * `thanos-sidecar` + // + // Overriding containers is entirely outside the scope of what the + // maintainers will support and by doing so, you accept that this behaviour + // may break at any time without notice. + // +optional + Containers []v1.Container `json:"containers,omitempty"` + // InitContainers allows injecting initContainers to the Pod definition. Those + // can be used to e.g. fetch secrets for injection into the Prometheus + // configuration from external sources. Any errors during the execution of + // an initContainer will lead to a restart of the Pod. More info: + // https://kubernetes.io/docs/concepts/workloads/pods/init-containers/ + // InitContainers described here modify an operator generated init + // containers if they share the same name and modifications are done via a + // strategic merge patch. + // + // The names of init container name managed by the operator are: + // * `init-config-reloader`. + // + // Overriding init containers is entirely outside the scope of what the + // maintainers will support and by doing so, you accept that this behaviour + // may break at any time without notice. + // +optional + InitContainers []v1.Container `json:"initContainers,omitempty"` + + // AdditionalScrapeConfigs allows specifying a key of a Secret containing + // additional Prometheus scrape configurations. Scrape configurations + // specified are appended to the configurations generated by the Prometheus + // Operator. Job configurations specified must have the form as specified + // in the official Prometheus documentation: + // https://prometheus.io/docs/prometheus/latest/configuration/configuration/#scrape_config. + // As scrape configs are appended, the user is responsible to make sure it + // is valid. Note that using this feature may expose the possibility to + // break upgrades of Prometheus. It is advised to review Prometheus release + // notes to ensure that no incompatible scrape configs are going to break + // Prometheus after the upgrade. + // +optional + AdditionalScrapeConfigs *v1.SecretKeySelector `json:"additionalScrapeConfigs,omitempty"` + + // APIServerConfig allows specifying a host and auth methods to access the + // Kuberntees API server. + // If null, Prometheus is assumed to run inside of the cluster: it will + // discover the API servers automatically and use the Pod's CA certificate + // and bearer token file at /var/run/secrets/kubernetes.io/serviceaccount/. + // +optional + APIServerConfig *APIServerConfig `json:"apiserverConfig,omitempty"` + + // Priority class assigned to the Pods. + PriorityClassName string `json:"priorityClassName,omitempty"` + // Port name used for the pods and governing service. + // Default: "web" + // +kubebuilder:default:="web" + PortName string `json:"portName,omitempty"` + + // When true, ServiceMonitor, PodMonitor and Probe object are forbidden to + // reference arbitrary files on the file system of the 'prometheus' + // container. + // When a ServiceMonitor's endpoint specifies a `bearerTokenFile` value + // (e.g. '/var/run/secrets/kubernetes.io/serviceaccount/token'), a + // malicious target can get access to the Prometheus service account's + // token in the Prometheus' scrape request. Setting + // `spec.arbitraryFSAccessThroughSM` to 'true' would prevent the attack. + // Users should instead provide the credentials using the + // `spec.bearerTokenSecret` field. + ArbitraryFSAccessThroughSMs ArbitraryFSAccessThroughSMsConfig `json:"arbitraryFSAccessThroughSMs,omitempty"` + + // When true, Prometheus resolves label conflicts by renaming the labels in + // the scraped data to "exported_