protocol

package
v1.0.0-beta.37 Latest Latest
Warning

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

Go to latest
Published: Nov 26, 2026 License: AGPL-3.0 Imports: 11 Imported by: 1 module, 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 protocol is the contract between the moin daemon and the hub. The daemon dials out: it registers once over HTTP, then holds one WebSocket session. The daemon and the hub both import this package, so a change here is a change on both sides.

Index

Constants

View Source
const (
	RestoreRunning = "running"
	RestoreDone    = "done"
	RestoreFailed  = "failed"
)

The states of a RestoreState.

View Source
const (
	// ExecMaxOutput is how much a run may write before the rest is dropped.
	ExecMaxOutput = 1 << 20
	// ExecTimeout is how long a run may take unless asked otherwise, and
	// ExecMaxTimeout how long it may take at most, in seconds.
	ExecTimeout    = 10 * 60
	ExecMaxTimeout = 60 * 60
)
View Source
const (
	// RegisterPath trades a one-time install token, sent as
	// "Authorization: Bearer <install token>", for a daemon token.
	RegisterPath = "/daemon/register"
	// SessionPath upgrades to the WebSocket session, authorized with
	// "Authorization: Bearer <daemon token>".
	SessionPath = "/daemon/session"
)
View Source
const (
	SecretTailscale = "tailscale"
	SecretTunnel    = "tunnel"
)

The names of the secrets every server may keep.

View Source
const (
	SSHTailscale = "tailscale"
	SSHEveryone  = "everyone"
	SSHOff       = "off"
)

Who SSH answers on a server: only through Tailscale, everyone, or nobody, with sshd stopped.

View Source
const BackupLinkLife = 15 * time.Minute

BackupLinkLife is how long a download link works.

View Source
const CopyIDLayout = "20060102T150405Z"

CopyIDLayout is the time a copy, or the state before a restore, was taken. Its ID is that time and six random digits, like 20261107T140000Z-482913: sorted by time, and two of the same second still apart. IDs of only the time, from before, stay valid.

View Source
const DatabasePostgres = "postgres"

DatabasePostgres is the Kind of a Postgres service.

View Source
const DownloadPath = "/download/"

DownloadPath is where the hub serves the binaries, as <name>-<os>-<arch>: the install script and the update command take them from there, and daemons from before signed releases.

View Source
const KeepReleases = 5

KeepReleases is how many releases that brought something new, a source build or an image, a daemon keeps per app. Releases without a build, like restarts, domain changes and rollbacks, are small: the daemon keeps them as long as they are newer than the oldest build it keeps. It always keeps the current release. The hub offers rollbacks by the same rule.

View Source
const LegacySessionPath = "/agent/session"

LegacySessionPath is SessionPath before protocol 3.

View Source
const LegacyTokenMarker = "agt_"

LegacyTokenMarker starts the daemon tokens handed out before protocol 3; they stay valid.

View Source
const MaxRefLength = 255

MaxRefLength is the longest branch, tag or commit name moin accepts.

View Source
const MetricsEvery = 15 * time.Second

MetricsEvery is how often the daemon samples its server and apps and sends the sample.

View Source
const SecurityEvery = 5 * time.Minute

SecurityEvery is how often the daemon checks that its server still has the security of its ServerConfig, puts back what drifted and sends TypeServerSecurity. It checks after each start too.

View Source
const Version = 7

Version is the protocol version the daemon reports in Hello. Bump it when a message changes in a way an older peer cannot read. Version 2 brought backups as copies on a schedule, restores and undos; version 3 the daemon, which was called the agent before (legacy.go); version 4 the command the daemon masks for the activity (ExecDone.Command); version 5 secrets that live only on the server (secrets.go); version 6 compose.yml as plain Docker, with every setting from the hub; version 7 one password for an app's domains and its instant address (Domains.Password).

Variables

View Source
var (
	Everies = []int{15, 60, 24 * 60}
	Keeps   = []int{1, 3, 7, 30}
)

Everies and Keeps are the choices of a Schedule: every 15 minutes, hourly or daily; kept 1, 3, 7 or 30 days.

View Source
var DefaultSchedule = Schedule{Every: 60, Keep: 7}

DefaultSchedule is the schedule of an app nobody set one for.

View Source
var InstantProviders = []string{"sslip.io", "nip.io"}

InstantProviders are the services that name an IP without any setup: <name>.<ip with dashes>.<provider> resolves to the IP.

Functions

func BeforeCopyID

func BeforeCopyID(at time.Time) string

BeforeCopyID is the ID of the copies taken at at just before a deploy or an edit, the hub finds them by: the digits 000000, which no other copy has.

func BucketSecret

func BucketSecret(id string) string

BucketSecret names the secret key of the bucket with the hub's ID id.

func CopyFile

func CopyFile(id string, postgres bool) string

CopyFile is the copy id in its database's folder: a gzipped SQLite file, or a pg_dump in its custom format.

func CopyTime

func CopyTime(id string) (time.Time, bool)

CopyTime is the time in a copy's ID.

func DaemonRules

func DaemonRules(name string) string

DaemonRules is the rules file the install script writes on a new server, /etc/<name>/rules: every rule, each with the value the daemon takes when the file is missing, so the owner sees what moin may do. A rule that has no such value, such as deploy-from, stands as a comment.

func DaemonUnit

func DaemonUnit(name string) string

DaemonUnit is the systemd unit of the daemon.

func DatabaseFolder

func DatabaseFolder(bucket Bucket, app, appID, database string) string

DatabaseFolder is the folder of a database in its app's bucket: <path>/<workspace>/<app>/<app ID>/<database>, its path in the container with ~ for /, like data~app.db, postgres-db or postgres-db~analytics.

func EveryMinutes

func EveryMinutes(word string) (int, bool)

EveryMinutes is how often a word means, in minutes: 15m, 1h or 1d.

func InstantHost

func InstantHost(app, ip, provider string) string

InstantHost is the instant address of an app on a server with the public IPv4 ip, such as my-app.203-0-113-7.sslip.io, or "" when the provider is none of InstantProviders or the IP is not IPv4.

func JoinCommand

func JoinCommand(argv []string) string

JoinCommand writes argv as one line SplitCommand reads back, quoting the words that need it, for people to read.

func KeepDays

func KeepDays(word string) (int, bool)

KeepDays is how long a word means, in days: 1d, 3d, 7d or 30d.

func KeptReleases

func KeptReleases(releases []Release, current int) map[int]bool

KeptReleases returns the numbers of the releases a daemon keeps of releases, which may come in any order, with current the running one.

func LegacyUpdateCommand

func LegacyUpdateCommand(baseURL, name, arch string) string

LegacyUpdateCommand is UpdateCommand for a daemon from before protocol 3, which runs as the unit <name>-agent. The new binary, started by that unit, moves itself to <name>-daemon.

func Needs

func Needs(messageType MessageType) int

Needs is the protocol version a daemon must speak for a request: the hub answers "update the daemon" to an older one instead of sending it. Since version 5 backups and the server config take their secrets from the server: an older daemon would run them without. Since version 6 a deploy takes its domains only from the hub: an older daemon would still let compose.yml change them. Since version 7 the app's password guards its instant address too: an older daemon would leave it open.

func NewCopyID

func NewCopyID(at time.Time) string

NewCopyID is the ID of a copy taken at at.

func PostgresKey

func PostgresKey(service string) string

PostgresKey is the name of a Postgres service's database in moin: in the bucket, the API and on every surface.

func RegistryHost

func RegistryHost(image string) string

RegistryHost is the registry of an image reference: its first part when that looks like a host, else Docker Hub.

func RegistrySecret

func RegistrySecret(host string) string

RegistrySecret names the login for the registry host, such as ghcr.io.

func SecretOf

func SecretOf(name string) (kind, of string)

SecretOf splits a secret's name into its kind, bucket or registry, and what it is for: the bucket's ID or the registry's host. A name without a part, like tailscale, is its own kind.

func SplitCommand

func SplitCommand(line string) ([]string, error)

SplitCommand splits a command line into its words the way a shell quotes them, and nothing more: 'single' and "double" quotes keep spaces, a backslash keeps the next character. No variable, glob, pipe or ; does anything: they stay text in the words. For those, run sh -c '…'.

func UninstallCommand

func UninstallCommand(name string) string

UninstallCommand removes the daemon from a server, run on it as root: its service, binary and state. The apps keep running with their data; add --apps to remove them too.

func UpdateCommand

func UpdateCommand(baseURL, name, arch string) string

UpdateCommand updates a daemon by hand on the server, as root: for a daemon too old to update itself, or one without systemd.

func ValidAppName

func ValidAppName(name string) bool

ValidAppName reports whether name is a valid app name.

func ValidCopyID

func ValidCopyID(id string) bool

ValidCopyID reports whether id is the ID of a copy. Anything else never reaches the bucket as part of a key.

func ValidRefName

func ValidRefName(name string) bool

ValidRefName reports whether name is a branch, tag or commit name by git's rules (git check-ref-format), plus two of moin: at most 255 bytes, and no leading dash, so a name is never read as a command line flag.

func ValidSSH

func ValidSSH(ssh string) bool

ValidSSH says whether ssh is one of SSHTailscale, SSHEveryone and SSHOff.

Types

type AppEnv

type AppEnv struct {
	Keys      []string  `json:"keys"`
	ChangedAt time.Time `json:"changed_at"`
}

AppEnv names the env keys an app has on the server, from its app.env, and when that file last changed: never a value. The server is the truth for them; the hub shows what it reports.

type AppMetrics

type AppMetrics struct {
	App string `json:"app"`
	// CPU is the app's share of the whole server in percent, so the apps
	// add up to at most the server's CPU.
	CPU        float64 `json:"cpu"`
	MemoryUsed uint64  `json:"memory_used"`
	// MemoryLimit is the sum of the containers' limits; 0 means no limit,
	// so the server's memory is the limit.
	MemoryLimit uint64  `json:"memory_limit,omitempty"`
	NetRx       float64 `json:"net_rx"`
	NetTx       float64 `json:"net_tx"`
	Containers  int     `json:"containers"`
}

AppMetrics are the numbers of the running containers of one app, added up.

type AppRemove

type AppRemove struct {
	App string `json:"app"`
}

AppRemove names the app to remove.

type AppStop

type AppStop struct {
	App string `json:"app"`
}

AppStop names the app to stop.

type BackupConfig

type BackupConfig struct {
	Bucket     *Bucket             `json:"storage,omitempty"`
	AppBuckets map[string]*Bucket  `json:"app_storage,omitempty"`
	Apps       map[string]string   `json:"apps,omitempty"`
	Schedules  map[string]Schedule `json:"schedules,omitempty"`
	// Paused are the apps whose bucket the server has no key for, with
	// why: the daemon copies and deletes nothing of them until it can.
	Paused map[string]string `json:"paused,omitempty"`
}

BackupConfig is where backups go and how often. Bucket is the workspace's default bucket; without it the daemon copies nothing. AppBuckets is the bucket of each app, by name, that uses another one than the default. Apps are the IDs of the server's apps by name: an app deployed before deploys brought its ID gets it here. Schedules are the backup settings of each app by name; an app without one gets DefaultSchedule. The JSON keys storage and app_storage stay as they are: daemons of protocol version 1 read them.

type BackupLink struct {
	App      string `json:"app"`
	Database string `json:"database"`
	Copy     string `json:"copy"`
	Name     string `json:"name"`
}

BackupLink asks for a link to download the copy Copy of the database Database of App, signed by the daemon with the bucket's key, valid BackupLinkLife. Name starts the file's name, the app's name in moin.

type BackupLinkResult

type BackupLinkResult struct {
	Link string `json:"link"`
}

BackupLinkResult is the signed link.

type BackupRequest

type BackupRequest struct {
	App      string `json:"app"`
	Database string `json:"database,omitempty"`
}

BackupRequest names an app; Database narrows it to one database.

type BackupRestore

type BackupRestore struct {
	ID       string `json:"id"`
	App      string `json:"app"`
	Database string `json:"database,omitempty"`
	Copy     string `json:"copy,omitempty"`
	Undo     string `json:"undo,omitempty"`
}

BackupRestore puts one database back: to the copy Copy, or to the state Undo before an earlier restore, which undoes that restore. The daemon builds the database beside the live one, stops the app, switches in one step and starts it; the live one stays as the undo of this restore.

type Backups

type Backups struct {
	App       string           `json:"app"`
	Databases []DatabaseBackup `json:"databases"`
	// Restores are the restores of the app that run now, and how the
	// last ones ended, by the ID the hub gave them. A daemon
	// that reports restores sends a list, empty or not.
	Restores []RestoreState `json:"restores"`
	// Detected is set when the daemon found a new database in the live
	// deploy, long after the deploy ended.
	Detected *Detected `json:"detected,omitempty"`
}

Backups are the backups of an app's databases.

type Bucket

type Bucket struct {
	ID        string `json:"id"`
	Endpoint  string `json:"endpoint"`
	Region    string `json:"region"`
	Bucket    string `json:"bucket"`
	Path      string `json:"path,omitempty"`
	Workspace string `json:"workspace"`
	AccessKey string `json:"access_key"`
	SecretKey string `json:"-"`
	Name      string `json:"name,omitempty"`
}

Bucket is an S3-compatible bucket. Everything of a workspace goes under <Path>/<Workspace>/, each app under <app>/<app ID>/:

<app>/<app ID>/<database>/copies/        the copies, as long as the app keeps them

Workspace is the workspace's ID, which never changes, so workspaces sharing one bucket never touch each other's files. ID is the bucket's ID in the hub, Name its name in moin. SecretKey never travels in a Bucket: the daemon keeps it in server.json under BucketSecret(ID) and fills it in (BucketSet).

type BucketSet

type BucketSet struct {
	Bucket    Bucket `json:"bucket"`
	SecretKey string `json:"secret_key,omitempty"`
}

BucketSet has the daemon write a test file to Bucket with SecretKey, or with the key it keeps when SecretKey is empty, and keep the key under BucketSecret(Bucket.ID) when the write works.

type Copy

type Copy struct {
	ID   string    `json:"id"`
	At   time.Time `json:"at"`
	Size int64     `json:"size"`
}

Copy is one copy of a database in the bucket, or one state before a restore on the server. Its ID starts with when it was taken (NewCopyID). Size is 0 when moin does not know it.

type DBColumn

type DBColumn struct {
	Name       string `json:"name"`
	Type       string `json:"type"`
	NotNull    bool   `json:"not_null,omitempty"`
	PrimaryKey bool   `json:"primary_key,omitempty"`
}

DBColumn is one column of a table.

type DBMigration

type DBMigration struct {
	Tool      string `json:"tool"`
	Version   string `json:"version"`
	AppliedAt string `json:"applied_at,omitempty"`
}

DBMigration is the newest migration of goose, golang-migrate, Prisma or Drizzle. The app runs its migrations; moin only reads where they are.

type DBQuery

type DBQuery struct {
	DBRequest
	SQL    string `json:"sql"`
	Params []any  `json:"params,omitempty"`
	Write  bool   `json:"write,omitempty"`
	Limit  int    `json:"limit,omitempty"`
}

DBQuery runs SQL with positional parameters. A read runs read-only and returns at most Limit rows. A write runs in one transaction and returns the number of changed rows.

type DBRequest

type DBRequest struct {
	App      string `json:"app"`
	Database string `json:"database,omitempty"`
}

DBRequest names an app's database by its Path in Detected.Databases: a SQLite file in the container, or postgres-<service>. An empty Database means the first one.

type DBResult

type DBResult struct {
	Database  string   `json:"database"`
	Columns   []string `json:"columns"`
	Rows      [][]any  `json:"rows"`
	Truncated bool     `json:"truncated,omitempty"`
	Changes   int64    `json:"changes,omitempty"`
	// Before is when the daemon took the copy just before a write, the
	// time in its ID: the hub names it "Before your edit".
	Before *time.Time `json:"before,omitempty"`
}

DBResult is the answer to a DBQuery. Values are null, numbers or text; a blob that is not text comes as "0x" and its hex. Truncated is true when the query had more rows than the limit.

type DBTable

type DBTable struct {
	Name    string     `json:"name"`
	Type    string     `json:"type"`
	Rows    int64      `json:"rows"`
	RowID   bool       `json:"rowid"`
	Columns []DBColumn `json:"columns"`
	// SQL is the CREATE statement, Indexes the CREATE INDEX statements.
	SQL     string   `json:"sql,omitempty"`
	Indexes []string `json:"indexes,omitempty"`
}

DBTable is one table or view. RowID is false for views, WITHOUT ROWID tables and every Postgres table: their rows cannot be edited by rowid.

type DBTables

type DBTables struct {
	Database  string       `json:"database"`
	Tables    []DBTable    `json:"tables"`
	Migration *DBMigration `json:"migration,omitempty"`
}

DBTables lists the tables and views of a database, and the newest migration a known migration tool recorded in it.

type DaemonURL

type DaemonURL struct {
	URL string `json:"url"`
}

DaemonURL is the address of the hub a daemon should dial.

type DaemonUpdate

type DaemonUpdate struct {
	Version string `json:"version"`
	SHA256  string `json:"sha256"`
}

DaemonUpdate is the release the daemon should run, the hub's version. The daemon takes the binary from the release on GitHub and installs it only when a release key signed its checksums, so the hub names the version and never the binary. SHA256 is the binary the hub serves under DownloadPath, for daemons from before signed releases, which download it from the hub.

type Database

type Database struct {
	Path     string `json:"path"`
	HostPath string `json:"host_path"`
	// HostFolder is the folder of the server HostPath was found in: the
	// mount of the app. The daemon touches the file only through it, so a
	// link the app leaves there never leads out of it.
	HostFolder string `json:"host_folder,omitempty"`
	Kind       string `json:"kind,omitempty"`
	Service    string `json:"service,omitempty"`
	Name       string `json:"name,omitempty"`
}

Database is a database of an app: a SQLite file the daemon found on one of the app's mounts, or, with Kind "postgres", a compose service that runs Postgres. Path names a SQLite file in the container; for Postgres it is postgres-<service>, and HostPath is empty. Older daemons send no Kind. Name is a database of a Postgres service besides the one POSTGRES_DB names, which backups copy too; its Path is postgres-<service>/<name>.

func (Database) Postgres

func (d Database) Postgres() bool

Postgres reports whether the database is a Postgres service.

type DatabaseBackup

type DatabaseBackup struct {
	Database   string     `json:"database"`
	Kind       string     `json:"kind,omitempty"`
	CopiedAt   *time.Time `json:"copied_at,omitempty"`
	Copies     []Copy     `json:"copies,omitempty"`
	Undos      []Copy     `json:"undos,omitempty"`
	CheckedAt  *time.Time `json:"verified_at,omitempty"`
	CheckError string     `json:"drill_error,omitempty"`
	Error      string     `json:"error,omitempty"`
}

DatabaseBackup is how one database is backed up. Copies are its copies in the bucket, newest first; CopiedAt is the newest. Undos are the states before its restores, kept on the server: going back to one undoes that restore. CheckedAt is the newest daily check: it restored the newest copy into a throwaway database and read it, and CheckError says why it failed. Error says what keeps the backup from working. The JSON keys verified_at and drill_error stay as they are: daemons of protocol version 1 send them.

type DeployDone

type DeployDone struct {
	DeployID string   `json:"deploy_id"`
	OK       bool     `json:"ok"`
	Error    string   `json:"error,omitempty"`
	Detected Detected `json:"detected"`
	// Before is when the daemon took the copies just before the new
	// release started over an older one, the time in their IDs: the hub
	// names them "Before v12".
	Before *time.Time `json:"before,omitempty"`
	// Env names the env keys the app has after the deploy, which may have
	// made the secrets of a catalog app: never a value.
	Env *AppEnv `json:"env,omitempty"`
	// ComposeFile is the compose file of a deploy that worked, YAML:
	// everything the daemon runs for the app, written to run anywhere,
	// without the instant address and with no value of the env. image,
	// ports, expose, volumes, user, the env PORT and the paths of a build
	// are as the deploy filled them in; every other ${NAME} stays as
	// written. Daemons before it send none.
	ComposeFile string `json:"compose_file,omitempty"`
}

DeployDone reports how a deploy ended and what the daemon found.

type DeployLog

type DeployLog struct {
	DeployID string `json:"deploy_id"`
	Line     string `json:"line"`
}

DeployLog is one line of build or start output.

type DeployStart

type DeployStart struct {
	DeployID string `json:"deploy_id"`
	// App names the app on the server in every message: its folder, the
	// name it was created with, which a rename never changes. Name is its
	// name now, which its Compose project and containers carry, such as
	// my-app-web-1; a hub from before renames sends none, and the daemon
	// takes App.
	App  string `json:"app"`
	Name string `json:"name,omitempty"`
	// AppID is the app's ID in the hub. Its backups live under
	// it, so an app removed and created again with the same name starts
	// with an empty backup folder.
	AppID  string `json:"app_id,omitempty"`
	Number int    `json:"number"`
	// SourceURL is a GitHub tarball of one commit; the daemon downloads
	// nothing else. SourceAuthorization is sent with the download, a GitHub
	// token; SourceStripTop drops the one folder GitHub wraps a repo in.
	// The hub never holds the source itself.
	SourceURL           string `json:"source_url,omitempty"`
	SourceAuthorization string `json:"source_authorization,omitempty"`
	SourceStripTop      bool   `json:"source_strip_top,omitempty"`
	// SourceNumber builds the source the server kept of release n again,
	// for a redeploy; nothing is downloaded.
	SourceNumber int `json:"source_number,omitempty"`
	// Catalog deploys the catalog app of this name, such as umami: the
	// daemon takes its compose file from the catalog built into it, never
	// from the hub. Daemons before v1.0.0-beta.35 do not know it.
	Catalog    string   `json:"catalog,omitempty"`
	FromNumber int      `json:"from_number,omitempty"`
	Image      string   `json:"image,omitempty"`
	Domains    *Domains `json:"routing,omitempty"`
}

DeployStart is one deploy. Number counts per app. A rollback carries FromNumber and no source: the daemon starts that release's images again. Image replaces the build of the main service with an image built elsewhere, such as in CI; without a source the daemon takes the compose file of the running release. Without source, image and FromNumber the deploy applies env and domains to the running release, without a build. The env never travels with a deploy: every release runs with the app's app.env on the server as it is then (EnvSet), and a login for Image comes from the server too (SecretSet).

type Detected

type Detected struct {
	// Kind is "compose", "dockerfile", "go" or "railpack": what the repo
	// brought, and for railpack that moin built it with Railpack. Builder
	// says what Railpack found, like "Node 24.22.1, start: npm start".
	// Image is the image of the main service when it came from CI.
	// Domains are the domains the main service answers on, Canonical the one
	// the others redirect to, Password whether the app's password guards it.
	Kind      string   `json:"kind"`
	Builder   string   `json:"builder,omitempty"`
	Image     string   `json:"image,omitempty"`
	Domains   []string `json:"domains,omitempty"`
	Canonical string   `json:"canonical,omitempty"`
	Password  bool     `json:"password,omitempty"`
	// ServiceDomains are the domains of the other services, by service;
	// Instant is the main service's instant address, "" when it has none.
	ServiceDomains map[string][]string `json:"service_domains,omitempty"`
	Instant        string              `json:"instant,omitempty"`
	Service        string              `json:"service"`
	Port           int                 `json:"port"`
	Databases      []Database          `json:"databases"`
	// NoBackup is what looks like a database but moin cannot back up.
	NoBackup []Database `json:"no_backup,omitempty"`
}

Detected is what the daemon learned about an app from its repo and its running containers.

func (Detected) Built

func (d Detected) Built() string

Built says for people how moin built the app: the language Railpack found, like "Node 24.22.1 (Railpack)", or the kind.

type Domains

type Domains struct {
	Domains   []string `json:"domains,omitempty"`
	Canonical string   `json:"canonical,omitempty"`
	Password  string   `json:"password,omitempty"`
	// Services are the domains of the app's other services, by service.
	Services map[string][]string `json:"services,omitempty"`
	// Instant is the provider of the app's instant address, such as
	// sslip.io, "" for none; InstantIP the server's public IPv4 it names.
	Instant   string `json:"instant,omitempty"`
	InstantIP string `json:"instant_ip,omitempty"`
}

Domains is how visitors reach the app, as set in web, CLI, TUI or MCP: the only place they are set. Password is an htpasswd line ("user:bcrypt hash") when the app's password is on: the app's domains, those of its other services and its instant address ask for it. DeployStart carries it under the JSON key routing, which daemons of protocol version 1 read.

type EnvSet

type EnvSet struct {
	App    string            `json:"app"`
	Set    map[string]string `json:"set,omitempty"`
	Remove []string          `json:"remove,omitempty"`
}

EnvSet sets the env values of Set and removes the keys of Remove in the app's app.env. Every compose up of the app reads that one file, so a change reaches the containers with the next deploy, restart or start. The daemon answers with TypeEnvResult: the keys the file has now.

type Error

type Error struct {
	Message string `json:"message"`
}

Error is the answer to a request that failed.

type ExecDone

type ExecDone struct {
	ExitCode  int    `json:"exit_code"`
	Truncated bool   `json:"truncated,omitempty"`
	TimedOut  bool   `json:"timed_out,omitempty"`
	Error     string `json:"error,omitempty"`
	Command   string `json:"command,omitempty"`
}

ExecDone ends a run: the exit code, or the error that kept the command from running. Truncated says the output passed ExecMaxOutput and the rest was dropped; TimedOut that the daemon stopped it. Command is the command line for the activity, with the env values of the app masked: only the daemon knows them.

type ExecOutput

type ExecOutput struct {
	Data string `json:"data"`
}

ExecOutput is a piece of what the command wrote, stdout and stderr as they came.

type ExecStart

type ExecStart struct {
	App     string   `json:"app"`
	Service string   `json:"service"`
	Argv    []string `json:"argv"`
	Timeout int      `json:"timeout"`
}

ExecStart runs Argv in a container of Service of App, as a list: no shell reads it. The daemon stops it after Timeout seconds.

type Hello

type Hello struct {
	ProtocolVersion int    `json:"protocol_version"`
	DaemonVersion   string `json:"daemon_version"`
	Hostname        string `json:"hostname"`
	OS              string `json:"os"`
	Arch            string `json:"arch"`
	// Addresses are the server's own public IPv4 and IPv6 addresses, as far
	// as it knows them. Older daemons send none; the hub then knows
	// only the address the daemon connected from.
	Addresses []string `json:"addresses,omitempty"`
	// Rules are the server's own rules for moin, from /etc/moin/rules. Nil
	// means the server has none and moin may do everything.
	Rules *Rules `json:"rules,omitempty"`
	// Secrets are the names of the secrets the daemon keeps in its
	// server.json (SecretSet), never their values.
	Secrets []string `json:"secrets,omitempty"`
	// Env are the env keys of every app on the server, by its folder,
	// never their values. An app without an entry has no env there.
	Env map[string]AppEnv `json:"env,omitempty"`
}

Hello describes the daemon and its server.

func DecodeHello

func DecodeHello(message Message) (Hello, error)

DecodeHello decodes a hello, also one from before protocol 3, which sent the daemon's version as agent_version.

type LogsRequest

type LogsRequest struct {
	App  string `json:"app"`
	Tail int    `json:"tail"`
}

LogsRequest asks for the last Tail lines of every container of an app.

type LogsResult

type LogsResult struct {
	Lines []string `json:"lines"`
}

LogsResult carries the lines, oldest first.

type Message

type Message struct {
	Type      MessageType     `json:"type"`
	RequestID string          `json:"request_id,omitempty"`
	Data      json.RawMessage `json:"data,omitempty"`
}

Message is the WebSocket envelope. A request carries a RequestID, and its answer carries the same one.

func NewMessage

func NewMessage(messageType MessageType, data any) (Message, error)

NewMessage wraps data in an envelope of the given type.

func (Message) Decode

func (m Message) Decode(target any) error

Decode reads Data into target.

type MessageType

type MessageType string

MessageType decides how Message.Data decodes.

const (
	// TypeHello is the first message the daemon sends on every session.
	TypeHello MessageType = "hello"

	// TypeDeployStart asks the daemon to deploy an app (DeployStart).
	TypeDeployStart MessageType = "deploy.start"
	// TypeDeployLog is one line of deploy output from the daemon (DeployLog).
	TypeDeployLog MessageType = "deploy.log"
	// TypeDeployDone ends a deploy (DeployDone).
	TypeDeployDone MessageType = "deploy.done"

	// TypeLogs asks for the last lines of an app's output (LogsRequest).
	// The daemon answers with TypeLogsResult or TypeError.
	TypeLogs       MessageType = "logs"
	TypeLogsResult MessageType = "logs.result"

	// TypeAppRemove stops an app and removes its containers and images
	// (AppRemove). Its data directory stays. The daemon answers with TypeOK
	// or TypeError.
	TypeAppRemove MessageType = "app.remove"
	// TypeAppStop stops the containers of an app and keeps them, so they
	// stay stopped after a reboot (AppStop). A deploy or a restart starts
	// them again. The daemon answers with TypeOK or TypeError.
	TypeAppStop MessageType = "app.stop"

	// TypeDBTables lists the tables of an app's database, a SQLite file or
	// a Postgres service (DBRequest). The daemon answers with
	// TypeDBTablesResult or TypeError.
	TypeDBTables       MessageType = "db.tables"
	TypeDBTablesResult MessageType = "db.tables.result"
	// TypeDBQuery runs SQL against an app's database, SQLite or Postgres
	// (DBQuery). The daemon answers with TypeDBQueryResult or TypeError.
	TypeDBQuery       MessageType = "db.query"
	TypeDBQueryResult MessageType = "db.query.result"

	// TypeBackupConfig tells the daemon where backups go and how often
	// (BackupConfig). The
	// hub sends it after hello and whenever it changes. The daemon
	// answers with TypeOK.
	TypeBackupConfig MessageType = "backup.config"
	// TypeBackupList says how the backups of an app stand (BackupRequest).
	// The daemon answers with TypeBackupsResult.
	TypeBackupList    MessageType = "backup.list"
	TypeBackupsResult MessageType = "backups.result"
	// TypeBackupRestore puts a database back to a copy or the
	// state before an earlier restore (BackupRestore). The daemon answers
	// with TypeOK or TypeError.
	TypeBackupRestore MessageType = "backup.restore"
	// TypeBackupRestores asks how the restores of an app stand
	// (BackupRequest), without looking into the bucket: also when the app
	// has no bucket or is gone. The daemon answers with TypeBackupsResult,
	// whose Restores is the answer and Databases empty.
	TypeBackupRestores MessageType = "backup.restores"
	// TypeBackupStatus is how the backups of an app stand (Backups), sent by
	// the daemon after a daily check or a restore, or when a backup breaks
	// or works again.
	TypeBackupStatus MessageType = "backup.status"

	// TypeEnvSet sets and removes env values of an app in its app.env on
	// the server (EnvSet). The daemon answers with TypeEnvResult (AppEnv)
	// or TypeError.
	TypeEnvSet    MessageType = "env.set"
	TypeEnvResult MessageType = "env.result"
	// TypeSecretSet keeps a secret of the server in its server.json, or
	// removes it (SecretSet). The daemon answers with TypeOK or TypeError.
	TypeSecretSet MessageType = "secret.set"
	// TypeBucketSet has the daemon write a test file to a bucket and keep
	// its secret key when that works (BucketSet). The daemon answers with
	// TypeOK or TypeError.
	TypeBucketSet MessageType = "bucket.set"
	// TypeBackupLink asks for a signed link to download a copy
	// (BackupLink). The daemon answers with TypeBackupLinkResult or
	// TypeError.
	TypeBackupLink       MessageType = "backup.link"
	TypeBackupLinkResult MessageType = "backup.link.result"

	// TypeServerConfig sets how the server is reached and locked down
	// (ServerConfig). The hub sends it after hello and whenever
	// it changes. The daemon answers with TypeServerConfigResult.
	TypeServerConfig       MessageType = "server.config"
	TypeServerConfigResult MessageType = "server.config.result"
	// TypeServerSecurity is what really is on the server and what the
	// daemon put back (ServerConfigResult), sent by the daemon after each
	// start, on each session and every SecurityEvery, without a request. A
	// hub that does not know it drops it.
	TypeServerSecurity MessageType = "server.security"

	// TypeDaemonUpdate has the daemon replace its binary with the signed
	// release of Version and restart (DaemonUpdate). The daemon answers
	// with TypeOK before it restarts, or with TypeError and changes nothing.
	TypeDaemonUpdate MessageType = "daemon.update"

	// TypeDaemonURL tells the daemon the hub's address when it
	// dialed an old one (DaemonURL). The daemon checks that the address
	// answers, keeps it and dials it from then on. It has no request ID and
	// no answer: a daemon that does not know it ignores it.
	TypeDaemonURL MessageType = "daemon.url"

	// TypeMetrics is a sample of the server and its apps (Metrics), sent by
	// the daemon every MetricsEvery without a request. A hub that
	// does not know it drops it; a daemon that does not send it shows no
	// metrics.
	TypeMetrics MessageType = "metrics"

	// TypeExecStart runs one command in a container of an app (ExecStart).
	// The daemon answers with TypeExecOutput messages as the command writes,
	// then one TypeExecDone, all with the request's ID. A daemon that does
	// not know it answers TypeError.
	TypeExecStart  MessageType = "exec.start"
	TypeExecOutput MessageType = "exec.output"
	TypeExecDone   MessageType = "exec.done"

	// TypeOK answers a request that has no result.
	TypeOK MessageType = "ok"
	// TypeError answers a request that failed (Error).
	TypeError MessageType = "error"
)

func WireType

func WireType(messageType MessageType, version int) MessageType

WireType is the name a peer speaking version knows a message type by.

type Metrics

type Metrics struct {
	At     time.Time      `json:"at"`
	Server *ServerMetrics `json:"server,omitempty"`
	Apps   []AppMetrics   `json:"apps,omitempty"`
}

Metrics is one sample of a server and the apps on it. Rates are per second since the sample before. Server is nil where the daemon cannot read the server's numbers, such as outside Linux.

type RegisterRequest

type RegisterRequest struct {
	Hello
}

RegisterRequest is the body of a register call.

type RegisterResponse

type RegisterResponse struct {
	ServerID    string `json:"server_id"`
	DaemonToken string `json:"daemon_token"`
}

RegisterResponse answers a register call. The daemon stores the token and uses it for every session.

type Release

type Release struct {
	Number int
	Build  bool
}

Release is one release of an app, for KeptReleases. Build is true when it brought something new.

type RestoreState

type RestoreState struct {
	ID         string     `json:"id"`
	Database   string     `json:"database"`
	State      string     `json:"state"`
	Error      string     `json:"error,omitempty"`
	FinishedAt *time.Time `json:"finished_at,omitempty"`
}

RestoreState is how a restore stands on the server: running, done or failed with Error.

type Rules

type Rules struct {
	// DataOff refuses tables, SQL, row edits and backup downloads.
	DataOff bool `json:"data_off,omitempty"`
	// LogsOff refuses container logs.
	LogsOff bool `json:"logs_off,omitempty"`
	// DeployFrom lists where deploys may come from, such as
	// "github.com/acme/*", "ghcr.io/acme/*" or "catalog". Empty allows all.
	DeployFrom []string `json:"deploy_from,omitempty"`
	// BackupsTo is the only bucket backups may go to and come from, as
	// "<endpoint host>/<bucket>". Empty allows any.
	BackupsTo string `json:"backups_to,omitempty"`
	// NetworkLocked refuses changes to the tunnel, Tailscale and firewall.
	NetworkLocked bool `json:"network_locked,omitempty"`
	// ExecOff refuses running commands in containers.
	ExecOff bool `json:"exec_off,omitempty"`
	// Mounts are folders of the server an app may mount, such as
	// "/mnt/media". Without them an app mounts only its own folders.
	Mounts []string `json:"mounts,omitempty"`
	// ServerAccess allows compose settings that reach beyond the app, such
	// as privileged containers or a mount of the Docker socket. Without it
	// the daemon refuses them, with or without a rules file.
	ServerAccess bool `json:"server_access,omitempty"`
}

Rules are what the owner of a server allows moin to do there, written in /etc/moin/rules on the server. The hub cannot change them; the daemon refuses every request they do not allow.

func (*Rules) Lines

func (r *Rules) Lines() []string

Lines are the rules as written in the rules file, for every surface to show them the same way.

type Schedule

type Schedule struct {
	Every int `json:"every_minutes"`
	Keep  int `json:"keep_days"`
}

Schedule is how an app is backed up: a copy every Every minutes, each kept Keep days.

type SecretSet

type SecretSet struct {
	Name  string `json:"name"`
	Value string `json:"value,omitempty"`
}

SecretSet keeps the secret Value under Name in the server's server.json; an empty Value removes it. Names say what a secret is for:

BucketSecret(id)      the secret key of a bucket
RegistrySecret(host)  a registry login, as <username>:<password>
SecretTailscale       the auth key that joins the server to a tailnet
SecretTunnel          the token of the server's Cloudflare Tunnel

type ServerConfig

type ServerConfig struct {
	SSH            string `json:"ssh,omitempty"`
	SSHOnTailscale bool   `json:"ssh_on_tailscale,omitempty"`
	Firewall       bool   `json:"firewall,omitempty"`
}

ServerConfig is how a server is reached and locked down. It carries no secret: the tunnel token and the Tailscale key are secrets the daemon keeps (SecretTunnel, SecretTailscale).

With a tunnel token the daemon runs cloudflared, which carries all app traffic from Cloudflare to Traefik; the proxy then opens no port. Without it Traefik takes 80 and 443. The Tailscale key joins the server to the user's tailnet when SSH is SSHTailscale. SSH says who SSH answers: SSHTailscale only through Tailscale, SSHEveryone, or SSHOff with sshd stopped. Firewall drops every other inbound connection.

SSHOnTailscale is SSH == SSHTailscale for daemons before SSH: the hub sends both, and a daemon without SSH reads SSHOnTailscale.

func (ServerConfig) WantSSH

func (c ServerConfig) WantSSH() string

WantSSH is who SSH should answer, also for a config from before SSH.

type ServerConfigResult

type ServerConfigResult struct {
	Proxy       string   `json:"proxy"`
	TailscaleIP string   `json:"tailscale_ip,omitempty"`
	SSH         string   `json:"ssh,omitempty"`
	Firewall    bool     `json:"firewall"`
	OpenPorts   []string `json:"open_ports"`
	Problems    []string `json:"problems,omitempty"`
	Fixed       []string `json:"fixed,omitempty"`
}

ServerConfigResult is what the daemon set up and what really is on the server. Problems are the parts it could not, in words; the rest stands. TailscaleIP is the server's address in a tailnet, also one joined by hand. SSH is who SSH answers now; daemons before it leave it empty. Fixed is what the daemon put back since its last report, in words, for the activity.

func (ServerConfigResult) OpenText

func (r ServerConfigResult) OpenText() string

OpenText says what the firewall leaves open to everyone, the same on every surface: "80, 443, 41641/udp", or "nothing". A TCP port is only its number.

type ServerMetrics

type ServerMetrics struct {
	// CPU is the busy share of all cores in percent, 0 to 100.
	CPU         float64 `json:"cpu"`
	Cores       int     `json:"cores,omitempty"`
	MemoryUsed  uint64  `json:"memory_used"`
	MemoryTotal uint64  `json:"memory_total"`
	DiskUsed    uint64  `json:"disk_used"`
	DiskTotal   uint64  `json:"disk_total"`
	// NetRx and NetTx are bytes per second in and out over the server's
	// own interfaces, not Docker's bridges.
	NetRx float64 `json:"net_rx"`
	NetTx float64 `json:"net_tx"`
	// Load is the load average over one minute.
	Load float64 `json:"load"`
}

ServerMetrics are the numbers of the whole server. Disk is the disk that holds the apps' data.

Jump to

Keyboard shortcuts

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