daemon

package
v1.15.0 Latest Latest
Warning

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

Go to latest
Published: Oct 7, 2026 License: MIT Imports: 21 Imported by: 0

Documentation

Overview

Package daemon implements background-process lifecycle for wick: Start/Stop/Restart/Status with a PID file. Targets headless environments where the system tray is not usable (Termux, SSH sessions, Linux servers).

The daemon re-execs the same binary with the existing `all` subcommand (server + worker in one process), detached from the caller's terminal so the parent shell can exit without killing it. Output goes to a log file alongside the PID file so users can tail it after start.

Index

Constants

This section is empty.

Variables

View Source
var ErrAlreadyRunning = errors.New("daemon already running")

ErrAlreadyRunning signals Start was called while a live daemon was already recorded in the PID file.

View Source
var ErrDrainTimeout = errors.New("previous process still draining")

ErrDrainTimeout signals the previous process was still finishing work when the wait window expired. Harmless on its own: it drains on its own schedule, bounded by WICK_DRAIN_TIMEOUT.

View Source
var ErrNotInstalled = errors.New("service not installed")

ErrNotInstalled signals UninstallService was called when no service integration was found.

View Source
var ErrNotRunning = errors.New("daemon not running")

ErrNotRunning signals Stop was called with no live daemon recorded.

View Source
var ErrReloadTimeout = errors.New("successor did not take over in time")

ErrReloadTimeout signals the successor never became the service's main process within the wait window. The old process keeps serving in that case — tableflip only steps aside once the successor reports ready — so this is a failed upgrade, not an outage.

Functions

func FileFingerprint added in v1.2.9

func FileFingerprint(path string) string

FileFingerprint identifies the exact bytes at path, cheaply: size and modification time, which together change on any replacement a deploy can perform (rename, copy, install). Empty when the file cannot be read.

Used to answer "is this still the file I put here?" — the question a rollback has to ask before undoing anything, because on a busy host the answer is sometimes no.

func FileSHA256 added in v1.2.9

func FileSHA256(path string) (string, error)

FileSHA256 hashes a file, for --sha256 verification of a binary that arrived from somewhere else.

func InstallBinary added in v1.2.9

func InstallBinary(src, target string, sudo bool) (string, error)

InstallBinary replaces target with src atomically and returns the path of the backup holding the previous binary.

Two details matter and both are learned the hard way:

  • writing straight over a running binary fails with ETXTBSY, so the new bytes go to a sibling temp file first;
  • rename(2) within the same directory is atomic, and the running process keeps its old inode alive until it exits on its own — which is exactly what a graceful handoff needs.

When sudo is true the three file operations are delegated to sudo(8), for the common layout where the binary lives in a root-owned directory but the daemon runs as a user unit.

func InstallService

func InstallService(p Paths, appName string) error

InstallService registers the binary to launch at user login / boot. Routing depends on the runtime environment:

GUI present (Win / Mac / desktop Linux) → forwards to the same
internal/autostart entry the tray uses AND flips
userconfig.AutoStartApp=true so the tray's `Auto-start app at
login` checkbox stays in sync with what the CLI did.

Headless (Termux, Linux server / RPi) → writes a daemon-style
auto-start unit (systemd-user or Termux:Boot script) that runs
`<exe> all` directly.

Re-running install over an existing install is safe — the GUI path rewrites the autostart entry, the headless path rewrites the unit.

func ProcessImageIs added in v1.2.9

func ProcessImageIs(pid int, path string) bool

ProcessImageIs reports whether the process is running the file at path. Compared by inode, not by name, so a swapped-but-not-reloaded daemon is correctly reported as still running the old image.

func ReadPID added in v0.16.13

func ReadPID(p Paths) (int, time.Time, error)

ReadPID returns the PID recorded in p.PIDFile plus the file mtime (best-effort start time). Exported for the systemd jalur in `status`, where Check() can't be used — the systemd-spawned process self-writes run.pid but no `start` parent verified it. os.ErrNotExist is returned verbatim when the file is absent.

func RefusedRecently added in v1.2.9

func RefusedRecently(dir string, window time.Duration) (string, bool)

RefusedRecently reports a refusal recorded within the last window. Used by a reload that does NOT wait for the successor: the daemon answers "I will not start one" immediately, and that is worth catching even when nothing is being waited for. Anything older belongs to an earlier reload.

func Reload added in v1.2.9

func Reload(p Paths) error

Reload asks the running daemon to upgrade in place: it starts a successor from the binary currently on disk, hands it the listening socket, and only then drains and exits. No connection is refused and no in-flight agent turn is killed — unlike Restart, which stops first and starts second.

Requires the daemon to have graceful upgrade enabled (WICK_GRACEFUL_UPGRADE=1); without it the signal is logged and ignored, and the caller should fall back to Restart.

func ReloadPID added in v1.2.9

func ReloadPID(pid int) error

Restart stops the running daemon (if any) then starts a fresh instance with the supplied argv tail. ReloadPID sends the reload signal to an explicit pid. Used when the service manager knows the process but wick has no PID file of its own (a systemd unit installed by hand).

func Restart

func Restart(p Paths, timeout time.Duration, args []string) (int, error)

func RestoreBinary added in v1.2.9

func RestoreBinary(backup, target string, sudo bool) error

RestoreBinary puts a backup taken by InstallBinary back in place, used when the successor never came up.

func RunningTarget added in v1.2.9

func RunningTarget(p Paths, appName string) (string, int, error)

RunningTarget resolves the file a graceful reload will actually execute, plus the pid of the daemon that will do the handing over.

It is deliberately argv[0] and not /proc/<pid>/exe. tableflip spawns the successor with os.Args[0] resolved through exec.LookPath, so THAT is the path whose bytes decide which binary comes up next — the inode currently executing is already gone the moment someone replaces the file. Installing anywhere else produces the most confusing possible outcome: a reload that reports success and brings back the old version.

func SameBuild added in v1.2.9

func SameBuild(a, b BinaryInfo) bool

SameBuild reports whether two binaries are the same build — same app version and same build timestamp. Swapping one for the other is a no-op.

func SelfRegister added in v0.16.13

func SelfRegister(p Paths, src Source) error

SelfRegister writes the running process's own PID + source to the daemon files. Called from `<app> all` on boot so the PID file is accurate no matter who spawned the process — systemd, the daemon parent, or a direct foreground run. Idempotent across restarts.

func ServiceActive added in v0.16.13

func ServiceActive(appName string) bool

ServiceActive reports whether systemctl considers the unit active (running). Best-effort; used by `status` for the systemd jalur.

func ServiceCtl added in v0.16.13

func ServiceCtl(appName, verb string) error

ServiceCtl runs `systemctl --user <verb> <app>.service` and returns the combined error. verb is start | stop | restart. Intentional stop/restart here means systemd does NOT treat the exit as a failure, so Restart=on-failure won't respawn behind our back.

func ServiceMainPID added in v1.2.9

func ServiceMainPID(appName string) int

ServiceMainPID returns the unit's MainPID, or 0 when systemd does not know one. Needed by `reload`: a unit written before graceful upgrade existed has no ExecReload, so the CLI signals the process itself instead of failing.

func ServiceManaged added in v0.16.13

func ServiceManaged(appName string) bool

ServiceManaged reports whether a systemd-user unit for appName is installed AND enabled — i.e. systemd is the authority for this app's lifecycle, so start/stop/restart must delegate to systemctl rather than spawn a second PID-file daemon. False on Termux (no systemd) and when the unit file is absent.

func ServingBinaryPath added in v1.2.9

func ServingBinaryPath() string

ServingBinaryPath resolves the path a successor would exec: argv[0] through PATH, the same way the handover resolves it.

Deliberately NOT /proc/self/exe — once the file has been replaced that still points at the old, now-unlinked inode, which is exactly the thing we are trying to detect a difference from.

func Start

func Start(p Paths, args []string) (int, error)

Start spawns the binary with the supplied subcommand detached from the caller's terminal, redirecting stdout+stderr to the daemon log file. Returns ErrAlreadyRunning if a live daemon is already recorded in the PID file.

args is the full argv tail passed to the spawned binary — callers choose between "all" (headless server + worker, default daemon mode) and "tray" (interactive tray icon on GUI hosts).

func Stop

func Stop(p Paths, timeout time.Duration) error

Stop sends SIGTERM (or the OS equivalent) to the running daemon and waits up to timeout for it to exit. Falls back to a force kill if the process is still alive at the deadline. ErrNotRunning is returned if no live daemon was recorded.

func TailLog

func TailLog(p Paths, n int64, w io.Writer) error

TailLog copies the last n bytes of the daemon log to w. Convenience for `status` output. Returns nil if the log doesn't exist yet.

The log is dated, so a daemon started on a previous day writes to a file whose name today's ResolvePaths would not reproduce. Tail the NEWEST daemon-*.log in the logs dir (falling back to p.LogFile) so `status` shows the running daemon's actual output, not an empty today-file.

func UninstallService

func UninstallService(p Paths, appName string) error

UninstallService removes whichever auto-start mechanism is in place. ErrNotInstalled is returned if nothing was registered. On the GUI path it also flips userconfig.AutoStartApp=false so the tray's checkbox follows the CLI.

func WaitDrain added in v1.2.9

func WaitDrain(oldPID int, timeout time.Duration) error

WaitDrain blocks until the old process has finished its in-flight work and exited. That exit is the moment cron, channels and the schedule runner move to the successor, so a deploy script that cares about "fully over" waits for this and not merely for the successor to serve HTTP.

func WaitSuccessor added in v1.2.9

func WaitSuccessor(p Paths, appName string, oldPID int, timeout time.Duration) (int, error)

WaitSuccessor blocks until the daemon's main pid moves away from oldPID, i.e. the successor has taken over as the service's main process.

func Writable added in v1.2.9

func Writable(path string) bool

Writable reports whether the current process can replace the file at path — it needs to create a sibling and rename over it, so the check is on the directory, not the file.

func WriteSource added in v0.16.13

func WriteSource(p Paths, src Source)

WriteSource records the spawn Source next to run.pid. Best-effort — a failure here only degrades `status` reporting, never blocks boot.

Types

type BinaryInfo added in v1.2.9

type BinaryInfo struct {
	Path        string
	MainModule  string // main module path, e.g. "abc-support-tools"
	AppName     string // -X ...BuildAppName (empty for a plain `go build`)
	AppVersion  string // -X ...BuildAppVersion ("dev" when not injected)
	BuildTime   string // -X ...BuildTime
	WickVersion string // version of the github.com/yogasw/wick dependency
	WickLocal   bool   // wick dep is `replace`d by a local tree
	GOOS        string
	GOARCH      string
	Size        int64
	ModTime     time.Time
}

BinaryInfo is everything we can learn about a binary WITHOUT running it.

Running an unknown binary to ask its version is self-defeating: the check exists precisely because the file may not be what the operator thinks it is. Go records enough in the binary itself (module graph + the -X ldflags `wick build` bakes in) to answer every question we care about statically.

func InspectBinary added in v1.2.9

func InspectBinary(path string) (BinaryInfo, error)

InspectBinary reads a binary's embedded build info. The file is never executed.

func (BinaryInfo) Describe added in v1.2.9

func (b BinaryInfo) Describe() string

Describe renders the one-line identity used in the confirmation summary.

func (BinaryInfo) IsWick added in v1.2.9

func (b BinaryInfo) IsWick() bool

IsWick reports whether the binary was built against wick at all.

type Finding added in v1.2.9

type Finding struct {
	Severity Severity
	Label    string
	Detail   string
}

Finding is one preflight result about a candidate binary.

func CompareBinaries added in v1.2.9

func CompareBinaries(candidate, running BinaryInfo, hostGOOS, hostGOARCH string) []Finding

CompareBinaries runs the preflight gate: is the candidate a wick binary, for this host, for THIS app, and is it moving forward?

running may be a zero BinaryInfo when the current binary could not be inspected; identity checks that need it are then skipped rather than guessed at.

type Paths

type Paths struct {
	Dir     string // ~/.<appname>/
	PIDFile string // run.pid
	LogFile string // logs/daemon-YYYY-MM-DD.log (dated; see ResolvePaths)
	ExePath string // resolved path to the currently running binary
}

Paths bundles the per-app filesystem locations used by the daemon.

func ResolvePaths

func ResolvePaths(appName string) (Paths, error)

ResolvePaths returns the canonical daemon paths for an app. The directory is created if missing.

The daemon log is dated (logs/daemon-YYYY-MM-DD.log), resolved to the current day at call time. Since ResolvePaths runs on every start / restart / systemd-install, each run lands in that day's file instead of one ever-growing daemon.log — giving the per-day split the operator expects and letting the shared logfiles prune reap old ones. This is a pre-Setup safety net for panics that fire before logfiles.Setup takes over stdout/stderr inside the `all` process; steady-state logs still live in the component-specific dated files.

type Pending added in v1.2.9

type Pending struct {
	Path    string // where the waiting binary sits
	Version string // its app version
	Built   string // its build timestamp
	Size    int64
	ModTime int64 // unix seconds, used to tell a finished copy from one in progress
	// Blocked, when non-empty, is why this build must NOT be applied — the
	// same verdict `reload --binary` reaches, phrased for someone reading the
	// update card. A blocked build is still reported as pending on purpose:
	// an operator who installed a file needs to see that it arrived and why
	// it is going nowhere, which is strictly better than a card that never
	// appears or one that counts down forever.
	Blocked string
	// Want is the smallest version that would be accepted, when the block is
	// about the version. It turns "no" into an instruction.
	Want string
}

Pending describes a build installed at the daemon's exec path that the running process is not the image of — the gap between "new binary in place" and "reload". Nothing else reports that state: the app looks perfectly normal while the version an operator believes they deployed is not the one answering.

func PendingSwap added in v1.2.9

func PendingSwap(runningVersion, runningBuiltAt string) (Pending, bool)

PendingSwap compares the binary at the exec path with the running version. A differing version OR a differing build timestamp counts: rebuilding the same version number is the normal case on a host that deploys from its own tree, and reporting "nothing waiting" there would be wrong.

The file is inspected, never executed.

type ServiceState

type ServiceState struct {
	Installed bool   // unit / script / login-item is registered with the OS
	Active    bool   // best-effort runtime check; not always supported
	Path      string // canonical location of the registration
	Backend   string // "autostart-gui", "systemd-user", "termux-boot", "headless-unsupported"
	Note      string // free-form hint shown in `service status`
}

ServiceState describes whether per-OS auto-start integration is installed and (where the platform exposes it) whether the service is currently active.

func ServiceStatus

func ServiceStatus(p Paths, appName string) (ServiceState, error)

ServiceStatus reports the registration state for whichever backend applies to the current host. On GUI hosts Installed/Active reflects the actual OS entry (what fires at login); a separate note flags when userconfig.AutoStartApp disagrees so the user can spot drift.

type Severity added in v1.2.9

type Severity int

Severity ranks a preflight finding.

const (
	SevInfo  Severity = iota // shown, never blocks
	SevWarn                  // shown prominently, never blocks
	SevBlock                 // blocks unless --force
	SevFatal                 // blocks, period
)

func Worst added in v1.2.9

func Worst(checks []Finding) Severity

Worst returns the highest severity among findings.

func (Severity) String added in v1.2.9

func (s Severity) String() string

type Source added in v0.16.13

type Source string

Source labels the spawn origin of a running daemon, recorded in the run.source file next to run.pid so `status` can report it without guessing.

const (
	SourceCLI     Source = "cli"     // direct `<app> all` / `<app> start` from a shell
	SourceSystemd Source = "systemd" // spawned by the systemd-user unit
	SourceTray    Source = "tray"    // GUI tray started the server in-process
	SourceUnknown Source = "unknown"
)

func DetectSource added in v0.16.13

func DetectSource() Source

DetectSource inspects the current process environment to decide how it was spawned. systemd injects INVOCATION_ID into every unit it starts, which is the most reliable signal that systemd owns this process. The caller (`<app> all`) records the result so later `status`/`stop` calls know the supervisor without re-deriving it from a different process.

func ReadSource added in v0.16.13

func ReadSource(p Paths) Source

ReadSource returns the recorded spawn Source, or SourceUnknown when the file is missing / unreadable.

type Status

type Status struct {
	Running bool
	PID     int
	Started time.Time // mtime of PID file as a best-effort start time
	LogFile string
	PIDFile string
}

Status reflects the running state of the daemon.

func Check

func Check(p Paths) (Status, error)

Check inspects the PID file and returns the current daemon state. Stale PID files (process no longer alive) are reported as not running; callers may then proceed with Start without manually cleaning up.

Jump to

Keyboard shortcuts

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