Skip to content
Merged
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
1 change: 1 addition & 0 deletions QUICKSTART.ko.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ JDK 21과 [운영체제에 맞는 ZIP](docs/ko/installation.md)을 설치한 뒤
```sh
scouterctl --version
scouterctl --help
scouterctl capture --help
```

여러 줄로 적은 명령은 Bash 예시입니다. Windows에서는 각 명령을 한 줄로 입력하면 같은 옵션을 사용할 수 있습니다.
Expand Down
1 change: 1 addition & 0 deletions QUICKSTART.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ Install the [Linux x64 or Windows x64 command package](docs/installation.md) wit
```sh
scouterctl --version
scouterctl --help
scouterctl capture --help
```

## 1. Connect to a Collector
Expand Down
3 changes: 3 additions & 0 deletions docs/cli-contract.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ This guide describes the output consumed by scripts and other tools. Output sche
- Command and argument errors also go to stdout as JSON. Do not assume stderr is the error API. Keep stdout and stderr separate when parsing.
- Explicit interactive password input uses a terminal and a human-readable prompt on stderr. Automation should provide `SCOUTERCTL_PASSWORD` and use `--no-input`; it must not depend on prompt text.
- `--help` and `--version` are plain-text stdout with exit 0, outside the JSON format. Help layout and diagnostic messages may change. Parse error codes rather than message text.
- `scouterctl COMMAND --help` shows that command's required and accepted options, combinations and an example (for example `scouterctl capture --help` or `scouterctl counter history --help`). A command-family help request such as `scouterctl counter --help` lists its commands. Help contains no ANSI escapes when output is redirected or `NO_COLOR` is set, including an empty value.
- These formats apply after the JVM and CLI start successfully. A missing/incompatible JVM, process termination or an unwritable output stream can prevent a valid JSON response. Missing or malformed output must not be treated as successful execution.

## Single-result commands
Expand All @@ -32,6 +33,8 @@ Completion never certifies traffic coverage, sampling, comparability or profile

The example message is illustrative. `error.code` is the machine-readable identifier; `error.message` is a human-readable string. An error object contains no result data. During a stream, previously emitted records remain on stdout but are not a complete result.

Unknown options, invalid/missing option values and unsupported command-option combinations identify the offending option in `error.message` where available. Argument values are not echoed; error schema and exit codes are unchanged.

| Exit | Error code when an error object is emitted | Meaning |
| --- | --- | --- |
| 0 | None | Requested command completed; scope limitations still apply |
Expand Down
6 changes: 4 additions & 2 deletions src/main/kotlin/dev/scouterctl/bootstrap/Bootstrap.kt
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,11 @@ fun runCli(args: Array<String>) {
OnlineCommands(contexts, { endpoint, password -> CollectorSource.connect(endpoint, password, BuildInfo.version) },
::CaptureStore, ::EvidenceStore, ::CounterCaptureStore, TerminalPasswordInput(), output),
)
val command = CommandLine(Cli(dispatcher, output))
val cli = Cli(dispatcher, output)
val command = CommandLine(cli)
cli.configureHelp(command)
command.commandSpec.version("scouterctl ${BuildInfo.version}")
command.setParameterExceptionHandler { _, _ -> output.failure(OperationFailure(ErrorCode.INVALID_ARGUMENT, "Invalid command arguments; use --help")) }
command.setParameterExceptionHandler { error, _ -> output.failure(argumentFailure(error)) }
exitProcess(command.execute(*args))
}

Expand Down
21 changes: 21 additions & 0 deletions src/main/kotlin/dev/scouterctl/cli/ArgumentFailure.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
package dev.scouterctl.cli

import dev.scouterctl.core.ErrorCode
import dev.scouterctl.core.OperationFailure
import picocli.CommandLine.Model.OptionSpec
import picocli.CommandLine.MissingParameterException
import picocli.CommandLine.ParameterException
import picocli.CommandLine.UnmatchedArgumentException

internal fun argumentFailure(error: ParameterException): OperationFailure {
val option = (error.argSpec as? OptionSpec)?.longestName()
?: (error as? MissingParameterException)?.missing?.filterIsInstance<OptionSpec>()?.firstOrNull()?.longestName()
val message = if (option != null) {
"Invalid or missing value for $option; use --help"
} else if (error is UnmatchedArgumentException) {
val unknown = error.unmatched.firstOrNull { it.substringBefore('=').matches(Regex("--?[A-Za-z][A-Za-z0-9-]*")) }
?.substringBefore('=')
if (unknown == null) "Invalid command arguments; use --help" else "Unknown option $unknown; use --help"
} else "Invalid command arguments; use --help"
return OperationFailure(ErrorCode.INVALID_ARGUMENT, message)
}
2 changes: 1 addition & 1 deletion src/main/kotlin/dev/scouterctl/cli/Cli.kt
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ import java.util.concurrent.Callable
"Password: SCOUTERCTL_PASSWORD, or --interactive for hidden terminal input. Passwords are never saved.",
"TCP has no native TLS; use a trusted path."])
class Cli(private val dispatcher: CommandDispatcher, private val output: JsonOutput) : Callable<Int> {
@Parameters(arity = "1..2", paramLabel = "COMMAND") lateinit var words: List<String>
@Parameters(arity = "1..2", paramLabel = "COMMAND") var words: List<String> = emptyList()
@Mixin val connection = ConnectionOptions()
@Spec lateinit var spec: CommandSpec
@Option(names = ["--name"], description = ["Name for context add/use"]) var name: String? = null
Expand Down
70 changes: 70 additions & 0 deletions src/main/kotlin/dev/scouterctl/cli/CommandGuide.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
package dev.scouterctl.cli

internal data class CommandGuide(
val name: String,
val description: String,
val required: Set<String>,
val optional: Set<String>,
val example: String,
val notes: List<String> = emptyList(),
) {
val allowed: Set<String> get() = required + optional
}

private val connectionOptions = setOf("--host", "--port", "--user", "--context", "--timeout-ms", "--interactive", "--no-input")
private val windowOptions = setOf("--from", "--to", "--timezone", "--object-hash")
private val xlogOptions = windowOptions + "--date"
private val pagingOptions = setOf("--page-size", "--max-pages")
private val offlineOptions = setOf("--include-text", "--no-input")
private val connectionNotes = listOf("Connection options override a saved context; otherwise host/port default to 127.0.0.1:6100.",
"Provide an account with --user or a saved context. Use SCOUTERCTL_PASSWORD, or --interactive for hidden terminal input.")
private const val windowExample = "--date 20261101 --from 2026-11-01T00:00:00Z --to 2026-11-01T00:01:00Z --timezone UTC --object-hash 42"

internal val commandGuides = listOf(
CommandGuide("doctor", "Check Collector connectivity and authentication.", emptySet(), connectionOptions,
"doctor --host localhost --user reader --no-input", connectionNotes),
CommandGuide("auth login", "Check credentials without saving a password.", emptySet(), connectionOptions,
"auth login --host localhost --user reader --interactive", connectionNotes),
CommandGuide("context add", "Save a named connection without its password.", setOf("--name", "--user"),
setOf("--host", "--port", "--no-input"), "context add --name local --host localhost --user reader"),
CommandGuide("context list", "List saved connections and the selected context.", emptySet(), setOf("--no-input"), "context list"),
CommandGuide("context use", "Select a saved connection.", setOf("--name"), setOf("--no-input"), "context use --name local"),
CommandGuide("collector status", "Read Collector status.", emptySet(), connectionOptions,
"collector status --user reader --no-input", connectionNotes),
CommandGuide("collector config", "Read safe Collector settings; optionally select an exact key.", emptySet(), connectionOptions + "--key",
"collector config --user reader --no-input", connectionNotes),
CommandGuide("agent status", "Read Agent JVM and runtime status.", setOf("--object-hash"), connectionOptions,
"agent status --object-hash 42 --user reader --no-input", connectionNotes),
CommandGuide("agent config", "Read safe Agent settings; optionally select an exact key.", setOf("--object-hash"), connectionOptions + "--key",
"agent config --object-hash 42 --user reader --no-input", connectionNotes),
CommandGuide("object list", "List live objects, or recorded objects for --date.", emptySet(), connectionOptions + "--date",
"object list --user reader --no-input", connectionNotes),
CommandGuide("counter list", "List available real-time counters for an object.", setOf("--object-hash"), connectionOptions,
"counter list --object-hash 42 --user reader --no-input", connectionNotes),
CommandGuide("counter get", "Read one exact real-time counter.", setOf("--object-hash", "--counter"), connectionOptions,
"counter get --object-hash 42 --counter Cpu --user reader --no-input", connectionNotes),
CommandGuide("counter history", "Stream stored counter values for a dated window.", xlogOptions + "--counter", connectionOptions,
"counter history $windowExample --counter Cpu --user reader --no-input", connectionNotes),
CommandGuide("counter export", "Export stored counters in resumable chunks.", windowOptions + setOf("--counter", "--directory"),
connectionOptions + setOf("--resume", "--chunk-minutes", "--max-chunks"),
"counter export --from 2026-11-01T00:00:00Z --to 2026-11-01T00:01:00Z --timezone UTC --object-hash 42 --counter Cpu --directory counters --user reader --no-input",
connectionNotes + "Use the same query and directory with --resume; chunk boundaries split at Collector midnight."),
CommandGuide("xlog search", "Stream XLogs for a storage date and time window.", xlogOptions, connectionOptions + pagingOptions + "--include-text",
"xlog search $windowExample --user reader --no-input", connectionNotes),
CommandGuide("profile get", "Read one stored transaction profile.", setOf("--date", "--txid"), connectionOptions + "--include-text",
"profile get --date 20261101 --txid 123 --user reader --no-input", connectionNotes),
CommandGuide("capture", "Save a resumable XLog capture, optionally including profiles.", xlogOptions + "--directory",
connectionOptions + pagingOptions + setOf("--resume", "--include-profiles", "--include-text"),
"capture $windowExample --directory capture --user reader --no-input",
connectionNotes + listOf("--include-text requires --include-profiles. Text can contain sensitive values.",
"Use the same query and directory with --resume. Profile capture defaults to page size 25, maximum 100.")),
CommandGuide("inspect", "Read a captured profile offline.", setOf("--directory", "--txid"), offlineOptions,
"inspect --directory capture --txid 123"),
CommandGuide("inspect search", "Search captured requests offline.", setOf("--directory"), offlineOptions +
setOf("--limit", "--min-elapsed-ms", "--errors-only", "--service-hash", "--service-name"),
"inspect search --directory capture --errors-only", listOf("--service-name requires --include-text and stored dictionary text.")),
CommandGuide("inspect summary", "Summarize captured services offline.", setOf("--directory"), offlineOptions + setOf("--limit", "--sort"),
"inspect summary --directory capture --sort elapsed"),
CommandGuide("inspect compare", "Compare baseline and candidate captures offline.", setOf("--before", "--after"), offlineOptions + "--limit",
"inspect compare --before baseline --after candidate"),
).associateBy { it.name }
36 changes: 36 additions & 0 deletions src/main/kotlin/dev/scouterctl/cli/CommandHelp.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
package dev.scouterctl.cli

import picocli.CommandLine
import picocli.CommandLine.Help
import picocli.CommandLine.Model.CommandSpec

internal fun Cli.configureHelp(command: CommandLine) {
val ansi = if (System.console() == null || System.getenv("NO_COLOR") != null) Help.Ansi.OFF else Help.Ansi.AUTO
command.setColorScheme(Help.defaultColorScheme(ansi))
command.setHelpFactory { root, colors -> Help(helpSpec(root, words.joinToString(" ")), colors) }
}

private fun helpSpec(root: CommandSpec, name: String): CommandSpec {
val guide = commandGuides[name]
val children = commandGuides.values.filter { it.name.startsWith("$name ") }
val help = CommandSpec.create().name(if (guide == null) "scouterctl" else "scouterctl $name")
val usage = help.usageMessage().optionListHeading("Options:%n").sortOptions(false)
if (guide != null) {
val footer = listOf(" scouterctl ${guide.example}") + if (children.isEmpty()) emptyList() else
listOf("", "Subcommands:") + children.map { " ${it.name.padEnd(18)} ${it.description}" }
usage.description(guide.description, *guide.notes.toTypedArray())
.footerHeading("%nExample:%n").footer(*footer.toTypedArray())
root.options().filter { it.usageHelp() || it.versionHelp() || it.longestName() in guide.allowed }.forEach { option ->
help.addOption(option.toBuilder().required(option.longestName() in guide.required).build())
}
} else {
val entries = if (name.isEmpty()) commandGuides.values else children
if (entries.isEmpty()) return root
usage.customSynopsis("scouterctl ${if (name.isEmpty()) "COMMAND" else "$name COMMAND"} [OPTIONS]")
.description(*(if (name.isEmpty()) root.usageMessage().description() else arrayOf("Scouter $name commands.")))
.footerHeading("%nCommands:%n").footer(*entries.map { " ${it.name.padEnd(18)} ${it.description}" }.toTypedArray(),
"", "Use scouterctl COMMAND --help for required options, accepted options and an example.")
root.options().filter { it.usageHelp() || it.versionHelp() }.forEach { help.addOption(it.toBuilder().build()) }
}
return help
}
38 changes: 16 additions & 22 deletions src/main/kotlin/dev/scouterctl/cli/CommandInterpreter.kt
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,11 @@ internal fun Cli.interpret(): CommandRequest {
if (command in setOf("context add", "context list", "context use")) return contextRequest(command)
if (name != null) invalid("--name requires context add/use")
if (command == "inspect compare") {
allowedOptions(setOf("--before", "--after", "--limit", "--include-text", "--no-input"))
allowedOptions()
return OfflineRequest.Compare(required(before, "--before"), required(after, "--after"), ComparisonOptions(limit ?: 20, includeText))
}
if (command == "counter export") {
allowedOptions(setOf("--host", "--port", "--user", "--context", "--timeout-ms", "--interactive", "--no-input",
"--object-hash", "--counter", "--from", "--to", "--timezone", "--directory", "--resume", "--chunk-minutes", "--max-chunks"))
allowedOptions()
val budget = maxChunks ?: 24
if (budget !in 1..10000) invalid("Use max-chunks 1..10000")
val query = CounterExportQuery(Instant.parse(required(from, "--from")).toEpochMilli(),
Expand All @@ -27,24 +26,20 @@ internal fun Cli.interpret(): CommandRequest {
}
if (chunkMinutes != null || maxChunks != null) invalid("--chunk-minutes and --max-chunks require counter export")
if (command == "counter history") {
allowedOptions(setOf("--host", "--port", "--user", "--context", "--timeout-ms", "--interactive", "--no-input",
"--object-hash", "--counter", "--date", "--from", "--to", "--timezone"))
allowedOptions()
return OnlineRequest.CounterHistory(CounterHistoryQuery(required(date, "--date"),
Instant.parse(required(from, "--from")).toEpochMilli(), Instant.parse(required(to, "--to")).toEpochMilli(),
required(timezone, "--timezone"), required(objHash, "--object-hash"), required(counterName, "--counter")).also { it.validate() })
}
if (command in setOf("counter list", "counter get")) {
allowedOptions(setOf("--host", "--port", "--user", "--context", "--timeout-ms", "--interactive", "--no-input", "--object-hash") +
if (command == "counter get") setOf("--counter") else emptySet())
allowedOptions()
val counter = if (command == "counter get") required(counterName, "--counter") else null
if (counter != null && (counter.isBlank() || counter.length > 256 || counter.any(Char::isISOControl))) invalid("Invalid counter name")
return OnlineRequest.Counters(required(objHash, "--object-hash"), counter)
}
if (counterName != null) invalid("--counter requires counter get, counter history or counter export")
if (command in setOf("collector status", "collector config", "agent status", "agent config")) {
allowedOptions(setOf("--host", "--port", "--user", "--context", "--timeout-ms", "--interactive", "--no-input") +
(if (command.endsWith("config")) setOf("--key") else emptySet()) +
if (command.startsWith("agent ")) setOf("--object-hash") else emptySet())
allowedOptions()
settingKey?.let { if (!it.matches(Regex("[A-Za-z_][A-Za-z0-9_.-]{0,255}"))) invalid("Use a setting name for --key") }
return when (command) {
"collector status" -> OnlineRequest.CollectorStatus
Expand All @@ -56,7 +51,7 @@ internal fun Cli.interpret(): CommandRequest {
if (settingKey != null) invalid("--key requires collector config or agent config")
if (before != null || after != null) invalid("--before and --after require inspect compare")
if (command == "inspect summary") {
allowedOptions(setOf("--directory", "--limit", "--sort", "--include-text", "--no-input"))
allowedOptions()
return OfflineRequest.Summary(required(directory, "--directory"),
ServiceSummaryOptions(limit ?: 20, ServiceSort.parse(summarySort ?: "errors"), includeText))
}
Expand All @@ -77,12 +72,7 @@ internal fun Cli.interpret(): CommandRequest {
}

private fun Cli.contextRequest(command: String): ContextRequest {
val allowed = when (command) {
"context add" -> setOf("--name", "--host", "--port", "--user", "--no-input")
"context use" -> setOf("--name", "--no-input")
else -> setOf("--no-input")
}
allowedOptions(allowed)
allowedOptions()
return when (command) {
"context add" -> ContextRequest.Add(name, connection.host ?: "127.0.0.1", connection.port ?: 6100, connection.user)
"context use" -> ContextRequest.Use(name)
Expand All @@ -94,10 +84,13 @@ private fun Cli.validateGeneralOptions(command: String) {
val supported = setOf("doctor", "auth login", "object list", "xlog search", "profile get", "capture", "inspect", "inspect search")
if (command !in supported) invalid("Unknown command")
if (command == "auth login") {
allowedOptions(setOf("--host", "--port", "--user", "--context", "--timeout-ms", "--interactive", "--no-input"))
allowedOptions()
}
if (command != "inspect search" && (limit != null || minElapsedMs != null || errorsOnly || serviceHash != null || serviceName != null)) {
invalid("Search filters require inspect search")
val option = spec.commandLine().parseResult.matchedOptions().first {
it.longestName() in setOf("--limit", "--min-elapsed-ms", "--errors-only", "--service-hash", "--service-name")
}.longestName()
invalid("$option requires inspect search")
}
if (includeProfiles && command != "capture") invalid("--include-profiles requires capture")
if (includeText && command !in setOf("xlog search", "profile get", "inspect", "inspect search") && !(command == "capture" && includeProfiles)) {
Expand Down Expand Up @@ -135,9 +128,10 @@ private fun Cli.query(): Query = Query(required(date, "--date"),
Instant.parse(required(from, "--from")).toEpochMilli(), Instant.parse(required(to, "--to")).toEpochMilli(),
required(timezone, "--timezone"), required(objHash, "--object-hash"), pageSize ?: if (includeProfiles) 25 else 1000).also { it.validate() }

private fun Cli.allowedOptions(allowed: Set<String>) {
if (spec.commandLine().parseResult.matchedOptions().any { it.longestName() !in allowed }) {
invalid("Option is not supported by this command; use --help")
private fun Cli.allowedOptions() {
val allowed = commandGuides.getValue(words.joinToString(" ")).allowed
spec.commandLine().parseResult.matchedOptions().firstOrNull { it.longestName() !in allowed }?.let {
invalid("Option ${it.longestName()} is not supported by this command; use --help")
}
}
private fun invalid(message: String): Nothing = throw OperationFailure(ErrorCode.INVALID_ARGUMENT, message)
Expand Down
Loading
Loading