Documentation
¶
Overview ¶
Package install installs, updates and removes plugins from GitHub releases, and updates the homed binary itself.
It has no daemon or store dependencies: the admin API (T2.3) and the wiring (T2.6) call it and supply Hooks that touch the store and the plugin host. Nothing in the package logs, so no token can reach a log line.
Release conventions (PLAN §5.1) ¶
A plugin release holds GoReleaser archives <binary>_<version>_<os>_<arch>.tar.gz (version without the "v"; 32-bit ARM is tried as armv7, armv6, arm), a checksums.txt ("<sha256> <name>"), and homie-plugin.json: {"id","title","description","binary","args":["serve"],"minHubVersion","homepage"}. A homed release has the same archives for the binary "homed" and checksums.txt, but no manifest. Archives may be flat or wrapped in a single directory.
Plugin API ¶
cl := install.NewClient(install.TokenFromEnv())
in := &install.Installer{Client: cl, DataDir: dataDir, HubVersion: hubVersion}
cand, err := in.Resolve(ctx, "devXpro/homie-tv", "latest") // GET /plugins/preview: release, manifest, asset?, compatible?
got, err := in.Install(ctx, "devXpro/homie-tv", "", "tv", h) // POST /plugins (job plugin.install)
got, err := in.Update(ctx, "tv", repo, current, "", false, h) // POST /plugins/{id}/update (job plugin.update)
err := in.Remove("tv", keepData) // DELETE /plugins/{id} (after the plugin stopped)
got, err := in.Locate("tv", "0.2.0") // read an installed version back, offline
rel, err := cl.Latest(ctx, repo) // check-updates: compare rel.Version with the store's
Install and Update run the job steps of ADMIN-API §3 and report each one through Hooks.Step: resolve, download, verify, unpack, (update only) switch, start, and rollback when a start fails. Hooks.Progress carries archive download bytes for the job's progress bar. Errors map to job error codes with Code(err): checksum_mismatch, no_asset, incompatible, start_failed, rolled_back, downgrade, upstream, internal, plus not_found and up_to_date. A release older than the installed one (or the running hub) is ErrDowngrade unless the caller allows it; the admin allows it only on the local socket with an explicit flag.
Layout and atomicity. Files land in <data_dir>/plugins/<id>/bin/<version>/. A release is downloaded and unpacked in a staging directory .stage-* under <data_dir>/plugins/ and appears with one rename, so a crash never leaves a half-unpacked version. The "current version" is not a symlink: it is store.Plugin.Command (the absolute binary path plus the manifest args, Installed.Command), Version and PreviousVersion. The atomic switch is therefore the Hooks.Switch store update, followed by Hooks.Start (restart the plugin and wait until initialize and tools/list answer). If Start fails, Hooks.Rollback restores the previous store row and restarts the old binary, the new directory is deleted, and the error wraps ErrStartFailed and ErrRolledBack. If Rollback itself fails both directories stay for the operator. After a successful update only the new and the previous version remain on disk.
Install calls only Start (it must create the store row and start the plugin); Update calls Switch, then Start.
Security ¶
Only https is used, for the API, every asset and every redirect hop (at most 5). The optional token is sent as a bearer header to the API host only, never to the asset host, and never appears in an error. The archive's sha256 must equal its line in the release's checksums.txt before anything is unpacked (ErrChecksumMismatch, or ErrNoChecksum when the file or line is missing). Note that checksums.txt comes from the same release, so this guards against corruption and a bad mirror, not against a compromised repository; the trust anchor is the repo the owner chose in the admin. Unpacking refuses absolute and ".." paths, backslashes, duplicate entries, links of any kind (symbolic and hard), devices and FIFOs; every file operation goes through os.Root, which independently refuses to leave the target directory, and the stored manifest is written through it too (O_EXCL, no link followed). Downloads (256 MiB), unpacked bytes (512 MiB, counted on real decompressed bytes) and entry counts (2000) are capped; see Limits. File modes are normalized to 0755 or 0644, so setuid bits never survive.
Self-update of homed ¶
u := &install.HubUpdater{Client: cl, Version: hubVersion}
rel, newer, err := u.Latest(ctx) // POST /system/check-update
res, err := u.Update(ctx, "", false, hooks) // job hub.update: resolve, download, verify, replace
// then: finish the job, shut down gracefully, os.Exit(install.ExitCodeRestart)
Update downloads homed_<version>_<os>_<arch>.tar.gz, verifies it, unpacks it into a temporary directory, runs "<new> version" (must exit 0 within 15 s; disable with SkipSmokeTest) and renames a copy over the running binary inside the same directory, keeping the old one as <exe>.prev (HubUpdater.Rollback restores it). The running process keeps its old inode, so it can finish the job, answer the last SSE event and exit by itself; Update does not exit and does not touch the daemon. A symlinked executable (Homebrew's /opt/homebrew/bin/homed) is resolved and its real file replaced; a directory that is not writable gives ErrNotWritable, and then the update must go through the package manager ("brew upgrade").
Expected service-manager behaviour: after the exit with ExitCodeRestart (75, non-zero on purpose) the manager must start the binary again. launchd: KeepAlive true (the LaunchAgent in docs/DEV.md has it; ThrottleInterval bounds restart storms). systemd: Restart=always, or Restart=on-failure (75 counts as a failure, so keep 75 out of SuccessExitStatus= and RestartPreventExitStatus=). Docker: a restart policy (unless-stopped). Without a manager the process just ends and the user starts homed again.
Only unix-like systems (darwin, linux) are supported: archives are tar.gz and the swap relies on rename over a running file.
Index ¶
- Constants
- Variables
- func ArchiveName(binary, version, goos, goarch string) string
- func Code(err error) string
- func CompareVersions(a, b string) (int, error)
- func NormalizeVersion(v string) (string, error)
- func ParseChecksums(data []byte) (map[string]string, error)
- func TokenFromEnv() string
- func Unpack(archive, dest string, lim Limits) error
- type Asset
- type Candidate
- type Client
- func (c *Client) Checksums(ctx context.Context, rel *Release) (map[string]string, error)
- func (c *Client) Download(ctx context.Context, a Asset, dir string, maxBytes int64, progress Progress) (string, error)
- func (c *Client) FetchManifest(ctx context.Context, rel *Release) (*Manifest, []byte, error)
- func (c *Client) Latest(ctx context.Context, repo string) (*Release, error)
- func (c *Client) ReleaseByVersion(ctx context.Context, repo, version string) (*Release, error)
- func (c *Client) Verify(ctx context.Context, rel *Release, a Asset, path string) error
- type Hooks
- type HubUpdate
- type HubUpdater
- type Installed
- type Installer
- func (i *Installer) Fetch(ctx context.Context, cand *Candidate, hooks *Hooks) (*Installed, error)
- func (i *Installer) Install(ctx context.Context, repo, version, wantID string, hooks *Hooks) (*Installed, error)
- func (i *Installer) Locate(id, version string) (*Installed, error)
- func (i *Installer) Prune(id string, keep ...string) error
- func (i *Installer) Remove(id string, keepData bool) error
- func (i *Installer) Resolve(ctx context.Context, repo, version string) (*Candidate, error)
- func (i *Installer) Update(ctx context.Context, id, repo, current, version string, allowDowngrade bool, ...) (*Installed, error)
- func (i *Installer) VersionDir(id, version string) string
- type Limits
- type Manifest
- type Progress
- type Release
Constants ¶
const ( StepResolve = "resolve" StepDownload = "download" StepVerify = "verify" StepUnpack = "unpack" StepSwitch = "switch" StepStart = "start" StepRollback = "rollback" StepReplace = "replace" StepRestart = "restart" )
Job step names, as in ADMIN-API §3.
const ChecksumsAsset = "checksums.txt"
ChecksumsAsset is the GoReleaser checksum file.
const DefaultHubRepo = "devXpro/homie"
DefaultHubRepo is where homed releases come from.
const ExitCodeRestart = 75
ExitCodeRestart is the exit status homed should use after a successful HubUpdater.Update, once it has shut down gracefully. It is non-zero (EX_TEMPFAIL) so that both systemd "Restart=on-failure" and "Restart=always", and launchd "KeepAlive" in either form, bring the new binary up. See the package doc for the unit settings.
const ManifestAsset = "homie-plugin.json"
ManifestAsset is the release asset that describes a plugin (PLAN §5.1).
Variables ¶
var ( // ErrNotFound means the repository, the release or the version does not exist. ErrNotFound = errors.New("install: release not found") // ErrUpstream means GitHub or the asset host failed or answered nonsense. ErrUpstream = errors.New("install: upstream failure") // ErrRateLimited is an ErrUpstream caused by the GitHub API rate limit (set a token to raise it). ErrRateLimited = errors.New("install: GitHub API rate limit reached") // ErrInsecureURL means a URL (or a redirect) was not https. ErrInsecureURL = errors.New("install: only https URLs are allowed") // ErrNoAsset means the release has no build for this OS and CPU. ErrNoAsset = errors.New("install: no release asset for this OS and CPU") // ErrIncompatible means the plugin needs a newer hub (minHubVersion). ErrIncompatible = errors.New("install: plugin needs a newer hub version") // ErrBadManifest means homie-plugin.json is missing fields or has invalid ones. ErrBadManifest = errors.New("install: invalid homie-plugin.json") // ErrNoChecksum means checksums.txt is missing or has no line for the archive. ErrNoChecksum = errors.New("install: no checksum for the archive") // ErrChecksumMismatch means the downloaded bytes do not match checksums.txt. ErrChecksumMismatch = errors.New("install: checksum mismatch") // ErrTooLarge means a download or an archive exceeds its size limit. ErrTooLarge = errors.New("install: size limit exceeded") // ErrUnsafeArchive means the archive tried path traversal, a link escape or holds a forbidden entry type. ErrUnsafeArchive = errors.New("install: unsafe archive") // ErrStartFailed means the new version did not come up (the Start hook failed). ErrStartFailed = errors.New("install: the new version did not start") // ErrRolledBack marks an ErrStartFailed whose previous version was put back. ErrRolledBack = errors.New("install: rolled back to the previous version") // ErrUpToDate means the requested version is already installed. ErrUpToDate = errors.New("install: already up to date") // ErrDowngrade means the release is older than the installed version and the caller did not allow a downgrade. ErrDowngrade = errors.New("install: the release is older than the installed version") // ErrIDMismatch means the requested plugin id differs from the manifest's. ErrIDMismatch = errors.New("install: plugin id does not match the manifest") // ErrNotWritable means the running binary cannot be replaced (for example a package manager owns it). ErrNotWritable = errors.New("install: the binary location is not writable") )
Sentinel errors. Callers test them with errors.Is; Code maps them to the job error codes of ADMIN-API §3.
Functions ¶
func ArchiveName ¶
ArchiveName builds the GoReleaser archive name: <binary>_<version>_<os>_<arch>.tar.gz.
func Code ¶
Code maps an error to the job error codes of ADMIN-API (checksum_mismatch, no_asset, incompatible, start_failed, rolled_back, downgrade, upstream, internal) plus not_found and up_to_date. Unknown errors are "internal". Callers should put err.Error() in the job's message: it never contains a token.
func CompareVersions ¶
CompareVersions returns -1, 0 or 1 following semver precedence (a pre-release is lower than its release).
func NormalizeVersion ¶
NormalizeVersion strips a leading "v" and validates the rest ("v0.2.0" -> "0.2.0").
func ParseChecksums ¶
ParseChecksums reads a checksums.txt ("<sha256> <name>" per line, "*name" for binary mode) into name -> hex.
func TokenFromEnv ¶
func TokenFromEnv() string
TokenFromEnv reads the optional GitHub token from HOMIE_GITHUB_TOKEN, then GITHUB_TOKEN.
func Unpack ¶
Unpack extracts the tar.gz at archive into dest, which must exist and should be empty. It refuses absolute and ".." paths, duplicate entries, links of any kind (symbolic and hard), devices and FIFOs, and anything over the limits (counted on real decompressed bytes, so a gzip bomb stops at the cap). Release archives hold regular files and directories only; a symlink, even one that looks harmless on its own, can be chained with another (a/b/up -> ../.. and then x -> a/b/up/..) so that a later write outside os.Root follows it out of dest. Every filesystem call goes through os.Root, which independently refuses to leave dest. Permissions are normalized to 0755 (any exec bit) or 0644; setuid and friends are dropped.
Types ¶
type Asset ¶
Asset is one downloadable file of a release.
type Candidate ¶
type Candidate struct {
Release *Release
Manifest *Manifest
RawManifest []byte // the manifest exactly as released
Asset Asset
AssetFound bool
Compatible bool
}
Candidate is a resolved release that has not been downloaded yet. It is what GET /plugins/preview shows.
type Client ¶
type Client struct {
// APIBase is the API root, https only. Default https://api.github.com.
APIBase string
// Token is an optional GitHub token (see TokenFromEnv).
Token string
// HTTP is the underlying client. Default: a plain http.Client. Redirects are always limited to 5 hops and
// https, whatever CheckRedirect the client had.
HTTP *http.Client
// UserAgent is sent with every request. Default "homie-installer".
UserAgent string
}
Client talks to the GitHub Releases API and downloads release assets. All URLs must be https. The optional token raises the API rate limit; it is sent only to the API host, never to an asset host, and never appears in an error.
func NewClient ¶
NewClient returns a client for api.github.com with the given token (empty means unauthenticated).
func (*Client) Download ¶
func (c *Client) Download(ctx context.Context, a Asset, dir string, maxBytes int64, progress Progress) (string, error)
Download streams asset into a new 0600 file inside dir and returns its path; the caller removes it. maxBytes caps the download (the advertised size is checked up front too). The bytes are NOT trusted until Verify passes.
func (*Client) FetchManifest ¶
FetchManifest downloads and parses the release's homie-plugin.json. A release without it is ErrBadManifest: it is not a plugin release.
func (*Client) Latest ¶
Latest returns the latest published, non-prerelease release of repo ("owner/name").
func (*Client) ReleaseByVersion ¶
ReleaseByVersion returns the release of a specific version ("0.2.0" or "v0.2.0"); it tries the tag v0.2.0, then 0.2.0.
type Hooks ¶
type Hooks struct {
// Step is called as each job step begins.
Step func(step string)
// Progress reports archive download progress.
Progress Progress
// Switch persists the new version as the plugin's current one (the store row: Command, Version,
// PreviousVersion). It runs before Start and only for updates. An error aborts the update with nothing
// changed on disk but the new, unused version directory, which is removed.
Switch func(ctx context.Context, next *Installed) error
// Start makes the new version live: for an install it creates the store row and starts the plugin; for an
// update it restarts the plugin on the switched command. It must return nil only when the plugin is up
// (initialize + tools/list answered). An error means the new version did not come up.
Start func(ctx context.Context, next *Installed) error
// Rollback puts the previous version back after a failed Start (store row and a restart). It runs on a
// context that is not cancelled with the job's.
Rollback func(ctx context.Context, prev *Installed) error
}
Hooks connect the installer to the rest of homed (T2.6 supplies them over the store and the plugin host). Every field is optional.
type HubUpdate ¶
type HubUpdate struct {
From string // running version before the update
To string // the installed release version
ExePath string // the replaced binary
BackupPath string // the previous binary (ExePath + ".prev"), "" when it could not be kept
}
HubUpdate describes a finished replacement.
type HubUpdater ¶
type HubUpdater struct {
Client *Client
Repo string // default DefaultHubRepo
Binary string // archive and file name, default "homed"
Version string // the running version; "" or a dev build never counts as up to date
ExePath string // the binary to replace; default os.Executable() with symlinks resolved
GOOS string // default runtime.GOOS
GOARCH string // default runtime.GOARCH
Limits Limits
// SkipSmokeTest disables running "<new binary> version" before the swap. By default the new binary must
// exit 0 within 15 s, which catches a wrong-platform or corrupt build while the old one is still in place.
SkipSmokeTest bool
}
HubUpdater replaces the running homed binary with a newer release.
func (*HubUpdater) Latest ¶
Latest returns the latest release and whether it is newer than the running version. A dev build is always updatable.
func (*HubUpdater) Rollback ¶
func (u *HubUpdater) Rollback() error
Rollback puts the binary kept by Update back (ExePath+".prev" renamed over ExePath). It is for an operator or a failed restart; a running homed does not call it on its own.
func (*HubUpdater) Update ¶
func (u *HubUpdater) Update(ctx context.Context, version string, allowDowngrade bool, hooks *Hooks) (*HubUpdate, error)
Update downloads version ("" or "latest" is the latest release), verifies it against checksums.txt, unpacks it to a temporary directory, smoke-tests it and atomically swaps it over the running binary (a same-directory rename; the old binary stays at ExePath+".prev"). It does not exit: the caller finishes its job, shuts homed down gracefully and calls os.Exit(ExitCodeRestart) so the service manager starts the new binary. A package- manager-owned or read-only location gives ErrNotWritable; then the update has to go through that manager. A release older than the running version is ErrDowngrade unless allowDowngrade.
type Installed ¶
type Installed struct {
ID string
Repo string
Version string
Manifest *Manifest
Dir string // <data_dir>/plugins/<id>/bin/<version>
Binary string // absolute path of the executable inside Dir
Command []string // Binary + manifest args: what plugins.Spec.Command and store.Plugin.Command hold
}
Installed is one unpacked, verified plugin release on disk.
type Installer ¶
type Installer struct {
Client *Client
DataDir string
HubVersion string // the running hub's version, for minHubVersion; a dev build is compatible with everything
GOOS string // default runtime.GOOS (tests override)
GOARCH string // default runtime.GOARCH
Limits Limits
}
Installer manages plugin releases under <DataDir>/plugins/<id>/bin/<version>/.
func (*Installer) Fetch ¶
Fetch downloads, verifies and unpacks a candidate into <data_dir>/plugins/<id>/bin/<version>/ and returns it. The directory appears atomically (one rename from a staging directory on the same filesystem); an existing directory of the same version is replaced. Nothing is unpacked before the sha256 matches checksums.txt.
func (*Installer) Install ¶
func (i *Installer) Install(ctx context.Context, repo, version, wantID string, hooks *Hooks) (*Installed, error)
Install resolves repo at version, downloads, verifies and unpacks it, then calls hooks.Start. wantID, when not empty, must equal the manifest's id (the plugin's tools are prefixed with it, so it cannot be renamed). If Start fails the unpacked files are removed and the error wraps ErrStartFailed. The caller checks that the id is free in the store first.
func (*Installer) Locate ¶
Locate reads an installed version back from disk (its stored manifest) without any network access.
func (*Installer) Prune ¶
Prune deletes every installed version of id except those in keep. Empty names in keep are ignored.
func (*Installer) Remove ¶
Remove deletes a plugin's files: the whole plugins/<id> directory, or only its bin/ when keepData is true. The caller has stopped the plugin and deletes the store row.
func (*Installer) Resolve ¶
Resolve finds the release (version "" or "latest" means the latest one), reads its manifest and looks for the archive for this OS and CPU. It downloads only the small manifest.
func (*Installer) Update ¶
func (i *Installer) Update(ctx context.Context, id, repo, current, version string, allowDowngrade bool, hooks *Hooks) (*Installed, error)
Update moves an installed plugin from current to version ("" or "latest" is the latest release): download, verify, unpack, hooks.Switch, hooks.Start. If Start fails, hooks.Rollback restores current and the new files are removed; the error then wraps ErrStartFailed and ErrRolledBack. ErrUpToDate when version is current, and ErrDowngrade when it is older (also when "latest" resolves to an older release) unless allowDowngrade. After a success only the new and the previous version stay on disk.
func (*Installer) VersionDir ¶
VersionDir returns <data_dir>/plugins/<id>/bin/<version>.
type Limits ¶
type Limits struct {
MaxArchiveBytes int64 // compressed download, default 256 MiB
MaxUnpackedBytes int64 // all regular files together, default 512 MiB
MaxEntries int // archive entries, default 2000
}
Limits bounds what the installer downloads and unpacks. Zero fields take the defaults.
type Manifest ¶
type Manifest struct {
ID string `json:"id"`
Title string `json:"title"`
Description string `json:"description"`
Binary string `json:"binary"`
Args []string `json:"args"`
MinHubVersion string `json:"minHubVersion"`
Homepage string `json:"homepage"`
}
Manifest is homie-plugin.json.
func ParseManifest ¶
ParseManifest decodes and validates a manifest: exactly one JSON object, nothing after it but white space. Args default to ["serve"], Title to the id.
func (*Manifest) Compatible ¶
Compatible reports whether a hub of this version satisfies minHubVersion. A development build (no release version) is always compatible.
type Progress ¶
type Progress func(done, total int64)
Progress receives download progress. total is 0 when unknown.
type Release ¶
type Release struct {
Repo string // "devXpro/homie-tv"
Tag string // "v0.2.0"
Version string // "0.2.0" (the tag without the leading v)
Name string // the release title
NotesURL string // the release page
PublishedAt time.Time // zero when GitHub gave none
Prerelease bool
Assets []Asset
}
Release is one GitHub release, reduced to what the installer needs.