fleet

package
v0.4.118 Latest Latest
Warning

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

Go to latest
Published: Nov 20, 2026 License: Apache-2.0 Imports: 37 Imported by: ? 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 fleet lets one box be the master of the owner's other boxes: each member keeps an outbound tunnel to the master, and the master relays an allow-listed set of each box's own API routes so one dashboard sees and acts on all of them.

Index

Constants

View Source
const DefaultRelayURL = "https://relay.recasaos.org"

DefaultRelayURL is the official relay. Provisional: the owner picks the final name.

View Source
const MaxBody = 4 << 20

MaxBody bounds a relayed request or response body, in each direction.

View Source
const StateDir = "/var/lib/casaos/fleet"

StateDir holds master.json, member.json, relay.json and boxkey.json, under Root.

Variables

View Source
var (
	ErrOffline    = errors.New("box offline")
	ErrBusy       = errors.New("too many requests in flight for this box")
	ErrTimeout    = errors.New("the box did not answer in time")
	ErrNotAllowed = errors.New("this route is not relayed")
	ErrNoBox      = errors.New("no such box")
	ErrMasterOff  = errors.New("the master role is off")
)
View Source
var (
	// ErrRelayBusy: 429, 502 or 503. Retry later; the error is a *RelayBusyError carrying
	// the relay's Retry-After, when it gave one. A 503 "relay full" on CreateFleet is ErrRelayFull.
	ErrRelayBusy = errors.New("the relay is busy, try again later")
	// ErrRelayQuota: 409. The fleet is at its node quota, or holds too many unused join keys.
	ErrRelayQuota = errors.New("the relay refused: this fleet has reached its limit of boxes or unused join keys")
	// ErrRelayAuth: 401. The relay rejected the fleet secret (or, for CreateFleet, the box's signature,
	// which includes a clock too far off).
	ErrRelayAuth = errors.New("the relay rejected this box's credentials")
	// ErrRelayFleetGone: 404 on JoinKey, RemoveNode or FleetNodes, and the relay's JSON "fleet not
	// found" 404 on DeviceCode, Devices and RemoveDevice. The relay no longer knows the fleet, for
	// instance after it idled out.
	ErrRelayFleetGone = errors.New("the relay no longer knows this fleet")
	// ErrRelayFailed: another 5xx, the relay's own failure; the error names the status.
	ErrRelayFailed = errors.New("the relay failed to answer")
	// ErrRelayUnreachable wraps every transport failure (and the caller's cancelled context);
	// the cause stays reachable with errors.Is.
	ErrRelayUnreachable = errors.New("the relay cannot be reached")
	// ErrRelayNoDevices: 404 without the relay's JSON error on a device call. A relay older than
	// remote access answers an unknown path with Go's plain "404 page not found".
	ErrRelayNoDevices = errors.New("this relay does not offer remote access yet: its operator must update it")
	// ErrRelayFull: 503 "relay full, retry later" on CreateFleet. Unlike ErrRelayBusy, waiting a few
	// seconds does not help.
	ErrRelayFull = errors.New("the relay is full and takes no new network for now: try again later, or use another relay")
	// ErrTooManyDeviceCodes: 409 on DeviceCode.
	ErrTooManyDeviceCodes = errors.New("too many codes not used yet: use one, or wait until they expire (10 minutes)")
	// ErrRelayNoShare: 404 without the relay's JSON error, or 503 "sharing not enabled".
	ErrRelayNoShare = errors.New("this relay does not support public sharing")
	// ErrNodeUnknown: 404 {"error":"node not found"} on SetBoxKey.
	ErrNodeUnknown = errors.New("the relay does not know this box's node")
	// ErrBoxKeyLinked: 409 on SetBoxKey.
	ErrBoxKeyLinked = errors.New("a different key is already linked to this box at the relay")
)

The errors of the relay API, mapped from its status codes (see recasaos-relay, README "API"). None carries a secret, a key, a signature or anything the relay sent back: a response body is never quoted.

View Source
var (
	// ErrFleetFull: the relay refused one more join key (ErrRelayQuota). The
	// dashboard matches "limit of boxes" (FleetModal.vue): keep it in the text.
	ErrFleetFull error = &relayError{"the relay refused: this fleet has reached its limit of boxes, codes not used yet included: remove a box you no longer use, or wait for unused codes to expire (a day, by default)", ErrRelayQuota}
	// ErrFleetGone: the relay no longer knows the fleet (ErrRelayFleetGone), for instance after a long idle time.
	ErrFleetGone error = &relayError{"the relay no longer knows this fleet (it deletes idle fleets): enable the master on a relay again by changing the relay (the same one will do), then give each box a new code", ErrRelayFleetGone}
)
View Source
var (
	ErrRemoteOff = errors.New("remote access is off on this box")
	// ErrRemoteGone: the relay forgot a box's network; wraps ErrRelayFleetGone.
	ErrRemoteGone error = &relayError{"the relay no longer knows this box's network (it deletes networks idle for 30 days): turn remote access off and on again, then add your devices again", ErrRelayFleetGone}

	// ErrRemoteOn: Join would end remote access, which only a confirmed request may do.
	ErrRemoteOn = errors.New("this box has remote access: joining a fleet turns it off and its phones and PCs lose access; confirm to go on")
)
View Source
var Default = New("/")

Default is this box's fleet, wired by main.

View Source
var ErrNoPrivateNet = errors.New("the private network is not available on this box")

ErrNoPrivateNet is returned when the box has no private-network driver.

View Source
var ErrNoSystemctl = errors.New("the private network cannot be started on this box: systemctl was not found")

ErrNoSystemctl: tailscale is there, but not systemctl, which starts tailscaled.

View Source
var ErrNotFleetOwner = errors.New("only the master registers this box's key at the relay")

ErrNotFleetOwner: a member cannot register its key at the relay, only the fleet's owner can.

View Source
var ErrOtherNetwork = errors.New("this box is already in another private network")

ErrOtherNetwork is returned by Net.Up when the box is already connected to a private network other than the one asked for. The box is left untouched.

Functions

func Allowed

func Allowed(method, path string) (slow, ok bool)

Allowed says whether method+path (the path alone, no query) is in the table, and whether it is one of the slow routes. The path is compared as it is: no decoding, no trimming, no case folding, so the table cannot be reached around. A path carrying a character a URL reads as a delimiter or an escape (? # % \ or a control byte) is refused outright: an {id} that held one would turn a row of the table into another route once a request is built from it.

func CertFingerprint

func CertFingerprint(certFile string) (string, error)

CertFingerprint is the fingerprint of the first certificate in a PEM file.

func Fingerprint

func Fingerprint(cert *x509.Certificate) string

Fingerprint is the sha256 of a certificate as sent, hex: what a code pins.

func KeyHash

func KeyHash(key string) string

KeyHash is the sha256 of a key, hex: the only form of a key the master stores.

func NewKey

func NewKey() (key, keyHash string, err error)

NewKey makes a box's key (32 random bytes, hex) and the hash the master keeps.

func Timeout

func Timeout(slow bool) time.Duration

Timeout is how long the master waits for a box to answer one relayed request.

func ValidMasterURL

func ValidMasterURL(raw string) error

ValidMasterURL accepts https://host[:port], or plain http on this box's loopback (tests and the install check); never user info, a query or a fragment.

Types

type BackupsView added in v0.4.104

type BackupsView struct {
	Notify          bool         `json:"notify"`
	IntervalSeconds int          `json:"interval_seconds"`
	Boxes           []BoxBackups `json:"boxes"`
}

BackupsView is GET /v1/fleet/backups: every box of the fleet, and what the page needs to say who hears about a problem and how often boxes are read.

type Box

type Box struct {
	ID        string    `json:"id"`
	Name      string    `json:"name"`
	URL       string    `json:"url"`
	KeyHash   string    `json:"key_sha256"`
	Self      bool      `json:"self"`
	CreatedAt time.Time `json:"created_at,omitzero"`
	LastSeen  time.Time `json:"last_seen,omitzero"`
	Hostname  string    `json:"hostname"`
	Version   string    `json:"version"`
	// WebScheme and WebPort: where the box says its dashboard listens (validated hello), empty if unknown.
	WebScheme string `json:"web_scheme,omitempty"`
	WebPort   string `json:"web_port,omitempty"`
	// NeedsRecode: the master changed relay since this box's code was made, so the box
	// still looks for it on the old relay's network; cleared by RotateCode.
	NeedsRecode bool `json:"needs_recode,omitempty"`
}

Box is one enrolled box as the master keeps it: its key only hashed.

type BoxBackups added in v0.4.104

type BoxBackups struct {
	BoxID                string                `json:"box_id"`
	Name                 string                `json:"name"`
	Online               bool                  `json:"online"`
	PolledAt             time.Time             `json:"polled_at,omitzero"`
	Stale                bool                  `json:"stale"`
	Error                string                `json:"error"`
	State                string                `json:"state"`
	Green                bool                  `json:"green"`
	Problems             int                   `json:"problems"`
	Couples              []Couple              `json:"couples"`
	VerificationSchedule *VerificationSchedule `json:"verification_schedule,omitempty"`
}

BoxBackups is one box's backups as GET /v1/fleet/backups shows them.

type BoxStatus

type BoxStatus struct {
	ID       string    `json:"id"`
	Name     string    `json:"name"`
	URL      string    `json:"url"`
	Self     bool      `json:"self"`
	Online   bool      `json:"online"`
	LastSeen time.Time `json:"last_seen,omitzero"`
	Hostname string    `json:"hostname"`
	Version  string    `json:"version"`
	// NeedsRecode: the master changed relay; the box needs a new code (RotateCode) to follow it.
	NeedsRecode bool `json:"needs_recode,omitempty"`
	// ShareKey: whether the box's key is linked at the relay, "linked" or "error: <message>"; "" with no relay, for this box itself, or before the box said hello.
	ShareKey string `json:"share_key,omitempty"`
}

BoxStatus is one box as the dashboard sees it: never its key.

type Code

type Code struct {
	MasterURL  string `json:"u"`
	BoxID      string `json:"b"`
	Key        string `json:"k"`
	CertSHA256 string `json:"f"`
	Relay      string `json:"r,omitempty"`
	JoinKey    string `json:"j,omitempty"`
	// Fleet is the master's fleet at the relay: a member told to join another one
	// leaves its own first. Absent from the codes of an older master.
	Fleet string `json:"n,omitempty"`
}

Code is what the owner copies from the master into a box's settings: where the master is, which box this is, the box's key, and the fingerprint of the master's certificate for when its chain does not verify. When the fleet runs over a relay, it also carries the relay's address and the key to join it (no key for a box that was on the relay's network when the code was made). It is shown once.

func ParseCode

func ParseCode(s string) (Code, error)

ParseCode reads a pasted code back, refusing anything a box could not join with.

func (Code) String

func (c Code) String() string

String is the one line the owner copies.

type Couple added in v0.4.104

type Couple struct {
	App         string       `json:"app"`
	Destination string       `json:"destination"`
	State       string       `json:"state"`
	Running     bool         `json:"running"`
	LastRunAt   time.Time    `json:"last_run_at,omitzero"`
	LastOKAt    time.Time    `json:"last_ok_at,omitzero"`
	LastOKStamp string       `json:"last_ok_stamp"`
	LastError   string       `json:"last_error"`
	NextSlot    time.Time    `json:"next_slot,omitzero"`
	Restic      bool         `json:"restic"`
	ResticCheck *ResticCheck `json:"restic_check"`
	Verify      CoupleVerify `json:"verify"`
	// contains filtered or unexported fields
}

Couple is one (app, destination) pair with an enabled schedule.

type CoupleVerify added in v0.4.104

type CoupleVerify struct {
	State string    `json:"state"`
	At    time.Time `json:"at,omitzero"`
	Error string    `json:"error"`
}

CoupleVerify is the last restore test of a couple: none, passed, failed, not_verifiable, running or unknown.

type Device added in v0.4.96

type Device struct {
	ID       string    `json:"id"`
	Hostname string    `json:"hostname"`
	IP       string    `json:"ip"`
	Online   bool      `json:"online"`
	LastSeen time.Time `json:"last_seen,omitzero"`
}

Device is a phone or PC that joined with a code.

type DeviceCode added in v0.4.96

type DeviceCode struct {
	Code      string    `json:"code"`
	ExpiresAt time.Time `json:"expires_at"`
}

DeviceCode is a one-time code a phone or PC types to join the fleet's network.

type Fleet

type Fleet struct {
	Root        string                                 // "/" on a box; a temp dir in tests
	RuntimePath func() string                          // where internal.secret lives
	Now         func() time.Time                       // the clock of what is recorded
	Log         func(msg string, err error)            // one line when a file cannot be read
	Gateway     func() (GatewayInfo, error)            // where this box's gateway listens
	Hostname    func() (string, error)                 // this box's name, said in the hello
	Version     func() string                          // this box's ReCasaOS version, said in the hello
	Offline     func(boxID, name string, offline bool) // the alerts hub's hook: a box gone, or back
	Net         Net                                    // the private network; nil in New: callers go through PrivateNet
	RelayAPI    *RelayClient                           // the relay's enrolment API; boxkey.json in the state directory

	// OnLeavingRelay is called just before this box leaves its relay, while it can still sign a call to it; nil in New.
	OnLeavingRelay func()

	// BackupProblem is the alerts hub's hook: a box's backup problem, raised at every pass while it lasts, or resolved.
	BackupProblem func(key, sentence string, problem bool)
	Notifies      func() bool // whether the hub would send a Fleet alert anywhere: said by the page, never asked by the poller
	// contains filtered or unexported fields
}

Fleet holds both roles of one box. Its func fields are what main wires and tests replace.

func New

func New(root string) *Fleet

New makes a Fleet rooted at root, with the box's defaults.

func (*Fleet) AddBox

func (f *Fleet) AddBox(name, link string, self bool) (Box, Code, error)

AddBox enrols a box and returns its code, the one time the key is handed over. self enrols this box itself: its code points at its own gateway, and its member.json is written. There is at most one self box. Over a relay, the code of another box also carries a join key asked of the relay first: when the relay refuses (ErrFleetFull, ErrFleetGone, ErrRelayBusy...) no box is added.

func (*Fleet) BackupsView added in v0.4.104

func (f *Fleet) BackupsView() (BackupsView, bool)

BackupsView lists one entry per box of the fleet, in the master's order, from the last snapshots. Online is the tunnel at this moment; a box never polled is "unknown"; a snapshot older than staleAfter is stale. Only an online, fresh, error-free box can be green. false: this box is not a master.

func (*Fleet) BoxKey added in v0.4.111

func (f *Fleet) BoxKey() (ed25519.PrivateKey, error)

BoxKey is this box's signing key, made on first use.

func (*Fleet) ChangeRelay added in v0.4.93

func (f *Fleet) ChangeRelay(ctx context.Context, relayURL string) error

ChangeRelay moves a master running over a relay to relayURL (DefaultRelayURL when empty): a fleet is created there, this box leaves the old private network for the new one, and the old fleet is deleted. The same relay is allowed: a new fleet there, which is how a fleet the relay forgot (ErrFleetGone) is replaced.

Every other box is then marked NeedsRecode: its key stays valid, but it still looks for the master on the old network, and its old code no longer works either, its join key belonging to the deleted fleet. RotateCode gives it a code for the new relay.

Nothing changes when the new relay fails before this box left the old network (its fleet, if created, is deleted again). A box is in one private network at a time, and a left one cannot be rejoined with its old node: when joining the new network fails after that, the new fleet is dropped, master.json and relay.json still name the old relay, and the error says this box is off the private network until the relay is changed again.

func (*Fleet) Devices added in v0.4.96

func (f *Fleet) Devices(ctx context.Context) ([]Device, error)

Devices lists the phones and PCs on the network.

func (*Fleet) DisableMaster

func (f *Fleet) DisableMaster() error

DisableMaster closes every tunnel and forgets the boxes. A self-enrolled master's own member.json pointed at this box's own gateway, which goes with the master, so it is cleared too; a member.json of another fleet is left. Over a relay, the fleet is then deleted there and the private network left, best-effort: the local disable never fails because the relay is down. With no master on, the remote access of a box alone is left as it is.

func (*Fleet) DisableRemote added in v0.4.96

func (f *Fleet) DisableRemote(ctx context.Context) error

DisableRemote turns remote access off: the fleet of one is deleted at the relay (best-effort), the private network left and relay.json removed. When the network cannot be left, relay.json is kept and the error returned: the box never sits on a network nothing records. The network of a member.json naming another fleet may be that member's: it is not left. A master's fleet is not touched, and no remote access is not an error.

func (*Fleet) EnableMaster

func (f *Fleet) EnableMaster(address string) error

EnableMaster turns the role on at address, keeping the boxes already enrolled. A box that is a member of another fleet cannot become a master: the two roles are exclusive (a self-enrolled master's own member.json names itself, which is not another fleet). A master running over a relay is not switched to an address typed by hand: it is disabled first.

func (*Fleet) EnableMasterRelay added in v0.4.93

func (f *Fleet) EnableMasterRelay(ctx context.Context, relayURL string) error

EnableMasterRelay turns the role on over a relay (DefaultRelayURL when relayURL is empty): a fleet is created there, this box joins its private network, and the master's address is this box's address on it. Nothing is asked of the relay before every local check passed, and what was done is undone on a later failure. A master already on over this relay is left as it is; one on over another relay changes relay instead.

func (*Fleet) EnableRemote added in v0.4.96

func (f *Fleet) EnableRemote(ctx context.Context, relayURL string) error

EnableRemote gives a box with no fleet remote access: a fleet of one is created at the relay (DefaultRelayURL when relayURL is empty) and this box joins its private network; relay.json is flagged remote and there is no master.json. Phones join it with codes later. Nothing is asked of the relay before every local check passed. Already on, over this relay or as a master over a relay, is left as it is.

func (*Fleet) HandleTunnel

func (f *Fleet) HandleTunnel(w http.ResponseWriter, r *http.Request)

HandleTunnel is GET /v1/fleet/tunnel: a box's tunnel. 401 unless the Authorization header is "Fleet <id>:<key>" of an enrolled box; then the hello, then res frames until the connection goes. A member's req frame is ignored: only the master asks.

func (*Fleet) Join

func (f *Fleet) Join(code string) error

Join makes this box a member: the code is kept in member.json and the loop dials at once. A master does not join another fleet.

A code that names a relay first joins the relay's private network with its join key (ErrOtherNetwork when the box is in another one, untouched), and member.json is written only once the box has an address there; on a failure after that, the network is left again and nothing is saved. The join key is spent: it is never kept.

func (*Fleet) Leave

func (f *Fleet) Leave() error

Leave closes the tunnel and forgets the master. A member over a relay then leaves its private network, best-effort: the local leave never fails for it. It does so for the network of a Join that did not finish too (netown.json). It waits for a Join in progress (relayMu), never cutting one half-way.

func (*Fleet) MasterStatus

func (f *Fleet) MasterStatus() (MasterStatus, bool)

MasterStatus is the master's view: ok is false when the role is off.

func (f *Fleet) MemberLink() (masterURL, boxID string, ok bool)

MemberLink is the master's address and this box's id there, for a link into the master. ok is false when the box is no member, or when the master is this box itself (a loopback address). ok is also false for a relay member, whose master_url is a private-network address a phone cannot reach.

func (*Fleet) MemberStatus

func (f *Fleet) MemberStatus() (MemberStatus, bool)

MemberStatus is the member's view: ok is false when the role is off.

func (*Fleet) NewDeviceCode added in v0.4.96

func (f *Fleet) NewDeviceCode(ctx context.Context) (DeviceCode, error)

NewDeviceCode asks the relay for a code a phone or PC joins the network with.

func (*Fleet) PrivateNet added in v0.4.93

func (f *Fleet) PrivateNet() (Net, error)

PrivateNet returns the box's private-network driver, or ErrNoPrivateNet when Fleet.Net is nil.

func (*Fleet) RefreshBackups added in v0.4.104

func (f *Fleet) RefreshBackups(boxID string)

RefreshBackups asks for a pass over one box soon. It never blocks (safe under f.mu): a wake that finds the queue full is dropped, the next pass reads the box.

func (*Fleet) RegisterOwnBoxKey added in v0.4.111

func (f *Fleet) RegisterOwnBoxKey(ctx context.Context) error

RegisterOwnBoxKey links this box's key to its own node at the relay, with the fleet secret of relay.json and the node id of the private network. A member gets ErrNotFleetOwner.

func (*Fleet) Relay

func (f *Fleet) Relay(ctx context.Context, boxID, method, path, query, contentType string, body []byte) (Response, error)

Relay sends one request down the box's tunnel and returns what the box answered. The table is checked here, before anything reaches the tunnel.

func (*Fleet) RemoteView added in v0.4.96

func (f *Fleet) RemoteView(ctx context.Context) (RemoteView, error)

RemoteView asks the relay for the devices and, on a master, the boxes' nodes.

func (*Fleet) RemoveBox

func (f *Fleet) RemoveBox(id string) error

RemoveBox revokes a box: its tunnel is closed and its key is worth nothing. Over a relay, the box is then taken off the private network too, best-effort: the local removal never fails because the relay is down.

func (*Fleet) RemoveDevice added in v0.4.96

func (f *Fleet) RemoveDevice(ctx context.Context, id string) error

RemoveDevice takes one phone or PC off the network.

func (*Fleet) RenameBox

func (f *Fleet) RenameBox(id string, name, link *string) error

RenameBox changes the name and/or the dashboard link of a box; nil leaves one as it is.

func (*Fleet) RotateCode

func (f *Fleet) RotateCode(id string) (Code, error)

RotateCode gives a box a new key: the old one is worth nothing and its tunnel is closed; the new code is returned once. Over a relay, it names the relay the master runs over now (which clears NeedsRecode), and carries a new join key unless the box is online and need not follow the master to another relay: such a box is on the network already, and an unused join key would count against the fleet's quota at the relay until it expires. A box that left the network meanwhile is told by Join to ask for a new code, which then carries one (rotating closed its tunnel). When the relay refuses a join key, the old key stays as it was.

func (*Fleet) Run

func (f *Fleet) Run(ctx context.Context)

Run is the member loop, started once by main: while member.json exists, keep a tunnel to the master and serve what it relays; otherwise wait for a code.

func (*Fleet) ShareRelay added in v0.4.111

func (f *Fleet) ShareRelay() (relay string, ok bool)

ShareRelay is the relay this box shares through: relay.json's for a master or a box alone, member.json's for a member.

func (*Fleet) Status

func (f *Fleet) Status() Status

Status says which role this box plays and its state. The role is master when the master is on (a self-enrolled master also has a member half, its own tunnel), member when only member.json exists, else none.

type FleetCreds added in v0.4.93

type FleetCreds struct {
	FleetID     string
	Secret      string
	LoginServer string // the coordination server boxes join; valid by the ValidMasterURL rule
}

FleetCreds is what the relay hands out once, when a fleet is created.

type FleetNode added in v0.4.96

type FleetNode struct {
	Hostname, IP string
	Online       bool
}

FleetNode is a box of the fleet as the relay sees it.

type GatewayInfo

type GatewayInfo struct {
	Public       *url.URL // http(s)://127.0.0.1:<port>: where a member executes relayed requests
	HTTPS        *url.URL // https://127.0.0.1:<httpsport or 443>; nil when a configured certificate makes Public itself https, or HTTPS is off (httpsport=0)
	CertFile     string   // the certificate the gateway serves: tlscert, or the default self-signed one
	LoopbackOnly bool     // the gateway is bound to the loopback address alone: fine for the box itself, not for a master that other boxes reach over a network
	Unreachable  string   // non-empty when the gateway is bound off loopback: the member cannot relay, and says so, but the master can still read the certificate to enrol boxes
}

GatewayInfo is where this box's gateway listens, as seen from the box itself.

func ReadGatewayINI

func ReadGatewayINI(path, dataPath string) (GatewayInfo, error)

ReadGatewayINI reads [gateway] port, address, tlscert, tlskey and httpsport from path; dataPath is where the default certificate lives (/var/lib/casaos). It errors only on config a box cannot use at all (no port, a bad httpsport). A gateway bound off loopback, and HTTPS turned off with httpsport=0, are normal states, not errors: the member's relay reports the first, and the certificate is still read so the master can enrol boxes.

type MasterState

type MasterState struct {
	Enabled bool   `json:"enabled"`
	Address string `json:"address"`
	Boxes   []Box  `json:"boxes"`
	Relay   string `json:"relay,omitempty"`
	FleetID string `json:"fleet_id,omitempty"`
	NetAddr string `json:"net_addr,omitempty"`
}

MasterState is master.json. Over a relay, it names the relay and the fleet there, and this box's address on the private network; the fleet's secret is in relay.json only.

type MasterStatus

type MasterStatus struct {
	Address string      `json:"address"`
	Boxes   []BoxStatus `json:"boxes"`
	Relay   string      `json:"relay,omitempty"`    // the relay the master runs over; none in advanced mode
	NetAddr string      `json:"net_addr,omitempty"` // this box's address on the relay's private network
	// Over a relay: whether this box is on its private network now (cached
	// netEvery), NetError saying why not.
	NetConnected bool   `json:"net_connected,omitempty"`
	NetError     string `json:"net_error,omitempty"`
}

MasterStatus is the master half of GET /v1/fleet.

type MemberState

type MemberState struct {
	MasterURL        string `json:"master_url"`
	BoxID            string `json:"box_id"`
	Key              string `json:"key"`
	MasterCertSHA256 string `json:"master_cert_sha256"`
	Relay            string `json:"relay,omitempty"`
	// FleetID is the code's fleet at the relay: another fleet's code makes this
	// box leave this one first. Empty for a code of an older master.
	FleetID string `json:"fleet_id,omitempty"`
}

MemberState is member.json: the code the owner pasted, kept, without its join key (spent on joining the relay's private network).

type MemberStatus

type MemberStatus struct {
	MasterURL string    `json:"master_url"`
	Connected bool      `json:"connected"`
	Since     time.Time `json:"since,omitzero"`
	LastError string    `json:"last_error,omitempty"`
	LastTry   time.Time `json:"last_try,omitzero"`
	// Over a relay: the relay, and whether this box is on its private network
	// (NetError says why not). Nothing repairs it: a stopped or logged-out box
	// joins again with a new code.
	Relay        string `json:"relay,omitempty"`
	NetConnected bool   `json:"net_connected,omitempty"`
	NetError     string `json:"net_error,omitempty"`
}

MemberStatus is the member half of GET /v1/fleet.

type Net added in v0.4.93

type Net interface {
	State(ctx context.Context) (NetState, error)
	// Up joins the network of loginServer. It returns ErrOtherNetwork if the
	// box is already in another one, leaving it as it was. On any error, Up has
	// undone what it did itself: the caller has nothing to take down.
	Up(ctx context.Context, loginServer, authKey, hostname string) error
	// Down leaves the network and stops the daemon. Only for a network this box
	// joined itself, the one of relay: a login to any other server is left alone
	// (an empty relay logs out whatever the box is logged in to). It returns nil
	// only once the box is logged out of that network, or was in none.
	Down(ctx context.Context, relay string) error
}

Net drives the box's private network.

func NewTailscale added in v0.4.93

func NewTailscale(run func(ctx context.Context, args ...string) ([]byte, error)) Net

NewTailscale returns a Net over the tailscale command. A nil run executes the real command.

type NetState added in v0.4.93

type NetState struct {
	Connected bool
	Addr      string // this box's address on the private network
	// LoginServer is the coordination server the box is logged in to, without a
	// trailing slash, connected or not (a stopped tailscale is still in its
	// network); empty when the box is in none.
	LoginServer string
	// RelayUnreachable: connected, with an address, but the coordination server
	// does not answer (tailscale reports this node offline). Links already made
	// may carry on; nothing new can join.
	RelayUnreachable bool
	// NodeID is this node's id at the coordination server (Headscale's numeric id, as a
	// decimal string); empty when not running.
	NodeID string
}

NetState is what the box's private network looks like right now.

type RelayBusyError added in v0.4.93

type RelayBusyError struct{ RetryAfter time.Duration }

RelayBusyError is the ErrRelayBusy a client gets, with how long the relay asked to wait (0 when it did not say). errors.Is(err, ErrRelayBusy) holds.

func (*RelayBusyError) Error added in v0.4.93

func (e *RelayBusyError) Error() string

func (*RelayBusyError) Is added in v0.4.93

func (e *RelayBusyError) Is(target error) bool

type RelayClient added in v0.4.93

type RelayClient struct {
	HTTP *http.Client     // nil: a client with a 15 s timeout. Redirects are never followed.
	Now  func() time.Time // nil: time.Now. Stamps X-Box-Time.
	Dir  string           // where boxkey.json lives (StateDir under Root on a box); required by CreateFleet
}

RelayClient talks to a recasaos-relay. The zero value works except for Dir.

func (*RelayClient) CreateFleet added in v0.4.93

func (c *RelayClient) CreateFleet(ctx context.Context, relay string) (FleetCreds, error)

CreateFleet asks the relay for a new fleet, signing with the box's key (made on first use in c.Dir): POST /v1/fleets, answered 201. Errors: ErrRelayAuth (signature or clock refused), ErrRelayFull (503 "relay full"), ErrRelayBusy (429, another 503), ErrRelayUnreachable, or an error naming the status or saying the answer was not valid. The login server it returns is checked as a master address, since boxes pass it to tailscale up.

func (*RelayClient) DeleteFleet added in v0.4.93

func (c *RelayClient) DeleteFleet(ctx context.Context, relay, fleetID, secret string) error

DeleteFleet deletes the fleet: DELETE /v1/fleets/{id}, answered 204. A 404 means the relay already deleted it (the secret authenticates nothing once the fleet is gone), which is what the caller wanted: nil. Errors: ErrRelayAuth, ErrRelayBusy, ErrRelayUnreachable; after one the same call can be repeated.

func (*RelayClient) DeviceCode added in v0.4.96

func (c *RelayClient) DeviceCode(ctx context.Context, relay, fleetID, secret string) (DeviceCode, error)

DeviceCode asks for a device code: POST /v1/fleets/{id}/device-codes, answered 201. Errors: ErrRelayAuth, ErrRelayFleetGone, ErrRelayNoDevices (old relay), ErrTooManyDeviceCodes (409), ErrRelayBusy, ErrRelayUnreachable.

func (*RelayClient) Devices added in v0.4.96

func (c *RelayClient) Devices(ctx context.Context, relay, fleetID, secret string) ([]Device, error)

Devices lists the fleet's devices: GET /v1/fleets/{id}/devices, answered 200. Errors as DeviceCode, minus ErrTooManyDeviceCodes. The slice is never nil on success.

func (*RelayClient) FleetNodes added in v0.4.96

func (c *RelayClient) FleetNodes(ctx context.Context, relay, fleetID, secret string) ([]FleetNode, error)

FleetNodes lists the fleet's boxes: GET /v1/fleets/{id}, answered 200. Errors as Devices, but any 404 is ErrRelayFleetGone: that path exists on every relay version.

func (*RelayClient) JoinKey added in v0.4.93

func (c *RelayClient) JoinKey(ctx context.Context, relay, fleetID, secret string) (key string, expires time.Time, err error)

JoinKey asks for a single-use key for one more box: POST /v1/fleets/{id}/keys with the fleet secret, answered 201. Errors: ErrRelayAuth, ErrRelayFleetGone (404), ErrRelayQuota (409), ErrRelayBusy (429, 502, 503), ErrRelayUnreachable.

func (*RelayClient) RemoveDevice added in v0.4.96

func (c *RelayClient) RemoveDevice(ctx context.Context, relay, fleetID, secret, id string) error

RemoveDevice removes one device: DELETE /v1/fleets/{id}/devices/{id}, answered 204. The id is the relay's node number, digits only; anything else is refused before a request leaves.

func (*RelayClient) RemoveNode added in v0.4.93

func (c *RelayClient) RemoveNode(ctx context.Context, relay, fleetID, secret, hostname string) error

RemoveNode removes one box from the fleet: DELETE /v1/fleets/{id}/nodes/{hostname}, answered 204, also for a hostname the fleet does not have. Errors as JoinKey, minus ErrRelayQuota.

func (*RelayClient) SetBoxKey added in v0.4.111

func (c *RelayClient) SetBoxKey(ctx context.Context, relay, fleetID, secret, nodeID string, pub ed25519.PublicKey) error

SetBoxKey links the box's public key to its node: PUT /v1/fleets/{id}/nodes/{node}/box-key with the fleet secret, answered 204. Errors: ErrNodeUnknown, ErrRelayNoShare, ErrBoxKeyLinked, ErrRelayAuth, ErrRelayBusy, ErrRelayUnreachable.

func (*RelayClient) Signed added in v0.4.111

func (c *RelayClient) Signed(ctx context.Context, relay, method, path string, body []byte, maxReply int) (status int, reply []byte, retryAfter time.Duration, err error)

Signed calls the relay as this box: the X-Box-* headers over "<METHOD> <PATH>\n"+time, a JSON body when body != nil. It returns the status, the body (cut at maxReply bytes, 64 KiB when 0) and a 429's Retry-After (0 otherwise) whatever the status; only a transport failure is an error (ErrRelayUnreachable).

type RelayState added in v0.4.93

type RelayState struct {
	Relay   string `json:"relay"`
	FleetID string `json:"fleet_id"`
	Secret  string `json:"secret"`
	Remote  bool   `json:"remote,omitempty"`
	NetAddr string `json:"net_addr,omitempty"`
}

RelayState is relay.json: the fleet this master owns at its relay. The secret lives here only, never in master.json, a log line or an error.

type RemoteBox added in v0.4.96

type RemoteBox struct {
	ID     string `json:"id"`
	Name   string `json:"name"`
	Addr   string `json:"addr"`
	Online bool   `json:"online"`
	URL    string `json:"url,omitempty"` // where the dashboard is, when the box told its scheme and port
}

RemoteBox is a box of the master's fleet on the private network.

type RemoteStatus added in v0.4.96

type RemoteStatus struct {
	Relay     string `json:"relay"`
	Addr      string `json:"addr,omitempty"`
	Connected bool   `json:"connected"`
	Error     string `json:"error,omitempty"`
	Alone     bool   `json:"alone"`
}

RemoteStatus is the box's remote access as last known locally; no relay call is made for it.

type RemoteView added in v0.4.96

type RemoteView struct {
	Relay   string      `json:"relay"`
	Addr    string      `json:"addr"`
	Devices []Device    `json:"devices"`
	Boxes   []RemoteBox `json:"boxes,omitempty"`
}

RemoteView is what the dashboard shows of remote access: the devices, and for a master its boxes.

type Response

type Response struct {
	Status      int
	ContentType string
	Body        []byte
}

Response is what a box answered to a relayed request, passed on as it is.

type ResticCheck added in v0.4.104

type ResticCheck struct {
	At    time.Time `json:"at,omitzero"`
	OK    bool      `json:"ok"`
	Error string    `json:"error,omitempty"`
}

ResticCheck is the last integrity check of a restic destination.

type Status

type Status struct {
	Role   string        `json:"role"` // none | master | member
	Master *MasterStatus `json:"master,omitempty"`
	Member *MemberStatus `json:"member,omitempty"`
	Remote *RemoteStatus `json:"remote,omitempty"`
}

Status is GET /v1/fleet: the role, and the half that is on.

type VerificationSchedule added in v0.4.104

type VerificationSchedule struct {
	Enabled   bool      `json:"enabled"`
	EveryDays int       `json:"every_days"`
	At        string    `json:"at"`
	LastRun   time.Time `json:"last_run,omitzero"`
}

VerificationSchedule is the box schedule of restore tests.

Jump to

Keyboard shortcuts

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