install

package
v0.2.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 29, 2026 License: MIT Imports: 24 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

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

View Source
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.

View Source
const ChecksumsAsset = "checksums.txt"

ChecksumsAsset is the GoReleaser checksum file.

View Source
const DefaultHubRepo = "devXpro/homie"

DefaultHubRepo is where homed releases come from.

View Source
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.

View Source
const ManifestAsset = "homie-plugin.json"

ManifestAsset is the release asset that describes a plugin (PLAN §5.1).

Variables

View Source
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

func ArchiveName(binary, version, goos, goarch string) string

ArchiveName builds the GoReleaser archive name: <binary>_<version>_<os>_<arch>.tar.gz.

func Code

func Code(err error) string

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

func CompareVersions(a, b string) (int, error)

CompareVersions returns -1, 0 or 1 following semver precedence (a pre-release is lower than its release).

func NormalizeVersion

func NormalizeVersion(v string) (string, error)

NormalizeVersion strips a leading "v" and validates the rest ("v0.2.0" -> "0.2.0").

func ParseChecksums

func ParseChecksums(data []byte) (map[string]string, error)

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

func Unpack(archive, dest string, lim Limits) error

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

type Asset struct {
	Name string
	URL  string // the public download URL (https)
	Size int64
}

Asset is one downloadable file of a release.

func FindAsset

func FindAsset(rel *Release, binary, goos, goarch string) (Asset, error)

FindAsset picks the archive for binary at the release's version for goos/goarch. Empty goos/goarch mean the running platform. For 32-bit ARM the GoReleaser spellings armv7, armv6 and arm are tried in that order.

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.

func (*Candidate) Err

func (c *Candidate) Err() error

Err returns ErrNoAsset or ErrIncompatible when the candidate cannot be installed, else nil.

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

func NewClient(token string) *Client

NewClient returns a client for api.github.com with the given token (empty means unauthenticated).

func (*Client) Checksums

func (c *Client) Checksums(ctx context.Context, rel *Release) (map[string]string, error)

Checksums downloads and parses the release's checksums.txt.

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

func (c *Client) FetchManifest(ctx context.Context, rel *Release) (*Manifest, []byte, error)

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

func (c *Client) Latest(ctx context.Context, repo string) (*Release, error)

Latest returns the latest published, non-prerelease release of repo ("owner/name").

func (*Client) ReleaseByVersion

func (c *Client) ReleaseByVersion(ctx context.Context, repo, version string) (*Release, error)

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.

func (*Client) Verify

func (c *Client) Verify(ctx context.Context, rel *Release, a Asset, path string) error

Verify compares the sha256 of the file at path with the line for asset in the release's checksums.txt. Nothing may be unpacked before it returns nil. A missing checksums.txt or line is ErrNoChecksum, a different hash is ErrChecksumMismatch.

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

func (u *HubUpdater) Latest(ctx context.Context) (*Release, bool, error)

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

func (i *Installer) Fetch(ctx context.Context, cand *Candidate, hooks *Hooks) (*Installed, error)

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

func (i *Installer) Locate(id, version string) (*Installed, error)

Locate reads an installed version back from disk (its stored manifest) without any network access.

func (*Installer) Prune

func (i *Installer) Prune(id string, keep ...string) error

Prune deletes every installed version of id except those in keep. Empty names in keep are ignored.

func (*Installer) Remove

func (i *Installer) Remove(id string, keepData bool) error

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

func (i *Installer) Resolve(ctx context.Context, repo, version string) (*Candidate, error)

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

func (i *Installer) VersionDir(id, version string) string

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

func ParseManifest(data []byte) (*Manifest, error)

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

func (m *Manifest) Compatible(hubVersion string) bool

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.

func (*Release) Asset

func (r *Release) Asset(name string) (Asset, bool)

Asset returns the asset with this exact name.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL