store

package
v0.38.2 Latest Latest
Warning

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

Go to latest
Published: Nov 6, 2026 License: GPL-3.0 Imports: 22 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// ActivityRawSeconds is how long a remote address is kept.
	ActivityRawSeconds = 86400
	// ActivityRetention is how long samples, hourly totals and alerts are kept.
	ActivityRetention = 35 * 24 * time.Hour
)
View Source
const UsageRetention = 35 * 24 * time.Hour

UsageRetention is how long hourly usage is kept. The graphs read 30 days; a few more so the oldest point is never half-trimmed.

Variables

View Source
var ErrCustomServiceNotFound = errors.New("custom service not found")

ErrCustomServiceNotFound is returned when an update names no live custom service.

View Source
var ErrProxyNotFound = errors.New("no such proxy")

ErrProxyNotFound is returned when an id names no proxy.

Functions

func EffectiveFleetStatus added in v0.8.0

func EffectiveFleetStatus(status, lastSeen string, threshold time.Duration) string

EffectiveFleetStatus returns the status a fleet device should DISPLAY given how long ago it last checked in. It is the read-path sibling of SweepStaleFleetDevices' SQL: an "online" device whose lastSeen is older than threshold is shown as "offline" immediately, so the Fleet view is accurate between scheduler ticks without the read path ever mutating storage. lastSeen is parsed as RFC3339 (the format the heartbeat writes); a value that does not parse (e.g. AddFleetDevice's "not connected yet", or an empty last_seen) leaves the status unchanged, as does any non-"online" status.

func HashFleetKey added in v0.10.0

func HashFleetKey(key string) string

HashFleetKey returns the SHA-256 hex digest of a per-worker fleet key. The desktop fleet server only verifies inbound heartbeats and issues keys (it never calls out to devices), so a one-way hash is sufficient storage at rest.

Types

type ActivityAlert added in v0.34.0

type ActivityAlert struct {
	Kind      string `json:"kind"`
	Subject   string `json:"subject"`
	Message   string `json:"message"`
	CreatedAt int64  `json:"createdAt"`
}

ActivityAlert is one alert raised.

type ActivityDest added in v0.34.0

type ActivityDest struct {
	Dir, Proto, IP, Class, ASN, CC string
	Port, Seen                     int
}

ActivityDest is one destination to store, with its network and country.

type ActivityDim added in v0.34.0

type ActivityDim struct {
	Container string
	Dim       string
	Value     string
	Sightings int64
}

ActivityDim is the sightings of one value of one dimension over a period.

type ActivityPoint added in v0.34.0

type ActivityPoint struct {
	Container    string `json:"-"`
	T            int64  `json:"t"`
	Opens        *int64 `json:"opens"`
	AttemptFails *int64 `json:"attemptFails"`
	EstMax       *int64 `json:"estMax"`
}

ActivityPoint is one point of a container's series: opens, failures and peak open.

type ActivityRawRow added in v0.34.0

type ActivityRawRow struct {
	WindowEnd int64  `json:"windowEnd"`
	Dir       string `json:"dir"`
	Proto     string `json:"proto"`
	IP        string `json:"ip"`
	Port      int    `json:"port"`
	Class     string `json:"class"`
	ASN       string `json:"asn"`
	CC        string `json:"cc"`
	Seen      int    `json:"seen"`
}

ActivityRawRow is one raw destination still inside the one-day window.

type ActivitySample added in v0.34.0

type ActivitySample struct {
	Container    string         `json:"container"`
	WindowEnd    int64          `json:"windowEnd"`
	Status       string         `json:"status"`
	Reason       string         `json:"reason"`
	Members      []string       `json:"members"`
	NetworkMode  string         `json:"networkMode"`
	Opens        *int64         `json:"opens"`
	PassiveOpens *int64         `json:"passiveOpens"`
	AttemptFails *int64         `json:"attemptFails"`
	Resets       *int64         `json:"resets"`
	UDPIn        *int64         `json:"udpIn"`
	UDPOut       *int64         `json:"udpOut"`
	EstMax       *int64         `json:"estMax"`
	SynSentMax   *int64         `json:"synSentMax"`
	UDPBound     *int64         `json:"udpBound"`
	ListenPorts  []int          `json:"listenPorts"`
	RemotesTotal *int64         `json:"remotesTotal"`
	Truncated    bool           `json:"truncated"`
	Dests        []ActivityDest `json:"-"`
}

ActivitySample is one stored row of activity_samples.

type CustomService added in v0.33.0

type CustomService struct {
	Slug       string
	Definition []byte
}

CustomService is one stored definition, decrypted. Definition is the JSON the services package wrote; the store never reads inside it.

type DailyBalance added in v0.6.0

type DailyBalance struct {
	Platform string
	Currency string
	Day      string // "YYYY-MM-DD" (UTC)
	Balance  float64
}

type Deployment

type Deployment struct {
	Slug        string  `json:"slug"`
	ContainerID string  `json:"containerId"`
	Name        string  `json:"name"`
	Image       string  `json:"image"`
	Status      string  `json:"status"`
	Runtime     string  `json:"runtime"`
	CPUPercent  float64 `json:"cpuPercent"`
	MemoryMB    float64 `json:"memoryMb"`
	// CustomImage is the image the user chose to run instead of the catalog's, or ""
	// when the deployment follows the catalog. Only a deploy writes it (see
	// SetCustomImage); UpsertDeployment leaves it alone, so the runtime refresh that
	// rewrites every row on a timer cannot drop the choice.
	CustomImage string `json:"customImage"`
	// Instances is how many copies of the service the user asked this machine to
	// run (1 for most). Like CustomImage, only a deploy writes it (SetInstances), so
	// the refresh cannot reset it, and a redeploy that does not ask keeps it.
	Instances int    `json:"instances"`
	CreatedAt string `json:"createdAt"`
	UpdatedAt string `json:"updatedAt"`
}

type EarningsRecord

type EarningsRecord struct {
	Platform string  `json:"platform"`
	Balance  float64 `json:"balance"`
	Currency string  `json:"currency"`
	Error    string  `json:"error,omitempty"`
	// ErrorKind says what kind of failure Error is, when the collector knows:
	// "unread" means the login worked but no node could be read, so the
	// credentials are not what is wrong. Empty for a failure of unknown kind.
	ErrorKind string `json:"errorKind,omitempty"`
	CreatedAt string `json:"createdAt"`
}

type FleetDevice added in v0.6.0

type FleetDevice struct {
	ID        int64    `json:"id"`
	Name      string   `json:"name"`
	Kind      string   `json:"kind"`
	Endpoint  string   `json:"endpoint"`
	OS        string   `json:"os"`
	Arch      string   `json:"arch"`
	Status    string   `json:"status"`
	Services  []string `json:"services"`
	LastSeen  string   `json:"lastSeen"`
	CreatedAt string   `json:"createdAt"`
}

type HealthScore added in v0.8.0

type HealthScore struct {
	Score         int     `json:"score"`
	UptimePercent float64 `json:"uptimePercent"`
	Samples       int     `json:"samples"`
	Restarts      int     `json:"restarts"`
	Crashes       int     `json:"crashes"`
	Stops         int     `json:"stops"`
}

HealthScore is one service's rolling health over the query window: a 0-100 Score, the uptime percentage it was blended from, and the raw event counts the score penalises. Samples is the number of health_up/health_down datapoints in the window; a service with lifecycle events but no samples yet (uptime sampling has not run) reports Samples==0 and a Score equal to its event-score, so it is not dragged to 0 merely for lacking sampling data.

type Payout added in v0.29.0

type Payout struct {
	ID        int64    `json:"id"`
	Platform  string   `json:"platform"`
	Amount    float64  `json:"amount"`
	Currency  string   `json:"currency"`
	FxRateUSD *float64 `json:"fxRateUsd"`
	Method    string   `json:"method"`
	// PaidOn is the day the cash-out happened, YYYY-MM-DD.
	PaidOn    string `json:"paidOn"`
	CreatedAt string `json:"createdAt"`
}

Payout is a cash-out: money that left a service's balance for the user.

The dashboard total is the sum of current balances, so it drops by the amount of every cash-out, and on its own it says what is waiting, never what the services have made. The payout ledger is the rest of that answer: lifetime earned is the current balance plus what was cashed out.

FxRateUSD is what one unit of Currency was worth in USD when the cash-out landed, so a token payout keeps the value it had that day instead of being restated at today's price. Nil when no rate for that day was known: such a payout is counted as unpriced, never as zero.

type ProxiedCopy added in v0.38.0

type ProxiedCopy struct {
	ProxyID      int64
	Slug         string
	StoppedByCap bool
}

ProxiedCopy is the record of a copy of a service running through a proxy.

type Proxy added in v0.38.0

type Proxy struct {
	ID         int64
	Definition []byte
	State      []byte
}

Proxy is one stored proxy, decrypted. Definition and State are the JSON the proxies package wrote; the store never reads inside them.

type Store

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

func Open

func Open(dataDir string) (*Store, error)

func (*Store) ActivityAlerts added in v0.34.0

func (s *Store) ActivityAlerts(since int64) ([]ActivityAlert, error)

ActivityAlerts is every alert raised since since, newest first.

func (*Store) ActivityDims added in v0.34.0

func (s *Store) ActivityDims(sinceHour int64, container string) ([]ActivityDim, error)

ActivityDims sums sightings per container, dimension and value since sinceHour.

func (*Store) ActivityLatest added in v0.34.0

func (s *Store) ActivityLatest(since int64) ([]ActivitySample, error)

ActivityLatest is the newest sample of every container seen since since.

func (*Store) ActivityOpensHourly added in v0.34.0

func (s *Store) ActivityOpensHourly(sinceHour int64) (map[string]map[int64]*int64, error)

ActivityOpensHourly is connections opened per container and hour since sinceHour; nil when most windows of the hour had no count.

func (*Store) ActivityRaw added in v0.34.0

func (s *Store) ActivityRaw(container string, now time.Time) ([]ActivityRawRow, error)

ActivityRaw is the newest raw destinations of one container, at most 2000.

func (*Store) ActivitySeries added in v0.34.0

func (s *Store) ActivitySeries(since int64, hourly bool, container string) ([]ActivityPoint, error)

ActivitySeries is per window, or summed per hour in SQL: SUM over only NULLs is NULL, so an hour with no counted window stays unknown.

func (*Store) AddPayout added in v0.29.0

func (s *Store) AddPayout(p Payout) (Payout, error)

AddPayout records a cash-out and returns it with its id. An empty PaidOn is today (UTC).

func (*Store) ClearStateBackup added in v0.31.0

func (s *Store) ClearStateBackup(slug string) error

ClearStateBackup withdraws a confirmation, so the service shows as not backed up.

func (*Store) Close

func (s *Store) Close() error

func (*Store) ConfirmFleetDeviceKey added in v0.10.0

func (s *Store) ConfirmFleetDeviceKey(kind, name string) error

ConfirmFleetDeviceKey marks a device's key confirmed — it has authenticated with its own key, so the shared bootstrap key is refused for it from now on.

func (*Store) ConfirmStateBackup added in v0.31.0

func (s *Store) ConfirmStateBackup(slug, stateID, method string, at time.Time) error

ConfirmStateBackup records that slug's state, as fingerprinted by stateID, is backed up as of at.

func (*Store) CustomServiceSlugs added in v0.33.0

func (s *Store) CustomServiceSlugs() (map[string]bool, error)

CustomServiceSlugs is every slug ever used for a custom service, deleted ones included, so a new one never takes a slug whose data volume may still exist.

func (*Store) DeleteActivity added in v0.34.0

func (s *Store) DeleteActivity(all bool) (busy bool, err error)

DeleteActivity deletes the raw destinations, or with all every Activity row. busy is true when a reader kept the database log from being emptied: the deleted rows may stay in it until the next hourly purge.

func (*Store) DeleteCustomService added in v0.33.0

func (s *Store) DeleteCustomService(slug string) error

DeleteCustomService drops the definition and keeps the slug as a tombstone.

func (*Store) DeleteDeployment

func (s *Store) DeleteDeployment(slug string) error

func (*Store) DeleteFleetDevice added in v0.6.0

func (s *Store) DeleteFleetDevice(id int64) error

func (*Store) DeletePayout added in v0.29.0

func (s *Store) DeletePayout(id int64) (bool, error)

DeletePayout removes a cash-out recorded by mistake, the way back out of AddPayout: a wrong entry would otherwise inflate lifetime earnings with no way to correct it. False when no payout has that id.

func (*Store) DeleteProxiedCopiesOf added in v0.38.0

func (s *Store) DeleteProxiedCopiesOf(slug string) error

DeleteProxiedCopiesOf drops every copy record of a service, when it is removed.

func (*Store) DeleteProxiedCopy added in v0.38.0

func (s *Store) DeleteProxiedCopy(proxyID int64, slug string) error

DeleteProxiedCopy drops one copy record.

func (*Store) DeleteProxy added in v0.38.0

func (s *Store) DeleteProxy(id int64) error

DeleteProxy drops a proxy and its copy records.

func (*Store) FleetDeviceKeyState added in v0.10.0

func (s *Store) FleetDeviceKeyState(kind, name string) (hash string, confirmed bool, err error)

FleetDeviceKeyState returns the stored per-worker key hash and confirmed flag for the device identified by (kind, name). hash is "" when the device has no key yet (unenrolled).

func (*Store) GetCredentials

func (s *Store) GetCredentials(slug string) (map[string]string, error)

func (*Store) GetCustomService added in v0.33.0

func (s *Store) GetCustomService(slug string) (CustomService, bool, error)

GetCustomService returns a live custom service's definition.

func (*Store) GetDeployment

func (s *Store) GetDeployment(slug string) (Deployment, bool, error)

func (*Store) GetProxy added in v0.38.0

func (s *Store) GetProxy(id int64) (Proxy, bool, error)

GetProxy returns one proxy.

func (*Store) GetServiceDetail added in v0.9.0

func (s *Store) GetServiceDetail(slug string) (string, error)

GetServiceDetail returns the stored JSON detail blob for a slug, or "" (and no error) when the slug has no detail row yet — an absent detail is a normal state, not a failure, mirroring GetCredentials' empty-map-on-ErrNoRows contract.

func (*Store) HealthScores added in v0.8.0

func (s *Store) HealthScores(days int) map[string]HealthScore

HealthScores computes a 0-100 health score per service from the runtime_events written over the last `days` days, keyed by slug. It adapts the production CashPilot health formula to the Desktop's event vocabulary:

  • event-score: start at 100, then -5 per restart (a "restarted" event), -20 per crash (any "*_error" or "missing_from_runtime"), -2 per stop (a "stopped" event); floored at 0 (and capped at 100, a no-op while subtracting).
  • uptime%: health_up / (health_up + health_down) * 100 over the window, from the per-cycle up/down sampling. Zero samples -> 0.
  • final score: once there is at least one uptime sample, blend 40% event-score with 60% uptime% (full-precision uptime, as the original does); with NO samples yet the score is the event-score alone, so a service is not punished to 0 merely because sampling has not produced data.

runtime_events.created_at is written as datetime('now') ("YYYY-MM-DD HH:MM:SS", UTC), so the window is compared against datetime('now', '-N days') in that same format — NOT the RFC3339Nano earnings uses. Only slugs with at least one event in the window appear in the returned map.

func (*Store) InsertCustomService added in v0.33.0

func (s *Store) InsertCustomService(slug string, definition []byte) error

InsertCustomService stores a new custom service. It fails when the slug was ever used, deleted ones included.

func (*Store) InsertProxy added in v0.38.0

func (s *Store) InsertProxy(definition []byte) (int64, error)

InsertProxy stores a new proxy and returns its id.

func (*Store) ListCredentialSlugs added in v0.7.0

func (s *Store) ListCredentialSlugs() []string

ListCredentialSlugs returns the slug of every service that has saved credentials, ordered by slug. collectAll unions this with the deployment set so imageless supported services (which never create a deployment row) still participate in the scheduled collection cycle.

func (*Store) ListCustomServices added in v0.33.0

func (s *Store) ListCustomServices() ([]CustomService, error)

ListCustomServices returns every live custom service, by slug. A definition that fails to decrypt fails the whole read rather than vanishing from the list.

func (*Store) ListDailyBalances added in v0.6.0

func (s *Store) ListDailyBalances(daysBack int) []DailyBalance

ListDailyBalances returns the latest successful balance (rows whose error column is empty) for each (platform, day) over the last daysBack days. The latest row per (platform, day) is chosen by MAX(id), not MAX(created_at): created_at is stored as RFC3339Nano whose variable-length fraction makes a lexicographic MAX(created_at) mis-order same-second rows (e.g. "…:00Z" sorts AFTER "…:00.5Z" because 'Z' > '.'), so the monotonic AUTOINCREMENT id is the deterministic "last written wins" key.

func (*Store) ListDeployments

func (s *Store) ListDeployments() []Deployment

func (*Store) ListFleetDevices added in v0.6.0

func (s *Store) ListFleetDevices() []FleetDevice

func (*Store) ListLatestEarnings

func (s *Store) ListLatestEarnings() []EarningsRecord

ListLatestEarnings returns the most recently written row per platform, INCLUDING error rows (the dashboard breakdown and notifications rely on the latest row even when it failed). The latest row per platform is chosen by MAX(id), not MAX(created_at): created_at is RFC3339Nano whose variable-length fraction makes a lexicographic MAX(created_at) mis-order same-second rows (e.g. "…:00Z" sorts ABOVE "…:00.5Z" because 'Z' > '.'), so the monotonic AUTOINCREMENT id is the deterministic "last written wins" key — matching the shape ListDailyBalances already uses.

func (*Store) ListPayouts added in v0.29.0

func (s *Store) ListPayouts(platform string) ([]Payout, error)

ListPayouts returns the cash-outs of one platform, or of every platform when platform is "", newest first. Unlike the earnings reads it returns its error: a ledger that could not be read is unknown, and an empty list would claim nothing was ever cashed out.

func (*Store) ListProxiedCopies added in v0.38.0

func (s *Store) ListProxiedCopies(proxyID int64) ([]ProxiedCopy, error)

ListProxiedCopies returns the copy records, of one proxy when proxyID > 0.

func (*Store) ListProxies added in v0.38.0

func (s *Store) ListProxies() ([]Proxy, error)

ListProxies returns every proxy, by id. A definition that fails to decrypt fails the whole read rather than vanishing from the list.

func (*Store) ListServiceDetails added in v0.9.0

func (s *Store) ListServiceDetails() map[string]string

ListServiceDetails returns every stored per-service detail blob keyed by slug, so GetAppState can hand the frontend all detail documents in one read. A query or scan error yields an empty (non-nil) map rather than failing, matching the best-effort intent of the other list methods; callers can always range over the result safely.

func (*Store) PurgeActivity added in v0.34.0

func (s *Store) PurgeActivity(now time.Time) (busy bool, err error)

PurgeActivity deletes raw destinations older than a day and every other Activity row older than ActivityRetention, then folds the WAL back into the file so the deleted addresses are not left in it. busy is true when a reader kept the checkpoint from finishing; the next purge tries again.

func (*Store) PurgeOldData added in v0.8.0

func (s *Store) PurgeOldData(retentionDays int) (int64, error)

PurgeOldData deletes earnings and runtime_events rows older than the cutoff, but NEVER the most-recent earnings row per platform (so ListLatestEarnings and the dashboard breakdown keep working for a service that hasn't updated in a long time). Returns the number of rows deleted. A retentionDays <= 0 is a no-op (retention disabled).

func (*Store) PurgeUsage added in v0.30.0

func (s *Store) PurgeUsage(now time.Time) error

PurgeUsage drops hourly rows older than UsageRetention and baselines older than a day (a baseline is useless after an hour; internal/usage refuses it).

func (*Store) RaiseActivityAlert added in v0.34.0

func (s *Store) RaiseActivityAlert(a ActivityAlert, cooldown time.Duration) (bool, error)

RaiseActivityAlert stores an alert unless the same kind and subject was raised within cooldown. It reports whether it stored one.

func (*Store) RecordActivity added in v0.34.0

func (s *Store) RecordActivity(windowEnd int64, samples []ActivitySample, now time.Time, wanted func() bool) (int, error)

RecordActivity stores one window. A window already stored for a container is ignored whole, so a retried write cannot count its destinations twice. The raw purge runs in the same transaction. wanted is read inside the write lock: when it says no (Activity was switched off meanwhile), nothing is stored.

func (*Store) RecordEvent

func (s *Store) RecordEvent(slug, event, detail string)

func (*Store) RecordUsage added in v0.30.0

func (s *Store) RecordUsage(fold func(map[string]UsageBaseline) ([]UsageHour, map[string]UsageBaseline)) error

RecordUsage reads the baselines, lets fold turn them and one reading into hourly rows and new baselines, and stores both, all in one transaction. Reading the baselines and storing the new ones must be one step: a failure halfway would otherwise keep the rows without the baselines, and the next reading would count the same traffic again. The window and the background daemon can both sample the same database, so the read has to be inside the write lock.

func (*Store) SaveCredentials

func (s *Store) SaveCredentials(slug string, values map[string]string) error

func (*Store) SaveEarnings

func (s *Store) SaveEarnings(record EarningsRecord) (EarningsRecord, error)

func (*Store) SaveProxiedCopy added in v0.38.0

func (s *Store) SaveProxiedCopy(proxyID int64, slug string) error

SaveProxiedCopy records a copy of slug through a proxy.

func (*Store) SaveServiceDetail added in v0.9.0

func (s *Store) SaveServiceDetail(slug, detailJSON string) error

SaveServiceDetail upserts a per-service JSON detail blob keyed by slug. It is a generic sidecar to the flat earnings row: any collector can stash a JSON document (e.g. the MystNodes per-node earnings breakdown) alongside its balance without widening the earnings schema. The blob is stored verbatim — the collector owns its shape and the frontend parses it — so this method never inspects detailJSON.

func (*Store) SetCustomImage added in v0.22.0

func (s *Store) SetCustomImage(slug, image string) error

SetCustomImage records the image a deploy of slug used instead of the catalog's, or clears it with "". It is kept with the deployment row, so the next redeploy finds it there, and removing the service forgets it with the rest of the row.

func (*Store) SetFleetDeviceKey added in v0.10.0

func (s *Store) SetFleetDeviceKey(kind, name, hash string) error

SetFleetDeviceKey stores a device's per-worker key hash and marks it unconfirmed (the device confirms by authenticating with the key later). It errors if the device row does not exist, so a caller never hands a client a key that was not actually persisted (which would lock that client out).

func (*Store) SetInstances added in v0.23.0

func (s *Store) SetInstances(slug string, n int) error

SetInstances records how many copies of slug a deploy started, so the next redeploy that does not say starts the same number.

func (*Store) SetProxiedCopyCapped added in v0.38.0

func (s *Store) SetProxiedCopyCapped(proxyID int64, slug string, capped bool) error

SetProxiedCopyCapped marks whether the cap (rather than the owner) stopped a copy.

func (*Store) StateBackup added in v0.31.0

func (s *Store) StateBackup(slug string) (*statebackup.Confirmation, error)

StateBackup returns slug's confirmation, or nil when there is none.

func (*Store) SweepStaleFleetDevices added in v0.8.0

func (s *Store) SweepStaleFleetDevices(offlineAfter, reapAfter time.Duration) (offlined int64, reaped int64, err error)

SweepStaleFleetDevices ages fleet devices out of the online set as heartbeats stop arriving, mirroring production CashPilot's device lifecycle: a device whose last_seen is older than offlineAfter is flipped to "offline" (the ~180s / 3-missed-heartbeat grace), and one already "offline" whose last_seen is older than reapAfter is deleted (the ~1h reap). It returns how many rows were offlined and how many were reaped.

last_seen is written by UpsertFleetHeartbeat / fleet_server as an RFC3339 timestamp WITHOUT a fractional part, so it is fixed-length and UTC; formatting the cutoffs the same way makes the lexicographic string comparison a correct chronological order. A non-timestamp placeholder such as AddFleetDevice's "not connected yet" sorts above any real cutoff, so a never-connected device is never swept.

func (*Store) UpdateCustomService added in v0.33.0

func (s *Store) UpdateCustomService(slug string, definition []byte) error

UpdateCustomService replaces a live custom service's definition.

func (*Store) UpdateProxyDefinition added in v0.38.0

func (s *Store) UpdateProxyDefinition(id int64, definition []byte) error

UpdateProxyDefinition replaces a proxy's definition.

func (*Store) UpdateProxyState added in v0.38.0

func (s *Store) UpdateProxyState(id int64, state []byte) error

UpdateProxyState replaces a proxy's state.

func (*Store) UpsertDeployment

func (s *Store) UpsertDeployment(dep Deployment) error

func (*Store) UpsertFleetDevice added in v0.6.0

func (s *Store) UpsertFleetDevice(device FleetDevice) (FleetDevice, error)

func (*Store) UpsertFleetHeartbeat added in v0.6.0

func (s *Store) UpsertFleetHeartbeat(device FleetDevice) (FleetDevice, error)

func (*Store) UsageHours added in v0.30.0

func (s *Store) UsageHours(since int64) ([]UsageHour, error)

UsageHours returns every hourly row from since (Unix seconds) on, oldest first.

type UsageBaseline added in v0.30.0

type UsageBaseline struct {
	Rx, Tx int64
	SeenAt float64
}

UsageBaseline is the last cumulative network counters seen for a container id, and when (Unix seconds), so the next reading can be differenced.

type UsageHour added in v0.30.0

type UsageHour struct {
	Container string
	Hour      int64
	Slug      string
	// Beats is how many readings saw the container running. CPUN or MemN below it
	// means a stats read failed in that hour, so a total without it is a floor.
	Beats  int
	CPUSum float64
	CPUN   int
	MemSum float64
	MemN   int
	// Bytes moved over NetSeconds, nil when no reading carried a usable delta.
	RxBytes    *int64
	TxBytes    *int64
	NetSeconds float64
	// Readings with no counters at all (host network, a native program).
	NoCounters int
	// Readings whose traffic since the last one was lost (a stale baseline).
	TrafficLost int
}

UsageHour is one container's row for one UTC hour (Hour is its start, in Unix seconds). RecordUsage takes one heartbeat's worth per container (Beats 1) and adds it to the stored row.

Jump to

Keyboard shortcuts

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