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 ¶
- Variables
- func Addresses(sys System) []string
- func DefaultConfigPath() (string, error)
- func DefaultStatePath() (string, error)
- func OperationNames() []string
- func Operations() map[string]Operation
- func ParseCPUModel(text string) string
- func ParseMemTotal(text string) int64
- func ParseOSRelease(text string) (name, version string)
- func Run(ctx context.Context, o RunOptions) error
- func SaveState(path string, s State) error
- func SocketURL(server string) (string, error)
- func Streams() map[string]Stream
- func ValidName(name string) bool
- type ActionConfig
- type ComposeProject
- type Config
- type Conn
- func (c *Conn) Close()
- func (c *Conn) Done() <-chan struct{}
- func (c *Conn) Err() error
- func (c *Conn) Events() <-chan Event
- func (c *Conn) Join(ctx context.Context, topic string, payload map[string]any) (map[string]any, error)
- func (c *Conn) Push(ctx context.Context, topic, event string, payload map[string]any) (map[string]any, error)
- type DialError
- type Event
- type ExecFunc
- type ExecResult
- type ExecSpec
- type Inventory
- type JoinError
- type LogsConfig
- type OpEnv
- type Operation
- type PairOptions
- type Result
- type RunOptions
- type State
- type Stats
- type StatsSystem
- type Stream
- type StreamFunc
- type System
- type VolumeUsage
Constants ¶
This section is empty.
Variables ¶
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.
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.
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 ¶
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
DefaultConfigPath is where the owner writes it: /etc/dym/daemon.yaml for root (the service), the user's config otherwise.
func DefaultStatePath ¶
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
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 ¶
ParseCPUModel reads the model of the CPU from /proc/cpuinfo (x86 says "model name", Arm says "Model" or "Processor").
func ParseMemTotal ¶
ParseMemTotal reads MemTotal from /proc/meminfo, which is in KiB, and gives bytes.
func ParseOSRelease ¶
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 ¶
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 ¶
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.
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.
type ComposeProject ¶ added in v0.14.0
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
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
ActionNames lists the actions, sorted.
func (Config) AllowsService ¶ added in v0.14.0
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.
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 ¶
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) Done ¶
func (c *Conn) Done() <-chan struct{}
Done is closed when the connection has ended.
func (*Conn) Events ¶
Events delivers what the server pushes on the topics that were joined. It is closed when the connection ends.
type DialError ¶
DialError is a handshake that the server rejected (a wrong secret, a deleted host, too many attempts).
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
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.
type LogsConfig ¶ added in v0.14.0
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.
type Operation ¶ added in v0.14.0
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
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.
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 ¶
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 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.
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
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.
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.