-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgithub.go
272 lines (229 loc) · 6.53 KB
/
github.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
package main
import (
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"slices"
"strings"
"time"
)
type StatusWriter interface {
Write(status string)
}
type GithubClientConfig struct {
Token string
OrgRepo string
Org string
Timeout time.Duration
CheckInterval time.Duration
}
type GitHubClient struct {
Config GithubClientConfig
}
func NewGitHubClient(sw StatusWriter, config GithubClientConfig) *GitHubClient {
if config.Timeout == 0 {
config.Timeout = 30 * time.Second
}
if config.CheckInterval == 0 {
config.CheckInterval = 1 * time.Second
}
return &GitHubClient{Config: config}
}
func (g *GitHubClient) callAPI(method, url string, body io.Reader) (*http.Response, error) {
req, err := http.NewRequest(method, url, body)
if err != nil {
return nil, fmt.Errorf("failed to create request: %w", err)
}
req.Header.Set("Authorization", "Bearer "+g.Config.Token)
req.Header.Set("Accept", "application/vnd.github.v3+json")
req.Header.Set("Content-Type", "application/json")
client := &http.Client{Timeout: g.Config.Timeout}
resp, err := client.Do(req)
if err != nil {
return nil, fmt.Errorf("failed to call API: %w", err)
}
return resp, nil
}
func (g *GitHubClient) IsImageAlreadyMirrored(image string) (bool, time.Duration) {
_, remainder, tag := splitDockerImageParts(image)
container := shortenRemainder(remainder)
container = strings.ReplaceAll(container, "/", "%2F")
url := fmt.Sprintf("https://api.github.com/orgs/%s/packages/container/%s/versions", g.Config.Org, container)
resp, err := g.callAPI("GET", url, nil)
if err != nil {
log.Printf("failed to call api for checking mirrored image: %v", err)
return false, 0
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return false, 0
}
var versions []struct {
UpdatedAt time.Time `json:"updated_at"`
Metadata struct {
Container struct {
Tags []string `json:"tags"`
} `json:"container"`
} `json:"metadata"`
}
if err := json.NewDecoder(resp.Body).Decode(&versions); err != nil {
log.Printf("failed to decode response json: %v", err)
return false, 0
}
if len(versions) == 0 {
return false, 0
}
var lastTimestamp time.Time
for _, version := range versions {
if slices.Contains(version.Metadata.Container.Tags, tag) {
if lastTimestamp.Before(version.UpdatedAt) {
lastTimestamp = version.UpdatedAt
}
}
}
if lastTimestamp.IsZero() {
return false, 0
}
return true, time.Since(lastTimestamp)
}
func (g *GitHubClient) LaunchGithubAction(image, id string) error {
_, remainder, tag := splitDockerImageParts(image)
remainder = shortenRemainder(remainder)
payload := map[string]interface{}{
"ref": "main",
"inputs": map[string]string{
"image_name": fmt.Sprintf("%s:%s", remainder, tag),
"id": id,
},
}
payloadBytes, err := json.Marshal(payload)
if err != nil {
return fmt.Errorf("failed to marshall json: %w", err)
}
url := fmt.Sprintf("https://api.github.com/repos/%s/actions/workflows/mirror.yml/dispatches", g.Config.OrgRepo)
_, err = g.callAPI("POST", url, strings.NewReader(string(payloadBytes)))
if err != nil {
return fmt.Errorf("failed to call dispatch workflow: %w", err)
}
return nil
}
type runsResponse struct {
WorkflowRuns []struct {
ID int `json:"id"`
Status string `json:"status"`
JobsURL string `json:"jobs_url"`
} `json:"workflow_runs"`
}
func (g *GitHubClient) getLastRuns() (*runsResponse, error) {
var dateFilter string = "%3E" + time.Now().UTC().Add(-5*time.Minute).Format("2006-01-02T15:04")
url := fmt.Sprintf("https://api.github.com/repos/%s/actions/runs?created=%s", g.Config.OrgRepo, dateFilter)
resp, err := g.callAPI("GET", url, nil)
if err != nil {
return nil, fmt.Errorf("failed to call api: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("call api ended with status: %s", resp.Status)
}
var runs runsResponse
if err := json.NewDecoder(resp.Body).Decode(&runs); err != nil {
return nil, fmt.Errorf("failed to decode response json: %w", err)
}
return &runs, nil
}
type jobsResponse struct {
Jobs []struct {
ID int `json:"id"`
Name string `json:"name"`
RunID int `json:"run_id"`
Steps []struct {
Name string `json:"name"`
Status string `json:"status"`
} `json:"steps"`
} `json:"jobs"`
}
func (c *GitHubClient) getJobs(url string) (*jobsResponse, error) {
resp, err := c.callAPI("GET", url, nil)
if err != nil {
return nil, fmt.Errorf("failed to call API: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("call API ended with status: %s", resp.Status)
}
var jobs jobsResponse
if err := json.NewDecoder(resp.Body).Decode(&jobs); err != nil {
return nil, fmt.Errorf("failed to decode response json: %w", err)
}
return &jobs, nil
}
func (g *GitHubClient) FollowWorkflowRun(sw StatusWriter, id string) error {
var workflowID = ""
var workflow_jobs_url = ""
for workflowID == "" {
// Get the list of workflow runs
runs, err := g.getLastRuns()
if err != nil {
return fmt.Errorf("failed to get last runs: %w", err)
}
if len(runs.WorkflowRuns) == 0 {
sw.Write("⏳ No workflow runs found yet")
time.Sleep(g.Config.CheckInterval)
continue // Retry
}
// Get the latest workflow run
for _, run := range runs.WorkflowRuns {
jobs, err := g.getJobs(run.JobsURL)
if err != nil {
return fmt.Errorf("failed to get jobs: %w", err)
}
for _, job := range jobs.Jobs {
for _, step := range job.Steps {
if step.Name == id {
workflowID = fmt.Sprintf("%d", job.RunID)
break
}
}
if workflowID != "" {
workflow_jobs_url = run.JobsURL
break
}
}
if workflowID != "" {
break
}
}
}
sw.Write(fmt.Sprintf("✨ Workflow run found – https://github.com/%s/actions/runs/%s", g.Config.OrgRepo, workflowID))
stepsStatus := make(map[string]string)
for {
jobs, err := g.getJobs(workflow_jobs_url)
if err != nil {
return fmt.Errorf("failed to get jobs: %w", err)
}
allFinished := true
for _, job := range jobs.Jobs {
if job.Name == "Workflow ID Provider" {
continue
}
for i, step := range job.Steps {
if step.Status != "completed" {
allFinished = false
} else {
if _, exists := stepsStatus[step.Name]; !exists {
stepsStatus[step.Name] = step.Status
sw.Write(fmt.Sprintf("🔄 Completed step %d/%d: %s", i+1, len(job.Steps), step.Name))
}
}
}
}
if allFinished {
sw.Write("🎉 All workflow steps completed")
break
}
time.Sleep(g.Config.CheckInterval)
}
return nil
}