Functions
func AllocatePort() (int, error)
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(path string) (*os.File, error)
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(args []string) int
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(path string, expected, contents []byte) error
SaveConfig validates and atomically replaces an existing trusted launcher
file only when its current contents still match expected.
func Template() []byte
Template is the commented launcher file `rotari config --launchers` writes.
It registers nothing by itself; its examples are comments.
func VerifyListener(port, pgid int) error
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(path string) error
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 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
// FilePatterns, when set, limit only files, for a command that also
// takes a directory of any name.
FilePatterns []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() []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(data []byte) ([]Command, error)
ParseCommands parses and validates launcher file contents. Every problem is
an error; nothing is ignored or corrected.
func (command Command) Accepts(kind TargetKind) bool
Accepts reports whether the command can run against a target of kind.
func (command Command) Executable() string
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 Command) Matches(kind TargetKind, name string) bool
Matches reports whether a target of kind named name (its base name) fits the
command's patterns; a command without patterns accepts every name.
func (command Command) PatternsFor(kind TargetKind) []string
PatternsFor are the patterns that limit a target of kind.
func (command Command) Unavailable() string
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 Command) WorkingDirectory(target string, kind TargetKind) string
WorkingDirectory applies the command's cwd rule to an absolute target.
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"`
// Has unexported fields.
}
Launch is a snapshot of one launch.
type Lifetime struct {
// Has 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() (*Lifetime, error)
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.
func (lifetime *Lifetime) Close() error
Close closes both ends. Every wrapper still running then stops its command.
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 struct {
// Has unexported fields.
}
Manager owns every launch of one Web server.
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 *Manager) Close() error
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 *Manager) Get(id string) (Launch, error)
Get returns one launch.
func (manager *Manager) List() []Launch
List returns every known launch, oldest first.
func (manager *Manager) ReadLog(id string, offset int64, limit int) (LogChunk, error)
ReadLog returns a page of a launch's output; see rotatingLog.Read.
func (manager *Manager) ServiceUpstream(id string) (Upstream, error)
ServiceUpstream returns a ready service's upstream.
func (manager *Manager) Start(request StartRequest) (Launch, error)
Start runs request's command, or returns the matching live launch with
Reused set. A command that cannot start is recorded as StateFailed and
returned together with the error.
func (manager *Manager) Stop(id string) (Launch, error)
Stop stops a live launch and waits for it to end. Stopping an ended launch
returns it unchanged.
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 Mode string
Mode says whether a command is expected to exit or to serve HTTP.
const (
ModeCommand Mode = "command"
ModeService Mode = "service"
)
type Process struct {
// Has unexported fields.
}
Process is a started command.
func Start(lifetime *Lifetime, spec Spec) (*Process, error)
Start starts spec's command under its wrapper and returns once the command
is running in its own process group.
func (process *Process) Done() <-chan struct{}
Done is closed after the command and its process group have ended.
func (process *Process) PGID() int
PGID is the command's process group. The group's leader is the shell.
func (process *Process) Stop() (Result, error)
Stop asks the wrapper to stop the command's process group (SIGTERM,
then SIGKILL after the grace period) and waits for it. If the wrapper does
not finish in time, Stop kills the group and the wrapper itself.
func (process *Process) Wait() (Result, error)
Wait waits for the command and its process group to end.
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(path string) (Registry, error)
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.
func (registry Registry) Lookup(name string) (Command, bool)
Lookup finds a registered command by name.
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 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 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 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 string
TargetKind is the kind of artifact a command accepts.
const (
TargetFile TargetKind = "file"
TargetDirectory TargetKind = "directory"
)
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.