forked from buildkite/buildkite-agent-metrics
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
406 lines (336 loc) · 9.21 KB
/
main.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
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
package main
import (
"flag"
"fmt"
"log"
"os"
"regexp"
"time"
"gopkg.in/buildkite/go-buildkite.v2/buildkite"
)
// Version is passed in via ldflags
var Version string
var queuePattern *regexp.Regexp
func init() {
queuePattern = regexp.MustCompile(`(?i)^queue=(.+?)$`)
}
func main() {
var (
accessToken = flag.String("token", "", "A Buildkite API Access Token")
orgSlug = flag.String("org", "", "A Buildkite Organization Slug")
interval = flag.Duration("interval", 0, "Update metrics every interval, rather than once")
history = flag.Duration("history", time.Hour*24, "Historical data to use for finished builds")
debug = flag.Bool("debug", false, "Show API debugging output")
version = flag.Bool("version", false, "Show the version")
// filters
queue = flag.String("queue", "", "Only include a specific queue")
)
flag.Parse()
if *version {
fmt.Printf("buildkite-metrics %s\n", Version)
os.Exit(0)
}
if *accessToken == "" {
log.Fatal("Must provide a value for -token")
}
if *orgSlug == "" {
log.Fatal("Must provide a value for -org")
}
config, err := buildkite.NewTokenConfig(*accessToken, false)
if err != nil {
log.Fatalf("client config failed: %s", err)
}
client := buildkite.NewClient(config.Client())
buildkite.SetHttpDebug(*debug)
f := func() error {
t := time.Now()
res, err := collectResults(client, collectOpts{
OrgSlug: *orgSlug,
Historical: *history,
Queue: *queue,
})
if err != nil {
return err
}
dumpResults(res)
err = cloudwatchSend(res)
if err != nil {
return err
}
log.Printf("Finished in %s", time.Now().Sub(t))
return nil
}
if err := f(); err != nil {
log.Fatal(err)
}
if *interval > 0 {
for _ = range time.NewTicker(*interval).C {
if err := f(); err != nil {
log.Println(err)
}
}
}
}
type collectOpts struct {
OrgSlug string
Historical time.Duration
Queue string
}
func collectResults(client *buildkite.Client, opts collectOpts) (*result, error) {
res := &result{
totals: newCounts(),
queues: map[string]counts{},
pipelines: map[string]counts{},
}
if opts.Queue == "" {
log.Println("Collecting historical metrics")
if err := res.addHistoricalMetrics(client, opts); err != nil {
return nil, err
}
}
log.Println("Collecting running and scheduled build and job metrics")
if err := res.addBuildAndJobMetrics(client, opts); err != nil {
return nil, err
}
log.Println("Collecting agent metrics")
if err := res.addAgentMetrics(client, opts); err != nil {
return nil, err
}
if opts.Queue != "" {
if c, ok := res.queues[opts.Queue]; ok {
return &result{
queues: map[string]counts{
opts.Queue: c,
},
}, nil
}
return &result{}, nil
}
return res, nil
}
func dumpResults(res *result) {
for name, c := range res.totals {
log.Printf("Buildkite > %s = %d", name, c)
}
for name, c := range res.queues {
for k, v := range c {
log.Printf("Buildkite > [queue = %s] > %s = %d", name, k, v)
}
}
for name, c := range res.pipelines {
for k, v := range c {
log.Printf("Buildkite > [pipeline = %s] > %s = %d", name, k, v)
}
}
}
const (
runningBuildsCount = "RunningBuildsCount"
runningJobsCount = "RunningJobsCount"
scheduledBuildsCount = "ScheduledBuildsCount"
scheduledJobsCount = "ScheduledJobsCount"
unfinishedJobsCount = "UnfinishedJobsCount"
totalAgentCount = "TotalAgentCount"
busyAgentCount = "BusyAgentCount"
idleAgentCount = "IdleAgentCount"
)
type counts map[string]int
func newCounts() counts {
return counts{
runningBuildsCount: 0,
scheduledBuildsCount: 0,
runningJobsCount: 0,
scheduledJobsCount: 0,
unfinishedJobsCount: 0,
}
}
func queue(j *buildkite.Job) string {
for _, m := range j.AgentQueryRules {
if match := queuePattern.FindStringSubmatch(m); match != nil {
return match[1]
}
}
return "default"
}
func uniqueQueues(builds []buildkite.Build) []string {
queueMap := map[string]struct{}{}
for _, b := range builds {
for _, j := range b.Jobs {
queueMap[queue(j)] = struct{}{}
}
}
queues := []string{}
for q := range queueMap {
queues = append(queues, q)
}
return queues
}
type result struct {
totals counts
queues, pipelines map[string]counts
}
func (r *result) addHistoricalMetrics(client *buildkite.Client, opts collectOpts) error {
finishedBuilds := listBuildsByOrg(client.Builds, opts.OrgSlug, buildkite.BuildsListOptions{
FinishedFrom: time.Now().UTC().Add(opts.Historical * -1),
})
return finishedBuilds.Pages(func(v interface{}, lastPage bool) bool {
for _, queue := range uniqueQueues(v.([]buildkite.Build)) {
if _, ok := r.queues[queue]; !ok {
r.queues[queue] = newCounts()
}
}
for _, build := range v.([]buildkite.Build) {
r.pipelines[*build.Pipeline.Name] = newCounts()
}
return true
})
}
func (r *result) addBuildAndJobMetrics(client *buildkite.Client, opts collectOpts) error {
currentBuilds := listBuildsByOrg(client.Builds, opts.OrgSlug, buildkite.BuildsListOptions{
State: []string{"scheduled", "running"},
})
return currentBuilds.Pages(func(v interface{}, lastPage bool) bool {
for _, build := range v.([]buildkite.Build) {
// log.Printf("Adding build to stats (id=%q, pipeline=%q, branch=%q, state=%q)",
// *build.ID, *build.Pipeline.Name, *build.Branch, *build.State)
if _, ok := r.pipelines[*build.Pipeline.Name]; !ok {
r.pipelines[*build.Pipeline.Name] = newCounts()
}
switch *build.State {
case "running":
r.totals[runningBuildsCount]++
r.pipelines[*build.Pipeline.Name][runningBuildsCount]++
case "scheduled":
r.totals[scheduledBuildsCount]++
r.pipelines[*build.Pipeline.Name][scheduledBuildsCount]++
}
var buildQueues = map[string]int{}
for _, job := range build.Jobs {
if job.Type != nil && *job.Type == "waiter" {
continue
}
state := ""
if job.State != nil {
state = *job.State
}
// log.Printf("Adding job to stats (id=%q, pipeline=%q, queue=%q, type=%q, state=%q)",
// *job.ID, *build.Pipeline.Name, queue(job), *job.Type, state)
if _, ok := r.queues[queue(job)]; !ok {
r.queues[queue(job)] = newCounts()
}
if state == "running" || state == "scheduled" {
switch state {
case "running":
r.totals[runningJobsCount]++
r.queues[queue(job)][runningJobsCount]++
case "scheduled":
r.totals[scheduledJobsCount]++
r.queues[queue(job)][scheduledJobsCount]++
}
r.totals[unfinishedJobsCount]++
r.queues[queue(job)][unfinishedJobsCount]++
}
buildQueues[queue(job)]++
}
// add build metrics to queues
if len(buildQueues) > 0 {
for queue := range buildQueues {
switch *build.State {
case "running":
r.queues[queue][runningBuildsCount]++
case "scheduled":
r.queues[queue][scheduledBuildsCount]++
}
}
}
}
return true
})
}
func (r *result) addAgentMetrics(client *buildkite.Client, opts collectOpts) error {
p := &pager{
lister: func(page int) (interface{}, int, error) {
agents, resp, err := client.Agents.List(opts.OrgSlug, &buildkite.AgentListOptions{
ListOptions: buildkite.ListOptions{
Page: page,
},
})
log.Printf("Agents page %d has %d agents, next page is %d",
page,
len(agents),
resp.NextPage,
)
return agents, resp.NextPage, err
},
}
r.totals[busyAgentCount] = 0
r.totals[idleAgentCount] = 0
r.totals[totalAgentCount] = 0
for queue := range r.queues {
r.queues[queue][busyAgentCount] = 0
r.queues[queue][idleAgentCount] = 0
r.queues[queue][totalAgentCount] = 0
}
err := p.Pages(func(v interface{}, lastPage bool) bool {
agents := v.([]buildkite.Agent)
for _, agent := range agents {
queue := "default"
for _, m := range agent.Metadata {
if match := queuePattern.FindStringSubmatch(m); match != nil {
queue = match[1]
break
}
}
if _, ok := r.queues[queue]; !ok {
r.queues[queue] = newCounts()
r.queues[queue][busyAgentCount] = 0
r.queues[queue][idleAgentCount] = 0
r.queues[queue][totalAgentCount] = 0
}
// log.Printf("Adding agent to stats (name=%q, queue=%q, job=%#v)",
// *agent.Name, queue, agent.Job != nil)
if agent.Job != nil {
r.totals[busyAgentCount]++
r.queues[queue][busyAgentCount]++
} else {
r.totals[idleAgentCount]++
r.queues[queue][idleAgentCount]++
}
r.totals[totalAgentCount]++
r.queues[queue][totalAgentCount]++
}
return true
})
if err != nil {
return err
}
return nil
}
type pager struct {
lister func(page int) (v interface{}, nextPage int, err error)
}
func (p *pager) Pages(f func(v interface{}, lastPage bool) bool) error {
page := 1
for {
val, nextPage, err := p.lister(page)
if err != nil {
return err
}
if !f(val, nextPage == 0) || nextPage == 0 {
break
}
page = nextPage
}
return nil
}
func listBuildsByOrg(builds *buildkite.BuildsService, orgSlug string, opts buildkite.BuildsListOptions) *pager {
return &pager{
lister: func(page int) (interface{}, int, error) {
opts.ListOptions = buildkite.ListOptions{
Page: page,
}
builds, resp, err := builds.ListByOrg(orgSlug, &opts)
log.Printf("Builds page %d has %d builds, next page is %d", page, len(builds), resp.NextPage)
return builds, resp.NextPage, err
},
}
}