-
Notifications
You must be signed in to change notification settings - Fork 19
/
exporterscrape.go
235 lines (190 loc) · 5.17 KB
/
exporterscrape.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
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
package scrape
import (
"time"
"github.com/prometheus/prometheus/retrieval"
"github.com/prometheus/prometheus/config"
"github.com/prometheus/common/model"
"sort"
"fmt"
"net/http"
"github.com/prometheus/common/version"
"github.com/prometheus/common/expfmt"
"io"
"bytes"
"strings"
"os"
"io/ioutil"
)
var pushGateway string
func init() {
pushGateway = getOr("PUSH_GATEWAY", "http://pushgateway.example.org:9091")
}
type JobTargets struct {
tm *retrieval.TargetManager
}
func NewJobTargets(tm *retrieval.TargetManager) *JobTargets {
return &JobTargets{
tm: tm,
}
}
func (jt *JobTargets) Targets() []*jobTarget {
tps := map[string][]*retrieval.Target{}
for _, t := range jt.tm.Targets() {
job := string(t.Labels()[model.JobLabel])
tps[job] = append(tps[job], t)
}
for _, targets := range tps {
sort.Slice(targets, func(i, j int) bool {
return targets[i].Labels()[model.InstanceLabel] < targets[j].Labels()[model.InstanceLabel]
})
}
targets := []*jobTarget{}
for job, pool := range tps {
targets = append(targets, &jobTarget{
Name: job,
Endpoints: covertToEndpoints(pool),
})
}
return targets
}
func covertToEndpoints(targets []*retrieval.Target) []*jobEndpoint {
endpoints := []*jobEndpoint{}
for _, endpoint := range targets {
endpoints = append(endpoints, &jobEndpoint{
Endpoint: endpoint.URL().String(),
Health: string(endpoint.Health()),
})
}
return endpoints
}
type jobTarget struct {
Name string
Endpoints []*jobEndpoint
}
func (jt *jobTarget) Scrape(labels []string, values []string) {
for _, endpoint := range jt.Endpoints {
go func(endpoint *jobEndpoint) {
endpoint.scrape(jt.Name, labels, values)
}(endpoint)
}
}
const acceptHeader = `application/vnd.google.protobuf;proto=io.prometheus.client.MetricFamily;encoding=delimited;q=0.7,text/plain;version=0.0.4;q=0.3,*/*;q=0.1`
var userAgentHeader = fmt.Sprintf("Prometheus/%s", version.Version)
func (endpoint *jobEndpoint) scrape(jobName string, labels []string, values []string) error {
req, err := http.NewRequest("GET", endpoint.Endpoint, nil)
if err != nil {
return err
}
req.Header.Add("Accept", acceptHeader)
req.Header.Set("User-Agent", userAgentHeader)
req.Header.Set("X-Prometheus-Scrape-Timeout-Seconds", fmt.Sprintf("%f", 15))
//
client := &http.Client{}
//
resp, err := client.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
if (resp.StatusCode != http.StatusOK) {
return fmt.Errorf("server returned HTTP status %s", resp.Status)
}
var (
allSamples = make(model.Samples, 0, 200)
decSamples = make(model.Vector, 0, 50)
)
sdec := expfmt.SampleDecoder{
Dec: expfmt.NewDecoder(resp.Body, expfmt.ResponseFormat(resp.Header)),
Opts: &expfmt.DecodeOptions{
Timestamp: model.TimeFromUnixNano(time.Now().UnixNano()),
},
}
for {
if err = sdec.Decode(&decSamples); err != nil {
break
}
allSamples = append(allSamples, decSamples...)
decSamples = decSamples[:0]
}
if err == io.EOF {
// Set err to nil since it is used in the scrape health recording.
err = nil
}
var buffer bytes.Buffer
for _, sample := range allSamples {
for i, customLabel := range labels {
sample.Metric[model.LabelName(customLabel)] = model.LabelValue(values[i])
}
metric := fmt.Sprintf("%s %s\n", sample.Metric, sample.Value)
if strings.Contains(metric, "node_") || strings.Contains(metric, "container_") || strings.Contains(metric, "rancher_") {
buffer.WriteString(metric)
}
}
url := fmt.Sprintf("%s/metrics/job/%s/instance/%s", pushGateway, jobName, endpoint.instance())
fmt.Println("send data to pushgateway :" + url)
post, err := http.NewRequest("POST", url, strings.NewReader(buffer.String()))
if err != nil {
fmt.Println(err.Error(), "post data to push gateway error!!!!!!!!!!")
return err
}
response2, err := client.Do(post)
if err != nil {
fmt.Println(err.Error(), "post data to push gateway error!!!!!!!!!!")
} else {
body, _ := ioutil.ReadAll(response2.Body)
fmt.Println(string(body))
}
return nil
}
type jobEndpoint struct {
Endpoint string
Health string
}
func (je *jobEndpoint) instance() string {
return strings.Replace(strings.Replace(strings.Replace(strings.TrimLeft(je.Endpoint, "http://"), "/", "-", -1), ".", "-", -1), ":", "-", -1)
}
type ExporterScrape struct {
jt *JobTargets
ticker *time.Ticker
quit chan struct{}
ScrapeInterval model.Duration
labels []string
values []string
}
func NewExporterScrape(jt *JobTargets, labels []string, values []string) *ExporterScrape {
return &ExporterScrape{
jt: jt,
ticker: time.NewTicker(time.Second * 15),
quit: make(chan struct{}),
labels: labels,
values: values,
}
}
func (es *ExporterScrape) Run() {
go func() {
for {
select {
case <-es.ticker.C:
for _, jt := range es.jt.Targets() {
jt.Scrape(es.labels, es.values)
}
case <-es.quit:
es.ticker.Stop()
return
}
}
}()
}
func (es *ExporterScrape) Stop() {
es.ticker.Stop()
}
func (es *ExporterScrape) AppConfig(conf *config.Config) {
es.ScrapeInterval = conf.GlobalConfig.ScrapeInterval
}
func getOr(env string, value string) string {
envValue := os.Getenv(env)
if envValue == "" {
return value
}
return envValue
}