aboutsummaryrefslogtreecommitdiffstats
path: root/library/go/core/metrics/solomon/histogram.go
blob: 6f4d3629e09c68e6e718f6546f9ab2f1c4413e50 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
package solomon

import (
	"encoding/binary"
	"encoding/json"
	"io"
	"sort"
	"sync"
	"time"

	"github.com/ydb-platform/ydb/library/go/core/metrics"
	"github.com/ydb-platform/ydb/library/go/core/xerrors"
	"go.uber.org/atomic"
)

var (
	_ metrics.Histogram = (*Histogram)(nil)
	_ metrics.Timer     = (*Histogram)(nil)
	_ Metric            = (*Histogram)(nil)
)

type Histogram struct {
	name         string
	metricType   metricType
	tags         map[string]string
	bucketBounds []float64
	bucketValues []int64
	infValue     atomic.Int64
	mutex        sync.Mutex
	timestamp    *time.Time
	useNameTag   bool
}

type histogram struct {
	Bounds  []float64 `json:"bounds"`
	Buckets []int64   `json:"buckets"`
	Inf     int64     `json:"inf,omitempty"`
}

func (h *histogram) writeHistogram(w io.Writer) error {
	err := writeULEB128(w, uint32(len(h.Buckets)))
	if err != nil {
		return xerrors.Errorf("writeULEB128 size histogram buckets failed: %w", err)
	}

	for _, upperBound := range h.Bounds {
		err = binary.Write(w, binary.LittleEndian, float64(upperBound))
		if err != nil {
			return xerrors.Errorf("binary.Write upper bound failed: %w", err)
		}
	}

	for _, bucketValue := range h.Buckets {
		err = binary.Write(w, binary.LittleEndian, uint64(bucketValue))
		if err != nil {
			return xerrors.Errorf("binary.Write histogram buckets failed: %w", err)
		}
	}
	return nil
}

func (h *Histogram) RecordValue(value float64) {
	boundIndex := sort.SearchFloat64s(h.bucketBounds, value)

	if boundIndex < len(h.bucketValues) {
		h.mutex.Lock()
		h.bucketValues[boundIndex] += 1
		h.mutex.Unlock()
	} else {
		h.infValue.Inc()
	}
}

func (h *Histogram) RecordDuration(value time.Duration) {
	h.RecordValue(value.Seconds())
}

func (h *Histogram) Reset() {
	h.mutex.Lock()
	defer h.mutex.Unlock()

	h.bucketValues = make([]int64, len(h.bucketValues))
	h.infValue.Store(0)
}

func (h *Histogram) Name() string {
	return h.name
}

func (h *Histogram) getType() metricType {
	return h.metricType
}

func (h *Histogram) getLabels() map[string]string {
	return h.tags
}

func (h *Histogram) getValue() interface{} {
	return histogram{
		Bounds:  h.bucketBounds,
		Buckets: h.bucketValues,
	}
}

func (h *Histogram) getTimestamp() *time.Time {
	return h.timestamp
}

func (h *Histogram) getNameTag() string {
	if h.useNameTag {
		return "name"
	} else {
		return "sensor"
	}
}

// MarshalJSON implements json.Marshaler.
func (h *Histogram) MarshalJSON() ([]byte, error) {
	valuesCopy := make([]int64, len(h.bucketValues))
	h.mutex.Lock()
	copy(valuesCopy, h.bucketValues)
	h.mutex.Unlock()
	return json.Marshal(struct {
		Type      string            `json:"type"`
		Labels    map[string]string `json:"labels"`
		Histogram histogram         `json:"hist"`
		Timestamp *int64            `json:"ts,omitempty"`
	}{
		Type: h.metricType.String(),
		Histogram: histogram{
			Bounds:  h.bucketBounds,
			Buckets: valuesCopy,
			Inf:     h.infValue.Load(),
		},
		Labels: func() map[string]string {
			labels := make(map[string]string, len(h.tags)+1)
			labels[h.getNameTag()] = h.Name()
			for k, v := range h.tags {
				labels[k] = v
			}
			return labels
		}(),
		Timestamp: tsAsRef(h.timestamp),
	})
}

// Snapshot returns independent copy on metric.
func (h *Histogram) Snapshot() Metric {
	bucketBounds := make([]float64, len(h.bucketBounds))
	bucketValues := make([]int64, len(h.bucketValues))

	copy(bucketBounds, h.bucketBounds)
	h.mutex.Lock()
	copy(bucketValues, h.bucketValues)
	h.mutex.Unlock()

	return &Histogram{
		name:         h.name,
		metricType:   h.metricType,
		tags:         h.tags,
		bucketBounds: bucketBounds,
		bucketValues: bucketValues,
		infValue:     *atomic.NewInt64(h.infValue.Load()),
		useNameTag:   h.useNameTag,
	}
}

// InitBucketValues cleans internal bucketValues and saves new values in order.
// Length of internal bucketValues stays unchanged.
// If length of slice in argument bucketValues more than length of internal one,
// the first extra element of bucketValues is stored in infValue.
func (h *Histogram) InitBucketValues(bucketValues []int64) {
	h.mutex.Lock()
	defer h.mutex.Unlock()

	h.bucketValues = make([]int64, len(h.bucketValues))
	h.infValue.Store(0)
	copy(h.bucketValues, bucketValues)
	if len(bucketValues) > len(h.bucketValues) {
		h.infValue.Store(bucketValues[len(h.bucketValues)])
	}
}