Skip to content

Commit 229a85b

Browse files
avivkellerTrott
authored andcommitted
feat: post CI results in PRs
Signed-off-by: avivkeller <me@aviv.sh>
1 parent 6cc4382 commit 229a85b

15 files changed

Lines changed: 5786 additions & 238 deletions

‎README.md‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,8 @@ See [CONTRIBUTING.md](CONTRIBUTING.md).
1717
- **`GITHUB_WEBHOOK_SECRET`**<br>
1818
The webhook secret that GitHub signs the POSTed payloads with. This is created when the webhook is defined. The default is `hush-hush`.
1919
- **`JENKINS_WORKER_IPS`**<br>
20-
List of valid Jenkins worker IPs allowed to push PR status updates, split by comma: `192.168.1.100,192.168.1.101`.
20+
Required list of valid Jenkins worker IPs allowed to push PR status updates, split by comma:
21+
`192.168.1.100,192.168.1.101`. Jenkins callbacks are rejected when this variable is not set.
2122
- **`JENKINS_API_CREDENTIALS`** (optional)<br>
2223
For scripts that communicate with Jenkins on http://ci.nodejs.org. The Jenkins API token is visible on
2324
your own profile page `https://ci.nodejs.org/user/<YOUR_GITHUB_USERNAME>/configure`, by clicking the

‎lib/jenkins-ci-results.js‎

Lines changed: 132 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,132 @@
1+
import { Writable } from 'node:stream'
2+
3+
import CLI from '@node-core/utils/lib/cli.js'
4+
import Request from '@node-core/utils/lib/request.js'
5+
import { PRBuild } from '@node-core/utils/lib/ci/build-types/pr_build.js'
6+
7+
import { createPrComment } from './github-comment.js'
8+
9+
const maxCommentLength = 60_000
10+
11+
function findLastDetailsCloseOutsideFence (markdown) {
12+
let inCodeFence = false
13+
let lastDetailsClose = -1
14+
let offset = 0
15+
16+
for (const line of markdown.split('\n')) {
17+
if (line.trimStart().startsWith('```')) {
18+
inCodeFence = !inCodeFence
19+
} else if (!inCodeFence) {
20+
const closeIndex = line.lastIndexOf('</details>')
21+
if (closeIndex !== -1) {
22+
lastDetailsClose = offset + closeIndex + '</details>'.length
23+
}
24+
}
25+
offset += line.length + 1
26+
}
27+
28+
return lastDetailsClose
29+
}
30+
31+
export function extractBuildNumber (build) {
32+
// e.g. https://ci.nodejs.org/job/node-test-pull-request/21633/
33+
const match = /\/job\/node-test-pull-request\/(\d+)/.exec(build.url || '')
34+
return match ? parseInt(match[1], 10) : null
35+
}
36+
37+
export async function fetchResultsMarkdown (buildNumber, destination) {
38+
// node-core-utils insists on writing progress output to a stream
39+
const nullStream = new Writable({ write (chunk, encoding, callback) { callback() } })
40+
const cli = new CLI(nullStream)
41+
const request = new Request({
42+
jenkins: Buffer.from(process.env.JENKINS_API_CREDENTIALS).toString('base64')
43+
})
44+
45+
const prBuild = new PRBuild(cli, request, buildNumber)
46+
const results = await prBuild.getResults()
47+
throwOnTopLevelRetrievalFailure(results)
48+
49+
validateBuildDestination(prBuild.params, destination)
50+
return prBuild.formatAsMarkdown()
51+
}
52+
53+
export function throwOnTopLevelRetrievalFailure (results) {
54+
if (!Array.isArray(results)) return
55+
56+
const requestFailure = results.find(failure => failure?.type === 'NCU_FAILURE')
57+
if (requestFailure) {
58+
throw new Error(`Unable to retrieve Jenkins CI results: ${requestFailure.reason}`)
59+
}
60+
}
61+
62+
export function validateBuildDestination (params, { owner, repo, pr }) {
63+
const matches =
64+
params.TARGET_GITHUB_ORG?.toLowerCase() === owner.toLowerCase() &&
65+
params.TARGET_REPO_NAME?.toLowerCase() === repo.toLowerCase() &&
66+
String(params.PR_ID) === String(pr)
67+
68+
if (!matches) {
69+
throw new Error('Jenkins build does not belong to the destination pull request')
70+
}
71+
}
72+
73+
export function limitResultsMarkdown (markdown, buildUrl) {
74+
if (markdown.length <= maxCommentLength) return markdown
75+
76+
const notice = `\n\n---\nCI results were truncated. [View the complete results in Jenkins](${buildUrl}).`
77+
const availableLength = maxCommentLength - notice.length
78+
let truncated = markdown.slice(0, availableLength)
79+
80+
// node-core-utils puts detailed failures in <details> blocks containing
81+
// fenced code. Avoid cutting a block in half and producing broken Markdown.
82+
const firstDetails = truncated.indexOf('<details>')
83+
const lastCompleteDetails = findLastDetailsCloseOutsideFence(truncated)
84+
if (firstDetails !== -1) {
85+
if (lastCompleteDetails === -1) {
86+
const closing = '\n... diagnostic output truncated ...\n```\n</details>'
87+
const openingFence = markdown.indexOf('```', firstDetails)
88+
const excerptLength = availableLength - closing.length
89+
90+
truncated = openingFence !== -1 && openingFence < excerptLength
91+
? markdown.slice(0, excerptLength).trimEnd() + closing
92+
: truncated.slice(0, firstDetails)
93+
} else {
94+
truncated = truncated.slice(0, lastCompleteDetails)
95+
}
96+
}
97+
98+
return truncated.trimEnd() + notice
99+
}
100+
101+
export async function postBuildResults (options, build, fetchResults = fetchResultsMarkdown) {
102+
const { pr } = options
103+
const buildNumber = extractBuildNumber(build)
104+
105+
const traceFields = { pr, job: build.identifier, gitRef: build.ref, buildNumber }
106+
const logger = options.logger.child(traceFields, true)
107+
108+
if (!process.env.JENKINS_API_CREDENTIALS) {
109+
logger.info('JENKINS_API_CREDENTIALS is not set, skipping CI results comment')
110+
return
111+
}
112+
113+
if (buildNumber === null) {
114+
logger.warn('Unable to find build number in build URL, skipping CI results comment')
115+
return
116+
}
117+
118+
const markdown = await fetchResults(buildNumber, {
119+
owner: options.owner,
120+
repo: options.repo,
121+
pr
122+
})
123+
124+
if (!markdown) {
125+
logger.warn('Got no CI results back from node-core-utils, skipping CI results comment')
126+
return
127+
}
128+
129+
const comment = limitResultsMarkdown(markdown, build.url)
130+
await createPrComment({ issue_number: pr, ...options, logger }, comment)
131+
logger.info('Jenkins CI results comment posted')
132+
}

‎lib/jenkins-events.js‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -7,12 +7,13 @@ const enabledRepos = process.env.JENKINS_ENABLED_REPOS
77
? process.env.JENKINS_ENABLED_REPOS.split(',')
88
: ['citgm', 'http-parser', 'node', 'node-auto-test']
99

10-
const listOfKnownJenkinsIps = process.env.JENKINS_WORKER_IPS ? process.env.JENKINS_WORKER_IPS.split(',') : []
11-
1210
function isKnownJenkinsIp (req) {
1311
const ip = req.connection.remoteAddress.split(':').pop()
12+
const listOfKnownJenkinsIps = process.env.JENKINS_WORKER_IPS
13+
? process.env.JENKINS_WORKER_IPS.split(',')
14+
: []
1415

15-
if (listOfKnownJenkinsIps.length && !listOfKnownJenkinsIps.includes(ip)) {
16+
if (!listOfKnownJenkinsIps.includes(ip)) {
1617
req.log.warn({ ip }, 'Ignoring, not allowed to push Jenkins updates')
1718
return false
1819
}

‎lib/push-jenkins-update.js‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import githubClient from './github-client.js'
22
import { createPrComment } from './github-comment.js'
3+
import { postBuildResults } from './jenkins-ci-results.js'
34

45
export function pushStarted (options, build, cb) {
56
const pr = findPrInRef(build.ref)
@@ -54,6 +55,14 @@ export function pushEnded (options, build, cb) {
5455

5556
const optsWithPr = Object.assign({ pr }, options)
5657

58+
if (build.identifier === 'node-test-pull-request' && build.status === 'failure') {
59+
// fetching the CI results involves many Jenkins API calls, so let them
60+
// finish in the background instead of holding up the status update
61+
postBuildResults(optsWithPr, build).catch((err) => {
62+
logger.error(err, 'Error while posting Jenkins CI results')
63+
})
64+
}
65+
5766
findLatestCommitInPr(optsWithPr).then(latestCommit => {
5867
const statusOpts = Object.assign({
5968
sha: latestCommit.sha,

0 commit comments

Comments
 (0)