-
Notifications
You must be signed in to change notification settings - Fork 0
/
prommerge.go
197 lines (179 loc) · 4.93 KB
/
prommerge.go
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
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
package prommerge
import (
"bytes"
"fmt"
"log/slog"
"sort"
"time"
"net/http"
"regexp"
"sync"
)
const (
MetricReStr = `^([\w]+)(?:{(.+?)})? ([0-9.e+-]+)`
LabelReStr = `^([\w]+)="(.+)"`
TypeReStr = `^#\sTYPE\s(\w+)\s.+`
HelpReStr = `^#\sHELP\s(\w+)\s.+`
DefaultWorkerPoolSize = 100
)
var (
metricRe = regexp.MustCompile(MetricReStr)
labelRe = regexp.MustCompile(LabelReStr)
typeRe = regexp.MustCompile(TypeReStr)
helpRe = regexp.MustCompile(HelpReStr)
)
type PromDataOpts struct {
EmptyOnFailure bool
Async bool
Sort bool
OmitMeta bool
SupressErrors bool
HTTPClient *http.Client
}
func NewPromData(promTargets []PromTarget, opts PromDataOpts) *PromData {
pd := &PromData{
PromTargets: promTargets,
PromMetricsStream: make(chan []*PromMetric, 20),
MergeWorkerDoneHook: make(chan struct{}),
EmptyOnFailure: opts.EmptyOnFailure,
Async: opts.Async,
Sort: opts.Sort,
OmitMeta: opts.OmitMeta,
SupressErrors: opts.SupressErrors,
workerPoolSize: func() int {
if opts.Async {
return DefaultWorkerPoolSize
}
return 1
}(),
httpClient: opts.HTTPClient,
}
return pd
}
type PromData struct {
PromMetrics []*PromMetric
PromTargets []PromTarget
PromMetricsStream chan []*PromMetric
PromMetricsOutStream chan string
MergeWorkerDoneHook chan struct{}
CollectTargetsDuration time.Duration
SortDuration time.Duration
OutputPrepareDuration time.Duration
OutputProcessDuration time.Duration
OutputGenerateDuration time.Duration
workerPoolSize int
httpClient *http.Client
EmptyOnFailure bool
Async bool
Sort bool
OmitMeta bool
SupressErrors bool
}
type PromTarget struct {
Name string
Url string
ExtraLabels []string
}
// CollectTargets fetches metrics from multiple URLs concurrently and combines them
func (pd *PromData) CollectTargets() error {
err := pd.AsyncHTTP()
if err != nil {
return err
}
if pd.Sort {
if pd.OmitMeta {
slog.Debug("Meta collecting is disabled, sort may not work")
}
t := time.Now()
pd.sortPromMetrics()
pd.SortDuration = time.Since(t)
slog.Debug("Metrics sorted", slog.String("duration", pd.SortDuration.String()))
}
return nil
}
func (pd *PromData) sortPromMetrics() {
sort.Slice(pd.PromMetrics, func(i, j int) bool {
return pd.PromMetrics[i].sort < pd.PromMetrics[j].sort
//return pd.PromMetrics[i].Name < pd.PromMetrics[j].Name
})
}
// httpClient is a shared http.Client with a custom Transport
/*
var httpClient = &http.Client{
Timeout: time.Second * 30, // Set a total timeout for the request
Transport: &http.Transport{
MaxIdleConns: 100,
IdleConnTimeout: 30 * time.Second,
DisableCompression: true,
},
}
*/
type PromChanData struct {
Data string
Source string
ExtraLabels []string
Err error
}
func (pd *PromData) ToString() string {
var prevMetric string
var buffer bytes.Buffer
tP := time.Now()
wg := &sync.WaitGroup{}
workerPool := make(chan struct{}, 900)
for n, _ := range pd.PromMetrics {
wg.Add(1)
workerPool <- struct{}{}
go func(wg *sync.WaitGroup) {
defer func() {
<-workerPool
wg.Done()
}()
pd.PromMetrics[n].Output = pd.BuildMetricString(n)
}(wg)
}
wg.Wait()
pd.OutputPrepareDuration = time.Since(tP)
slog.Debug("Output is prepared", slog.String("duration", pd.OutputPrepareDuration.String()))
t := time.Now()
for n, _ := range pd.PromMetrics {
// Process metadata
if prevMetric != pd.PromMetrics[n].Name && (pd.PromMetrics[n].Help != "" || pd.PromMetrics[n].Type != "") {
buffer.WriteString(pd.PromMetrics[n].Help)
buffer.WriteString("\n")
buffer.WriteString(pd.PromMetrics[n].Type)
buffer.WriteString("\n")
}
tB := time.Now()
buffer.WriteString(pd.PromMetrics[n].Output)
slog.Debug("Processed output string", slog.String("duration", time.Since(tB).String()))
prevMetric = pd.PromMetrics[n].Name
}
pd.OutputProcessDuration = time.Since(t)
slog.Debug("Output processed", slog.Int("lines", len(pd.PromMetrics)), slog.String("duration", pd.OutputProcessDuration.String()))
tB := time.Now()
defer func() {
pd.OutputGenerateDuration = time.Since(tB)
}()
defer func() {
buffer.Reset()
}()
return buffer.String()
}
func (pd *PromData) BuildMetricString(n int) string {
mStr := fmt.Sprintf("%v%v %v\n", pd.PromMetrics[n].Name, func() string {
if len(pd.PromMetrics[n].LabelList) == 0 {
return ""
}
var labelPairs string
labelPairs = "{"
for i := 0; i < len(pd.PromMetrics[n].LabelList); i += 2 {
labelPairs = labelPairs + pd.PromMetrics[n].LabelList[i] + `="` + pd.PromMetrics[n].LabelList[i+1] + `"`
if i != len(pd.PromMetrics[n].LabelList)-2 {
labelPairs = labelPairs + ","
}
}
labelPairs = labelPairs + "}"
return labelPairs
}(), pd.PromMetrics[n].Value)
return mStr
}