Documentation
¶
Overview ¶
Package selfupdater provides a portable, framework-agnostic self-update mechanism for self-hosted Go applications. It checks GitHub Releases for a newer version, reports status, and (when running on a host with a writable executable) downloads, verifies and swaps the running binary, then restarts.
The package knows nothing about the host application's business logic. All integration happens through Config and the Hooks interface.
Index ¶
- Constants
- Variables
- type Config
- type Environment
- type Hooks
- type Status
- type Updater
- func (u *Updater) Apply(ctx context.Context) error
- func (u *Updater) ApplyHandler() http.HandlerFunc
- func (u *Updater) CheckHandler() http.HandlerFunc
- func (u *Updater) CheckNow(ctx context.Context) (Status, error)
- func (u *Updater) Start(ctx context.Context)
- func (u *Updater) Status() Status
- func (u *Updater) StatusHandler() http.HandlerFunc
Constants ¶
const DefaultCheckInterval = 6 * time.Hour
DefaultCheckInterval is used when Config.CheckInterval is zero.
Variables ¶
var ( // ErrInContainer is returned by Apply when the process runs inside a // container and therefore cannot replace its own binary. ErrInContainer = errors.New("self-updater: cannot self-update inside a container") // ErrNotWritable is returned by Apply when the executable (or its // directory) is not writable by the current user. ErrNotWritable = errors.New("self-updater: executable is not writable") // ErrNoUpdate is returned by Apply when no update is available. ErrNoUpdate = errors.New("self-updater: no update available") // ErrUpdateInProgress is returned by Apply (and CheckNow) when another // update operation is already running. ErrUpdateInProgress = errors.New("self-updater: update already in progress") // ErrNotConfigured is returned when a required Config field is missing. ErrNotConfigured = errors.New("self-updater: config is incomplete (need CurrentVersion, RepoOwner, RepoName)") )
Functions ¶
This section is empty.
Types ¶
type Config ¶
type Config struct {
// CurrentVersion is the version of the running binary (e.g. "1.4.2").
CurrentVersion string
// RepoOwner and RepoName identify the GitHub repository to query, e.g.
// "iAHTOH" and "go-selfupdater".
RepoOwner string
RepoName string
// AssetPrefix is the prefix of the release asset filename used to locate
// the correct archive for the current OS/arch, e.g. "eopds" for assets
// named "eopds_1.4.2_linux_amd64.tar.gz". Optional; when empty the
// go-selfupdate default naming is used.
AssetPrefix string
// CheckInterval is how often the background checker runs. Zero means
// DefaultCheckInterval.
CheckInterval time.Duration
// AllowPreRelease includes pre-releases when looking for the latest
// version. Disabled by default.
AllowPreRelease bool
// GitHubToken is an optional personal access token used to raise the
// GitHub API rate limit or to access private repositories.
GitHubToken string
// HTTPClient is an optional HTTP client used for API calls and downloads.
// It is mainly useful to configure a proxy or to inject a stub in tests.
// When nil, http.DefaultClient is used.
HTTPClient *http.Client
// Hooks receives update callbacks. Optional.
Hooks Hooks
// Logger is the structured logger. When nil, slog.Default() is used.
Logger *slog.Logger
}
Config configures an Updater. CurrentVersion, RepoOwner and RepoName are required; everything else has sensible defaults.
type Environment ¶
type Environment struct {
// InContainer is true when the process appears to run inside a container.
InContainer bool
// Writable is true when the executable can be replaced in place: both the
// executable file and its parent directory must be writable.
Writable bool
// ExecPath is the resolved absolute path of the running executable.
ExecPath string
}
Environment describes where the process is running and whether it can replace its own binary.
func (Environment) CanSelfUpdate ¶
func (e Environment) CanSelfUpdate() bool
CanSelfUpdate reports whether an in-place update is possible: we must be on a host (not in a container) and the executable must be replaceable.
type Hooks ¶
type Hooks struct {
// OnUpdateAvailable is called by the background checker and by CheckNow
// whenever a newer version than the current one is discovered. It may be
// called from a background goroutine, so implementations must be
// concurrency-safe.
OnUpdateAvailable func(status Status)
// BeforeRestart is called right before the process is replaced during
// Apply. It gives the host a chance to close database connections, stop
// background workers and flush logs. Returning an error aborts the
// restart (the already-swapped binary stays in place and will be used on
// the next manual start).
BeforeRestart func() error
}
Hooks lets the host application observe update events and react before a restart. All fields are optional; nil hooks are ignored.
type Status ¶
type Status struct {
// CurrentVersion is the version currently running.
CurrentVersion string `json:"current_version"`
// LatestVersion is the most recent version found on GitHub. Empty until
// the first successful check.
LatestVersion string `json:"latest_version"`
// UpdateAvailable reports whether LatestVersion is newer than
// CurrentVersion.
UpdateAvailable bool `json:"update_available"`
// InContainer reports whether the process runs inside a container. In a
// container the binary cannot be replaced in place, so only update
// notifications are possible.
InContainer bool `json:"in_container"`
// CanSelfUpdate reports whether applying an update is possible in this
// environment (not in a container and the executable is writable).
CanSelfUpdate bool `json:"can_self_update"`
// ReleaseURL is a link to the release page on GitHub.
ReleaseURL string `json:"release_url,omitempty"`
// ReleaseNotes is the release body (changelog) of the latest release.
ReleaseNotes string `json:"release_notes,omitempty"`
// LastCheckedAt is the time of the last check attempt.
LastCheckedAt time.Time `json:"last_checked_at,omitempty"`
// LastError is the error message of the most recent failed check, if any.
LastError string `json:"last_error,omitempty"`
}
Status is a snapshot of the updater state, safe to serialize to JSON and to expose over HTTP.
type Updater ¶
type Updater struct {
// contains filtered or unexported fields
}
Updater checks for and applies updates. It is safe for concurrent use.
func New ¶
New creates an Updater from cfg, validating required fields and detecting the runtime environment.
func (*Updater) Apply ¶
Apply downloads, verifies and swaps the running binary with the latest release, then schedules a restart. It returns ErrInContainer or ErrNotWritable when the environment does not allow an in-place update, ErrNoUpdate when there is nothing to apply, and ErrUpdateInProgress when an apply is already running.
Apply returns as soon as the binary has been replaced; the actual restart is performed from a short-lived goroutine after Apply returns, so an HTTP handler can still write its response before the process image is replaced. The BeforeRestart hook runs synchronously before the restart is scheduled; if it returns an error, the restart is aborted and the error is returned.
func (*Updater) ApplyHandler ¶
func (u *Updater) ApplyHandler() http.HandlerFunc
ApplyHandler returns an http.HandlerFunc that downloads and applies the latest update, then schedules a restart. It accepts POST only.
When the environment does not allow an in-place update (running in a container or the executable is not writable), it responds with 400 Bad Request and a JSON reason, so the caller can fall back to a manual update procedure.
func (*Updater) CheckHandler ¶
func (u *Updater) CheckHandler() http.HandlerFunc
CheckHandler returns an http.HandlerFunc that forces an update check now and returns the resulting status. It accepts POST only.
func (*Updater) CheckNow ¶
CheckNow performs a synchronous update check and updates the cached status. It returns ErrUpdateInProgress when another check or apply is running.
func (*Updater) Start ¶
Start launches the background checker. It checks once shortly after start and then every CheckInterval until ctx is cancelled. It returns immediately.
func (*Updater) StatusHandler ¶
func (u *Updater) StatusHandler() http.HandlerFunc
StatusHandler returns an http.HandlerFunc that reports the cached updater status as JSON. The request method is not restricted so it can be used both as a read endpoint and behind routers that only dispatch on path.