forked from docker-library/meta-scripts
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Jenkinsfile.trigger
189 lines (176 loc) · 5.51 KB
/
Jenkinsfile.trigger
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
// one job per arch (for now) that triggers builds for all unbuilt images
properties([
disableConcurrentBuilds(),
disableResume(),
durabilityHint('PERFORMANCE_OPTIMIZED'),
pipelineTriggers([
upstream(threshold: 'UNSTABLE', upstreamProjects: 'meta'),
]),
])
env.BASHBREW_ARCH = env.JOB_NAME.split('/')[-1].minus('trigger-') // "windows-amd64", "arm64v8", etc
def queue = []
def breakEarly = false // thanks Jenkins...
// this includes the number of attempts per failing buildId
// { buildId: { "count": 1, ... }, ... }
def pastFailedJobsJson = '{}'
node {
stage('Checkout') {
checkout(scmGit(
userRemoteConfigs: [[
url: 'https://github.com/docker-library/meta.git',
name: 'origin',
]],
branches: [[name: '*/main']],
extensions: [
submodule(
parentCredentials: true,
recursiveSubmodules: true,
trackingSubmodules: true,
),
cleanBeforeCheckout(),
cleanAfterCheckout(),
[$class: 'RelativeTargetDirectory', relativeTargetDir: 'meta'],
],
))
pastFailedJobsJson = sh(returnStdout: true, script: '''#!/usr/bin/env bash
set -Eeuo pipefail -x
if ! json="$(wget --timeout=5 -qO- "$JOB_URL/lastSuccessfulBuild/artifact/pastFailedJobs.json")"; then
echo >&2 'failed to get pastFailedJobs.json'
json='{}'
fi
jq <<<"$json" '.'
''').trim()
}
dir('meta') {
def queueJson = ''
stage('Queue') {
withEnv([
'pastFailedJobsJson=' + pastFailedJobsJson,
]) {
// using pastFailedJobsJson, sort the needs_build queue so that failing builds always live at the bottom of the queue
queueJson = sh(returnStdout: true, script: '''
jq -L.scripts '
include "meta";
include "jenkins";
(env.pastFailedJobsJson | fromjson) as $pastFailedJobs
| [
.[]
| select(
needs_build
and (
.build.arch as $arch
| if env.BASHBREW_ARCH == "gha" then
[ "amd64", "i386", "windows-amd64" ]
else [ env.BASHBREW_ARCH ] end
| index($arch)
)
)
| if env.BASHBREW_ARCH == "gha" then
.gha_payload = (gha_payload | @json)
else . end
]
# this Jenkins job exports a JSON file that includes the number of attempts so far per failing buildId so that this can sort by attempts which means failing builds always live at the bottom of the queue (sorted by the number of times they have failed, so the most failing is always last)
| sort_by($pastFailedJobs[.buildId].count // 0)
' builds.json
''').trim()
}
}
if (queueJson && queueJson != '[]') {
queue = readJSON(text: queueJson)
currentBuild.displayName = 'queue size: ' + queue.size() + ' (#' + currentBuild.number + ')'
} else {
currentBuild.displayName = 'empty queue (#' + currentBuild.number + ')'
breakEarly = true
return
}
}
}
if (breakEarly) { return } // thanks Jenkins...
// now that we have our parsed queue, we can release the node we're holding up (since we handle GHA builds above)
def pastFailedJobs = readJSON(text: pastFailedJobsJson)
def newFailedJobs = [:]
for (buildObj in queue) {
def identifier = buildObj.source.arches[buildObj.build.arch].tags[0]
if (buildObj.build.arch != env.BASHBREW_ARCH) {
identifier += ' (' + buildObj.build.arch + ')'
}
stage(identifier) {
def json = writeJSON(json: buildObj, returnText: true)
echo(json) // for debugging/data purposes
// "catchError" to set "stageResult" :(
catchError(message: 'Build of "' + identifier + '" failed', buildResult: 'UNSTABLE', stageResult: 'FAILURE') {
if (buildObj.gha_payload) {
node {
withEnv([
'payload=' + buildObj.gha_payload,
]) {
withCredentials([
string(
variable: 'GH_TOKEN',
credentialsId: 'github-access-token-docker-library-bot-meta',
),
]) {
sh '''
set -u +x
# https://docs.github.com/en/free-pro-team@latest/rest/actions/workflows?apiVersion=2022-11-28#create-a-workflow-dispatch-event
curl -fL \
-X POST \
-H 'Accept: application/vnd.github+json' \
-H "Authorization: Bearer $GH_TOKEN" \
-H 'X-GitHub-Api-Version: 2022-11-28' \
https://api.github.com/repos/docker-library/meta/actions/workflows/build.yml/dispatches \
-d "$payload"
'''
}
}
}
} else {
def res = build(
job: 'build-' + env.BASHBREW_ARCH,
parameters: [
string(name: 'buildId', value: buildObj.buildId),
],
propagate: false,
quietPeriod: 5, // seconds
)
if (res.result != 'SUCCESS') {
def c = 1
if (pastFailedJobs[buildObj.buildId]) {
// TODO more defensive access of .count? (it is created just below, so it should be safe)
c += pastFailedJobs[buildObj.buildId].count
}
// TODO maybe implement some amount of backoff? keep first url/endTime?
newFailedJobs[buildObj.buildId] = [
count: c,
identifier: identifier,
url: res.absoluteUrl,
endTime: (res.startTimeInMillis + res.duration) / 1000.0, // convert to seconds
]
error(res.result)
}
}
}
}
}
// save newFailedJobs so we can use it next run as pastFailedJobs
node {
def newFailedJobsJson = writeJSON(json: newFailedJobs, returnText: true)
withEnv([
'newFailedJobsJson=' + newFailedJobsJson,
]) {
stage('Archive') {
dir('builds') {
deleteDir()
sh '''#!/usr/bin/env bash
set -Eeuo pipefail -x
jq <<<"$newFailedJobsJson" '.' | tee pastFailedJobs.json
'''
archiveArtifacts(
artifacts: '*.json',
fingerprint: true,
onlyIfSuccessful: true,
)
}
}
}
}