diff --git a/go.mod b/go.mod
index 66fbc2c4b..ca900c171 100644
--- a/go.mod
+++ b/go.mod
@@ -7,7 +7,7 @@ require (
github.com/coreos/go-iptables v0.8.0
github.com/fsnotify/fsnotify v1.10.1
github.com/golang/glog v1.2.5
- github.com/prometheus/client_golang v1.23.2
+ github.com/prometheus/client_golang v1.24.1
github.com/spf13/pflag v1.0.10
github.com/stretchr/testify v1.11.1
github.com/vishvananda/netlink v1.2.1-beta.2
@@ -41,16 +41,16 @@ require (
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect
github.com/prometheus/client_model v0.6.2 // indirect
- github.com/prometheus/common v0.66.1 // indirect
- github.com/prometheus/procfs v0.16.1 // indirect
+ github.com/prometheus/common v0.70.1 // indirect
+ github.com/prometheus/procfs v0.21.1 // indirect
github.com/safchain/ethtool v0.3.0 // indirect
github.com/x448/float16 v0.8.4 // indirect
- go.yaml.in/yaml/v2 v2.4.3 // indirect
+ go.yaml.in/yaml/v2 v2.4.4 // indirect
go.yaml.in/yaml/v3 v3.0.4 // indirect
- golang.org/x/net v0.55.0 // indirect
- golang.org/x/oauth2 v0.34.0 // indirect
- golang.org/x/term v0.43.0 // indirect
- golang.org/x/text v0.37.0 // indirect
+ golang.org/x/net v0.57.0 // indirect
+ golang.org/x/oauth2 v0.36.0 // indirect
+ golang.org/x/term v0.45.0 // indirect
+ golang.org/x/text v0.40.0 // indirect
golang.org/x/time v0.14.0 // indirect
google.golang.org/protobuf v1.36.12-0.20260120151049-f2248ac996af // indirect
gopkg.in/evanphx/json-patch.v4 v4.13.0 // indirect
diff --git a/go.sum b/go.sum
index 226b18127..2735d1f1e 100644
--- a/go.sum
+++ b/go.sum
@@ -113,12 +113,18 @@ github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRI
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/prometheus/client_golang v1.23.2 h1:Je96obch5RDVy3FDMndoUsjAhG5Edi49h0RJWRi/o0o=
github.com/prometheus/client_golang v1.23.2/go.mod h1:Tb1a6LWHB3/SPIzCoaDXI4I8UHKeFTEQ1YCr+0Gyqmg=
+github.com/prometheus/client_golang v1.24.1 h1:JnJkREXzWxUdCuPFpIWZiPispT9xVV59uiuyR2bPlnU=
+github.com/prometheus/client_golang v1.24.1/go.mod h1:F+oSRECHg4sse5ucfYpYDeIv/hu68Zo0uoHKetWnzcE=
github.com/prometheus/client_model v0.6.2 h1:oBsgwpGs7iVziMvrGhE53c/GrLUsZdHnqNwqPLxwZyk=
github.com/prometheus/client_model v0.6.2/go.mod h1:y3m2F6Gdpfy6Ut/GBsUqTWZqCUvMVzSfMLjcu6wAwpE=
github.com/prometheus/common v0.66.1 h1:h5E0h5/Y8niHc5DlaLlWLArTQI7tMrsfQjHV+d9ZoGs=
github.com/prometheus/common v0.66.1/go.mod h1:gcaUsgf3KfRSwHY4dIMXLPV0K/Wg1oZ8+SbZk/HH/dA=
+github.com/prometheus/common v0.70.1 h1:1HvjP4D5oL3t8RsPlwxA9onvvStjtIHYE5XuuwOi/PY=
+github.com/prometheus/common v0.70.1/go.mod h1:VdFUQDMZK3VLkurFUVhia6uys/0suUp86TJz5qbJRhc=
github.com/prometheus/procfs v0.16.1 h1:hZ15bTNuirocR6u0JZ6BAHHmwS1p8B4P6MRqxtzMyRg=
github.com/prometheus/procfs v0.16.1/go.mod h1:teAbpZRB1iIAJYREa1LsoWUXykVXA1KlTmWl8x/U+Is=
+github.com/prometheus/procfs v0.21.1 h1:GljZCt+zSTS+NZq88cyQ1LjZ+RCHp3uVuabBWA5+OJI=
+github.com/prometheus/procfs v0.21.1/go.mod h1:aB55Cww9pdSJVHk0hUf0inxWyyjPogFIjmHKYgMKmtY=
github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ=
github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc=
github.com/safchain/ethtool v0.3.0 h1:gimQJpsI6sc1yIqP/y8GYgiXn/NjgvpM0RNoWLVVmP0=
@@ -149,6 +155,8 @@ go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=
go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=
go.yaml.in/yaml/v2 v2.4.3 h1:6gvOSjQoTB3vt1l+CU+tSyi/HOjfOjRLJ4YwYZGwRO0=
go.yaml.in/yaml/v2 v2.4.3/go.mod h1:zSxWcmIDjOzPXpjlTTbAsKokqkDNAVtZO0WOMiT90s8=
+go.yaml.in/yaml/v2 v2.4.4 h1:tuyd0P+2Ont/d6e2rl3be67goVK4R6deVxCUX5vyPaQ=
+go.yaml.in/yaml/v2 v2.4.4/go.mod h1:gMZqIpDtDqOfM0uNfy0SkpRhvUryYH0Z6wdMYcacYXQ=
go.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc=
go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
@@ -165,10 +173,14 @@ golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwY
golang.org/x/net v0.0.0-20210428140749-89ef3d95e781/go.mod h1:OJAsFXCWl8Ukc7SiCT/9KSuxbyM7479/AVlXFRxuMCk=
golang.org/x/net v0.55.0 h1:bcvxaJn3e1U6InsFWt1JUq1aSjnRxLzT2rtD2KfkDF8=
golang.org/x/net v0.55.0/go.mod h1:L5U2KuzuOe1lY7Z+aWVIKK6qEeJXnXV9yzGA+WCHJww=
+golang.org/x/net v0.57.0 h1:K5+3DljvIuDG9/Jv9rvyMywYNFCQ9RSUY6OOTTkT+tE=
+golang.org/x/net v0.57.0/go.mod h1:KpXc8iv+r3XplLAG/f7Jsf9RPszJzdR0f58q9vGOuEU=
golang.org/x/oauth2 v0.30.0 h1:dnDm7JmhM45NNpd8FDDeLhK6FwqbOf4MLCM9zb1BOHI=
golang.org/x/oauth2 v0.30.0/go.mod h1:B++QgG3ZKulg6sRPGD/mqlHQs5rB3Ml9erfeDY7xKlU=
golang.org/x/oauth2 v0.34.0 h1:hqK/t4AKgbqWkdkcAeI8XLmbK+4m4G5YeQRrmiotGlw=
golang.org/x/oauth2 v0.34.0/go.mod h1:lzm5WQJQwKZ3nwavOZ3IS5Aulzxi68dUSgRHujetwEA=
+golang.org/x/oauth2 v0.36.0 h1:peZ/1z27fi9hUOFCAZaHyrpWG5lwe0RJEEEeH0ThlIs=
+golang.org/x/oauth2 v0.36.0/go.mod h1:YDBUJMTkDnJS+A4BP4eZBjCqtokkg1hODuPjwiGPO7Q=
golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
@@ -196,11 +208,15 @@ golang.org/x/sys v0.47.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/term v0.43.0 h1:S4RLU2sB31O/NCl+zFN9Aru9A/Cq2aqKpTZJ6B+DwT4=
golang.org/x/term v0.43.0/go.mod h1:lrhlHNdQJHO+1qVYiHfFKVuVioJIheAc3fBSMFYEIsk=
+golang.org/x/term v0.45.0 h1:NwWyBmoJCbfTHpxrWoZ9C6/VxOf7ic219I8xZZFdrf0=
+golang.org/x/term v0.45.0/go.mod h1:9aqxs0blBcrm/n0L9QW0aRVD+ktan8ssZromtqJC43w=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc=
golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38=
+golang.org/x/text v0.40.0 h1:Ub2Z6/xjgF1WrYQz2nuITOEegKFtiIy+rieRJ5lHZKs=
+golang.org/x/text v0.40.0/go.mod h1:hpnzDAfGV753zIKo+wk3u1bVKCGPbrnF7+7LBF/UHVY=
golang.org/x/time v0.9.0 h1:EsRrnYcQiGH+5FfbgvV4AP7qEZstoyrHB0DzarOQ4ZY=
golang.org/x/time v0.9.0/go.mod h1:3BpzKBy/shNhVucY/MWOyx10tF3SFh9QdLuxbVysPQM=
golang.org/x/time v0.14.0 h1:MRx4UaLrDotUKUdCIqzPC48t1Y9hANFKIRpNx+Te8PI=
diff --git a/vendor/github.com/prometheus/client_golang/internal/github.com/golang/gddo/httputil/header/header.go b/vendor/github.com/prometheus/client_golang/internal/github.com/golang/gddo/httputil/header/header.go
index 8547c8dfd..820bf436a 100644
--- a/vendor/github.com/prometheus/client_golang/internal/github.com/golang/gddo/httputil/header/header.go
+++ b/vendor/github.com/prometheus/client_golang/internal/github.com/golang/gddo/httputil/header/header.go
@@ -90,7 +90,7 @@ loop:
s = skipSpace(s[1:])
}
}
- return
+ return specs
}
func skipSpace(s string) (rest string) {
diff --git a/vendor/github.com/prometheus/client_golang/prometheus/counter.go b/vendor/github.com/prometheus/client_golang/prometheus/counter.go
index 4ce84e7a8..7d963d3af 100644
--- a/vendor/github.com/prometheus/client_golang/prometheus/counter.go
+++ b/vendor/github.com/prometheus/client_golang/prometheus/counter.go
@@ -85,11 +85,12 @@ type CounterVecOpts struct {
// Both internal tracking values are added up in the Write method. This has to
// be taken into account when it comes to precision and overflow behavior.
func NewCounter(opts CounterOpts) Counter {
- desc := NewDesc(
+ desc := V2.NewDesc(
BuildFQName(opts.Namespace, opts.Subsystem, opts.Name),
opts.Help,
- nil,
+ UnconstrainedLabels(nil),
opts.ConstLabels,
+ WithUnit(opts.Unit),
)
if opts.now == nil {
opts.now = time.Now
@@ -205,6 +206,7 @@ func (v2) NewCounterVec(opts CounterVecOpts) *CounterVec {
opts.Help,
opts.VariableLabels,
opts.ConstLabels,
+ WithUnit(opts.Unit),
)
if opts.now == nil {
opts.now = time.Now
@@ -349,10 +351,11 @@ type CounterFunc interface {
//
// Check out the ExampleGaugeFunc examples for the similar GaugeFunc.
func NewCounterFunc(opts CounterOpts, function func() float64) CounterFunc {
- return newValueFunc(NewDesc(
+ return newValueFunc(V2.NewDesc(
BuildFQName(opts.Namespace, opts.Subsystem, opts.Name),
opts.Help,
- nil,
+ UnconstrainedLabels(nil),
opts.ConstLabels,
+ WithUnit(opts.Unit),
), CounterValue, function)
}
diff --git a/vendor/github.com/prometheus/client_golang/prometheus/desc.go b/vendor/github.com/prometheus/client_golang/prometheus/desc.go
index 2331b8b4f..a3c92e7a4 100644
--- a/vendor/github.com/prometheus/client_golang/prometheus/desc.go
+++ b/vendor/github.com/prometheus/client_golang/prometheus/desc.go
@@ -47,6 +47,8 @@ type Desc struct {
fqName string
// help provides some helpful information about this metric.
help string
+ // unit provides the unit of this metric.
+ unit string
// constLabelPairs contains precalculated DTO label pairs based on
// the constant labels.
constLabelPairs []*dto.LabelPair
@@ -66,6 +68,16 @@ type Desc struct {
err error
}
+// DescOpt allows setting optional fields for NewDesc.
+type DescOpt func(*Desc)
+
+// WithUnit sets the unit for a Desc.
+func WithUnit(unit string) DescOpt {
+ return func(d *Desc) {
+ d.unit = unit
+ }
+}
+
// NewDesc allocates and initializes a new Desc. Errors are recorded in the Desc
// and will be reported on registration time. variableLabels and constLabels can
// be nil if no such labels should be set. fqName must not be empty.
@@ -89,14 +101,17 @@ func NewDesc(fqName, help string, variableLabels []string, constLabels Labels) *
//
// For constLabels, the label values are constant. Therefore, they are fully
// specified in the Desc. See the Collector example for a usage pattern.
-func (v2) NewDesc(fqName, help string, variableLabels ConstrainableLabels, constLabels Labels) *Desc {
+func (v2) NewDesc(fqName, help string, variableLabels ConstrainableLabels, constLabels Labels, opts ...DescOpt) *Desc {
d := &Desc{
fqName: fqName,
help: help,
variableLabels: variableLabels.compile(),
}
- //nolint:staticcheck // TODO: Don't use deprecated model.NameValidationScheme.
- if !model.NameValidationScheme.IsValidMetricName(fqName) {
+
+ for _, opt := range opts {
+ opt(d)
+ }
+ if !model.UTF8Validation.IsValidMetricName(fqName) {
d.err = fmt.Errorf("%q is not a valid metric name", fqName)
return d
}
@@ -150,11 +165,13 @@ func (v2) NewDesc(fqName, help string, variableLabels ConstrainableLabels, const
d.id = xxh.Sum64()
// Sort labelNames so that order doesn't matter for the hash.
sort.Strings(labelNames)
- // Now hash together (in this order) the help string and the sorted
+ // Now hash together (in this order) the help string, the unit string and the sorted
// label names.
xxh.Reset()
xxh.WriteString(help)
xxh.Write(separatorByteSlice)
+ xxh.WriteString(d.unit)
+ xxh.Write(separatorByteSlice)
for _, labelName := range labelNames {
xxh.WriteString(labelName)
xxh.Write(separatorByteSlice)
@@ -182,6 +199,15 @@ func NewInvalidDesc(err error) *Desc {
}
}
+// Err returns an error that occurred during construction, if any.
+//
+// Calling this method is optional. It can be used to detect construction
+// errors early, before invoking other methods on the Desc. If an error is
+// present, later operations may not behave as expected.
+func (d *Desc) Err() error {
+ return d.err
+}
+
func (d *Desc) String() string {
lpStrings := make([]string, 0, len(d.constLabelPairs))
for _, lp := range d.constLabelPairs {
@@ -202,9 +228,10 @@ func (d *Desc) String() string {
}
}
return fmt.Sprintf(
- "Desc{fqName: %q, help: %q, constLabels: {%s}, variableLabels: {%s}}",
+ "Desc{fqName: %q, help: %q, unit: %q, constLabels: {%s}, variableLabels: {%s}}",
d.fqName,
d.help,
+ d.unit,
strings.Join(lpStrings, ","),
strings.Join(vlStrings, ","),
)
diff --git a/vendor/github.com/prometheus/client_golang/prometheus/expvar_collector.go b/vendor/github.com/prometheus/client_golang/prometheus/expvar_collector.go
index de5a85629..327746f43 100644
--- a/vendor/github.com/prometheus/client_golang/prometheus/expvar_collector.go
+++ b/vendor/github.com/prometheus/client_golang/prometheus/expvar_collector.go
@@ -47,14 +47,14 @@ func (e *expvarCollector) Collect(ch chan<- Metric) {
if expVar == nil {
continue
}
- var v interface{}
+ var v any
labels := make([]string, len(desc.variableLabels.names))
if err := json.Unmarshal([]byte(expVar.String()), &v); err != nil {
ch <- NewInvalidMetric(desc, err)
continue
}
- var processValue func(v interface{}, i int)
- processValue = func(v interface{}, i int) {
+ var processValue func(v any, i int)
+ processValue = func(v any, i int) {
if i >= len(labels) {
copiedLabels := append(make([]string, 0, len(labels)), labels...)
switch v := v.(type) {
@@ -72,7 +72,7 @@ func (e *expvarCollector) Collect(ch chan<- Metric) {
ch <- m
return
}
- vm, ok := v.(map[string]interface{})
+ vm, ok := v.(map[string]any)
if !ok {
return
}
diff --git a/vendor/github.com/prometheus/client_golang/prometheus/gauge.go b/vendor/github.com/prometheus/client_golang/prometheus/gauge.go
index dd2eac940..41e54bf27 100644
--- a/vendor/github.com/prometheus/client_golang/prometheus/gauge.go
+++ b/vendor/github.com/prometheus/client_golang/prometheus/gauge.go
@@ -76,11 +76,12 @@ type GaugeVecOpts struct {
// scenarios for Gauges and Counters, where the former tends to be Set-heavy and
// the latter Inc-heavy.
func NewGauge(opts GaugeOpts) Gauge {
- desc := NewDesc(
+ desc := V2.NewDesc(
BuildFQName(opts.Namespace, opts.Subsystem, opts.Name),
opts.Help,
- nil,
+ UnconstrainedLabels(nil),
opts.ConstLabels,
+ WithUnit(opts.Unit),
)
result := &gauge{desc: desc, labelPairs: desc.constLabelPairs}
result.init(result) // Init self-collection.
@@ -163,6 +164,7 @@ func (v2) NewGaugeVec(opts GaugeVecOpts) *GaugeVec {
opts.Help,
opts.VariableLabels,
opts.ConstLabels,
+ WithUnit(opts.Unit),
)
return &GaugeVec{
MetricVec: NewMetricVec(desc, func(lvs ...string) Metric {
@@ -302,10 +304,11 @@ type GaugeFunc interface {
// value of 1. Example:
// https://github.com/prometheus/common/blob/8558a5b7db3c84fa38b4766966059a7bd5bfa2ee/version/info.go#L36-L56
func NewGaugeFunc(opts GaugeOpts, function func() float64) GaugeFunc {
- return newValueFunc(NewDesc(
+ return newValueFunc(V2.NewDesc(
BuildFQName(opts.Namespace, opts.Subsystem, opts.Name),
opts.Help,
- nil,
+ UnconstrainedLabels(nil),
opts.ConstLabels,
+ WithUnit(opts.Unit),
), GaugeValue, function)
}
diff --git a/vendor/github.com/prometheus/client_golang/prometheus/go_collector_go116.go b/vendor/github.com/prometheus/client_golang/prometheus/go_collector_go116.go
deleted file mode 100644
index 897a6e906..000000000
--- a/vendor/github.com/prometheus/client_golang/prometheus/go_collector_go116.go
+++ /dev/null
@@ -1,122 +0,0 @@
-// Copyright 2021 The Prometheus Authors
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-//go:build !go1.17
-// +build !go1.17
-
-package prometheus
-
-import (
- "runtime"
- "sync"
- "time"
-)
-
-type goCollector struct {
- base baseGoCollector
-
- // ms... are memstats related.
- msLast *runtime.MemStats // Previously collected memstats.
- msLastTimestamp time.Time
- msMtx sync.Mutex // Protects msLast and msLastTimestamp.
- msMetrics memStatsMetrics
- msRead func(*runtime.MemStats) // For mocking in tests.
- msMaxWait time.Duration // Wait time for fresh memstats.
- msMaxAge time.Duration // Maximum allowed age of old memstats.
-}
-
-// NewGoCollector is the obsolete version of collectors.NewGoCollector.
-// See there for documentation.
-//
-// Deprecated: Use collectors.NewGoCollector instead.
-func NewGoCollector() Collector {
- msMetrics := goRuntimeMemStats()
- msMetrics = append(msMetrics, struct {
- desc *Desc
- eval func(*runtime.MemStats) float64
- valType ValueType
- }{
- // This metric is omitted in Go1.17+, see https://github.com/prometheus/client_golang/issues/842#issuecomment-861812034
- desc: NewDesc(
- memstatNamespace("gc_cpu_fraction"),
- "The fraction of this program's available CPU time used by the GC since the program started.",
- nil, nil,
- ),
- eval: func(ms *runtime.MemStats) float64 { return ms.GCCPUFraction },
- valType: GaugeValue,
- })
- return &goCollector{
- base: newBaseGoCollector(),
- msLast: &runtime.MemStats{},
- msRead: runtime.ReadMemStats,
- msMaxWait: time.Second,
- msMaxAge: 5 * time.Minute,
- msMetrics: msMetrics,
- }
-}
-
-// Describe returns all descriptions of the collector.
-func (c *goCollector) Describe(ch chan<- *Desc) {
- c.base.Describe(ch)
- for _, i := range c.msMetrics {
- ch <- i.desc
- }
-}
-
-// Collect returns the current state of all metrics of the collector.
-func (c *goCollector) Collect(ch chan<- Metric) {
- var (
- ms = &runtime.MemStats{}
- done = make(chan struct{})
- )
- // Start reading memstats first as it might take a while.
- go func() {
- c.msRead(ms)
- c.msMtx.Lock()
- c.msLast = ms
- c.msLastTimestamp = time.Now()
- c.msMtx.Unlock()
- close(done)
- }()
-
- // Collect base non-memory metrics.
- c.base.Collect(ch)
-
- timer := time.NewTimer(c.msMaxWait)
- select {
- case <-done: // Our own ReadMemStats succeeded in time. Use it.
- timer.Stop() // Important for high collection frequencies to not pile up timers.
- c.msCollect(ch, ms)
- return
- case <-timer.C: // Time out, use last memstats if possible. Continue below.
- }
- c.msMtx.Lock()
- if time.Since(c.msLastTimestamp) < c.msMaxAge {
- // Last memstats are recent enough. Collect from them under the lock.
- c.msCollect(ch, c.msLast)
- c.msMtx.Unlock()
- return
- }
- // If we are here, the last memstats are too old or don't exist. We have
- // to wait until our own ReadMemStats finally completes. For that to
- // happen, we have to release the lock.
- c.msMtx.Unlock()
- <-done
- c.msCollect(ch, ms)
-}
-
-func (c *goCollector) msCollect(ch chan<- Metric, ms *runtime.MemStats) {
- for _, i := range c.msMetrics {
- ch <- MustNewConstMetric(i.desc, i.valType, i.eval(ms))
- }
-}
diff --git a/vendor/github.com/prometheus/client_golang/prometheus/go_collector_latest.go b/vendor/github.com/prometheus/client_golang/prometheus/go_collector_latest.go
index 6b8684731..1db1c4be0 100644
--- a/vendor/github.com/prometheus/client_golang/prometheus/go_collector_latest.go
+++ b/vendor/github.com/prometheus/client_golang/prometheus/go_collector_latest.go
@@ -98,7 +98,7 @@ type goCollector struct {
// snapshot is always produced by Collect.
mu sync.Mutex
- // Contains all samples that has to retrieved from runtime/metrics (not all of them will be exposed).
+ // Contains all samples that have to be retrieved from runtime/metrics (not all of them will be exposed).
sampleBuf []metrics.Sample
// sampleMap allows lookup for MemStats metrics and runtime/metrics histograms for exact sums.
sampleMap map[string]*metrics.Sample
@@ -210,16 +210,26 @@ func NewGoCollector(opts ...func(o *internal.GoCollectorOptions)) Collector {
sampleBuf = append(sampleBuf, metrics.Sample{Name: d.Name})
sampleMap[d.Name] = &sampleBuf[len(sampleBuf)-1]
+ // Extract unit from the runtime/metrics name (e.g., "/gc/heap/allocs:bytes" -> "bytes")
+ // and sanitize to match Prometheus naming conventions (e.g., "cpu-seconds" -> "cpu_seconds")
+ var unit string
+ if idx := strings.IndexRune(d.Name, ':'); idx >= 0 {
+ unit = d.Name[idx+1:]
+ unit = strings.ReplaceAll(unit, "-", "_")
+ unit = strings.ReplaceAll(unit, "*", "_")
+ unit = strings.ReplaceAll(unit, "/", "_per_")
+ }
+
var m collectorMetric
if d.Kind == metrics.KindFloat64Histogram {
_, hasSum := opt.RuntimeMetricSumForHist[d.Name]
- unit := d.Name[strings.IndexRune(d.Name, ':')+1:]
m = newBatchHistogram(
- NewDesc(
+ V2.NewDesc(
BuildFQName(namespace, subsystem, name),
help,
+ UnconstrainedLabels(nil),
nil,
- nil,
+ WithUnit(unit),
),
internal.RuntimeMetricsBucketsForUnit(bucketsMap[d.Name], unit),
hasSum,
@@ -230,6 +240,7 @@ func NewGoCollector(opts ...func(o *internal.GoCollectorOptions)) Collector {
Subsystem: subsystem,
Name: name,
Help: help,
+ Unit: unit,
},
)
} else {
@@ -238,6 +249,7 @@ func NewGoCollector(opts ...func(o *internal.GoCollectorOptions)) Collector {
Subsystem: subsystem,
Name: name,
Help: help,
+ Unit: unit,
})
}
metricSet = append(metricSet, m)
diff --git a/vendor/github.com/prometheus/client_golang/prometheus/histogram.go b/vendor/github.com/prometheus/client_golang/prometheus/histogram.go
index c453b754a..88bae3b32 100644
--- a/vendor/github.com/prometheus/client_golang/prometheus/histogram.go
+++ b/vendor/github.com/prometheus/client_golang/prometheus/histogram.go
@@ -378,6 +378,9 @@ type HistogramOpts struct {
// string.
Help string
+ // Unit provides the unit of this Histogram.
+ Unit string
+
// ConstLabels are used to attach fixed labels to this metric. Metrics
// with the same fully-qualified name must have the same label names in
// their ConstLabels.
@@ -522,11 +525,12 @@ type HistogramVecOpts struct {
// for each bucket.
func NewHistogram(opts HistogramOpts) Histogram {
return newHistogram(
- NewDesc(
+ V2.NewDesc(
BuildFQName(opts.Namespace, opts.Subsystem, opts.Name),
opts.Help,
- nil,
+ UnconstrainedLabels(nil),
opts.ConstLabels,
+ WithUnit(opts.Unit),
),
opts,
)
@@ -966,7 +970,7 @@ func (h *histogram) maybeReset(
// We are using the possibly mocked h.now() rather than
// time.Since(h.lastResetTime) to enable testing.
if h.nativeHistogramMinResetDuration == 0 || // No reset configured.
- h.resetScheduled || // Do not interefere if a reset is already scheduled.
+ h.resetScheduled || // Do not interfere if a reset is already scheduled.
h.now().Sub(h.lastResetTime) < h.nativeHistogramMinResetDuration {
return false
}
@@ -1053,8 +1057,8 @@ func (h *histogram) maybeWidenZeroBucket(hot, cold *histogramCounts) bool {
atomic.StoreUint64(&cold.nativeHistogramZeroThresholdBits, math.Float64bits(newZeroThreshold))
// ...and then merge the newly deleted buckets into the wider zero
// bucket.
- mergeAndDeleteOrAddAndReset := func(hotBuckets, coldBuckets *sync.Map) func(k, v interface{}) bool {
- return func(k, v interface{}) bool {
+ mergeAndDeleteOrAddAndReset := func(hotBuckets, coldBuckets *sync.Map) func(k, v any) bool {
+ return func(k, v any) bool {
key := k.(int)
bucket := v.(*int64)
if key == smallestKey {
@@ -1107,8 +1111,8 @@ func (h *histogram) doubleBucketWidth(hot, cold *histogramCounts) {
// ...adjust the schema in the cold counts, too...
atomic.StoreInt32(&cold.nativeHistogramSchema, coldSchema)
// ...and then merge the cold buckets into the wider hot buckets.
- merge := func(hotBuckets *sync.Map) func(k, v interface{}) bool {
- return func(k, v interface{}) bool {
+ merge := func(hotBuckets *sync.Map) func(k, v any) bool {
+ return func(k, v any) bool {
key := k.(int)
bucket := v.(*int64)
// Adjust key to match the bucket to merge into.
@@ -1190,6 +1194,7 @@ func (v2) NewHistogramVec(opts HistogramVecOpts) *HistogramVec {
opts.Help,
opts.VariableLabels,
opts.ConstLabels,
+ WithUnit(opts.Unit),
)
return &HistogramVec{
MetricVec: NewMetricVec(desc, func(lvs ...string) Metric {
@@ -1476,7 +1481,7 @@ func pickSchema(bucketFactor float64) int32 {
func makeBuckets(buckets *sync.Map) ([]*dto.BucketSpan, []int64) {
var ii []int
- buckets.Range(func(k, v interface{}) bool {
+ buckets.Range(func(k, v any) bool {
ii = append(ii, k.(int))
return true
})
@@ -1553,8 +1558,8 @@ func addToBucket(buckets *sync.Map, key int, increment int64) bool {
// according to the buckets ranged through. It then resets all buckets ranged
// through to 0 (but leaves them in place so that they don't need to get
// recreated on the next scrape).
-func addAndReset(hotBuckets *sync.Map, bucketNumber *uint32) func(k, v interface{}) bool {
- return func(k, v interface{}) bool {
+func addAndReset(hotBuckets *sync.Map, bucketNumber *uint32) func(k, v any) bool {
+ return func(k, v any) bool {
bucket := v.(*int64)
if addToBucket(hotBuckets, k.(int), atomic.LoadInt64(bucket)) {
atomic.AddUint32(bucketNumber, 1)
@@ -1565,7 +1570,7 @@ func addAndReset(hotBuckets *sync.Map, bucketNumber *uint32) func(k, v interface
}
func deleteSyncMap(m *sync.Map) {
- m.Range(func(k, v interface{}) bool {
+ m.Range(func(k, v any) bool {
m.Delete(k)
return true
})
@@ -1573,7 +1578,7 @@ func deleteSyncMap(m *sync.Map) {
func findSmallestKey(m *sync.Map) int {
result := math.MaxInt32
- m.Range(func(k, v interface{}) bool {
+ m.Range(func(k, v any) bool {
key := k.(int)
if key < result {
result = key
diff --git a/vendor/github.com/prometheus/client_golang/prometheus/internal/difflib.go b/vendor/github.com/prometheus/client_golang/prometheus/internal/difflib.go
index 7bac0da33..2db270f21 100644
--- a/vendor/github.com/prometheus/client_golang/prometheus/internal/difflib.go
+++ b/vendor/github.com/prometheus/client_golang/prometheus/internal/difflib.go
@@ -78,7 +78,7 @@ type OpCode struct {
// notion, pairing up elements that appear uniquely in each sequence.
// That, and the method here, appear to yield more intuitive difference
// reports than does diff. This method appears to be the least vulnerable
-// to synching up on blocks of "junk lines", though (like blank lines in
+// to syncing up on blocks of "junk lines", though (like blank lines in
// ordinary text files, or maybe "
" lines in HTML files). That may be
// because this is the only method of the 3 that has a *concept* of
// "junk" .
@@ -567,7 +567,7 @@ type UnifiedDiff struct {
func WriteUnifiedDiff(writer io.Writer, diff UnifiedDiff) error {
buf := bufio.NewWriter(writer)
defer buf.Flush()
- wf := func(format string, args ...interface{}) error {
+ wf := func(format string, args ...any) error {
_, err := fmt.Fprintf(buf, format, args...)
return err
}
diff --git a/vendor/github.com/prometheus/client_golang/prometheus/labels.go b/vendor/github.com/prometheus/client_golang/prometheus/labels.go
index 5fe8d3b4d..a0285489a 100644
--- a/vendor/github.com/prometheus/client_golang/prometheus/labels.go
+++ b/vendor/github.com/prometheus/client_golang/prometheus/labels.go
@@ -184,6 +184,5 @@ func validateLabelValues(vals []string, expectedNumberOfValues int) error {
}
func checkLabelName(l string) bool {
- //nolint:staticcheck // TODO: Don't use deprecated model.NameValidationScheme.
- return model.NameValidationScheme.IsValidLabelName(l) && !strings.HasPrefix(l, reservedLabelPrefix)
+ return model.UTF8Validation.IsValidLabelName(l) && !strings.HasPrefix(l, reservedLabelPrefix)
}
diff --git a/vendor/github.com/prometheus/client_golang/prometheus/metric.go b/vendor/github.com/prometheus/client_golang/prometheus/metric.go
index 76e59f128..c5cb90adf 100644
--- a/vendor/github.com/prometheus/client_golang/prometheus/metric.go
+++ b/vendor/github.com/prometheus/client_golang/prometheus/metric.go
@@ -81,6 +81,9 @@ type Opts struct {
// string.
Help string
+ // Unit provides the unit of this metric as per https://prometheus.io/docs/specs/om
+ Unit string
+
// ConstLabels are used to attach fixed labels to this metric. Metrics
// with the same fully-qualified name must have the same label names in
// their ConstLabels.
diff --git a/vendor/github.com/prometheus/client_golang/prometheus/process_collector_darwin.go b/vendor/github.com/prometheus/client_golang/prometheus/process_collector_darwin.go
index b32c95fa3..2b16298f4 100644
--- a/vendor/github.com/prometheus/client_golang/prometheus/process_collector_darwin.go
+++ b/vendor/github.com/prometheus/client_golang/prometheus/process_collector_darwin.go
@@ -72,7 +72,13 @@ func getOpenFileCount() (float64, error) {
}
func (c *processCollector) processCollect(ch chan<- Metric) {
- if procs, err := unix.SysctlKinfoProcSlice("kern.proc.pid", os.Getpid()); err == nil {
+ pid, err := c.pidFn()
+ if err != nil {
+ c.reportError(ch, nil, err)
+ return
+ }
+
+ if procs, err := unix.SysctlKinfoProcSlice("kern.proc.pid", pid); err == nil {
if len(procs) == 1 {
startTime := float64(procs[0].Proc.P_starttime.Nano() / 1e9)
ch <- MustNewConstMetric(c.startTime, GaugeValue, startTime)
@@ -84,6 +90,11 @@ func (c *processCollector) processCollect(ch chan<- Metric) {
c.reportError(ch, c.startTime, err)
}
+ if pid != os.Getpid() {
+ c.reportError(ch, nil, fmt.Errorf("collecting metrics for pid %d is not supported on darwin: process metrics collection is limited to the current process (pid %d)", pid, os.Getpid()))
+ return
+ }
+
// The proc structure returned by kern.proc.pid above has an Rusage member,
// but it is not filled in, so it needs to be fetched by getrusage(2). For
// that call, the UTime, STime, and Maxrss members are filled out, but not
diff --git a/vendor/github.com/prometheus/client_golang/prometheus/process_collector_windows.go b/vendor/github.com/prometheus/client_golang/prometheus/process_collector_windows.go
index fa474289e..c08dd05f0 100644
--- a/vendor/github.com/prometheus/client_golang/prometheus/process_collector_windows.go
+++ b/vendor/github.com/prometheus/client_golang/prometheus/process_collector_windows.go
@@ -30,6 +30,10 @@ var (
procGetProcessMemoryInfo = modpsapi.NewProc("GetProcessMemoryInfo")
procGetProcessHandleCount = modkernel32.NewProc("GetProcessHandleCount")
+
+ openProcess = windows.OpenProcess
+ closeHandle = windows.CloseHandle
+ getProcessTimes = windows.GetProcessTimes
)
type processMemoryCounters struct {
@@ -79,10 +83,21 @@ func getProcessHandleCount(handle windows.Handle) (uint32, error) {
}
func (c *processCollector) processCollect(ch chan<- Metric) {
- h := windows.CurrentProcess()
+ pid, err := c.pidFn()
+ if err != nil {
+ c.reportError(ch, nil, err)
+ return
+ }
+
+ h, err := openProcess(windows.PROCESS_QUERY_INFORMATION|windows.PROCESS_VM_READ, false, uint32(pid))
+ if err != nil {
+ c.reportError(ch, nil, err)
+ return
+ }
+ defer closeHandle(h)
var startTime, exitTime, kernelTime, userTime windows.Filetime
- err := windows.GetProcessTimes(h, &startTime, &exitTime, &kernelTime, &userTime)
+ err = getProcessTimes(h, &startTime, &exitTime, &kernelTime, &userTime)
if err != nil {
c.reportError(ch, nil, err)
return
diff --git a/vendor/github.com/prometheus/client_golang/prometheus/promhttp/http.go b/vendor/github.com/prometheus/client_golang/prometheus/promhttp/http.go
index 763d99e36..c28af5ce2 100644
--- a/vendor/github.com/prometheus/client_golang/prometheus/promhttp/http.go
+++ b/vendor/github.com/prometheus/client_golang/prometheus/promhttp/http.go
@@ -37,10 +37,12 @@ import (
"fmt"
"io"
"net/http"
+ "slices"
"strconv"
"sync"
"time"
+ dto "github.com/prometheus/client_model/go"
"github.com/prometheus/common/expfmt"
"github.com/prometheus/client_golang/internal/github.com/golang/gddo/httputil"
@@ -74,11 +76,118 @@ func defaultCompressionFormats() []Compression {
}
var gzipPool = sync.Pool{
- New: func() interface{} {
+ New: func() any {
return gzip.NewWriter(nil)
},
}
+// coalescingGatherer wraps a TransactionalGatherer to deduplicate concurrent
+// Gather calls. When a Gather is already in flight, new callers join the
+// existing cycle and receive the same result once it completes. The underlying
+// done function is called exactly once, when the last joined caller releases.
+//
+// This prevents goroutine pile-up when the scrape rate is faster than the
+// time collectors need to produce metrics.
+type coalescingGatherer struct {
+ g prometheus.TransactionalGatherer
+ mu sync.Mutex
+ cycle *gatherCycle
+}
+
+// gatherCycle tracks a single in-flight Gather and all HTTP handlers sharing it.
+type gatherCycle struct {
+ ready chan struct{} // closed when Gather completes; happens-before reads of mfs/err/done
+ mfs []*dto.MetricFamily // canonical result, set before ready is closed; callers get a slices.Clone, the element values stay shared and must not be mutated
+ err error // set before ready is closed
+ done func() // underlying done callback; set before ready is closed
+ refs int // number of handlers using this cycle; protected by coalescingGatherer.mu
+}
+
+var _ prometheus.TransactionalGatherer = (*coalescingGatherer)(nil) // compile-time interface check
+
+// errGatherPanicked is returned to callers that joined an in-flight coalesced
+// Gather whose underlying gatherer panicked. See the panic guard in Gather for
+// why joiners receive this error instead of the panic itself.
+var errGatherPanicked = errors.New("coalesced gather panicked")
+
+func (c *coalescingGatherer) Gather() ([]*dto.MetricFamily, func(), error) {
+ c.mu.Lock()
+ if cy := c.cycle; cy != nil {
+ // c.cycle is non-nil while Gather runs or handlers are still consuming its results.
+ cy.refs++
+ c.mu.Unlock()
+ <-cy.ready
+ // Each caller gets its own slice header so it can filter or reorder
+ // without racing other callers sharing this cycle. The *dto.MetricFamily
+ // values remain shared and must not be mutated in place.
+ return slices.Clone(cy.mfs), c.releaseFunc(cy), cy.err
+ }
+ cy := &gatherCycle{
+ ready: make(chan struct{}),
+ done: func() {},
+ refs: 1,
+ }
+ c.cycle = cy
+ c.mu.Unlock()
+
+ // Guard against a panic in c.g.Gather. The common case, a panicking
+ // Collector, never reaches here: Registry.Gather recovers Collector panics
+ // and returns them as an error. This guard only covers the rare case where
+ // the wrapped gatherer itself panics.
+ //
+ // We deliberately do not recover: the leader's panic propagates and is
+ // handled by net/http exactly as it would be without coalescing. We only
+ // set cy.err before closing cy.ready so joiners waiting on <-cy.ready fail
+ // with that error instead of silently returning an empty, successful
+ // response, and we clear c.cycle so the next Gather starts a fresh cycle.
+ //
+ // The leader never runs its own releaseFunc on this path, so its ref is
+ // not decremented; that is harmless because the cycle is detached (c.cycle
+ // = nil) and cy.done is still the no-op set at construction (c.g.Gather
+ // panicked before assigning a real done). If cy.done is ever made non-nil
+ // before c.g.Gather runs, this path would need to release it.
+ panicked := true
+ defer func() {
+ if panicked {
+ c.mu.Lock()
+ if c.cycle == cy {
+ c.cycle = nil
+ }
+ c.mu.Unlock()
+ cy.err = errGatherPanicked // set before close: happens-before joiners' reads
+ close(cy.ready)
+ }
+ }()
+ cy.mfs, cy.done, cy.err = c.g.Gather()
+ panicked = false
+ close(cy.ready) // happens-before joiners' reads of cy.mfs/err/done
+
+ // Clone here too so cy.mfs stays the write-once canonical slice: joiners
+ // read it concurrently via slices.Clone, so the leader must not hand out
+ // (and potentially reorder) the same backing array.
+ return slices.Clone(cy.mfs), c.releaseFunc(cy), cy.err
+}
+
+// releaseFunc returns the done callback for one caller sharing cy.
+// When the last caller releases, the underlying done is invoked and the
+// cycle is cleared so the next Gather starts fresh.
+func (c *coalescingGatherer) releaseFunc(cy *gatherCycle) func() {
+ return func() {
+ c.mu.Lock()
+ cy.refs--
+ if cy.refs > 0 {
+ c.mu.Unlock()
+ return
+ }
+ // Last caller.
+ if c.cycle == cy {
+ c.cycle = nil
+ }
+ c.mu.Unlock()
+ cy.done() // called outside the lock to avoid holding it during done
+ }
+}
+
// Handler returns an http.Handler for the prometheus.DefaultGatherer, using
// default HandlerOpts, i.e. it reports the first error as an HTTP error, it has
// no error logging, and it applies compression if requested by the client.
@@ -89,6 +198,10 @@ var gzipPool = sync.Pool{
// metrics used for instrumentation will be shared between them, providing
// global scrape counts.
//
+// The handler supports filtering metrics by name using the `name[]` query parameter.
+// Multiple metric names can be specified by providing the parameter multiple times.
+// When no name[] parameters are provided, all metrics are returned.
+//
// This function is meant to cover the bulk of basic use cases. If you are doing
// anything that requires more customization (including using a non-default
// Gatherer, different instrumentation, and non-default HandlerOpts), use the
@@ -105,6 +218,10 @@ func Handler() http.Handler {
// Gatherers, with non-default HandlerOpts, and/or with custom (or no)
// instrumentation. Use the InstrumentMetricHandler function to apply the same
// kind of instrumentation as it is used by the Handler function.
+//
+// The handler supports filtering metrics by name using the `name[]` query parameter.
+// Multiple metric names can be specified by providing the parameter multiple times.
+// When no name[] parameters are provided, all metrics are returned.
func HandlerFor(reg prometheus.Gatherer, opts HandlerOpts) http.Handler {
return HandlerForTransactional(prometheus.ToTransactionalGatherer(reg), opts)
}
@@ -112,7 +229,15 @@ func HandlerFor(reg prometheus.Gatherer, opts HandlerOpts) http.Handler {
// HandlerForTransactional is like HandlerFor, but it uses transactional gather, which
// can safely change in-place returned *dto.MetricFamily before call to `Gather` and after
// call to `done` of that `Gather`.
+//
+// The handler supports filtering metrics by name using the `name[]` query parameter.
+// Multiple metric names can be specified by providing the parameter multiple times.
+// When no name[] parameters are provided, all metrics are returned.
func HandlerForTransactional(reg prometheus.TransactionalGatherer, opts HandlerOpts) http.Handler {
+ if opts.CoalesceGather {
+ reg = &coalescingGatherer{g: reg}
+ }
+
var (
inFlightSem chan struct{}
errCnt = prometheus.NewCounterVec(
@@ -214,12 +339,14 @@ func HandlerForTransactional(reg prometheus.TransactionalGatherer, opts HandlerO
rsp.Header().Set(contentEncodingHeader, encodingHeader)
}
- var enc expfmt.Encoder
+ var (
+ enc expfmt.Encoder
+ encOpts []expfmt.EncoderOption
+ )
if opts.EnableOpenMetricsTextCreatedSamples {
- enc = expfmt.NewEncoder(w, contentType, expfmt.WithCreatedLines())
- } else {
- enc = expfmt.NewEncoder(w, contentType)
+ encOpts = append(encOpts, expfmt.WithCreatedLines())
}
+ enc = expfmt.NewEncoder(w, contentType, encOpts...)
// handleError handles the error according to opts.ErrorHandling
// and returns true if we have to abort after the handling.
@@ -245,7 +372,24 @@ func HandlerForTransactional(reg prometheus.TransactionalGatherer, opts HandlerO
return false
}
+ // Build metric name filter set from query params (if any). The URL
+ // can be nil on hand-constructed requests.
+ var metricFilter map[string]struct{}
+ if req.URL != nil {
+ if metricNames := req.URL.Query()["name[]"]; len(metricNames) > 0 {
+ metricFilter = make(map[string]struct{}, len(metricNames))
+ for _, name := range metricNames {
+ metricFilter[name] = struct{}{}
+ }
+ }
+ }
+
for _, mf := range mfs {
+ if metricFilter != nil {
+ if _, ok := metricFilter[mf.GetName()]; !ok {
+ continue
+ }
+ }
if handleError(enc.Encode(mf)) {
return
}
@@ -353,7 +497,7 @@ const (
// log.Logger from the standard library implements this interface, and it is
// easy to implement by custom loggers, if they don't do so already anyway.
type Logger interface {
- Println(v ...interface{})
+ Println(v ...any)
}
// HandlerOpts specifies options how to serve metrics via an http.Handler. The
@@ -400,6 +544,40 @@ type HandlerOpts struct {
// Service Unavailable and a suitable message in the body. If
// MaxRequestsInFlight is 0 or negative, no limit is applied.
MaxRequestsInFlight int
+ // CoalesceGather, if true, deduplicates concurrent Gather calls so that
+ // only one collection runs at a time. Additional requests that arrive
+ // while a Gather is in flight will receive the same result once it
+ // completes. This prevents goroutine pile-up when the scrape rate is
+ // faster than the time collectors need to produce metrics.
+ //
+ // When enabled, concurrent scrapers share a single metric snapshot per
+ // collection cycle. Each request receives its own copy of the returned
+ // slice, so filtering or reordering it (for example via name[] query
+ // parameters) is safe. The pointed-to MetricFamily values are still
+ // shared: the built-in handler only reads them, so this is safe in
+ // practice, but a custom TransactionalGatherer that mutates the returned
+ // families in place after Gather returns must not use this option.
+ //
+ // Because the snapshot is shared, a request that arrives while a cycle is
+ // in flight receives that cycle's result even though collection began
+ // before the request; two scrapers joined to one cycle observe the same
+ // timestamps rather than independently gathered data.
+ //
+ // Consider using CoalesceGather together with Timeout. Timeout bounds the
+ // client-facing response time and keeps at most one collection running at
+ // a time, but it does not cancel the underlying Gather: a joined request
+ // that times out still holds a MaxRequestsInFlight slot until the shared
+ // collection completes.
+ //
+ // Panic handling: a panicking Collector is already turned into an error by
+ // the registry, so joiners receive that error like any other. In the rare
+ // case where the wrapped gatherer itself panics, the panicking request's
+ // panic propagates as usual (handled by net/http), while requests that
+ // joined the same cycle receive an error rather than an empty response.
+ //
+ // NOTE: This option is experimental and may change or be removed in a
+ // future release.
+ CoalesceGather bool
// If handling a request takes longer than Timeout, it is responded to
// with 503 ServiceUnavailable and a suitable Message. No timeout is
// applied if Timeout is 0 or negative. Note that with the current
@@ -407,8 +585,9 @@ type HandlerOpts struct {
// described above (and even that only if sending of the body hasn't
// started yet), while the bulk work of gathering all the metrics keeps
// running in the background (with the eventual result to be thrown
- // away). Until the implementation is improved, it is recommended to
- // implement a separate timeout in potentially slow Collectors.
+ // away). When CoalesceGather is enabled, only one such background Gather
+ // can be in flight at a time. It is also recommended to implement a
+ // separate timeout in potentially slow Collectors.
Timeout time.Duration
// If true, the experimental OpenMetrics encoding is added to the
// possible options during content negotiation. Note that Prometheus
@@ -460,7 +639,7 @@ func httpError(rsp http.ResponseWriter, err error) {
// negotiateEncodingWriter reads the Accept-Encoding header from a request and
// selects the right compression based on an allow-list of supported
-// compressions. It returns a writer implementing the compression and an the
+// compressions. It returns a writer implementing the compression and the
// correct value that the caller can set in the response header.
func negotiateEncodingWriter(r *http.Request, rw io.Writer, compressions []string) (_ io.Writer, encodingHeaderValue string, closeWriter func(), _ error) {
if len(compressions) == 0 {
diff --git a/vendor/github.com/prometheus/client_golang/prometheus/promhttp/instrument_client.go b/vendor/github.com/prometheus/client_golang/prometheus/promhttp/instrument_client.go
index d3482c40c..024857974 100644
--- a/vendor/github.com/prometheus/client_golang/prometheus/promhttp/instrument_client.go
+++ b/vendor/github.com/prometheus/client_golang/prometheus/promhttp/instrument_client.go
@@ -75,10 +75,10 @@ func InstrumentRoundTripperCounter(counter *prometheus.CounterVec, next http.Rou
resp, err := next.RoundTrip(r)
if err == nil {
l := labels(code, method, r.Method, resp.StatusCode, rtOpts.extraMethods...)
- for label, resolve := range rtOpts.extraLabelsFromCtx {
- l[label] = resolve(resp.Request.Context())
+ for label, resolve := range rtOpts.extraLabelsFromRequest {
+ l[label] = resolve(resp.Request)
}
- addWithExemplar(counter.With(l), 1, rtOpts.getExemplarFn(r.Context()))
+ addWithExemplar(counter.With(l), 1, rtOpts.getExemplarFn(r))
}
return resp, err
}
@@ -119,10 +119,10 @@ func InstrumentRoundTripperDuration(obs prometheus.ObserverVec, next http.RoundT
resp, err := next.RoundTrip(r)
if err == nil {
l := labels(code, method, r.Method, resp.StatusCode, rtOpts.extraMethods...)
- for label, resolve := range rtOpts.extraLabelsFromCtx {
- l[label] = resolve(resp.Request.Context())
+ for label, resolve := range rtOpts.extraLabelsFromRequest {
+ l[label] = resolve(resp.Request)
}
- observeWithExemplar(obs.With(l), time.Since(start).Seconds(), rtOpts.getExemplarFn(r.Context()))
+ observeWithExemplar(obs.With(l), time.Since(start).Seconds(), rtOpts.getExemplarFn(r))
}
return resp, err
}
diff --git a/vendor/github.com/prometheus/client_golang/prometheus/promhttp/instrument_server.go b/vendor/github.com/prometheus/client_golang/prometheus/promhttp/instrument_server.go
index 9332b0249..9dec091ac 100644
--- a/vendor/github.com/prometheus/client_golang/prometheus/promhttp/instrument_server.go
+++ b/vendor/github.com/prometheus/client_golang/prometheus/promhttp/instrument_server.go
@@ -28,24 +28,36 @@ import (
// magicString is used for the hacky label test in checkLabels. Remove once fixed.
const magicString = "zZgWfBxLqvG8kc8IMv3POi2Bb0tZI3vAnBx+gBaFi9FyPzB/CzKUer1yufDa"
-// observeWithExemplar is a wrapper for [prometheus.ExemplarAdder.ExemplarObserver],
-// which falls back to [prometheus.Observer.Observe] if no labels are provided.
+// observeWithExemplar records val on obs. If labels is non-nil and obs
+// implements [prometheus.ExemplarObserver], the exemplar is attached via
+// ObserveWithExemplar; otherwise the exemplar is dropped and the value is
+// recorded with a plain [prometheus.Observer.Observe]. This mirrors the
+// safe-cast pattern in [prometheus.Timer.ObserveDurationWithExemplar] and
+// ensures we never panic when callers pass an ObserverVec backed by a
+// summary, which cannot carry exemplars in the Prometheus exposition format.
func observeWithExemplar(obs prometheus.Observer, val float64, labels map[string]string) {
- if labels == nil {
- obs.Observe(val)
- return
+ if labels != nil {
+ if eo, ok := obs.(prometheus.ExemplarObserver); ok {
+ eo.ObserveWithExemplar(val, labels)
+ return
+ }
}
- obs.(prometheus.ExemplarObserver).ObserveWithExemplar(val, labels)
+ obs.Observe(val)
}
-// addWithExemplar is a wrapper for [prometheus.ExemplarAdder.AddWithExemplar],
-// which falls back to [prometheus.Counter.Add] if no labels are provided.
-func addWithExemplar(obs prometheus.Counter, val float64, labels map[string]string) {
- if labels == nil {
- obs.Add(val)
- return
+// addWithExemplar records val on c. If labels is non-nil and c implements
+// [prometheus.ExemplarAdder], the exemplar is attached via AddWithExemplar;
+// otherwise the exemplar is dropped and the value is recorded with a plain
+// [prometheus.Counter.Add]. The safe-cast keeps the helper robust against
+// custom Counter implementations that do not advertise exemplar support.
+func addWithExemplar(c prometheus.Counter, val float64, labels map[string]string) {
+ if labels != nil {
+ if ea, ok := c.(prometheus.ExemplarAdder); ok {
+ ea.AddWithExemplar(val, labels)
+ return
+ }
}
- obs.(prometheus.ExemplarAdder).AddWithExemplar(val, labels)
+ c.Add(val)
}
// InstrumentHandlerInFlight is a middleware that wraps the provided
@@ -97,10 +109,10 @@ func InstrumentHandlerDuration(obs prometheus.ObserverVec, next http.Handler, op
next.ServeHTTP(d, r)
l := labels(code, method, r.Method, d.Status(), hOpts.extraMethods...)
- for label, resolve := range hOpts.extraLabelsFromCtx {
- l[label] = resolve(r.Context())
+ for label, resolve := range hOpts.extraLabelsFromRequest {
+ l[label] = resolve(r)
}
- observeWithExemplar(obs.With(l), time.Since(now).Seconds(), hOpts.getExemplarFn(r.Context()))
+ observeWithExemplar(obs.With(l), time.Since(now).Seconds(), hOpts.getExemplarFn(r))
}
}
@@ -108,10 +120,10 @@ func InstrumentHandlerDuration(obs prometheus.ObserverVec, next http.Handler, op
now := time.Now()
next.ServeHTTP(w, r)
l := labels(code, method, r.Method, 0, hOpts.extraMethods...)
- for label, resolve := range hOpts.extraLabelsFromCtx {
- l[label] = resolve(r.Context())
+ for label, resolve := range hOpts.extraLabelsFromRequest {
+ l[label] = resolve(r)
}
- observeWithExemplar(obs.With(l), time.Since(now).Seconds(), hOpts.getExemplarFn(r.Context()))
+ observeWithExemplar(obs.With(l), time.Since(now).Seconds(), hOpts.getExemplarFn(r))
}
}
@@ -147,10 +159,10 @@ func InstrumentHandlerCounter(counter *prometheus.CounterVec, next http.Handler,
next.ServeHTTP(d, r)
l := labels(code, method, r.Method, d.Status(), hOpts.extraMethods...)
- for label, resolve := range hOpts.extraLabelsFromCtx {
- l[label] = resolve(r.Context())
+ for label, resolve := range hOpts.extraLabelsFromRequest {
+ l[label] = resolve(r)
}
- addWithExemplar(counter.With(l), 1, hOpts.getExemplarFn(r.Context()))
+ addWithExemplar(counter.With(l), 1, hOpts.getExemplarFn(r))
}
}
@@ -158,10 +170,10 @@ func InstrumentHandlerCounter(counter *prometheus.CounterVec, next http.Handler,
next.ServeHTTP(w, r)
l := labels(code, method, r.Method, 0, hOpts.extraMethods...)
- for label, resolve := range hOpts.extraLabelsFromCtx {
- l[label] = resolve(r.Context())
+ for label, resolve := range hOpts.extraLabelsFromRequest {
+ l[label] = resolve(r)
}
- addWithExemplar(counter.With(l), 1, hOpts.getExemplarFn(r.Context()))
+ addWithExemplar(counter.With(l), 1, hOpts.getExemplarFn(r))
}
}
@@ -200,10 +212,10 @@ func InstrumentHandlerTimeToWriteHeader(obs prometheus.ObserverVec, next http.Ha
now := time.Now()
d := newDelegator(w, func(status int) {
l := labels(code, method, r.Method, status, hOpts.extraMethods...)
- for label, resolve := range hOpts.extraLabelsFromCtx {
- l[label] = resolve(r.Context())
+ for label, resolve := range hOpts.extraLabelsFromRequest {
+ l[label] = resolve(r)
}
- observeWithExemplar(obs.With(l), time.Since(now).Seconds(), hOpts.getExemplarFn(r.Context()))
+ observeWithExemplar(obs.With(l), time.Since(now).Seconds(), hOpts.getExemplarFn(r))
})
next.ServeHTTP(d, r)
}
@@ -244,10 +256,10 @@ func InstrumentHandlerRequestSize(obs prometheus.ObserverVec, next http.Handler,
size := computeApproximateRequestSize(r)
l := labels(code, method, r.Method, d.Status(), hOpts.extraMethods...)
- for label, resolve := range hOpts.extraLabelsFromCtx {
- l[label] = resolve(r.Context())
+ for label, resolve := range hOpts.extraLabelsFromRequest {
+ l[label] = resolve(r)
}
- observeWithExemplar(obs.With(l), float64(size), hOpts.getExemplarFn(r.Context()))
+ observeWithExemplar(obs.With(l), float64(size), hOpts.getExemplarFn(r))
}
}
@@ -256,10 +268,10 @@ func InstrumentHandlerRequestSize(obs prometheus.ObserverVec, next http.Handler,
size := computeApproximateRequestSize(r)
l := labels(code, method, r.Method, 0, hOpts.extraMethods...)
- for label, resolve := range hOpts.extraLabelsFromCtx {
- l[label] = resolve(r.Context())
+ for label, resolve := range hOpts.extraLabelsFromRequest {
+ l[label] = resolve(r)
}
- observeWithExemplar(obs.With(l), float64(size), hOpts.getExemplarFn(r.Context()))
+ observeWithExemplar(obs.With(l), float64(size), hOpts.getExemplarFn(r))
}
}
@@ -296,10 +308,10 @@ func InstrumentHandlerResponseSize(obs prometheus.ObserverVec, next http.Handler
next.ServeHTTP(d, r)
l := labels(code, method, r.Method, d.Status(), hOpts.extraMethods...)
- for label, resolve := range hOpts.extraLabelsFromCtx {
- l[label] = resolve(r.Context())
+ for label, resolve := range hOpts.extraLabelsFromRequest {
+ l[label] = resolve(r)
}
- observeWithExemplar(obs.With(l), float64(d.Written()), hOpts.getExemplarFn(r.Context()))
+ observeWithExemplar(obs.With(l), float64(d.Written()), hOpts.getExemplarFn(r))
})
}
@@ -366,7 +378,7 @@ func checkLabels(c prometheus.Collector) (code, method bool) {
panic("metric partitioned with non-supported labels")
}
}
- return
+ return code, method
}
func isLabelCurried(c prometheus.Collector, label string) bool {
diff --git a/vendor/github.com/prometheus/client_golang/prometheus/promhttp/option.go b/vendor/github.com/prometheus/client_golang/prometheus/promhttp/option.go
index 5d4383aa1..d4c0954f3 100644
--- a/vendor/github.com/prometheus/client_golang/prometheus/promhttp/option.go
+++ b/vendor/github.com/prometheus/client_golang/prometheus/promhttp/option.go
@@ -15,6 +15,7 @@ package promhttp
import (
"context"
+ "net/http"
"github.com/prometheus/client_golang/prometheus"
)
@@ -24,28 +25,31 @@ type Option interface {
apply(*options)
}
+// LabelValueFromRequest is used to compute the label value from request.
+type LabelValueFromRequest func(request *http.Request) string
+
// LabelValueFromCtx are used to compute the label value from request context.
// Context can be filled with values from request through middleware.
type LabelValueFromCtx func(ctx context.Context) string
// options store options for both a handler or round tripper.
type options struct {
- extraMethods []string
- getExemplarFn func(requestCtx context.Context) prometheus.Labels
- extraLabelsFromCtx map[string]LabelValueFromCtx
+ extraMethods []string
+ getExemplarFn func(req *http.Request) prometheus.Labels
+ extraLabelsFromRequest map[string]LabelValueFromRequest
}
func defaultOptions() *options {
return &options{
- getExemplarFn: func(ctx context.Context) prometheus.Labels { return nil },
- extraLabelsFromCtx: map[string]LabelValueFromCtx{},
+ getExemplarFn: func(req *http.Request) prometheus.Labels { return nil },
+ extraLabelsFromRequest: map[string]LabelValueFromRequest{},
}
}
func (o *options) emptyDynamicLabels() prometheus.Labels {
labels := prometheus.Labels{}
- for label := range o.extraLabelsFromCtx {
+ for label := range o.extraLabelsFromRequest {
labels[label] = ""
}
@@ -66,19 +70,39 @@ func WithExtraMethods(methods ...string) Option {
})
}
-// WithExemplarFromContext allows to inject function that will get exemplar from context that will be put to counter and histogram metrics.
+// WithExemplarFromRequest allows you to inject a function that will get exemplar from request that will be put to counter and histogram metrics.
// If the function returns nil labels or the metric does not support exemplars, no exemplar will be added (noop), but
// metric will continue to observe/increment.
-func WithExemplarFromContext(getExemplarFn func(requestCtx context.Context) prometheus.Labels) Option {
+func WithExemplarFromRequest(getExemplarFn func(req *http.Request) prometheus.Labels) Option {
return optionApplyFunc(func(o *options) {
o.getExemplarFn = getExemplarFn
})
}
+// WithExemplarFromContext allows you to inject a function that will get exemplar from context that will be put to counter and histogram metrics.
+// If the function returns nil labels or the metric does not support exemplars, no exemplar will be added (noop), but
+// metric will continue to observe/increment.
+func WithExemplarFromContext(getExemplarFn func(requestCtx context.Context) prometheus.Labels) Option {
+ return optionApplyFunc(func(o *options) {
+ o.getExemplarFn = func(req *http.Request) prometheus.Labels {
+ return getExemplarFn(req.Context())
+ }
+ })
+}
+
+// WithLabelFromRequest registers a label for dynamic resolution with access to the request.
+func WithLabelFromRequest(name string, valueFn LabelValueFromRequest) Option {
+ return optionApplyFunc(func(o *options) {
+ o.extraLabelsFromRequest[name] = valueFn
+ })
+}
+
// WithLabelFromCtx registers a label for dynamic resolution with access to context.
// See the example for ExampleInstrumentHandlerWithLabelResolver for example usage
func WithLabelFromCtx(name string, valueFn LabelValueFromCtx) Option {
return optionApplyFunc(func(o *options) {
- o.extraLabelsFromCtx[name] = valueFn
+ o.extraLabelsFromRequest[name] = func(req *http.Request) string {
+ return valueFn(req.Context())
+ }
})
}
diff --git a/vendor/github.com/prometheus/client_golang/prometheus/registry.go b/vendor/github.com/prometheus/client_golang/prometheus/registry.go
index c6fd2f58b..ed0681c8b 100644
--- a/vendor/github.com/prometheus/client_golang/prometheus/registry.go
+++ b/vendor/github.com/prometheus/client_golang/prometheus/registry.go
@@ -214,6 +214,19 @@ func (err AlreadyRegisteredError) Error() string {
// by a Gatherer to report multiple errors during MetricFamily gathering.
type MultiError []error
+// SafeMultiError is a thread-safe wrapper around MultiError using a mutex.
+type SafeMultiError struct {
+ mu sync.Mutex
+ errs MultiError
+}
+
+// Appends the provided error to the contained MultiError in a thread-safe way.
+func (s *SafeMultiError) Append(err error) {
+ s.mu.Lock()
+ s.errs.Append(err)
+ s.mu.Unlock()
+}
+
// Error formats the contained errors as a bullet point list, preceded by the
// total number of errors. Note that this results in a multi-line string.
func (errs MultiError) Error() string {
@@ -408,6 +421,16 @@ func (r *Registry) MustRegister(cs ...Collector) {
}
}
+// MustGather implements Gatherer.
+// Wraps around Gather and panics if Gather fails for any reason.
+func (r *Registry) MustGather() []*dto.MetricFamily {
+ mfs, err := r.Gather()
+ if err != nil {
+ panic(err)
+ }
+ return mfs
+}
+
// Gather implements Gatherer.
func (r *Registry) Gather() ([]*dto.MetricFamily, error) {
r.mtx.RLock()
@@ -423,7 +446,7 @@ func (r *Registry) Gather() ([]*dto.MetricFamily, error) {
uncheckedMetricChan = make(chan Metric, capMetricChan)
metricHashes = map[uint64]struct{}{}
wg sync.WaitGroup
- errs MultiError // The collected errors to return in the end.
+ safeErrs = &SafeMultiError{} // To collect errors in a threadsafe way
registeredDescIDs map[uint64]struct{} // Only used for pedantic checks
)
@@ -453,9 +476,9 @@ func (r *Registry) Gather() ([]*dto.MetricFamily, error) {
for {
select {
case collector := <-checkedCollectors:
- collector.Collect(checkedMetricChan)
+ safeErrs.Append((safeCollect(collector, checkedMetricChan)))
case collector := <-uncheckedCollectors:
- collector.Collect(uncheckedMetricChan)
+ safeErrs.Append(safeCollect(collector, uncheckedMetricChan))
default:
return
}
@@ -499,7 +522,7 @@ func (r *Registry) Gather() ([]*dto.MetricFamily, error) {
cmc = nil
break
}
- errs.Append(processMetric(
+ safeErrs.Append(processMetric(
metric, metricFamiliesByName,
metricHashes,
registeredDescIDs,
@@ -509,7 +532,7 @@ func (r *Registry) Gather() ([]*dto.MetricFamily, error) {
umc = nil
break
}
- errs.Append(processMetric(
+ safeErrs.Append(processMetric(
metric, metricFamiliesByName,
metricHashes,
nil,
@@ -526,7 +549,7 @@ func (r *Registry) Gather() ([]*dto.MetricFamily, error) {
cmc = nil
break
}
- errs.Append(processMetric(
+ safeErrs.Append(processMetric(
metric, metricFamiliesByName,
metricHashes,
registeredDescIDs,
@@ -536,7 +559,7 @@ func (r *Registry) Gather() ([]*dto.MetricFamily, error) {
umc = nil
break
}
- errs.Append(processMetric(
+ safeErrs.Append(processMetric(
metric, metricFamiliesByName,
metricHashes,
nil,
@@ -556,7 +579,8 @@ func (r *Registry) Gather() ([]*dto.MetricFamily, error) {
break
}
}
- return internal.NormalizeMetricFamilies(metricFamiliesByName), errs.MaybeUnwrap()
+
+ return internal.NormalizeMetricFamilies(metricFamiliesByName), safeErrs.errs.MaybeUnwrap()
}
// Describe implements Collector.
@@ -571,6 +595,24 @@ func (r *Registry) Describe(ch chan<- *Desc) {
}
}
+// Helper wrapper around Collector.Collect.
+// It tries to collect from the channel, recovers on panic and
+// if it has recovered from a panic, then it sends an InvalidMetric into
+// the channel with an InvalidDesc, and an error that includes a stack trace.
+func safeCollect(c Collector, ch chan<- Metric) (err error) {
+ defer func() {
+ if r := recover(); r != nil {
+ buf := make([]byte, 64<<10) // 64 KB
+ n := runtime.Stack(buf, false)
+ err = fmt.Errorf("prometheus collector panic recovered: type=%T: error=%v\nstack trace=%s", c, r, buf[:n])
+ ch <- NewInvalidMetric(NewInvalidDesc(err), err)
+ }
+ }()
+ c.Collect(ch)
+
+ return err
+}
+
// Collect implements Collector.
func (r *Registry) Collect(ch chan<- Metric) {
r.mtx.RLock()
@@ -599,10 +641,12 @@ func WriteToTextfile(filename string, g Gatherer) error {
mfs, err := g.Gather()
if err != nil {
+ tmp.Close()
return err
}
for _, mf := range mfs {
if _, err := expfmt.MetricFamilyToText(tmp, mf); err != nil {
+ tmp.Close()
return err
}
}
@@ -685,6 +729,9 @@ func processMetric(
metricFamily = &dto.MetricFamily{}
metricFamily.Name = proto.String(desc.fqName)
metricFamily.Help = proto.String(desc.help)
+ if desc.unit != "" {
+ metricFamily.Unit = proto.String(desc.unit)
+ }
// TODO(beorn7): Simplify switch once Desc has type.
switch {
case dtoMetric.Gauge != nil:
diff --git a/vendor/github.com/prometheus/client_golang/prometheus/summary.go b/vendor/github.com/prometheus/client_golang/prometheus/summary.go
index ac5203c6f..c12b8d13d 100644
--- a/vendor/github.com/prometheus/client_golang/prometheus/summary.go
+++ b/vendor/github.com/prometheus/client_golang/prometheus/summary.go
@@ -101,6 +101,9 @@ type SummaryOpts struct {
// string.
Help string
+ // Unit provides the unit of this Summary.
+ Unit string
+
// ConstLabels are used to attach fixed labels to this metric. Metrics
// with the same fully-qualified name must have the same label names in
// their ConstLabels.
@@ -181,11 +184,12 @@ type SummaryVecOpts struct {
// NewSummary creates a new Summary based on the provided SummaryOpts.
func NewSummary(opts SummaryOpts) Summary {
return newSummary(
- NewDesc(
+ V2.NewDesc(
BuildFQName(opts.Namespace, opts.Subsystem, opts.Name),
opts.Help,
- nil,
+ UnconstrainedLabels(nil),
opts.ConstLabels,
+ WithUnit(opts.Unit),
),
opts,
)
@@ -578,6 +582,7 @@ func (v2) NewSummaryVec(opts SummaryVecOpts) *SummaryVec {
opts.Help,
opts.VariableLabels,
opts.ConstLabels,
+ WithUnit(opts.Unit),
)
return &SummaryVec{
MetricVec: NewMetricVec(desc, func(lvs ...string) Metric {
diff --git a/vendor/github.com/prometheus/client_golang/prometheus/timer.go b/vendor/github.com/prometheus/client_golang/prometheus/timer.go
index 52344fef5..c1318ffb5 100644
--- a/vendor/github.com/prometheus/client_golang/prometheus/timer.go
+++ b/vendor/github.com/prometheus/client_golang/prometheus/timer.go
@@ -37,10 +37,10 @@ type Timer struct {
// or
//
// func TimeMeWithExemplar() {
-// timer := NewTimer(myHistogram)
-// defer timer.ObserveDurationWithExemplar(exemplar)
-// // Do actual work.
-// }
+// timer := NewTimer(myHistogram)
+// defer timer.ObserveDurationWithExemplar(exemplar)
+// // Do actual work.
+// }
func NewTimer(o Observer) *Timer {
return &Timer{
begin: time.Now(),
@@ -66,7 +66,7 @@ func (t *Timer) ObserveDuration() time.Duration {
// ObserveDurationWithExemplar is like ObserveDuration, but it will also
// observe exemplar with the duration unless exemplar is nil or provided Observer can't
-// be casted to ExemplarObserver.
+// be cast to ExemplarObserver.
func (t *Timer) ObserveDurationWithExemplar(exemplar Labels) time.Duration {
d := time.Since(t.begin)
eo, ok := t.observer.(ExemplarObserver)
diff --git a/vendor/github.com/prometheus/client_golang/prometheus/vec.go b/vendor/github.com/prometheus/client_golang/prometheus/vec.go
index 487b46656..121d2a963 100644
--- a/vendor/github.com/prometheus/client_golang/prometheus/vec.go
+++ b/vendor/github.com/prometheus/client_golang/prometheus/vec.go
@@ -193,9 +193,11 @@ func (m *MetricVec) CurryWith(labels Labels) (*MetricVec, error) {
//
// Keeping the Metric for later use is possible (and should be considered if
// performance is critical), but keep in mind that Reset, DeleteLabelValues and
-// Delete can be used to delete the Metric from the MetricVec. In that case, the
-// Metric will still exist, but it will not be exported anymore, even if a
-// Metric with the same label values is created later.
+// Delete can be used to delete the Metric from the MetricVec. In that case, if
+// you have previously kept a reference to that Metric, the Metric object still
+// exists and can be used, but it will not be exported anymore. If a Metric with
+// the same label values is created later, updates to the old Metric reference
+// will not be exported.
//
// An error is returned if the number of label values is not the same as the
// number of variable labels in Desc (minus any curried labels).
@@ -657,7 +659,7 @@ func inlineLabelValues(lvs []string, curry []curriedLabelValue) []string {
}
var labelsPool = &sync.Pool{
- New: func() interface{} {
+ New: func() any {
return make(Labels)
},
}
diff --git a/vendor/github.com/prometheus/client_golang/prometheus/wrap.go b/vendor/github.com/prometheus/client_golang/prometheus/wrap.go
index 2ed128506..697f55558 100644
--- a/vendor/github.com/prometheus/client_golang/prometheus/wrap.go
+++ b/vendor/github.com/prometheus/client_golang/prometheus/wrap.go
@@ -230,6 +230,7 @@ func wrapDesc(desc *Desc, prefix string, labels Labels) *Desc {
return &Desc{
fqName: desc.fqName,
help: desc.help,
+ unit: desc.unit,
variableLabels: desc.variableLabels,
constLabelPairs: desc.constLabelPairs,
err: fmt.Errorf("attempted wrapping with already existing label name %q", ln),
@@ -238,8 +239,8 @@ func wrapDesc(desc *Desc, prefix string, labels Labels) *Desc {
constLabels[ln] = lv
}
// NewDesc will do remaining validations.
- newDesc := V2.NewDesc(prefix+desc.fqName, desc.help, desc.variableLabels, constLabels)
- // Propagate errors if there was any. This will override any errer
+ newDesc := V2.NewDesc(prefix+desc.fqName, desc.help, desc.variableLabels, constLabels, WithUnit(desc.unit))
+ // Propagate errors if there was any. This will override any error
// created by NewDesc above, i.e. earlier errors get precedence.
if desc.err != nil {
newDesc.err = desc.err
diff --git a/vendor/github.com/prometheus/common/expfmt/decode.go b/vendor/github.com/prometheus/common/expfmt/decode.go
index 7b762370e..8f8dc65d3 100644
--- a/vendor/github.com/prometheus/common/expfmt/decode.go
+++ b/vendor/github.com/prometheus/common/expfmt/decode.go
@@ -220,7 +220,7 @@ func extractSamples(f *dto.MetricFamily, o *DecodeOptions) (model.Vector, error)
return extractSummary(o, f), nil
case dto.MetricType_UNTYPED:
return extractUntyped(o, f), nil
- case dto.MetricType_HISTOGRAM:
+ case dto.MetricType_HISTOGRAM, dto.MetricType_GAUGE_HISTOGRAM:
return extractHistogram(o, f), nil
}
return nil, fmt.Errorf("expfmt.extractSamples: unknown metric family type %v", f.GetType())
@@ -403,9 +403,13 @@ func extractHistogram(o *DecodeOptions, f *dto.MetricFamily) model.Vector {
infSeen = true
}
+ v := q.GetCumulativeCountFloat()
+ if v <= 0 {
+ v = float64(q.GetCumulativeCount())
+ }
samples = append(samples, &model.Sample{
Metric: model.Metric(lset),
- Value: model.SampleValue(q.GetCumulativeCount()),
+ Value: model.SampleValue(v),
Timestamp: timestamp,
})
}
@@ -428,9 +432,13 @@ func extractHistogram(o *DecodeOptions, f *dto.MetricFamily) model.Vector {
}
lset[model.MetricNameLabel] = model.LabelValue(f.GetName() + "_count")
+ v := m.Histogram.GetSampleCountFloat()
+ if v <= 0 {
+ v = float64(m.Histogram.GetSampleCount())
+ }
count := &model.Sample{
Metric: model.Metric(lset),
- Value: model.SampleValue(m.Histogram.GetSampleCount()),
+ Value: model.SampleValue(v),
Timestamp: timestamp,
}
samples = append(samples, count)
diff --git a/vendor/github.com/prometheus/common/expfmt/expfmt.go b/vendor/github.com/prometheus/common/expfmt/expfmt.go
index c34c7de43..10bf35708 100644
--- a/vendor/github.com/prometheus/common/expfmt/expfmt.go
+++ b/vendor/github.com/prometheus/common/expfmt/expfmt.go
@@ -45,6 +45,7 @@ const (
// The Content-Type values for the different wire protocols. Do not do direct
// comparisons to these constants, instead use the comparison functions.
+ //
// Deprecated: Use expfmt.NewFormat(expfmt.TypeUnknown) instead.
FmtUnknown Format = ``
// Deprecated: Use expfmt.NewFormat(expfmt.TypeTextPlain) instead.
@@ -121,7 +122,7 @@ func NewOpenMetricsFormat(version string) (Format, error) {
// removed.
func (f Format) WithEscapingScheme(s model.EscapingScheme) Format {
var terms []string
- for _, p := range strings.Split(string(f), ";") {
+ for p := range strings.SplitSeq(string(f), ";") {
toks := strings.Split(p, "=")
if len(toks) != 2 {
trimmed := strings.TrimSpace(p)
@@ -193,7 +194,7 @@ func (f Format) FormatType() FormatType {
// "escaping" term exists, that will be used. Otherwise, the global default will
// be returned.
func (f Format) ToEscapingScheme() model.EscapingScheme {
- for _, p := range strings.Split(string(f), ";") {
+ for p := range strings.SplitSeq(string(f), ";") {
toks := strings.Split(p, "=")
if len(toks) != 2 {
continue
diff --git a/vendor/github.com/prometheus/common/expfmt/fuzz.go b/vendor/github.com/prometheus/common/expfmt/fuzz.go
index 0290f6abc..872c0c15b 100644
--- a/vendor/github.com/prometheus/common/expfmt/fuzz.go
+++ b/vendor/github.com/prometheus/common/expfmt/fuzz.go
@@ -13,7 +13,6 @@
// Build only when actually fuzzing
//go:build gofuzz
-// +build gofuzz
package expfmt
diff --git a/vendor/github.com/prometheus/common/expfmt/openmetrics_create.go b/vendor/github.com/prometheus/common/expfmt/openmetrics_create.go
index 8dbf6d04e..0480e7af5 100644
--- a/vendor/github.com/prometheus/common/expfmt/openmetrics_create.go
+++ b/vendor/github.com/prometheus/common/expfmt/openmetrics_create.go
@@ -30,7 +30,6 @@ import (
type encoderOption struct {
withCreatedLines bool
- withUnit bool
}
type EncoderOption func(*encoderOption)
@@ -51,17 +50,6 @@ func WithCreatedLines() EncoderOption {
}
}
-// WithUnit is an EncoderOption enabling a set unit to be written to the output
-// and to be added to the metric name, if it's not there already, as a suffix.
-// Without opting in this way, the unit will not be added to the metric name and,
-// on top of that, the unit will not be passed onto the output, even if it
-// were declared in the *dto.MetricFamily struct, i.e. even if in.Unit !=nil.
-func WithUnit() EncoderOption {
- return func(t *encoderOption) {
- t.withUnit = true
- }
-}
-
// MetricFamilyToOpenMetrics converts a MetricFamily proto message into the
// OpenMetrics text format and writes the resulting lines to 'out'. It returns
// the number of bytes written and any error encountered. The output will have
@@ -99,15 +87,6 @@ func WithUnit() EncoderOption {
// its type will be set to `unknown` in that case to avoid invalid OpenMetrics
// output.
//
-// - According to the OM specs, the `# UNIT` line is optional, but if populated,
-// the unit has to be present in the metric name as its suffix:
-// (see https://github.com/prometheus/OpenMetrics/blob/v1.0.0/specification/OpenMetrics.md#unit).
-// However, in order to accommodate any potential scenario where such a change in the
-// metric name is not desirable, the users are here given the choice of either explicitly
-// opt in, in case they wish for the unit to be included in the output AND in the metric name
-// as a suffix (see the description of the WithUnit function above),
-// or not to opt in, in case they don't want for any of that to happen.
-//
// - No support for the following (optional) features: info type,
// stateset type, gaugehistogram type.
//
@@ -151,47 +130,44 @@ func MetricFamilyToOpenMetrics(out io.Writer, in *dto.MetricFamily, options ...E
if metricType == dto.MetricType_COUNTER && strings.HasSuffix(compliantName, "_total") {
compliantName = name[:len(name)-6]
}
- if toOM.withUnit && in.Unit != nil && !strings.HasSuffix(compliantName, "_"+*in.Unit) {
- compliantName = compliantName + "_" + *in.Unit
- }
// Comments, first HELP, then TYPE.
if in.Help != nil {
n, err = w.WriteString("# HELP ")
written += n
if err != nil {
- return
+ return written, err
}
n, err = writeName(w, compliantName)
written += n
if err != nil {
- return
+ return written, err
}
err = w.WriteByte(' ')
written++
if err != nil {
- return
+ return written, err
}
n, err = writeEscapedString(w, *in.Help, true)
written += n
if err != nil {
- return
+ return written, err
}
err = w.WriteByte('\n')
written++
if err != nil {
- return
+ return written, err
}
}
n, err = w.WriteString("# TYPE ")
written += n
if err != nil {
- return
+ return written, err
}
n, err = writeName(w, compliantName)
written += n
if err != nil {
- return
+ return written, err
}
switch metricType {
case dto.MetricType_COUNTER:
@@ -208,39 +184,41 @@ func MetricFamilyToOpenMetrics(out io.Writer, in *dto.MetricFamily, options ...E
n, err = w.WriteString(" unknown\n")
case dto.MetricType_HISTOGRAM:
n, err = w.WriteString(" histogram\n")
+ case dto.MetricType_GAUGE_HISTOGRAM:
+ n, err = w.WriteString(" gaugehistogram\n")
default:
return written, fmt.Errorf("unknown metric type %s", metricType.String())
}
written += n
if err != nil {
- return
+ return written, err
}
- if toOM.withUnit && in.Unit != nil {
+ if in.Unit != nil {
n, err = w.WriteString("# UNIT ")
written += n
if err != nil {
- return
+ return written, err
}
n, err = writeName(w, compliantName)
written += n
if err != nil {
- return
+ return written, err
}
err = w.WriteByte(' ')
written++
if err != nil {
- return
+ return written, err
}
n, err = writeEscapedString(w, *in.Unit, true)
written += n
if err != nil {
- return
+ return written, err
}
err = w.WriteByte('\n')
written++
if err != nil {
- return
+ return written, err
}
}
@@ -304,7 +282,7 @@ func MetricFamilyToOpenMetrics(out io.Writer, in *dto.MetricFamily, options ...E
)
written += n
if err != nil {
- return
+ return written, err
}
}
n, err = writeOpenMetricsSample(
@@ -314,7 +292,7 @@ func MetricFamilyToOpenMetrics(out io.Writer, in *dto.MetricFamily, options ...E
)
written += n
if err != nil {
- return
+ return written, err
}
n, err = writeOpenMetricsSample(
w, compliantName, "_count", metric, "", 0,
@@ -325,7 +303,7 @@ func MetricFamilyToOpenMetrics(out io.Writer, in *dto.MetricFamily, options ...E
createdTsBytesWritten, err = writeOpenMetricsCreated(w, compliantName, "", metric, "", 0, metric.Summary.GetCreatedTimestamp())
n += createdTsBytesWritten
}
- case dto.MetricType_HISTOGRAM:
+ case dto.MetricType_HISTOGRAM, dto.MetricType_GAUGE_HISTOGRAM:
if metric.Histogram == nil {
return written, fmt.Errorf(
"expected histogram in metric %s %s", compliantName, metric,
@@ -333,6 +311,12 @@ func MetricFamilyToOpenMetrics(out io.Writer, in *dto.MetricFamily, options ...E
}
infSeen := false
for _, b := range metric.Histogram.Bucket {
+ if b.GetCumulativeCountFloat() > 0 {
+ return written, fmt.Errorf(
+ "OpenMetrics v1.0 does not support float histogram %s %s",
+ compliantName, metric,
+ )
+ }
n, err = writeOpenMetricsSample(
w, compliantName, "_bucket", metric,
model.BucketLabel, b.GetUpperBound(),
@@ -341,7 +325,7 @@ func MetricFamilyToOpenMetrics(out io.Writer, in *dto.MetricFamily, options ...E
)
written += n
if err != nil {
- return
+ return written, err
}
if math.IsInf(b.GetUpperBound(), +1) {
infSeen = true
@@ -354,9 +338,12 @@ func MetricFamilyToOpenMetrics(out io.Writer, in *dto.MetricFamily, options ...E
0, metric.Histogram.GetSampleCount(), true,
nil,
)
+ // We do not check for a float sample count here
+ // because we will check for it below (and error
+ // out if needed).
written += n
if err != nil {
- return
+ return written, err
}
}
n, err = writeOpenMetricsSample(
@@ -366,7 +353,13 @@ func MetricFamilyToOpenMetrics(out io.Writer, in *dto.MetricFamily, options ...E
)
written += n
if err != nil {
- return
+ return written, err
+ }
+ if metric.Histogram.GetSampleCountFloat() > 0 {
+ return written, fmt.Errorf(
+ "OpenMetrics v1.0 does not support float histogram %s %s",
+ compliantName, metric,
+ )
}
n, err = writeOpenMetricsSample(
w, compliantName, "_count", metric, "", 0,
@@ -384,10 +377,10 @@ func MetricFamilyToOpenMetrics(out io.Writer, in *dto.MetricFamily, options ...E
}
written += n
if err != nil {
- return
+ return written, err
}
}
- return
+ return written, err
}
// FinalizeOpenMetrics writes the final `# EOF\n` line required by OpenMetrics.
diff --git a/vendor/github.com/prometheus/common/expfmt/text_create.go b/vendor/github.com/prometheus/common/expfmt/text_create.go
index c4e9c1bbc..f4074ae9a 100644
--- a/vendor/github.com/prometheus/common/expfmt/text_create.go
+++ b/vendor/github.com/prometheus/common/expfmt/text_create.go
@@ -42,12 +42,12 @@ const (
var (
bufPool = sync.Pool{
- New: func() interface{} {
+ New: func() any {
return bufio.NewWriter(io.Discard)
},
}
numBufPool = sync.Pool{
- New: func() interface{} {
+ New: func() any {
b := make([]byte, 0, initialNumBufSize)
return &b
},
@@ -108,38 +108,38 @@ func MetricFamilyToText(out io.Writer, in *dto.MetricFamily) (written int, err e
n, err = w.WriteString("# HELP ")
written += n
if err != nil {
- return
+ return written, err
}
n, err = writeName(w, name)
written += n
if err != nil {
- return
+ return written, err
}
err = w.WriteByte(' ')
written++
if err != nil {
- return
+ return written, err
}
n, err = writeEscapedString(w, *in.Help, false)
written += n
if err != nil {
- return
+ return written, err
}
err = w.WriteByte('\n')
written++
if err != nil {
- return
+ return written, err
}
}
n, err = w.WriteString("# TYPE ")
written += n
if err != nil {
- return
+ return written, err
}
n, err = writeName(w, name)
written += n
if err != nil {
- return
+ return written, err
}
metricType := in.GetType()
switch metricType {
@@ -151,14 +151,17 @@ func MetricFamilyToText(out io.Writer, in *dto.MetricFamily) (written int, err e
n, err = w.WriteString(" summary\n")
case dto.MetricType_UNTYPED:
n, err = w.WriteString(" untyped\n")
- case dto.MetricType_HISTOGRAM:
+ case dto.MetricType_HISTOGRAM, dto.MetricType_GAUGE_HISTOGRAM:
+ // The classic Prometheus text format has no notion of a gauge
+ // histogram. We render a gauge histogram in the same way as a
+ // regular histogram.
n, err = w.WriteString(" histogram\n")
default:
return written, fmt.Errorf("unknown metric type %s", metricType.String())
}
written += n
if err != nil {
- return
+ return written, err
}
// Finally the samples, one line for each.
@@ -208,7 +211,7 @@ func MetricFamilyToText(out io.Writer, in *dto.MetricFamily) (written int, err e
)
written += n
if err != nil {
- return
+ return written, err
}
}
n, err = writeSample(
@@ -217,13 +220,13 @@ func MetricFamilyToText(out io.Writer, in *dto.MetricFamily) (written int, err e
)
written += n
if err != nil {
- return
+ return written, err
}
n, err = writeSample(
w, name, "_count", metric, "", 0,
float64(metric.Summary.GetSampleCount()),
)
- case dto.MetricType_HISTOGRAM:
+ case dto.MetricType_HISTOGRAM, dto.MetricType_GAUGE_HISTOGRAM:
if metric.Histogram == nil {
return written, fmt.Errorf(
"expected histogram in metric %s %s", name, metric,
@@ -231,28 +234,36 @@ func MetricFamilyToText(out io.Writer, in *dto.MetricFamily) (written int, err e
}
infSeen := false
for _, b := range metric.Histogram.Bucket {
+ v := b.GetCumulativeCountFloat()
+ if v == 0 {
+ v = float64(b.GetCumulativeCount())
+ }
n, err = writeSample(
w, name, "_bucket", metric,
model.BucketLabel, b.GetUpperBound(),
- float64(b.GetCumulativeCount()),
+ v,
)
written += n
if err != nil {
- return
+ return written, err
}
if math.IsInf(b.GetUpperBound(), +1) {
infSeen = true
}
}
if !infSeen {
+ v := metric.Histogram.GetSampleCountFloat()
+ if v == 0 {
+ v = float64(metric.Histogram.GetSampleCount())
+ }
n, err = writeSample(
w, name, "_bucket", metric,
model.BucketLabel, math.Inf(+1),
- float64(metric.Histogram.GetSampleCount()),
+ v,
)
written += n
if err != nil {
- return
+ return written, err
}
}
n, err = writeSample(
@@ -261,12 +272,13 @@ func MetricFamilyToText(out io.Writer, in *dto.MetricFamily) (written int, err e
)
written += n
if err != nil {
- return
+ return written, err
}
- n, err = writeSample(
- w, name, "_count", metric, "", 0,
- float64(metric.Histogram.GetSampleCount()),
- )
+ v := metric.Histogram.GetSampleCountFloat()
+ if v == 0 {
+ v = float64(metric.Histogram.GetSampleCount())
+ }
+ n, err = writeSample(w, name, "_count", metric, "", 0, v)
default:
return written, fmt.Errorf(
"unexpected type in metric %s %s", name, metric,
@@ -274,10 +286,10 @@ func MetricFamilyToText(out io.Writer, in *dto.MetricFamily) (written int, err e
}
written += n
if err != nil {
- return
+ return written, err
}
}
- return
+ return written, err
}
// writeSample writes a single sample in text format to w, given the metric
diff --git a/vendor/github.com/prometheus/common/expfmt/text_parse.go b/vendor/github.com/prometheus/common/expfmt/text_parse.go
index 8f2edde32..4ce1f40b8 100644
--- a/vendor/github.com/prometheus/common/expfmt/text_parse.go
+++ b/vendor/github.com/prometheus/common/expfmt/text_parse.go
@@ -48,8 +48,10 @@ func (e ParseError) Error() string {
return fmt.Sprintf("text format parsing error in line %d: %s", e.Line, e.Msg)
}
-// TextParser is used to parse the simple and flat text-based exchange format. Its
-// zero value is ready to use.
+// TextParser is used to parse the simple and flat text-based exchange format.
+//
+// TextParser instances must be created with NewTextParser, the zero value of
+// TextParser is invalid.
type TextParser struct {
metricFamiliesByName map[string]*dto.MetricFamily
buf *bufio.Reader // Where the parsed input is read through.
@@ -129,9 +131,44 @@ func (p *TextParser) TextToMetricFamilies(in io.Reader) (map[string]*dto.MetricF
if p.err != nil && errors.Is(p.err, io.EOF) {
p.parseError("unexpected end of input stream")
}
+ for _, histogramMetric := range p.histograms {
+ normalizeHistogram(histogramMetric.GetHistogram())
+ }
return p.metricFamiliesByName, p.err
}
+// normalizeHistogram makes sure that all the buckets and the count in each
+// histogram is either completely float or completely integer.
+func normalizeHistogram(histogram *dto.Histogram) {
+ if histogram == nil {
+ return
+ }
+ anyFloats := false
+ if histogram.GetSampleCountFloat() != 0 {
+ anyFloats = true
+ } else {
+ for _, b := range histogram.GetBucket() {
+ if b.GetCumulativeCountFloat() != 0 {
+ anyFloats = true
+ break
+ }
+ }
+ }
+ if !anyFloats {
+ return
+ }
+ if histogram.GetSampleCountFloat() == 0 {
+ histogram.SampleCountFloat = proto.Float64(float64(histogram.GetSampleCount()))
+ histogram.SampleCount = nil
+ }
+ for _, b := range histogram.GetBucket() {
+ if b.GetCumulativeCountFloat() == 0 {
+ b.CumulativeCountFloat = proto.Float64(float64(b.GetCumulativeCount()))
+ b.CumulativeCount = nil
+ }
+ }
+}
+
func (p *TextParser) reset(in io.Reader) {
p.metricFamiliesByName = map[string]*dto.MetricFamily{}
p.currentLabelPairs = nil
@@ -281,7 +318,9 @@ func (p *TextParser) readingLabels() stateFn {
// Summaries/histograms are special. We have to reset the
// currentLabels map, currentQuantile and currentBucket before starting to
// read labels.
- if p.currentMF.GetType() == dto.MetricType_SUMMARY || p.currentMF.GetType() == dto.MetricType_HISTOGRAM {
+ if p.currentMF.GetType() == dto.MetricType_SUMMARY ||
+ p.currentMF.GetType() == dto.MetricType_HISTOGRAM ||
+ p.currentMF.GetType() == dto.MetricType_GAUGE_HISTOGRAM {
p.currentLabels = map[string]string{}
p.currentLabels[string(model.MetricNameLabel)] = p.currentMF.GetName()
p.currentQuantile = math.NaN()
@@ -300,6 +339,16 @@ func (p *TextParser) startLabelName() stateFn {
return nil // Unexpected end of input.
}
if p.currentByte == '}' {
+ if p.currentMF == nil {
+ // The closing brace was reached before any metric name was read,
+ // e.g. for the input "{}". There is no metric to attach labels to,
+ // so this is a malformed exposition. This mirrors the guard in
+ // startLabelValue. currentMF (not currentMetric) is checked because
+ // reset only clears currentMF between parses.
+ p.parseError("invalid metric name")
+ p.currentLabelPairs = nil
+ return nil
+ }
p.currentMetric.Label = append(p.currentMetric.Label, p.currentLabelPairs...)
p.currentLabelPairs = nil
if p.skipBlankTab(); p.err != nil {
@@ -374,7 +423,9 @@ func (p *TextParser) startLabelName() stateFn {
// Special summary/histogram treatment. Don't add 'quantile' and 'le'
// labels to 'real' labels.
if (p.currentMF.GetType() != dto.MetricType_SUMMARY || p.currentLabelPair.GetName() != model.QuantileLabel) &&
- (p.currentMF.GetType() != dto.MetricType_HISTOGRAM || p.currentLabelPair.GetName() != model.BucketLabel) {
+ ((p.currentMF.GetType() != dto.MetricType_HISTOGRAM &&
+ p.currentMF.GetType() != dto.MetricType_GAUGE_HISTOGRAM) ||
+ p.currentLabelPair.GetName() != model.BucketLabel) {
p.currentLabelPairs = append(p.currentLabelPairs, p.currentLabelPair)
}
// Check for duplicate label names.
@@ -425,7 +476,7 @@ func (p *TextParser) startLabelValue() stateFn {
}
}
// Similar special treatment of histograms.
- if p.currentMF.GetType() == dto.MetricType_HISTOGRAM {
+ if p.currentMF.GetType() == dto.MetricType_HISTOGRAM || p.currentMF.GetType() == dto.MetricType_GAUGE_HISTOGRAM {
if p.currentLabelPair.GetName() == model.BucketLabel {
if p.currentBucket, p.err = parseFloat(p.currentLabelPair.GetValue()); p.err != nil {
// Create a more helpful error message.
@@ -476,7 +527,7 @@ func (p *TextParser) readingValue() stateFn {
p.summaries[signature] = p.currentMetric
p.currentMF.Metric = append(p.currentMF.Metric, p.currentMetric)
}
- case dto.MetricType_HISTOGRAM:
+ case dto.MetricType_HISTOGRAM, dto.MetricType_GAUGE_HISTOGRAM:
signature := model.LabelsToSignature(p.currentLabels)
if histogram := p.histograms[signature]; histogram != nil {
p.currentMetric = histogram
@@ -522,24 +573,38 @@ func (p *TextParser) readingValue() stateFn {
},
)
}
- case dto.MetricType_HISTOGRAM:
+ case dto.MetricType_HISTOGRAM, dto.MetricType_GAUGE_HISTOGRAM:
// *sigh*
if p.currentMetric.Histogram == nil {
p.currentMetric.Histogram = &dto.Histogram{}
}
switch {
case p.currentIsHistogramCount:
- p.currentMetric.Histogram.SampleCount = proto.Uint64(uint64(value))
+ if uintValue := uint64(value); value == float64(uintValue) {
+ p.currentMetric.Histogram.SampleCount = proto.Uint64(uintValue)
+ } else {
+ if value < 0 {
+ p.parseError(fmt.Sprintf("negative count for histogram %q", p.currentMF.GetName()))
+ return nil
+ }
+ p.currentMetric.Histogram.SampleCountFloat = proto.Float64(value)
+ }
case p.currentIsHistogramSum:
p.currentMetric.Histogram.SampleSum = proto.Float64(value)
case !math.IsNaN(p.currentBucket):
- p.currentMetric.Histogram.Bucket = append(
- p.currentMetric.Histogram.Bucket,
- &dto.Bucket{
- UpperBound: proto.Float64(p.currentBucket),
- CumulativeCount: proto.Uint64(uint64(value)),
- },
- )
+ b := &dto.Bucket{
+ UpperBound: proto.Float64(p.currentBucket),
+ }
+ if uintValue := uint64(value); value == float64(uintValue) {
+ b.CumulativeCount = proto.Uint64(uintValue)
+ } else {
+ if value < 0 {
+ p.parseError(fmt.Sprintf("negative bucket population for histogram %q", p.currentMF.GetName()))
+ return nil
+ }
+ b.CumulativeCountFloat = proto.Float64(value)
+ }
+ p.currentMetric.Histogram.Bucket = append(p.currentMetric.Histogram.Bucket, b)
}
default:
p.err = fmt.Errorf("unexpected type for metric name %q", p.currentMF.GetName())
@@ -602,10 +667,18 @@ func (p *TextParser) readingType() stateFn {
if p.readTokenUntilNewline(false); p.err != nil {
return nil // Unexpected end of input.
}
- metricType, ok := dto.MetricType_value[strings.ToUpper(p.currentToken.String())]
+ typ := strings.ToUpper(p.currentToken.String()) // Tolerate any combination of upper and lower case.
+ metricType, ok := dto.MetricType_value[typ] // Tolerate "gauge_histogram" (not originally part of the text format).
if !ok {
- p.parseError(fmt.Sprintf("unknown metric type %q", p.currentToken.String()))
- return nil
+ // We also want to tolerate "gaugehistogram" to mark a gauge
+ // histogram, because that string is used in OpenMetrics. Note,
+ // however, that gauge histograms do not officially exist in the
+ // classic text format.
+ if typ != "GAUGEHISTOGRAM" {
+ p.parseError(fmt.Sprintf("unknown metric type %q", p.currentToken.String()))
+ return nil
+ }
+ metricType = int32(dto.MetricType_GAUGE_HISTOGRAM)
}
p.currentMF.Type = dto.MetricType(metricType).Enum()
return p.startOfLine
@@ -855,7 +928,8 @@ func (p *TextParser) setOrCreateCurrentMF() {
}
histogramName := histogramMetricName(name)
if p.currentMF = p.metricFamiliesByName[histogramName]; p.currentMF != nil {
- if p.currentMF.GetType() == dto.MetricType_HISTOGRAM {
+ if p.currentMF.GetType() == dto.MetricType_HISTOGRAM ||
+ p.currentMF.GetType() == dto.MetricType_GAUGE_HISTOGRAM {
if isCount(name) {
p.currentIsHistogramCount = true
}
diff --git a/vendor/github.com/prometheus/common/model/labels.go b/vendor/github.com/prometheus/common/model/labels.go
index dfeb34be5..29688a13c 100644
--- a/vendor/github.com/prometheus/common/model/labels.go
+++ b/vendor/github.com/prometheus/common/model/labels.go
@@ -124,7 +124,7 @@ func (ln LabelName) IsValidLegacy() bool {
}
// UnmarshalYAML implements the yaml.Unmarshaler interface.
-func (ln *LabelName) UnmarshalYAML(unmarshal func(interface{}) error) error {
+func (ln *LabelName) UnmarshalYAML(unmarshal func(any) error) error {
var s string
if err := unmarshal(&s); err != nil {
return err
diff --git a/vendor/github.com/prometheus/common/model/labelset.go b/vendor/github.com/prometheus/common/model/labelset.go
index 9de47b256..6010b26a8 100644
--- a/vendor/github.com/prometheus/common/model/labelset.go
+++ b/vendor/github.com/prometheus/common/model/labelset.go
@@ -16,6 +16,7 @@ package model
import (
"encoding/json"
"fmt"
+ "maps"
"sort"
)
@@ -107,9 +108,7 @@ func (ls LabelSet) Before(o LabelSet) bool {
// Clone returns a copy of the label set.
func (ls LabelSet) Clone() LabelSet {
lsn := make(LabelSet, len(ls))
- for ln, lv := range ls {
- lsn[ln] = lv
- }
+ maps.Copy(lsn, ls)
return lsn
}
@@ -117,13 +116,9 @@ func (ls LabelSet) Clone() LabelSet {
func (ls LabelSet) Merge(other LabelSet) LabelSet {
result := make(LabelSet, len(ls))
- for k, v := range ls {
- result[k] = v
- }
+ maps.Copy(result, ls)
- for k, v := range other {
- result[k] = v
- }
+ maps.Copy(result, other)
return result
}
diff --git a/vendor/github.com/prometheus/common/model/metric.go b/vendor/github.com/prometheus/common/model/metric.go
index 3feebf328..2fe461511 100644
--- a/vendor/github.com/prometheus/common/model/metric.go
+++ b/vendor/github.com/prometheus/common/model/metric.go
@@ -17,6 +17,7 @@ import (
"encoding/json"
"errors"
"fmt"
+ "maps"
"regexp"
"sort"
"strconv"
@@ -24,7 +25,6 @@ import (
"unicode/utf8"
dto "github.com/prometheus/client_model/go"
- "go.yaml.in/yaml/v2"
"google.golang.org/protobuf/proto"
)
@@ -78,14 +78,6 @@ const (
UTF8Validation
)
-var _ interface {
- yaml.Marshaler
- yaml.Unmarshaler
- json.Marshaler
- json.Unmarshaler
- fmt.Stringer
-} = new(ValidationScheme)
-
// String returns the string representation of s.
func (s ValidationScheme) String() string {
switch s {
@@ -267,9 +259,7 @@ func (m Metric) Before(o Metric) bool {
// Clone returns a copy of the Metric.
func (m Metric) Clone() Metric {
clone := make(Metric, len(m))
- for k, v := range m {
- clone[k] = v
- }
+ maps.Copy(clone, m)
return clone
}
diff --git a/vendor/github.com/prometheus/common/model/time.go b/vendor/github.com/prometheus/common/model/time.go
index 1730b0fdc..0854753f4 100644
--- a/vendor/github.com/prometheus/common/model/time.go
+++ b/vendor/github.com/prometheus/common/model/time.go
@@ -123,44 +123,38 @@ func (t Time) MarshalJSON() ([]byte, error) {
// UnmarshalJSON implements the json.Unmarshaler interface.
func (t *Time) UnmarshalJSON(b []byte) error {
- p := strings.Split(string(b), ".")
- switch len(p) {
- case 1:
- v, err := strconv.ParseInt(p[0], 10, 64)
+ base, frac, found := strings.Cut(string(b), ".")
+ if !found {
+ v, err := strconv.ParseInt(base, 10, 64)
if err != nil {
return err
}
*t = Time(v * second)
-
- case 2:
- v, err := strconv.ParseInt(p[0], 10, 64)
+ } else {
+ v, err := strconv.ParseInt(base, 10, 64)
if err != nil {
return err
}
- v *= second
- prec := dotPrecision - len(p[1])
+ prec := dotPrecision - len(frac)
if prec < 0 {
- p[1] = p[1][:dotPrecision]
- } else if prec > 0 {
- p[1] += strings.Repeat("0", prec)
+ frac = frac[:dotPrecision]
}
-
- va, err := strconv.ParseInt(p[1], 10, 32)
+ va, err := strconv.ParseInt(frac, 10, 32)
if err != nil {
return err
}
-
- // If the value was something like -0.1 the negative is lost in the
- // parsing because of the leading zero, this ensures that we capture it.
- if len(p[0]) > 0 && p[0][0] == '-' && v+va > 0 {
- *t = Time(v+va) * -1
- } else {
- *t = Time(v + va)
+ switch prec {
+ case 1:
+ va *= 10
+ case 2:
+ va *= 100
}
- default:
- return fmt.Errorf("invalid time %q", string(b))
+ if len(base) > 0 && base[0] == '-' {
+ va = -va
+ }
+ *t = Time(v*second + va)
}
return nil
}
@@ -340,12 +334,12 @@ func (d *Duration) UnmarshalText(text []byte) error {
}
// MarshalYAML implements the yaml.Marshaler interface.
-func (d Duration) MarshalYAML() (interface{}, error) {
+func (d Duration) MarshalYAML() (any, error) {
return d.String(), nil
}
// UnmarshalYAML implements the yaml.Unmarshaler interface.
-func (d *Duration) UnmarshalYAML(unmarshal func(interface{}) error) error {
+func (d *Duration) UnmarshalYAML(unmarshal func(any) error) error {
var s string
if err := unmarshal(&s); err != nil {
return err
diff --git a/vendor/github.com/prometheus/common/model/value.go b/vendor/github.com/prometheus/common/model/value.go
index a9995a37e..8dffd9c4a 100644
--- a/vendor/github.com/prometheus/common/model/value.go
+++ b/vendor/github.com/prometheus/common/model/value.go
@@ -259,13 +259,13 @@ func (s Scalar) String() string {
// MarshalJSON implements json.Marshaler.
func (s Scalar) MarshalJSON() ([]byte, error) {
v := strconv.FormatFloat(float64(s.Value), 'f', -1, 64)
- return json.Marshal([...]interface{}{s.Timestamp, v})
+ return json.Marshal([...]any{s.Timestamp, v})
}
// UnmarshalJSON implements json.Unmarshaler.
func (s *Scalar) UnmarshalJSON(b []byte) error {
var f string
- v := [...]interface{}{&s.Timestamp, &f}
+ v := [...]any{&s.Timestamp, &f}
if err := json.Unmarshal(b, &v); err != nil {
return err
@@ -291,12 +291,12 @@ func (s *String) String() string {
// MarshalJSON implements json.Marshaler.
func (s String) MarshalJSON() ([]byte, error) {
- return json.Marshal([]interface{}{s.Timestamp, s.Value})
+ return json.Marshal([]any{s.Timestamp, s.Value})
}
// UnmarshalJSON implements json.Unmarshaler.
func (s *String) UnmarshalJSON(b []byte) error {
- v := [...]interface{}{&s.Timestamp, &s.Value}
+ v := [...]any{&s.Timestamp, &s.Value}
return json.Unmarshal(b, &v)
}
diff --git a/vendor/github.com/prometheus/common/model/value_float.go b/vendor/github.com/prometheus/common/model/value_float.go
index 6bfc757d1..b7d93615e 100644
--- a/vendor/github.com/prometheus/common/model/value_float.go
+++ b/vendor/github.com/prometheus/common/model/value_float.go
@@ -79,7 +79,7 @@ func (s SamplePair) MarshalJSON() ([]byte, error) {
if err != nil {
return nil, err
}
- return []byte(fmt.Sprintf("[%s,%s]", t, v)), nil
+ return fmt.Appendf(nil, "[%s,%s]", t, v), nil
}
// UnmarshalJSON implements json.Unmarshaler.
diff --git a/vendor/github.com/prometheus/common/model/value_histogram.go b/vendor/github.com/prometheus/common/model/value_histogram.go
index 91ce5b7a4..f27856ccc 100644
--- a/vendor/github.com/prometheus/common/model/value_histogram.go
+++ b/vendor/github.com/prometheus/common/model/value_histogram.go
@@ -67,11 +67,11 @@ func (s HistogramBucket) MarshalJSON() ([]byte, error) {
if err != nil {
return nil, err
}
- return []byte(fmt.Sprintf("[%s,%s,%s,%s]", b, l, u, c)), nil
+ return fmt.Appendf(nil, "[%s,%s,%s,%s]", b, l, u, c), nil
}
func (s *HistogramBucket) UnmarshalJSON(buf []byte) error {
- tmp := []interface{}{&s.Boundaries, &s.Lower, &s.Upper, &s.Count}
+ tmp := []any{&s.Boundaries, &s.Lower, &s.Upper, &s.Count}
wantLen := len(tmp)
if err := json.Unmarshal(buf, &tmp); err != nil {
return err
@@ -152,11 +152,11 @@ func (s SampleHistogramPair) MarshalJSON() ([]byte, error) {
if err != nil {
return nil, err
}
- return []byte(fmt.Sprintf("[%s,%s]", t, v)), nil
+ return fmt.Appendf(nil, "[%s,%s]", t, v), nil
}
func (s *SampleHistogramPair) UnmarshalJSON(buf []byte) error {
- tmp := []interface{}{&s.Timestamp, &s.Histogram}
+ tmp := []any{&s.Timestamp, &s.Histogram}
wantLen := len(tmp)
if err := json.Unmarshal(buf, &tmp); err != nil {
return err
diff --git a/vendor/github.com/prometheus/procfs/.golangci.yml b/vendor/github.com/prometheus/procfs/.golangci.yml
index 3c3bf910f..eac920ba8 100644
--- a/vendor/github.com/prometheus/procfs/.golangci.yml
+++ b/vendor/github.com/prometheus/procfs/.golangci.yml
@@ -1,7 +1,9 @@
version: "2"
linters:
enable:
+ - errorlint
- forbidigo
+ - gocritic
- godot
- misspell
- revive
@@ -11,6 +13,20 @@ linters:
forbid:
- pattern: ^fmt\.Print.*$
msg: Do not commit print statements.
+ gocritic:
+ enable-all: true
+ disabled-checks:
+ - commentFormatting
+ - commentedOutCode
+ - deferInLoop
+ - filepathJoin
+ - hugeParam
+ - importShadow
+ - paramTypeCombine
+ - rangeValCopy
+ - tooManyResultsChecker
+ - unnamedResult
+ - whyNoLint
godot:
exclude:
# Ignore "See: URL".
@@ -18,17 +34,21 @@ linters:
capital: true
misspell:
locale: US
+ revive:
+ rules:
+ - name: var-naming
+ # TODO(SuperQ): See: https://github.com/prometheus/prometheus/issues/17766
+ arguments:
+ - []
+ - []
+ - - skip-package-name-checks: true
exclusions:
- generated: lax
presets:
- comments
- common-false-positives
- legacy
- std-error-handling
- paths:
- - third_party$
- - builtin$
- - examples$
+ warn-unused: true
formatters:
enable:
- gofmt
@@ -37,9 +57,3 @@ formatters:
goimports:
local-prefixes:
- github.com/prometheus/procfs
- exclusions:
- generated: lax
- paths:
- - third_party$
- - builtin$
- - examples$
diff --git a/vendor/github.com/prometheus/procfs/Makefile b/vendor/github.com/prometheus/procfs/Makefile
index 7edfe4d09..bce50a19c 100644
--- a/vendor/github.com/prometheus/procfs/Makefile
+++ b/vendor/github.com/prometheus/procfs/Makefile
@@ -1,4 +1,4 @@
-# Copyright 2018 The Prometheus Authors
+# Copyright The Prometheus Authors
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
diff --git a/vendor/github.com/prometheus/procfs/Makefile.common b/vendor/github.com/prometheus/procfs/Makefile.common
index 0ed55c2ba..a7c5f553e 100644
--- a/vendor/github.com/prometheus/procfs/Makefile.common
+++ b/vendor/github.com/prometheus/procfs/Makefile.common
@@ -1,4 +1,4 @@
-# Copyright 2018 The Prometheus Authors
+# Copyright The Prometheus Authors
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
@@ -33,7 +33,7 @@ GOHOSTOS ?= $(shell $(GO) env GOHOSTOS)
GOHOSTARCH ?= $(shell $(GO) env GOHOSTARCH)
GO_VERSION ?= $(shell $(GO) version)
-GO_VERSION_NUMBER ?= $(word 3, $(GO_VERSION))Error Parsing File
+GO_VERSION_NUMBER ?= $(word 3, $(GO_VERSION))
PRE_GO_111 ?= $(shell echo $(GO_VERSION_NUMBER) | grep -E 'go1\.(10|[0-9])\.')
PROMU := $(FIRST_GOPATH)/bin/promu
@@ -55,13 +55,14 @@ ifneq ($(shell command -v gotestsum 2> /dev/null),)
endif
endif
-PROMU_VERSION ?= 0.17.0
+PROMU_VERSION ?= 0.20.0
PROMU_URL := https://github.com/prometheus/promu/releases/download/v$(PROMU_VERSION)/promu-$(PROMU_VERSION).$(GO_BUILD_PLATFORM).tar.gz
SKIP_GOLANGCI_LINT :=
GOLANGCI_LINT :=
GOLANGCI_LINT_OPTS ?=
-GOLANGCI_LINT_VERSION ?= v2.0.2
+GOLANGCI_LINT_VERSION ?= v2.11.4
+GOLANGCI_FMT_OPTS ?=
# golangci-lint only supports linux, darwin and windows platforms on i386/amd64/arm64.
# windows isn't included here because of the path separator being different.
ifeq ($(GOHOSTOS),$(filter $(GOHOSTOS),linux darwin))
@@ -81,11 +82,32 @@ endif
PREFIX ?= $(shell pwd)
BIN_DIR ?= $(shell pwd)
DOCKER_IMAGE_TAG ?= $(subst /,-,$(shell git rev-parse --abbrev-ref HEAD))
-DOCKERFILE_PATH ?= ./Dockerfile
DOCKERBUILD_CONTEXT ?= ./
DOCKER_REPO ?= prom
-DOCKER_ARCHS ?= amd64
+# Check if deprecated DOCKERFILE_PATH is set
+ifdef DOCKERFILE_PATH
+$(error DOCKERFILE_PATH is deprecated. Use DOCKERFILE_VARIANTS ?= $(DOCKERFILE_PATH) in the Makefile)
+endif
+
+DOCKER_ARCHS ?= amd64 arm64 armv7 ppc64le riscv64 s390x
+DOCKERFILE_VARIANTS ?= $(wildcard Dockerfile Dockerfile.*)
+
+# Function to extract variant from Dockerfile label.
+# Returns the variant name from io.prometheus.image.variant label, or "default" if not found.
+define dockerfile_variant
+$(strip $(or $(shell sed -n 's/.*io\.prometheus\.image\.variant="\([^"]*\)".*/\1/p' $(1)),default))
+endef
+
+# Check for duplicate variant names (including default for Dockerfiles without labels).
+DOCKERFILE_VARIANT_NAMES := $(foreach df,$(DOCKERFILE_VARIANTS),$(call dockerfile_variant,$(df)))
+DOCKERFILE_VARIANT_NAMES_SORTED := $(sort $(DOCKERFILE_VARIANT_NAMES))
+ifneq ($(words $(DOCKERFILE_VARIANT_NAMES)),$(words $(DOCKERFILE_VARIANT_NAMES_SORTED)))
+$(error Duplicate variant names found. Each Dockerfile must have a unique io.prometheus.image.variant label, and only one can be without a label (default))
+endif
+
+# Build variant:dockerfile pairs for shell iteration.
+DOCKERFILE_VARIANTS_WITH_NAMES := $(foreach df,$(DOCKERFILE_VARIANTS),$(call dockerfile_variant,$(df)):$(df))
BUILD_DOCKER_ARCHS = $(addprefix common-docker-,$(DOCKER_ARCHS))
PUBLISH_DOCKER_ARCHS = $(addprefix common-docker-publish-,$(DOCKER_ARCHS))
@@ -111,7 +133,7 @@ common-all: precheck style check_license lint yamllint unused build test
.PHONY: common-style
common-style:
@echo ">> checking code style"
- @fmtRes=$$($(GOFMT) -d $$(find . -path ./vendor -prune -o -name '*.go' -print)); \
+ @fmtRes=$$($(GOFMT) -d $$(git ls-files '*.go' ':!:vendor/*' || find . -path ./vendor -prune -o -name '*.go' -print)); \
if [ -n "$${fmtRes}" ]; then \
echo "gofmt checking failed!"; echo "$${fmtRes}"; echo; \
echo "Please ensure you are using $$($(GO) version) for formatting code."; \
@@ -121,13 +143,19 @@ common-style:
.PHONY: common-check_license
common-check_license:
@echo ">> checking license header"
- @licRes=$$(for file in $$(find . -type f -iname '*.go' ! -path './vendor/*') ; do \
+ @licRes=$$(for file in $$(git ls-files '*.go' ':!:vendor/*' || find . -path ./vendor -prune -o -type f -iname '*.go' -print) ; do \
awk 'NR<=3' $$file | grep -Eq "(Copyright|generated|GENERATED)" || echo $$file; \
done); \
if [ -n "$${licRes}" ]; then \
echo "license header checking failed:"; echo "$${licRes}"; \
exit 1; \
fi
+ @echo ">> checking for copyright years 2026 or later"
+ @futureYearRes=$$(git grep -E 'Copyright (202[6-9]|20[3-9][0-9])' -- '*.go' ':!:vendor/*' || true); \
+ if [ -n "$${futureYearRes}" ]; then \
+ echo "Files with copyright year 2026 or later found (should use 'Copyright The Prometheus Authors'):"; echo "$${futureYearRes}"; \
+ exit 1; \
+ fi
.PHONY: common-deps
common-deps:
@@ -138,7 +166,7 @@ common-deps:
update-go-deps:
@echo ">> updating Go dependencies"
@for m in $$($(GO) list -mod=readonly -m -f '{{ if and (not .Indirect) (not .Main)}}{{.Path}}{{end}}' all); do \
- $(GO) get -d $$m; \
+ $(GO) get $$m; \
done
$(GO) mod tidy
@@ -156,9 +184,13 @@ $(GOTEST_DIR):
@mkdir -p $@
.PHONY: common-format
-common-format:
+common-format: $(GOLANGCI_LINT)
@echo ">> formatting code"
$(GO) fmt $(pkgs)
+ifdef GOLANGCI_LINT
+ @echo ">> formatting code with golangci-lint"
+ $(GOLANGCI_LINT) fmt $(GOLANGCI_FMT_OPTS)
+endif
.PHONY: common-vet
common-vet:
@@ -215,28 +247,142 @@ common-docker-repo-name:
.PHONY: common-docker $(BUILD_DOCKER_ARCHS)
common-docker: $(BUILD_DOCKER_ARCHS)
$(BUILD_DOCKER_ARCHS): common-docker-%:
- docker build -t "$(DOCKER_REPO)/$(DOCKER_IMAGE_NAME)-linux-$*:$(SANITIZED_DOCKER_IMAGE_TAG)" \
- -f $(DOCKERFILE_PATH) \
- --build-arg ARCH="$*" \
- --build-arg OS="linux" \
- $(DOCKERBUILD_CONTEXT)
+ @for variant in $(DOCKERFILE_VARIANTS_WITH_NAMES); do \
+ dockerfile=$${variant#*:}; \
+ variant_name=$${variant%%:*}; \
+ distroless_arch="$*"; \
+ if [ "$*" = "armv7" ]; then \
+ distroless_arch="arm"; \
+ fi; \
+ if [ "$$dockerfile" = "Dockerfile" ]; then \
+ echo "Building default variant ($$variant_name) for linux-$* using $$dockerfile"; \
+ docker build -t "$(DOCKER_REPO)/$(DOCKER_IMAGE_NAME)-linux-$*:$(SANITIZED_DOCKER_IMAGE_TAG)" \
+ -f $$dockerfile \
+ --build-arg ARCH="$*" \
+ --build-arg OS="linux" \
+ --build-arg DISTROLESS_ARCH="$$distroless_arch" \
+ $(DOCKERBUILD_CONTEXT); \
+ if [ "$$variant_name" != "default" ]; then \
+ echo "Tagging default variant with $$variant_name suffix"; \
+ docker tag "$(DOCKER_REPO)/$(DOCKER_IMAGE_NAME)-linux-$*:$(SANITIZED_DOCKER_IMAGE_TAG)" \
+ "$(DOCKER_REPO)/$(DOCKER_IMAGE_NAME)-linux-$*:$(SANITIZED_DOCKER_IMAGE_TAG)-$$variant_name"; \
+ fi; \
+ else \
+ echo "Building $$variant_name variant for linux-$* using $$dockerfile"; \
+ docker build -t "$(DOCKER_REPO)/$(DOCKER_IMAGE_NAME)-linux-$*:$(SANITIZED_DOCKER_IMAGE_TAG)-$$variant_name" \
+ -f $$dockerfile \
+ --build-arg ARCH="$*" \
+ --build-arg OS="linux" \
+ --build-arg DISTROLESS_ARCH="$$distroless_arch" \
+ $(DOCKERBUILD_CONTEXT); \
+ fi; \
+ done
.PHONY: common-docker-publish $(PUBLISH_DOCKER_ARCHS)
common-docker-publish: $(PUBLISH_DOCKER_ARCHS)
$(PUBLISH_DOCKER_ARCHS): common-docker-publish-%:
- docker push "$(DOCKER_REPO)/$(DOCKER_IMAGE_NAME)-linux-$*:$(SANITIZED_DOCKER_IMAGE_TAG)"
+ @for variant in $(DOCKERFILE_VARIANTS_WITH_NAMES); do \
+ dockerfile=$${variant#*:}; \
+ variant_name=$${variant%%:*}; \
+ if [ "$$dockerfile" != "Dockerfile" ] || [ "$$variant_name" != "default" ]; then \
+ echo "Pushing $$variant_name variant for linux-$*"; \
+ docker push "$(DOCKER_REPO)/$(DOCKER_IMAGE_NAME)-linux-$*:$(SANITIZED_DOCKER_IMAGE_TAG)-$$variant_name"; \
+ fi; \
+ if [ "$$dockerfile" = "Dockerfile" ]; then \
+ echo "Pushing default variant ($$variant_name) for linux-$*"; \
+ docker push "$(DOCKER_REPO)/$(DOCKER_IMAGE_NAME)-linux-$*:$(SANITIZED_DOCKER_IMAGE_TAG)"; \
+ fi; \
+ if [ "$(DOCKER_IMAGE_TAG)" = "latest" ]; then \
+ if [ "$$dockerfile" != "Dockerfile" ] || [ "$$variant_name" != "default" ]; then \
+ echo "Pushing $$variant_name variant version tags for linux-$*"; \
+ docker push "$(DOCKER_REPO)/$(DOCKER_IMAGE_NAME)-linux-$*:v$(DOCKER_MAJOR_VERSION_TAG)-$$variant_name"; \
+ fi; \
+ if [ "$$dockerfile" = "Dockerfile" ]; then \
+ echo "Pushing default variant version tag for linux-$*"; \
+ docker push "$(DOCKER_REPO)/$(DOCKER_IMAGE_NAME)-linux-$*:v$(DOCKER_MAJOR_VERSION_TAG)"; \
+ fi; \
+ fi; \
+ done
DOCKER_MAJOR_VERSION_TAG = $(firstword $(subst ., ,$(shell cat VERSION)))
.PHONY: common-docker-tag-latest $(TAG_DOCKER_ARCHS)
common-docker-tag-latest: $(TAG_DOCKER_ARCHS)
$(TAG_DOCKER_ARCHS): common-docker-tag-latest-%:
- docker tag "$(DOCKER_REPO)/$(DOCKER_IMAGE_NAME)-linux-$*:$(SANITIZED_DOCKER_IMAGE_TAG)" "$(DOCKER_REPO)/$(DOCKER_IMAGE_NAME)-linux-$*:latest"
- docker tag "$(DOCKER_REPO)/$(DOCKER_IMAGE_NAME)-linux-$*:$(SANITIZED_DOCKER_IMAGE_TAG)" "$(DOCKER_REPO)/$(DOCKER_IMAGE_NAME)-linux-$*:v$(DOCKER_MAJOR_VERSION_TAG)"
+ @for variant in $(DOCKERFILE_VARIANTS_WITH_NAMES); do \
+ dockerfile=$${variant#*:}; \
+ variant_name=$${variant%%:*}; \
+ if [ "$$dockerfile" != "Dockerfile" ] || [ "$$variant_name" != "default" ]; then \
+ echo "Tagging $$variant_name variant for linux-$* as latest"; \
+ docker tag "$(DOCKER_REPO)/$(DOCKER_IMAGE_NAME)-linux-$*:$(SANITIZED_DOCKER_IMAGE_TAG)-$$variant_name" "$(DOCKER_REPO)/$(DOCKER_IMAGE_NAME)-linux-$*:latest-$$variant_name"; \
+ docker tag "$(DOCKER_REPO)/$(DOCKER_IMAGE_NAME)-linux-$*:$(SANITIZED_DOCKER_IMAGE_TAG)-$$variant_name" "$(DOCKER_REPO)/$(DOCKER_IMAGE_NAME)-linux-$*:v$(DOCKER_MAJOR_VERSION_TAG)-$$variant_name"; \
+ fi; \
+ if [ "$$dockerfile" = "Dockerfile" ]; then \
+ echo "Tagging default variant ($$variant_name) for linux-$* as latest"; \
+ docker tag "$(DOCKER_REPO)/$(DOCKER_IMAGE_NAME)-linux-$*:$(SANITIZED_DOCKER_IMAGE_TAG)" "$(DOCKER_REPO)/$(DOCKER_IMAGE_NAME)-linux-$*:latest"; \
+ docker tag "$(DOCKER_REPO)/$(DOCKER_IMAGE_NAME)-linux-$*:$(SANITIZED_DOCKER_IMAGE_TAG)" "$(DOCKER_REPO)/$(DOCKER_IMAGE_NAME)-linux-$*:v$(DOCKER_MAJOR_VERSION_TAG)"; \
+ fi; \
+ done
.PHONY: common-docker-manifest
common-docker-manifest:
- DOCKER_CLI_EXPERIMENTAL=enabled docker manifest create -a "$(DOCKER_REPO)/$(DOCKER_IMAGE_NAME):$(SANITIZED_DOCKER_IMAGE_TAG)" $(foreach ARCH,$(DOCKER_ARCHS),$(DOCKER_REPO)/$(DOCKER_IMAGE_NAME)-linux-$(ARCH):$(SANITIZED_DOCKER_IMAGE_TAG))
- DOCKER_CLI_EXPERIMENTAL=enabled docker manifest push "$(DOCKER_REPO)/$(DOCKER_IMAGE_NAME):$(SANITIZED_DOCKER_IMAGE_TAG)"
+ @for variant in $(DOCKERFILE_VARIANTS_WITH_NAMES); do \
+ dockerfile=$${variant#*:}; \
+ variant_name=$${variant%%:*}; \
+ if [ "$$dockerfile" != "Dockerfile" ] || [ "$$variant_name" != "default" ]; then \
+ echo "Creating manifest for $$variant_name variant"; \
+ refs=""; \
+ for arch in $(DOCKER_ARCHS); do \
+ refs="$$refs $(DOCKER_REPO)/$(DOCKER_IMAGE_NAME)-linux-$$arch:$(SANITIZED_DOCKER_IMAGE_TAG)-$$variant_name"; \
+ done; \
+ if [ -z "$$refs" ]; then \
+ echo "Skipping manifest for $$variant_name variant (no supported architectures)"; \
+ continue; \
+ fi; \
+ DOCKER_CLI_EXPERIMENTAL=enabled docker manifest create -a "$(DOCKER_REPO)/$(DOCKER_IMAGE_NAME):$(SANITIZED_DOCKER_IMAGE_TAG)-$$variant_name" $$refs; \
+ DOCKER_CLI_EXPERIMENTAL=enabled docker manifest push "$(DOCKER_REPO)/$(DOCKER_IMAGE_NAME):$(SANITIZED_DOCKER_IMAGE_TAG)-$$variant_name"; \
+ fi; \
+ if [ "$$dockerfile" = "Dockerfile" ]; then \
+ echo "Creating default variant ($$variant_name) manifest"; \
+ refs=""; \
+ for arch in $(DOCKER_ARCHS); do \
+ refs="$$refs $(DOCKER_REPO)/$(DOCKER_IMAGE_NAME)-linux-$$arch:$(SANITIZED_DOCKER_IMAGE_TAG)"; \
+ done; \
+ if [ -z "$$refs" ]; then \
+ echo "Skipping default variant manifest (no supported architectures)"; \
+ continue; \
+ fi; \
+ DOCKER_CLI_EXPERIMENTAL=enabled docker manifest create -a "$(DOCKER_REPO)/$(DOCKER_IMAGE_NAME):$(SANITIZED_DOCKER_IMAGE_TAG)" $$refs; \
+ DOCKER_CLI_EXPERIMENTAL=enabled docker manifest push "$(DOCKER_REPO)/$(DOCKER_IMAGE_NAME):$(SANITIZED_DOCKER_IMAGE_TAG)"; \
+ fi; \
+ if [ "$(DOCKER_IMAGE_TAG)" = "latest" ]; then \
+ if [ "$$dockerfile" != "Dockerfile" ] || [ "$$variant_name" != "default" ]; then \
+ echo "Creating manifest for $$variant_name variant version tag"; \
+ refs=""; \
+ for arch in $(DOCKER_ARCHS); do \
+ refs="$$refs $(DOCKER_REPO)/$(DOCKER_IMAGE_NAME)-linux-$$arch:v$(DOCKER_MAJOR_VERSION_TAG)-$$variant_name"; \
+ done; \
+ if [ -z "$$refs" ]; then \
+ echo "Skipping version-tag manifest for $$variant_name variant (no supported architectures)"; \
+ continue; \
+ fi; \
+ DOCKER_CLI_EXPERIMENTAL=enabled docker manifest create -a "$(DOCKER_REPO)/$(DOCKER_IMAGE_NAME):v$(DOCKER_MAJOR_VERSION_TAG)-$$variant_name" $$refs; \
+ DOCKER_CLI_EXPERIMENTAL=enabled docker manifest push "$(DOCKER_REPO)/$(DOCKER_IMAGE_NAME):v$(DOCKER_MAJOR_VERSION_TAG)-$$variant_name"; \
+ fi; \
+ if [ "$$dockerfile" = "Dockerfile" ]; then \
+ echo "Creating default variant version tag manifest"; \
+ refs=""; \
+ for arch in $(DOCKER_ARCHS); do \
+ refs="$$refs $(DOCKER_REPO)/$(DOCKER_IMAGE_NAME)-linux-$$arch:v$(DOCKER_MAJOR_VERSION_TAG)"; \
+ done; \
+ if [ -z "$$refs" ]; then \
+ echo "Skipping default variant version-tag manifest (no supported architectures)"; \
+ continue; \
+ fi; \
+ DOCKER_CLI_EXPERIMENTAL=enabled docker manifest create -a "$(DOCKER_REPO)/$(DOCKER_IMAGE_NAME):v$(DOCKER_MAJOR_VERSION_TAG)" $$refs; \
+ DOCKER_CLI_EXPERIMENTAL=enabled docker manifest push "$(DOCKER_REPO)/$(DOCKER_IMAGE_NAME):v$(DOCKER_MAJOR_VERSION_TAG)"; \
+ fi; \
+ fi; \
+ done
.PHONY: promu
promu: $(PROMU)
@@ -248,8 +394,8 @@ $(PROMU):
cp $(PROMU_TMP)/promu-$(PROMU_VERSION).$(GO_BUILD_PLATFORM)/promu $(FIRST_GOPATH)/bin/promu
rm -r $(PROMU_TMP)
-.PHONY: proto
-proto:
+.PHONY: common-proto
+common-proto:
@echo ">> generating code from proto files"
@./scripts/genproto.sh
@@ -261,6 +407,10 @@ $(GOLANGCI_LINT):
| sh -s -- -b $(FIRST_GOPATH)/bin $(GOLANGCI_LINT_VERSION)
endif
+.PHONY: common-print-golangci-lint-version
+common-print-golangci-lint-version:
+ @echo $(GOLANGCI_LINT_VERSION)
+
.PHONY: precheck
precheck::
@@ -275,9 +425,3 @@ $(1)_precheck:
exit 1; \
fi
endef
-
-govulncheck: install-govulncheck
- govulncheck ./...
-
-install-govulncheck:
- command -v govulncheck > /dev/null || go install golang.org/x/vuln/cmd/govulncheck@latest
diff --git a/vendor/github.com/prometheus/procfs/README.md b/vendor/github.com/prometheus/procfs/README.md
index 0718239cf..363524094 100644
--- a/vendor/github.com/prometheus/procfs/README.md
+++ b/vendor/github.com/prometheus/procfs/README.md
@@ -7,7 +7,7 @@ metrics from the pseudo-filesystems /proc and /sys.
backwards-incompatible ways without warnings. Use it at your own risk.
[](https://pkg.go.dev/github.com/prometheus/procfs)
-[](https://circleci.com/gh/prometheus/procfs/tree/master)
+[](https://github.com/prometheus/procfs/actions/workflows/ci.yml)
[](https://goreportcard.com/report/github.com/prometheus/procfs)
## Usage
diff --git a/vendor/github.com/prometheus/procfs/SECURITY.md b/vendor/github.com/prometheus/procfs/SECURITY.md
index fed02d85c..5e6f976db 100644
--- a/vendor/github.com/prometheus/procfs/SECURITY.md
+++ b/vendor/github.com/prometheus/procfs/SECURITY.md
@@ -3,4 +3,4 @@
The Prometheus security policy, including how to report vulnerabilities, can be
found here:
-
+[https://prometheus.io/docs/operating/security/](https://prometheus.io/docs/operating/security/)
diff --git a/vendor/github.com/prometheus/procfs/arp.go b/vendor/github.com/prometheus/procfs/arp.go
index 2e5334415..716bdef10 100644
--- a/vendor/github.com/prometheus/procfs/arp.go
+++ b/vendor/github.com/prometheus/procfs/arp.go
@@ -1,4 +1,4 @@
-// Copyright 2019 The Prometheus Authors
+// Copyright The Prometheus Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
@@ -73,15 +73,16 @@ func parseARPEntries(data []byte) ([]ARPEntry, error) {
columns := strings.Fields(line)
width := len(columns)
- if width == expectedHeaderWidth || width == 0 {
+ switch width {
+ case expectedHeaderWidth, 0:
continue
- } else if width == expectedDataWidth {
+ case expectedDataWidth:
entry, err := parseARPEntry(columns)
if err != nil {
return []ARPEntry{}, fmt.Errorf("%w: Failed to parse ARP entry: %v: %w", ErrFileParse, entry, err)
}
entries = append(entries, entry)
- } else {
+ default:
return []ARPEntry{}, fmt.Errorf("%w: %d columns found, but expected %d: %w", ErrFileParse, width, expectedDataWidth, err)
}
diff --git a/vendor/github.com/prometheus/procfs/buddyinfo.go b/vendor/github.com/prometheus/procfs/buddyinfo.go
index 838075009..53243e687 100644
--- a/vendor/github.com/prometheus/procfs/buddyinfo.go
+++ b/vendor/github.com/prometheus/procfs/buddyinfo.go
@@ -1,4 +1,4 @@
-// Copyright 2017 The Prometheus Authors
+// Copyright The Prometheus Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
@@ -64,14 +64,12 @@ func parseBuddyInfo(r io.Reader) ([]BuddyInfo, error) {
if bucketCount == -1 {
bucketCount = arraySize
- } else {
- if bucketCount != arraySize {
- return nil, fmt.Errorf("%w: mismatch in number of buddyinfo buckets, previous count %d, new count %d", ErrFileParse, bucketCount, arraySize)
- }
+ } else if bucketCount != arraySize {
+ return nil, fmt.Errorf("%w: mismatch in number of buddyinfo buckets, previous count %d, new count %d", ErrFileParse, bucketCount, arraySize)
}
sizes := make([]float64, arraySize)
- for i := 0; i < arraySize; i++ {
+ for i := range arraySize {
sizes[i], err = strconv.ParseFloat(parts[i+4], 64)
if err != nil {
return nil, fmt.Errorf("%w: Invalid valid in buddyinfo: %f: %w", ErrFileParse, sizes[i], err)
diff --git a/vendor/github.com/prometheus/procfs/cmdline.go b/vendor/github.com/prometheus/procfs/cmdline.go
index bf4f3b48c..4f1cac1f0 100644
--- a/vendor/github.com/prometheus/procfs/cmdline.go
+++ b/vendor/github.com/prometheus/procfs/cmdline.go
@@ -1,4 +1,4 @@
-// Copyright 2021 The Prometheus Authors
+// Copyright The Prometheus Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
diff --git a/vendor/github.com/prometheus/procfs/cpuinfo.go b/vendor/github.com/prometheus/procfs/cpuinfo.go
index f0950bb49..4b23d8d6b 100644
--- a/vendor/github.com/prometheus/procfs/cpuinfo.go
+++ b/vendor/github.com/prometheus/procfs/cpuinfo.go
@@ -1,4 +1,4 @@
-// Copyright 2019 The Prometheus Authors
+// Copyright The Prometheus Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
@@ -12,7 +12,6 @@
// limitations under the License.
//go:build linux
-// +build linux
package procfs
@@ -502,7 +501,7 @@ func parseCPUInfoRISCV(info []byte) ([]CPUInfo, error) {
return cpuinfo, nil
}
-func parseCPUInfoDummy(_ []byte) ([]CPUInfo, error) { // nolint:unused,deadcode
+func parseCPUInfoDummy(_ []byte) ([]CPUInfo, error) { //nolint:unused
return nil, errors.New("not implemented")
}
diff --git a/vendor/github.com/prometheus/procfs/cpuinfo_armx.go b/vendor/github.com/prometheus/procfs/cpuinfo_armx.go
index 64cfd534c..b09035ff3 100644
--- a/vendor/github.com/prometheus/procfs/cpuinfo_armx.go
+++ b/vendor/github.com/prometheus/procfs/cpuinfo_armx.go
@@ -1,4 +1,4 @@
-// Copyright 2020 The Prometheus Authors
+// Copyright The Prometheus Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
@@ -12,8 +12,6 @@
// limitations under the License.
//go:build linux && (arm || arm64)
-// +build linux
-// +build arm arm64
package procfs
diff --git a/vendor/github.com/prometheus/procfs/cpuinfo_loong64.go b/vendor/github.com/prometheus/procfs/cpuinfo_loong64.go
index d88442f0e..7bb20211f 100644
--- a/vendor/github.com/prometheus/procfs/cpuinfo_loong64.go
+++ b/vendor/github.com/prometheus/procfs/cpuinfo_loong64.go
@@ -1,4 +1,4 @@
-// Copyright 2022 The Prometheus Authors
+// Copyright The Prometheus Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
@@ -12,7 +12,6 @@
// limitations under the License.
//go:build linux
-// +build linux
package procfs
diff --git a/vendor/github.com/prometheus/procfs/cpuinfo_mipsx.go b/vendor/github.com/prometheus/procfs/cpuinfo_mipsx.go
index c11207f3a..fd75d0f79 100644
--- a/vendor/github.com/prometheus/procfs/cpuinfo_mipsx.go
+++ b/vendor/github.com/prometheus/procfs/cpuinfo_mipsx.go
@@ -1,4 +1,4 @@
-// Copyright 2020 The Prometheus Authors
+// Copyright The Prometheus Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
@@ -12,8 +12,6 @@
// limitations under the License.
//go:build linux && (mips || mipsle || mips64 || mips64le)
-// +build linux
-// +build mips mipsle mips64 mips64le
package procfs
diff --git a/vendor/github.com/prometheus/procfs/cpuinfo_others.go b/vendor/github.com/prometheus/procfs/cpuinfo_others.go
index a6b2b3127..3d36ba0e6 100644
--- a/vendor/github.com/prometheus/procfs/cpuinfo_others.go
+++ b/vendor/github.com/prometheus/procfs/cpuinfo_others.go
@@ -1,4 +1,4 @@
-// Copyright 2020 The Prometheus Authors
+// Copyright The Prometheus Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
@@ -12,7 +12,6 @@
// limitations under the License.
//go:build linux && !386 && !amd64 && !arm && !arm64 && !loong64 && !mips && !mips64 && !mips64le && !mipsle && !ppc64 && !ppc64le && !riscv64 && !s390x
-// +build linux,!386,!amd64,!arm,!arm64,!loong64,!mips,!mips64,!mips64le,!mipsle,!ppc64,!ppc64le,!riscv64,!s390x
package procfs
diff --git a/vendor/github.com/prometheus/procfs/cpuinfo_ppcx.go b/vendor/github.com/prometheus/procfs/cpuinfo_ppcx.go
index 003bc2ad4..b3425051e 100644
--- a/vendor/github.com/prometheus/procfs/cpuinfo_ppcx.go
+++ b/vendor/github.com/prometheus/procfs/cpuinfo_ppcx.go
@@ -1,4 +1,4 @@
-// Copyright 2020 The Prometheus Authors
+// Copyright The Prometheus Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
@@ -12,8 +12,6 @@
// limitations under the License.
//go:build linux && (ppc64 || ppc64le)
-// +build linux
-// +build ppc64 ppc64le
package procfs
diff --git a/vendor/github.com/prometheus/procfs/cpuinfo_riscvx.go b/vendor/github.com/prometheus/procfs/cpuinfo_riscvx.go
index 1c9b7313b..72598230c 100644
--- a/vendor/github.com/prometheus/procfs/cpuinfo_riscvx.go
+++ b/vendor/github.com/prometheus/procfs/cpuinfo_riscvx.go
@@ -1,4 +1,4 @@
-// Copyright 2020 The Prometheus Authors
+// Copyright The Prometheus Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
@@ -12,8 +12,6 @@
// limitations under the License.
//go:build linux && (riscv || riscv64)
-// +build linux
-// +build riscv riscv64
package procfs
diff --git a/vendor/github.com/prometheus/procfs/cpuinfo_s390x.go b/vendor/github.com/prometheus/procfs/cpuinfo_s390x.go
index fa3686bc0..50a8239cb 100644
--- a/vendor/github.com/prometheus/procfs/cpuinfo_s390x.go
+++ b/vendor/github.com/prometheus/procfs/cpuinfo_s390x.go
@@ -1,4 +1,4 @@
-// Copyright 2020 The Prometheus Authors
+// Copyright The Prometheus Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
@@ -12,7 +12,6 @@
// limitations under the License.
//go:build linux
-// +build linux
package procfs
diff --git a/vendor/github.com/prometheus/procfs/cpuinfo_x86.go b/vendor/github.com/prometheus/procfs/cpuinfo_x86.go
index a0ef55562..00edb30a5 100644
--- a/vendor/github.com/prometheus/procfs/cpuinfo_x86.go
+++ b/vendor/github.com/prometheus/procfs/cpuinfo_x86.go
@@ -1,4 +1,4 @@
-// Copyright 2020 The Prometheus Authors
+// Copyright The Prometheus Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
@@ -12,8 +12,6 @@
// limitations under the License.
//go:build linux && (386 || amd64)
-// +build linux
-// +build 386 amd64
package procfs
diff --git a/vendor/github.com/prometheus/procfs/crypto.go b/vendor/github.com/prometheus/procfs/crypto.go
index 5f2a37a78..d93b712e0 100644
--- a/vendor/github.com/prometheus/procfs/crypto.go
+++ b/vendor/github.com/prometheus/procfs/crypto.go
@@ -1,4 +1,4 @@
-// Copyright 2019 The Prometheus Authors
+// Copyright The Prometheus Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
@@ -48,11 +48,13 @@ type Crypto struct {
Walksize *uint64
}
+var cryptoFile = "crypto"
+
// Crypto parses an crypto-file (/proc/crypto) and returns a slice of
// structs containing the relevant info. More information available here:
// https://kernel.readthedocs.io/en/sphinx-samples/crypto-API.html
func (fs FS) Crypto() ([]Crypto, error) {
- path := fs.proc.Path("crypto")
+ path := fs.proc.Path(cryptoFile)
b, err := util.ReadFileNoStat(path)
if err != nil {
return nil, fmt.Errorf("%w: Cannot read file %v: %w", ErrFileRead, b, err)
@@ -82,6 +84,10 @@ func parseCrypto(r io.Reader) ([]Crypto, error) {
continue
}
+ if len(out) == 0 {
+ return nil, fmt.Errorf("%w: parsed invalid line before name parsed: %q", ErrFileParse, text)
+ }
+
kv := strings.Split(text, ":")
if len(kv) != 2 {
return nil, fmt.Errorf("%w: Cannot parse line: %q", ErrFileParse, text)
diff --git a/vendor/github.com/prometheus/procfs/doc.go b/vendor/github.com/prometheus/procfs/doc.go
index f9d961e44..26bfea071 100644
--- a/vendor/github.com/prometheus/procfs/doc.go
+++ b/vendor/github.com/prometheus/procfs/doc.go
@@ -1,4 +1,4 @@
-// Copyright 2014 Prometheus Team
+// Copyright The Prometheus Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
diff --git a/vendor/github.com/prometheus/procfs/fs.go b/vendor/github.com/prometheus/procfs/fs.go
index 9bdaccc7c..8f27912a1 100644
--- a/vendor/github.com/prometheus/procfs/fs.go
+++ b/vendor/github.com/prometheus/procfs/fs.go
@@ -1,4 +1,4 @@
-// Copyright 2018 The Prometheus Authors
+// Copyright The Prometheus Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
diff --git a/vendor/github.com/prometheus/procfs/fs_statfs_notype.go b/vendor/github.com/prometheus/procfs/fs_statfs_notype.go
index 1b5bdbdf8..0bef25bdd 100644
--- a/vendor/github.com/prometheus/procfs/fs_statfs_notype.go
+++ b/vendor/github.com/prometheus/procfs/fs_statfs_notype.go
@@ -1,4 +1,4 @@
-// Copyright 2018 The Prometheus Authors
+// Copyright The Prometheus Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
@@ -12,7 +12,6 @@
// limitations under the License.
//go:build !freebsd && !linux
-// +build !freebsd,!linux
package procfs
diff --git a/vendor/github.com/prometheus/procfs/fs_statfs_type.go b/vendor/github.com/prometheus/procfs/fs_statfs_type.go
index 80df79c31..d18333039 100644
--- a/vendor/github.com/prometheus/procfs/fs_statfs_type.go
+++ b/vendor/github.com/prometheus/procfs/fs_statfs_type.go
@@ -1,4 +1,4 @@
-// Copyright 2018 The Prometheus Authors
+// Copyright The Prometheus Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
@@ -12,7 +12,6 @@
// limitations under the License.
//go:build freebsd || linux
-// +build freebsd linux
package procfs
diff --git a/vendor/github.com/prometheus/procfs/fscache.go b/vendor/github.com/prometheus/procfs/fscache.go
index 7db863307..9dde85707 100644
--- a/vendor/github.com/prometheus/procfs/fscache.go
+++ b/vendor/github.com/prometheus/procfs/fscache.go
@@ -1,4 +1,4 @@
-// Copyright 2019 The Prometheus Authors
+// Copyright The Prometheus Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
@@ -388,20 +388,21 @@ func parseFscacheinfo(r io.Reader) (*Fscacheinfo, error) {
}
}
case "CacheOp:":
- if strings.Split(fields[1], "=")[0] == "alo" {
+ switch strings.Split(fields[1], "=")[0] {
+ case "alo":
err := setFSCacheFields(fields[1:], &m.CacheopAllocationsinProgress, &m.CacheopLookupObjectInProgress,
&m.CacheopLookupCompleteInPorgress, &m.CacheopGrabObjectInProgress)
if err != nil {
return &m, err
}
- } else if strings.Split(fields[1], "=")[0] == "inv" {
+ case "inv":
err := setFSCacheFields(fields[1:], &m.CacheopInvalidations, &m.CacheopUpdateObjectInProgress,
&m.CacheopDropObjectInProgress, &m.CacheopPutObjectInProgress, &m.CacheopAttributeChangeInProgress,
&m.CacheopSyncCacheInProgress)
if err != nil {
return &m, err
}
- } else {
+ default:
err := setFSCacheFields(fields[1:], &m.CacheopReadOrAllocPageInProgress, &m.CacheopReadOrAllocPagesInProgress,
&m.CacheopAllocatePageInProgress, &m.CacheopAllocatePagesInProgress, &m.CacheopWritePagesInProgress,
&m.CacheopUncachePagesInProgress, &m.CacheopDissociatePagesInProgress)
diff --git a/vendor/github.com/prometheus/procfs/internal/fs/fs.go b/vendor/github.com/prometheus/procfs/internal/fs/fs.go
index 3a43e8391..e7ccad66b 100644
--- a/vendor/github.com/prometheus/procfs/internal/fs/fs.go
+++ b/vendor/github.com/prometheus/procfs/internal/fs/fs.go
@@ -1,4 +1,4 @@
-// Copyright 2019 The Prometheus Authors
+// Copyright The Prometheus Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
diff --git a/vendor/github.com/prometheus/procfs/internal/util/parse.go b/vendor/github.com/prometheus/procfs/internal/util/parse.go
index 5a7d2df06..30c587201 100644
--- a/vendor/github.com/prometheus/procfs/internal/util/parse.go
+++ b/vendor/github.com/prometheus/procfs/internal/util/parse.go
@@ -1,4 +1,4 @@
-// Copyright 2018 The Prometheus Authors
+// Copyright The Prometheus Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
diff --git a/vendor/github.com/prometheus/procfs/internal/util/readfile.go b/vendor/github.com/prometheus/procfs/internal/util/readfile.go
index 71b7a70eb..0e41f71af 100644
--- a/vendor/github.com/prometheus/procfs/internal/util/readfile.go
+++ b/vendor/github.com/prometheus/procfs/internal/util/readfile.go
@@ -1,4 +1,4 @@
-// Copyright 2019 The Prometheus Authors
+// Copyright The Prometheus Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
diff --git a/vendor/github.com/prometheus/procfs/internal/util/sysreadfile.go b/vendor/github.com/prometheus/procfs/internal/util/sysreadfile.go
index d5404a6d7..f6a4a4de6 100644
--- a/vendor/github.com/prometheus/procfs/internal/util/sysreadfile.go
+++ b/vendor/github.com/prometheus/procfs/internal/util/sysreadfile.go
@@ -1,4 +1,4 @@
-// Copyright 2018 The Prometheus Authors
+// Copyright The Prometheus Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
@@ -12,8 +12,6 @@
// limitations under the License.
//go:build (linux || darwin) && !appengine
-// +build linux darwin
-// +build !appengine
package util
diff --git a/vendor/github.com/prometheus/procfs/internal/util/sysreadfile_compat.go b/vendor/github.com/prometheus/procfs/internal/util/sysreadfile_compat.go
index 1d86f5e63..c80e082cb 100644
--- a/vendor/github.com/prometheus/procfs/internal/util/sysreadfile_compat.go
+++ b/vendor/github.com/prometheus/procfs/internal/util/sysreadfile_compat.go
@@ -1,4 +1,4 @@
-// Copyright 2019 The Prometheus Authors
+// Copyright The Prometheus Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
@@ -12,7 +12,6 @@
// limitations under the License.
//go:build (linux && appengine) || (!linux && !darwin)
-// +build linux,appengine !linux,!darwin
package util
diff --git a/vendor/github.com/prometheus/procfs/internal/util/valueparser.go b/vendor/github.com/prometheus/procfs/internal/util/valueparser.go
index fe2355d3c..e0ed671ea 100644
--- a/vendor/github.com/prometheus/procfs/internal/util/valueparser.go
+++ b/vendor/github.com/prometheus/procfs/internal/util/valueparser.go
@@ -1,4 +1,4 @@
-// Copyright 2019 The Prometheus Authors
+// Copyright The Prometheus Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
diff --git a/vendor/github.com/prometheus/procfs/ipvs.go b/vendor/github.com/prometheus/procfs/ipvs.go
index bc3a20c93..5374da9fa 100644
--- a/vendor/github.com/prometheus/procfs/ipvs.go
+++ b/vendor/github.com/prometheus/procfs/ipvs.go
@@ -1,4 +1,4 @@
-// Copyright 2018 The Prometheus Authors
+// Copyright The Prometheus Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
diff --git a/vendor/github.com/prometheus/procfs/kernel_hung.go b/vendor/github.com/prometheus/procfs/kernel_hung.go
new file mode 100644
index 000000000..0c7a69f99
--- /dev/null
+++ b/vendor/github.com/prometheus/procfs/kernel_hung.go
@@ -0,0 +1,44 @@
+// Copyright The Prometheus Authors
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+//go:build !windows
+
+package procfs
+
+import (
+ "os"
+ "strconv"
+ "strings"
+)
+
+// KernelHung contains information about to the kernel's hung_task_detect_count number.
+type KernelHung struct {
+ // Indicates the total number of tasks that have been detected as hung since the system boot.
+ // This file shows up if `CONFIG_DETECT_HUNG_TASK` is enabled.
+ HungTaskDetectCount *uint64
+}
+
+// KernelHung returns values from /proc/sys/kernel/hung_task_detect_count.
+func (fs FS) KernelHung() (KernelHung, error) {
+ data, err := os.ReadFile(fs.proc.Path("sys", "kernel", "hung_task_detect_count"))
+ if err != nil {
+ return KernelHung{}, err
+ }
+ val, err := strconv.ParseUint(strings.TrimSpace(string(data)), 10, 64)
+ if err != nil {
+ return KernelHung{}, err
+ }
+ return KernelHung{
+ HungTaskDetectCount: &val,
+ }, nil
+}
diff --git a/vendor/github.com/prometheus/procfs/kernel_random.go b/vendor/github.com/prometheus/procfs/kernel_random.go
index db88566bd..e7c5b8cf2 100644
--- a/vendor/github.com/prometheus/procfs/kernel_random.go
+++ b/vendor/github.com/prometheus/procfs/kernel_random.go
@@ -1,4 +1,4 @@
-// Copyright 2020 The Prometheus Authors
+// Copyright The Prometheus Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
@@ -12,7 +12,6 @@
// limitations under the License.
//go:build !windows
-// +build !windows
package procfs
diff --git a/vendor/github.com/prometheus/procfs/loadavg.go b/vendor/github.com/prometheus/procfs/loadavg.go
index 332e76c17..c8c78a65e 100644
--- a/vendor/github.com/prometheus/procfs/loadavg.go
+++ b/vendor/github.com/prometheus/procfs/loadavg.go
@@ -1,4 +1,4 @@
-// Copyright 2019 The Prometheus Authors
+// Copyright The Prometheus Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
diff --git a/vendor/github.com/prometheus/procfs/mdstat.go b/vendor/github.com/prometheus/procfs/mdstat.go
index 67a9d2b44..d66eeda82 100644
--- a/vendor/github.com/prometheus/procfs/mdstat.go
+++ b/vendor/github.com/prometheus/procfs/mdstat.go
@@ -1,4 +1,4 @@
-// Copyright 2018 The Prometheus Authors
+// Copyright The Prometheus Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
@@ -27,13 +27,34 @@ var (
recoveryLinePctRE = regexp.MustCompile(`= (.+)%`)
recoveryLineFinishRE = regexp.MustCompile(`finish=(.+)min`)
recoveryLineSpeedRE = regexp.MustCompile(`speed=(.+)[A-Z]`)
- componentDeviceRE = regexp.MustCompile(`(.*)\[\d+\]`)
+ componentDeviceRE = regexp.MustCompile(`(.*)\[(\d+)\](\([SF]+\))?`)
+ personalitiesPrefix = "Personalities : "
)
+type MDStatComponent struct {
+ // Name of the component device.
+ Name string
+ // DescriptorIndex number of component device, e.g. the order in the superblock.
+ DescriptorIndex int32
+ // Flags per Linux drivers/md/md.[ch] as of v6.12-rc1
+ // Subset that are exposed in mdstat
+ WriteMostly bool
+ Journal bool
+ Faulty bool // "Faulty" is what kernel source uses for "(F)"
+ Spare bool
+ Replacement bool
+ // Some additional flags that are NOT exposed in procfs today; they may
+ // be available via sysfs.
+ // In_sync, Bitmap_sync, Blocked, WriteErrorSeen, FaultRecorded,
+ // BlockedBadBlocks, WantReplacement, Candidate, ...
+}
+
// MDStat holds info parsed from /proc/mdstat.
type MDStat struct {
// Name of the device.
Name string
+ // raid type of the device.
+ Type string
// activity-state of the device.
ActivityState string
// Number of active disks.
@@ -58,8 +79,8 @@ type MDStat struct {
BlocksSyncedFinishTime float64
// current sync speed (in Kilobytes/sec)
BlocksSyncedSpeed float64
- // Name of md component devices
- Devices []string
+ // component devices
+ Devices []MDStatComponent
}
// MDStat parses an mdstat-file (/proc/mdstat) and returns a slice of
@@ -80,28 +101,52 @@ func (fs FS) MDStat() ([]MDStat, error) {
// parseMDStat parses data from mdstat file (/proc/mdstat) and returns a slice of
// structs containing the relevant info.
func parseMDStat(mdStatData []byte) ([]MDStat, error) {
+ // TODO:
+ // - parse global hotspares from the "unused devices" line.
mdStats := []MDStat{}
lines := strings.Split(string(mdStatData), "\n")
+ knownRaidTypes := make(map[string]bool)
for i, line := range lines {
if strings.TrimSpace(line) == "" || line[0] == ' ' ||
- strings.HasPrefix(line, "Personalities") ||
strings.HasPrefix(line, "unused") {
continue
}
+ // Personalities : [linear] [multipath] [raid0] [raid1] [raid6] [raid5] [raid4] [raid10]
+ if len(knownRaidTypes) == 0 && strings.HasPrefix(line, personalitiesPrefix) {
+ personalities := strings.Fields(line[len(personalitiesPrefix):])
+ for _, word := range personalities {
+ word := word[1 : len(word)-1]
+ knownRaidTypes[word] = true
+ }
+ continue
+ }
deviceFields := strings.Fields(line)
if len(deviceFields) < 3 {
return nil, fmt.Errorf("%w: Expected 3+ lines, got %q", ErrFileParse, line)
}
mdName := deviceFields[0] // mdx
- state := deviceFields[2] // active or inactive
+ state := deviceFields[2] // active, inactive, broken
+
+ mdType := "unknown" // raid1, raid5, etc.
+ var deviceStartIndex int
+ if len(deviceFields) > 3 { // mdType may be in the 3rd or 4th field
+ if isRaidType(deviceFields[3], knownRaidTypes) {
+ mdType = deviceFields[3]
+ deviceStartIndex = 4
+ } else if len(deviceFields) > 4 && isRaidType(deviceFields[4], knownRaidTypes) {
+ // if the 3rd field is (...), the 4th field is the mdType
+ mdType = deviceFields[4]
+ deviceStartIndex = 5
+ }
+ }
if len(lines) <= i+3 {
return nil, fmt.Errorf("%w: Too few lines for md device: %q", ErrFileParse, mdName)
}
- // Failed disks have the suffix (F) & Spare disks have the suffix (S).
+ // Failed (Faulty) disks have the suffix (F) & Spare disks have the suffix (S).
fail := int64(strings.Count(line, "(F)"))
spare := int64(strings.Count(line, "(S)"))
active, total, down, size, err := evalStatusLine(lines[i], lines[i+1])
@@ -123,16 +168,20 @@ func parseMDStat(mdStatData []byte) ([]MDStat, error) {
finish := float64(0)
pct := float64(0)
recovering := strings.Contains(lines[syncLineIdx], "recovery")
+ reshaping := strings.Contains(lines[syncLineIdx], "reshape")
resyncing := strings.Contains(lines[syncLineIdx], "resync")
checking := strings.Contains(lines[syncLineIdx], "check")
// Append recovery and resyncing state info.
- if recovering || resyncing || checking {
- if recovering {
+ if recovering || resyncing || checking || reshaping {
+ switch {
+ case recovering:
state = "recovering"
- } else if checking {
+ case reshaping:
+ state = "reshaping"
+ case checking:
state = "checking"
- } else {
+ default:
state = "resyncing"
}
@@ -148,8 +197,14 @@ func parseMDStat(mdStatData []byte) ([]MDStat, error) {
}
}
+ devices, err := evalComponentDevices(deviceFields[deviceStartIndex:])
+ if err != nil {
+ return nil, fmt.Errorf("error parsing components in md device %q: %w", mdName, err)
+ }
+
mdStats = append(mdStats, MDStat{
Name: mdName,
+ Type: mdType,
ActivityState: state,
DisksActive: active,
DisksFailed: fail,
@@ -162,14 +217,24 @@ func parseMDStat(mdStatData []byte) ([]MDStat, error) {
BlocksSyncedPct: pct,
BlocksSyncedFinishTime: finish,
BlocksSyncedSpeed: speed,
- Devices: evalComponentDevices(deviceFields),
+ Devices: devices,
})
}
return mdStats, nil
}
+// check if a string's format is like the mdType
+// Rule 1: mdType should not be like (...)
+// Rule 2: mdType should not be like sda[0]
+// .
+func isRaidType(mdType string, knownRaidTypes map[string]bool) bool {
+ _, ok := knownRaidTypes[mdType]
+ return !strings.ContainsAny(mdType, "([") && ok
+}
+
func evalStatusLine(deviceLine, statusLine string) (active, total, down, size int64, err error) {
+ // e.g. 523968 blocks super 1.2 [4/4] [UUUU]
statusFields := strings.Fields(statusLine)
if len(statusFields) < 1 {
return 0, 0, 0, 0, fmt.Errorf("%w: Unexpected statusline %q: %w", ErrFileParse, statusLine, err)
@@ -260,17 +325,29 @@ func evalRecoveryLine(recoveryLine string) (blocksSynced int64, blocksToBeSynced
return blocksSynced, blocksToBeSynced, pct, finish, speed, nil
}
-func evalComponentDevices(deviceFields []string) []string {
- mdComponentDevices := make([]string, 0)
- if len(deviceFields) > 3 {
- for _, field := range deviceFields[4:] {
- match := componentDeviceRE.FindStringSubmatch(field)
- if match == nil {
- continue
- }
- mdComponentDevices = append(mdComponentDevices, match[1])
+func evalComponentDevices(deviceFields []string) ([]MDStatComponent, error) {
+ mdComponentDevices := make([]MDStatComponent, 0)
+ for _, field := range deviceFields {
+ match := componentDeviceRE.FindStringSubmatch(field)
+ if match == nil {
+ continue
+ }
+ descriptorIndex, err := strconv.ParseInt(match[2], 10, 32)
+ if err != nil {
+ return mdComponentDevices, fmt.Errorf("error parsing int from device %q: %w", match[2], err)
}
+ mdComponentDevices = append(mdComponentDevices, MDStatComponent{
+ Name: match[1],
+ DescriptorIndex: int32(descriptorIndex),
+ // match may contain one or more of these
+ // https://github.com/torvalds/linux/blob/7ec462100ef9142344ddbf86f2c3008b97acddbe/drivers/md/md.c#L8376-L8392
+ Faulty: strings.Contains(match[3], "(F)"),
+ Spare: strings.Contains(match[3], "(S)"),
+ Journal: strings.Contains(match[3], "(J)"),
+ Replacement: strings.Contains(match[3], "(R)"),
+ WriteMostly: strings.Contains(match[3], "(W)"),
+ })
}
- return mdComponentDevices
+ return mdComponentDevices, nil
}
diff --git a/vendor/github.com/prometheus/procfs/meminfo.go b/vendor/github.com/prometheus/procfs/meminfo.go
index 4b2c4050a..342038318 100644
--- a/vendor/github.com/prometheus/procfs/meminfo.go
+++ b/vendor/github.com/prometheus/procfs/meminfo.go
@@ -1,4 +1,4 @@
-// Copyright 2019 The Prometheus Authors
+// Copyright The Prometheus Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
@@ -66,6 +66,10 @@ type Meminfo struct {
// Memory which has been evicted from RAM, and is temporarily
// on the disk
SwapFree *uint64
+ // Memory consumed by the zswap backend (compressed size)
+ Zswap *uint64
+ // Amount of anonymous memory stored in zswap (original size)
+ Zswapped *uint64
// Memory which is waiting to get written back to the disk
Dirty *uint64
// Memory which is actively being written back to the disk
@@ -85,6 +89,8 @@ type Meminfo struct {
// amount of memory dedicated to the lowest level of page
// tables.
PageTables *uint64
+ // secondary page tables.
+ SecPageTables *uint64
// NFS pages sent to the server, but not yet committed to
// stable storage
NFSUnstable *uint64
@@ -129,15 +135,18 @@ type Meminfo struct {
Percpu *uint64
HardwareCorrupted *uint64
AnonHugePages *uint64
+ FileHugePages *uint64
ShmemHugePages *uint64
ShmemPmdMapped *uint64
CmaTotal *uint64
CmaFree *uint64
+ Unaccepted *uint64
HugePagesTotal *uint64
HugePagesFree *uint64
HugePagesRsvd *uint64
HugePagesSurp *uint64
Hugepagesize *uint64
+ Hugetlb *uint64
DirectMap4k *uint64
DirectMap2M *uint64
DirectMap1G *uint64
@@ -161,6 +170,8 @@ type Meminfo struct {
MlockedBytes *uint64
SwapTotalBytes *uint64
SwapFreeBytes *uint64
+ ZswapBytes *uint64
+ ZswappedBytes *uint64
DirtyBytes *uint64
WritebackBytes *uint64
AnonPagesBytes *uint64
@@ -171,6 +182,7 @@ type Meminfo struct {
SUnreclaimBytes *uint64
KernelStackBytes *uint64
PageTablesBytes *uint64
+ SecPageTablesBytes *uint64
NFSUnstableBytes *uint64
BounceBytes *uint64
WritebackTmpBytes *uint64
@@ -182,11 +194,14 @@ type Meminfo struct {
PercpuBytes *uint64
HardwareCorruptedBytes *uint64
AnonHugePagesBytes *uint64
+ FileHugePagesBytes *uint64
ShmemHugePagesBytes *uint64
ShmemPmdMappedBytes *uint64
CmaTotalBytes *uint64
CmaFreeBytes *uint64
+ UnacceptedBytes *uint64
HugepagesizeBytes *uint64
+ HugetlbBytes *uint64
DirectMap4kBytes *uint64
DirectMap2MBytes *uint64
DirectMap1GBytes *uint64
@@ -287,6 +302,12 @@ func parseMemInfo(r io.Reader) (*Meminfo, error) {
case "SwapFree:":
m.SwapFree = &val
m.SwapFreeBytes = &valBytes
+ case "Zswap:":
+ m.Zswap = &val
+ m.ZswapBytes = &valBytes
+ case "Zswapped:":
+ m.Zswapped = &val
+ m.ZswappedBytes = &valBytes
case "Dirty:":
m.Dirty = &val
m.DirtyBytes = &valBytes
@@ -317,6 +338,9 @@ func parseMemInfo(r io.Reader) (*Meminfo, error) {
case "PageTables:":
m.PageTables = &val
m.PageTablesBytes = &valBytes
+ case "SecPageTables:":
+ m.SecPageTables = &val
+ m.SecPageTablesBytes = &valBytes
case "NFS_Unstable:":
m.NFSUnstable = &val
m.NFSUnstableBytes = &valBytes
@@ -350,6 +374,9 @@ func parseMemInfo(r io.Reader) (*Meminfo, error) {
case "AnonHugePages:":
m.AnonHugePages = &val
m.AnonHugePagesBytes = &valBytes
+ case "FileHugePages:":
+ m.FileHugePages = &val
+ m.FileHugePagesBytes = &valBytes
case "ShmemHugePages:":
m.ShmemHugePages = &val
m.ShmemHugePagesBytes = &valBytes
@@ -362,6 +389,9 @@ func parseMemInfo(r io.Reader) (*Meminfo, error) {
case "CmaFree:":
m.CmaFree = &val
m.CmaFreeBytes = &valBytes
+ case "Unaccepted:":
+ m.Unaccepted = &val
+ m.UnacceptedBytes = &valBytes
case "HugePages_Total:":
m.HugePagesTotal = &val
case "HugePages_Free:":
@@ -373,6 +403,9 @@ func parseMemInfo(r io.Reader) (*Meminfo, error) {
case "Hugepagesize:":
m.Hugepagesize = &val
m.HugepagesizeBytes = &valBytes
+ case "Hugetlb:":
+ m.Hugetlb = &val
+ m.HugetlbBytes = &valBytes
case "DirectMap4k:":
m.DirectMap4k = &val
m.DirectMap4kBytes = &valBytes
diff --git a/vendor/github.com/prometheus/procfs/mountinfo.go b/vendor/github.com/prometheus/procfs/mountinfo.go
index a704c5e73..8594ae7f1 100644
--- a/vendor/github.com/prometheus/procfs/mountinfo.go
+++ b/vendor/github.com/prometheus/procfs/mountinfo.go
@@ -1,4 +1,4 @@
-// Copyright 2019 The Prometheus Authors
+// Copyright The Prometheus Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
@@ -17,10 +17,10 @@ import (
"bufio"
"bytes"
"fmt"
+ "io"
+ "os"
"strconv"
"strings"
-
- "github.com/prometheus/procfs/internal/util"
)
// A MountInfo is a type that describes the details, options
@@ -147,8 +147,7 @@ func mountOptionsParseOptionalFields(o []string) (map[string]string, error) {
// mountOptionsParser parses the mount options, superblock options.
func mountOptionsParser(mountOptions string) map[string]string {
opts := make(map[string]string)
- options := strings.Split(mountOptions, ",")
- for _, opt := range options {
+ for opt := range strings.SplitSeq(mountOptions, ",") {
splitOption := strings.Split(opt, "=")
if len(splitOption) < 2 {
key := splitOption[0]
@@ -161,9 +160,19 @@ func mountOptionsParser(mountOptions string) map[string]string {
return opts
}
+// readMountInfo reads a full mountinfo file (no 1 MiB cap, unlike util.ReadFileNoStat).
+func readMountInfo(path string) ([]byte, error) {
+ f, err := os.Open(path)
+ if err != nil {
+ return nil, err
+ }
+ defer f.Close()
+ return io.ReadAll(f)
+}
+
// GetMounts retrieves mountinfo information from `/proc/self/mountinfo`.
func GetMounts() ([]*MountInfo, error) {
- data, err := util.ReadFileNoStat("/proc/self/mountinfo")
+ data, err := readMountInfo("/proc/self/mountinfo")
if err != nil {
return nil, err
}
@@ -172,7 +181,25 @@ func GetMounts() ([]*MountInfo, error) {
// GetProcMounts retrieves mountinfo information from a processes' `/proc//mountinfo`.
func GetProcMounts(pid int) ([]*MountInfo, error) {
- data, err := util.ReadFileNoStat(fmt.Sprintf("/proc/%d/mountinfo", pid))
+ data, err := readMountInfo(fmt.Sprintf("/proc/%d/mountinfo", pid))
+ if err != nil {
+ return nil, err
+ }
+ return parseMountInfo(data)
+}
+
+// GetMounts retrieves mountinfo information from `/proc/self/mountinfo`.
+func (fs FS) GetMounts() ([]*MountInfo, error) {
+ data, err := readMountInfo(fs.proc.Path("self/mountinfo"))
+ if err != nil {
+ return nil, err
+ }
+ return parseMountInfo(data)
+}
+
+// GetProcMounts retrieves mountinfo information from a processes' `/proc//mountinfo`.
+func (fs FS) GetProcMounts(pid int) ([]*MountInfo, error) {
+ data, err := readMountInfo(fs.proc.Path(fmt.Sprintf("%d/mountinfo", pid)))
if err != nil {
return nil, err
}
diff --git a/vendor/github.com/prometheus/procfs/mountstats.go b/vendor/github.com/prometheus/procfs/mountstats.go
index 50caa7327..e503cb3a6 100644
--- a/vendor/github.com/prometheus/procfs/mountstats.go
+++ b/vendor/github.com/prometheus/procfs/mountstats.go
@@ -1,4 +1,4 @@
-// Copyright 2018 The Prometheus Authors
+// Copyright The Prometheus Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
@@ -383,7 +383,7 @@ func parseMountStatsNFS(s *bufio.Scanner, statVersion string) (*MountStatsNFS, e
if stats.Opts == nil {
stats.Opts = map[string]string{}
}
- for _, opt := range strings.Split(ss[1], ",") {
+ for opt := range strings.SplitSeq(ss[1], ",") {
split := strings.Split(opt, "=")
if len(split) == 2 {
stats.Opts[split[0]] = split[1]
diff --git a/vendor/github.com/prometheus/procfs/net_conntrackstat.go b/vendor/github.com/prometheus/procfs/net_conntrackstat.go
index 316df5fbb..e9ca35707 100644
--- a/vendor/github.com/prometheus/procfs/net_conntrackstat.go
+++ b/vendor/github.com/prometheus/procfs/net_conntrackstat.go
@@ -1,4 +1,4 @@
-// Copyright 2020 The Prometheus Authors
+// Copyright The Prometheus Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
diff --git a/vendor/github.com/prometheus/procfs/net_dev.go b/vendor/github.com/prometheus/procfs/net_dev.go
index e66208aa0..7b3e1d61c 100644
--- a/vendor/github.com/prometheus/procfs/net_dev.go
+++ b/vendor/github.com/prometheus/procfs/net_dev.go
@@ -1,4 +1,4 @@
-// Copyright 2018 The Prometheus Authors
+// Copyright The Prometheus Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
diff --git a/vendor/github.com/prometheus/procfs/net_dev_snmp6.go b/vendor/github.com/prometheus/procfs/net_dev_snmp6.go
index f50b38e35..2a0f60f29 100644
--- a/vendor/github.com/prometheus/procfs/net_dev_snmp6.go
+++ b/vendor/github.com/prometheus/procfs/net_dev_snmp6.go
@@ -1,4 +1,4 @@
-// Copyright 2018 The Prometheus Authors
+// Copyright The Prometheus Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
@@ -18,6 +18,7 @@ import (
"errors"
"io"
"os"
+ "path/filepath"
"strconv"
"strings"
)
@@ -56,7 +57,9 @@ func newNetDevSNMP6(dir string) (NetDevSNMP6, error) {
}
for _, iFaceFile := range ifaceFiles {
- f, err := os.Open(dir + "/" + iFaceFile.Name())
+ filePath := filepath.Join(dir, iFaceFile.Name())
+
+ f, err := os.Open(filePath)
if err != nil {
return netDevSNMP6, err
}
diff --git a/vendor/github.com/prometheus/procfs/net_ip_socket.go b/vendor/github.com/prometheus/procfs/net_ip_socket.go
index 19e3378f7..9291f8cd4 100644
--- a/vendor/github.com/prometheus/procfs/net_ip_socket.go
+++ b/vendor/github.com/prometheus/procfs/net_ip_socket.go
@@ -1,4 +1,4 @@
-// Copyright 2020 The Prometheus Authors
+// Copyright The Prometheus Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
diff --git a/vendor/github.com/prometheus/procfs/net_protocols.go b/vendor/github.com/prometheus/procfs/net_protocols.go
index 8d4b1ac05..eaa996cbc 100644
--- a/vendor/github.com/prometheus/procfs/net_protocols.go
+++ b/vendor/github.com/prometheus/procfs/net_protocols.go
@@ -1,4 +1,4 @@
-// Copyright 2020 The Prometheus Authors
+// Copyright The Prometheus Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
@@ -169,7 +169,7 @@ func (pc *NetProtocolCapabilities) parseCapabilities(capabilities []string) erro
&pc.EnterMemoryPressure,
}
- for i := 0; i < len(capabilities); i++ {
+ for i := range capabilities {
switch capabilities[i] {
case "y":
*capabilityFields[i] = true
diff --git a/vendor/github.com/prometheus/procfs/net_route.go b/vendor/github.com/prometheus/procfs/net_route.go
index deb7029fe..fa3812d9d 100644
--- a/vendor/github.com/prometheus/procfs/net_route.go
+++ b/vendor/github.com/prometheus/procfs/net_route.go
@@ -1,4 +1,4 @@
-// Copyright 2023 The Prometheus Authors
+// Copyright The Prometheus Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
diff --git a/vendor/github.com/prometheus/procfs/net_sockstat.go b/vendor/github.com/prometheus/procfs/net_sockstat.go
index fae62b13d..8b221ebff 100644
--- a/vendor/github.com/prometheus/procfs/net_sockstat.go
+++ b/vendor/github.com/prometheus/procfs/net_sockstat.go
@@ -1,4 +1,4 @@
-// Copyright 2019 The Prometheus Authors
+// Copyright The Prometheus Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
@@ -139,9 +139,6 @@ func parseSockstatKVs(kvs []string) (map[string]int, error) {
func parseSockstatProtocol(kvs map[string]int) NetSockstatProtocol {
var nsp NetSockstatProtocol
for k, v := range kvs {
- // Capture the range variable to ensure we get unique pointers for
- // each of the optional fields.
- v := v
switch k {
case "inuse":
nsp.InUse = v
diff --git a/vendor/github.com/prometheus/procfs/net_softnet.go b/vendor/github.com/prometheus/procfs/net_softnet.go
index 71c8059f4..4a2dfa18f 100644
--- a/vendor/github.com/prometheus/procfs/net_softnet.go
+++ b/vendor/github.com/prometheus/procfs/net_softnet.go
@@ -1,4 +1,4 @@
-// Copyright 2019 The Prometheus Authors
+// Copyright The Prometheus Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
diff --git a/vendor/github.com/prometheus/procfs/net_tcp.go b/vendor/github.com/prometheus/procfs/net_tcp.go
index 0396d7201..2c7f9bc7c 100644
--- a/vendor/github.com/prometheus/procfs/net_tcp.go
+++ b/vendor/github.com/prometheus/procfs/net_tcp.go
@@ -1,4 +1,4 @@
-// Copyright 2020 The Prometheus Authors
+// Copyright The Prometheus Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
@@ -25,6 +25,7 @@ type (
// NetTCP returns the IPv4 kernel/networking statistics for TCP datagrams
// read from /proc/net/tcp.
+//
// Deprecated: Use github.com/mdlayher/netlink#Conn (with syscall.AF_INET) instead.
func (fs FS) NetTCP() (NetTCP, error) {
return newNetTCP(fs.proc.Path("net/tcp"))
@@ -32,6 +33,7 @@ func (fs FS) NetTCP() (NetTCP, error) {
// NetTCP6 returns the IPv6 kernel/networking statistics for TCP datagrams
// read from /proc/net/tcp6.
+//
// Deprecated: Use github.com/mdlayher/netlink#Conn (with syscall.AF_INET6) instead.
func (fs FS) NetTCP6() (NetTCP, error) {
return newNetTCP(fs.proc.Path("net/tcp6"))
@@ -39,6 +41,7 @@ func (fs FS) NetTCP6() (NetTCP, error) {
// NetTCPSummary returns already computed statistics like the total queue lengths
// for TCP datagrams read from /proc/net/tcp.
+//
// Deprecated: Use github.com/mdlayher/netlink#Conn (with syscall.AF_INET) instead.
func (fs FS) NetTCPSummary() (*NetTCPSummary, error) {
return newNetTCPSummary(fs.proc.Path("net/tcp"))
@@ -46,6 +49,7 @@ func (fs FS) NetTCPSummary() (*NetTCPSummary, error) {
// NetTCP6Summary returns already computed statistics like the total queue lengths
// for TCP datagrams read from /proc/net/tcp6.
+//
// Deprecated: Use github.com/mdlayher/netlink#Conn (with syscall.AF_INET6) instead.
func (fs FS) NetTCP6Summary() (*NetTCPSummary, error) {
return newNetTCPSummary(fs.proc.Path("net/tcp6"))
diff --git a/vendor/github.com/prometheus/procfs/net_tls_stat.go b/vendor/github.com/prometheus/procfs/net_tls_stat.go
index 13994c178..b1b3f6a6a 100644
--- a/vendor/github.com/prometheus/procfs/net_tls_stat.go
+++ b/vendor/github.com/prometheus/procfs/net_tls_stat.go
@@ -1,4 +1,4 @@
-// Copyright 2023 Prometheus Team
+// Copyright The Prometheus Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
diff --git a/vendor/github.com/prometheus/procfs/net_udp.go b/vendor/github.com/prometheus/procfs/net_udp.go
index 9ac3daf2d..8a3277910 100644
--- a/vendor/github.com/prometheus/procfs/net_udp.go
+++ b/vendor/github.com/prometheus/procfs/net_udp.go
@@ -1,4 +1,4 @@
-// Copyright 2020 The Prometheus Authors
+// Copyright The Prometheus Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
diff --git a/vendor/github.com/prometheus/procfs/net_unix.go b/vendor/github.com/prometheus/procfs/net_unix.go
index d7e0cacb4..e4d635923 100644
--- a/vendor/github.com/prometheus/procfs/net_unix.go
+++ b/vendor/github.com/prometheus/procfs/net_unix.go
@@ -1,4 +1,4 @@
-// Copyright 2018 The Prometheus Authors
+// Copyright The Prometheus Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
diff --git a/vendor/github.com/prometheus/procfs/net_wireless.go b/vendor/github.com/prometheus/procfs/net_wireless.go
index 7c597bc87..f74dd3bed 100644
--- a/vendor/github.com/prometheus/procfs/net_wireless.go
+++ b/vendor/github.com/prometheus/procfs/net_wireless.go
@@ -1,4 +1,4 @@
-// Copyright 2023 The Prometheus Authors
+// Copyright The Prometheus Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
@@ -114,47 +114,47 @@ func parseWireless(r io.Reader) ([]*Wireless, error) {
qlink, err := strconv.Atoi(strings.TrimSuffix(stats[1], "."))
if err != nil {
- return nil, fmt.Errorf("%w: parse Quality:link as integer %q: %w", ErrFileParse, qlink, err)
+ return nil, fmt.Errorf("%w: parse Quality:link as integer %q: %w", ErrFileParse, stats[1], err)
}
qlevel, err := strconv.Atoi(strings.TrimSuffix(stats[2], "."))
if err != nil {
- return nil, fmt.Errorf("%w: Quality:level as integer %q: %w", ErrFileParse, qlevel, err)
+ return nil, fmt.Errorf("%w: Quality:level as integer %q: %w", ErrFileParse, stats[2], err)
}
qnoise, err := strconv.Atoi(strings.TrimSuffix(stats[3], "."))
if err != nil {
- return nil, fmt.Errorf("%w: Quality:noise as integer %q: %w", ErrFileParse, qnoise, err)
+ return nil, fmt.Errorf("%w: Quality:noise as integer %q: %w", ErrFileParse, stats[3], err)
}
dnwid, err := strconv.Atoi(stats[4])
if err != nil {
- return nil, fmt.Errorf("%w: Discarded:nwid as integer %q: %w", ErrFileParse, dnwid, err)
+ return nil, fmt.Errorf("%w: Discarded:nwid as integer %q: %w", ErrFileParse, stats[4], err)
}
dcrypt, err := strconv.Atoi(stats[5])
if err != nil {
- return nil, fmt.Errorf("%w: Discarded:crypt as integer %q: %w", ErrFileParse, dcrypt, err)
+ return nil, fmt.Errorf("%w: Discarded:crypt as integer %q: %w", ErrFileParse, stats[5], err)
}
dfrag, err := strconv.Atoi(stats[6])
if err != nil {
- return nil, fmt.Errorf("%w: Discarded:frag as integer %q: %w", ErrFileParse, dfrag, err)
+ return nil, fmt.Errorf("%w: Discarded:frag as integer %q: %w", ErrFileParse, stats[6], err)
}
dretry, err := strconv.Atoi(stats[7])
if err != nil {
- return nil, fmt.Errorf("%w: Discarded:retry as integer %q: %w", ErrFileParse, dretry, err)
+ return nil, fmt.Errorf("%w: Discarded:retry as integer %q: %w", ErrFileParse, stats[7], err)
}
dmisc, err := strconv.Atoi(stats[8])
if err != nil {
- return nil, fmt.Errorf("%w: Discarded:misc as integer %q: %w", ErrFileParse, dmisc, err)
+ return nil, fmt.Errorf("%w: Discarded:misc as integer %q: %w", ErrFileParse, stats[8], err)
}
mbeacon, err := strconv.Atoi(stats[9])
if err != nil {
- return nil, fmt.Errorf("%w: Missed:beacon as integer %q: %w", ErrFileParse, mbeacon, err)
+ return nil, fmt.Errorf("%w: Missed:beacon as integer %q: %w", ErrFileParse, stats[9], err)
}
w := &Wireless{
diff --git a/vendor/github.com/prometheus/procfs/net_xfrm.go b/vendor/github.com/prometheus/procfs/net_xfrm.go
index 932ef2046..5a9f497d1 100644
--- a/vendor/github.com/prometheus/procfs/net_xfrm.go
+++ b/vendor/github.com/prometheus/procfs/net_xfrm.go
@@ -1,4 +1,4 @@
-// Copyright 2017 Prometheus Team
+// Copyright The Prometheus Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
diff --git a/vendor/github.com/prometheus/procfs/netstat.go b/vendor/github.com/prometheus/procfs/netstat.go
index 742dff453..dbdae4739 100644
--- a/vendor/github.com/prometheus/procfs/netstat.go
+++ b/vendor/github.com/prometheus/procfs/netstat.go
@@ -1,4 +1,4 @@
-// Copyright 2020 The Prometheus Authors
+// Copyright The Prometheus Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
diff --git a/vendor/github.com/prometheus/procfs/nfnetlink_queue.go b/vendor/github.com/prometheus/procfs/nfnetlink_queue.go
new file mode 100644
index 000000000..b0a73b11e
--- /dev/null
+++ b/vendor/github.com/prometheus/procfs/nfnetlink_queue.go
@@ -0,0 +1,85 @@
+// Copyright The Prometheus Authors
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package procfs
+
+import (
+ "bufio"
+ "bytes"
+ "fmt"
+
+ "github.com/prometheus/procfs/internal/util"
+)
+
+const nfNetLinkQueueFormat = "%d %d %d %d %d %d %d %d %d"
+
+// NFNetLinkQueue contains general information about netfilter queues found in /proc/net/netfilter/nfnetlink_queue.
+type NFNetLinkQueue struct {
+ // id of the queue
+ QueueID uint
+ // pid of process handling the queue
+ PeerPID uint
+ // number of packets waiting for a decision
+ QueueTotal uint
+ // indicate how userspace receive packets
+ CopyMode uint
+ // size of copy
+ CopyRange uint
+ // number of items dropped by the kernel because too many packets were waiting a decision.
+ // It queue_total is superior to queue_max_len (1024 per default) the packets are dropped.
+ QueueDropped uint
+ // number of packets dropped by userspace (due to kernel send failure on the netlink socket)
+ QueueUserDropped uint
+ // sequence number of packets queued. It gives a correct approximation of the number of queued packets.
+ SequenceID uint
+ // internal value (number of entity using the queue)
+ Use uint
+}
+
+// NFNetLinkQueue returns information about current state of netfilter queues.
+func (fs FS) NFNetLinkQueue() ([]NFNetLinkQueue, error) {
+ data, err := util.ReadFileNoStat(fs.proc.Path("net/netfilter/nfnetlink_queue"))
+ if err != nil {
+ return nil, err
+ }
+
+ queue := []NFNetLinkQueue{}
+ if len(data) == 0 {
+ return queue, nil
+ }
+
+ scanner := bufio.NewScanner(bytes.NewReader(data))
+ for scanner.Scan() {
+ line := scanner.Text()
+ nFNetLinkQueue, err := parseNFNetLinkQueueLine(line)
+ if err != nil {
+ return nil, err
+ }
+ queue = append(queue, *nFNetLinkQueue)
+ }
+ return queue, nil
+}
+
+// parseNFNetLinkQueueLine parses each line of the /proc/net/netfilter/nfnetlink_queue file.
+func parseNFNetLinkQueueLine(line string) (*NFNetLinkQueue, error) {
+ nFNetLinkQueue := NFNetLinkQueue{}
+ _, err := fmt.Sscanf(
+ line, nfNetLinkQueueFormat,
+ &nFNetLinkQueue.QueueID, &nFNetLinkQueue.PeerPID, &nFNetLinkQueue.QueueTotal, &nFNetLinkQueue.CopyMode,
+ &nFNetLinkQueue.CopyRange, &nFNetLinkQueue.QueueDropped, &nFNetLinkQueue.QueueUserDropped, &nFNetLinkQueue.SequenceID, &nFNetLinkQueue.Use,
+ )
+ if err != nil {
+ return nil, err
+ }
+ return &nFNetLinkQueue, nil
+}
diff --git a/vendor/github.com/prometheus/procfs/proc.go b/vendor/github.com/prometheus/procfs/proc.go
index 368187fa8..39c14aa55 100644
--- a/vendor/github.com/prometheus/procfs/proc.go
+++ b/vendor/github.com/prometheus/procfs/proc.go
@@ -1,4 +1,4 @@
-// Copyright 2018 The Prometheus Authors
+// Copyright The Prometheus Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
@@ -49,7 +49,7 @@ func (p Procs) Less(i, j int) bool { return p[i].PID < p[j].PID }
// Self returns a process for the current process read via /proc/self.
func Self() (Proc, error) {
fs, err := NewFS(DefaultMountPoint)
- if err != nil || errors.Unwrap(err) == ErrMountPoint {
+ if err != nil || errors.Is(err, ErrMountPoint) {
return Proc{}, err
}
return fs.Self()
diff --git a/vendor/github.com/prometheus/procfs/proc_cgroup.go b/vendor/github.com/prometheus/procfs/proc_cgroup.go
index 4a64347c0..7e8a12297 100644
--- a/vendor/github.com/prometheus/procfs/proc_cgroup.go
+++ b/vendor/github.com/prometheus/procfs/proc_cgroup.go
@@ -1,4 +1,4 @@
-// Copyright 2020 The Prometheus Authors
+// Copyright The Prometheus Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
@@ -60,7 +60,7 @@ func parseCgroupString(cgroupStr string) (*Cgroup, error) {
}
cgroup.HierarchyID, err = strconv.Atoi(fields[0])
if err != nil {
- return nil, fmt.Errorf("%w: hierarchy ID: %q", ErrFileParse, cgroup.HierarchyID)
+ return nil, fmt.Errorf("%w: hierarchy ID: %q", ErrFileParse, fields[0])
}
if fields[1] != "" {
ssNames := strings.Split(fields[1], ",")
diff --git a/vendor/github.com/prometheus/procfs/proc_cgroups.go b/vendor/github.com/prometheus/procfs/proc_cgroups.go
index 5dd493899..0b275c3b1 100644
--- a/vendor/github.com/prometheus/procfs/proc_cgroups.go
+++ b/vendor/github.com/prometheus/procfs/proc_cgroups.go
@@ -1,4 +1,4 @@
-// Copyright 2021 The Prometheus Authors
+// Copyright The Prometheus Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
@@ -40,13 +40,13 @@ type CgroupSummary struct {
// parseCgroupSummary parses each line of the /proc/cgroup file
// Line format is `subsys_name hierarchy num_cgroups enabled`.
-func parseCgroupSummaryString(CgroupSummaryStr string) (*CgroupSummary, error) {
+func parseCgroupSummaryString(cgroupSummaryStr string) (*CgroupSummary, error) {
var err error
- fields := strings.Fields(CgroupSummaryStr)
+ fields := strings.Fields(cgroupSummaryStr)
// require at least 4 fields
if len(fields) < 4 {
- return nil, fmt.Errorf("%w: 4+ fields required, found %d fields in cgroup info string: %s", ErrFileParse, len(fields), CgroupSummaryStr)
+ return nil, fmt.Errorf("%w: 4+ fields required, found %d fields in cgroup info string: %s", ErrFileParse, len(fields), cgroupSummaryStr)
}
CgroupSummary := &CgroupSummary{
diff --git a/vendor/github.com/prometheus/procfs/proc_environ.go b/vendor/github.com/prometheus/procfs/proc_environ.go
index 57a89895d..5b941de04 100644
--- a/vendor/github.com/prometheus/procfs/proc_environ.go
+++ b/vendor/github.com/prometheus/procfs/proc_environ.go
@@ -1,4 +1,4 @@
-// Copyright 2019 The Prometheus Authors
+// Copyright The Prometheus Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
diff --git a/vendor/github.com/prometheus/procfs/proc_fdinfo.go b/vendor/github.com/prometheus/procfs/proc_fdinfo.go
index fa761b352..fa57761db 100644
--- a/vendor/github.com/prometheus/procfs/proc_fdinfo.go
+++ b/vendor/github.com/prometheus/procfs/proc_fdinfo.go
@@ -1,4 +1,4 @@
-// Copyright 2019 The Prometheus Authors
+// Copyright The Prometheus Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
@@ -60,15 +60,16 @@ func (p Proc) FDInfo(fd string) (*ProcFDInfo, error) {
scanner := bufio.NewScanner(bytes.NewReader(data))
for scanner.Scan() {
text = scanner.Text()
- if rPos.MatchString(text) {
+ switch {
+ case rPos.MatchString(text):
pos = rPos.FindStringSubmatch(text)[1]
- } else if rFlags.MatchString(text) {
+ case rFlags.MatchString(text):
flags = rFlags.FindStringSubmatch(text)[1]
- } else if rMntID.MatchString(text) {
+ case rMntID.MatchString(text):
mntid = rMntID.FindStringSubmatch(text)[1]
- } else if rIno.MatchString(text) {
+ case rIno.MatchString(text):
ino = rIno.FindStringSubmatch(text)[1]
- } else if rInotify.MatchString(text) {
+ case rInotify.MatchString(text):
newInotify, err := parseInotifyInfo(text)
if err != nil {
return nil, err
diff --git a/vendor/github.com/prometheus/procfs/proc_interrupts.go b/vendor/github.com/prometheus/procfs/proc_interrupts.go
index 86b4b4524..643b500d5 100644
--- a/vendor/github.com/prometheus/procfs/proc_interrupts.go
+++ b/vendor/github.com/prometheus/procfs/proc_interrupts.go
@@ -1,4 +1,4 @@
-// Copyright 2022 The Prometheus Authors
+// Copyright The Prometheus Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
@@ -42,7 +42,7 @@ type Interrupts map[string]Interrupt
// Interrupts creates a new instance from a given Proc instance.
func (p Proc) Interrupts() (Interrupts, error) {
- data, err := util.ReadFileNoStat(p.path("interrupts"))
+ data, err := util.ReadFileNoStat(p.fs.proc.Path("interrupts"))
if err != nil {
return nil, err
}
diff --git a/vendor/github.com/prometheus/procfs/proc_io.go b/vendor/github.com/prometheus/procfs/proc_io.go
index d15b66ddb..dd8086ba2 100644
--- a/vendor/github.com/prometheus/procfs/proc_io.go
+++ b/vendor/github.com/prometheus/procfs/proc_io.go
@@ -1,4 +1,4 @@
-// Copyright 2018 The Prometheus Authors
+// Copyright The Prometheus Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
diff --git a/vendor/github.com/prometheus/procfs/proc_limits.go b/vendor/github.com/prometheus/procfs/proc_limits.go
index 9530b14bc..4b7d33784 100644
--- a/vendor/github.com/prometheus/procfs/proc_limits.go
+++ b/vendor/github.com/prometheus/procfs/proc_limits.go
@@ -1,4 +1,4 @@
-// Copyright 2018 The Prometheus Authors
+// Copyright The Prometheus Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
@@ -19,6 +19,7 @@ import (
"os"
"regexp"
"strconv"
+ "strings"
)
// ProcLimits represents the soft limits for each of the process's resource
@@ -74,7 +75,7 @@ const (
)
var (
- limitsMatch = regexp.MustCompile(`(Max \w+\s{0,1}?\w*\s{0,1}\w*)\s{2,}(\w+)\s+(\w+)`)
+ limitsMatch = regexp.MustCompile(`(Max \w+\s??\w*\s?\w*)\s{2,}(\w+)\s+(\w+)`)
)
// NewLimits returns the current soft limits of the process.
@@ -106,7 +107,7 @@ func (p Proc) Limits() (ProcLimits, error) {
return ProcLimits{}, fmt.Errorf("%w: couldn't parse %q line %q", ErrFileParse, f.Name(), s.Text())
}
- switch fields[1] {
+ switch strings.TrimSpace(fields[1]) {
case "Max cpu time":
l.CPUTime, err = parseUint(fields[2])
case "Max file size":
diff --git a/vendor/github.com/prometheus/procfs/proc_maps.go b/vendor/github.com/prometheus/procfs/proc_maps.go
index 7e75c286b..08b89a6eb 100644
--- a/vendor/github.com/prometheus/procfs/proc_maps.go
+++ b/vendor/github.com/prometheus/procfs/proc_maps.go
@@ -1,4 +1,4 @@
-// Copyright 2019 The Prometheus Authors
+// Copyright The Prometheus Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
@@ -12,8 +12,6 @@
// limitations under the License.
//go:build (aix || darwin || dragonfly || freebsd || linux || netbsd || openbsd || solaris) && !js
-// +build aix darwin dragonfly freebsd linux netbsd openbsd solaris
-// +build !js
package procfs
diff --git a/vendor/github.com/prometheus/procfs/proc_netstat.go b/vendor/github.com/prometheus/procfs/proc_netstat.go
index 4248c1716..7f94cc891 100644
--- a/vendor/github.com/prometheus/procfs/proc_netstat.go
+++ b/vendor/github.com/prometheus/procfs/proc_netstat.go
@@ -1,4 +1,4 @@
-// Copyright 2022 The Prometheus Authors
+// Copyright The Prometheus Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
diff --git a/vendor/github.com/prometheus/procfs/proc_ns.go b/vendor/github.com/prometheus/procfs/proc_ns.go
index 0f8f847f9..5fc0eb9e2 100644
--- a/vendor/github.com/prometheus/procfs/proc_ns.go
+++ b/vendor/github.com/prometheus/procfs/proc_ns.go
@@ -1,4 +1,4 @@
-// Copyright 2018 The Prometheus Authors
+// Copyright The Prometheus Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
diff --git a/vendor/github.com/prometheus/procfs/proc_psi.go b/vendor/github.com/prometheus/procfs/proc_psi.go
index ccd35f153..cc2c5de87 100644
--- a/vendor/github.com/prometheus/procfs/proc_psi.go
+++ b/vendor/github.com/prometheus/procfs/proc_psi.go
@@ -1,4 +1,4 @@
-// Copyright 2019 The Prometheus Authors
+// Copyright The Prometheus Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
diff --git a/vendor/github.com/prometheus/procfs/proc_smaps.go b/vendor/github.com/prometheus/procfs/proc_smaps.go
index 9a297afcf..f637309b3 100644
--- a/vendor/github.com/prometheus/procfs/proc_smaps.go
+++ b/vendor/github.com/prometheus/procfs/proc_smaps.go
@@ -1,4 +1,4 @@
-// Copyright 2020 The Prometheus Authors
+// Copyright The Prometheus Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
@@ -12,7 +12,6 @@
// limitations under the License.
//go:build !windows
-// +build !windows
package procfs
diff --git a/vendor/github.com/prometheus/procfs/proc_snmp.go b/vendor/github.com/prometheus/procfs/proc_snmp.go
index 4bdc90b07..8d9a9bcd6 100644
--- a/vendor/github.com/prometheus/procfs/proc_snmp.go
+++ b/vendor/github.com/prometheus/procfs/proc_snmp.go
@@ -1,4 +1,4 @@
-// Copyright 2022 The Prometheus Authors
+// Copyright The Prometheus Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
diff --git a/vendor/github.com/prometheus/procfs/proc_snmp6.go b/vendor/github.com/prometheus/procfs/proc_snmp6.go
index fb7fd3995..841fef464 100644
--- a/vendor/github.com/prometheus/procfs/proc_snmp6.go
+++ b/vendor/github.com/prometheus/procfs/proc_snmp6.go
@@ -1,4 +1,4 @@
-// Copyright 2022 The Prometheus Authors
+// Copyright The Prometheus Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
diff --git a/vendor/github.com/prometheus/procfs/proc_stat.go b/vendor/github.com/prometheus/procfs/proc_stat.go
index 06a8d931c..02e3f9e31 100644
--- a/vendor/github.com/prometheus/procfs/proc_stat.go
+++ b/vendor/github.com/prometheus/procfs/proc_stat.go
@@ -1,4 +1,4 @@
-// Copyright 2018 The Prometheus Authors
+// Copyright The Prometheus Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
@@ -101,6 +101,12 @@ type ProcStat struct {
RSS int
// Soft limit in bytes on the rss of the process.
RSSLimit uint64
+ // The address above which program text can run.
+ StartCode uint64
+ // The address below which program text can run.
+ EndCode uint64
+ // The address of the start (i.e., bottom) of the stack.
+ StartStack uint64
// CPU number last executed on.
Processor uint
// Real-time scheduling priority, a number in the range 1 to 99 for processes
@@ -177,9 +183,9 @@ func (p Proc) Stat() (ProcStat, error) {
&s.VSize,
&s.RSS,
&s.RSSLimit,
- &ignoreUint64,
- &ignoreUint64,
- &ignoreUint64,
+ &s.StartCode,
+ &s.EndCode,
+ &s.StartStack,
&ignoreUint64,
&ignoreUint64,
&ignoreUint64,
diff --git a/vendor/github.com/prometheus/procfs/proc_statm.go b/vendor/github.com/prometheus/procfs/proc_statm.go
new file mode 100644
index 000000000..6bcc97ec9
--- /dev/null
+++ b/vendor/github.com/prometheus/procfs/proc_statm.go
@@ -0,0 +1,117 @@
+// Copyright The Prometheus Authors
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package procfs
+
+import (
+ "os"
+ "strconv"
+ "strings"
+
+ "github.com/prometheus/procfs/internal/util"
+)
+
+// - https://man7.org/linux/man-pages/man5/proc_pid_statm.5.html
+
+// ProcStatm Provides memory usage information for a process, measured in memory pages.
+// Read from /proc/[pid]/statm.
+type ProcStatm struct {
+ // The process ID.
+ PID int
+ // total program size (same as VmSize in status)
+ Size uint64
+ // resident set size (same as VmRSS in status)
+ Resident uint64
+ // number of resident shared pages (i.e., backed by a file)
+ Shared uint64
+ // text (code)
+ Text uint64
+ // library (unused since Linux 2.6; always 0)
+ Lib uint64
+ // data + stack
+ Data uint64
+ // dirty pages (unused since Linux 2.6; always 0)
+ Dt uint64
+}
+
+// NewStatm returns the current status information of the process.
+//
+// Deprecated: Use p.Statm() instead.
+func (p Proc) NewStatm() (ProcStatm, error) {
+ return p.Statm()
+}
+
+// Statm returns the current memory usage information of the process.
+func (p Proc) Statm() (ProcStatm, error) {
+ data, err := util.ReadFileNoStat(p.path("statm"))
+ if err != nil {
+ return ProcStatm{}, err
+ }
+
+ statmSlice, err := parseStatm(data)
+ if err != nil {
+ return ProcStatm{}, err
+ }
+
+ procStatm := ProcStatm{
+ PID: p.PID,
+ Size: statmSlice[0],
+ Resident: statmSlice[1],
+ Shared: statmSlice[2],
+ Text: statmSlice[3],
+ Lib: statmSlice[4],
+ Data: statmSlice[5],
+ Dt: statmSlice[6],
+ }
+
+ return procStatm, nil
+}
+
+// parseStatm return /proc/[pid]/statm data to uint64 slice.
+func parseStatm(data []byte) ([]uint64, error) {
+ var statmSlice []uint64
+ statmItems := strings.Fields(string(data))
+ for i := range statmItems {
+ statmItem, err := strconv.ParseUint(statmItems[i], 10, 64)
+ if err != nil {
+ return nil, err
+ }
+ statmSlice = append(statmSlice, statmItem)
+ }
+ return statmSlice, nil
+}
+
+// SizeBytes returns the process of total program size in bytes.
+func (s ProcStatm) SizeBytes() uint64 {
+ return s.Size * uint64(os.Getpagesize())
+}
+
+// ResidentBytes returns the process of resident set size in bytes.
+func (s ProcStatm) ResidentBytes() uint64 {
+ return s.Resident * uint64(os.Getpagesize())
+}
+
+// SHRBytes returns the process of share memory size in bytes.
+func (s ProcStatm) SHRBytes() uint64 {
+ return s.Shared * uint64(os.Getpagesize())
+}
+
+// TextBytes returns the process of text (code) size in bytes.
+func (s ProcStatm) TextBytes() uint64 {
+ return s.Text * uint64(os.Getpagesize())
+}
+
+// DataBytes returns the process of data + stack size in bytes.
+func (s ProcStatm) DataBytes() uint64 {
+ return s.Data * uint64(os.Getpagesize())
+}
diff --git a/vendor/github.com/prometheus/procfs/proc_status.go b/vendor/github.com/prometheus/procfs/proc_status.go
index dd8aa5688..12d65581c 100644
--- a/vendor/github.com/prometheus/procfs/proc_status.go
+++ b/vendor/github.com/prometheus/procfs/proc_status.go
@@ -1,4 +1,4 @@
-// Copyright 2018 The Prometheus Authors
+// Copyright The Prometheus Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
@@ -16,7 +16,7 @@ package procfs
import (
"bytes"
"math/bits"
- "sort"
+ "slices"
"strconv"
"strings"
@@ -83,6 +83,19 @@ type ProcStatus struct {
// CpusAllowedList: List of cpu cores processes are allowed to run on.
CpusAllowedList []uint64
+
+ // CapInh is the bitmap of inheritable capabilities
+ //
+ // See: https://www.kernel.org/doc/man-pages/online/pages/man7/capabilities.7.html
+ CapInh uint64
+ // CapPrm is the bitmap of permitted capabilities
+ CapPrm uint64
+ // CapEff is the bitmap of effective capabilities
+ CapEff uint64
+ // CapBnd is the bitmap of bounding capabilities
+ CapBnd uint64
+ // CapAmb is the bitmap of ambient capabilities
+ CapAmb uint64
}
// NewStatus returns the current status information of the process.
@@ -94,8 +107,7 @@ func (p Proc) NewStatus() (ProcStatus, error) {
s := ProcStatus{PID: p.PID}
- lines := strings.Split(string(data), "\n")
- for _, line := range lines {
+ for line := range strings.SplitSeq(string(data), "\n") {
if !bytes.Contains([]byte(line), []byte(":")) {
continue
}
@@ -191,6 +203,36 @@ func (s *ProcStatus) fillStatus(k string, vString string, vUint uint64, vUintByt
s.NonVoluntaryCtxtSwitches = vUint
case "Cpus_allowed_list":
s.CpusAllowedList = calcCpusAllowedList(vString)
+ case "CapInh":
+ var err error
+ s.CapInh, err = strconv.ParseUint(vString, 16, 64)
+ if err != nil {
+ return err
+ }
+ case "CapPrm":
+ var err error
+ s.CapPrm, err = strconv.ParseUint(vString, 16, 64)
+ if err != nil {
+ return err
+ }
+ case "CapEff":
+ var err error
+ s.CapEff, err = strconv.ParseUint(vString, 16, 64)
+ if err != nil {
+ return err
+ }
+ case "CapBnd":
+ var err error
+ s.CapBnd, err = strconv.ParseUint(vString, 16, 64)
+ if err != nil {
+ return err
+ }
+ case "CapAmb":
+ var err error
+ s.CapAmb, err = strconv.ParseUint(vString, 16, 64)
+ if err != nil {
+ return err
+ }
}
return nil
@@ -222,7 +264,7 @@ func calcCpusAllowedList(cpuString string) []uint64 {
}
- sort.Slice(g, func(i, j int) bool { return g[i] < g[j] })
+ slices.Sort(g)
return g
}
diff --git a/vendor/github.com/prometheus/procfs/proc_sys.go b/vendor/github.com/prometheus/procfs/proc_sys.go
index 3810d1ac9..52658a4d5 100644
--- a/vendor/github.com/prometheus/procfs/proc_sys.go
+++ b/vendor/github.com/prometheus/procfs/proc_sys.go
@@ -1,4 +1,4 @@
-// Copyright 2022 The Prometheus Authors
+// Copyright The Prometheus Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
diff --git a/vendor/github.com/prometheus/procfs/schedstat.go b/vendor/github.com/prometheus/procfs/schedstat.go
index 5f7f32dc8..fafd8dff7 100644
--- a/vendor/github.com/prometheus/procfs/schedstat.go
+++ b/vendor/github.com/prometheus/procfs/schedstat.go
@@ -1,4 +1,4 @@
-// Copyright 2019 The Prometheus Authors
+// Copyright The Prometheus Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
diff --git a/vendor/github.com/prometheus/procfs/slab.go b/vendor/github.com/prometheus/procfs/slab.go
index 8611c9017..32a04678a 100644
--- a/vendor/github.com/prometheus/procfs/slab.go
+++ b/vendor/github.com/prometheus/procfs/slab.go
@@ -1,4 +1,4 @@
-// Copyright 2020 The Prometheus Authors
+// Copyright The Prometheus Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
diff --git a/vendor/github.com/prometheus/procfs/softirqs.go b/vendor/github.com/prometheus/procfs/softirqs.go
index 403e6ae70..47b73a729 100644
--- a/vendor/github.com/prometheus/procfs/softirqs.go
+++ b/vendor/github.com/prometheus/procfs/softirqs.go
@@ -1,4 +1,4 @@
-// Copyright 2022 The Prometheus Authors
+// Copyright The Prometheus Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
diff --git a/vendor/github.com/prometheus/procfs/stat.go b/vendor/github.com/prometheus/procfs/stat.go
index e36b41c18..593ad0f62 100644
--- a/vendor/github.com/prometheus/procfs/stat.go
+++ b/vendor/github.com/prometheus/procfs/stat.go
@@ -1,4 +1,4 @@
-// Copyright 2018 The Prometheus Authors
+// Copyright The Prometheus Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
@@ -16,6 +16,7 @@ package procfs
import (
"bufio"
"bytes"
+ "errors"
"fmt"
"io"
"strconv"
@@ -92,7 +93,7 @@ func parseCPUStat(line string) (CPUStat, int64, error) {
&cpuStat.Iowait, &cpuStat.IRQ, &cpuStat.SoftIRQ, &cpuStat.Steal,
&cpuStat.Guest, &cpuStat.GuestNice)
- if err != nil && err != io.EOF {
+ if err != nil && !errors.Is(err, io.EOF) {
return CPUStat{}, -1, fmt.Errorf("%w: couldn't parse %q (cpu): %w", ErrFileParse, line, err)
}
if count == 0 {
diff --git a/vendor/github.com/prometheus/procfs/swaps.go b/vendor/github.com/prometheus/procfs/swaps.go
index 65fec834b..ee17bf488 100644
--- a/vendor/github.com/prometheus/procfs/swaps.go
+++ b/vendor/github.com/prometheus/procfs/swaps.go
@@ -1,4 +1,4 @@
-// Copyright 2019 The Prometheus Authors
+// Copyright The Prometheus Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
diff --git a/vendor/github.com/prometheus/procfs/thread.go b/vendor/github.com/prometheus/procfs/thread.go
index 80e0e947b..0cfbb5418 100644
--- a/vendor/github.com/prometheus/procfs/thread.go
+++ b/vendor/github.com/prometheus/procfs/thread.go
@@ -1,4 +1,4 @@
-// Copyright 2022 The Prometheus Authors
+// Copyright The Prometheus Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
diff --git a/vendor/github.com/prometheus/procfs/vm.go b/vendor/github.com/prometheus/procfs/vm.go
index 51c49d89e..52180c03e 100644
--- a/vendor/github.com/prometheus/procfs/vm.go
+++ b/vendor/github.com/prometheus/procfs/vm.go
@@ -1,4 +1,4 @@
-// Copyright 2019 The Prometheus Authors
+// Copyright The Prometheus Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
@@ -12,7 +12,6 @@
// limitations under the License.
//go:build !windows
-// +build !windows
package procfs
diff --git a/vendor/github.com/prometheus/procfs/zoneinfo.go b/vendor/github.com/prometheus/procfs/zoneinfo.go
index e54d94b09..63d1898bc 100644
--- a/vendor/github.com/prometheus/procfs/zoneinfo.go
+++ b/vendor/github.com/prometheus/procfs/zoneinfo.go
@@ -1,4 +1,4 @@
-// Copyright 2019 The Prometheus Authors
+// Copyright The Prometheus Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
@@ -12,7 +12,6 @@
// limitations under the License.
//go:build !windows
-// +build !windows
package procfs
@@ -88,11 +87,9 @@ func parseZoneinfo(zoneinfoData []byte) ([]Zoneinfo, error) {
zoneinfo := []Zoneinfo{}
- zoneinfoBlocks := bytes.Split(zoneinfoData, []byte("\nNode"))
- for _, block := range zoneinfoBlocks {
+ for block := range bytes.SplitSeq(zoneinfoData, []byte("\nNode")) {
var zoneinfoElement Zoneinfo
- lines := strings.Split(string(block), "\n")
- for _, line := range lines {
+ for line := range strings.SplitSeq(string(block), "\n") {
if nodeZone := nodeZoneRE.FindStringSubmatch(line); nodeZone != nil {
zoneinfoElement.Node = nodeZone[1]
diff --git a/vendor/golang.org/x/net/http2/server_wrap.go b/vendor/golang.org/x/net/http2/server_wrap.go
index a7a09551c..737f1f057 100644
--- a/vendor/golang.org/x/net/http2/server_wrap.go
+++ b/vendor/golang.org/x/net/http2/server_wrap.go
@@ -10,9 +10,11 @@ package http2
import (
"context"
+ "crypto/tls"
"errors"
"net"
"net/http"
+ "slices"
"sync"
"time"
)
@@ -44,6 +46,20 @@ func configureServer(s *http.Server, conf *Server) error {
h2.IdleTimeout = h1.ReadTimeout
}
}
+
+ // Register h2 and http/1.1 ALPN protocols on s.TLSConfig, matching
+ // the pre-wrapping implementation in server.go, so that TLS listeners
+ // built from s.TLSConfig still negotiate HTTP/2.
+ if s.TLSConfig == nil {
+ s.TLSConfig = new(tls.Config)
+ }
+ if !slices.Contains(s.TLSConfig.NextProtos, NextProtoTLS) {
+ s.TLSConfig.NextProtos = append(s.TLSConfig.NextProtos, NextProtoTLS)
+ }
+ if !slices.Contains(s.TLSConfig.NextProtos, "http/1.1") {
+ s.TLSConfig.NextProtos = append(s.TLSConfig.NextProtos, "http/1.1")
+ }
+
conf.state = &serverInternalState{
s1: s,
}
diff --git a/vendor/golang.org/x/net/http2/transport_wrap.go b/vendor/golang.org/x/net/http2/transport_wrap.go
index d25d99bdb..534e77ab9 100644
--- a/vendor/golang.org/x/net/http2/transport_wrap.go
+++ b/vendor/golang.org/x/net/http2/transport_wrap.go
@@ -22,8 +22,8 @@ import (
)
func configureTransport(t1 *http.Transport) error {
- // ConfigureTransport is a no-op: The http.Transport already supports HTTP/2.
- return nil
+ _, err := configureTransports(t1)
+ return err
}
func configureTransports(t1 *http.Transport) (*Transport, error) {
@@ -31,6 +31,17 @@ func configureTransports(t1 *http.Transport) (*Transport, error) {
// linked to the http.Transport's.
tr2 := &Transport{}
tr2.configure(t1)
+ // Enable HTTP/2 on the transport, as the pre-wrapping implementation did:
+ // net/http does not auto-enable it for a transport with a custom
+ // TLSClientConfig or dialer.
+ if t1.TLSClientConfig == nil {
+ t1.TLSClientConfig = &tls.Config{}
+ }
+ if t1.Protocols == nil {
+ t1.Protocols = new(http.Protocols)
+ t1.Protocols.SetHTTP1(true)
+ }
+ t1.Protocols.SetHTTP2(true)
return tr2, nil
}
@@ -44,7 +55,7 @@ type transportConfig struct {
// Registered is called by net/http.Transport.RegisterProtocol,
// to let us know that it understands the registration mechanism we're using.
func (t transportConfig) Registered(t1 *http.Transport) {
- t.t.t1 = t1
+ t.t.lazyt1 = t1
}
func (t transportConfig) DisableCompression() bool {
@@ -134,29 +145,30 @@ func (t transportConfig) DialFromContext(ctx context.Context, network, address s
type transportInternal struct {
initOnce sync.Once
- t1 *http.Transport
+ lazyt1 *http.Transport
}
-func (t *Transport) init() {
+func (t *Transport) init() *http.Transport {
t.initOnce.Do(func() {
- if t.t1 != nil {
+ if t.lazyt1 != nil {
return
}
t1 := &http.Transport{}
t.configure(t1)
})
+ return t.lazyt1
}
func (t *Transport) configure(t1 *http.Transport) {
t1.RegisterProtocol("http/2", transportConfig{t})
- // tr2.t1 is set by transportConfig.Registered.
- if t.t1 != t1 {
+ // tr2.lazyt1 is set by transportConfig.Registered.
+ if t.lazyt1 != t1 {
panic("http2: net/http does not support this version of x/net/http2")
}
}
func (t *Transport) roundTripOpt(req *http.Request, opt RoundTripOpt) (*http.Response, error) {
- t.init()
+ t1 := t.init()
if req.URL.Scheme == "http" && !t.AllowHTTP {
return nil, errors.New("http2: unencrypted HTTP/2 not enabled")
@@ -177,22 +189,23 @@ func (t *Transport) roundTripOpt(req *http.Request, opt RoundTripOpt) (*http.Res
ctx := context.WithValue(req.Context(), http2TransportContextKey{}, t)
req = req.WithContext(ctx)
- return t.t1.RoundTrip(req)
+ return t1.RoundTrip(req)
}
func (t *Transport) closeIdleConnections() {
- t.init()
- t.t1.CloseIdleConnections()
+ t1 := t.init()
+ t1.CloseIdleConnections()
}
func (t *Transport) newUserClientConn(c net.Conn) (*ClientConn, error) {
+ t1 := t.init()
// http.Transport's NewClientConn doesn't provide a supported way to create
// a connection from a net.Conn. (This might be useful to add in the future?)
// We're going to craftily sneak one in via the context key, with the
// scheme of "http/2" telling NewClientConn to look for it.
ctx := context.WithValue(context.Background(), netConnContextKey{}, c)
- nhcc, err := t.t1.NewClientConn(ctx, "http/2", "")
+ nhcc, err := t1.NewClientConn(ctx, "http/2", "")
if err != nil {
return nil, err
}
diff --git a/vendor/golang.org/x/net/idna/idna.go b/vendor/golang.org/x/net/idna/idna.go
index 22767125b..e2f28fed4 100644
--- a/vendor/golang.org/x/net/idna/idna.go
+++ b/vendor/golang.org/x/net/idna/idna.go
@@ -400,7 +400,11 @@ func (p *Profile) process(s string, toASCII bool) (string, error) {
// Spec says keep the old label.
continue
}
- if unicode16 && err == nil && len(u) > 0 && isASCII(u) {
+ if err == nil && len(u) > 0 && isASCII(u) {
+ // UTS 43 pre-revision 33 doesn't classify a xn-- label
+ // which contains only ASCII characters as an error,
+ // but that's a specification bug and a security issue.
+ // Always return an error in this case.
err = punyError(enc)
}
isBidi = isBidi || bidirule.DirectionString(u) != bidi.LeftToRight
diff --git a/vendor/golang.org/x/text/unicode/norm/forminfo.go b/vendor/golang.org/x/text/unicode/norm/forminfo.go
index f3a234e5f..b3cf5d9bd 100644
--- a/vendor/golang.org/x/text/unicode/norm/forminfo.go
+++ b/vendor/golang.org/x/text/unicode/norm/forminfo.go
@@ -121,8 +121,12 @@ func (p Properties) BoundaryAfter() bool {
//
// When all 6 bits are zero, the character is inert, meaning it is never
// influenced by normalization.
+//
+// We set flags to 0x80 (high bit 7 unused in quick check data) to indicate an invalid rune.
type qcInfo uint8
+func (p Properties) isInvalid() bool { return p.flags == 0x80 }
+
func (p Properties) isYesC() bool { return p.flags&0x10 == 0 }
func (p Properties) isYesD() bool { return p.flags&0x4 == 0 }
@@ -247,6 +251,9 @@ func (f Form) PropertiesString(s string) Properties {
// to a Properties. See the comment at the top of the file
// for more information on the format.
func compInfo(v uint16, sz int) Properties {
+ if sz == 0 {
+ return Properties{flags: 0x80, size: 1}
+ }
if v == 0 {
return Properties{size: uint8(sz)}
} else if v >= 0x8000 {
@@ -254,7 +261,7 @@ func compInfo(v uint16, sz int) Properties {
size: uint8(sz),
ccc: uint8(v),
tccc: uint8(v),
- flags: qcInfo(v >> 8),
+ flags: qcInfo(v>>8) & 0x3f,
}
if p.ccc > 0 || p.combinesBackward() {
p.nLead = uint8(p.flags & 0x3)
diff --git a/vendor/golang.org/x/text/unicode/norm/iter.go b/vendor/golang.org/x/text/unicode/norm/iter.go
index 417c6b268..3cc059224 100644
--- a/vendor/golang.org/x/text/unicode/norm/iter.go
+++ b/vendor/golang.org/x/text/unicode/norm/iter.go
@@ -376,16 +376,12 @@ func nextComposed(i *Iter) []byte {
goto doNorm
}
prevCC = i.info.tccc
- sz := int(i.info.size)
- if sz == 0 {
- sz = 1 // illegal rune: copy byte-by-byte
- }
- p := outp + sz
+ p := outp + int(i.info.size)
if p > len(i.buf) {
break
}
outp = p
- i.p += sz
+ i.p += int(i.info.size)
if i.p >= i.rb.nsrc {
i.setDone()
break
diff --git a/vendor/golang.org/x/text/unicode/norm/normalize.go b/vendor/golang.org/x/text/unicode/norm/normalize.go
index 4747ad07a..60b1511ca 100644
--- a/vendor/golang.org/x/text/unicode/norm/normalize.go
+++ b/vendor/golang.org/x/text/unicode/norm/normalize.go
@@ -148,7 +148,7 @@ func (f Form) IsNormalString(s string) bool {
// patched buffer and whether the decomposition is still in progress.
func patchTail(rb *reorderBuffer) bool {
info, p := lastRuneStart(&rb.f, rb.out)
- if p == -1 || info.size == 0 {
+ if p == -1 || info.isInvalid() {
return true
}
end := p + int(info.size)
@@ -225,7 +225,7 @@ func doAppend(rb *reorderBuffer, out []byte, p int) []byte {
}
fd := &rb.f
if doMerge {
- var info Properties
+ info := Properties{flags: 0x80, size: 1} // invalid rune
if p < n {
info = fd.info(src, p)
if !info.BoundaryBefore() || info.nLeadingNonStarters() > 0 {
@@ -235,7 +235,7 @@ func doAppend(rb *reorderBuffer, out []byte, p int) []byte {
p = decomposeSegment(rb, p, true)
}
}
- if info.size == 0 {
+ if info.isInvalid() {
rb.doFlush()
// Append incomplete UTF-8 encoding.
return src.appendSlice(rb.out, p, n)
@@ -314,7 +314,7 @@ func (f *formInfo) quickSpan(src input, i, end int, atEOF bool) (n int, ok bool)
continue
}
info := f.info(src, i)
- if info.size == 0 {
+ if info.isInvalid() {
if atEOF {
// include incomplete runes
return n, true
@@ -379,7 +379,7 @@ func (f Form) firstBoundary(src input, nsrc int) int {
// CGJ insertion points correctly. Luckily it doesn't have to.
for {
info := fd.info(src, i)
- if info.size == 0 {
+ if info.isInvalid() {
return -1
}
if s := ss.next(info); s != ssSuccess {
@@ -424,7 +424,7 @@ func (f Form) nextBoundary(src input, nsrc int, atEOF bool) int {
}
fd := formTable[f]
info := fd.info(src, 0)
- if info.size == 0 {
+ if info.isInvalid() {
if atEOF {
return 1
}
@@ -435,7 +435,7 @@ func (f Form) nextBoundary(src input, nsrc int, atEOF bool) int {
for i := int(info.size); i < nsrc; i += int(info.size) {
info = fd.info(src, i)
- if info.size == 0 {
+ if info.isInvalid() {
if atEOF {
return i
}
@@ -465,7 +465,7 @@ func lastBoundary(fd *formInfo, b []byte) int {
if p == -1 {
return -1
}
- if info.size == 0 { // ends with incomplete rune
+ if info.isInvalid() { // ends with incomplete rune
if p == 0 { // starts with incomplete rune
return -1
}
@@ -504,7 +504,7 @@ func lastBoundary(fd *formInfo, b []byte) int {
func decomposeSegment(rb *reorderBuffer, sp int, atEOF bool) int {
// Force one character to be consumed.
info := rb.f.info(rb.src, sp)
- if info.size == 0 {
+ if info.isInvalid() {
return 0
}
if s := rb.ss.next(info); s == ssStarter {
@@ -528,7 +528,7 @@ func decomposeSegment(rb *reorderBuffer, sp int, atEOF bool) int {
break
}
info = rb.f.info(rb.src, sp)
- if info.size == 0 {
+ if info.isInvalid() {
if !atEOF {
return int(iShortSrc)
}
diff --git a/vendor/modules.txt b/vendor/modules.txt
index 9db5974da..59201a927 100644
--- a/vendor/modules.txt
+++ b/vendor/modules.txt
@@ -86,8 +86,8 @@ github.com/munnerz/goautoneg
# github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2
## explicit
github.com/pmezard/go-difflib/difflib
-# github.com/prometheus/client_golang v1.23.2
-## explicit; go 1.23.0
+# github.com/prometheus/client_golang v1.24.1
+## explicit; go 1.25.0
github.com/prometheus/client_golang/internal/github.com/golang/gddo/httputil
github.com/prometheus/client_golang/internal/github.com/golang/gddo/httputil/header
github.com/prometheus/client_golang/prometheus
@@ -97,12 +97,12 @@ github.com/prometheus/client_golang/prometheus/promhttp/internal
# github.com/prometheus/client_model v0.6.2
## explicit; go 1.22.0
github.com/prometheus/client_model/go
-# github.com/prometheus/common v0.66.1
-## explicit; go 1.23.0
+# github.com/prometheus/common v0.70.1
+## explicit; go 1.25.0
github.com/prometheus/common/expfmt
github.com/prometheus/common/model
-# github.com/prometheus/procfs v0.16.1
-## explicit; go 1.23.0
+# github.com/prometheus/procfs v0.21.1
+## explicit; go 1.25.0
github.com/prometheus/procfs
github.com/prometheus/procfs/internal/fs
github.com/prometheus/procfs/internal/util
@@ -126,13 +126,13 @@ github.com/vishvananda/netns
# github.com/x448/float16 v0.8.4
## explicit; go 1.11
github.com/x448/float16
-# go.yaml.in/yaml/v2 v2.4.3
+# go.yaml.in/yaml/v2 v2.4.4
## explicit; go 1.15
go.yaml.in/yaml/v2
# go.yaml.in/yaml/v3 v3.0.4
## explicit; go 1.16
go.yaml.in/yaml/v3
-# golang.org/x/net v0.55.0
+# golang.org/x/net v0.57.0
## explicit; go 1.25.0
golang.org/x/net/http/httpguts
golang.org/x/net/http2
@@ -140,8 +140,8 @@ golang.org/x/net/http2/hpack
golang.org/x/net/idna
golang.org/x/net/internal/httpcommon
golang.org/x/net/internal/httpsfv
-# golang.org/x/oauth2 v0.34.0
-## explicit; go 1.24.0
+# golang.org/x/oauth2 v0.36.0
+## explicit; go 1.25.0
golang.org/x/oauth2
golang.org/x/oauth2/internal
# golang.org/x/sys v0.47.0
@@ -149,10 +149,10 @@ golang.org/x/oauth2/internal
golang.org/x/sys/plan9
golang.org/x/sys/unix
golang.org/x/sys/windows
-# golang.org/x/term v0.43.0
+# golang.org/x/term v0.45.0
## explicit; go 1.25.0
golang.org/x/term
-# golang.org/x/text v0.37.0
+# golang.org/x/text v0.40.0
## explicit; go 1.25.0
golang.org/x/text/secure/bidirule
golang.org/x/text/transform