procutil

package
v0.6.1 Latest Latest
Warning

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

Go to latest
Published: Nov 12, 2026 License: MIT Imports: 22 Imported by: 0

Documentation

Overview

Package procutil provides shared process helpers for Compozy runtime components.

Index

Constants

View Source
const InternalHandoffEnvPrefix = "COMPOZY_INTERNAL_"

InternalHandoffEnvPrefix marks variables that carry one-shot handoff state between a CompozyOS process and the specific process it launches. They must never reach ordinary children.

Variables

View Source
var ErrAccountShellUnavailable = errors.New("procutil: account login shell is unavailable")

ErrAccountShellUnavailable reports that the account database names no usable login shell.

View Source
var ErrProcessIdentityGone = errors.New("procutil: process identity is gone")

ErrProcessIdentityGone distinguishes a vanished process from unreadable identity data.

Functions

func AccountLoginShell

func AccountLoginShell(ctx context.Context) (string, error)

AccountLoginShell returns the login shell recorded for the current user's account.

A daemon started by launchd, the desktop app, or a service manager inherits whatever SHELL its launcher had, which is not necessarily the shell the operator chose with chsh. The account database (directory services on macOS, passwd/NSS elsewhere) is the authority for that choice.

func Alive

func Alive(pid int) bool

Alive reports whether a process with the given PID is running.

func ConfigureCommandProcessGroup

func ConfigureCommandProcessGroup(cmd *exec.Cmd)

ConfigureCommandProcessGroup starts the command in its own process group so callers can signal and observe the full descendant tree.

func ConfigureCommandSession

func ConfigureCommandSession(cmd *exec.Cmd)

ConfigureCommandSession starts the command in a new Unix session.

func ConfigureCommandTerminalSession

func ConfigureCommandTerminalSession(cmd *exec.Cmd)

ConfigureCommandTerminalSession starts the command in a new session with a controlling terminal.

func CreationProcessToken

func CreationProcessToken(pid int) string

CreationProcessToken preserves timestamp identity when kernel identity is unavailable at creation. Existing tokenized records must still propagate lookup errors instead of downgrading identity.

func CurrentProcessNiceness

func CurrentProcessNiceness() (int, error)

CurrentProcessNiceness reports the niceness of the calling process.

func EnrichProcesses

func EnrichProcesses(ctx context.Context, rows []ScannedProcess)

EnrichProcesses adds best-effort cwd and listener metadata to already attributed rows.

func FilteredDaemonEnv

func FilteredDaemonEnv(base []string) []string

FilteredDaemonEnv returns process environment entries safe to pass to child processes. It drops credential-shaped variables and internal handoff variables.

func InternalHandoffEnvName

func InternalHandoffEnvName(name string) bool

InternalHandoffEnvName reports whether name is an internal handoff variable.

func IsProcessMissingError

func IsProcessMissingError(err error) bool

IsProcessMissingError reports whether a signal failed because its target no longer exists.

func IsolatedDaemonEnv

func IsolatedDaemonEnv(base []string) []string

IsolatedDaemonEnv returns only the fixed operational environment allowlist needed to launch local subprocesses. It intentionally drops all non-allowlisted daemon variables, including provider CLI credentials.

func KillCommandProcessGroupAndWait

func KillCommandProcessGroupAndWait(cmd *exec.Cmd, timeout time.Duration) error

KillCommandProcessGroupAndWait forcefully terminates any remaining members of the command's process group, then waits for the group to disappear.

func KillProcessGroupIDAndWait

func KillProcessGroupIDAndWait(pgid int, timeout time.Duration) error

KillProcessGroupIDAndWait forcefully terminates any remaining members of a process group.

func MatchesObservedStartTime

func MatchesObservedStartTime(observed, startedAt time.Time) bool

MatchesObservedStartTime compares persisted and kernel timestamps with launcher skew tolerance.

func MatchesProcessIdentity

func MatchesProcessIdentity(pid int, startedAt time.Time, token string) (bool, error)

MatchesProcessIdentity prefers a persisted kernel identity when available.

func MatchesStartTime

func MatchesStartTime(pid int, startedAt time.Time) bool

MatchesStartTime reports whether pid currently belongs to a process whose observed start time matches the recorded value closely enough to account for launcher-vs-kernel timestamp skew.

func OwnsFileLock

func OwnsFileLock(pid int, path string) (_ bool, returnErr error)

OwnsFileLock verifies Linux kernel lock ownership independently of wall-clock drift.

func ProcessGroupNiceness

func ProcessGroupNiceness(pgid int) (int, error)

ProcessGroupNiceness reports the niceness of the least-niced member of the process group.

func ProcessToken

func ProcessToken(pid int) (string, error)

ProcessToken identifies a process without converting kernel ticks to wall time.

func RegisterCommandProcessGroup

func RegisterCommandProcessGroup(_ *exec.Cmd) error

RegisterCommandProcessGroup keeps Unix parity with Windows job registration.

func ResolveLoginShellPath

func ResolveLoginShellPath(
	ctx context.Context,
	environment []string,
	options LoginShellPathOptions,
) (string, error)

ResolveLoginShellPath returns the PATH produced by the operator's login shell.

func SensitiveEnvName

func SensitiveEnvName(name string) bool

SensitiveEnvName reports whether an environment variable name commonly carries credentials.

func SetProcessGroupNiceness

func SetProcessGroupNiceness(pgid int, niceness int) error

SetProcessGroupNiceness lowers the CPU scheduling priority of every process in the process group to at least niceness. Descendants forked after the call returns inherit the value. A child whose fork is still in flight during the call can keep its parent's previous niceness: the kernel copies the value before the child joins the group, and setpriority(PRIO_PGRP) only reaches joined members. No userspace re-check can observe that child, so callers that need complete coverage must apply niceness before the group can fork (Linux launch paths use StartWithNiceness). Unprivileged callers can only raise niceness, so a group already at or above niceness (for example under a niced daemon) is left unchanged instead of failing with a permission error.

func Signal

func Signal(pid int, sig syscall.Signal) error

Signal sends sig to the process with the given PID.

func SignalCommandProcessGroup

func SignalCommandProcessGroup(cmd *exec.Cmd, sig syscall.Signal) error

SignalCommandProcessGroup delivers sig to the command's process group.

func SignalProcessGroupID

func SignalProcessGroupID(pgid int, sig syscall.Signal) error

SignalProcessGroupID delivers sig to the process group identified by pgid.

func SignalProcessGroupIDStrict

func SignalProcessGroupIDStrict(pgid int, sig syscall.Signal) error

SignalProcessGroupIDStrict reports when no member remains to receive the signal.

func StartWithNiceness

func StartWithNiceness(niceness int, start func() error) (priorityErr, startErr error)

StartWithNiceness starts on a disposable Linux thread so the child inherits priority before exec.

func StartedAt

func StartedAt(pid int) (time.Time, error)

StartedAt reports the observed start time for pid using the host process table.

func VerifyProcessExit

func VerifyProcessExit(pid int, startedAt time.Time) (bool, error)

VerifyProcessExit checks whether the recorded process identity is gone. A reused PID proves the original process exited; a failed lookup does not.

func WaitForCommandProcessGroupExit

func WaitForCommandProcessGroupExit(cmd *exec.Cmd, timeout time.Duration) error

WaitForCommandProcessGroupExit blocks until the command's process group no longer exists, which ensures descendants are gone before returning.

func WaitForProcessGroupIDExit

func WaitForProcessGroupIDExit(pgid int, timeout time.Duration) error

WaitForProcessGroupIDExit blocks until the process group identified by pgid no longer exists.

func WatchParentExit

func WatchParentExit(ctx context.Context, poll time.Duration, onExit func())

WatchParentExit calls onExit once if this process is reparented because its original parent exited, then returns; it stops early when ctx is done. It lets a child self-terminate when its launcher dies abruptly (SIGKILL, test timeout, Ctrl-C) — Darwin has no Pdeathsig. On Windows the kill-on-close job object (RegisterCommandProcessGroup) handles this, so that build is a no-op.

func WithoutInternalHandoffEnv

func WithoutInternalHandoffEnv(env []string) []string

WithoutInternalHandoffEnv returns a copy of env without internal handoff variables.

Types

type DetachedLaunchRequest

type DetachedLaunchRequest struct {
	Binary  string
	Args    []string
	Sandbox []string
	LogPath string
}

DetachedLaunchRequest describes one detached process launch with log capture.

type DetachedProcess

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

DetachedProcess wraps a detached child process whose stderr/stdout were appended to a log file.

func SpawnDetachedLoggedProcess

func SpawnDetachedLoggedProcess(
	ctx context.Context,
	req DetachedLaunchRequest,
) (*DetachedProcess, error)

SpawnDetachedLoggedProcess launches one detached child process whose stdout/stderr are appended to req.LogPath.

func (*DetachedProcess) Done

func (p *DetachedProcess) Done() <-chan struct{}

Done closes after the detached child has been reaped.

func (*DetachedProcess) PID

func (p *DetachedProcess) PID() int

PID reports the launched process id.

func (*DetachedProcess) Terminate

func (p *DetachedProcess) Terminate() error

Terminate stops the detached child when it has not exited yet.

func (*DetachedProcess) Wait

func (p *DetachedProcess) Wait() error

Wait blocks until the detached process exits and attaches recent log output to failures.

type LoginShellPathOptions

type LoginShellPathOptions struct {
	Timeout        time.Duration
	MaxOutputBytes int
	// AccountShell resolves the account's recorded login shell. Nil uses AccountLoginShell.
	AccountShell func(context.Context) (string, error)
}

LoginShellPathOptions bounds login shell PATH resolution.

type ProcessSnapshot

type ProcessSnapshot struct {
	Supported bool
	ScannedAt time.Time
	Duration  time.Duration
	Processes []ScannedProcess
}

func ScanProcessTree

func ScanProcessTree(ctx context.Context) (ProcessSnapshot, error)

ScanProcessTree is the inexpensive lineage pass used during active tool calls.

func ScanProcesses

func ScanProcesses(ctx context.Context) (ProcessSnapshot, error)

type ProcessTermination

type ProcessTermination struct {
	Outcome string
	Err     error
}

func TerminateObservedProcess

func TerminateObservedProcess(ctx context.Context, target ScannedProcess, grace time.Duration) ProcessTermination

TerminateObservedProcess accepts a durable lineage identity verified by the session process service. Lineage authority permits only an individual PID signal, never an inferred group signal.

func TerminateScannedProcess

func TerminateScannedProcess(ctx context.Context, target ScannedProcess, grace time.Duration) ProcessTermination

TerminateScannedProcess never uses the launch-time skew tolerance for user-selected process identities.

type ScannedProcess

type ScannedProcess struct {
	PID, PPID, PGID                     int
	StartedAt                           time.Time
	KernelToken                         string
	SessionID, Home, Profile, Workspace string
	Argv0, Command, CWD                 string
	Ports                               []int
	Zombie                              bool
}

ScannedProcess retains only attribution markers, never the complete environment.

func InspectProcess

func InspectProcess(pid int) (ScannedProcess, error)

Jump to

Keyboard shortcuts

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