servicemgr

package
v0.167.0 Latest Latest
Warning

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

Go to latest
Published: Oct 17, 2026 License: MIT Imports: 30 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 servicemgr owns the local metadata and coordination primitives used by the native Windows and Linux service backends.

Index

Constants

View Source
const (
	SpecSchema     = 1
	DefaultName    = "gofer-serve"
	EnvManagedSpec = "GOFER_MANAGED_SPEC"
)
View Source
const StateSchema = 1
View Source
const UpgradeSchema = 1

Variables

View Source
var ErrIdentityMismatch = errors.New("service process identity mismatch")
View Source
var ErrLockBusy = errors.New("service instance is busy")
View Source
var ErrRunningSpecChange = errors.New("stop the running service before changing its registration")

Functions

func OwnsListeningPort

func OwnsListeningPort(pid int, host string, port uint16) (bool, error)

OwnsListeningPort binds a health probe to the already verified server PID. Both native backends implement the platform-specific socket ownership check.

func RunUpgradeHelper

func RunUpgradeHelper(ctx context.Context, receiptPath string) error

RunUpgradeHelper is the private process entry. It must see a precommitted receipt and gate, publish its own identity, then wait for the server bridge's durable accepted transition. No old process is stopped before that point.

func RuntimeDirFor

func RuntimeDirFor(configDir, explicitConfig string) (string, error)

RuntimeDirFor follows the existing serve -c rule: only an explicit -c puts serve.pid beside that file. GOFER_CONFIG affects file selection, not this runtime path. Callers supply the selected ConfigDir independently.

func SystemdJournal

func SystemdJournal(ctx context.Context, m *Manager, lines int) ([]byte, error)

SystemdJournal reads the native journal without routing through a shell.

func SystemdRegister

func SystemdRegister(ctx context.Context, m *Manager, spec Spec) error

SystemdRegister installs and enables an owned unit. It never starts it.

func SystemdStop

func SystemdStop(ctx context.Context, m *Manager) error

SystemdStop stops through systemctl so Restart=on-failure cannot revive serve.

func SystemdUninstall

func SystemdUninstall(ctx context.Context, m *Manager) error

SystemdUninstall only removes an owned unit. Config, logs and binary remain.

Types

type Backend

type Backend string
const (
	BackendWindowsTask   Backend = "windows-task"
	BackendSystemdSystem Backend = "systemd-system"
	BackendSystemdUser   Backend = "systemd-user"
)

type Lock

type Lock struct {
	// contains filtered or unexported fields
}

Lock holds an OS file lock for an entire lifecycle operation. The lock file is intentionally retained after release: removing it could let a contender create a different inode while another process still holds the old one.

func AcquireLock

func AcquireLock(path string) (*Lock, error)

func (*Lock) Release

func (l *Lock) Release() error

type Manager

type Manager struct {
	ConfigDir string
	Name      string
}

Manager locates one instance's metadata. Platform backends extend its lifecycle; the shared core does not write OS registrations.

func NewManager

func NewManager(configDir, name string) (*Manager, error)

func (*Manager) AcceptUpgradeControl

func (m *Manager) AcceptUpgradeControl(id, verifiedSourceJobID string) error

AcceptUpgradeControl is the durable CAS used only after the server bridge has verified the source job and drained all other work. The helper has to prove independent liveness first; it never grants itself this transition.

func (*Manager) Acquire

func (m *Manager) Acquire() (*Lock, error)

func (*Manager) InspectServer

func (m *Manager) InspectServer() (daemon.ProcessIdentity, error)

InspectServer reads the recorded pid and checks the live process against the spec and the required recorded creation identity. A native backend must separately verify its task/unit command line and config-file ownership.

func (*Manager) LoadSpec

func (m *Manager) LoadSpec() (Spec, error)

func (*Manager) LoadState

func (m *Manager) LoadState() (State, error)

func (*Manager) LoadUpgradeControl

func (m *Manager) LoadUpgradeControl() (UpgradeControl, error)

func (*Manager) LoadUpgradeReceipt

func (m *Manager) LoadUpgradeReceipt(id string) (UpgradeReceipt, error)

func (*Manager) LockPath

func (m *Manager) LockPath() string

func (*Manager) SaveSpec

func (m *Manager) SaveSpec(spec Spec) error

SaveSpec is a registration update. Its caller holds Acquire across the full native task/unit transaction; this method also rejects changes while either recorded process remains live.

func (*Manager) SaveState

func (m *Manager) SaveState(state State) error

func (*Manager) SaveUpgradeControl

func (m *Manager) SaveUpgradeControl(control UpgradeControl) error

SaveUpgradeControl atomically updates the gate. The caller holds m.Acquire while creating or transitioning a transaction; readers never see half JSON.

func (*Manager) SaveUpgradeReceipt

func (m *Manager) SaveUpgradeReceipt(receipt UpgradeReceipt) error

func (*Manager) SpecPath

func (m *Manager) SpecPath() string

func (*Manager) StatePath

func (m *Manager) StatePath() string

func (*Manager) UpgradeControlPath

func (m *Manager) UpgradeControlPath() string

func (*Manager) UpgradeReceiptPath

func (m *Manager) UpgradeReceiptPath(id string) (string, error)

func (*Manager) VerifyUpgradeTarget

func (m *Manager) VerifyUpgradeTarget(ctx context.Context) error

VerifyUpgradeTarget uses the platform's owned task/unit and current process identity. The server drain bridge calls it before accepting a transaction.

type ServeOptions

type ServeOptions struct {
	Addr            string `json:"addr,omitempty"`
	NoWeb           bool   `json:"no_web,omitempty"`
	WebDir          string `json:"web_dir,omitempty"`
	AllowEmptyToken bool   `json:"allow_empty_token,omitempty"`
}

ServeOptions is an allowlist of non-secret arguments. In particular there is no token or arbitrary argument list in the durable spec.

type Spec

type Spec struct {
	SchemaVersion     int          `json:"schema_version"`
	Backend           Backend      `json:"backend"`
	Name              string       `json:"name"`
	Owner             string       `json:"owner"`
	Exe               string       `json:"exe"`
	WorkDir           string       `json:"work_dir"`
	ConfigFile        string       `json:"config_file"`
	ConfigDir         string       `json:"config_dir"`
	RuntimeDir        string       `json:"runtime_dir"`
	RunAs             string       `json:"run_as,omitempty"`
	Elevated          bool         `json:"elevated,omitempty"`
	Serve             ServeOptions `json:"serve"`
	RegisteredVersion string       `json:"registered_version,omitempty"`
}

Spec is the durable, non-secret description of one managed serve instance. RuntimeDir is recorded separately because an explicit -c puts serve.pid and serve.log beside that config file, which can differ from ConfigDir.

func LoadSpec

func LoadSpec(path string) (Spec, error)

func (Spec) CheckFiles

func (s Spec) CheckFiles() error

CheckFiles is the registration preflight. config.Load intentionally accepts a missing explicit -c for config editing; a managed serve cannot use it.

func (Spec) ServerArgs

func (s Spec) ServerArgs() ([]string, error)

ServerArgs produces only known serve flags; no caller-supplied free-form args or credentials can be serialized into an OS task/unit command line.

func (Spec) Validate

func (s Spec) Validate() error

type State

type State struct {
	SchemaVersion      int                    `json:"schema_version"`
	Name               string                 `json:"name"`
	StopRequested      bool                   `json:"stop_requested"`
	NativeInvocationID string                 `json:"native_invocation_id,omitempty"`
	Supervisor         daemon.ProcessIdentity `json:"supervisor,omitempty"`
	Server             daemon.ProcessIdentity `json:"server,omitempty"`
}

State is local control state, not an OS manager's status source. A backend still has to verify its task/unit and the process before reporting success.

func LoadState

func LoadState(path string) (State, error)

func (State) Validate

func (s State) Validate() error

type SystemdStatus

type SystemdStatus struct {
	Installed      bool
	Enabled        bool
	Active         bool
	SubState       string
	MainPID        int
	Server         daemon.ProcessIdentity
	UnitPath       string
	ApplicationLog string
}

SystemdStatus combines the native unit state and verified process identity.

func SystemdRestart

func SystemdRestart(ctx context.Context, m *Manager) (SystemdStatus, error)

func SystemdStart

func SystemdStart(ctx context.Context, m *Manager) (SystemdStatus, error)

SystemdStart starts a previously registered unit and verifies its process.

func SystemdStatusOf

func SystemdStatusOf(ctx context.Context, m *Manager) (SystemdStatus, error)

type UpgradeControl

type UpgradeControl struct {
	SchemaVersion    int          `json:"schema_version"`
	UpgradeID        string       `json:"upgrade_id"`
	Name             string       `json:"name"`
	SourceJobID      string       `json:"source_job_id,omitempty"`
	InitiatorPID     int          `json:"initiator_pid"`
	InitiatorStartID string       `json:"initiator_start_id"`
	Deadline         time.Time    `json:"deadline"`
	Phase            UpgradePhase `json:"phase"`
}

UpgradeControl is the local admission/drain gate. SourceJobID is informational until the job bridge checks it against trusted current-job metadata; the helper never treats a caller-supplied ID as authorization to ignore a job.

func (UpgradeControl) Validate

func (c UpgradeControl) Validate() error

type UpgradePhase

type UpgradePhase string
const (
	UpgradeDraining   UpgradePhase = "draining"
	UpgradeAccepted   UpgradePhase = "accepted"
	UpgradeSwitching  UpgradePhase = "switching"
	UpgradeSucceeded  UpgradePhase = "succeeded"
	UpgradeRolledBack UpgradePhase = "rolled_back"
	UpgradeFailed     UpgradePhase = "failed"
)

type UpgradeReceipt

type UpgradeReceipt struct {
	SchemaVersion    int                    `json:"schema_version"`
	UpgradeID        string                 `json:"upgrade_id"`
	Name             string                 `json:"name"`
	Phase            UpgradePhase           `json:"phase"`
	SourceJobID      string                 `json:"source_job_id,omitempty"`
	CandidateSHA256  string                 `json:"candidate_sha256"`
	CandidateVersion string                 `json:"candidate_version"`
	PreviousVersion  string                 `json:"previous_version,omitempty"`
	CandidatePath    string                 `json:"candidate_path"`
	Helper           daemon.ProcessIdentity `json:"helper,omitempty"`
	StartedAt        time.Time              `json:"started_at"`
	AcceptedAt       *time.Time             `json:"accepted_at,omitempty"`
	FinishedAt       *time.Time             `json:"finished_at,omitempty"`
	Error            string                 `json:"error,omitempty"`
}

UpgradeReceipt survives process restarts and is the source of truth for an upgrade outcome. An interrupted nonterminal phase is never reported as done.

func BeginUpgrade

func BeginUpgrade(ctx context.Context, m *Manager, request UpgradeRequest) (UpgradeReceipt, error)

BeginUpgrade prepares and launches a helper; it returns only after that independent process has recorded its own live identity. The server bridge still has to drain and AcceptUpgradeControl before any stop or switch.

func WaitUpgradeAccepted

func WaitUpgradeAccepted(ctx context.Context, m *Manager, id string) (UpgradeReceipt, error)

WaitUpgradeAccepted waits only for the bridge's durable drain/identity ACK. A job caller must return this ID and exit; its helper waits for that exact initiator process to exit before stopping the old server.

func (UpgradeReceipt) Validate

func (r UpgradeReceipt) Validate() error

type UpgradeRequest

type UpgradeRequest struct {
	CandidatePath    string
	HelperExecutable string // internal current management CLI image; never a user-facing flag
	Size             int64
	SHA256           string
	SourceJobID      string // untrusted claim until the server bridge checks local runner PID and birth
	Deadline         time.Time
}

Jump to

Keyboard shortcuts

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