-
Notifications
You must be signed in to change notification settings - Fork 14
/
Jenkinsfile.trigger
224 lines (208 loc) · 7.19 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
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
// 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.minus('/trigger').split('/')[-1] // "windows-amd64", "arm64v8", etc
def queue = []
def breakEarly = false // thanks Jenkins...
// string filled with all images needing build and whether they were skipped this time for recording after queue completion
// { buildId: { "count": 1, skip: 0, ... }, ... }
def currentJobsJson = ''
node {
stage('Checkout') {
checkout(scmGit(
userRemoteConfigs: [[
url: 'https://github.com/docker-library/meta.git',
name: 'origin',
]],
branches: [[name: '*/main']],
extensions: [
cloneOption(
noTags: true,
shallow: true,
depth: 1,
),
submodule(
parentCredentials: true,
recursiveSubmodules: true,
trackingSubmodules: true,
),
cleanBeforeCheckout(),
cleanAfterCheckout(),
[$class: 'RelativeTargetDirectory', relativeTargetDir: 'meta'],
],
))
}
dir('meta') {
stage('Queue') {
// using pastJobsJson, sort the needs_build queue so that previously attempted builds always live at the bottom of the queue
// list of builds that have been failing and will be skipped this trigger
def queueAndFailsJson = sh(returnStdout: true, script: '''
if \\
! wget --timeout=5 -qO past-jobs.json "$JOB_URL/lastSuccessfulBuild/artifact/past-jobs.json" \\
|| ! jq 'empty' past-jobs.json \\
; then
echo '{}' > past-jobs.json
fi
jq -c -L.scripts --slurpfile pastJobs past-jobs.json '
include "jenkins";
get_arch_queue as $rawQueue
| $rawQueue | jobs_record($pastJobs[0]) as $newJobs
| $rawQueue | filter_skips_queue($newJobs) as $filteredQueue
| (
($rawQueue | length) - ($filteredQueue | length)
) as $skippedCount
# queue, skips/builds record, number of skipped items
| $filteredQueue, $newJobs, $skippedCount
' builds.json
''').tokenize('\r\n')
def queueJson = queueAndFailsJson[0]
currentJobsJson = queueAndFailsJson[1]
def skips = queueAndFailsJson[2].toInteger()
//echo(queueJson)
def jobName = ''
if (queueJson && queueJson != '[]') {
queue = readJSON(text: queueJson)
jobName += 'queue: ' + queue.size()
} else {
jobName += 'queue: 0'
breakEarly = true
}
if (skips > 0) {
jobName += ' skip: ' + skips
if (breakEarly) {
// if we're skipping some builds but the effective queue is empty, we want to set the job as "unstable" instead of successful (so we know there's still *something* that needs to build but it isn't being built right now)
currentBuild.result = 'UNSTABLE'
}
// queue to build might be empty, be we still need to record these skipped builds
breakEarly = false
}
currentBuild.displayName = jobName + ' (#' + currentBuild.number + ')'
}
}
}
// with an empty queue and nothing to skip we can end early
if (breakEarly) { return } // thanks Jenkins...
// new data to be added to the past-jobs.json
// { lastTime: unixTimestamp, url: "" }
buildCompletionData = [:]
// list of closures that we can use to wait for the jobs on.
def waitQueue = [:]
def waitQueueClosure(identifier, buildId, externalizableId) {
return {
stage(identifier) {
// "catchError" to set "stageResult" :(
catchError(message: 'Build of "' + identifier + '" failed', buildResult: 'UNSTABLE', stageResult: 'FAILURE') {
def res = waitForBuild(
runId: externalizableId,
propagateAbort: true, // allow cancelling this job to cancel all the triggered jobs
)
buildCompletionData[buildId] = [
lastTime: (res.startTimeInMillis + res.duration) / 1000, // convert to seconds
url: res.absoluteUrl,
]
if (res.result != 'SUCCESS') {
// set stage result via catchError
error(res.result)
}
}
}
}
}
// stage to wrap up all the build job triggers that get waited on later
stage('trigger') {
for (buildObj in queue) {
if (buildObj.gha_payload) {
stage(buildObj.identifier) {
// "catchError" to set "stageResult" :(
catchError(message: 'Build of "' + buildObj.identifier + '" failed', buildResult: 'UNSTABLE', stageResult: 'FAILURE') {
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"
'''
}
}
// record that GHA was triggered (for tracking continued triggers that fail to push an image)
buildCompletionData[buildObj.buildId] = [
lastTime: System.currentTimeMillis() / 1000, // convert to seconds
url: currentBuild.absoluteUrl,
]
}
}
}
} else {
// "catchError" to set "stageResult" :(
catchError(message: 'Build of "' + buildObj.identifier + '" failed', buildResult: 'UNSTABLE', stageResult: 'FAILURE') {
// why not parallel these build() invocations?
// jenkins parallel closures get started in a randomish order, ruining our sorted queue
def res = build(
job: 'build',
parameters: [
string(name: 'buildId', value: buildObj.buildId),
string(name: 'identifier', value: buildObj.identifier),
],
propagate: false,
// trigger these quickly so they all get added to Jenkins queue in "queue" order (also using "waitForStart" means we have to wait for the entire "quietPeriod" before we get to move on and schedule more)
quietPeriod: 0, // seconds
// we'll wait on the builds in parallel after they are all queued (so our sorted order is the queue order)
waitForStart: true,
)
waitQueue[buildObj.identifier] = waitQueueClosure(buildObj.identifier, buildObj.buildId, res.externalizableId)
}
}
}
}
// wait on all the 'build' jobs that were queued
if (waitQueue.size() > 0) {
parallel waitQueue
}
// save currentJobs so we can use it next run as pastJobs
node {
def buildCompletionDataJson = writeJSON(json: buildCompletionData, returnText: true)
withEnv([
'buildCompletionDataJson=' + buildCompletionDataJson,
'currentJobsJson=' + currentJobsJson,
]) {
stage('Archive') {
dir('builds') {
deleteDir()
sh '''#!/usr/bin/env bash
set -Eeuo pipefail -x
jq <<<"$currentJobsJson" '
# save firstTime if it is not set yet
map_values(.firstTime //= .lastTime)
# merge the two objects recursively, preferring data from "buildCompletionDataJson"
| . * ( env.buildCompletionDataJson | fromjson )
' | tee past-jobs.json
'''
archiveArtifacts(
artifacts: '*.json',
fingerprint: true,
onlyIfSuccessful: true,
)
}
}
}
}