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
- type AdminRequest
- type AlarmKind
- type CloseClass
- type Config
- type EffectKind
- type EventKind
- type Fleet
- func (f *Fleet) AgentConnected(nodeID string) bool
- func (f *Fleet) AgentHandler() http.Handler
- func (f *Fleet) AgentTLSConfig(h *tls.ClientHelloInfo) (*tls.Config, error)
- func (f *Fleet) ApplyFix(ctx context.Context, nodeID, fixID string, dryRun bool, ...) (*agentv1.CommandResult, error)
- func (f *Fleet) CACertPEM() string
- func (f *Fleet) CAFingerprint() string
- func (f *Fleet) CPUUsage(nodeID string) (pct float64, sampledAt time.Time, ok bool)
- func (f *Fleet) CreateProvisionEnrollment(ctx context.Context, spec provision.NodeSpec, actor string, ...) (string, string, error)
- func (f *Fleet) FleetHandler(opts ...connect.HandlerOption) (string, http.Handler)
- func (f *Fleet) LinkHandler() http.Handler
- func (f *Fleet) Live(nodeID string) (connected bool, caps []string, drift bool)
- func (f *Fleet) NetworkUsage(nodeID string) (rxBps, txBps uint64, sampledAt time.Time, ok bool)
- func (f *Fleet) NodeHandler(opts ...connect.HandlerOption) (string, http.Handler)
- func (f *Fleet) NodeStatus(ctx context.Context, n store.NodeRow) adminv1.NodeStatus
- func (f *Fleet) Online() []OnlineSession
- func (f *Fleet) OnlineByInbound() map[string]int
- func (f *Fleet) OnlineUsers() map[string]string
- func (f *Fleet) OnlineUsersByNode() map[string]int
- func (f *Fleet) ProvisionNodeConnected(nodeID string) bool
- func (f *Fleet) ProvisionNodeState(ctx context.Context, nodeID string) (string, error)
- func (f *Fleet) RollbackAgent(ctx context.Context, nodeID string, wait time.Duration) (*agentv1.CommandResult, error)
- func (f *Fleet) Run(ctx context.Context) error
- func (f *Fleet) RunDoctor(ctx context.Context, nodeID string, checks []string, wait time.Duration) (*agentv1.DoctorReport, error)
- func (f *Fleet) SetHealth(h Health)
- func (f *Fleet) SetUpdates(u Updates)
- func (f *Fleet) SetWarp(w Warp)
- func (f *Fleet) StateChanged()
- func (f *Fleet) UpdateAgent(ctx context.Context, nodeID string, manifest, signature []byte, ...) (*agentv1.CommandResult, error)
- func (f *Fleet) WarpPauseApplied(ctx context.Context, nodeID string) bool
- type Health
- type LiveSnapshot
- type OnlineSession
- type PendingRequest
- type PendingRequestKind
- type SessionClose
- type SessionCore
- type SessionEffect
- type SessionEvent
- type SessionSidecar
- type SessionStarted
- type SessionState
- type Transition
- type Updates
- type Warp
Constants ¶
const APIVersion = 1
APIVersion is the agent wire API version this panel serves (Hello.api_version, EnrollRequest.api_version).
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type AdminRequest ¶ added in v0.1.26
type AdminRequest struct {
RequestID string
Deadline time.Time
Frame *agentv1.ConnectResponse
Kind PendingRequestKind
}
AdminRequest carries a request frame and its correlation metadata into the core.
type AlarmKind ¶ added in v0.1.26
type AlarmKind uint8
AlarmKind identifies a session deadline or periodic action.
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
// LinkServed reports whether the signed WebSocket agent link is mounted on the public listener.
LinkServed bool
// ExpectedAgentVersion is the newest agent version this panel ships (ListNodes marks older agents).
ExpectedAgentVersion 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 when a node reports that the build of its AmneziaWG kernel module failed (the Telegram
// alerts hang on it). at is the time the node gave; a replay of the same report carries the same value. Must not block.
OnAwgPrepareFailed func(nodeID, code string, at int64)
// 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 EffectKind ¶ added in v0.1.26
type EffectKind uint8
EffectKind identifies an adapter action requested by the session core.
const ( EffectSessionStarted EffectKind = iota + 1 EffectAutoBandwidth EffectLiveUpdate EffectUsage EffectCommandResult EffectDoctorReport EffectLogChunk EffectAwgPrepare EffectCheckCertificate EffectWarpAttention EffectDesiredReconcile )
type EventKind ¶ added in v0.1.26
type EventKind uint8
EventKind identifies one input that the session core can process.
type Fleet ¶
type Fleet struct {
// contains filtered or unexported fields
}
Fleet is the fleet module.
func New ¶
New builds the module: it loads (or creates) the panel CA. Call Run to start the background work.
func (*Fleet) AgentConnected ¶ added in v0.1.17
AgentConnected reports whether the node's agent holds a live session with the panel (access.AgentSessionSource: the user page calls a server that answers "online").
func (*Fleet) AgentHandler ¶
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 ¶
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) CAFingerprint ¶
CAFingerprint is the lowercase hex SHA-256 of the panel CA certificate (what install commands carry).
func (*Fleet) CPUUsage ¶ added in v0.1.19
CPUUsage returns the CPU use of the latest host sample of a connected node, with the time the panel received it.
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) FleetHandler ¶
FleetHandler is the admin FleetService (Overview, ListEvents); see NodeHandler for opts.
func (*Fleet) LinkHandler ¶ added in v0.1.26
LinkHandler serves the public, signed WebSocket transport. Mount it only beneath the stored secret path prefix.
func (*Fleet) Live ¶
Live reports whether the node has a stream now, the capabilities its Hello listed and whether the desired state stays different from the applied one after the automatic resend (state drift).
func (*Fleet) NetworkUsage ¶ added in v0.1.9
NetworkUsage returns the latest host-network sample received from a connected node. The timestamp is when the panel received that sample, so callers can hide percentages when the agent stops reporting.
func (*Fleet) NodeHandler ¶
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) NodeStatus ¶
NodeStatus is the status the admin UI shows for a node row.
func (*Fleet) Online ¶
func (f *Fleet) Online() []OnlineSession
Online returns the open sessions of every connected node (in memory, refreshed by each stats batch).
func (*Fleet) OnlineByInbound ¶
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) OnlineUsers ¶
OnlineUsers maps each user with an open session to the node of the newest one (access.OnlineSource).
func (*Fleet) OnlineUsersByNode ¶
OnlineUsersByNode counts the distinct users with an open session on each connected node (the canary is the node with the fewest).
func (*Fleet) ProvisionNodeConnected ¶
ProvisionNodeConnected reports whether the agent has established its authenticated stream.
func (*Fleet) ProvisionNodeState ¶
ProvisionNodeState reports the durable fleet state 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 ¶
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) SetHealth ¶
SetHealth connects the health module. Call it before serving; nil disconnects.
func (*Fleet) SetUpdates ¶
SetUpdates connects the updates module. Call it before serving; nil disconnects (FetchUpdate answers UNIMPLEMENTED).
func (*Fleet) SetWarp ¶
SetWarp connects the WARP module. Call it before serving; nil disconnects (no WarpSpec is sent, no health is stored).
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) UpdateAgent ¶
func (f *Fleet) UpdateAgent(ctx context.Context, nodeID string, manifest, signature []byte, wait 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) WarpPauseApplied ¶
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.
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)
// NodeHealth is what the node status and card show: 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.
NodeHealth(nodeID string) (noTraffic bool, failed, total int, doctorFail string)
// 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 LiveSnapshot ¶ added in v0.1.26
type LiveSnapshot struct {
Metrics *agentv1.HostMetrics
MetricsAt time.Time
Health []*agentv1.InboundHealth
Online []onlineSess
UserDown map[string]uint64
UserUp map[string]uint64
}
LiveSnapshot is the current admin view of one agent, refreshed only by accepted StatsBatch messages.
type OnlineSession ¶
type OnlineSession struct {
NodeID, UserID, DeviceID, Protocol, InboundID, RemoteIP 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
DeadlineUnixNano int64
}
PendingRequest is durable 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 adapter-owned request awaiting an agent result.
const ( PendingCommand PendingRequestKind = iota + 1 PendingDoctor PendingLog )
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, sidecar SessionSidecar, event SessionEvent) (Transition, error)
Step processes one event. On error, the caller must discard both the transition and the sidecar it passed in; Step may have mutated maps shared with that sidecar.
type SessionEffect ¶ added in v0.1.26
type SessionEffect struct {
Kind EffectKind
RequestID string
CommandResult *agentv1.CommandResult
DoctorReport *agentv1.DoctorReport
LogChunk *agentv1.LogChunk
Live *LiveSnapshot
Users []string
Started *SessionStarted
Event *store.EventRow
WarpReason string
ReconcileMode reconcileMode
ErrorLog string
}
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
Alarm AlarmKind
Mode reconcileMode
Prepared *preparedDesiredState
AutoBandwidthAt time.Time
}
SessionEvent is a timestamped input to SessionCore.Step.
type SessionSidecar ¶ added in v0.1.26
type SessionSidecar struct {
Version uint32
SentDesired *nodeState
Live LiveSnapshot
CertSeen map[string]string
L3 l3Intake
Pending map[string]PendingRequest
}
SessionSidecar holds desired/live state that is too large for SessionState.
type SessionStarted ¶ added in v0.1.26
type SessionStarted struct {
Previous store.NodeRow
BootAt time.Time
Now time.Time
AutoMeasure bool
}
SessionStarted carries connection metadata needed by the transport adapter.
type SessionState ¶ added in v0.1.26
type SessionState struct {
Version uint8 `json:"v"`
NodeID string `json:"n,omitempty"`
OwnerGeneration uint64 `json:"o,omitempty"`
InstanceID string `json:"i,omitempty"`
Capabilities []string `json:"c,omitempty"`
LivenessNanos int64 `json:"l,omitempty"`
HelloDeadlineUnixNano int64 `json:"h,omitempty"`
LivenessDeadlineUnixNano int64 `json:"d,omitempty"`
AutoBandwidthUnixNano int64 `json:"b,omitempty"`
AutoBandwidthPending bool `json:"ap,omitempty"`
NextAckTickUnixNano int64 `json:"a,omitempty"`
NextCertCheckUnixNano int64 `json:"x,omitempty"`
AckPending uint64 `json:"p,omitempty"`
AckSent uint64 `json:"s,omitempty"`
LastAckUnixNano int64 `json:"k,omitempty"`
LastRejectUnixNano int64 `json:"r,omitempty"`
LastEndUnix int64 `json:"e,omitempty"`
LastSeenUnixNano int64 `json:"v_at,omitempty"`
SentRevision uint64 `json:"q,omitempty"`
SentStateHash string `json:"sh,omitempty"`
SentSettingsHash string `json:"ss,omitempty"`
DriftResent bool `json:"dr,omitempty"`
Drift bool `json:"dt,omitempty"`
SidecarVersion uint32 `json:"sv,omitempty"`
}
SessionState is the compact connection state. Large snapshots and memo tables live in SessionSidecar.
type Transition ¶ added in v0.1.26
type Transition struct {
State SessionState
Sidecar SessionSidecar
Frames []*agentv1.ConnectResponse
Effects []SessionEffect
NextAlarm *time.Time
Close *SessionClose
}
Transition contains the updated state and outputs produced by one session event.
type Updates ¶
type Updates interface {
// 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
// Serve streams the named file of the current trusted bundle from offset: send gets at most 256 KiB at a time
// and the size of the whole file. Errors are Connect errors (NOT_FOUND, RESOURCE_EXHAUSTED, FAILED_PRECONDITION).
Serve(ctx context.Context, nodeID, name string, offset uint64, 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. Both methods must be cheap; Serve blocks for the length of 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.