-
Notifications
You must be signed in to change notification settings - Fork 3.8k
Expand file tree
/
Copy pathoperator.go
More file actions
360 lines (306 loc) · 11.5 KB
/
operator.go
File metadata and controls
360 lines (306 loc) · 11.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
// Copyright The prometheus-operator Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package prometheus
import (
"context"
"fmt"
"log/slog"
"reflect"
"strconv"
"strings"
"time"
"github.com/google/uuid"
appsv1 "k8s.io/api/apps/v1"
corev1 "k8s.io/api/core/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/util/sets"
"k8s.io/client-go/kubernetes"
"k8s.io/utils/ptr"
monitoringv1 "github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1"
"github.com/prometheus-operator/prometheus-operator/pkg/operator"
)
// Config defines the operator's parameters for the Prometheus controllers.
// Whenever the value of one of these parameters is changed, it triggers an
// update of the managed statefulsets.
type Config struct {
LocalHost string
ReloaderConfig operator.ContainerConfig
PrometheusDefaultBaseImage string
ThanosDefaultBaseImage string
Annotations operator.Map
Labels operator.Map
}
// StatefulSetGetter returns a statefulset object identified by
// <namespace>/<name>.
type StatefulSetGetter interface {
Get(string) (runtime.Object, error)
}
// ReconciledConditionGetter returns the Reconciled condition for the
// workload resource identified by <namespace>/<name>. The second argument is
// the observed generation.
type ReconciledConditionGetter interface {
GetCondition(string, int64) monitoringv1.Condition
}
// DeletionChecker returns true if the given object is being deleted.
type DeletionChecker interface {
DeletionInProgress(o metav1.Object) bool
}
// StatusReporter reports the status for Prometheus and PrometheusAgent
// resources based on the state of the statefulsets and pods.
type StatusReporter struct {
client kubernetes.Interface
rcg ReconciledConditionGetter
ssg StatefulSetGetter
dc DeletionChecker
repairPolicy operator.RepairPolicy
}
// NewStatusReporter returns a new StatusReporter.
func NewStatusReporter(client kubernetes.Interface, rcg ReconciledConditionGetter, ssg StatefulSetGetter, dc DeletionChecker, repairPolicy operator.RepairPolicy) *StatusReporter {
return &StatusReporter{
client: client,
rcg: rcg,
ssg: ssg,
dc: dc,
repairPolicy: repairPolicy,
}
}
func KeyToStatefulSetKey(p monitoringv1.PrometheusInterface, key string, shard int) string {
keyParts := strings.Split(key, "/")
return fmt.Sprintf("%s/%s", keyParts[0], statefulSetNameFromPrometheusName(p, keyParts[1], shard))
}
func statefulSetNameFromPrometheusName(p monitoringv1.PrometheusInterface, name string, shard int) string {
if shard == 0 {
return fmt.Sprintf("%s-%s", Prefix(p), name)
}
return fmt.Sprintf("%s-%s-shard-%d", Prefix(p), name, shard)
}
func NewTLSAssetSecret(p monitoringv1.PrometheusInterface, config Config) *corev1.Secret {
s := &corev1.Secret{
Data: map[string][]byte{},
}
operator.UpdateObject(
s,
operator.WithLabels(config.Labels),
operator.WithAnnotations(config.Annotations),
operator.WithManagingOwner(p),
operator.WithName(TLSAssetsSecretName(p)),
operator.WithNamespace(p.GetObjectMeta().GetNamespace()),
)
return s
}
// validateRemoteWriteSpec checks that mutually exclusive configurations are not
// included in the Prometheus remoteWrite configuration section, while also validating
// the RemoteWriteSpec child fields.
// Reference:
// https://github.com/prometheus/prometheus/blob/main/docs/configuration/configuration.md#remote_write
func (cg *ConfigGenerator) validateRemoteWriteSpec(spec monitoringv1.RemoteWriteSpec) error {
var nonNilFields []string
for k, v := range map[string]any{
"basicAuth": spec.BasicAuth,
"oauth2": spec.OAuth2,
"authorization": spec.Authorization,
"sigv4": spec.Sigv4,
"azureAd": spec.AzureAD,
} {
if reflect.ValueOf(v).IsNil() {
continue
}
nonNilFields = append(nonNilFields, fmt.Sprintf("%q", k))
}
if len(nonNilFields) > 1 {
return fmt.Errorf("%s can't be set at the same time, at most one of them must be defined", strings.Join(nonNilFields, " and "))
}
if spec.AzureAD != nil {
if spec.AzureAD.ManagedIdentity == nil && spec.AzureAD.OAuth == nil && spec.AzureAD.SDK == nil && spec.AzureAD.WorkloadIdentity == nil {
return fmt.Errorf("must provide Azure Managed Identity, Azure OAuth, Azure SDK, or Azure Workload Identity in the Azure AD config")
}
if spec.AzureAD.ManagedIdentity != nil && spec.AzureAD.OAuth != nil {
return fmt.Errorf("cannot provide both Azure Managed Identity and Azure OAuth in the Azure AD config")
}
if spec.AzureAD.OAuth != nil && spec.AzureAD.SDK != nil {
return fmt.Errorf("cannot provide both Azure OAuth and Azure SDK in the Azure AD config")
}
if spec.AzureAD.ManagedIdentity != nil && spec.AzureAD.SDK != nil {
return fmt.Errorf("cannot provide both Azure Managed Identity and Azure SDK in the Azure AD config")
}
if spec.AzureAD.ManagedIdentity != nil && spec.AzureAD.WorkloadIdentity != nil {
return fmt.Errorf("cannot provide both Azure Managed Identity and Azure Workload Identity in the Azure AD config")
}
if spec.AzureAD.OAuth != nil && spec.AzureAD.WorkloadIdentity != nil {
return fmt.Errorf("cannot provide both Azure OAuth and Azure Workload Identity in the Azure AD config")
}
if spec.AzureAD.SDK != nil && spec.AzureAD.WorkloadIdentity != nil {
return fmt.Errorf("cannot provide both Azure SDK and Azure Workload Identity in the Azure AD config")
}
if spec.AzureAD.ManagedIdentity != nil {
if err := cg.checkAzureADManagedIdentity(spec.AzureAD.ManagedIdentity); err != nil {
return err
}
}
if spec.AzureAD.OAuth != nil {
if !cg.WithMinimumVersion("2.48.0").IsCompatible() {
return fmt.Errorf("azureAD.oauth requires Prometheus >= v2.48.0")
}
_, err := uuid.Parse(spec.AzureAD.OAuth.ClientID)
if err != nil {
return fmt.Errorf("the provided Azure OAuth clientId is invalid")
}
}
if spec.AzureAD.SDK != nil {
if !cg.WithMinimumVersion("2.52.0").IsCompatible() {
return fmt.Errorf("azureAD.sdk requires Prometheus >= v2.52.0")
}
}
if spec.AzureAD.WorkloadIdentity != nil {
if !cg.WithMinimumVersion("3.7.0").IsCompatible() {
return fmt.Errorf("azureAD.workloadIdentity requires Prometheus >= v3.7.0")
}
_, err := uuid.Parse(spec.AzureAD.WorkloadIdentity.ClientID)
if err != nil {
return fmt.Errorf("the provided Azure Workload Identity clientId is invalid")
}
_, err = uuid.Parse(spec.AzureAD.WorkloadIdentity.TenantID)
if err != nil {
return fmt.Errorf("the provided Azure Workload Identity tenantId is invalid")
}
}
}
return spec.Validate()
}
func (cg *ConfigGenerator) checkAzureADManagedIdentity(mid *monitoringv1.ManagedIdentity) error {
// Prometheus >= v3.5.0 allows empty clientID values.
if cg.WithMinimumVersion("3.5.0").IsCompatible() {
return nil
}
if ptr.Deref(mid.ClientID, "") == "" {
return fmt.Errorf("managedIdentidy: clientId is required with Prometheus < 3.5.0, current = %s", cg.version.String())
}
return nil
}
func combinedStatus(statuses []monitoringv1.ConditionStatus) monitoringv1.ConditionStatus {
var status monitoringv1.ConditionStatus
for _, s := range statuses {
switch s {
case monitoringv1.ConditionFalse:
return monitoringv1.ConditionFalse
case monitoringv1.ConditionDegraded:
status = monitoringv1.ConditionDegraded
case monitoringv1.ConditionUnknown:
if status == "" {
status = monitoringv1.ConditionUnknown
}
}
}
if status == "" {
return monitoringv1.ConditionTrue
}
return status
}
func combinedReason(reasons []string) string {
uniqReasons := sets.New[string]()
for _, r := range reasons {
if r != "" {
uniqReasons.Insert(r)
}
}
return strings.Join(sets.List(uniqReasons), "And")
}
// Process will determine the Status of a Prometheus or PrometheusAgent
// resource depending on the current state of the underlying workload resources
// (including pods).
func (sr *StatusReporter) Process(ctx context.Context, logger *slog.Logger, p monitoringv1.PrometheusInterface, key string) (*monitoringv1.PrometheusStatus, error) {
commonFields := p.GetCommonPrometheusFields()
pStatus := monitoringv1.PrometheusStatus{
Paused: commonFields.Paused,
}
var (
statuses []monitoringv1.ConditionStatus
reasons []string
messages []string
replicas = 1
)
if commonFields.Replicas != nil {
replicas = int(*commonFields.Replicas)
}
for shard := range ExpectedStatefulSetShardNames(p) {
ssetName := KeyToStatefulSetKey(p, key, shard)
obj, err := sr.ssg.Get(ssetName)
if err != nil {
if apierrors.IsNotFound(err) {
// Statefulset hasn't been created or is already deleted.
statuses, reasons = append(statuses, monitoringv1.ConditionFalse), append(reasons, "StatefulSetNotFound")
messages = append(messages, fmt.Sprintf("shard %d: statefulset %s not found", shard, ssetName))
pStatus.ShardStatuses = append(
pStatus.ShardStatuses,
monitoringv1.ShardStatus{
ShardID: strconv.Itoa(shard),
})
continue
}
return nil, fmt.Errorf("failed to retrieve statefulset: %w", err)
}
sset := obj.(*appsv1.StatefulSet).DeepCopy()
if sr.dc.DeletionInProgress(sset) {
continue
}
stsReporter, err := operator.NewStatefulSetReporter(ctx, sr.client, sset)
if err != nil {
return nil, fmt.Errorf("failed to retrieve statefulset state: %w", err)
}
pStatus.Replicas += int32(len(stsReporter.Pods))
pStatus.UpdatedReplicas += int32(len(stsReporter.UpdatedPods()))
pStatus.AvailableReplicas += int32(len(stsReporter.ReadyPods()))
pStatus.UnavailableReplicas += int32(len(stsReporter.Pods) - len(stsReporter.ReadyPods()))
pStatus.ShardStatuses = append(
pStatus.ShardStatuses,
monitoringv1.ShardStatus{
ShardID: strconv.Itoa(shard),
Replicas: int32(len(stsReporter.Pods)),
UpdatedReplicas: int32(len(stsReporter.UpdatedPods())),
AvailableReplicas: int32(len(stsReporter.ReadyPods())),
UnavailableReplicas: int32(len(stsReporter.Pods) - len(stsReporter.ReadyPods())),
},
)
status, reason := stsReporter.StatusAndReasonForAvailableCondition(replicas)
statuses, reasons = append(statuses, status), append(reasons, reason)
if status == monitoringv1.ConditionTrue {
continue
}
for _, p := range stsReporter.Pods {
if m := p.Message(); m != "" {
messages = append(messages, fmt.Sprintf("shard %d: pod %s: %s", shard, p.Name, m))
}
}
if err := stsReporter.Repair(ctx, logger, sr.repairPolicy); err != nil {
logger.Warn("failed to repair statefulset", "err", err)
}
}
pStatus.Conditions = operator.UpdateConditions(
p.GetStatus().Conditions,
monitoringv1.Condition{
Type: monitoringv1.Available,
Status: combinedStatus(statuses),
Reason: combinedReason(reasons),
Message: strings.Join(messages, "\n"),
LastTransitionTime: metav1.Time{
Time: time.Now().UTC(),
},
ObservedGeneration: p.GetObjectMeta().GetGeneration(),
},
sr.rcg.GetCondition(key, p.GetObjectMeta().GetGeneration()),
)
return &pStatus, nil
}