appdbhealth

package
v1.167.0 Latest Latest
Warning

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

Go to latest
Published: Nov 24, 2026 License: Apache-2.0 Imports: 6 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 appdbhealth reads an application database's health from its own statistics views (#2409): the server and its extensions, table and index sizes and their vacuum state, unused, duplicate and invalid indexes, transaction id age, connections against the limit, long-running and idle-in-transaction sessions, blocking lock chains, the cache hit ratio, replication lag, and the statements pg_stat_statements ranks first when the extension is installed.

It reads through the postgres toolkit's Query as the connection's own login, so the own-database refusal and the reset a released connection runs hold. A section the database refuses is reported under Errors with the toolkit's value-free summary; the rest of the report stands.

Statement and session text can repeat a literal. Report carries it for the administrator reading the report and nothing else: Summary, the form the history keeps and the alerts are built from, carries none of it.

Index

Constants

View Source
const (
	SectionServer      = "server"
	SectionExtensions  = "extensions"
	SectionConnections = "connections"
	SectionTables      = "tables"
	SectionIndexes     = "indexes"
	SectionSessions    = "sessions"
	SectionBlocking    = "blocking"
	SectionReplication = "replication"
	SectionStatements  = "statements"
)

The sections a report reads, as Errors names them.

View Source
const (
	ProblemTransactionIDAge  = "transaction_id_age"
	ProblemIdleInTransaction = "idle_in_transaction"
	ProblemConnections       = "connections"
	ProblemInvalidIndex      = "invalid_index"
	ProblemDeadTuples        = "dead_tuples"
	ProblemUnusedIndex       = "unused_index"
	ProblemDuplicateIndex    = "duplicate_index"
	ProblemBlocking          = "blocking"
	ProblemLongRunning       = "long_running"
)

The kinds of problem.

View Source
const (
	StatusHealthy  = "healthy"
	StatusWarning  = "warning"
	StatusCritical = "critical"
	LevelInfo      = "info"
)

The statuses a report is judged to, and the advice level.

View Source
const (
	FindingUnusedIndex    = "unused_index"
	FindingDuplicateIndex = "duplicate_index"
	FindingDeadTuples     = "dead_tuples"
)

The kinds of finding.

View Source
const DefaultLongRunning = time.Minute

DefaultLongRunning lists a statement running a minute or more.

View Source
const MinTuplesForRatio = 1000

MinTuplesForRatio is how many rows a table holds before its dead tuple ratio means anything: a table of ten rows with five deleted is not a design problem.

Variables

This section is empty.

Functions

This section is empty.

Types

type Blocked

type Blocked struct {
	PID       int64   `json:"pid"`
	User      string  `json:"user"`
	BlockedBy []int64 `json:"blocked_by"`
	Seconds   float64 `json:"seconds"`
}

Blocked is a backend waiting on a lock others hold.

type ConnectionUse

type ConnectionUse struct {
	Max     int64            `json:"max"`
	Total   int64            `json:"total"`
	ByState map[string]int64 `json:"by_state"`
}

ConnectionUse is the server's client connections against its limit.

type DuplicateIndexes

type DuplicateIndexes struct {
	Schema     string   `json:"schema"`
	Table      string   `json:"table"`
	Names      []string `json:"names"`
	Definition string   `json:"definition"`
}

DuplicateIndexes are indexes of one table over the same columns, operator classes, expressions and predicate.

type Extension

type Extension struct {
	Name    string `json:"name"`
	Version string `json:"version"`
}

Extension is one installed extension.

type Finding

type Finding struct {
	// Kind is unused_index, duplicate_index or dead_tuples.
	Kind   string `json:"kind"`
	Table  string `json:"table"`
	Index  string `json:"index,omitempty"`
	Detail string `json:"detail"`
}

Finding is one thing a build can act on in a schema its migrations made, as manage_schema describe reports it (#2409). It names objects and numbers, never statement text.

func Findings

func Findings(ctx context.Context, q Querier, connection, schema string, deadRatio float64) []Finding

Findings reads what describe reports about schema beside its objects: an index never scanned, indexes that index the same thing, and a table whose dead tuple ratio is past deadRatio. A read that fails reports nothing rather than failing describe.

type IndexRef

type IndexRef struct {
	Schema    string `json:"schema"`
	Table     string `json:"table"`
	Name      string `json:"name"`
	SizeBytes int64  `json:"size_bytes"`
	Scans     int64  `json:"scans"`
}

IndexRef is one index.

type IndexReport

type IndexReport struct {
	// Unused were never scanned since the statistics were reset and back no
	// constraint.
	Unused    []IndexRef         `json:"unused"`
	Duplicate []DuplicateIndexes `json:"duplicate"`
	// Invalid were left by a failed CREATE INDEX CONCURRENTLY or REINDEX.
	Invalid []IndexRef `json:"invalid"`
}

IndexReport lists the indexes worth an operator's look.

type Options

type Options struct {
	// LongRunning is how long a statement runs before its session is listed.
	LongRunning time.Duration
}

Options bound what a session must do to be listed.

type Problem added in v1.154.1

type Problem struct {
	// Kind is one of the Problem* kinds.
	Kind string `json:"kind"`
	// Level is critical or warning, from the alert thresholds, or info for
	// advice no alert is posted for.
	Level  string `json:"level"`
	Title  string `json:"title"`
	Detail string `json:"detail"`
	// Value is the number judged, and Threshold the level it crossed; 0 for
	// advice.
	Value     float64 `json:"value"`
	Threshold float64 `json:"threshold,omitempty"`
	Table     string  `json:"table,omitempty"`
	Index     string  `json:"index,omitempty"`
	PID       int64   `json:"pid,omitempty"`
}

Problem is one thing an application database's health card names (#2528): a condition past its alert threshold, or advice an operator may act on. It names objects, numbers and a session's process, never statement text; the card joins a session's text from Sessions by PID.

type Querier

type Querier interface {
	Query(ctx context.Context, s postgres.Statement) (*postgres.Result, error)
}

Querier runs one read-only statement on an application database: the postgres toolkit's Query, which runs it as the connection's own login in a READ ONLY transaction when the context carries no persona.

type QueryIDReader added in v1.154.2

type QueryIDReader interface {
	PlatformQueryIDs(ctx context.Context, connection string, extra []string) ([]string, error)
}

QueryIDReader reads the pg_stat_statements query id of every statement the platform runs on an application database, and of each of extra (#2536): the postgres toolkit's PlatformQueryIDs. A Querier that is one has the report leave the platform's statements out of the ranking by id.

type Replica

type Replica struct {
	Name       string  `json:"name"`
	State      string  `json:"state"`
	LagBytes   int64   `json:"lag_bytes"`
	LagSeconds float64 `json:"lag_seconds"`
}

Replica is one standby streaming from the server.

type Report

type Report struct {
	Connection  string    `json:"connection"`
	GeneratedAt time.Time `json:"generated_at"`
	Server      Server    `json:"server"`
	// Extensions are the extensions the database holds.
	Extensions  []Extension   `json:"extensions"`
	Connections ConnectionUse `json:"connections"`
	// Status and Findings are the report judged against the health settings,
	// by the rule the alerts are posted by (#2528); empty until judged.
	Status      string            `json:"status,omitempty"`
	Findings    []Problem         `json:"findings"`
	Tables      []TableStats      `json:"tables"`
	Indexes     IndexReport       `json:"indexes"`
	Sessions    []Session         `json:"sessions"`
	Blocking    []Blocked         `json:"blocking"`
	Replication []Replica         `json:"replication"`
	Statements  StatementsSection `json:"statements"`
	// Errors names each section the database did not answer, with the
	// toolkit's summary of why. Empty when the report is complete.
	Errors []SectionError `json:"errors"`
}

Report is one reading of an application database's health.

func Read

func Read(ctx context.Context, q Querier, connection string, o Options) *Report

Read reads connection's health now.

type SectionError

type SectionError struct {
	Section string `json:"section"`
	Error   string `json:"error"`
}

SectionError is a section the database did not answer.

type Server

type Server struct {
	Version   string `json:"version"`
	VersionNo int64  `json:"version_num"`
	Database  string `json:"database"`
	SizeBytes int64  `json:"size_bytes"`
	// TransactionIDAge is the age of the database's oldest unfrozen
	// transaction id; PostgreSQL stops accepting writes near 2^31.
	TransactionIDAge int64 `json:"transaction_id_age"`
	// CacheHitRatio is the share of block reads served from shared buffers.
	CacheHitRatio float64 `json:"cache_hit_ratio"`
	InRecovery    bool    `json:"in_recovery"`
	StatsReset    string  `json:"stats_reset,omitempty"`
}

Server is the server and the database the connection reaches.

type Session

type Session struct {
	PID         int64  `json:"pid"`
	User        string `json:"user"`
	Application string `json:"application"`
	State       string `json:"state"`
	// Seconds is how long the transaction (or, outside one, the statement)
	// has run; StateSeconds how long the session has been in its state.
	Seconds      float64 `json:"seconds"`
	StateSeconds float64 `json:"state_seconds"`
	Wait         string  `json:"wait,omitempty"`
	// Query is the session's current or last statement. It can repeat a
	// literal: it is shown to the administrator and kept nowhere.
	Query string `json:"query"`
}

Session is a backend running a statement past the long-running bound, or idle in a transaction.

type Statement

type Statement struct {
	QueryID string  `json:"query_id"`
	Calls   int64   `json:"calls"`
	TotalMS float64 `json:"total_ms"`
	MeanMS  float64 `json:"mean_ms"`
	// MaxMS is the slowest single call.
	MaxMS float64 `json:"max_ms"`
	Rows  int64   `json:"rows"`
	Query string  `json:"query"`
}

Statement is one normalized statement and its totals. Query is PostgreSQL's normalized text, which can keep a literal of a DDL or utility statement: it is shown to the administrator and kept nowhere.

type StatementsSection

type StatementsSection struct {
	Installed bool `json:"installed"`
	// Note says why there are no statements: the extension is not installed,
	// or installed and not loaded by shared_preload_libraries.
	Note string      `json:"note,omitempty"`
	Top  []Statement `json:"top"`
	// HiddenOtherRoles counts the statements of other roles whose text this
	// connection's role cannot read; they are left out of Top (#2528).
	HiddenOtherRoles int64 `json:"hidden_other_roles"`
}

StatementsSection is what pg_stat_statements ranks first by total time.

type Summary

type Summary struct {
	SizeBytes        int64   `json:"size_bytes"`
	TransactionIDAge int64   `json:"transaction_id_age"`
	Connections      int64   `json:"connections"`
	MaxConnections   int64   `json:"max_connections"`
	CacheHitRatio    float64 `json:"cache_hit_ratio"`
	// IdleInTransaction counts the sessions idle in a transaction, and
	// LongestIdleSeconds is how long the longest has been.
	IdleInTransaction  int     `json:"idle_in_transaction"`
	LongestIdleSeconds float64 `json:"longest_idle_seconds"`
	LongRunning        int     `json:"long_running"`
	Blocked            int     `json:"blocked"`
	UnusedIndexes      int     `json:"unused_indexes"`
	DuplicateIndexes   int     `json:"duplicate_indexes"`
	InvalidIndexes     int     `json:"invalid_indexes"`
	// MaxDeadRatio is the highest dead tuple ratio of a table holding at
	// least MinTuplesForRatio rows, and MaxDeadTable that table.
	MaxDeadRatio   float64 `json:"max_dead_ratio"`
	MaxDeadTable   string  `json:"max_dead_table,omitempty"`
	ReplicaLagByte int64   `json:"replica_lag_bytes"`
	Errors         int     `json:"errors"`
}

Summary is a report reduced to numbers: what the history keeps, the gauges show and the alerts are judged on. It carries no statement or session text, no role and no value.

func Summarize

func Summarize(r *Report) Summary

Summarize reduces r.

func (Summary) ConnectionShare

func (s Summary) ConnectionShare() float64

ConnectionShare is the share of max_connections in use, 0 when unknown.

type TableStats

type TableStats struct {
	Schema      string `json:"schema"`
	Name        string `json:"name"`
	SizeBytes   int64  `json:"size_bytes"`
	RowEstimate int64  `json:"row_estimate"`
	LiveTuples  int64  `json:"live_tuples"`
	DeadTuples  int64  `json:"dead_tuples"`
	// DeadRatio is dead tuples over live and dead together.
	DeadRatio       float64 `json:"dead_ratio"`
	SeqScans        int64   `json:"seq_scans"`
	IndexScans      int64   `json:"index_scans"`
	LastVacuum      string  `json:"last_vacuum,omitempty"`
	LastAutovacuum  string  `json:"last_autovacuum,omitempty"`
	LastAnalyze     string  `json:"last_analyze,omitempty"`
	LastAutoanalyze string  `json:"last_autoanalyze,omitempty"`
	// TransactionIDAge is the age of the table's oldest unfrozen
	// transaction id.
	TransactionIDAge int64 `json:"transaction_id_age"`
}

TableStats is one table's size and maintenance state.

Jump to

Keyboard shortcuts

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