Documentation
¶
Overview ¶
Package loki is Loki's settings: what an operator may change, the ranges pstack holds them to, and the bytes they become in control/loki/config.yaml and control/loki/s3-credentials.
── PSTACK CLAMPS, BECAUSE LOKI DOES NOT ─────────────────────────────────────────────────────────
retentionDays 1–365 retention_period AND max_query_lookback, <d×24>h chunks.idlePeriodMinutes 5–60 chunk_idle_period; never above the max age chunks.maxAgeMinutes 30–180 max_chunk_age; query_ingesters_within = max age + 60m chunks.targetSizeKiB 512–1536 chunk_target_size; the ceiling is slice 1's value chunks.encoding snappy gzip lz4 zstd
Loki range-checks none of the chunk values but the encoding. A max age at or above query_ingesters_within hides unflushed chunks from queries, so the window is derived, not set. The size ceiling is slice 1's because memory grows with it and mem_limit/GOMEMLIMIT are not settings. The ranges live in ONE value (bounds): GET /api/logging serves it as `limits`, Validate enforces it, and the two cannot drift.
── RENDERING IS LITERAL ─────────────────────────────────────────────────────────────────────────
Render starts from slice 1's embedded file and walks an ordered anchor list: strings.Contains, then strings.Replace(n=1) (invariant 18, rule 8). An anchor is the value half of a line, so trailing comments survive. All ten are checked on every render — on filesystem the three S3 anchors write themselves back — so a template edit that moves one fails the next save by name, not the first S3 save months later. With Defaults() every replacement writes the text it found: the default bytes ARE slice 1's, and a slice-1 host reconciles to nothing.
Nothing is quoted or escaped. Render runs Validate's value checks before it writes a byte, so every string it renders passed a charset rule and every number is an int, whoever the caller is.
── S3 IS A SECOND PERIOD; CREDENTIALS NEVER TOUCH config.yaml ───────────────────────────────────
Filesystem → S3 appends a schema period from the cutover and never edits one: a period whose date has passed cannot change without making its data unreadable. The keys go in an AWS shared-credentials file the SDK re-reads on every restart (AWS_SHARED_CREDENTIALS_FILE, set by init). `docker restart` keeps a container's environment, so a key in the env would never rotate. config.yaml stays 0644 and credential-free. s3-credentials is 0600 and must be Loki's: root chowns it, Loki's own uid writes it as is, any other euid is refused (ErrNeedsRoot). A root-owned 0600 file would verify, go ready and fail only at the first flush after the cutover.
── ERRORS ───────────────────────────────────────────────────────────────────────────────────────
*Error is a refused value: 400 with its sentence. ErrOneWay, ErrFixed and ErrNeedsRoot conflict with the host's state: handlers map them to 409 with errors.Is (the inspect.ErrNoDocker shape), and one that escapes to fail() is a 500, never a mislabelled 400.
Pure: it may import pstack, store, yamlx, omap/jsonx and stdlib, nothing that reaches a server or docker, so its tests need neither.
Index ¶
- Constants
- Variables
- func Changed(before *Row, after Settings, afterSecret string) []string
- func CheckPeriods(loaded, next []Period, now time.Time, lead time.Duration, adding bool) error
- func Credentials(keyID, secret string) string
- func CredentialsOwner(lokiUID int) error
- func Dir(dataDir string) string
- func EarliestCutover(t time.Time, lead time.Duration) string
- func Finish(st *store.Store) error
- func IsError(err error) bool
- func Lead(readyTimeout time.Duration) time.Duration
- func Probe(ctx context.Context, s S3, secret string) error
- func Render(s Settings) (string, error)
- func Revert(st *store.Store) error
- func Save(st *store.Store, s Settings, secret string, previous *Row) error
- func Validate(s Settings, secret string, addingS3 bool, lead time.Duration) error
- func Writable(dir string) bool
- func WriteFile(path, body string, mode os.FileMode, lokiUID int) error
- type Chunks
- type ChunksPatch
- type Error
- type Limits
- type Period
- type Range
- type Row
- type S3
- type Settings
- type Storage
- type StoragePatch
Constants ¶
const ( StorageFilesystem = "filesystem" StorageS3 = "s3" )
The storage types.
const ( ConfigFile = "config.yaml" CredentialsFile = "s3-credentials" NextSuffix = ".next" )
The files, in <LokiDir>. A write goes to <name>.next and is renamed over <name>.
Variables ¶
var ( ErrOneWay = errors.New("S3 is one-way on this host") ErrFixed = errors.New("S3 storage is fixed once saved — only accessKeyId and secretAccessKey change") ErrNeedsRoot = errors.New("the S3 credentials file needs root") )
The conflicts with the host's state. Not *Error: handlers answer 409 with errors.Is.
Functions ¶
func Changed ¶
Changed is logging.changed's `changed`, in this order: chunks, retention, storage (the type or any S3 field but the key id), credentials (the key id or the secret). Never nil. Empty means after equals the row, which is how the apply and the PUT spot a no-op.
func CheckPeriods ¶
CheckPeriods refuses writing `next` over `loaded`.
Rule 1: every loaded period starting at or before now+lead stays in next, unchanged, at its index. Rule 2 (adding): every next period not in loaded starts after now+2×lead, so the swap, a failed ready wait and a whole rollback all finish before it. A rollback passes adding=false: a period that has not started stores nothing, so undoing a failed apply may drop it.
A `from` that is not YYYY-MM-DD parses to the zero time, so it counts as started: live for rule 1, too close for rule 2.
func Credentials ¶
Credentials is s3-credentials. Both values passed iniValue, so nothing needs escaping.
func CredentialsOwner ¶
CredentialsOwner is nil when this process can give Loki (lokiUID) a 0600 file it can read: as root, by chowning, or as Loki's own uid.
func Dir ¶
Dir is control/loki for THIS process (routing.DynamicDir's resolution): PSTACK_LOKI_DIR by presence (rule 11), then the in-container mount, then the host-side path under the data dir.
func EarliestCutover ¶
EarliestCutover is the first UTC date whose 00:00 is strictly after t + 2×lead + 10m: the swap, a failed ready wait and a whole rollback all finish before the S3 period starts. Truncating to 24h lands on a UTC midnight at or before the window's end, so the next one is strictly after it.
func Probe ¶
Probe PUTs then DELETEs an empty pstack-probe-<16 hex> object in s.Bucket. Every failure is a *Error (400).
func Revert ¶
Revert undoes an apply: the row becomes previous, or goes when previous is empty. The two WHEREs are disjoint and NULL matches neither, so the pair needs no transaction and leaves a row with no apply in flight untouched.
func Save ¶
Save stores a save and its undo record in ONE statement, so no crash leaves one without the other. previous is the row the apply read (nil: the table was empty).
func Validate ¶
Validate is every rule a save must pass. addingS3 is true on the save that turns S3 on: only that save's cutover is held to EarliestCutover; a key rotation after the cutover is not.
func Writable ¶
Writable is true when dir holds config.yaml and this process may write beside it. A mount can be present but `:ro`, which only a write shows (routing.RoutingStore.Writable, copied: loki does not import routing).
func WriteFile ¶
WriteFile writes body at exactly mode. A 0600 file is refused unless CredentialsOwner passes, and as root it is chowned to lokiUID.
Created at mode, not 0o666-then-chmod: the secret is never world-readable, even for an instant. A leftover (a .next from a killed apply, or a symlink) is removed first: a truncating write keeps an old file's mode and follows a link. The Chmod still runs, because umask may strip bits a 0644 config.yaml needs for Loki's uid to read it.
Types ¶
type Chunks ¶
type Chunks struct {
IdlePeriodMinutes int `json:"idlePeriodMinutes"`
MaxAgeMinutes int `json:"maxAgeMinutes"`
TargetSizeKiB int `json:"targetSizeKiB"`
Encoding string `json:"encoding"`
}
Chunks is the ingester's chunk shape.
type ChunksPatch ¶
ChunksPatch is PUT /api/logging's body: the whole chunks-and-retention section.
type Limits ¶
type Limits struct {
RetentionDays Range `json:"retentionDays"`
IdlePeriodMinutes Range `json:"idlePeriodMinutes"`
MaxAgeMinutes Range `json:"maxAgeMinutes"`
TargetSizeKiB Range `json:"targetSizeKiB"`
Encodings []string `json:"encodings"`
EarliestCutover string `json:"earliestCutover"`
}
Limits is GET /api/logging's `limits`, so the UI never hard-codes a range or a date.
type Period ¶
type Period struct {
From, Store, ObjectStore, Schema, IndexPrefix, IndexPeriod string
}
Period is one schema_config.configs entry. Compared with ==: any changed field is a changed period.
type Row ¶
Row is the stored settings. Previous is set only while an apply is in flight over an earlier row; InFlight with a nil Previous means the table was empty before, so undoing renders Defaults(). Previous.UpdatedAt is 0: no column keeps it.
type S3 ¶
type S3 struct {
Endpoint string `json:"endpoint"` // http(s)://host[:port]
Region string `json:"region"`
Bucket string `json:"bucket"`
PathStyle bool `json:"pathStyle"`
AccessKeyID string `json:"accessKeyId"`
Cutover string `json:"cutover"` // YYYY-MM-DD UTC: the S3 period's `from`
}
S3 is an S3-compatible store. The secret is not here: it is its own column and has no read path.
type Settings ¶
type Settings struct {
RetentionDays int `json:"retentionDays"`
Chunks Chunks `json:"chunks"`
Storage Storage `json:"storage"`
}
Settings is what an operator saved. Field order is the JSON order (rule 1).
func Defaults ¶
func Defaults() Settings
Defaults is slice 1's config: what an empty loki_config table means.
func Merge ¶
func Merge(row *Row, c *ChunksPatch, sp *StoragePatch, lead time.Duration) (Settings, string, error)
Merge lays the patches over the row (Defaults() when there is none) and resolves KeepSecret. The storage rules run against THIS row, so a second save that queued behind a first is refused once the first is stored. ErrOneWay and ErrFixed (409) come before *Error (400), and Validate runs last. addingS3 is filesystem → s3 only, so a rotation on a host past its cutover passes.
type Storage ¶
type Storage struct {
Type string `json:"type"` // StorageFilesystem | StorageS3
S3 *S3 `json:"s3"` // null on filesystem — a pointer without omitempty (rule 2)
}
Storage is filesystem, or filesystem then S3 from a cutover.
type StoragePatch ¶
StoragePatch is PUT /api/logging/storage's body. KeepSecret is an empty or masked secretAccessKey, resolved against the row Merge is given, never the one the request saw.