1
0
Fork 0
mirror of https://github.com/prometheus-operator/prometheus-operator.git synced 2025-04-15 16:56:24 +00:00

*: Rename RuleFile to PrometheusRule

This commit is contained in:
Frederic Branczyk 2018-06-05 13:09:13 +02:00
parent 5eb0b7414b
commit fb32e57837
No known key found for this signature in database
GPG key ID: 7741A52782A90069
36 changed files with 854 additions and 508 deletions

View file

@ -16,7 +16,7 @@ jobs:
# Build Prometheus config reloader
- script: cd contrib/prometheus-config-reloader && make build
# Build Prometheus Operator rule config map to rule file crds cli tool
- script: cd cmd/po-rule-cm-to-rule-file-crds && go install
- script: cd cmd/po-rule-migration && go install
# Ensure vendor folder matches vendor.json
- script: ./scripts/golang-dep-ensure.sh
# Unit tests

View file

@ -21,15 +21,15 @@ This Document documents the types introduced by the Prometheus Operator to be co
* [NamespaceSelector](#namespaceselector)
* [Prometheus](#prometheus)
* [PrometheusList](#prometheuslist)
* [PrometheusRule](#prometheusrule)
* [PrometheusRuleList](#prometheusrulelist)
* [PrometheusRuleSpec](#prometheusrulespec)
* [PrometheusSpec](#prometheusspec)
* [PrometheusStatus](#prometheusstatus)
* [RelabelConfig](#relabelconfig)
* [RemoteReadSpec](#remotereadspec)
* [RemoteWriteSpec](#remotewritespec)
* [Rule](#rule)
* [RuleFile](#rulefile)
* [RuleFileList](#rulefilelist)
* [RuleFileSpec](#rulefilespec)
* [RuleGroup](#rulegroup)
* [ServiceMonitor](#servicemonitor)
* [ServiceMonitorList](#servicemonitorlist)
@ -195,6 +195,38 @@ PrometheusList is a list of Prometheuses.
[Back to TOC](#table-of-contents)
## PrometheusRule
PrometheusRule defines alerting rules for a Prometheus instance
| Field | Description | Scheme | Required |
| ----- | ----------- | ------ | -------- |
| metadata | Standard objects metadata. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata | [metav1.ObjectMeta](https://v1-6.docs.kubernetes.io/docs/api-reference/v1.6/#objectmeta-v1-meta) | false |
| spec | Specification of desired alerting rule definitions for Prometheus. | [PrometheusRuleSpec](#prometheusrulespec) | true |
[Back to TOC](#table-of-contents)
## PrometheusRuleList
A list of PrometheusRules.
| Field | Description | Scheme | Required |
| ----- | ----------- | ------ | -------- |
| metadata | Standard list metadata More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata | [metav1.ListMeta](https://v1-6.docs.kubernetes.io/docs/api-reference/v1.6/#listmeta-v1-meta) | false |
| items | List of Rules | []*[PrometheusRule](#prometheusrule) | true |
[Back to TOC](#table-of-contents)
## PrometheusRuleSpec
PrometheusRuleSpec contains specification parameters for a Rule.
| Field | Description | Scheme | Required |
| ----- | ----------- | ------ | -------- |
| groups | Content of Prometheus rule file | [][RuleGroup](#rulegroup) | false |
[Back to TOC](#table-of-contents)
## PrometheusSpec
Specification of the desired behavior of the Prometheus cluster. More info: https://github.com/kubernetes/community/blob/master/contributors/devel/api-conventions.md#spec-and-status
@ -217,9 +249,9 @@ Specification of the desired behavior of the Prometheus cluster. More info: http
| externalUrl | The external URL the Prometheus instances will be available under. This is necessary to generate correct URLs. This is necessary if Prometheus is not served from root of a DNS name. | string | false |
| routePrefix | The route prefix Prometheus 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`. | string | false |
| storage | Storage spec to specify how storage shall be used. | *[StorageSpec](#storagespec) | false |
| ruleFileSelector | A selector to select which RuleFiles to mount for loading alerting rules from. | *[metav1.LabelSelector](https://v1-6.docs.kubernetes.io/docs/api-reference/v1.6/#labelselector-v1-meta) | false |
| ruleSelector | DEPRECATED with Prometheus Operator 'v0.20.0'. Any value in this field will just be copied to 'RuleFileSelector' field | *[metav1.LabelSelector](https://v1-6.docs.kubernetes.io/docs/api-reference/v1.6/#labelselector-v1-meta) | false |
| ruleFileNamespaceSelector | Namespaces to be selected for RuleFiles discovery. If empty, only check own namespace. | *[metav1.LabelSelector](https://v1-6.docs.kubernetes.io/docs/api-reference/v1.6/#labelselector-v1-meta) | false |
| prometheusRuleSelector | A selector to select which PrometheusRules to mount for loading alerting rules from. | *[metav1.LabelSelector](https://v1-6.docs.kubernetes.io/docs/api-reference/v1.6/#labelselector-v1-meta) | false |
| ruleSelector | DEPRECATED with Prometheus Operator 'v0.20.0'. Any value in this field will just be copied to 'PrometheusRuleSelector' field | *[metav1.LabelSelector](https://v1-6.docs.kubernetes.io/docs/api-reference/v1.6/#labelselector-v1-meta) | false |
| ruleNamespaceSelector | Namespaces to be selected for PrometheusRules discovery. If empty, only check own namespace. | *[metav1.LabelSelector](https://v1-6.docs.kubernetes.io/docs/api-reference/v1.6/#labelselector-v1-meta) | false |
| alerting | Define details regarding alerting. | *[AlertingSpec](#alertingspec) | false |
| resources | Define resources requests and limits for single Pods. | [v1.ResourceRequirements](https://v1-6.docs.kubernetes.io/docs/api-reference/v1.6/#resourcerequirements-v1-core) | false |
| nodeSelector | Define which Nodes the Pods are scheduled on. | map[string]string | false |
@ -317,38 +349,6 @@ Rule describes an alerting or recording rule.
[Back to TOC](#table-of-contents)
## RuleFile
RuleFile defines alerting rules for a Prometheus instance
| Field | Description | Scheme | Required |
| ----- | ----------- | ------ | -------- |
| metadata | Standard objects metadata. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata | [metav1.ObjectMeta](https://v1-6.docs.kubernetes.io/docs/api-reference/v1.6/#objectmeta-v1-meta) | false |
| spec | Specification of desired alerting rule definitions for Prometheus. | [RuleFileSpec](#rulefilespec) | true |
[Back to TOC](#table-of-contents)
## RuleFileList
A list of RuleFiles.
| Field | Description | Scheme | Required |
| ----- | ----------- | ------ | -------- |
| metadata | Standard list metadata More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata | [metav1.ListMeta](https://v1-6.docs.kubernetes.io/docs/api-reference/v1.6/#listmeta-v1-meta) | false |
| items | List of Rules | []*[RuleFile](#rulefile) | true |
[Back to TOC](#table-of-contents)
## RuleFileSpec
RuleFileSpec contains specification parameters for a Rule.
| Field | Description | Scheme | Required |
| ----- | ----------- | ------ | -------- |
| groups | Content of Prometheus rule file | [][RuleGroup](#rulegroup) | false |
[Back to TOC](#table-of-contents)
## RuleGroup
RuleGroup is a list of sequentially evaluated recording and alerting rules.

View file

@ -34,7 +34,7 @@ rules:
- prometheuses/finalizers
- alertmanagers/finalizers
- servicemonitors
- rulefiles
- prometheusrules
verbs:
- "*"
- apiGroups:

View file

@ -48,7 +48,7 @@ rules:
- prometheuses/finalizers
- alertmanagers/finalizers
- servicemonitors
- rulefiles
- prometheusrules
verbs:
- "*"
- apiGroups:

View file

@ -128,6 +128,6 @@ generate-crd: generate-openapi po-crdgen
po-crdgen prometheus > example/prometheus-operator-crd/prometheus.crd.yaml
po-crdgen alertmanager > example/prometheus-operator-crd/alertmanager.crd.yaml
po-crdgen servicemonitor > example/prometheus-operator-crd/servicemonitor.crd.yaml
po-crdgen rulefile > example/prometheus-operator-crd/rulefile.crd.yaml
po-crdgen prometheusrule > example/prometheus-operator-crd/prometheusrule.crd.yaml
.PHONY: all build crossbuild test format check-license container e2e-test e2e-status e2e clean-e2e embedmd apidocgen docs generate-crd jb

View file

@ -30,7 +30,7 @@ rules:
- prometheuses/finalizers
- alertmanagers/finalizers
- servicemonitors
- rulefiles
- prometheusrules
verbs:
- "*"
- apiGroups:

View file

@ -17,11 +17,12 @@ package main
import (
"flag"
"fmt"
"os"
crdutils "github.com/ant31/crd-validation/pkg"
monitoringv1 "github.com/coreos/prometheus-operator/pkg/client/monitoring/v1"
k8sutil "github.com/coreos/prometheus-operator/pkg/k8sutil"
extensionsobj "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1"
"os"
)
var (
@ -45,7 +46,7 @@ func initFlags(crdkind monitoringv1.CrdKind, flagset *flag.FlagSet) *flag.FlagSe
func init() {
var command *flag.FlagSet
if len(os.Args) == 1 {
fmt.Println("usage: po-crdgen [prometheus | alertmanager | servicemonitor | rulefile] [<options>]")
fmt.Println("usage: po-crdgen [prometheus | alertmanager | servicemonitor | prometheusrule] [<options>]")
os.Exit(1)
}
switch os.Args[1] {
@ -55,10 +56,10 @@ func init() {
command = initFlags(monitoringv1.DefaultCrdKinds.ServiceMonitor, flag.NewFlagSet("servicemonitor", flag.ExitOnError))
case "alertmanager":
command = initFlags(monitoringv1.DefaultCrdKinds.Alertmanager, flag.NewFlagSet("alertmanager", flag.ExitOnError))
case "rulefile":
command = initFlags(monitoringv1.DefaultCrdKinds.RuleFile, flag.NewFlagSet("rulefile", flag.ExitOnError))
case "prometheusrule":
command = initFlags(monitoringv1.DefaultCrdKinds.PrometheusRule, flag.NewFlagSet("prometheusrule", flag.ExitOnError))
default:
fmt.Printf("%q is not valid command.\n choices: [prometheus, alertmanager, servicemonitor, rulefile]", os.Args[1])
fmt.Printf("%q is not valid command.\n choices: [prometheus, alertmanager, servicemonitor, prometheusrule]", os.Args[1])
os.Exit(2)
}
command.Parse(os.Args[2:])

View file

@ -65,7 +65,7 @@ func main() {
log.Fatalf("failed to decode manifest: %v", err.Error())
}
ruleFiles, err := prometheus.CMToRuleFiles(&configMap)
ruleFiles, err := prometheus.CMToRule(&configMap)
if err != nil {
log.Fatalf("failed to transform config map to rule file crds: %v", err.Error())
}

View file

@ -11,7 +11,7 @@ crdtojsonnet:
cat ../../example/prometheus-operator-crd/alertmanager.crd.yaml | gojsontoyaml -yamltojson > jsonnet/kube-prometheus/prometheus-operator/alertmanager-crd.libsonnet
cat ../../example/prometheus-operator-crd/prometheus.crd.yaml | gojsontoyaml -yamltojson > jsonnet/kube-prometheus/prometheus-operator/prometheus-crd.libsonnet
cat ../../example/prometheus-operator-crd/servicemonitor.crd.yaml | gojsontoyaml -yamltojson > jsonnet/kube-prometheus/prometheus-operator/servicemonitor-crd.libsonnet
cat ../../example/prometheus-operator-crd/rulefile.crd.yaml | gojsontoyaml -yamltojson > jsonnet/kube-prometheus/prometheus-operator/rulefile-crd.libsonnet
cat ../../example/prometheus-operator-crd/prometheusrule.crd.yaml | gojsontoyaml -yamltojson > jsonnet/kube-prometheus/prometheus-operator/prometheusrule-crd.libsonnet
generate-raw: crdtojsonnet fmt
jb install

View file

@ -21,6 +21,7 @@ local k = import 'ksonnet/ksonnet.beta.3/k.libsonnet';
'0alertmanagerCustomResourceDefinition': import 'alertmanager-crd.libsonnet',
'0prometheusCustomResourceDefinition': import 'prometheus-crd.libsonnet',
'0servicemonitorCustomResourceDefinition': import 'servicemonitor-crd.libsonnet',
'0prometheusruleCustomResourceDefinition': import 'prometheusrule-crd.libsonnet',
clusterRoleBinding:
local clusterRoleBinding = k.rbac.v1.clusterRoleBinding;
@ -51,7 +52,7 @@ local k = import 'ksonnet/ksonnet.beta.3/k.libsonnet';
'prometheuses/finalizers',
'alertmanagers/finalizers',
'servicemonitors',
'rulefiles',
'prometheusrules',
]) +
policyRule.withVerbs(['*']);

File diff suppressed because one or more lines are too long

View file

@ -42,7 +42,7 @@ local k = import 'ksonnet/ksonnet.beta.3/k.libsonnet';
rules:
{
apiVersion: 'monitoring.coreos.com/v1',
kind: 'RuleFile',
kind: 'PrometheusRule',
metadata: {
labels: {
prometheus: $._config.prometheus.name,

View file

@ -1662,6 +1662,48 @@ spec:
Populated by the system. Read-only. More info: http://kubernetes.io/docs/user-guide/identifiers#uids
type: string
prometheusRuleSelector:
description: A label selector is a label query over a set of resources.
The result of matchLabels and matchExpressions are ANDed. An empty
label selector matches all objects. A null label selector matches
no objects.
properties:
matchExpressions:
description: matchExpressions is a list of label selector requirements.
The requirements are ANDed.
items:
description: A label selector requirement is a selector that contains
values, a key, and an operator that relates the key and values.
properties:
key:
description: key is the label key that the selector applies
to.
type: string
operator:
description: operator represents a key's relationship to a
set of values. Valid operators are In, NotIn, Exists and
DoesNotExist.
type: string
values:
description: values is an array of string values. If the operator
is In or NotIn, the values array must be non-empty. If the
operator is Exists or DoesNotExist, the values array must
be empty. This array is replaced during a strategic merge
patch.
items:
type: string
type: array
required:
- key
- operator
type: array
matchLabels:
description: matchLabels is a map of {key,value} pairs. A single
{key,value} in the matchLabels map is equivalent to an element
of matchExpressions, whose key field is "key", the operator is
"In", and the values array contains only "value". The requirements
are ANDed.
type: object
remoteRead:
description: If specified, the remote_read spec. This is an experimental
feature, it may change in any upcoming release in a breaking way.
@ -1899,49 +1941,7 @@ spec:
the server serves requests under a different route prefix. For example
for use with `kubectl proxy`.
type: string
ruleFileNamespaceSelector:
description: A label selector is a label query over a set of resources.
The result of matchLabels and matchExpressions are ANDed. An empty
label selector matches all objects. A null label selector matches
no objects.
properties:
matchExpressions:
description: matchExpressions is a list of label selector requirements.
The requirements are ANDed.
items:
description: A label selector requirement is a selector that contains
values, a key, and an operator that relates the key and values.
properties:
key:
description: key is the label key that the selector applies
to.
type: string
operator:
description: operator represents a key's relationship to a
set of values. Valid operators are In, NotIn, Exists and
DoesNotExist.
type: string
values:
description: values is an array of string values. If the operator
is In or NotIn, the values array must be non-empty. If the
operator is Exists or DoesNotExist, the values array must
be empty. This array is replaced during a strategic merge
patch.
items:
type: string
type: array
required:
- key
- operator
type: array
matchLabels:
description: matchLabels is a map of {key,value} pairs. A single
{key,value} in the matchLabels map is equivalent to an element
of matchExpressions, whose key field is "key", the operator is
"In", and the values array contains only "value". The requirements
are ANDed.
type: object
ruleFileSelector:
ruleNamespaceSelector:
description: A label selector is a label query over a set of resources.
The result of matchLabels and matchExpressions are ANDed. An empty
label selector matches all objects. A null label selector matches

View file

@ -0,0 +1,341 @@
apiVersion: apiextensions.k8s.io/v1beta1
kind: CustomResourceDefinition
metadata:
creationTimestamp: null
name: prometheusrules.monitoring.coreos.com
spec:
group: monitoring.coreos.com
names:
kind: PrometheusRule
plural: prometheusrules
scope: Namespaced
validation:
openAPIV3Schema:
description: PrometheusRule defines alerting rules for a Prometheus instance
properties:
apiVersion:
description: 'APIVersion defines the versioned schema of this representation
of an object. Servers should convert recognized schemas to the latest
internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#resources'
type: string
kind:
description: 'Kind is a string value representing the REST resource this
object represents. Servers may infer this from the endpoint the client
submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#types-kinds'
type: string
metadata:
description: ObjectMeta is metadata that all persisted resources must have,
which includes all objects users must create.
properties:
annotations:
description: 'Annotations is an unstructured key value map stored with
a resource that may be set by external tools to store and retrieve
arbitrary metadata. They are not queryable and should be preserved
when modifying objects. More info: http://kubernetes.io/docs/user-guide/annotations'
type: object
clusterName:
description: The name of the cluster which the object belongs to. This
is used to distinguish resources with same name and namespace in different
clusters. This field is not set anywhere right now and apiserver is
going to ignore it if set in create or update request.
type: string
creationTimestamp:
format: date-time
type: string
deletionGracePeriodSeconds:
description: Number of seconds allowed for this object to gracefully
terminate before it will be removed from the system. Only set when
deletionTimestamp is also set. May only be shortened. Read-only.
format: int64
type: integer
deletionTimestamp:
format: date-time
type: string
finalizers:
description: Must be empty before the object is deleted from the registry.
Each entry is an identifier for the responsible component that will
remove the entry from the list. If the deletionTimestamp of the object
is non-nil, entries in this list can only be removed.
items:
type: string
type: array
generateName:
description: |-
GenerateName is an optional prefix, used by the server, to generate a unique name ONLY IF the Name field has not been provided. If this field is used, the name returned to the client will be different than the name passed. This value will also be combined with a unique suffix. The provided value has the same validation rules as the Name field, and may be truncated by the length of the suffix required to make the value unique on the server.
If this field is specified and the generated name exists, the server will NOT return a 409 - instead, it will either return 201 Created or 500 with Reason ServerTimeout indicating a unique name could not be found in the time allotted, and the client should retry (optionally after the time indicated in the Retry-After header).
Applied only if Name is not specified. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#idempotency
type: string
generation:
description: A sequence number representing a specific generation of
the desired state. Populated by the system. Read-only.
format: int64
type: integer
initializers:
description: Initializers tracks the progress of initialization.
properties:
pending:
description: Pending is a list of initializers that must execute
in order before this object is visible. When the last pending
initializer is removed, and no failing result is set, the initializers
struct will be set to nil and the object is considered as initialized
and visible to all clients.
items:
description: Initializer is information about an initializer that
has not yet completed.
properties:
name:
description: name of the process that is responsible for initializing
this object.
type: string
required:
- name
type: array
result:
description: Status is a return value for calls that don't return
other objects.
properties:
apiVersion:
description: 'APIVersion defines the versioned schema of this
representation of an object. Servers should convert recognized
schemas to the latest internal value, and may reject unrecognized
values. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#resources'
type: string
code:
description: Suggested HTTP return code for this status, 0 if
not set.
format: int32
type: integer
details:
description: StatusDetails is a set of additional properties
that MAY be set by the server to provide additional information
about a response. The Reason field of a Status object defines
what attributes will be set. Clients must ignore fields that
do not match the defined type of each attribute, and should
assume that any attribute may be empty, invalid, or under
defined.
properties:
causes:
description: The Causes array includes more details associated
with the StatusReason failure. Not all StatusReasons may
provide detailed causes.
items:
description: StatusCause provides more information about
an api.Status failure, including cases when multiple
errors are encountered.
properties:
field:
description: |-
The field of the resource that has caused this error, as named by its JSON serialization. May include dot and postfix notation for nested attributes. Arrays are zero-indexed. Fields may appear more than once in an array of causes due to fields having multiple errors. Optional.
Examples:
"name" - the field "name" on the current resource
"items[0].name" - the field "name" on the first array entry in "items"
type: string
message:
description: A human-readable description of the cause
of the error. This field may be presented as-is
to a reader.
type: string
reason:
description: A machine-readable description of the
cause of the error. If this value is empty there
is no information available.
type: string
type: array
group:
description: The group attribute of the resource associated
with the status StatusReason.
type: string
kind:
description: 'The kind attribute of the resource associated
with the status StatusReason. On some operations may differ
from the requested resource Kind. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#types-kinds'
type: string
name:
description: The name attribute of the resource associated
with the status StatusReason (when there is a single name
which can be described).
type: string
retryAfterSeconds:
description: If specified, the time in seconds before the
operation should be retried. Some errors may indicate
the client must take an alternate action - for those errors
this field may indicate how long to wait before taking
the alternate action.
format: int32
type: integer
uid:
description: 'UID of the resource. (when there is a single
resource which can be described). More info: http://kubernetes.io/docs/user-guide/identifiers#uids'
type: string
kind:
description: 'Kind is a string value representing the REST resource
this object represents. Servers may infer this from the endpoint
the client submits requests to. Cannot be updated. In CamelCase.
More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#types-kinds'
type: string
message:
description: A human-readable description of the status of this
operation.
type: string
metadata:
description: ListMeta describes metadata that synthetic resources
must have, including lists and various status objects. A resource
may have only one of {ObjectMeta, ListMeta}.
properties:
continue:
description: continue may be set if the user set a limit
on the number of items returned, and indicates that the
server has more data available. The value is opaque and
may be used to issue another request to the endpoint that
served this list to retrieve the next set of available
objects. Continuing a list may not be possible if the
server configuration has changed or more than a few minutes
have passed. The resourceVersion field returned when using
this continue value will be identical to the value in
the first response.
type: string
resourceVersion:
description: 'String that identifies the server''s internal
version of this object that can be used by clients to
determine when objects have changed. Value must be treated
as opaque by clients and passed unmodified back to the
server. Populated by the system. Read-only. More info:
https://git.k8s.io/community/contributors/devel/api-conventions.md#concurrency-control-and-consistency'
type: string
selfLink:
description: selfLink is a URL representing this object.
Populated by the system. Read-only.
type: string
reason:
description: A machine-readable description of why this operation
is in the "Failure" status. If this value is empty there is
no information available. A Reason clarifies an HTTP status
code but does not override it.
type: string
status:
description: 'Status of the operation. One of: "Success" or
"Failure". More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#spec-and-status'
type: string
required:
- pending
labels:
description: 'Map of string keys and values that can be used to organize
and categorize (scope and select) objects. May match selectors of
replication controllers and services. More info: http://kubernetes.io/docs/user-guide/labels'
type: object
name:
description: 'Name must be unique within a namespace. Is required when
creating resources, although some resources may allow a client to
request the generation of an appropriate name automatically. Name
is primarily intended for creation idempotence and configuration definition.
Cannot be updated. More info: http://kubernetes.io/docs/user-guide/identifiers#names'
type: string
namespace:
description: |-
Namespace defines the space within each name must be unique. An empty namespace is equivalent to the "default" namespace, but "default" is the canonical representation. Not all objects are required to be scoped to a namespace - the value of this field for those objects will be empty.
Must be a DNS_LABEL. Cannot be updated. More info: http://kubernetes.io/docs/user-guide/namespaces
type: string
ownerReferences:
description: List of objects depended by this object. If ALL objects
in the list have been deleted, this object will be garbage collected.
If this object is managed by a controller, then an entry in this list
will point to this controller, with the controller field set to true.
There cannot be more than one managing controller.
items:
description: OwnerReference contains enough information to let you
identify an owning object. Currently, an owning object must be in
the same namespace, so there is no namespace field.
properties:
apiVersion:
description: API version of the referent.
type: string
blockOwnerDeletion:
description: If true, AND if the owner has the "foregroundDeletion"
finalizer, then the owner cannot be deleted from the key-value
store until this reference is removed. Defaults to false. To
set this field, a user needs "delete" permission of the owner,
otherwise 422 (Unprocessable Entity) will be returned.
type: boolean
controller:
description: If true, this reference points to the managing controller.
type: boolean
kind:
description: 'Kind of the referent. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#types-kinds'
type: string
name:
description: 'Name of the referent. More info: http://kubernetes.io/docs/user-guide/identifiers#names'
type: string
uid:
description: 'UID of the referent. More info: http://kubernetes.io/docs/user-guide/identifiers#uids'
type: string
required:
- apiVersion
- kind
- name
- uid
type: array
resourceVersion:
description: |-
An opaque value that represents the internal version of this object that can be used by clients to determine when objects have changed. May be used for optimistic concurrency, change detection, and the watch operation on a resource or set of resources. Clients must treat these values as opaque and passed unmodified back to the server. They may only be valid for a particular resource or set of resources.
Populated by the system. Read-only. Value must be treated as opaque by clients and . More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#concurrency-control-and-consistency
type: string
selfLink:
description: SelfLink is a URL representing this object. Populated by
the system. Read-only.
type: string
uid:
description: |-
UID is the unique in time and space value for this object. It is typically generated by the server on successful creation of a resource and is not allowed to change on PUT operations.
Populated by the system. Read-only. More info: http://kubernetes.io/docs/user-guide/identifiers#uids
type: string
spec:
description: PrometheusRuleSpec contains specification parameters for a
Rule.
properties:
groups:
description: Content of Prometheus rule file
items:
description: RuleGroup is a list of sequentially evaluated recording
and alerting rules.
properties:
interval:
type: string
name:
type: string
rules:
items:
description: Rule describes an alerting or recording rule.
properties:
alert:
type: string
annotations:
type: object
expr:
type: string
for:
type: string
labels:
type: object
record:
type: string
required:
- expr
type: array
required:
- name
- rules
type: array
required:
- spec
version: v1
status:
acceptedNames:
kind: ""
plural: ""
conditions: null

View file

@ -17,7 +17,7 @@ rules:
- prometheuses/finalizers
- alertmanagers/finalizers
- servicemonitors
- rulefiles
- prometheusrules
verbs:
- '*'
- apiGroups:

View file

@ -1,5 +1,5 @@
apiVersion: monitoring.coreos.com/v1
kind: RuleFile
kind: PrometheusRule
metadata:
labels:
prometheus: k8s

View file

@ -1663,6 +1663,48 @@ spec:
Populated by the system. Read-only. More info: http://kubernetes.io/docs/user-guide/identifiers#uids
type: string
prometheusRuleSelector:
description: A label selector is a label query over a set of resources.
The result of matchLabels and matchExpressions are ANDed. An empty
label selector matches all objects. A null label selector matches
no objects.
properties:
matchExpressions:
description: matchExpressions is a list of label selector requirements.
The requirements are ANDed.
items:
description: A label selector requirement is a selector that contains
values, a key, and an operator that relates the key and values.
properties:
key:
description: key is the label key that the selector applies
to.
type: string
operator:
description: operator represents a key's relationship to a
set of values. Valid operators are In, NotIn, Exists and
DoesNotExist.
type: string
values:
description: values is an array of string values. If the operator
is In or NotIn, the values array must be non-empty. If the
operator is Exists or DoesNotExist, the values array must
be empty. This array is replaced during a strategic merge
patch.
items:
type: string
type: array
required:
- key
- operator
type: array
matchLabels:
description: matchLabels is a map of {key,value} pairs. A single
{key,value} in the matchLabels map is equivalent to an element
of matchExpressions, whose key field is "key", the operator is
"In", and the values array contains only "value". The requirements
are ANDed.
type: object
remoteRead:
description: If specified, the remote_read spec. This is an experimental
feature, it may change in any upcoming release in a breaking way.
@ -1900,49 +1942,7 @@ spec:
the server serves requests under a different route prefix. For example
for use with `kubectl proxy`.
type: string
ruleFileNamespaceSelector:
description: A label selector is a label query over a set of resources.
The result of matchLabels and matchExpressions are ANDed. An empty
label selector matches all objects. A null label selector matches
no objects.
properties:
matchExpressions:
description: matchExpressions is a list of label selector requirements.
The requirements are ANDed.
items:
description: A label selector requirement is a selector that contains
values, a key, and an operator that relates the key and values.
properties:
key:
description: key is the label key that the selector applies
to.
type: string
operator:
description: operator represents a key's relationship to a
set of values. Valid operators are In, NotIn, Exists and
DoesNotExist.
type: string
values:
description: values is an array of string values. If the operator
is In or NotIn, the values array must be non-empty. If the
operator is Exists or DoesNotExist, the values array must
be empty. This array is replaced during a strategic merge
patch.
items:
type: string
type: array
required:
- key
- operator
type: array
matchLabels:
description: matchLabels is a map of {key,value} pairs. A single
{key,value} in the matchLabels map is equivalent to an element
of matchExpressions, whose key field is "key", the operator is
"In", and the values array contains only "value". The requirements
are ANDed.
type: object
ruleFileSelector:
ruleNamespaceSelector:
description: A label selector is a label query over a set of resources.
The result of matchLabels and matchExpressions are ANDed. An empty
label selector matches all objects. A null label selector matches

View file

@ -3,16 +3,16 @@ apiVersion: apiextensions.k8s.io/v1beta1
kind: CustomResourceDefinition
metadata:
creationTimestamp: null
name: rulefiles.monitoring.coreos.com
name: prometheusrules.monitoring.coreos.com
spec:
group: monitoring.coreos.com
names:
kind: RuleFile
plural: rulefiles
kind: PrometheusRule
plural: prometheusrules
scope: Namespaced
validation:
openAPIV3Schema:
description: RuleFile defines alerting rules for a Prometheus instance
description: PrometheusRule defines alerting rules for a Prometheus instance
properties:
apiVersion:
description: 'APIVersion defines the versioned schema of this representation
@ -296,7 +296,8 @@ spec:
Populated by the system. Read-only. More info: http://kubernetes.io/docs/user-guide/identifiers#uids
type: string
spec:
description: RuleFileSpec contains specification parameters for a Rule.
description: PrometheusRuleSpec contains specification parameters for a
Rule.
properties:
groups:
description: Content of Prometheus rule file

View file

@ -17,7 +17,7 @@ rules:
- prometheuses/finalizers
- alertmanagers/finalizers
- servicemonitors
- rulefiles
- prometheusrules
verbs:
- "*"
- apiGroups:

View file

@ -16,12 +16,13 @@ package v1
import (
"fmt"
"strings"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apimachinery/pkg/runtime/serializer"
"k8s.io/client-go/dynamic"
"k8s.io/client-go/kubernetes/scheme"
"k8s.io/client-go/rest"
"strings"
)
const (
@ -29,7 +30,7 @@ const (
PrometheusKindKey = "prometheus"
AlertManagerKindKey = "alertmanager"
ServiceMonitorKindKey = "servicemonitor"
RuleFileKindKey = "rulefile"
PrometheusRuleKindKey = "prometheusrule"
)
type CrdKind struct {
@ -43,7 +44,7 @@ type CrdKinds struct {
Prometheus CrdKind
Alertmanager CrdKind
ServiceMonitor CrdKind
RuleFile CrdKind
PrometheusRule CrdKind
}
var DefaultCrdKinds CrdKinds = CrdKinds{
@ -51,7 +52,7 @@ var DefaultCrdKinds CrdKinds = CrdKinds{
Prometheus: CrdKind{Plural: PrometheusName, Kind: PrometheusesKind, SpecName: "github.com/coreos/prometheus-operator/pkg/client/monitoring/v1.Prometheus"},
ServiceMonitor: CrdKind{Plural: ServiceMonitorName, Kind: ServiceMonitorsKind, SpecName: "github.com/coreos/prometheus-operator/pkg/client/monitoring/v1.ServiceMonitor"},
Alertmanager: CrdKind{Plural: AlertmanagerName, Kind: AlertmanagersKind, SpecName: "github.com/coreos/prometheus-operator/pkg/client/monitoring/v1.Alertmanager"},
RuleFile: CrdKind{Plural: RuleFileName, Kind: RuleFilesKind, SpecName: "github.com/coreos/prometheus-operator/pkg/client/monitoring/v1.RuleFile"},
PrometheusRule: CrdKind{Plural: PrometheusRuleName, Kind: PrometheusRuleKind, SpecName: "github.com/coreos/prometheus-operator/pkg/client/monitoring/v1.PrometheusRule"},
}
// Implement the flag.Value interface
@ -67,7 +68,7 @@ func (crdkinds *CrdKinds) Set(value string) error {
PrometheusKindKey, PrometheusesKind, PrometheusName,
AlertManagerKindKey, AlertmanagersKind, AlertmanagerName,
ServiceMonitorKindKey, ServiceMonitorsKind, ServiceMonitorName,
RuleFileKindKey, RuleFilesKind, RuleFileName,
PrometheusRuleKindKey, PrometheusRuleKind, PrometheusRuleName,
)
}
splited := strings.Split(value, ",")
@ -82,8 +83,8 @@ func (crdkinds *CrdKinds) Set(value string) error {
(*crdkinds).ServiceMonitor = crdKind
case AlertManagerKindKey:
(*crdkinds).Alertmanager = crdKind
case RuleFileKindKey:
(*crdkinds).RuleFile = crdKind
case PrometheusRuleKindKey:
(*crdkinds).PrometheusRule = crdKind
default:
fmt.Printf("Warning: unknown kind: %s... ignoring", kindKey)
}
@ -100,7 +101,7 @@ type MonitoringV1Interface interface {
PrometheusesGetter
AlertmanagersGetter
ServiceMonitorsGetter
RuleFilesGetter
PrometheusRulesGetter
}
// +k8s:deepcopy-gen=false
@ -122,8 +123,8 @@ func (c *MonitoringV1Client) ServiceMonitors(namespace string) ServiceMonitorInt
return newServiceMonitors(c.restClient, c.dynamicClient, c.crdKinds.ServiceMonitor, namespace)
}
func (c *MonitoringV1Client) RuleFiles(namespace string) RuleFileInterface {
return newRuleFiles(c.restClient, c.dynamicClient, c.crdKinds.RuleFile, namespace)
func (c *MonitoringV1Client) PrometheusRules(namespace string) PrometheusRuleInterface {
return newPrometheusRules(c.restClient, c.dynamicClient, c.crdKinds.PrometheusRule, namespace)
}
func (c *MonitoringV1Client) RESTClient() rest.Interface {

View file

@ -668,6 +668,113 @@ func GetOpenAPIDefinitions(ref common.ReferenceCallback) map[string]common.OpenA
Dependencies: []string{
"github.com/coreos/prometheus-operator/pkg/client/monitoring/v1.Prometheus", "k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta"},
},
"github.com/coreos/prometheus-operator/pkg/client/monitoring/v1.PrometheusRule": {
Schema: spec.Schema{
SchemaProps: spec.SchemaProps{
Description: "PrometheusRule defines alerting rules for a Prometheus instance",
Properties: map[string]spec.Schema{
"kind": {
SchemaProps: spec.SchemaProps{
Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#types-kinds",
Type: []string{"string"},
Format: "",
},
},
"apiVersion": {
SchemaProps: spec.SchemaProps{
Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#resources",
Type: []string{"string"},
Format: "",
},
},
"metadata": {
SchemaProps: spec.SchemaProps{
Description: "Standard objects metadata. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata",
Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta"),
},
},
"spec": {
SchemaProps: spec.SchemaProps{
Description: "Specification of desired alerting rule definitions for Prometheus.",
Ref: ref("github.com/coreos/prometheus-operator/pkg/client/monitoring/v1.PrometheusRuleSpec"),
},
},
},
Required: []string{"spec"},
},
},
Dependencies: []string{
"github.com/coreos/prometheus-operator/pkg/client/monitoring/v1.PrometheusRuleSpec", "k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta"},
},
"github.com/coreos/prometheus-operator/pkg/client/monitoring/v1.PrometheusRuleList": {
Schema: spec.Schema{
SchemaProps: spec.SchemaProps{
Description: "A list of PrometheusRules.",
Properties: map[string]spec.Schema{
"kind": {
SchemaProps: spec.SchemaProps{
Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#types-kinds",
Type: []string{"string"},
Format: "",
},
},
"apiVersion": {
SchemaProps: spec.SchemaProps{
Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#resources",
Type: []string{"string"},
Format: "",
},
},
"metadata": {
SchemaProps: spec.SchemaProps{
Description: "Standard list metadata More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata",
Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta"),
},
},
"items": {
SchemaProps: spec.SchemaProps{
Description: "List of Rules",
Type: []string{"array"},
Items: &spec.SchemaOrArray{
Schema: &spec.Schema{
SchemaProps: spec.SchemaProps{
Ref: ref("github.com/coreos/prometheus-operator/pkg/client/monitoring/v1.PrometheusRule"),
},
},
},
},
},
},
Required: []string{"items"},
},
},
Dependencies: []string{
"github.com/coreos/prometheus-operator/pkg/client/monitoring/v1.PrometheusRule", "k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta"},
},
"github.com/coreos/prometheus-operator/pkg/client/monitoring/v1.PrometheusRuleSpec": {
Schema: spec.Schema{
SchemaProps: spec.SchemaProps{
Description: "PrometheusRuleSpec contains specification parameters for a Rule.",
Properties: map[string]spec.Schema{
"groups": {
SchemaProps: spec.SchemaProps{
Description: "Content of Prometheus rule file",
Type: []string{"array"},
Items: &spec.SchemaOrArray{
Schema: &spec.Schema{
SchemaProps: spec.SchemaProps{
Ref: ref("github.com/coreos/prometheus-operator/pkg/client/monitoring/v1.RuleGroup"),
},
},
},
},
},
},
},
},
Dependencies: []string{
"github.com/coreos/prometheus-operator/pkg/client/monitoring/v1.RuleGroup"},
},
"github.com/coreos/prometheus-operator/pkg/client/monitoring/v1.PrometheusSpec": {
Schema: spec.Schema{
SchemaProps: spec.SchemaProps{
@ -794,21 +901,21 @@ func GetOpenAPIDefinitions(ref common.ReferenceCallback) map[string]common.OpenA
Ref: ref("github.com/coreos/prometheus-operator/pkg/client/monitoring/v1.StorageSpec"),
},
},
"ruleFileSelector": {
"prometheusRuleSelector": {
SchemaProps: spec.SchemaProps{
Description: "A selector to select which RuleFiles to mount for loading alerting rules from.",
Description: "A selector to select which PrometheusRules to mount for loading alerting rules from.",
Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.LabelSelector"),
},
},
"ruleSelector": {
SchemaProps: spec.SchemaProps{
Description: "DEPRECATED with Prometheus Operator 'v0.20.0'. Any value in this field will just be copied to 'RuleFileSelector' field",
Description: "DEPRECATED with Prometheus Operator 'v0.20.0'. Any value in this field will just be copied to 'PrometheusRuleSelector' field",
Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.LabelSelector"),
},
},
"ruleFileNamespaceSelector": {
"ruleNamespaceSelector": {
SchemaProps: spec.SchemaProps{
Description: "Namespaces to be selected for RuleFiles discovery. If empty, only check own namespace.",
Description: "Namespaces to be selected for PrometheusRules discovery. If empty, only check own namespace.",
Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.LabelSelector"),
},
},
@ -1273,113 +1380,6 @@ func GetOpenAPIDefinitions(ref common.ReferenceCallback) map[string]common.OpenA
},
Dependencies: []string{},
},
"github.com/coreos/prometheus-operator/pkg/client/monitoring/v1.RuleFile": {
Schema: spec.Schema{
SchemaProps: spec.SchemaProps{
Description: "RuleFile defines alerting rules for a Prometheus instance",
Properties: map[string]spec.Schema{
"kind": {
SchemaProps: spec.SchemaProps{
Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#types-kinds",
Type: []string{"string"},
Format: "",
},
},
"apiVersion": {
SchemaProps: spec.SchemaProps{
Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#resources",
Type: []string{"string"},
Format: "",
},
},
"metadata": {
SchemaProps: spec.SchemaProps{
Description: "Standard objects metadata. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata",
Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta"),
},
},
"spec": {
SchemaProps: spec.SchemaProps{
Description: "Specification of desired alerting rule definitions for Prometheus.",
Ref: ref("github.com/coreos/prometheus-operator/pkg/client/monitoring/v1.RuleFileSpec"),
},
},
},
Required: []string{"spec"},
},
},
Dependencies: []string{
"github.com/coreos/prometheus-operator/pkg/client/monitoring/v1.RuleFileSpec", "k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta"},
},
"github.com/coreos/prometheus-operator/pkg/client/monitoring/v1.RuleFileList": {
Schema: spec.Schema{
SchemaProps: spec.SchemaProps{
Description: "A list of RuleFiles.",
Properties: map[string]spec.Schema{
"kind": {
SchemaProps: spec.SchemaProps{
Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#types-kinds",
Type: []string{"string"},
Format: "",
},
},
"apiVersion": {
SchemaProps: spec.SchemaProps{
Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#resources",
Type: []string{"string"},
Format: "",
},
},
"metadata": {
SchemaProps: spec.SchemaProps{
Description: "Standard list metadata More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata",
Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta"),
},
},
"items": {
SchemaProps: spec.SchemaProps{
Description: "List of Rules",
Type: []string{"array"},
Items: &spec.SchemaOrArray{
Schema: &spec.Schema{
SchemaProps: spec.SchemaProps{
Ref: ref("github.com/coreos/prometheus-operator/pkg/client/monitoring/v1.RuleFile"),
},
},
},
},
},
},
Required: []string{"items"},
},
},
Dependencies: []string{
"github.com/coreos/prometheus-operator/pkg/client/monitoring/v1.RuleFile", "k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta"},
},
"github.com/coreos/prometheus-operator/pkg/client/monitoring/v1.RuleFileSpec": {
Schema: spec.Schema{
SchemaProps: spec.SchemaProps{
Description: "RuleFileSpec contains specification parameters for a Rule.",
Properties: map[string]spec.Schema{
"groups": {
SchemaProps: spec.SchemaProps{
Description: "Content of Prometheus rule file",
Type: []string{"array"},
Items: &spec.SchemaOrArray{
Schema: &spec.Schema{
SchemaProps: spec.SchemaProps{
Ref: ref("github.com/coreos/prometheus-operator/pkg/client/monitoring/v1.RuleGroup"),
},
},
},
},
},
},
},
},
Dependencies: []string{
"github.com/coreos/prometheus-operator/pkg/client/monitoring/v1.RuleGroup"},
},
"github.com/coreos/prometheus-operator/pkg/client/monitoring/v1.RuleGroup": {
Schema: spec.Schema{
SchemaProps: spec.SchemaProps{

View file

@ -28,35 +28,35 @@ import (
)
const (
RuleFilesKind = "RuleFile"
RuleFileName = "rulefiles"
PrometheusRuleKind = "PrometheusRule"
PrometheusRuleName = "prometheusrules"
)
type RuleFilesGetter interface {
RuleFiles(namespace string) RuleFileInterface
type PrometheusRulesGetter interface {
PrometheusRules(namespace string) PrometheusRuleInterface
}
var _ RuleFileInterface = &rulefiles{}
var _ PrometheusRuleInterface = &prometheusrules{}
type RuleFileInterface interface {
Create(*RuleFile) (*RuleFile, error)
Get(name string, opts metav1.GetOptions) (*RuleFile, error)
Update(*RuleFile) (*RuleFile, error)
type PrometheusRuleInterface interface {
Create(*PrometheusRule) (*PrometheusRule, error)
Get(name string, opts metav1.GetOptions) (*PrometheusRule, error)
Update(*PrometheusRule) (*PrometheusRule, error)
Delete(name string, options *metav1.DeleteOptions) error
List(opts metav1.ListOptions) (runtime.Object, error)
Watch(opts metav1.ListOptions) (watch.Interface, error)
DeleteCollection(dopts *metav1.DeleteOptions, lopts metav1.ListOptions) error
}
type rulefiles struct {
type prometheusrules struct {
restClient rest.Interface
client dynamic.ResourceInterface
crdKind CrdKind
ns string
}
func newRuleFiles(r rest.Interface, c *dynamic.Client, crdKind CrdKind, namespace string) *rulefiles {
return &rulefiles{
func newPrometheusRules(r rest.Interface, c *dynamic.Client, crdKind CrdKind, namespace string) *prometheusrules {
return &prometheusrules{
restClient: r,
client: c.Resource(
&metav1.APIResource{
@ -71,8 +71,8 @@ func newRuleFiles(r rest.Interface, c *dynamic.Client, crdKind CrdKind, namespac
}
}
func (s *rulefiles) Create(o *RuleFile) (*RuleFile, error) {
us, err := UnstructuredFromRuleFile(o)
func (s *prometheusrules) Create(o *PrometheusRule) (*PrometheusRule, error) {
us, err := UnstructuredFromPrometheusRule(o)
if err != nil {
return nil, err
}
@ -82,19 +82,19 @@ func (s *rulefiles) Create(o *RuleFile) (*RuleFile, error) {
return nil, err
}
return RuleFileFromUnstructured(us)
return PrometheusRuleFromUnstructured(us)
}
func (s *rulefiles) Get(name string, opts metav1.GetOptions) (*RuleFile, error) {
func (s *prometheusrules) Get(name string, opts metav1.GetOptions) (*PrometheusRule, error) {
obj, err := s.client.Get(name, opts)
if err != nil {
return nil, err
}
return RuleFileFromUnstructured(obj)
return PrometheusRuleFromUnstructured(obj)
}
func (s *rulefiles) Update(o *RuleFile) (*RuleFile, error) {
us, err := UnstructuredFromRuleFile(o)
func (s *prometheusrules) Update(o *PrometheusRule) (*PrometheusRule, error) {
us, err := UnstructuredFromPrometheusRule(o)
if err != nil {
return nil, err
}
@ -110,14 +110,14 @@ func (s *rulefiles) Update(o *RuleFile) (*RuleFile, error) {
return nil, err
}
return RuleFileFromUnstructured(us)
return PrometheusRuleFromUnstructured(us)
}
func (s *rulefiles) Delete(name string, options *metav1.DeleteOptions) error {
func (s *prometheusrules) Delete(name string, options *metav1.DeleteOptions) error {
return s.client.Delete(name, options)
}
func (s *rulefiles) List(opts metav1.ListOptions) (runtime.Object, error) {
func (s *prometheusrules) List(opts metav1.ListOptions) (runtime.Object, error) {
req := s.restClient.Get().
Namespace(s.ns).
Resource(s.crdKind.Plural)
@ -126,11 +126,11 @@ func (s *rulefiles) List(opts metav1.ListOptions) (runtime.Object, error) {
if err != nil {
return nil, err
}
var sm RuleFileList
var sm PrometheusRuleList
return &sm, json.Unmarshal(b, &sm)
}
func (s *rulefiles) Watch(opts metav1.ListOptions) (watch.Interface, error) {
func (s *prometheusrules) Watch(opts metav1.ListOptions) (watch.Interface, error) {
r, err := s.restClient.Get().
Prefix("watch").
Namespace(s.ns).
@ -139,34 +139,34 @@ func (s *rulefiles) Watch(opts metav1.ListOptions) (watch.Interface, error) {
if err != nil {
return nil, err
}
return watch.NewStreamWatcher(&ruleFileDecoder{
return watch.NewStreamWatcher(&prometheusRuleDecoder{
dec: json.NewDecoder(r),
close: r.Close,
}), nil
}
func (s *rulefiles) DeleteCollection(dopts *metav1.DeleteOptions, lopts metav1.ListOptions) error {
func (s *prometheusrules) DeleteCollection(dopts *metav1.DeleteOptions, lopts metav1.ListOptions) error {
return s.client.DeleteCollection(dopts, lopts)
}
// RuleFileFromUnstructured unmarshals a RuleFile object from dynamic client's unstructured
func RuleFileFromUnstructured(r *unstructured.Unstructured) (*RuleFile, error) {
// PrometheusRuleFromUnstructured unmarshals a PrometheusRule object from dynamic client's unstructured
func PrometheusRuleFromUnstructured(r *unstructured.Unstructured) (*PrometheusRule, error) {
b, err := json.Marshal(r.Object)
if err != nil {
return nil, err
}
var s RuleFile
var s PrometheusRule
if err := json.Unmarshal(b, &s); err != nil {
return nil, err
}
s.TypeMeta.Kind = RuleFilesKind
s.TypeMeta.Kind = PrometheusRuleKind
s.TypeMeta.APIVersion = Group + "/" + Version
return &s, nil
}
// UnstructuredFromRuleFile marshals a RuleFile object into dynamic client's unstructured
func UnstructuredFromRuleFile(s *RuleFile) (*unstructured.Unstructured, error) {
s.TypeMeta.Kind = RuleFilesKind
// UnstructuredFromPrometheusRule marshals a PrometheusRule object into dynamic client's unstructured
func UnstructuredFromPrometheusRule(s *PrometheusRule) (*unstructured.Unstructured, error) {
s.TypeMeta.Kind = PrometheusRuleKind
s.TypeMeta.APIVersion = Group + "/" + Version
b, err := json.Marshal(s)
if err != nil {
@ -179,19 +179,19 @@ func UnstructuredFromRuleFile(s *RuleFile) (*unstructured.Unstructured, error) {
return &r, nil
}
type ruleFileDecoder struct {
type prometheusRuleDecoder struct {
dec *json.Decoder
close func() error
}
func (d *ruleFileDecoder) Close() {
func (d *prometheusRuleDecoder) Close() {
d.close()
}
func (d *ruleFileDecoder) Decode() (action watch.EventType, object runtime.Object, err error) {
func (d *prometheusRuleDecoder) Decode() (action watch.EventType, object runtime.Object, err error) {
var e struct {
Type watch.EventType
Object RuleFile
Object PrometheusRule
}
if err := d.dec.Decode(&e); err != nil {
return watch.Error, nil, err

View file

@ -98,14 +98,15 @@ type PrometheusSpec struct {
RoutePrefix string `json:"routePrefix,omitempty"`
// Storage spec to specify how storage shall be used.
Storage *StorageSpec `json:"storage,omitempty"`
// A selector to select which RuleFiles to mount for loading alerting rules from.
RuleFileSelector *metav1.LabelSelector `json:"ruleFileSelector,omitempty"`
// A selector to select which PrometheusRules to mount for loading alerting
// rules from.
PrometheusRuleSelector *metav1.LabelSelector `json:"prometheusRuleSelector,omitempty"`
// DEPRECATED with Prometheus Operator 'v0.20.0'. Any value in this field
// will just be copied to 'RuleFileSelector' field
// will just be copied to 'PrometheusRuleSelector' field
RuleSelector *metav1.LabelSelector `json:"ruleSelector,omitempty"`
// Namespaces to be selected for RuleFiles discovery. If empty, only
// Namespaces to be selected for PrometheusRules discovery. If empty, only
// check own namespace.
RuleFileNamespaceSelector *metav1.LabelSelector `json:"ruleFileNamespaceSelector,omitempty"`
RuleNamespaceSelector *metav1.LabelSelector `json:"ruleNamespaceSelector,omitempty"`
// Define details regarding alerting.
Alerting *AlertingSpec `json:"alerting,omitempty"`
// Define resources requests and limits for single Pods.
@ -405,31 +406,31 @@ type ServiceMonitorList struct {
Items []*ServiceMonitor `json:"items"`
}
// A list of RuleFiles.
// A list of PrometheusRules.
// +k8s:openapi-gen=true
type RuleFileList struct {
type PrometheusRuleList struct {
metav1.TypeMeta `json:",inline"`
// Standard list metadata
// More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata
metav1.ListMeta `json:"metadata,omitempty"`
// List of Rules
Items []*RuleFile `json:"items"`
Items []*PrometheusRule `json:"items"`
}
// RuleFile defines alerting rules for a Prometheus instance
// PrometheusRule defines alerting rules for a Prometheus instance
// +k8s:openapi-gen=true
type RuleFile struct {
type PrometheusRule struct {
metav1.TypeMeta `json:",inline"`
// Standard objects metadata. More info:
// http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata
metav1.ObjectMeta `json:"metadata,omitempty"`
// Specification of desired alerting rule definitions for Prometheus.
Spec RuleFileSpec `json:"spec"`
Spec PrometheusRuleSpec `json:"spec"`
}
// RuleFileSpec contains specification parameters for a Rule.
// PrometheusRuleSpec contains specification parameters for a Rule.
// +k8s:openapi-gen=true
type RuleFileSpec struct {
type PrometheusRuleSpec struct {
// Content of Prometheus rule file
Groups []RuleGroup `json:"groups,omitempty"`
}
@ -610,10 +611,10 @@ func (l *ServiceMonitorList) DeepCopyObject() runtime.Object {
return l.DeepCopy()
}
func (f *RuleFile) DeepCopyObject() runtime.Object {
func (f *PrometheusRule) DeepCopyObject() runtime.Object {
return f.DeepCopy()
}
func (l *RuleFileList) DeepCopyObject() runtime.Object {
func (l *PrometheusRuleList) DeepCopyObject() runtime.Object {
return l.DeepCopy()
}

View file

@ -274,7 +274,7 @@ func (in *CrdKinds) DeepCopyInto(out *CrdKinds) {
out.Prometheus = in.Prometheus
out.Alertmanager = in.Alertmanager
out.ServiceMonitor = in.ServiceMonitor
out.RuleFile = in.RuleFile
out.PrometheusRule = in.PrometheusRule
return
}
@ -435,6 +435,78 @@ func (in *PrometheusList) DeepCopy() *PrometheusList {
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *PrometheusRule) DeepCopyInto(out *PrometheusRule) {
*out = *in
out.TypeMeta = in.TypeMeta
in.ObjectMeta.DeepCopyInto(&out.ObjectMeta)
in.Spec.DeepCopyInto(&out.Spec)
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PrometheusRule.
func (in *PrometheusRule) DeepCopy() *PrometheusRule {
if in == nil {
return nil
}
out := new(PrometheusRule)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *PrometheusRuleList) DeepCopyInto(out *PrometheusRuleList) {
*out = *in
out.TypeMeta = in.TypeMeta
out.ListMeta = in.ListMeta
if in.Items != nil {
in, out := &in.Items, &out.Items
*out = make([]*PrometheusRule, len(*in))
for i := range *in {
if (*in)[i] == nil {
(*out)[i] = nil
} else {
(*out)[i] = new(PrometheusRule)
(*in)[i].DeepCopyInto((*out)[i])
}
}
}
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PrometheusRuleList.
func (in *PrometheusRuleList) DeepCopy() *PrometheusRuleList {
if in == nil {
return nil
}
out := new(PrometheusRuleList)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *PrometheusRuleSpec) DeepCopyInto(out *PrometheusRuleSpec) {
*out = *in
if in.Groups != nil {
in, out := &in.Groups, &out.Groups
*out = make([]RuleGroup, len(*in))
for i := range *in {
(*in)[i].DeepCopyInto(&(*out)[i])
}
}
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PrometheusRuleSpec.
func (in *PrometheusRuleSpec) DeepCopy() *PrometheusRuleSpec {
if in == nil {
return nil
}
out := new(PrometheusRuleSpec)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *PrometheusSpec) DeepCopyInto(out *PrometheusSpec) {
*out = *in
@ -495,8 +567,8 @@ func (in *PrometheusSpec) DeepCopyInto(out *PrometheusSpec) {
(*in).DeepCopyInto(*out)
}
}
if in.RuleFileSelector != nil {
in, out := &in.RuleFileSelector, &out.RuleFileSelector
if in.PrometheusRuleSelector != nil {
in, out := &in.PrometheusRuleSelector, &out.PrometheusRuleSelector
if *in == nil {
*out = nil
} else {
@ -513,8 +585,8 @@ func (in *PrometheusSpec) DeepCopyInto(out *PrometheusSpec) {
(*in).DeepCopyInto(*out)
}
}
if in.RuleFileNamespaceSelector != nil {
in, out := &in.RuleFileNamespaceSelector, &out.RuleFileNamespaceSelector
if in.RuleNamespaceSelector != nil {
in, out := &in.RuleNamespaceSelector, &out.RuleNamespaceSelector
if *in == nil {
*out = nil
} else {
@ -770,78 +842,6 @@ func (in *Rule) DeepCopy() *Rule {
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *RuleFile) DeepCopyInto(out *RuleFile) {
*out = *in
out.TypeMeta = in.TypeMeta
in.ObjectMeta.DeepCopyInto(&out.ObjectMeta)
in.Spec.DeepCopyInto(&out.Spec)
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new RuleFile.
func (in *RuleFile) DeepCopy() *RuleFile {
if in == nil {
return nil
}
out := new(RuleFile)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *RuleFileList) DeepCopyInto(out *RuleFileList) {
*out = *in
out.TypeMeta = in.TypeMeta
out.ListMeta = in.ListMeta
if in.Items != nil {
in, out := &in.Items, &out.Items
*out = make([]*RuleFile, len(*in))
for i := range *in {
if (*in)[i] == nil {
(*out)[i] = nil
} else {
(*out)[i] = new(RuleFile)
(*in)[i].DeepCopyInto((*out)[i])
}
}
}
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new RuleFileList.
func (in *RuleFileList) DeepCopy() *RuleFileList {
if in == nil {
return nil
}
out := new(RuleFileList)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *RuleFileSpec) DeepCopyInto(out *RuleFileSpec) {
*out = *in
if in.Groups != nil {
in, out := &in.Groups, &out.Groups
*out = make([]RuleGroup, len(*in))
for i := range *in {
(*in)[i].DeepCopyInto(&(*out)[i])
}
}
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new RuleFileSpec.
func (in *RuleFileSpec) DeepCopy() *RuleFileSpec {
if in == nil {
return nil
}
out := new(RuleFileSpec)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *RuleGroup) DeepCopyInto(out *RuleGroup) {
*out = *in

View file

@ -60,13 +60,13 @@ type Operator struct {
crdclient apiextensionsclient.Interface
logger log.Logger
promInf cache.SharedIndexInformer
smonInf cache.SharedIndexInformer
ruleFileInf cache.SharedIndexInformer
cmapInf cache.SharedIndexInformer
secrInf cache.SharedIndexInformer
ssetInf cache.SharedIndexInformer
nsInf cache.SharedIndexInformer
promInf cache.SharedIndexInformer
smonInf cache.SharedIndexInformer
ruleInf cache.SharedIndexInformer
cmapInf cache.SharedIndexInformer
secrInf cache.SharedIndexInformer
ssetInf cache.SharedIndexInformer
nsInf cache.SharedIndexInformer
queue workqueue.RateLimitingInterface
@ -216,14 +216,14 @@ func New(conf Config, logger log.Logger) (*Operator, error) {
UpdateFunc: c.handleSmonUpdate,
})
c.ruleFileInf = cache.NewSharedIndexInformer(
c.ruleInf = cache.NewSharedIndexInformer(
&cache.ListWatch{
ListFunc: mclient.MonitoringV1().RuleFiles(c.config.Namespace).List,
WatchFunc: mclient.MonitoringV1().RuleFiles(c.config.Namespace).Watch,
ListFunc: mclient.MonitoringV1().PrometheusRules(c.config.Namespace).List,
WatchFunc: mclient.MonitoringV1().PrometheusRules(c.config.Namespace).Watch,
},
&monitoringv1.RuleFile{}, resyncPeriod, cache.Indexers{},
&monitoringv1.PrometheusRule{}, resyncPeriod, cache.Indexers{},
)
c.ruleFileInf.AddEventHandler(cache.ResourceEventHandlerFuncs{
c.ruleInf.AddEventHandler(cache.ResourceEventHandlerFuncs{
AddFunc: c.handleRuleAdd,
DeleteFunc: c.handleRuleDelete,
UpdateFunc: c.handleRuleUpdate,
@ -312,7 +312,7 @@ func (c *Operator) Run(stopc <-chan struct{}) error {
go c.promInf.Run(stopc)
go c.smonInf.Run(stopc)
go c.ruleFileInf.Run(stopc)
go c.ruleInf.Run(stopc)
go c.cmapInf.Run(stopc)
go c.secrInf.Run(stopc)
go c.ssetInf.Run(stopc)
@ -731,12 +731,12 @@ func (c *Operator) sync(key string) error {
level.Info(c.logger).Log("msg", "sync prometheus", "key", key)
// TODO: Remove migration with Prometheus Operator v0.21.0
err = c.migrateRuleConfigMapsToRuleFileCRDs(p)
err = c.migrateRuleConfigMapsToRuleCRDs(p)
if err != nil {
return err
}
err = c.createOrUpdateRuleFileConfigMap(p)
err = c.createOrUpdateRuleConfigMap(p)
if err != nil {
return err
}
@ -1108,7 +1108,7 @@ func (c *Operator) createCRDs() error {
crds := []*extensionsobj.CustomResourceDefinition{
k8sutil.NewCustomResourceDefinition(c.config.CrdKinds.Prometheus, c.config.CrdGroup, c.config.Labels.LabelsMap, c.config.EnableValidation),
k8sutil.NewCustomResourceDefinition(c.config.CrdKinds.ServiceMonitor, c.config.CrdGroup, c.config.Labels.LabelsMap, c.config.EnableValidation),
k8sutil.NewCustomResourceDefinition(c.config.CrdKinds.RuleFile, c.config.CrdGroup, c.config.Labels.LabelsMap, c.config.EnableValidation),
k8sutil.NewCustomResourceDefinition(c.config.CrdKinds.PrometheusRule, c.config.CrdGroup, c.config.Labels.LabelsMap, c.config.EnableValidation),
}
crdClient := c.crdclient.ApiextensionsV1beta1().CustomResourceDefinitions()
@ -1139,7 +1139,7 @@ func (c *Operator) createCRDs() error {
}{
{"Prometheus", c.mclient.MonitoringV1().Prometheuses(c.config.Namespace).List},
{"ServiceMonitor", c.mclient.MonitoringV1().ServiceMonitors(c.config.Namespace).List},
{"RuleFile", c.mclient.MonitoringV1().RuleFiles(c.config.Namespace).List},
{"PrometheusRule", c.mclient.MonitoringV1().PrometheusRules(c.config.Namespace).List},
}
for _, crdListFunc := range crdListFuncs {

View file

@ -187,7 +187,7 @@ func generateTestConfig(version string) ([]byte, error) {
"group": "group1",
},
},
RuleFileSelector: &metav1.LabelSelector{
PrometheusRuleSelector: &metav1.LabelSelector{
MatchLabels: map[string]string{
"role": "rulefile",
},

View file

@ -30,7 +30,7 @@ import (
"github.com/pkg/errors"
)
func (c *Operator) migrateRuleConfigMapsToRuleFileCRDs(p *monitoringv1.Prometheus) error {
func (c *Operator) migrateRuleConfigMapsToRuleCRDs(p *monitoringv1.Prometheus) error {
configMaps, err := c.getRuleCMs(p.Namespace, p.Spec.RuleSelector)
if err != nil {
return err
@ -47,32 +47,32 @@ func (c *Operator) migrateRuleConfigMapsToRuleFileCRDs(p *monitoringv1.Prometheu
"prometheus", p.Name,
)
ruleFiles := []monitoringv1.RuleFile{}
rules := []monitoringv1.PrometheusRule{}
for _, cm := range configMaps {
files, err := CMToRuleFiles(cm)
cmRules, err := CMToRule(cm)
if err != nil {
return err
}
ruleFiles = append(ruleFiles, files...)
rules = append(rules, cmRules...)
}
ruleFileNames := []string{}
for _, file := range configMaps {
ruleFileNames = append(ruleFileNames, file.Name)
ruleNames := []string{}
for _, rule := range configMaps {
ruleNames = append(ruleNames, rule.Name)
}
level.Debug(c.logger).Log(
"msg", "rule files to be created",
"rulefiles", strings.Join(ruleFileNames, ","),
"rules", strings.Join(ruleNames, ","),
"namespace", p.Namespace,
"prometheus", p.Name,
)
for _, ruleFile := range ruleFiles {
_, err := c.mclient.MonitoringV1().RuleFiles(p.Namespace).Create(&ruleFile)
for _, rule := range rules {
_, err := c.mclient.MonitoringV1().PrometheusRules(p.Namespace).Create(&rule)
if apierrors.IsAlreadyExists(err) {
level.Debug(c.logger).Log(
"msg", "rule file already exists for configmap key",
"rulefilename", ruleFile.Name,
"rule", rule.Name,
"namespace", p.Namespace,
"prometheus", p.Name,
)
@ -105,26 +105,26 @@ func (c *Operator) getRuleCMs(ns string, cmLabelSelector *metav1.LabelSelector)
return configMaps, nil
}
// CMToRuleFiles takes a rule config map and transforms it to possibly multiple
// CMToRule takes a rule config map and transforms it to possibly multiple
// rule file crds. It is used in `cmd/po-rule-cm-to-rule-file-crds`. Thereby it
// needs to be public.
func CMToRuleFiles(cm *v1.ConfigMap) ([]monitoringv1.RuleFile, error) {
ruleFiles := []monitoringv1.RuleFile{}
func CMToRule(cm *v1.ConfigMap) ([]monitoringv1.PrometheusRule, error) {
rules := []monitoringv1.PrometheusRule{}
for name, content := range cm.Data {
ruleFileSpec := monitoringv1.RuleFileSpec{}
ruleSpec := monitoringv1.PrometheusRuleSpec{}
if err := yaml.NewYAMLOrJSONDecoder(bytes.NewBufferString(content), 1000).Decode(&ruleFileSpec); err != nil {
return []monitoringv1.RuleFile{}, errors.Wrapf(
if err := yaml.NewYAMLOrJSONDecoder(bytes.NewBufferString(content), 1000).Decode(&ruleSpec); err != nil {
return []monitoringv1.PrometheusRule{}, errors.Wrapf(
err,
"unmarshal rules file %v in configmap '%v' in namespace '%v'",
name, cm.Name, cm.Namespace,
)
}
ruleFile := monitoringv1.RuleFile{
rule := monitoringv1.PrometheusRule{
TypeMeta: metav1.TypeMeta{
Kind: monitoringv1.RuleFilesKind,
Kind: monitoringv1.PrometheusRuleKind,
APIVersion: monitoringv1.Group + "/" + monitoringv1.Version,
},
@ -133,11 +133,11 @@ func CMToRuleFiles(cm *v1.ConfigMap) ([]monitoringv1.RuleFile, error) {
Namespace: cm.Namespace,
Labels: cm.Labels,
},
Spec: ruleFileSpec,
Spec: ruleSpec,
}
ruleFiles = append(ruleFiles, ruleFile)
rules = append(rules, rule)
}
return ruleFiles, nil
return rules, nil
}

View file

@ -32,7 +32,7 @@ func TestCMToRuleFiles(t *testing.T) {
t.Fatal(err)
}
_, err = CMToRuleFiles(cm)
_, err = CMToRule(cm)
if err != nil {
t.Fatal(err)
}

View file

@ -32,41 +32,41 @@ import (
"github.com/pkg/errors"
)
func (c *Operator) createOrUpdateRuleFileConfigMap(p *monitoringv1.Prometheus) error {
func (c *Operator) createOrUpdateRuleConfigMap(p *monitoringv1.Prometheus) error {
cClient := c.kclient.CoreV1().ConfigMaps(p.Namespace)
namespaces, err := c.selectRuleFileNamespaces(p)
namespaces, err := c.selectRuleNamespaces(p)
if err != nil {
return err
}
ruleFiles, err := c.selectRuleFiles(p, namespaces)
rules, err := c.selectRules(p, namespaces)
if err != nil {
return err
}
newConfigMap := c.makeRulesConfigMap(p, ruleFiles)
newConfigMap := c.makeRulesConfigMap(p, rules)
currentConfigMap, err := cClient.Get(prometheusRuleFilesConfigMapName(p.Name), metav1.GetOptions{})
currentConfigMap, err := cClient.Get(prometheusRuleConfigMapName(p.Name), metav1.GetOptions{})
if err != nil && !apierrors.IsNotFound(err) {
return err
}
isNotFound := false
if apierrors.IsNotFound(err) {
level.Debug(c.logger).Log(
"msg", "no RuleFiles configmap created yet",
"msg", "no PrometheusRule configmap created yet",
"namespace", p.Namespace,
"prometheus", p.Name,
)
isNotFound = true
}
newChecksum := checksumRuleFiles(ruleFiles)
currentChecksum := checksumRuleFiles(currentConfigMap.Data)
newChecksum := checksumRules(rules)
currentChecksum := checksumRules(currentConfigMap.Data)
if newChecksum == currentChecksum && !isNotFound {
level.Debug(c.logger).Log(
"msg", "no RuleFile changes",
"msg", "no PrometheusRule changes",
"namespace", p.Namespace,
"prometheus", p.Name,
)
@ -75,14 +75,14 @@ func (c *Operator) createOrUpdateRuleFileConfigMap(p *monitoringv1.Prometheus) e
if isNotFound {
level.Debug(c.logger).Log(
"msg", "no RuleFile found, creating new one",
"msg", "no PrometheusRule found, creating new one",
"namespace", p.Namespace,
"prometheus", p.Name,
)
_, err = cClient.Create(newConfigMap)
} else {
level.Debug(c.logger).Log(
"msg", "updating RuleFile",
"msg", "updating PrometheusRule",
"namespace", p.Namespace,
"prometheus", p.Name,
)
@ -95,25 +95,25 @@ func (c *Operator) createOrUpdateRuleFileConfigMap(p *monitoringv1.Prometheus) e
return nil
}
func (c *Operator) selectRuleFileNamespaces(p *monitoringv1.Prometheus) ([]string, error) {
func (c *Operator) selectRuleNamespaces(p *monitoringv1.Prometheus) ([]string, error) {
namespaces := []string{}
// If 'RuleFilesNamespaceSelector' is nil, only check own namespace.
if p.Spec.RuleFileNamespaceSelector == nil {
// If 'RuleNamespaceSelector' is nil, only check own namespace.
if p.Spec.RuleNamespaceSelector == nil {
namespaces = append(namespaces, p.Namespace)
} else {
ruleFileNamespaceSelector, err := metav1.LabelSelectorAsSelector(p.Spec.RuleFileNamespaceSelector)
ruleNamespaceSelector, err := metav1.LabelSelectorAsSelector(p.Spec.RuleNamespaceSelector)
if err != nil {
return namespaces, errors.Wrap(err, "convert rule file namespace label selector to selector")
return namespaces, errors.Wrap(err, "convert rule namespace label selector to selector")
}
cache.ListAll(c.nsInf.GetStore(), ruleFileNamespaceSelector, func(obj interface{}) {
cache.ListAll(c.nsInf.GetStore(), ruleNamespaceSelector, func(obj interface{}) {
namespaces = append(namespaces, obj.(*v1.Namespace).Name)
})
}
level.Debug(c.logger).Log(
"msg", "selected RuleFileNamespaces",
"msg", "selected RuleNamespaces",
"namespaces", strings.Join(namespaces, ","),
"namespace", p.Namespace,
"prometheus", p.Name,
@ -122,31 +122,31 @@ func (c *Operator) selectRuleFileNamespaces(p *monitoringv1.Prometheus) ([]strin
return namespaces, nil
}
func (c *Operator) selectRuleFiles(p *monitoringv1.Prometheus, namespaces []string) (map[string]string, error) {
ruleFiles := map[string]string{}
func (c *Operator) selectRules(p *monitoringv1.Prometheus, namespaces []string) (map[string]string, error) {
rules := map[string]string{}
// With Prometheus Operator v0.20.0 the 'RuleSelector' field in the Prometheus
// CRD Spec is deprecated. Any value in 'RuleSelector' is just copied to the new
// field 'RuleFileSelector'.
if p.Spec.RuleFileSelector == nil && p.Spec.RuleSelector != nil {
p.Spec.RuleFileSelector = p.Spec.RuleSelector
// field 'PrometheusRuleSelector'.
if p.Spec.PrometheusRuleSelector == nil && p.Spec.RuleSelector != nil {
p.Spec.PrometheusRuleSelector = p.Spec.RuleSelector
}
fileSelector, err := metav1.LabelSelectorAsSelector(p.Spec.RuleFileSelector)
ruleSelector, err := metav1.LabelSelectorAsSelector(p.Spec.PrometheusRuleSelector)
if err != nil {
return ruleFiles, errors.Wrap(err, "convert rule file label selector to selector")
return rules, errors.Wrap(err, "convert rule label selector to selector")
}
for _, ns := range namespaces {
var marshalErr error
err := cache.ListAllByNamespace(c.ruleFileInf.GetIndexer(), ns, fileSelector, func(obj interface{}) {
file := obj.(*monitoringv1.RuleFile)
content, err := yaml.Marshal(file.Spec)
err := cache.ListAllByNamespace(c.ruleInf.GetIndexer(), ns, ruleSelector, func(obj interface{}) {
rule := obj.(*monitoringv1.PrometheusRule)
content, err := yaml.Marshal(rule.Spec)
if err != nil {
marshalErr = err
return
}
ruleFiles[fmt.Sprintf("%v-%v.yaml", file.Namespace, file.Name)] = string(content)
rules[fmt.Sprintf("%v-%v.yaml", rule.Namespace, rule.Name)] = string(content)
})
if err != nil {
return nil, err
@ -156,32 +156,32 @@ func (c *Operator) selectRuleFiles(p *monitoringv1.Prometheus, namespaces []stri
}
}
// sort ruleFiles map
filenames := []string{}
for k := range ruleFiles {
filenames = append(filenames, k)
// sort rules map
rulenames := []string{}
for k := range rules {
rulenames = append(rulenames, k)
}
sort.Strings(filenames)
sortedRuleFiles := map[string]string{}
for _, name := range filenames {
sortedRuleFiles[name] = ruleFiles[name]
sort.Strings(rulenames)
sortedRules := map[string]string{}
for _, name := range rulenames {
sortedRules[name] = rules[name]
}
level.Debug(c.logger).Log(
"msg", "selected RuleFiles",
"rulefiles", strings.Join(filenames, ","),
"msg", "selected Rules",
"rules", strings.Join(rulenames, ","),
"namespace", p.Namespace,
"prometheus", p.Name,
)
return sortedRuleFiles, nil
return sortedRules, nil
}
func (c *Operator) makeRulesConfigMap(p *monitoringv1.Prometheus, ruleFiles map[string]string) *v1.ConfigMap {
boolTrue := true
return &v1.ConfigMap{
ObjectMeta: metav1.ObjectMeta{
Name: prometheusRuleFilesConfigMapName(p.Name),
Name: prometheusRuleConfigMapName(p.Name),
Labels: managedByOperatorLabels,
OwnerReferences: []metav1.OwnerReference{
{
@ -198,7 +198,7 @@ func (c *Operator) makeRulesConfigMap(p *monitoringv1.Prometheus, ruleFiles map[
}
}
func checksumRuleFiles(files map[string]string) string {
func checksumRules(files map[string]string) string {
var sum string
for name, value := range files {
sum = sum + name + value
@ -207,6 +207,6 @@ func checksumRuleFiles(files map[string]string) string {
return fmt.Sprintf("%x", sha256.Sum256([]byte(sum)))
}
func prometheusRuleFilesConfigMapName(prometheusName string) string {
func prometheusRuleConfigMapName(prometheusName string) string {
return "prometheus-" + prometheusName + "-rulefiles"
}

View file

@ -410,7 +410,7 @@ func makeStatefulSetSpec(p monitoringv1.Prometheus, c *Config) (*appsv1.Stateful
VolumeSource: v1.VolumeSource{
ConfigMap: &v1.ConfigMapVolumeSource{
LocalObjectReference: v1.LocalObjectReference{
Name: prometheusRuleFilesConfigMapName(p.Name),
Name: prometheusRuleConfigMapName(p.Name),
},
},
},

View file

@ -424,7 +424,7 @@ inhibit_rules:
p.Spec.EvaluationInterval = "100ms"
framework.AddAlertingToPrometheus(p, ns, alertmanager.Name)
_, err = framework.MakeAndCreateFiringRuleFile(ns, p.Name, alertName)
_, err = framework.MakeAndCreateFiringRule(ns, p.Name, alertName)
if err != nil {
t.Fatal(err)
}

View file

@ -423,7 +423,7 @@ func TestPrometheusReloadRules(t *testing.T) {
firtAlertName := "firstAlert"
secondAlertName := "secondAlert"
ruleFile, err := framework.MakeAndCreateFiringRuleFile(ns, name, firtAlertName)
ruleFile, err := framework.MakeAndCreateFiringRule(ns, name, firtAlertName)
if err != nil {
t.Fatal(err)
}
@ -457,7 +457,7 @@ func TestPrometheusReloadRules(t *testing.T) {
},
},
}
err = framework.UpdateRuleFile(ns, ruleFile)
err = framework.UpdateRule(ns, ruleFile)
if err != nil {
t.Fatal(err)
}
@ -483,7 +483,7 @@ func TestPrometheusDeprecatedRuleSelectorField(t *testing.T) {
name := "test"
firtAlertName := "firstAlert"
_, err := framework.MakeAndCreateFiringRuleFile(ns, name, firtAlertName)
_, err := framework.MakeAndCreateFiringRule(ns, name, firtAlertName)
if err != nil {
t.Fatal(err)
}
@ -491,7 +491,7 @@ func TestPrometheusDeprecatedRuleSelectorField(t *testing.T) {
p := framework.MakeBasicPrometheus(ns, name, name, 1)
p.Spec.EvaluationInterval = "1s"
// Reset new 'RuleFileSelector' field
p.Spec.RuleFileSelector = nil
p.Spec.PrometheusRuleSelector = nil
// Specify old 'RuleFile' field
p.Spec.RuleSelector = &metav1.LabelSelector{
MatchLabels: map[string]string{
@ -548,7 +548,7 @@ groups:
p := framework.MakeBasicPrometheus(ns, name, name, 1)
// Reset new 'RuleFileSelector' field
p.Spec.RuleFileSelector = nil
p.Spec.PrometheusRuleSelector = nil
// Specify old 'RuleFile' field
p.Spec.RuleSelector = &metav1.LabelSelector{
MatchLabels: map[string]string{
@ -566,7 +566,7 @@ groups:
ctx.AddFinalizerFn(finalizerFn)
}
if err := framework.WaitForRuleFile(ns, cm.Name+"-"+ruleFileName); err != nil {
if err := framework.WaitForRule(ns, cm.Name+"-"+ruleFileName); err != nil {
t.Fatalf("waiting for rule config map to be converted to rule file crd: %v", err)
}
@ -587,7 +587,7 @@ func TestPrometheusMultipleRuleFilesSameNS(t *testing.T) {
alertNames := []string{"first-alert", "second-alert"}
for _, alertName := range alertNames {
_, err := framework.MakeAndCreateFiringRuleFile(ns, alertName, alertName)
_, err := framework.MakeAndCreateFiringRule(ns, alertName, alertName)
if err != nil {
t.Fatal(err)
}
@ -637,7 +637,7 @@ func TestPrometheusMultipleRuleFilesDifferentNS(t *testing.T) {
}
for _, file := range ruleFiles {
_, err := framework.MakeAndCreateFiringRuleFile(file.ns, file.alertName, file.alertName)
_, err := framework.MakeAndCreateFiringRule(file.ns, file.alertName, file.alertName)
if err != nil {
t.Fatal(err)
}
@ -645,7 +645,7 @@ func TestPrometheusMultipleRuleFilesDifferentNS(t *testing.T) {
p := framework.MakeBasicPrometheus(rootNS, name, name, 1)
p.Spec.EvaluationInterval = "1s"
p.Spec.RuleFileNamespaceSelector = &metav1.LabelSelector{
p.Spec.RuleNamespaceSelector = &metav1.LabelSelector{
MatchLabels: ruleFilesNamespaceSelector,
}
if err := framework.CreatePrometheusAndWaitUntilReady(rootNS, p); err != nil {

View file

@ -48,7 +48,7 @@ func (f *Framework) MakeBasicPrometheus(ns, name, group string, replicas int32)
},
},
ServiceAccountName: "prometheus",
RuleFileSelector: &metav1.LabelSelector{
PrometheusRuleSelector: &metav1.LabelSelector{
MatchLabels: map[string]string{
"role": "rulefile",
},

View file

@ -24,8 +24,8 @@ import (
"k8s.io/apimachinery/pkg/util/wait"
)
func (f *Framework) MakeBasicRuleFile(ns, name string, groups []monitoringv1.RuleGroup) monitoringv1.RuleFile {
return monitoringv1.RuleFile{
func (f *Framework) MakeBasicRule(ns, name string, groups []monitoringv1.RuleGroup) monitoringv1.PrometheusRule {
return monitoringv1.PrometheusRule{
ObjectMeta: metav1.ObjectMeta{
Name: name,
Namespace: ns,
@ -33,14 +33,14 @@ func (f *Framework) MakeBasicRuleFile(ns, name string, groups []monitoringv1.Rul
"role": "rulefile",
},
},
Spec: monitoringv1.RuleFileSpec{
Spec: monitoringv1.PrometheusRuleSpec{
Groups: groups,
},
}
}
func (f *Framework) CreateRuleFile(ns string, ar monitoringv1.RuleFile) error {
_, err := f.MonClientV1.RuleFiles(ns).Create(&ar)
func (f *Framework) CreateRule(ns string, ar monitoringv1.PrometheusRule) error {
_, err := f.MonClientV1.PrometheusRules(ns).Create(&ar)
if err != nil {
return fmt.Errorf("creating %v RuleFile failed: %v", ar.Name, err)
}
@ -48,7 +48,7 @@ func (f *Framework) CreateRuleFile(ns string, ar monitoringv1.RuleFile) error {
return nil
}
func (f *Framework) MakeAndCreateFiringRuleFile(ns, name, alertName string) (monitoringv1.RuleFile, error) {
func (f *Framework) MakeAndCreateFiringRule(ns, name, alertName string) (monitoringv1.PrometheusRule, error) {
groups := []monitoringv1.RuleGroup{
monitoringv1.RuleGroup{
Name: alertName,
@ -60,9 +60,9 @@ func (f *Framework) MakeAndCreateFiringRuleFile(ns, name, alertName string) (mon
},
},
}
file := f.MakeBasicRuleFile(ns, name, groups)
file := f.MakeBasicRule(ns, name, groups)
err := f.CreateRuleFile(ns, file)
err := f.CreateRule(ns, file)
if err != nil {
return file, err
}
@ -70,11 +70,11 @@ func (f *Framework) MakeAndCreateFiringRuleFile(ns, name, alertName string) (mon
return file, nil
}
// WaitForRuleFile waits for a rule file with a given name to exist in a given
// WaitForRule waits for a rule file with a given name to exist in a given
// namespace.
func (f *Framework) WaitForRuleFile(ns, name string) error {
func (f *Framework) WaitForRule(ns, name string) error {
return wait.Poll(time.Second, f.DefaultTimeout, func() (bool, error) {
_, err := f.MonClientV1.RuleFiles(ns).Get(name, metav1.GetOptions{})
_, err := f.MonClientV1.PrometheusRules(ns).Get(name, metav1.GetOptions{})
if apierrors.IsNotFound(err) {
return false, nil
} else if err != nil {
@ -84,8 +84,8 @@ func (f *Framework) WaitForRuleFile(ns, name string) error {
})
}
func (f *Framework) UpdateRuleFile(ns string, ar monitoringv1.RuleFile) error {
_, err := f.MonClientV1.RuleFiles(ns).Update(&ar)
func (f *Framework) UpdateRule(ns string, ar monitoringv1.PrometheusRule) error {
_, err := f.MonClientV1.PrometheusRules(ns).Update(&ar)
if err != nil {
return fmt.Errorf("updating %v RuleFile failed: %v", ar.Name, err)
}