-
Notifications
You must be signed in to change notification settings - Fork 784
/
validate.go
262 lines (222 loc) · 9.57 KB
/
validate.go
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
package validation
import (
"net/http"
"strings"
"time"
"unicode/utf8"
"github.com/go-kit/log"
"github.com/go-kit/log/level"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/common/model"
"github.com/weaveworks/common/httpgrpc"
"github.com/cortexproject/cortex/pkg/cortexpb"
"github.com/cortexproject/cortex/pkg/util"
"github.com/cortexproject/cortex/pkg/util/extract"
)
const (
discardReasonLabel = "reason"
errMetadataMissingMetricName = "metadata missing metric name"
errMetadataTooLong = "metadata '%s' value too long: %.200q metric %.200q"
typeMetricName = "METRIC_NAME"
typeHelp = "HELP"
typeUnit = "UNIT"
metricNameTooLong = "metric_name_too_long"
helpTooLong = "help_too_long"
unitTooLong = "unit_too_long"
// ErrQueryTooLong is used in chunk store, querier and query frontend.
ErrQueryTooLong = "the query time range exceeds the limit (query length: %s, limit: %s)"
missingMetricName = "missing_metric_name"
invalidMetricName = "metric_name_invalid"
greaterThanMaxSampleAge = "greater_than_max_sample_age"
maxLabelNamesPerSeries = "max_label_names_per_series"
tooFarInFuture = "too_far_in_future"
invalidLabel = "label_invalid"
labelNameTooLong = "label_name_too_long"
duplicateLabelNames = "duplicate_label_names"
labelsNotSorted = "labels_not_sorted"
labelValueTooLong = "label_value_too_long"
labelsSizeBytesExceeded = "labels_size_bytes_exceeded"
// Exemplar-specific validation reasons
exemplarLabelsMissing = "exemplar_labels_missing"
exemplarLabelsTooLong = "exemplar_labels_too_long"
exemplarTimestampInvalid = "exemplar_timestamp_invalid"
// RateLimited is one of the values for the reason to discard samples.
// Declared here to avoid duplication in ingester and distributor.
RateLimited = "rate_limited"
// Too many HA clusters is one of the reasons for discarding samples.
TooManyHAClusters = "too_many_ha_clusters"
// DroppedByRelabelConfiguration Samples can also be discarded because of relabeling configuration
DroppedByRelabelConfiguration = "relabel_configuration"
// DroppedByUserConfigurationOverride Samples discarded due to user configuration removing label __name__
DroppedByUserConfigurationOverride = "user_label_removal_configuration"
// The combined length of the label names and values of an Exemplar's LabelSet MUST NOT exceed 128 UTF-8 characters
// https://github.com/OpenObservability/OpenMetrics/blob/main/specification/OpenMetrics.md#exemplars
ExemplarMaxLabelSetLength = 128
)
// DiscardedSamples is a metric of the number of discarded samples, by reason.
var DiscardedSamples = prometheus.NewCounterVec(
prometheus.CounterOpts{
Name: "cortex_discarded_samples_total",
Help: "The total number of samples that were discarded.",
},
[]string{discardReasonLabel, "user"},
)
// DiscardedExemplars is a metric of the number of discarded exemplars, by reason.
var DiscardedExemplars = prometheus.NewCounterVec(
prometheus.CounterOpts{
Name: "cortex_discarded_exemplars_total",
Help: "The total number of exemplars that were discarded.",
},
[]string{discardReasonLabel, "user"},
)
// DiscardedMetadata is a metric of the number of discarded metadata, by reason.
var DiscardedMetadata = prometheus.NewCounterVec(
prometheus.CounterOpts{
Name: "cortex_discarded_metadata_total",
Help: "The total number of metadata that were discarded.",
},
[]string{discardReasonLabel, "user"},
)
func init() {
prometheus.MustRegister(DiscardedSamples)
prometheus.MustRegister(DiscardedExemplars)
prometheus.MustRegister(DiscardedMetadata)
}
// ValidateSample returns an err if the sample is invalid.
// The returned error may retain the provided series labels.
func ValidateSample(limits *Limits, userID string, ls []cortexpb.LabelAdapter, s cortexpb.Sample) ValidationError {
unsafeMetricName, _ := extract.UnsafeMetricNameFromLabelAdapters(ls)
if limits.RejectOldSamples && model.Time(s.TimestampMs) < model.Now().Add(-time.Duration(limits.RejectOldSamplesMaxAge)) {
DiscardedSamples.WithLabelValues(greaterThanMaxSampleAge, userID).Inc()
return newSampleTimestampTooOldError(unsafeMetricName, s.TimestampMs)
}
if model.Time(s.TimestampMs) > model.Now().Add(time.Duration(limits.CreationGracePeriod)) {
DiscardedSamples.WithLabelValues(tooFarInFuture, userID).Inc()
return newSampleTimestampTooNewError(unsafeMetricName, s.TimestampMs)
}
return nil
}
// ValidateExemplar returns an error if the exemplar is invalid.
// The returned error may retain the provided series labels.
func ValidateExemplar(userID string, ls []cortexpb.LabelAdapter, e cortexpb.Exemplar) ValidationError {
if len(e.Labels) <= 0 {
DiscardedExemplars.WithLabelValues(exemplarLabelsMissing, userID).Inc()
return newExemplarEmtpyLabelsError(ls, []cortexpb.LabelAdapter{}, e.TimestampMs)
}
if e.TimestampMs == 0 {
DiscardedExemplars.WithLabelValues(exemplarTimestampInvalid, userID).Inc()
return newExemplarMissingTimestampError(
ls,
e.Labels,
e.TimestampMs,
)
}
// Exemplar label length does not include chars involved in text
// rendering such as quotes, commas, etc. See spec and const definition.
labelSetLen := 0
for _, l := range e.Labels {
labelSetLen += utf8.RuneCountInString(l.Name)
labelSetLen += utf8.RuneCountInString(l.Value)
}
if labelSetLen > ExemplarMaxLabelSetLength {
DiscardedExemplars.WithLabelValues(exemplarLabelsTooLong, userID).Inc()
return newExemplarLabelLengthError(
ls,
e.Labels,
e.TimestampMs,
)
}
return nil
}
// ValidateLabels returns an err if the labels are invalid.
// The returned error may retain the provided series labels.
func ValidateLabels(limits *Limits, userID string, ls []cortexpb.LabelAdapter, skipLabelNameValidation bool) ValidationError {
if limits.EnforceMetricName {
unsafeMetricName, err := extract.UnsafeMetricNameFromLabelAdapters(ls)
if err != nil {
DiscardedSamples.WithLabelValues(missingMetricName, userID).Inc()
return newNoMetricNameError()
}
if !model.IsValidMetricName(model.LabelValue(unsafeMetricName)) {
DiscardedSamples.WithLabelValues(invalidMetricName, userID).Inc()
return newInvalidMetricNameError(unsafeMetricName)
}
}
numLabelNames := len(ls)
if numLabelNames > limits.MaxLabelNamesPerSeries {
DiscardedSamples.WithLabelValues(maxLabelNamesPerSeries, userID).Inc()
return newTooManyLabelsError(ls, limits.MaxLabelNamesPerSeries)
}
maxLabelNameLength := limits.MaxLabelNameLength
maxLabelValueLength := limits.MaxLabelValueLength
lastLabelName := ""
maxLabelsSizeBytes := limits.MaxLabelsSizeBytes
labelsSizeBytes := 0
for _, l := range ls {
if !skipLabelNameValidation && !model.LabelName(l.Name).IsValid() {
DiscardedSamples.WithLabelValues(invalidLabel, userID).Inc()
return newInvalidLabelError(ls, l.Name)
} else if len(l.Name) > maxLabelNameLength {
DiscardedSamples.WithLabelValues(labelNameTooLong, userID).Inc()
return newLabelNameTooLongError(ls, l.Name, maxLabelNameLength)
} else if len(l.Value) > maxLabelValueLength {
DiscardedSamples.WithLabelValues(labelValueTooLong, userID).Inc()
return newLabelValueTooLongError(ls, l.Name, l.Value, maxLabelValueLength)
} else if cmp := strings.Compare(lastLabelName, l.Name); cmp >= 0 {
if cmp == 0 {
DiscardedSamples.WithLabelValues(duplicateLabelNames, userID).Inc()
return newDuplicatedLabelError(ls, l.Name)
}
DiscardedSamples.WithLabelValues(labelsNotSorted, userID).Inc()
return newLabelsNotSortedError(ls, l.Name)
}
lastLabelName = l.Name
labelsSizeBytes += l.Size()
}
if maxLabelsSizeBytes > 0 && labelsSizeBytes > maxLabelsSizeBytes {
DiscardedSamples.WithLabelValues(labelsSizeBytesExceeded, userID).Inc()
return labelSizeBytesExceededError(ls, labelsSizeBytes, maxLabelsSizeBytes)
}
return nil
}
// ValidateMetadata returns an err if a metric metadata is invalid.
func ValidateMetadata(cfg *Limits, userID string, metadata *cortexpb.MetricMetadata) error {
if cfg.EnforceMetadataMetricName && metadata.GetMetricFamilyName() == "" {
DiscardedMetadata.WithLabelValues(missingMetricName, userID).Inc()
return httpgrpc.Errorf(http.StatusBadRequest, errMetadataMissingMetricName)
}
maxMetadataValueLength := cfg.MaxMetadataLength
var reason string
var cause string
var metadataType string
if len(metadata.GetMetricFamilyName()) > maxMetadataValueLength {
metadataType = typeMetricName
reason = metricNameTooLong
cause = metadata.GetMetricFamilyName()
} else if len(metadata.Help) > maxMetadataValueLength {
metadataType = typeHelp
reason = helpTooLong
cause = metadata.Help
} else if len(metadata.Unit) > maxMetadataValueLength {
metadataType = typeUnit
reason = unitTooLong
cause = metadata.Unit
}
if reason != "" {
DiscardedMetadata.WithLabelValues(reason, userID).Inc()
return httpgrpc.Errorf(http.StatusBadRequest, errMetadataTooLong, metadataType, cause, metadata.GetMetricFamilyName())
}
return nil
}
func DeletePerUserValidationMetrics(userID string, log log.Logger) {
filter := map[string]string{"user": userID}
if err := util.DeleteMatchingLabels(DiscardedSamples, filter); err != nil {
level.Warn(log).Log("msg", "failed to remove cortex_discarded_samples_total metric for user", "user", userID, "err", err)
}
if err := util.DeleteMatchingLabels(DiscardedExemplars, filter); err != nil {
level.Warn(log).Log("msg", "failed to remove cortex_discarded_exemplars_total metric for user", "user", userID, "err", err)
}
if err := util.DeleteMatchingLabels(DiscardedMetadata, filter); err != nil {
level.Warn(log).Log("msg", "failed to remove cortex_discarded_metadata_total metric for user", "user", userID, "err", err)
}
}