Documentation
¶
Overview ¶
Package deploy provides the SSH + SFTP primitives used by the agent deploy service to install and start the QuicBaaS fleet node daemon on a remote host.
The package is intentionally narrow: it knows how to open an SSH session, upload a binary via SFTP, render a systemd unit or a nohup-backed start script, and invoke short remote commands. It contains no orchestration logic, no polling, and no SDK coupling. All orchestration lives in pkg/service/fleet_deploy_service.go.
Index ¶
- Constants
- func DetectSystemdUser(ctx context.Context, target Target) bool
- func DialFleetRuntime(ctx context.Context, addr string) error
- func EnsureLinger(ctx context.Context, target Target, user string) error
- func FixFor(err error) string
- func Hostname(target string) string
- func InstallAndStart(ctx context.Context, target Target, unitContent, unitName string) error
- func IsSSHAuthFailure(err error) bool
- func LoadSpecFile(path string, into *Spec) error
- func ReadNodeCertificate(ctx context.Context, c Target, l Layout) (*x509.Certificate, error)
- func RenderNodeConfig(s *Spec, l Layout) ([]byte, error)
- func RenderStartScript(spec *Spec) string
- func RenderUnit(spec *Spec) string
- func StartBackground(ctx context.Context, target Target, scriptContent, scriptPath string) error
- func UploadBinary(ctx context.Context, target Target, localPath, remotePath string) error
- type AgentConfigInvalidError
- type AgentIdentityMissingError
- type CapacityUndeclaredError
- type ContainerRuntimeFailure
- type ContainerRuntimeUnavailableError
- type ControlPlaneUnreachableError
- type DeployOwnedFieldError
- type Fixer
- type FleetNodeUnreachableError
- type HostKeyPolicy
- type InsufficientDiskError
- type InvalidSpecError
- type Layout
- type LifecycleResult
- type LingerNotEnabledError
- type LocalExecError
- type LocalSSHConflictError
- type LocalTarget
- func (t *LocalTarget) DialTCP(ctx context.Context, addr string) (net.Conn, error)
- func (t *LocalTarget) Exec(ctx context.Context, cmd string) (string, string, error)
- func (t *LocalTarget) Host() string
- func (t *LocalTarget) Upload(ctx context.Context, localPath, path string) error
- func (t *LocalTarget) User() string
- func (t *LocalTarget) WriteFile(ctx context.Context, path string, data []byte, mode os.FileMode) error
- type LocalTargetError
- type LocalWriteError
- type NotDeployedError
- type PreflightCheck
- type PreflightFailedError
- type PreflightInput
- type PreflightReport
- type PurgeRefusedError
- type RemoteExecError
- type Result
- type SFTPUploadError
- type SSHClient
- func DialSSH(ctx context.Context, spec *Spec) (*SSHClient, error)
- func DialSSHWithAuth(ctx context.Context, spec *Spec, authMethods []ssh.AuthMethod) (*SSHClient, error)
- func DialSSHWithAuthAndHostKey(ctx context.Context, spec *Spec, authMethods []ssh.AuthMethod, ...) (*SSHClient, error)
- func DialSSHWithHostKey(ctx context.Context, spec *Spec, hostKey *HostKeyPolicy) (*SSHClient, error)
- func (c *SSHClient) Close() error
- func (c *SSHClient) DialTCP(ctx context.Context, addr string) (net.Conn, error)
- func (c *SSHClient) Exec(ctx context.Context, cmd string) (string, string, error)
- func (c *SSHClient) Host() string
- func (c *SSHClient) UnderlyingClient() *ssh.Client
- func (c *SSHClient) Upload(ctx context.Context, localPath, remotePath string) error
- func (c *SSHClient) User() string
- func (c *SSHClient) WriteFile(ctx context.Context, remotePath string, data []byte, mode os.FileMode) error
- type SSHDialError
- type SSHKeyNotAuthorizedError
- type Spec
- func (s *Spec) DaemonConfig(l Layout) *fleet.Config
- func (s *Spec) DefaultNodeBind() error
- func (s *Spec) Layout(home string) Layout
- func (s *Spec) LocalSSHConflict() error
- func (s *Spec) ResolvedDataDir() string
- func (s *Spec) ResolvedInstallDir() string
- func (s *Spec) SystemdExplicit() bool
- func (s *Spec) UseSystemd() bool
- func (s *Spec) ValidateDaemonConfig() error
- type SpecFileError
- type StartTimeoutError
- type Supervisor
- type SystemdInstallError
- type SystemdUserUnavailableError
- type Target
- type UninstallResult
- type WorkerImageUIDMismatchError
- type WorkerImageUnavailableError
Constants ¶
const ( MinFreeImageBytes uint64 = 20 << 30 MinFreeWorkspaceBytes uint64 = 10 << 30 )
Minimum free space preflight requires. Worker images are several GiB each and are layered on the runtime's data root; workspaces hold full checkouts plus build caches for every job the node runs concurrently.
const ( CheckSSH = "ssh connection" CheckHostKey = "pinned host key" CheckDeployKey = "deploy key authorized" CheckRemoteUser = "remote user" CheckSystemd = "systemd --user" CheckLinger = "linger" CheckContainerRuntime = "container runtime" CheckImageDisk = "disk for worker images" CheckWorkspaceDisk = "disk for workspaces" CheckWorkerImage = "worker image" CheckControlPlane = "control plane reachable from node" )
Check names, in the order a report lists them.
const ( // NodeCertFilename is the basename of the daemon's mTLS client // certificate inside DataDir. NodeCertFilename = "agent.crt" // NodeKeyFilename is the basename of the daemon's mTLS client // private key inside DataDir. Installed with 0600 permissions. NodeKeyFilename = "agent.key" // ServerCAFilename is the basename of the PEM-encoded CA bundle the // daemon trusts when dialing the QuicBaaS server. ServerCAFilename = "server-ca.crt" )
Agent identity material filenames. The deploy flow uploads the mTLS client certificate, private key, and server CA bundle into DataDir on the remote host; the rendered systemd unit / nohup script references these paths on the daemon command line.
const DefaultNodePort = "9091"
DefaultNodePort is the port a fleet node's runtime binds when the spec names no bind address.
const DefaultUnitName = "quicbaas-agent.service"
DefaultUnitName is the systemd unit file installed by the deploy primitives. It lives under ~/.config/systemd/user/ on the remote host so a system-level install is never required.
const NodeConfigFilename = "agent.yaml"
NodeConfigFilename is the basename of the daemon config file deploy renders next to the binary. The installed unit runs `quicbaas fleet serve --config <install-dir>/agent.yaml`.
const StartScriptFilename = "start-quicbaas-agent.sh"
StartScriptFilename is the basename of the nohup fallback launcher.
Variables ¶
This section is empty.
Functions ¶
func DetectSystemdUser ¶
DetectSystemdUser returns true when the remote host has a working user-scoped systemd. It does the minimal probe — asking systemctl for its version — so the detect step takes milliseconds.
func DialFleetRuntime ¶
DialFleetRuntime opens and immediately closes a TCP connection to the deployed agent's runtime listener.
This is the only check that distinguishes an agent that is running from an agent the fleet registry merely remembers: a registration keeps its last-seen status after the process is gone, so a deploy that trusts the registry alone can report a healthy agent that no longer holds its port. The probe is therefore made from the operator's side after the deploy's SSH session is closed, which is the moment a systemd --user agent without lingering dies.
func EnsureLinger ¶
EnsureLinger guarantees the remote user's systemd manager survives the deploy's SSH session. It reads the Linger property with loginctl and, when lingering is off, enables it over sudo -n.
Enabling lingering needs root. When sudo is unavailable or would prompt, the call fails with a *LingerNotEnabledError naming the exact command the operator must run — a deploy that cannot make the agent outlive its own session must fail rather than report a healthy unit.
An unreadable Linger property is treated as "off": loginctl declining to answer is not evidence that the manager lingers, and running enable-linger a second time is harmless.
func FixFor ¶
FixFor returns the fix carried by the outermost Fixer in err's chain, or "". An error that merely wraps a more specific one (an *SSHDialError around a host-key mismatch) defers to the fix of what it wraps; see SSHDialError.Fix.
func Hostname ¶
Hostname returns the host part of target, which may be "host", "host:port", "user@host[:port]" or an IPv6 literal with or without brackets and port.
func InstallAndStart ¶
InstallAndStart writes the rendered unit content to the remote host under ~/.config/systemd/user/<unitName>, then reloads the user daemon, enables the unit so it starts at next login, ensures the remote user's manager lingers, and starts the unit immediately.
The linger step is not optional housekeeping: without it the user manager, and the agent with it, dies when this SSH session closes. A host where it cannot be enabled fails the install with a *LingerNotEnabledError instead of reporting a started agent.
The caller must have verified that systemctl --user is available on the remote (see DetectSystemdUser).
func IsSSHAuthFailure ¶
IsSSHAuthFailure reports whether a dial failed because the server refused every credential offered, as opposed to being unreachable or presenting an unexpected host key.
func LoadSpecFile ¶
LoadSpecFile decodes the YAML node spec at path onto into. Keys the file does not name keep into's values, so a caller seeds into with its defaults (DefaultSpec, plus any flag defaults) and the file overrides what it states.
Unknown keys are refused, so a misspelt setting fails the deploy instead of being dropped. A node spec is a committed file, so it may not carry an SSH password: that belongs on the command line or, better, in the SSH key store.
func ReadNodeCertificate ¶
ReadNodeCertificate reads the mTLS certificate the deploy installed. The fleet registry keys an agent by an ID derived from this certificate's Common Name, so this is how stop and undeploy find the registration to remove without trusting the caller to name it.
func RenderNodeConfig ¶
RenderNodeConfig renders the daemon config file for the spec under the given layout. The config is validated first, so a file the daemon would refuse is never written.
func RenderStartScript ¶
RenderStartScript renders the nohup fallback start script used when systemd is unavailable. The script is idempotent: rerunning it will terminate the previous daemon (if any) and relaunch it detached from the SSH session.
The script lives at $HOME/<install-dir>/start-quicbaas-agent.sh on the remote and logs to $HOME/<data-dir>/agent.log so operators can tail it post-deploy.
func RenderUnit ¶
RenderUnit produces the systemd --user unit content for the given spec. The unit is intentionally minimal: a single ExecStart line and a bounded Restart=on-failure policy. Keeping the body small makes it easy for operators to audit after the deploy finishes.
The restart policy is deliberately not a flat retry. The daemon itself waits out a control plane that is merely unreachable (see the enrollment classifier in pkg/fleet), so a process that still exits is reporting something restarting cannot fix. Escalating the delay and capping the start rate turns that into a unit that lands in "failed", where monitoring can see it, instead of one that sits in "activating (auto-restart)" forever and reads as almost healthy.
func StartBackground ¶
StartBackground uploads the rendered script to scriptPath, marks it executable, and runs it. scriptPath should be an absolute path (or use $HOME expansion) that the caller already reserved on the remote.
Types ¶
type AgentConfigInvalidError ¶
type AgentConfigInvalidError struct {
Cause error
}
AgentConfigInvalidError reports a daemon config the deploy would render but the daemon would refuse at start-up. Cause is fleet.Config.Validate's error.
func (*AgentConfigInvalidError) Error ¶
func (e *AgentConfigInvalidError) Error() string
Error implements the error interface.
func (*AgentConfigInvalidError) Unwrap ¶
func (e *AgentConfigInvalidError) Unwrap() error
Unwrap exposes the underlying cause for errors.Is / errors.As.
type AgentIdentityMissingError ¶
AgentIdentityMissingError reports that the agent certificate the deploy installed could not be read from the node.
func (*AgentIdentityMissingError) Error ¶
func (e *AgentIdentityMissingError) Error() string
Error implements the error interface.
func (*AgentIdentityMissingError) Unwrap ¶
func (e *AgentIdentityMissingError) Unwrap() error
Unwrap exposes the underlying cause for errors.Is / errors.As.
type CapacityUndeclaredError ¶
CapacityUndeclaredError reports a spec that does not declare how many jobs the node can run at once. A daemon that reports no capacity leaves the fleet's capacity undeclared, so admission cannot bound the fleet at all.
func (*CapacityUndeclaredError) Error ¶
func (e *CapacityUndeclaredError) Error() string
Error implements the error interface.
type ContainerRuntimeFailure ¶
type ContainerRuntimeFailure string
ContainerRuntimeFailure classifies why a container runtime is unusable.
const ( // RuntimeNotInstalled: no runtime binary on the user's PATH. RuntimeNotInstalled ContainerRuntimeFailure = "not installed" // RuntimeNotInGroup: docker is installed but the user is not in the // docker group, so the daemon socket refuses it. RuntimeNotInGroup ContainerRuntimeFailure = "user not in the docker group" // RuntimeNotResponding: the binary is there and permitted, but the // runtime does not answer. RuntimeNotResponding ContainerRuntimeFailure = "not responding" )
type ContainerRuntimeUnavailableError ¶
type ContainerRuntimeUnavailableError struct {
}
ContainerRuntimeUnavailableError reports that the node's container runtime cannot be used by the deploy user. Reason says which part is missing so Fix can name the one command that resolves it.
func (*ContainerRuntimeUnavailableError) Error ¶
func (e *ContainerRuntimeUnavailableError) Error() string
Error implements the error interface.
func (*ContainerRuntimeUnavailableError) Fix ¶
func (e *ContainerRuntimeUnavailableError) Fix() string
Fix implements Fixer.
func (*ContainerRuntimeUnavailableError) Unwrap ¶
func (e *ContainerRuntimeUnavailableError) Unwrap() error
Unwrap exposes the underlying cause for errors.Is / errors.As.
type ControlPlaneUnreachableError ¶
ControlPlaneUnreachableError reports that the node cannot open a verified TLS connection to the control plane. Stage is "dial" (no route, refused, no name) or "tls" (the server's certificate does not verify against the CA the deploy installs).
func (*ControlPlaneUnreachableError) Error ¶
func (e *ControlPlaneUnreachableError) Error() string
Error implements the error interface.
func (*ControlPlaneUnreachableError) Fix ¶
func (e *ControlPlaneUnreachableError) Fix() string
Fix implements Fixer.
func (*ControlPlaneUnreachableError) Unwrap ¶
func (e *ControlPlaneUnreachableError) Unwrap() error
Unwrap exposes the underlying cause for errors.Is / errors.As.
type DeployOwnedFieldError ¶
DeployOwnedFieldError reports an agent-section key the deploy sets itself. Owner is the spec field that declares the setting instead.
func (*DeployOwnedFieldError) Error ¶
func (e *DeployOwnedFieldError) Error() string
Error implements the error interface.
type Fixer ¶
type Fixer interface {
Fix() string
}
Fixer is implemented by errors that know the command or edit that resolves them.
type FleetNodeUnreachableError ¶
FleetNodeUnreachableError indicates the deployed agent's runtime port did not accept a connection. Addr is the host:port that was dialed.
func (*FleetNodeUnreachableError) Error ¶
func (e *FleetNodeUnreachableError) Error() string
Error implements the error interface.
func (*FleetNodeUnreachableError) Unwrap ¶
func (e *FleetNodeUnreachableError) Unwrap() error
Unwrap exposes the underlying cause for errors.Is / errors.As.
type HostKeyPolicy ¶
type HostKeyPolicy struct {
// Callback verifies the presented host key. Required.
Callback ssh.HostKeyCallback
// Algorithms lists the host-key signature algorithms to negotiate, in
// preference order. Empty keeps the library's default negotiation.
Algorithms []string
}
HostKeyPolicy is how a dial verifies the target's host key: the callback that checks the key the host presents, and the host-key algorithms to negotiate so the host presents a key the callback can accept.
Algorithms matters because golang.org/x/crypto/ssh negotiates ECDSA host keys before ed25519: a host pinned by its ed25519 key presents its ECDSA key unless the client asks for ed25519, and the callback then rejects a perfectly legitimate host.
type InsufficientDiskError ¶
type InsufficientDiskError struct {
Path string
Purpose string
FreeBytes uint64
RequiredBytes uint64
}
InsufficientDiskError reports a filesystem with less free space than the node needs for Purpose ("worker images" or "workspaces").
func (*InsufficientDiskError) Error ¶
func (e *InsufficientDiskError) Error() string
Error implements the error interface.
func (*InsufficientDiskError) Fix ¶
func (e *InsufficientDiskError) Fix() string
Fix implements Fixer.
type InvalidSpecError ¶
InvalidSpecError indicates the caller supplied a Spec that cannot be turned into a valid remote invocation. The Field reports the first problematic field name.
func (*InvalidSpecError) Error ¶
func (e *InvalidSpecError) Error() string
Error implements the error interface.
type Layout ¶
type Layout struct {
Home string
InstallDir string
Binary string
ConfigFile string
StartScript string
DataDir string
WorkDir string
ProjectsRoot string
CertFile string
KeyFile string
ServerCAFile string
LogFile string
PIDFile string
UnitFile string
}
Layout is every remote path one deployment owns, resolved against the remote user's home directory. The install, the lifecycle commands and preflight all read paths from here, so none of them derive a path the others would not.
type LifecycleResult ¶
type LifecycleResult struct {
// Host is the SSH destination the command ran against.
Host string `json:"host" yaml:"host"`
// Action is "stop", "start" or "undeploy".
Action string `json:"action" yaml:"action"`
// Supervisor is how the agent was installed: "systemd", "nohup", or
// empty when nothing was installed.
Supervisor Supervisor `json:"supervisor,omitempty" yaml:"supervisor,omitempty"`
// AgentID is the fleet registry ID of the node's agent, derived from the
// certificate the deploy installed. Empty when it could not be read.
NodeID string `json:"node_id,omitempty" yaml:"node_id,omitempty"`
// Deregistered reports that the agent is no longer in the fleet
// registry after the command: it was removed, or was not there.
Deregistered bool `json:"deregistered" yaml:"deregistered"`
// Removed lists the remote paths undeploy removed.
Removed []string `json:"removed,omitempty" yaml:"removed,omitempty"`
// OnlineAt is when a started agent was observed online. Empty when
// start did not wait.
OnlineAt string `json:"online_at,omitempty" yaml:"online_at,omitempty"`
// Note explains anything the command could not do that did not fail
// it, such as a registration it had no ID to remove.
Note string `json:"note,omitempty" yaml:"note,omitempty"`
}
LifecycleResult describes the outcome of `fleet stop`, `fleet start` or `fleet undeploy` on one node.
type LingerNotEnabledError ¶
LingerNotEnabledError indicates the remote user's systemd --user manager will not outlive the deploy's SSH session, and the deploy could not enable lingering itself. Command carries the exact privileged command the operator must run before re-deploying.
func (*LingerNotEnabledError) Error ¶
func (e *LingerNotEnabledError) Error() string
Error implements the error interface.
func (*LingerNotEnabledError) Fix ¶
func (e *LingerNotEnabledError) Fix() string
Fix implements Fixer for the linger check.
func (*LingerNotEnabledError) Unwrap ¶
func (e *LingerNotEnabledError) Unwrap() error
Unwrap exposes the underlying cause for errors.Is / errors.As.
type LocalExecError ¶
LocalExecError reports a command on the local install target that returned a non-zero exit status or failed to launch.
func (*LocalExecError) Error ¶
func (e *LocalExecError) Error() string
Error implements the error interface.
func (*LocalExecError) Unwrap ¶
func (e *LocalExecError) Unwrap() error
Unwrap exposes the underlying cause for errors.Is / errors.As.
type LocalSSHConflictError ¶
type LocalSSHConflictError struct {
// Field is the ssh setting given alongside --local.
Field string
}
LocalSSHConflictError reports a local install that also names an ssh target: --local installs on this host, so --ssh (or a spec's host or ssh credentials) contradicts it.
func (*LocalSSHConflictError) Error ¶
func (e *LocalSSHConflictError) Error() string
Error implements the error interface.
type LocalTarget ¶
type LocalTarget struct {
// contains filtered or unexported fields
}
LocalTarget is the install Target for the host this process runs on: a fleet node co-located with quicbaasd installs through it with no sshd. Commands run under /bin/sh through os/exec, and files are staged beside their destination and renamed into place, as the sftp upload does.
func NewLocalTarget ¶
func NewLocalTarget(host string) (*LocalTarget, error)
NewLocalTarget returns the local install target for the current user. host is the name this host is advertised under; it appears in errors and reports.
func (*LocalTarget) Host ¶
func (t *LocalTarget) Host() string
Host returns the name this host is advertised under.
func (*LocalTarget) Upload ¶
func (t *LocalTarget) Upload(ctx context.Context, localPath, path string) error
Upload copies the local file at localPath to path, executable. Like the sftp upload, the copy is staged and renamed into place: a redeploy replaces the binary of an agent that is running, which keeps its inode.
func (*LocalTarget) User ¶
func (t *LocalTarget) User() string
User returns the user the install runs as.
type LocalTargetError ¶
type LocalTargetError struct {
Cause error
}
LocalTargetError reports that the local install target could not resolve the user or home directory it installs for.
func (*LocalTargetError) Error ¶
func (e *LocalTargetError) Error() string
Error implements the error interface.
func (*LocalTargetError) Unwrap ¶
func (e *LocalTargetError) Unwrap() error
Unwrap exposes the underlying cause for errors.Is / errors.As.
type LocalWriteError ¶
LocalWriteError reports a file the local install target could not write. Source names the local file an upload copied from, if any.
func (*LocalWriteError) Error ¶
func (e *LocalWriteError) Error() string
Error implements the error interface.
func (*LocalWriteError) Unwrap ¶
func (e *LocalWriteError) Unwrap() error
Unwrap exposes the underlying cause for errors.Is / errors.As.
type NotDeployedError ¶
NotDeployedError reports a node with no agent installed where a lifecycle command expected one: neither the systemd unit nor the start script exists.
func (*NotDeployedError) Error ¶
func (e *NotDeployedError) Error() string
Error implements the error interface.
type PreflightCheck ¶
type PreflightCheck struct {
Name string `json:"name" yaml:"name"`
Passed bool `json:"passed" yaml:"passed"`
Detail string `json:"detail,omitempty" yaml:"detail,omitempty"`
Error string `json:"error,omitempty" yaml:"error,omitempty"`
Fix string `json:"fix,omitempty" yaml:"fix,omitempty"`
// contains filtered or unexported fields
}
PreflightCheck is one check's outcome. A failed check carries its typed error and the fix that error names.
func FailedCheck ¶
func FailedCheck(name string, err error) PreflightCheck
FailedCheck builds a failing check from its typed error.
func PassedCheck ¶
func PassedCheck(name, detail string) PreflightCheck
PassedCheck builds a passing check.
func RunPreflight ¶
func RunPreflight(ctx context.Context, c Target, in PreflightInput) []PreflightCheck
RunPreflight runs every session-level check against the node and returns their outcomes in report order. Nothing on the node is changed.
func (PreflightCheck) Err ¶
func (c PreflightCheck) Err() error
Err returns the check's typed error, nil when it passed.
type PreflightFailedError ¶
PreflightFailedError is the result of a preflight with at least one failed check. Failures holds each check's typed error; errors.As reaches any of them.
func (*PreflightFailedError) Error ¶
func (e *PreflightFailedError) Error() string
Error implements the error interface. Each failure is listed with its fix.
func (*PreflightFailedError) Unwrap ¶
func (e *PreflightFailedError) Unwrap() []error
Unwrap exposes every failure for errors.Is / errors.As.
type PreflightInput ¶
type PreflightInput struct {
// Spec is the node spec being checked.
Spec *Spec
// Layout is the spec's layout resolved against the remote home.
Layout Layout
// ServerCAPEM is the CA bundle the deploy installs as server-ca.crt —
// the one the daemon will verify the control plane against. The
// control-plane check verifies with exactly this bundle and never skips
// verification.
ServerCAPEM []byte
}
PreflightInput is what the session checks need beyond the connection.
type PreflightReport ¶
type PreflightReport struct {
Host string `json:"host" yaml:"host"`
Checks []PreflightCheck `json:"checks" yaml:"checks"`
}
PreflightReport is the full preflight outcome for one node.
func (*PreflightReport) Add ¶
func (r *PreflightReport) Add(checks ...PreflightCheck)
Add appends checks to the report.
func (*PreflightReport) Err ¶
func (r *PreflightReport) Err() error
Err returns a *PreflightFailedError listing every failed check, or nil.
func (*PreflightReport) Passed ¶
func (r *PreflightReport) Passed() bool
Passed reports whether every check passed.
type PurgeRefusedError ¶
type PurgeRefusedError struct {
Path string
}
PurgeRefusedError reports a --purge-workspaces target undeploy will not delete: the filesystem root, the user's home, or an ancestor of it.
func (*PurgeRefusedError) Error ¶
func (e *PurgeRefusedError) Error() string
Error implements the error interface.
type RemoteExecError ¶
RemoteExecError indicates a remote command returned a non-zero exit status or failed to launch.
func (*RemoteExecError) Error ¶
func (e *RemoteExecError) Error() string
Error implements the error interface.
func (*RemoteExecError) Unwrap ¶
func (e *RemoteExecError) Unwrap() error
Unwrap exposes the underlying cause for errors.Is / errors.As.
type Result ¶
type Result struct {
// Host is the SSH destination that was deployed to.
Host string `json:"host" yaml:"host"`
// InstalledPath is the absolute path of the uploaded binary on
// the remote host.
InstalledPath string `json:"installed_path" yaml:"installed_path"`
// ConfigPath is the absolute path of the rendered daemon config file
// the installed unit runs with.
ConfigPath string `json:"config_path,omitempty" yaml:"config_path,omitempty"`
// ServiceStatus is a short description of how the daemon was
// started: "systemd", "nohup", or "unknown".
ServiceStatus string `json:"service_status" yaml:"service_status"`
// AgentID is the identifier the control plane assigned to
// the agent once it enrolled. Empty when WaitOnline==0.
NodeID string `json:"node_id,omitempty" yaml:"node_id,omitempty"`
// OnlineAt is the RFC3339 timestamp when the agent was first
// observed online by the control plane. Empty when
// WaitOnline==0.
OnlineAt string `json:"online_at,omitempty" yaml:"online_at,omitempty"`
// NodeCertPath is the absolute path on the remote host where the
// daemon's mTLS client certificate was installed. Empty when the
// deploy flow did not issue a certificate.
NodeCertPath string `json:"node_cert_path,omitempty" yaml:"node_cert_path,omitempty"`
// NodeCertSerial is the serial number of the issued agent
// certificate, hex-encoded. Surfaced so operators can correlate
// deploys against the CA's certificate store.
NodeCertSerial string `json:"node_cert_serial,omitempty" yaml:"node_cert_serial,omitempty"`
// Preflight is the report of the checks that ran before the install.
// Nil when the deploy ran with SkipPreflight.
Preflight *PreflightReport `json:"preflight,omitempty" yaml:"preflight,omitempty"`
}
Result describes the outcome of a successful deployment.
type SFTPUploadError ¶
SFTPUploadError indicates the SFTP transfer failed. It carries both the local and remote paths so the caller can build accurate diagnostic messages.
func (*SFTPUploadError) Error ¶
func (e *SFTPUploadError) Error() string
Error implements the error interface.
func (*SFTPUploadError) Unwrap ¶
func (e *SFTPUploadError) Unwrap() error
Unwrap exposes the underlying cause for errors.Is / errors.As.
type SSHClient ¶
type SSHClient struct {
// contains filtered or unexported fields
}
SSHClient owns a live SSH connection and exposes the small set of operations the deploy primitives need: exec, and access to the underlying *ssh.Client so sftp.go can negotiate an SFTP subsystem.
An SSHClient must be Closed exactly once; double-close is a no-op.
func DialSSH ¶
DialSSH opens an SSH connection using the credentials in the Spec. Password auth is the only spec-embedded credential supported; stored keys flow through DialSSHWithAuth / DialSSHWithAuthAndHostKey with a signer resolved by the caller.
Host-key verification requires InsecureHostKey=true (explicit operator opt-out) or one of the entry points that accepts a caller-supplied HostKeyPolicy — DialSSHWithHostKey for these same credentials, DialSSHWithAuthAndHostKey for injected auth. No policy + InsecureHostKey=false yields an InvalidSpecError at dial time so a misconfigured deploy fails loudly.
func DialSSHWithAuth ¶
func DialSSHWithAuth(ctx context.Context, spec *Spec, authMethods []ssh.AuthMethod) (*SSHClient, error)
DialSSHWithAuth opens an SSH connection using a caller-supplied set of authentication methods. It mirrors DialSSH but lets higher layers inject auth that the spec alone cannot express — notably an ssh.Signer backed by a KMS-resident private key. Host key policy, port parsing, timeouts, and context handling are identical to DialSSH so callers get the same error types.
authMethods must be non-empty; an empty slice is treated as an invalid spec and returns a typed error immediately.
func DialSSHWithAuthAndHostKey ¶
func DialSSHWithAuthAndHostKey(ctx context.Context, spec *Spec, authMethods []ssh.AuthMethod, hostKey *HostKeyPolicy) (*SSHClient, error)
DialSSHWithAuthAndHostKey opens an SSH connection using both a caller-supplied set of authentication methods and an explicit HostKeyPolicy. It is the preferred entry point for the service layer, which injects an xkms-backed known-hosts policy so host-key pins live in the shared SSH store rather than in deploy.Spec. When hostKey is nil the call falls back to buildHostKeyCallback(spec) — mirroring DialSSHWithAuth — so callers that only need InsecureHostKey can still use this entry point.
func DialSSHWithHostKey ¶
func DialSSHWithHostKey(ctx context.Context, spec *Spec, hostKey *HostKeyPolicy) (*SSHClient, error)
DialSSHWithHostKey opens an SSH connection using the spec's own credentials plus an explicit HostKeyPolicy. It is the password-auth counterpart of DialSSHWithAuthAndHostKey: the service layer resolves the target's pinned host key from the SSH known-hosts store and injects the resulting policy here, so a password deploy verifies its host exactly as a stored-key deploy does.
A nil policy falls back to the spec's own policy (InsecureHostKey), which refuses to dial unless the operator opted out explicitly.
func (*SSHClient) Close ¶
Close tears down the SSH connection. Calling Close on a nil or already-closed SSHClient is safe.
func (*SSHClient) DialTCP ¶
DialTCP opens a TCP connection FROM THE REMOTE HOST to addr, tunnelled through this SSH connection (an RFC 4254 direct-tcpip channel). Name resolution and routing happen on the remote host, so a successful dial proves the remote host can reach addr — which is what preflight needs to know about the control plane, and not something a dial from the operator's machine could show.
func (*SSHClient) Exec ¶
Exec runs cmd on the remote host and returns the captured stdout and stderr. A non-zero exit is surfaced as a RemoteExecError.
On cancellation the returned output is whatever had been captured by then, which may be partial — see syncBuffer for why that is read under a lock rather than after waiting for the command to finish.
func (*SSHClient) UnderlyingClient ¶
UnderlyingClient exposes the *ssh.Client so adjacent primitives (sftp.go) can wrap it. Callers must not Close the returned client; the SSHClient owns its lifecycle.
func (*SSHClient) Upload ¶
Upload streams localPath to remotePath and marks the resulting file executable (0o755). The transfer is performed over the SFTP subsystem negotiated on top of the SSH connection.
Directories up to and including filepath.Dir(remotePath) are created on demand. Any partial transfer that fails midway leaves a best-effort cleanup: the partial file is removed before the error is returned so retries do not see a truncated binary.
THE BINARY IS STAGED AND RENAMED, NEVER WRITTEN IN PLACE. A redeploy replaces the binary of an agent that is running, and the remote refuses to open a running executable for writing (SFTP answers a bare "Failure"), so an in-place upload fails on every host that already has an agent running (measured redeploying the fleet, 2026-09-23). The upload lands at remotePath+uploadSuffix and a POSIX rename swaps it in atomically: the running process keeps its old inode, and a restart runs the new one.
func (*SSHClient) User ¶
User returns the login user the connection authenticated as. The linger check needs it: `systemctl --user` and `loginctl enable-linger` both act on this account, so reading it from the live connection keeps the check honest even if a caller's spec says something else.
func (*SSHClient) WriteFile ¶
func (c *SSHClient) WriteFile(ctx context.Context, remotePath string, data []byte, mode os.FileMode) error
WriteFile writes data to the remote path using cat > path; for small text payloads (units, scripts) this is simpler than opening a second SFTP session. The file mode is encoded with an explicit chmod after the write.
type SSHDialError ¶
SSHDialError indicates the SSH handshake to the remote host failed. The Cause preserves the underlying crypto/ssh or net error so the caller can still see network diagnostics.
func (*SSHDialError) Error ¶
func (e *SSHDialError) Error() string
Error implements the error interface.
func (*SSHDialError) Fix ¶
func (e *SSHDialError) Fix() string
Fix implements Fixer. A dial that failed for a reason with a fix of its own — a host-key mismatch the resolver reported — defers to that fix; otherwise the fix is to make the host reachable.
func (*SSHDialError) Unwrap ¶
func (e *SSHDialError) Unwrap() error
Unwrap exposes the underlying cause for errors.Is / errors.As.
type SSHKeyNotAuthorizedError ¶
SSHKeyNotAuthorizedError reports a deploy key the remote user does not accept. AuthorizedKey is the key's authorized_keys line, so the fix can be pasted as-is.
func (*SSHKeyNotAuthorizedError) Error ¶
func (e *SSHKeyNotAuthorizedError) Error() string
Error implements the error interface.
func (*SSHKeyNotAuthorizedError) Fix ¶
func (e *SSHKeyNotAuthorizedError) Fix() string
Fix implements Fixer.
func (*SSHKeyNotAuthorizedError) Unwrap ¶
func (e *SSHKeyNotAuthorizedError) Unwrap() error
Unwrap exposes the underlying cause for errors.Is / errors.As.
type Spec ¶
type Spec struct {
// Host is the SSH destination in "host" or "host:port" form.
// When no port is supplied, port 22 is assumed.
Host string `json:"host" yaml:"host"`
// SSHUser is the login user for the SSH session. Required.
SSHUser string `json:"ssh_user" yaml:"ssh_user"`
// SSHPassword is a password-based SSH auth option. Mutually
// exclusive with SSHKeyName; when neither is set the dial falls
// back to a caller-injected ssh.Signer via DialSSHWithAuth.
SSHPassword string `json:"ssh_password,omitempty" yaml:"ssh_password,omitempty"`
// SSHKeyName references a private key stored in the QuicBaaS SSH key
// store (xkms-backed). When set, the deploy service resolves the key
// through the configured SSHSignerResolver (or the xkms SSH client
// directly); the private material never leaves xkms. Operators stage
// keys into the store via `quicbaas ssh keys import` — there is no
// local PEM-file fallback.
SSHKeyName string `json:"ssh_key_name,omitempty" yaml:"ssh_key_name,omitempty"`
// SSHKeyScope selects the xkms SSH store scope used to resolve
// SSHKeyName. Valid values: "user", "tenant", "service". Empty
// defaults to "user".
SSHKeyScope string `json:"ssh_key_scope,omitempty" yaml:"ssh_key_scope,omitempty"`
// SSHKeyOwner is the owner identifier for the SSH key lookup.
// Empty defaults depend on SSHKeyScope: user → current OS user,
// tenant → current tenant ID, service → "default".
SSHKeyOwner string `json:"ssh_key_owner,omitempty" yaml:"ssh_key_owner,omitempty"`
// InsecureHostKey disables host key verification. Exposed as an
// explicit operator opt-out only; production deploys pin host keys
// via the xkms-backed SSH known-hosts store, which is consulted
// through a HostKeyPolicy injected into DialSSHWithAuthAndHostKey
// at the service layer.
InsecureHostKey bool `json:"insecure_host_key,omitempty" yaml:"insecure_host_key,omitempty"`
// Server is the QuicBaaS control-plane address the agent will dial
// (e.g. https://quicbaas.example.com:8443). The server may be a
// single quicbaasd process or a Raft-replicated cluster — the agent
// dials the same endpoint either way.
Server string `json:"server" yaml:"server"`
// Tenant is the tenant the agent runs under.
Tenant string `json:"tenant" yaml:"tenant"`
// NodeBind is the local bind address the fleet node daemon exposes for
// its FleetRuntime gRPC service on the remote host.
NodeBind string `json:"node_bind" yaml:"node_bind"`
// Backends is the ordered list of backends the node serves, each by its
// own name (fleet.BackendKind), or the "acp" group of every agent backend
// — e.g. []string{"opencode", "openvino", "ollama"} for a node that must
// never be handed claude or codex work.
Backends []string `json:"backends" yaml:"backends"`
// Binary is the local filesystem path to the static CLI binary
// produced by `make build-static-cli`.
Binary string `json:"binary" yaml:"binary"`
// InstallDir is the remote directory the binary is uploaded to.
// Defaults to ~/.quicbaas/bin when empty.
InstallDir string `json:"install_dir,omitempty" yaml:"install_dir,omitempty"`
// DataDir is the remote work directory the agent stores state in.
// Defaults to ~/.quicbaas/agent when empty.
DataDir string `json:"data_dir,omitempty" yaml:"data_dir,omitempty"`
// Systemd controls whether a systemd --user unit is installed.
// When nil, the service auto-detects support; when non-nil the
// explicit value is honoured.
Systemd *bool `json:"systemd,omitempty" yaml:"systemd,omitempty"`
// WaitOnline is the maximum time the deploy will wait for the
// agent to appear in the fleet registry with a live heartbeat.
// Zero means "do not wait".
WaitOnline time.Duration `json:"wait_online,omitempty" yaml:"wait_online,omitempty"`
// MCPEndpoint is the fully-qualified https://host:port/mcp address of
// the control plane's MCP listener. When set, the rendered daemon
// command line carries --mcp-endpoint so spawned agents can resolve the
// "quicbaas" MCP preset against the long-lived mTLS identity uploaded by
// this deploy. Populated by the deploy service from its configured MCP
// endpoint; empty when the control plane has MCP disabled or unconfigured,
// in which case the flag is omitted entirely (no behavior change).
MCPEndpoint string `json:"mcp_endpoint,omitempty" yaml:"mcp_endpoint,omitempty"`
// ProjectsRoot is the directory the daemon provisions job workspaces
// under. An absolute path is used as written; a relative one is taken
// under the remote user's home, like InstallDir and DataDir. Empty takes
// the daemon's default, <data-dir>/work/projects. The deploy owns this
// setting — preflight measures its free space and undeploy
// --purge-workspaces removes it — so it is declared here rather than in
// the node section.
ProjectsRoot string `json:"projects_root,omitempty" yaml:"projects_root,omitempty"`
// WorkerImages are the container images this node's sandboxed sessions
// run. Preflight checks each is present or pullable on the node and that
// its build-time AGENT_UID matches the uid the daemon runs as; a
// mismatch makes every signed commit in the container fail.
WorkerImages []string `json:"worker_images,omitempty" yaml:"worker_images,omitempty"`
// Agent is the daemon's own configuration: exactly fleet.Config, the
// schema `fleet serve --config` reads. Deploy renders it into the config
// file it installs next to the binary, filling in the settings the deploy
// owns (server, tenant, bind address, backends, work and projects
// directories, identity paths, MCP endpoint) from the fields above;
// setting any of those here is refused rather than silently overwritten.
//
// agent.max_concurrent_jobs is required: a node that declares no capacity
// leaves the whole fleet's capacity undeclared (see
// fleet.Config.MaxConcurrentJobs).
Node fleet.Config `json:"node" yaml:"node"`
// SkipPreflight deploys without running the preflight checks first. It
// is an operator's per-invocation choice (--skip-preflight), never part
// of a committed node spec, so the spec file cannot set it.
SkipPreflight bool `json:"skip_preflight,omitempty" yaml:"-"`
// Local installs on the host this process runs on, through a
// LocalTarget instead of ssh: a fleet node co-located with quicbaasd
// needs no sshd. Host is then the host this node is advertised under,
// and every ssh setting is empty (see LocalSSHConflict). It is an
// operator's per-invocation choice (--local), so the spec file cannot
// set it.
Local bool `json:"local,omitempty" yaml:"-"`
}
Spec is the full deployment specification consumed by the agent deploy service and the CLI.
Fields carry user intent. Default/derived values (InstallDir, DataDir, WaitOnline) are filled in by the service layer before the primitives are invoked, so the primitives themselves never need to inspect optional state.
func DefaultSpec ¶
func DefaultSpec() *Spec
DefaultSpec returns a Spec carrying the defaults a node spec's agent section starts from. The one that matters is the sandbox policy: the fleet.Config zero value is opt-in, the least secure policy, while a daemon started without a policy has always run "required". Seeding it here keeps a spec that says nothing about sandboxing on "required".
func (*Spec) DaemonConfig ¶
DaemonConfig is the fleet.Config the deployed daemon runs with: the spec's agent section with every deploy-owned setting filled in from the spec and the layout.
func (*Spec) DefaultNodeBind ¶
DefaultNodeBind fills an empty NodeBind with the host being deployed to and DefaultNodePort. The default is the advertised host, never the wildcard (go-quicbaas#185): a fleet node listens where it is reached, not on every interface. An explicit NodeBind, wildcard included, is the operator's choice and is left as it is.
func (*Spec) Layout ¶
Layout resolves the spec's directories under home. InstallDir and DataDir are always taken as home-relative (a leading "/" is ignored), matching the %h and $HOME joins the rendered unit and script make. ProjectsRoot is the exception: an absolute one is used as written, because it names a volume the operator chose rather than a place inside the deploy's own tree.
An empty home yields "$HOME"-prefixed paths for use inside a remote shell.
func (*Spec) LocalSSHConflict ¶
LocalSSHConflict reports the first ssh setting a local install carries. A local install reaches no host over ssh, so any of them is a mistake.
func (*Spec) ResolvedDataDir ¶
ResolvedDataDir returns DataDir or the default when empty.
func (*Spec) ResolvedInstallDir ¶
ResolvedInstallDir returns InstallDir or the default when empty.
func (*Spec) SystemdExplicit ¶
SystemdExplicit reports whether the caller pinned the Systemd field to a non-nil value. When false, the service layer should auto-detect.
func (*Spec) UseSystemd ¶
UseSystemd returns true when the spec explicitly requests a systemd install. The service layer uses this helper to drive its auto-detect fallback when Systemd is nil.
func (*Spec) ValidateDaemonConfig ¶
ValidateDaemonConfig checks the daemon half of the spec before anything is issued or installed: no deploy-owned key is set in the node section, the node declares its capacity, and the config the deploy would render passes fleet.Config.Validate — so a daemon that would refuse to start is refused here, on the operator's machine, instead of in a restart loop on the node.
type SpecFileError ¶
SpecFileError reports a node spec file that could not be read, decoded, or accepted. Path names the file.
func (*SpecFileError) Error ¶
func (e *SpecFileError) Error() string
Error implements the error interface.
func (*SpecFileError) Unwrap ¶
func (e *SpecFileError) Unwrap() error
Unwrap exposes the underlying cause for errors.Is / errors.As.
type StartTimeoutError ¶
type StartTimeoutError struct {
Host string
Tenant string
Elapsed string
// Cause is the last reason the agent was rejected as online, when
// there was one — typically the failed liveness probe of the
// agent's runtime port. Nil when the agent simply never appeared
// in the fleet registry.
Cause error
}
StartTimeoutError indicates the agent did not come online within the caller's WaitOnline budget.
func (*StartTimeoutError) Error ¶
func (e *StartTimeoutError) Error() string
Error implements the error interface.
func (*StartTimeoutError) Unwrap ¶
func (e *StartTimeoutError) Unwrap() error
Unwrap exposes the underlying cause for errors.Is / errors.As.
type Supervisor ¶
type Supervisor string
Supervisor names how an installed agent is run.
const ( // SupervisorSystemd is a systemd --user unit. SupervisorSystemd Supervisor = "systemd" // SupervisorNohup is the nohup start script. SupervisorNohup Supervisor = "nohup" // SupervisorNone means nothing is installed. SupervisorNone Supervisor = "" )
func InstalledSupervisor ¶
func InstalledSupervisor(ctx context.Context, c Target, l Layout) Supervisor
InstalledSupervisor reports how the agent under l is installed, or SupervisorNone when neither a unit nor a start script is there.
type SystemdInstallError ¶
SystemdInstallError indicates a systemd unit could not be installed or started on the remote host.
func (*SystemdInstallError) Error ¶
func (e *SystemdInstallError) Error() string
Error implements the error interface.
func (*SystemdInstallError) Unwrap ¶
func (e *SystemdInstallError) Unwrap() error
Unwrap exposes the underlying cause for errors.Is / errors.As.
type SystemdUserUnavailableError ¶
type SystemdUserUnavailableError struct {
}
SystemdUserUnavailableError reports a host with no working systemd --user manager when the spec asked for a systemd install.
func (*SystemdUserUnavailableError) Error ¶
func (e *SystemdUserUnavailableError) Error() string
Error implements the error interface.
func (*SystemdUserUnavailableError) Fix ¶
func (e *SystemdUserUnavailableError) Fix() string
Fix implements Fixer.
type Target ¶
type Target interface {
// Host names the target in errors and reports.
Host() string
// User is the login user commands run as.
User() string
// Exec runs cmd under the target's POSIX shell and returns its
// stdout and stderr. A non-zero exit is an error.
Exec(ctx context.Context, cmd string) (stdout, stderr string, err error)
// WriteFile writes data to path with the given mode, creating the
// parent directories.
WriteFile(ctx context.Context, path string, data []byte, mode os.FileMode) error
// Upload copies the local file at localPath to path, executable
// (0o755), staged and renamed into place so a running binary is never
// written in place.
Upload(ctx context.Context, localPath, path string) error
// DialTCP opens a TCP connection to addr as seen from the target.
DialTCP(ctx context.Context, addr string) (net.Conn, error)
}
Target is the host an install runs on. The install primitives (UploadBinary, InstallAndStart, StartBackground, EnsureLinger, the lifecycle verbs and RunPreflight) need only this, so one install path serves two transports: *SSHClient reaches a remote host over ssh, and *LocalTarget installs on the host this process runs on, with no sshd.
Paths may begin with "$HOME", which the target resolves to its login user's home directory.
type UninstallResult ¶
type UninstallResult struct {
Supervisor Supervisor
Removed []string
}
UninstallResult lists what UninstallNode removed.
func UninstallNode ¶
func UninstallNode(ctx context.Context, c Target, l Layout, purgeWorkspaces bool) (*UninstallResult, error)
UninstallNode stops and disables the agent, then removes everything the deploy installed: the unit, the config file, the binary, the start script, the mTLS identity, the daemon's persisted credentials, and its log and pid files. Workspaces — the projects root and the rest of the work directory — are kept unless purgeWorkspaces is set, because they hold checkouts a job may still need. Removing an agent that is already gone succeeds.
type WorkerImageUIDMismatchError ¶
type WorkerImageUIDMismatchError struct {
Image string
ImageUser string
RemoteUID string
RemoteGID string
}
WorkerImageUIDMismatchError reports a worker image built for a different uid than the one the daemon runs as. Sandboxed sessions run as the daemon's uid, and an image with no passwd entry for it fails every signed commit ("No user exists for uid").
func (*WorkerImageUIDMismatchError) Error ¶
func (e *WorkerImageUIDMismatchError) Error() string
Error implements the error interface.
func (*WorkerImageUIDMismatchError) Fix ¶
func (e *WorkerImageUIDMismatchError) Fix() string
Fix implements Fixer.
type WorkerImageUnavailableError ¶
type WorkerImageUnavailableError struct {
}
WorkerImageUnavailableError reports a worker image that is neither present on the node nor pullable from its registry.
func (*WorkerImageUnavailableError) Error ¶
func (e *WorkerImageUnavailableError) Error() string
Error implements the error interface.
func (*WorkerImageUnavailableError) Fix ¶
func (e *WorkerImageUnavailableError) Fix() string
Fix implements Fixer.
func (*WorkerImageUnavailableError) Unwrap ¶
func (e *WorkerImageUnavailableError) Unwrap() error
Unwrap exposes the underlying cause for errors.Is / errors.As.