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: 15 additions & 0 deletions docs/PLUGIN_API_CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,21 @@ milestone. **[verified]** = read from the checked-in ABI dump. **[reconstructed]
= diffed from `plugin-api/src` history (predates the dump; symbol-accurate).

### 26.43 — unreleased
- **breaking — A `ShellCommand` stops at its timeout or `cancel()`, with every process it started** _(ADFA-7178)_
A timeout used to wait for the command to exit, and a stop killed only the command's own
process, never its children. Each command now runs in a process group of its own, and a
timeout, `cancel()` or `cancelAllCommands()` stops the whole group: SIGTERM, then SIGKILL
250 ms later. `await()` returns within a second of the timeout, and a stopped command frees its slot.
On Android 11, whose `setsid` always forks, the IDE uses the Terminal's `setsid` instead, but
only if that one runs commands in place when the IDE first checks it. Where neither does, for
example because the Terminal isn't installed yet, commands get no group of their own until the
IDE's next start, and a stop leaves their children running, as before.
A command that exits on its own is never reported as timed out. If a background child still
holds its output 500 ms after the command exits, the child is stopped, and `await()` returns
within about 1.5 s of the exit. A command that exits before the IDE starts reading its output
is the exception: Java drains and closes the output as it exits, so such a child is not seen.
A child whose output goes elsewhere (`server >log 2>&1 &`) is left running, as is a process
that calls `setsid` itself.
- **breaking — JavaScript highlighting and the IDE's grammar names are the IDE's** _(ADFA-7084)_
The IDE now highlights `js`, `mjs`, `cjs` and `jsx` itself. A `LanguageDefinition` can still
claim them, but only with a language server: its grammar is ignored for them, and its server
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,20 +7,27 @@ import com.itsaky.androidide.plugins.extensions.CommandSpec
import com.itsaky.androidide.plugins.services.CommandExecution
import com.itsaky.androidide.plugins.services.IdeCommandService
import com.itsaky.androidide.utils.TermuxProcessEnvironment
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.NonCancellable
import kotlinx.coroutines.cancel
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.emptyFlow
import kotlinx.coroutines.flow.receiveAsFlow
import kotlinx.coroutines.joinAll
import kotlinx.coroutines.launch
import kotlinx.coroutines.withTimeout
import kotlinx.coroutines.runInterruptible
import kotlinx.coroutines.withContext
import kotlinx.coroutines.withTimeoutOrNull
import java.io.BufferedReader
import java.io.Closeable
import java.io.File
import java.io.IOException
import java.io.InputStream
import java.io.InputStreamReader
import java.nio.file.InvalidPathException
import java.util.UUID
Expand All @@ -32,6 +39,7 @@ class IdeCommandServiceImpl internal constructor(
private val projectRootProvider: () -> File?,
private val appFilesDir: File,
private val gradleTaskRunner: GradleTaskRunner = GradleTaskRunner(IdeBuildServiceImpl.getInstance()::startTasks),
private val processGroups: ProcessGroups = ProcessGroups.android(File(appFilesDir, "usr/bin/setsid")),
) : IdeCommandService {
private val runningCommands = ConcurrentHashMap<String, RunningCommand>()

Expand Down Expand Up @@ -60,13 +68,14 @@ class IdeCommandServiceImpl internal constructor(
} catch (e: IOException) {
return RejectedCommandExecution(executionId, "Invalid working directory: ${e.message}")
}
val command = processGroups.isolate(listOf(spec.executable) + spec.arguments, workDir)
val processBuilder =
try {
shellProcess(spec, workDir)
shellProcess(command.command, spec.environment, workDir)
} catch (e: IllegalArgumentException) {
return RejectedCommandExecution(executionId, "Invalid environment: ${e.message}")
}
CommandExecutionImpl(executionId, processBuilder, timeoutMs)
CommandExecutionImpl(executionId, processBuilder::start, command.grouped, processGroups, timeoutMs)
}
}
runningCommands[executionId] = execution
Expand All @@ -75,12 +84,13 @@ class IdeCommandServiceImpl internal constructor(
}

private fun shellProcess(
spec: CommandSpec.ShellCommand,
command: List<String>,
environment: Map<String, String>,
workDir: File?,
): ProcessBuilder =
ProcessBuilder(listOf(spec.executable) + spec.arguments).apply {
ProcessBuilder(command).apply {
workDir?.let { directory(it) }
environment().putAll(spec.environment)
environment().putAll(environment)
redirectErrorStream(false)
TermuxProcessEnvironment.applyTo(environment(), appFilesDir)
}
Expand Down Expand Up @@ -131,15 +141,32 @@ internal interface RunningCommand : CommandExecution {
fun isRunning(): Boolean
}

private class CommandExecutionImpl(
/**
* A shell command. However it ends - on its own, by timing out, by [cancel], or with an error -
* nothing it started is left running and no thread is left reading its output, with two
* exceptions. A command that exits on its own with its output closed may leave a process behind on
* purpose, as `nohup server >log 2>&1 &` does. And a process that left the group with its own
* `setsid` is not stopped; on a desktop JVM, its reader is not freed either.
*
* @param startProcess starts the process, which is the leader of its own process group if [grouped].
* @param outputGraceMs how long output may stay open once the command has exited.
*/
internal class CommandExecutionImpl(
override val executionId: String,
private val processBuilder: ProcessBuilder,
private val startProcess: () -> Process,
private val grouped: Boolean,
private val processGroups: ProcessGroups,
private val timeoutMs: Long,
private val outputGraceMs: Long = OUTPUT_GRACE_MS,
) : RunningCommand {
private val outputChannel = Channel<CommandOutput>(capacity = Channel.UNLIMITED)
private val resultDeferred = CompletableDeferred<CommandResult>()
private val scope = CoroutineScope(Dispatchers.IO + Job())

@Volatile
private var process: Process? = null

// Appended to by the reader threads, read by whichever thread ends the command.
private val stdoutBuilder = StringBuilder()
private val stderrBuilder = StringBuilder()

Expand All @@ -153,97 +180,126 @@ private class CommandExecutionImpl(
this.onComplete = onComplete
scope.launch {
val startTime = System.currentTimeMillis()

runCatching {
withTimeout(timeoutMs) {
process = processBuilder.start()
val proc = process!!

val stdoutJob = launch { readStream(proc, isStdErr = false) }
val stderrJob = launch { readStream(proc, isStdErr = true) }

val exitCode = proc.waitFor()
stdoutJob.join()
stderrJob.join()

outputChannel.send(CommandOutput.ExitCode(exitCode))
outputChannel.close()

val duration = System.currentTimeMillis() - startTime
if (exitCode == 0) {
CommandResult.Success(exitCode, stdoutBuilder.toString(), stderrBuilder.toString(), duration)
} else {
CommandResult.Failure(exitCode, stdoutBuilder.toString(), stderrBuilder.toString(), null, duration)
}
var started: Process? = null
var readers = emptyList<Job>()
var exitCode: Int? = null
var outputClosed = false
var cancelled = false
var error: Exception? = null
try {
withTimeoutOrNull(timeoutMs) {
// Recorded before the next suspension point, so that a cancel() landing while
// startProcess() ran, when there was no process yet to stop, has the finally below
// stop it (ADFA-7109).
val proc = startProcess()
started = proc
process = proc
readers = listOf(readLines(proc.inputStream, isStdErr = false), readLines(proc.errorStream, isStdErr = true))
// Interruptible, so that the timeout and cancel() end the wait at once.
runInterruptible { proc.waitFor() }
}
}.onSuccess { result ->
resultDeferred.complete(result)
}.onFailure { e ->
process?.destroyForcibly()
outputChannel.close()
val stdout = stdoutBuilder.toString()
val stderr = stderrBuilder.toString()
val duration = System.currentTimeMillis() - startTime
val failureResult =
when (e) {
is kotlinx.coroutines.TimeoutCancellationException -> {
CommandResult.Failure(-1, stdout, stderr, "Command timed out after ${timeoutMs}ms: ${e.message}", duration)
}

is kotlinx.coroutines.CancellationException -> {
CommandResult.Cancelled(stdout, stderr)
}

else -> {
CommandResult.Failure(-1, stdout, stderr, "Unexpected error: ${e.message}", duration)
}
// Read from the process, not the block's result: one that exits just as the time runs
// out ended on its own.
exitCode = started?.takeUnless { it.isAlive }?.exitValue()
if (exitCode != null) {
// Not under the timeout: the command has ended. A background child can hold the
// output open long after that, and is then stopped below. Unless no reader was in
// read() yet when the command exited: Process then drains the pipe and closes its
// end (ProcessPipeInputStream.processExited), so the output looks closed.
outputClosed = withTimeoutOrNull(outputGraceMs) { readers.joinAll() } != null
}
} catch (e: CancellationException) {
cancelled = true
} catch (e: Exception) {
error = e
} finally {
withContext(NonCancellable) {
started?.let { proc ->
if (exitCode == null || !outputClosed) processGroups.stop(proc, grouped)
// Ends the reads of any process that escaped the group or outlived the kill.
// A desktop JVM, where the unit tests run, does not wake a read on close.
closeQuietly(proc.inputStream, proc.errorStream, proc.outputStream)
}
if (resultDeferred.isActive) {
resultDeferred.complete(failureResult)
withTimeoutOrNull(READERS_STOP_MS) { readers.joinAll() }
}
}

val stdout = snapshot(stdoutBuilder)
val stderr = snapshot(stderrBuilder)
val duration = System.currentTimeMillis() - startTime
val result =
when {
error != null -> CommandResult.Failure(-1, stdout, stderr, "Unexpected error: ${error.message}", duration)
exitCode == 0 -> CommandResult.Success(0, stdout, stderr, duration)
exitCode != null -> CommandResult.Failure(exitCode, stdout, stderr, null, duration)
cancelled -> CommandResult.Cancelled(stdout, stderr)
else -> CommandResult.Failure(-1, stdout, stderr, "Command timed out after ${timeoutMs}ms", duration)
}
exitCode?.let { outputChannel.trySend(CommandOutput.ExitCode(it)) }
outputChannel.close()
// First, so that a caller resuming from await() finds the slot free.
onComplete()
// cancel() has already completed it with Cancelled.
resultDeferred.complete(result)
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}
}

private suspend fun readStream(
process: Process,
private fun readLines(
stream: InputStream,
isStdErr: Boolean,
) {
val stream = if (isStdErr) process.errorStream else process.inputStream
val builder = if (isStdErr) stderrBuilder else stdoutBuilder
BufferedReader(InputStreamReader(stream)).use { reader ->
var line = reader.readLine()
while (line != null) {
if (builder.length + line.length <= MAX_OUTPUT_BYTES) {
builder.appendLine(line)
): Job =
scope.launch {
val builder = if (isStdErr) stderrBuilder else stdoutBuilder
try {
BufferedReader(InputStreamReader(stream)).use { reader ->
while (true) {
val line = reader.readLine() ?: break
synchronized(builder) {
if (builder.length + line.length <= MAX_OUTPUT_BYTES) builder.appendLine(line)
}
outputChannel.trySend(if (isStdErr) CommandOutput.StdErr(line) else CommandOutput.StdOut(line))
}
}
val output = if (isStdErr) CommandOutput.StdErr(line) else CommandOutput.StdOut(line)
outputChannel.send(output)
line = reader.readLine()
} catch (e: IOException) {
// Closed under the read when the command was stopped.
}
}
}

private fun snapshot(builder: StringBuilder): String = synchronized(builder) { builder.toString() }

override suspend fun await(): CommandResult = resultDeferred.await()

override fun cancel() {
process?.destroyForcibly()
outputChannel.close()
// First, so that a caller resuming from await() finds the slot free.
onComplete()
if (resultDeferred.isActive) {
resultDeferred.complete(
CommandResult.Cancelled(stdoutBuilder.toString(), stderrBuilder.toString()),
)
resultDeferred.complete(CommandResult.Cancelled(snapshot(stdoutBuilder), snapshot(stderrBuilder)))
}
// The command's coroutine stops the process and its group as it ends.
scope.cancel()
onComplete()
}

override fun isRunning(): Boolean = process?.isAlive == true

companion object {
private const val MAX_OUTPUT_BYTES = 10 * 1024 * 1024

/** How long output may stay open once the command has exited. */
const val OUTPUT_GRACE_MS = 500L

/** How long a reader may take to end once the command is stopped and its output closed. */
private const val READERS_STOP_MS = 500L
}
}

private fun closeQuietly(vararg closeables: Closeable) {
for (closeable in closeables) {
try {
closeable.close()
} catch (e: IOException) {
// An InterruptedIOException here (ADFA-3945) only means a read was cut short.
}
}
}

Expand Down
Loading
Loading