From cceec985080758e5c32c38d5c99c1cca4394ffe1 Mon Sep 17 00:00:00 2001 From: trafalgarzzz Date: Thu, 20 Mar 2025 10:00:08 +0800 Subject: [PATCH 1/3] Downgrade github.com/prometheus/client_golang to v1.20.5 Signed-off-by: trafalgarzzz --- go.mod | 5 +- go.sum | 4 +- .../client_golang/prometheus/atomic_update.go | 50 ---- .../client_golang/prometheus/counter.go | 10 +- .../client_golang/prometheus/desc.go | 15 +- .../client_golang/prometheus/gauge.go | 10 +- .../prometheus/go_collector_latest.go | 2 +- .../client_golang/prometheus/histogram.go | 259 ++---------------- .../prometheus/internal/difflib.go | 19 +- .../prometheus/internal/go_runtime_metrics.go | 3 +- .../client_golang/prometheus/metric.go | 24 +- .../prometheus/process_collector.go | 31 +-- .../prometheus/process_collector_cgo_darwin.c | 84 ------ .../process_collector_cgo_darwin.go | 51 ---- .../prometheus/process_collector_darwin.go | 128 --------- ...r_wasip1_js.go => process_collector_js.go} | 17 +- .../process_collector_nocgo_darwin.go | 39 --- .../prometheus/process_collector_other.go | 20 +- .../prometheus/process_collector_wasip1.go | 26 ++ .../prometheus/process_collector_windows.go | 21 +- .../client_golang/prometheus/promhttp/http.go | 23 +- .../client_golang/prometheus/summary.go | 32 ++- vendor/modules.txt | 4 +- 23 files changed, 139 insertions(+), 738 deletions(-) delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/atomic_update.go delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/process_collector_cgo_darwin.c delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/process_collector_cgo_darwin.go delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/process_collector_darwin.go rename vendor/github.com/prometheus/client_golang/prometheus/{process_collector_wasip1_js.go => process_collector_js.go} (57%) delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/process_collector_nocgo_darwin.go create mode 100644 vendor/github.com/prometheus/client_golang/prometheus/process_collector_wasip1.go diff --git a/go.mod b/go.mod index 7fd2030effb..b0d3b25af25 100644 --- a/go.mod +++ b/go.mod @@ -1,6 +1,7 @@ module github.com/fluid-cloudnative/fluid -go 1.22.10 +go 1.23.0 + toolchain go1.23.7 replace k8s.io/api => k8s.io/api v0.29.5 @@ -69,7 +70,7 @@ require ( github.com/onsi/ginkgo v1.16.5 github.com/onsi/gomega v1.36.2 github.com/pkg/errors v0.9.1 - github.com/prometheus/client_golang v1.21.0 + github.com/prometheus/client_golang v1.20.5 github.com/smartystreets/goconvey v1.8.1 github.com/spf13/cobra v1.9.1 github.com/stretchr/testify v1.10.0 diff --git a/go.sum b/go.sum index 612abd9aefd..e143414360a 100644 --- a/go.sum +++ b/go.sum @@ -1227,8 +1227,8 @@ github.com/prometheus/client_golang v1.12.1/go.mod h1:3Z9XVyYiZYEO+YQWt3RD2R3jrb github.com/prometheus/client_golang v1.14.0/go.mod h1:8vpkKitgIVNcqrRBWh1C4TIUQgYNtG/XQE4E/Zae36Y= github.com/prometheus/client_golang v1.15.1/go.mod h1:e9yaBhRPU2pPNsZwE+JdQl0KEt1N9XgF6zxWmaC0xOk= github.com/prometheus/client_golang v1.16.0/go.mod h1:Zsulrv/L9oM40tJ7T815tM89lFEugiJ9HzIqaAx4LKc= -github.com/prometheus/client_golang v1.21.0 h1:DIsaGmiaBkSangBgMtWdNfxbMNdku5IK6iNhrEqWvdA= -github.com/prometheus/client_golang v1.21.0/go.mod h1:U9NM32ykUErtVBxdvD3zfi+EuFkkaBvMb09mIfe0Zgg= +github.com/prometheus/client_golang v1.20.5 h1:cxppBPuYhUnsO6yo/aoRol4L7q7UFfdm+bR9r+8l63Y= +github.com/prometheus/client_golang v1.20.5/go.mod h1:PIEt8X02hGcP8JWbeHyeZ53Y/jReSnHgO035n//V5WE= github.com/prometheus/client_model v0.0.0-20180712105110-5c3871d89910/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo= github.com/prometheus/client_model v0.0.0-20190129233127-fd36f4220a90/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= diff --git a/vendor/github.com/prometheus/client_golang/prometheus/atomic_update.go b/vendor/github.com/prometheus/client_golang/prometheus/atomic_update.go deleted file mode 100644 index b65896a3195..00000000000 --- a/vendor/github.com/prometheus/client_golang/prometheus/atomic_update.go +++ /dev/null @@ -1,50 +0,0 @@ -// Copyright 2014 The Prometheus Authors -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package prometheus - -import ( - "math" - "sync/atomic" - "time" -) - -// atomicUpdateFloat atomically updates the float64 value pointed to by bits -// using the provided updateFunc, with an exponential backoff on contention. -func atomicUpdateFloat(bits *uint64, updateFunc func(float64) float64) { - const ( - // both numbers are derived from empirical observations - // documented in this PR: https://github.com/prometheus/client_golang/pull/1661 - maxBackoff = 320 * time.Millisecond - initialBackoff = 10 * time.Millisecond - ) - backoff := initialBackoff - - for { - loadedBits := atomic.LoadUint64(bits) - oldFloat := math.Float64frombits(loadedBits) - newFloat := updateFunc(oldFloat) - newBits := math.Float64bits(newFloat) - - if atomic.CompareAndSwapUint64(bits, loadedBits, newBits) { - break - } else { - // Exponential backoff with sleep and cap to avoid infinite wait - time.Sleep(backoff) - backoff *= 2 - if backoff > maxBackoff { - backoff = maxBackoff - } - } - } -} diff --git a/vendor/github.com/prometheus/client_golang/prometheus/counter.go b/vendor/github.com/prometheus/client_golang/prometheus/counter.go index 2996aef6a0a..4ce84e7a80e 100644 --- a/vendor/github.com/prometheus/client_golang/prometheus/counter.go +++ b/vendor/github.com/prometheus/client_golang/prometheus/counter.go @@ -134,9 +134,13 @@ func (c *counter) Add(v float64) { return } - atomicUpdateFloat(&c.valBits, func(oldVal float64) float64 { - return oldVal + v - }) + for { + oldBits := atomic.LoadUint64(&c.valBits) + newBits := math.Float64bits(math.Float64frombits(oldBits) + v) + if atomic.CompareAndSwapUint64(&c.valBits, oldBits, newBits) { + return + } + } } func (c *counter) AddWithExemplar(v float64, e Labels) { diff --git a/vendor/github.com/prometheus/client_golang/prometheus/desc.go b/vendor/github.com/prometheus/client_golang/prometheus/desc.go index ad347113c04..68ffe3c2480 100644 --- a/vendor/github.com/prometheus/client_golang/prometheus/desc.go +++ b/vendor/github.com/prometheus/client_golang/prometheus/desc.go @@ -189,15 +189,12 @@ func (d *Desc) String() string { fmt.Sprintf("%s=%q", lp.GetName(), lp.GetValue()), ) } - vlStrings := []string{} - if d.variableLabels != nil { - vlStrings = make([]string, 0, len(d.variableLabels.names)) - for _, vl := range d.variableLabels.names { - if fn, ok := d.variableLabels.labelConstraints[vl]; ok && fn != nil { - vlStrings = append(vlStrings, fmt.Sprintf("c(%s)", vl)) - } else { - vlStrings = append(vlStrings, vl) - } + vlStrings := make([]string, 0, len(d.variableLabels.names)) + for _, vl := range d.variableLabels.names { + if fn, ok := d.variableLabels.labelConstraints[vl]; ok && fn != nil { + vlStrings = append(vlStrings, fmt.Sprintf("c(%s)", vl)) + } else { + vlStrings = append(vlStrings, vl) } } return fmt.Sprintf( diff --git a/vendor/github.com/prometheus/client_golang/prometheus/gauge.go b/vendor/github.com/prometheus/client_golang/prometheus/gauge.go index aa18463654f..dd2eac94067 100644 --- a/vendor/github.com/prometheus/client_golang/prometheus/gauge.go +++ b/vendor/github.com/prometheus/client_golang/prometheus/gauge.go @@ -120,9 +120,13 @@ func (g *gauge) Dec() { } func (g *gauge) Add(val float64) { - atomicUpdateFloat(&g.valBits, func(oldVal float64) float64 { - return oldVal + val - }) + for { + oldBits := atomic.LoadUint64(&g.valBits) + newBits := math.Float64bits(math.Float64frombits(oldBits) + val) + if atomic.CompareAndSwapUint64(&g.valBits, oldBits, newBits) { + return + } + } } func (g *gauge) Sub(val float64) { diff --git a/vendor/github.com/prometheus/client_golang/prometheus/go_collector_latest.go b/vendor/github.com/prometheus/client_golang/prometheus/go_collector_latest.go index 6b8684731c9..51174641729 100644 --- a/vendor/github.com/prometheus/client_golang/prometheus/go_collector_latest.go +++ b/vendor/github.com/prometheus/client_golang/prometheus/go_collector_latest.go @@ -288,7 +288,7 @@ func NewGoCollector(opts ...func(o *internal.GoCollectorOptions)) Collector { } func attachOriginalName(desc, origName string) string { - return fmt.Sprintf("%s Sourced from %s.", desc, origName) + return fmt.Sprintf("%s Sourced from %s", desc, origName) } // Describe returns all descriptions of the collector. diff --git a/vendor/github.com/prometheus/client_golang/prometheus/histogram.go b/vendor/github.com/prometheus/client_golang/prometheus/histogram.go index 1a279035b30..519db348a74 100644 --- a/vendor/github.com/prometheus/client_golang/prometheus/histogram.go +++ b/vendor/github.com/prometheus/client_golang/prometheus/histogram.go @@ -14,7 +14,6 @@ package prometheus import ( - "errors" "fmt" "math" "runtime" @@ -29,11 +28,6 @@ import ( "google.golang.org/protobuf/types/known/timestamppb" ) -const ( - nativeHistogramSchemaMaximum = 8 - nativeHistogramSchemaMinimum = -4 -) - // nativeHistogramBounds for the frac of observed values. Only relevant for // schema > 0. The position in the slice is the schema. (0 is never used, just // here for convenience of using the schema directly as the index.) @@ -336,11 +330,11 @@ func ExponentialBuckets(start, factor float64, count int) []float64 { // used for the Buckets field of HistogramOpts. // // The function panics if 'count' is 0 or negative, if 'min' is 0 or negative. -func ExponentialBucketsRange(minBucket, maxBucket float64, count int) []float64 { +func ExponentialBucketsRange(min, max float64, count int) []float64 { if count < 1 { panic("ExponentialBucketsRange count needs a positive count") } - if minBucket <= 0 { + if min <= 0 { panic("ExponentialBucketsRange min needs to be greater than 0") } @@ -348,12 +342,12 @@ func ExponentialBucketsRange(minBucket, maxBucket float64, count int) []float64 // max = min*growthFactor^(bucketCount-1) // We know max/min and highest bucket. Solve for growthFactor. - growthFactor := math.Pow(maxBucket/minBucket, 1.0/float64(count-1)) + growthFactor := math.Pow(max/min, 1.0/float64(count-1)) // Now that we know growthFactor, solve for each bucket. buckets := make([]float64, count) for i := 1; i <= count; i++ { - buckets[i-1] = minBucket * math.Pow(growthFactor, float64(i-1)) + buckets[i-1] = min * math.Pow(growthFactor, float64(i-1)) } return buckets } @@ -864,35 +858,15 @@ func (h *histogram) Write(out *dto.Metric) error { // findBucket returns the index of the bucket for the provided value, or // len(h.upperBounds) for the +Inf bucket. func (h *histogram) findBucket(v float64) int { - n := len(h.upperBounds) - if n == 0 { - return 0 - } - - // Early exit: if v is less than or equal to the first upper bound, return 0 - if v <= h.upperBounds[0] { - return 0 - } - - // Early exit: if v is greater than the last upper bound, return len(h.upperBounds) - if v > h.upperBounds[n-1] { - return n - } - - // For small arrays, use simple linear search - // "magic number" 35 is result of tests on couple different (AWS and baremetal) servers - // see more details here: https://github.com/prometheus/client_golang/pull/1662 - if n < 35 { - for i, bound := range h.upperBounds { - if v <= bound { - return i - } - } - // If v is greater than all upper bounds, return len(h.upperBounds) - return n - } - - // For larger arrays, use stdlib's binary search + // TODO(beorn7): For small numbers of buckets (<30), a linear search is + // slightly faster than the binary search. If we really care, we could + // switch from one search strategy to the other depending on the number + // of buckets. + // + // Microbenchmarks (BenchmarkHistogramNoLabels): + // 11 buckets: 38.3 ns/op linear - binary 48.7 ns/op + // 100 buckets: 78.1 ns/op linear - binary 54.9 ns/op + // 300 buckets: 154 ns/op linear - binary 61.6 ns/op return sort.SearchFloat64s(h.upperBounds, v) } @@ -1466,9 +1440,9 @@ func pickSchema(bucketFactor float64) int32 { floor := math.Floor(math.Log2(math.Log2(bucketFactor))) switch { case floor <= -8: - return nativeHistogramSchemaMaximum + return 8 case floor >= 4: - return nativeHistogramSchemaMinimum + return -4 default: return -int32(floor) } @@ -1647,9 +1621,13 @@ func waitForCooldown(count uint64, counts *histogramCounts) { // atomicAddFloat adds the provided float atomically to another float // represented by the bit pattern the bits pointer is pointing to. func atomicAddFloat(bits *uint64, v float64) { - atomicUpdateFloat(bits, func(oldVal float64) float64 { - return oldVal + v - }) + for { + loadedBits := atomic.LoadUint64(bits) + newBits := math.Float64bits(math.Float64frombits(loadedBits) + v) + if atomic.CompareAndSwapUint64(bits, loadedBits, newBits) { + break + } + } } // atomicDecUint32 atomically decrements the uint32 p points to. See @@ -1857,196 +1835,3 @@ func (n *nativeExemplars) addExemplar(e *dto.Exemplar) { n.exemplars = append(n.exemplars[:nIdx], append([]*dto.Exemplar{e}, append(n.exemplars[nIdx:rIdx], n.exemplars[rIdx+1:]...)...)...) } } - -type constNativeHistogram struct { - desc *Desc - dto.Histogram - labelPairs []*dto.LabelPair -} - -func validateCount(sum float64, count uint64, negativeBuckets, positiveBuckets map[int]int64, zeroBucket uint64) error { - var bucketPopulationSum int64 - for _, v := range positiveBuckets { - bucketPopulationSum += v - } - for _, v := range negativeBuckets { - bucketPopulationSum += v - } - bucketPopulationSum += int64(zeroBucket) - - // If the sum of observations is NaN, the number of observations must be greater or equal to the sum of all bucket counts. - // Otherwise, the number of observations must be equal to the sum of all bucket counts . - - if math.IsNaN(sum) && bucketPopulationSum > int64(count) || - !math.IsNaN(sum) && bucketPopulationSum != int64(count) { - return errors.New("the sum of all bucket populations exceeds the count of observations") - } - return nil -} - -// NewConstNativeHistogram returns a metric representing a Prometheus native histogram with -// fixed values for the count, sum, and positive/negative/zero bucket counts. As those parameters -// cannot be changed, the returned value does not implement the Histogram -// interface (but only the Metric interface). Users of this package will not -// have much use for it in regular operations. However, when implementing custom -// OpenTelemetry Collectors, it is useful as a throw-away metric that is generated on the fly -// to send it to Prometheus in the Collect method. -// -// zeroBucket counts all (positive and negative) -// observations in the zero bucket (with an absolute value less or equal -// the current threshold). -// positiveBuckets and negativeBuckets are separate maps for negative and positive -// observations. The map's value is an int64, counting observations in -// that bucket. The map's key is the -// index of the bucket according to the used -// Schema. Index 0 is for an upper bound of 1 in positive buckets and for a lower bound of -1 in negative buckets. -// NewConstNativeHistogram returns an error if -// - the length of labelValues is not consistent with the variable labels in Desc or if Desc is invalid. -// - the schema passed is not between 8 and -4 -// - the sum of counts in all buckets including the zero bucket does not equal the count if sum is not NaN (or exceeds the count if sum is NaN) -// -// See https://opentelemetry.io/docs/specs/otel/compatibility/prometheus_and_openmetrics/#exponential-histograms for more details about the conversion from OTel to Prometheus. -func NewConstNativeHistogram( - desc *Desc, - count uint64, - sum float64, - positiveBuckets, negativeBuckets map[int]int64, - zeroBucket uint64, - schema int32, - zeroThreshold float64, - createdTimestamp time.Time, - labelValues ...string, -) (Metric, error) { - if desc.err != nil { - return nil, desc.err - } - if err := validateLabelValues(labelValues, len(desc.variableLabels.names)); err != nil { - return nil, err - } - if schema > nativeHistogramSchemaMaximum || schema < nativeHistogramSchemaMinimum { - return nil, errors.New("invalid native histogram schema") - } - if err := validateCount(sum, count, negativeBuckets, positiveBuckets, zeroBucket); err != nil { - return nil, err - } - - NegativeSpan, NegativeDelta := makeBucketsFromMap(negativeBuckets) - PositiveSpan, PositiveDelta := makeBucketsFromMap(positiveBuckets) - ret := &constNativeHistogram{ - desc: desc, - Histogram: dto.Histogram{ - CreatedTimestamp: timestamppb.New(createdTimestamp), - Schema: &schema, - ZeroThreshold: &zeroThreshold, - SampleCount: &count, - SampleSum: &sum, - - NegativeSpan: NegativeSpan, - NegativeDelta: NegativeDelta, - - PositiveSpan: PositiveSpan, - PositiveDelta: PositiveDelta, - - ZeroCount: proto.Uint64(zeroBucket), - }, - labelPairs: MakeLabelPairs(desc, labelValues), - } - if *ret.ZeroThreshold == 0 && *ret.ZeroCount == 0 && len(ret.PositiveSpan) == 0 && len(ret.NegativeSpan) == 0 { - ret.PositiveSpan = []*dto.BucketSpan{{ - Offset: proto.Int32(0), - Length: proto.Uint32(0), - }} - } - return ret, nil -} - -// MustNewConstNativeHistogram is a version of NewConstNativeHistogram that panics where -// NewConstNativeHistogram would have returned an error. -func MustNewConstNativeHistogram( - desc *Desc, - count uint64, - sum float64, - positiveBuckets, negativeBuckets map[int]int64, - zeroBucket uint64, - nativeHistogramSchema int32, - nativeHistogramZeroThreshold float64, - createdTimestamp time.Time, - labelValues ...string, -) Metric { - nativehistogram, err := NewConstNativeHistogram(desc, - count, - sum, - positiveBuckets, - negativeBuckets, - zeroBucket, - nativeHistogramSchema, - nativeHistogramZeroThreshold, - createdTimestamp, - labelValues...) - if err != nil { - panic(err) - } - return nativehistogram -} - -func (h *constNativeHistogram) Desc() *Desc { - return h.desc -} - -func (h *constNativeHistogram) Write(out *dto.Metric) error { - out.Histogram = &h.Histogram - out.Label = h.labelPairs - return nil -} - -func makeBucketsFromMap(buckets map[int]int64) ([]*dto.BucketSpan, []int64) { - if len(buckets) == 0 { - return nil, nil - } - var ii []int - for k := range buckets { - ii = append(ii, k) - } - sort.Ints(ii) - - var ( - spans []*dto.BucketSpan - deltas []int64 - prevCount int64 - nextI int - ) - - appendDelta := func(count int64) { - *spans[len(spans)-1].Length++ - deltas = append(deltas, count-prevCount) - prevCount = count - } - - for n, i := range ii { - count := buckets[i] - // Multiple spans with only small gaps in between are probably - // encoded more efficiently as one larger span with a few empty - // buckets. Needs some research to find the sweet spot. For now, - // we assume that gaps of one or two buckets should not create - // a new span. - iDelta := int32(i - nextI) - if n == 0 || iDelta > 2 { - // We have to create a new span, either because we are - // 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), - 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++ { - appendDelta(0) - } - } - appendDelta(count) - nextI = i + 1 - } - return spans, deltas -} diff --git a/vendor/github.com/prometheus/client_golang/prometheus/internal/difflib.go b/vendor/github.com/prometheus/client_golang/prometheus/internal/difflib.go index 8b016355adb..a595a203625 100644 --- a/vendor/github.com/prometheus/client_golang/prometheus/internal/difflib.go +++ b/vendor/github.com/prometheus/client_golang/prometheus/internal/difflib.go @@ -22,18 +22,17 @@ import ( "bytes" "fmt" "io" - "strconv" "strings" ) -func minInt(a, b int) int { +func min(a, b int) int { if a < b { return a } return b } -func maxInt(a, b int) int { +func max(a, b int) int { if a > b { return a } @@ -428,12 +427,12 @@ func (m *SequenceMatcher) GetGroupedOpCodes(n int) [][]OpCode { if codes[0].Tag == 'e' { c := codes[0] i1, i2, j1, j2 := c.I1, c.I2, c.J1, c.J2 - codes[0] = OpCode{c.Tag, maxInt(i1, i2-n), i2, maxInt(j1, j2-n), j2} + codes[0] = OpCode{c.Tag, max(i1, i2-n), i2, max(j1, j2-n), j2} } if codes[len(codes)-1].Tag == 'e' { c := codes[len(codes)-1] i1, i2, j1, j2 := c.I1, c.I2, c.J1, c.J2 - codes[len(codes)-1] = OpCode{c.Tag, i1, minInt(i2, i1+n), j1, minInt(j2, j1+n)} + codes[len(codes)-1] = OpCode{c.Tag, i1, min(i2, i1+n), j1, min(j2, j1+n)} } nn := n + n groups := [][]OpCode{} @@ -444,12 +443,12 @@ func (m *SequenceMatcher) GetGroupedOpCodes(n int) [][]OpCode { // there is a large range with no changes. if c.Tag == 'e' && i2-i1 > nn { group = append(group, OpCode{ - c.Tag, i1, minInt(i2, i1+n), - j1, minInt(j2, j1+n), + c.Tag, i1, min(i2, i1+n), + j1, min(j2, j1+n), }) groups = append(groups, group) group = []OpCode{} - i1, j1 = maxInt(i1, i2-n), maxInt(j1, j2-n) + i1, j1 = max(i1, i2-n), max(j1, j2-n) } group = append(group, OpCode{c.Tag, i1, i2, j1, j2}) } @@ -516,7 +515,7 @@ func (m *SequenceMatcher) QuickRatio() float64 { // is faster to compute than either .Ratio() or .QuickRatio(). func (m *SequenceMatcher) RealQuickRatio() float64 { la, lb := len(m.a), len(m.b) - return calculateRatio(minInt(la, lb), la+lb) + return calculateRatio(min(la, lb), la+lb) } // Convert range to the "ed" format @@ -525,7 +524,7 @@ func formatRangeUnified(start, stop int) string { beginning := start + 1 // lines start numbering with one length := stop - start if length == 1 { - return strconv.Itoa(beginning) + return fmt.Sprintf("%d", beginning) } if length == 0 { beginning-- // empty ranges begin at line just before the range diff --git a/vendor/github.com/prometheus/client_golang/prometheus/internal/go_runtime_metrics.go b/vendor/github.com/prometheus/client_golang/prometheus/internal/go_runtime_metrics.go index f7f97ef9262..97d17d6cb60 100644 --- a/vendor/github.com/prometheus/client_golang/prometheus/internal/go_runtime_metrics.go +++ b/vendor/github.com/prometheus/client_golang/prometheus/internal/go_runtime_metrics.go @@ -66,8 +66,7 @@ func RuntimeMetricsToProm(d *metrics.Description) (string, string, string, bool) name += "_total" } - // Our current conversion moves to legacy naming, so use legacy validation. - valid := model.IsValidLegacyMetricName(namespace + "_" + subsystem + "_" + name) + valid := model.IsValidMetricName(model.LabelValue(namespace + "_" + subsystem + "_" + name)) switch d.Kind { case metrics.KindUint64: case metrics.KindFloat64: diff --git a/vendor/github.com/prometheus/client_golang/prometheus/metric.go b/vendor/github.com/prometheus/client_golang/prometheus/metric.go index 592eec3e24f..9d9b81ab448 100644 --- a/vendor/github.com/prometheus/client_golang/prometheus/metric.go +++ b/vendor/github.com/prometheus/client_golang/prometheus/metric.go @@ -108,23 +108,15 @@ func BuildFQName(namespace, subsystem, name string) string { if name == "" { return "" } - - sb := strings.Builder{} - sb.Grow(len(namespace) + len(subsystem) + len(name) + 2) - - if namespace != "" { - sb.WriteString(namespace) - sb.WriteString("_") - } - - if subsystem != "" { - sb.WriteString(subsystem) - sb.WriteString("_") + switch { + case namespace != "" && subsystem != "": + return strings.Join([]string{namespace, subsystem, name}, "_") + case namespace != "": + return strings.Join([]string{namespace, name}, "_") + case subsystem != "": + return strings.Join([]string{subsystem, name}, "_") } - - sb.WriteString(name) - - return sb.String() + return name } type invalidMetric struct { diff --git a/vendor/github.com/prometheus/client_golang/prometheus/process_collector.go b/vendor/github.com/prometheus/client_golang/prometheus/process_collector.go index e7bce8b58ec..62a4e7ad9a0 100644 --- a/vendor/github.com/prometheus/client_golang/prometheus/process_collector.go +++ b/vendor/github.com/prometheus/client_golang/prometheus/process_collector.go @@ -23,7 +23,6 @@ import ( type processCollector struct { collectFn func(chan<- Metric) - describeFn func(chan<- *Desc) pidFn func() (int, error) reportErrors bool cpuTotal *Desc @@ -123,23 +122,26 @@ func NewProcessCollector(opts ProcessCollectorOpts) Collector { // Set up process metric collection if supported by the runtime. if canCollectProcess() { c.collectFn = c.processCollect - c.describeFn = c.describe } else { - c.collectFn = c.errorCollectFn - c.describeFn = c.errorDescribeFn + c.collectFn = func(ch chan<- Metric) { + c.reportError(ch, nil, errors.New("process metrics not supported on this platform")) + } } return c } -func (c *processCollector) errorCollectFn(ch chan<- Metric) { - c.reportError(ch, nil, errors.New("process metrics not supported on this platform")) -} - -func (c *processCollector) errorDescribeFn(ch chan<- *Desc) { - if c.reportErrors { - ch <- NewInvalidDesc(errors.New("process metrics not supported on this platform")) - } +// Describe returns all descriptions of the collector. +func (c *processCollector) Describe(ch chan<- *Desc) { + ch <- c.cpuTotal + ch <- c.openFDs + ch <- c.maxFDs + ch <- c.vsize + ch <- c.maxVsize + ch <- c.rss + ch <- c.startTime + ch <- c.inBytes + ch <- c.outBytes } // Collect returns the current state of all metrics of the collector. @@ -147,11 +149,6 @@ func (c *processCollector) Collect(ch chan<- Metric) { c.collectFn(ch) } -// Describe returns all descriptions of the collector. -func (c *processCollector) Describe(ch chan<- *Desc) { - c.describeFn(ch) -} - func (c *processCollector) reportError(ch chan<- Metric, desc *Desc, err error) { if !c.reportErrors { return diff --git a/vendor/github.com/prometheus/client_golang/prometheus/process_collector_cgo_darwin.c b/vendor/github.com/prometheus/client_golang/prometheus/process_collector_cgo_darwin.c deleted file mode 100644 index 1554f674d85..00000000000 --- a/vendor/github.com/prometheus/client_golang/prometheus/process_collector_cgo_darwin.c +++ /dev/null @@ -1,84 +0,0 @@ -// Copyright 2024 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 darwin && cgo - -#include -#include -#include - -// The compiler warns that mach/shared_memory_server.h is deprecated, and to use -// mach/shared_region.h instead. But that doesn't define -// SHARED_DATA_REGION_SIZE or SHARED_TEXT_REGION_SIZE, so redefine them here and -// avoid a warning message when running tests. -#define GLOBAL_SHARED_TEXT_SEGMENT 0x90000000U -#define SHARED_DATA_REGION_SIZE 0x10000000 -#define SHARED_TEXT_REGION_SIZE 0x10000000 - - -int get_memory_info(unsigned long long *rss, unsigned long long *vsize) -{ - // This is lightly adapted from how ps(1) obtains its memory info. - // https://github.com/apple-oss-distributions/adv_cmds/blob/8744084ea0ff41ca4bb96b0f9c22407d0e48e9b7/ps/tasks.c#L109 - - kern_return_t error; - task_t task = MACH_PORT_NULL; - mach_task_basic_info_data_t info; - mach_msg_type_number_t info_count = MACH_TASK_BASIC_INFO_COUNT; - - error = task_info( - mach_task_self(), - MACH_TASK_BASIC_INFO, - (task_info_t) &info, - &info_count ); - - if( error != KERN_SUCCESS ) - { - return error; - } - - *rss = info.resident_size; - *vsize = info.virtual_size; - - { - vm_region_basic_info_data_64_t b_info; - mach_vm_address_t address = GLOBAL_SHARED_TEXT_SEGMENT; - mach_vm_size_t size; - mach_port_t object_name; - - /* - * try to determine if this task has the split libraries - * mapped in... if so, adjust its virtual size down by - * the 2 segments that are used for split libraries - */ - info_count = VM_REGION_BASIC_INFO_COUNT_64; - - error = mach_vm_region( - mach_task_self(), - &address, - &size, - VM_REGION_BASIC_INFO_64, - (vm_region_info_t) &b_info, - &info_count, - &object_name); - - if (error == KERN_SUCCESS) { - if (b_info.reserved && size == (SHARED_TEXT_REGION_SIZE) && - *vsize > (SHARED_TEXT_REGION_SIZE + SHARED_DATA_REGION_SIZE)) { - *vsize -= (SHARED_TEXT_REGION_SIZE + SHARED_DATA_REGION_SIZE); - } - } - } - - return 0; -} diff --git a/vendor/github.com/prometheus/client_golang/prometheus/process_collector_cgo_darwin.go b/vendor/github.com/prometheus/client_golang/prometheus/process_collector_cgo_darwin.go deleted file mode 100644 index b375c3a7719..00000000000 --- a/vendor/github.com/prometheus/client_golang/prometheus/process_collector_cgo_darwin.go +++ /dev/null @@ -1,51 +0,0 @@ -// Copyright 2024 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 darwin && cgo - -package prometheus - -/* -int get_memory_info(unsigned long long *rss, unsigned long long *vs); -*/ -import "C" -import "fmt" - -func getMemory() (*memoryInfo, error) { - var rss, vsize C.ulonglong - - if err := C.get_memory_info(&rss, &vsize); err != 0 { - return nil, fmt.Errorf("task_info() failed with 0x%x", int(err)) - } - - return &memoryInfo{vsize: uint64(vsize), rss: uint64(rss)}, nil -} - -// describe returns all descriptions of the collector for Darwin. -// Ensure that this list of descriptors is kept in sync with the metrics collected -// in the processCollect method. Any changes to the metrics in processCollect -// (such as adding or removing metrics) should be reflected in this list of descriptors. -func (c *processCollector) describe(ch chan<- *Desc) { - ch <- c.cpuTotal - ch <- c.openFDs - ch <- c.maxFDs - ch <- c.maxVsize - ch <- c.startTime - ch <- c.rss - ch <- c.vsize - - /* the process could be collected but not implemented yet - ch <- c.inBytes - ch <- c.outBytes - */ -} diff --git a/vendor/github.com/prometheus/client_golang/prometheus/process_collector_darwin.go b/vendor/github.com/prometheus/client_golang/prometheus/process_collector_darwin.go deleted file mode 100644 index 50eb860a682..00000000000 --- a/vendor/github.com/prometheus/client_golang/prometheus/process_collector_darwin.go +++ /dev/null @@ -1,128 +0,0 @@ -// Copyright 2024 The Prometheus Authors -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package prometheus - -import ( - "errors" - "fmt" - "os" - "syscall" - "time" - - "golang.org/x/sys/unix" -) - -// notImplementedErr is returned by stub functions that replace cgo functions, when cgo -// isn't available. -var notImplementedErr = errors.New("not implemented") - -type memoryInfo struct { - vsize uint64 // Virtual memory size in bytes - rss uint64 // Resident memory size in bytes -} - -func canCollectProcess() bool { - return true -} - -func getSoftLimit(which int) (uint64, error) { - rlimit := syscall.Rlimit{} - - if err := syscall.Getrlimit(which, &rlimit); err != nil { - return 0, err - } - - return rlimit.Cur, nil -} - -func getOpenFileCount() (float64, error) { - // Alternately, the undocumented proc_pidinfo(PROC_PIDLISTFDS) can be used to - // return a list of open fds, but that requires a way to call C APIs. The - // 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 { - 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 - } - } -} - -func (c *processCollector) processCollect(ch chan<- Metric) { - if procs, err := unix.SysctlKinfoProcSlice("kern.proc.pid", os.Getpid()); err == nil { - if len(procs) == 1 { - startTime := float64(procs[0].Proc.P_starttime.Nano() / 1e9) - ch <- MustNewConstMetric(c.startTime, GaugeValue, startTime) - } else { - err = fmt.Errorf("sysctl() returned %d proc structs (expected 1)", len(procs)) - c.reportError(ch, c.startTime, err) - } - } else { - c.reportError(ch, c.startTime, err) - } - - // The proc structure returned by kern.proc.pid above has an Rusage member, - // but it is not filled in, so it needs to be fetched by getrusage(2). For - // that call, the UTime, STime, and Maxrss members are filled out, but not - // Ixrss, Idrss, or Isrss for the memory usage. Memory stats will require - // access to the C API to call task_info(TASK_BASIC_INFO). - rusage := unix.Rusage{} - - if err := unix.Getrusage(syscall.RUSAGE_SELF, &rusage); err == nil { - cpuTime := time.Duration(rusage.Stime.Nano() + rusage.Utime.Nano()).Seconds() - ch <- MustNewConstMetric(c.cpuTotal, CounterValue, cpuTime) - } else { - c.reportError(ch, c.cpuTotal, err) - } - - if memInfo, err := getMemory(); err == nil { - ch <- MustNewConstMetric(c.rss, GaugeValue, float64(memInfo.rss)) - ch <- MustNewConstMetric(c.vsize, GaugeValue, float64(memInfo.vsize)) - } else if !errors.Is(err, notImplementedErr) { - // Don't report an error when support is not compiled in. - c.reportError(ch, c.rss, err) - c.reportError(ch, c.vsize, err) - } - - if fds, err := getOpenFileCount(); err == nil { - ch <- MustNewConstMetric(c.openFDs, GaugeValue, fds) - } else { - c.reportError(ch, c.openFDs, err) - } - - if openFiles, err := getSoftLimit(syscall.RLIMIT_NOFILE); err == nil { - ch <- MustNewConstMetric(c.maxFDs, GaugeValue, float64(openFiles)) - } else { - c.reportError(ch, c.maxFDs, err) - } - - if addressSpace, err := getSoftLimit(syscall.RLIMIT_AS); err == nil { - ch <- MustNewConstMetric(c.maxVsize, GaugeValue, float64(addressSpace)) - } else { - c.reportError(ch, c.maxVsize, err) - } - - // TODO: socket(PF_SYSTEM) to fetch "com.apple.network.statistics" might - // be able to get the per-process network send/receive counts. -} diff --git a/vendor/github.com/prometheus/client_golang/prometheus/process_collector_wasip1_js.go b/vendor/github.com/prometheus/client_golang/prometheus/process_collector_js.go similarity index 57% rename from vendor/github.com/prometheus/client_golang/prometheus/process_collector_wasip1_js.go rename to vendor/github.com/prometheus/client_golang/prometheus/process_collector_js.go index c68f7f85187..b1e363d6cf6 100644 --- a/vendor/github.com/prometheus/client_golang/prometheus/process_collector_wasip1_js.go +++ b/vendor/github.com/prometheus/client_golang/prometheus/process_collector_js.go @@ -1,4 +1,4 @@ -// Copyright 2023 The Prometheus Authors +// Copyright 2019 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 @@ -11,8 +11,8 @@ // See the License for the specific language governing permissions and // limitations under the License. -//go:build wasip1 || js -// +build wasip1 js +//go:build js +// +build js package prometheus @@ -21,13 +21,6 @@ func canCollectProcess() bool { } func (c *processCollector) processCollect(ch chan<- Metric) { - c.errorCollectFn(ch) -} - -// describe returns all descriptions of the collector for wasip1 and js. -// Ensure that this list of descriptors is kept in sync with the metrics collected -// in the processCollect method. Any changes to the metrics in processCollect -// (such as adding or removing metrics) should be reflected in this list of descriptors. -func (c *processCollector) describe(ch chan<- *Desc) { - c.errorDescribeFn(ch) + // noop on this platform + return } diff --git a/vendor/github.com/prometheus/client_golang/prometheus/process_collector_nocgo_darwin.go b/vendor/github.com/prometheus/client_golang/prometheus/process_collector_nocgo_darwin.go deleted file mode 100644 index 5165047311e..00000000000 --- a/vendor/github.com/prometheus/client_golang/prometheus/process_collector_nocgo_darwin.go +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright 2024 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 darwin && !cgo - -package prometheus - -func getMemory() (*memoryInfo, error) { - return nil, notImplementedErr -} - -// describe returns all descriptions of the collector for Darwin. -// Ensure that this list of descriptors is kept in sync with the metrics collected -// in the processCollect method. Any changes to the metrics in processCollect -// (such as adding or removing metrics) should be reflected in this list of descriptors. -func (c *processCollector) describe(ch chan<- *Desc) { - ch <- c.cpuTotal - ch <- c.openFDs - ch <- c.maxFDs - ch <- c.maxVsize - ch <- c.startTime - - /* the process could be collected but not implemented yet - ch <- c.rss - ch <- c.vsize - ch <- c.inBytes - ch <- c.outBytes - */ -} diff --git a/vendor/github.com/prometheus/client_golang/prometheus/process_collector_other.go b/vendor/github.com/prometheus/client_golang/prometheus/process_collector_other.go index 9f4b130befa..14d56d2d068 100644 --- a/vendor/github.com/prometheus/client_golang/prometheus/process_collector_other.go +++ b/vendor/github.com/prometheus/client_golang/prometheus/process_collector_other.go @@ -11,8 +11,8 @@ // See the License for the specific language governing permissions and // limitations under the License. -//go:build !windows && !js && !wasip1 && !darwin -// +build !windows,!js,!wasip1,!darwin +//go:build !windows && !js && !wasip1 +// +build !windows,!js,!wasip1 package prometheus @@ -78,19 +78,3 @@ func (c *processCollector) processCollect(ch chan<- Metric) { c.reportError(ch, nil, err) } } - -// describe returns all descriptions of the collector for others than windows, js, wasip1 and darwin. -// Ensure that this list of descriptors is kept in sync with the metrics collected -// in the processCollect method. Any changes to the metrics in processCollect -// (such as adding or removing metrics) should be reflected in this list of descriptors. -func (c *processCollector) describe(ch chan<- *Desc) { - ch <- c.cpuTotal - ch <- c.openFDs - ch <- c.maxFDs - ch <- c.vsize - ch <- c.maxVsize - ch <- c.rss - ch <- c.startTime - ch <- c.inBytes - ch <- c.outBytes -} diff --git a/vendor/github.com/prometheus/client_golang/prometheus/process_collector_wasip1.go b/vendor/github.com/prometheus/client_golang/prometheus/process_collector_wasip1.go new file mode 100644 index 00000000000..d8d9a6d7a2f --- /dev/null +++ b/vendor/github.com/prometheus/client_golang/prometheus/process_collector_wasip1.go @@ -0,0 +1,26 @@ +// Copyright 2023 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 wasip1 +// +build wasip1 + +package prometheus + +func canCollectProcess() bool { + return false +} + +func (*processCollector) processCollect(chan<- Metric) { + // noop on this platform + return +} diff --git a/vendor/github.com/prometheus/client_golang/prometheus/process_collector_windows.go b/vendor/github.com/prometheus/client_golang/prometheus/process_collector_windows.go index fa474289ef8..f973398df2d 100644 --- a/vendor/github.com/prometheus/client_golang/prometheus/process_collector_windows.go +++ b/vendor/github.com/prometheus/client_golang/prometheus/process_collector_windows.go @@ -79,10 +79,14 @@ func getProcessHandleCount(handle windows.Handle) (uint32, error) { } func (c *processCollector) processCollect(ch chan<- Metric) { - h := windows.CurrentProcess() + h, err := windows.GetCurrentProcess() + if err != nil { + c.reportError(ch, nil, err) + return + } var startTime, exitTime, kernelTime, userTime windows.Filetime - err := windows.GetProcessTimes(h, &startTime, &exitTime, &kernelTime, &userTime) + err = windows.GetProcessTimes(h, &startTime, &exitTime, &kernelTime, &userTime) if err != nil { c.reportError(ch, nil, err) return @@ -107,19 +111,6 @@ func (c *processCollector) processCollect(ch chan<- Metric) { ch <- MustNewConstMetric(c.maxFDs, GaugeValue, float64(16*1024*1024)) // Windows has a hard-coded max limit, not per-process. } -// describe returns all descriptions of the collector for windows. -// Ensure that this list of descriptors is kept in sync with the metrics collected -// in the processCollect method. Any changes to the metrics in processCollect -// (such as adding or removing metrics) should be reflected in this list of descriptors. -func (c *processCollector) describe(ch chan<- *Desc) { - ch <- c.cpuTotal - ch <- c.openFDs - ch <- c.maxFDs - ch <- c.vsize - ch <- c.rss - ch <- c.startTime -} - func fileTimeToSeconds(ft windows.Filetime) float64 { return float64(uint64(ft.HighDateTime)<<32+uint64(ft.LowDateTime)) / 1e7 } diff --git a/vendor/github.com/prometheus/client_golang/prometheus/promhttp/http.go b/vendor/github.com/prometheus/client_golang/prometheus/promhttp/http.go index 28eed26727a..e598e66e688 100644 --- a/vendor/github.com/prometheus/client_golang/prometheus/promhttp/http.go +++ b/vendor/github.com/prometheus/client_golang/prometheus/promhttp/http.go @@ -207,13 +207,7 @@ func HandlerForTransactional(reg prometheus.TransactionalGatherer, opts HandlerO if encodingHeader != string(Identity) { rsp.Header().Set(contentEncodingHeader, encodingHeader) } - - var enc expfmt.Encoder - if opts.EnableOpenMetricsTextCreatedSamples { - enc = expfmt.NewEncoder(w, contentType, expfmt.WithCreatedLines()) - } else { - enc = expfmt.NewEncoder(w, contentType) - } + enc := expfmt.NewEncoder(w, contentType) // handleError handles the error according to opts.ErrorHandling // and returns true if we have to abort after the handling. @@ -414,21 +408,6 @@ type HandlerOpts struct { // (which changes the identity of the resulting series on the Prometheus // server). EnableOpenMetrics bool - // EnableOpenMetricsTextCreatedSamples specifies if this handler should add, extra, synthetic - // Created Timestamps for counters, histograms and summaries, which for the current - // version of OpenMetrics are defined as extra series with the same name and "_created" - // suffix. See also the OpenMetrics specification for more details - // https://github.com/prometheus/OpenMetrics/blob/v1.0.0/specification/OpenMetrics.md#counter-1 - // - // Created timestamps are used to improve the accuracy of reset detection, - // but the way it's designed in OpenMetrics 1.0 it also dramatically increases cardinality - // if the scraper does not handle those metrics correctly (converting to created timestamp - // instead of leaving those series as-is). New OpenMetrics versions might improve - // this situation. - // - // Prometheus introduced the feature flag 'created-timestamp-zero-ingestion' - // in version 2.50.0 to handle this situation. - EnableOpenMetricsTextCreatedSamples bool // ProcessStartTime allows setting process start timevalue that will be exposed // with "Process-Start-Time-Unix" response header along with the metrics // payload. This allow callers to have efficient transformations to cumulative diff --git a/vendor/github.com/prometheus/client_golang/prometheus/summary.go b/vendor/github.com/prometheus/client_golang/prometheus/summary.go index 76a9e12f4a4..1ab0e479655 100644 --- a/vendor/github.com/prometheus/client_golang/prometheus/summary.go +++ b/vendor/github.com/prometheus/client_golang/prometheus/summary.go @@ -243,7 +243,6 @@ func newSummary(desc *Desc, opts SummaryOpts, labelValues ...string) Summary { s := &summary{ desc: desc, - now: opts.now, objectives: opts.Objectives, sortedObjectives: make([]float64, 0, len(opts.Objectives)), @@ -281,8 +280,6 @@ type summary struct { desc *Desc - now func() time.Time - objectives map[float64]float64 sortedObjectives []float64 @@ -310,7 +307,7 @@ func (s *summary) Observe(v float64) { s.bufMtx.Lock() defer s.bufMtx.Unlock() - now := s.now() + now := time.Now() if now.After(s.hotBufExpTime) { s.asyncFlush(now) } @@ -329,7 +326,7 @@ func (s *summary) Write(out *dto.Metric) error { s.bufMtx.Lock() s.mtx.Lock() // Swap bufs even if hotBuf is empty to set new hotBufExpTime. - s.swapBufs(s.now()) + s.swapBufs(time.Now()) s.bufMtx.Unlock() s.flushColdBuf() @@ -471,9 +468,13 @@ func (s *noObjectivesSummary) Observe(v float64) { n := atomic.AddUint64(&s.countAndHotIdx, 1) hotCounts := s.counts[n>>63] - atomicUpdateFloat(&hotCounts.sumBits, func(oldVal float64) float64 { - return oldVal + v - }) + for { + oldBits := atomic.LoadUint64(&hotCounts.sumBits) + newBits := math.Float64bits(math.Float64frombits(oldBits) + v) + if atomic.CompareAndSwapUint64(&hotCounts.sumBits, oldBits, newBits) { + break + } + } // Increment count last as we take it as a signal that the observation // is complete. atomic.AddUint64(&hotCounts.count, 1) @@ -515,13 +516,14 @@ func (s *noObjectivesSummary) Write(out *dto.Metric) error { // Finally add all the cold counts to the new hot counts and reset the cold counts. atomic.AddUint64(&hotCounts.count, count) atomic.StoreUint64(&coldCounts.count, 0) - - // Use atomicUpdateFloat to update hotCounts.sumBits atomically. - atomicUpdateFloat(&hotCounts.sumBits, func(oldVal float64) float64 { - return oldVal + sum.GetSampleSum() - }) - atomic.StoreUint64(&coldCounts.sumBits, 0) - + for { + oldBits := atomic.LoadUint64(&hotCounts.sumBits) + newBits := math.Float64bits(math.Float64frombits(oldBits) + sum.GetSampleSum()) + if atomic.CompareAndSwapUint64(&hotCounts.sumBits, oldBits, newBits) { + atomic.StoreUint64(&coldCounts.sumBits, 0) + break + } + } return nil } diff --git a/vendor/modules.txt b/vendor/modules.txt index a529a03d954..90fd8b95e9c 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -211,8 +211,8 @@ github.com/pkg/errors # github.com/pmezard/go-difflib v1.0.0 ## explicit github.com/pmezard/go-difflib/difflib -# github.com/prometheus/client_golang v1.21.0 -## explicit; go 1.21 +# github.com/prometheus/client_golang v1.20.5 +## explicit; go 1.20 github.com/prometheus/client_golang/internal/github.com/golang/gddo/httputil github.com/prometheus/client_golang/internal/github.com/golang/gddo/httputil/header github.com/prometheus/client_golang/prometheus From fb903f5e8b808ab86ac82aa4446bf9d2b7479eac Mon Sep 17 00:00:00 2001 From: trafalgarzzz Date: Thu, 20 Mar 2025 10:03:04 +0800 Subject: [PATCH 2/3] go fmt Signed-off-by: trafalgarzzz --- pkg/ddc/alluxio/cache.go | 4 +-- pkg/ddc/alluxio/load_data.go | 3 ++- pkg/ddc/alluxio/master_test.go | 3 ++- pkg/ddc/alluxio/transform_resources.go | 8 +++--- pkg/ddc/alluxio/transform_resources_test.go | 22 ++++++++-------- pkg/ddc/alluxio/transform_test.go | 24 ++++++++++-------- pkg/ddc/alluxio/transform_ufs_test.go | 8 +++--- pkg/ddc/alluxio/utils_test.go | 28 ++++++++++----------- pkg/ddc/jindo/dataset_test.go | 4 +-- pkg/ddc/jindo/delete_volume_test.go | 26 +++++++++---------- pkg/ddc/juicefs/data_process_test.go | 2 +- pkg/ddc/juicefs/datasetinfo_parser.go | 20 +++++++-------- pkg/ddc/juicefs/datasetinfo_parser_test.go | 2 +- pkg/ddc/juicefs/delete_volume_test.go | 19 +++++++------- 14 files changed, 89 insertions(+), 84 deletions(-) diff --git a/pkg/ddc/alluxio/cache.go b/pkg/ddc/alluxio/cache.go index 651d880c51a..4ad78335df1 100644 --- a/pkg/ddc/alluxio/cache.go +++ b/pkg/ddc/alluxio/cache.go @@ -68,13 +68,13 @@ func (e *AlluxioEngine) queryCacheStatus() (states cacheStates, err error) { // - When the Dataset's UfsTotal field is empty // - When the Dataset's UfsTotal field contains the metadata sync pending message // The cached percentage is calculated as (cached bytes / UfsTotal bytes) * 100. -// +// // Parameters: // - dataset (v1alpha1.Dataset): Pointer to the Dataset object containing UFS metadata. // The Status.UfsTotal field must be a valid human-readable size string (e.g. "10GiB") // - states (cacheStates): Pointer to the cache state structure that will be modified in-place. // The cached field must be a valid human-readable size string (e.g. "5GiB") -// +// // Returns: // - None: Modifies the states.cachedPercentage field directly with formatted percentage string. // The percentage is stored as a string using cachedPercentageFormat (e.g. "45.60%") diff --git a/pkg/ddc/alluxio/load_data.go b/pkg/ddc/alluxio/load_data.go index 1c6d775e828..5bfd8c6fad7 100644 --- a/pkg/ddc/alluxio/load_data.go +++ b/pkg/ddc/alluxio/load_data.go @@ -175,7 +175,8 @@ func (e *AlluxioEngine) genDataLoadValue(image string, targetDataset *datav1alph // It obtains master pod details, creates file utilities, and checks readiness. // // Returns: -// ready bool - Runtime readiness status (true = ready, false = not ready). +// +// ready bool - Runtime readiness status (true = ready, false = not ready). func (e *AlluxioEngine) CheckRuntimeReady() (ready bool) { podName, containerName := e.getMasterPodInfo() fileUtils := operations.NewAlluxioFileUtils(podName, containerName, e.namespace, e.Log) diff --git a/pkg/ddc/alluxio/master_test.go b/pkg/ddc/alluxio/master_test.go index ab13c51d948..4a52a0eec98 100644 --- a/pkg/ddc/alluxio/master_test.go +++ b/pkg/ddc/alluxio/master_test.go @@ -166,8 +166,9 @@ func TestCheckMasterReady(t *testing.T) { // TestShouldSetupMaster tests the ShouldSetupMaster function of AlluxioEngine. // Functionality: Verifies if the Alluxio master should be set up based on runtime status. -// Parameters: +// Parameters: // - t *testing.T: Standard testing object for test reporting and logging. +// // Return: None (testing function). // Notes: // - Uses fake client to simulate interactions with Kubernetes API. diff --git a/pkg/ddc/alluxio/transform_resources.go b/pkg/ddc/alluxio/transform_resources.go index cc9c4a402bd..4c089963062 100644 --- a/pkg/ddc/alluxio/transform_resources.go +++ b/pkg/ddc/alluxio/transform_resources.go @@ -48,14 +48,14 @@ func (e *AlluxioEngine) transformResourcesForMaster(runtime *datav1alpha1.Alluxi } // transformResourcesForWorker is responsible for transforming and setting resource limits for the Alluxio Worker component. -// This function updates the resource requirements for the Worker and JobWorker based on the runtime configuration +// This function updates the resource requirements for the Worker and JobWorker based on the runtime configuration // and ensures that memory requests meet the required constraints. // // Parameters: -// - runtime: *datav1alpha1.AlluxioRuntime, the runtime configuration of Alluxio, including resource definitions -// for Worker and JobWorker. +// - runtime: *datav1alpha1.AlluxioRuntime, the runtime configuration of Alluxio, including resource definitions +// for Worker and JobWorker. // - value: *Alluxio, the Alluxio runtime instance used to store the transformed resource information. -// +// // Return value: // - error: Returns an error if any issue occurs during resource transformation; otherwise, returns nil. func (e *AlluxioEngine) transformResourcesForWorker(runtime *datav1alpha1.AlluxioRuntime, value *Alluxio) error { diff --git a/pkg/ddc/alluxio/transform_resources_test.go b/pkg/ddc/alluxio/transform_resources_test.go index ca1ee2121e2..5e127c0f2c5 100644 --- a/pkg/ddc/alluxio/transform_resources_test.go +++ b/pkg/ddc/alluxio/transform_resources_test.go @@ -218,8 +218,8 @@ func TestTransformResourcesForWorkerWithTieredStore(t *testing.T) { // Test cases structured to validate different tiered storage configurations var tests = []struct { - runtime *datav1alpha1.AlluxioRuntime // Input Alluxio runtime configuration - alluxioValue *Alluxio // Expected output configuration + runtime *datav1alpha1.AlluxioRuntime // Input Alluxio runtime configuration + alluxioValue *Alluxio // Expected output configuration }{ {&datav1alpha1.AlluxioRuntime{ ObjectMeta: metav1.ObjectMeta{ @@ -229,20 +229,20 @@ func TestTransformResourcesForWorkerWithTieredStore(t *testing.T) { Spec: datav1alpha1.AlluxioRuntimeSpec{ TieredStore: datav1alpha1.TieredStore{ Levels: []datav1alpha1.Level{{ - MediumType: common.Memory, // Memory-based tiered storage configuration + MediumType: common.Memory, // Memory-based tiered storage configuration Quota: &result, // 20Gi quota allocation }}, }, }, }, &Alluxio{ - Properties: map[string]string{}, // Expected empty properties map + Properties: map[string]string{}, // Expected empty properties map }}, } // Iterate through test cases to validate transformation logic for _, test := range tests { // Initialize test environment with mocked dependencies engine := &AlluxioEngine{ - Log: fake.NullLogger(), // Discard logging output + Log: fake.NullLogger(), // Discard logging output name: "test", namespace: "test", } @@ -472,12 +472,12 @@ func TestTransformResourcesForWorkerWithOnlyRequest(t *testing.T) { // resource requests are handled as expected. // // The function performs the following steps: -// 1. Defines resource requirements with limits for memory (20Gi) and CPU (500m). -// 2. Sets up test cases to validate the transformation logic, including scenarios with and without -// tiered store configurations. -// 3. Initializes an AlluxioEngine instance with a fake client and runtime objects for testing. -// 4. Transforms the resource requirements for the worker using the AlluxioEngine. -// 5. Validates the transformed resource limits and requests against the expected results. +// 1. Defines resource requirements with limits for memory (20Gi) and CPU (500m). +// 2. Sets up test cases to validate the transformation logic, including scenarios with and without +// tiered store configurations. +// 3. Initializes an AlluxioEngine instance with a fake client and runtime objects for testing. +// 4. Transforms the resource requirements for the worker using the AlluxioEngine. +// 5. Validates the transformed resource limits and requests against the expected results. // // Test cases include: // - A scenario where tiered store configuration is provided, ensuring memory limits and requests are set correctly. diff --git a/pkg/ddc/alluxio/transform_test.go b/pkg/ddc/alluxio/transform_test.go index 5acb920a096..a83a524ee63 100755 --- a/pkg/ddc/alluxio/transform_test.go +++ b/pkg/ddc/alluxio/transform_test.go @@ -183,9 +183,9 @@ func TestTransformMaster(t *testing.T) { } } -// TestTransformWorkers verifies that the transformWorkers function correctly transforms -// the worker configuration of AlluxioRuntime into the expected Alluxio structure. -// It tests different network modes, node selectors, and image pull secrets to ensure +// TestTransformWorkers verifies that the transformWorkers function correctly transforms +// the worker configuration of AlluxioRuntime into the expected Alluxio structure. +// It tests different network modes, node selectors, and image pull secrets to ensure // correct transformation behavior. func TestTransformWorkers(t *testing.T) { testCases := map[string]struct { @@ -588,19 +588,21 @@ func TestGetMediumTypeFromVolumeSource(t *testing.T) { } } -// TestAlluxioEngine_allocateSinglePort is a unit test function that tests +// TestAlluxioEngine_allocateSinglePort is a unit test function that tests // the `allocateSinglePort` method of the `AlluxioEngine` struct. -// The function verifies the behavior of port allocation for Alluxio master +// The function verifies the behavior of port allocation for Alluxio master // and worker components under different scenarios, -// including when properties are set, unset, or when runtime specifications +// including when properties are set, unset, or when runtime specifications // are provided. -// +// // Parameters: -// - t: A testing.T object provided by the Go testing framework, used to +// - t: A testing.T object provided by the Go testing framework, used to +// // manage test state and support formatted test logs. // // Returns: -// - None. The function is a test function and does not return any value. +// - None. The function is a test function and does not return any value. +// // It reports test failures using the `t.Errorf` method. func TestAlluxioEngine_allocateSinglePort(t *testing.T) { // Define the fields required for the AlluxioEngine struct. @@ -902,10 +904,10 @@ func TestAlluxioEngine_allocatePorts(t *testing.T) { // // Test Cases: // 1. "master properties is not null": -// - Ensures that when master-specific properties exist, they override the global properties. +// - Ensures that when master-specific properties exist, they override the global properties. // // 2. "properties is not null for master": -// - Ensures that both master-specific and additional global properties are correctly handled. +// - Ensures that both master-specific and additional global properties are correctly handled. // // The function iterates over multiple test cases and checks if the transformed properties // match the expected values. If the transformation does not produce the expected result, the test fails. diff --git a/pkg/ddc/alluxio/transform_ufs_test.go b/pkg/ddc/alluxio/transform_ufs_test.go index 7ae5394355b..efb2cefdce0 100644 --- a/pkg/ddc/alluxio/transform_ufs_test.go +++ b/pkg/ddc/alluxio/transform_ufs_test.go @@ -23,8 +23,8 @@ import ( v1 "k8s.io/api/core/v1" ) -// TestTransformDatasetToVolume is a unit test function that verifies the transformation of a Dataset into a UFSPath -// in the Alluxio runtime. It ensures that the Dataset's mount points are correctly converted into corresponding +// TestTransformDatasetToVolume is a unit test function that verifies the transformation of a Dataset into a UFSPath +// in the Alluxio runtime. It ensures that the Dataset's mount points are correctly converted into corresponding // container and host paths. // // Parameters: @@ -60,7 +60,7 @@ func TestTransformDatasetToVolume(t *testing.T) { }}, }, }, &Alluxio{}, ufsPath}, - + // Test case 2: Mount with a path specified {&datav1alpha1.AlluxioRuntime{}, &datav1alpha1.Dataset{ Spec: datav1alpha1.DatasetSpec{ @@ -72,7 +72,7 @@ func TestTransformDatasetToVolume(t *testing.T) { }, }, &Alluxio{}, ufsPath1}, } - + // Iterate through all test cases and run the test. for _, test := range tests { // Create an instance of AlluxioEngine to call the function under test. diff --git a/pkg/ddc/alluxio/utils_test.go b/pkg/ddc/alluxio/utils_test.go index 32db3ab0ca5..9a10102e2a2 100644 --- a/pkg/ddc/alluxio/utils_test.go +++ b/pkg/ddc/alluxio/utils_test.go @@ -222,17 +222,17 @@ func Test_lookUpUsedCapacity(t *testing.T) { node corev1.Node usedCapacityMap map[string]int64 } - + internalIP := "192.168.1.147" var usageForInternalIP int64 = 1024 - + internalHost := "slave001" var usageForInternalHost int64 = 4096 - + usedCapacityMap := map[string]int64{} usedCapacityMap[internalIP] = usageForInternalIP usedCapacityMap[internalHost] = usageForInternalHost - + tests := []struct { name string args args @@ -485,16 +485,16 @@ func TestGetMasterPod(t *testing.T) { } } -// TestGetMasterStatefulset tests the getMasterStatefulset method of the AlluxioEngine struct. -// It verifies that the method correctly retrieves the expected StatefulSet based on the provided -// AlluxioRuntime, name, and namespace. The test includes a sample runtime and expected -// StatefulSet, checking for both successful retrieval and error scenarios. -// -// Parameters: -// - t: The test framework's context, which provides methods for logging and error reporting. -// -// Returns: -// - The test does not return any value, but it reports errors using the t.Error and +// TestGetMasterStatefulset tests the getMasterStatefulset method of the AlluxioEngine struct. +// It verifies that the method correctly retrieves the expected StatefulSet based on the provided +// AlluxioRuntime, name, and namespace. The test includes a sample runtime and expected +// StatefulSet, checking for both successful retrieval and error scenarios. +// +// Parameters: +// - t: The test framework's context, which provides methods for logging and error reporting. +// +// Returns: +// - The test does not return any value, but it reports errors using the t.Error and // t.Errorf methods to indicate whether the test passed or failed. func TestGetMasterStatefulset(t *testing.T) { type fields struct { diff --git a/pkg/ddc/jindo/dataset_test.go b/pkg/ddc/jindo/dataset_test.go index 25f4136a92f..3a412675305 100644 --- a/pkg/ddc/jindo/dataset_test.go +++ b/pkg/ddc/jindo/dataset_test.go @@ -253,8 +253,8 @@ func TestUpdateDatasetStatus(t *testing.T) { } } -// TestBindToDataset tests the BindToDataset method of JindoEngine to verify whether it can correctly bind the dataset to the runtime -// and update the dataset's cache state and HCFS status. The test creates mock Dataset and JindoRuntime objects, +// TestBindToDataset tests the BindToDataset method of JindoEngine to verify whether it can correctly bind the dataset to the runtime +// and update the dataset's cache state and HCFS status. The test creates mock Dataset and JindoRuntime objects, // uses a fake client to simulate operations, and finally checks if the dataset's Phase, CacheStates, and HCFSStatus match the expected results. func TestBindToDataset(t *testing.T) { testDatasetInputs := []*datav1alpha1.Dataset{ diff --git a/pkg/ddc/jindo/delete_volume_test.go b/pkg/ddc/jindo/delete_volume_test.go index 4bb0db939a7..21ad222867f 100644 --- a/pkg/ddc/jindo/delete_volume_test.go +++ b/pkg/ddc/jindo/delete_volume_test.go @@ -83,19 +83,19 @@ func doTestCases(testCases []TestCase, t *testing.T) { // // Test Strategy: // 1. Setup test environment with mocked Kubernetes resources: -// - PVs with 'CreatedBy=fluid' annotation to simulate Fluid-managed persistent volumes -// - PVCs with different configurations (normal vs error cases) -// 2. Create 3 test scenarios using parameterized test pattern: -// Case 1: Normal deletion (JindoEngineCommon) -// - Input: Valid PV/PVC without conflicting annotations -// - Expected: Successful deletion (isDeleted=true, isErr=false) -// Case 2: Protected PVC deletion (JindoEngineErr) -// - Input: PVC with 'CreatedBy=fluid' annotation (protected resource) -// - Expected: Failed deletion (isErr=true) -// Case 3: Missing runtime scenario (JindoEngineNoRunTime) -// - Input: Engine with runtime=false configuration -// - Expected: Failed deletion (isErr=true) -// 3. Verification: Uses doTestCases() helper to validate deletion outcomes against expectations +// - PVs with 'CreatedBy=fluid' annotation to simulate Fluid-managed persistent volumes +// - PVCs with different configurations (normal vs error cases) +// 2. Create 3 test scenarios using parameterized test pattern: +// Case 1: Normal deletion (JindoEngineCommon) +// - Input: Valid PV/PVC without conflicting annotations +// - Expected: Successful deletion (isDeleted=true, isErr=false) +// Case 2: Protected PVC deletion (JindoEngineErr) +// - Input: PVC with 'CreatedBy=fluid' annotation (protected resource) +// - Expected: Failed deletion (isErr=true) +// Case 3: Missing runtime scenario (JindoEngineNoRunTime) +// - Input: Engine with runtime=false configuration +// - Expected: Failed deletion (isErr=true) +// 3. Verification: Uses doTestCases() helper to validate deletion outcomes against expectations // // Test Resources: // - fake.NewFakeClientWithScheme: Simulates Kubernetes API server with predefined resources diff --git a/pkg/ddc/juicefs/data_process_test.go b/pkg/ddc/juicefs/data_process_test.go index 87487c6f707..13597c034f5 100644 --- a/pkg/ddc/juicefs/data_process_test.go +++ b/pkg/ddc/juicefs/data_process_test.go @@ -31,7 +31,7 @@ import ( // It verifies the behavior of the function under different scenarios, including invalid input and missing datasets. // // Parameters: -// - t: The testing context used for reporting test failures and logging. +// - t: The testing context used for reporting test failures and logging. func TestJuiceFSEngine_generateDataProcessValueFile(t *testing.T) { // 1. Define a sample dataset and dataProcess object for testing. dataset := &datav1alpha1.Dataset{ diff --git a/pkg/ddc/juicefs/datasetinfo_parser.go b/pkg/ddc/juicefs/datasetinfo_parser.go index 3848b0026c8..95013d63bf0 100644 --- a/pkg/ddc/juicefs/datasetinfo_parser.go +++ b/pkg/ddc/juicefs/datasetinfo_parser.go @@ -67,21 +67,21 @@ func GetFSInfoFromConfigMap(client client.Client, name string, namespace string) return parseFSInfoFromConfigMap(configMap) } -// parseFSInfoFromConfigMap extracts file system configuration information -// from the provided ConfigMap. It parses the data field of the ConfigMap -// into a JuiceFS structure and populates the returned map with relevant -// configuration details. If the parsing fails or the data field is missing, +// parseFSInfoFromConfigMap extracts file system configuration information +// from the provided ConfigMap. It parses the data field of the ConfigMap +// into a JuiceFS structure and populates the returned map with relevant +// configuration details. If the parsing fails or the data field is missing, // an error is returned. // // Parameters: -// - configMap: A pointer to a v1.ConfigMap object that contains the -// configuration data. +// - configMap: A pointer to a v1.ConfigMap object that contains the +// configuration data. // // Returns: -// - info: A map containing parsed configuration details such as MetaUrlSecret, -// TokenSecret, AccessKeySecret, SecretKeySecret, FormatCmd, Name, and Edition. -// - err: An error if the data parsing process fails or if the required data -// field is missing. +// - info: A map containing parsed configuration details such as MetaUrlSecret, +// TokenSecret, AccessKeySecret, SecretKeySecret, FormatCmd, Name, and Edition. +// - err: An error if the data parsing process fails or if the required data +// field is missing. func parseFSInfoFromConfigMap(configMap *v1.ConfigMap) (info map[string]string, err error) { var value JuiceFS info = map[string]string{} diff --git a/pkg/ddc/juicefs/datasetinfo_parser_test.go b/pkg/ddc/juicefs/datasetinfo_parser_test.go index 13973de3555..63c97e97b19 100644 --- a/pkg/ddc/juicefs/datasetinfo_parser_test.go +++ b/pkg/ddc/juicefs/datasetinfo_parser_test.go @@ -170,7 +170,7 @@ func TestGetFSInfoFromConfigMap(t *testing.T) { } // Test_parseFSInfoFromConfigMap is a unit test function for the parseFSInfoFromConfigMap method. -// It validates whether the function correctly extracts and parses dataset information +// It validates whether the function correctly extracts and parses dataset information // from a given Kubernetes ConfigMap. // // Steps: diff --git a/pkg/ddc/juicefs/delete_volume_test.go b/pkg/ddc/juicefs/delete_volume_test.go index d4f73d3e2c6..c73e35d59fa 100644 --- a/pkg/ddc/juicefs/delete_volume_test.go +++ b/pkg/ddc/juicefs/delete_volume_test.go @@ -41,14 +41,15 @@ type TestCase struct { // newTestJuiceEngine creates a JuiceFSEngine for testing // Parameters: -// - client: fake client +// - client: fake client // - name: the name of the JuiceFS engine // - namespace: the namespace of the JuiceFS engine // - withRunTime: whether the JuiceFS engine has runtime +// // Returns: // - JuiceFSEngine: the JuiceFS engine for testing func newTestJuiceEngine(client client.Client, name string, namespace string, withRunTime bool) *JuiceFSEngine { - // 1. Create a JuiceFSRuntime and RuntimeInfo + // 1. Create a JuiceFSRuntime and RuntimeInfo runTime := &datav1alpha1.JuiceFSRuntime{} runTimeInfo, _ := base.BuildRuntimeInfo(name, namespace, common.JuiceFSRuntime) // 2. If the JuiceFS engine does not have runtime, set the runtime and runtimeInfo to nil @@ -172,10 +173,10 @@ func TestJuiceFSEngine_DeleteVolume(t *testing.T) { doTestCases(testCases, t) } -// TestJuiceFSEngine_deleteFusePersistentVolume tests the deletion of a FUSE PersistentVolume -// in the JuiceFS engine. It creates test PersistentVolume objects and initializes -// JuiceFS engine instances with and without runtime. The function verifies if the -// PersistentVolume is correctly deleted and whether an error is expected based on +// TestJuiceFSEngine_deleteFusePersistentVolume tests the deletion of a FUSE PersistentVolume +// in the JuiceFS engine. It creates test PersistentVolume objects and initializes +// JuiceFS engine instances with and without runtime. The function verifies if the +// PersistentVolume is correctly deleted and whether an error is expected based on // the engine configuration. // // Test Scenario: @@ -223,17 +224,17 @@ func TestJuiceFSEngine_deleteFusePersistentVolume(t *testing.T) { // - Proper handling of PVC finalizers (e.g., kubernetes.io/pvc-protection) // - Failure scenarios when Runtime integration is disabled // - Interaction with mocked Kubernetes API using fake client -// +// // The test suite includes two primary cases: // 1. Normal deletion with Runtime enabled (expected success) // 2. Deletion failure when Runtime is disabled (simulates missing dependency) -// +// // Setup steps: // - Creates test PVCs with protection finalizer to simulate real-world conditions // - Uses deep copies to ensure test data isolation // - Configures fake client with predefined test objects for controlled testing // - Exercises both enabled/disabled Runtime engine variations -// +// // This test ensures JuiceFS Engine correctly handles PVC lifecycle operations while respecting Kubernetes resource protection mechanisms. func TestJuiceFSEngine_deleteFusePersistentVolumeClaim(t *testing.T) { testPVCInputs := []*v1.PersistentVolumeClaim{ From 7933b71c74ea5866672be4cd08348ad8c81e927a Mon Sep 17 00:00:00 2001 From: trafalgarzzz Date: Thu, 20 Mar 2025 10:31:55 +0800 Subject: [PATCH 3/3] Upgrade go.mod to 1.23.7 Signed-off-by: trafalgarzzz --- go.mod | 4 +--- pkg/ddc/jindo/delete_volume_test.go | 16 ++++++++-------- 2 files changed, 9 insertions(+), 11 deletions(-) diff --git a/go.mod b/go.mod index b0d3b25af25..5a826256807 100644 --- a/go.mod +++ b/go.mod @@ -1,8 +1,6 @@ module github.com/fluid-cloudnative/fluid -go 1.23.0 - -toolchain go1.23.7 +go 1.23.7 replace k8s.io/api => k8s.io/api v0.29.5 diff --git a/pkg/ddc/jindo/delete_volume_test.go b/pkg/ddc/jindo/delete_volume_test.go index 21ad222867f..ff3d64a7f06 100644 --- a/pkg/ddc/jindo/delete_volume_test.go +++ b/pkg/ddc/jindo/delete_volume_test.go @@ -85,17 +85,17 @@ func doTestCases(testCases []TestCase, t *testing.T) { // 1. Setup test environment with mocked Kubernetes resources: // - PVs with 'CreatedBy=fluid' annotation to simulate Fluid-managed persistent volumes // - PVCs with different configurations (normal vs error cases) -// 2. Create 3 test scenarios using parameterized test pattern: +// 2. Create 3 test scenarios using parameterized test pattern: // Case 1: Normal deletion (JindoEngineCommon) -// - Input: Valid PV/PVC without conflicting annotations -// - Expected: Successful deletion (isDeleted=true, isErr=false) +// - Input: Valid PV/PVC without conflicting annotations +// - Expected: Successful deletion (isDeleted=true, isErr=false) // Case 2: Protected PVC deletion (JindoEngineErr) -// - Input: PVC with 'CreatedBy=fluid' annotation (protected resource) -// - Expected: Failed deletion (isErr=true) +// - Input: PVC with 'CreatedBy=fluid' annotation (protected resource) +// - Expected: Failed deletion (isErr=true) // Case 3: Missing runtime scenario (JindoEngineNoRunTime) -// - Input: Engine with runtime=false configuration -// - Expected: Failed deletion (isErr=true) -// 3. Verification: Uses doTestCases() helper to validate deletion outcomes against expectations +// - Input: Engine with runtime=false configuration +// - Expected: Failed deletion (isErr=true) +// 3. Verification: Uses doTestCases() helper to validate deletion outcomes against expectations // // Test Resources: // - fake.NewFakeClientWithScheme: Simulates Kubernetes API server with predefined resources