process

package
v0.0.1 Latest Latest
Warning

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

Go to latest
Published: Sep 28, 2025 License: MIT Imports: 19 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ReadPIDFileWithMeta

func ReadPIDFileWithMeta(path string) (int, *Spec, *PIDMeta, error)

ReadPIDFileWithMeta reads a PID file written by Process.WritePIDFile. Returns PID, optional Spec, and optional Meta (may be nil if absent or unparsable).

Types

type DetectorConfig

type DetectorConfig struct {
	Type    string `json:"type" mapstructure:"type"`
	Path    string `json:"path" mapstructure:"path"`
	Command string `json:"command" mapstructure:"command"`
}

DetectorConfig represents a detector configuration that can be parsed from config files

type FailureMode

type FailureMode string

FailureMode defines how to handle hook execution failures

const (
	FailureModeIgnore FailureMode = "ignore" // Continue regardless of hook failure
	FailureModeFail   FailureMode = "fail"   // Fail the entire operation if hook fails
	FailureModeRetry  FailureMode = "retry"  // Retry the hook on failure
)

type Hook

type Hook struct {
	Name        string        `json:"name" mapstructure:"name"`                 // Hook name for identification
	Command     string        `json:"command" mapstructure:"command"`           // Command to execute
	WorkDir     string        `json:"work_dir" mapstructure:"work_dir"`         // Working directory (optional)
	Env         []string      `json:"env" mapstructure:"env"`                   // Additional environment variables
	Timeout     time.Duration `json:"timeout" mapstructure:"timeout"`           // Execution timeout (default: 30s)
	FailureMode FailureMode   `json:"failure_mode" mapstructure:"failure_mode"` // How to handle failures
	RunMode     RunMode       `json:"run_mode" mapstructure:"run_mode"`         // Blocking or async execution
}

Hook represents a single lifecycle hook command

func (*Hook) DeepCopy

func (h *Hook) DeepCopy() Hook

DeepCopy creates a deep copy of a Hook

func (*Hook) GetDefaults

func (h *Hook) GetDefaults()

GetDefaults applies default values to hook configuration

func (*Hook) Validate

func (h *Hook) Validate() error

Validate validates a single hook configuration

type LifecycleHooks

type LifecycleHooks struct {
	PreStart  []Hook `json:"pre_start" mapstructure:"pre_start"`   // Before process starts
	PostStart []Hook `json:"post_start" mapstructure:"post_start"` // After process starts successfully
	PreStop   []Hook `json:"pre_stop" mapstructure:"pre_stop"`     // Before process stops
	PostStop  []Hook `json:"post_stop" mapstructure:"post_stop"`   // After process stops
}

LifecycleHooks defines hooks that run at different stages of process lifecycle

func (*LifecycleHooks) DeepCopy

func (lh *LifecycleHooks) DeepCopy() LifecycleHooks

DeepCopy creates a deep copy of LifecycleHooks

func (*LifecycleHooks) GetHooksForPhase

func (lh *LifecycleHooks) GetHooksForPhase(phase LifecyclePhase) []Hook

GetHooksForPhase returns hooks for a specific lifecycle phase

func (*LifecycleHooks) HasAnyHooks

func (lh *LifecycleHooks) HasAnyHooks() bool

HasAnyHooks returns true if there are any hooks defined

func (*LifecycleHooks) Validate

func (lh *LifecycleHooks) Validate() error

Validate validates the lifecycle hooks configuration

type LifecyclePhase

type LifecyclePhase string

LifecyclePhase represents different phases of process lifecycle

const (
	PhasePreStart  LifecyclePhase = "pre_start"
	PhasePostStart LifecyclePhase = "post_start"
	PhasePreStop   LifecyclePhase = "pre_stop"
	PhasePostStop  LifecyclePhase = "post_stop"
)

func (LifecyclePhase) String

func (p LifecyclePhase) String() string

String returns the string representation of the lifecycle phase

type PIDMeta

type PIDMeta struct {
	StartUnix int64 `json:"start_unix"`
}

PIDMeta holds additional identity information for a PID to avoid PID reuse issues. StartUnix is the process start time in Unix seconds (UTC/local agnostic for equality checks).

type Process

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

func New

func New(spec Spec) *Process

func (*Process) CloseWriters

func (r *Process) CloseWriters()

func (*Process) ConfigureCmd

func (r *Process) ConfigureCmd(mergedEnv []string) *exec.Cmd

ConfigureCmd builds and configures *exec.Cmd for this process using mergedEnv. It sets workdir, environment, stdio/logging, and process group attributes. Logging writers are prepared and stored via EnsureLogClosers.

func (*Process) CopyCmd

func (r *Process) CopyCmd() *exec.Cmd

func (*Process) DetectAlive

func (r *Process) DetectAlive() (bool, string)

DetectAlive probes liveness without accessing cmd to avoid races.

func (*Process) EnforceStartDuration

func (r *Process) EnforceStartDuration(d time.Duration) error

EnforceStartDuration waits until d ensuring process stays up; returns error if it exits early.

func (*Process) EnsureLogClosers

func (r *Process) EnsureLogClosers(stdout, stderr io.WriteCloser)

func (*Process) GetAutoStart

func (r *Process) GetAutoStart() bool

func (*Process) GetName

func (r *Process) GetName() string

func (*Process) GetSpec

func (r *Process) GetSpec() *Spec

func (*Process) Kill

func (r *Process) Kill() error

Kill sends SIGKILL to the process group and attempts to reap promptly.

func (*Process) MarkExited

func (r *Process) MarkExited(err error)

func (*Process) OutErrClosers

func (r *Process) OutErrClosers() (io.WriteCloser, io.WriteCloser)

func (*Process) RemovePIDFile

func (r *Process) RemovePIDFile()

RemovePIDFile best-effort

func (*Process) SeedPID

func (r *Process) SeedPID(pid int)

SeedPID seeds the internal PID (e.g., after manager restart) without changing running state. It also updates the Snapshot() PID for observability.

func (*Process) SetStarted

func (r *Process) SetStarted(cmd *exec.Cmd)

func (*Process) SetStopRequested

func (r *Process) SetStopRequested(v bool)

func (*Process) Snapshot

func (r *Process) Snapshot() Status

Snapshot returns a copy of the current status.

func (*Process) Stop

func (r *Process) Stop(_ time.Duration) error

Stop keeps backward compatibility with previous API. It sends SIGTERM and returns immediately. The wait parameter is ignored to preserve SRP; upper layers handle waiting and state.

func (*Process) StopRequested

func (r *Process) StopRequested() bool

func (*Process) StopWithSignal

func (r *Process) StopWithSignal(sig syscall.Signal) error

StopWithSignal sends the provided signal to the process group. It does not wait. If sending the signal fails, it falls back to Kill().

func (*Process) TryStart

func (r *Process) TryStart(cmd *exec.Cmd) error

TryStart atomically starts the command and updates internal state and PID file. It encapsulates cmd.Start + SetStarted + WritePIDFile to reduce races.

func (*Process) UpdateSpec

func (r *Process) UpdateSpec(s Spec)

UpdateSpec replaces the internal spec under lock.

func (*Process) WritePIDFile

func (r *Process) WritePIDFile()

type RunMode

type RunMode string

RunMode defines how hooks are executed

const (
	RunModeBlocking RunMode = "blocking" // Wait for hook completion before continuing
	RunModeAsync    RunMode = "async"    // Start hook and continue immediately
)

type Spec

type Spec struct {
	Name            string              `json:"name" mapstructure:"name"`
	Command         string              `json:"command" mapstructure:"command"`                   // command to start the process (shell)
	WorkDir         string              `json:"work_dir" mapstructure:"work_dir"`                 // optional working dir
	Env             []string            `json:"env" mapstructure:"env"`                           // optional extra env
	PIDFile         string              `json:"pid_file" mapstructure:"pid_file"`                 // optional pidfile path; if set a PIDFileDetector will be used
	Priority        int                 `json:"priority" mapstructure:"priority"`                 // startup priority (lower numbers start first, default 0)
	RetryCount      uint32              `json:"retry_count" mapstructure:"retry_count"`           // number of retries on start failure
	RetryInterval   time.Duration       `json:"retry_interval" mapstructure:"retry_interval"`     // interval between retries
	StartDuration   time.Duration       `json:"start_duration" mapstructure:"start_duration"`     // minimum time the process must stay up to be considered started
	AutoRestart     bool                `json:"auto_restart" mapstructure:"auto_restart"`         // restart automatically if the process dies unexpectedly
	RestartInterval time.Duration       `json:"restart_interval" mapstructure:"restart_interval"` // wait before attempting an auto-restart
	Instances       int                 `json:"instances" mapstructure:"instances"`               // number of instances to run concurrently (default 1)
	Detached        bool                `json:"detached" mapstructure:"detached"`                 // run in detached mode
	Detectors       []detector.Detector `json:"-" mapstructure:"-"`                               // excluded from mapstructure
	DetectorConfigs []DetectorConfig    `json:"detectors" mapstructure:"detectors"`               // for config parsing
	Log             logger.Config       `json:"log" mapstructure:"log"`                           // unified slog-based logging configuration
	Lifecycle       LifecycleHooks      `json:"lifecycle" mapstructure:"lifecycle"`               // lifecycle hooks for pre/post operations
}

Spec describes a process to be managed. All logging is now handled through slog-based structured logging.

func ReadPIDFile

func ReadPIDFile(path string) (int, *Spec, error)

ReadPIDFile is a compatibility wrapper returning only pid and spec.

func (*Spec) BuildCommand

func (s *Spec) BuildCommand() *exec.Cmd

BuildCommand constructs an *exec.Cmd for the given spec.Command. It avoids invoking a shell when not necessary, and it also respects an explicit shell invocation already present in the command string (e.g., "sh -c 'echo hi'"), avoiding double-wrapping with another shell.

func (*Spec) DeepCopy

func (s *Spec) DeepCopy() *Spec

func (*Spec) Validate

func (s *Spec) Validate() error

Validate enforces Spec invariants.

type Status

type Status struct {
	Name       string    `json:"name"`
	Running    bool      `json:"running"`
	PID        int       `json:"pid"`
	StartedAt  time.Time `json:"started_at"`
	StoppedAt  time.Time `json:"stopped_at"`
	ExitErr    error     `json:"exit_error,omitempty"`
	DetectedBy string    `json:"detected_by"`
	Restarts   uint32    `json:"restarts"`
	State      string    `json:"state"` // State machine state: stopped, starting, running, stopping
}

Status mirrors process.Status to avoid import cycle; kept minimal for internal use.

Jump to

Keyboard shortcuts

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