Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 14 additions & 1 deletion rules/impl.bzl
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -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
Expand Down
13 changes: 8 additions & 5 deletions src/cli/AndroidLintAction.kt
Original file line number Diff line number Diff line change
@@ -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 {
Expand All @@ -18,23 +19,25 @@ object AndroidLintAction {
) : Worker.WorkRequestCallback {
override fun processWorkRequest(
args: List<String>,
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)
}
}
}
Expand Down
37 changes: 28 additions & 9 deletions src/cli/AndroidLintActionArgs.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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<Path, Path> = {
val (aar, aarDir) = this.split(":")
Pair(Paths.get(aar), Paths.get(aarDir))
Pair(resolve(aar), resolve(aarDir))
}

val androidLintCliTool: Path by parser.storing(
Expand All @@ -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
Expand Down Expand Up @@ -155,16 +160,30 @@ internal class AndroidLintActionArgs(
).default { false }

companion object {
internal fun parseArgs(args: List<String>): 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<String>,
executionRoot: Path,
): AndroidLintActionArgs {
require(executionRoot.isAbsolute) { "The execution root must be absolute: $executionRoot" }
// TODO Need to handle the --flagfile argument here
val unwrappedArgs: Array<String> =
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())
}
}
}
18 changes: 10 additions & 8 deletions src/cli/AndroidLintCliInvokerCache.kt
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,10 @@ internal class AndroidLintCliInvokerCache(

@Synchronized
internal fun acquire(jars: List<Path>): 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
Expand All @@ -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)
Expand Down Expand Up @@ -81,11 +84,10 @@ internal class AndroidLintCliInvokerCache(
}
}

private fun cacheKey(jars: List<Path>): 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<Path>): String =
realJars.joinToString(separator = "|") { jar ->
val size = Files.size(jar)
val lastModified = Files.getLastModifiedTime(jar).toMillis()
"$jar:$size:$lastModified"
}
}
24 changes: 7 additions & 17 deletions src/cli/AndroidLintRunner.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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,
Expand All @@ -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,
Expand All @@ -83,7 +77,6 @@ internal class AndroidLintRunner(
private fun invokeAndroidLintCLI(
invoker: AndroidLintCliInvoker,
actionArgs: AndroidLintActionArgs,
rootDirPath: String,
projectFilePath: Path,
baselineFilePath: Path,
cacheDirectoryPath: Path,
Expand All @@ -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,
Expand Down Expand Up @@ -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(
Expand Down
26 changes: 26 additions & 0 deletions src/cli/LintUserHome.kt
Original file line number Diff line number Diff line change
@@ -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
}
}
13 changes: 12 additions & 1 deletion src/worker/InvocationWorker.kt
Original file line number Diff line number Diff line change
@@ -1,11 +1,22 @@
package com.rules.android.lint.worker

import java.io.PrintWriter

internal class InvocationWorker(
private val args: Array<String>,
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()
}
}
}
29 changes: 24 additions & 5 deletions src/worker/PersistentWorker.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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()
Expand Down
Loading