diff --git a/rules/impl.bzl b/rules/impl.bzl index 41e71aa..ca80300 100644 --- a/rules/impl.bzl +++ b/rules/impl.bzl @@ -126,7 +126,14 @@ def _run_android_lint( aar = aar_node_info.aar aar_dir = aar_node_info.aar_dir if aar and aar_dir: - args.add("--classpath-aar", "%s:%s" % (aar.path, aar_dir.path)) + # Pass Files rather than a formatted string so that path mapping can rewrite them. + # aar_dir is a tree artifact, which must stay a single path. + args.add_joined( + "--classpath-aar", + [aar, aar_dir], + join_with = ":", + expand_directories = False, + ) inputs.append(aar) inputs.append(aar_dir) if android_lint_enable_check_dependencies: @@ -156,6 +163,12 @@ def _run_android_lint( execution_requirements = { "supports-workers": "1", "supports-multiplex-workers": "1", + # The worker resolves every path against the request's sandbox directory. + "supports-multiplex-sandboxing": "1", + # Every bazel-out path reaches the command line as a File, so Bazel can rewrite it. + # --android-home and --jdk-home are toolchain roots outside bazel-out, which path + # mapping leaves unchanged. + "supports-path-mapping": "1", }, env = { # https://googlesamples.github.io/android-custom-lint-rules/usage/variables.md.html diff --git a/src/cli/AndroidLintAction.kt b/src/cli/AndroidLintAction.kt index 323705e..e8fd21a 100644 --- a/src/cli/AndroidLintAction.kt +++ b/src/cli/AndroidLintAction.kt @@ -1,8 +1,9 @@ package com.rules.android.lint.cli import com.rules.android.lint.worker.Worker -import java.io.PrintStream +import java.io.PrintWriter import java.nio.file.Files +import java.nio.file.Path import kotlin.system.exitProcess object AndroidLintAction { @@ -18,23 +19,25 @@ object AndroidLintAction { ) : Worker.WorkRequestCallback { override fun processWorkRequest( args: List, - printStream: PrintStream, + executionRoot: Path, + output: PrintWriter, ): Int { val workingDirectory = Files.createTempDirectory("rules") try { val runner = AndroidLintRunner(invokerCache) - val parsedArgs = AndroidLintActionArgs.parseArgs(args) + val parsedArgs = AndroidLintActionArgs.parseArgs(args, executionRoot) runner.runAndroidLint(parsedArgs, workingDirectory) return 0 } catch (exception: Exception) { - exception.printStackTrace() + if (exception is InterruptedException) throw exception + exception.printStackTrace(output) return 1 } finally { try { workingDirectory.toFile().deleteRecursively() } catch (e: Exception) { - e.printStackTrace() + e.printStackTrace(output) } } } diff --git a/src/cli/AndroidLintActionArgs.kt b/src/cli/AndroidLintActionArgs.kt index 574f1bc..c95fee5 100644 --- a/src/cli/AndroidLintActionArgs.kt +++ b/src/cli/AndroidLintActionArgs.kt @@ -2,20 +2,23 @@ package com.rules.android.lint.cli import com.xenomachina.argparser.ArgParser import com.xenomachina.argparser.default -import java.io.File import java.nio.charset.Charset import java.nio.file.Path -import java.nio.file.Paths +import kotlin.io.path.readLines -internal class AndroidLintActionArgs( +internal class AndroidLintActionArgs private constructor( parser: ArgParser, + /** The absolute directory that every path argument resolves against. */ + val executionRoot: Path, ) { + private fun resolve(path: String): Path = executionRoot.resolve(path).normalize() + private val argsParserPathTransformer: String.() -> Path = { - Paths.get(this) + resolve(this) } private val argsParserAarPairPathTransformer: String.() -> Pair = { val (aar, aarDir) = this.split(":") - Pair(Paths.get(aar), Paths.get(aarDir)) + Pair(resolve(aar), resolve(aarDir)) } val androidLintCliTool: Path by parser.storing( @@ -29,10 +32,12 @@ internal class AndroidLintActionArgs( help = "", ) - val androidHome: String? by parser + val androidHome: Path? by parser .storing( names = arrayOf("--android-home"), help = "The relative location of Android home", + // An empty location means the toolchain has no Android home. + transform = { ifEmpty { null }?.let { resolve(it) } }, ).default { null } val jdkHome: Path? by parser @@ -155,16 +160,30 @@ internal class AndroidLintActionArgs( ).default { false } companion object { - internal fun parseArgs(args: List): AndroidLintActionArgs { + /** + * Parses [args], reading them from the `@flagfile` when that is the only argument. + * + * The flagfile and every path argument resolve against [executionRoot] rather than the + * process's working directory, which differs from it for multiplex sandboxed requests. + */ + internal fun parseArgs( + args: List, + executionRoot: Path, + ): AndroidLintActionArgs { + require(executionRoot.isAbsolute) { "The execution root must be absolute: $executionRoot" } // TODO Need to handle the --flagfile argument here val unwrappedArgs: Array = if (args.size == 1 && args[0].startsWith("@")) { - File(args[0].removePrefix("@")).readLines(Charset.defaultCharset()).toTypedArray() + executionRoot + .resolve(args[0].removePrefix("@")) + .normalize() + .readLines(Charset.defaultCharset()) + .toTypedArray() } else { args.toTypedArray() } - return AndroidLintActionArgs(ArgParser(unwrappedArgs)) + return AndroidLintActionArgs(ArgParser(unwrappedArgs), executionRoot.normalize()) } } } diff --git a/src/cli/AndroidLintCliInvokerCache.kt b/src/cli/AndroidLintCliInvokerCache.kt index 8f3ea7a..4c55c9d 100644 --- a/src/cli/AndroidLintCliInvokerCache.kt +++ b/src/cli/AndroidLintCliInvokerCache.kt @@ -36,7 +36,10 @@ internal class AndroidLintCliInvokerCache( @Synchronized internal fun acquire(jars: List): AndroidLintCliInvoker { - val key = cacheKey(jars) + // Multiplex sandboxing stages each jar as a symlink in a per-request sandbox, which Bazel deletes + // after the request while the cached classloader lives on. Key on and load from the real paths. + val realJars = jars.map { it.toRealPath() } + val key = cacheKey(realJars) current?.let { entry -> if (entry.key == key) { entry.activeLeases += 1 @@ -52,7 +55,7 @@ internal class AndroidLintCliInvokerCache( val invoker = AndroidLintCliInvoker.createUsingJars( parentClassloader = parentClassloader, - jars = jars.toTypedArray(), + jars = realJars.toTypedArray(), ) createdCount += 1 current = Entry(key = key, invoker = invoker, activeLeases = 1) @@ -81,11 +84,10 @@ internal class AndroidLintCliInvokerCache( } } - private fun cacheKey(jars: List): String = - jars.joinToString(separator = "|") { jar -> - val realPath = jar.toRealPath() - val size = Files.size(realPath) - val lastModified = Files.getLastModifiedTime(realPath).toMillis() - "$realPath:$size:$lastModified" + private fun cacheKey(realJars: List): String = + realJars.joinToString(separator = "|") { jar -> + val size = Files.size(jar) + val lastModified = Files.getLastModifiedTime(jar).toMillis() + "$jar:$size:$lastModified" } } diff --git a/src/cli/AndroidLintRunner.kt b/src/cli/AndroidLintRunner.kt index 4b5658f..29b10ec 100644 --- a/src/cli/AndroidLintRunner.kt +++ b/src/cli/AndroidLintRunner.kt @@ -2,8 +2,6 @@ package com.rules.android.lint.cli import java.nio.file.Files import java.nio.file.Path -import java.nio.file.Paths -import kotlin.io.path.absolutePathString import kotlin.io.path.exists import kotlin.io.path.isRegularFile import kotlin.io.path.pathString @@ -34,11 +32,10 @@ internal class AndroidLintRunner( val projectFile = workingDirectory.resolve("${args.label}_project_config.xml") Files.createFile(projectFile) - val rootDir = System.getenv("PWD") projectFile.writeText( createProjectXMLString( moduleName = args.label, - rootDir = rootDir, + rootDir = args.executionRoot.pathString, srcs = args.srcs.sortedDescending(), resources = args.resources.sortedDescending(), androidManifest = args.androidManifest, @@ -52,17 +49,14 @@ internal class AndroidLintRunner( // Run Android Lint val androidCacheFolder = workingDirectory.resolve("android-cache") Files.createDirectory(androidCacheFolder) - val lintUserHomeFolder = workingDirectory.resolve("lint-user-home") - Files.createDirectory(lintUserHomeFolder) + LintUserHome.install() val invoker = invokerCache.acquire(listOf(args.androidLintCliTool)) val exitCode = try { - System.setProperty("user.home", lintUserHomeFolder.toString()) invokeAndroidLintCLI( invoker = invoker, actionArgs = args, - rootDirPath = rootDir, projectFilePath = projectFile, baselineFilePath = baselineFile, cacheDirectoryPath = androidCacheFolder, @@ -83,7 +77,6 @@ internal class AndroidLintRunner( private fun invokeAndroidLintCLI( invoker: AndroidLintCliInvoker, actionArgs: AndroidLintActionArgs, - rootDirPath: String, projectFilePath: Path, baselineFilePath: Path, cacheDirectoryPath: Path, @@ -95,7 +88,7 @@ internal class AndroidLintRunner( "--xml", actionArgs.output.pathString, "--path-variables", - "PWD=$rootDirPath", + "PWD=${actionArgs.executionRoot.pathString}", "--exitcode", "--compile-sdk-version", actionArgs.compileSdkVersion, @@ -132,17 +125,14 @@ internal class AndroidLintRunner( args.add(actionArgs.disableChecks.joinToString(",")) } - if (actionArgs.androidHome?.isNotEmpty() == true) { - val androidHomePath = - Paths.get(System.getenv("PWD"), actionArgs.androidHome).absolutePathString() + actionArgs.androidHome?.let { args.add("--sdk-home") - args.add(androidHomePath) + args.add(it.pathString) } - if (actionArgs.jdkHome != null) { - val jdkHome = actionArgs.jdkHome!! + actionArgs.jdkHome?.let { args.add("--jdk-home") - args.add(jdkHome.absolutePathString()) + args.add(it.pathString) } return invoker.invoke( diff --git a/src/cli/LintUserHome.kt b/src/cli/LintUserHome.kt new file mode 100644 index 0000000..6c6b1d8 --- /dev/null +++ b/src/cli/LintUserHome.kt @@ -0,0 +1,26 @@ +package com.rules.android.lint.cli + +import java.nio.file.Files +import java.nio.file.Path + +/** + * A writable `user.home` for lint, owned by the worker process. + * + * Lint keeps state under `user.home`, so the worker points it at a private temporary directory + * instead of the real home directory. The property is JVM-global and lint caches the locations it + * derives from it per classloader, so it is set once per process, before lint first runs, rather + * than per request, where concurrent multiplex requests would race on it. + */ +internal object LintUserHome { + private val directory: Path by lazy { + Files.createTempDirectory("lint-user-home").also { home -> + System.setProperty("user.home", home.toString()) + Runtime.getRuntime().addShutdownHook(Thread { home.toFile().deleteRecursively() }) + } + } + + /** Points `user.home` at the lint user home, creating it on the first call. Thread-safe. */ + fun install() { + directory + } +} diff --git a/src/worker/InvocationWorker.kt b/src/worker/InvocationWorker.kt index 4fd8ca7..bdd4d17 100644 --- a/src/worker/InvocationWorker.kt +++ b/src/worker/InvocationWorker.kt @@ -1,11 +1,22 @@ package com.rules.android.lint.worker +import java.io.PrintWriter + internal class InvocationWorker( private val args: Array, private val workerMessageProcessor: Worker.WorkRequestCallback, ) : Worker { override fun processRequests(): Int { // Handle a single work request - return workerMessageProcessor.processWorkRequest(args.toList(), System.err) + val output = PrintWriter(System.err, true) + return try { + workerMessageProcessor.processWorkRequest( + args.toList(), + processWorkingDirectory(), + output, + ) + } finally { + output.flush() + } } } diff --git a/src/worker/PersistentWorker.kt b/src/worker/PersistentWorker.kt index daaed37..cba28ca 100644 --- a/src/worker/PersistentWorker.kt +++ b/src/worker/PersistentWorker.kt @@ -3,11 +3,17 @@ package com.rules.android.lint.worker import com.google.devtools.build.lib.worker.ProtoWorkerMessageProcessor import com.google.devtools.build.lib.worker.WorkRequestHandler import java.io.IOException +import java.io.InputStream +import java.io.OutputStream import java.io.PrintStream +import java.nio.file.Path import java.time.Duration internal class PersistentWorker( private val workerWorkRequestCallback: Worker.WorkRequestCallback, + private val stdin: InputStream = System.`in`, + private val stdout: OutputStream = System.out, + private val workingDirectory: Path = processWorkingDirectory(), ) : Worker { override fun processRequests(): Int { val realStdErr: PrintStream = System.err @@ -17,13 +23,26 @@ internal class PersistentWorker( WorkRequestHandler .WorkRequestHandlerBuilder( WorkRequestHandler.WorkRequestCallback { request, pw -> - return@WorkRequestCallback workerWorkRequestCallback.processWorkRequest( - request.argumentsList.toList(), - System.err, - ) + // Multiplex sandboxing stages each request's inputs under its own sandbox + // directory, relative to the worker's working directory. + val executionRoot = workingDirectory.resolve(request.sandboxDir).normalize() + try { + workerWorkRequestCallback.processWorkRequest( + request.argumentsList.toList(), + executionRoot, + pw, + ) + } catch (e: Exception) { + // WorkRequestHandler answers only RuntimeExceptions and InterruptedExceptions. Kotlin + // does not declare checked exceptions, so any other one escaping here would leave + // Bazel waiting on a request that never gets a response. + if (e is InterruptedException) throw e + e.printStackTrace(pw) + 1 + } }, realStdErr, - ProtoWorkerMessageProcessor(System.`in`, System.out), + ProtoWorkerMessageProcessor(stdin, stdout), ).setCpuUsageBeforeGc(Duration.ofSeconds(10)) .build() workerHandler.processRequests() diff --git a/src/worker/Worker.kt b/src/worker/Worker.kt index 9f32adf..08fb083 100644 --- a/src/worker/Worker.kt +++ b/src/worker/Worker.kt @@ -1,17 +1,28 @@ package com.rules.android.lint.worker -import java.io.PrintStream +import java.io.IOException +import java.io.PrintWriter +import java.nio.file.Files +import java.nio.file.Path +import java.nio.file.Paths interface Worker { fun processRequests(): Int - interface WorkRequestCallback { + fun interface WorkRequestCallback { /** * Processes an individual work request. + * + * @param args the request arguments, possibly a single `@flagfile`. + * @param executionRoot the absolute directory that relative paths in [args], including a + * `@flagfile`, resolve against. For a multiplex sandboxed request this is the request's + * sandbox directory; otherwise it is the worker's working directory. + * @param output receives the diagnostic output for this request only. */ fun processWorkRequest( args: List, - printStream: PrintStream, + executionRoot: Path, + output: PrintWriter, ): Int } @@ -32,3 +43,30 @@ interface Worker { } } } + +/** The worker process's working directory: the execution root for unsandboxed requests. */ +internal fun processWorkingDirectory(): Path = + workingDirectory(pwd = System.getenv("PWD"), userDir = System.getProperty("user.dir")) + +/** + * Prefers [pwd], which keeps the path in the form the worker was launched with, but only when it + * names the same directory as [userDir]: a launcher that changes directory without a shell can + * leave a stale `PWD` behind. + */ +internal fun workingDirectory( + pwd: String?, + userDir: String, +): Path { + val current = Paths.get(userDir).toAbsolutePath().normalize() + if (pwd.isNullOrEmpty()) { + return current + } + val logical = Paths.get(pwd).normalize() + val namesCurrent = + try { + logical.isAbsolute && Files.isSameFile(logical, current) + } catch (e: IOException) { + false + } + return if (namesCurrent) logical else current +} diff --git a/tests/rules/BUILD.bazel b/tests/rules/BUILD.bazel index e7d7b71..d3ec24b 100644 --- a/tests/rules/BUILD.bazel +++ b/tests/rules/BUILD.bazel @@ -1,3 +1,4 @@ +load("@rules_java//java:defs.bzl", "java_library") load("//rules:defs.bzl", "android_lint") load(":android_lint_analysis_test.bzl", "android_lint_analysis_test_suite") @@ -16,4 +17,21 @@ android_lint( warnings_as_errors = True, ) +java_library( + name = "fixture_dep", + srcs = ["FixtureDep.java"], +) + +# Depends on a compiled jar and an AAR, so its lint command line names bazel-out inputs. +android_lint( + name = "path_mapping_fixture_lint", + srcs = ["Fixture.java"], + lib = ":fixture_lib", + tags = ["manual"], + deps = [ + ":fixture_dep", + "//tests/integration:compose_lint_aar", + ], +) + android_lint_analysis_test_suite(name = "tests") diff --git a/tests/rules/FixtureDep.java b/tests/rules/FixtureDep.java new file mode 100644 index 0000000..1f1dac0 --- /dev/null +++ b/tests/rules/FixtureDep.java @@ -0,0 +1,6 @@ +package tests.rules; + +/** A dependency of the path mapping analysis fixture. */ +public final class FixtureDep { + private FixtureDep() {} +} diff --git a/tests/rules/android_lint_analysis_test.bzl b/tests/rules/android_lint_analysis_test.bzl index ab85e33..8ded52c 100644 --- a/tests/rules/android_lint_analysis_test.bzl +++ b/tests/rules/android_lint_analysis_test.bzl @@ -37,7 +37,14 @@ def _android_lint_action_impl(ctx): ) asserts.equals(env, "DefaultLocale", _argument_value(argv, "--disable-check")) asserts.true(env, "--warnings-as-errors" in argv) - asserts.equals(env, target[AndroidLintResultsInfo].output.path, output) + + # A global --experimental_output_paths=strip maps the output path; see the path mapping test. + output_file = target[AndroidLintResultsInfo].output + asserts.true( + env, + output in [output_file.path, "bazel-out/cfg/bin/" + output_file.short_path], + "unexpected --output {}".format(output), + ) asserts.false(env, "--baseline-file" in argv) asserts.false(env, "--regenerate-baseline-files" in argv) @@ -52,11 +59,71 @@ def _android_lint_action_impl(ctx): asserts.equals(env, "1", action.execution_info.get("supports-workers")) asserts.equals(env, "1", action.execution_info.get("supports-multiplex-workers")) + asserts.equals(env, "1", action.execution_info.get("supports-multiplex-sandboxing")) + asserts.equals(env, "1", action.execution_info.get("supports-path-mapping")) return analysistest.end(env) _android_lint_action_test = analysistest.make(_android_lint_action_impl) +def _android_lint_path_mapping_impl(ctx): + env = analysistest.begin(ctx) + actions = [ + action + for action in analysistest.target_actions(env) + if action.mnemonic == "AndroidLint" + ] + asserts.equals(env, 1, len(actions)) + if actions: + argv = actions[0].argv + + # An AAR and its extracted directory travel as one "aar:dir" argument, and all generated + # inputs/outputs must resolve under bazel-out/cfg/ so the fixture never becomes vacuous. + aar = _argument_value(argv, "--classpath-aar") + aar_parts = aar.split(":") if aar != None else [] + asserts.equals(env, 2, len(aar_parts)) + for part in aar_parts: + asserts.true( + env, + part.startswith("bazel-out/cfg/"), + "unmapped --classpath-aar part: {}".format(part), + ) + + classpath_jar = _argument_value(argv, "--classpath-jar") + asserts.true( + env, + classpath_jar != None and classpath_jar.startswith("bazel-out/cfg/"), + "unmapped --classpath-jar: {}".format(classpath_jar), + ) + + output = _argument_value(argv, "--output") + asserts.true( + env, + output != None and output.startswith("bazel-out/cfg/"), + "unmapped --output: {}".format(output), + ) + + # Path mapping must rewrite every bazel-out/ occurrence on the command line, including + # inside joined or flag-prefixed arguments (e.g. --flag=bazel-out/...). + # Bazel 9 also maps the AndroidLint mnemonic on its own, so this checks the command line + # rather than the declaration, which _android_lint_action_test covers. + for arg in argv: + for suffix in arg.split("bazel-out/")[1:]: + asserts.true( + env, + suffix.startswith("cfg/"), + "unmapped bazel-out path in {}".format(arg), + ) + + return analysistest.end(env) + +_android_lint_path_mapping_test = analysistest.make( + _android_lint_path_mapping_impl, + config_settings = { + "//command_line_option:experimental_output_paths": "strip", + }, +) + def android_lint_analysis_test_suite(name): """Defines the android_lint analysis test suite. @@ -68,7 +135,15 @@ def android_lint_analysis_test_suite(name): name = action_test, target_under_test = ":analysis_fixture_lint", ) + path_mapping_test = name + "_path_mapping_test" + _android_lint_path_mapping_test( + name = path_mapping_test, + target_under_test = ":path_mapping_fixture_lint", + ) native.test_suite( name = name, - tests = [":" + action_test], + tests = [ + ":" + action_test, + ":" + path_mapping_test, + ], ) diff --git a/tests/src/cli/AndroidLintActionArgsTest.kt b/tests/src/cli/AndroidLintActionArgsTest.kt index 6023a52..eb3aecd 100644 --- a/tests/src/cli/AndroidLintActionArgsTest.kt +++ b/tests/src/cli/AndroidLintActionArgsTest.kt @@ -10,6 +10,7 @@ import java.nio.file.Paths class AndroidLintActionArgsTest { @Test fun `does parse all arguments`() { + val executionRoot = Paths.get("/sandbox") val parseArgs = AndroidLintActionArgs.parseArgs( args = @@ -28,6 +29,8 @@ class AndroidLintActionArgsTest { "path/to/resource/strings.xml", "--android-manifest", "AndroidManifest.xml", + "--jdk-home", + "external/jdk", "--baseline-file", "lib_lint_baseline.xml", "--config-file", @@ -53,20 +56,27 @@ class AndroidLintActionArgsTest { "1.8", "--enable-check-dependencies", ), + executionRoot = executionRoot, ) assertThat(parseArgs.label).isEqualTo("test") - assertThat(parseArgs.androidHome).isEqualTo("external/androidsdk") - assertThat(parseArgs.srcs).containsExactly(Paths.get("path/to/Foo.kt")) - assertThat(parseArgs.output).isEqualTo(Paths.get("output.jar")) - assertThat(parseArgs.resources).containsExactly(Paths.get("path/to/resource/strings.xml")) - assertThat(parseArgs.baselineFile).isEqualTo(Paths.get("lib_lint_baseline.xml")) - assertThat(parseArgs.config).isEqualTo(Paths.get("lint_config.xml")) - assertThat(parseArgs.customChecks).containsExactly(Paths.get("custom_rule.jar")) + assertThat(parseArgs.androidHome).isEqualTo(executionRoot.resolve("external/androidsdk")) + assertThat(parseArgs.srcs).containsExactly(executionRoot.resolve("path/to/Foo.kt")) + assertThat(parseArgs.output).isEqualTo(executionRoot.resolve("output.jar")) + assertThat(parseArgs.androidManifest).isEqualTo(executionRoot.resolve("AndroidManifest.xml")) + assertThat(parseArgs.jdkHome).isEqualTo(executionRoot.resolve("external/jdk")) + assertThat( + parseArgs.resources, + ).containsExactly(executionRoot.resolve("path/to/resource/strings.xml")) + assertThat(parseArgs.baselineFile).isEqualTo(executionRoot.resolve("lib_lint_baseline.xml")) + assertThat(parseArgs.config).isEqualTo(executionRoot.resolve("lint_config.xml")) + assertThat(parseArgs.customChecks).containsExactly(executionRoot.resolve("custom_rule.jar")) assertThat(parseArgs.classpath) - .containsExactly(Paths.get("classpath.jar")) + .containsExactly(executionRoot.resolve("classpath.jar")) assertThat(parseArgs.classpathAarPairs) - .containsExactly(Paths.get("classpath.aar") to Paths.get("aar_directory")) + .containsExactly( + executionRoot.resolve("classpath.aar") to executionRoot.resolve("aar_directory"), + ) assertThat(parseArgs.autofix).isTrue assertThat(parseArgs.regenerateBaselineFile).isTrue assertThat(parseArgs.warningsAsErrors).isTrue @@ -77,4 +87,31 @@ class AndroidLintActionArgsTest { assertThat(parseArgs.kotlinLanguageLevel).isEqualTo("1.8") assertThat(parseArgs.enableCheckDependencies).isTrue() } + + @Test + fun `empty android home means the toolchain has none`() { + val parseArgs = + AndroidLintActionArgs.parseArgs( + args = + listOf( + "--android-lint-cli-tool", + "cli.jar", + "--label", + "test", + "--output", + "output.xml", + "--compile-sdk-version", + "34", + "--java-language-level", + "17", + "--kotlin-language-level", + "1.9", + "--android-home", + "", + ), + executionRoot = Paths.get("/sandbox"), + ) + + assertThat(parseArgs.androidHome).isNull() + } } diff --git a/tests/src/cli/AndroidLintActionTest.kt b/tests/src/cli/AndroidLintActionTest.kt index b60b2a6..f84e95d 100644 --- a/tests/src/cli/AndroidLintActionTest.kt +++ b/tests/src/cli/AndroidLintActionTest.kt @@ -8,17 +8,25 @@ import org.junit.Test import org.junit.rules.TemporaryFolder import org.junit.runner.RunWith import org.junit.runners.JUnit4 +import java.io.PrintWriter +import java.io.StringWriter import java.nio.file.Files import java.nio.file.Path import java.nio.file.Paths +import java.util.concurrent.CyclicBarrier import java.util.jar.JarEntry import java.util.jar.JarOutputStream +import kotlin.concurrent.thread @RunWith(JUnit4::class) class AndroidLintActionTest { @get:Rule val temporaryFolder = TemporaryFolder() + private val executionRoot: Path by lazy { temporaryFolder.root.toPath() } + + private val stderr = PrintWriter(System.err, true) + @Before fun setUp() { Main.reset() @@ -28,10 +36,20 @@ class AndroidLintActionTest { fun `sequential work requests reuse a single cached lint classloader`() { val cache = AndroidLintCliInvokerCache(parentClassloader = javaClass.classLoader) val executor = AndroidLintAction.AndroidLintExecutor(cache) - val jar = writeStubLintJar() + val jar = writeStubLintJar(executionRoot.resolve("lint.jar")) - val firstExitCode = executor.processWorkRequest(workRequestArgs(jar, "first"), System.err) - val secondExitCode = executor.processWorkRequest(workRequestArgs(jar, "second"), System.err) + val firstExitCode = + executor.processWorkRequest( + workRequestArgs(jar, "first"), + executionRoot, + stderr, + ) + val secondExitCode = + executor.processWorkRequest( + workRequestArgs(jar, "second"), + executionRoot, + stderr, + ) assertThat(firstExitCode).isEqualTo(0) assertThat(secondExitCode).isEqualTo(0) @@ -45,13 +63,23 @@ class AndroidLintActionTest { // android_lint_test validator. A lint exit code must not kill or degrade the worker. val cache = AndroidLintCliInvokerCache(parentClassloader = javaClass.classLoader) val executor = AndroidLintAction.AndroidLintExecutor(cache) - val jar = writeStubLintJar() + val jar = writeStubLintJar(executionRoot.resolve("lint.jar")) Main.exitCode = AndroidLintCliInvoker.ERRNO_ERRORS - val errorsExitCode = executor.processWorkRequest(workRequestArgs(jar, "failing"), System.err) + val errorsExitCode = + executor.processWorkRequest( + workRequestArgs(jar, "failing"), + executionRoot, + stderr, + ) Main.exitCode = AndroidLintCliInvoker.ERRNO_SUCCESS - val successExitCode = executor.processWorkRequest(workRequestArgs(jar, "passing"), System.err) + val successExitCode = + executor.processWorkRequest( + workRequestArgs(jar, "passing"), + executionRoot, + stderr, + ) assertThat(errorsExitCode).isEqualTo(0) assertThat(successExitCode).isEqualTo(0) @@ -60,56 +88,157 @@ class AndroidLintActionTest { } @Test - fun `lint runs with an invocation-scoped user home`() { + fun `concurrent requests share one lint user home that outlives them`() { val cache = AndroidLintCliInvokerCache(parentClassloader = javaClass.classLoader) val executor = AndroidLintAction.AndroidLintExecutor(cache) - val jar = writeStubLintJar() + val jar = writeStubLintJar(executionRoot.resolve("lint.jar")) + Main.runBarrier = CyclicBarrier(2) + + val exitCodes = IntArray(2) + listOf("first", "second") + .mapIndexed { index, label -> + thread { + exitCodes[index] = + executor.processWorkRequest( + workRequestArgs(jar, label), + executionRoot, + stderr, + ) + } + }.forEach { it.join() } + + val userHomes = Main.recordedRuns.map { it.userHome } + assertThat(exitCodes).containsOnly(0) + assertThat(userHomes).hasSize(2).doesNotContainNull() + assertThat(userHomes.distinct()).hasSize(1) + assertThat(userHomes.first()).contains("lint-user-home") + assertThat(Files.isDirectory(Paths.get(userHomes.first()!!))).isTrue() + } + + @Test + fun `sandboxed request resolves every path against its sandbox`() { + // The worker runs in a different directory than the sandbox, so any path resolved against the + // worker's own working directory would miss these files. + val sandbox = temporaryFolder.newFolder("worker", "__sandbox", "7", "_main").toPath() + writeStubLintJar(sandbox.resolve("tools/lint.jar")) + writeFile(sandbox.resolve("src/Foo.java")) + writeFile(sandbox.resolve("src/AndroidManifest.xml")) + writeFile(sandbox.resolve("lib/dep.jar")) + writeFile(sandbox.resolve("libs/fixture.aar")) + writeStubLintJar(sandbox.resolve("libs/fixture-aar/lint.jar")) + writeFile(sandbox.resolve("lint.xml")) + writeFile(sandbox.resolve("baseline.xml")) + Files.createDirectories(sandbox.resolve("external/androidsdk")) + Files.createDirectories(sandbox.resolve("external/jdk")) + Files.write( + sandbox.resolve("lint.flags"), + listOf( + "--android-lint-cli-tool", + "tools/lint.jar", + "--label", + "sandboxed", + "--src", + "src/Foo.java", + "--android-manifest", + "src/AndroidManifest.xml", + "--classpath-jar", + "lib/dep.jar", + "--classpath-aar", + "libs/fixture.aar:libs/fixture-aar", + "--config-file", + "lint.xml", + "--baseline-file", + "baseline.xml", + "--android-home", + "external/androidsdk", + "--jdk-home", + "external/jdk", + "--output", + "bazel-out/cfg/bin/report.xml", + "--compile-sdk-version", + "34", + "--java-language-level", + "17", + "--kotlin-language-level", + "1.9", + ), + ) + val executor = + AndroidLintAction.AndroidLintExecutor( + AndroidLintCliInvokerCache(parentClassloader = javaClass.classLoader), + ) + val output = StringWriter() - val exitCode = executor.processWorkRequest(workRequestArgs(jar, "user-home"), System.err) + val exitCode = executor.processWorkRequest(listOf("@lint.flags"), sandbox, PrintWriter(output)) + assertThat(output.toString()).isEmpty() assertThat(exitCode).isEqualTo(0) - assertThat(Main.recordedRuns).hasSize(1) - assertThat(Main.recordedRuns.single().userHome) - .contains("lint-user-home") + val run = Main.recordedRuns.single() + val lintArgs = run.args + assertThat(lintArgs.argumentAfter("--xml")) + .isEqualTo(sandbox.resolve("bazel-out/cfg/bin/report.xml").toString()) + assertThat(lintArgs.argumentAfter("--path-variables")).isEqualTo("PWD=$sandbox") + assertThat(lintArgs.argumentAfter("--config")).isEqualTo(sandbox.resolve("lint.xml").toString()) + assertThat(lintArgs.argumentAfter("--sdk-home")) + .isEqualTo(sandbox.resolve("external/androidsdk").toString()) + assertThat(lintArgs.argumentAfter("--jdk-home")) + .isEqualTo(sandbox.resolve("external/jdk").toString()) + assertThat(run.projectXml) + .contains("") + .contains("") + .contains("") + .contains("") + .contains( + "", + ).contains("") } @Test - fun `lint receives sdk home from android home`() { + fun `requests in different sandboxes share the cached lint classloader`() { + // Sandboxes stage the same lint jar through different symlinks; the cache must see through + // them, or every sandboxed request would reload lint. + val realJar = writeStubLintJar(executionRoot.resolve("execroot/lint.jar")) val cache = AndroidLintCliInvokerCache(parentClassloader = javaClass.classLoader) val executor = AndroidLintAction.AndroidLintExecutor(cache) - val jar = writeStubLintJar() - val exitCode = - executor.processWorkRequest( - workRequestArgs( - lintJar = jar, - label = "android-home", - extraArgs = - listOf( - "--android-home", - "external/androidsdk", - ), - ), - System.err, + val exitCodes = + listOf("1", "2").map { id -> + val sandbox = temporaryFolder.newFolder("sandbox-$id").toPath() + Files.createDirectories(sandbox.resolve("tools")) + Files.createSymbolicLink(sandbox.resolve("tools/lint.jar"), realJar) + executor.processWorkRequest( + workRequestArgs(Paths.get("tools/lint.jar"), "sandbox-$id"), + sandbox, + stderr, + ) + } + + assertThat(exitCodes).containsOnly(0) + assertThat(Main.recordedRuns).hasSize(2) + assertThat(cache.createdCount).isEqualTo(1) + } + + @Test + fun `failed request reports its error to its own output`() { + val executor = + AndroidLintAction.AndroidLintExecutor( + AndroidLintCliInvokerCache(parentClassloader = javaClass.classLoader), ) + val output = StringWriter() - val rootDir = Paths.get(System.getenv("PWD")).toAbsolutePath().normalize() - val sdkHome = - Main.recordedRuns - .single() - .args - .argumentAfter("--sdk-home") + val exitCode = + executor.processWorkRequest(listOf("@missing.flags"), executionRoot, PrintWriter(output)) - assertThat(exitCode).isEqualTo(0) - assertThat(sdkHome).isEqualTo(rootDir.resolve("external/androidsdk").toString()) + assertThat(exitCode).isEqualTo(1) + assertThat(output.toString()).contains("missing.flags") } private fun workRequestArgs( lintJar: Path, label: String, - extraArgs: List = emptyList(), ): List { - val output = temporaryFolder.root.toPath().resolve("$label-output.xml") + val output = executionRoot.resolve("$label-output.xml") return listOf( "--android-lint-cli-tool", lintJar.toString(), @@ -123,11 +252,16 @@ class AndroidLintActionTest { "17", "--kotlin-language-level", "1.9", - ) + extraArgs + ) + } + + private fun writeFile(path: Path) { + Files.createDirectories(path.parent) + Files.writeString(path, "stub") } - private fun writeStubLintJar(): Path { - val jar = temporaryFolder.newFile("lint.jar").toPath() + private fun writeStubLintJar(jar: Path): Path { + Files.createDirectories(jar.parent) JarOutputStream(Files.newOutputStream(jar)).use { stream -> stream.putNextEntry(JarEntry("stub.txt")) stream.write("stub".toByteArray()) diff --git a/tests/src/cli/AndroidLintCliInvokerCacheTest.kt b/tests/src/cli/AndroidLintCliInvokerCacheTest.kt index fc20d57..102d41b 100644 --- a/tests/src/cli/AndroidLintCliInvokerCacheTest.kt +++ b/tests/src/cli/AndroidLintCliInvokerCacheTest.kt @@ -81,6 +81,31 @@ class AndroidLintCliInvokerCacheTest { assertThat(UastEnvironment.disposeCount.get()).isEqualTo(disposesBefore + 1) } + @Test + fun `cached invoker outlives the sandbox symlink it was acquired through`() { + // Multiplex sandboxing stages the lint jar as a symlink in a per-request sandbox, which Bazel + // deletes once the request finishes. Later requests reuse the cached classloader. + val cache = AndroidLintCliInvokerCache(parentClassloader = javaClass.classLoader) + val jar = writeJar("lint.jar", entryCount = 1) + val firstSandbox = temporaryFolder.newFolder("sandbox-1").toPath() + val first = + cache.acquire( + listOf(Files.createSymbolicLink(firstSandbox.resolve("lint.jar"), jar)), + ) + cache.release(first) + firstSandbox.toFile().deleteRecursively() + + val secondSandbox = temporaryFolder.newFolder("sandbox-2").toPath() + val second = + cache.acquire( + listOf(Files.createSymbolicLink(secondSandbox.resolve("lint.jar"), jar)), + ) + cache.release(second) + + assertThat(second).isSameAs(first) + assertThat(second.classLoader.getResource("entry-0.txt")).isNotNull() + } + @Test fun `invoke creates a fresh Main per call and applies checkDependencies per call`() { val cache = AndroidLintCliInvokerCache(parentClassloader = javaClass.classLoader) diff --git a/tests/src/cli/AndroidLintRunnerTest.kt b/tests/src/cli/AndroidLintRunnerTest.kt index 3c50752..c15be08 100644 --- a/tests/src/cli/AndroidLintRunnerTest.kt +++ b/tests/src/cli/AndroidLintRunnerTest.kt @@ -54,6 +54,7 @@ class AndroidLintRunnerTest { "--kotlin-language-level", "1.9", ), + executionRoot = temporaryFolder.root.toPath(), ) val exitCode = diff --git a/tests/src/cli/stubs/Main.kt b/tests/src/cli/stubs/Main.kt index 04d6bd7..5dcac76 100644 --- a/tests/src/cli/stubs/Main.kt +++ b/tests/src/cli/stubs/Main.kt @@ -1,5 +1,6 @@ package com.android.tools.lint +import java.io.File import java.util.concurrent.CopyOnWriteArrayList import java.util.concurrent.CyclicBarrier import java.util.concurrent.TimeUnit @@ -21,6 +22,12 @@ class Main { args = args.toList(), checkDependencies = flags.checkDependencies, userHome = System.getProperty("user.home"), + // The worker deletes the project file once the request finishes, so read it now. + projectXml = + args + .indexOf("--project") + .takeIf { it >= 0 } + ?.let { File(args[it + 1]).readText() }, ), ) return exitCode @@ -31,6 +38,7 @@ class Main { val args: List, val checkDependencies: Boolean, val userHome: String?, + val projectXml: String?, ) companion object { diff --git a/tests/src/worker/BUILD b/tests/src/worker/BUILD index 653f459..f99f482 100644 --- a/tests/src/worker/BUILD +++ b/tests/src/worker/BUILD @@ -8,6 +8,8 @@ kt_jvm_test( associates = ["//src/worker"], test_class = "com.rules.android.lint.worker.WorkerTest", deps = [ + "@bazel_worker_java//:worker_protocol_java_proto", + "@com_google_protobuf//:protobuf_java", "@rules_android_lint_test_deps//:junit_junit", "@rules_android_lint_test_deps//:org_assertj_assertj_core", ], diff --git a/tests/src/worker/WorkerTest.kt b/tests/src/worker/WorkerTest.kt index d904754..10a8cf7 100644 --- a/tests/src/worker/WorkerTest.kt +++ b/tests/src/worker/WorkerTest.kt @@ -1,13 +1,29 @@ package com.rules.android.lint.worker +import com.google.devtools.build.lib.worker.WorkerProtocol.WorkRequest +import com.google.devtools.build.lib.worker.WorkerProtocol.WorkResponse import org.assertj.core.api.Assertions.assertThat +import org.junit.Rule import org.junit.Test +import org.junit.rules.TemporaryFolder import org.junit.runner.RunWith import org.junit.runners.JUnit4 -import java.io.PrintStream +import java.io.IOException +import java.nio.channels.Channels +import java.nio.channels.Pipe +import java.nio.file.Files +import java.nio.file.Path +import java.nio.file.Paths +import java.util.concurrent.CyclicBarrier +import java.util.concurrent.Executors +import java.util.concurrent.TimeUnit +import kotlin.concurrent.thread @RunWith(JUnit4::class) class WorkerTest { + @get:Rule + val temporaryFolder = TemporaryFolder() + @Test fun `does return persistent worker when persistent worker flags are passed`() { val worker = Worker.fromArgs(arrayOf("--persistent_worker"), NO_OP_CALLBACK) @@ -22,23 +38,158 @@ class WorkerTest { @Test fun `does invocation worker return expected exit code`() { - val worker = Worker.fromArgs(arrayOf(""), stubWorkRequestCallback({ 100 })) + val worker = Worker.fromArgs(arrayOf(""), Worker.WorkRequestCallback { _, _, _ -> 100 }) val exitCode = worker.processRequests() assertThat(exitCode).isEqualTo(100) } - companion object { - fun stubWorkRequestCallback(callback: () -> Int): Worker.WorkRequestCallback = - object : Worker.WorkRequestCallback { - override fun processWorkRequest( - args: List, - printStream: PrintStream, - ): Int = callback() + @Test + fun `invocation worker runs its request in the process working directory`() { + var executionRoot: Path? = null + val worker = + Worker.fromArgs(arrayOf("--label", "one-shot")) { args, root, _ -> + assertThat(args).containsExactly("--label", "one-shot") + executionRoot = root + 0 + } + + worker.processRequests() + + assertThat(executionRoot!!.isAbsolute).isTrue() + assertThat( + Files.isSameFile(executionRoot!!, Paths.get(System.getProperty("user.dir"))), + ).isTrue() + } + + @Test + fun `concurrent multiplex requests run in their own sandbox and report their own output`() { + // Both requests write their output while both are still in flight, so output written to a + // stream shared between requests would show up in both responses. + val bothWritten = CyclicBarrier(2) + val responses = + runPersistentWorker( + workingDirectory = Paths.get("/worker"), + requests = + listOf( + WorkRequest + .newBuilder() + .setRequestId(1) + .addArguments("first") + .setSandboxDir("__sandbox/1/_main") + .build(), + WorkRequest + .newBuilder() + .setRequestId(2) + .addArguments("second") + .setSandboxDir("__sandbox/2/_main") + .build(), + ), + ) { args, executionRoot, output -> + output.print("${args.single()} ran in $executionRoot") + bothWritten.await(5, TimeUnit.SECONDS) + 0 + } + + assertThat(responses.values.map { it.exitCode }).containsOnly(0) + assertThat(responses.getValue(1).output) + .contains("first ran in /worker/__sandbox/1/_main") + .doesNotContain("second") + assertThat(responses.getValue(2).output) + .contains("second ran in /worker/__sandbox/2/_main") + .doesNotContain("first") + } + + @Test + fun `unsandboxed requests run in the worker working directory`() { + val responses = + runPersistentWorker( + workingDirectory = Paths.get("/execroot/_main"), + requests = listOf(WorkRequest.newBuilder().addArguments("only").build()), + ) { args, executionRoot, output -> + output.print("${args.single()} ran in $executionRoot") + 0 } - private val NO_OP_CALLBACK = - stubWorkRequestCallback( - callback = { TODO("NO-OP!") }, + assertThat(responses.getValue(0).exitCode).isEqualTo(0) + assertThat(responses.getValue(0).output).contains("only ran in /execroot/_main") + } + + @Test + fun `a checked exception fails the request instead of leaving it unanswered`() { + val responses = + runPersistentWorker( + workingDirectory = Paths.get("/execroot/_main"), + requests = listOf(WorkRequest.newBuilder().setRequestId(3).build()), + ) { _, _, _ -> throw IOException("disk full") } + + assertThat(responses.getValue(3).exitCode).isEqualTo(1) + assertThat(responses.getValue(3).output).contains("disk full") + } + + @Test + fun `working directory keeps PWD when it names the current directory`() { + val directory = temporaryFolder.newFolder("execroot").toPath() + val link = Files.createSymbolicLink(temporaryFolder.root.toPath().resolve("link"), directory) + + assertThat(workingDirectory(pwd = link.toString(), userDir = directory.toString())) + .isEqualTo(link) + } + + @Test + fun `working directory ignores a stale PWD`() { + val directory = temporaryFolder.newFolder("execroot").toPath() + val elsewhere = temporaryFolder.newFolder("elsewhere").toPath() + + assertThat(workingDirectory(pwd = elsewhere.toString(), userDir = directory.toString())) + .isEqualTo(directory) + assertThat(workingDirectory(pwd = null, userDir = directory.toString())) + .isEqualTo(directory) + } + + /** Sends [requests] to a [PersistentWorker] and returns its responses keyed by request id. */ + private fun runPersistentWorker( + workingDirectory: Path, + requests: List, + callback: Worker.WorkRequestCallback, + ): Map { + val requestPipe = Pipe.open() + val responsePipe = Pipe.open() + val worker = + PersistentWorker( + workerWorkRequestCallback = callback, + stdin = Channels.newInputStream(requestPipe.source()), + stdout = Channels.newOutputStream(responsePipe.sink()), + workingDirectory = workingDirectory, ) + val workerThread = thread { worker.processRequests() } + val reader = Executors.newSingleThreadExecutor() + val responses = + try { + val requestStream = Channels.newOutputStream(requestPipe.sink()) + requests.forEach { it.writeDelimitedTo(requestStream) } + requestStream.flush() + val responseStream = Channels.newInputStream(responsePipe.source()) + val responses = + reader + .submit> { + requests.map { WorkResponse.parseDelimitedFrom(responseStream) } + }.get(10, TimeUnit.SECONDS) + assertThat(responses).doesNotContainNull() + responses.filterNotNull().associateBy { it.requestId } + } finally { + // Closing the request pipe ends the worker loop, which restores the System streams. + requestPipe.sink().close() + workerThread.join(TimeUnit.SECONDS.toMillis(5)) + reader.shutdownNow() + requestPipe.source().close() + responsePipe.sink().close() + responsePipe.source().close() + } + assertThat(workerThread.isAlive).isFalse() + return responses + } + + companion object { + private val NO_OP_CALLBACK = Worker.WorkRequestCallback { _, _, _ -> TODO("NO-OP!") } } }