inspektor-gadget
89 строк · 2.3 Кб
1// Copyright 2023 The Inspektor Gadget authors
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15package prometheus
16
17import (
18"math"
19"strings"
20
21"github.com/shopspring/decimal"
22log "github.com/sirupsen/logrus"
23
24"github.com/inspektor-gadget/inspektor-gadget/pkg/prometheus/config"
25)
26
27type BucketType string
28
29const (
30BucketTypeExp2 BucketType = "exp2"
31BucketTypeLinear BucketType = "linear"
32)
33
34var AllBucketTypes = map[string]struct{}{
35string(BucketTypeExp2): {},
36string(BucketTypeLinear): {},
37}
38
39type BucketConfig struct {
40Type BucketType
41Min int
42Max int
43Multiplier float64
44}
45
46func bucketConfigsFromConfig(c *config.Config) map[string]*BucketConfig {
47buckets := make(map[string]*BucketConfig)
48for _, m := range c.Metrics {
49if strings.ToLower(m.Type) == "histogram" {
50buckets[m.Name] = &BucketConfig{
51Type: BucketType(m.Bucket.Type),
52Min: m.Bucket.Min,
53Max: m.Bucket.Max,
54Multiplier: m.Bucket.Multiplier,
55}
56}
57}
58return buckets
59}
60
61func (c *BucketConfig) buckets() []float64 {
62switch c.Type {
63case BucketTypeExp2:
64return exp2Buckets(c.Min, c.Max, c.Multiplier)
65case BucketTypeLinear:
66return linearBuckets(c.Min, c.Max, c.Multiplier)
67default:
68log.Warnf("unknown bucket type: %s", c.Type)
69return nil
70}
71}
72
73func exp2Buckets(min, max int, multiplier float64) []float64 {
74buckets := make([]float64, 0, max-min)
75for i := min; i < max; i++ {
76buckets = append(buckets, math.Pow(2, float64(i))*multiplier)
77}
78return buckets
79}
80
81func linearBuckets(min, max int, multiplier float64) []float64 {
82buckets := make([]float64, 0, max-min)
83for i := min; i < max; i++ {
84bucketId := decimal.NewFromInt(int64(i))
85bucketValue, _ := bucketId.Mul(decimal.NewFromFloat(multiplier)).Float64()
86buckets = append(buckets, bucketValue)
87}
88return buckets
89}
90