Skip to content

Commit 139cb5a

Browse files
authored
[7.17] [Gradle] Fix build finished hooks on ci when using configuration cache (#116888) (#122744)
* [Gradle] Fix build finished hooks on ci when using configuration cache (#116888) Fixes two incompatibilities with Gradle configuration cache in our build scan build finished hook: referencing static methods from build script referencing gradle object from closure (cherry picked from commit 929d398) # Conflicts: # build-tools-internal/src/main/groovy/elasticsearch.build-scan.gradle * Update elasticsearch.build-scan.gradle fix license * Fix license header
1 parent fbce9c5 commit 139cb5a

File tree

3 files changed

+157
-147
lines changed

3 files changed

+157
-147
lines changed

build-tools-internal/src/main/groovy/elasticsearch.build-scan.gradle

+102-147
Original file line numberDiff line numberDiff line change
@@ -10,173 +10,128 @@ import java.lang.management.ManagementFactory;
1010
import java.time.LocalDateTime;
1111

1212
import org.elasticsearch.gradle.Architecture
13-
import org.elasticsearch.gradle.OS
1413
import org.elasticsearch.gradle.internal.info.BuildParams
15-
import org.gradle.initialization.BuildRequestMetaData
14+
import org.elasticsearch.gradle.OS
15+
import static org.elasticsearch.gradle.internal.util.CiUtils.safeName
1616

17-
buildScan {
18-
URL jenkinsUrl = System.getenv('JENKINS_URL') ? new URL(System.getenv('JENKINS_URL')) : null
19-
String buildKiteUrl = System.getenv('BUILDKITE_BUILD_URL') ? System.getenv('BUILDKITE_BUILD_URL') : null
17+
import java.lang.management.ManagementFactory
18+
import java.time.LocalDateTime
2019

21-
// Automatically publish scans from Elasticsearch CI
22-
if (jenkinsUrl?.host?.endsWith('elastic.co') || jenkinsUrl?.host?.endsWith('elastic.dev') || System.getenv('BUILDKITE') == 'true') {
23-
publishAlways()
24-
buildScan.server = 'https://gradle-enterprise.elastic.co'
25-
}
20+
// Resolving this early to avoid issues with the build scan plugin in combination with the configuration cache usage
21+
def taskNames = gradle.startParameter.taskNames.join(' ')
22+
23+
develocity {
2624

27-
background {
28-
tag OS.current().name()
29-
tag Architecture.current().name()
25+
buildScan {
3026

31-
// Tag if this build is run in FIPS mode
32-
if (BuildParams.inFipsJvm) {
33-
tag 'FIPS'
27+
def onCI = System.getenv('CI') ? Boolean.parseBoolean(System.getenv('CI')) : false
28+
29+
// Disable async upload in CI to ensure scan upload completes before CI agent is terminated
30+
uploadInBackground = onCI == false
31+
32+
// Automatically publish scans from Elasticsearch CI
33+
if (onCI) {
34+
publishing.onlyIf { true }
35+
server = 'https://gradle-enterprise.elastic.co'
36+
} else if( server.isPresent() == false) {
37+
publishing.onlyIf { false }
3438
}
3539

36-
// Jenkins-specific build scan metadata
37-
if (jenkinsUrl) {
38-
// Disable async upload in CI to ensure scan upload completes before CI agent is terminated
39-
uploadInBackground = false
40-
41-
String buildNumber = System.getenv('BUILD_NUMBER')
42-
String buildUrl = System.getenv('BUILD_URL')
43-
String jobName = System.getenv('JOB_NAME')
44-
String nodeName = System.getenv('NODE_NAME')
45-
String jobBranch = System.getenv('ghprbTargetBranch') ?: System.getenv('JOB_BRANCH')
46-
47-
// Link to Jenkins worker logs and system metrics
48-
if (nodeName) {
49-
link 'System logs', "https://ci-stats.elastic.co/app/infra#/logs?&logFilter=(expression:'host.name:${nodeName}',kind:kuery)"
50-
buildFinished {
51-
link 'System metrics', "https://ci-stats.elastic.co/app/metrics/detail/host/${nodeName}"
52-
}
53-
}
40+
def fips = BuildParams.inFipsJvm
41+
def gitRevision = BuildParams.gitRevision
5442

55-
// Parse job name in the case of matrix builds
56-
// Matrix job names come in the form of "base-job-name/matrix_param1=value1,matrix_param2=value2"
57-
def splitJobName = jobName.split('/')
58-
if (splitJobName.length > 1 && splitJobName.last() ==~ /^([a-zA-Z0-9_\-]+=[a-zA-Z0-9_\-&\.]+,?)+$/) {
59-
def baseJobName = splitJobName.dropRight(1).join('/')
60-
tag baseJobName
61-
tag splitJobName.last()
62-
value 'Job Name', baseJobName
63-
def matrixParams = splitJobName.last().split(',')
64-
matrixParams.collect { it.split('=') }.each { param ->
65-
value "MATRIX_${param[0].toUpperCase()}", param[1]
66-
}
67-
} else {
68-
tag jobName
69-
value 'Job Name', jobName
70-
}
43+
background {
44+
tag OS.current().name()
45+
tag Architecture.current().name()
7146

72-
tag 'CI'
73-
link 'CI Build', buildUrl
74-
link 'GCP Upload', "https://console.cloud.google.com/storage/browser/_details/elasticsearch-ci-artifacts/jobs/${URLEncoder.encode(jobName, "UTF-8")}/build/${buildNumber}.tar.bz2"
75-
value 'Job Number', buildNumber
76-
if (jobBranch) {
77-
tag jobBranch
78-
value 'Git Branch', jobBranch
47+
// Tag if this build is run in FIPS mode
48+
if (fips) {
49+
tag 'FIPS'
7950
}
8051

81-
System.getenv().getOrDefault('NODE_LABELS', '').split(' ').each {
82-
value 'Jenkins Worker Label', it
83-
}
52+
if (onCI) { //Buildkite-specific build scan metadata
53+
String buildKiteUrl = System.getenv('BUILDKITE_BUILD_URL')
54+
def branch = System.getenv('BUILDKITE_PULL_REQUEST_BASE_BRANCH') ?: System.getenv('BUILDKITE_BRANCH')
55+
def repoMatcher = System.getenv('BUILDKITE_REPO') =~ /(https:\/\/github\.com\/|git@github\.com:)(\S+)\.git/
56+
def repository = repoMatcher.matches() ? repoMatcher.group(2) : "<unknown>"
57+
def jobLabel = System.getenv('BUILDKITE_LABEL') ?: ''
58+
def jobName = safeName(jobLabel)
8459

85-
// Add SCM information
86-
def isPrBuild = System.getenv('ROOT_BUILD_CAUSE_GHPRBCAUSE') != null
87-
if (isPrBuild) {
88-
value 'Git Commit ID', System.getenv('ghprbActualCommit')
89-
tag "pr/${System.getenv('ghprbPullId')}"
90-
tag 'pull-request'
91-
link 'Source', "https://github.com/elastic/elasticsearch/tree/${System.getenv('ghprbActualCommit')}"
92-
link 'Pull Request', System.getenv('ghprbPullLink')
93-
} else {
94-
value 'Git Commit ID', BuildParams.gitRevision
95-
link 'Source', "https://github.com/elastic/elasticsearch/tree/${BuildParams.gitRevision}"
96-
}
97-
} else if (buildKiteUrl) { //Buildkite-specific build scan metadata
98-
// Disable async upload in CI to ensure scan upload completes before CI agent is terminated
99-
uploadInBackground = false
100-
101-
def branch = System.getenv('BUILDKITE_PULL_REQUEST_BASE_BRANCH') ?: System.getenv('BUILDKITE_BRANCH')
102-
def repoMatcher = System.getenv('BUILDKITE_REPO') =~ /(https:\/\/github\.com\/|git@github\.com:)(\S+)\.git/
103-
def repository = repoMatcher.matches() ? repoMatcher.group(2) : "<unknown>"
104-
def jobLabel = System.getenv('BUILDKITE_LABEL') ?: ''
105-
def jobName = safeName(jobLabel)
106-
107-
tag 'CI'
108-
link 'CI Build', "${buildKiteUrl}#${System.getenv('BUILDKITE_JOB_ID')}"
109-
value 'Job Number', System.getenv('BUILDKITE_BUILD_NUMBER')
110-
value 'Build ID', System.getenv('BUILDKITE_BUILD_ID')
111-
value 'Job ID', System.getenv('BUILDKITE_JOB_ID')
112-
113-
value 'Pipeline', System.getenv('BUILDKITE_PIPELINE_SLUG')
114-
tag System.getenv('BUILDKITE_PIPELINE_SLUG')
115-
116-
value 'Job Name', jobName
117-
tag jobName
118-
if (jobLabel.contains("/")) {
119-
jobLabel.split("/").collect {safeName(it) }.each {matrix ->
120-
tag matrix
60+
tag 'CI'
61+
link 'CI Build', "${buildKiteUrl}#${System.getenv('BUILDKITE_JOB_ID')}"
62+
value 'Job Number', System.getenv('BUILDKITE_BUILD_NUMBER')
63+
value 'Build ID', System.getenv('BUILDKITE_BUILD_ID')
64+
value 'Job ID', System.getenv('BUILDKITE_JOB_ID')
65+
66+
value 'Pipeline', System.getenv('BUILDKITE_PIPELINE_SLUG')
67+
tag System.getenv('BUILDKITE_PIPELINE_SLUG')
68+
69+
value 'Job Name', jobName
70+
tag jobName
71+
if (jobLabel.contains("/")) {
72+
jobLabel.split("/").collect { safeName(it) }.each { matrix ->
73+
tag matrix
74+
}
12175
}
122-
}
12376

124-
def uptime = ManagementFactory.getRuntimeMXBean().getUptime() / 1000;
125-
def metricsStartTime = LocalDateTime.now().minusSeconds(uptime.longValue()).minusMinutes(15).toString()
126-
def metricsEndTime = LocalDateTime.now().plusMinutes(15).toString()
77+
def uptime = ManagementFactory.getRuntimeMXBean().getUptime() / 1000;
78+
def metricsStartTime = LocalDateTime.now().minusSeconds(uptime.longValue()).minusMinutes(15).toString()
79+
def metricsEndTime = LocalDateTime.now().plusMinutes(15).toString()
12780

128-
link 'Agent Metrics', "https://es-buildkite-agents.elastic.dev/app/metrics/detail/host/${System.getenv('BUILDKITE_AGENT_NAME')}?_a=(time:(from:%27${metricsStartTime}Z%27,interval:%3E%3D1m,to:%27${metricsEndTime}Z%27))"
129-
link 'Agent Logs', "https://es-buildkite-agents.elastic.dev/app/logs/stream?logFilter=(filters:!(),query:(language:kuery,query:%27host.name:%20${System.getenv('BUILDKITE_AGENT_NAME')}%27),timeRange:(from:%27${metricsStartTime}Z%27,to:%27${metricsEndTime}Z%27))"
81+
link 'Agent Metrics',
82+
"https://es-buildkite-agents.elastic.dev/app/metrics/detail/host/${System.getenv('BUILDKITE_AGENT_NAME')}?_a=(time:(from:%27${metricsStartTime}Z%27,interval:%3E%3D1m,to:%27${metricsEndTime}Z%27))"
83+
link 'Agent Logs',
84+
"https://es-buildkite-agents.elastic.dev/app/logs/stream?logFilter=(filters:!(),query:(language:kuery,query:%27host.name:%20${System.getenv('BUILDKITE_AGENT_NAME')}%27),timeRange:(from:%27${metricsStartTime}Z%27,to:%27${metricsEndTime}Z%27))"
13085

131-
if (branch) {
132-
tag branch
133-
value 'Git Branch', branch
134-
}
86+
if (branch) {
87+
tag branch
88+
value 'Git Branch', branch
89+
}
13590

136-
// Add SCM information
137-
def prId = System.getenv('BUILDKITE_PULL_REQUEST')
138-
if (prId != 'false') {
139-
def prBaseUrl = (System.getenv('BUILDKITE_PULL_REQUEST_REPO') - ".git").replaceFirst("git://", "https://")
140-
value 'Git Commit ID', System.getenv('BUILDKITE_COMMIT')
141-
tag "pr/${prId}"
142-
tag 'pull-request'
143-
link 'Source', "${prBaseUrl}/tree/${System.getenv('BUILDKITE_COMMIT')}"
144-
link 'Pull Request', "https://github.com/${repository}/pull/${prId}"
145-
} else {
146-
value 'Git Commit ID', BuildParams.gitRevision
147-
link 'Source', "https://github.com/${repository}/tree/${BuildParams.gitRevision}"
148-
}
91+
// Add SCM information
92+
def prId = System.getenv('BUILDKITE_PULL_REQUEST')
93+
if (prId != 'false') {
94+
def prBaseUrl = (System.getenv('BUILDKITE_PULL_REQUEST_REPO') - ".git").replaceFirst("git://", "https://")
95+
value 'Git Commit ID', System.getenv('BUILDKITE_COMMIT')
96+
tag "pr/${prId}"
97+
tag 'pull-request'
98+
link 'Source', "${prBaseUrl}/tree/${System.getenv('BUILDKITE_COMMIT')}"
99+
link 'Pull Request', "https://github.com/${repository}/pull/${prId}"
100+
} else {
101+
value 'Git Commit ID', gitRevision
102+
link 'Source', "https://github.com/${repository}/tree/${gitRevision}"
103+
}
149104

150-
buildFinished { result ->
151-
buildScanPublished { scan ->
152-
// Attach build scan link as build metadata
153-
// See: https://buildkite.com/docs/pipelines/build-meta-data
154-
new ProcessBuilder('buildkite-agent', 'meta-data', 'set', "build-scan-${System.getenv('BUILDKITE_JOB_ID')}", "${scan.buildScanUri}")
155-
.start()
156-
.waitFor()
157-
158-
// Add a build annotation
159-
// See: https://buildkite.com/docs/agent/v3/cli-annotate
160-
def body = """<div class="mb3"><span class="p1 border rounded">${System.getenv('BUILDKITE_LABEL')}</span> :gradle: ${result.failure ? 'failed' : 'successful'} build: <a href="${scan.buildScanUri}"><code>gradle ${gradle.startParameter.taskNames.join(' ')}</code></a></div>"""
161-
def process = [
162-
'buildkite-agent',
163-
'annotate',
164-
'--context',
165-
result.failure ? 'gradle-build-scans-failed' : 'gradle-build-scans',
166-
'--append',
167-
'--style',
168-
result.failure ? 'error' : 'info'
169-
].execute()
170-
process.withWriter { it.write(body) } // passing the body in as an argument has issues on Windows, so let's use stdin of the process instead
171-
process.waitFor()
105+
buildFinished { result ->
106+
107+
buildScanPublished { scan
108+
->
109+
// Attach build scan link as build metadata
110+
// See: https://buildkite.com/docs/pipelines/build-meta-data
111+
new ProcessBuilder('buildkite-agent', 'meta-data', 'set', "build-scan-${System.getenv('BUILDKITE_JOB_ID')}", "${scan.buildScanUri}")
112+
.start()
113+
.waitFor()
114+
115+
// Add a build annotation
116+
// See: https://buildkite.com/docs/agent/v3/cli-annotate
117+
def body = """<div class="mb3"><span class="p1 border rounded">${System.getenv('BUILDKITE_LABEL')}</span> :gradle: ${result.failures ? 'failed' : 'successful'} build: <a href="${scan.buildScanUri}"><code>gradle ${taskNames}</code></a></div>"""
118+
def process = [
119+
'buildkite-agent',
120+
'annotate',
121+
'--context',
122+
result.failures ? 'gradle-build-scans-failed' : 'gradle-build-scans',
123+
'--append',
124+
'--style',
125+
result.failures ? 'error' : 'info'
126+
].execute()
127+
process.withWriter { it.write(body) }
128+
// passing the body in as an argument has issues on Windows, so let's use stdin of the process instead
129+
process.waitFor()
130+
}
172131
}
132+
} else {
133+
tag 'LOCAL'
173134
}
174-
} else {
175-
tag 'LOCAL'
176135
}
177136
}
178137
}
179-
180-
static def safeName(String string) {
181-
return string.replaceAll(/[^a-zA-Z0-9_\-\.]+/, ' ').trim().replaceAll(' ', '_').toLowerCase()
182-
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
/*
2+
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
3+
* or more contributor license agreements. Licensed under the Elastic License
4+
* 2.0 and the Server Side Public License, v 1; you may not use this file except
5+
* in compliance with, at your election, the Elastic License 2.0 or the Server
6+
* Side Public License, v 1.
7+
*/
8+
9+
package org.elasticsearch.gradle.internal.util;
10+
11+
public class CiUtils {
12+
13+
static String safeName(String input) {
14+
return input.replaceAll("[^a-zA-Z0-9_\\-\\.]+", " ").trim().replaceAll(" ", "_").toLowerCase();
15+
}
16+
17+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
/*
2+
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
3+
* or more contributor license agreements. Licensed under the "Elastic License
4+
* 2.0", the "GNU Affero General Public License v3.0 only", and the "Server Side
5+
* Public License v 1"; you may not use this file except in compliance with, at
6+
* your election, the "Elastic License 2.0", the "GNU Affero General Public
7+
* License v3.0 only", or the "Server Side Public License, v 1".
8+
*/
9+
10+
package org.elasticsearch.gradle.internal.util;
11+
12+
/*
13+
* Licensed to the Apache Software Foundation (ASF) under one
14+
* or more contributor license agreements. See the NOTICE file
15+
* distributed with this work for additional information
16+
* regarding copyright ownership. The ASF licenses this file
17+
* to you under the Apache License, Version 2.0 (the
18+
* "License"); you may not use this file except in compliance
19+
* with the License. You may obtain a copy of the License at
20+
*
21+
* http://www.apache.org/licenses/LICENSE-2.0
22+
*
23+
* Unless required by applicable law or agreed to in writing,
24+
* software distributed under the License is distributed on an
25+
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
26+
* KIND, either express or implied. See the License for the
27+
* specific language governing permissions and limitations
28+
* under the License.
29+
*/
30+
31+
32+
public class CiUtils {
33+
34+
static String safeName(String input) {
35+
return input.replaceAll("[^a-zA-Z0-9_\\-\\.]+", " ").trim().replaceAll(" ", "_").toLowerCase();
36+
}
37+
38+
}

0 commit comments

Comments
 (0)