-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtriggerAndWaitForGitHubAction.jenkinsfile
277 lines (251 loc) · 10.6 KB
/
triggerAndWaitForGitHubAction.jenkinsfile
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
273
274
275
276
277
final def Date startDate = new Date()
final def String startDateTimestamp = startDate.format("yyyy-MM-dd'T'HH:mm:ssZ")
final def long artifactPollIntervalSeconds = 15
final def long artifactPollTimeoutMinutes = 10
final def Integer artifactPollMaxConsecutiveExceptionsAllowed = 3
final def long runCompletionPollIntervalSeconds = 10
final def long runCompletionPollTimeoutMinutes = 2
final def Integer runCompletionPollMaxConsecutiveExceptionsAllowed = 3
node {
checkout scm
}
pipeline {
agent any
environment {
WORKFLOW_RUNS_PER_PAGE = "50"
ARTIFACTS_PER_PAGE = "30"
TRIGGER_ID = "TRIGGER-${UUID.randomUUID().toString()}"
GITHUB_CREDENTIALS = credentials("GITHUB_PRIVATE_REPOS_AND_WORKFLOWS_CREDENTIALS")
GITHUB_USER = "$GITHUB_CREDENTIALS_USR"
GITHUB_TOKEN = "$GITHUB_CREDENTIALS_PSW"
}
options {
timeout(time: 20, unit: "MINUTES")
}
stages {
stage("Input validation") {
steps {
script {
if (!REPO_OWNER) {
error("❌ REPO_OWNER is required")
}
if (!REPO_NAME) {
error("❌ REPO_NAME is required")
}
if (!REPO_REF) {
error("❌ REPO_REF is required")
}
if (!GITHUB_ACTION_FILE_NAME) {
error("❌ GITHUB_ACTION_FILE_NAME is required")
}
}
}
}
stage("Log environment") {
steps {
println(
"REPO_OWNER: $REPO_OWNER"
+ "\n" + "REPO_NAME: $REPO_NAME"
+ "\n" + "REPO_REF: $REPO_REF"
+ "\n" + "GITHUB_ACTION_FILE_NAME: $GITHUB_ACTION_FILE_NAME"
+ "\n" + "TRIGGER_ID: $TRIGGER_ID"
+ "\n" + "startDateTimestamp: $startDateTimestamp"
+ "\n" + "WORKFLOW_RUNS_PER_PAGE: $WORKFLOW_RUNS_PER_PAGE"
+ "\n" + "ARTIFACTS_PER_PAGE: $ARTIFACTS_PER_PAGE"
+ "\n" + "artifactPollIntervalSeconds: $artifactPollIntervalSeconds"
+ "\n" + "artifactPollTimeoutMinutes: $artifactPollTimeoutMinutes"
+ "\n" + "artifactPollMaxConsecutiveExceptionsAllowed: $artifactPollMaxConsecutiveExceptionsAllowed"
+ "\n" + "runCompletionPollIntervalSeconds: $runCompletionPollIntervalSeconds"
+ "\n" + "runCompletionPollTimeoutMinutes: $runCompletionPollTimeoutMinutes"
+ "\n" + "runCompletionPollMaxConsecutiveExceptionsAllowed: $runCompletionPollMaxConsecutiveExceptionsAllowed"
)
}
}
stage("Trigger GitHub Action") {
steps {
triggerGitHubAction()
}
}
stage("Wait for GitHub Action completion") {
steps {
waitForGitHubActionCompletion(
artifactPollIntervalSeconds, artifactPollTimeoutMinutes, artifactPollMaxConsecutiveExceptionsAllowed,
runCompletionPollIntervalSeconds, runCompletionPollTimeoutMinutes, runCompletionPollMaxConsecutiveExceptionsAllowed
)
}
}
}
post {
always {
script {
if (getContext(hudson.FilePath)) {
cleanWs deleteDirs: true
}
}
}
success {
println("✅ Success!")
}
}
}
def triggerGitHubAction() {
def url = "https://api.github.com/repos/$REPO_OWNER/$REPO_NAME/actions/workflows/$GITHUB_ACTION_FILE_NAME/dispatches"
def connection = new URL(url).openConnection()
connection.setRequestMethod("POST")
connection.setRequestProperty("Authorization", "token $GITHUB_TOKEN")
connection.setRequestProperty("Accept", "application/vnd.github.v3+json")
connection.setDoOutput(true)
def body = [
ref: "$REPO_REF",
inputs: [ trigger_id: "$TRIGGER_ID" ]
]
def json = groovy.json.JsonOutput.toJson(body)
connection.outputStream.write(json.getBytes("UTF-8"))
def responseCode = connection.getResponseCode()
if (responseCode.equals(204)) {
println(
"✅ GitHub Action '$GITHUB_ACTION_FILE_NAME' triggered for '$REPO_OWNER/$REPO_NAME'"
+ "\n🏃🏻♂️ Workflow runs: https://github.com/$REPO_OWNER/$REPO_NAME/actions/workflows/$GITHUB_ACTION_FILE_NAME"
)
} else {
throw new Exception("❌ Triggering GitHub Action '$GITHUB_ACTION_FILE_NAME' for '$REPO_OWNER/$REPO_NAME' FAILED (code $responseCode)")
}
}
def waitForGitHubActionCompletion(
artifactPollIntervalSeconds, artifactPollTimeoutMinutes, artifactPollMaxConsecutiveExceptionsAllowed,
runCompletionPollIntervalSeconds, runCompletionPollTimeoutMinutes, runCompletionPollMaxConsecutiveExceptionsAllowed
) {
def workflowRuns = poll(
artifactPollIntervalSeconds,
artifactPollTimeoutMinutes,
artifactPollMaxConsecutiveExceptionsAllowed,
{ fetchWorkflowRuns() },
{ workflowRuns -> doesTriggerIdArtifactExist(workflowRuns) }
)
def runId = workflowRunWithTriggerIdArtifact(workflowRuns).id
def runDetails = poll(
runCompletionPollIntervalSeconds,
runCompletionPollTimeoutMinutes,
runCompletionPollMaxConsecutiveExceptionsAllowed,
{ fetchWorkflowRunDetails(runId) },
{ runDetails -> didWorkflowRunComplete(runDetails) }
)
if (runDetails.conclusion == "success") {
println(
"✅ Workflow run with ID $runDetails.id completed successfully"
+ "\n🏃🏻♂️ Workflow run: https://github.com/$REPO_OWNER/$REPO_NAME/actions/runs/$runDetails.id"
)
} else {
error(
"❌ Workflow run with ID $runDetails.id completed unsuccessfully (conclusion: '$runDetails.conclusion')"
+ "\n🏃🏻♂️ Workflow run: https://github.com/$REPO_OWNER/$REPO_NAME/actions/runs/$runDetails.id"
)
}
}
def fetchWorkflowRuns() {
def url = "https://api.github.com/repos/$REPO_OWNER/$REPO_NAME/actions/workflows/$GITHUB_ACTION_FILE_NAME/runs?per_page=$WORKFLOW_RUNS_PER_PAGE"
def connection = new URL(url).openConnection()
connection.setRequestMethod("GET")
connection.setRequestProperty("Authorization", "token $GITHUB_TOKEN")
connection.setRequestProperty("Accept", "application/vnd.github.v3+json")
connection.setDoOutput(true)
def responseCode = connection.getResponseCode()
if (responseCode.equals(200)) {
def responseBody = jsonDecode(connection.getInputStream().getText())
return responseBody.workflow_runs.collect { [ id: it.id, created_at: it.created_at ] }
} else {
throw new Exception("❌ Fetching workflow runs FAILED (code $responseCode)")
}
}
def fetchWorkflowRunArtifacts(runId) {
def url = "https://api.github.com/repos/$REPO_OWNER/$REPO_NAME/actions/runs/$runId/artifacts?per_page=$ARTIFACTS_PER_PAGE"
def connection = new URL(url).openConnection()
connection.setRequestMethod("GET")
connection.setRequestProperty("Authorization", "token $GITHUB_TOKEN")
connection.setRequestProperty("Accept", "application/vnd.github.v3+json")
connection.setDoOutput(true)
def responseCode = connection.getResponseCode()
if (responseCode.equals(200)) {
def responseBody = jsonDecode(connection.getInputStream().getText())
return responseBody.artifacts.collect({ it.name })
} else {
throw new Exception("❌ Fetching workflow run artifacts FAILED (code $responseCode)")
}
}
def Boolean doesTriggerIdArtifactExist(workflowRuns) {
def run = workflowRunWithTriggerIdArtifact(workflowRuns)
if (run == null) {
println("⏱ Trigger ID $TRIGGER_ID named artifact NOT yet found among workflow runs")
} else {
println(
"✅ Trigger ID $TRIGGER_ID FOUND for workflow run ID $run.id (created at $run.created_at)"
+ "\n🏃🏻♂️ Workflow run: https://github.com/$REPO_OWNER/$REPO_NAME/actions/runs/$run.id"
)
}
return run != null
}
def workflowRunWithTriggerIdArtifact(workflowRuns) {
return workflowRuns.find {
def artifacts = fetchWorkflowRunArtifacts(it.id)
return artifacts.contains(TRIGGER_ID)
}
}
def fetchWorkflowRunDetails(runId) {
def url = "https://api.github.com/repos/$REPO_OWNER/$REPO_NAME/actions/runs/$runId"
def connection = new URL(url).openConnection()
connection.setRequestMethod("GET")
connection.setRequestProperty("Authorization", "token $GITHUB_TOKEN")
connection.setRequestProperty("Accept", "application/vnd.github.v3+json")
connection.setDoOutput(true)
def responseCode = connection.getResponseCode()
if (responseCode.equals(200)) {
def responseBody = jsonDecode(connection.getInputStream().getText())
return responseBody
} else {
throw new Exception("❌ Fetching workflow run FAILED (code $responseCode)")
}
}
def Boolean didWorkflowRunComplete(runDetails) {
def Boolean result = runDetails.status == "completed"
if (!result) {
println("⏱ Workflow run with ID $runDetails.id NOT yet completed (status: '$runDetails.status')")
}
return result
}
def <T> T poll(pollIntervalSeconds, timeoutMinutes, maxConsecutiveExceptionsAllowed, functionToPoll, successConditionOnFnResult) {
def Boolean isDone = false
def Boolean isTimeout = false
def Integer exceptionCounter = 0
def T result
def long timeoutDateMillis = new Date().getTime() + 60 * 1000 * timeoutMinutes
while (!isDone && !isTimeout) {
try {
result = functionToPoll()
isDone = successConditionOnFnResult(result)
exceptionCounter = 0
} catch(e) {
exceptionCounter += 1
if (exceptionCounter > maxConsecutiveExceptionsAllowed) {
throw new Exception("Polling failed: base function threw $exceptionCounter exceptions in a row. Last exception: $e.message")
}
}
if (!isDone) {
sleep(time: pollIntervalSeconds, unit: 'SECONDS')
}
isTimeout = new Date().getTime() >= timeoutDateMillis
}
if (isDone) {
return result
}
if (isTimeout) {
throw new Exception("Polling timed out after $timeoutMinutes minutes")
}
}
@NonCPS
def jsonDecode(jsonText) {
return new groovy.json.JsonSlurperClassic().parseText(jsonText)
}
@NonCPS
def jsonEncode(obj) {
return new groovy.json.JsonBuilder(obj).toPrettyString()
}