This repository has been archived by the owner on Sep 20, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 28
/
exporter.go
280 lines (224 loc) · 7.01 KB
/
exporter.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
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
package docker_hub_exporter
import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"strings"
"sync"
"time"
"github.com/prometheus/client_golang/prometheus"
)
// Namespace of the prometheus metrics
const Namespace = "docker_hub_image"
var (
dockerHubImageLastUpdated = prometheus.NewDesc(
prometheus.BuildFQName(Namespace, "", "last_updated"),
"docker_hub_exporter: Docker Image Last Updated",
[]string{"image", "user"}, nil,
)
dockerHubImagePullsTotal = prometheus.NewDesc(
prometheus.BuildFQName(Namespace, "", "pulls_total"),
"docker_hub_exporter: Docker Image Pulls Total.",
[]string{"image", "user"}, nil,
)
dockerHubImageStars = prometheus.NewDesc(
prometheus.BuildFQName(Namespace, "", "stars"),
"docker_hub_exporter: Docker Image Stars.",
[]string{"image", "user"}, nil,
)
dockerHubImageIsAutomated = prometheus.NewDesc(
prometheus.BuildFQName(Namespace, "", "is_automated"),
"docker_hub_exporter: Docker Image Is Automated.",
[]string{"image", "user"}, nil,
)
)
// Exporter is used to store Metrics data
type Exporter struct {
timeout time.Duration
baseURL string
organisations []string
images []string
logger *log.Logger
connectionRetries int
}
type OrganisationResult struct {
Count int `json:"count"`
Next string `json:"next"`
Previous string `json:"previous"`
Results []ImageResult `json:"results"`
}
type ImageResult struct {
Name string `json:"name"`
User string `json:"user"`
StarCount float64 `json:"star_count"`
IsAutomated bool `json:"is_automated"`
PullCount float64 `json:"pull_count"`
LastUpdated time.Time `json:"last_updated"`
}
// New creates a new Exporter and returns it
func New(organisations, images []string, connectionRetries int, opts ...Option) *Exporter {
e := &Exporter{
timeout: time.Second * 5,
baseURL: "https://hub.docker.com/v2/repositories/",
organisations: organisations,
images: images,
logger: log.New(ioutil.Discard, "docker_hub_exporter: ", log.LstdFlags),
connectionRetries: connectionRetries,
}
for _, opt := range opts {
opt(e)
}
e.logger.Printf("Organisations to monitor: %v", e.organisations)
e.logger.Printf("Images to monitor: %v", e.images)
return e
}
type Option func(*Exporter)
func WithLogger(logger *log.Logger) Option {
return func(e *Exporter) { e.logger = logger }
}
func WithBaseURL(baseURL string) Option {
return func(e *Exporter) { e.baseURL = baseURL }
}
func WithTimeout(timeout time.Duration) Option {
return func(e *Exporter) { e.timeout = timeout }
}
// Describe implements the prometheus.Collector interface.
func (e Exporter) Describe(ch chan<- *prometheus.Desc) {
ch <- dockerHubImageLastUpdated
ch <- dockerHubImagePullsTotal
ch <- dockerHubImageStars
ch <- dockerHubImageIsAutomated
}
// Collect implements the prometheus.Collector interface.
func (e Exporter) Collect(ch chan<- prometheus.Metric) {
e.logger.Println("Collecting metrics")
e.collectMetrics(ch)
}
func (e Exporter) collectMetrics(ch chan<- prometheus.Metric) {
wg := sync.WaitGroup{}
wg.Add(len(e.organisations) + len(e.images))
for _, url := range e.organisations {
go func(url string) {
if url != "" {
response, err := e.getOrgMetrics(fmt.Sprintf("%s%s", e.baseURL, url))
if err != nil {
e.logger.Println("error ", err)
wg.Done()
return
}
for _, orgResp := range response {
for _, result := range orgResp.Results {
e.processImageResult(result, ch)
}
}
}
wg.Done()
}(strings.TrimSpace(url))
}
for _, url := range e.images {
go func(url string) {
if url != "" {
response, err := e.getImageMetrics(fmt.Sprintf("%s%s", e.baseURL, url))
if err != nil {
e.logger.Println("error ", err)
wg.Done()
return
}
e.processImageResult(response, ch)
}
wg.Done()
}(strings.TrimSpace(url))
}
wg.Wait()
}
func (e Exporter) processImageResult(result ImageResult, ch chan<- prometheus.Metric) {
if result.Name != "" && result.User != "" {
var isAutomated float64
if result.IsAutomated {
isAutomated = float64(1)
} else {
isAutomated = float64(0)
}
lastUpdated := float64(result.LastUpdated.UnixNano()) / 1e9
ch <- prometheus.MustNewConstMetric(dockerHubImageStars, prometheus.GaugeValue, result.StarCount, result.Name, result.User)
ch <- prometheus.MustNewConstMetric(dockerHubImageIsAutomated, prometheus.GaugeValue, isAutomated, result.Name, result.User)
ch <- prometheus.MustNewConstMetric(dockerHubImagePullsTotal, prometheus.CounterValue, result.PullCount, result.Name, result.User)
ch <- prometheus.MustNewConstMetric(dockerHubImageLastUpdated, prometheus.GaugeValue, lastUpdated, result.Name, result.User)
}
}
func (e Exporter) getImageMetrics(url string) (ImageResult, error) {
imageResult := ImageResult{}
body, err := e.getResponse(url)
if err != nil {
return ImageResult{}, err
}
err = json.Unmarshal(body, &imageResult)
if err != nil {
return ImageResult{}, fmt.Errorf("Error unmarshalling response: %v", err)
}
return imageResult, nil
}
func (e Exporter) getOrgMetrics(url string) ([]OrganisationResult, error) {
orgResult := OrganisationResult{}
body, err := e.getResponse(url)
if err != nil {
return []OrganisationResult{}, err
}
err = json.Unmarshal(body, &orgResult)
if err != nil {
return []OrganisationResult{}, fmt.Errorf("Error unmarshalling response: %v", err)
}
if orgResult.Count == 0 || len(orgResult.Results) == 0 {
return []OrganisationResult{}, fmt.Errorf("No images found for url: %s", url)
}
if orgResult.Next != "" {
orgResult1, err := e.getOrgMetrics(orgResult.Next)
if err != nil {
return []OrganisationResult{}, err
}
return append([]OrganisationResult{orgResult}, orgResult1...), nil
}
return []OrganisationResult{orgResult}, nil
}
// getResponse collects an individual http.response and returns a *Response
func (e Exporter) getResponse(url string) ([]byte, error) {
e.logger.Printf("Fetching %s \n", url)
resp, err := e.getHTTPResponse(url) // do this earlier
if err != nil {
return nil, fmt.Errorf("Error converting body to byte array: %v", err)
}
// Read the body to a byte array so it can be used elsewhere
body, err := ioutil.ReadAll(resp.Body)
defer resp.Body.Close()
if err != nil {
return nil, fmt.Errorf("Error converting body to byte array: %v", err)
}
return body, nil
}
// getHTTPResponse handles the http client creation, token setting and returns the *http.response
func (e Exporter) getHTTPResponse(url string) (*http.Response, error) {
client := &http.Client{
Timeout: e.timeout,
}
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return nil, fmt.Errorf("Failed to create http request: %v", err)
}
var retries = e.connectionRetries
for retries > 0 {
resp, err := client.Do(req)
if err != nil {
retries -= 1
if retries == 0 {
return nil, err
} else {
e.logger.Printf("Retrying HTTP request %s", url)
}
} else {
return resp, nil
}
}
return nil, nil
}