File: distributionTesting.gradle

package info (click to toggle)
gradle 4.4.1-6
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 85,104 kB
  • sloc: java: 319,724; xml: 14,356; cpp: 4,200; ansic: 1,025; sh: 300; makefile: 60; asm: 17; jsp: 17; objc: 10
file content (358 lines) | stat: -rw-r--r-- 13,445 bytes parent folder | download | duplicates (2)
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
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
/*
 * Copyright 2016 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import java.util.regex.Pattern
import org.gradle.testing.DistributionTest
import org.gradle.util.GradleVersion

ext.distributionTestTasks = tasks.withType(DistributionTest)

distributionTestTasks.all { DistributionTest task ->
    dependsOn ':toolingApi:toolingApiShadedJar'
    dependsOn ':cleanUpCaches'
    finalizedBy ':cleanUpDaemons'
    shouldRunAfter 'test'

    jvmArgs '-Xmx512m', '-XX:+HeapDumpOnOutOfMemoryError'
    if (!javaVersion.java8Compatible) {
        jvmArgs '-XX:MaxPermSize=768m'

    }

    reports.junitXml.destination = new File(project.testResultsDir, name)

    // use -PtestVersions=all or -PtestVersions=1.2,1.3…
    if (project.hasProperty('testVersions')) {
        systemProperties['org.gradle.integtest.versions'] = project.testVersions
    }
    if (!systemProperties['org.gradle.integtest.versions']) {
        systemProperties['org.gradle.integtest.versions'] = 'latest'
    }

    systemProperties['org.gradle.integtest.cpp.toolChains'] = project.hasProperty("testAllPlatforms") && project.testAllPlatforms ? 'all' : 'default'

    systemProperties['org.gradle.integtest.multiversion'] = project.hasProperty("testAllVersions") && project.testAllVersions ? 'all' : 'default'

    def mirrorUrls = collectMirrorUrls()
    def mirrors = ['mavencentral', 'jcenter', 'lightbendmaven', 'ligthbendivy', 'google']
    mirrors.each { mirror ->
        systemProperties["org.gradle.integtest.mirrors.$mirror"] = mirrorUrls[mirror] ?: ''
    }

    dependsOn project.task("configure${task.name.capitalize()}") {
        doLast {
            configure(task) {
                reports.html.destination = file("${project.reporting.baseDir}/$name")
                gradleHomeDir = intTestImage.destinationDir
                gradleUserHomeDir = rootProject.file('intTestHomeDir')
                toolingApiShadedJarDir = rootProject.project(':toolingApi').toolingApiShadedJar.destinationDir

                if (requiresLibsRepo) {
                    libsRepo = rootProject.file('build/repo')
                }
                if (requiresDists) {
                    distsDir = rootProject.distsDir
                    systemProperties['integTest.distZipVersion'] = version
                }
                if (requiresBinZip) {
                    binZip = project(':distributions').binZip.archivePath
                }
                daemonRegistry = file("$rootProject.buildDir/daemon")
            }
        }
    }

    ext.daemonListener = null

    doFirst {
        def daemonPids = rootProject.cleanUpDaemons.daemonPids
        def suspiciousDaemons = rootProject.cleanUpDaemons.suspiciousDaemons
        daemonListener = [
            beforeTest : { test -> },
            afterTest  : { test, result -> },
            beforeSuite: { suite ->
                forEachJavaProcess { pid, process ->
                    // processes that exist before the test suite execution should
                    // not trigger a warning
                    daemonPids << pid
                }
            },
            afterSuite : { suite, result ->
                forEachJavaProcess { pid, process ->
                    if (!daemonPids.contains(pid)) {
                        daemonPids << pid
                        suspiciousDaemons."$suite" << pid
                    }
                }
            }] as TestListener
        gradle.addListener(daemonListener)
    }

    doLast {
        gradle.removeListener(daemonListener)
    }
}

def collectMirrorUrls() {
    // expected env var format: repo1_id:repo1_url,repo2_id:repo2_url,...
    System.getenv('REPO_MIRROR_URLS')?.split(',')?.collectEntries { nameToUrl ->
        def index = nameToUrl.indexOf(':')
        [(nameToUrl.substring(0, index)) : nameToUrl.substring(index + 1)]
    } ?: [:]
}

/**
 * Clean up cache files for older versions that aren't multi-process safe.
 */
def removeDodgyCacheFiles(File dir) {
    if (dir.directory) {
        for (File cacheDir : dir.listFiles()) {
            if (!cacheDir.name.matches("\\d+\\.\\d+(\\.\\d+)?(-\\w+)*(-\\d{14}[+-]\\d{4})?")) {
                continue
            }
            for (String name : ["fileHashes", "outputFileStates", "fileSnapshots"]) {
                def stateDir = new File(cacheDir, name)
                if (stateDir.directory) {
                    println "Removing old cache directory : ${stateDir}"
                    delete(stateDir)
                }
            }
        }
    }
}


/**
 * Clean up daemon log files produced in integration tests.
 */
def removeDaemonLogFiles(File dir) {
    if (dir.directory) {
        def daemonLogFiles = fileTree(dir) {
            include '**/*.log'
        }
        delete daemonLogFiles
    }
}

/**
 * Removes state for versions that we're unlikely to ever need again, such as old snapshot versions.
 */
def removeOldVersionsFromDir(File dir, shouldDelete, dirPrefix = "", dirSuffix = "") {
    if (dir.directory) {

        for (File cacheDir : dir.listFiles()) {
            if (!cacheDir.name.startsWith(dirPrefix) || !cacheDir.name.endsWith(dirSuffix)) {
                continue
            }
            def dirVersion = cacheDir.name.substring(dirPrefix.length(), cacheDir.name.length() - dirSuffix.length())
            if (!dirVersion.matches("\\d+\\.\\d+(\\.\\d+)?(-\\w+)*(-\\d{14}[+-]\\d{4})?")) {
                continue
            }

            def cacheVersion
            try {
                cacheVersion = GradleVersion.version(dirVersion)
            } catch (IllegalArgumentException e) {
                // Ignore
                continue
            }

            if (shouldDelete(cacheVersion)) {
                println "Removing old cache directory : ${cacheDir}"
                delete(cacheDir)
            }
        }
    }
}

def removeCachedScripts(File cachesDir) {
    if (cachesDir.directory) {
        for (File cacheDir : cachesDir.listFiles()) {
            if(cacheDir.directory) {
                ["scripts", "scripts-remapped"].each {
                    File scriptsCacheDir = new File(cacheDir, it)
                    if(scriptsCacheDir.directory) {
                        println "Removing scripts cache directory : ${scriptsCacheDir}"
                        delete(scriptsCacheDir)
                    }
                }
            }
        }
    }
}

project(":") {
    if (tasks.findByName('cleanUpCaches')) {
        return
    }

    task cleanUpCaches {
        dependsOn ':createBuildReceipt'
        doLast {
            def executingVersion = GradleVersion.version(gradle.gradleVersion)

            // Expire .gradle cache where major version is older than executing version
            def expireTaskCache = { candidateVersion ->
                return candidateVersion.baseVersion < executingVersion.baseVersion
            }

            // Expire intTestImage cache snapshots that are older than the tested version
            // Also expire version-specific cache snapshots when they can't be re-used (for 'snapshot-1' developer builds)
            def expireIntegTestCache = { candidateVersion ->
                return (candidateVersion.snapshot && candidateVersion < GradleVersion.version(version)) || candidateVersion.version.endsWith('-snapshot-1')
            }

            // Remove state for old versions of Gradle that we're unlikely to ever require again
            removeOldVersionsFromDir(file("buildSrc/.gradle"), expireTaskCache)
            removeOldVersionsFromDir(file(".gradle"), expireTaskCache)
            removeOldVersionsFromDir(file("intTestHomeDir/worker-1/caches"), expireIntegTestCache)

            // Remove scripts caches
            removeCachedScripts(file("intTestHomeDir/worker-1/caches"))
            // Remove script caches from TestKit integTest temp dir
            // location defined in TempTestKitDirProvider, copied here
            def testKitTmpDir = new File(new File(System.getProperty("java.io.tmpdir")), String.format(".gradle-test-kit-%s", System.getProperty("user.name")))
            removeCachedScripts(new File(testKitTmpDir, "caches"))

            removeOldVersionsFromDir(file("intTestHomeDir/worker-1/daemon"), expireIntegTestCache)

            // Remove old distributions used by wrapper that we're unlikely to ever require again
            removeOldVersionsFromDir(file("intTestHomeDir/worker-1/wrapper/dists"), expireIntegTestCache, "gradle-", "-bin")
            delete(file("intTestHomeDir/worker-1/wrapper/dists/dist"))

            // Remove caches that weren't multi-process safe and may be corrupt
            removeDodgyCacheFiles(file("intTestHomeDir/worker-1/caches"))

            // Remove old daemon log files
            removeDaemonLogFiles(file("intTestHomeDir/worker-1/daemon"))
        }
    }
}

def forEachJavaProcess(Closure action) {
    String queryString = "(?i)[/\\\\](java(?:\\.exe)?.+?(?:(?:-cp.+${Pattern.quote(rootProject.projectDir.absolutePath)}.+?(org\\.gradle\\.|[a-zA-Z]+))|(?:-classpath.+${Pattern.quote(rootProject.buildDir.absolutePath)}.+?(org\\.gradle\\.|[a-zA-Z]+))).+)"
    def output = new ByteArrayOutputStream()
    def error = new ByteArrayOutputStream()
    def pidPattern
    def result
    if (org.gradle.internal.os.OperatingSystem.current().windows) {
        result = exec {
            commandLine('wmic', 'process', 'get', 'processid,commandline')
            standardOutput = output
            errorOutput = error
            ignoreExitValue = true
        }
        pidPattern = /([0-9]+)\s*$/
    } else {
        result = exec {
            commandLine('ps', 'x')
            standardOutput = output
            errorOutput = output
            ignoreExitValue = true
        }
        pidPattern = /([0-9]+)/
    }
    if (result.exitValue != 0) {
        def errorLog = file("${rootProject.buildDir}/errorLogs/process-list-${System.currentTimeMillis()}.log")
        project.mkdir(errorLog.parent)
        errorLog.text = "[Output]\n${output.toString()}\n[Error Output]\n${error.toString()}"
        logger.quiet "Error obtaining process list, output log created at $errorLog"
        result.assertNormalExitValue()
    }
    output.toString().readLines().each { String line ->
        def processMatcher = line =~ queryString
        if (processMatcher.find()) {
            def pidMatcher = line =~ pidPattern
            if (pidMatcher.find()) {
                def pid = pidMatcher.group(1)
                def process = processMatcher.group(1)
                if (!isMe(process)) {
                    action.call(pid, process)
                }
            }
        }
    }
}

def isMe(process) {
    process.contains(project.gradle.gradleHomeDir.path)
}

def pkill(pid) {
    def killOutput = new ByteArrayOutputStream()
    def result = exec {
        if (org.gradle.internal.os.OperatingSystem.current().windows) {
            commandLine = ["taskkill.exe", "/F", "/T", "/PID", pid]
        } else {
            commandLine = ["kill", pid]
        }
        standardOutput = killOutput
        errorOutput = killOutput
        ignoreExitValue = true
    }
    if (result.exitValue != 0) {
        String out = killOutput.toString()
        if (!out.contains('No such process')) {
            logger.warn("""Failed to kill daemon process $pid. Maybe already killed?
Output: ${killOutput}
""")
        }
    }
}

project(":") {
    if (tasks.findByName('cleanUpDaemons')) {
        return
    }
    task killExistingProcessesStartedByGradle {
        doLast {
            def didKill = false
            forEachJavaProcess { pid, process ->
                logger.warn("A process wasn't shutdown properly in a previous Gradle run. Killing process with PID $pid (Command line: $process)")
                pkill(pid)
                didKill = true
            }
            if (didKill) {
                //it might take a moment until file handles are released
                Thread.sleep(5000)
            }
        }
    }

    task cleanUpDaemons {
        ext.suspiciousDaemons = [:].withDefault { [].asSynchronized() }.asSynchronized()
        ext.daemonPids = ([] as Set).asSynchronized()
        doLast {
            Set alreadyKilled = []
            forEachJavaProcess { pid, process ->
                suspiciousDaemons.each { suite, pids ->
                    if (pids.contains(pid) && !alreadyKilled.contains(pid)) {
                        logger.warn("A process was created in $suite but wasn't shutdown properly. Killing PID $pid (Command line: $process)")
                        pkill(pid)
                    }
                }
            }
        }
    }
    if (isCiServer) {
        clean.dependsOn killExistingProcessesStartedByGradle
        subprojects {
            tasks.all {
                mustRunAfter(killExistingProcessesStartedByGradle)
            }
        }
    }
}