Documentation
¶
Overview ¶
Package launcher runs the commands a user registered for artifacts and owns their processes. It knows nothing about jobs, runs, or HTTP: callers supply a command, its working directory, and its environment.
Every launch runs under a wrapper process (RunWrapper) that puts the command in a process group of its own and stops that group when the command is stopped, when the command exits, or when the process that holds the Lifetime exits for any reason, including SIGKILL.
Index ¶
- Constants
- Variables
- func AllocatePort() (int, error)
- func OpenTrustedFile(path string) (*os.File, error)
- func RunWrapper(args []string) int
- func SaveConfig(path string, expected, contents []byte) error
- func Template() []byte
- func VerifyListener(port, pgid int) error
- func WriteTemplate(path string) error
- type Command
- type Launch
- type Lifetime
- type LogChunk
- type Manager
- func (manager *Manager) Close() error
- func (manager *Manager) Get(id string) (Launch, error)
- func (manager *Manager) List() []Launch
- func (manager *Manager) ReadLog(id string, offset int64, limit int) (LogChunk, error)
- func (manager *Manager) ServiceUpstream(id string) (Upstream, error)
- func (manager *Manager) Start(request StartRequest) (Launch, error)
- func (manager *Manager) Stop(id string) (Launch, error)
- type ManagerConfig
- type Mode
- type Process
- type Registry
- type Result
- type Spec
- type StartRequest
- type State
- type TargetKind
- type Upstream
Constants ¶
const ( DefaultMaxLive = 16 DefaultMaxEnded = 50 )
Manager limits.
const ( EnvArtifact = "ROTARI_LAUNCHER_ARTIFACT" EnvCWD = "ROTARI_LAUNCHER_CWD" EnvPort = "ROTARI_LAUNCHER_PORT" EnvBasePath = "ROTARI_LAUNCHER_BASE_PATH" // EnvToken is a secret made for each service launch. A service that // can require one should, with ProxyHeaders presenting it, so that // other local users who reach its loopback port cannot use it. EnvToken = "ROTARI_LAUNCHER_TOKEN" )
Environment variables a launched command receives.
const ( // CWDTarget is the target directory, or a target file's directory. CWDTarget = "target" // CWDParent is the directory containing the target. CWDParent = "parent" )
Working directory rules besides an absolute directory.
const ( DefaultReadyPath = "/" DefaultReadyTimeout = 60 * time.Second DefaultStopGrace = 5 * time.Second )
Defaults for optional settings.
const DefaultLogSegmentBytes = 8 << 20
DefaultLogSegmentBytes is the size of each of a launch's two log segments.
const FileName = "launchers.toml"
FileName is the launcher file. Only the global config directory is read; the caller supplies the path.
const LoopbackHost = "127.0.0.1"
LoopbackHost is the only address a launched service may listen on.
const Shell = "/bin/sh"
Shell runs every launched command as `Shell -c COMMAND`.
const WrapperCommand = "__launch"
WrapperCommand is the hidden rotari subcommand that runs RunWrapper.
Variables ¶
var ( // ErrClosed is returned by Start after Close. ErrClosed = errors.New("the launcher is shutting down") // ErrTooManyLaunches is returned when MaxLive launches are running. ErrTooManyLaunches = errors.New("too many launches are running; stop one first") // ErrUnknownLaunch is returned for an ID the manager does not know. ErrUnknownLaunch = errors.New("unknown launch") // ErrNotServing is returned by ServiceUpstream for a launch that is not // a ready service. ErrNotServing = errors.New("launch is not serving") )
var ErrConfigChanged = errors.New("launcher config changed since it was loaded")
ErrConfigChanged reports that the launcher file changed since the editor loaded it.
var ErrTemplateExists = errors.New("launcher file already exists")
ErrTemplateExists is returned by WriteTemplate when the file exists.
Functions ¶
func AllocatePort ¶
AllocatePort returns a TCP port on LoopbackHost that was free when this function returned. Another process can bind it before the service does; VerifyListener detects that.
func OpenTrustedFile ¶
OpenTrustedFile opens the file at the absolute path for reading after checking, in the manner of OpenSSH StrictModes, that no other OS user can write or replace it: the file and every directory from the root down to it must be owned by the current user or root and must not be writable by group or others. A directory writable by others is accepted only when it is sticky (like /tmp), because others cannot rename files they do not own there. Symlinks are followed one by one, so the directories holding each link are checked as well as the target's.
A missing file returns an error satisfying errors.Is(err, fs.ErrNotExist).
func RunWrapper ¶
RunWrapper is the hidden `rotari __launch [--grace D] -- COMMAND...`. It starts COMMAND in a new process group and reports on descriptor 4:
started PGID once COMMAND is running error MESSAGE instead, if COMMAND could not start exit CODE after COMMAND and its group have ended signal NUMBER instead, if a signal ended COMMAND
It stops the whole group (SIGTERM, then SIGKILL after the grace period) when it receives SIGTERM, SIGINT, or SIGHUP, or when descriptor 3 (the read end of a Lifetime) reports EOF. When COMMAND exits by itself, members it left in its group are stopped the same way. Processes that leave the group (setsid, setpgid) are not tracked.
func SaveConfig ¶
SaveConfig validates and atomically replaces an existing trusted launcher file only when its current contents still match expected.
func Template ¶
func Template() []byte
Template is the commented launcher file `rotari config --launchers` writes. It registers nothing by itself; its examples are comments.
func VerifyListener ¶
VerifyListener returns nil only if a process in process group pgid listens on exactly LoopbackHost:port and no process outside the group listens on an address that also accepts connections to it (0.0.0.0, ::, or ::ffff:127.0.0.1). Call it after a connection to the port succeeds and before trusting anything the port returns.
It fails when it cannot inspect listeners on this platform, so callers never skip the check by accident.
func WriteTemplate ¶
WriteTemplate creates the launcher file at path with Template's contents, private (0600, in a directory created 0700) so it passes OpenTrustedFile. It never replaces an existing file.
Types ¶
type Command ¶
type Command struct {
Name string
Command string
Targets []TargetKind
Mode Mode
// CWD is CWDTarget, CWDParent, or an absolute directory.
CWD string
// ReadyPath and ReadyTimeout apply to ModeService only.
ReadyPath string
ReadyTimeout time.Duration
StopGrace time.Duration
// Builtin marks a command rotari provides without a launcher file
// entry (BuiltinCommands).
Builtin bool
// Patterns, when set, limit the command to targets whose base name
// matches one of these filepath.Match patterns, such as "*.py".
Patterns []string
// ProxyHeaders are request headers the Web server's proxy adds when it
// forwards to the service, with $ROTARI_LAUNCHER_TOKEN replaced by the
// launch's token, so a service can require a secret that only the
// proxy presents. Service mode only.
ProxyHeaders map[string]string
}
Command is one registered command.
func BuiltinCommands ¶
func BuiltinCommands() []Command
BuiltinCommands are registered without a launcher file. An entry in the file with the same name replaces one, for example to run a tool from a particular environment. A built-in whose program is not installed is shown unavailable (Command.Unavailable).
func ParseCommands ¶
ParseCommands parses and validates launcher file contents. Every problem is an error; nothing is ignored or corrected.
func (Command) Accepts ¶
func (command Command) Accepts(kind TargetKind) bool
Accepts reports whether the command can run against a target of kind.
func (Command) Executable ¶
Executable is the program a command runs first: the first word of its first simple command, after any variable assignments. It is "" when that word is not a plain literal (it uses an expansion or quoting), is a shell builtin, or the command does not parse, since none of those can be checked by name. A relative or ~ path is returned as written.
func (Command) Matches ¶
Matches reports whether a target named name (its base name) fits the command's patterns; a command without patterns accepts every name.
func (Command) Unavailable ¶
Unavailable says why the command cannot run on this host, or "" when it can or cannot be checked. Only its first program is looked up, on the Web server's PATH, which launched commands inherit; a program it starts later, such as the tool `conda run` runs, is not checked.
func (Command) WorkingDirectory ¶
func (command Command) WorkingDirectory(target string, kind TargetKind) string
WorkingDirectory applies the command's cwd rule to an absolute target.
type Launch ¶
type Launch struct {
ID string `json:"id"`
Name string `json:"name"`
Command string `json:"command"`
Mode Mode `json:"mode"`
Target string `json:"target"`
Kind TargetKind `json:"kind"`
CWD string `json:"cwd"`
Labels map[string]string `json:"labels,omitempty"`
State State `json:"state"`
StartedAt time.Time `json:"started_at"`
EndedAt *time.Time `json:"ended_at,omitempty"`
ExitCode *int `json:"exit_code,omitempty"`
Signal string `json:"signal,omitempty"`
Error string `json:"error,omitempty"`
Reused bool `json:"reused,omitempty"`
// Port and BasePath are a service's upstream port and URL path.
Port int `json:"port,omitempty"`
BasePath string `json:"base_path,omitempty"`
// contains filtered or unexported fields
}
Launch is a snapshot of one launch.
type Lifetime ¶
type Lifetime struct {
// contains filtered or unexported fields
}
Lifetime is a pipe whose write end only its creator holds. Wrappers inherit the read end and stop their command when it reports EOF, which the kernel delivers when the creator exits, however it exits.
func NewLifetime ¶
NewLifetime creates the pipe. Both ends are close-on-exec, so only the wrappers started by Start receive the read end and nothing receives the write end.
type LogChunk ¶
type LogChunk struct {
// Offset is where Data starts in the command's whole output.
Offset int64 `json:"offset"`
Data []byte `json:"data"`
// Next is the offset to request for the following page.
Next int64 `json:"next"`
// Dropped is true when output before Offset that the caller asked for
// was discarded to bound the log's size.
Dropped bool `json:"dropped"`
// Total is how many bytes the command has written so far.
Total int64 `json:"total"`
}
LogChunk is a page of a launch's output.
type Manager ¶
type Manager struct {
// contains filtered or unexported fields
}
Manager owns every launch of one Web server.
func NewManager ¶
func NewManager(config ManagerConfig) (*Manager, error)
NewManager creates the manager's lifetime pipe and private runtime directory, removing runtime directories that managers which died without Close left behind.
func (*Manager) Close ¶
Close rejects new launches, stops every live one, and removes the runtime directory. The lifetime pipe is closed last, so a wrapper that Stop could not reach still stops its command.
func (*Manager) ServiceUpstream ¶
ServiceUpstream returns a ready service's upstream.
type ManagerConfig ¶
type ManagerConfig struct {
// Wrapper is the argv that runs RunWrapper.
Wrapper []string
// Env is the environment launches inherit, normally os.Environ().
Env []string
MaxLive int
MaxEnded int
LogSegmentBytes int64
// ServicePath returns the URL path a service launch is served under,
// which it receives as ROTARI_LAUNCHER_BASE_PATH. Without it, services
// cannot be launched.
ServicePath func(id string) string
}
ManagerConfig configures a Manager. Zero limits use the defaults.
type Process ¶
type Process struct {
// contains filtered or unexported fields
}
Process is a started command.
func Start ¶
Start starts spec's command under its wrapper and returns once the command is running in its own process group.
func (*Process) Done ¶
func (process *Process) Done() <-chan struct{}
Done is closed after the command and its process group have ended.
type Registry ¶
type Registry struct {
// Path is the file that was read, or would have been when Missing.
Path string
// Missing is true when the file does not exist; no command is
// registered then.
Missing bool
Commands []Command
}
Registry is the loaded launcher file.
func LoadRegistry ¶
LoadRegistry reads the launcher file at the absolute path after OpenTrustedFile's checks, and adds the built-in commands it does not replace. A missing file is not an error and registers only the built-ins; an untrusted, unreadable, or invalid one is an error.
type Result ¶
type Result struct {
// ExitCode is the command's exit status, or -1 when a signal ended it.
ExitCode int
// Signal is the signal that ended the command, or 0.
Signal syscall.Signal
}
Result is how a command ended.
type Spec ¶
type Spec struct {
// Wrapper is the argv that runs RunWrapper, for example the rotari
// executable followed by WrapperCommand.
Wrapper []string
// Command is shell source, run as `Shell -c Command`.
Command string
// Dir is the command's working directory.
Dir string
// Env is the complete environment of the wrapper and the command.
Env []string
// Output receives the command's standard output and standard error.
// Standard input is always empty.
Output io.Writer
// Grace is how long the command's process group has to exit after
// SIGTERM before it receives SIGKILL.
Grace time.Duration
}
Spec describes one command to start.
type StartRequest ¶
type StartRequest struct {
Command Command
// Target is the absolute path of the selected file or directory.
Target string
Kind TargetKind
// Labels describe where the target came from, for display only.
Labels map[string]string
// NewInstance starts another instance even if a matching one is live.
NewInstance bool
}
StartRequest asks for a registered command to run against a target.
type State ¶
type State string
State is a launch's lifecycle state.
const ( // StateStarting is a service that has not passed its readiness check. StateStarting State = "starting" // StateRunning is a running command, or a service that is ready. StateRunning State = "running" StateStopping State = "stopping" // StateExited means the command ended by itself; Result says how. StateExited State = "exited" // StateStopped means Stop ended the command. StateStopped State = "stopped" // StateFailed means the command could not start; Error says why. StateFailed State = "failed" )
type TargetKind ¶
type TargetKind string
TargetKind is the kind of artifact a command accepts.
const ( TargetFile TargetKind = "file" TargetDirectory TargetKind = "directory" )
type Upstream ¶
type Upstream struct {
Port int
// PGID owns Port; a proxy checks it per connection (VerifyListener).
PGID int
// Headers are added to every forwarded request (Command.ProxyHeaders,
// with the launch's token resolved).
Headers map[string]string
}
Upstream is where a proxy sends a ready service's requests.