-
Notifications
You must be signed in to change notification settings - Fork 1
/
agent_job_history.go
90 lines (81 loc) · 2.12 KB
/
agent_job_history.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
package gocdexporter
import (
"fmt"
"github.com/pagero/go-gocd-ashwanth"
"sort"
"time"
)
type AgentJobHistoryCache map[string]string
type AgentJobHistory struct {
AgentJobHistory map[string][]*JobHistory
}
type JobHistory struct {
*gocd.AgentJobHistory
}
func (j *JobHistory) GetOrderedStateTransitions() []gocd.AgentJobStateTransition {
t := j.JobStateTransitions
sort.Slice(t, func(i, j int) bool {
t1, err := time.Parse(time.RFC3339, t[i].StateChangeTime)
if err != nil {
return false
}
t2, err := time.Parse(time.RFC3339, t[j].StateChangeTime)
if err != nil {
return false
}
return t1.Unix() < t2.Unix()
})
return t
}
func (a *AgentJobHistory) Add(agent string, jobHistory *JobHistory) {
if len(a.AgentJobHistory) == 0 {
a.AgentJobHistory = make(map[string][]*JobHistory)
}
a.AgentJobHistory[agent] = append(a.AgentJobHistory[agent], jobHistory)
}
func (a *AgentJobHistory) GetJobHistory(client gocd.Client, agents []*gocd.Agent, cache AgentJobHistoryCache) error {
offset := 0
pageSize := 100
for _, agent := range agents {
firstRun := false
cachedJobID := cache[agent.Hostname]
if cachedJobID == "" {
firstRun = true
}
history, err := client.AgentRunJobHistory(agent.UUID, offset, pageSize)
if err != nil {
return err
}
jobs := history.Jobs
firstID := ""
if len(jobs) > 0 {
firstID = getJobID(&JobHistory{jobs[0]})
if firstID != cachedJobID {
cache[agent.Hostname] = firstID
}
}
for _, job := range jobs {
jh := &JobHistory{job}
if cachedJobID == getJobID(jh) && !firstRun {
break
}
a.Add(agent.Hostname, jh)
}
}
return nil
}
func getJobID(jh *JobHistory) string {
return fmt.Sprintf("%v-%v-%v-%v-%v", jh.PipelineName, jh.PipelineCounter, jh.StageName, jh.StageCounter, jh.Name)
}
func (ajh *JobHistory) getScheduled() (int64, error) {
for _, t := range ajh.JobStateTransitions {
if t.State == "Scheduled" {
timestamp, err := time.Parse(time.RFC3339, t.StateChangeTime)
if err != nil {
return 0, err
}
return timestamp.Unix(), nil
}
}
return 0, fmt.Errorf("Could not find Scheduled time for job with id: %v", getJobID(ajh))
}