Documentation
¶
Overview ¶
Package prometheus provides Prometheus client functionality with advanced features including caching, circuit breaking, connection pooling, and batch query processing. It supports authentication, TLS configuration, retry mechanisms, and comprehensive error handling for reliable metric collection from Prometheus servers.
Package prometheus provides streaming capabilities for large Prometheus query results.
IMPORTANT: Prometheus API does not natively support streaming responses. This implementation provides CLIENT-SIDE streaming by: 1. Fetching complete responses from Prometheus 2. Post-processing large datasets into manageable chunks 3. Streaming chunks to consumer applications for memory efficiency
This is particularly useful for: - Large range queries with many data points - Memory-constrained environments - Progressive data processing without blocking on large datasets
Index ¶
- Variables
- func BuildQueryString(template string, params map[string]interface{}) string
- func TestTemplateOutput()
- type Alert
- type AlertState
- type BatchQueryConfig
- type CacheEfficiencyStats
- type CacheEntry
- type CacheKeyContext
- type CacheKeyGenerator
- func (g *CacheKeyGenerator) AnalyzeQueryPatterns(queries []string) CacheEfficiencyStats
- func (g *CacheKeyGenerator) BatchGenerateKeys(queries map[string]string, queryTime *time.Time) map[string]string
- func (g *CacheKeyGenerator) GenerateInstantQueryKey(query string, queryTime *time.Time) string
- func (g *CacheKeyGenerator) GenerateKey(ctx CacheKeyContext) string
- func (g *CacheKeyGenerator) GenerateLabelsQueryKey() string
- func (g *CacheKeyGenerator) GenerateRangeQueryKey(query string, start, end time.Time, step time.Duration) string
- func (g *CacheKeyGenerator) GenerateSeriesQueryKey(matches []string, start, end time.Time) string
- type CacheStats
- type CachedClient
- func (cc *CachedClient) BatchQuery(ctx context.Context, queries map[string]string, ts time.Time) (map[string]*QueryResult, error)
- func (cc *CachedClient) CacheStats() CacheStats
- func (cc *CachedClient) ClearCache()
- func (cc *CachedClient) InvalidatePattern(pattern string)
- func (cc *CachedClient) Labels(ctx context.Context) ([]string, error)
- func (cc *CachedClient) Query(ctx context.Context, query string, time time.Time) (*QueryResult, error)
- func (cc *CachedClient) QueryRange(ctx context.Context, query string, start, end time.Time, step time.Duration) (*QueryResult, error)
- func (cc *CachedClient) Series(ctx context.Context, matches []string, start, end time.Time) ([]map[string]string, error)
- func (cc *CachedClient) Stop()
- func (cc *CachedClient) TestConnection(ctx context.Context) error
- type CircuitBreaker
- type CircuitBreakerClient
- func (cb *CircuitBreakerClient) BatchQuery(ctx context.Context, queries map[string]string, queryTime time.Time) (map[string]*QueryResult, error)
- func (cb *CircuitBreakerClient) BatchQueryWithConfig(ctx context.Context, queries map[string]string, queryTime time.Time, ...) (map[string]*QueryResult, error)
- func (cb *CircuitBreakerClient) GetCounts() Counts
- func (cb *CircuitBreakerClient) GetState() CircuitState
- func (cb *CircuitBreakerClient) Labels(ctx context.Context) ([]string, error)
- func (cb *CircuitBreakerClient) Query(ctx context.Context, query string, time time.Time) (*QueryResult, error)
- func (cb *CircuitBreakerClient) QueryRange(ctx context.Context, query string, start, end time.Time, step time.Duration) (*QueryResult, error)
- func (cb *CircuitBreakerClient) Series(ctx context.Context, matches []string, start, end time.Time) ([]map[string]string, error)
- func (cb *CircuitBreakerClient) TestConnection(ctx context.Context) error
- type CircuitBreakerConfig
- type CircuitState
- type Client
- func (c *Client) BatchQuery(ctx context.Context, queries map[string]string, queryTime time.Time) (map[string]*QueryResult, error)
- func (c *Client) BatchQueryWithConfig(ctx context.Context, queries map[string]string, queryTime time.Time, ...) (map[string]*QueryResult, error)
- func (c *Client) Close()
- func (c *Client) Labels(ctx context.Context) ([]string, error)
- func (c *Client) Query(ctx context.Context, query string, time time.Time) (*QueryResult, error)
- func (c *Client) QueryRange(ctx context.Context, query string, start, end time.Time, step time.Duration) (*QueryResult, error)
- func (c *Client) QueryRangeStream(ctx context.Context, query string, start, end time.Time, step time.Duration) (*QueryResultStream, error)
- func (c *Client) QueryRangeStreamWithConfig(ctx context.Context, query string, start, end time.Time, step time.Duration, ...) (*QueryResultStream, error)
- func (c *Client) Series(ctx context.Context, matches []string, start, end time.Time) ([]map[string]string, error)
- func (c *Client) TestConnection(ctx context.Context) error
- type ClientConfig
- type ClientInterface
- type Counts
- type Matrix
- type MatrixSeries
- type Metadata
- type MetricCache
- func (mc *MetricCache) Clear()
- func (mc *MetricCache) Delete(query string)
- func (mc *MetricCache) Get(query string) (*QueryResult, bool)
- func (mc *MetricCache) GetInstantQuery(query string, queryTime *time.Time) (*QueryResult, bool)
- func (mc *MetricCache) GetRangeQuery(query string, start, end time.Time, step time.Duration) (*QueryResult, bool)
- func (mc *MetricCache) GetSeries(matches []string, start, end time.Time) ([]map[string]string, bool)
- func (mc *MetricCache) GetWithKey(cacheKey, _ string) (*QueryResult, bool)
- func (mc *MetricCache) Set(query string, result *QueryResult, ttl time.Duration)
- func (mc *MetricCache) SetInstantQuery(query string, queryTime *time.Time, result *QueryResult, ttl time.Duration)
- func (mc *MetricCache) SetRangeQuery(query string, start, end time.Time, step time.Duration, result *QueryResult, ...)
- func (mc *MetricCache) SetWithKey(cacheKey, originalQuery string, result *QueryResult, ttl time.Duration)
- func (mc *MetricCache) Stats() CacheStats
- func (mc *MetricCache) Stop()
- type PrometheusClientInterface
- type QueryBuilder
- func (qb *QueryBuilder) BuildQuery(queryName string, params map[string]interface{}) (string, error)
- func (qb *QueryBuilder) GetClusterQueries() (map[string]string, error)
- func (qb *QueryBuilder) GetJobQueries(jobID string) (map[string]string, error)
- func (qb *QueryBuilder) GetNodeQueries(nodeName, labelName string) (map[string]string, error)
- type QueryResult
- type QueryResultStream
- type QueryType
- type ResultData
- type ResultType
- type SamplePair
- type StreamingConfig
- type StreamingDataChunk
- type StreamingResultData
- type Target
- type Vector
- type VectorSample
Constants ¶
This section is empty.
Variables ¶
var QueryTemplates = map[string]string{
"node_cpu_usage": `100 - (avg by ({{.NodeLabel}}) (rate(node_cpu_seconds_total` + `{mode="idle", {{.NodeLabel}}=~"{{.NodePattern}}"}[{{.Range}}])) * 100)`,
"node_cpu_cores": `count by ({{.NodeLabel}}) (node_cpu_seconds_total` + `{mode="idle", {{.NodeLabel}}=~"{{.NodePattern}}"})`,
"node_memory_usage": `(1 - (node_memory_MemAvailable_bytes` + `{{{.NodeLabel}}=~"{{.NodePattern}}"} / node_memory_MemTotal_bytes` + `{{{.NodeLabel}}=~"{{.NodePattern}}"})) * 100`,
"node_memory_total": `node_memory_MemTotal_bytes` + `{{{.NodeLabel}}=~"{{.NodePattern}}"}`,
"node_memory_available": `node_memory_MemAvailable_bytes` + `{{{.NodeLabel}}=~"{{.NodePattern}}"}`,
"node_load_1m": `node_load1` + `{{{.NodeLabel}}=~"{{.NodePattern}}"}`,
"node_load_5m": `node_load5` + `{{{.NodeLabel}}=~"{{.NodePattern}}"}`,
"node_load_15m": `node_load15` + `{{{.NodeLabel}}=~"{{.NodePattern}}"}`,
"node_disk_read_bytes": `rate(node_disk_read_bytes_total` + `{{{.NodeLabel}}=~"{{.NodePattern}}", device!~"dm-.*"}[{{.Range}}])`,
"node_disk_write_bytes": `rate(node_disk_write_bytes_total` + `{{{.NodeLabel}}=~"{{.NodePattern}}", device!~"dm-.*"}[{{.Range}}])`,
"node_network_receive_bytes": `rate(node_network_receive_bytes_total` + `{{{.NodeLabel}}=~"{{.NodePattern}}", device!~"lo"}[{{.Range}}])`,
"node_network_transmit_bytes": `rate(node_network_transmit_bytes_total` + `{{{.NodeLabel}}=~"{{.NodePattern}}", device!~"lo"}[{{.Range}}])`,
"node_filesystem_usage": `(1 - (node_filesystem_avail_bytes` + `{{{.NodeLabel}}=~"{{.NodePattern}}", fstype!~"tmpfs|fuse.lxcfs"} / node_filesystem_size_bytes` + `{{{.NodeLabel}}=~"{{.NodePattern}}", fstype!~"tmpfs|fuse.lxcfs"})) * 100`,
"job_cpu_usage": `rate(container_cpu_usage_seconds_total` + `{cpu="total",id=~"/system.slice/.*slurmstepd.scope/job_{{.JobID}}"}[{{.Range}}]) * 100`,
"job_cpu_throttled": `rate(container_cpu_throttled_seconds_total` + `{id=~"/system.slice/.*slurmstepd.scope/job_{{.JobID}}"}[{{.Range}}])`,
"job_memory_usage": `container_memory_usage_bytes` + `{id=~"/system.slice/.*slurmstepd.scope/job_{{.JobID}}"}`,
"job_memory_limit": `container_spec_memory_limit_bytes` + `{id=~"/system.slice/.*slurmstepd.scope/job_{{.JobID}}"}`,
"job_memory_cache": `container_memory_cache` + `{id=~"/system.slice/.*slurmstepd.scope/job_{{.JobID}}"}`,
"job_memory_rss": `container_memory_rss` + `{id=~"/system.slice/.*slurmstepd.scope/job_{{.JobID}}"}`,
"cluster_cpu_usage": `100 - (avg(rate(node_cpu_seconds_total` + `{mode="idle"}[{{.Range}}])) * 100)`,
"cluster_memory_usage": `(1 - (sum(node_memory_MemAvailable_bytes) / sum(node_memory_MemTotal_bytes))) * 100`,
"cluster_nodes_up": `count(up` + `{job="node-exporter"} == 1)`,
"cluster_nodes_down": `count(up` + `{job="node-exporter"} == 0)`,
}
QueryTemplates contains standard PromQL query templates Using a function to build the string to avoid template parsing issues
Functions ¶
func BuildQueryString ¶
BuildQueryString builds the actual query string by replacing template variables This avoids the template parsing issues with curly braces
func TestTemplateOutput ¶
func TestTemplateOutput()
TestTemplateOutput is a helper function for testing query template output.
Types ¶
type Alert ¶
type Alert struct {
Labels map[string]string `json:"labels"`
Annotations map[string]string `json:"annotations"`
State string `json:"state"`
ActiveAt time.Time `json:"activeAt"`
Value float64 `json:"value"`
}
Alert represents a Prometheus alert
type AlertState ¶
type AlertState string
AlertState represents the state of an alert
const ( // AlertStatePending is the pending alert state. AlertStatePending AlertState = "pending" // AlertStateFiring is the firing alert state. AlertStateFiring AlertState = "firing" // AlertStateInactive is the inactive alert state. AlertStateInactive AlertState = "inactive" )
type BatchQueryConfig ¶
type BatchQueryConfig struct {
MaxConcurrency int // Maximum concurrent queries (default: 10)
BatchTimeout time.Duration // Timeout for entire batch (default: 30s)
RetryAttempts int // Number of retry attempts for failed queries (default: 3)
}
BatchQueryConfig holds configuration for batch query execution
func DefaultBatchQueryConfig ¶
func DefaultBatchQueryConfig() BatchQueryConfig
DefaultBatchQueryConfig returns default batch query configuration
type CacheEfficiencyStats ¶
type CacheEfficiencyStats struct {
TotalQueries int
UniqueNormalized int
PotentialHitRate float64
AverageKeyLength float64
LongQueryCount int // Queries that will be hashed
}
CacheEfficiencyStats holds statistics about cache effectiveness for query patterns.
func (CacheEfficiencyStats) String ¶
func (s CacheEfficiencyStats) String() string
String returns a string representation of cache efficiency stats
type CacheEntry ¶
CacheEntry represents a cached metric value
func (*CacheEntry) IsExpired ¶
func (ce *CacheEntry) IsExpired() bool
IsExpired checks if the cache entry has expired
type CacheKeyContext ¶
type CacheKeyContext struct {
Query string
StartTime *time.Time
EndTime *time.Time
Step *time.Duration
QueryType QueryType
}
CacheKeyContext holds context information for cache key generation
type CacheKeyGenerator ¶
type CacheKeyGenerator struct {
// contains filtered or unexported fields
}
CacheKeyGenerator provides optimized cache key generation for Prometheus queries
func NewCacheKeyGenerator ¶
func NewCacheKeyGenerator() *CacheKeyGenerator
NewCacheKeyGenerator creates a new cache key generator with compiled patterns
func (*CacheKeyGenerator) AnalyzeQueryPatterns ¶
func (g *CacheKeyGenerator) AnalyzeQueryPatterns(queries []string) CacheEfficiencyStats
AnalyzeQueryPatterns analyzes a set of queries to estimate cache efficiency
func (*CacheKeyGenerator) BatchGenerateKeys ¶
func (g *CacheKeyGenerator) BatchGenerateKeys(queries map[string]string, queryTime *time.Time) map[string]string
BatchGenerateKeys generates cache keys for multiple queries efficiently
func (*CacheKeyGenerator) GenerateInstantQueryKey ¶
func (g *CacheKeyGenerator) GenerateInstantQueryKey(query string, queryTime *time.Time) string
GenerateInstantQueryKey generates a cache key for instant queries
func (*CacheKeyGenerator) GenerateKey ¶
func (g *CacheKeyGenerator) GenerateKey(ctx CacheKeyContext) string
GenerateKey creates an optimized cache key for a Prometheus query
func (*CacheKeyGenerator) GenerateLabelsQueryKey ¶
func (g *CacheKeyGenerator) GenerateLabelsQueryKey() string
GenerateLabelsQueryKey generates a cache key for labels queries
func (*CacheKeyGenerator) GenerateRangeQueryKey ¶
func (g *CacheKeyGenerator) GenerateRangeQueryKey(query string, start, end time.Time, step time.Duration) string
GenerateRangeQueryKey generates a cache key for range queries
func (*CacheKeyGenerator) GenerateSeriesQueryKey ¶
func (g *CacheKeyGenerator) GenerateSeriesQueryKey(matches []string, start, end time.Time) string
GenerateSeriesQueryKey generates a cache key for series queries
type CacheStats ¶
type CacheStats struct {
Entries int
Hits int64
Misses int64
Evictions int64
HitRate float64
MaxSize int
}
CacheStats contains cache statistics
type CachedClient ¶
type CachedClient struct {
// contains filtered or unexported fields
}
CachedClient wraps a Prometheus client with caching
func NewCachedClient ¶
func NewCachedClient(client *Client, cacheTTL time.Duration, cacheSize int) *CachedClient
NewCachedClient creates a new cached Prometheus client
func NewCachedClientWithInterface ¶
func NewCachedClientWithInterface(client PrometheusClientInterface, cacheTTL time.Duration, cacheSize int) *CachedClient
NewCachedClientWithInterface creates a new cached client using the interface
func (*CachedClient) BatchQuery ¶
func (cc *CachedClient) BatchQuery(ctx context.Context, queries map[string]string, ts time.Time) (map[string]*QueryResult, error)
BatchQuery executes multiple queries with caching
func (*CachedClient) CacheStats ¶
func (cc *CachedClient) CacheStats() CacheStats
CacheStats returns cache statistics
func (*CachedClient) InvalidatePattern ¶
func (cc *CachedClient) InvalidatePattern(pattern string)
InvalidatePattern removes cache entries matching a pattern
func (*CachedClient) Labels ¶
func (cc *CachedClient) Labels(ctx context.Context) ([]string, error)
Labels executes a labels query with caching
func (*CachedClient) Query ¶
func (cc *CachedClient) Query(ctx context.Context, query string, time time.Time) (*QueryResult, error)
Query executes a query with caching
func (*CachedClient) QueryRange ¶
func (cc *CachedClient) QueryRange(ctx context.Context, query string, start, end time.Time, step time.Duration) (*QueryResult, error)
QueryRange executes a range query with caching
func (*CachedClient) Series ¶
func (cc *CachedClient) Series(ctx context.Context, matches []string, start, end time.Time) ([]map[string]string, error)
Series executes a series query with caching
func (*CachedClient) Stop ¶
func (cc *CachedClient) Stop()
Stop gracefully shuts down the cached client
func (*CachedClient) TestConnection ¶
func (cc *CachedClient) TestConnection(ctx context.Context) error
TestConnection tests the connection to Prometheus
type CircuitBreaker ¶
type CircuitBreaker struct {
// contains filtered or unexported fields
}
CircuitBreaker prevents cascading failures by temporarily stopping calls to a failing service
func NewCircuitBreaker ¶
func NewCircuitBreaker(name string, config CircuitBreakerConfig) *CircuitBreaker
NewCircuitBreaker creates a new circuit breaker
func (*CircuitBreaker) Counts ¶
func (cb *CircuitBreaker) Counts() Counts
Counts returns a copy of the current counts
func (*CircuitBreaker) Execute ¶
func (cb *CircuitBreaker) Execute(_ context.Context, req func() (interface{}, error)) (interface{}, error)
Execute wraps a function call with circuit breaker logic
func (*CircuitBreaker) State ¶
func (cb *CircuitBreaker) State() CircuitState
State returns the current state of the circuit breaker
type CircuitBreakerClient ¶
type CircuitBreakerClient struct {
// contains filtered or unexported fields
}
CircuitBreakerClient wraps a Prometheus client with circuit breaker functionality
func NewCircuitBreakerClient ¶
func NewCircuitBreakerClient(client PrometheusClientInterface, config CircuitBreakerConfig) *CircuitBreakerClient
NewCircuitBreakerClient creates a new circuit breaker client
func (*CircuitBreakerClient) BatchQuery ¶
func (cb *CircuitBreakerClient) BatchQuery(ctx context.Context, queries map[string]string, queryTime time.Time) (map[string]*QueryResult, error)
BatchQuery executes multiple queries with circuit breaker protection
func (*CircuitBreakerClient) BatchQueryWithConfig ¶
func (cb *CircuitBreakerClient) BatchQueryWithConfig(ctx context.Context, queries map[string]string, queryTime time.Time, config BatchQueryConfig) (map[string]*QueryResult, error)
BatchQueryWithConfig executes multiple queries with custom configuration and circuit breaker protection
func (*CircuitBreakerClient) GetCounts ¶
func (cb *CircuitBreakerClient) GetCounts() Counts
GetCounts returns the current circuit breaker counts
func (*CircuitBreakerClient) GetState ¶
func (cb *CircuitBreakerClient) GetState() CircuitState
GetState returns the current circuit breaker state
func (*CircuitBreakerClient) Labels ¶
func (cb *CircuitBreakerClient) Labels(ctx context.Context) ([]string, error)
Labels returns the list of label names with circuit breaker protection
func (*CircuitBreakerClient) Query ¶
func (cb *CircuitBreakerClient) Query(ctx context.Context, query string, time time.Time) (*QueryResult, error)
Query executes a Prometheus query with circuit breaker protection
func (*CircuitBreakerClient) QueryRange ¶
func (cb *CircuitBreakerClient) QueryRange(ctx context.Context, query string, start, end time.Time, step time.Duration) (*QueryResult, error)
QueryRange executes a Prometheus range query with circuit breaker protection
func (*CircuitBreakerClient) Series ¶
func (cb *CircuitBreakerClient) Series(ctx context.Context, matches []string, start, end time.Time) ([]map[string]string, error)
Series returns the list of time series that match a label set with circuit breaker protection
func (*CircuitBreakerClient) TestConnection ¶
func (cb *CircuitBreakerClient) TestConnection(ctx context.Context) error
TestConnection tests the connection to Prometheus with circuit breaker protection
type CircuitBreakerConfig ¶
type CircuitBreakerConfig struct {
// MaxRequests is the maximum number of requests allowed to pass through when the CircuitBreaker is half-open
MaxRequests uint32
// Interval is the cyclic period of the closed state for the CircuitBreaker to clear the internal Counts
Interval time.Duration
// Timeout is the period of the open state, after which the state of the CircuitBreaker becomes half-open
Timeout time.Duration
// ReadyToTrip returns true when the CircuitBreaker should trip and become open
ReadyToTrip func(counts Counts) bool
// OnStateChange is called whenever the state of the CircuitBreaker changes
OnStateChange func(name string, from CircuitState, to CircuitState)
}
CircuitBreakerConfig contains configuration for the circuit breaker
func DefaultCircuitBreakerConfig ¶
func DefaultCircuitBreakerConfig() CircuitBreakerConfig
DefaultCircuitBreakerConfig returns a default circuit breaker configuration
type CircuitState ¶
type CircuitState int
CircuitState represents the state of the circuit breaker
const ( // CircuitClosed - Circuit is closed, requests pass through CircuitClosed CircuitState = iota // CircuitOpen - Circuit is open, requests fail fast CircuitOpen // CircuitHalfOpen - Circuit is half-open, testing if service recovered CircuitHalfOpen )
func (CircuitState) String ¶
func (s CircuitState) String() string
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client represents a Prometheus API client
func NewClient ¶
func NewClient(config *ClientConfig) (*Client, error)
NewClient creates a new Prometheus client
func (*Client) BatchQuery ¶
func (c *Client) BatchQuery(ctx context.Context, queries map[string]string, queryTime time.Time) (map[string]*QueryResult, error)
BatchQuery executes multiple queries with configurable concurrency and retry logic
func (*Client) BatchQueryWithConfig ¶
func (c *Client) BatchQueryWithConfig(ctx context.Context, queries map[string]string, queryTime time.Time, config BatchQueryConfig) (map[string]*QueryResult, error)
BatchQueryWithConfig executes multiple queries with custom configuration
func (*Client) QueryRange ¶
func (c *Client) QueryRange(ctx context.Context, query string, start, end time.Time, step time.Duration) (*QueryResult, error)
QueryRange executes a Prometheus range query
func (*Client) QueryRangeStream ¶
func (c *Client) QueryRangeStream(ctx context.Context, query string, start, end time.Time, step time.Duration) (*QueryResultStream, error)
QueryRangeStream executes a Prometheus range query and returns results as a client-side stream Note: Prometheus API does not natively support streaming. This method fetches the complete response and then streams it in chunks for better memory management and progressive processing.
func (*Client) QueryRangeStreamWithConfig ¶
func (c *Client) QueryRangeStreamWithConfig(ctx context.Context, query string, start, end time.Time, step time.Duration, config StreamingConfig) (*QueryResultStream, error)
QueryRangeStreamWithConfig executes a range query with client-side streaming and custom configuration This provides memory-efficient processing of large datasets by chunking the response.
type ClientConfig ¶
type ClientConfig struct {
Endpoint string
Username string
Password string
BearerToken string
Timeout time.Duration
TLSSkipVerify bool
TLSCertFile string
TLSKeyFile string
TLSCAFile string
}
ClientConfig contains configuration for the Prometheus client
type ClientInterface ¶ added in v0.3.0
type ClientInterface interface {
TestConnection(ctx context.Context) error
Query(ctx context.Context, query string, time time.Time) (*QueryResult, error)
QueryRange(ctx context.Context, query string, start, end time.Time, step time.Duration) (*QueryResult, error)
BatchQuery(ctx context.Context, queries map[string]string, time time.Time) (map[string]*QueryResult, error)
Series(ctx context.Context, matches []string, start, end time.Time) ([]map[string]string, error)
Labels(ctx context.Context) ([]string, error)
}
ClientInterface defines the interface for Prometheus clients
type Counts ¶
type Counts struct {
Requests uint32
TotalSuccesses uint32
TotalFailures uint32
ConsecutiveSuccesses uint32
ConsecutiveFailures uint32
}
Counts holds the numbers of requests and their successes/failures
type MatrixSeries ¶
type MatrixSeries struct {
Metric map[string]string `json:"metric"`
Values []SamplePair `json:"values"`
}
MatrixSeries represents a time series in a matrix result
type Metadata ¶
type Metadata struct {
Type string `json:"type"`
Help string `json:"help"`
Unit string `json:"unit"`
}
Metadata represents metric metadata
type MetricCache ¶
type MetricCache struct {
// contains filtered or unexported fields
}
MetricCache provides caching for Prometheus query results
func NewMetricCache ¶
func NewMetricCache(defaultTTL time.Duration, maxSize int) *MetricCache
NewMetricCache creates a new metric cache
func (*MetricCache) Delete ¶
func (mc *MetricCache) Delete(query string)
Delete removes a specific query from the cache
func (*MetricCache) Get ¶
func (mc *MetricCache) Get(query string) (*QueryResult, bool)
Get retrieves a cached query result using raw query string (legacy method)
func (*MetricCache) GetInstantQuery ¶
func (mc *MetricCache) GetInstantQuery(query string, queryTime *time.Time) (*QueryResult, bool)
GetInstantQuery retrieves a cached instant query result with optimized key
func (*MetricCache) GetRangeQuery ¶
func (mc *MetricCache) GetRangeQuery(query string, start, end time.Time, step time.Duration) (*QueryResult, bool)
GetRangeQuery retrieves a cached range query result with optimized key
func (*MetricCache) GetSeries ¶
func (mc *MetricCache) GetSeries(matches []string, start, end time.Time) ([]map[string]string, bool)
GetSeries retrieves a cached series query result with optimized key
func (*MetricCache) GetWithKey ¶
func (mc *MetricCache) GetWithKey(cacheKey, _ string) (*QueryResult, bool)
GetWithKey retrieves a cached query result using a specific cache key
func (*MetricCache) Set ¶
func (mc *MetricCache) Set(query string, result *QueryResult, ttl time.Duration)
Set stores a query result in the cache using raw query string (legacy method)
func (*MetricCache) SetInstantQuery ¶
func (mc *MetricCache) SetInstantQuery(query string, queryTime *time.Time, result *QueryResult, ttl time.Duration)
SetInstantQuery stores an instant query result with optimized key
func (*MetricCache) SetRangeQuery ¶
func (mc *MetricCache) SetRangeQuery(query string, start, end time.Time, step time.Duration, result *QueryResult, ttl time.Duration)
SetRangeQuery stores a range query result with optimized key
func (*MetricCache) SetWithKey ¶
func (mc *MetricCache) SetWithKey(cacheKey, originalQuery string, result *QueryResult, ttl time.Duration)
SetWithKey stores a query result in the cache using a specific cache key
func (*MetricCache) Stats ¶
func (mc *MetricCache) Stats() CacheStats
Stats returns cache statistics
func (*MetricCache) Stop ¶
func (mc *MetricCache) Stop()
Stop gracefully shuts down the cache cleanup goroutine
type PrometheusClientInterface ¶
type PrometheusClientInterface = ClientInterface
type QueryBuilder ¶
type QueryBuilder struct {
}
QueryBuilder helps build PromQL queries with parameters
func NewQueryBuilder ¶
func NewQueryBuilder() (*QueryBuilder, error)
NewQueryBuilder creates a new query builder
func (*QueryBuilder) BuildQuery ¶
func (qb *QueryBuilder) BuildQuery(queryName string, params map[string]interface{}) (string, error)
BuildQuery builds a query from a template with parameters
func (*QueryBuilder) GetClusterQueries ¶
func (qb *QueryBuilder) GetClusterQueries() (map[string]string, error)
GetClusterQueries returns cluster-level aggregation queries
func (*QueryBuilder) GetJobQueries ¶
func (qb *QueryBuilder) GetJobQueries(jobID string) (map[string]string, error)
GetJobQueries returns all job-level queries for a specific job
func (*QueryBuilder) GetNodeQueries ¶
func (qb *QueryBuilder) GetNodeQueries(nodeName, labelName string) (map[string]string, error)
GetNodeQueries returns all node-level queries for a specific node
type QueryResult ¶
type QueryResult struct {
Status string `json:"status"`
Data ResultData `json:"data"`
Error string `json:"error,omitempty"`
ErrorType string `json:"errorType,omitempty"`
Warnings []string `json:"warnings,omitempty"`
}
QueryResult represents a Prometheus query result
func CollectStreamingResults ¶
func CollectStreamingResults(ctx context.Context, streamResult *QueryResultStream) (*QueryResult, error)
CollectStreamingResults collects all chunks from a streaming result into a standard QueryResult
func (*QueryResult) GetMatrix ¶
func (r *QueryResult) GetMatrix() (Matrix, error)
GetMatrix extracts matrix data from the result
func (*QueryResult) GetScalar ¶
func (r *QueryResult) GetScalar() (float64, time.Time, error)
GetScalar extracts scalar data from the result
func (*QueryResult) GetString ¶
func (r *QueryResult) GetString() (string, time.Time, error)
GetString extracts string data from the result
func (*QueryResult) GetVector ¶
func (r *QueryResult) GetVector() (Vector, error)
GetVector extracts vector data from the result
type QueryResultStream ¶
type QueryResultStream struct {
Status string `json:"status"`
Data StreamingResultData `json:"data"`
Error string `json:"error,omitempty"`
ErrorType string `json:"errorType,omitempty"`
Warnings []string `json:"warnings,omitempty"`
Stream <-chan StreamingDataChunk `json:"-"`
}
QueryResultStream represents a streaming query result
type QueryType ¶
type QueryType int
QueryType represents the type of Prometheus query
const ( // QueryTypeInstant is the query type for instant queries. QueryTypeInstant QueryType = iota // QueryTypeRange is the query type for range queries. QueryTypeRange // QueryTypeSeries is the query type for series queries. QueryTypeSeries // QueryTypeLabels is the query type for label queries. QueryTypeLabels )
type ResultData ¶
type ResultData struct {
ResultType ResultType `json:"resultType"`
Result json.RawMessage `json:"result"`
}
ResultData represents the data portion of a query result
type ResultType ¶
type ResultType string
ResultType represents the type of result returned by Prometheus
const ( // ResultTypeMatrix is the result type for matrix results. ResultTypeMatrix ResultType = "matrix" // ResultTypeVector is the result type for vector results. ResultTypeVector ResultType = "vector" // ResultTypeScalar is the result type for scalar results. ResultTypeScalar ResultType = "scalar" // ResultTypeString is the result type for string results. ResultTypeString ResultType = "string" )
type SamplePair ¶
SamplePair represents a timestamp-value pair
func (SamplePair) Timestamp ¶
func (s SamplePair) Timestamp() time.Time
Timestamp returns the timestamp of the sample
type StreamingConfig ¶
type StreamingConfig struct {
ChunkSize int // Number of data points per chunk (default: 1000)
BufferSize int // Buffer size for streaming (default: 64KB)
ReadTimeout time.Duration // Timeout for reading each chunk (default: 10s)
WriteTimeout time.Duration // Timeout for writing each chunk (default: 5s)
}
StreamingConfig holds configuration for streaming queries
func DefaultStreamingConfig ¶
func DefaultStreamingConfig() StreamingConfig
DefaultStreamingConfig returns default streaming configuration
type StreamingDataChunk ¶
type StreamingDataChunk struct {
ChunkID int `json:"chunkId"`
Data json.RawMessage `json:"data"`
Error error `json:"error,omitempty"`
IsComplete bool `json:"isComplete"`
Timestamp time.Time `json:"timestamp"`
}
StreamingDataChunk represents a chunk of streaming data
type StreamingResultData ¶
type StreamingResultData struct {
ResultType ResultType `json:"resultType"`
ChunkCount int `json:"chunkCount"`
TotalPoints int `json:"totalPoints"`
StartTime time.Time `json:"startTime"`
EndTime time.Time `json:"endTime"`
}
StreamingResultData represents streaming result metadata
type Target ¶
type Target struct {
Labels map[string]string `json:"labels"`
ScrapeURL string `json:"scrapeUrl"`
LastError string `json:"lastError"`
LastScrape time.Time `json:"lastScrape"`
Health string `json:"health"`
GlobalURL string `json:"globalUrl"`
LastScrapeDuration float64 `json:"lastScrapeDuration"`
}
Target represents a Prometheus target
type VectorSample ¶
type VectorSample struct {
Metric map[string]string `json:"metric"`
Value SamplePair `json:"value"`
Timestamp time.Time `json:"-"`
}
VectorSample represents a single sample in a vector
func (*VectorSample) UnmarshalJSON ¶
func (v *VectorSample) UnmarshalJSON(data []byte) error
UnmarshalJSON implements custom JSON unmarshaling for VectorSample