daemon

package
v0.16.1 Latest Latest
Warning

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

Go to latest
Published: Oct 30, 2026 License: MIT Imports: 28 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 daemon is the part of dym that runs on a host and reaches Dymmer by itself, instead of Dymmer reaching the host over SSH: it pairs with a one-time PIN, keeps one connection open, and tells Dymmer that the host is alive and what it is. It accepts no command from Dymmer.

Index

Constants

This section is empty.

Variables

View Source
var ErrNotPaired = errors.New("this host is not paired yet: run `dym auth daemon`")

ErrNotPaired is returned when there is no state yet: `dym auth daemon` has not been run on this host.

View Source
var ErrPairingExpired = errors.New("the PIN expired before it was entered in Dymmer: run `dym auth daemon` again")

ErrPairingExpired is the end of a PIN that nobody entered in Dymmer in time.

View Source
var HeartbeatEvery = 30 * time.Second

HeartbeatEvery is how often the heartbeat is sent. The server of Dymmer closes a connection that is silent for a minute, so this must stay well under that.

Functions

func Addresses

func Addresses(sys System) []string

Addresses are the addresses of the host that can say where it is: not loopback, not link-local, not multicast.

func DefaultConfigPath added in v0.14.0

func DefaultConfigPath() (string, error)

DefaultConfigPath is where the owner writes it: /etc/dym/daemon.yaml for root (the service), the user's config otherwise.

func DefaultStatePath

func DefaultStatePath() (string, error)

DefaultStatePath is where the state lives: /var/lib/dym for root (the service), the user's config otherwise.

func OperationNames added in v0.14.0

func OperationNames() []string

OperationNames lists them, sorted, for the host to tell Dymmer which ones it answers.

func Operations added in v0.14.0

func Operations() map[string]Operation

Operations are the operations that this host answers. They are named like the scripts Dymmer used to send, so that a host reached by SSH and one reached through the daemon are asked the same way.

func ParseCPUModel

func ParseCPUModel(text string) string

ParseCPUModel reads the model of the CPU from /proc/cpuinfo (x86 says "model name", Arm says "Model" or "Processor").

func ParseMemTotal

func ParseMemTotal(text string) int64

ParseMemTotal reads MemTotal from /proc/meminfo, which is in KiB, and gives bytes.

func ParseOSRelease

func ParseOSRelease(text string) (name, version string)

ParseOSRelease reads /etc/os-release and gives the ID (debian, ubuntu...) and the VERSION_ID.

func Run

func Run(ctx context.Context, o RunOptions) error

Run keeps the host connected to Dymmer until ctx ends. While the host is not paired it only waits for the state that `dym auth daemon` leaves. A connection that fails or ends is retried with a wait that grows, so that a Dymmer that is down is not hammered by every host at once, and the wait starts again after a connection that held.

func SaveState

func SaveState(path string, s State) error

SaveState writes the state so that nobody else can read it, and so that a crash never leaves half of it: it is written aside and renamed.

func SocketURL

func SocketURL(server string) (string, error)

SocketURL turns the address of Dymmer (https://dymmer.com) into the websocket endpoint of its daemon socket. Plain http is accepted for a Dymmer that runs on this machine or inside a private network.

func Streams added in v0.14.0

func Streams() map[string]Stream

Streams are the operations of this kind.

func ValidName added in v0.14.0

func ValidName(name string) bool

ValidName says whether a text can be the name of a service, a container or an action.

Types

type ActionConfig added in v0.14.0

type ActionConfig struct {
	Command    []string          `yaml:"command"`
	Dir        string            `yaml:"dir"`
	Env        map[string]string `yaml:"env"`
	Timeout    string            `yaml:"timeout"`
	Privileged bool              `yaml:"privileged"`
}

ActionConfig is a command that has a name. Dymmer asks for the name; what runs is written here.

func (ActionConfig) Duration added in v0.14.0

func (a ActionConfig) Duration() (time.Duration, error)

Duration is how long the action may run: what it says, one minute without it, never more than half an hour.

type ComposeProject added in v0.14.0

type ComposeProject struct {
	Path     string   `yaml:"path"`
	Services []string `yaml:"services"`
}

ComposeProject is a docker compose project, and the services of it that Dymmer may handle.

type Config added in v0.14.0

type Config struct {
	Privilege []string                `yaml:"privilege"`
	Services  map[string][]string     `yaml:"services"`
	Compose   []ComposeProject        `yaml:"compose"`
	Actions   map[string]ActionConfig `yaml:"actions"`
	Logs      LogsConfig              `yaml:"logs"`
}

Config is what the owner of this host allows Dymmer to do beyond reading. It is a file that only the owner writes (root, readable by the daemon), and it is read again for every order, so that a change needs no restart. Without the file nothing that changes the host can be asked: the daemon only answers readings.

privilege: [sudo, -n]          # put before the commands that change something (optional)
services:                      # what Dymmer may start, stop, restart or reload; reading the status needs no entry
  systemctl: [nginx, myapp]
  docker: [web]
compose:                       # docker compose projects; every operation on one needs its entry
  - path: /srv/app
    services: [web, worker]
actions:                       # what an action of a project or a command of a deployment may run, by name
  deploy-site:
    command: [/usr/local/bin/deploy-site, --prod]
    dir: /srv/site
    env: {MODE: prod}
    timeout: 5m
    privileged: true
logs:                          # the only files and units whose lines Dymmer may read
  files: [/var/log/nginx/access.log]
  units: [nginx]

func LoadConfig added in v0.14.0

func LoadConfig(path string) (Config, error)

LoadConfig reads and checks the file. A file that is not there is an empty configuration, not an error; a file that is wrong is an error and none of it is used, so a typo can never allow more than was written.

func (Config) ActionNames added in v0.14.0

func (c Config) ActionNames() []string

ActionNames lists the actions, sorted.

func (Config) AllowsService added in v0.14.0

func (c Config) AllowsService(manager, name string) bool

AllowsService says whether Dymmer may change that service, container or process.

func (Config) ComposeProject added in v0.14.0

func (c Config) ComposeProject(path string) (ComposeProject, bool)

ComposeProject finds a project by its path.

func (Config) Validate added in v0.14.0

func (c Config) Validate() error

Validate checks every entry. The first thing wrong is reported.

type Conn

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

Conn is a connection to a Phoenix socket (serializer 2.0.0: a frame is [join_ref, ref, topic, event, payload]). It sends the heartbeat the server expects, answers the pushes of the topics joined with Events, and ends when the connection does: Done is closed and Err says why.

func Dial

func Dial(ctx context.Context, url string, header http.Header) (*Conn, error)

Dial opens the connection. `url` is the websocket endpoint without the query (the version is added here) and `header` carries the credentials, which must not go in the URL because proxies write it in their logs.

func (*Conn) Close

func (c *Conn) Close()

Close ends the connection.

func (*Conn) Done

func (c *Conn) Done() <-chan struct{}

Done is closed when the connection has ended.

func (*Conn) Err

func (c *Conn) Err() error

Err says why the connection ended, once Done is closed.

func (*Conn) Events

func (c *Conn) Events() <-chan Event

Events delivers what the server pushes on the topics that were joined. It is closed when the connection ends.

func (*Conn) Join

func (c *Conn) Join(ctx context.Context, topic string, payload map[string]any) (map[string]any, error)

Join asks the server to join a topic and returns what it answered.

func (*Conn) Push

func (c *Conn) Push(ctx context.Context, topic, event string, payload map[string]any) (map[string]any, error)

Push sends a message on a joined topic and waits for the answer of the server.

type DialError

type DialError struct {
	Status int
	Err    error
}

DialError is a handshake that the server rejected (a wrong secret, a deleted host, too many attempts).

func (*DialError) Error

func (e *DialError) Error() string

func (*DialError) Unwrap

func (e *DialError) Unwrap() error

type Event

type Event struct {
	Topic   string
	Name    string
	Payload map[string]any
}

Event is a message that the server pushed on a topic that was joined.

type ExecFunc added in v0.14.0

type ExecFunc func(ctx context.Context, spec ExecSpec) ExecResult

ExecFunc runs a command; tests give their own.

type ExecResult added in v0.14.0

type ExecResult struct {
	Output   string // standard output and error together, the end of it if it was long
	ExitCode int
	Err      error
}

ExecResult is how it ended. ExitCode is -1 when it did not start or did not end by itself.

func HostExec added in v0.14.0

func HostExec(ctx context.Context, spec ExecSpec) ExecResult

HostExec runs the command on this host without a shell, in its own process group so that a timeout ends the children too, with a clean environment and the output bounded.

func HostStream added in v0.14.0

func HostStream(ctx context.Context, spec ExecSpec, onLine func(string)) ExecResult

HostStream is HostExec for a command that keeps running (`journalctl -f`): the same without a shell, with a clean environment and its own process group, and the standard output delivered line by line.

type ExecSpec added in v0.14.0

type ExecSpec struct {
	Argv    []string
	Dir     string
	Env     map[string]string
	Timeout time.Duration
}

ExecSpec is a command to run. It is a list of arguments and never a line for a shell: nothing in it is interpreted.

type Inventory

type Inventory struct {
	Hostname    string   `json:"hostname,omitempty"`
	IPAddresses []string `json:"ip_addresses,omitempty"`
	OSName      string   `json:"os_name,omitempty"`
	OSVersion   string   `json:"os_version,omitempty"`
	CPUName     string   `json:"cpu_name,omitempty"`
	CPUCores    int      `json:"cpu_cores,omitempty"`
	Memory      int64    `json:"memory,omitempty"` // bytes
}

Inventory is what the daemon tells Dymmer about its host. The names are the ones Dymmer stores.

func Collect

func Collect(sys System) Inventory

Collect reads the inventory. A piece that cannot be read is left out: the daemon is useful with what it has.

func (Inventory) Payload

func (i Inventory) Payload() map[string]any

Payload is the inventory as the map that goes in a channel message.

type JoinError

type JoinError struct {
	Topic  string
	Reason string
}

JoinError is the answer of a server that refused to let the client join a topic.

func (*JoinError) Error

func (e *JoinError) Error() string

type LogsConfig added in v0.14.0

type LogsConfig struct {
	Files []string `yaml:"files"`
	Units []string `yaml:"units"`
}

LogsConfig lists what may be read.

type OpEnv added in v0.14.0

type OpEnv struct {
	StatsSystem
	Exec   ExecFunc
	Stream StreamFunc
	Config func() (Config, error)
}

OpEnv is what an operation can use: the machine it reads, a way to run a command, and the configuration of the owner.

func HostOpEnv added in v0.14.0

func HostOpEnv(goos, configPath string) OpEnv

HostOpEnv is the host itself, with the configuration read from path.

type Operation added in v0.14.0

type Operation func(env OpEnv, args []string) Result

Operation is something Dymmer can ask this host to do, by name. It is a fixed implementation that lives in this program for each system: Dymmer sends a name and arguments, never a script or a command line, and an operation that is not here is refused. Arguments are checked by the operation before it does anything.

type PairOptions

type PairOptions struct {
	// URL is the websocket endpoint of Dymmer's daemon socket.
	URL string
	// StatePath is where the host and its permanent secret are kept once Dymmer gives them.
	StatePath string
	// Inventory is what to tell Dymmer about this host, so that the host is created already filled in.
	Inventory Inventory
	// OnPIN is called as soon as Dymmer hands out the PIN, to show it to whoever is at the console.
	OnPIN func(pin string, validFor time.Duration)
}

PairOptions says how to pair this host.

type Result added in v0.14.0

type Result struct {
	Status  string // "OK" or "FAIL"
	Message string
	Output  string // "OK" (running), "NO" (stopped), "ERROR" or "UNKNOWN"
	Service string
}

Result is what an operation answers: the shape the scripts of Dymmer print, so that Dymmer reads it as it always did. Output and Service are for the operations on services, whose scripts also printed them.

func RunOperation added in v0.14.0

func RunOperation(env OpEnv, name string, args []string) Result

RunOperation runs the operation with that name. A name that is not one of ours, or arguments that the operation does not take, are a failure and nothing is run.

func (Result) Payload added in v0.14.0

func (r Result) Payload() map[string]any

Payload is the result as the map that goes in a channel message.

type RunOptions

type RunOptions struct {

	// URL is the websocket endpoint of Dymmer's daemon socket.
	URL string
	// StatePath is where the pairing is kept.
	StatePath string
	// Collect reads the inventory of the host; the default reads the machine.
	Collect func() Inventory
	// CollectStats takes a sample of how the host is doing; the default reads the machine. It says false when there
	// is nothing to send (a system that is not supported).
	CollectStats func() (Stats, bool)
	// Operations is what the operations use (the machine they read, the way to run a command, the configuration of the
	// owner); the default is the host itself.
	Operations *OpEnv
	// ConfigPath is the configuration of the owner (see Config); without it, the default of the user that runs.
	ConfigPath string
	// Logger receives what happens; the default discards it.
	Logger *slog.Logger
	// MinBackoff and MaxBackoff bound the wait between attempts to connect (1s and 60s by default).
	MinBackoff, MaxBackoff time.Duration
	// StableAfter is how long a connection has to last for the wait to start again from the minimum (60s).
	StableAfter time.Duration
	// StatsEvery is how often a sample is sent (5 minutes). Dymmer keeps one every quarter of an hour.
	StatsEvery time.Duration
	// InventoryEvery is how often the inventory is read again and sent if it changed (5 minutes).
	InventoryEvery time.Duration
	// PollPairing is how often it looks for the state while the host is not paired (5s).
	PollPairing time.Duration
	// contains filtered or unexported fields
}

RunOptions says how the daemon runs.

type State

type State struct {
	HostID string `json:"host_id"`
	Secret string `json:"secret"`
}

State is what the daemon keeps after pairing: which host it is and the permanent secret that proves it. The secret lets anyone connect as this host, so the file is readable only by its owner.

func LoadState

func LoadState(path string) (State, error)

LoadState reads the state, or ErrNotPaired when there is none.

func Pair

func Pair(ctx context.Context, o PairOptions) (State, error)

Pair asks Dymmer for a PIN and waits, on the same connection, until somebody enters it in Dymmer. Dymmer then creates the host and sends its permanent secret down the open connection; that is saved before Pair returns, so the daemon can reconnect by itself from now on.

type Stats added in v0.13.0

type Stats struct {
	CPULoad     float64 // load average of the last minute
	MemoryUsage int64   // bytes in use (total less what is available)
	Uptime      int64   // seconds
	NetworkIn   int64   // bytes received since boot, every interface but loopback
	NetworkOut  int64   // bytes sent since boot, every interface but loopback
	Volumes     []VolumeUsage
}

Stats is a sample of how the host is doing. The names are the ones Dymmer stores (its host statistics).

func CollectStats added in v0.13.0

func CollectStats(sys StatsSystem) (Stats, bool)

CollectStats takes a sample. The second result is false when this system is not supported (Linux and FreeBSD are) or when not even the basics could be read: the daemon then sends nothing rather than made-up numbers.

func (Stats) Payload added in v0.13.0

func (s Stats) Payload() map[string]any

Payload is the sample as the map that goes in a channel message.

type StatsSystem added in v0.13.0

type StatsSystem struct {
	GOOS     string
	ReadFile func(path string) ([]byte, error)
	// Statfs gives the size and the free space of the file system mounted at path, in bytes.
	Statfs func(path string) (total, free uint64, err error)
	// Run runs a command and gives its output (FreeBSD is read through sysctl, netstat and df).
	Run func(name string, args ...string) (string, error)
	// Sleep waits; the operations that take two samples use it (tests do not wait).
	Sleep func(time.Duration)
	// Now is the clock; the uptime of FreeBSD is the time since the boot it reports.
	Now func() time.Time
	// ResolveDevice follows /dev/mapper/x and similar links to the name the kernel counts I/O under (dm-0).
	ResolveDevice func(device string) string
}

StatsSystem is what CollectStats reads from the machine; tests give their own.

func HostStatsSystem added in v0.13.0

func HostStatsSystem(goos string) StatsSystem

HostStatsSystem is the machine the daemon runs on.

type Stream added in v0.14.0

type Stream func(ctx context.Context, env OpEnv, args []string, emit func(string)) Result

Stream is an operation that keeps sending until it is stopped: it hands lines to emit, in batches, and ends with a result that says why. Like the other operations it is fixed, and it only reads what the owner declared.

type StreamFunc added in v0.14.0

type StreamFunc func(ctx context.Context, spec ExecSpec, onLine func(string)) ExecResult

StreamFunc runs a command and hands over its output line by line while it runs, until it ends or ctx does.

type System

type System struct {
	GOOS, GOARCH string
	NumCPU       int
	Hostname     func() (string, error)
	Addrs        func() ([]net.Addr, error)
	ReadFile     func(path string) ([]byte, error)
	Sysctl       func(name string) (string, error)
}

System is what Collect reads from the machine; tests give their own.

func HostSystem

func HostSystem() System

HostSystem is the machine the daemon runs on.

type VolumeUsage added in v0.13.0

type VolumeUsage struct {
	Device string
	Size   int64  // bytes, the whole volume
	Used   int64  // bytes
	Reads  *int64 // completed reads since boot
	Writes *int64 // completed writes since boot
}

VolumeUsage is how full a volume is and, when the kernel counts them, the reads and writes it has done.

Jump to

Keyboard shortcuts

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