repl

package
v0.5.14 Latest Latest
Warning

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

Go to latest
Published: Dec 9, 2025 License: Apache-2.0 Imports: 34 Imported by: 0

Documentation

Overview

Package repl provides an interactive REPL (Read-Eval-Print Loop) for PromQL queries.

Index

Constants

View Source
const PromQLSeparators = " (){},=!~\"\t\n+-*/^%"

PromQLSeparators defines PromQL-aware word separators used for word boundary detection.

Variables

View Source
var AdHocCommands = []AdHocCommand{
	{
		Command:     ".help",
		Description: "Show usage for ad-hoc commands",
		Usage:       ".help",
	},
	{
		Command:     ".ai",
		Description: "Use AI to propose PromQL queries for your loaded metrics",
		Usage:       ".ai <intent> | .ai ask <intent> | .ai show | .ai run <N> | .ai edit <N>",
		Examples: []string{
			".ai top 5 pods by http error rate over last hour",
			".ai cpu usage by mode per instance in 30m",
		},
	},
	{
		Command:     ".labels",
		Description: "Show labels and example values for a metric",
		Usage:       ".labels <metric>",
		Examples:    []string{".labels http_requests_total"},
	},
	{
		Command:     ".metrics",
		Description: "List metric names in the loaded dataset",
		Usage:       ".metrics",
	},
	{
		Command:     ".rules",
		Description: "Show or set active Prometheus rule files (dir, glob, or file)",
		Usage:       ".rules [<dir|glob|file>]",
		Examples: []string{
			".rules",
			".rules ./example-rules.yaml",
			".rules ./rules/",
			".rules 'rules/*.yaml'",
		},
	},
	{
		Command:     ".alerts",
		Description: "Show alerting rules from active rule files",
		Usage:       ".alerts",
	},
	{
		Command:     ".timestamps",
		Description: "Summarize timestamps for a metric",
		Usage:       ".timestamps <metric>",
		Examples:    []string{".timestamps http_requests_total"},
	},
	{
		Command:     ".stats",
		Description: "Show current store totals (metrics and samples)",
		Usage:       ".stats",
	},
	{
		Command:     ".load",
		Description: "Load metrics from a Prometheus text-format file",
		Usage:       ".load <file.prom> [timestamp={now|remove|<timespec>}] [regex='<series regex>']",
		Examples: []string{
			".load metrics.prom",
			".load metrics.prom timestamp=now",
			".load metrics.prom timestamp=2025-09-28T12:00:00Z",
			".load metrics.prom timestamp=remove",
			".load metrics.prom regex='^up\\{.*\\}$'",
		},
	},
	{
		Command:     ".source",
		Description: "Execute PromQL expressions from a file (one per line)",
		Usage:       ".source <file>",
		Examples: []string{
			".source queries.promql",
			".source /path/to/expressions.txt",
		},
	},
	{
		Command:     ".save",
		Description: "Save current store to a Prometheus text-format file",
		Usage:       ".save <file.prom> [timestamp={now|remove|<timespec>}] [regex='<series regex>']",
		Examples: []string{
			".save snapshot.prom",
			".save snapshot.prom timestamp=now",
			".save snapshot.prom timestamp=remove",
			".save snapshot.prom regex='http_requests_total\\{.*code=\"5..\".*\\}'",
		},
	},
	{
		Command:     ".seed",
		Description: "Backfill historical points for rate/increase",
		Usage:       ".seed <metric> [steps=N] [step=1m] OR .seed <metric> <steps> [<step>]",
		Examples: []string{
			".seed http_requests_total steps=10 step=30s",
			".seed http_requests_total 10 30s",
		},
	},
	{
		Command:     ".scrape",
		Description: "Fetch metrics from HTTP(S) endpoint",
		Usage:       ".scrape <URI> [metrics_regex] [count] [delay]",
		Examples: []string{
			".scrape http://localhost:9100/metrics",
			".scrape http://localhost:9100/metrics '^(up|process_.*)$'",
			".scrape http://localhost:9100/metrics 3 5s",
			".scrape http://localhost:9100/metrics 'http_.*' 5 2s",
		},
	},
	{
		Command:     ".prom_scrape",
		Description: "Query a remote Prometheus API and import the results",
		Usage:       ".prom_scrape <PROM_API_URI> 'query' [count] [delay]",
		Examples: []string{
			".prom_scrape http://localhost:9090/api/v1 'up'",
			".prom_scrape http://localhost:9090 'rate(http_requests_total[5m])' 3 10s",
		},
	},
	{
		Command:     ".prom_scrape_range",
		Description: "Query a remote Prometheus API over a time range and import the results",
		Usage:       ".prom_scrape_range <PROM_API_URI> 'query' <start> <end> <step> [count] [delay]",
		Examples: []string{
			".prom_scrape_range http://localhost:9090 'up' now-15m now 30s",
			".prom_scrape_range http://localhost:9090 'rate(http_requests_total[5m])' 2025-09-27T00:00:00Z 2025-09-27T00:30:00Z 15s",
		},
	},
	{
		Command:     ".drop",
		Description: "Drop all series matching a regex (by series signature name{labels})",
		Usage:       ".drop <series regex>",
		Examples: []string{
			".drop '^up\\{.*instance=\"db-.*\".*\\}$'",
			".drop 'http_requests_total\\{.*code=\"5..\".*\\}'",
		},
	},
	{
		Command:     ".keep",
		Description: "Keep only series matching a regex (drop the rest)",
		Usage:       ".keep <series regex>",
		Examples: []string{
			".keep '^up\\{.*job=\"node-exporter\".*\\}$'",
			".keep 'node_cpu_seconds_total\\{.*mode=\"idle\".*\\}'",
		},
	},
	{
		Command:     ".at",
		Description: "Evaluate a query at a specific time",
		Usage:       ".at <time> <query>",
		Examples:    []string{".at now-10m sum by (path) (rate(http_requests_total[5m]))"},
	},
	{
		Command:     ".pinat",
		Description: "Pin evaluation time for all future queries",
		Usage:       ".pinat [time|now|remove]",
		Examples: []string{
			".pinat",
			".pinat now",
			".pinat 2025-09-16T20:40:00Z",
			".pinat remove",
		},
	},
	{
		Command:     ".quit",
		Description: "Exit the REPL",
		Usage:       ".quit",
	},
	{
		Command:     ".history",
		Description: "Show REPL history (all or last N entries)",
		Usage:       ".history [N]",
		Examples: []string{
			".history",
			".history 20",
		},
	},
	{
		Command:     ".rename",
		Description: "Rename a metric (all series with that metric name)",
		Usage:       ".rename <old_metric> <new_metric>",
		Examples: []string{
			".rename http_requests_total http_requests",
			".rename old_metric_name new_metric_name",
		},
	},
}

AdHocCommands is the centralized list of all ad-hoc commands This serves as the source of truth for both the help text and autocompletion

Functions

func ApplyFilteredLoad

func ApplyFilteredLoad(storage *sstorage.SimpleStorage, tmp *sstorage.SimpleStorage, re *regexp.Regexp, tsMode string, tsFixed int64)

ApplyFilteredLoad loads samples from tmp storage into target storage, applying regex filter and timestamp overrides. This is used when loading metrics with a regex filter from CLI or REPL commands.

func ApplyTimestampOverride

func ApplyTimestampOverride(storage *sstorage.SimpleStorage, beforeCounts map[string]int, mode string, fixed int64)

ApplyTimestampOverride updates only newly loaded samples to the given mode

func BuildFilteredHistory

func BuildFilteredHistory(prefix string, history []string) []string

BuildFilteredHistory builds a newest-first filtered history slice based on the given prefix. - Preserves duplicates for 1:1 navigation - Returns entries from most recent to oldest

func EvaluateActiveRules

func EvaluateActiveRules(storage *sstorage.SimpleStorage) (added int, alerts int, err error)

EvaluateActiveRules evaluates currently active rule files (if any) over the provided storage. Uses pinnedEvalTime when set, else time.Now(). Prints a brief summary.

func EvaluateRulesOnStorage

func EvaluateRulesOnStorage(engine *promql.Engine, storage *sstorage.SimpleStorage, files []string, evalTime time.Time, printFn func(string)) (int, int, error)

EvaluateRulesOnStorage parses and evaluates Prometheus rules and applies recording results into storage. Alerts are printed via the provided printFn (or collected if nil). Returns number of recording samples added and the number of alert instances detected.

func ExecuteQueriesFromFile

func ExecuteQueriesFromFile(engine *promql.Engine, storage *sstorage.SimpleStorage, path string) error

ExecuteQueriesFromFile reads and executes PromQL expressions from a file This is exported for use by the CLI -f flag Queries are separated by blank lines, EOF is treated as query terminator Supports backslash continuation within queries

func ExecuteQueryLine

func ExecuteQueryLine(engine *promql.Engine, storage *sstorage.SimpleStorage, line string)

ExecuteQueryLine evaluates a single PromQL expression or command and prints the result. This is exported for use by adhoc commands like .source.

func GetActiveRules

func GetActiveRules() (string, []string)

GetActiveRules returns the current spec and files.

func GetAdHocCommandNames

func GetAdHocCommandNames() []string

GetAdHocCommandNames returns just the command names for autocompletion

func GetAlertExpr

func GetAlertExpr(alertName string) string

GetAlertExpr returns the expression for a given alert name, or empty string if not found.

func GetRecordingRuleNames

func GetRecordingRuleNames() []string

GetRecordingRuleNames returns configured recording rule metric names.

func ParseRegexArg

func ParseRegexArg(args []string) (*regexp.Regexp, bool)

ParseRegexArg finds regex=... and returns a compiled regexp (or nil if absent).

func ParseTimestampArg

func ParseTimestampArg(args []string) (string, int64, bool)

ParseTimestampArg scans args for timestamp=... and returns (mode, fixedMs, ok) mode is one of: keep (default), remove, set

func PrintResultJSON

func PrintResultJSON(result *promql.Result) error

PrintResultJSON renders the result as JSON similar to Prometheus API shapes.

func PrintUpstreamQueryResult

func PrintUpstreamQueryResult(result *promql.Result)

PrintUpstreamQueryResult formats and displays query results from the upstream PromQL engine. It handles different result types (Vector, Scalar, Matrix) with appropriate formatting.

func PrintUpstreamQueryResultToWriter

func PrintUpstreamQueryResultToWriter(result *promql.Result, w io.Writer)

func ResolveRuleSpec

func ResolveRuleSpec(spec string) ([]string, error)

ResolveRuleSpec returns the list of rule files from a directory or glob or single file. - If spec contains shell wildcards (*?[...]), it's treated as a glob. - If spec is a directory, all .yml/.yaml files (non-recursive) are used. - Otherwise, spec is treated as a single file path.

func RunInitCommands

func RunInitCommands(engine *promql.Engine, storage *sstorage.SimpleStorage, commands string, silent bool)

RunInitCommands executes semicolon-separated commands before interactive session or one-off query. When silent is true, outputs produced by these commands are suppressed.

func RunInteractiveQueriesDispatch

func RunInteractiveQueriesDispatch(engine *promql.Engine, storage *sstorage.SimpleStorage, silent bool, replBackend string)

RunInteractiveQueriesDispatch determines which REPL backend to use

func SetActiveRules

func SetActiveRules(files []string, spec string)

SetActiveRules sets the active rule files and spec used for auto-evaluation.

func SetEvalEngine

func SetEvalEngine(e *promql.Engine)

SetEvalEngine stores a reference to the promql.Engine for rule evaluations in the REPL.

Types

type AdHocCommand

type AdHocCommand struct {
	Command     string
	Description string
	Usage       string
	Examples    []string
}

AdHocCommand represents an ad-hoc command with its description

func GetAdHocCommandByName

func GetAdHocCommandByName(name string) *AdHocCommand

GetAdHocCommandByName returns a command by its name

type AlertRule

type AlertRule struct {
	Name string
	Expr string
}

AlertRule represents an alerting rule with its name and expression

func GetAlertingRules

func GetAlertingRules() []AlertRule

GetAlertingRules returns configured alerting rules with their names and expressions.

type AutoCompleteOptions

type AutoCompleteOptions struct {
	AutoBrace       bool // when completing a metric name uniquely, append '{'
	LabelNameEquals bool // when completing a label name, append '="'
	AutoCloseQuote  bool // when completing a label value, append closing '"'
}

AutoCompleteOptions controls optional completion behaviors, configurable via env vars.

type PromQLContext

type PromQLContext struct {
	Type         string // "function_arg", "label_name", "label_value", "range_duration", "after_operator", etc.
	MetricName   string
	LabelName    string
	FunctionName string
}

PromQLContext represents the current context in a PromQL expression

type PrometheusAutoCompleter

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

PrometheusAutoCompleter provides dynamic auto-completion for PromQL queries based on the loaded metrics data, similar to the Prometheus UI experience.

func NewPrometheusAutoCompleter

func NewPrometheusAutoCompleter(storage *sstorage.SimpleStorage) *PrometheusAutoCompleter

NewPrometheusAutoCompleter creates a new auto-completer with access to metric data.

func (*PrometheusAutoCompleter) Do

func (pac *PrometheusAutoCompleter) Do(line []rune, pos int) (newLine [][]rune, length int)

Do implements the readline.AutoCompleter interface to provide dynamic completions.

type QueryContext

type QueryContext struct {
	Type       string // "metric_name", "label_name", "label_value", "function", "operator"
	MetricName string // The metric name if we're inside label selectors
	LabelName  string // The label name if we're typing a label value
}

QueryContext represents the context of the current query position.

Jump to

Keyboard shortcuts

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