This repository has been archived by the owner on Mar 3, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 16
/
resource.go
207 lines (180 loc) · 4.76 KB
/
resource.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
package main
import (
"bytes"
"fmt"
"io/ioutil"
"net/http"
"os"
"sync"
"time"
"github.com/sirupsen/logrus"
)
type resources struct {
wg *sync.WaitGroup
ticker *time.Ticker
sig chan os.Signal
exit chan struct{}
rs map[string]*resource
}
func createResources(cfg *pusherConfig, grm *routeMap) *resources {
rs := make(map[string]*resource)
for name := range cfg.resources {
rs[name] = newResource(name, cfg, grm)
}
return &resources{
rs: rs,
ticker: time.NewTicker(cfg.pushInterval),
sig: make(chan os.Signal, 1),
exit: make(chan struct{}, 1),
wg: &sync.WaitGroup{},
}
}
func (rs *resources) process(cfg *pusherConfig) {
for _, r := range rs.rs {
rs.wg.Add(1)
go r.getAndPush(rs.wg, cfg)
}
rs.wg.Wait()
}
func (rs *resources) run() <-chan time.Time {
return rs.ticker.C
}
func (rs *resources) stop() <-chan struct{} {
return rs.exit
}
func (rs *resources) shutdown() {
rs.ticker.Stop()
rs.exit <- struct{}{}
}
type resource struct {
name string
pushGatewayURL string
resURL string
routes *routeMap
httpClient *http.Client
}
// creates new instance of resource
//
func newResource(name string, cfg *pusherConfig, grm *routeMap) *resource {
var pushgatewayURL string
if cfg.resources[name].pushGatewayURL != "" {
pushgatewayURL = cfg.resources[name].pushGatewayURL
} else if cfg.pushGatewayURL != "" {
pushgatewayURL = cfg.pushGatewayURL
} else {
logger.Fatalf("No pushgateway_url derived from config for resource '%s'", name)
}
defaultRoute := cfg.defaultRoute
if cfg.resources[name].defaultRoute != "" {
defaultRoute = cfg.resources[name].defaultRoute
}
var rm *routeMap
if cfg.resources[name].routeMap != "" {
rm = newRouteMap(cfg.resources[name].routeMap, defaultRoute)
} else {
rm = newRouteMap(cfg.routeMap, defaultRoute)
}
return &resource{
name: name,
pushGatewayURL: pushgatewayURL,
resURL: cfg.resources[name].resURL,
routes: rm,
httpClient: &http.Client{
Timeout: httpClientTimeout,
},
}
}
// retrieve metrics of a resource
//
func (r *resource) getMetrics() []byte {
logger.WithFields(logrus.Fields{
"resource_name": r.name,
"resource_url": r.resURL,
}).Debug("Getting metrics")
resp, err := r.httpClient.Get(r.resURL)
if err != nil {
logger.WithFields(logrus.Fields{
"error": err.Error(),
"resource_name": r.name,
"resource_url": r.resURL,
}).Error("Failed to get metrics.")
return nil
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
logger.WithFields(logrus.Fields{
"error": err.Error(),
"resource_name": r.name,
"resource_url": r.resURL,
}).Error("Failed to read response body while getting metrics.")
return nil
}
if resp.StatusCode != http.StatusOK {
logger.WithFields(logrus.Fields{
"body": body,
"status": resp.StatusCode,
"resource_name": r.name,
"resource_url": r.resURL,
}).Error("Got non-OK status code while getting metrics.")
return nil
}
return body
}
// push metrics into given destination
//
func (r *resource) pushMetrics(metrics []byte, dst string, wg *sync.WaitGroup) {
defer wg.Done()
postURL := fmt.Sprintf(r.pushGatewayURL, dst) + fmt.Sprintf("/job/%s/instance/%s", r.name, hostname)
if dummy {
printMutex.Lock()
defer printMutex.Unlock()
fmt.Printf("POST %s\n%s\n", postURL, string(metrics))
return
}
logger.WithFields(logrus.Fields{
"endpoint_url": postURL,
"resource_name": r.name,
}).Debug("Pushing metrics.")
data := bytes.NewReader(metrics)
resp, err := r.httpClient.Post(postURL, "text/plain", data)
if err != nil {
logger.WithFields(logrus.Fields{
"endpoint_url": postURL,
"error": err.Error(),
}).Error("Failed to push metrics.")
return
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
logger.WithFields(logrus.Fields{
"error": err.Error(),
"resource_name": r.name,
"resource_url": r.resURL,
}).Error("Failed to read response body while pushing metrics.")
}
if resp.StatusCode != http.StatusAccepted {
logger.WithFields(logrus.Fields{
"body": string(body),
"status": resp.StatusCode,
"resource_name": r.name,
"resource_url": r.resURL,
}).Error("Got non-OK status code while pushing metrics.")
}
}
// gets metrics, does inverse-multiplexing on the data
// by metrics names and route definitions and pushes the
// data into promethei
//
func (r *resource) getAndPush(wgImux *sync.WaitGroup, cfg *pusherConfig) {
defer wgImux.Done()
wgPush := &sync.WaitGroup{}
if metricsBytes := r.getMetrics(); metricsBytes != nil {
m := newMetrics(metricsBytes, cfg)
for dst, body := range m.imux(r.routes, cfg) {
wgPush.Add(1)
go r.pushMetrics(body, dst, wgPush)
}
}
}