daemon

package
v0.6.3 Latest Latest
Warning

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

Go to latest
Published: Dec 15, 2025 License: MIT Imports: 23 Imported by: 0

Documentation

Overview

Package daemon provides the stateful daemon process that manages processes, proxies, and traffic logs across client connections.

Index

Constants

View Source
const Version = "0.1.0"

Version is the daemon version.

Variables

View Source
var (
	// ErrNotConnected is returned when trying to use a closed client.
	ErrNotConnected = errors.New("not connected to daemon")
	// ErrServerError is returned when the daemon returns an error response.
	ErrServerError = errors.New("daemon error")
)
View Source
var (
	// ErrReconnecting is returned when an operation is attempted during reconnection.
	ErrReconnecting = errors.New("client is reconnecting")
	// ErrShutdown is returned when an operation is attempted after shutdown.
	ErrShutdown = errors.New("client has been shut down")
)
View Source
var (
	// ErrSocketInUse is returned when the socket is already in use.
	ErrSocketInUse = errors.New("socket already in use")
	// ErrSocketNotFound is returned when the socket doesn't exist.
	ErrSocketNotFound = errors.New("socket not found")
	// ErrDaemonRunning is returned when another daemon is already running.
	ErrDaemonRunning = errors.New("daemon already running")
)

Functions

func CleanupZombieDaemons

func CleanupZombieDaemons(socketPath string) int

CleanupZombieDaemons finds and kills any zombie daemon processes that aren't responding on their socket. This is called during startup to clean up any leftover processes from previous runs.

func Connect

func Connect(path string) (net.Conn, error)

Connect attempts to connect to an existing daemon socket.

func DefaultSocketPath

func DefaultSocketPath() string

DefaultSocketPath returns the default socket path for the current platform.

func DefaultStatePath

func DefaultStatePath() string

DefaultStatePath returns the default state file path.

func IsDaemonRunning

func IsDaemonRunning(socketPath string) bool

IsDaemonRunning checks if the daemon is running at the given socket path.

func IsRunning

func IsRunning(path string) bool

IsRunning checks if a daemon is running at the given socket path.

func StopDaemon

func StopDaemon(socketPath string) error

StopDaemon connects to a running daemon and requests shutdown.

Types

type AutoStartClient

type AutoStartClient struct {
	*Client
	// contains filtered or unexported fields
}

AutoStartClient creates a client that auto-starts the daemon if needed.

func NewAutoStartClient

func NewAutoStartClient(config AutoStartConfig) *AutoStartClient

NewAutoStartClient creates a new auto-start client.

func (*AutoStartClient) Connect

func (c *AutoStartClient) Connect() error

Connect connects to the daemon, starting it if necessary.

type AutoStartConfig

type AutoStartConfig struct {
	// SocketPath is the socket path to connect to.
	SocketPath string
	// DaemonPath is the path to the daemon executable.
	DaemonPath string
	// StartTimeout is how long to wait for the daemon to start.
	StartTimeout time.Duration
	// RetryInterval is how long to wait between connection attempts.
	RetryInterval time.Duration
	// MaxRetries is the maximum number of connection attempts.
	MaxRetries int
}

AutoStartConfig holds configuration for auto-starting the daemon.

func DefaultAutoStartConfig

func DefaultAutoStartConfig() AutoStartConfig

DefaultAutoStartConfig returns sensible defaults.

type BufferedWriter

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

BufferedWriter wraps a connection with buffered writing.

func NewBufferedWriter

func NewBufferedWriter(conn net.Conn) *BufferedWriter

NewBufferedWriter creates a buffered writer for a connection.

func (*BufferedWriter) Flush

func (w *BufferedWriter) Flush() error

Flush flushes the buffer to the connection.

func (*BufferedWriter) Write

func (w *BufferedWriter) Write(p []byte) (n int, err error)

Write writes data to the buffer.

type Client

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

Client is a client for communicating with the daemon over the socket.

func EnsureDaemonRunning

func EnsureDaemonRunning(config AutoStartConfig) (*Client, error)

EnsureDaemonRunning ensures the daemon is running, starting it if needed. Returns a connected client.

func NewClient

func NewClient(opts ...ClientOption) *Client

NewClient creates a new daemon client.

func (*Client) BroadcastActivity

func (c *Client) BroadcastActivity(active bool, proxyIDs ...string) error

BroadcastActivity broadcasts an activity state update to connected browsers via specified proxies. If proxyIDs is empty, broadcasts to all proxies (backward compatibility).

func (*Client) ChaosAddRule

func (c *Client) ChaosAddRule(proxyID string, rule protocol.ChaosRuleConfig) (map[string]interface{}, error)

ChaosAddRule adds a single rule to a proxy's chaos engine.

func (*Client) ChaosClear

func (c *Client) ChaosClear(proxyID string) (map[string]interface{}, error)

ChaosClear clears all chaos rules and resets stats for a proxy.

func (*Client) ChaosDisable

func (c *Client) ChaosDisable(proxyID string) (map[string]interface{}, error)

ChaosDisable disables chaos injection on a proxy.

func (*Client) ChaosEnable

func (c *Client) ChaosEnable(proxyID string) (map[string]interface{}, error)

ChaosEnable enables chaos injection on a proxy.

func (*Client) ChaosListPresets

func (c *Client) ChaosListPresets() (map[string]interface{}, error)

ChaosListPresets returns the list of available chaos presets.

func (*Client) ChaosListRules

func (c *Client) ChaosListRules(proxyID string) (map[string]interface{}, error)

ChaosListRules lists all chaos rules for a proxy.

func (*Client) ChaosPreset

func (c *Client) ChaosPreset(proxyID, preset string) (map[string]interface{}, error)

ChaosPreset applies a preset chaos configuration to a proxy.

func (*Client) ChaosRemoveRule

func (c *Client) ChaosRemoveRule(proxyID, ruleID string) (map[string]interface{}, error)

ChaosRemoveRule removes a rule from a proxy's chaos engine.

func (*Client) ChaosSet

func (c *Client) ChaosSet(proxyID string, config protocol.ChaosConfigPayload) (map[string]interface{}, error)

ChaosSet sets the full chaos configuration on a proxy.

func (*Client) ChaosStats

func (c *Client) ChaosStats(proxyID string) (map[string]interface{}, error)

ChaosStats gets chaos statistics for a proxy.

func (*Client) ChaosStatus

func (c *Client) ChaosStatus(proxyID string) (map[string]interface{}, error)

ChaosStatus gets the chaos status of a proxy.

func (*Client) Close

func (c *Client) Close() error

Close closes the connection to the daemon.

func (*Client) Connect

func (c *Client) Connect() error

Connect connects to the daemon.

func (*Client) CurrentPageClear

func (c *Client) CurrentPageClear(proxyID string) error

CurrentPageClear clears page sessions.

func (*Client) CurrentPageGet

func (c *Client) CurrentPageGet(proxyID, sessionID string) (map[string]interface{}, error)

CurrentPageGet gets details for a specific page session.

func (*Client) CurrentPageList

func (c *Client) CurrentPageList(proxyID string) (map[string]interface{}, error)

CurrentPageList lists active page sessions.

func (*Client) Detect

func (c *Client) Detect(path string) (map[string]interface{}, error)

Detect detects the project type at the given path.

func (*Client) Info

func (c *Client) Info() (*DaemonInfo, error)

Info retrieves daemon information.

func (*Client) IsConnected

func (c *Client) IsConnected() bool

IsConnected returns whether the client is connected.

func (*Client) OverlayClear

func (c *Client) OverlayClear() error

OverlayClear clears the overlay endpoint configuration.

func (*Client) OverlayGet

func (c *Client) OverlayGet() (map[string]interface{}, error)

OverlayGet gets the current overlay endpoint configuration.

func (*Client) OverlaySet

func (c *Client) OverlaySet(endpoint string) (map[string]interface{}, error)

OverlaySet sets the overlay endpoint URL. The endpoint should be the full URL, e.g., "http://127.0.0.1:19191".

func (*Client) Ping

func (c *Client) Ping() error

Ping sends a ping to the daemon and waits for a pong response.

func (*Client) ProcCleanupPort

func (c *Client) ProcCleanupPort(port int) (map[string]interface{}, error)

ProcCleanupPort kills processes on a specific port.

func (*Client) ProcList

func (c *Client) ProcList(dirFilter protocol.DirectoryFilter) (map[string]interface{}, error)

ProcList lists all processes.

func (*Client) ProcOutput

func (c *Client) ProcOutput(processID string, filter protocol.OutputFilter) (string, error)

ProcOutput gets the output of a process.

func (*Client) ProcStatus

func (c *Client) ProcStatus(processID string) (map[string]interface{}, error)

ProcStatus gets the status of a process.

func (*Client) ProcStop

func (c *Client) ProcStop(processID string, force bool) (map[string]interface{}, error)

ProcStop stops a process.

func (*Client) ProxyExec

func (c *Client) ProxyExec(id, code string) (map[string]interface{}, error)

ProxyExec executes JavaScript in connected browsers.

func (*Client) ProxyList

func (c *Client) ProxyList(dirFilter protocol.DirectoryFilter) (map[string]interface{}, error)

ProxyList lists all proxies.

func (*Client) ProxyLogClear

func (c *Client) ProxyLogClear(proxyID string) error

ProxyLogClear clears proxy logs.

func (*Client) ProxyLogQuery

func (c *Client) ProxyLogQuery(proxyID string, filter protocol.LogQueryFilter) (map[string]interface{}, error)

ProxyLogQuery queries proxy logs.

func (*Client) ProxyLogStats

func (c *Client) ProxyLogStats(proxyID string) (map[string]interface{}, error)

ProxyLogStats gets proxy log statistics.

func (*Client) ProxyStart

func (c *Client) ProxyStart(id, targetURL string, port, maxLogSize int, path string) (map[string]interface{}, error)

ProxyStart starts a reverse proxy.

func (*Client) ProxyStartWithConfig

func (c *Client) ProxyStartWithConfig(id, targetURL string, port, maxLogSize int, config ProxyStartConfig) (map[string]interface{}, error)

ProxyStartWithConfig starts a reverse proxy with extended configuration.

func (*Client) ProxyStatus

func (c *Client) ProxyStatus(id string) (map[string]interface{}, error)

ProxyStatus gets the status of a proxy.

func (*Client) ProxyStop

func (c *Client) ProxyStop(id string) error

ProxyStop stops a reverse proxy.

func (*Client) ProxyToast

func (c *Client) ProxyToast(id string, toast protocol.ToastConfig) (map[string]interface{}, error)

ProxyToast sends a toast notification to connected browsers.

func (*Client) Run

func (c *Client) Run(config protocol.RunConfig) (map[string]interface{}, error)

Run starts a process on the daemon.

func (*Client) Shutdown

func (c *Client) Shutdown() error

Shutdown requests the daemon to shut down.

func (*Client) TunnelList

func (c *Client) TunnelList() (map[string]interface{}, error)

TunnelList lists all active tunnels.

func (*Client) TunnelStart

func (c *Client) TunnelStart(config protocol.TunnelStartConfig) (map[string]interface{}, error)

TunnelStart starts a tunnel for a local port.

func (*Client) TunnelStatus

func (c *Client) TunnelStatus(id string) (map[string]interface{}, error)

TunnelStatus gets the status of a tunnel.

func (*Client) TunnelStop

func (c *Client) TunnelStop(id string) error

TunnelStop stops a running tunnel.

type ClientOption

type ClientOption func(*Client)

ClientOption configures a Client.

func WithSocketPath

func WithSocketPath(path string) ClientOption

WithSocketPath sets the socket path for the client.

func WithTimeout

func WithTimeout(d time.Duration) ClientOption

WithTimeout sets the default timeout for operations.

type Connection

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

Connection represents a client connection to the daemon.

func (*Connection) Close

func (c *Connection) Close() error

Close closes the connection.

func (*Connection) Handle

func (c *Connection) Handle(ctx context.Context)

Handle processes commands from the client until disconnect or error.

type Daemon

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

Daemon is the main daemon process that manages state across client connections.

func New

func New(config DaemonConfig) *Daemon

New creates a new daemon instance.

func (*Daemon) Info

func (d *Daemon) Info() DaemonInfo

Info returns daemon information.

func (*Daemon) OverlayEndpoint

func (d *Daemon) OverlayEndpoint() string

OverlayEndpoint returns the current overlay endpoint URL, or empty string if not set.

func (*Daemon) ProcessManager

func (d *Daemon) ProcessManager() *process.ProcessManager

ProcessManager returns the process manager.

func (*Daemon) ProxyManager

func (d *Daemon) ProxyManager() *proxy.ProxyManager

ProxyManager returns the proxy manager.

func (*Daemon) SetOverlayEndpoint

func (d *Daemon) SetOverlayEndpoint(endpoint string)

SetOverlayEndpoint sets the overlay endpoint URL and updates all existing proxies. The endpoint should be the full URL, e.g., "http://127.0.0.1:19191". Pass an empty string to disable overlay forwarding.

func (*Daemon) Start

func (d *Daemon) Start() error

Start starts the daemon and begins accepting connections.

func (*Daemon) StateManager

func (d *Daemon) StateManager() *StateManager

StateManager returns the state manager (may be nil if persistence is disabled).

func (*Daemon) Stop

func (d *Daemon) Stop(ctx context.Context) error

Stop gracefully shuts down the daemon.

func (*Daemon) TunnelManager

func (d *Daemon) TunnelManager() *tunnel.Manager

TunnelManager returns the tunnel manager.

func (*Daemon) Wait

func (d *Daemon) Wait()

Wait blocks until the daemon stops.

type DaemonConfig

type DaemonConfig struct {
	// Socket configuration
	SocketPath string

	// Process manager configuration
	ProcessConfig process.ManagerConfig

	// Max concurrent clients (0 = unlimited)
	MaxClients int

	// Connection read timeout (0 = no timeout)
	ReadTimeout time.Duration

	// Connection write timeout (0 = no timeout)
	WriteTimeout time.Duration

	// OverlayEndpoint is the URL of the agnt overlay server for forwarding events.
	// Example: "http://127.0.0.1:19191"
	// When set, proxies will forward panel messages, sketches, etc. to the overlay.
	OverlayEndpoint string

	// EnableStatePersistence enables persisting proxy configs for recovery.
	EnableStatePersistence bool

	// StatePath is the path to the state file.
	// If empty, uses default location.
	StatePath string
}

DaemonConfig holds configuration for the daemon.

func DefaultDaemonConfig

func DefaultDaemonConfig() DaemonConfig

DefaultDaemonConfig returns sensible defaults.

type DaemonInfo

type DaemonInfo struct {
	Version     string        `json:"version"`
	SocketPath  string        `json:"socket_path"`
	Uptime      time.Duration `json:"uptime"`
	ClientCount int64         `json:"client_count"`
	ProcessInfo ProcessInfo   `json:"process_info"`
	ProxyInfo   ProxyInfo     `json:"proxy_info"`
	TunnelInfo  TunnelInfo    `json:"tunnel_info"`
}

DaemonInfo holds daemon status information.

type PersistentProxyConfig

type PersistentProxyConfig struct {
	ID         string `json:"id"`
	TargetURL  string `json:"target_url"`
	Port       int    `json:"port"`
	MaxLogSize int    `json:"max_log_size"`
	Path       string `json:"path"`
	CreatedAt  string `json:"created_at"`
}

PersistentProxyConfig stores the configuration needed to recreate a proxy.

type PersistentState

type PersistentState struct {
	Version         int                     `json:"version"`
	OverlayEndpoint string                  `json:"overlay_endpoint,omitempty"`
	Proxies         []PersistentProxyConfig `json:"proxies,omitempty"`
	UpdatedAt       string                  `json:"updated_at"`
}

PersistentState stores daemon state that should survive restarts.

type ProcessInfo

type ProcessInfo struct {
	Active       int64 `json:"active"`
	TotalStarted int64 `json:"total_started"`
	TotalFailed  int64 `json:"total_failed"`
}

ProcessInfo holds process manager statistics.

type ProxyInfo

type ProxyInfo struct {
	Active       int64 `json:"active"`
	TotalStarted int64 `json:"total_started"`
}

ProxyInfo holds proxy manager statistics.

type ProxyStartConfig

type ProxyStartConfig struct {
	Path        string                 `json:"path,omitempty"`
	BindAddress string                 `json:"bind_address,omitempty"`
	PublicURL   string                 `json:"public_url,omitempty"`
	Tunnel      *protocol.TunnelConfig `json:"tunnel,omitempty"`
}

ProxyStartConfig holds configuration for starting a proxy.

type ReconnectCallback

type ReconnectCallback func(client *Client) error

ReconnectCallback is called after successful reconnection. It should restore any state that needs to be re-registered with the daemon.

type ResilientClient

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

ResilientClient wraps Client with automatic reconnection and health monitoring.

func NewResilientClient

func NewResilientClient(config ResilientClientConfig) *ResilientClient

NewResilientClient creates a new resilient client.

func (*ResilientClient) BroadcastActivity

func (rc *ResilientClient) BroadcastActivity(active bool, proxyIDs ...string) error

BroadcastActivity sends an activity state update to connected browsers via specified proxies. If proxyIDs is empty, broadcasts to all proxies (backward compatibility).

func (*ResilientClient) Client

func (rc *ResilientClient) Client() *Client

Client returns the underlying client for direct access. Returns nil if not connected.

func (*ResilientClient) Close

func (rc *ResilientClient) Close() error

Close shuts down the resilient client.

func (*ResilientClient) Connect

func (rc *ResilientClient) Connect() error

Connect establishes the initial connection to the daemon.

func (*ResilientClient) Info

func (rc *ResilientClient) Info() (*DaemonInfo, error)

Info retrieves daemon information.

func (*ResilientClient) IsConnected

func (rc *ResilientClient) IsConnected() bool

IsConnected returns whether the client is currently connected.

func (*ResilientClient) IsReconnecting

func (rc *ResilientClient) IsReconnecting() bool

IsReconnecting returns whether the client is currently reconnecting.

func (*ResilientClient) OverlaySet

func (rc *ResilientClient) OverlaySet(endpoint string) (map[string]interface{}, error)

OverlaySet sets the overlay endpoint.

func (*ResilientClient) Ping

func (rc *ResilientClient) Ping() error

Ping sends a ping to the daemon.

func (*ResilientClient) ProxyList

func (rc *ResilientClient) ProxyList(dirFilter protocol.DirectoryFilter) (map[string]interface{}, error)

ProxyList lists all proxies.

func (*ResilientClient) ProxyStart

func (rc *ResilientClient) ProxyStart(id, targetURL string, port, maxLogSize int, path string) (map[string]interface{}, error)

ProxyStart starts a reverse proxy.

func (*ResilientClient) ProxyStop

func (rc *ResilientClient) ProxyStop(id string) error

ProxyStop stops a reverse proxy.

func (*ResilientClient) Stats

func (rc *ResilientClient) Stats() map[string]interface{}

Stats returns connection statistics.

func (*ResilientClient) WithClient

func (rc *ResilientClient) WithClient(fn func(*Client) error) error

WithClient executes a function with the client, handling reconnection.

type ResilientClientConfig

type ResilientClientConfig struct {
	// AutoStartConfig for daemon auto-start
	AutoStartConfig AutoStartConfig

	// HeartbeatInterval is how often to send heartbeats (0 disables)
	HeartbeatInterval time.Duration

	// HeartbeatTimeout is how long to wait for heartbeat response
	HeartbeatTimeout time.Duration

	// ReconnectBackoffMin is the minimum backoff between reconnection attempts
	ReconnectBackoffMin time.Duration

	// ReconnectBackoffMax is the maximum backoff between reconnection attempts
	ReconnectBackoffMax time.Duration

	// MaxReconnectAttempts limits reconnection attempts (0 = unlimited)
	MaxReconnectAttempts int

	// OnReconnect is called after successful reconnection
	OnReconnect ReconnectCallback

	// OnDisconnect is called when connection is lost
	OnDisconnect func(err error)

	// OnReconnectFailed is called when reconnection fails permanently
	OnReconnectFailed func(err error)
}

ResilientClientConfig configures a ResilientClient.

func DefaultResilientClientConfig

func DefaultResilientClientConfig() ResilientClientConfig

DefaultResilientClientConfig returns sensible defaults.

type SocketConfig

type SocketConfig struct {
	// Path is the socket file path. If empty, uses default path.
	Path string
	// Mode is the socket file permissions (default 0600).
	Mode os.FileMode
}

SocketConfig holds configuration for socket management.

func DefaultSocketConfig

func DefaultSocketConfig() SocketConfig

DefaultSocketConfig returns the default socket configuration.

type SocketManager

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

SocketManager handles Unix socket lifecycle.

func NewSocketManager

func NewSocketManager(config SocketConfig) *SocketManager

NewSocketManager creates a new socket manager.

func (*SocketManager) Close

func (sm *SocketManager) Close() error

Close closes the socket and removes the socket and PID files.

func (*SocketManager) Listen

func (sm *SocketManager) Listen() (net.Listener, error)

Listen creates and binds the Unix socket. It handles stale socket cleanup and creates a PID file.

func (*SocketManager) Path

func (sm *SocketManager) Path() string

Path returns the socket path.

type StateManager

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

StateManager handles persisting and restoring daemon state.

func NewStateManager

func NewStateManager(config StateManagerConfig) *StateManager

NewStateManager creates a new state manager.

func (*StateManager) AddProxy

func (sm *StateManager) AddProxy(config PersistentProxyConfig)

AddProxy adds a proxy configuration to state.

func (*StateManager) Clear

func (sm *StateManager) Clear() error

Clear removes all state.

func (*StateManager) Flush

func (sm *StateManager) Flush() error

Flush ensures any pending saves are written immediately.

func (*StateManager) GetOverlayEndpoint

func (sm *StateManager) GetOverlayEndpoint() string

GetOverlayEndpoint returns the persisted overlay endpoint.

func (*StateManager) GetProxies

func (sm *StateManager) GetProxies() []PersistentProxyConfig

GetProxies returns all persisted proxy configurations.

func (*StateManager) GetProxy

func (sm *StateManager) GetProxy(id string) (PersistentProxyConfig, bool)

GetProxy returns a specific proxy configuration.

func (*StateManager) Load

func (sm *StateManager) Load() error

Load loads state from disk.

func (*StateManager) RemoveProxy

func (sm *StateManager) RemoveProxy(id string)

RemoveProxy removes a proxy configuration from state.

func (*StateManager) Save

func (sm *StateManager) Save() error

Save saves state to disk.

func (*StateManager) SaveDebounced

func (sm *StateManager) SaveDebounced()

SaveDebounced saves state with debouncing to avoid excessive writes.

func (*StateManager) SetOverlayEndpoint

func (sm *StateManager) SetOverlayEndpoint(endpoint string)

SetOverlayEndpoint updates the overlay endpoint in state.

func (*StateManager) State

func (sm *StateManager) State() PersistentState

State returns a copy of the current state.

type StateManagerConfig

type StateManagerConfig struct {
	// StatePath is the path to the state file.
	// If empty, uses default location.
	StatePath string

	// SaveInterval is the minimum time between saves (debouncing).
	SaveInterval time.Duration

	// AutoLoad loads state on creation if true.
	AutoLoad bool
}

StateManagerConfig configures the state manager.

func DefaultStateManagerConfig

func DefaultStateManagerConfig() StateManagerConfig

DefaultStateManagerConfig returns sensible defaults.

type TunnelInfo

type TunnelInfo struct {
	Active int64 `json:"active"`
}

TunnelInfo holds tunnel manager statistics.

Jump to

Keyboard shortcuts

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