loki

package
v0.44.0 Latest Latest
Warning

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

Go to latest
Published: Oct 28, 2026 License: MIT, MIT Imports: 26 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 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

View Source
const (
	StorageFilesystem = "filesystem"
	StorageS3         = "s3"
)

The storage types.

View Source
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

View Source
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

func Changed(before *Row, after Settings, afterSecret string) []string

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

func CheckPeriods(loaded, next []Period, now time.Time, lead time.Duration, adding bool) error

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

func Credentials(keyID, secret string) string

Credentials is s3-credentials. Both values passed iniValue, so nothing needs escaping.

func CredentialsOwner

func CredentialsOwner(lokiUID int) error

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

func Dir(dataDir string) string

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

func EarliestCutover(t time.Time, lead time.Duration) string

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 Finish

func Finish(st *store.Store) error

Finish ends an apply: the save stays, the undo record goes.

func IsError

func IsError(err error) bool

IsError reports whether err is, or wraps, a *Error.

func Lead

func Lead(readyTimeout time.Duration) time.Duration

Lead is one restart plus a ready wait, with slack.

func Probe

func Probe(ctx context.Context, s S3, secret string) error

Probe PUTs then DELETEs an empty pstack-probe-<16 hex> object in s.Bucket. Every failure is a *Error (400).

func Render

func Render(s Settings) (string, error)

Render is config.yaml for s.

func Revert

func Revert(st *store.Store) error

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

func Save(st *store.Store, s Settings, secret string, previous *Row) error

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

func Validate(s Settings, secret string, addingS3 bool, lead time.Duration) error

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

func Writable(dir string) bool

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

func WriteFile(path, body string, mode os.FileMode, lokiUID int) error

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

type ChunksPatch struct {
	RetentionDays int
	Chunks        Chunks
}

ChunksPatch is PUT /api/logging's body: the whole chunks-and-retention section.

type Error

type Error struct{ Msg string }

Error is a refused value. The API maps it to 400.

func (*Error) Error

func (e *Error) Error() string

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.

func LimitsAt

func LimitsAt(t time.Time, lead time.Duration) Limits

LimitsAt is the limits at t. Encodings is a fresh non-nil slice (rule 3), so a caller cannot edit what Validate reads.

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.

func Periods

func Periods(configYAML string) ([]Period, error)

Periods reads schema_config.configs from a config.yaml text, in file order. `from` is quoted in every file pstack writes (templates/control/loki/config.yaml:22); a `from` that is not a string reads as "", which CheckPeriods treats as started.

type Range

type Range struct {
	Min int `json:"min"`
	Max int `json:"max"`
}

Range is an inclusive bound.

type Row

type Row struct {
	Settings  Settings
	Secret    string
	UpdatedAt int64
	InFlight  bool
	Previous  *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.

func Read

func Read(st *store.Store) (*Row, error)

Read is the stored row, or nil when the table is empty (slice 1's config exactly).

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

type StoragePatch struct {
	Storage    Storage
	Secret     string
	KeepSecret bool
}

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.

Jump to

Keyboard shortcuts

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