runtime

package
v0.14.10 Latest Latest
Warning

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

Go to latest
Published: Oct 15, 2026 License: AGPL-3.0 Imports: 45 Imported by: 0

Documentation

Overview

Package runtime is the shared daemon skeleton of the fallbck agents: configuration lookup and self-enrollment, the Temporal client and PBS tunnel connections through the server gateway, the activity worker, and the heartbeat / token-rotation loop. Agent binaries only add their activities.

Index

Constants

This section is empty.

Variables

View Source
var ErrRestart = errors.New("agent binary updated; restart required")

ErrRestart is returned by RunUntil when the binary was replaced and the process should re-execute itself

Functions

func ConnectionOptions

func ConnectionOptions(cfg *config.AgentConfig) (string, client.ConnectionOptions, error)

ConnectionOptions derives the Temporal gRPC endpoint and TLS settings from ServerURL. The FallBCK server multiplexes gRPC and HTTP on the same port; https → TLS, http → h2c.

func DBEnginesProbe added in v0.11.3

func DBEnginesProbe(cfg dbspec.Config, refresh time.Duration) func() []string

DBEnginesProbe returns a cached probe for the database engines this agent can back up: postgres, mysql and mongodb when their client tools are found, mssql always (built-in driver). The first call runs the detection and logs what it found; later calls reuse the result for refresh and re-detect after that, so a heartbeat never pays for executing the tools. Tools installed after the agent started are picked up within one refresh interval.

func DBPasswordFetcher added in v0.9.5

func DBPasswordFetcher(cfg *config.AgentConfig, store *TokenStore) func(ctx context.Context, ticket string) (string, error)

DBPasswordFetcher retrieves the server-stored password of a database job (GET /api/v1/agents/db-credentials with the run's ticket)

func DialTunnel added in v0.7.2

func DialTunnel(cfg *config.AgentConfig, store *TokenStore) (*grpc.ClientConn, error)

DialTunnel opens only the agent-authenticated gRPC connection to the gateway (PBS tunnel and other agent services); used by worker processes that need no Temporal client.

func EncryptionKeyFetcher added in v0.13.0

func EncryptionKeyFetcher(cfg *config.AgentConfig, store *TokenStore) func(ctx context.Context, ticket string) (*backup.Encryption, error)

EncryptionKeyFetcher retrieves the target's client-side encryption key for a run (GET /api/v1/agents/encryption-key with the run's ticket); nil when the target is not encrypted. The key stays in memory for the run only.

func FindDefaultConfig

func FindDefaultConfig(agentType string) string

FindDefaultConfig returns the first existing agent.yaml among the conventional locations for the agent type: the default data dir (env / system dir as root / home), then the others.

func IsWindowsService added in v0.9.5

func IsWindowsService() bool

IsWindowsService is always false outside Windows

func LoadConfig

func LoadConfig(a Agent, configPath string) (*config.AgentConfig, string, error)

LoadConfig loads the agent configuration (configPath or the default location) and self-enrolls when the agent has no identity but an enrollment key is configured (config file or FALLBCK_AGENT_ENROLLMENT_KEY). It returns the configuration and the path it should be persisted to.

func M365CredentialsFetcher added in v0.14.0

func M365CredentialsFetcher(cfg *config.AgentConfig, store *TokenStore) func(ctx context.Context, ticket string) (*m365.Credentials, error)

M365CredentialsFetcher retrieves the tenant credentials of a Microsoft 365 job (GET /api/v1/agents/m365-credentials with the run's ticket)

func MergeStoredProfiles added in v0.12.0

func MergeStoredProfiles(cfg *config.AgentConfig) error

MergeStoredProfiles overlays the encrypted credential store onto the profiles the configuration already carries (agent.yaml and FALLBCK_AGENT_DB_PROFILE_* env, both plain text). The store wins on a name clash. Plain-text profiles keep working but are logged once so operators know to import them.

func MigrateDBAgent added in v0.10.1

func MigrateDBAgent(fromDir, cfgPath string) error

MigrateDBAgent takes over a fallbck-db-agent installation for the combined agent: the binlog/WAL chain state (state/db) is copied into this agent's data directory so continuation backups keep their chain, and the credential profiles and tool directories from the old agent.yaml are merged into this agent's configuration when it has none. Nothing is deleted; the server-side move of the jobs and the removal of the old service are printed for the operator.

func PBSCredentialsFetcher

func PBSCredentialsFetcher(cfg *config.AgentConfig, store *TokenStore) func(ctx context.Context, ticket string) (*backup.DirectOptions, error)

PBSCredentialsFetcher retrieves PBS connection details for direct-mode jobs

func PrintEnrolled

func PrintEnrolled(a Agent, cfg *config.AgentConfig)

PrintEnrolled prints the post-enrollment summary and how to start the service

func ProfileSummaries added in v0.12.0

func ProfileSummaries(cfg *config.AgentConfig) []dbspec.ProfileSummary

ProfileSummaries lists the profiles an agent will report to the server: names, engines, users and hosts, never passwords

func ProgressReporter added in v0.9.0

func ProgressReporter(cfg *config.AgentConfig, store *TokenStore) func(ctx context.Context, ticket string, runID uuid.UUID, phase string, items map[string]rundetail.ProgressItem) error

ProgressReporter returns a best-effort function that posts live run progress to the server (phase and/or per-item statuses), authenticated with the run's backup ticket.

func Run

func Run(a Agent, cfg *config.AgentConfig, configPath string, register func(w worker.Worker, conns *Conns, store *TokenStore) error) error

Run starts the daemon: connections, an activity-only worker on the agent's task queue with the activities registered by register, and the heartbeat loop; it blocks until SIGINT/SIGTERM.

func RunAsService added in v0.9.5

func RunAsService(string, func(stop <-chan struct{}) error) error

RunAsService is Windows-only

func RunUntil added in v0.9.5

func RunUntil(a Agent, cfg *config.AgentConfig, configPath string, register func(w worker.Worker, conns *Conns, store *TokenStore) error, stop <-chan struct{}) error

RunUntil is Run with an explicit stop signal (the Windows service control manager closes stop on a stop request)

func ServerHTTPClient

func ServerHTTPClient(cfg *config.AgentConfig) *http.Client

ServerHTTPClient builds the HTTP client for the FallBCK server (trusting a private CA and/or skipping verification if configured). A CA bundle that cannot be loaded is logged and the system roots are used instead, so the failure shows up here rather than as an opaque certificate error on the first request.

func ServiceCommand added in v0.9.5

func ServiceCommand(name, _, _, action, _ string) error

ServiceCommand is Windows-only; Linux installs use the packaged systemd/OpenRC units

func StartHeartbeat

func StartHeartbeat(ctx context.Context, cfg *config.AgentConfig, store *TokenStore, a Agent)

StartHeartbeat reports the agent online every 30 s, applies the server's remote debug-logging toggle from the response, and rotates the token when it approaches expiry; it returns when ctx is cancelled. logging may be nil.

func SubTicketFetcher added in v0.14.0

func SubTicketFetcher(cfg *config.AgentConfig, store *TokenStore) func(ctx context.Context, sessionTicket, group string) (string, int64, error)

SubTicketFetcher mints the ticket of one unit snapshot of a run (POST /api/v1/agents/sub-ticket); the group must extend the run's own group

func TicketGet

func TicketGet(ctx context.Context, httpClient *http.Client, cfg *config.AgentConfig, store *TokenStore, path, ticket string, out any) error

TicketGet performs an agent-authenticated GET carrying a backup ticket and decodes the JSON response into out.

func TicketPost added in v0.7.2

func TicketPost(ctx context.Context, httpClient *http.Client, cfg *config.AgentConfig, store *TokenStore, path, ticket string, body, out any) error

TicketPost performs an agent-authenticated POST carrying a backup ticket, a JSON body, and decodes the JSON response into out.

func TicketRefresher added in v0.9.5

func TicketRefresher(cfg *config.AgentConfig, store *TokenStore) func(ctx context.Context, ticket string) (string, int64, error)

TicketRefresher returns a function that re-issues a run's backup ticket with a fresh snapshot timestamp (POST /api/v1/agents/ticket/refresh); retried backup activities use it so PBS does not reject the retry as older than the previous attempt's snapshot.

Types

type Agent

type Agent struct {
	// Name is the binary name (fallbck-agent, fallbck-k8s-agent); used for identities and messages
	Name string
	// Type is config.AgentTypeFilesystem or config.AgentTypeDatabase
	Type    string
	Version string
	// Logging is the process logging setup (SetupLogging); the heartbeat loop applies
	// the server's per-agent debug toggle to it and failures attach its ring buffer
	Logging *Logging
	// PersistToken overrides where token rotations are stored (TokenStore.Persist);
	// used by the kubernetes agent to write into its identity Secret
	PersistToken func(cfg *config.AgentConfig) error
	// DBEngines reports the database engines this agent can back up (the combined
	// filesystem agent probes them); nil means the agent never runs database jobs
	DBEngines func() []string
	// Inventory builds the periodic summary attached to heartbeats (nil: none)
	Inventory *Inventory
	// contains filtered or unexported fields
}

Agent identifies the binary using the runtime

type Conns

type Conns struct {
	HostPort string
	Temporal client.Client
	// Tunnel carries PBS backup sessions and other agent-authenticated gRPC services
	Tunnel *grpc.ClientConn
}

Conns are the agent's connections to the server gateway

func Connect

func Connect(cfg *config.AgentConfig, store *TokenStore, identity string) (*Conns, error)

Connect opens the Temporal client and the tunnel connection through the gateway, both authenticated with the agent token

func (*Conns) Close

func (c *Conns) Close()

Close releases both connections

type DebugControl added in v0.6.2

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

DebugControl owns the agent's stdout log level: a base level from environment and config, and a runtime override the server toggles per agent via heartbeats.

func (*DebugControl) Level added in v0.6.2

func (d *DebugControl) Level() slog.Level

Level reports the current stdout log level

func (*DebugControl) SetBase added in v0.6.2

func (d *DebugControl) SetBase(level slog.Level)

SetBase installs the configured base level (unless a remote override is active)

func (*DebugControl) SetRemoteDebug added in v0.6.2

func (d *DebugControl) SetRemoteDebug(enabled bool) bool

SetRemoteDebug applies or clears the server-side debug toggle; it reports whether the state changed.

type Inventory added in v0.12.0

type Inventory struct {

	// Extra fills type-specific detail (nil on agents without any)
	Extra func(ctx context.Context, d *inventory.Detail)
	// ExtraCounts fills the cheap resource counts of the summary
	ExtraCounts func(ctx context.Context, counts map[string]int)
	// contains filtered or unexported fields
}

Inventory builds what the agent reports about its host: the compact Summary the heartbeat carries every few minutes and the full Detail an operator asks for. Agents plug in the type-specific parts (Docker containers, cluster namespaces).

func NewInventory added in v0.12.0

func NewInventory(cfg *config.AgentConfig, configPath, version string) *Inventory

NewInventory prepares the collector for a running agent

func (*Inventory) Detail added in v0.12.0

func (inv *Inventory) Detail(ctx context.Context) *inventory.Detail

Detail is the full inventory

func (*Inventory) Summary added in v0.12.0

func (inv *Inventory) Summary(ctx context.Context) *inventory.Summary

Summary is the periodic part (tools are re-detected at most every ten minutes)

type LogRing added in v0.6.2

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

LogRing keeps the most recent log lines (all levels, independent of the stdout level) so a failed backup can ship them to the server.

func (*LogRing) Tail added in v0.6.2

func (r *LogRing) Tail() string

Tail returns the buffered lines, oldest first

func (*LogRing) Write added in v0.6.2

func (r *LogRing) Write(p []byte) (int, error)

type Logging added in v0.6.2

type Logging struct {
	Control *DebugControl
	Ring    *LogRing
}

Logging is the agent's logging setup: the stdout logger (level adjustable at runtime) plus the ring buffer that always captures debug-level lines.

func SetupLogging added in v0.6.2

func SetupLogging() *Logging

SetupLogging installs the process-wide logger: JSON on stdout at the environment's level (adjustable later), and a text copy of every record — including debug — into the ring buffer.

func (*Logging) ApplyConfigLogLevel added in v0.6.2

func (l *Logging) ApplyConfigLogLevel(cfg *config.AgentConfig)

ApplyConfigLogLevel applies agent.yaml's log_level as the base level unless the environment already chose one (DEBUG / FALLBCK_LOG_LEVEL win).

func (*Logging) Tail added in v0.6.2

func (l *Logging) Tail() string

Tail returns the recent log lines for failure reports

type TokenStore

type TokenStore struct {

	// Persist overrides where rotations are stored (e.g. a Kubernetes Secret);
	// default: rewrite the token fields of the config file
	Persist func(cfg *config.AgentConfig) error
	// contains filtered or unexported fields
}

TokenStore holds the current agent token and persists rotations

func NewTokenStore

func NewTokenStore(cfg *config.AgentConfig, configPath string) *TokenStore

NewTokenStore wraps the loaded configuration; rotations are written to configPath

func (*TokenStore) ExpiresAt

func (t *TokenStore) ExpiresAt() time.Time

func (*TokenStore) Token

func (t *TokenStore) Token() string

func (*TokenStore) Update

func (t *TokenStore) Update(token string, expires time.Time) error

Update installs a rotated token and persists it (only the token fields are rewritten)

Jump to

Keyboard shortcuts

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