fleet

package
v0.2.1 Latest Latest
Warning

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

Go to latest
Published: Nov 23, 2026 License: AGPL-3.0 Imports: 74 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package fleet is the panel side of the node fleet: the panel CA and the agent endpoint (mTLS), node enrollment, the agent stream (liveness, reliable stats/events ingestion), desired-state computation and push, and the admin NodeService / FleetService handlers backed by that data.

Index

Constants

View Source
const APIVersion = 1

APIVersion is the agent wire API version this panel serves (Hello.api_version, EnrollRequest.api_version).

View Source
const AssetMarkerHeader = "X-Mistgate-Asset"

AssetMarkerHeader carries the release asset URL of a download answer; the Worker streams that URL and strips the header.

View Source
const LinkMarkerHeader = "X-Mistgate-Link"

LinkMarkerHeader carries the node id of a LinkMarker answer; the Worker strips it.

Variables

View Source
var ErrGlobalpingOff = errors.New("fleet: Globalping is off")

ErrGlobalpingOff marks the owner's explicit choice to switch Globalping off.

View Source
var ErrIPv6Address = errors.New("fleet: not a global IPv6 address")

ErrIPv6Address: the address given to CheckIPv6 is not a global unicast IPv6 address.

Functions

func LinkChallenge added in v0.1.27

func LinkChallenge(audience string) (nonce, frame []byte, err error)

LinkChallenge is the panel's first handshake frame: a fresh nonce bound to the host the agent dialled. The VPS handler and the edge Durable Object both run it.

func LinkMarker added in v0.1.27

func LinkMarker() http.Handler

LinkMarker is what LinkHandler answers with on the edge (Config.Remote set): a Worker cannot keep a WebSocket in the panel's wasm, so a GET with an upgrade is answered 204 with the node's id, and the Worker hands the original request to that node's Durable Object.

Types

type AdminRequest added in v0.1.26

type AdminRequest struct {
	RequestID string
	Deadline  time.Time
	Frame     *agentv1.ConnectResponse
	Record    bool // update/rollback command results are persisted instead of replied to the request adapter
}

AdminRequest carries a request frame and its correlation metadata into the core.

type CloseClass added in v0.1.26

type CloseClass uint8

CloseClass identifies why a session should terminate.

const (
	CloseInvalidArgument CloseClass = iota + 1
	CloseFailedPrecondition
	CloseUnauthenticated
	CloseConflict
	CloseDeadline
	CloseInternal
	CloseCanceled
)

type Config

type Config struct {
	// AgentSNI is the secret server name of the agent endpoint (e.g. "q3m8x2kd7w.invalid"). Required.
	AgentSNI string
	// PanelAddr is the host:port agents dial; it goes into the install command. Required for CreateEnrollment.
	PanelAddr string
	// LinkURL is the base link-only agents are given (wss://host/<secret-prefix>/): the install command of an edge panel
	// (Remote set) carries it instead of PanelAddr and the agent SNI. Empty = no link install command.
	LinkURL string
	// JournalSecrets are this panel's secret SNI and path prefixes; the journal writer scrubs them from node-provided text.
	JournalSecrets []string
	// LinkServed reports whether the signed WebSocket agent link is mounted on the public listener.
	LinkServed bool
	// Remote sends admin requests through the edge edition's node link. Nil uses the VPS stream adapter.
	Remote Remote
	// AfterResponse starts work that must not delay a request response. Nil uses a goroutine.
	AfterResponse func(func())
	// ExpectedAgentVersion is the newest agent version this panel ships (ListNodes marks older agents).
	ExpectedAgentVersion string
	// DecoyDir is the panel's own --decoy-dir bundle. Empty means new nodes default to builtin.
	DecoyDir string
	// PublicURL is the panel's public address (its public listener shows the panel's decoy site there). Empty = not known.
	PublicURL string
	// Debounce is the StateChanged coalescing window. Default 200 ms.
	Debounce time.Duration
	// Desired is the desired-state source, required: it returns the enabled inbounds of a node with their
	// complete credential sets (the access module's effective-access rule, so it exists once). Spec.ID must
	// be set. This module owns revisions, hashes, deltas and push.
	Desired func(ctx context.Context, nodeID string) ([]statehash.Inbound, error)
	// MaxNodeBytesPerSec is the most traffic one node may report in total per second of a stats interval; a batch
	// above it is dropped (see statsguard.go). Default 1.25e9 bytes/s (10 Gbit/s).
	MaxNodeBytesPerSec uint64
	// OnUsage is called after a stats batch added usage to these users (new used_bytes are committed), e.g.
	// access.Service.Recompute, so a quota overrun takes effect within one stats interval.
	OnUsage func(ctx context.Context, userIDs []string)
	// OnAwgPrepareFailed is called once when a panel-requested AmneziaWG build transitions from running to failed. at is
	// the panel time. Must not block.
	OnAwgPrepareFailed func(nodeID, code string, at int64)
	// GlobalpingTCP6 asks Globalping for a TCP ping of port on an IPv6 address from probes around the world, and says how many
	// probes answered and how many of them connected. It is the last resort of CheckIPv6, when no node can send over IPv6. Nil means
	// there is no Globalping source; ErrGlobalpingOff distinguishes an explicitly disabled source from a failed check.
	GlobalpingTCP6 func(ctx context.Context, addr string, port uint16) (answered, connected int, err error)
	// Actor returns the admin id for audit rows. Default: the signed-in admin from the auth interceptor.
	Actor func(context.Context) string
	Log   *slog.Logger
	// Now is the clock (tests). Default time.Now.
	Now func() time.Time
	// Limiter is the shared backend for security-sensitive limits. Nil uses bounded in-memory state.
	Limiter securitylimit.Limiter
}

Config configures Fleet.

type CountryProbeRequest added in v0.1.42

type CountryProbeRequest struct {
	Control    string // an IPv4 address that is not blocked in the country (RU: 77.88.55.88)
	ControlSNI string // reserved, the SYN method sends no hello
	BlockedRef string // an IPv4 address that is blocked in the country; "" = the agent answers no_dpi_hop
	Targets    []CountryProbeTarget
	HopLimit   uint32
	MaxTTL     uint32
}

CountryProbeRequest is what the scheduler asks of a probe node. HopLimit and MaxTTL are 0 for the agent's defaults (3 and 30).

type CountryProbeResult added in v0.1.42

type CountryProbeResult struct {
	DPIHop    int
	ControlOK bool
	Verdicts  map[string]string
	Code      string
	Reason    string
}

CountryProbeResult is the agent's answer. Code is "" when the probe ran; otherwise the agent's word for why it did not: control_failed (the method does not apply on that network, no verdict about any node; DPIHop is set), no_dpi_hop, busy, bad_params, unsupported_host, unsupported, or failed. Verdicts maps "host:port" to blocked | open | refused | timeout, for the pairs the agent answered. Reason is the agent's word for why a no_dpi_hop could not place the box (ref_open, ref_refused, no_hops, no_ref); "" for any other code and for an agent that does not say.

type CountryProbeTarget added in v0.1.42

type CountryProbeTarget struct {
	Host  string
	Ports []uint16
}

CountryProbeTarget is one fleet node as the panel knows it: node.address and the TCP ports to test.

type DebugStart

type DebugStart struct {
	NodeID    string
	Level     string // "debug" or "info"
	Sources   []string
	DurationS uint32
}

DebugStart is a request to capture one node.

type EffectKind added in v0.1.26

type EffectKind uint8

EffectKind identifies an adapter action requested by the session core.

const (
	EffectUsage EffectKind = iota + 1
	EffectReply
	EffectLogChunk
	EffectWarpAttention
	EffectPrepareDesired
	EffectConnectEvents
	EffectRecordAnswer
)

type EventKind added in v0.1.26

type EventKind uint8

EventKind identifies one input that the session core can process.

const (
	EventOpen EventKind = iota + 1
	EventHello
	EventAgentFrame
	EventDesiredChanged
	EventDesiredPrepared
	EventAdminCommand
	EventLogStart
	EventLogCancel
	EventAlarm
	EventDisconnected
	EventOwnerSuperseded
)

type Fleet

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

Fleet is the fleet module.

func New

func New(st *store.Store, v *vault.Vault, reg *protocols.Registry, cfg Config) (*Fleet, error)

New builds the module: it loads (or creates) the panel CA. Call Run to start the background work.

func (*Fleet) AgentHandler

func (f *Fleet) AgentHandler() http.Handler

AgentHandler serves EnrollmentService and AgentService. Mount it on the agent endpoint only (TLS with AgentTLSConfig); it refuses requests that did not arrive with the agent SNI.

func (*Fleet) AgentTLSConfig

func (f *Fleet) AgentTLSConfig(h *tls.ClientHelloInfo) (*tls.Config, error)

AgentTLSConfig is the per-SNI tls.Config of the agent endpoint, for tls.Config.GetConfigForClient of the panel's main listener. For any other server name it returns (nil, nil): the listener then keeps its normal behaviour, so a prober without the secret name sees only the decoy.

For the agent SNI the panel presents a server certificate from its own CA and asks for a client certificate without demanding one (VerifyClientCertIfGiven): the Enroll RPC has no certificate yet. AgentHandler enforces per RPC that everything except Enroll carries a verified, non-revoked node certificate; VerifyConnection already rejects revoked or retired certificates at the handshake.

func (*Fleet) ApplyFix

func (f *Fleet) ApplyFix(ctx context.Context, nodeID, fixID string, dryRun bool, params map[string]string) (*agentv1.CommandResult, error)

ApplyFix sends one fix (or its dry run) to a connected node with the doctor capability and waits up to the node's apply timeout for the CommandResult.

func (*Fleet) CACertPEM

func (f *Fleet) CACertPEM() string

CACertPEM is the panel CA certificate.

func (*Fleet) CAFingerprint

func (f *Fleet) CAFingerprint() string

CAFingerprint is the lowercase hex SHA-256 of the panel CA certificate (what install commands carry).

func (*Fleet) CapacityNodes

func (f *Fleet) CapacityNodes(ctx context.Context, hours int) ([]capacity.Node, error)

CapacityNodes reads what the capacity read (internal/panel/capacity, OpsService.GetFleetLoad) needs for every node that is not retired: its hours of host load over the window, its CPU count and memory, the owner's bandwidth, whether its agent is connected and the root disk of its latest sample. Plain reads of rows the panel keeps; no node is contacted. The VPS edition only, like GetNodeHostHistory.

func (*Fleet) CheckIPv6 added in v0.1.66

func (f *Fleet) CheckIPv6(ctx context.Context, nodeID, address string) (store.IPv6Check, error)

CheckIPv6 (node.proto CheckIpv6): is this IPv6 address of the node reachable from outside, and is what answers there the node itself? It sends nothing but test packets and changes nothing on any host.

The probes are those of the port check, sent to the address instead of the node's main one: the UDP delivery of every enabled UDP server (counted at the node, as the port check does) and the TLS identity of every TCP server of the node (the certificate, pin or REALITY chain that proves the connection reached Mistgate). The specs are built from the node's real row, so the names and pins are those of the main address; only the host that is dialled changes (portDial). Port 80 is left out: the HTTP-01 challenge goes to the name's A record, never to this address.

Who sends: another node whose doctor says that outbound IPv6 works and that lists the capability, two at most per half, ordered as the port check orders them; the panel itself only after those and only when it has IPv6 and is not on the node's host. Only when no needed half has any sender may Globalping connect to one TLS port from two probes (IPv6Check.By = globalping): that proves the address answers a connection, not that it is this node's, and the result says so by its By. A sender that cannot run or a missing half fails closed; an address nobody could test is never passed.

The whole node-side run holds the node's port-check gate (acquirePortCheck): the node has one UDP counter table. Nothing is written to port_check or tcp_check (those are the main address's); the check is returned and audited as node.ipv6_check.

func (*Fleet) CheckPorts added in v0.1.28

func (f *Fleet) CheckPorts(ctx context.Context, nodeID string, requested []uint16) ([]store.PortCheck, string, string)

CheckPorts runs one bounded UDP delivery check and returns the sending node id (or "panel") and a stable result code. It leaves the TCP half out: callers that save a port wait for this and need only the UDP verdict.

func (*Fleet) CheckPortsAsSystem added in v0.1.29

func (f *Fleet) CheckPortsAsSystem(ctx context.Context, nodeID string, requested []uint16) ([]store.PortCheck, string, string)

CheckPortsAsSystem runs the same check for a panel-owned schedule and audits it as the system actor. It probes the TCP ports too (design/vless.md section 7.4).

func (*Fleet) CheckPortsAsSystemUDP added in v0.1.35

func (f *Fleet) CheckPortsAsSystemUDP(ctx context.Context, nodeID string, requested []uint16) ([]store.PortCheck, string, string)

CheckPortsAsSystemUDP is CheckPortsAsSystem without the TCP half: the confirming second sample after UDP loss.

func (*Fleet) CheckPortsForGate

func (f *Fleet) CheckPortsForGate(ctx context.Context, nodeID string) (sender string, udp []store.PortCheck, tcp []store.TCPCheck, code string)

CheckPortsForGate is the update gate's second vantage point (internal/panel/update, healthGate): the system port check of a node, UDP and TCP, with the guarantee the gate needs: the sender is another node. A run whose sender (UDP or TCP) is the panel or the target itself says nothing about the panel's own path, so it answers "no_sender" and its rows are dropped. code is "" for a finished run (the verdicts are in the rows), else the check's own error code.

func (*Fleet) CheckRelay added in v0.1.65

func (f *Fleet) CheckRelay(ctx context.Context, relayID string, stages ...string) (store.RelayCheck, error)

CheckRelay (relay.proto): does a relay work, in two stages, with only packets and a TLS hello and nothing changed on any host.

  • leg: the entry node sends to the exit's server (its address and own port). TCP: a probe that has to come back "ours" (the server's certificate, pin or REALITY chain, as the port check proves it). UDP: the entry sends a counted burst and the exit counts it, as the UDP port check does.
  • path: only when the relay is switched on and the entry reported the forward. A third node (never the entry or the exit) sends to the entry's address and forwarded port; the answer is the same as for the leg, so TCP must prove the exit's server and UDP is counted at the exit, after it went through the entry's DNAT. The panel itself sends only when no third node can.

The whole check holds both nodes' port-check gates (acquirePortCheck): the exit has one UDP counter table, and the reverse probe targets the entry. A relay check and a port check must not measure either node at once. The result goes into the relay (check_json) and comes back; it is the caller's to act on (the gate that switches a relay on is in the access module).

stages names what to run (store.RelayStageLeg, RelayStagePath, RelayStageReverseReach, RelayStageReverseSpeed or RelayStageDirectSpeed; none = leg and path). A reverse reach check also runs after a failed leg. The two speed proofs only run when named: reverse_speed at the owner's request, direct_speed at the mode controller's (it is what lets a reverse relay go back to the direct way). The result carries the bridge stage of a relay in the reverse way, derived from the exit's report.

func (*Fleet) CountryProbe added in v0.1.42

func (f *Fleet) CountryProbe(ctx context.Context, nodeID string, req CountryProbeRequest) (CountryProbeResult, error)

CountryProbe asks one node to run the probe and returns its answer. An error means no answer at all: the node is offline, its agent does not list country-probe/1 ("agent too old"), the link was lost or the 130 s ran out.

func (*Fleet) CreateProvisionEnrollment

func (f *Fleet) CreateProvisionEnrollment(ctx context.Context, spec provision.NodeSpec, actor string, now, expires time.Time) (string, string, error)

CreateProvisionEnrollment creates the pending node, or rotates its pending enrollment token when a job is resumed. The token is returned exactly once to the caller and is never written to an audit row.

func (*Fleet) DecoySiteHandler

func (f *Fleet) DecoySiteHandler(opts ...connect.HandlerOption) (string, http.Handler)

DecoySiteHandler is the admin DecoySiteService; see NodeHandler for opts. Only the calls that carry files may be large.

func (*Fleet) FleetHandler

func (f *Fleet) FleetHandler(opts ...connect.HandlerOption) (string, http.Handler)

FleetHandler is the admin FleetService (Overview, ListEvents); see NodeHandler for opts.

func (*Fleet) HasSession added in v0.1.46

func (f *Fleet) HasSession(nodeID string) bool

HasSession reports whether this process currently owns the node's agent stream.

func (*Fleet) LastSpeeds

func (f *Fleet) LastSpeeds(ctx context.Context, since time.Time, nodeID string) ([]SpeedSummary, error)

LastSpeeds is the newest stored test of every pair and direction, newest first.

func (f *Fleet) Link(ctx context.Context, in LinkIn) (LinkOut, error)

Link runs one NodeLink event through the session core. It returns an error (the object then closes the socket with 1011 and writes nothing) when the state does not decode, Generation is 0 on open, any other event arrives without a live state, the core fails, or one call needs more than linkMaxSteps core steps: folding errors into LinkOut would let the object save a half-applied state.

func (*Fleet) LinkAccept added in v0.1.27

func (f *Fleet) LinkAccept(ctx context.Context, nodeID, audience string, nonce, authFrame []byte) (serial string, notAfter time.Time, frame, seal []byte, ok bool)

LinkAccept is linkAccept for the edge Durable Object (the VPS runs it inside LinkHandler): it reports the certificate the agent proved and the seal keys, which the object hands back on the open step (LinkIn.Seal).

func (*Fleet) LinkHandler added in v0.1.26

func (f *Fleet) LinkHandler() http.Handler

LinkHandler serves the public, signed WebSocket transport. Mount it only beneath the stored secret path prefix. With Config.Remote set (the edge edition) it answers with the LinkMarker instead: the node's Durable Object holds the socket there, so both editions share this one mount.

func (*Fleet) Live

func (f *Fleet) Live(ctx context.Context) ([]store.NodeLiveRow, error)

Live reads the durable live projection without the admin view's larger live_json column.

func (*Fleet) NetworkMode

func (f *Fleet) NetworkMode() uint32

NetworkMode returns the in-memory operator setting. The edge edition always returns zero.

func (*Fleet) NodeHandler

func (f *Fleet) NodeHandler(opts ...connect.HandlerOption) (string, http.Handler)

NodeHandler is the admin NodeService. Pass connect.WithInterceptors(auth.Interceptor()) so that it is behind the admin session; the path is the Connect prefix to mount it on.

func (*Fleet) NodeLive added in v0.1.29

func (f *Fleet) NodeLive(ctx context.Context, nodeID string) (store.NodeLiveRow, error)

NodeLive reads one node's durable liveness projection without live_json.

func (*Fleet) NodeStatusWithLive added in v0.1.29

func (f *Fleet) NodeStatusWithLive(ctx context.Context, n store.NodeRow, live store.NodeLiveRow, summaries map[string]store.NodeHealthSummary) adminv1.NodeStatus

NodeStatusWithLive derives status from a projection and the health summaries already read for the surrounding request.

func (*Fleet) Online

func (f *Fleet) Online(ctx context.Context) []OnlineSession

Online returns the open sessions reported by connected nodes' live projections.

func (*Fleet) OnlineByInbound

func (f *Fleet) OnlineByInbound(ctx context.Context) map[string]int

OnlineByInbound counts the open sessions of every inbound of the connected nodes (the health and WARP dialogs say how many connections a restart or a pause drops).

func (*Fleet) OnlineDevices added in v0.1.39

func (f *Fleet) OnlineDevices() map[string][]string

OnlineDevices maps each device with an open session to the connected nodes it has one on, in node order (access.OnlineSource). Two nodes: the same keys are in use on two servers at once.

func (*Fleet) OnlineUsers

func (f *Fleet) OnlineUsers() map[string]string

OnlineUsers maps each user with an open session to the node of the newest one (access.OnlineSource).

func (*Fleet) ProbeHandler

func (f *Fleet) ProbeHandler(opts ...connect.HandlerOption) (string, http.Handler)

ProbeHandler is the admin ProbeService; see NodeHandler for opts. Only the panel VPS mounts it.

func (*Fleet) ProvisionNodeState

func (f *Fleet) ProvisionNodeState(ctx context.Context, nodeID string) (string, bool, error)

ProvisionNodeState reports the durable fleet state and connection used to resume an installation safely.

func (*Fleet) RollbackAgent

func (f *Fleet) RollbackAgent(ctx context.Context, nodeID string, wait time.Duration) (*agentv1.CommandResult, error)

RollbackAgent asks a connected node with the update capability to put its previous binary back.

func (*Fleet) Run

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

Run drives the debounced recompute and the node-down sweeper until ctx ends, then closes all streams.

func (*Fleet) RunDoctor

func (f *Fleet) RunDoctor(ctx context.Context, nodeID string, checks []string, wait time.Duration) (*agentv1.DoctorReport, error)

RunDoctor asks a connected node with the doctor capability to run checks (nil = all) and waits for the report that echoes the request. The report has been handed to Health by then. A node without the capability is never sent anything (FAILED_PRECONDITION "agent too old").

func (*Fleet) SendRollbackAgent added in v0.1.48

func (f *Fleet) SendRollbackAgent(ctx context.Context, nodeID, requestID string, deadline time.Time) error

SendRollbackAgent sends a rollback command through the edge link without waiting for CommandResult.

func (*Fleet) SendUpdateAgent added in v0.1.48

func (f *Fleet) SendUpdateAgent(ctx context.Context, nodeID, requestID string, manifest, signature []byte, downloadToken string, deadline time.Time, downloadTimeout time.Duration) error

SendUpdateAgent sends an update command through the edge link without waiting for CommandResult.

func (*Fleet) SetHealth

func (f *Fleet) SetHealth(h Health)

SetHealth connects the health module. Call it before serving; nil disconnects.

func (*Fleet) SetNetworkMode

func (f *Fleet) SetNetworkMode(mode uint32) bool

SetNetworkMode updates the stream setting cache and reports whether it changed.

func (*Fleet) SetRelayControl

func (f *Fleet) SetRelayControl(control func(context.Context, string))

SetRelayControl attaches the access module's mode controller after both services are built.

func (*Fleet) SetUpdates

func (f *Fleet) SetUpdates(u Updates)

SetUpdates connects the updates module. Call it before serving; nil disconnects (FetchUpdate answers UNIMPLEMENTED).

func (*Fleet) SetWarp

func (f *Fleet) SetWarp(w Warp)

SetWarp connects the WARP module. Call it before serving; nil disconnects (no WarpSpec is sent, no health is stored).

func (*Fleet) StartDebugCapture

func (f *Fleet) StartDebugCapture(ctx context.Context, in DebugStart) (store.DebugCaptureRow, error)

StartDebugCapture asks the node to capture. The capture row is written before the frame is sent, so a report can never arrive for a capture the panel does not know. The audit entry names the actor, the node, the sources and the duration.

func (*Fleet) StateChanged

func (f *Fleet) StateChanged()

StateChanged tells the module that something that feeds desired state changed (users, profiles, inbounds, nodes). It returns at once; a debounced recompute pushes the result to connected nodes.

func (*Fleet) StopDebugCapture

func (f *Fleet) StopDebugCapture(ctx context.Context, captureID string) (store.DebugCaptureRow, error)

StopDebugCapture ends a running capture now: the node ships what it holds before it answers. A capture that is over is returned as it is.

func (*Fleet) Sweep added in v0.1.31

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

Sweep runs one node-down pass for scheduled callers.

func (*Fleet) UpdateAgent

func (f *Fleet) UpdateAgent(ctx context.Context, nodeID string, manifest, signature []byte, wait, downloadTimeout time.Duration) (*agentv1.CommandResult, error)

UpdateAgent sends a signed manifest to a connected node with the update capability and waits up to wait for the CommandResult (the download is part of it). The agent answers before it re-executes; a stream that drops right after the answer still delivers it.

func (*Fleet) UpdateAgentWithRequestID

func (f *Fleet) UpdateAgentWithRequestID(ctx context.Context, nodeID, requestID string, manifest, signature []byte, wait, downloadTimeout time.Duration, options panelupdate.UpdateAgentOptions) (*agentv1.CommandResult, error)

UpdateAgentWithRequestID is the rollout path. The caller persists the request ID with the step so progress and command replies from a previous attempt cannot be mistaken for the current update after a reconnect or restart.

func (*Fleet) UpdateOs

func (f *Fleet) UpdateOs(ctx context.Context, nodeID string, req panelupdate.OsJobRequest, wait time.Duration) (*agentv1.CommandResult, error)

UpdateOs sends one OS job to a connected node that listed "os-update/1" (FAILED_PRECONDITION "agent too old" otherwise, "node is offline" when it is not connected: nothing was sent) and waits up to wait for the CommandResult. The result is ok whatever the node decided; params.state says what happened (started, running, finished, unsupported; agent.proto "OS UPDATES").

func (*Fleet) WarpPauseApplied

func (f *Fleet) WarpPauseApplied(ctx context.Context, nodeID string) bool

WarpPauseApplied reports whether the node holds a paused WARP: the last state sent on its stream pauses it, and the node confirmed exactly that state. It is RestartWarp's proof that the tunnel went down; another change applied meanwhile (a state that still runs WARP) does not count.

func (*Fleet) WarpReach

func (f *Fleet) WarpReach(ctx context.Context, nodeID string, domains []string) (string, []store.WarpReachItem, error)

WarpReach asks the node to check the sites and returns the colo of its WARP exit at that run and one answer per site, in the order asked. An error means no usable answer: the node is offline, its agent does not list warp-reach/1 ("agent too old"), the link was lost, the 60 s ran out, or the agent refused (busy, too_soon, warp_down, bad_params: the error says which).

type Health

type Health interface {
	// DoctorReport hands over every DoctorReport of a node (periodic, requested or the re-check after a fix).
	DoctorReport(ctx context.Context, nodeID string, r *agentv1.DoctorReport)
	// NodeReturned says that an active node came back after a silence of less than the blip window with an
	// unchanged boot time: health writes the history record.
	NodeReturned(ctx context.Context, nodeID string, silentSince, now time.Time)
	// NodeHealthSummaries is what the node status and card show, per node: the synthetic checks of the node all failing
	// (NoTraffic, with how many of how many) and the check of the worst FAIL of its last doctor report. A request reads
	// it once: on the edge it is one D1 read.
	NodeHealthSummaries(ctx context.Context) map[string]store.NodeHealthSummary
	// AlertCounts feeds the badge of the Overview: active alerts not muted and not INFO, and the critical ones.
	AlertCounts(ctx context.Context) (active, critical uint32)
}

Health is implemented by the health module. All methods must be cheap and must not call back into the stream they run on.

type LinkClose added in v0.1.30

type LinkClose struct {
	Code   uint16
	Reason string // at most 123 bytes
}

LinkClose is a WebSocket close the session asks for.

type LinkIn added in v0.1.30

type LinkIn struct {
	NodeID       string    // ctx.id.name
	State        string    // the previous LinkOut.State; "" before the node's first session
	Kind         LinkKind  //
	At           time.Time // the object's Date.now()
	Generation   uint64    // open: the generation the accepted LinkAuth stored = OwnerGeneration = node_live.session
	CertSerial   string    // open: from LinkAccept
	CertNotAfter time.Time // open
	Seal         []byte    // open: the seal keys LinkAccept returned; nil = a plain session
	Frame        []byte    // frame: one ConnectRequest; request: one ConnectResponse
	RequestID    string    // request
	DeadlineAt   time.Time // request: the caller's absolute deadline
	Record       bool      // request: persist a later CommandResult through the shared update service
}

LinkIn is one NodeLink event, filled from the object's name, storage and clock.

type LinkKind added in v0.1.30

type LinkKind string

LinkKind is the kind of a NodeLink event (the LinkEvent kinds of edge/worker/src/panellink.ts).

const (
	LinkOpen    LinkKind = "open"
	LinkFrame   LinkKind = "frame"
	LinkAlarm   LinkKind = "alarm"
	LinkDesired LinkKind = "desired"
	LinkRequest LinkKind = "request"
	LinkClosed  LinkKind = "closed"
)

type LinkOut added in v0.1.30

type LinkOut struct {
	State   string      // written by the object before it sends Frames
	Frames  [][]byte    // ConnectResponse, in order
	Close   *LinkClose  // after Frames; the object then runs the closed step
	AlarmAt time.Time   // zero = no session alarm
	Replies []LinkReply // Frame nil = refused, expired or gone
	Forget  bool        // the node is retired: delete all storage and the alarm after this block
}

LinkOut is what the object does with the result of one event: write State, send Frames, resolve Replies, set the alarm, then close.

type LinkReply added in v0.1.30

type LinkReply struct {
	RequestID string
	Frame     []byte
}

LinkReply answers an admin request: the agent's whole ConnectRequest frame, or nil when the request was refused, expired or gone.

type OnlineSession

type OnlineSession struct {
	NodeID, UserID, DeviceID, Protocol, InboundID string
	ConnectedAt                                   time.Time
}

OnlineSession is one open client session as last reported by a node.

type PendingRequest added in v0.1.26

type PendingRequest struct {
	Kind     PendingRequestKind `json:"k,omitempty"`
	Deadline time.Time          `json:"d,omitzero"`
}

PendingRequest is serialized request metadata. VPS channels remain in the adapter; edge delivery is a later round.

type PendingRequestKind added in v0.1.26

type PendingRequestKind uint8

PendingRequestKind identifies the agent result expected for a request.

const (
	PendingCommand PendingRequestKind = iota + 1
	PendingDoctor
	PendingLog
	PendingAutoBandwidth
	PendingRetire
	PendingRecorded PendingRequestKind = 6
)

type PoisonBatch added in v0.1.27

type PoisonBatch struct {
	Instance       string    `json:"i"`
	Seq            uint64    `json:"s"`
	FirstFailureAt time.Time `json:"fa,omitzero"`
}

PoisonBatch identifies a stats batch refused by the store and when its first refusal happened.

type Remote added in v0.1.30

type Remote interface {
	Ask(ctx context.Context, nodeID, requestID string, frame *agentv1.ConnectResponse, deadline time.Time) (*agentv1.ConnectRequest, error)
	// Send writes one frame to the node's live link and returns immediately; any error means the frame was not sent.
	Send(ctx context.Context, nodeID, requestID string, frame *agentv1.ConnectResponse, deadline time.Time) error
	Close(ctx context.Context, nodeID, reason string) error
	Poke(ctx context.Context, nodeIDs []string) error
}

Remote sends requests through the edge edition's external node link. Ask receives an absolute deadline so a queued request can be refused before it reaches the session core. A request that got no answer is (nil, nil) or an error that is context.DeadlineExceeded or carries connect.CodeDeadlineExceeded ("no answer"); any other error is "link lost".

type SessionClose added in v0.1.26

type SessionClose struct {
	Class  CloseClass
	Reason string
}

SessionClose describes a protocol-level reason to end the connection.

type SessionCore added in v0.1.26

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

SessionCore processes one event at a time without owning goroutines, timers, channels, or transports.

func NewSessionCore added in v0.1.26

func NewSessionCore(f *Fleet) *SessionCore

NewSessionCore creates a session transition engine backed by fleet services.

func (*SessionCore) Step added in v0.1.26

func (c *SessionCore) Step(ctx context.Context, state *SessionState, event SessionEvent) (Transition, error)

Step processes one event and writes the resulting protocol state back to the supplied session. On error the caller must end the session; state may already reflect work completed before the error.

type SessionEffect added in v0.1.26

type SessionEffect struct {
	Kind         EffectKind
	RequestID    string
	Reply        *agentv1.ConnectRequest
	PreviousNode *store.NodeRow
	BootAt       time.Time
	At           time.Time
	LogChunk     *agentv1.LogChunk
	Users        []string
	WarpReason   string
	Instance     string // EffectConnectEvents: the agent process that said hello
	Result       *agentv1.CommandResult
}

SessionEffect asks the adapter to perform work requested by a core transition.

type SessionEvent added in v0.1.26

type SessionEvent struct {
	Kind     EventKind
	At       time.Time
	Frame    *agentv1.ConnectRequest
	Request  *AdminRequest
	Prepared *preparedDesiredState
	Err      error
}

SessionEvent is a timestamped input to SessionCore.Step.

type SessionState added in v0.1.26

type SessionState struct {
	Version         uint8     `json:"v"`
	NodeID          string    `json:"n,omitempty"`
	LinkViaNodeID   string    `json:"lv,omitempty"`
	OwnerGeneration uint64    `json:"o,omitempty"`
	InstanceID      string    `json:"i,omitempty"`
	AgentCaps       []string  `json:"ac,omitempty"`
	LivenessNanos   int64     `json:"l,omitempty"`
	HelloDeadline   time.Time `json:"h,omitzero"`
	// LivenessDeadline keeps Go's monotonic reading on the VPS: a wall-clock step cannot close a live session.
	LivenessDeadline      time.Time                 `json:"d,omitzero"`
	AutoBandwidthDeadline time.Time                 `json:"b,omitzero"`
	RetireAt              time.Time                 `json:"rt,omitzero"`
	NextAckTick           time.Time                 `json:"a,omitzero"`
	NextCertCheck         time.Time                 `json:"x,omitzero"`
	EventTokens           uint8                     `json:"evt,omitempty"`
	EventTokenAt          time.Time                 `json:"evta,omitzero"`
	ReliableEventTokens   uint16                    `json:"revt,omitempty"`
	ReliableEventTokenAt  time.Time                 `json:"revta,omitzero"`
	DroppedEvents         uint64                    `json:"evd,omitempty"`
	DroppedEventLogAt     time.Time                 `json:"evdl,omitzero"`
	AckPending            uint64                    `json:"p,omitempty"`
	AckSent               uint64                    `json:"s,omitempty"`
	LastAck               time.Time                 `json:"k,omitzero"`
	LastReject            time.Time                 `json:"r,omitzero"`
	StatsBudgetLeftNanos  int64                     `json:"sbl,omitempty"`
	StatsBudgetAt         time.Time                 `json:"sba,omitzero"`
	LastSeenAt            time.Time                 `json:"v_at,omitzero"`
	SentRevision          uint64                    `json:"q,omitempty"`
	SentStateHash         string                    `json:"sh,omitempty"`
	SentWithheld          []string                  `json:"wh,omitempty"`
	SentWithheldShare     []string                  `json:"whs,omitempty"`
	SentSettingsHash      string                    `json:"ss,omitempty"`
	OsStatusEnabled       bool                      `json:"os_status,omitempty"`
	DriftResent           bool                      `json:"dr,omitempty"`
	Drift                 bool                      `json:"dt,omitempty"`
	FullResendPending     bool                      `json:"fr,omitempty"`
	HelloAppliedRevision  uint64                    `json:"har,omitempty"`
	HelloAppliedStateHash string                    `json:"hah,omitempty"`
	Preparing             bool                      `json:"prep,omitempty"`
	PrepareDirty          bool                      `json:"pd,omitempty"`
	PrepareRetryAt        time.Time                 `json:"pra,omitzero"`
	Poison                *PoisonBatch              `json:"p_seq,omitempty"`
	PeerCertSerial        string                    `json:"cs,omitempty"`
	PeerCertNotAfter      time.Time                 `json:"ce,omitzero"`
	Pending               map[string]PendingRequest `json:"pr,omitempty"`
	L3                    l3MemoState               `json:"m,omitzero"`
	Disconnected          bool                      `json:"z,omitempty"`
	// Seal is a sealed session's keys (agentlink.SealKeys) and SealUp/SealDown the next frame number of the agent's and
	// the panel's direction. Only the edge keeps them here (Link opens and seals); the VPS keeps them in agentlink.Link.
	Seal     []byte `json:"sk,omitempty"`
	SealUp   uint64 `json:"su,omitempty"`
	SealDown uint64 `json:"sd,omitempty"`
}

SessionState is the compact connection protocol state. The live admin view is stored in node_live.

type SpeedSummary

type SpeedSummary struct {
	FromID, ToID, Direction string
	At                      time.Time
	MbitS                   float64
	FirstByteMS             uint32
}

SpeedSummary is the newest stored speed test of a pair and direction, for the digest views.

type Transition added in v0.1.26

type Transition struct {
	Frames    []*agentv1.ConnectResponse
	Effects   []SessionEffect
	NextAlarm *time.Time
	Close     *SessionClose
}

Transition contains the outputs produced by one session event.

type Updates

type Updates interface {
	// LinkDownload authorizes one file of the signed manifest pinned to a current SENT step.
	LinkDownload(ctx context.Context, nodeID, name, token string) (string, error)
	// RecordAnswer stores the first result of an edge update command against its sent step. Other command results never call it.
	RecordAnswer(ctx context.Context, nodeID, requestID string, result *agentv1.CommandResult) error
	// RecordProgress stores the latest best-effort progress for an in-flight update command.
	RecordProgress(ctx context.Context, nodeID string, progress *agentv1.UpdateProgress) error
	// Updating reports that a rollout step of the node is in flight (command sent, reconnect or gate pending): its
	// stream drops when the agent re-executes, and that is neither a blip nor an outage.
	Updating(nodeID string) bool
	// ServeWithWriteDeadline streams the file and arms the HTTP response's write deadline for each chunk.
	ServeWithWriteDeadline(ctx context.Context, nodeID, name string, offset uint64, setWriteDeadline func(time.Time) error,
		send func(chunk []byte, total uint64) error) error
	// NodeBinary is the absolute path, on the panel's server, of the agent binary for the platform in the current
	// trusted bundle; "" when there is none. The add-node window offers it as a ready scp command.
	NodeBinary(goos, goarch string) string
}

Updates is implemented by the updates module. Its three metadata methods are cheap; Serve blocks for a download.

type Warp

type Warp interface {
	// Spec is the node's WarpSpec (nil = the node has no account; Enabled=false = paused). It is sent only to a stream
	// that listed "warp/1".
	Spec(ctx context.Context, nodeID string) (*plugin.WarpSpec, error)
	// StoreHealth keeps the last WarpHealth of a node (for GetWarp and the node badge).
	StoreHealth(ctx context.Context, nodeID string, h *agentv1.WarpHealth) error
	// NeedsAttention records why the owner has to decide ("" clears it).
	NeedsAttention(ctx context.Context, nodeID, reason string) error
	// RefreshByNode reads the account back from Cloudflare because the node's WARP could not heal itself (read only).
	RefreshByNode(ctx context.Context, nodeID string) error
	// AutoReregister replaces a revoked registered account when the owner switched that on; reports whether it did.
	AutoReregister(ctx context.Context, nodeID string) (bool, error)
	// Summary is the badge of a node card; a is nil when the node has no account.
	Summary(a *store.WarpAccountRow, online bool, now time.Time) *adminv1.WarpSummary
}

Warp is implemented by the WARP module (internal/panel/warp). The fleet asks it for the node's WarpSpec and hands it what the node reports; it never touches an account itself. Every method must be cheap or return quickly: Spec runs for every reconcile of a node, StoreHealth for every stats batch.

Jump to

Keyboard shortcuts

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