forked from docker-library/meta-scripts
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Jenkinsfile.trigger
194 lines (180 loc) · 5.9 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
// 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
# temporary migration of old data
if ! wget --timeout=5 -qO past-jobs.json "$JOB_URL/lastSuccessfulBuild/artifact/pastFailedJobs.json" || ! jq 'empty' past-jobs.json; then
echo '{}' > past-jobs.json
fi
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: "" }
def buildCompletionData = [:]
for (buildObj in queue) {
stage(buildObj.identifier) {
//def json = writeJSON(json: buildObj, returnText: true)
//echo(json) // for debugging/data purposes
// "catchError" to set "stageResult" :(
catchError(message: 'Build of "' + buildObj.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"
'''
}
}
// 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 {
def res = build(
job: 'build',
parameters: [
string(name: 'buildId', value: buildObj.buildId),
],
propagate: false,
quietPeriod: 5, // seconds
)
// record the job failure
buildCompletionData[buildObj.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)
}
}
}
}
}
// 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" '
# merge the two objects recursively, preferring data from "buildCompletionDataJson"
. * ( env.buildCompletionDataJson | fromjson )
' | tee past-jobs.json
'''
archiveArtifacts(
artifacts: '*.json',
fingerprint: true,
onlyIfSuccessful: true,
)
}
}
}
}