carlos / platform Public

cli: carlos run -it and carlos console (rootfs plan 6)

carlos run -it (--interactive) and carlos console open a terminal
session through the console's session door: one dial, the Open with
$TERM and the window's size, the Status lines before raw mode, then
stdin as KindData, resizes as KindResize, output to stdout and
keepalives, until the End. sessionExit maps every End to RFS-6-C61's
codes and lines; a refusal before the upgrade prints the console's
sentence (exit 2). The terminal is restored once, before the last line,
on every way out: an End, a dropped or silent connection, SIGTERM or
SIGHUP, and a panic in the stdin copier. A Ctrl-C before the command
starts cancels it (130, RFS-6-C23). -it refuses --file, --timeout,
--follow and --idempotency-key before any dial. Raw mode is termios
through ioctl on linux and macOS; elsewhere -it says RFS-6-C07.

Copy: RFS-6-C01 to C26, C28 to C31 and C65 built; deck file cells
rewritten to the paths (PF-12).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev b087cc3f693610a15a6cbb7772157ace29d383ed parent b7a6760
11 files changed, +1,574 −25
  • approved_rootfs_copy_test.go +6 −0
  • docs/superpowers/plans/2026-10-24-rootfs-apps-copy.md +21 −21
  • interactive_cli.go +554 −0
  • interactive_cli_test.go +764 −0
  • interactive_term_darwin.go +9 −0
  • interactive_term_linux.go +9 −0
  • interactive_term_other.go +26 −0
  • interactive_term_unix.go +92 −0
  • main.go +2 −0
  • run.go +44 −4
  • run_test.go +47 −0
diff --git a/approved_rootfs_copy_test.go b/approved_rootfs_copy_test.go
index 17cf2f88c..e1bb9a84e 100644
--- a/approved_rootfs_copy_test.go
+++ b/approved_rootfs_copy_test.go
@@ -272,6 +272,12 @@ var rootfsCopyBuilt = []string{
// (internal/console/apiinstanceimport.go) and a replaced session's
// reason (internal/host/interactive.go)
"RFS-6-C66", "RFS-6-C67", "RFS-6-C68", "RFS-6-C69",
+ // Plan 6 Task 13: carlos run -it and carlos console (run.go,
+ // interactive_cli.go, interactive_term_other.go); RFS-6-C27 is Task 10's
+ "RFS-6-C01", "RFS-6-C02", "RFS-6-C03", "RFS-6-C04", "RFS-6-C05", "RFS-6-C06", "RFS-6-C07", "RFS-6-C08",
+ "RFS-6-C09", "RFS-6-C10", "RFS-6-C11", "RFS-6-C12", "RFS-6-C13", "RFS-6-C14", "RFS-6-C15", "RFS-6-C16",
+ "RFS-6-C17", "RFS-6-C18", "RFS-6-C19", "RFS-6-C20", "RFS-6-C21", "RFS-6-C22", "RFS-6-C23", "RFS-6-C24",
+ "RFS-6-C25", "RFS-6-C26", "RFS-6-C28", "RFS-6-C29", "RFS-6-C30", "RFS-6-C31", "RFS-6-C65",
}
func mustParseRootfsRecord(t *testing.T) []copyRow {
diff --git a/docs/superpowers/plans/2026-10-24-rootfs-apps-copy.md b/docs/superpowers/plans/2026-10-24-rootfs-apps-copy.md
index c9ed4c1ab..c823ecce7 100644
--- a/docs/superpowers/plans/2026-10-24-rootfs-apps-copy.md
+++ b/docs/superpowers/plans/2026-10-24-rootfs-apps-copy.md
@@ -473,37 +473,37 @@ From the plan: Every string is human text the plan introduces. Existing approved
| id | file | text | status |
|---|---|---|---|
-| RFS-6-C01 | `run.go` usage | carlos run --app <app> --instance <host> -it -- <arg>... | approved |
-| RFS-6-C02 | `run.go` flag `-it`, `--interactive` | run the command in a terminal session. what you type goes to it, and its screen comes back | approved |
+| RFS-6-C01 | run.go (usage, runUsageInteractive, built by Plan 6 Task 13) | carlos run --app <app> --instance <host> -it -- <arg>... | approved |
+| RFS-6-C02 | run.go (the flags -it and --interactive, runInteractiveFlagUsage, built by Plan 6 Task 13) | run the command in a terminal session. what you type goes to it, and its screen comes back | approved |
| RFS-6-C03 | run.go | -it takes no --file. a session reads from your keyboard instead | approved |
| RFS-6-C04 | run.go | -it takes no --timeout. a session ends after 30 minutes without a keystroke, and after 6 hours at most | approved |
| RFS-6-C05 | run.go | -it takes no --follow. a session cannot be picked up again once its connection is gone | approved |
| RFS-6-C06 | interactive_cli.go | carlos run -it needs a terminal. run it from an interactive shell, or leave out -it to run the command without one | approved |
| RFS-6-C07 | interactive_term_other.go | terminal sessions do not work on Windows yet. use carlos run without -it, or a macOS or Linux terminal | approved |
-| RFS-6-C08 | `interactive_cli.go` usage | usage: carlos console --app <app> --instance <host> | approved |
-| RFS-6-C09 | flag `--app` | the app whose console to open | approved |
-| RFS-6-C10 | flag `--instance` | the instance to open it on | approved |
+| RFS-6-C08 | interactive_cli.go (carlos console usage, consoleUsage, built by Plan 6 Task 13) | usage: carlos console --app <app> --instance <host> | approved |
+| RFS-6-C09 | interactive_cli.go (carlos console flag --app, built by Plan 6 Task 13) | the app whose console to open | approved |
+| RFS-6-C10 | interactive_cli.go (carlos console flag --instance, built by Plan 6 Task 13) | the instance to open it on | approved |
| RFS-6-C11 | interactive_cli.go | carlos console takes no command. it opens the console process the app's manifest declares. to run another command: carlos run -it --app <app> --instance <host> -- <command> | approved |
| RFS-6-C12 | interactive_cli.go | carlos console works only through a signed-in console, and this shell is in direct bucket mode. unset CARLOS_DEPLOYMENT_BUCKET and CARLOS_DEPLOYMENT_DIR, then run carlos auth login --console <url> | approved |
-| RFS-6-C13 | status | %s: waiting for its box to open the session | approved |
-| RFS-6-C14 | status | %s: starting the session. a sleeping instance wakes first | approved |
-| RFS-6-C15 | status | %s: connected. the session ends when the command exits | approved |
+| RFS-6-C13 | interactive_cli.go (a Status line, built by Plan 6 Task 13) | %s: waiting for its box to open the session | approved |
+| RFS-6-C14 | interactive_cli.go (a Status line, built by Plan 6 Task 13) | %s: starting the session. a sleeping instance wakes first | approved |
+| RFS-6-C15 | interactive_cli.go (a Status line, built by Plan 6 Task 13) | %s: connected. the session ends when the command exits | approved |
| RFS-6-C16 | interactive_cli.go | could not open a session connection to %s: %v | approved |
| RFS-6-C17 | interactive_cli.go | lost the connection to %s. the box closes the session within two minutes | approved |
-| RFS-6-C18 | sessionExit | %s: no box opened the session within 60 seconds. its box may be running an older release, or may not reach the console | approved |
-| RFS-6-C19 | sessionExit | %s: the session ended after 30 minutes without a keystroke | approved |
-| RFS-6-C20 | sessionExit | %s: the session ended at its 6 hour limit | approved |
-| RFS-6-C21 | sessionExit | %s: the session was interrupted: %s | approved |
-| RFS-6-C22 | sessionExit | %s: the connection to its box dropped, so the session was closed | approved |
-| RFS-6-C23 | sessionExit | %s: the session was cancelled before it started | approved |
-| RFS-6-C24 | sessionExit | %s: the box is not on the nested layout yet, so it cannot open a session | approved |
-| RFS-6-C25 | sessionExit | %s: the box has host claims armed. it cannot open a session yet | approved |
-| RFS-6-C26 | sessionExit | %s: the instance did not wake. %s | approved |
+| RFS-6-C18 | interactive_cli.go (sessionExit, built by Plan 6 Task 13) | %s: no box opened the session within 60 seconds. its box may be running an older release, or may not reach the console | approved |
+| RFS-6-C19 | interactive_cli.go (sessionExit, built by Plan 6 Task 13) | %s: the session ended after 30 minutes without a keystroke | approved |
+| RFS-6-C20 | interactive_cli.go (sessionExit, built by Plan 6 Task 13) | %s: the session ended at its 6 hour limit | approved |
+| RFS-6-C21 | interactive_cli.go (sessionExit, built by Plan 6 Task 13) | %s: the session was interrupted: %s | approved |
+| RFS-6-C22 | interactive_cli.go (sessionExit, built by Plan 6 Task 13) | %s: the connection to its box dropped, so the session was closed | approved |
+| RFS-6-C23 | interactive_cli.go (sessionExit, built by Plan 6 Task 13) | %s: the session was cancelled before it started | approved |
+| RFS-6-C24 | interactive_cli.go (sessionExit, built by Plan 6 Task 13) | %s: the box is not on the nested layout yet, so it cannot open a session | approved |
+| RFS-6-C25 | interactive_cli.go (sessionExit, built by Plan 6 Task 13) | %s: the box has host claims armed. it cannot open a session yet | approved |
+| RFS-6-C26 | interactive_cli.go (sessionExit, built by Plan 6 Task 13) | %s: the instance did not wake. %s | approved |
| RFS-6-C27 | internal/console/apiinteractive.go (console door, built by Plan 6 Task 10; `sessionExit` is Task 13's) | interactive sessions are off for %s. an owner can turn them on with carlos apps set %s --interactive on | approved |
-| RFS-6-C28 | sessionExit | %s was deleted and created again after this session was requested. the session did not start | approved |
-| RFS-6-C29 | sessionExit | %s is an import that is not committed yet. the session did not start | approved |
-| RFS-6-C30 | sessionExit | %s: its box is still closing the last session. try again in a minute | approved |
-| RFS-6-C31 | sessionExit | carlos run: the box did not open the session: %s | approved |
+| RFS-6-C28 | interactive_cli.go (sessionExit, built by Plan 6 Task 13) | %s was deleted and created again after this session was requested. the session did not start | approved |
+| RFS-6-C29 | interactive_cli.go (sessionExit, built by Plan 6 Task 13) | %s is an import that is not committed yet. the session did not start | approved |
+| RFS-6-C30 | interactive_cli.go (sessionExit, built by Plan 6 Task 13) | %s: its box is still closing the last session. try again in a minute | approved |
+| RFS-6-C31 | interactive_cli.go (sessionExit, built by Plan 6 Task 13) | carlos run: the box did not open the session: %s | approved |
| RFS-6-C32 | internal/console/apiinteractive.go (console door, built by Plan 6 Task 10) | %s already has an interactive session open, started by %s | approved |
| RFS-6-C33 | internal/console/apiinteractive.go (console door, built by Plan 6 Task 10) | %s runs a release that declares no console process. add a console entry to processes in the app's manifest, or name the command: carlos run -it --app %s --instance %s -- <command> | approved |
| RFS-6-C34 | internal/console/apiinteractive.go (console door, built by Plan 6 Task 10) | interactive sessions need this console to hold the release signing key | approved |
diff --git a/interactive_cli.go b/interactive_cli.go
new file mode 100644
index 000000000..ea7748084
--- /dev/null
+++ b/interactive_cli.go
@@ -0,0 +1,554 @@
+package main
+
+// carlos run -it and carlos console (rootfs apps spec §5.10, Plan 6 Task
+// 13): a terminal session on one instance, through the console's session
+// door (internal/console/apiinteractive.go). The CLI dials the door once,
+// sends its Open, prints the session's progress, puts the terminal in raw
+// mode when the command starts, and then bridges the keyboard and the
+// window size to the session and the session's output to the screen,
+// until the session's End. The terminal is restored on every way out
+// before the last line is printed.
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "flag"
+ "fmt"
+ "io"
+ "log"
+ "net/http"
+ "net/url"
+ "os"
+ "os/signal"
+ "slices"
+ "strings"
+ "sync"
+ "syscall"
+ "time"
+
+ "golang.org/x/net/websocket"
+
+ "github.com/carlosframework/platform/internal/interactive"
+ "github.com/carlosframework/platform/internal/release"
+ "github.com/carlosframework/platform/internal/runs"
+)
+
+const (
+ // RFS-6-C06: -it from something that is not a terminal.
+ sessionNeedsTerminalMsg = "carlos run -it needs a terminal. run it from an interactive shell, or leave out -it to run the command without one"
+ // RFS-6-C08 to C10: carlos console's usage and flags.
+ consoleUsage = "usage: carlos console --app <app> --instance <host>"
+ consoleAppFlagUsage = "the app whose console to open"
+ consoleInstanceFlagUsage = "the instance to open it on"
+ // RFS-6-C11: carlos console given a command.
+ consoleNoCommandMsg = "carlos console takes no command. it opens the console process the app's manifest declares. to run another command: carlos run -it --app <app> --instance <host> -- <command>"
+ // RFS-6-C12: carlos console in direct bucket mode.
+ consoleDirectModeMsg = "carlos console works only through a signed-in console, and this shell is in direct bucket mode. unset CARLOS_DEPLOYMENT_BUCKET and CARLOS_DEPLOYMENT_DIR, then run carlos auth login --console <url>"
+ // RFS-6-C13 to C15: the session's Status lines, before raw mode. The
+ // host.
+ sessionWaitingMsg = "%s: waiting for its box to open the session"
+ sessionStartingMsg = "%s: starting the session. a sleeping instance wakes first"
+ sessionConnectedMsg = "%s: connected. the session ends when the command exits"
+ // RFS-6-C16: the dial failed. The console, then the error.
+ sessionDialMsg = "could not open a session connection to %s: %v"
+ // RFS-6-C17: the connection to the console went with no End. The
+ // console.
+ sessionLostConsoleMsg = "lost the connection to %s. the box closes the session within two minutes"
+ // RFS-6-C18 to C31: sessionExit's lines. The host first, where there
+ // is one.
+ sessionExpiredMsg = "%s: no box opened the session within 60 seconds. its box may be running an older release, or may not reach the console"
+ sessionIdleMsg = "%s: the session ended after 30 minutes without a keystroke"
+ sessionLimitMsg = "%s: the session ended at its 6 hour limit"
+ sessionInterruptedMsg = "%s: the session was interrupted: %s"
+ sessionLostBoxMsg = "%s: the connection to its box dropped, so the session was closed"
+ sessionCancelledMsg = "%s: the session was cancelled before it started"
+ sessionFlatMsg = "%s: the box is not on the nested layout yet, so it cannot open a session"
+ sessionClaimMsg = "%s: the box has host claims armed. it cannot open a session yet"
+ sessionWakeMsg = "%s: the instance did not wake. %s"
+ // RFS-6-C27, shared with the console's door: the app, then the app.
+ sessionOffMsg = "interactive sessions are off for %s. an owner can turn them on with carlos apps set %s --interactive on"
+ sessionIncarnationMsg = "%s was deleted and created again after this session was requested. the session did not start"
+ sessionImportMsg = "%s is an import that is not committed yet. the session did not start"
+ sessionBusyMsg = "%s: its box is still closing the last session. try again in a minute"
+ sessionRefusedMsg = "carlos run: the box did not open the session: %s"
+ // RFS-6-C69, the reason carlos logs gives for a replaced session, is
+ // RFS-6-C21's reason here too.
+ sessionReplacedWords = "a newer session on the same instance replaced it"
+)
+
+// sessionDialTimeout bounds the dial: the upgrade, or the door's refusal.
+const sessionDialTimeout = 30 * time.Second
+
+// sessionReadBytes is the most one stdin read sends as one KindData frame.
+const sessionReadBytes = 4 << 10
+
+// terminal is the user's terminal: stdin and stdout.
+type terminal interface {
+ // MakeRaw puts the terminal in raw mode; restore puts it back.
+ MakeRaw() (restore func() error, err error)
+ Size() (cols, rows uint16, err error)
+ // Resizes signals each change of the window size (SIGWINCH on unix)
+ // until its stop is called.
+ Resizes() (<-chan struct{}, func())
+ // IsTerminal reports whether stdin and stdout are both a terminal.
+ IsTerminal() bool
+}
+
+// sessionClient is what runSession runs on: the dial, the terminal, the
+// streams and the signals that end a session (SIGINT, SIGTERM, SIGHUP).
+type sessionClient struct {
+ dial func(ctx context.Context, url, origin string, h http.Header) (*websocket.Conn, error)
+ term terminal
+ in io.Reader
+ out, errw io.Writer
+ signals <-chan os.Signal
+ // alive and lost are the keepalive interval and the silence after
+ // which the console is lost; 0 is interactive.KeepaliveEvery and
+ // interactive.KeepaliveLost.
+ alive, lost time.Duration
+}
+
+func (c sessionClient) say(line string) { fmt.Fprintln(c.errw, line) }
+
+// consoleOpen is carlos console's Open: the console process, no command.
+func consoleOpen() interactive.Open {
+ return interactive.Open{Schema: 1, Process: release.ProcessConsole}
+}
+
+// sessionOpen is open with the terminal filled in: $TERM (DefaultTerm when
+// it is empty or not a terminal type the console takes) and the window's
+// size, held within 1 to 1000 (80x24 when it cannot be read).
+func sessionOpen(open interactive.Open, term terminal) interactive.Open {
+ open.Schema = 1
+ open.Term = os.Getenv("TERM")
+ probe := interactive.Open{Schema: 1, Argv: []string{"x"}, Term: open.Term, Cols: 1, Rows: 1}
+ if probe.Check() != nil {
+ open.Term = interactive.DefaultTerm
+ }
+ open.Cols, open.Rows = 0, 0
+ if cols, rows, err := term.Size(); err == nil {
+ open.Cols, open.Rows = int(min(cols, interactive.MaxCols)), int(min(rows, interactive.MaxRows))
+ }
+ return open.Normalized()
+}
+
+// runSession runs one session through the door at doorURL (http or https)
+// on origin's console, as token, and returns the exit code: the command's
+// own status, or sessionExit's code for another end. Every line it prints
+// goes to c.errw.
+func runSession(ctx context.Context, c sessionClient, doorURL, origin, token, host, app string, open interactive.Open) int {
+ if err := termSupported(); err != nil {
+ c.say(err.Error())
+ return 2
+ }
+ if !c.term.IsTerminal() {
+ c.say(sessionNeedsTerminalMsg)
+ return 2
+ }
+ wsURL, err := interactive.WebSocketURL(doorURL)
+ if err != nil {
+ c.say(fmt.Sprintf(sessionDialMsg, origin, err))
+ return 1
+ }
+ open = sessionOpen(open, c.term)
+ ws, code, ok := dialSession(ctx, c, wsURL, origin, token, host)
+ if !ok {
+ return code
+ }
+ s := &session{c: c, ws: ws, origin: origin, host: host, app: app, open: open, stop: make(chan struct{})}
+ return s.run(ctx)
+}
+
+// dialSession dials the door once. A refusal before the upgrade is the
+// console's sentence, exit 2 (a 5xx with no sentence is a failed dial); a
+// failed dial is RFS-6-C16, exit 1; a signal while it dials cancels the
+// session before it started.
+func dialSession(ctx context.Context, c sessionClient, wsURL, origin, token, host string) (*websocket.Conn, int, bool) {
+ dctx, cancel := context.WithTimeout(ctx, sessionDialTimeout)
+ defer cancel()
+ type dialed struct {
+ ws *websocket.Conn
+ err error
+ }
+ done := make(chan dialed, 1)
+ go func() {
+ ws, err := c.dial(dctx, wsURL, origin, http.Header{"Authorization": {"Bearer " + token}})
+ done <- dialed{ws, err}
+ }()
+ var d dialed
+ select {
+ case d = <-done:
+ case <-c.signals:
+ cancel()
+ if d := <-done; d.ws != nil {
+ d.ws.Close()
+ }
+ c.say(fmt.Sprintf(sessionCancelledMsg, host))
+ return nil, 130, false
+ }
+ if d.err == nil {
+ return d.ws, 0, true
+ }
+ var re *interactive.RefusedError
+ if errors.As(d.err, &re) {
+ refusal := apiErrorFromBody(re.Status, re.Body)
+ if hasJSONError(re.Body) || re.Status >= 400 && re.Status < 500 {
+ c.say(refusal.Error())
+ return nil, 2, false
+ }
+ c.say(fmt.Sprintf(sessionDialMsg, origin, refusal))
+ return nil, 1, false
+ }
+ c.say(fmt.Sprintf(sessionDialMsg, origin, d.err))
+ return nil, 1, false
+}
+
+// session is one dialled session.
+type session struct {
+ c sessionClient
+ ws *websocket.Conn
+ origin, host, app string
+ open interactive.Open
+
+ stop chan struct{} // closed when the session is over
+ stopOnce sync.Once
+ restore func() error // set once raw mode is on
+ restored bool
+ resizes func() // stops the terminal's resizes, once they are watched
+}
+
+type sessionFrame struct {
+ kind byte
+ payload []byte
+}
+
+// run sends the Open and then serves the session until it ends.
+func (s *session) run(ctx context.Context) int {
+ defer func() {
+ // A panic anywhere in the session leaves the terminal as it found
+ // it, then goes on.
+ if p := recover(); p != nil {
+ s.end()
+ panic(p)
+ }
+ }()
+ lost := cmpOr(s.c.lost, interactive.KeepaliveLost)
+ if err := interactive.SendJSON(s.ws, interactive.KindOpen, s.open); err != nil {
+ return s.finish(1, fmt.Sprintf(sessionLostConsoleMsg, s.origin))
+ }
+ frames := make(chan sessionFrame)
+ readErr := make(chan error, 1)
+ go func() {
+ for {
+ _ = s.ws.SetReadDeadline(time.Now().Add(lost))
+ kind, payload, err := interactive.Receive(s.ws)
+ if err != nil {
+ readErr <- err
+ return
+ }
+ if kind == interactive.KindAlive {
+ continue
+ }
+ select {
+ case frames <- sessionFrame{kind, payload}:
+ case <-s.stop:
+ return
+ }
+ }
+ }()
+ go s.keepalive()
+ panics := make(chan any, 1)
+ started := false
+ for {
+ select {
+ case f := <-frames:
+ switch f.kind {
+ case interactive.KindStatus:
+ var st interactive.Status
+ if json.Unmarshal(f.payload, &st) != nil {
+ continue
+ }
+ switch st.State {
+ case interactive.StateWaiting:
+ s.c.say(fmt.Sprintf(sessionWaitingMsg, s.host))
+ case interactive.StateStarting:
+ s.c.say(fmt.Sprintf(sessionStartingMsg, s.host))
+ case interactive.StateStarted:
+ if started {
+ continue
+ }
+ s.c.say(fmt.Sprintf(sessionConnectedMsg, s.host))
+ restore, err := s.c.term.MakeRaw()
+ if err != nil {
+ return s.finish(2, sessionNeedsTerminalMsg)
+ }
+ s.restore, started = restore, true
+ s.bridge(panics)
+ }
+ case interactive.KindData:
+ _, _ = s.c.out.Write(f.payload)
+ case interactive.KindEnd:
+ var e interactive.End
+ if json.Unmarshal(f.payload, &e) != nil || e.Reason == "" {
+ return s.finish(1, fmt.Sprintf(sessionLostConsoleMsg, s.origin))
+ }
+ return s.finish(sessionExit(s.host, s.app, e))
+ }
+ case <-readErr:
+ return s.finish(1, fmt.Sprintf(sessionLostConsoleMsg, s.origin))
+ case sig := <-s.c.signals:
+ if !started {
+ return s.finish(130, fmt.Sprintf(sessionCancelledMsg, s.host))
+ }
+ return s.finish(signalExit(sig), "")
+ case p := <-panics:
+ panic(p)
+ case <-ctx.Done():
+ return s.finish(1, fmt.Sprintf(sessionLostConsoleMsg, s.origin))
+ }
+ }
+}
+
+// bridge starts, once the command has started, the stdin copier (KindData,
+// sessionReadBytes a read) and the window's resizes (KindResize): first the
+// size now, if it is not the Open's. A panic in the copier goes to panics.
+func (s *session) bridge(panics chan<- any) {
+ go func() {
+ defer func() {
+ if p := recover(); p != nil {
+ panics <- p
+ }
+ }()
+ buf := make([]byte, sessionReadBytes)
+ for {
+ n, err := s.c.in.Read(buf)
+ if n > 0 && interactive.Send(s.ws, interactive.KindData, buf[:n]) != nil {
+ return
+ }
+ if err != nil {
+ return
+ }
+ select {
+ case <-s.stop:
+ return
+ default:
+ }
+ }
+ }()
+ ch, stop := s.c.term.Resizes()
+ s.resizes = stop
+ sent := [2]int{s.open.Cols, s.open.Rows}
+ send := func() {
+ cols, rows, err := s.c.term.Size()
+ if err != nil || cols == 0 || rows == 0 {
+ return
+ }
+ size := [2]int{int(min(cols, interactive.MaxCols)), int(min(rows, interactive.MaxRows))}
+ if size == sent {
+ return
+ }
+ if interactive.Send(s.ws, interactive.KindResize, interactive.ResizePayload(uint16(size[0]), uint16(size[1]))) == nil {
+ sent = size
+ }
+ }
+ go func() {
+ send()
+ for {
+ select {
+ case <-s.stop:
+ return
+ case <-ch:
+ send()
+ }
+ }
+ }()
+}
+
+// keepalive sends KindAlive every alive until the session is over.
+func (s *session) keepalive() {
+ t := time.NewTicker(cmpOr(s.c.alive, interactive.KeepaliveEvery))
+ defer t.Stop()
+ for {
+ select {
+ case <-s.stop:
+ return
+ case <-t.C:
+ if interactive.Send(s.ws, interactive.KindAlive, nil) != nil {
+ return
+ }
+ }
+ }
+}
+
+// end is every way out's first step: the terminal restored, once, then
+// the session's goroutines stopped and its connection closed. A send
+// stuck on a console that stopped reading is cut off by the write
+// deadline, so the close never waits on it.
+func (s *session) end() {
+ if s.restore != nil && !s.restored {
+ s.restored = true
+ _ = s.restore()
+ }
+ s.stopOnce.Do(func() {
+ close(s.stop)
+ if s.resizes != nil {
+ s.resizes()
+ }
+ _ = s.ws.SetWriteDeadline(time.Now().Add(time.Second))
+ _ = s.ws.Close()
+ })
+}
+
+// finish ends the session, then prints line, if any, and returns code.
+func (s *session) finish(code int, line string) int {
+ s.end()
+ if line != "" {
+ s.c.say(line)
+ }
+ return code
+}
+
+// signalExit is the shell's code for a process a signal ended.
+func signalExit(sig os.Signal) int {
+ if n, ok := sig.(syscall.Signal); ok {
+ return 128 + int(n)
+ }
+ return 1
+}
+
+func cmpOr(d, def time.Duration) time.Duration {
+ if d > 0 {
+ return d
+ }
+ return def
+}
+
+// sessionExit is the exit code and the line (none for a command that
+// exited) for a session's End (RFS-6-C61): the command's status; 124 for
+// idle or the limit; 125 for an interruption or a lost box; 130 for a
+// session cancelled before it started; 3 for a box's refusal or no box at
+// all; 2 for the console's refusal, whose sentence is the Detail.
+func sessionExit(host, app string, e interactive.End) (int, string) {
+ switch e.Reason {
+ case interactive.EndExited:
+ return e.Exit, ""
+ case interactive.EndIdle:
+ return 124, fmt.Sprintf(sessionIdleMsg, host)
+ case interactive.EndLimit:
+ return 124, fmt.Sprintf(sessionLimitMsg, host)
+ case interactive.EndLost:
+ return 125, fmt.Sprintf(sessionLostBoxMsg, host)
+ case interactive.EndReplaced:
+ return 125, fmt.Sprintf(sessionInterruptedMsg, host, sessionReplacedWords)
+ case interactive.EndCancelled:
+ return 130, fmt.Sprintf(sessionCancelledMsg, host)
+ case interactive.EndExpired:
+ return 3, fmt.Sprintf(sessionExpiredMsg, host)
+ case interactive.EndRefused:
+ return sessionRefusal(host, app, e)
+ }
+ // Interrupted, with its reason, and any end this CLI does not know,
+ // with its code.
+ why := e.Detail
+ if why == "" {
+ why = e.Reason
+ }
+ return 125, fmt.Sprintf(sessionInterruptedMsg, host, why)
+}
+
+// sessionRefusal is sessionExit for a refusal. A box's refusal carries a
+// code and no sentence, except a wake's, whose Detail is its reason; the
+// console's carries its sentence in Detail.
+func sessionRefusal(host, app string, e interactive.End) (int, string) {
+ switch {
+ case e.Refused == runs.RefusedWake:
+ return 3, strings.TrimRight(fmt.Sprintf(sessionWakeMsg, host, e.Detail), " ")
+ case e.Detail != "":
+ return 2, e.Detail
+ }
+ switch e.Refused {
+ case runs.RefusedFlat:
+ return 3, fmt.Sprintf(sessionFlatMsg, host)
+ case runs.RefusedClaim:
+ return 3, fmt.Sprintf(sessionClaimMsg, host)
+ case interactive.RefusedOff:
+ return 3, fmt.Sprintf(sessionOffMsg, app, app)
+ case runs.RefusedIncarnation:
+ return 3, fmt.Sprintf(sessionIncarnationMsg, host)
+ case runs.RefusedImport:
+ return 3, fmt.Sprintf(sessionImportMsg, host)
+ case interactive.RefusedBusy:
+ return 3, fmt.Sprintf(sessionBusyMsg, host)
+ }
+ return 3, fmt.Sprintf(sessionRefusedMsg, e.Refused)
+}
+
+// openSession is carlos run -it's and carlos console's session on the
+// signed-in console: this terminal, its signals, the door's URL.
+func openSession(sess *apiSession, acct apiAcct, app, host string, open interactive.Open) int {
+ sig := make(chan os.Signal, 2)
+ signal.Notify(sig, os.Interrupt, syscall.SIGTERM, syscall.SIGHUP)
+ defer signal.Stop(sig)
+ c := sessionClient{dial: interactive.Dial, term: newTerminal(os.Stdin, os.Stdout),
+ in: os.Stdin, out: os.Stdout, errw: os.Stderr, signals: sig}
+ door := sess.c.base + apiPath(acct, app, "/instances/"+url.PathEscape(host)+"/interactive")
+ return runSession(context.Background(), c, door, sess.c.base, sess.c.token, host, app, open)
+}
+
+// consoleOpts is carlos console parsed.
+type consoleOpts struct {
+ app, instance, console string
+ acctRaw, acctIDRaw *string
+}
+
+// parseConsoleArgs parses carlos console, which takes no command: anything
+// after the flags, or a "--", is RFS-6-C11.
+func parseConsoleArgs(args []string, stderr io.Writer) (consoleOpts, error) {
+ fs := flag.NewFlagSet("console", flag.ContinueOnError)
+ fs.SetOutput(stderr)
+ app := appFlag(fs, consoleAppFlagUsage)
+ instance := fs.String("instance", "", consoleInstanceFlagUsage)
+ acctRaw, acctIDRaw, _ := accountFlags(fs)
+ console := consoleOption(fs, "console to act through (default: the only logged-in one)")
+ fs.Usage = flagUsage(fs, consoleUsage+"\n")
+ if err := fs.Parse(args); err != nil {
+ return consoleOpts{}, err
+ }
+ if fs.NArg() > 0 || slices.Contains(args, "--") {
+ return consoleOpts{}, errors.New(consoleNoCommandMsg)
+ }
+ o := consoleOpts{app: strings.TrimSpace(*app), instance: strings.TrimSpace(*instance), console: *console,
+ acctRaw: acctRaw, acctIDRaw: acctIDRaw}
+ if o.instance == "" {
+ return o, errRunUsage
+ }
+ return o, nil
+}
+
+// runConsole is carlos console: carlos run -it of the console process the
+// app's manifest declares.
+func runConsole(args []string) {
+ o, err := parseConsoleArgs(args, os.Stderr)
+ if err != nil {
+ if errors.Is(err, flag.ErrHelp) {
+ os.Exit(0)
+ }
+ if !errors.Is(err, errRunUsage) {
+ fmt.Fprintln(os.Stderr, err.Error())
+ }
+ fmt.Fprintln(os.Stderr, consoleUsage)
+ os.Exit(2)
+ }
+ sess, err := resolveMode(o.console)
+ if err != nil {
+ log.Fatal(err)
+ }
+ if sess == nil {
+ log.Fatal(consoleDirectModeMsg)
+ }
+ printUsing(os.Stderr, sess)
+ acct := resolvedAccount(sess, o.acctRaw, o.acctIDRaw)
+ app := resolvedApp(sess, acct, o.app, consoleUsage)
+ os.Exit(openSession(sess, acct, app, o.instance, consoleOpen()))
+}
diff --git a/interactive_cli_test.go b/interactive_cli_test.go
new file mode 100644
index 000000000..63a05c507
--- /dev/null
+++ b/interactive_cli_test.go
@@ -0,0 +1,764 @@
+package main
+
+// carlos run -it and carlos console (rootfs apps Plan 6 Task 13): the
+// parse, the session's bridge, its exit codes and lines, and the terminal
+// restored on every way out. The session tests run runSession against a
+// fake terminal and an httptest WebSocket server playing the console; the
+// end-to-end tests at the bottom run it against a real console.Server and
+// its session door (Task 10). Account bah, app shop, host shop.example.com.
+
+import (
+ "bytes"
+ "context"
+ "crypto/ed25519"
+ "crypto/rand"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "net"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "path/filepath"
+ "slices"
+ "strings"
+ "sync"
+ "syscall"
+ "testing"
+ "time"
+
+ "golang.org/x/net/websocket"
+
+ "github.com/carlosframework/platform/internal/appconfig"
+ "github.com/carlosframework/platform/internal/console"
+ "github.com/carlosframework/platform/internal/domains"
+ "github.com/carlosframework/platform/internal/interactive"
+ "github.com/carlosframework/platform/internal/provision"
+ "github.com/carlosframework/platform/internal/release"
+ "github.com/carlosframework/platform/internal/runs"
+)
+
+const ixCLIHost = "shop.example.com"
+
+// eventLog is the order of what a session did to the terminal and printed
+// on stderr: "raw", "restore", and "err: <text>" for each stderr write.
+type eventLog struct {
+ mu sync.Mutex
+ events []string
+}
+
+func (l *eventLog) add(e string) {
+ l.mu.Lock()
+ defer l.mu.Unlock()
+ l.events = append(l.events, e)
+}
+
+func (l *eventLog) all() []string {
+ l.mu.Lock()
+ defer l.mu.Unlock()
+ return slices.Clone(l.events)
+}
+
+// stderr is every stderr write, joined.
+func (l *eventLog) stderr() string {
+ var b strings.Builder
+ for _, e := range l.all() {
+ if s, ok := strings.CutPrefix(e, "err: "); ok {
+ b.WriteString(s)
+ }
+ }
+ return b.String()
+}
+
+func (l *eventLog) count(e string) int {
+ n := 0
+ for _, got := range l.all() {
+ if got == e {
+ n++
+ }
+ }
+ return n
+}
+
+// stderrLog logs each write as an "err: " event.
+type stderrLog struct{ l *eventLog }
+
+func (w stderrLog) Write(p []byte) (int, error) {
+ w.l.add("err: " + string(p))
+ return len(p), nil
+}
+
+// lockedBuffer is a bytes.Buffer safe to read while a session writes it.
+type lockedBuffer struct {
+ mu sync.Mutex
+ buf bytes.Buffer
+}
+
+func (b *lockedBuffer) Write(p []byte) (int, error) {
+ b.mu.Lock()
+ defer b.mu.Unlock()
+ return b.buf.Write(p)
+}
+
+func (b *lockedBuffer) String() string {
+ b.mu.Lock()
+ defer b.mu.Unlock()
+ return b.buf.String()
+}
+
+// fakeTerm is a terminal whose size the test sets and whose resizes it
+// fires; MakeRaw and its restore are logged.
+type fakeTerm struct {
+ log *eventLog
+ notTerm bool
+ mu sync.Mutex
+ cols, rows uint16
+ resizes chan struct{}
+}
+
+func newFakeTerm(l *eventLog, cols, rows uint16) *fakeTerm {
+ return &fakeTerm{log: l, cols: cols, rows: rows, resizes: make(chan struct{}, 1)}
+}
+
+func (f *fakeTerm) IsTerminal() bool { return !f.notTerm }
+
+func (f *fakeTerm) MakeRaw() (func() error, error) {
+ f.log.add("raw")
+ return func() error { f.log.add("restore"); return nil }, nil
+}
+
+func (f *fakeTerm) Size() (uint16, uint16, error) {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ return f.cols, f.rows, nil
+}
+
+func (f *fakeTerm) Resizes() (<-chan struct{}, func()) { return f.resizes, func() {} }
+
+func (f *fakeTerm) resize(cols, rows uint16) {
+ f.mu.Lock()
+ f.cols, f.rows = cols, rows
+ f.mu.Unlock()
+ f.resizes <- struct{}{}
+}
+
+// fakeDoor is an httptest server playing the console's session door at
+// /api/cli/apps/bah/shop/instances/shop.example.com/interactive. It checks
+// the bearer, reads the Open and hands the connection to script.
+type fakeDoor struct {
+ url string
+ dials int
+ mu sync.Mutex
+}
+
+func newFakeDoor(t *testing.T, script func(t *testing.T, ws *websocket.Conn, open interactive.Open)) *fakeDoor {
+ t.Helper()
+ d := &fakeDoor{}
+ ws := interactive.NewServer(func(ws *websocket.Conn) {
+ defer ws.Close()
+ _ = ws.SetDeadline(time.Now().Add(10 * time.Second))
+ kind, payload, err := interactive.Receive(ws)
+ if err != nil || kind != interactive.KindOpen {
+ t.Errorf("first frame: %q, %v", kind, err)
+ return
+ }
+ var o interactive.Open
+ if err := json.Unmarshal(payload, &o); err != nil {
+ t.Errorf("open: %v", err)
+ return
+ }
+ script(t, ws, o)
+ })
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ d.mu.Lock()
+ d.dials++
+ d.mu.Unlock()
+ if r.URL.Path != "/api/cli/apps/bah/shop/instances/"+ixCLIHost+"/interactive" || r.Header.Get("Authorization") != "Bearer tok" {
+ t.Errorf("dialled %s with %q", r.URL.Path, r.Header.Get("Authorization"))
+ http.NotFound(w, r)
+ return
+ }
+ ws.ServeHTTP(w, r)
+ }))
+ t.Cleanup(srv.Close)
+ d.url = srv.URL
+ return d
+}
+
+func (d *fakeDoor) doorURL() string {
+ return d.url + "/api/cli/apps/bah/shop/instances/" + ixCLIHost + "/interactive"
+}
+
+func sendStatus(ws *websocket.Conn, state string) error {
+ return interactive.SendJSON(ws, interactive.KindStatus, interactive.Status{State: state})
+}
+
+func sendEnd(ws *websocket.Conn, e interactive.End) error {
+ return interactive.SendJSON(ws, interactive.KindEnd, e)
+}
+
+// started sends the three states a session passes through.
+func started(t *testing.T, ws *websocket.Conn) {
+ t.Helper()
+ for _, s := range []string{interactive.StateWaiting, interactive.StateStarting, interactive.StateStarted} {
+ if err := sendStatus(ws, s); err != nil {
+ t.Errorf("status %s: %v", s, err)
+ }
+ }
+}
+
+// nextFrame is the CLI's next frame that is not a keepalive.
+func nextFrame(ws *websocket.Conn) (byte, []byte, error) {
+ for {
+ kind, payload, err := interactive.Receive(ws)
+ if err != nil || kind != interactive.KindAlive {
+ return kind, payload, err
+ }
+ }
+}
+
+// sessionRig is one runSession: its terminal, stdin, stdout, signals and
+// event log.
+type sessionRig struct {
+ log *eventLog
+ term *fakeTerm
+ inW *io.PipeWriter
+ out *lockedBuffer
+ sig chan os.Signal
+ c sessionClient
+}
+
+func newRig(t *testing.T) *sessionRig {
+ t.Helper()
+ l := &eventLog{}
+ inR, inW := io.Pipe()
+ t.Cleanup(func() { inW.Close() })
+ r := &sessionRig{log: l, term: newFakeTerm(l, 120, 40), inW: inW, out: &lockedBuffer{}, sig: make(chan os.Signal, 1)}
+ r.c = sessionClient{dial: interactive.Dial, term: r.term, in: inR, out: r.out, errw: stderrLog{l}, signals: r.sig}
+ return r
+}
+
+func (r *sessionRig) run(url, origin string, open interactive.Open) int {
+ ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
+ defer cancel()
+ return runSession(ctx, r.c, url, origin, "tok", ixCLIHost, "shop", open)
+}
+
+func argvOpen(argv ...string) interactive.Open {
+ return interactive.Open{Schema: 1, Argv: argv}
+}
+
+func TestRunConsoleTakesNoCommand(t *testing.T) {
+ const c11 = "carlos console takes no command. it opens the console process the app's manifest declares. to run another command: carlos run -it --app <app> --instance <host> -- <command>"
+ for _, args := range [][]string{
+ {"--app", "shop", "--instance", ixCLIHost, "--", "bin/rails", "console"},
+ {"--app", "shop", "--instance", ixCLIHost, "sh"},
+ {"--app", "shop", "--instance", ixCLIHost, "--"},
+ } {
+ if _, err := parseConsoleArgs(args, io.Discard); err == nil || err.Error() != c11 {
+ t.Errorf("%q: %v, want RFS-6-C11", args, err)
+ }
+ }
+ o, err := parseConsoleArgs([]string{"-a", "shop", "--instance", ixCLIHost}, io.Discard)
+ if err != nil || o.app != "shop" || o.instance != ixCLIHost {
+ t.Fatalf("parseConsoleArgs = %+v, %v", o, err)
+ }
+ if _, err := parseConsoleArgs([]string{"--app", "shop"}, io.Discard); !errors.Is(err, errRunUsage) {
+ t.Errorf("no --instance: %v, want the usage", err)
+ }
+ var help strings.Builder
+ parseConsoleArgs([]string{"-h"}, &help)
+ for _, want := range []string{"usage: carlos console --app <app> --instance <host>\n", "the app whose console to open", "the instance to open it on"} {
+ if !strings.Contains(help.String(), want) {
+ t.Errorf("-h lacks %q:\n%s", want, help.String())
+ }
+ }
+}
+
+func TestSessionRefusesWithoutATerminal(t *testing.T) {
+ r := newRig(t)
+ r.term.notTerm = true
+ dialled := false
+ r.c.dial = func(context.Context, string, string, http.Header) (*websocket.Conn, error) {
+ dialled = true
+ return nil, errors.New("no")
+ }
+ if code := r.run("http://127.0.0.1:1/x", "http://127.0.0.1:1", argvOpen("sh")); code != 2 || dialled {
+ t.Fatalf("code %d, dialled %v", code, dialled)
+ }
+ if got, want := r.log.stderr(), "carlos run -it needs a terminal. run it from an interactive shell, or leave out -it to run the command without one\n"; got != want {
+ t.Fatalf("stderr %q, want RFS-6-C06", got)
+ }
+}
+
+func TestSessionSendsOpenAndBridges(t *testing.T) {
+ for env, wantTerm := range map[string]string{"": interactive.DefaultTerm, "screen-256color": "screen-256color", "bad term!": interactive.DefaultTerm} {
+ t.Run("TERM="+env, func(t *testing.T) {
+ t.Setenv("TERM", env)
+ r := newRig(t)
+ r.c.alive = 10 * time.Millisecond
+ opened := make(chan interactive.Open, 1)
+ door := newFakeDoor(t, func(t *testing.T, ws *websocket.Conn, o interactive.Open) {
+ opened <- o
+ started(t, ws)
+ // Keepalives come, and the keystrokes as KindData.
+ var got []byte
+ alive := 0
+ for alive == 0 || len(got) < len("ls\r") {
+ kind, p, err := interactive.Receive(ws)
+ switch {
+ case err != nil:
+ t.Errorf("receive: %v", err)
+ return
+ case kind == interactive.KindAlive:
+ alive++
+ case kind == interactive.KindData:
+ got = append(got, p...)
+ default:
+ t.Errorf("frame %q", kind)
+ }
+ }
+ if string(got) != "ls\r" {
+ t.Errorf("stdin arrived as %q", got)
+ }
+ interactive.Send(ws, interactive.KindData, []byte("Gemfile\r\n"))
+ sendEnd(ws, interactive.End{Reason: interactive.EndExited, Exit: 0})
+ })
+ go r.inW.Write([]byte("ls\r"))
+ if code := r.run(door.doorURL(), door.url, argvOpen("bin/rails", "console")); code != 0 {
+ t.Fatalf("code %d; stderr %q", code, r.log.stderr())
+ }
+ o := <-opened
+ want := interactive.Open{Schema: 1, Argv: []string{"bin/rails", "console"}, Term: wantTerm, Cols: 120, Rows: 40}
+ if o.Schema != want.Schema || !slices.Equal(o.Argv, want.Argv) || o.Process != "" || o.Term != want.Term || o.Cols != 120 || o.Rows != 40 {
+ t.Fatalf("Open = %+v, want %+v", o, want)
+ }
+ if r.out.String() != "Gemfile\r\n" {
+ t.Errorf("stdout %q", r.out.String())
+ }
+ wantErr := ixCLIHost + ": waiting for its box to open the session\n" +
+ ixCLIHost + ": starting the session. a sleeping instance wakes first\n" +
+ ixCLIHost + ": connected. the session ends when the command exits\n"
+ if got := r.log.stderr(); got != wantErr {
+ t.Errorf("stderr %q, want C13 to C15", got)
+ }
+ // The status lines come before raw mode, and raw mode is undone.
+ ev := r.log.all()
+ if i := slices.Index(ev, "raw"); i < 3 || ev[len(ev)-1] != "restore" || r.log.count("restore") != 1 {
+ t.Errorf("events %q", ev)
+ }
+ })
+ }
+}
+
+func TestSessionForwardsResizes(t *testing.T) {
+ r := newRig(t)
+ door := newFakeDoor(t, func(t *testing.T, ws *websocket.Conn, o interactive.Open) {
+ started(t, ws)
+ // The session is started: the window changes.
+ r.term.resize(100, 30)
+ kind, p, err := nextFrame(ws)
+ if c, rows, ok := interactive.ParseResize(p); err != nil || kind != interactive.KindResize || !ok || c != 100 || rows != 30 {
+ t.Errorf("frame %q %v %v; want resize 100x30", kind, p, err)
+ }
+ sendEnd(ws, interactive.End{Reason: interactive.EndExited, Exit: 4})
+ })
+ if code := r.run(door.doorURL(), door.url, argvOpen("sh")); code != 4 {
+ t.Fatalf("code %d; stderr %q", code, r.log.stderr())
+ }
+}
+
+func TestSessionExitCodes(t *testing.T) {
+ const h = ixCLIHost
+ for _, tc := range []struct {
+ e interactive.End
+ code int
+ line string
+ }{
+ {interactive.End{Reason: interactive.EndExited, Exit: 0}, 0, ""},
+ {interactive.End{Reason: interactive.EndExited, Exit: 42}, 42, ""},
+ {interactive.End{Reason: interactive.EndIdle}, 124, h + ": the session ended after 30 minutes without a keystroke"},
+ {interactive.End{Reason: interactive.EndLimit}, 124, h + ": the session ended at its 6 hour limit"},
+ {interactive.End{Reason: interactive.EndInterrupted, Detail: "the instance was restarted"}, 125, h + ": the session was interrupted: the instance was restarted"},
+ {interactive.End{Reason: interactive.EndReplaced}, 125, h + ": the session was interrupted: a newer session on the same instance replaced it"},
+ {interactive.End{Reason: interactive.EndLost}, 125, h + ": the connection to its box dropped, so the session was closed"},
+ {interactive.End{Reason: interactive.EndCancelled}, 130, h + ": the session was cancelled before it started"},
+ {interactive.End{Reason: interactive.EndExpired}, 3, h + ": no box opened the session within 60 seconds. its box may be running an older release, or may not reach the console"},
+ {interactive.End{Reason: interactive.EndRefused, Refused: runs.RefusedFlat}, 3, h + ": the box is not on the nested layout yet, so it cannot open a session"},
+ {interactive.End{Reason: interactive.EndRefused, Refused: runs.RefusedClaim}, 3, h + ": the box has host claims armed. it cannot open a session yet"},
+ {interactive.End{Reason: interactive.EndRefused, Refused: runs.RefusedWake, Detail: "the image could not be fetched"}, 3, h + ": the instance did not wake. the image could not be fetched"},
+ {interactive.End{Reason: interactive.EndRefused, Refused: interactive.RefusedOff}, 3, "interactive sessions are off for shop. an owner can turn them on with carlos apps set shop --interactive on"},
+ {interactive.End{Reason: interactive.EndRefused, Refused: runs.RefusedIncarnation}, 3, h + " was deleted and created again after this session was requested. the session did not start"},
+ {interactive.End{Reason: interactive.EndRefused, Refused: runs.RefusedImport}, 3, h + " is an import that is not committed yet. the session did not start"},
+ {interactive.End{Reason: interactive.EndRefused, Refused: interactive.RefusedBusy}, 3, h + ": its box is still closing the last session. try again in a minute"},
+ {interactive.End{Reason: interactive.EndRefused, Refused: "quota"}, 3, "carlos run: the box did not open the session: quota"},
+ // The console's refusals carry its sentence, busy and import too.
+ {interactive.End{Reason: interactive.EndRefused, Detail: "the session request is malformed"}, 2, "the session request is malformed"},
+ {interactive.End{Reason: interactive.EndRefused, Refused: interactive.RefusedBusy, Detail: h + " already has an interactive session open, started by alice@example.com"}, 2, h + " already has an interactive session open, started by alice@example.com"},
+ {interactive.End{Reason: interactive.EndRefused, Refused: runs.RefusedImport, Detail: "an import sentence"}, 2, "an import sentence"},
+ } {
+ code, line := sessionExit(h, "shop", tc.e)
+ if code != tc.code || line != tc.line {
+ t.Errorf("sessionExit(%+v) = %d, %q; want %d, %q", tc.e, code, line, tc.code, tc.line)
+ }
+ }
+}
+
+// panicReader panics on its first read: a fault in the stdin copier.
+type panicReader struct{}
+
+func (panicReader) Read([]byte) (int, error) { panic("copier fault") }
+
+// TestSessionRestoresTheTerminalOnEveryExit (Review Focus 1): whichever way
+// a started session ends, the terminal is restored exactly once, and before
+// the last line.
+func TestSessionRestoresTheTerminalOnEveryExit(t *testing.T) {
+ const c17 = "lost the connection to %s. the box closes the session within two minutes\n"
+ for _, tc := range []struct {
+ name string
+ code int
+ last string // the last stderr line, "" for none
+ setup func(r *sessionRig)
+ door func(t *testing.T, r *sessionRig, ws *websocket.Conn)
+ }{
+ {name: "End exited", code: 0, door: func(t *testing.T, r *sessionRig, ws *websocket.Conn) {
+ sendEnd(ws, interactive.End{Reason: interactive.EndExited})
+ }},
+ {name: "End refused after started", code: 3, last: ixCLIHost + ": the box has host claims armed. it cannot open a session yet\n",
+ door: func(t *testing.T, r *sessionRig, ws *websocket.Conn) {
+ sendEnd(ws, interactive.End{Reason: interactive.EndRefused, Refused: runs.RefusedClaim})
+ }},
+ {name: "connection dropped", code: 1, last: c17, door: func(t *testing.T, r *sessionRig, ws *websocket.Conn) {
+ ws.Close()
+ }},
+ {name: "connection silent", code: 1, last: c17,
+ setup: func(r *sessionRig) { r.c.lost = 200 * time.Millisecond },
+ door: func(t *testing.T, r *sessionRig, ws *websocket.Conn) {
+ // The door says nothing; the CLI gives up after lost.
+ start := time.Now()
+ nextFrame(ws)
+ if d := time.Since(start); d > 3*time.Second {
+ t.Errorf("the CLI waited %s on a silent console", d)
+ }
+ }},
+ {name: "SIGTERM", code: 128 + int(syscall.SIGTERM), door: func(t *testing.T, r *sessionRig, ws *websocket.Conn) {
+ r.sig <- syscall.SIGTERM
+ // The CLI closes the connection.
+ if _, _, err := nextFrame(ws); err == nil {
+ t.Error("the connection stayed open after SIGTERM")
+ }
+ }},
+ {name: "SIGHUP", code: 128 + int(syscall.SIGHUP), door: func(t *testing.T, r *sessionRig, ws *websocket.Conn) {
+ r.sig <- syscall.SIGHUP
+ nextFrame(ws)
+ }},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ r := newRig(t)
+ if tc.setup != nil {
+ tc.setup(r)
+ }
+ door := newFakeDoor(t, func(t *testing.T, ws *websocket.Conn, o interactive.Open) {
+ started(t, ws)
+ // Raw mode is on before the door goes on.
+ for deadline := time.Now().Add(5 * time.Second); r.log.count("raw") == 0 && time.Now().Before(deadline); {
+ time.Sleep(5 * time.Millisecond)
+ }
+ tc.door(t, r, ws)
+ })
+ code := r.run(door.doorURL(), door.url, argvOpen("sh"))
+ if code != tc.code {
+ t.Fatalf("code %d, want %d; stderr %q", code, tc.code, r.log.stderr())
+ }
+ ev := r.log.all()
+ if r.log.count("restore") != 1 {
+ t.Fatalf("restored %d times: %q", r.log.count("restore"), ev)
+ }
+ last := strings.ReplaceAll(tc.last, "%s", door.url)
+ i := slices.Index(ev, "restore")
+ switch {
+ case last == "" && i != len(ev)-1:
+ t.Fatalf("events after the restore: %q", ev)
+ case last != "" && (i != len(ev)-2 || ev[len(ev)-1] != "err: "+last):
+ t.Fatalf("events %q; want restore, then %q", ev, last)
+ }
+ })
+ }
+
+ t.Run("a panic in the stdin copier", func(t *testing.T) {
+ r := newRig(t)
+ r.c.in = panicReader{}
+ door := newFakeDoor(t, func(t *testing.T, ws *websocket.Conn, o interactive.Open) {
+ started(t, ws)
+ nextFrame(ws)
+ })
+ var p any
+ func() {
+ defer func() { p = recover() }()
+ r.run(door.doorURL(), door.url, argvOpen("sh"))
+ }()
+ if p != "copier fault" {
+ t.Fatalf("recovered %v, want the copier's panic", p)
+ }
+ if ev := r.log.all(); r.log.count("restore") != 1 || ev[len(ev)-1] != "restore" {
+ t.Fatalf("events %q; want one restore, last", ev)
+ }
+ })
+}
+
+// TestSessionCtrlCBeforeStarted: a Ctrl-C while the session waits, in
+// cooked mode, closes the connection and exits 130 with RFS-6-C23; raw mode
+// was never entered.
+func TestSessionCtrlCBeforeStarted(t *testing.T) {
+ r := newRig(t)
+ r.c.errw = io.MultiWriter(stderrLog{r.log}, interruptOnWaiting(r.sig))
+ closed := make(chan error, 1)
+ door := newFakeDoor(t, func(t *testing.T, ws *websocket.Conn, o interactive.Open) {
+ sendStatus(ws, interactive.StateWaiting)
+ _, _, err := nextFrame(ws)
+ closed <- err
+ })
+ if code := r.run(door.doorURL(), door.url, argvOpen("sh")); code != 130 {
+ t.Fatalf("code %d; stderr %q", code, r.log.stderr())
+ }
+ if err := <-closed; err == nil {
+ t.Fatal("the connection stayed open")
+ }
+ if got, want := r.log.stderr(), ixCLIHost+": waiting for its box to open the session\n"+ixCLIHost+": the session was cancelled before it started\n"; got != want {
+ t.Fatalf("stderr %q, want %q", got, want)
+ }
+ if r.log.count("raw") != 0 || r.log.count("restore") != 0 {
+ t.Fatalf("events %q", r.log.all())
+ }
+}
+
+// TestSessionDialFailures: a refusal before the upgrade prints the door's
+// sentence and exits 2, from the one dial (no second request); a dial that
+// fails is RFS-6-C16, exit 1.
+func TestSessionDialFailures(t *testing.T) {
+ const off = "interactive sessions are off for shop. an owner can turn them on with carlos apps set shop --interactive on"
+ for _, tc := range []struct {
+ name string
+ status int
+ body string
+ code int
+ want string
+ }{
+ {"a JSON refusal", http.StatusConflict, `{"error":"` + off + `"}`, 2, off + "\n"},
+ {"the rate", http.StatusTooManyRequests, `{"error":"too many"}`, 2, "too many\n"},
+ {"a 503 the console explains", http.StatusServiceUnavailable, `{"error":"interactive sessions need this console to hold the release signing key"}`, 2,
+ "interactive sessions need this console to hold the release signing key\n"},
+ {"the membership 404", http.StatusNotFound, "404 page not found\n", 2, errMembershipNotFound.Error() + "\n"},
+ {"a 502 nobody explains", http.StatusBadGateway, "bad gateway", 1, "could not open a session connection to %s: unexpected response (status 502)\n"},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ n := 0
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ n++
+ w.WriteHeader(tc.status)
+ io.WriteString(w, tc.body)
+ }))
+ t.Cleanup(srv.Close)
+ r := newRig(t)
+ if code := r.run(srv.URL+"/door", srv.URL, argvOpen("sh")); code != tc.code {
+ t.Fatalf("code %d, want %d; stderr %q", code, tc.code, r.log.stderr())
+ }
+ if got, want := r.log.stderr(), strings.ReplaceAll(tc.want, "%s", srv.URL); got != want || n != 1 {
+ t.Fatalf("stderr %q after %d requests; want %q after 1", got, n, want)
+ }
+ })
+ }
+ t.Run("nothing listening", func(t *testing.T) {
+ ln, err := net.Listen("tcp", "127.0.0.1:0")
+ if err != nil {
+ t.Fatal(err)
+ }
+ u := "http://" + ln.Addr().String()
+ ln.Close()
+ r := newRig(t)
+ if code := r.run(u+"/door", u, argvOpen("sh")); code != 1 {
+ t.Fatalf("code %d", code)
+ }
+ if got := r.log.stderr(); !strings.HasPrefix(got, "could not open a session connection to "+u+": ") {
+ t.Fatalf("stderr %q, want RFS-6-C16", got)
+ }
+ })
+}
+
+func TestConsoleSendsTheConsoleProcess(t *testing.T) {
+ if o := consoleOpen(); o.Schema != 1 || o.Process != release.ProcessConsole || o.Argv != nil {
+ t.Fatalf("consoleOpen() = %+v", o)
+ }
+ r := newRig(t)
+ opened := make(chan interactive.Open, 1)
+ door := newFakeDoor(t, func(t *testing.T, ws *websocket.Conn, o interactive.Open) {
+ opened <- o
+ sendEnd(ws, interactive.End{Reason: interactive.EndExited})
+ })
+ if code := r.run(door.doorURL(), door.url, consoleOpen()); code != 0 {
+ t.Fatalf("code %d", code)
+ }
+ if o := <-opened; o.Process != release.ProcessConsole || o.Argv != nil || o.Normalized().Check() != nil {
+ t.Fatalf("Open = %+v", o)
+ }
+}
+
+// ---- end to end, against a real console --------------------------------
+
+// ixConsole is a real console.Server on httptest: account bah (Sqid 7)
+// owned by paul@keymail.dev, app shop, a hibernating instance at
+// shop.example.com on channel stable (which serves nothing yet), and a
+// signed-in CLI token.
+type ixConsole struct {
+ url string
+ token string
+ store release.Store
+ acct string
+ cst *console.Store
+}
+
+// sessionRows waits until every interactive-start row has its
+// interactive-end row, and returns the end rows' details.
+func (c *ixConsole) sessionRows(t *testing.T) []string {
+ t.Helper()
+ for deadline := time.Now().Add(10 * time.Second); ; time.Sleep(20 * time.Millisecond) {
+ evs, err := c.cst.Events(7, "shop", 100)
+ if err != nil {
+ t.Fatal(err)
+ }
+ starts := 0
+ var ends []string
+ for _, e := range evs {
+ switch e.Action {
+ case "interactive-start":
+ starts++
+ case "interactive-end":
+ ends = append(ends, e.Detail)
+ }
+ }
+ if starts == len(ends) {
+ return ends
+ }
+ if time.Now().After(deadline) {
+ t.Fatalf("%d sessions started, %d ended", starts, len(ends))
+ }
+ }
+}
+
+func newIxConsole(t *testing.T) *ixConsole {
+ t.Helper()
+ tmp := t.TempDir()
+ cst, err := console.Open(filepath.Join(tmp, "console.db"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { cst.Close() })
+ store := release.NewDirStore(filepath.Join(tmp, "store"))
+ pub, priv, err := ed25519.GenerateKey(rand.Reader)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var srv *console.Server
+ ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { srv.ServeHTTP(w, r) }))
+ t.Cleanup(ts.Close)
+ srv, err = console.NewServer(console.Config{Origin: ts.URL, Keymail: "http://keymail.invalid",
+ Registry: filepath.Join(tmp, "registry.db"), Releases: store, ReleasePub: pub, Key: priv, AppScheme: "http"}, cst)
+ if err != nil {
+ t.Fatal(err)
+ }
+ const id, owner = 7, "paul@keymail.dev"
+ sqid := domains.Sqid(id)
+ now := time.Now()
+ if err := cst.CreateAccount(id, sqid, "Shop", owner, now); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := cst.CreateAppIn(id, "shop", owner, now); err != nil {
+ t.Fatal(err)
+ }
+ if err := console.WriteAccountManifest(context.Background(), store, id, sqid, "Shop", now); err != nil {
+ t.Fatal(err)
+ }
+ yes := true
+ body, _ := json.Marshal(provision.Record{Host: ixCLIHost, App: "shop", Account: sqid, Channel: "stable", Region: "uk",
+ Hibernate: &yes, CreatedAt: now.UTC()})
+ if _, err := store.Put(context.Background(), provision.RecordKey(sqid, "shop", ixCLIHost), body, ""); err != nil {
+ t.Fatal(err)
+ }
+ token, _ := e2eDeviceLogin(t, ts.URL, cst, owner, "e2e@laptop")
+ c := &ixConsole{url: ts.URL, token: token, store: store, acct: sqid, cst: cst}
+ // Every session's end is written before the store closes.
+ t.Cleanup(func() { c.sessionRows(t) })
+ return c
+}
+
+func (c *ixConsole) run(t *testing.T, r *sessionRig, open interactive.Open) int {
+ t.Helper()
+ ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
+ defer cancel()
+ u := c.url + apiPath(apiAcct{Seg: c.acct}, "shop", "/instances/"+ixCLIHost+"/interactive")
+ return runSession(ctx, r.c, u, c.url, c.token, ixCLIHost, "shop", open)
+}
+
+// TestSessionAgainstTheConsole: the CLI against the real session door.
+// Sessions off: the refusal before the upgrade, RFS-6-C27, exit 2. On, and
+// carlos console on a release with no console process: the door's End after
+// the upgrade, RFS-6-C33, exit 2. On, and a command: the session waits for a
+// box (RFS-6-C13) until Ctrl-C, which exits 130 with RFS-6-C23.
+func TestSessionAgainstTheConsole(t *testing.T) {
+ c := newIxConsole(t)
+
+ r := newRig(t)
+ if code := c.run(t, r, argvOpen("sh")); code != 2 {
+ t.Fatalf("off: code %d; stderr %q", code, r.log.stderr())
+ }
+ if got, want := r.log.stderr(), "interactive sessions are off for shop. an owner can turn them on with carlos apps set shop --interactive on\n"; got != want {
+ t.Fatalf("off: stderr %q, want RFS-6-C27", got)
+ }
+
+ if _, err := appconfig.SetInteractive(context.Background(), c.store, c.acct, "shop", true); err != nil {
+ t.Fatal(err)
+ }
+ r = newRig(t)
+ if code := c.run(t, r, consoleOpen()); code != 2 {
+ t.Fatalf("console: code %d; stderr %q", code, r.log.stderr())
+ }
+ want := fmt.Sprintf("%s runs a release that declares no console process. add a console entry to processes in the app's manifest, or name the command: carlos run -it --app %s --instance %s -- <command>\n", ixCLIHost, "shop", ixCLIHost)
+ if got := r.log.stderr(); got != want {
+ t.Fatalf("console: stderr %q, want RFS-6-C33", got)
+ }
+
+ r = newRig(t)
+ r.c.errw = io.MultiWriter(stderrLog{r.log}, interruptOnWaiting(r.sig))
+ if code := c.run(t, r, argvOpen("bin/rails", "console")); code != 130 {
+ t.Fatalf("waiting: code %d; stderr %q", code, r.log.stderr())
+ }
+ if got, want := r.log.stderr(), ixCLIHost+": waiting for its box to open the session\n"+ixCLIHost+": the session was cancelled before it started\n"; got != want {
+ t.Fatalf("waiting: stderr %q", got)
+ }
+ // The console saw the CLI go: the session ended as cancelled, and the
+ // instance is free for the next one, which is admitted and waits too.
+ if ends := c.sessionRows(t); len(ends) != 1 || !strings.Contains(ends[0], `"reason":"cancelled"`) {
+ t.Fatalf("end rows %q, want one cancelled", ends)
+ }
+ r = newRig(t)
+ r.c.errw = io.MultiWriter(stderrLog{r.log}, interruptOnWaiting(r.sig))
+ if code := c.run(t, r, argvOpen("sh")); code != 130 {
+ t.Fatalf("second session: code %d; stderr %q", code, r.log.stderr())
+ }
+}
+
+// interruptOnWaiting is a stderr that sends sig an interrupt once the
+// waiting line (RFS-6-C13) is written.
+func interruptOnWaiting(sig chan os.Signal) io.Writer {
+ var once sync.Once
+ return writerFunc(func(p []byte) {
+ if strings.Contains(string(p), "waiting for its box") {
+ once.Do(func() { sig <- os.Interrupt })
+ }
+ })
+}
+
+type writerFunc func([]byte)
+
+func (f writerFunc) Write(p []byte) (int, error) { f(p); return len(p), nil }
diff --git a/interactive_term_darwin.go b/interactive_term_darwin.go
new file mode 100644
index 000000000..7716a1243
--- /dev/null
+++ b/interactive_term_darwin.go
@@ -0,0 +1,9 @@
+package main
+
+import "golang.org/x/sys/unix"
+
+// The termios requests on macOS.
+const (
+ ioctlGetTermios = unix.TIOCGETA
+ ioctlSetTermios = unix.TIOCSETA
+)
diff --git a/interactive_term_linux.go b/interactive_term_linux.go
new file mode 100644
index 000000000..824603513
--- /dev/null
+++ b/interactive_term_linux.go
@@ -0,0 +1,9 @@
+package main
+
+import "golang.org/x/sys/unix"
+
+// The termios requests on linux.
+const (
+ ioctlGetTermios = unix.TCGETS
+ ioctlSetTermios = unix.TCSETS
+)
diff --git a/interactive_term_other.go b/interactive_term_other.go
new file mode 100644
index 000000000..177473d56
--- /dev/null
+++ b/interactive_term_other.go
@@ -0,0 +1,26 @@
+//go:build !linux && !darwin
+
+package main
+
+// No terminal sessions here yet: carlos run -it and carlos console refuse
+// with RFS-6-C07 before they dial.
+
+import (
+ "errors"
+ "os"
+)
+
+// errTermUnsupported is RFS-6-C07.
+var errTermUnsupported = errors.New("terminal sessions do not work on Windows yet. use carlos run without -it, or a macOS or Linux terminal")
+
+type noTerm struct{}
+
+func newTerminal(in, out *os.File) terminal { return noTerm{} }
+
+// termSupported: sessions do not work here.
+func termSupported() error { return errTermUnsupported }
+
+func (noTerm) IsTerminal() bool { return false }
+func (noTerm) MakeRaw() (func() error, error) { return nil, errTermUnsupported }
+func (noTerm) Size() (uint16, uint16, error) { return 0, 0, errTermUnsupported }
+func (noTerm) Resizes() (<-chan struct{}, func()) { return nil, func() {} }
diff --git a/interactive_term_unix.go b/interactive_term_unix.go
new file mode 100644
index 000000000..87464cb0f
--- /dev/null
+++ b/interactive_term_unix.go
@@ -0,0 +1,92 @@
+//go:build linux || darwin
+
+package main
+
+// The user's terminal on linux and macOS: termios through ioctl, with the
+// request numbers in interactive_term_linux.go and interactive_term_darwin.go.
+
+import (
+ "os"
+ "os/signal"
+ "sync"
+
+ "golang.org/x/sys/unix"
+)
+
+// unixTerm is stdin and stdout.
+type unixTerm struct{ in, out *os.File }
+
+func newTerminal(in, out *os.File) terminal { return &unixTerm{in: in, out: out} }
+
+// termSupported: sessions work here.
+func termSupported() error { return nil }
+
+func isTTY(f *os.File) bool {
+ _, err := unix.IoctlGetTermios(int(f.Fd()), ioctlGetTermios)
+ return err == nil
+}
+
+func (t *unixTerm) IsTerminal() bool { return isTTY(t.in) && isTTY(t.out) }
+
+// MakeRaw is cfmakeraw on stdin: no echo, no line editing, no signals from
+// keys, no flow control and no output processing, one byte at a time.
+func (t *unixTerm) MakeRaw() (func() error, error) {
+ fd := int(t.in.Fd())
+ old, err := unix.IoctlGetTermios(fd, ioctlGetTermios)
+ if err != nil {
+ return nil, err
+ }
+ raw := *old
+ raw.Iflag &^= unix.IGNBRK | unix.BRKINT | unix.PARMRK | unix.ISTRIP | unix.INLCR | unix.IGNCR | unix.ICRNL | unix.IXON
+ raw.Oflag &^= unix.OPOST
+ raw.Lflag &^= unix.ECHO | unix.ECHONL | unix.ICANON | unix.ISIG | unix.IEXTEN
+ raw.Cflag &^= unix.CSIZE | unix.PARENB
+ raw.Cflag |= unix.CS8
+ raw.Cc[unix.VMIN] = 1
+ raw.Cc[unix.VTIME] = 0
+ if err := unix.IoctlSetTermios(fd, ioctlSetTermios, &raw); err != nil {
+ return nil, err
+ }
+ var once sync.Once
+ return func() error {
+ var err error
+ once.Do(func() { err = unix.IoctlSetTermios(fd, ioctlSetTermios, old) })
+ return err
+ }, nil
+}
+
+func (t *unixTerm) Size() (uint16, uint16, error) {
+ ws, err := unix.IoctlGetWinsize(int(t.out.Fd()), unix.TIOCGWINSZ)
+ if err != nil {
+ return 0, 0, err
+ }
+ return ws.Col, ws.Row, nil
+}
+
+// Resizes is SIGWINCH, coalesced: a change not yet read is not queued twice.
+func (t *unixTerm) Resizes() (<-chan struct{}, func()) {
+ sig := make(chan os.Signal, 1)
+ signal.Notify(sig, unix.SIGWINCH)
+ ch := make(chan struct{}, 1)
+ done := make(chan struct{})
+ go func() {
+ for {
+ select {
+ case <-done:
+ return
+ case <-sig:
+ select {
+ case ch <- struct{}{}:
+ default:
+ }
+ }
+ }
+ }()
+ var once sync.Once
+ return ch, func() {
+ once.Do(func() {
+ signal.Stop(sig)
+ close(done)
+ })
+ }
+}
diff --git a/main.go b/main.go
index 62f138eb2..115dcfd93 100644
--- a/main.go
+++ b/main.go
@@ -102,6 +102,8 @@ func main() {
runDB(args)
case "run":
runRun(args)
+ case "console":
+ runConsole(args)
case "steering":
runSteering(args)
case "schedule":
diff --git a/run.go b/run.go
index 0da9a1bc9..bd8bca022 100644
--- a/run.go
+++ b/run.go
@@ -23,6 +23,7 @@ import (
"syscall"
"time"
+ "github.com/carlosframework/platform/internal/interactive"
"github.com/carlosframework/platform/internal/provision"
"github.com/carlosframework/platform/internal/runs"
)
@@ -31,10 +32,13 @@ const runUsageRun = "usage: carlos run --app <app> --instance <host> [--file <pa
const runUsageFollow = "carlos run --app <app> --instance <host> --follow <id>"
+// runUsageInteractive is RFS-6-C01.
+const runUsageInteractive = "carlos run --app <app> --instance <host> -it -- <arg>..."
+
const runUsageKey = "add --idempotency-key <key> to start a run you can safely run again: the same key and request follow the run already started"
func runUsageText() string {
- return runUsageRun + "\n " + runUsageFollow + "\n " + runUsageKey + "\n"
+ return runUsageRun + "\n " + runUsageFollow + "\n " + runUsageInteractive + "\n " + runUsageKey + "\n"
}
const runDirectModeMsg = "carlos run works through a console, and this shell is in direct bucket mode. unset CARLOS_DEPLOYMENT_BUCKET and CARLOS_DEPLOYMENT_DIR, then run carlos auth login --console <url>"
@@ -47,6 +51,7 @@ var errRunUsage = errors.New("carlos run: usage")
type runOpts struct {
app, instance, follow, console string
idempotencyKey string
+ interactive bool // -it: a terminal session (runSession)
acctRaw, acctIDRaw *string
files []string
timeout time.Duration
@@ -71,6 +76,9 @@ func parseRunArgs(args []string, stderr io.Writer) (runOpts, error) {
timeout := fs.Duration("timeout", runs.DefaultTimeout, "how long the command may run (1s to 6h)")
follow := fs.String("follow", "", "attach to a run already started, by its id")
key := fs.String("idempotency-key", "", "a key of your choosing: run again with the same key and the same request, and you follow the run already started instead of starting a second")
+ var it bool
+ fs.BoolVar(&it, "it", false, runInteractiveFlagUsage)
+ fs.BoolVar(&it, "interactive", false, runInteractiveFlagUsage)
acctRaw, acctIDRaw, _ := accountFlags(fs)
console := consoleOption(fs, "console to run through (default: the only logged-in one)")
fs.Usage = flagUsage(fs, runUsageText())
@@ -82,10 +90,29 @@ func parseRunArgs(args []string, stderr io.Writer) (runOpts, error) {
}
o := runOpts{app: strings.TrimSpace(*app), instance: strings.TrimSpace(*instance), follow: strings.TrimSpace(*follow),
console: *console, acctRaw: acctRaw, acctIDRaw: acctIDRaw, files: files, timeout: *timeout, argv: argv,
- idempotencyKey: *key}
- switch {
- case o.instance == "":
+ idempotencyKey: *key, interactive: it}
+ if o.instance == "" {
return o, errors.New("--app and --instance name the instance to run against")
+ }
+ if o.interactive {
+ // What a session cannot use, refused before any dial.
+ timeoutGiven := false
+ fs.Visit(func(f *flag.Flag) { timeoutGiven = timeoutGiven || f.Name == "timeout" })
+ switch {
+ case len(o.files) > 0:
+ return o, errors.New(runInteractiveFileMsg)
+ case timeoutGiven:
+ return o, errors.New(runInteractiveTimeoutMsg)
+ case o.follow != "":
+ return o, errors.New(runInteractiveFollowMsg)
+ case o.idempotencyKey != "":
+ return o, errors.New(runInteractiveKeyMsg)
+ case len(o.argv) == 0:
+ return o, errRunUsage
+ }
+ return o, nil
+ }
+ switch {
case o.follow != "" && (len(o.argv) > 0 || len(o.files) > 0):
return o, errors.New("--follow takes a run id and no command after --")
case runs.CheckTimeout(o.timeout) != nil:
@@ -98,6 +125,16 @@ func parseRunArgs(args []string, stderr io.Writer) (runOpts, error) {
return o, nil
}
+const (
+ // RFS-6-C02: the -it and --interactive flags.
+ runInteractiveFlagUsage = "run the command in a terminal session. what you type goes to it, and its screen comes back"
+ // RFS-6-C03 to C05 and C65: what -it refuses.
+ runInteractiveFileMsg = "-it takes no --file. a session reads from your keyboard instead"
+ runInteractiveTimeoutMsg = "-it takes no --timeout. a session ends after 30 minutes without a keystroke, and after 6 hours at most"
+ runInteractiveFollowMsg = "-it takes no --follow. a session cannot be picked up again once its connection is gone"
+ runInteractiveKeyMsg = "-it takes no --idempotency-key. a session is never repeated by a retry"
+)
+
// runKeyShapeMsg is what the CLI says of a key that the console would refuse.
const runKeyShapeMsg = "--idempotency-key is 1 to 128 characters: letters, digits, dots, underscores, colons and hyphens"
@@ -846,6 +883,9 @@ func runRun(args []string) {
printUsing(os.Stderr, sess)
acct := resolvedAccount(sess, o.acctRaw, o.acctIDRaw)
app := resolvedApp(sess, acct, o.app, runUsageText())
+ if o.interactive {
+ os.Exit(openSession(sess, acct, app, o.instance, interactive.Open{Schema: 1, Argv: o.argv}))
+ }
interrupts := make(chan os.Signal, 2)
signal.Notify(interrupts, os.Interrupt, syscall.SIGTERM)
t := runTerm{stdout: os.Stdout, stderr: os.Stderr, interrupts: interrupts, after: time.After, now: time.Now}
diff --git a/run_test.go b/run_test.go
index 0caf9cabe..4c195c34c 100644
--- a/run_test.go
+++ b/run_test.go
@@ -1462,3 +1462,50 @@ func TestRunCLIRetryOfARunWhoseOutputIsGone(t *testing.T) {
t.Fatalf("unnamed replay: exit %d, stderr %q", code, f.err.String())
}
}
+
+// TestParseRunArgsInteractive: -it and --interactive set a session, which
+// needs a command after -- and refuses what a session cannot use: --file
+// (RFS-6-C03), a given --timeout (C04), --follow (C05) and
+// --idempotency-key (C65), each before any dial.
+func TestParseRunArgsInteractive(t *testing.T) {
+ for _, flag := range []string{"-it", "--interactive"} {
+ o, err := parseRunArgs([]string{flag, "--app", "shop", "--instance", "h.example.com", "--", "bin/rails", "console"}, io.Discard)
+ if err != nil || !o.interactive || !slices.Equal(o.argv, []string{"bin/rails", "console"}) {
+ t.Fatalf("%s: %+v, %v", flag, o, err)
+ }
+ }
+ if o, err := parseRunArgs([]string{"--instance", "h.example.com", "--", "x"}, io.Discard); err != nil || o.interactive {
+ t.Fatalf("without -it: %+v, %v", o, err)
+ }
+ for args, want := range map[string]string{
+ "-it --instance h.example.com --file a.csv -- x": "-it takes no --file. a session reads from your keyboard instead",
+ "-it --instance h.example.com --timeout 30m -- x": "-it takes no --timeout. a session ends after 30 minutes without a keystroke, and after 6 hours at most",
+ "--interactive --instance h.example.com --timeout 2m -- x": "-it takes no --timeout. a session ends after 30 minutes without a keystroke, and after 6 hours at most",
+ "-it --instance h.example.com --follow run_x": "-it takes no --follow. a session cannot be picked up again once its connection is gone",
+ "-it --instance h.example.com --follow run_x -- x": "-it takes no --follow. a session cannot be picked up again once its connection is gone",
+ "-it --instance h.example.com --idempotency-key k1 -- x": "-it takes no --idempotency-key. a session is never repeated by a retry",
+ "--interactive --instance h.example.com --idempotency-key k1": "-it takes no --idempotency-key. a session is never repeated by a retry",
+ } {
+ _, err := parseRunArgs(strings.Fields(args), io.Discard)
+ if err == nil || err.Error() != want {
+ t.Errorf("%s: %v, want %q", args, err, want)
+ }
+ }
+ for _, args := range []string{"-it --instance h.example.com", "-it --instance h.example.com --", "-it --instance h.example.com sh"} {
+ if _, err := parseRunArgs(strings.Fields(args), io.Discard); !errors.Is(err, errRunUsage) {
+ t.Errorf("%s: %v, want the usage", args, err)
+ }
+ }
+ // Without -it the same key still parses as it does today.
+ if o, err := parseRunArgs([]string{"--instance", "h.example.com", "--idempotency-key", "k1", "--", "x"}, io.Discard); err != nil || o.idempotencyKey != "k1" {
+ t.Fatalf("key without -it: %+v, %v", o, err)
+ }
+ if !strings.Contains(runUsageText(), "\n carlos run --app <app> --instance <host> -it -- <arg>...\n") {
+ t.Errorf("usage lacks RFS-6-C01:\n%s", runUsageText())
+ }
+ var help strings.Builder
+ parseRunArgs([]string{"-h"}, &help)
+ if strings.Count(help.String(), "run the command in a terminal session. what you type goes to it, and its screen comes back") != 2 {
+ t.Errorf("-h does not show RFS-6-C02 for -it and --interactive:\n%s", help.String())
+ }
+}