-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmetrics_github_workflows.go
557 lines (475 loc) · 15.6 KB
/
metrics_github_workflows.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
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
package main
import (
"errors"
"fmt"
"time"
"github.com/google/go-github/v61/github"
"github.com/prometheus/client_golang/prometheus"
"github.com/webdevops/go-common/prometheus/collector"
"github.com/webdevops/go-common/utils/to"
"golang.org/x/exp/slices"
)
const (
CUSTOMPROP_LABEL_FMT = "prop_%s"
)
var (
githubWorkflowRunningStatus = []string{"in_progress", "action_required", "queued", "waiting", "pending"}
)
type (
MetricsCollectorGithubWorkflows struct {
collector.Processor
prometheus struct {
repository *prometheus.GaugeVec
workflow *prometheus.GaugeVec
workflowRunRunning *prometheus.GaugeVec
workflowRunRunningStartTime *prometheus.GaugeVec
workflowLatestRun *prometheus.GaugeVec
workflowLatestRunStartTime *prometheus.GaugeVec
workflowLatestRunDuration *prometheus.GaugeVec
workflowConsecutiveFailures *prometheus.GaugeVec
}
}
)
func (m *MetricsCollectorGithubWorkflows) Setup(collector *collector.Collector) {
m.Processor.Setup(collector)
var customPropLabels []string
for _, customProp := range Opts.GitHub.Repositories.CustomProperties {
customPropLabels = append(customPropLabels, fmt.Sprintf(CUSTOMPROP_LABEL_FMT, customProp))
}
// ##############################################################3
// Infrastructure
m.prometheus.repository = prometheus.NewGaugeVec(
prometheus.GaugeOpts{
Name: "github_repository_info",
Help: "GitHub repository info",
},
append(
[]string{
"org",
"repo",
"defaultBranch",
},
customPropLabels...,
),
)
m.Collector.RegisterMetricList("repository", m.prometheus.repository, true)
m.prometheus.workflow = prometheus.NewGaugeVec(
prometheus.GaugeOpts{
Name: "github_workflow_info",
Help: "GitHub workflow info",
},
append(
[]string{
"org",
"repo",
"workflowID",
"workflow",
"state",
"path",
},
customPropLabels...,
),
)
m.Collector.RegisterMetricList("workflow", m.prometheus.workflow, true)
// ##############################################################3
// Workflow run running
m.prometheus.workflowRunRunning = prometheus.NewGaugeVec(
prometheus.GaugeOpts{
Name: "github_workflow_run_running",
Help: "GitHub workflow running information",
},
[]string{
"org",
"repo",
"workflowID",
"workflow",
"event",
"branch",
"status",
"actorLogin",
"actorType",
},
)
m.Collector.RegisterMetricList("workflowRunRunning", m.prometheus.workflowRunRunning, true)
m.prometheus.workflowRunRunningStartTime = prometheus.NewGaugeVec(
prometheus.GaugeOpts{
Name: "github_workflow_run_running_start_time_seconds",
Help: "GitHub workflow run running start time as unix timestamp",
},
[]string{
"org",
"repo",
"workflowID",
},
)
m.Collector.RegisterMetricList("workflowRunRunningStartTime", m.prometheus.workflowRunRunningStartTime, true)
// ##############################################################3
// Workflow run latest
m.prometheus.workflowLatestRun = prometheus.NewGaugeVec(
prometheus.GaugeOpts{
Name: "github_workflow_latest_run",
Help: "GitHub workflow latest run information",
},
[]string{
"org",
"repo",
"workflowID",
"workflow",
"event",
"branch",
"conclusion",
"actorLogin",
"actorType",
},
)
m.Collector.RegisterMetricList("workflowLatestRun", m.prometheus.workflowLatestRun, true)
m.prometheus.workflowLatestRunStartTime = prometheus.NewGaugeVec(
prometheus.GaugeOpts{
Name: "github_workflow_latest_run_start_time_seconds",
Help: "GitHub workflow latest run last executed timestamp",
},
[]string{
"org",
"repo",
"workflowID",
},
)
m.Collector.RegisterMetricList("workflowLatestRunStartTime", m.prometheus.workflowLatestRunStartTime, true)
m.prometheus.workflowLatestRunDuration = prometheus.NewGaugeVec(
prometheus.GaugeOpts{
Name: "github_workflow_latest_run_duration_seconds",
Help: "GitHub workflow latest run last duration in seconds",
},
[]string{
"org",
"repo",
"workflowID",
},
)
m.Collector.RegisterMetricList("workflowLatestRunDuration", m.prometheus.workflowLatestRunDuration, true)
// ##############################################################3
// Workflow consecutive failed runs
m.prometheus.workflowConsecutiveFailures = prometheus.NewGaugeVec(
prometheus.GaugeOpts{
Name: "github_workflow_consecutive_failed_runs",
Help: "GitHub workflow consecutive count of failed runs per workflow",
},
[]string{
"org",
"repo",
"workflowID",
"workflow",
"branch",
"actorLogin",
"actorType",
},
)
m.Collector.RegisterMetricList("workflowConsecutiveFailures", m.prometheus.workflowConsecutiveFailures, true)
}
func (m *MetricsCollectorGithubWorkflows) Reset() {}
func (m *MetricsCollectorGithubWorkflows) getRepoList(org string) ([]*github.Repository, error) {
var repositories []*github.Repository
opts := github.RepositoryListByOrgOptions{
ListOptions: github.ListOptions{PerPage: 100, Page: 1},
}
for {
m.Logger().Debugf(`fetching repository list with page "%d"`, opts.Page)
result, response, err := githubClient.Repositories.ListByOrg(m.Context(), org, &opts)
var ghRateLimitError *github.RateLimitError
if ok := errors.As(err, &ghRateLimitError); ok {
m.Logger().Debugf("ListByOrg ratelimited. Pausing until %s", ghRateLimitError.Rate.Reset.Time.String())
time.Sleep(time.Until(ghRateLimitError.Rate.Reset.Time))
continue
} else if err != nil {
return repositories, err
}
repositories = append(repositories, result...)
// calc next page
if response.NextPage == 0 {
break
}
opts.Page = response.NextPage
}
if len(Opts.GitHub.Repositories.CustomProperties) >= 1 {
for _, repository := range repositories {
var err error
var repoCustomProperties []*github.CustomPropertyValue
for {
repoCustomProperties, _, err = githubClient.Repositories.GetAllCustomPropertyValues(m.Context(), org, repository.GetName())
var ghRateLimitError *github.RateLimitError
if ok := errors.As(err, &ghRateLimitError); ok {
m.Logger().Debugf("GetAllCustomPropertyValues ratelimited. Pausing until %s", ghRateLimitError.Rate.Reset.Time.String())
time.Sleep(time.Until(ghRateLimitError.Rate.Reset.Time))
continue
} else if err != nil {
panic(err)
}
break
}
repository.CustomProperties = map[string]string{}
for _, property := range repoCustomProperties {
repository.CustomProperties[property.PropertyName] = property.GetValue()
}
}
}
return repositories, nil
}
func (m *MetricsCollectorGithubWorkflows) getRepoWorkflows(org, repo string) ([]*github.Workflow, error) {
var workflows []*github.Workflow
opts := github.ListOptions{PerPage: 100, Page: 1}
for {
m.Logger().Debugf(`fetching workflows list for repo "%s" with page "%d"`, repo, opts.Page)
result, response, err := githubClient.Actions.ListWorkflows(m.Context(), org, repo, &opts)
var ghRateLimitError *github.RateLimitError
if ok := errors.As(err, &ghRateLimitError); ok {
m.Logger().Debugf("ListWorkflows ratelimited. Pausing until %s", ghRateLimitError.Rate.Reset.Time.String())
time.Sleep(time.Until(ghRateLimitError.Rate.Reset.Time))
continue
} else if err != nil {
return workflows, err
}
workflows = append(workflows, result.Workflows...)
// calc next page
if response.NextPage == 0 {
break
}
opts.Page = response.NextPage
}
return workflows, nil
}
func (m *MetricsCollectorGithubWorkflows) getRepoWorkflowRuns(repo *github.Repository) ([]*github.WorkflowRun, error) {
var workflowRuns []*github.WorkflowRun
opts := github.ListWorkflowRunsOptions{
Branch: repo.GetDefaultBranch(),
ExcludePullRequests: true,
ListOptions: github.ListOptions{PerPage: 100, Page: 1},
Created: ">=" + time.Now().Add(-Opts.GitHub.Workflows.Timeframe).Format(time.RFC3339),
}
for {
m.Logger().Debugf(`fetching list of workflow runs for repo "%s" with page "%d"`, repo.GetName(), opts.Page)
result, response, err := githubClient.Actions.ListRepositoryWorkflowRuns(m.Context(), Opts.GitHub.Organization, *repo.Name, &opts)
var ghRateLimitError *github.RateLimitError
if ok := errors.As(err, &ghRateLimitError); ok {
m.Logger().Debugf("ListRepositoryWorkflowRuns ratelimited. Pausing until %s", ghRateLimitError.Rate.Reset.Time.String())
time.Sleep(time.Until(ghRateLimitError.Rate.Reset.Time))
continue
} else if err != nil {
return workflowRuns, err
}
workflowRuns = append(workflowRuns, result.WorkflowRuns...)
// calc next page
if response.NextPage == 0 {
break
}
opts.Page = response.NextPage
}
return workflowRuns, nil
}
func (m *MetricsCollectorGithubWorkflows) Collect(callback chan<- func()) {
repositoryMetric := m.Collector.GetMetricList("repository")
workflowMetric := m.Collector.GetMetricList("workflow")
org := Opts.GitHub.Organization
repositories, err := m.getRepoList(org)
if err != nil {
panic(err)
}
for _, repo := range repositories {
// skip archived or disabled repos
if repo.GetArchived() || repo.GetDisabled() {
continue
}
// skip repos without default branch (not setup yet?)
if repo.GetDefaultBranch() == "" {
// repo doesn't have default branch
continue
}
// build custom properties
propLabels := prometheus.Labels{}
if len(Opts.GitHub.Repositories.CustomProperties) >= 1 {
for _, customProp := range Opts.GitHub.Repositories.CustomProperties {
labelName := fmt.Sprintf(CUSTOMPROP_LABEL_FMT, customProp)
propLabels[labelName] = ""
if val, exists := repo.CustomProperties[customProp]; exists {
propLabels[labelName] = val
}
}
}
// repo info metric
labels := prometheus.Labels{
"org": org,
"repo": repo.GetName(),
"defaultBranch": to.String(repo.DefaultBranch),
}
for labelName, labelValue := range propLabels {
labels[labelName] = labelValue
}
repositoryMetric.AddInfo(labels)
// get workflows
workflows, err := m.getRepoWorkflows(org, repo.GetName())
if err != nil {
panic(err)
}
// workflow info metrics
for _, workflow := range workflows {
labels := prometheus.Labels{
"org": org,
"repo": repo.GetName(),
"workflowID": fmt.Sprintf("%v", workflow.GetID()),
"workflow": workflow.GetName(),
"state": workflow.GetState(),
"path": workflow.GetPath(),
}
for labelName, labelValue := range propLabels {
labels[labelName] = labelValue
}
workflowMetric.AddInfo(labels)
}
if len(workflows) >= 1 {
workflowRuns, err := m.getRepoWorkflowRuns(repo)
if err != nil {
panic(err)
}
if len(workflowRuns) >= 1 {
m.collectRunningRuns(Opts.GitHub.Organization, repo, workflowRuns, callback)
m.collectLatestRun(Opts.GitHub.Organization, repo, workflowRuns, callback)
m.collectConsecutiveFailures(Opts.GitHub.Organization, repo, workflowRuns, callback)
}
}
}
}
func (m *MetricsCollectorGithubWorkflows) collectRunningRuns(org string, repo *github.Repository, workflowRun []*github.WorkflowRun, callback chan<- func()) {
runMetric := m.Collector.GetMetricList("workflowRunRunning")
runStartTimeMetric := m.Collector.GetMetricList("workflowRunRunningStartTime")
for _, row := range workflowRun {
workflowRun := row
// ignore non running workflows
if !slices.Contains(githubWorkflowRunningStatus, workflowRun.GetStatus()) {
continue
}
if workflowRun.GetConclusion() != "" {
// skip if task has a conclusion
continue
}
infoLabels := prometheus.Labels{
"org": org,
"repo": repo.GetName(),
"workflowID": fmt.Sprintf("%v", workflowRun.GetWorkflowID()),
"workflow": workflowRun.GetName(),
"event": workflowRun.GetEvent(),
"branch": workflowRun.GetHeadBranch(),
"status": workflowRun.GetStatus(),
"actorLogin": workflowRun.Actor.GetLogin(),
"actorType": workflowRun.Actor.GetType(),
}
statLabels := prometheus.Labels{
"org": org,
"repo": repo.GetName(),
"workflowID": fmt.Sprintf("%v", workflowRun.GetWorkflowID()),
}
runMetric.AddInfo(infoLabels)
runStartTimeMetric.AddTime(statLabels, workflowRun.GetRunStartedAt().Time)
}
}
func (m *MetricsCollectorGithubWorkflows) collectLatestRun(org string, repo *github.Repository, workflowRun []*github.WorkflowRun, callback chan<- func()) {
runMetric := m.Collector.GetMetricList("workflowLatestRun")
runTimestampMetric := m.Collector.GetMetricList("workflowLatestRunStartTime")
runDurationMetric := m.Collector.GetMetricList("workflowLatestRunDuration")
latestJobs := map[int64]*github.WorkflowRun{}
for _, row := range workflowRun {
workflowRun := row
workflowId := workflowRun.GetWorkflowID()
// ignore running/not finished workflow runs
if slices.Contains(githubWorkflowRunningStatus, workflowRun.GetStatus()) {
continue
}
if workflowRun.GetConclusion() == "" {
// skip empty conclusions or runs which are currently running
continue
}
if _, exists := latestJobs[workflowId]; !exists {
latestJobs[workflowId] = workflowRun
} else if latestJobs[workflowId].GetCreatedAt().Before(workflowRun.GetCreatedAt().Time) {
latestJobs[workflowId] = workflowRun
}
}
for _, workflowRun := range latestJobs {
infoLabels := prometheus.Labels{
"org": org,
"repo": repo.GetName(),
"workflowID": fmt.Sprintf("%v", workflowRun.GetWorkflowID()),
"workflow": workflowRun.GetName(),
"event": workflowRun.GetEvent(),
"branch": workflowRun.GetHeadBranch(),
"conclusion": workflowRun.GetConclusion(),
"actorLogin": workflowRun.Actor.GetLogin(),
"actorType": workflowRun.Actor.GetType(),
}
statLabels := prometheus.Labels{
"org": org,
"repo": repo.GetName(),
"workflowID": fmt.Sprintf("%v", workflowRun.GetWorkflowID()),
}
runMetric.AddInfo(infoLabels)
runTimestampMetric.AddTime(statLabels, workflowRun.GetRunStartedAt().Time)
runDurationMetric.Add(statLabels, workflowRun.GetUpdatedAt().Sub(workflowRun.GetCreatedAt().Time).Seconds())
}
}
func (m *MetricsCollectorGithubWorkflows) collectConsecutiveFailures(org string, repo *github.Repository, workflowRun []*github.WorkflowRun, callback chan<- func()) {
consecutiveFailuresMetric := m.Collector.GetMetricList("workflowConsecutiveFailures")
consecutiveFailMap := map[int64]*struct {
count int64
labels prometheus.Labels
}{}
consecutiveFinishedMap := map[int64]bool{}
for _, row := range workflowRun {
workflowRun := row
workflowId := workflowRun.GetWorkflowID()
// ignore running/not finished workflow runs
switch workflowRun.GetStatus() {
case "in_progress":
continue
case "action_required":
continue
case "queued":
continue
case "waiting":
continue
case "pending":
continue
}
if _, exists := consecutiveFailMap[workflowId]; !exists {
consecutiveFailMap[workflowId] = &struct {
count int64
labels prometheus.Labels
}{
count: 0,
labels: prometheus.Labels{
"org": org,
"repo": repo.GetName(),
"workflowID": fmt.Sprintf("%v", workflowRun.GetWorkflowID()),
"workflow": workflowRun.GetName(),
"branch": workflowRun.GetHeadBranch(),
"actorLogin": workflowRun.Actor.GetLogin(),
"actorType": workflowRun.Actor.GetType(),
},
}
consecutiveFinishedMap[workflowId] = false
}
// successful run found for workload id, skipping all further runs
if consecutiveFinishedMap[workflowId] {
continue
}
switch workflowRun.GetConclusion() {
case "":
continue
case "failure":
consecutiveFailMap[workflowId].count++
case "success":
consecutiveFinishedMap[workflowId] = true
}
}
// process metrics
for _, row := range consecutiveFailMap {
consecutiveFailuresMetric.Add(row.labels, float64(row.count))
}
}