MSP-8974 up deps

This commit is contained in:
chashintv committed 2026-11-20 10:42:39 +03:00
1 parent 0abaaf740f
commit a0aafd93b9
602 files changed
+47724 -13295

No files matched your search

@@ -39,7 +39,7 @@ func init() {
// token = 1*<any CHAR except CTLs or separators>
// qdtext = <any TEXT except <">>
for c := 0; c < 256; c++ {
for c := range 256 {
var t octetType
isCtl := c <= 31 || c == 127
isChar := 0 <= c && c <= 127
@@ -32,7 +32,8 @@ func NewBuildInfoCollector() Collector {
"Build information about the main Go module.",
nil, Labels{"path": path, "version": version, "checksum": sum},
),
GaugeValue, 1)}
GaugeValue, 1,
)}
c.init(c.self)
return c
}
@@ -11,9 +11,6 @@
// See the License for the specific language governing permissions and
// limitations under the License.
//go:build go1.17
// +build go1.17
package collectors
import (
+2 -3
View File
@@ -21,7 +21,6 @@ import (
"github.com/cespare/xxhash/v2"
dto "github.com/prometheus/client_model/go"
"github.com/prometheus/common/model"
"google.golang.org/protobuf/proto"
"github.com/prometheus/client_golang/prometheus/internal"
)
@@ -181,8 +180,8 @@ func (v2) NewDesc(fqName, help string, variableLabels ConstrainableLabels, const
d.constLabelPairs = make([]*dto.LabelPair, 0, len(constLabels))
for n, v := range constLabels {
d.constLabelPairs = append(d.constLabelPairs, &dto.LabelPair{
Name: proto.String(n),
Value: proto.String(v),
Name: new(n),
Value: new(v),
})
}
sort.Sort(internal.LabelPairSorter(d.constLabelPairs))
-1
View File
@@ -12,7 +12,6 @@
// limitations under the License.
//go:build !js || wasm
// +build !js wasm
package prometheus
@@ -12,7 +12,6 @@
// limitations under the License.
//go:build js && !wasm
// +build js,!wasm
package prometheus
+10 -5
View File
@@ -211,23 +211,28 @@ func newBaseGoCollector() baseGoCollector {
goroutinesDesc: NewDesc(
"go_goroutines",
"Number of goroutines that currently exist.",
nil, nil),
nil, nil,
),
threadsDesc: NewDesc(
"go_threads",
"Number of OS threads created.",
nil, nil),
nil, nil,
),
gcDesc: NewDesc(
"go_gc_duration_seconds",
"A summary of the wall-time pause (stop-the-world) duration in garbage collection cycles.",
nil, nil),
nil, nil,
),
gcLastTimeDesc: NewDesc(
"go_memstats_last_gc_time_seconds",
"Number of seconds since 1970 of last garbage collection.",
nil, nil),
nil, nil,
),
goInfoDesc: NewDesc(
"go_info",
"Information about the Go environment.",
nil, Labels{"version": runtime.Version()}),
nil, Labels{"version": runtime.Version()},
),
}
}
@@ -11,9 +11,6 @@
// See the License for the specific language governing permissions and
// limitations under the License.
//go:build go1.17
// +build go1.17
package prometheus
import (
@@ -27,7 +24,6 @@ import (
"github.com/prometheus/client_golang/prometheus/internal"
dto "github.com/prometheus/client_model/go"
"google.golang.org/protobuf/proto"
)
const (
@@ -573,14 +569,14 @@ func (h *batchHistogram) Write(out *dto.Metric) error {
// by obtaining the next float64 value down, in order.
upperBound := math.Nextafter(h.buckets[i+1], h.buckets[i])
dtoBuckets = append(dtoBuckets, &dto.Bucket{
CumulativeCount: proto.Uint64(totalCount),
UpperBound: proto.Float64(upperBound),
CumulativeCount: new(totalCount),
UpperBound: new(upperBound),
})
}
out.Histogram = &dto.Histogram{
Bucket: dtoBuckets,
SampleCount: proto.Uint64(totalCount),
SampleSum: proto.Float64(sum),
SampleCount: new(totalCount),
SampleSum: new(sum),
}
return nil
}
+21 -21
View File
@@ -803,8 +803,8 @@ func (h *histogram) Write(out *dto.Metric) error {
his := &dto.Histogram{
Bucket: make([]*dto.Bucket, len(h.upperBounds)),
SampleCount: proto.Uint64(count),
SampleSum: proto.Float64(math.Float64frombits(atomic.LoadUint64(&coldCounts.sumBits))),
SampleCount: new(count),
SampleSum: new(math.Float64frombits(atomic.LoadUint64(&coldCounts.sumBits))),
CreatedTimestamp: timestamppb.New(h.lastResetTime),
}
out.Histogram = his
@@ -814,8 +814,8 @@ func (h *histogram) Write(out *dto.Metric) error {
for i, upperBound := range h.upperBounds {
cumCount += atomic.LoadUint64(&coldCounts.buckets[i])
his.Bucket[i] = &dto.Bucket{
CumulativeCount: proto.Uint64(cumCount),
UpperBound: proto.Float64(upperBound),
CumulativeCount: new(cumCount),
UpperBound: new(upperBound),
}
if e := h.exemplars[i].Load(); e != nil {
his.Bucket[i].Exemplar = e.(*dto.Exemplar)
@@ -824,15 +824,15 @@ func (h *histogram) Write(out *dto.Metric) error {
// If there is an exemplar for the +Inf bucket, we have to add that bucket explicitly.
if e := h.exemplars[len(h.upperBounds)].Load(); e != nil {
b := &dto.Bucket{
CumulativeCount: proto.Uint64(count),
UpperBound: proto.Float64(math.Inf(1)),
CumulativeCount: new(count),
UpperBound: new(math.Inf(1)),
Exemplar: e.(*dto.Exemplar),
}
his.Bucket = append(his.Bucket, b)
}
if h.nativeHistogramSchema > math.MinInt32 {
his.ZeroThreshold = proto.Float64(math.Float64frombits(atomic.LoadUint64(&coldCounts.nativeHistogramZeroThresholdBits)))
his.Schema = proto.Int32(atomic.LoadInt32(&coldCounts.nativeHistogramSchema))
his.ZeroThreshold = new(math.Float64frombits(atomic.LoadUint64(&coldCounts.nativeHistogramZeroThresholdBits)))
his.Schema = new(atomic.LoadInt32(&coldCounts.nativeHistogramSchema))
zeroBucket := atomic.LoadUint64(&coldCounts.nativeHistogramZeroBucket)
defer func() {
@@ -840,7 +840,7 @@ func (h *histogram) Write(out *dto.Metric) error {
coldCounts.nativeHistogramBucketsNegative.Range(addAndReset(&hotCounts.nativeHistogramBucketsNegative, &hotCounts.nativeHistogramBucketsNumber))
}()
his.ZeroCount = proto.Uint64(zeroBucket)
his.ZeroCount = new(zeroBucket)
his.NegativeSpan, his.NegativeDelta = makeBuckets(&coldCounts.nativeHistogramBucketsNegative)
his.PositiveSpan, his.PositiveDelta = makeBuckets(&coldCounts.nativeHistogramBucketsPositive)
@@ -1331,12 +1331,12 @@ func (h *constHistogram) Write(out *dto.Metric) error {
buckets := make([]*dto.Bucket, 0, len(h.buckets))
his.SampleCount = proto.Uint64(h.count)
his.SampleSum = proto.Float64(h.sum)
his.SampleCount = new(h.count)
his.SampleSum = new(h.sum)
for upperBound, count := range h.buckets {
buckets = append(buckets, &dto.Bucket{
CumulativeCount: proto.Uint64(count),
UpperBound: proto.Float64(upperBound),
CumulativeCount: new(count),
UpperBound: new(upperBound),
})
}
@@ -1481,7 +1481,7 @@ func pickSchema(bucketFactor float64) int32 {
func makeBuckets(buckets *sync.Map) ([]*dto.BucketSpan, []int64) {
var ii []int
buckets.Range(func(k, v any) bool {
buckets.Range(func(k, _ any) bool {
ii = append(ii, k.(int))
return true
})
@@ -1518,13 +1518,13 @@ func makeBuckets(buckets *sync.Map) ([]*dto.BucketSpan, []int64) {
// at the very beginning, or because we have found a gap
// of more than two buckets.
spans = append(spans, &dto.BucketSpan{
Offset: proto.Int32(iDelta),
Offset: new(iDelta),
Length: proto.Uint32(0),
})
} else {
// We have found a small gap (or no gap at all).
// Insert empty buckets as needed.
for j := int32(0); j < iDelta; j++ {
for range iDelta {
appendDelta(0)
}
}
@@ -1570,7 +1570,7 @@ func addAndReset(hotBuckets *sync.Map, bucketNumber *uint32) func(k, v any) bool
}
func deleteSyncMap(m *sync.Map) {
m.Range(func(k, v any) bool {
m.Range(func(k, _ any) bool {
m.Delete(k)
return true
})
@@ -1578,7 +1578,7 @@ func deleteSyncMap(m *sync.Map) {
func findSmallestKey(m *sync.Map) int {
result := math.MaxInt32
m.Range(func(k, v any) bool {
m.Range(func(k, _ any) bool {
key := k.(int)
if key < result {
result = key
@@ -1956,7 +1956,7 @@ func NewConstNativeHistogram(
PositiveSpan: PositiveSpan,
PositiveDelta: PositiveDelta,
ZeroCount: proto.Uint64(zeroBucket),
ZeroCount: new(zeroBucket),
},
labelPairs: MakeLabelPairs(desc, labelValues),
}
@@ -2044,13 +2044,13 @@ func makeBucketsFromMap(buckets map[int]int64) ([]*dto.BucketSpan, []int64) {
// at the very beginning, or because we have found a gap
// of more than two buckets.
spans = append(spans, &dto.BucketSpan{
Offset: proto.Int32(iDelta),
Offset: new(iDelta),
Length: proto.Uint32(0),
})
} else {
// We have found a small gap (or no gap at all).
// Insert empty buckets as needed.
for j := int32(0); j < iDelta; j++ {
for range iDelta {
appendDelta(0)
}
}
@@ -11,9 +11,6 @@
// See the License for the specific language governing permissions and
// limitations under the License.
//go:build go1.17
// +build go1.17
package internal
import (
+3 -4
View File
@@ -22,7 +22,6 @@ import (
dto "github.com/prometheus/client_model/go"
"github.com/prometheus/common/model"
"google.golang.org/protobuf/proto"
)
var separatorByteSlice = []byte{model.SeparatorByte} // For convenient use with xxhash.
@@ -153,7 +152,7 @@ type timestampedMetric struct {
func (m timestampedMetric) Write(pb *dto.Metric) error {
e := m.Metric.Write(pb)
pb.TimestampMs = proto.Int64(m.t.Unix()*1000 + int64(m.t.Nanosecond()/1000000))
pb.TimestampMs = new(m.t.Unix()*1000 + int64(m.t.Nanosecond()/1000000))
return e
}
@@ -209,8 +208,8 @@ func (m *withExemplarsMetric) Write(pb *dto.Metric) error {
} else {
// The +Inf bucket should be explicitly added if there is an exemplar for it, similar to non-const histogram logic in https://github.com/prometheus/client_golang/blob/main/prometheus/histogram.go#L357-L365.
b := &dto.Bucket{
CumulativeCount: proto.Uint64(h.GetSampleCount()),
UpperBound: proto.Float64(math.Inf(1)),
CumulativeCount: new(h.GetSampleCount()),
UpperBound: new(math.Inf(1)),
Exemplar: e,
}
h.Bucket = append(h.Bucket, b)
-1
View File
@@ -12,7 +12,6 @@
// limitations under the License.
//go:build !js || wasm
// +build !js wasm
package prometheus
@@ -12,7 +12,6 @@
// limitations under the License.
//go:build js && !wasm
// +build js,!wasm
package prometheus
@@ -54,21 +54,22 @@ func getOpenFileCount() (float64, error) {
// benefits, however, include fewer system calls and not failing when at the
// open file soft limit.
if dir, err := os.Open("/dev/fd"); err != nil {
dir, err := os.Open("/dev/fd")
if err != nil {
return 0.0, err
} else {
defer dir.Close()
// Avoid ReadDir(), as it calls stat(2) on each descriptor. Not only is
// that info not used, but KQUEUE descriptors fail stat(2), which causes
// the whole method to fail.
if names, err := dir.Readdirnames(0); err != nil {
return 0.0, err
} else {
// Subtract 1 to ignore the open /dev/fd descriptor above.
return float64(len(names) - 1), nil
}
}
defer dir.Close()
// Avoid ReadDir(), as it calls stat(2) on each descriptor. Not only is
// that info not used, but KQUEUE descriptors fail stat(2), which causes
// the whole method to fail.
names, err := dir.Readdirnames(0)
if err != nil {
return 0.0, err
}
// Subtract 1 to ignore the open /dev/fd descriptor above.
return float64(len(names) - 1), nil
}
func (c *processCollector) processCollect(ch chan<- Metric) {
@@ -12,7 +12,6 @@
// limitations under the License.
//go:build wasip1 || js || ios
// +build wasip1 js ios
package prometheus
@@ -12,7 +12,6 @@
// limitations under the License.
//go:build !windows && !js && !wasip1 && !darwin
// +build !windows,!js,!wasip1,!darwin
package prometheus
+31 -7
View File
@@ -51,10 +51,12 @@ import (
)
const (
acceptHeader = "Accept"
contentTypeHeader = "Content-Type"
contentEncodingHeader = "Content-Encoding"
acceptEncodingHeader = "Accept-Encoding"
processStartTimeHeader = "Process-Start-Time-Unix"
varyHeader = "Vary"
)
// Compression represents the content encodings handlers support for the HTTP
@@ -70,9 +72,8 @@ const (
func defaultCompressionFormats() []Compression {
if internal.NewZstdWriter != nil {
return []Compression{Identity, Gzip, Zstd}
} else {
return []Compression{Identity, Gzip}
}
return []Compression{Identity, Gzip}
}
var gzipPool = sync.Pool{
@@ -315,11 +316,20 @@ func HandlerForTransactional(reg prometheus.TransactionalGatherer, opts HandlerO
}
}
var contentType expfmt.Format
if opts.EnableOpenMetrics {
contentType = expfmt.NegotiateIncludingOpenMetrics(req.Header)
} else {
contentType = expfmt.Negotiate(req.Header)
var (
contentType expfmt.Format
acceptedFormats = opts.AcceptedFormats
)
if len(acceptedFormats) == 0 {
acceptedFormats = expfmt.DefaultAcceptedFormats()
if opts.EnableOpenMetrics {
acceptedFormats = expfmt.DefaultOpenMetricsAcceptedFormats()
}
}
contentType = expfmt.NegotiateAccept(req.Header, acceptedFormats...)
rsp.Header().Add(varyHeader, acceptHeader)
if len(compressions) > 0 {
rsp.Header().Add(varyHeader, acceptEncodingHeader)
}
rsp.Header().Set(contentTypeHeader, string(contentType))
@@ -598,6 +608,8 @@ type HandlerOpts struct {
// a trailing ".0" if they would otherwise look like integer numbers
// (which changes the identity of the resulting series on the Prometheus
// server).
//
// Note that setting AcceptedFormats overrides this option.
EnableOpenMetrics bool
// EnableOpenMetricsTextCreatedSamples specifies if this handler should add, extra, synthetic
// Created Timestamps for counters, histograms and summaries, which for the current
@@ -622,6 +634,18 @@ type HandlerOpts struct {
// NOTE: This feature is experimental and not covered by OpenMetrics or Prometheus
// exposition format.
ProcessStartTime time.Time
// AcceptedFormats allows customizing the formats the handler will negotiate
// with the client based on the request's Accept header.
// The client's Accept header and q-values take precedence, but the order of
// formats in AcceptedFormats specifies the server's preference order used as a
// tie-breaker (e.g. for wildcard "*/*" requests or equal q-values) and fallback.
// If empty, the default set is used (expfmt.DefaultAcceptedFormats()).
// If empty and EnableOpenMetrics is true, stable OpenMetrics formats are negotiated
// (expfmt.DefaultOpenMetricsAcceptedFormats()).
// This is useful for testing experimental formats (e.g. OpenMetrics 2.0)
// or restricting the formats you want to allow.
// Using EnableOpenMetrics with an empty AcceptedFormats is still the recommended option for the majority of cases.
AcceptedFormats []expfmt.Format
}
// httpError removes any content-encoding header and then calls http.Error with
+1 -1
View File
@@ -41,7 +41,7 @@ type options struct {
func defaultOptions() *options {
return &options{
getExemplarFn: func(req *http.Request) prometheus.Labels { return nil },
getExemplarFn: func(_ *http.Request) prometheus.Labels { return nil },
extraLabelsFromRequest: map[string]LabelValueFromRequest{},
}
}
+13 -11
View File
@@ -17,6 +17,7 @@ import (
"bytes"
"errors"
"fmt"
"maps"
"os"
"path/filepath"
"runtime"
@@ -31,7 +32,6 @@ import (
"github.com/cespare/xxhash/v2"
dto "github.com/prometheus/client_model/go"
"github.com/prometheus/common/expfmt"
"google.golang.org/protobuf/proto"
)
const (
@@ -296,6 +296,7 @@ func (r *Registry) Register(c Collector) error {
defer func() {
// Drain channel in case of premature return to not leak a goroutine.
for range descChan {
continue
}
r.mtx.Unlock()
}()
@@ -369,9 +370,7 @@ func (r *Registry) Register(c Collector) error {
for hash := range newDescIDs {
r.descIDs[hash] = struct{}{}
}
for name, dimHash := range newDimHashesByName {
r.dimHashesByName[name] = dimHash
}
maps.Copy(r.dimHashesByName, newDimHashesByName)
return nil
}
@@ -476,7 +475,7 @@ func (r *Registry) Gather() ([]*dto.MetricFamily, error) {
for {
select {
case collector := <-checkedCollectors:
safeErrs.Append((safeCollect(collector, checkedMetricChan)))
safeErrs.Append(safeCollect(collector, checkedMetricChan))
case collector := <-uncheckedCollectors:
safeErrs.Append(safeCollect(collector, uncheckedMetricChan))
default:
@@ -502,10 +501,12 @@ func (r *Registry) Gather() ([]*dto.MetricFamily, error) {
defer func() {
if checkedMetricChan != nil {
for range checkedMetricChan {
continue
}
}
if uncheckedMetricChan != nil {
for range uncheckedMetricChan {
continue
}
}
}()
@@ -727,10 +728,10 @@ func processMetric(
}
} else { // New name.
metricFamily = &dto.MetricFamily{}
metricFamily.Name = proto.String(desc.fqName)
metricFamily.Help = proto.String(desc.help)
metricFamily.Name = new(desc.fqName)
metricFamily.Help = new(desc.help)
if desc.unit != "" {
metricFamily.Unit = proto.String(desc.unit)
metricFamily.Unit = new(desc.unit)
}
// TODO(beorn7): Simplify switch once Desc has type.
switch {
@@ -956,7 +957,8 @@ func checkMetricConsistency(
if !utf8.ValidString(labelPair.GetValue()) {
return fmt.Errorf(
"collected metric %q { %s} has a label named %q whose value is not utf8: %#v",
name, dtoMetric, labelName, labelPair.GetValue())
name, dtoMetric, labelName, labelPair.GetValue(),
)
}
previousLabelName = labelName
}
@@ -981,7 +983,7 @@ func checkMetricConsistency(
h.Write(separatorByteSlice)
}
if dtoMetric.TimestampMs != nil {
h.WriteString(strconv.FormatInt(*(dtoMetric.TimestampMs), 10))
h.WriteString(strconv.FormatInt(*dtoMetric.TimestampMs, 10))
h.Write(separatorByteSlice)
}
hSum := h.Sum64()
@@ -1013,7 +1015,7 @@ func checkDescConsistency(
copy(lpsFromDesc, desc.constLabelPairs)
for _, l := range desc.variableLabels.names {
lpsFromDesc = append(lpsFromDesc, &dto.LabelPair{
Name: proto.String(l),
Name: new(l),
})
}
if len(lpsFromDesc) != len(dtoMetric.Label) {
+10 -11
View File
@@ -25,7 +25,6 @@ import (
dto "github.com/prometheus/client_model/go"
"github.com/beorn7/perks/quantile"
"google.golang.org/protobuf/proto"
"google.golang.org/protobuf/types/known/timestamppb"
)
@@ -337,8 +336,8 @@ func (s *summary) Write(out *dto.Metric) error {
s.bufMtx.Unlock()
s.flushColdBuf()
sum.SampleCount = proto.Uint64(s.cnt)
sum.SampleSum = proto.Float64(s.sum)
sum.SampleCount = new(s.cnt)
sum.SampleSum = new(s.sum)
for _, rank := range s.sortedObjectives {
var q float64
@@ -348,8 +347,8 @@ func (s *summary) Write(out *dto.Metric) error {
q = s.headStream.Query(rank)
}
qs = append(qs, &dto.Quantile{
Quantile: proto.Float64(rank),
Value: proto.Float64(q),
Quantile: new(rank),
Value: new(q),
})
}
@@ -512,8 +511,8 @@ func (s *noObjectivesSummary) Write(out *dto.Metric) error {
}
sum := &dto.Summary{
SampleCount: proto.Uint64(count),
SampleSum: proto.Float64(math.Float64frombits(atomic.LoadUint64(&coldCounts.sumBits))),
SampleCount: new(count),
SampleSum: new(math.Float64frombits(atomic.LoadUint64(&coldCounts.sumBits))),
CreatedTimestamp: s.createdTs,
}
@@ -718,13 +717,13 @@ func (s *constSummary) Write(out *dto.Metric) error {
}
qs := make([]*dto.Quantile, 0, len(s.quantiles))
sum.SampleCount = proto.Uint64(s.count)
sum.SampleSum = proto.Float64(s.sum)
sum.SampleCount = new(s.count)
sum.SampleSum = new(s.sum)
for rank, q := range s.quantiles {
qs = append(qs, &dto.Quantile{
Quantile: proto.Float64(rank),
Value: proto.Float64(q),
Quantile: new(rank),
Value: new(q),
})
}
+8 -9
View File
@@ -23,7 +23,6 @@ import (
"github.com/prometheus/client_golang/prometheus/internal"
dto "github.com/prometheus/client_model/go"
"google.golang.org/protobuf/proto"
"google.golang.org/protobuf/types/known/timestamppb"
)
@@ -196,11 +195,11 @@ func populateMetric(
m.Label = labelPairs
switch t {
case CounterValue:
m.Counter = &dto.Counter{Value: proto.Float64(v), Exemplar: e, CreatedTimestamp: ct}
m.Counter = &dto.Counter{Value: new(v), Exemplar: e, CreatedTimestamp: ct}
case GaugeValue:
m.Gauge = &dto.Gauge{Value: proto.Float64(v)}
m.Gauge = &dto.Gauge{Value: new(v)}
case UntypedValue:
m.Untyped = &dto.Untyped{Value: proto.Float64(v)}
m.Untyped = &dto.Untyped{Value: new(v)}
default:
return fmt.Errorf("encountered unknown type %v", t)
}
@@ -227,8 +226,8 @@ func MakeLabelPairs(desc *Desc, labelValues []string) []*dto.LabelPair {
labelPairs := make([]*dto.LabelPair, 0, totalLen)
for i, l := range desc.variableLabels.names {
labelPairs = append(labelPairs, &dto.LabelPair{
Name: proto.String(l),
Value: proto.String(labelValues[i]),
Name: new(l),
Value: new(labelValues[i]),
})
}
labelPairs = append(labelPairs, desc.constLabelPairs...)
@@ -244,7 +243,7 @@ const ExemplarMaxRunes = 128
// number of runes in the label names and values exceeds ExemplarMaxRunes.
func newExemplar(value float64, ts time.Time, l Labels) (*dto.Exemplar, error) {
e := &dto.Exemplar{}
e.Value = proto.Float64(value)
e.Value = new(value)
tsProto := timestamppb.New(ts)
if err := tsProto.CheckValid(); err != nil {
return nil, err
@@ -262,8 +261,8 @@ func newExemplar(value float64, ts time.Time, l Labels) (*dto.Exemplar, error) {
}
runes += utf8.RuneCountInString(value)
labelPairs = append(labelPairs, &dto.LabelPair{
Name: proto.String(name),
Value: proto.String(value),
Name: new(name),
Value: new(value),
})
}
if runes > ExemplarMaxRunes {
+2 -3
View File
@@ -20,7 +20,6 @@ import (
"github.com/prometheus/client_golang/prometheus/internal"
dto "github.com/prometheus/client_model/go"
"google.golang.org/protobuf/proto"
)
// WrapRegistererWith returns a Registerer wrapping the provided
@@ -212,8 +211,8 @@ func (m *wrappingMetric) Write(out *dto.Metric) error {
}
for ln, lv := range m.labels {
out.Label = append(out.Label, &dto.LabelPair{
Name: proto.String(ln),
Value: proto.String(lv),
Name: new(ln),
Value: new(lv),
})
}
sort.Sort(internal.LabelPairSorter(out.Label))
+86 -7
View File
@@ -61,10 +61,30 @@ func ResponseFormat(h http.Header) Format {
return FmtProtoDelim
case textType:
if params["version"] == TextVersion_1_0_0 {
if _, ok := params[model.EscapingKey]; ok {
return FmtText_1_0_0.WithEscapingScheme(Format(ct).ToEscapingScheme())
}
return FmtText_1_0_0
}
if v, ok := params["version"]; ok && v != TextVersion {
return FmtUnknown
}
return FmtText
case OpenMetricsType:
switch params["version"] {
case "", OpenMetricsVersion_0_0_1:
return FmtOpenMetrics_0_0_1
case OpenMetricsVersion_1_0_0:
return FmtOpenMetrics_1_0_0
case OpenMetricsVersion_2_0_0_rc:
return FmtOpenMetrics_2_0_0_rc
case OpenMetricsVersion_2_0_0:
return FmtOpenMetrics_2_0_0
default:
return FmtUnknown
}
}
return FmtUnknown
@@ -72,13 +92,13 @@ func ResponseFormat(h http.Header) Format {
// NewDecoder returns a new decoder based on the given input format. Metric
// names are validated based on the provided Format -- if the format requires
// escaping, raditional Prometheues validity checking is used. Otherwise, names
// are checked for UTF-8 validity. Supported formats include delimited protobuf
// and Prometheus text format. For historical reasons, this decoder fallbacks
// to classic text decoding for any other format. This decoder does not fully
// support OpenMetrics although it may often succeed due to the similarities
// between the formats. This decoder may not support the latest features of
// Prometheus text format and is not intended for high-performance applications.
// escaping, traditional Prometheus validity checking is used. Otherwise, names
// are checked for UTF-8 validity. Supported formats include delimited protobuf,
// Prometheus text format, and OpenMetrics 0.0.1 / 1.0.0 / 2.0.0-rc / 2.0.0. For historical
// reasons, this decoder falls back to classic text decoding for other legacy
// formats, and returns an error for unsupported formats such as text protobuf.
// This decoder may not support the latest features of Prometheus text format
// and is not intended for high-performance applications.
// See: https://github.com/prometheus/common/issues/812
func NewDecoder(r io.Reader, format Format) Decoder {
scheme := model.LegacyValidation
@@ -90,6 +110,26 @@ func NewDecoder(r io.Reader, format Format) Decoder {
return &protoDecoder{r: bufio.NewReader(r), s: scheme}
case TypeProtoText, TypeProtoCompact:
return &errDecoder{err: fmt.Errorf("format %s not supported for decoding", format)}
case TypeOpenMetrics:
_, params, err := mime.ParseMediaType(string(format))
if err != nil {
return &errDecoder{err: fmt.Errorf("format %s not supported for decoding", format)}
}
switch params["version"] {
case "", OpenMetricsVersion_0_0_1, OpenMetricsVersion_1_0_0:
return &openMetricsDecoder{p: newOpenMetricsParser(r, scheme)}
case OpenMetricsVersion_2_0_0_rc, OpenMetricsVersion_2_0_0:
// format.ToEscapingScheme() defaults to UnderscoreEscaping when no escaping
// parameter is set, whereas OpenMetrics 2.0 supports UTF-8 names by default
// unless a non-UTF-8 escaping scheme is explicitly requested.
om2Scheme := model.UTF8Validation
if _, hasEscaping := params[model.EscapingKey]; hasEscaping && format.ToEscapingScheme() != model.NoEscaping {
om2Scheme = model.LegacyValidation
}
return &openMetrics20Decoder{p: newOpenMetrics20Parser(r, om2Scheme)}
default:
return &errDecoder{err: fmt.Errorf("format %s not supported for decoding", format)}
}
}
return &textDecoder{r: r, s: scheme}
}
@@ -139,6 +179,45 @@ func (d *errDecoder) Decode(*dto.MetricFamily) error {
return d.err
}
// openMetricsDecoder implements the Decoder interface for the OpenMetrics 1.0 protocol.
type openMetricsDecoder struct {
p *openMetricsParser
err error
}
// Decode implements the Decoder interface.
func (d *openMetricsDecoder) Decode(v *dto.MetricFamily) error {
if d.err != nil {
return d.err
}
if err := d.p.next(v); err != nil {
d.err = err
return err
}
return nil
}
// openMetrics20Decoder implements the Decoder interface for the OpenMetrics 2.0 protocol.
// Like openMetricsDecoder, it uses goabnf.ParseForest per line without a line-length
// cap (which has superlinear parse time in line length) and is intended for
// reference/conformance decoding rather than high-performance or untrusted inputs.
type openMetrics20Decoder struct {
p *openMetrics20Parser
err error
}
// Decode implements the Decoder interface.
func (d *openMetrics20Decoder) Decode(v *dto.MetricFamily) error {
if d.err != nil {
return d.err
}
if err := d.p.next(v); err != nil {
d.err = err
return err
}
return nil
}
// textDecoder implements the Decoder interface for the text protocol.
type textDecoder struct {
r io.Reader
+155 -57
View File
@@ -16,7 +16,9 @@ package expfmt
import (
"fmt"
"io"
"mime"
"net/http"
"slices"
"github.com/munnerz/goautoneg"
dto "github.com/prometheus/client_model/go"
@@ -26,6 +28,60 @@ import (
"github.com/prometheus/common/model"
)
var formatToAccept = map[Format]goautoneg.Accept{}
func init() {
for _, f := range []Format{
FmtText,
FmtText_1_0_0,
FmtProtoDelim,
FmtProtoText,
FmtProtoCompact,
FmtOpenMetrics_1_0_0,
FmtOpenMetrics_2_0_0_rc,
FmtOpenMetrics_2_0_0,
FmtOpenMetrics_0_0_1,
} {
if parsed := goautoneg.ParseAccept(string(f)); len(parsed) > 0 {
formatToAccept[f] = parsed[0]
}
}
}
var (
defaultAcceptedFormats = []Format{
FmtProtoDelim,
FmtProtoText,
FmtProtoCompact,
FmtText,
FmtText_1_0_0,
}
defaultOpenMetricsAcceptedFormats = []Format{
FmtOpenMetrics_1_0_0,
FmtOpenMetrics_0_0_1,
FmtProtoDelim,
FmtProtoText,
FmtProtoCompact,
FmtText,
FmtText_1_0_0,
}
)
// DefaultAcceptedFormats returns a copy of standard accepted formats for Negotiate,
// ordered by preference (delimited protobuf, protobuf text, compact protobuf text,
// and Prometheus text formats). Version 0.0.4 remains the fallback when no
// supported version is requested.
func DefaultAcceptedFormats() []Format {
return slices.Clone(defaultAcceptedFormats)
}
// DefaultOpenMetricsAcceptedFormats returns a copy of standard accepted formats including
// stable OpenMetrics formats, ordered by preference.
func DefaultOpenMetricsAcceptedFormats() []Format {
return slices.Clone(defaultOpenMetricsAcceptedFormats)
}
// Encoder types encode metric families into an underlying wire protocol.
type Encoder interface {
Encode(*dto.MetricFamily) error
@@ -57,77 +113,106 @@ func (ec encoderCloser) Close() error {
// Negotiate returns the Content-Type based on the given Accept header. If no
// appropriate accepted type is found, FmtText is returned (which is the
// Prometheus text format). This function will never negotiate FmtOpenMetrics,
// as the support is still experimental. To include the option to negotiate
// FmtOpenMetrics, use NegotiateIncludingOpenMetrics.
// Prometheus text format).
//
// Deprecated: Use NegotiateAccept(h, DefaultAcceptedFormats()...)
// or specify only the formats supported by your server.
func Negotiate(h http.Header) Format {
escapingScheme := Format(fmt.Sprintf("; escaping=%s", Format(model.NameEscapingScheme.String())))
return NegotiateAccept(h, defaultAcceptedFormats...)
}
// NegotiateIncludingOpenMetrics works like Negotiate but includes all stable
// FmtOpenMetrics formats as an option for the result.
//
// Deprecated: Use NegotiateAccept(h, DefaultOpenMetricsAcceptedFormats()...)
// or specify only the formats supported by your server.
func NegotiateIncludingOpenMetrics(h http.Header) Format {
return NegotiateAccept(h, defaultOpenMetricsAcceptedFormats...)
}
// NegotiateAccept returns the Content-Type based on the given Accept header
// and the list of accepted Formats provided by the caller, in order of preference.
// If no accepted format matches the Accept header, it falls back to the text
// format if present in the accepted list, or the first accepted format (or FmtText
// if accepted is empty).
// The escaping scheme is taken from the matching Accept clause. Without one,
// OpenMetrics 2.0 gets allow-utf-8 and all other formats model.NameEscapingScheme.
func NegotiateAccept(h http.Header, accepted ...Format) Format {
escapingScheme := Format("; escaping=" + model.NameEscapingScheme.String())
for _, ac := range goautoneg.ParseAccept(h.Get(hdrAccept)) {
if escapeParam := ac.Params[model.EscapingKey]; escapeParam != "" {
switch Format(escapeParam) {
case model.AllowUTF8, model.EscapeUnderscores, model.EscapeDots, model.EscapeValues:
escapingScheme = Format("; escaping=" + escapeParam)
default:
// If the escaping parameter is unknown, ignore it.
for _, f := range accepted {
if matchFormat(ac, f) {
return f + escapingFor(ac, f)
}
}
ver := ac.Params["version"]
if ac.Type+"/"+ac.SubType == ProtoType && ac.Params["proto"] == ProtoProtocol {
switch ac.Params["encoding"] {
case "delimited":
return FmtProtoDelim + escapingScheme
case "text":
return FmtProtoText + escapingScheme
case "compact-text":
return FmtProtoCompact + escapingScheme
}
}
if ac.Type == "text" && ac.SubType == "plain" && (ver == TextVersion || ver == "") {
return FmtText + escapingScheme
}
for _, f := range accepted {
if f.FormatType() == TypeTextPlain {
return f + escapingScheme
}
}
if len(accepted) > 0 {
return accepted[0] + escapingScheme
}
return FmtText + escapingScheme
}
// NegotiateIncludingOpenMetrics works like Negotiate but includes
// FmtOpenMetrics as an option for the result. Note that this function is
// temporary and will disappear once FmtOpenMetrics is fully supported and as
// such may be negotiated by the normal Negotiate function.
func NegotiateIncludingOpenMetrics(h http.Header) Format {
escapingScheme := Format(fmt.Sprintf("; escaping=%s", Format(model.NameEscapingScheme.String())))
for _, ac := range goautoneg.ParseAccept(h.Get(hdrAccept)) {
if escapeParam := ac.Params[model.EscapingKey]; escapeParam != "" {
switch Format(escapeParam) {
case model.AllowUTF8, model.EscapeUnderscores, model.EscapeDots, model.EscapeValues:
escapingScheme = Format("; escaping=" + escapeParam)
default:
// If the escaping parameter is unknown, ignore it.
}
// escapingFor returns the escaping term for the Accept clause that matched f.
func escapingFor(ac goautoneg.Accept, f Format) Format {
switch p := ac.Params[model.EscapingKey]; p {
case model.AllowUTF8, model.EscapeUnderscores, model.EscapeDots, model.EscapeValues:
// An explicit request always wins, also for OpenMetrics 2.0.
return Format("; escaping=" + p)
}
if f.FormatType() == TypeOpenMetrics && isOpenMetrics20Version(f.Version()) {
// OpenMetrics 2.0 is UTF-8 native, so asking for it implies UTF-8 name support.
return Format("; escaping=" + model.AllowUTF8)
}
return Format("; escaping=" + model.NameEscapingScheme.String())
}
// matchFormat checks if a parsed accept clause matches a given Format.
func matchFormat(ac goautoneg.Accept, f Format) bool {
target, ok := formatToAccept[f]
if !ok {
parsed := goautoneg.ParseAccept(string(f))
if len(parsed) == 0 {
return false
}
ver := ac.Params["version"]
if ac.Type+"/"+ac.SubType == ProtoType && ac.Params["proto"] == ProtoProtocol {
switch ac.Params["encoding"] {
case "delimited":
return FmtProtoDelim + escapingScheme
case "text":
return FmtProtoText + escapingScheme
case "compact-text":
return FmtProtoCompact + escapingScheme
}
target = parsed[0]
}
if ac.Type != "*" && ac.Type != target.Type {
return false
}
if ac.SubType != "*" && ac.SubType != target.SubType {
return false
}
// Default OpenMetrics version to OpenMetricsVersion_0_0_1.
acVersion := ac.Params["version"]
if acVersion == "" && ac.Type+"/"+ac.SubType == OpenMetricsType {
acVersion = OpenMetricsVersion_0_0_1
}
if acVersion == "" && ac.Type == "text" && ac.SubType == "plain" {
acVersion = TextVersion
}
// General param matching.
for k, v := range target.Params {
if k == "charset" {
continue
}
if ac.Type == "text" && ac.SubType == "plain" && (ver == TextVersion || ver == "") {
return FmtText + escapingScheme
acVal := ac.Params[k]
if k == "version" {
acVal = acVersion
}
if ac.Type+"/"+ac.SubType == OpenMetricsType && (ver == OpenMetricsVersion_0_0_1 || ver == OpenMetricsVersion_1_0_0 || ver == "") {
switch ver {
case OpenMetricsVersion_1_0_0:
return FmtOpenMetrics_1_0_0 + escapingScheme
default:
return FmtOpenMetrics_0_0_1 + escapingScheme
}
if acVal != v {
return false
}
}
return FmtText + escapingScheme
return true
}
// NewEncoder returns a new encoder based on content type negotiation. All
@@ -181,6 +266,19 @@ func NewEncoder(w io.Writer, format Format, options ...EncoderOption) Encoder {
close: func() error { return nil },
}
case TypeOpenMetrics:
_, params, err := mime.ParseMediaType(string(format))
if err == nil && isOpenMetrics20Version(params["version"]) {
return encoderCloser{
encode: func(v *dto.MetricFamily) error {
_, err := MetricFamilyToOpenMetrics20(w, model.EscapeMetricFamily(v, escapingScheme), options...)
return err
},
close: func() error {
_, err := FinalizeOpenMetrics(w)
return err
},
}
}
return encoderCloser{
encode: func(v *dto.MetricFamily) error {
_, err := MetricFamilyToOpenMetrics(w, model.EscapeMetricFamily(v, escapingScheme), options...)
+87 -56
View File
@@ -16,50 +16,56 @@ package expfmt
import (
"errors"
"mime"
"strings"
"github.com/prometheus/common/model"
)
// Format specifies the HTTP content type of the different wire protocols.
type Format string
// Constants to assemble the Content-Type values for the different wire
// protocols. The Content-Type strings here are all for the legacy exposition
// formats, where valid characters for metric names and label names are limited.
// Support for arbitrary UTF-8 characters in those names is already partially
// implemented in this module (see model.ValidationScheme), but to actually use
// it on the wire, new content-type strings will have to be agreed upon and
// added here.
// protocols.
const (
TextVersion = "0.0.4"
ProtoType = `application/vnd.google.protobuf`
ProtoProtocol = `io.prometheus.client.MetricFamily`
// Deprecated: Use expfmt.NewFormat(expfmt.TypeProtoCompact) instead.
ProtoFmt = ProtoType + "; proto=" + ProtoProtocol + ";"
TextVersion = "0.0.4"
//nolint:revive // Allow for underscores.
TextVersion_1_0_0 = "1.0.0"
ProtoType = `application/vnd.google.protobuf`
ProtoProtocol = `io.prometheus.client.MetricFamily`
ProtoFmt = ProtoType + "; proto=" + ProtoProtocol + ";"
OpenMetricsType = `application/openmetrics-text`
//nolint:revive // Allow for underscores.
OpenMetricsVersion_0_0_1 = "0.0.1"
//nolint:revive // Allow for underscores.
OpenMetricsVersion_1_0_0 = "1.0.0"
//nolint:revive // Allow for underscores.
OpenMetricsVersion_2_0_0_rc = "2.0.0-rc"
//nolint:revive // Allow for underscores.
OpenMetricsVersion_2_0_0 = "2.0.0"
)
// 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.
// Format specifies the HTTP content type of the different wire protocols.
// The Content-Type values for the different wire protocols represent
// baseline Content-Types used for HTTP headers and content negotiation.
//
// Because Content-Types on the wire may include dynamic parameters
// (such as "; escaping=...") or whitespace variations, avoid comparing Format
// values using direct equality (==).
type Format string
const (
FmtUnknown Format = `<unknown>`
// Deprecated: Use expfmt.NewFormat(expfmt.TypeTextPlain) instead.
FmtText Format = `text/plain; version=` + TextVersion + `; charset=utf-8`
// Deprecated: Use expfmt.NewFormat(expfmt.TypeProtoDelim) instead.
FmtProtoDelim Format = ProtoFmt + ` encoding=delimited`
// Deprecated: Use expfmt.NewFormat(expfmt.TypeProtoText) instead.
FmtProtoText Format = ProtoFmt + ` encoding=text`
// Deprecated: Use expfmt.NewFormat(expfmt.TypeProtoCompact) instead.
FmtText Format = `text/plain; version=` + TextVersion + `; charset=utf-8`
//nolint:revive // Allow for underscores.
FmtText_1_0_0 Format = `text/plain; version=` + TextVersion_1_0_0 + `; charset=utf-8`
FmtProtoDelim Format = ProtoFmt + ` encoding=delimited`
FmtProtoText Format = ProtoFmt + ` encoding=text`
FmtProtoCompact Format = ProtoFmt + ` encoding=compact-text`
// Deprecated: Use expfmt.NewFormat(expfmt.TypeOpenMetrics) instead.
//nolint:revive // Allow for underscores.
FmtOpenMetrics_2_0_0 Format = OpenMetricsType + `; version=` + OpenMetricsVersion_2_0_0 + `; charset=utf-8`
//nolint:revive // Allow for underscores.
FmtOpenMetrics_2_0_0_rc Format = OpenMetricsType + `; version=` + OpenMetricsVersion_2_0_0_rc + `; charset=utf-8`
//nolint:revive // Allow for underscores.
FmtOpenMetrics_1_0_0 Format = OpenMetricsType + `; version=` + OpenMetricsVersion_1_0_0 + `; charset=utf-8`
// Deprecated: Use expfmt.NewFormat(expfmt.TypeOpenMetrics) instead.
//nolint:revive // Allow for underscores.
FmtOpenMetrics_0_0_1 Format = OpenMetricsType + `; version=` + OpenMetricsVersion_0_0_1 + `; charset=utf-8`
)
@@ -86,8 +92,8 @@ const (
// NewFormat generates a new Format from the type provided. Mostly used for
// tests, most Formats should be generated as part of content negotiation in
// encode.go. If a type has more than one version, the latest version will be
// returned.
// encode.go. If a type has more than one version, the latest stable version will be
// returned, except that TypeTextPlain retains version 0.0.4 for compatibility.
func NewFormat(t FormatType) Format {
switch t {
case TypeProtoCompact:
@@ -107,37 +113,39 @@ func NewFormat(t FormatType) Format {
// NewOpenMetricsFormat generates a new OpenMetrics format matching the
// specified version number.
//
// Note: OpenMetrics versions 2.0.0-rc and 2.0.0 are experimental (supporting
// counter, gauge, summary, untyped, histogram, and gaugehistogram metric types).
func NewOpenMetricsFormat(version string) (Format, error) {
if version == OpenMetricsVersion_0_0_1 {
switch version {
case OpenMetricsVersion_0_0_1:
return FmtOpenMetrics_0_0_1, nil
}
if version == OpenMetricsVersion_1_0_0 {
case OpenMetricsVersion_1_0_0:
return FmtOpenMetrics_1_0_0, nil
case OpenMetricsVersion_2_0_0_rc:
// OpenMetrics 2.0.0-rc is experimental.
return FmtOpenMetrics_2_0_0_rc, nil
case OpenMetricsVersion_2_0_0:
// OpenMetrics 2.0.0 is experimental.
return FmtOpenMetrics_2_0_0, nil
default:
return FmtUnknown, errors.New("unknown open metrics version string")
}
return FmtUnknown, errors.New("unknown open metrics version string")
}
// WithEscapingScheme returns a copy of Format with the specified escaping
// scheme appended to the end. If an escaping scheme already exists it is
// removed.
func (f Format) WithEscapingScheme(s model.EscapingScheme) Format {
var terms []string
for p := range strings.SplitSeq(string(f), ";") {
toks := strings.Split(p, "=")
if len(toks) != 2 {
trimmed := strings.TrimSpace(p)
if len(trimmed) > 0 {
terms = append(terms, trimmed)
}
continue
}
key := strings.TrimSpace(toks[0])
if key != model.EscapingKey {
terms = append(terms, strings.TrimSpace(p))
}
func isOpenMetrics20Version(v string) bool {
return v == OpenMetricsVersion_2_0_0 || v == OpenMetricsVersion_2_0_0_rc
}
// Version returns the version parameter without validating whether it is supported.
// It returns an empty string if the parameter is absent or the Content-Type
// cannot be parsed.
func (f Format) Version() string {
_, params, err := mime.ParseMediaType(string(f))
if err != nil {
return ""
}
terms = append(terms, model.EscapingKey+"="+s.String())
return Format(strings.Join(terms, "; "))
return params["version"]
}
// FormatType deduces an overall FormatType for the given format.
@@ -180,7 +188,7 @@ func (f Format) FormatType() FormatType {
if !ok {
return TypeTextPlain
}
if v == TextVersion {
if v == TextVersion || v == TextVersion_1_0_0 {
return TypeTextPlain
}
return TypeUnknown
@@ -189,8 +197,31 @@ func (f Format) FormatType() FormatType {
}
}
// ToEscapingScheme returns an EscapingScheme depending on the Format. Iff the
// Format contains a escaping=allow-utf-8 term, it will select NoEscaping. If a valid
// WithEscapingScheme returns a copy of Format with the specified escaping
// scheme appended to the end. If an escaping scheme already exists it is
// removed.
func (f Format) WithEscapingScheme(s model.EscapingScheme) Format {
var terms []string
for p := range strings.SplitSeq(string(f), ";") {
toks := strings.Split(p, "=")
if len(toks) != 2 {
trimmed := strings.TrimSpace(p)
if len(trimmed) > 0 {
terms = append(terms, trimmed)
}
continue
}
key := strings.TrimSpace(toks[0])
if key != model.EscapingKey {
terms = append(terms, strings.TrimSpace(p))
}
}
terms = append(terms, model.EscapingKey+"="+s.String())
return Format(strings.Join(terms, "; "))
}
// ToEscapingScheme returns an EscapingScheme depending on the Format. IFF the
// Format contains an escaping=allow-utf-8 term, it will select NoEscaping. If a valid
// "escaping" term exists, that will be used. Otherwise, the global default will
// be returned.
func (f Format) ToEscapingScheme() model.EscapingScheme {
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+4 -4
View File
@@ -194,6 +194,7 @@ func (p *TextParser) reset(in io.Reader) {
// start of a line (or whitespace leading up to it).
func (p *TextParser) startOfLine() stateFn {
p.lineCount++
p.currentMetric = nil
p.currentMetricIsInsideBraces = false
p.currentMetricInsideBracesIsPresent = false
if p.skipBlankTab(); p.err != nil {
@@ -339,12 +340,11 @@ func (p *TextParser) startLabelName() stateFn {
return nil // Unexpected end of input.
}
if p.currentByte == '}' {
if p.currentMF == nil {
if p.currentMetric == 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.
// startLabelValue. currentMetric is cleared at the start of each line.
p.parseError("invalid metric name")
p.currentLabelPairs = nil
return nil
@@ -495,7 +495,7 @@ func (p *TextParser) startLabelValue() stateFn {
return p.startLabelName
case '}':
if p.currentMF == nil {
if p.currentMetric == nil {
p.parseError("invalid metric name")
return nil
}
+5 -5
View File
@@ -14,7 +14,7 @@
package model
import (
"sort"
"slices"
)
// SeparatorByte is a byte that cannot occur in valid UTF-8 sequences and is
@@ -37,7 +37,7 @@ func LabelsToSignature(labels map[string]string) uint64 {
for labelName := range labels {
labelNames = append(labelNames, labelName)
}
sort.Strings(labelNames)
slices.Sort(labelNames)
sum := hashNew()
for _, labelName := range labelNames {
@@ -60,7 +60,7 @@ func labelSetToFingerprint(ls LabelSet) Fingerprint {
for labelName := range ls {
labelNames = append(labelNames, labelName)
}
sort.Sort(labelNames)
slices.Sort(labelNames)
sum := hashNew()
for _, labelName := range labelNames {
@@ -100,7 +100,7 @@ func SignatureForLabels(m Metric, labels ...LabelName) uint64 {
return emptyLabelSignature
}
sort.Sort(LabelNames(labels))
slices.Sort(labels)
sum := hashNew()
for _, label := range labels {
@@ -129,7 +129,7 @@ func SignatureWithoutLabels(m Metric, labels map[LabelName]struct{}) uint64 {
if len(labelNames) == 0 {
return emptyLabelSignature
}
sort.Sort(labelNames)
slices.Sort(labelNames)
sum := hashNew()
for _, labelName := range labelNames {
+28
View File
@@ -164,6 +164,34 @@ func (t *Time) UnmarshalJSON(b []byte) error {
// This type should not propagate beyond the scope of input/output processing.
type Duration time.Duration
// Common durations. Day and Week are included because ParseDuration supports
// those units (unlike the standard time package).
//
// To count the number of units in a Duration, divide:
//
// second := model.Second
// fmt.Print(int64(second/model.Millisecond)) // prints 1000
//
// To convert an integer number of units to a Duration, multiply:
//
// seconds := 10
// fmt.Print(model.Duration(seconds)*model.Second) // prints 10s
const (
Nanosecond Duration = 1
Microsecond = 1000 * Nanosecond
Millisecond = 1000 * Microsecond
Second = 1000 * Millisecond
Minute = 60 * Second
Hour = 60 * Minute
Day = 24 * Hour
Week = 7 * Day
)
// Milliseconds returns the duration as an integer millisecond count.
// Prometheus stores timestamps in milliseconds; time.Duration already
// covers the other units.
func (d Duration) Milliseconds() int64 { return time.Duration(d).Milliseconds() }
// Set implements pflag/flag.Value.
func (d *Duration) Set(s string) error {
var err error
-22
View File
@@ -224,28 +224,6 @@ func (ss SampleStream) MarshalJSON() ([]byte, error) {
}
}
func (ss *SampleStream) UnmarshalJSON(b []byte) error {
v := struct {
Metric Metric `json:"metric"`
Values []SamplePair `json:"values"`
Histograms []SampleHistogramPair `json:"histograms"`
}{
Metric: ss.Metric,
Values: ss.Values,
Histograms: ss.Histograms,
}
if err := json.Unmarshal(b, &v); err != nil {
return err
}
ss.Metric = v.Metric
ss.Values = v.Values
ss.Histograms = v.Histograms
return nil
}
// Scalar is a scalar value evaluated at the set timestamp.
type Scalar struct {
Value SampleValue `json:"value"`
+70
View File
@@ -0,0 +1,70 @@
// 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 go1.27
package model
import (
"bytes"
"encoding/json/jsontext"
"errors"
)
var nullBytes = []byte("null")
func (s *SamplePair) UnmarshalJSONFrom(dec *jsontext.Decoder) error {
if t, err := dec.ReadToken(); err != nil {
return err
} else if t.Kind() == jsontext.KindNull {
return nil
} else if t.Kind() != jsontext.KindBeginArray {
return errors.New("expected [")
}
// Loop until we see the end of the array (tolerate arrays of any length).
for i := 0; dec.PeekKind() != jsontext.KindEndArray; i++ {
switch i {
case 0:
if v, err := dec.ReadValue(); err != nil {
return err
} else if bytes.Equal(v, nullBytes) {
// Skip null values to match SamplePair#UnmarshalJSON behavior.
} else if err := s.Timestamp.UnmarshalJSON(v); err != nil {
return err
}
case 1:
if v, err := dec.ReadValue(); err != nil {
return err
} else if bytes.Equal(v, nullBytes) {
// Skip null values to match SamplePair#UnmarshalJSON behavior.
} else if err := s.Value.UnmarshalJSON(v); err != nil {
return err
}
default:
// Skip any remaining array items to match UnmarshalJSON behavior.
if err := dec.SkipValue(); err != nil {
return err
}
}
}
// Read the final end array token.
if t, err := dec.ReadToken(); err != nil {
return err
} else if t.Kind() != jsontext.KindEndArray {
return errors.New("expected ]")
}
return nil
}
+95
View File
@@ -0,0 +1,95 @@
// 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 go1.27
package model
import (
"bytes"
"encoding/json/jsontext"
"encoding/json/v2"
"errors"
)
func (s *SampleHistogramPair) UnmarshalJSONFrom(dec *jsontext.Decoder) error {
if t, err := dec.ReadToken(); err != nil {
return err
} else if t.Kind() != jsontext.KindBeginArray {
return errors.New("expected [")
}
if v, err := dec.ReadValue(); err != nil {
return err
} else if bytes.Equal(v, nullBytes) {
// Skip null values to match SamplePair#UnmarshalJSON behavior.
} else if err := s.Timestamp.UnmarshalJSON(v); err != nil {
return err
}
if err := json.UnmarshalDecode(dec, &s.Histogram); err != nil {
return err
} else if s.Histogram == nil {
return errors.New("histogram is nil")
}
if t, err := dec.ReadToken(); err != nil {
return err
} else if t.Kind() != jsontext.KindEndArray {
return errors.New("expected ]")
}
return nil
}
func (s *HistogramBucket) UnmarshalJSONFrom(dec *jsontext.Decoder) error {
if t, err := dec.ReadToken(); err != nil {
return err
} else if t.Kind() != jsontext.KindBeginArray {
return errors.New("expected [")
}
if err := json.UnmarshalDecode(dec, &s.Boundaries); err != nil {
return err
}
if v, err := dec.ReadValue(); err != nil {
return err
} else if bytes.Equal(v, nullBytes) {
// Skip null values to match SamplePair#UnmarshalJSON behavior.
} else if err := s.Lower.UnmarshalJSON(v); err != nil {
return err
}
if v, err := dec.ReadValue(); err != nil {
return err
} else if bytes.Equal(v, nullBytes) {
// Skip null values to match SamplePair#UnmarshalJSON behavior.
} else if err := s.Upper.UnmarshalJSON(v); err != nil {
return err
}
if v, err := dec.ReadValue(); err != nil {
return err
} else if bytes.Equal(v, nullBytes) {
// Skip null values to match SamplePair#UnmarshalJSON behavior.
} else if err := s.Count.UnmarshalJSON(v); err != nil {
return err
}
if t, err := dec.ReadToken(); err != nil {
return err
} else if t.Kind() != jsontext.KindEndArray {
return errors.New("expected ]")
}
return nil
}
+12 -9
View File
@@ -6,6 +6,8 @@ linters:
- gocritic
- godot
- misspell
- modernize
- perfsprint
- revive
- testifylint
settings:
@@ -34,14 +36,6 @@ 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:
presets:
- comments
@@ -51,9 +45,18 @@ linters:
warn-unused: true
formatters:
enable:
- gofmt
- gci
- gofumpt
- goimports
settings:
gci:
sections:
- standard
- default
- prefix(github.com/prometheus/procfs)
gofumpt:
extra:
group-params: true
goimports:
local-prefixes:
- github.com/prometheus/procfs
+4 -4
View File
@@ -96,7 +96,7 @@ The `proc` and `sys` filesystems are pseudo file systems and work a bit differen
Many of the files are changing continuously and the data being read can in some cases change between subsequent
reads in the same file. Also, most of the files are relatively small (less than a few KBs), and system calls
to the `stat` function will often return the wrong size. Therefore, for most files it's recommended to read the
full file in a single operation using an internal utility function called `util.ReadFileNoStat`.
full file in a single operation using an internal utility function called `parsers.ReadFileNoStat`.
This function is similar to `os.ReadFile`, but it avoids the system call to `stat` to get the current size of
the file.
@@ -104,7 +104,7 @@ Note that parsing the file's contents can still be performed one line at a time.
the full file, and then using a scanner on the `[]byte` or `string` containing the data.
```
data, err := util.ReadFileNoStat("/proc/cpuinfo")
data, err := parsers.ReadFileNoStat("/proc/cpuinfo")
if err != nil {
return err
}
@@ -113,9 +113,9 @@ the full file, and then using a scanner on the `[]byte` or `string` containing t
```
The `/sys` filesystem contains many very small files which contain only a single numeric or text value. These files
can be read using an internal function called `util.SysReadFile` which is similar to `os.ReadFile` but does
can be read using an internal function called `parsers.SysReadFile` which is similar to `os.ReadFile` but does
not bother to check the size of the file before reading.
```
data, err := util.SysReadFile("/sys/class/power_supply/BAT0/capacity")
data, err := parsers.SysReadFile("/sys/class/power_supply/BAT0/capacity")
```
+16 -2
View File
@@ -61,7 +61,7 @@ PROMU_URL := https://github.com/prometheus/promu/releases/download/v$(PROMU_
SKIP_GOLANGCI_LINT :=
GOLANGCI_LINT :=
GOLANGCI_LINT_OPTS ?=
GOLANGCI_LINT_VERSION ?= v2.11.4
GOLANGCI_LINT_VERSION ?= v2.14.0
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.
@@ -165,8 +165,9 @@ common-deps:
.PHONY: update-go-deps
update-go-deps:
@echo ">> updating Go dependencies"
# GOTOOLCHAIN prevents go get from pulling deps that require a newer Go version.
@for m in $$($(GO) list -mod=readonly -m -f '{{ if and (not .Indirect) (not .Main)}}{{.Path}}{{end}}' all); do \
$(GO) get $$m; \
GOTOOLCHAIN=go$$($(GO) mod edit -json | jq -r .Go) $(GO) get $$m; \
done
$(GO) mod tidy
@@ -246,6 +247,12 @@ common-docker-repo-name:
.PHONY: common-docker $(BUILD_DOCKER_ARCHS)
common-docker: $(BUILD_DOCKER_ARCHS)
.PHONY: common-docker-current-arch
common-docker-current-arch:
$(MAKE) common-docker-$(GOHOSTARCH)
# DOCKER_ARCHS holds promu architecture names, which are not OCI platform strings.
$(BUILD_DOCKER_ARCHS): common-docker-%:
@for variant in $(DOCKERFILE_VARIANTS_WITH_NAMES); do \
dockerfile=$${variant#*:}; \
@@ -254,10 +261,16 @@ $(BUILD_DOCKER_ARCHS): common-docker-%:
if [ "$*" = "armv7" ]; then \
distroless_arch="arm"; \
fi; \
arch="$*"; \
case "$$arch" in \
armv*) docker_platform="linux/arm/v$${arch#armv}";; \
*) docker_platform="linux/$$arch";; \
esac; \
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 \
--platform "$$docker_platform" \
--build-arg ARCH="$*" \
--build-arg OS="linux" \
--build-arg DISTROLESS_ARCH="$$distroless_arch" \
@@ -271,6 +284,7 @@ $(BUILD_DOCKER_ARCHS): common-docker-%:
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 \
--platform "$$docker_platform" \
--build-arg ARCH="$*" \
--build-arg OS="linux" \
--build-arg DISTROLESS_ARCH="$$distroless_arch" \
+2 -2
View File
@@ -16,12 +16,12 @@ package procfs
import (
"strings"
"github.com/prometheus/procfs/internal/util"
"github.com/prometheus/procfs/internal/parsers"
)
// CmdLine returns the command line of the kernel.
func (fs FS) CmdLine() ([]string, error) {
data, err := util.ReadFileNoStat(fs.proc.Path("cmdline"))
data, err := parsers.ReadFileNoStat(fs.proc.Path("cmdline"))
if err != nil {
return nil, err
}
+90 -8
View File
@@ -24,7 +24,7 @@ import (
"strconv"
"strings"
"github.com/prometheus/procfs/internal/util"
"github.com/prometheus/procfs/internal/parsers"
)
// CPUInfo contains general information about a system CPU found in /proc/cpuinfo.
@@ -65,7 +65,7 @@ var (
// CPUInfo returns information about current system CPUs.
// See https://www.kernel.org/doc/Documentation/filesystems/proc.txt
func (fs FS) CPUInfo() ([]CPUInfo, error) {
data, err := util.ReadFileNoStat(fs.proc.Path("cpuinfo"))
data, err := parsers.ReadFileNoStat(fs.proc.Path("cpuinfo"))
if err != nil {
return nil, err
}
@@ -187,6 +187,24 @@ func parseCPUInfoX86(info []byte) ([]CPUInfo, error) {
return cpuinfo, nil
}
func formatSteppingARM(variant, revision string) string {
if variant == "" && revision == "" {
return ""
}
varNum, errV := strconv.ParseUint(variant, 0, 64)
revNum, errR := strconv.ParseUint(revision, 0, 64)
if errV == nil && errR == nil {
return fmt.Sprintf("r%dp%d", varNum, revNum)
}
if errV == nil {
return fmt.Sprintf("r%d", varNum)
}
if errR == nil {
return fmt.Sprintf("p%d", revNum)
}
return fmt.Sprintf("r%sp%s", variant, revision)
}
func parseCPUInfoARM(info []byte) ([]CPUInfo, error) {
scanner := bufio.NewScanner(bytes.NewReader(info))
@@ -194,12 +212,13 @@ func parseCPUInfoARM(info []byte) ([]CPUInfo, error) {
match, err := regexp.MatchString("^[Pp]rocessor", firstLine)
if !match || !strings.Contains(firstLine, ":") {
return nil, fmt.Errorf("%w: Cannot parse line: %q: %w", ErrFileParse, firstLine, err)
}
field := strings.SplitN(firstLine, ": ", 2)
cpuinfo := []CPUInfo{}
featuresLine := ""
commonCPUInfo := CPUInfo{}
variants := make(map[int]string)
revisions := make(map[int]string)
i := 0
if strings.TrimSpace(field[0]) == "Processor" {
commonCPUInfo = CPUInfo{ModelName: field[1]}
@@ -219,6 +238,9 @@ func parseCPUInfoARM(info []byte) ([]CPUInfo, error) {
continue
}
field := strings.SplitN(line, ": ", 2)
if len(field) < 2 {
continue
}
switch strings.TrimSpace(field[0]) {
case "processor":
cpuinfo = append(cpuinfo, commonCPUInfo) // start of the next processor
@@ -242,15 +264,75 @@ func parseCPUInfoARM(info []byte) ([]CPUInfo, error) {
case "Features":
featuresLine = line
case "model name":
cpuinfo[i].ModelName = field[1]
if i == -1 {
commonCPUInfo.ModelName = field[1]
} else {
cpuinfo[i].ModelName = field[1]
}
case "CPU implementer", "cpu implementer":
val := strings.TrimSpace(field[1])
if i == -1 {
commonCPUInfo.VendorID = val
} else {
cpuinfo[i].VendorID = val
}
case "CPU architecture", "cpu architecture":
val := strings.TrimSpace(field[1])
if i == -1 {
commonCPUInfo.CPUFamily = val
} else {
cpuinfo[i].CPUFamily = val
}
case "CPU part", "cpu part":
val := strings.TrimSpace(field[1])
if i == -1 {
commonCPUInfo.Model = val
} else {
cpuinfo[i].Model = val
}
case "CPU variant", "cpu variant":
variants[i] = strings.TrimSpace(field[1])
case "CPU revision", "cpu revision":
revisions[i] = strings.TrimSpace(field[1])
}
}
fields := strings.SplitN(featuresLine, ": ", 2)
for i := range cpuinfo {
cpuinfo[i].Flags = strings.Fields(fields[1])
for j := range cpuinfo {
stepping := formatSteppingARM(variants[j], revisions[j])
if stepping == "" {
stepping = formatSteppingARM(variants[-1], revisions[-1])
}
cpuinfo[j].Stepping = stepping
}
if len(cpuinfo) > 0 && cpuinfo[0].VendorID == "" && cpuinfo[len(cpuinfo)-1].VendorID != "" {
last := cpuinfo[len(cpuinfo)-1]
for j := range cpuinfo {
if cpuinfo[j].VendorID == "" {
cpuinfo[j].VendorID = last.VendorID
}
if cpuinfo[j].CPUFamily == "" {
cpuinfo[j].CPUFamily = last.CPUFamily
}
if cpuinfo[j].Model == "" {
cpuinfo[j].Model = last.Model
}
if cpuinfo[j].Stepping == "" {
cpuinfo[j].Stepping = last.Stepping
}
}
}
if featuresLine != "" {
fields := strings.SplitN(featuresLine, ": ", 2)
if len(fields) > 1 {
flags := strings.Fields(fields[1])
for i := range cpuinfo {
cpuinfo[i].Flags = flags
}
}
}
return cpuinfo, nil
}
func parseCPUInfoS390X(info []byte) ([]CPUInfo, error) {
+3 -4
View File
@@ -20,7 +20,7 @@ import (
"io"
"strings"
"github.com/prometheus/procfs/internal/util"
"github.com/prometheus/procfs/internal/parsers"
)
// Crypto holds info parsed from /proc/crypto.
@@ -55,10 +55,9 @@ var cryptoFile = "crypto"
// https://kernel.readthedocs.io/en/sphinx-samples/crypto-API.html
func (fs FS) Crypto() ([]Crypto, error) {
path := fs.proc.Path(cryptoFile)
b, err := util.ReadFileNoStat(path)
b, err := parsers.ReadFileNoStat(path)
if err != nil {
return nil, fmt.Errorf("%w: Cannot read file %v: %w", ErrFileRead, b, err)
}
crypto, err := parseCrypto(bytes.NewReader(b))
@@ -112,7 +111,7 @@ func parseCrypto(r io.Reader) ([]Crypto, error) {
// parseKV parses a key/value pair into the appropriate field of c.
func (c *Crypto) parseKV(k, v string) error {
vp := util.NewValueParser(v)
vp := parsers.NewValueParser(v)
switch k {
case "async":
+2 -2
View File
@@ -15,8 +15,8 @@
package procfs
// isRealProc returns true on architectures that don't have a Type argument
// isRealProc returns false on architectures that don't have a Type argument
// in their Statfs_t struct.
func isRealProc(_ string) (bool, error) {
return true, nil
return false, nil
}
+2 -2
View File
@@ -21,7 +21,7 @@ import (
"strconv"
"strings"
"github.com/prometheus/procfs/internal/util"
"github.com/prometheus/procfs/internal/parsers"
)
// Fscacheinfo represents fscache statistics.
@@ -229,7 +229,7 @@ type Fscacheinfo struct {
// Fscacheinfo returns information about current fscache statistics.
// See https://www.kernel.org/doc/Documentation/filesystems/caching/fscache.txt
func (fs FS) Fscacheinfo() (Fscacheinfo, error) {
b, err := util.ReadFileNoStat(fs.proc.Path("fs/fscache/stats"))
b, err := parsers.ReadFileNoStat(fs.proc.Path("fs/fscache/stats"))
if err != nil {
return Fscacheinfo{}, err
}
+3
View File
@@ -31,6 +31,9 @@ const (
// DefaultSelinuxMountPoint is the common mount point of the selinuxfs.
DefaultSelinuxMountPoint = "/sys/fs/selinux"
// DefaultResctrlMountPoint is the common mount point of the resctrl filesystem.
DefaultResctrlMountPoint = "/sys/fs/resctrl"
)
// FS represents a pseudo-filesystem, normally /proc or /sys, which provides an
@@ -11,7 +11,7 @@
// See the License for the specific language governing permissions and
// limitations under the License.
package util
package parsers
import (
"errors"
@@ -11,7 +11,7 @@
// See the License for the specific language governing permissions and
// limitations under the License.
package util
package parsers
import (
"io"
@@ -13,7 +13,7 @@
//go:build (linux || darwin) && !appengine
package util
package parsers
import (
"bytes"
@@ -13,7 +13,7 @@
//go:build (linux && appengine) || (!linux && !darwin)
package util
package parsers
import (
"fmt"
@@ -11,7 +11,7 @@
// See the License for the specific language governing permissions and
// limitations under the License.
package util
package parsers
import (
"strconv"
+5 -2
View File
@@ -25,7 +25,7 @@ import (
"strconv"
"strings"
"github.com/prometheus/procfs/internal/util"
"github.com/prometheus/procfs/internal/parsers"
)
// IPVSStats holds IPVS statistics, as exposed by the kernel in `/proc/net/ip_vs_stats`.
@@ -66,7 +66,7 @@ type IPVSBackendStatus struct {
// IPVSStats reads the IPVS statistics from the specified `proc` filesystem.
func (fs FS) IPVSStats() (IPVSStats, error) {
data, err := util.ReadFileNoStat(fs.proc.Path("net/ip_vs_stats"))
data, err := parsers.ReadFileNoStat(fs.proc.Path("net/ip_vs_stats"))
if err != nil {
return IPVSStats{}, err
}
@@ -149,6 +149,9 @@ func parseIPVSBackendStatus(file io.Reader) ([]IPVSBackendStatus, error) {
if len(fields) == 0 {
continue
}
if len(fields) < 2 {
return nil, fmt.Errorf("%w: Malformed line %q", ErrFileParse, scanner.Text())
}
switch {
case fields[0] == "IP" || fields[0] == "Prot" || fields[1] == "RemoteAddress:Port":
continue
+2 -2
View File
@@ -18,7 +18,7 @@ package procfs
import (
"os"
"github.com/prometheus/procfs/internal/util"
"github.com/prometheus/procfs/internal/parsers"
)
// KernelRandom contains information about to the kernel's random number generator.
@@ -48,7 +48,7 @@ func (fs FS) KernelRandom() (KernelRandom, error) {
"write_wakeup_threshold": &random.WriteWakeupThreshold,
"read_wakeup_threshold": &random.ReadWakeupThreshold,
} {
val, err := util.ReadUintFromFile(fs.proc.Path("sys", "kernel", "random", file))
val, err := parsers.ReadUintFromFile(fs.proc.Path("sys", "kernel", "random", file))
if os.IsNotExist(err) {
continue
}
+95
View File
@@ -0,0 +1,95 @@
// 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 linux
package procfs
import (
"github.com/prometheus/procfs/internal/parsers"
)
// KernelTaintBit represents a single kernel taint flag.
type KernelTaintBit struct {
// Index is the zero-based bit position in the tainted bitmask.
Index int
// Flag is the letter code identifying this taint (e.g. "L" for soft lockup).
// See https://www.kernel.org/doc/html/latest/admin-guide/tainted-kernels.html
Flag string
// Description is a human-readable explanation of what this taint means.
Description string
// Set indicates whether this taint flag is currently active.
Set bool
}
// KernelTainted holds the kernel taint state read from /proc/sys/kernel/tainted.
type KernelTainted struct {
// Value is the raw integer from /proc/sys/kernel/tainted.
Value uint64
// Bits contains each known taint flag and whether it is currently set.
// Flags are listed in bit-position order (bit 0 first).
Bits []KernelTaintBit
}
// kernelTaintBitDefs lists all known kernel taint flags in bit-position order.
// Reference: https://www.kernel.org/doc/html/latest/admin-guide/tainted-kernels.html
var kernelTaintBitDefs = []struct {
flag string
description string
}{
{"P", "Proprietary module was loaded."},
{"F", "Module was force loaded."},
{"S", "SMP kernel oops on an officially SMP incapable processor."},
{"R", "Module was force unloaded."},
{"M", "Processor reported a Machine Check Exception (MCE)."},
{"B", "Bad page referenced or some unexpected page flags."},
{"U", "Taint requested by userspace application."},
{"D", "Kernel died recently, i.e. there was an OOPS or BUG."},
{"A", "An ACPI table was overridden by user."},
{"W", "Kernel issued warning."},
{"C", "Staging driver was loaded."},
{"I", "Workaround for bug in platform firmware applied."},
{"O", "Externally-built (out-of-tree) module was loaded."},
{"E", "Unsigned module was loaded."},
{"L", "Soft lockup occurred."},
{"K", "Kernel has been live patched."},
{"X", "Auxiliary taint, defined and used by distros."},
{"T", "The kernel was built with the struct randomization plugin."},
{"N", "An in-kernel test such as a KUnit test has been run."},
{"J", "Userspace used a mutating debug operation in fwctl."},
}
// KernelTainted reads /proc/sys/kernel/tainted and returns the raw taint value
// along with each known flag parsed into a KernelTainted struct.
// See https://www.kernel.org/doc/html/latest/admin-guide/tainted-kernels.html
func (fs FS) KernelTainted() (KernelTainted, error) {
value, err := parsers.SysReadUintFromFile(fs.proc.Path("sys", "kernel", "tainted"))
if err != nil {
return KernelTainted{}, err
}
return parseTainted(value), nil
}
// parseTainted builds a KernelTainted from the raw taint bitmask value.
func parseTainted(value uint64) KernelTainted {
bits := make([]KernelTaintBit, len(kernelTaintBitDefs))
for i, def := range kernelTaintBitDefs {
bits[i] = KernelTaintBit{
Index: i,
Flag: def.flag,
Description: def.description,
Set: value&(1<<uint(i)) != 0,
}
}
return KernelTainted{Value: value, Bits: bits}
}
+2 -2
View File
@@ -18,7 +18,7 @@ import (
"strconv"
"strings"
"github.com/prometheus/procfs/internal/util"
"github.com/prometheus/procfs/internal/parsers"
)
// LoadAvg represents an entry in /proc/loadavg.
@@ -32,7 +32,7 @@ type LoadAvg struct {
func (fs FS) LoadAvg() (*LoadAvg, error) {
path := fs.proc.Path("loadavg")
data, err := util.ReadFileNoStat(path)
data, err := parsers.ReadFileNoStat(path)
if err != nil {
return nil, err
}
+3 -5
View File
@@ -27,7 +27,7 @@ var (
recoveryLinePctRE = regexp.MustCompile(`= (.+)%`)
recoveryLineFinishRE = regexp.MustCompile(`finish=(.+)min`)
recoveryLineSpeedRE = regexp.MustCompile(`speed=(.+)[A-Z]`)
componentDeviceRE = regexp.MustCompile(`(.*)\[(\d+)\](\([SF]+\))?`)
componentDeviceRE = regexp.MustCompile(`(.*)\[(\d+)\]((?:\([FJRSW]\))+)?`)
personalitiesPrefix = "Personalities : "
)
@@ -114,8 +114,7 @@ func parseMDStat(mdStatData []byte) ([]MDStat, error) {
}
// 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 {
for word := range strings.FieldsSeq(line[len(personalitiesPrefix):]) {
word := word[1 : len(word)-1]
knownRaidTypes[word] = true
}
@@ -150,7 +149,6 @@ func parseMDStat(mdStatData []byte) ([]MDStat, error) {
fail := int64(strings.Count(line, "(F)"))
spare := int64(strings.Count(line, "(S)"))
active, total, down, size, err := evalStatusLine(lines[i], lines[i+1])
if err != nil {
return nil, fmt.Errorf("%w: Cannot parse md device lines: %v: %w", ErrFileParse, active, err)
}
@@ -275,7 +273,7 @@ func evalStatusLine(deviceLine, statusLine string) (active, total, down, size in
return active, total, down, size, nil
}
func evalRecoveryLine(recoveryLine string) (blocksSynced int64, blocksToBeSynced int64, pct float64, finish float64, speed float64, err error) {
func evalRecoveryLine(recoveryLine string) (blocksSynced, blocksToBeSynced int64, pct, finish, speed float64, err error) {
matches := recoveryLineBlocksRE.FindStringSubmatch(recoveryLine)
if len(matches) != 2 {
return 0, 0, 0, 0, 0, fmt.Errorf("%w: Unexpected recoveryLine blocks %s: %w", ErrFileParse, recoveryLine, err)
+5 -2
View File
@@ -21,7 +21,7 @@ import (
"strconv"
"strings"
"github.com/prometheus/procfs/internal/util"
"github.com/prometheus/procfs/internal/parsers"
)
// Meminfo represents memory statistics.
@@ -210,7 +210,7 @@ type Meminfo struct {
// Meminfo returns an information about current kernel/system memory statistics.
// See https://www.kernel.org/doc/Documentation/filesystems/proc.txt
func (fs FS) Meminfo() (Meminfo, error) {
b, err := util.ReadFileNoStat(fs.proc.Path("meminfo"))
b, err := parsers.ReadFileNoStat(fs.proc.Path("meminfo"))
if err != nil {
return Meminfo{}, err
}
@@ -228,6 +228,9 @@ func parseMemInfo(r io.Reader) (*Meminfo, error) {
s := bufio.NewScanner(r)
for s.Scan() {
fields := strings.Fields(s.Text())
if len(fields) < 2 || len(fields) > 3 {
return nil, fmt.Errorf("%w: Malformed line %q", ErrFileParse, s.Text())
}
var val, valBytes uint64
val, err := strconv.ParseUint(fields[1], 0, 64)
+27 -20
View File
@@ -72,17 +72,18 @@ func parseMountInfo(info []byte) ([]*MountInfo, error) {
// Parses a mountinfo file line, and converts it to a MountInfo struct.
// An important check here is to see if the hyphen separator, as if it does not exist,
// it means that the line is malformed.
// See: https://man7.org/linux/man-pages/man5/proc_pid_mountinfo.5.html
func parseMountInfoString(mountString string) (*MountInfo, error) {
var err error
mountInfo := strings.Split(mountString, " ")
mountInfoLength := len(mountInfo)
if mountInfoLength < 10 {
return nil, fmt.Errorf("%w: Too few fields in mount string: %s", ErrFileParse, mountString)
fields := strings.Split(mountString, " - ")
if len(fields) != 2 {
return nil, fmt.Errorf("%w: Could not split hyphen separator: %s", ErrFileParse, mountString)
}
if mountInfo[mountInfoLength-4] != "-" {
return nil, fmt.Errorf("%w: couldn't find separator in expected field: %s", ErrFileParse, mountInfo[mountInfoLength-4])
mountInfo := strings.Split(fields[0], " ")
if len(mountInfo) < 6 {
return nil, fmt.Errorf("%w: Too few fields in mount string: %s", ErrFileParse, mountString)
}
mount := &MountInfo{
@@ -90,28 +91,36 @@ func parseMountInfoString(mountString string) (*MountInfo, error) {
Root: mountInfo[3],
MountPoint: mountInfo[4],
Options: mountOptionsParser(mountInfo[5]),
OptionalFields: nil,
FSType: mountInfo[mountInfoLength-3],
Source: mountInfo[mountInfoLength-2],
SuperOptions: mountOptionsParser(mountInfo[mountInfoLength-1]),
OptionalFields: map[string]string{},
}
mount.MountID, err = strconv.Atoi(mountInfo[0])
if err != nil {
return nil, fmt.Errorf("%w: mount ID: %q", ErrFileParse, mount.MountID)
return nil, fmt.Errorf("%w: mount ID: %q", ErrFileParse, mountInfo[0])
}
mount.ParentID, err = strconv.Atoi(mountInfo[1])
if err != nil {
return nil, fmt.Errorf("%w: parent ID: %q", ErrFileParse, mount.ParentID)
return nil, fmt.Errorf("%w: parent ID: %q", ErrFileParse, mountInfo[1])
}
// Has optional fields, which is a space separated list of values.
// Example: shared:2 master:7
if mountInfo[6] != "" {
mount.OptionalFields, err = mountOptionsParseOptionalFields(mountInfo[6 : mountInfoLength-4])
if len(mountInfo) > 6 {
mount.OptionalFields, err = mountOptionsParseOptionalFields(mountInfo[6:])
if err != nil {
return nil, fmt.Errorf("%w: %w", ErrFileParse, err)
}
}
mountInfo = strings.SplitN(fields[1], " ", 3)
if len(mountInfo) != 3 {
return nil, fmt.Errorf("%w: Too few fields after separator: %s", ErrFileParse, mountString)
}
mount.FSType = mountInfo[0]
mount.Source = mountInfo[1]
mount.SuperOptions = mountOptionsParser(mountInfo[2])
return mount, nil
}
@@ -148,19 +157,17 @@ func mountOptionsParseOptionalFields(o []string) (map[string]string, error) {
func mountOptionsParser(mountOptions string) map[string]string {
opts := make(map[string]string)
for opt := range strings.SplitSeq(mountOptions, ",") {
splitOption := strings.Split(opt, "=")
splitOption := strings.SplitN(opt, "=", 2)
if len(splitOption) < 2 {
key := splitOption[0]
opts[key] = ""
opts[splitOption[0]] = ""
} else {
key, value := splitOption[0], splitOption[1]
opts[key] = value
opts[splitOption[0]] = splitOption[1]
}
}
return opts
}
// readMountInfo reads a full mountinfo file (no 1 MiB cap, unlike util.ReadFileNoStat).
// readMountInfo reads a full mountinfo file (no 1 MiB cap, unlike parsers.ReadFileNoStat).
func readMountInfo(path string) ([]byte, error) {
f, err := os.Open(path)
if err != nil {
+3 -3
View File
@@ -20,7 +20,7 @@ import (
"io"
"strings"
"github.com/prometheus/procfs/internal/util"
"github.com/prometheus/procfs/internal/parsers"
)
// A ConntrackStatEntry represents one line from net/stat/nf_conntrack
@@ -49,7 +49,7 @@ func (fs FS) ConntrackStat() ([]ConntrackStatEntry, error) {
// Parses a slice of ConntrackStatEntries from the given filepath.
func readConntrackStat(path string) ([]ConntrackStatEntry, error) {
// This file is small and can be read with one syscall.
b, err := util.ReadFileNoStat(path)
b, err := parsers.ReadFileNoStat(path)
if err != nil {
// Do not wrap this error so the caller can detect os.IsNotExist and
// similar conditions.
@@ -84,7 +84,7 @@ func parseConntrackStat(r io.Reader) ([]ConntrackStatEntry, error) {
// Parses a ConntrackStatEntry from given array of fields.
func parseConntrackStatEntry(fields []string) (*ConntrackStatEntry, error) {
entries, err := util.ParseHexUint64s(fields)
entries, err := parsers.ParseHexUint64s(fields)
if err != nil {
return nil, fmt.Errorf("%w: Cannot parse entry: %d: %w", ErrFileParse, entries, err)
}
+9 -9
View File
@@ -178,7 +178,7 @@ func parseNetIPSocketLine(fields []string, isUDP bool) (*netIPSocketLine, error)
}
if line.Sl, err = strconv.ParseUint(s[0], 0, 64); err != nil {
return nil, fmt.Errorf("%w: Unable to parse sl field in %q: %w", ErrFileParse, line.Sl, err)
return nil, fmt.Errorf("%w: Unable to parse sl field in %q: %w", ErrFileParse, s[0], err)
}
// local_address
l := strings.Split(fields[1], ":")
@@ -189,7 +189,7 @@ func parseNetIPSocketLine(fields []string, isUDP bool) (*netIPSocketLine, error)
return nil, err
}
if line.LocalPort, err = strconv.ParseUint(l[1], 16, 64); err != nil {
return nil, fmt.Errorf("%w: Unable to parse local_address port value line %q: %w", ErrFileParse, line.LocalPort, err)
return nil, fmt.Errorf("%w: Unable to parse local_address port value line %q: %w", ErrFileParse, l[1], err)
}
// remote_address
@@ -201,12 +201,12 @@ func parseNetIPSocketLine(fields []string, isUDP bool) (*netIPSocketLine, error)
return nil, err
}
if line.RemPort, err = strconv.ParseUint(r[1], 16, 64); err != nil {
return nil, fmt.Errorf("%w: Cannot parse rem_address port value in %q: %w", ErrFileParse, line.RemPort, err)
return nil, fmt.Errorf("%w: Cannot parse rem_address port value in %q: %w", ErrFileParse, r[1], err)
}
// st
if line.St, err = strconv.ParseUint(fields[3], 16, 64); err != nil {
return nil, fmt.Errorf("%w: Cannot parse st value in %q: %w", ErrFileParse, line.St, err)
return nil, fmt.Errorf("%w: Cannot parse st value in %q: %w", ErrFileParse, fields[3], err)
}
// tx_queue and rx_queue
@@ -219,27 +219,27 @@ func parseNetIPSocketLine(fields []string, isUDP bool) (*netIPSocketLine, error)
)
}
if line.TxQueue, err = strconv.ParseUint(q[0], 16, 64); err != nil {
return nil, fmt.Errorf("%w: Cannot parse tx_queue value in %q: %w", ErrFileParse, line.TxQueue, err)
return nil, fmt.Errorf("%w: Cannot parse tx_queue value in %q: %w", ErrFileParse, q[0], err)
}
if line.RxQueue, err = strconv.ParseUint(q[1], 16, 64); err != nil {
return nil, fmt.Errorf("%w: Cannot parse trx_queue value in %q: %w", ErrFileParse, line.RxQueue, err)
return nil, fmt.Errorf("%w: Cannot parse trx_queue value in %q: %w", ErrFileParse, q[1], err)
}
// uid
if line.UID, err = strconv.ParseUint(fields[7], 0, 64); err != nil {
return nil, fmt.Errorf("%w: Cannot parse UID value in %q: %w", ErrFileParse, line.UID, err)
return nil, fmt.Errorf("%w: Cannot parse UID value in %q: %w", ErrFileParse, fields[7], err)
}
// inode
if line.Inode, err = strconv.ParseUint(fields[9], 0, 64); err != nil {
return nil, fmt.Errorf("%w: Cannot parse inode value in %q: %w", ErrFileParse, line.Inode, err)
return nil, fmt.Errorf("%w: Cannot parse inode value in %q: %w", ErrFileParse, fields[9], err)
}
// drops
if isUDP {
drops, err := strconv.ParseUint(fields[12], 0, 64)
if err != nil {
return nil, fmt.Errorf("%w: Cannot parse drops value in %q: %w", ErrFileParse, drops, err)
return nil, fmt.Errorf("%w: Cannot parse drops value in %q: %w", ErrFileParse, fields[12], err)
}
line.Drops = &drops
}
+2 -2
View File
@@ -20,7 +20,7 @@ import (
"strconv"
"strings"
"github.com/prometheus/procfs/internal/util"
"github.com/prometheus/procfs/internal/parsers"
)
// NetProtocolStats stores the contents from /proc/net/protocols.
@@ -71,7 +71,7 @@ type NetProtocolCapabilities struct {
// Linux 2.6.12-rc2 - https://elixir.bootlin.com/linux/v2.6.12-rc2/source/net/core/sock.c#L1452
// Linux 5.10 - https://elixir.bootlin.com/linux/v5.10.4/source/net/core/sock.c#L3586
func (fs FS) NetProtocols() (NetProtocolStats, error) {
data, err := util.ReadFileNoStat(fs.proc.Path("net/protocols"))
data, err := parsers.ReadFileNoStat(fs.proc.Path("net/protocols"))
if err != nil {
return NetProtocolStats{}, err
}
+2 -2
View File
@@ -21,7 +21,7 @@ import (
"strconv"
"strings"
"github.com/prometheus/procfs/internal/util"
"github.com/prometheus/procfs/internal/parsers"
)
const (
@@ -50,7 +50,7 @@ func (fs FS) NetRoute() ([]NetRouteLine, error) {
}
func readNetRoute(path string) ([]NetRouteLine, error) {
b, err := util.ReadFileNoStat(path)
b, err := parsers.ReadFileNoStat(path)
if err != nil {
return nil, err
}
+3 -3
View File
@@ -20,7 +20,7 @@ import (
"io"
"strings"
"github.com/prometheus/procfs/internal/util"
"github.com/prometheus/procfs/internal/parsers"
)
// A NetSockstat contains the output of /proc/net/sockstat{,6} for IPv4 or IPv6,
@@ -60,7 +60,7 @@ func (fs FS) NetSockstat6() (*NetSockstat, error) {
// readSockstat opens and parses a NetSockstat from the input file.
func readSockstat(name string) (*NetSockstat, error) {
// This file is small and can be read with one syscall.
b, err := util.ReadFileNoStat(name)
b, err := parsers.ReadFileNoStat(name)
if err != nil {
// Do not wrap this error so the caller can detect os.IsNotExist and
// similar conditions.
@@ -124,7 +124,7 @@ func parseSockstatKVs(kvs []string) (map[string]int, error) {
// Iterate two values at a time to gather key/value pairs.
out := make(map[string]int, len(kvs)/2)
for i := 0; i < len(kvs); i += 2 {
vp := util.NewValueParser(kvs[i+1])
vp := parsers.NewValueParser(kvs[i+1])
out[kvs[i]] = vp.Int()
if err := vp.Err(); err != nil {
+2 -2
View File
@@ -21,7 +21,7 @@ import (
"strconv"
"strings"
"github.com/prometheus/procfs/internal/util"
"github.com/prometheus/procfs/internal/parsers"
)
// For the proc file format details,
@@ -57,7 +57,7 @@ var softNetProcFile = "net/softnet_stat"
// NetSoftnetStat reads data from /proc/net/softnet_stat.
func (fs FS) NetSoftnetStat() ([]SoftnetStat, error) {
b, err := util.ReadFileNoStat(fs.proc.Path(softNetProcFile))
b, err := parsers.ReadFileNoStat(fs.proc.Path(softNetProcFile))
if err != nil {
return nil, err
}
+2 -2
View File
@@ -32,9 +32,9 @@ type TLSStat struct {
TLSCurrTxDevice int
// number of RX sessions currently installed where NIC handles cryptography
TLSCurrRxDevice int
//number of TX sessions opened with host cryptography
// number of TX sessions opened with host cryptography
TLSTxSw int
//number of RX sessions opened with host cryptography
// number of RX sessions opened with host cryptography
TLSRxSw int
// number of TX sessions opened with NIC cryptography
TLSTxDevice int
+2 -2
View File
@@ -21,7 +21,7 @@ import (
"strconv"
"strings"
"github.com/prometheus/procfs/internal/util"
"github.com/prometheus/procfs/internal/parsers"
)
// Wireless models the content of /proc/net/wireless.
@@ -61,7 +61,7 @@ type Wireless struct {
// Wireless returns kernel wireless statistics.
func (fs FS) Wireless() ([]*Wireless, error) {
b, err := util.ReadFileNoStat(fs.proc.Path("net/wireless"))
b, err := parsers.ReadFileNoStat(fs.proc.Path("net/wireless"))
if err != nil {
return nil, err
}
+10 -1
View File
@@ -61,7 +61,12 @@ func parseNetstat(filePath string) (NetStat, error) {
defer file.Close()
scanner := bufio.NewScanner(file)
scanner.Scan()
if !scanner.Scan() {
if err := scanner.Err(); err != nil {
return NetStat{}, err
}
return netStat, nil
}
// First string is always a header for stats
var headers []string
@@ -78,5 +83,9 @@ func parseNetstat(filePath string) (NetStat, error) {
}
}
if err := scanner.Err(); err != nil {
return NetStat{}, err
}
return netStat, nil
}
+2 -2
View File
@@ -18,7 +18,7 @@ import (
"bytes"
"fmt"
"github.com/prometheus/procfs/internal/util"
"github.com/prometheus/procfs/internal/parsers"
)
const nfNetLinkQueueFormat = "%d %d %d %d %d %d %d %d %d"
@@ -48,7 +48,7 @@ type NFNetLinkQueue struct {
// 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"))
data, err := parsers.ReadFileNoStat(fs.proc.Path("net/netfilter/nfnetlink_queue"))
if err != nil {
return nil, err
}
+4 -4
View File
@@ -22,7 +22,7 @@ import (
"strconv"
"strings"
"github.com/prometheus/procfs/internal/util"
"github.com/prometheus/procfs/internal/parsers"
)
// Proc provides information about a running process.
@@ -128,7 +128,7 @@ func (fs FS) AllProcs() (Procs, error) {
// CmdLine returns the command line of a process.
func (p Proc) CmdLine() ([]string, error) {
data, err := util.ReadFileNoStat(p.path("cmdline"))
data, err := parsers.ReadFileNoStat(p.path("cmdline"))
if err != nil {
return nil, err
}
@@ -163,7 +163,7 @@ func (p Proc) Wchan() (string, error) {
// Comm returns the command name of a process.
func (p Proc) Comm() (string, error) {
data, err := util.ReadFileNoStat(p.path("comm"))
data, err := parsers.ReadFileNoStat(p.path("comm"))
if err != nil {
return "", err
}
@@ -281,7 +281,7 @@ func (p Proc) MountStats() ([]*Mount, error) {
// It supplies information missing in `/proc/self/mounts` and
// fixes various other problems with that file too.
func (p Proc) MountInfo() ([]*MountInfo, error) {
data, err := util.ReadFileNoStat(p.path("mountinfo"))
data, err := parsers.ReadFileNoStat(p.path("mountinfo"))
if err != nil {
return nil, err
}
+2 -2
View File
@@ -20,7 +20,7 @@ import (
"strconv"
"strings"
"github.com/prometheus/procfs/internal/util"
"github.com/prometheus/procfs/internal/parsers"
)
// Cgroup models one line from /proc/[pid]/cgroup. Each Cgroup struct describes the placement of a PID inside a
@@ -90,7 +90,7 @@ func parseCgroups(data []byte) ([]Cgroup, error) {
// control hierarchy running on this system. On every system (v1 and v2), all hierarchies contain all processes,
// so the len of the returned struct is equal to the number of active hierarchies on this system.
func (p Proc) Cgroups() ([]Cgroup, error) {
data, err := util.ReadFileNoStat(p.path("cgroup"))
data, err := parsers.ReadFileNoStat(p.path("cgroup"))
if err != nil {
return nil, err
}
+2 -2
View File
@@ -20,7 +20,7 @@ import (
"strconv"
"strings"
"github.com/prometheus/procfs/internal/util"
"github.com/prometheus/procfs/internal/parsers"
)
// CgroupSummary models one line from /proc/cgroups.
@@ -90,7 +90,7 @@ func parseCgroupSummary(data []byte) ([]CgroupSummary, error) {
// CgroupSummarys returns information about current /proc/cgroups.
func (fs FS) CgroupSummarys() ([]CgroupSummary, error) {
data, err := util.ReadFileNoStat(fs.proc.Path("cgroups"))
data, err := parsers.ReadFileNoStat(fs.proc.Path("cgroups"))
if err != nil {
return nil, err
}
+3 -3
View File
@@ -16,20 +16,20 @@ package procfs
import (
"strings"
"github.com/prometheus/procfs/internal/util"
"github.com/prometheus/procfs/internal/parsers"
)
// Environ reads process environments from `/proc/<pid>/environ`.
func (p Proc) Environ() ([]string, error) {
environments := make([]string, 0)
data, err := util.ReadFileNoStat(p.path("environ"))
data, err := parsers.ReadFileNoStat(p.path("environ"))
if err != nil {
return environments, err
}
environments = strings.Split(string(data), "\000")
if len(environments) > 0 {
if environments[len(environments)-1] == "" {
environments = environments[:len(environments)-1]
}
+2 -2
View File
@@ -19,7 +19,7 @@ import (
"fmt"
"regexp"
"github.com/prometheus/procfs/internal/util"
"github.com/prometheus/procfs/internal/parsers"
)
var (
@@ -49,7 +49,7 @@ type ProcFDInfo struct {
// FDInfo constructor. On kernels older than 3.8, InotifyInfos will always be empty.
func (p Proc) FDInfo(fd string) (*ProcFDInfo, error) {
data, err := util.ReadFileNoStat(p.path("fdinfo", fd))
data, err := parsers.ReadFileNoStat(p.path("fdinfo", fd))
if err != nil {
return nil, err
}
+2 -2
View File
@@ -22,7 +22,7 @@ import (
"strconv"
"strings"
"github.com/prometheus/procfs/internal/util"
"github.com/prometheus/procfs/internal/parsers"
)
// Interrupt represents a single interrupt line.
@@ -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.fs.proc.Path("interrupts"))
data, err := parsers.ReadFileNoStat(p.fs.proc.Path("interrupts"))
if err != nil {
return nil, err
}
+2 -2
View File
@@ -16,7 +16,7 @@ package procfs
import (
"fmt"
"github.com/prometheus/procfs/internal/util"
"github.com/prometheus/procfs/internal/parsers"
)
// ProcIO models the content of /proc/<pid>/io.
@@ -43,7 +43,7 @@ type ProcIO struct {
func (p Proc) IO() (ProcIO, error) {
pio := ProcIO{}
data, err := util.ReadFileNoStat(p.path("io"))
data, err := parsers.ReadFileNoStat(p.path("io"))
if err != nil {
return pio, err
}
+1 -4
View File
@@ -74,9 +74,7 @@ const (
limitsUnlimited = "unlimited"
)
var (
limitsMatch = regexp.MustCompile(`(Max \w+\s??\w*\s?\w*)\s{2,}(\w+)\s+(\w+)`)
)
var limitsMatch = regexp.MustCompile(`(Max \w+\s??\w*\s?\w*)\s{2,}(\w+)\s+(\w+)`)
// NewLimits returns the current soft limits of the process.
//
@@ -101,7 +99,6 @@ func (p Proc) Limits() (ProcLimits, error) {
s.Scan() // Skip limits header
for s.Scan() {
//fields := limitsMatch.Split(s.Text(), limitsFields)
fields := limitsMatch.FindStringSubmatch(s.Text())
if len(fields) != limitsFields {
return ProcLimits{}, fmt.Errorf("%w: couldn't parse %q line %q", ErrFileParse, f.Name(), s.Text())
+8 -8
View File
@@ -61,17 +61,17 @@ type ProcMap struct {
// parseDevice parses the device token of a line and converts it to a dev_t
// (mkdev) like structure.
func parseDevice(s string) (uint64, error) {
i := strings.Index(s, ":")
if i == -1 {
before, after, ok := strings.Cut(s, ":")
if !ok {
return 0, fmt.Errorf("%w: expected separator `:` in %s", ErrFileParse, s)
}
major, err := strconv.ParseUint(s[0:i], 16, 0)
major, err := strconv.ParseUint(before, 16, 0)
if err != nil {
return 0, err
}
minor, err := strconv.ParseUint(s[i+1:], 16, 0)
minor, err := strconv.ParseUint(after, 16, 0)
if err != nil {
return 0, err
}
@@ -91,17 +91,17 @@ func parseAddress(s string) (uintptr, error) {
// parseAddresses parses the start-end address.
func parseAddresses(s string) (uintptr, uintptr, error) {
idx := strings.Index(s, "-")
if idx == -1 {
before, after, ok := strings.Cut(s, "-")
if !ok {
return 0, 0, fmt.Errorf("%w: expected separator `-` in %s", ErrFileParse, s)
}
saddr, err := parseAddress(s[0:idx])
saddr, err := parseAddress(before)
if err != nil {
return 0, 0, err
}
eaddr, err := parseAddress(s[idx+1:])
eaddr, err := parseAddress(after)
if err != nil {
return 0, 0, err
}
+36 -2
View File
@@ -21,7 +21,7 @@ import (
"strconv"
"strings"
"github.com/prometheus/procfs/internal/util"
"github.com/prometheus/procfs/internal/parsers"
)
// ProcNetstat models the content of /proc/<pid>/net/netstat.
@@ -146,6 +146,20 @@ type TcpExt struct { // nolint:revive
TCPMTUPFail *float64
TCPMTUPSuccess *float64
TCPWqueueTooBig *float64
// Legacy TcpExt counters dropped from recent kernels' TcpExt table;
// modeled so consumers retain metric parity with older kernels that
// still print them in /proc/net/netstat.
TCPLoss *float64
PAWSPassive *float64
TCPForwardRetrans *float64
TCPSchedulerFailed *float64
TCPPrequeued *float64
TCPDirectCopyFromBacklog *float64
TCPDirectCopyFromPrequeue *float64
TCPPrequeueDropped *float64
TCPFACKReorder *float64
TCPHPHitsToUser *float64
}
type IpExt struct { // nolint:revive
@@ -171,7 +185,7 @@ type IpExt struct { // nolint:revive
func (p Proc) Netstat() (ProcNetstat, error) {
filename := p.path("net/netstat")
data, err := util.ReadFileNoStat(filename)
data, err := parsers.ReadFileNoStat(filename)
if err != nil {
return ProcNetstat{PID: p.PID}, err
}
@@ -396,6 +410,26 @@ func parseProcNetstat(r io.Reader, fileName string) (ProcNetstat, error) {
procNetstat.TCPMTUPSuccess = &value
case "TCPWqueueTooBig":
procNetstat.TCPWqueueTooBig = &value
case "TCPLoss":
procNetstat.TCPLoss = &value
case "PAWSPassive":
procNetstat.PAWSPassive = &value
case "TCPForwardRetrans":
procNetstat.TCPForwardRetrans = &value
case "TCPSchedulerFailed":
procNetstat.TCPSchedulerFailed = &value
case "TCPPrequeued":
procNetstat.TCPPrequeued = &value
case "TCPDirectCopyFromBacklog":
procNetstat.TCPDirectCopyFromBacklog = &value
case "TCPDirectCopyFromPrequeue":
procNetstat.TCPDirectCopyFromPrequeue = &value
case "TCPPrequeueDropped":
procNetstat.TCPPrequeueDropped = &value
case "TCPFACKReorder":
procNetstat.TCPFACKReorder = &value
case "TCPHPHitsToUser":
procNetstat.TCPHPHitsToUser = &value
}
case "IpExt":
switch key {
+5 -5
View File
@@ -30,7 +30,7 @@ import (
"io"
"strings"
"github.com/prometheus/procfs/internal/util"
"github.com/prometheus/procfs/internal/parsers"
)
const lineFormat = "avg10=%f avg60=%f avg300=%f total=%d"
@@ -59,7 +59,7 @@ type PSIStats struct {
// resource from /proc/pressure/<resource>. At time of writing this can be
// either "cpu", "memory" or "io".
func (fs FS) PSIStatsForResource(resource string) (PSIStats, error) {
data, err := util.ReadFileNoStat(fs.proc.Path(fmt.Sprintf("%s/%s", "pressure", resource)))
data, err := parsers.ReadFileNoStat(fs.proc.Path(fmt.Sprintf("%s/%s", "pressure", resource)))
if err != nil {
return PSIStats{}, fmt.Errorf("%w: psi_stats: unavailable for %q: %w", ErrFileRead, resource, err)
}
@@ -74,18 +74,18 @@ func parsePSIStats(r io.Reader) (PSIStats, error) {
scanner := bufio.NewScanner(r)
for scanner.Scan() {
l := scanner.Text()
prefix := strings.Split(l, " ")[0]
prefix, _, _ := strings.Cut(l, " ")
switch prefix {
case "some":
psi := PSILine{}
_, err := fmt.Sscanf(l, fmt.Sprintf("some %s", lineFormat), &psi.Avg10, &psi.Avg60, &psi.Avg300, &psi.Total)
_, err := fmt.Sscanf(l, "some "+lineFormat, &psi.Avg10, &psi.Avg60, &psi.Avg300, &psi.Total)
if err != nil {
return PSIStats{}, err
}
psiStats.Some = &psi
case "full":
psi := PSILine{}
_, err := fmt.Sscanf(l, fmt.Sprintf("full %s", lineFormat), &psi.Avg10, &psi.Avg60, &psi.Avg300, &psi.Total)
_, err := fmt.Sscanf(l, "full "+lineFormat, &psi.Avg10, &psi.Avg60, &psi.Avg300, &psi.Total)
if err != nil {
return PSIStats{}, err
}
+4 -6
View File
@@ -23,13 +23,11 @@ import (
"strconv"
"strings"
"github.com/prometheus/procfs/internal/util"
"github.com/prometheus/procfs/internal/parsers"
)
var (
// Match the header line before each mapped zone in `/proc/pid/smaps`.
procSMapsHeaderLine = regexp.MustCompile(`^[a-f0-9].*$`)
)
// Match the header line before each mapped zone in `/proc/pid/smaps`.
var procSMapsHeaderLine = regexp.MustCompile(`^[a-f0-9].*$`)
type ProcSMapsRollup struct {
// Amount of the mapping that is currently resident in RAM.
@@ -60,7 +58,7 @@ type ProcSMapsRollup struct {
// If smaps_rollup does not exists (require kernel >= 4.15), the content of /proc/pid/smaps will
// we read and summed.
func (p Proc) ProcSMapsRollup() (ProcSMapsRollup, error) {
data, err := util.ReadFileNoStat(p.path("smaps_rollup"))
data, err := parsers.ReadFileNoStat(p.path("smaps_rollup"))
if err != nil && os.IsNotExist(err) {
return p.procSMapsRollupManual()
}
+2 -2
View File
@@ -21,7 +21,7 @@ import (
"strconv"
"strings"
"github.com/prometheus/procfs/internal/util"
"github.com/prometheus/procfs/internal/parsers"
)
// ProcSnmp models the content of /proc/<pid>/net/snmp.
@@ -135,7 +135,7 @@ type UdpLite struct { // nolint:revive
func (p Proc) Snmp() (ProcSnmp, error) {
filename := p.path("net/snmp")
data, err := util.ReadFileNoStat(filename)
data, err := parsers.ReadFileNoStat(filename)
if err != nil {
return ProcSnmp{PID: p.PID}, err
}
+2 -2
View File
@@ -22,7 +22,7 @@ import (
"strconv"
"strings"
"github.com/prometheus/procfs/internal/util"
"github.com/prometheus/procfs/internal/parsers"
)
// ProcSnmp6 models the content of /proc/<pid>/net/snmp6.
@@ -140,7 +140,7 @@ type UdpLite6 struct { // nolint:revive
func (p Proc) Snmp6() (ProcSnmp6, error) {
filename := p.path("net/snmp6")
data, err := util.ReadFileNoStat(filename)
data, err := parsers.ReadFileNoStat(filename)
if err != nil {
// On systems with IPv6 disabled, this file won't exist.
// Do nothing.
+2 -2
View File
@@ -18,7 +18,7 @@ import (
"fmt"
"os"
"github.com/prometheus/procfs/internal/util"
"github.com/prometheus/procfs/internal/parsers"
)
// Originally, this USER_HZ value was dynamically retrieved via a sysconf call
@@ -134,7 +134,7 @@ func (p Proc) NewStat() (ProcStat, error) {
// Stat returns the current status information of the process.
func (p Proc) Stat() (ProcStat, error) {
data, err := util.ReadFileNoStat(p.path("stat"))
data, err := parsers.ReadFileNoStat(p.path("stat"))
if err != nil {
return ProcStat{}, err
}
+2 -2
View File
@@ -18,7 +18,7 @@ import (
"strconv"
"strings"
"github.com/prometheus/procfs/internal/util"
"github.com/prometheus/procfs/internal/parsers"
)
// - https://man7.org/linux/man-pages/man5/proc_pid_statm.5.html
@@ -53,7 +53,7 @@ func (p Proc) NewStatm() (ProcStatm, error) {
// Statm returns the current memory usage information of the process.
func (p Proc) Statm() (ProcStatm, error) {
data, err := util.ReadFileNoStat(p.path("statm"))
data, err := parsers.ReadFileNoStat(p.path("statm"))
if err != nil {
return ProcStatm{}, err
}
+3 -4
View File
@@ -20,7 +20,7 @@ import (
"strconv"
"strings"
"github.com/prometheus/procfs/internal/util"
"github.com/prometheus/procfs/internal/parsers"
)
// ProcStatus provides status information about the process,
@@ -100,7 +100,7 @@ type ProcStatus struct {
// NewStatus returns the current status information of the process.
func (p Proc) NewStatus() (ProcStatus, error) {
data, err := util.ReadFileNoStat(p.path("status"))
data, err := parsers.ReadFileNoStat(p.path("status"))
if err != nil {
return ProcStatus{}, err
}
@@ -135,7 +135,7 @@ func (p Proc) NewStatus() (ProcStatus, error) {
return s, nil
}
func (s *ProcStatus) fillStatus(k string, vString string, vUint uint64, vUintBytes uint64) error {
func (s *ProcStatus) fillStatus(k, vString string, vUint, vUintBytes uint64) error {
switch k {
case "Tgid":
s.TGID = int(vUint)
@@ -261,7 +261,6 @@ func calcCpusAllowedList(cpuString string) []uint64 {
cpu, _ := strconv.ParseUint(l[0], 10, 64)
g = append(g, cpu)
}
}
slices.Sort(g)
+3 -4
View File
@@ -17,7 +17,7 @@ import (
"fmt"
"strings"
"github.com/prometheus/procfs/internal/util"
"github.com/prometheus/procfs/internal/parsers"
)
func sysctlToPath(sysctl string) string {
@@ -25,12 +25,11 @@ func sysctlToPath(sysctl string) string {
}
func (fs FS) SysctlStrings(sysctl string) ([]string, error) {
value, err := util.SysReadFile(fs.proc.Path("sys", sysctlToPath(sysctl)))
value, err := parsers.SysReadFile(fs.proc.Path("sys", sysctlToPath(sysctl)))
if err != nil {
return nil, err
}
return strings.Fields(value), nil
}
func (fs FS) SysctlInts(sysctl string) ([]int, error) {
@@ -41,7 +40,7 @@ func (fs FS) SysctlInts(sysctl string) ([]int, error) {
values := make([]int, len(fields))
for i, f := range fields {
vp := util.NewValueParser(f)
vp := parsers.NewValueParser(f)
values[i] = vp.Int()
if err := vp.Err(); err != nil {
return nil, fmt.Errorf("%w: field %d in sysctl %s is not a valid int: %w", ErrFileParse, i, sysctl, err)
+2 -2
View File
@@ -21,7 +21,7 @@ import (
"strconv"
"strings"
"github.com/prometheus/procfs/internal/util"
"github.com/prometheus/procfs/internal/parsers"
)
var (
@@ -142,7 +142,7 @@ func (fs FS) SlabInfo() (SlabInfo, error) {
// TODO: Consider passing options to allow for parsing different
// slabinfo versions. However, slabinfo 2.1 has been stable since
// kernel 2.6.10 and later.
data, err := util.ReadFileNoStat(fs.proc.Path("slabinfo"))
data, err := parsers.ReadFileNoStat(fs.proc.Path("slabinfo"))
if err != nil {
return SlabInfo{}, err
}
+2 -2
View File
@@ -21,7 +21,7 @@ import (
"strconv"
"strings"
"github.com/prometheus/procfs/internal/util"
"github.com/prometheus/procfs/internal/parsers"
)
// Softirqs represents the softirq statistics.
@@ -40,7 +40,7 @@ type Softirqs struct {
func (fs FS) Softirqs() (Softirqs, error) {
fileName := fs.proc.Path("softirqs")
data, err := util.ReadFileNoStat(fileName)
data, err := parsers.ReadFileNoStat(fileName)
if err != nil {
return Softirqs{}, err
}
+4 -5
View File
@@ -23,7 +23,7 @@ import (
"strings"
"github.com/prometheus/procfs/internal/fs"
"github.com/prometheus/procfs/internal/util"
"github.com/prometheus/procfs/internal/parsers"
)
// CPUStat shows how much time the cpu spend in various stages.
@@ -135,7 +135,6 @@ func parseSoftIRQStat(line string) (SoftIRQStat, uint64, error) {
&softIRQStat.Block, &softIRQStat.BlockIoPoll,
&softIRQStat.Tasklet, &softIRQStat.Sched,
&softIRQStat.Hrtimer, &softIRQStat.Rcu)
if err != nil {
return SoftIRQStat{}, 0, fmt.Errorf("%w: couldn't parse %q (softirq): %w", ErrFileParse, line, err)
}
@@ -167,7 +166,7 @@ func (fs FS) NewStat() (Stat, error) {
// See: https://www.kernel.org/doc/Documentation/filesystems/proc.txt
func (fs FS) Stat() (Stat, error) {
fileName := fs.proc.Path("stat")
data, err := util.ReadFileNoStat(fileName)
data, err := parsers.ReadFileNoStat(fileName)
if err != nil {
return Stat{}, err
}
@@ -178,7 +177,7 @@ func (fs FS) Stat() (Stat, error) {
return procStat, nil
}
// parseStat parses the metrics from /proc/[pid]/stat.
// parseStat parses the metrics from /proc/stat.
func parseStat(r io.Reader, fileName string) (Stat, error) {
var (
scanner = bufio.NewScanner(r)
@@ -194,7 +193,7 @@ func parseStat(r io.Reader, fileName string) (Stat, error) {
for scanner.Scan() {
line := scanner.Text()
parts := strings.Fields(scanner.Text())
parts := strings.Fields(line)
// require at least <key> <value>
if len(parts) < 2 {
continue
+2 -2
View File
@@ -20,7 +20,7 @@ import (
"strconv"
"strings"
"github.com/prometheus/procfs/internal/util"
"github.com/prometheus/procfs/internal/parsers"
)
// Swap represents an entry in /proc/swaps.
@@ -34,7 +34,7 @@ type Swap struct {
// Swaps returns a slice of all configured swap devices on the system.
func (fs FS) Swaps() ([]*Swap, error) {
data, err := util.ReadFileNoStat(fs.proc.Path("swaps"))
data, err := parsers.ReadFileNoStat(fs.proc.Path("swaps"))
if err != nil {
return nil, err
}
+4 -4
View File
@@ -21,7 +21,7 @@ import (
"path/filepath"
"strings"
"github.com/prometheus/procfs/internal/util"
"github.com/prometheus/procfs/internal/parsers"
)
// The VM interface is described at
@@ -102,11 +102,11 @@ func (fs FS) VM() (*VM, error) {
name := filepath.Join(path, f.Name())
// ignore errors on read, as there are some write only
// in /proc/sys/vm
value, err := util.SysReadFile(name)
value, err := parsers.SysReadFile(name)
if err != nil {
continue
}
vp := util.NewValueParser(value)
vp := parsers.NewValueParser(value)
switch f.Name() {
case "admin_reserve_kbytes":
@@ -143,7 +143,7 @@ func (fs FS) VM() (*VM, error) {
stringSlice := strings.Fields(value)
pint64Slice := make([]*int64, 0, len(stringSlice))
for _, value := range stringSlice {
vp := util.NewValueParser(value)
vp := parsers.NewValueParser(value)
pint64Slice = append(pint64Slice, vp.PInt64())
}
vm.LowmemReserveRatio = pint64Slice
+3 -4
View File
@@ -22,7 +22,7 @@ import (
"regexp"
"strings"
"github.com/prometheus/procfs/internal/util"
"github.com/prometheus/procfs/internal/parsers"
)
// Zoneinfo holds info parsed from /proc/zoneinfo.
@@ -84,7 +84,6 @@ func (fs FS) Zoneinfo() ([]Zoneinfo, error) {
}
func parseZoneinfo(zoneinfoData []byte) ([]Zoneinfo, error) {
zoneinfo := []Zoneinfo{}
for block := range bytes.SplitSeq(zoneinfoData, []byte("\nNode")) {
@@ -103,7 +102,7 @@ func parseZoneinfo(zoneinfoData []byte) ([]Zoneinfo, error) {
if len(parts) < 2 {
continue
}
vp := util.NewValueParser(parts[1])
vp := parsers.NewValueParser(parts[1])
switch parts[0] {
case "nr_free_pages":
zoneinfoElement.NrFreePages = vp.PInt64()
@@ -179,7 +178,7 @@ func parseZoneinfo(zoneinfoData []byte) ([]Zoneinfo, error) {
protectionValues = strings.Replace(protectionValues, ")", "", 1)
protectionValues = strings.TrimSpace(protectionValues)
protectionStringMap := strings.Split(protectionValues, ", ")
val, err := util.ParsePInt64s(protectionStringMap)
val, err := parsers.ParsePInt64s(protectionStringMap)
if err == nil {
zoneinfoElement.Protection = val
}