|
| 1 | +/* |
| 2 | + * Copyright (C) 2023 Slack Technologies, LLC |
| 3 | + * |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | + * you may not use this file except in compliance with the License. |
| 6 | + * You may obtain a copy of the License at |
| 7 | + * |
| 8 | + * https://www.apache.org/licenses/LICENSE-2.0 |
| 9 | + * |
| 10 | + * Unless required by applicable law or agreed to in writing, software |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | + * See the License for the specific language governing permissions and |
| 14 | + * limitations under the License. |
| 15 | + */ |
| 16 | +package slack.cli.shellsentry |
| 17 | + |
| 18 | +import com.squareup.moshi.adapter |
| 19 | +import eu.jrie.jetbrains.kotlinshell.shell.shell |
| 20 | +import java.nio.file.Path |
| 21 | +import kotlin.io.path.ExperimentalPathApi |
| 22 | +import kotlin.io.path.createDirectories |
| 23 | +import kotlin.io.path.createTempDirectory |
| 24 | +import kotlin.io.path.createTempFile |
| 25 | +import kotlin.io.path.deleteRecursively |
| 26 | +import kotlin.system.exitProcess |
| 27 | +import okio.buffer |
| 28 | +import okio.source |
| 29 | + |
| 30 | +/** |
| 31 | + * Executes a command with Bugsnag tracing and retries as needed. |
| 32 | + * |
| 33 | + * @property command the command to execute (i.e. './gradlew build'). |
| 34 | + * @property workingDir the working directory to execute the command in. |
| 35 | + * @property cacheDir the directory to use for caching temporary files. Defaults to |
| 36 | + * [createTempDirectory]. |
| 37 | + * @property bugsnagKey optional Bugsnag API key to use for reporting. |
| 38 | + * @property config the [ShellSentryConfig] to use. |
| 39 | + * @property verbose whether to print verbose output. |
| 40 | + * @property debug whether to keep the cache directory around for debugging. Otherwise, it will be |
| 41 | + * deleted at the end. |
| 42 | + * @property noExit whether to exit the process with the exit code. This is useful for testing. |
| 43 | + * @property logger a function to log output to. Defaults to [println]. |
| 44 | + */ |
| 45 | +@Suppress("LongParameterList") |
| 46 | +public data class ShellSentry( |
| 47 | + private val command: String, |
| 48 | + private val workingDir: Path, |
| 49 | + private val cacheDir: Path = createTempDirectory("shellsentry"), |
| 50 | + private val bugsnagKey: String? = null, |
| 51 | + private val config: ShellSentryConfig = ShellSentryConfig(), |
| 52 | + private val verbose: Boolean = false, |
| 53 | + private val debug: Boolean = false, |
| 54 | + private val noExit: Boolean = false, |
| 55 | + private val logger: (String) -> Unit = ::println, |
| 56 | +) { |
| 57 | + |
| 58 | + @Suppress("CyclomaticComplexMethod", "LongMethod") |
| 59 | + @OptIn(ExperimentalPathApi::class) |
| 60 | + public fun exec() { |
| 61 | + // Initial command execution |
| 62 | + val (initialExitCode, initialLogFile) = executeCommand(command, cacheDir) |
| 63 | + var exitCode = initialExitCode |
| 64 | + var logFile = initialLogFile |
| 65 | + var attempts = 0 |
| 66 | + while (exitCode != 0 && attempts < 1) { |
| 67 | + attempts++ |
| 68 | + logger( |
| 69 | + "Command failed with exit code $exitCode. Running processor script (attempt $attempts)..." |
| 70 | + ) |
| 71 | + |
| 72 | + logger("Processing CI failure") |
| 73 | + val resultProcessor = ResultProcessor(verbose, bugsnagKey, config, logger) |
| 74 | + |
| 75 | + when (val retrySignal = resultProcessor.process(logFile, false)) { |
| 76 | + is RetrySignal.Ack, |
| 77 | + RetrySignal.Unknown -> { |
| 78 | + logger("Processor exited with 0, exiting with original exit code...") |
| 79 | + break |
| 80 | + } |
| 81 | + is RetrySignal.RetryDelayed -> { |
| 82 | + logger( |
| 83 | + "Processor script exited with 2, rerunning the command after ${retrySignal.delay}..." |
| 84 | + ) |
| 85 | + // TODO add option to reclaim memory? |
| 86 | + Thread.sleep(retrySignal.delay.inWholeMilliseconds) |
| 87 | + val secondResult = executeCommand(command, cacheDir) |
| 88 | + exitCode = secondResult.exitCode |
| 89 | + logFile = secondResult.outputFile |
| 90 | + if (secondResult.exitCode != 0) { |
| 91 | + // Process the second failure, then bounce out |
| 92 | + resultProcessor.process(secondResult.outputFile, isAfterRetry = true) |
| 93 | + } |
| 94 | + } |
| 95 | + is RetrySignal.RetryImmediately -> { |
| 96 | + logger("Processor script exited with 1, rerunning the command immediately...") |
| 97 | + // TODO add option to reclaim memory? |
| 98 | + val secondResult = executeCommand(command, cacheDir) |
| 99 | + exitCode = secondResult.exitCode |
| 100 | + logFile = secondResult.outputFile |
| 101 | + if (secondResult.exitCode != 0) { |
| 102 | + // Process the second failure, then bounce out |
| 103 | + resultProcessor.process(secondResult.outputFile, isAfterRetry = true) |
| 104 | + } |
| 105 | + } |
| 106 | + } |
| 107 | + } |
| 108 | + |
| 109 | + // If we got here, all is well |
| 110 | + // Delete the tmp files |
| 111 | + if (!debug) { |
| 112 | + cacheDir.deleteRecursively() |
| 113 | + } |
| 114 | + |
| 115 | + logger("Exiting with code $exitCode") |
| 116 | + if (!noExit) { |
| 117 | + exitProcess(exitCode) |
| 118 | + } |
| 119 | + } |
| 120 | + |
| 121 | + // Function to execute command and capture output. Shorthand to the testable top-level function. |
| 122 | + private fun executeCommand(command: String, tmpDir: Path) = |
| 123 | + executeCommand(workingDir, command, tmpDir, logger) |
| 124 | + |
| 125 | + public companion object { |
| 126 | + /** Creates a new instance with the given [argv] command line args as input. */ |
| 127 | + public fun create(argv: Array<String>, echo: (String) -> Unit): ShellSentry { |
| 128 | + val cli = ShellSentryCli().apply { main(argv + "--parse-only") } |
| 129 | + return create(cli, echo) |
| 130 | + } |
| 131 | + |
| 132 | + /** Internal function to consolidate CLI args -> [ShellSentry] creation logic. */ |
| 133 | + internal fun create( |
| 134 | + cli: ShellSentryCli, |
| 135 | + logger: (String) -> Unit = { cli.echo(it) } |
| 136 | + ): ShellSentry { |
| 137 | + val moshi = ProcessingUtil.newMoshi() |
| 138 | + val config = |
| 139 | + cli.configurationFile?.let { |
| 140 | + logger("Parsing config file '$it'") |
| 141 | + it.source().buffer().use { source -> moshi.adapter<ShellSentryConfig>().fromJson(source) } |
| 142 | + } |
| 143 | + ?: ShellSentryConfig() |
| 144 | + |
| 145 | + // Temporary dir for command output |
| 146 | + val cacheDir = cli.projectDir.resolve("tmp/shellsentry") |
| 147 | + cacheDir.createDirectories() |
| 148 | + |
| 149 | + return ShellSentry( |
| 150 | + command = cli.args.joinToString(" "), |
| 151 | + workingDir = cli.projectDir, |
| 152 | + cacheDir = cacheDir, |
| 153 | + config = config, |
| 154 | + verbose = cli.verbose, |
| 155 | + bugsnagKey = cli.bugsnagKey, |
| 156 | + debug = cli.debug, |
| 157 | + noExit = cli.noExit, |
| 158 | + logger = logger |
| 159 | + ) |
| 160 | + } |
| 161 | + } |
| 162 | +} |
| 163 | + |
| 164 | +internal data class ProcessResult(val exitCode: Int, val outputFile: Path) |
| 165 | + |
| 166 | +// Function to execute command and capture output |
| 167 | +internal fun executeCommand( |
| 168 | + workingDir: Path, |
| 169 | + command: String, |
| 170 | + tmpDir: Path, |
| 171 | + echo: (String) -> Unit, |
| 172 | +): ProcessResult { |
| 173 | + echo("Running command: '$command'") |
| 174 | + |
| 175 | + val tmpFile = createTempFile(tmpDir, "shellsentry", ".txt").toAbsolutePath() |
| 176 | + |
| 177 | + var exitCode = 0 |
| 178 | + shell { |
| 179 | + // Weird but the only way to set the working dir |
| 180 | + shell(dir = workingDir.toFile()) { |
| 181 | + // Read the output of the process and write to both stdout and file |
| 182 | + // This makes it behave a bit like tee. |
| 183 | + val echoHandler = stringLambda { line -> |
| 184 | + // The line always includes a trailing newline, but we don't need that |
| 185 | + echo(line.removeSuffix("\n")) |
| 186 | + // Pass the line through unmodified |
| 187 | + line to "" |
| 188 | + } |
| 189 | + val process = command.process() forkErr { it pipe echoHandler pipe tmpFile.toFile() } |
| 190 | + pipeline { process pipe echoHandler pipe tmpFile.toFile() }.join() |
| 191 | + exitCode = process.process.pcb.exitCode |
| 192 | + } |
| 193 | + } |
| 194 | + |
| 195 | + return ProcessResult(exitCode, tmpFile) |
| 196 | +} |
0 commit comments